$(function() {
	scroller = new scrollTrack($("#thumbs"));
	
	$('#slider').css('width',($('#slider .product').length * 920) + 'px');

	$('.product .nav a').each(function(){
		$(this).click(function(){
			focusSegment($(this));
			return false;
		});
	});
		
	$('.tooltip-target').ezpz_tooltip({
		contentPosition: 'aboveStatic',
		offset: 5,
		showContent: function(content) {
				content.fadeIn('fast');
		},
		hideContent: function(content) {
			// if the showing animation is still running, be sure to stop it
			// and clear the animation queue. otherwise, repeatedly hovering will
			// cause the content to blink.
			content.stop(true, true).fadeOut('def');
		}
	});
	
	if($("#id_search").length){
		$("#id_search").labelify({labelledClass:'empty'});
	}
	
	var elem = $("#thumbs a.item.selected");
	if(scroller.slideMax > 1){
		scroller.revealItem(elem);
	}		

	$("#thumbs .items .active").removeClass('active');
	$(elem).children().addClass('active');

	initMaterialsPaging($(".product.line"));
	$("a.zoom").fancybox({
		'zoomSpeedIn' : 250,
		'zoomSpeedOut' : 0,
		'overlayShow' : false
	});

	var playerUrl = STATIC_URL + "swf/flowplayer-3.1.5.swf";
	$("a.zoom-video").each(function() {
		var url = $(this).attr("name");
		$(this).fancybox({
			'hideOnContentClick':false,
			'zoomSpeedIn' : 250,
			'zoomSpeedOut' : 0,
			'overlayShow' : false,
			'callbackOnShow': function() {
				var player = $f("fancy_content", playerUrl, {
					play:{opacity:0},
					clip:{
						url:url,
						autoPlay: true,
						autoBuffering: true,
						onStart:function(clip) {
							var wrap=$(this.getParent());
							var clipwidth = clip.metaData.width;
							var clipheight= clip.metaData.height;
							var pos = $.fn.fancybox.getViewport();
							$("#fancy_outer").css({width:clipwidth,height:clipheight});
							$("#fancy_outer").css('left', ((clipwidth + 36) > pos[0] ? pos[2] : pos[2] + Math.round((pos[0] - clipwidth - 36)	/ 2)));
							$("#fancy_outer").css('top',  ((clipheight + 50) > pos[1] ? pos[3] : pos[3] + Math.round((pos[1] - clipheight - 50) / 2)));
						},
						onFinish:function(){
							$('#fancy_close').trigger('click');
						}
					}
				});
				player.load();
			},
			'callbackOnClose':function(){
				$("#fancy_content_api").remove();
			}
		});
	});
});

scrollTrack = function(elem)
{
	this.container = elem;
	this.slideIndex = 0;
	//calculate this otherwise
	this.modW = 132;//TODO: cleanup
	//modW = $(this.container).find('.item').outerWidth();
	//alert(modW);
	
	$(this.container).find('.items').css('width',this.modW * $(this.container).find('.item').length);
	//determine the modulo, and fraction that crap out
		
	var r = $(this.container).find('.items').outerWidth() % $(this.container).find('.scrollable').width();
	this.slideMax = Math.ceil($(this.container).find('.items').outerWidth() / $(this.container).find('.scrollable').width());
	
	//TODO: cleanup
	if(r+this.modW < this.modW*2){
		this.slideMax--;
	}
	
	this.updateUI();
	
	var scope = this;
	$(this.container).find('.left').click(function(){
		scope.movePage(-1);
		return false;
	});
	$(this.container).find('.right').click(function(){
		scope.movePage(1);
		return false;
	});
	
}

scrollTrack.prototype.revealItem = function(elem)
{
	var x = $(elem).children().position().left + this.modW;
	this.slideIndex = Math.floor(x / $(this.container).find('.scrollable').outerWidth());
	this.viewPage(true);
}

scrollTrack.prototype.updateUI = function()
{
	$(this.container).find('.left').removeClass('disabled');
	$(this.container).find('.right').removeClass('disabled');
	
	if(this.slideIndex == 0){
		$(this.container).find('.left').addClass('disabled');
	}
	if(this.slideIndex == this.slideMax-1 || this.slideMax == 1){
		$(this.container).find('.right').addClass('disabled');
	}
}

