/***********************************************
***  PRELOAD IMAGES     ************************
************************************************/

$("<img>").attr("src", "/images/icons/ico-arrow-bullet-white.gif");

/***********************************************
***  BUTTON ROLLOVER & PRELOAD  ****************
************************************************/

$(function(){
	// button rollover
	if ($('.imgBtn') != null) {
		$('.imgBtn').hover(function(){
				if(!$(this).is('.disabled'))
					$(this).attr("src", $(this).attr("src").replace(/^(.*?)(?:-hover)?(\..*?)$/i,'$1-hover$2'));
			},
			function(){
					if(!$(this).is('.disabled'))
						$(this).attr("src", $(this).attr("src").replace(/^(.*)-hover(\..*?)$/i, '$1$2'));
				});
	}
	// preload image rollovers
	if ($("img.imgBtn, img[src^='images/buttons/btn'], input[src^='images/buttons/btn']") != null) {
	    $("img.imgBtn, img[src^='images/buttons/btn'], input[src^='images/buttons/btn']").each(function(){
			    $("<img>").attr("src", $(this).attr("src").replace(/(btn-.*)(\..*?)/i, '$1-hover$2'));
		    });
	}
});

/***********************************************
***  EXTERNAL LINKS  ***************************
************************************************/

$(document).ready(function() {
	$("a[rel=external]").each(function() {
		$(this).addClass('external');
		$(this).attr({
			title: "Open this page in a new window",
			target: "_blank"
		});
	})
});

/***********************************************
***  COMPACT FORM (LABEL OVER INPUT)  **********
************************************************/

$(function(){
	$('.compactForm input, .compactForm select, .compactForm textarea').focus(function(){
			$('label[for=' + $(this).attr('id') + ']').hide();
		});
	$('.compactForm input, .compactForm select, .compactForm textarea').each(function(ele){
			if($(this).val().length > 0)
				$('label[for=' + $(this).attr('id') + ']').css({ display: "none" });
		});
	$('.compactForm input, .compactForm select, .compactForm textarea').blur(function(){
			if($(this).val().length == 0)
				$('label[for=' + $(this).attr('id') + ']').show();
		});
	$('.compactForm').removeClass('compactForm');
});

/***********************************************
***  ADD CLASS=FOCUSED  ************************
************************************************/

$(function(){
        $("#headerControls .inputContainer input, .sidebarBlock #postCodeCheck .textContainer input").focus(function() {
            $(this).parent().addClass("focus")
        }).blur(function() {
            $(this).parent().removeClass("focus")
        })
});


/***********************************************
***  LOGIN TABS  *******************************
************************************************/

$(function(){
	$("#headerControls .tabs li").click(function() {
	    if(!$(this).hasClass('selected')) {
			$(this).addClass('selected');
			$(this).siblings().removeClass('selected');
			
			if($(this).attr('id') == "loginTab") {
				$(function(){ 
					$('#headerControls').attr('className', 'controlsLogin')
				});
			}
			if($(this).attr('id') == "searchTab") {
				$(function(){ 
					$('#headerControls').attr('className', 'controlsSearch')
				});
			}
			if($(this).attr('id') == "signupTab") {
				$(function(){ 
					$('#headerControls').attr('className', 'controlsSignup')
				});
			}
			if($(this).attr('id') == "myAccountTab") {
				$(function(){ 
					$('#headerControls').attr('className', 'controlsMyAccount')
				});
			}
		}
    	});
});


/***********************************************
***  TEXT SIZING  ******************************
************************************************/

$(function(){
	$('#pageControls #textSizeUp').click(function(){
			ts('main',1);
		});
	$('#pageControls #textSizeDown').click(function(){
			ts('main',-1);
		});
});


/***********************************************
***  EQUAL HEIGHT TABS  ************************
************************************************/

function equalHeight(group) {
	tallest = 0;
	group.each(function() {
		thisHeight = $(this).height();
		if(thisHeight > tallest) {
		    tallest = thisHeight;
		}
	});
	if ($.browser.msie && $.browser.version.substring(0,1) === '6'){
		group.css('height',tallest);
	}
	else {
		group.css('min-height',tallest);
	}
}

