// JavaScript Document

// This is a very simple demo that shows how a range of elements can
// be paginated.

/**
 * Callback function that displays the content.
 *
 * Gets called every time the user clicks on a pagination link.
 *
 * @param {int}page_index New Page index
 * @param {jQuery} jq the container with the pagination links as a jQuery object
 */
function pageselectCallback(page_index, jq) {
    var new_content = $('div#hidden-content ul.products-list:eq('+page_index+')').clone().hide('slow').fadeIn(2000);
    $('#main-products-list').empty().append(new_content);
    return false;
}

/** 
 * Callback function for the AJAX content loader.
 */
function initPagination() {
    var num_entries = $('div#hidden-content ul.products-list').length;
    // Create pagination element
    $("#main-products-list-nav").pagination(num_entries, {
	num_edge_entries: 1,
	num_display_entries: 10,
	callback: pageselectCallback,
	items_per_page:1
    });
}

/** 
 * Function used to filter products
 */
function filterProducts(name, id) {
    // Set up variables for AJAX function
    var curr_sort_type = $("h3.result").html();
    var cat_id = $("#id-category").val();
    var level_one_filters = new Object();
    
    $("#filter-summary li.added").each( function() {
	// Option ID + name is added as name to <li>
	var id_name = $(this).attr( "name" );
	var components = id_name.split( " ", 2 );
	var fid = components[0];
	var fname = components[1];

	if( typeof( level_one_filters[fname] ) == 'string' ) {
	    // Setting for this name already exists
	    level_one_filters[fname] += fid + ",";
	} else {
	    // Setting for this name does not exist
	    level_one_filters[fname] = fid + ",";
	}
    });

    var filters = "";
    for( var name in level_one_filters ) {
	filters += name + ":" + level_one_filters[name] + '/';
    }

    // Call AJAX function to filter products
    $.post( "/filter_products/", "cat_id=" + cat_id + "&filters=" + filters + '&curr_sort_type=' + curr_sort_type,
	    // Remake product list, and repaginate
	    function(data, status) {
		// No point checking status as it is
		// apparently always "success" when
		// called in this manner.
		$("div#hidden-content").empty().append( data );
		initPagination();
	    });
}