scrollTrack.prototype.movePage = function(dir)
{
	switch(true)
	{
		case this.slideIndex + dir > this.slideMax - 1:
			this.slideIndex = 0;
		break;

		case this.slideIndex + dir < 0:
			this.slideIndex = this.slideMax - 1;
		break;

		default:
			this.slideIndex += dir;
		break;
	}
	this.viewPage();
}

scrollTrack.prototype.viewPage = function(force)
{
	this.updateUI();
	if(force == undefined){
		$(this.container).find('.items').animate({left:-this.slideIndex*792},250,'easeInOutQuad');
	}
	if(force == true){
		$(this.container).find('.items').css('left',-this.slideIndex*792);
	}
}

function focusSegment(elem){
	var tA = $(elem).attr('href').split('-');
	$('#product-'+tA[1]+' .nav .active').removeClass('active');		
	$(elem).addClass('active');
	var item = $('#product-'+tA[1]+ ' .product_slider');
	$(item).animate({left:-$(elem).parent().index()*920},500,'easeInOutQuad');	 
}

function initMaterialsPaging(elem) {
	
	var catA = elem.find('ul.material_list');
	var matA = elem.find('ul.material_list > li');

	//if (catA.length > 3 || matA.length > 30) {
	
	//do pagination
	var pageA = [];
	var page = createPage();
	var rowC = 0;
	for (var i = 0; i < catA.length; i++) {
		var cat = catA[i];
		var label = $(cat).prev().text();
		page[rowC].label = label;
		var itemA = $(cat).find('li');
		for (var j = 0; j < itemA.length; j++) {
			if (page[rowC].items.length >= 10) {
				if (itemA[j + 1]) {
					page[rowC].label = label;
					rowC++;
					if (rowC == 3) {
						rowC = 0;
						pageA.push(page);
						page = createPage();
						page[rowC].label = label;
					}
				}
			}
			page[rowC].items.push($(itemA[j]).html());
		}
		rowC++;
		if (rowC == 3) {
			if (i < catA.length - 1) {
				rowC = 0;
				pageA.push(page);
				page = createPage();
				page[rowC].label = label;
			}
		}
	}
	pageA.push(page);

	if(pageA.length < 2){
		return;
	}

	//empty it out
	var cont = elem.find('.items');
	cont.empty();
	
	var paging = '<div class="paging material"><ul><li><span>Page</span></li>';
	
	for (var i = 0; i < pageA.length; i++) {
		paging += '<li><a href="#">' + (i + 1) + '</a></li>';
		var r = '<div class="page">';
		for (var j = 0; j < 3; j++) {
			if (pageA[i][j].items.length) {
				r += '<div class="group">';
				
				var label = pageA[i][j].label;
				
				//only show the label if it's different
				if (pageA[i][j - 1] != undefined) {
					if (pageA[i][j - 1].label == pageA[i][j].label) {
						label = undefined;
					}
				}
				
				if (label) {
					r += '<h6 class="light">' + label + '</h6>';
				}
				
				r += '<ul class="material_list">';
				for (var k = 0; k < pageA[i][j].items.length; k++) {
					r += '<li>' + pageA[i][j].items[k] + '</li>';
				}
				r += '</ul>';
				r += '</div>';
				r += '<br style="clear: both;">';
			}
		}
		r += '</div>';
		cont.append(r);
	}
	paging += '</ul></div>';
	elem.find('.paging').replaceWith(paging);
	
	//observe these
	elem.find('.paging a').click(function(){
		showMaterialsPage($(this));
	});
	//} 
	showMaterialsPage(elem.find('.paging a:eq(0)'));
}

function showMaterialsPage(pageLink)
{
	var elem = pageLink.parents(".paging");

	//toggle the love
	elem.find('.current_page').removeClass('current_page');
	$(pageLink).addClass('current_page');

	var index = $(pageLink).parent().index() - 1;

	//hide all pages, show the active one
	var pA = elem.parents('.product').find('.page');
	for(var i=0;i<pA.length;i++){
		if(i == index){
			$(pA[i]).show();//animate({opacity:1.0},250);
		}else{
			$(pA[i]).hide();//animate({opacity:0.0},250);
		}
	}	

}

function createPage()
{
	return [{items:[],label:''},{items:[],label:''},{items:[],label:''}];
}
