var replaceClass = function(e, oldClass, newClass) {
	if (e.hasClass(oldClass)) {
		e.removeClass(oldClass);
		e.addClass(newClass);
	}
}

var switchTab = function(tabTitle) {
	
	var tabContents = $("#tab-contents > div");
	var offTabContents = tabContents.not("[title=" + tabTitle + "]");
	var onTabContent = tabContents.filter("[title=" + tabTitle + "]");
	
	var tabs = $(".area-switch li").not(".submenu-delimeter");
	var offTabs = tabs.not("[title=" + tabTitle + "]");
	var onTab = tabs.filter("[title=" + tabTitle + "]");
	
	var offStyledElements = offTabs.find(".off1, .off2, .off3, .on1, .on2, .on3");
	var onStyledElements = onTab.find(".off1, .off2, .off3, .on1, .on2, .on3");
	
	replaceClass(offTabs, "on", "off");
	replaceClass(onTab, "off", "on");
	
	offStyledElements.each(function() {
		replaceClass($(this), "on", "off");
		replaceClass($(this), "on1", "off1");
		replaceClass($(this), "on2", "off2");
		replaceClass($(this), "on3", "off3");
	});
	
	onStyledElements.each(function() {
		replaceClass($(this), "off", "on");
		replaceClass($(this), "off1", "on1");
		replaceClass($(this), "off2", "on2");
		replaceClass($(this), "off3", "on3");
	});
	
	offTabContents.hide();
	onTabContent.show();
	//onTabContent.fadeIn("fast");

}

var toggleCheckbox = function(checkbox, forceStatus) {
	var oldStatus = checkbox.hasClass("off") ? "off" : "on";
	var status = checkbox.hasClass("off") ? "on" : "off";
	if (forceStatus != null) status = forceStatus;
	checkbox.removeClass(oldStatus).addClass(status).attr("src", "img/icons/checkbox_" + status + ".gif");
	return status;
}

var toggleCheckboxOff = function(checkbox, forceStatus) {
	var oldStatus = "on";
	var status = "off";
	if (forceStatus != null) status = forceStatus;
	checkbox.removeClass(oldStatus).addClass(status).attr("src", "img/icons/checkbox_" + status + ".gif");
	return status;
}