// == Document Main ==
$(document).ready(function(){
    initPagination(); // Initialise Pagination
    
    // Set up Tabbed Content Items
    $(".tabbed-content").hide(); //Hide all content
    $("ul.tabs li:first a").addClass("active").show(); //Activate first tab
    $(".tabbed-content:first").show(); //Show first tab content
    
    //General Info Tabs
    $("ul.tabs li").click(function() {
	$("ul.tabs li a").removeClass("active"); //Remove any "active" class
	$(this).children('a').addClass("active"); //Add "active" class to selected tab
	$(".tabbed-content").hide(); //Hide all tab content
	
	var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
	$(activeTab).fadeIn(1250); //Fade in the active ID content
	return false;
    });
    
    
    // Product Scroll Bar
    $.easing.custom = function (x, t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t*t + b;
	return c/2*((t-=2)*t*t + 2) + b;
    }
    
    // initialize scrollable  for product sliders
    $("div.product-slide").scrollable({
	next: 'a.prodSlideNext',
	prev: 'a.prodSlidePrev',
	easing: 'custom',
	items: '.items',
	size: 2,
	keyboard: true,
	clickable: false,
	speed: 1000			
    });


    // initialize scrollable  for product sliders
    $("div.product-slide-small").scrollable({
	next: 'a.prodSlideNext',
	prev: 'a.prodSlidePrev',
	easing: 'custom',
	items: '.items',
	size: 2,
	keyboard: true,
	clickable: false,
	speed: 1000					
    });
    
    // show filter sub-categories
    //$(".level-two-filter, #filter-summary").hide('fast');
    // Show "PRODUCT" tab by default
    
    $("#level-one-filter li").each( function() {
	if( $(this).attr("name") == "product" ) {
	    $(this).children("a").addClass( "selected" );

	    // Name is added to <li>
	    var name = $(this).attr( "name" );

	    // Hide other level-two filters, and show this
	    $("ul.level-two-filter").css('display', 'none');
	    $("ul[name='" + name + "']").show( 'fast' );
	    // Show filter summary ul
	    //$("#filter-summary").show( 'slow' );

	    return false;
	}
    });
    
    $("#level-one-filter li a").click(function(e){
	e.preventDefault();
	
	// if select don't fire animation as it's already visible
	if ($(this).hasClass('selected')) {
	    return false;
	}
	
	// Make this the selected item
	$("#level-one-filter li a").removeClass( "selected" );
	$(this).addClass( "selected" );
	
	// Name is added to <li>, hence parent
	var name = $(this).parent().attr( "name" );
	
	// Hide other level-two filters, and show this
	$("ul.level-two-filter").css('display', 'none');
	$("ul[name='" + name + "']").slideDown('normal', function() {
	    $("#filter-summary").show('slow');																						 
	});
	return false;
    });
    
    // add selected filter to summary filter line
    $(".level-two-filter li a").click( function(e) {
	e.preventDefault();
	
	// Text might have special characters and whitespace. Remove.
	var filterText = $(this).text().replace( /[\W\s]+/g, "");

	// Name is added to <ul>, hence parent of parent
	var name = $(this).parent().parent().attr( "name" );
	// Option ID is added as name to <li>. Hence parent
	var id = $(this).parent().attr( "name" );
	var addedFilter = '<li class="added add-' + filterText + '" name="' + id + " " + name + '"><a href="#">' + filterText + '</a><a href="#" class="remove"><img src="/site_media/img/img-remove-filter-a.gif" width="10" height="10" alt="" title=""></a></li>';

	if( $("#filter-summary li.add-" + filterText).length >= 1 ) { //if item already added
	    //alert('that item is already selected');
	} else { //If filter doesn't exist write out to filter summary line
	    $("#filter-summary").prepend( addedFilter );
	    $("#filter-summary li.added").unbind('click');
	    // clear individual filter
	    $("#filter-summary li.added").click(function(){
		$(this).remove();
		// Filter products: Must be done after remove
		filterProducts( name, id );
		return false;	
	    });
	    
	    $("#filter-summary").show('fast');
	    
	    // Filter products
	    filterProducts( name, id );
	}
	return false;
    });
    
    // clear all filters
    $("#filter-summary").find("li.last").click(function(e){
	e.preventDefault();
	$("#filter-summary").hide('fast');
	//$("#filter-summary li.added").unbind('click');
	$("#filter-summary li.added").remove();
	//$("ul.level-two-filter li, #filter-summary").hide('slow');
	$("#level-one-filter li a").removeClass("selected");
	// Filter products: Must be done after remove
	filterProducts("", "");
	return false;
    });
    
    
    var ie6 = false;																		  
    if ($.browser.msie && $.browser.version <= 6) {
	ie6  = true;
    }			
    
    $('#sort-by').mouseover(function() {
	$(this).css('cursor', 'pointer');
	// ie6 has trouble with the fade, so hard hide/show instead
	if (ie6) {
	    $('#sort-by-content').css('display', 'block');
	} else {
	    $('#sort-by-content').fadeIn('normal');
	}
    }).mouseleave(function() {
	$(this).css('cursor', 'auto');
	if (ie6) {
	    $('#sort-by-content').css('display', 'none');							
	} else {
	    $('#sort-by-content').slideUp('normal');
	}
    });
    
    // == Event Handler ==
    $("div#sort-by-content ul.filter li a").click( function() {
	
	$(this).css('cursor', 'auto');
	if (ie6) {
	    $('#sort-by-content').css('display', 'none');							
	} else {
	    $('#sort-by-content').slideUp('normal');
	}																				  
	
	// AJAX function to sort products
	var product_ids = "";
	$(".product-id").each(function() {
	    product_ids += $(this).val() + ","; 
	});
	// Sort name is added as name to <li>. Hence parent
	var sort_type = $(this).parent().attr( "name" );
	$( "h3.result" ).html( sort_type );

	$.post("/sort_products/", "product_ids=" + product_ids + "&sort_type=" + sort_type,
	       // Remake product list, and repaginate
	       function(data, status) {
		   // No point checking status as it is
		   // apparently always "success" when
		   // called in this manner.
		   
		   if( data ) {
		       $("div#hidden-content").empty().append( data );
		       initPagination();
		   }
	       });
	return false;
    });
    
    // Product Rollover
    /*	$("#main-products-list .products-list li a.tooltip-trigger").tooltip({
	tip: '.tooltip', 
	position: 'top center',
	offset: [8, 0],
	lazy: false,
	predelay: 500,
	delay: 100
	}).dynamic({ 
	bottom: {
	direction: 'down',
	bounce: true
	} 
	});*/
    
    // Cat Rollover
    /*		$("#main-products-list .products-list li a.tooltip-trigger-cat").tooltip({
		tip: '.tooltip', 
		position: 'top center',
		offset: [-120, 0],
		lazy: false,
		predelay: 500,
		delay: 100
		}).dynamic({ 
		bottom: {
		direction: 'down',
		bounce: true
		} 
		});*/

    // View All functionality		
    $("div#view-all a").click(function(event) {
	event.preventDefault();							   
	$("div#main-products-list, ul#main-products-list-nav, div#view-all").hide(10);
	$("div#hidden-content, div#paginate-container").fadeIn(750);
    });

    // Revert back to Paginate functionality
    $("div#paginate-container a").click(function(event) {
	event.preventDefault();							   
	$("div#hidden-content, div#paginate-container").hide(10);
	$("div#main-products-list, ul#main-products-list-nav, div#view-all").fadeIn(750);
    });
    
    if($("div#main-products-list ul.products-list li").length < 12)
    {
	$(this).find("div#view-all").addClass('disabled');
    }
	
	if ( $('#product-main-nav li.colours').is(":visible") )
	{	
	
	}
	else
	{
		$("div#product-main-img-container a.video").addClass('no-colour');
	}

	
});
