﻿// JScript File
var totalBasketPrice = 0;
var digitRegex=new RegExp("^\\d*$");
var defaultTab = 0;
var defaultBasketItemIndex = 0;
var productHistory;
var index;
var INDIVIDUAL_PRODUCT_PARTIAL_ACTION_URL = "/individualProduct/partial/{0}.do?att={1}&filter={2}&pageIndex={3}";
var PAGE_INDEX = 0;
var NUMBER_OF_PRODUCTS = 0;

var START_INDEX_FOR_MAIN_CAROUSEL = 0;

var LOAD_NEXT_SET_OF_PRODUCTS = true;

function SetDefaultTab(index, totalTabs){
		if (index > 7)
			defaultTab = totalTabs - 7;
		else
			defaultTab = 0;
}

function DisplayLastItemInBasketCarousel(index){
	if (index > 5){
		defaultBasketItemIndex = index - 4
	}
}

$(document).ready(function() {
//**********************Start of Carousel JQuery ************************//
	$('#productTBStationery a.deleteItem').css('visibility', 'visible');
	$('a.closeTBMyStationery').css('display', 'block'); 

	$('.basketAttribute *:hidden').show();
	$('.basketAttribute :input').attr('readonly', false);
	// tooltip

	$('a.tooltip').tooltip({
		background: 'transparent',
		color: '#372056',
		moreText: '<p>click image for more info</p>',
		rounded: false
	});
	
	updateProductAndBasketCost();
	
	$("a.addItem>img").click(function(){
		var parent = $(this).parents("li")[0];
		var currentQuantity = parseInt($(parent).find(".inputQuantity").val());
		$(parent).find(".inputQuantity").val(++currentQuantity);
		updateTotalCost(parent);
		updateBasketTotalCost();
		postToAddUpdateItem(parent,currentQuantity);
	});	
	
	$("input.inputQuantity").blur(function() {
		var parent = $(this).parents("li")[0];
		var currentQuantityValue = $(this).val();
		if ((currentQuantityValue < 1) || digitRegex.test(currentQuantityValue) != true)
			currentQuantityValue = 1;
		var currentQuantity = parseInt(currentQuantityValue);
		$(parent).find(".inputQuantity").val(currentQuantity);
		updateTotalCost(parent);
		updateBasketTotalCost();
		postToAddUpdateItem(parent,currentQuantity);
	});
	
	$("a.reduceItem>img").click(function(){
		var parent = $(this).parents("li")[0];
		var currentQuantity = parseInt($(parent).find(".inputQuantity").val());
		if (currentQuantity ==1)
			return;
		$(parent).find(".inputQuantity").val(--currentQuantity);
		updateTotalCost(parent);
		updateBasketTotalCost();
		var productCode = $(parent).find("#productCode").val();
		postToAddUpdateItem(parent,currentQuantity);
	});
	
	$("a.deleteItem>img").click(function() {
		var parent = $(this).parents("li")[0];
		postToRemoveItem(parent,0)
		updateBasketTotalCost();
	});
		//this line to wrap raounded image
	$('#productTBStationery').parent().wrap('<div class="shortlistTBTop"><div class="shortlistTBBottom"><div class="shortlistTBBody"></div></div></div>').css({'padding':'0px','position':'relative'});
	
	//remove TB 
	$('#TB_overlay').click(function(){tb_remove(window.location.toString())});
	
	
	$('.thickboxJavascriptQueryString').click(function() {
		productHistory = new Array;
		index = 0;
		productHistory[index] = $(this).attr('href');
		index++;
	});
	
	$(".carouselNextButton").click(function(){
		PAGE_INDEX +=1;
	});
	
	$(".carouselPrevButton").click(function(){
		PAGE_INDEX -=1;
	});
}
);