$(document).ready(function(){
						   
	var filterTimeout = null;
						   
	var applyOrdering = function(obj) {
		var o = $(obj.target).val();
		var o = o.split("|");
		
		$("#product-filter input[name=OrderBy]").attr("value", o[0]);
		$("#product-filter input[name=OrderType]").attr("value", o[1]);
		
		var base = $("form#OrderByFilter_id #BaseUrl_id").val();
		location.replace(base + "&OrderBy=" + o[0] + "&OrderType=" + o[1]);
		
		var reqParams = {};
		$("#product-filter input").each(function(){
			reqParams[this.name] = this.value;
		});

		$("#product-list-content").html("");
		$.ajax({
			url: "com/ProductList.cfc?method=show",
			type: "get",
			data: reqParams,
			success: function(data) {
				$("#ajax-loading").html('').hide();
				$("#product-list-content").html(jQuery.trim(data));
				$("form#OrderByFilter_id #OrderBy_id").bind("change", function(e) {					
					applyOrdering(e);
				});
			},
			beforeSend: function(){
				$("#ajax-loading").html('<img src=\"img/ajax-loader.gif\" width=\"128\" height=\"15\" alt=\"\">').show();
			}
		});

/*		$("#product-list-content").html("");
		$.get("com/ProductList.cfc?method=show", reqParams,	function(data) {
			$("#product-list-content").html(jQuery.trim(data));
			$("form#OrderByFilter_id #OrderBy_id").bind("change", function(e) {		
				applyOrdering(e);
			});
		});*/

		
	}			   
					   
	var showProductList = function() {
		// genre categories
		if ($("#product-genre-filter .checkbox-image").filter(".off").length == 0) {
			toggleCheckbox($("#product-genre-filter .checkbox-all-image"), "on");
		}
		else {
			toggleCheckbox($("#product-genre-filter .checkbox-all-image"), "off");
		}
		var genreCategoryID = [];
		$("#product-genre-filter .checkbox-image").filter(".on").each(function(){
			var c = $(this).attr("id").split("-");
			genreCategoryID.push(c[1]);
		});
		$("#product-genre-filter input[name=CategoryID]").attr("value", genreCategoryID.length > 0 ? genreCategoryID.join("|") : 0);
		
		// flags
		if ($("#product-flag-filter .checkbox-image").filter(".off").length == 0) {
			toggleCheckbox($("#product-flag-filter .checkbox-all-image"), "on");
		}
		else {
			toggleCheckbox($("#product-flag-filter .checkbox-all-image"), "off");
		}
		$("#product-flag-filter .checkbox-image").each(function(){
			var flag = $(this).attr("id").split("-");
			var isOn = $(this).hasClass("on");
			$("#product-filter input[name=" + flag[1] + "]").attr("value", isOn ? "1" : "");
			
		});

		// packaging types
		if ($("#product-packagingtype-filter .checkbox-image").filter(".off").length == 0) {
			toggleCheckbox($("#product-packagingtype-filter .checkbox-all-image"), "on");
		}
		else {
			toggleCheckbox($("#product-packagingtype-filter .checkbox-all-image"), "off");
		}
		var packagingTypeID = [];

		$("#product-packagingtype-filter .checkbox-image").filter(".on").each(function(){
			var c = $(this).attr("id").split("-");
			packagingTypeID.push(c[1]);
		});
		$("#product-packagingtype-filter input[name=PackagingType]").attr("value", packagingTypeID.length > 0 ? packagingTypeID.join("|") : '');

		// subtitles
		if ($("#product-subtitles-filter .checkbox-image").filter(".off").length == 0) {
			toggleCheckbox($("#product-subtitles-filter .checkbox-all-image"), "on");
		}
		else {
			toggleCheckbox($("#product-subtitles-filter .checkbox-all-image"), "off");
		}
		var subtitlesID = [];

		$("#product-subtitles-filter .checkbox-image").filter(".on").each(function(){
			var c = $(this).attr("id").split("-");
			subtitlesID.push(c[1]);
		});
		$("#product-subtitles-filter input[name=Subtitles]").attr("value", subtitlesID.length > 0 ? subtitlesID.join("|") : '');

		// origintype
		if ($("#product-origintype-filter .checkbox-image").filter(".off").length == 0) {
			toggleCheckbox($("#product-origintype-filter .checkbox-all-image"), "on");
		}
		else {
			toggleCheckbox($("#product-origintype-filter .checkbox-all-image"), "off");
		}
		var originTypeID = [];

		$("#product-origintype-filter .checkbox-image").filter(".on").each(function(){
			var c = $(this).attr("id").split("-");
			originTypeID.push(c[1]);
		});
		$("#product-origintype-filter input[name=OriginType]").attr("value", originTypeID.length > 0 ? originTypeID.join("|") : '');

		// languageversions
		if ($("#product-languageversions-filter .checkbox-image").filter(".off").length == 0) {
			toggleCheckbox($("#product-languageversions-filter .checkbox-all-image"), "on");
		}
		else {
			toggleCheckbox($("#product-languageversions-filter .checkbox-all-image"), "off");
		}
		var languageVersionsID = [];

		$("#product-languageversions-filter .checkbox-image").filter(".on").each(function(){
			var c = $(this).attr("id").split("-");
			languageVersionsID.push(c[1]);
		});
		$("#product-languageversions-filter input[name=LanguageVersions]").attr("value", languageVersionsID.length > 0 ? languageVersionsID.join("|") : '');

		// StockAvailability
		if ($("#product-stockavailability-filter .checkbox-image").filter(".off").length == 0) {
			toggleCheckbox($("#product-stockavailability-filter .checkbox-all-image"), "on");
		}
		else {
			toggleCheckbox($("#product-stockavailability-filter .checkbox-all-image"), "off");
		}
		var stockAvailabilityID = [];

		$("#product-stockavailability-filter .checkbox-image").filter(".on").each(function(){
			var c = $(this).attr("id").split("-");
			stockAvailabilityID.push(c[1]);
		});
		$("#product-stockavailability-filter input[name=StockAvailability]").attr("value", stockAvailabilityID.length > 0 ? stockAvailabilityID.join("|") : '');


		// prices
		
		if ($("#product-price-filter .checkbox-image").filter(".off").length == 0) {
			toggleCheckbox($("#product-price-filter .checkbox-all-image"), "on");
		}
		else {
			toggleCheckbox($("#product-price-filter .checkbox-all-image"), "off");
		}
		var priceFrom = [];
		var priceTo = [];
		$("#product-price-filter .checkbox-image").filter(".on").each(function(){
			var r = $(this).attr("id").split("-");
			priceFrom.push(r[1]);
			priceTo.push(r[2]);
		});
		$("#product-filter input[name=PriceFrom]").attr("value", priceFrom.length > 0 ? priceFrom.join("|") : 0);
		$("#product-filter input[name=PriceTo]").attr("value", priceTo.length > 0 ? priceTo.join("|") : 0);
		
		var reqParams = {};
		$("#product-filter input").each(function(){
			reqParams[this.name] = this.value;
		});

		/*function showProducts() {
			$("#product-list-content").html("");
			$.get("com/ProductList.cfc?method=show", reqParams,	function(data) {
				$("#product-list-content").html(jQuery.trim(data));
				$("form#OrderByFilter_id #OrderBy_id").bind("change", function(e) {					
					applyOrdering(e);
				});
			});

		}
		filterTimeout = setTimeout(showProducts, 1200);*/
		
		function showProducts() {
			$("#product-list-content").html("");
			$.ajax({
				url: "com/ProductList.cfc?method=show",
				type: "get",
				data: reqParams,
				success: function(data) {
					$("#ajax-loading").html('').hide();
					$("#product-list-content").html(jQuery.trim(data));
					$("form#OrderByFilter_id #OrderBy_id").bind("change", function(e) {					
						applyOrdering(e);
					});
				},
				beforeSend: function(){
					$("#ajax-loading").html('<img src=\"img/ajax-loader.gif\" width=\"128\" height=\"15\" alt=\"\">').show();
				}
			});

		}
		filterTimeout = setTimeout(showProducts, 1200);
		

	}
	
	$("#product-filter .checkbox-image").click(function(){
		clearTimeout(filterTimeout);
		toggleCheckbox($(this));
		showProductList();
	});
	
	$("#product-filter .checkbox-span").click(function(){
		clearTimeout(filterTimeout);
		var r = $(this).parents(".filter-container").attr("id");
		var divparentname = '#' + r + ' .checkbox-image';
		toggleCheckboxOff($(divparentname));
		$(this).siblings().removeClass('off').addClass('on').attr("src", "img/icons/checkbox_on.gif");
		showProductList();
	});
		
	$("#product-price-filter .checkbox-all-image").click(function(){
		clearTimeout(filterTimeout);
		var s = toggleCheckbox($(this));
		toggleCheckbox($("#product-price-filter .checkbox-image"), s);
		showProductList();
	});

	
	$("#product-flag-filter .checkbox-all-image").click(function(){
		clearTimeout(filterTimeout);
		var s = toggleCheckbox($(this));
		toggleCheckbox($("#product-flag-filter .checkbox-image"), s);
		showProductList();
	});


	$("#product-packagingtype-filter .checkbox-all-image").click(function(){
		clearTimeout(filterTimeout);
		var s = toggleCheckbox($(this));
		toggleCheckbox($("#product-packagingtype-filter .checkbox-image"), s);
		showProductList();
	});
	
	$("#product-subtitles-filter .checkbox-all-image").click(function(){
		clearTimeout(filterTimeout);
		var s = toggleCheckbox($(this));
		toggleCheckbox($("#product-subtitles-filter .checkbox-image"), s);
		showProductList();
	});

	$("#product-origintype-filter .checkbox-all-image").click(function(){
		clearTimeout(filterTimeout);
		var s = toggleCheckbox($(this));
		toggleCheckbox($("#product-origintype-filter .checkbox-image"), s);
		showProductList();
	});
	
	$("#product-languageversions-filter .checkbox-all-image").click(function(){
		clearTimeout(filterTimeout);
		var s = toggleCheckbox($(this));
		toggleCheckbox($("#product-languageversions-filter .checkbox-image"), s);
		showProductList();
	});

	$("#product-stockavailability-filter .checkbox-all-image").click(function(){
		clearTimeout(filterTimeout);
		var s = toggleCheckbox($(this));
		toggleCheckbox($("#product-stockavailability-filter .checkbox-image"), s);
		showProductList();
	});
	
	$("#product-genre-filter .checkbox-all-image").click(function(){
		clearTimeout(filterTimeout);
		var s = toggleCheckbox($(this));
		toggleCheckbox($("#product-genre-filter .checkbox-image"), s);
		showProductList();
	});
	
	$("#customer-info-form #PreviousOrderShipping").change(function(){
		var v = $(this).val();
		if (v != '') {
			var address = eval(v);
			$("#ShippingContactPerson").val(address[0]);
			$("#ShippingAddress").attr("value", address[1]);
			$("#ShippingZIP").attr("value", address[2]);
			$("#ShippingCity").attr("value", address[3]);
			$("#ShippingCountryID").val(address[4]);
		}
		else {
			$("#ShippingContactPerson").val("");
			$("#ShippingAddress").attr("value", "");
			$("#ShippingZIP").attr("value", "");
			$("#ShippingCity").attr("value", "");
			$("#ShippingCountryID").val("");
		}
	});
	
	$("#customer-info-form #ShippingAddressDifferent").click(function(){
		if ($(this).attr("checked")){
			$("#ShippingAddressForm").show();
			$("#ShippingContactPerson").val("");
			$("#ShippingAddress").attr("value", "");
			$("#ShippingZIP").attr("value", "");
			$("#ShippingCity").attr("value", "");
			$("#ShippingCountryID").val("");
		}
		else {
			$("#ShippingAddressForm").hide();
		}
	
	});
	
	$("#customer-info-form").submit(function(){
		if (!$("#ShippingAddressDifferent", this).attr("checked") && $("#ShippingAddressFromOrder", this).val() == 0) {
			$("#ShippingContactPerson").val($("#firstName").val() + " " + $("#lastName").val());
			$("#ShippingAddress").attr("value", $("#Address").val());
			$("#ShippingZIP").attr("value", $("#ZIP").val());
			$("#ShippingCity").attr("value", $("#City").val());
			$("#ShippingCountryID").val($("#CountryID").val());
		}
		//return false;
	});
	
	/*
	$("#shipping-form input[name=ShippingPriceID]").change(function(){
		if (this.value != '') $("#shipping-form").submit();
		
	});
	*/
	/*
	In IE - event .change not work correctly. Must be used .click event in IE
	*/
	$("#shipping-form input[name=ShippingPriceID]").bind(($.browser.msie ? "click" : "change"), function(){
		
		var topPosition = $("#shipping-form").position().top;
		var leftPosition = $("#shipping-form").position().left;
		var elementWidth = $("#shipping-form").width();
		var elementHeight = $("#paymentMethod-list").position().top + $("#paymentMethod-list").height() - topPosition;
		
		$("#main-container").append("<div id='ajaxLoading' style='display: block; position: absolute; background: transparent url(./img/bg_dark-transparent.png) repeat; top: " + topPosition + "px; left: " + leftPosition + "px; width: " + elementWidth + "; height: " + elementHeight + "px;'><div><div style='position: relative; top: " + ((elementHeight/2)-7) + "px; left: " + ((elementWidth/2)-64) + "px;'><img src='img/ajax-loader.gif' alt='loading' title='loading'></div></div></div>");
		$.ajax({
				type: "POST",
				url: "ajax/setOrderSession.cfm",
				data: "shippingPriceId=" + $(this).val(),
				success: function(){
					$("#totalOrderCost").load('indexAjax.cfm?module=basket&page=totalOrderCostAjax', {'shippingPriceId': $(this).val()});
					$("#paymentMethod-list").load('indexAjax.cfm?module=basket&page=paymentMethodListAjax', {'shippingPriceId': $(this).val()}, function(){
											if($("#contactRequired_id").val() == '0'){ $("#contactRequiredRow").attr("style","display: none");} 
											else { $("#contactRequiredRow").attr("style","");}
										});
					$("#ShippingPackaging-cost").load('indexAjax.cfm?module=basket&page=shippingPackagingCostAjax', {'shippingPriceId': $(this).val()});
					$("#ajaxLoading").remove();
			    }
			});
	});
	
	$(".registration-suggest-toggle").click(function(){
		$("#registration-suggest form[name=UserRegisterForm]").show("fast");
	});
	

	
    $("form#OrderByFilter_id #OrderBy_id").bind("change", function(e){
		applyOrdering(e);
    });

	/*
	$("form#OrderByFilter_id #OrderBy_id").change(function(){
		var o = $(this).val();
		var o = o.split("|");
		var base = $("form#OrderByFilter_id #BaseUrl_id").val();
		location.replace(base + "&OrderBy=" + o[0] + "&OrderType=" + o[1]);
	});
	*/
	
	/*$("#ajax-loading").bind("ajaxSend", function(){
		$(this).show();
		$(this).html('<img src=\"img/ajax-loader.gif\" width=\"128\" height=\"15\" alt=\"\">');
	}).bind("ajaxComplete", function(){
		$(this).hide();
		$(this).html('');
	});*/

	/* manage costomerInfoForm radio buttons (shipping addresses)  START */
	$("#CustomerInfoForm #PreviousOrderShipping").change(function(){
		var v = $(this).val();
		if (v != '') {
			var address = eval(v);
			$("#ShippingFirstName").attr("value", address[0]);
			$("#ShippingLastName").attr("value", address[1]);
			$("#ShippingAddress").attr("value", address[2]);
			$("#ShippingZIP").attr("value", address[3]);
			$("#ShippingCity").attr("value", address[4]);
			$("#ShippingCountryID").val(address[5]);
		}
		else {
			$("#ShippingFirstName").attr("value", "");
			$("#ShippingLastName").attr("value", "");
			$("#ShippingAddress").attr("value", "");
			$("#ShippingZIP").attr("value", "");
			$("#ShippingCity").attr("value", "");
			$("#ShippingCountryID").val("");
		}
	});
	
	$("#CustomerInfoForm").submit(function(){
		if (!$("#ShippingAddressDifferent", this).attr("checked") && $("#ShippingAddressFromOrder", this).val() == 0) {
			$("#ShippingFirstName").attr("value", $("#FirstName").val());
			$("#ShippingLastName").attr("value", $("#LastName").val());
			$("#ShippingAddress").attr("value", $("#Address").val());
			$("#ShippingZIP").attr("value", $("#ZIP").val());
			$("#ShippingCity").attr("value", $("#City").val());
			$("#ShippingCountryID").val($("#CountryID").val());
		}
		//return false;
	});
	
	$("#CustomerInfoForm #ShippingAddressInvoice").click(function(){
		if ($(this).attr("select")){
			$("#ShippingAddressForm").hide();
			$("#SelectShippingAddress").hide();
		}
	
	});
	
	$("#CustomerInfoForm #ShippingAddressOther").click(function(){
		if ($(this).attr("select")){
			$("#ShippingAddressForm").show();
			$("#SelectShippingAddress").show();
			$("option:first", "#CustomerInfoForm #SelectShippingAddress #PreviousOrderShipping").attr("selected","selected");
			var v = $("option:first", "#CustomerInfoForm #PreviousOrderShipping").val();
			if (v != undefined && v != null && v != '') {
				var address = eval(v);
				$("#ShippingFirstName").attr("value", address[0]);
				$("#ShippingLastName").attr("value", address[1]);
				$("#ShippingAddress").attr("value", address[2]);
				$("#ShippingZIP").attr("value", address[3]);
				$("#ShippingCity").attr("value", address[4]);
				$("#ShippingCountryID").val(address[5]);
			}
			else {
				$("#ShippingFirstName").attr("value", "");
				$("#ShippingLastName").attr("value", "");
				$("#ShippingAddress").attr("value", "");
				$("#ShippingZIP").attr("value", "");
				$("#ShippingCity").attr("value", "");
				$("#ShippingCountryID").val("");
			}
		}	
	});
	
	$("#CustomerInfoForm #ShippingAddressNew").click(function(){
		if ($(this).attr("select")){
			$("#ShippingAddressForm").show();
			$("#SelectShippingAddress").hide();
			$("#ShippingAddress").attr("value", "");
			$("#ShippingZIP").attr("value", "");
			$("#ShippingCity").attr("value", "");
			$("#ShippingCountryID").val("");
			$("#ShippingFirstName").val("");
			$("#ShippingLastName").val("");;
		}
	});
	/* manage costomerInfoForm radio buttons (shipping addresses) END */

});