function equalHeightRow(group) {
	var tmp = [];
	group.each(function() {
			var b =  $(this);
			var a = {
					'ele': b,
					'top' : Math.round(b.position().top),
					'height': Math.round(b.height())
				};
			tmp.push(a);
		});
	while(tmp.length){
		var b = tmp.pop();
		var c = [];
		c.push(b);
		for(var i=tmp.length; i--;){
			if(tmp[i].top === b.top){
				var z = tmp.splice(i, 1)[0];
				c.push(z);
			}
		}
		var d = 0;
		for(var j=c.length; j--;){
			d = Math.max(d, c[j].height);
		}
		var s = ($.browser.msie && $.browser.version.substring(0,1) === '6') ? 'height' : 'min-height';
		for(var k=c.length; k--;){
			c[k].ele.css(s, d);
		}
	}
}

/***********************************************
***  SIDEBAR PROMO TILES  **********************
************************************************/

$(document).ready(function() {

	$(".sidebarBlock .promoTile").hover(function() { 

		var thumbOver = $(this).find("img").attr("src");
		$(this).find("a").css({'background' : 'url(' + thumbOver + ') no-repeat center bottom'});
		$(this).find("span").stop().fadeTo('fast', 0 , function() {
			$(this).hide()
		});
	} , function() { 
		$(this).find("span").stop().fadeTo('fast', 1).show();
	});

});


/***********************************************
***  CUSTOM SELECT BOX  ************************
************************************************/

$('html').addClass('jsEnabled');

$(function(){
	$('.selectReplace').selectbox({maxHeight:400});
});


/***********************************************
***  TOOLTIP  **********************************
************************************************/

$(document).ready(function() {
	$(".checkoutError").each(function(){
			var trigger = $(this);
			var title = trigger.attr('title');
			trigger.tooltip({
					tip: '.errorTooltip', 
					position: 'bottom right',
					effect: 'slide',
					predelay: 10,  
					delay: 10,
					lazy: false,
					onBeforeShow: function(){
						$('.errorTooltip').html(title);
					}
				});
		});
		$(".cvcInfo").each(function(){
			var trigger = $(this);
			trigger.tooltip({
					tip: '.cvcTooltip', 
					offset: [-5, -170],
					effect: 'slide',
					lazy: false
				});
		});
});

/***********************************************
***  PROGRESSIVE ENHANCEMENT  ******************
************************************************/

$(function() {

	// Set .first / .last class
	$(".productList > li:nth-child(4n-3)").addClass("first");
	$(".recipeList > li:nth-child(3n-2)").addClass("first");
	$(".productCategoryList > li:nth-child(3n-2)").addClass("first");
	$(".moreRecipes li:last").addClass("last");
	$(".subNav > li:first").addClass("first");
		
	// Set .first and .last on submenu sets
	$(".flyout > li:last").addClass("last");
	$(".flyout > li:first").addClass("first");

	// Zebra striping
	$(".productItemList li:nth-child(2n)").addClass("dark");
	$(".checkoutTable tr:nth-child(2n-1)").addClass("dark");
	$(".orderHistory tr:nth-child(2n-1)").addClass("dark");
	
	// Set equal heights
	$(document).ready(function() {
	    equalHeightRow($(".productCategoryList > li"));
	    equalHeightRow($(".productList .productContent"));
	    equalHeight($(".flyout > li"));
	    equalHeight($(".tabContent > li"));
	    equalHeight($(".detailsCheckout fieldset:not(.orderForm1)"));
		equalHeight($(".detailsCheckout fieldset.orderForm1"));
	    equalHeightRow($(".recipeListContent"));
	});
	
	// Activate tabs
	$('.tabContent').addClass('hasJS')
	$('.tabMenu li').geeTabs({tabbedContentSelector: '.tabContent > li'});

	// Fix jumping tabs 
	$(".tabContent").css('min-height', $(".tabContent > li").height())

	// Fade in mega flyout 
	$(".flyout").hide();
	$("#menu > li").hover(function(){
			$(this).find(".flyout").stop(true, true).css('visibility','visible').fadeIn("fast");
		},
		function(){
				$(this).find(".flyout").stop(true, true).fadeOut("fast", function() { $(this).css('visibility','hidden') });
			});
	$(window).unload(function(){
			$(".flyout").stop(true, true);
		});
	
	$(".flyoutNarrow").hide();
	$("#menu > li").hover(function(){
			$(this).find(".flyoutNarrow").stop(true, true).css('visibility','visible').fadeIn("fast");
		},
		function(){
				$(this).find(".flyoutNarrow").stop(true, true).fadeOut("fast", function() { $(this).css('visibility','hidden') });
			});
	$(window).unload(function(){
			$(".flyoutNarrow").stop(true, true);
		});
	

	
});