function LoadNextSetOfProducts(){
	if (ShouldLoadNextSetOfProducts()){
		var defaultLiStyling = GetDefaultCarouselLiStyle();
		var categoryId = $(":hidden[name='productCategoryId']").val();
		var attributeId = $(":hidden[name='att']").val();
		var filterId = $(":hidden[name='filter']").val();
		var url = INDIVIDUAL_PRODUCT_PARTIAL_ACTION_URL.replace("{0}",categoryId).replace("{1}",attributeId).replace("{2}",filterId).replace("{3}",GetCurrentPageIndex());
		var loadProduct = $.ajax({
			url: url,
			success:function(html){
				var styledFragment = AddStyling(html,defaultLiStyling);
				$("#carousel ul").append(styledFragment);
				RemoveLiPlaceholders();
			},
			error:function (XMLHttpRequest, textStatus, errorThrown){
				DisplayErrorMessage(XMLHttpRequest, textStatus, errorThrown);
			}
		});
	}
}

function ShouldLoadNextSetOfProducts(){
	var shouldLoadProducts;
	if ($("div #carousel ul li").length != GetTotalProductCount()){
		var totalProductsOnCarouselBasedOnPageIndex = ((GetCurrentPageIndex() -1) * 3) + 3;
		var totalNumberOfProductsCurrentlyDisplayed = $("div #carousel ul li").length;
		shouldLoadProducts = totalProductsOnCarouselBasedOnPageIndex > totalNumberOfProductsCurrentlyDisplayed;
	}
	return shouldLoadProducts;
}

function CalculateMaxPageIndex(numberOfProducts){
	var maxPageIndex = numberOfProducts / GetPageIndex();
	alert(maxPageIndex);
}

function DisplayErrorMessage(xMLHttpRequest, textStatus, errorThrown){
	alert(xMLHttpRequest + " " + textStatus + " " + errorThrown);
}

function InitialiseStationery(pageIndex, numberOfProducts){
	//page Index is returned from server side variable
	PAGE_INDEX = parseInt(pageIndex);
	PAGE_INDEX +=1;
	NUMBER_OF_PRODUCTS = parseInt(numberOfProducts);
}


function GetTotalProductCount(){
	return NUMBER_OF_PRODUCTS;
}

function GetCurrentPageIndex(){
	return PAGE_INDEX;
}

function RemoveLiPlaceholders(){
	$("div #carousel ul li:not(:has(a))").remove();
}


function GetDefaultCarouselLiStyle(){
	return $("#carousel ul li:first").attr("style");
}

function AddStyling(fragment,styleToAdd){
	var styledFragment = $(fragment,"li").attr("style",styleToAdd);
	return styledFragment;
}

function initialiseJCarouselLiteForSingleProduct(){
	productQuantity = $(".jCarouselLite ul li").size();

	if ( productQuantity > 0){
		$(".jCarouselLite").jCarouselLite({
			btnNext: ".carouselNextButton",
			btnPrev: ".carouselPrevButton",
			visible: 4,
			circular: false,
			start: START_INDEX_FOR_MAIN_CAROUSEL,
			scroll:3,
			afterEnd : function(a){LoadNextSetOfProducts();}
		});
		$(".jCarouselLite").width(690).find('ul').css('margin-left', '25px');
		$('.carouselPrevButton').addClass('disabled');
	}
	$(".mixedContent .jCarouselLiteBasket").jCarouselLite({
		btnNext: ".carouselNextButtonBasket",
		btnPrev: ".carouselPrevButtonBasket",
		visible: 4,
		circular: false,
		start: defaultBasketItemIndex,
		scroll:3
	});
	$("ul#shortList li").css("height","95px");
		$('#carousel ul').css('display', 'block');
	//check if list element exist
	//initialiseJCarouselLiteForSingleProduct();

	//stationery basket
	$('#corouselBasket ul').css('display', 'block');

	$('#corouselTab ul').css('display', 'block');

	$(".nonImageContent .jCarouselLiteTab").jCarouselLite({
		btnNext: "#corouselPrevNav",
		btnPrev: "#corouselNextNav",
		visible: 4,
		circular: false,
		start: defaultTab
	});

	//dont need to specify width for this corousel li
	$(".jCarouselLiteTab li").css("width", "auto");
	$("#tabcontainer .jCarouselLiteTab").css("width", "672px");
	var totWidth = 0;
	$('#corouselTab li').each(function(){
		totWidth += $(this).outerWidth();
	});
	$('#corouselTab ul').css("width", 80 + totWidth);
	
	//this is to hide the tab button if total width for the list item smaller than 675px
	var totalWidthList = 0;
	$(".tabsNav li").each(function(){
		totalWidthList = totalWidthList + $(this).outerWidth(true);
    });
	//alert (totalWidthList);
	if (totalWidthList > 675){
		$('div.tabScollRight').css('display', 'block');
		$('div.tabScollLeft').css('display', 'block');
	}
	//hide the arrow if product less equal than 4
	$('a.carouselPrevButton').css('visibility', 'visible'); 
	$('a.carouselNextButton').css('visibility', 'visible');
	if($('#carousel li').size() <= 4  ){
		$('a.carouselPrevButton').css('visibility', 'hidden'); 
		$('a.carouselNextButton').css('visibility', 'hidden');
	};
	//hide basket shortlist button if product less than 4
	if($('#corouselBasket li').size() > 4  ){
		$('a.carouselPrevButtonBasket').css('visibility', 'visible'); 
		$('a.carouselNextButtonBasket').css('visibility', 'visible');
	};
	
	$('#carouselContainer .centeringCorousel').css({'height':'222px','clear':'both'});
	$('#productTBStationery a.deleteItem').css('visibility', 'visible');
	$('a.closeTBMyStationery').css('display', 'block'); 
	$('#seeAllMyChoices').css('visibility', 'visible');
	$('.basketAttribute *:hidden').show();
	$('.basketAttribute :input').attr('disabled', false);
	$('#seeAllMyChoices').css('visibility', 'visible');
}

