var itemsDiv, itemsController;

$(function(){				 
  var i = 0;
  var divSpecs = {'class':'opBG',
                   'css':{'position':'absolute',
                          'top':'0',
                          'left':'0',
                          'background':$('#popSkins li').eq(0).css('background-image'),
                          'width':'160px',
                          'height':'195px',
                          'z-index':'-1' /*don't know if this is acceptable in all browsers*/
                          }
                    };
  
  $('#popSkins li.focusItem').removeClass('focusItem');  
  $('#popSkins li').css({
                      'left':'1000px',
                      'background':'none',
                      'z-index':20 + i++
                      })
                      .prepend($('<div>',divSpecs));
  popAnim('new');
  
  $('#popSkinsController a').click(function(){
    popAnim($(this).attr('href').substring(1));
    $('#popSkinsController a').removeClass('selected').filter(this).addClass('selected');
    return false;
  });
  
  prepItemsList();
  
  $('#tagSearch input[type="text"]')
            .click(function(){if($(this).val() == 'tag search') $(this).val('');})
            .blur(function(){if($.trim($(this).val()) == '') $(this).val('tag search');})
            .blur();

  var cache = {}, lastXhr;
  $("#tagSearch input[type='text']").autocomplete({
    minLength: 2,
    appendTo: '#tagSearch',
    source: function(request, response){
      var term = request.term;
      if (term in cache){
        response(cache[term]);
        return;
      }

      lastXhr = $.getJSON("/index/tagSearch/"+term, request, function(data, status, xhr){
      cache[term] = data;
      if (xhr === lastXhr) {
        response(data);
      }
      });
    },
    select: function(event,ui){
			populateItemsList(ui.item.value);
    }
  });
	
	$('#homeTagList').hide();
	var viewTags = $('<a href="#">View All Tags</a>');
	viewTags.css({
							 'margin':'0 auto 10px',
							 'padding':'5px',
							 'color':'#fff',
							 'display':'block',
							 'text-align':'center',
							 'font-size':'1.4em',
							 'background':'#A3692F',
							 'font-family':'CaudexBold'
							 }).click(function(){
		if($('#homeTagList').is(':visible')){
			$('#homeTagList').slideUp('fast');
			viewTags.text('View All Tags');
		}else{
			$('#homeTagList').slideDown('slow');
			viewTags.text('Hide Tag List');
		}
		
		return false;
	});
	$('#homeTagList').after(viewTags);

	$('#popSkins .new .lightbox').lightBox({scsCustom:true});
	$('#popSkins .hot .lightbox').lightBox({scsCustom:true});
	$('.lightbox').css({'position':'relative','width':function(i,v){return v;}}).prepend('<img class="viewOverImg" src="/resources/img/overlay-icon-view.png"/>');
});

function populateItemsList(addTag){
	var tagNames = addTag;
	$('#appliedTags a').each(function(){
		tagNames += '/'+$(this).text();																
	});
	
	if(tagNames.charAt(0) == '/'){
		tagNames = tagNames.substring(1);
	}
			
	$.post('/items/getByTagName/'+tagNames,'',function(data){
		$('#homeItemsList').replaceWith(data);
		prepItemsList();

		if(!$('#appliedTags').length){
			$('#homeItemsList').before('<ul id="appliedTags"><li>Tags:</li></ul>');
		}
		
		if(addTag != ''){
			var tagLink = $('<a href="#" class="tagFilter">'+addTag+'</a>')
											.click(function(){
												$(this).parents('li').remove();
												populateItemsList('');
												return false;
											});
			var tagLi = $('<li></li>').append(tagLink);
			$('#appliedTags').append(tagLi);
		}
		
		if(!$('#appliedTags a').length){
			$('#appliedTags').remove();
		}
		
		$("#tagSearch input[type='text']").val('').blur();
	});
}