function isPositiveNumber(inStr){
	//var numRegex = !/^-?\d+$/;
	return /^\d+$/.test(inStr);
}


/***********************************************
***  Add item to shopping cart  ****************
************************************************/
$(function() {
	var qtyAjaxDelay = undefined;
	$('form.qtyForm,form.orderForm').submit(function(){
			//alert($(this).find("input[name='idProduct']").val());
			var t = this;
			var idProduct = $(this).find("input[name='idProduct']").val();
			var qty = $('#qty' + idProduct).val();
			var action = $(this).attr('action');

			var errorMsgs = new Array();
			var x = 0;

			if (!isPositiveNumber(qty)) {
				errorMsgs[x] = 'Please enter a valid qty.';
				x++;
			}else{
				if (parseInt(qty) == 0){
					errorMsgs[x] = 'Please enter a valid qty.';
					x++;				
				}
			}
			if (errorMsgs.length > 0) {
				$('#msgPanel'+idProduct).html('<div class="msgError">' + errorMsgs.join("<br/>") + '</div>');
				return false;
			} else {
				//return false;
				// Add items to cart

				//alert($('#hideFields').val());
				if ($('#hideFields')){
					$(t).find('.inputContainer').hide();
					$(t).find('.addBtn').hide();
					$(t).find('.price').hide();
					if($('#hideFields').val() == '2'){
						$(t).hide();
					}
				}
				$('#msgPanel'+idProduct).html('<div class="msgLoading">Updating your Cart&hellip;</div>');

				if (qtyAjaxDelay !== undefined){clearTimeout(qtyAjaxDelay);}
				qtyAjaxDelay = setTimeout(function(){
					$.ajax({type: "POST",
							url: action,
							dataType: 'json',
							data: { 'ajaxapp'	: 'AddToCart',
									'idProduct'	: idProduct,
									'qty'	: qty },
							beforeSend: function() {
								$('#qty' + idProduct).val('');
							},
							success: function(r) {
								
								if ($('#hideFields').length>=0){
									$(t).find('.inputContainer').hide();
									$(t).find('.addBtn').hide();
									$(t).find('.price').hide();
									$('#msgPanel'+idProduct).html(r.root.msgText);
									
								}else{
									$('#msgPanel'+idProduct).html('<div class="msgSuccess">Item added</div>');
								}
								
								if ($('#itemCount').length == 0){
									//alert(r.root.msgCart)
									$('.shoppingCartStats').first().html(r.root.msgCart);
								}else{
									$('#itemCount').html(r.root.orderItems)	
									$('#priceCount').html(r.root.orderTotal)
								}
							},
							error: function() {
								alert('Problem updating. Please try again.');
							}
					});
				},500);
			}
			return false;
		
		});
});


/***********************************************
***  Check Delivery Availability  **************
************************************************/
$(function() {
	var postcodeAjaxDelay = undefined;

	$("#postCodeCheck a[href='#']").click(function(){
		$('#postCodeCheck .pcodeUnavailable').hide();
		$('#postCodeCheck .pcodeAvailable').hide();
		$('#postCodeCheck form').show();
		return false;
	});
	$('#postcodeCheckBtn').click(function(){
		var postcode = $('#postcodeCheckInput').val();
		var errorMsgs = new Array();
		var x = 0;
		var action = $(this).closest('form').attr('action');
		if (!isPositiveNumber(postcode)) {
			errorMsgs[x] = 'Please enter a valid postcode.';
			x++;
		}else{
			if (parseInt(postcode) < 3000 || parseInt(postcode) > 3999){
				errorMsgs[x] = 'Please enter a valid postcode.';
				x++;				
			}
		}
		if (errorMsgs.length > 0) {
			$('#postCodeCheck form').hide();
			$('#postCodeCheck .pcodeUnavailable').show();
		} else {
			$('#postCodeCheck form').hide();
			$('#postCodeCheck .pcodeChecking').show();
			if (postcodeAjaxDelay !== undefined){clearTimeout(postcodeAjaxDelay);}
			
			postcodeAjaxDelay = setTimeout(function(){
				$.ajax({type: "POST",
						url: "/index.asp",
						dataType: 'json',
						data: { 'ajaxapp'	: 'CheckPostcodeAvailability',
								'postcode'	: postcode},
						beforeSend: function() {
							$('#postcodeCheckInput').val('');
						},
						success: function(r) {
							var status = r.root.status
							if (status){
								$('#postCodeCheck .pcodeChecking').hide();
								$('#postCodeCheck .pcodeAvailable').children().first().html(r.root.msg);
								$('#postCodeCheck .pcodeAvailable').show();
							}else{
								$('#postCodeCheck .pcodeChecking').hide();
								$('#postCodeCheck .pcodeUnavailable').show();
							}
						},
						error: function() {
							alert('Problem updating. Please try again.');
						}
				});
			},500);
		}
		return false;
	});
});