function hideIndividualProductsInformations(){
	$('#carousel li').each(function(){
		var $this = $(this);
	});
}
function updateTotalCost(parent) {
	var basePrice = parseFloat($(parent).find(".basePrice").val());
	var quantity = parseInt($(parent).find(".inputQuantity").val());
	var totalProductPrice = (basePrice * quantity);
	$(parent).find("span.priceThickBox").text(""+totalProductPrice.toFixed(2));
}

function updateBasketTotalCost() {
	//reset basket total price;
	totalBasketPrice = 0;
	var childrenLI = $("#shortList").children("li");
	$.each(childrenLI,function(name,value) {
		var parent = value;
		var productPrice = parseFloat($(parent).find("span.priceThickBox").text());
		totalBasketPrice+=productPrice;
	}
	);
	$("#engineBasketTotalCost").text(totalBasketPrice.toFixed(2));
	
	if (childrenLI.length == 0) {
		$("#aspnetForm").hide();
		if($("#stationeryBasket p#emptyBasketMsg").length == 0){
			$("#stationeryBasket").append("<p id='emptyBasketMsg'>Nothing selected yet...</p>");
		}
	}
}

function updateProductAndBasketCost() {
	var childrenLI = $("#shortList").children("li");
	$.each(childrenLI,function(name,value) {
		var parent = value;
		updateTotalCost(parent);
	}
	);
	updateBasketTotalCost();
	
}

function postToAddUpdateItem(parent,quantity) {
	var parameters = setParameterValues(parent,quantity);
	jQuery.post($("#engineBasketAddUpdatePostUrl").val(), $.param(parameters));
	
}

function postToRemoveItem(parent,quantity) {
	var parameters = setParameterValues(parent,quantity);
	jQuery.post($("#engineBasketRemovePostUrl").val(), $.param(parameters));
	$(parent).find("span.priceThickBox").text(quantity);
	
	
	
	if($(parent).siblings().length <= 4 ){
		$('a.carouselPrevButtonBasket').css('visibility', 'hidden'); 
		$('a.carouselNextButtonBasket').css('visibility', 'hidden');
	};
	$(parent).remove();
}

function setParameterValues(parent,quantity) {
	var setParameters = {};
	setParameters["productCategoryId"] = $("#hiddenProductCategoryId").val();
	setParameters["productCode"] = $(parent).find("#productCode").val();
	setParameters["productQuantity"] = quantity;
	return setParameters;
}