function prepItemsList(){		
  $('#itemsController').remove();

  var itemsNum = $('#homeItemsList .items').length;
	if(itemsNum > 0){
		itemsDiv = $('<div>',{'css':{'width':itemsNum*972+'px','height':'460px','position':'relative','left':'0'}});          
		itemsDiv.append($('#homeItemsList .items')).appendTo('#homeItemsList');
	
		itemsController = $('<div>',{'id':'itemsController'});
		var prevButton = $('<a>',{'href':'#','class':'prev'});
		var nextButton = $('<a>',{'href':'#','class':'next'});
		var itemsNav = $('<ul>');
		var currentItemPage = 1;
		
		prevButton.click(function(){
			if(currentItemPage == 1) return false;
			itemsToPage(--currentItemPage);
			return false;
		});
		nextButton.click(function(){
			if(currentItemPage == itemsNum) return false;
			itemsToPage(++currentItemPage);
			return false;
		});
		
		for(i=0;i<itemsNum;i++){
			var navLink = $('<a>',{'href':'#','text':i+1});
			if(i == 0) navLink.attr('class','selected');
			navLink.click(function(){
				if($(this).hasClass('selected')) return false;
				itemsToPage(currentItemPage = $(this).text());
				return false;
			});
			
			var li = $('<li>');
			if(i == 6) li.attr('class','last');
			li.append(navLink);
			itemsNav.append(li);
		}
		
		itemsController.append(prevButton).append(itemsNav).append(nextButton).insertAfter('#tagSearch');
	
		$('#homeItemsList .lightbox').lightBox({scsCustom:true})
                            .css({'position':'relative','width':function(i,v){return v;}})
                            .prepend('<img class="viewOverImg" src="/resources/img/overlay-icon-view.png"/>');
		$('#homeItemsList .view').click(function(){
			var index = $('#homeItemsList .lightbox').index($(this).parents('li').find('.lightbox'));
			$('#homeItemsList .lightbox').eq(index).click();
			return false;
		});
	}else{
		itemsController = $('<div>',{'id':'itemsController','css':{'visibility':'hidden'}}).insertAfter('#tagSearch');
	}
}

function hoverFunc(){
  if($(this).hasClass('focusItem')) return false;																	 
                                       
  $('#popSkins li.focusItem div.opBG').animate({opacity:1},200);
	$('#popSkins li.focusItem p').animate({left:'10px'},200);
  $('#popSkins li.focusItem').removeClass('focusItem').animate({width:140},200);
  $('#popSkins .download').removeClass('button button-orange');

  $(this).animate({width:200},200,function(){$(this).addClass('focusItem');});
  $('.download',this).addClass('button button-orange');
  $('div.opBG',this).animate({opacity:0},200);  
	$('p',this).animate({left:'40px'},200);
}

function popAnim(listClass){
  $('li',context).unbind('mouseenter mouseleave');
  var i = 0;
  var context = '#popSkins .'+listClass;

  $('li',context).removeClass('focusItem')
									.css({'width':'140px'})
									.unbind('mouseenter mouseleave')
									.find('div.opBG').css('opacity',1).end()
									.find('p').css('left','10px');
	
  
  $(context).prependTo('#popSkins');
  
  $('li',context).css('left','1000px').each(function(){
    var ii = i;
    var obj = $(this);
    setTimeout(
      function(){
        obj.animate({left:(-80*ii)},400,function(){
          obj.animate({left:0},100,function(){
						if(ii == 2){
							obj.addClass('focusItem').animate({width:200},200)
								.find('div.opBG').css('opacity',0).end().find('p').animate({left:'40px'},200);
							obj.find('.download').addClass('button button-orange');
						}else if(ii == 4){
              $('li',context).hoverIntent(hoverFunc,function(){});
						}
					});
        });      
      },
			i*100
    );
    i++;
  });
}

function itemsToPage(page){
  itemsDiv.animate({'left':-(page-1)*972+'px'},200);
  $('.selected',itemsController).removeClass('selected');
  $('li',itemsController).eq(page-1).find('a').addClass('selected');
}