/***********************************************
***  FORM  AUTHORISATION ***********************
************************************************/
$(function() {
	$('#formContactus, #formSignup').prepend('<input type="hidden" name="formAuth" value="001" />');
});

/***********************************************
***  CHECKOUT  ******************
************************************************/
$(function() {
		var fldArr = ['memDelFirstname', 'memDelLastname', 'memDelCompany', 'memDelAddress', 'memDelSuburb', 'memDelPostcode'];

		/* create account checkbox */
		$('#createAccount').click(function(){
			if (this.checked){
				$('fieldset.orderForm1').show();
			}else{
				$('fieldset.orderForm1').hide();				
			}
		})


		/* same as billing key sync */
		$('#sameAsBilling').click(function(){
				if($(this).is(':checked')){
					$(this).closest('fieldset').find('ol:first input[type="text"], ol:first select').attr('disabled', 'disabled');
					$('#memDelFirstname').val($('#memFirstname').val());
					$('#memDelLastname').val($('#memLastname').val());
					$('#memDelCompany').val($('#memCompany').val());
					$('#memDelAddress').val($('#memBillAddress').val());
					$('#memDelSuburb').val($('#memBillSuburb').val());
					changeSelectedValue('#memDelState', $('#memBillState').val());
					$('#memDelPostcode').val($('#memBillPostcode').val());
					for (var i =0; i<fldArr.length; i++){
						checkLabel(fldArr[i]);
					}
				}else{
					$(this).closest('fieldset').find('ol:first input[type="text"], ol:first select').removeAttr('disabled');
				}
			});

		$('#sameAsBilling:checked').each(function(){
			if($(this).is(':checked')){
				$(this).closest('fieldset').find('ol:first input[type="text"], ol:first select').attr('disabled', 'disabled');
				$('#memDelFirstname').val($('#memFirstname').val());
				$('#memDelLastname').val($('#memLastname').val());
				$('#memDelCompany').val($('#memCompany').val());
				$('#memDelAddress').val($('#memBillAddress').val());
				$('#memDelSuburb').val($('#memBillSuburb').val());
				changeSelectedValue('#memDelState', $('#memBillState').val());
				$('#memDelPostcode').val($('#memBillPostcode').val());
			}
		});
		

		function registerShippingSync(bI, sI){
			$('#' + bI).keyup(function(){
				if($('#sameAsBilling').is(':checked')) {
					var id = this.id;
					$('#' + sI).val($(this).val());
					checkLabel(sI);
				}
				if (this.id == 'memBillPostcode' && $('#sameAsBilling').is(':checked')  || this.id == 'memDelPostcode'){
					// do ajax call
					refreshShipping();
				}
			});

			$('#' + bI).change(function(){
				if($('#sameAsBilling').is(':checked')) {
					changeSelectedValue('#' + sI, $(this).val()) 
				}
			});
		}		
		

		function checkLabel(sI){
			if($('#' + sI).val().length == 0){
				$('label[for=' + sI + ']').show();
			}else{
				$('label[for=' + sI + ']').hide();
			}
		}


		if ($('input#sameAsBilling:enabled').length > 0){
			registerShippingSync('memFirstname', 'memDelFirstname');
			registerShippingSync('memLastname', 'memDelLastname');
			registerShippingSync('memCompany', 'memDelCompany');
			registerShippingSync('memBillAddress', 'memDelAddress');
			registerShippingSync('memBillSuburb', 'memDelSuburb');
			registerShippingSync('memBillState', 'memDelState');
			registerShippingSync('memBillPostcode', 'memDelPostcode');
			for (var i =0; i<fldArr.length; i++){
				checkLabel(fldArr[i]);
			}
			/* register additional memDelPostcode event handlers */

			$('#memDelPostcode').keyup(function(){
				if($('#sameAsBilling').is(':checked')){
					return false;
				}else{
					refreshShipping();
				}
			});

			$('#memDelPostcode').change(function(){
				if($('#sameAsBilling').is(':checked')){
					return false;
				}else{
					refreshShipping();
				}
			});



		}


		$('.restrict1000').keyup(function() {
			if ($(this).val().length > 1000)
				$(this).val($(this).val().substring(0, 1000));
		});


		// add a script block to the page which allows you to apply the modifier from this.

		// setup currency formatting. Probly don't need to change this.
		$.formatCurrency.regions['']. negativeFormat = '-%s%n';

		// calculate shipping
		var lastPostCode = null;
		var postcodeDelay = undefined;

		function refreshShipping(){
			var postCode = $('#memDelPostcode').val();
			//if(postCode.length < 3 || postCode.length > 4){return;}; 
			if(postCode == lastPostCode) {return;};

			lastPostCode = postCode;
			if (window.location.href.indexOf('checkout.asp') != -1) {		
				
				if (postcodeDelay !== undefined)
					clearTimeout(postcodeDelay);
				
				postcodeDelay = setTimeout(function() {
					$.ajax({type: "POST",
							url: $('#checkoutForm').attr('href'),
							dataType: 'json',
							data: $('#checkoutForm').serialize() + '&ajaxapp=CheckPostcode&postcode=' + postCode,
							success: function(r) {
								$('#shippingTotal').text(r.root.shippingTotal).formatCurrency();
								$('#surchargeTotal').text(r.root.surchargeTotal).formatCurrency();
								$('#couponValue').text('-'+r.root.couponValue).formatCurrency();
								$('#discountTotal').text('-'+r.root.discountTotal).formatCurrency();
								$('#orderTotal').text(r.root.orderTotal).formatCurrency();
							},
							error: function() {
								alert('Problem checking postcode. Please try again.');
							}
					});
				}, 250);
			}
		}

			
		$('#memDelPostcode').change(refreshShipping);
		$('#sameAsBilling').change(refreshShipping);


		// Dynamically updates discount and total
		var totalsDelay = undefined;
		function updateTotals() {
			if (totalsDelay !== undefined)
				clearTimeout(totalsDelay);
			
			totalsDelay = setTimeout(function() {
				$.ajax({type: "POST",
						url: $('#checkoutForm').attr('href'),
						dataType: 'json',
						data: $('#checkoutForm').serialize() + '&ajaxapp=UpdateDiscount',
						success: function(r) {
							$('#shippingTotal').text(r.root.shippingTotal).formatCurrency();
							$('#surchargeTotal').text(r.root.surchargeTotal).formatCurrency();
							$('#couponValue').text('-'+r.root.couponValue).formatCurrency();
							$('#discountTotal').text('-'+r.root.discountTotal).formatCurrency();
							$('#orderTotal').text(r.root.orderTotal).formatCurrency();
						},
						error: function() {
							alert('Problem checking discounts. Please try again.');
						}
				});
			}, 250);
		}

		$('#couponCode, #promotionCode').keyup(updateTotals);
		
		$('input[name="paymentMethod"]').change(function() {
			updateTotals();

			if ($(this).val() == '1') {
				// Credit Card Selected
				$('#bankTransferOption').hide();
				$('#creditCardOption').show();
			} else if ($(this).val() == '2') {
				// Bank Transfer Selected
				$('#creditCardOption').hide();
				$('#bankTransferOption').show();
				
			}
		});


		$('#btnEditOrder').click(function() {
			$('input[name="formID"]').val('00');
		});


		$('input[name^="qty"]').keypress(function(e){
			var a = e.which;
			if(((a >= 32 && a <= 126) || a === 128 || (a >= 130 && a <= 140) || a === 142 || (a >= 145 && a <= 156) || (a >= 158 && a <= 255)) && isNaN(String.fromCharCode(a)))
				return false;
		});
		$('input[name^="qty"]').focus(function(){
			this.select();
			
		});


});

var timesSubmitted = 0;
function submitPayment(){
	if (timesSubmitted == 0){
		$("a").click(function(){ 
			return false; 
		});
		//$('#btnProcess').html('<p>Processing Credit Card Transaction.  Please be patient.<img src="/images/ajax/ajax-loader-2.gif" alt="loading" /></p>')
		
		$('#checkoutForm').submit();
		timesSubmitted ++;
	}else{
		alert("Payment has already been submitted, please be patient");
	}
}
