﻿

var TIME_TO_DELAY_FADE_TEXT_WINDOW = 3000;
var DURATION_FADE_TEXT_WINDOW = 2000;

// Initialise JavaScript namespaces.

	Website = {};
	Website.Base = {};

// IE6 background image flicker fix.
try { document.execCommand("BackgroundImageCache", false, true); } catch (err) { }


// ## UTILS

Utils = { };

Utils.isMSIE = (navigator.userAgent.indexOf("MSIE") > -1) ? true : false;
Utils.isMSIE6 = (navigator.userAgent.indexOf("MSIE 6") > -1) ? true : false;


// ## ERROR BUBBLE
// this is used for form validation - it is used to highlight fields which have errors and display mouseover error message
ErrorBubble = { };
ErrorBubble.Visible = true;
ErrorBubble.ShowError = function(event, text) {
	if (ErrorBubble.Visible) {
		var e = new Event(event);
		var bubble = $('FormErrorBubble');
		var caller = Utils.isMSIE ? $(e.relatedTarget) : $(e.target);
        
		bubble.DoShow = true;
        
		if (caller.init != true) {
			caller.addEvent("mousemove", function(e) { ErrorBubble.MouseMove(e); });
			caller.addEvent("mouseout", function(e) { ErrorBubble.MouseOut(e); });
			caller.init = true;
		}
        
		$('errorBubbleText').innerHTML = text;
		bubble.setStyle("display", "block");
	}
}

ErrorBubble.MouseOut = function() {
    var bubble = $('FormErrorBubble');
    bubble.DoShow = false;
    
    clearInterval(bubble.interval);
    bubble.interval = setInterval("ErrorBubble.HideBubble();", 100);
}

ErrorBubble.HideBubble = function() {
	 var bubble = $('FormErrorBubble');
	 
	 if (!bubble.DoShow) {
		bubble.setStyle("display", "none");
	}
}

ErrorBubble.MouseMove = function(e) {
    if(e.page ==null) {
        return;
    }
    var bubble = $('FormErrorBubble');
    var top = e.page.y - 6;
    var left = e.page.x + 14;
    if (bubble.DoShow) {
		bubble.setStyle("top", top + "px");
		bubble.setStyle("left", left + "px");
	}
}

// ## OVERLAY

Overlay = { };

Overlay.BACKDROP_ID = "OverlayBackdrop";
Overlay.OPEN_OVERLAY = null;

Overlay.OpenWindow = function(id, showBackdrop) {
	if (showBackdrop == null) { showBackdrop = true; }
	if (showBackdrop) { Overlay.ShowBackdrop(); }
	Overlay.SetupOverlay(id);	
	Overlay.OPEN_OVERLAY = id;
}

Overlay.OpenWindowVariable = function(id) {
	var container = $(id);
	Overlay.OpenWindow(id);

	if (!container.SetupComplete) {
		var content = container.getElement(".popupBody");
		
		var bodyHeight = $(document.body).getHeight().toInt();
		var contentHeight = content.getHeight().toInt();

		if (contentHeight > bodyHeight - 200) {
			content.setStyle("height", (bodyHeight - 200) + "px");
			content.setStyle("overflow", "auto");
		}

		container.SetupComplete = true;
	}

	// Adjust the position and so forth as heights don't get calculated properly until all of the objects are visible.
	Overlay.AdjustPosition(id);
}

Overlay.CloseWindow = function() {
	Overlay.HideBackdrop();
	
	if (Overlay.OPEN_OVERLAY) {
		$(Overlay.OPEN_OVERLAY).setStyle("display", "none");
	}
}

Overlay.SetupOverlay = function(id) {
	var container = $(Overlay.BACKDROP_ID);
	var overlay = $(id);
	
	if (container == null) {
		container = $(document.body);
	}

	if (!overlay.Setup) {
		overlay.inject(container);
		overlay.addClass("Overlay");
		
		overlay.Setup = true;
	}
	
	overlay.setStyle("display", "block");
	Overlay.AdjustPosition(id);
}

Overlay.AdjustPosition = function(id) {
	var container = $(Overlay.BACKDROP_ID);
	var overlay = $(id);
	
	if (container == null) {
		container = $(document.body);
	}

	// Position in the middle of the container.
	var containerHeight = container.getHeight().toInt();
	var overlayHeight = overlay.getHeight().toInt();
	var positionTop = Math.ceil(containerHeight / 2) - Math.ceil(overlayHeight / 2);
	
	overlay.setStyle("margin-top", positionTop + "px");
}

Overlay.ShowBackdrop = function() {
	var backdropContainer = Overlay.SetupBackdrop();
	backdropContainer.setStyle("display", "block");
}

Overlay.HideBackdrop = function() {
	var backdropContainer = $(Overlay.BACKDROP_ID + "Container");
	
	if (backdropContainer) {
		backdropContainer.setStyle("display", "none");
	}
}

Overlay.SetupBackdrop = function() {
	var body = $(document.body);
	
	var backdrop = $(Overlay.BACKDROP_ID);
	var backdropContainer = $(Overlay.BACKDROP_ID + "Container");
	if (backdrop == null)			{ backdrop				= new Element('div', { id: Overlay.BACKDROP_ID }); }
	if (backdropContainer == null)	{ backdropContainer		= new Element('div', { id: Overlay.BACKDROP_ID + 'Container', style: 'display: none;' }); }
	
	backdrop.inject(backdropContainer);
	backdropContainer.inject(body);
	
	// If this is MSIE6, then we will have to adjust the position of the backdrop using JavaScript.
	if (Utils.isMSIE6) {
		backdropContainer.interval = setInterval("Overlay.AdjustBackdropPosition();", 10);
	}
	
	return backdropContainer;
}

Overlay.AdjustBackdropPosition = function() {
	var backdropContainer = $(Overlay.BACKDROP_ID + "Container");
	
	backdropContainer.setStyle("top", (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px");
	backdropContainer.setStyle("left", (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px");
}


// ## FORM VALIDATION

FormValidation = { };


// PRODUCT PAGE STOCK AVAILABILITY
FormValidation.postCodeNew = function() {
var txtPostcode = $('ctl00_ctl00_cBodyContainer_cBodyContainer_txtPostCodeNew');
	var hasError = false;

	txtPostcode.onmouseover = null;
	txtPostcode.removeClass("containsErrors");
	if (txtPostcode.value == '')
	{
		txtPostcode.onmouseover = function(e) { ErrorBubble.ShowError(e, "Please enter your Postcode"); };
		txtPostcode.addClass("containsErrors");
		hasError = true;
	}

		return !hasError;

}

FormValidation.postCodePO = function() {
var txtPostcode = $('ctl00_ctl00_cBodyContainer_cBodyContainer_txtPostCodePO');
	var hasError = false;

	txtPostcode.onmouseover = null;
	txtPostcode.removeClass("containsErrors");
	if (txtPostcode.value == '') {
		txtPostcode.onmouseover = function(e) { ErrorBubble.ShowError(e, "Please enter your Postcode"); };
		txtPostcode.addClass("containsErrors");
		hasError = true;
	}

	return !hasError;
}


// ## MY ACCOUNT UTILITIES

MyAccount = {};

MyAccount.show = function(elm)
{
	$(elm).setStyle("display", "block");
}
	
MyAccount.hide = function(elm)
{
	$(elm).setStyle("display", "none");
}

// When a platform image is clicked toggle the selection of the associated platform checkbox.
MyAccount.selectPlatformCheckbox = function(associatedCheckbox)
{
	var checkbox = $(associatedCheckbox);
	if (checkbox)
	{
		checkbox.checked = !checkbox.checked;
	}
}

MyAccount.copyAddress = function(fromAccountList, toAccountList)
{
	// Copy from ==> to.
	var fromCount = fromAccountList.length;
	
	var fromControl;
	var toControl;
	var fromValue;
	for (var i = 0; i < fromCount; i++)
	{
		fromControl = $(fromAccountList[i]);
		toControl = $(toAccountList[i]);
		
		if (fromControl.type == "select-one")
		{
			fromValue = fromControl.selectedIndex;
			toControl.selectedIndex = fromValue;
		}
		else
		{
			fromValue = fromControl.get("value");
			toControl.set("value", fromValue);
		}
	}
}

MyAccount.disableControls = function(controlList, disabled)
{
	var controlCount = controlList.length;
	
	var control;
	for (var i = 0; i < controlCount; i++)
	{
		control = $(controlList[i]);
		control.disabled = disabled;
	}
}

MyAccount.updateControlPrefixes = function(containerPrefix, controlList)
{
	// Set up the prefixes.
	var validatorInfo;
	for (var i = 0; i < controlList.length; i++)
	{
		validatorInfo = controlList[i];
		validatorInfo.control = containerPrefix + validatorInfo.control;
		
		if (validatorInfo.type == "match")
		{
			validatorInfo.valueTest = containerPrefix + validatorInfo.valueTest;
		}
	}
}


//=====================
// Member Wishlist
//=====================
MyAccount.validateWishlistEmail = function()
{
	var isValid = false;
	
	var containerPrefix = "ctl00_ctl00_ctl00_cBodyContainer_cBodyContainer_cBodyContainer_wishlistEmail_";
	var controlList = [
		{control:"txtEmailAddress",	type:"emailRegex", message:"Please enter a valid Email Address"},
		{control:"txtMessage",type:"required",	message:"Please enter a message"}
	];
	
	// Set up the prefixes - this alters the items in the array.
	MyAccount.updateControlPrefixes(containerPrefix, controlList);
	
	isValid = MyAccount.validateForm(controlList);
	
	return isValid;
}


//=====================
// Registration/Login
//=====================
MyAccount.validateLogin = function()
{
	
	var isValid = false;
	
	var containerPrefix = "ctl00_ctl00_cBodyContainer_cBodyContainer_loginForm_";
	var controlList = [
		{control:"txtEmailAddress",	type:"emailRegex", message:"Please enter a valid Email Address"},
		{control:"txtPassword",type:"required",	message:"Please enter your Password"}
	];
	
	// Set up the prefixes - this alters the items in the array.
	MyAccount.updateControlPrefixes(containerPrefix, controlList);
	
	isValid = MyAccount.validateForm(controlList);
	
	return isValid;
}

MyAccount.validateSimpleRegistration = function()
{
	var isValid = false;
	
	var containerPrefix = "ctl00_ctl00_cBodyContainer_cBodyContainer_registrationForm_";
	var controlList = [
		{control:"txtFirstName",type:"required",	message:"Please enter your First Name"},
		{control:"txtLastName",	type:"required",	message:"Please enter your Last Name"},
		{control:"txtEmailAddress",	type:"emailRegex", message:"Please enter a valid Email Address"},
		{control:"txtEmailAddressConfirmation",	type:"emailRegex", message:"Please enter a valid Email Address"},
		{control:"txtPassword",	type:"required",	message:"Please enter your Password"},
		{control:"txtPasswordConfirmation",	type:"required",	message:"Please enter your Password Confirmation"},
		
		{control:"txtEmailAddress",	type:"match", valueTest:"txtEmailAddressConfirmation",	message:"Your Email must match Email Confirmation"},
		{control:"txtPassword",		type:"match", valueTest:"txtPasswordConfirmation",			message:"Your Password must match Password Confirmation"},
		
		{control:"txtPassword",		type:"min_length", valueTest:6,		message:"Your Password must be at least 6 characters long"}
	];
	
	// Set up the prefixes - this alters the items in the array.
	MyAccount.updateControlPrefixes(containerPrefix, controlList);
	
	isValid = MyAccount.validateForm(controlList);
	
	return isValid;
}

MyAccount.validateDetailedRegistration = function()
{
	var isValid = false;
	
	var containerPrefix = "ctl00_ctl00_cBodyContainer_cBodyContainer_detailedRegistrationForm_";
	var controlList = [
		{control:"txtFirstName",	type:"required",	message:"Please enter your First Name"},
		{control:"txtLastName",		type:"required",	message:"Please enter your Last Name"},
		{control:"txtEmailAddress",	type:"emailRegex", message:"Please enter a valid Email Address"},
		{control:"txtConfirmEmailAddress",	type:"emailRegex", message:"Please enter a valid Email Address"},
		{control:"txtPassword",		type:"required",	message:"Please enter your Password"},
		{control:"txtConfirmPassword",	type:"required",	message:"Please enter your Password Confirmation"},
		
		{control:"txtEmailAddress",	type:"match", valueTest:"txtConfirmEmailAddress",	message:"Your Email must match Email Confirmation"},
		{control:"txtPassword",		type:"match", valueTest:"txtConfirmPassword",		message:"Your Password must match Password Confirmation"},
		
		{control:"txtPassword",		type:"min_length", valueTest:6,		message:"Your Password must be at least 6 characters long"}
	];
	
	// Set up the prefixes - this alters the items in the array.
	MyAccount.updateControlPrefixes(containerPrefix, controlList);
	
	isValid = MyAccount.validateForm(controlList);
	
	if (isValid)
	{
		txtEmailAddress
		txtConfirmEmailAddress
		
		txtPassword
		txtConfirmPassword
	}
	
	return isValid;
}


//=====================
// Personal Details
//=====================
MyAccount.validatePersonalDetails = function()
{
	var isValid = false;
	
	var containerPrefix = "ctl00_ctl00_ctl00_cBodyContainer_cBodyContainer_cBodyContainer_personalDetailsForm_";
	var controlList = [
		{control:"txtFirstName",type:"required",	message:"Please enter your First Name"},
		{control:"txtLastName",	type:"required",	message:"Please enter your Last Name"},
		{control:"txtEmailAddress",	type:"emailRegex", message:"Please enter a valid Email Address"}
		
		//{control:"txtPassword",	type:"required",message:""},
	];
	
	var password = $(containerPrefix + "txtPassword");
	var passwordConfirmation = $(containerPrefix + "txtConfirmPassword");
	if (password.value.length > 0 || passwordConfirmation.value.length > 0)
	{
		var passwordCheck = {control:"txtPassword",		type:"min_length", valueTest:6,		message:"Your Password must be at least 6 characters long"};
		controlList.push(passwordCheck);
		passwordCheck = {control:"txtPassword",		type:"match", valueTest:"txtConfirmPassword",		message:"Your Password must match Password Confirmation"};
		controlList.push(passwordCheck);
	}
	
	// Set up the prefixes - this alters the items in the array.
	MyAccount.updateControlPrefixes(containerPrefix, controlList);
	
	
	isValid = MyAccount.validateForm(controlList);
	
	return isValid;
}


//=====================
// Forgotten Password
//=====================
MyAccount.validateResetPasswordForm = function()
{
	var isValid = false;
	
	var containerPrefix = "ctl00_ctl00_cBodyContainer_cBodyContainer_forgottenPasswordForm_";
	var controlList = [
		{control:"txtEmailAddress",	type:"emailRegex", message:"Please enter a valid Email Address"}
	];
	
	// Set up the prefixes - this alters the items in the array.
	MyAccount.updateControlPrefixes(containerPrefix, controlList);
	
	isValid = MyAccount.validateForm(controlList);
	
	return isValid;
}

//=====================
// Esimated Shipping Cost Postcode Sidebar
//=====================
MyAccount.validateEstimatedShippingCost = function(containerPrefix)
{
	var isValid = false;

	//var containerPrefix = "ctl00_ctl00_ctl00_cBodyContainer_cBodyContainer_cBodyContainer_sideBar_";
	var controlList = [
		{control:"itxPostCode",	type:"required", message:"Please enter a Postcode"},
		
		// We are assuming that the postcodeValidation.js file has been loaded in this page.
		{control:"itxPostCode",	type:"regex", valueTest:/^\d{3,4}$/i, message:"Enter a postcode 3 or 4 digit postcode"},
		{control:"itxPostCode",	type:"custom_function", valueTest:PostcodeValidation.ValidatePostcode,	message:"Please enter a valid Postcode"}
	];
	
	// Set up the prefixes - this alters the items in the array.
	MyAccount.updateControlPrefixes(containerPrefix, controlList);
	
	isValid = MyAccount.validateForm(controlList);
	
	return isValid;
}

MyAccount.showEstimatedShipping = function(containerPrefix)
{
	try
	{
		AjaxShippingCost.Show(containerPrefix);
	}
	catch (e)
	{
		
	}
}



MyAccount.validatePaymentForm = function() {
    var containerPrefix = "ctl00_ctl00_cBodyContainer_cBodyContainer_";
    var controlList = [
		{ control: "cbTermsAndConditions", type: "checked", message: "You must accept the terms and conditions" }
	];

    // Set up the prefixes - this alters the items in the array.
    MyAccount.updateControlPrefixes(containerPrefix, controlList);

    var controlErrorList = new Object();

    // trigger screen blockout if isvalid

    var isValid = MyAccount.validateForm(controlList, controlErrorList);

    if (isValid) {
        document.getElementById("PaymentProcessingOverlay").style.display = 'block';
        document.getElementById("PaymentProcessingOverlayImage").src = document.getElementById("PaymentProcessingOverlayImage").src;
    }

    return isValid;
}


//=====================
// Credit Card Details Form
//=====================
MyAccount.validateCreditCardForm = function() {
    var isValid = false;
    var containerPrefix = "ctl00_ctl00_cBodyContainer_cBodyContainer_";
    var cardType = containerPrefix + "CardType";    
    var cardTypeIndex = document.getElementById(cardType).selectedIndex;

    if (cardTypeIndex == 0 || cardTypeIndex == 1) {
        var controlList = [
        { control: "CardName", type: "required", message: "Please enter a Name" },
		{ control: "CardName", type: "regex", valueTest: /[a-z]|[A-Z]/, message: "Can not contain numbers" },
		{ control: "CardNumber", type: "required", message: "Please enter a Card Number" },
		{ control: "CardCVN", type: "required", message: "Please enter a CVV" },
		{ control: "CardNumber", type: "regex", valueTest: /^(\d{4}\s*){4}$/i, message: "Credit card number may only contain 16 digits and spaces" },
		{ control: "CardCVN", type: "regex", valueTest: /^\d{3,4}$/i, message: "CVV may only contain 3 or 4 digits" }
	    ];
    }

    if (cardTypeIndex == 2 || cardTypeIndex == 3) {
        var controlList = [
        { control: "CardName", type: "required", message: "Please enter a Name" },
		{ control: "CardName", type: "regex", valueTest: /[a-z]|[A-Z]/, message: "Can not contain numbers" },
		{ control: "CardNumber", type: "required", message: "Please enter a Card Number" },
		{ control: "CardCVN", type: "required", message: "Please enter a CVV" },
		{ control: "CardNumber", type: "regex", valueTest: /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/i, message: "Please enter a valid Card Number" },
		{ control: "CardCVN", type: "regex", valueTest: /^\d{3,4}$/i, message: "CVV may only contain 3 or 4 digits" }
	    ];    
    }

    // Set up the prefixes - this alters the items in the array.
    MyAccount.updateControlPrefixes(containerPrefix, controlList);

    var controlErrorList = new Object();
    isValid = MyAccount.validateForm(controlList, controlErrorList);

    var cardMonth = containerPrefix + "CardMonth";
    var cardMonthRef = $(cardMonth);
    // Subtract 1 to convert to Javascript month range (i.e. January = 0, February = 1).
    var cardMonthVal = parseInt(cardMonthRef.value, 10) - 1;

    var cardYear = containerPrefix + "CardYear";
    var cardYearRef = $(cardYear);
    var cardYearVal = parseInt(cardYearRef.value, 10);

    // Remove any previous validation errors.
    MyAccount.removeValidationErrorFromControl(cardMonthRef);
    MyAccount.removeValidationErrorFromControl(cardYearRef);


    // Test the date values.
    // We are assuming that the user has their date set correctly...
    var date = new Date();
    var curYear = date.getFullYear();
    var curMonth = date.getMonth();

    var yearValid = (cardYearVal >= curYear);
    var monthValid = true;

    if (curYear == cardYearVal) {
        monthValid = cardMonthVal >= date.getMonth();
    }

    var dateValid = monthValid && yearValid;
    if (!monthValid) {
        MyAccount.addValidationErrorToControl(cardMonthRef, cardMonth, "The selected month must be after the current date", controlErrorList);
    }

    isValid = (isValid && dateValid);

    return isValid;
}


//=====================
// Address Details
//=====================
MyAccount.validateAddressDetails = function(billingContainerPrefix, deliveryContainerPrefix)
{
	var isValid = false;

	var billingError = MyAccount.validate_AddressDetails_BillingAddress(billingContainerPrefix + "_");
	var deliveryError = MyAccount.validate_AddressDetails_DeliveryAddress(deliveryContainerPrefix + "_");

	isValid = billingError && deliveryError;

	return isValid;
}

MyAccount.validate_AddressDetails_BillingAddress = function(containerPrefix)
{
	var isValid = false;
	
	//var containerPrefix = "ctl00_ctl00_ctl00_cBodyContainer_cBodyContainer_cBodyContainer_billingAddressForm_";
	var controlList = [
		{control:"txtFirstName",type:"required",	message:"Please enter your First Name"},
		{control:"txtLastName",	type:"required",	message:"Please enter your Last Name"},
		{control:"txtAddress1",	type:"required",	message:"Please enter your Address"},
		{control:"txtAddress2",	type:"",			message:""},
		{control:"txtCity",		type:"required",	message:"Please enter your City"},
		{control:"ddlState",	type:"not_value", valueTest:"", message:"Please select your State"},
		{control:"txtPostcode",	type:"required",	message:"Please enter your Postcode"},
		{control:"txtPhone",	type:"required",	message:"Please enter your Phone Number"},
		
		// We are assuming that the postcodeValidation.js file has been loaded in this page.
		{control:"txtPostcode",	type:"regex", valueTest:/^\d{3,4}$/i, message:"Enter a postcode 3 or 4 digit postcode"},
		{control:"txtPostcode",	type:"custom_function", valueTest:PostcodeValidation.ValidatePostcode,	message:"Please enter a valid Postcode"},
		
		{control:"txtPhone",	type:"regex", valueTest:/^[\d\s()]{8,20}$/i, message:"Your Phone Number must contain between 8 and 10 digits"},
		{control:"txtAddress1",	type:"regex_negated", valueTest:/p\W*o\W*box/i, message:"Please enter a street address"},
		{control:"txtAddress2",	type:"regex_negated", valueTest:/p\W*o\W*box/i, message:"Please enter a street address"}
	];
	
	// Set up the prefixes - this alters the items in the array.
	MyAccount.updateControlPrefixes(containerPrefix, controlList);
	
	isValid = MyAccount.validateForm(controlList);
	
	return isValid;
}

MyAccount.validate_AddressDetails_DeliveryAddress = function(containerPrefix)
{
	var isValid = false;
	
	//var containerPrefix = "ctl00_ctl00_ctl00_cBodyContainer_cBodyContainer_cBodyContainer_deliveryAddressForm_";
	var controlList = [
		{control:"txtFirstName",type:"required",	message:"Please enter your First Name"},
		{control:"txtLastName",	type:"required",	message:"Please enter your Last Name"},
		{control:"txtAddress1",	type:"required",	message:"Please enter your Address"},
		{control:"txtAddress2",	type:"",			message:""},
		{control:"txtCity",		type:"required",	message:"Please enter your City"},
		{control:"ddlState",	type:"not_value", valueTest:"", message:"Please select your State"},
		{control:"txtPostcode",	type:"required",	message:"Please enter your Postcode"},
		{control:"txtPhone",	type:"required",	message:"Please enter your Phone Number"},
		
		// We are assuming that the postcodeValidation.js file has been loaded in this page.
		{control:"txtPostcode",	type:"regex", valueTest:/^\d{3,4}$/i, message:"Enter a postcode 3 or 4 digit postcode"},
		{control:"txtPostcode",	type:"custom_function", valueTest:PostcodeValidation.ValidatePostcode,	message:"Please enter a valid Postcode"},
		
		{control:"txtPhone",	type:"regex", valueTest:/^[\d\s()]{8,20}$/i, message:"Your Phone Number must contain between 8 and 10 digits"},
		{control:"txtAddress1",	type:"regex_negated", valueTest:/p\W*o\W*box/i, message:"Please enter a street address"},
		{control:"txtAddress2",	type:"regex_negated", valueTest:/p\W*o\W*box/i, message:"Please enter a street address"}
	];
	
	// Set up the prefixes - this alters the items in the array.
	MyAccount.updateControlPrefixes(containerPrefix, controlList);
	
	isValid = MyAccount.validateForm(controlList);
	
	return isValid;
}

// The controlErrorList is an optional parameter.
// If it is passed in then when the function returns it will contain the (complete) IDs
// of controls that had validation errors.
MyAccount.validateForm = function(validatorList, controlErrorList)
{
	if (controlErrorList == null)
	{
		controlErrorList = new Object();
	}

	var isValid = true;
	var addError = false;

	var controlCount = validatorList.length;

	var control;
	var validator;
	var validationType;
	var valueTest;
	for (var i = 0; i < controlCount; i++)
	{

		validator = validatorList[i];
		control = $(validator.control);
		if (!control)
		{
			continue;
		}
		validationType = validator.type;

		if (controlErrorList[validator.control])
		{
			// There is already an error displayed for this control.
			continue;
		}

		MyAccount.removeValidationErrorFromControl(control);

		if (validationType == "checked")
		{
			var controlLabel = control.getNext();
			if (!control.checked)
			{
				addError = true;
			}
			else
			{
				MyAccount.removeValidationErrorFromControl(controlLabel);
			}
			control = controlLabel;
		}

		if (validationType == "required")
		{
			if (control.value == "")
			{
				addError = true;
			}
		}
		else if (validationType == "not_value")
		{
			valueTest = validator.valueTest;
			if (control.value == valueTest)
			{
				addError = true;
			}
		}
		else if (validationType == "match")
		{
			valueTest = validator.valueTest;
			var matchControl = $(valueTest);
			if (control.value != matchControl.value)
			{
				addError = true;
			}
		}
		else if (validationType == "min_length")
		{
			valueTest = validator.valueTest;
			if (control.value.length < valueTest)
			{
				addError = true;
			}
		}
		else if (validationType == "regex")
		{
			var regex = validator.valueTest; // This is assumed to be the regex instance itself.

			// The regex must be matched in order to be valid.
			if (!regex.test(control.value))
			{
				addError = true;
			}
		}
		else if (validationType == "regex_negated")
		{
			// This is assumed to be the regex instance itself.
			var regex = validator.valueTest;

			// The regex should NOT be matched in order to be valid.
			if (regex.test(control.value))
			{
				addError = true;
			}
		}
		else if (validationType == "emailRegex")
		{
			// Use the pre-defined email regex.
			valueTest = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$";

			var regex = new RegExp(valueTest, "i");
			if (!regex.test(control.value))
			{
				addError = true;
			}
		}
		else if (validationType == "custom_function")
		{
			// The custom validation function is expected to 
			// receive a string parameter and return a boolean 
			// indicating whether the value is valid (true)
			// or invalid (false).
			var customFunction = validator.valueTest;
			var controlValid = customFunction(control.value);
			addError = !controlValid;
		}

		if (addError)
		{
			// Add the error to the control.
			MyAccount.addValidationErrorToControl(control, validator.control, validator.message, controlErrorList);

			isValid = false;
		}

		addError = false;
	}

	return isValid;
}

// Adds a validation error to a control if one is not already applied.
MyAccount.addValidationErrorToControl = function(controlRef, controlID, message, controlErrorList)
{
	if (controlErrorList[controlID] != true)
	{
		controlRef.set("errMsg", message);
		controlRef.onmouseover = function(e) { ErrorBubble.ShowError(e, this.get("errMsg")); };
		controlRef.addClass("containsErrors");
		
		controlErrorList[controlID] = true;
	}
}

// Removes the validation message from a control.
MyAccount.removeValidationErrorFromControl = function(controlRef)
{
	controlRef.onmouseover = null;	
	
	controlRef.removeClass("containsErrors");
	controlRef.erase("errMsg");
}





var AjaxCart = {};

var CART_POPUP_WINDOW = 'CartPopupWindow';


AjaxCart.UpdateWithAddMessage = function(cart)
{
	AjaxCart.Update(cart);
	AjaxCart.SetAddMessage(cart.Message, cart.Description, cart.Total);
}

AjaxCart.UpdateWithErrorMessage = function(cart)
{
	AjaxCart.Update(cart);
	var message = cart.ErrorMessage;
	if (message != null)
	{
		AjaxCart.SetErrorMessage(message, cart.Description);
	}
}

AjaxCart.UpdateWithNoMessage = function(cart)
{
	AjaxCart.Update(cart);
}

AjaxCart.Update = function(cart)
{
	AjaxCart.UpdateEdit(cart);
	AjaxCart.UpdateSideBar(cart);
	AjaxCart.UpdateGameGuarantee(cart);
	AjaxCart.UpdateRecommendedProducts(cart);
	AjaxCart.UpdateNextStep(cart);
	AjaxCart.UpdateTotal(cart);
	AjaxCart.RemoveLoadingImages();
}

AjaxCart.RemoveLoadingImages = function()
{
	var loaders = $$('.loader');
	for (var i = 0; i < loaders.length; i++)
	{
		var loader = loaders[i];
		loader.dispose();
	}
}



AjaxCart.ToggleDisplay = function(elementId, cart)
{
	var container = $(elementId);
	if (container == null || container == undefined) return;
	var style = (cart.Items.length > 0) ? "block" : "none";
	container.setStyle("display", style);
}

AjaxCart.UpdateNextStep = function(cart)
{
	AjaxCart.ToggleDisplay('CartNextStep', cart);
}

AjaxCart.UpdateTotal = function(cart)
{
	var containerTotal = $('CartEditContainerTotal');
	if (containerTotal == null || containerTotal == undefined) return;
	AjaxCart.ToggleDisplay('CartEditContainerTotal', cart);	
	containerTotal.getElement('#CartEditTotal').innerHTML = cart.Cost;
}

AjaxCart.UpdateEdit = function(cart) {
	var container = $('CartEditContainer');
	if (container == null || container == undefined) return;

	if (cart.NeedsToVerifyAgeForItems) AgeVerification.ShowWindow();

	var count = cart.Items.length;
	var containsItems = (count > 0);
	var withItemStyle = (containsItems) ? "block" : "none";
	var noItemStyle = (containsItems) ? "none" : "block";
	container.getElement('#hasCartItems').setStyle("display", withItemStyle);
	container.getElement('#noCartItems').setStyle("display", noItemStyle);

	var template = container.getElement('#CartEditRowTemplate');
	var contentHolder = container.getElement('#CartEditContent');
	contentHolder.innerHTML = "";

	for (var i = 0; i < count; i++) {
		var currentItem = template.clone();
		var item = cart.Items[i];
		var sku = item.Sku;
		var gameGuarantee = item.IsGameGuarantee;
		var quantity = item.Quantity;
		//currentItem.getElement(".item").innerHTML = item.Sku;
		var displayPartialPaymentMessage = ((item.ShippingDate != '') && !item.IsGameGuarantee);

		var descriptionText = (item.IsGameGuarantee) ? item.Name : "<a href=\"" + item.Url + "\">" + item.Name + "</a>";
		var availabilityText = "";

		if (displayPartialPaymentMessage && !item.IsGameGuarantee && !item.IsBonusItem) {
			descriptionText += "<br /><span class=\"shippingBalanceLabel\">" + item.FullPriceText + "</div><br /><span class=\"shippingBalanceLabel\">Balance will be charged upon release</span>";
		}
		if (!item.IsGameGuarantee) {
			availabilityText = "<img src='" + item.AvailImage + "' alt='' />";
			if (displayPartialPaymentMessage) availabilityText += "<br /><span class=\"shippingBalanceLabel\">Available: " + item.ShippingDate + "</span>";
		}
		if (item.IsBonusItem) {
			descriptionText = item.Name + "<br><span class=\"shippingBalanceLabel\">Free bonus item</span>";
		}

		currentItem.getElement(".description").innerHTML = descriptionText;
		currentItem.getElement(".availability").innerHTML = availabilityText;

		currentItem.getElement(".price").innerHTML = item.Cost;

		if (item.IsGameGuarantee || item.IsBonusItem) {
			currentItem.getElement(".quantity").innerHTML = quantity;
		}
		else {
			var quantityInput = currentItem.getElement(".quantityInput");
			quantityInput.value = quantity;
			var updateFunction = new Function('AjaxCart.UpdateItem(this, \'' + sku + '\', ' + quantity + ')');
			quantityInput.addEvent('blur', updateFunction);
			quantityInput.addEvent('keyup', updateFunction);
		}
		currentItem.getElement(".subTotal").innerHTML = item.SubTotal;
		if (item.IsBonusItem) {
			currentItem.getElement(".removeInput").dispose();
		}
		else {
			//currentItem.getElement(".removeInput").setAttribute('onclick', 'AjaxCart.RemoveItem(' + count + ', this, \'' + sku + '\')');
			currentItem.getElement(".removeInput").addEvent('click', new Function('AjaxCart.RemoveItem(' + count + ', this, \'' + sku + '\')'));
		}
		currentItem.inject(contentHolder);
	}

}

AjaxCart.UpdateSideBar = function(cart) {
	var container = $('CartSideBarContainer');
	if (container == null || container == undefined) return;
	var template = container.getElement('#CartSideBarRowTemplate');
	var contentHolder = container.getElement('#CartSideBarContent');
	contentHolder.innerHTML = "";
	var count = cart.Items.length;

	for (var i = 0; i < count; i++) {
		var currentItem = template.clone();
		var item = cart.Items[i];
		var text = item.Name;
		if (item.Quantity > 1) text = item.Quantity + " x " + text;
		if (!item.IsGameGuarantee) text = "<a href=\"" + item.Url + "\">" + text + "</a>";
		if (item.IsPreSale) text += "<br /><div class=\"PreSaleLabel\">Preorder Item</div>";
		if (item.IsBonusItem) text = item.Name + "<br /><div class=\"PreSaleLabel\">Free bonus item</div>";
		currentItem.getElement(".description").innerHTML = text;
		if (item.IsBonusItem) {
			currentItem.getElement(".removeInput").dispose();
		}
		else {
			//REMOVEcurrentItem.getElement(".removeInput").setAttribute('onclick', 'AjaxCart.RemoveItem(' + count + ', this, \'' + item.Sku + '\')');
			currentItem.getElement(".removeInput").addEvent('click', new Function('AjaxCart.RemoveItem(' + count + ', this, \'' + item.Sku + '\')'));
		}
		currentItem.inject(contentHolder);
	}
	container.getElement('#CartSideBarTotal').innerHTML = cart.Cost;
	AjaxCart.ToggleDisplay("CartProceedToCheckout", cart)
	AjaxCart.ToggleDisplay("CartEstimatedShippingCost", cart);
	if (count == 0) {
		container.getElement('#SideBarCartHeading').innerHTML = "Your cart is currently empty";
		container.getElement('.CartSideBarTotalWrap').setStyle("display", "none");
	} else {
		container.getElement('#SideBarCartHeading').innerHTML = "Your cart contains";
		container.getElement('#CartSideBarContent').setStyle("display", "block");
		container.getElement('.CartSideBarTotalWrap').setStyle("display", "block");
	}
}

AjaxCart.UpdateGameGuarantee = function(cart)
{
	var container = $('GameGuaranteeContainer');
	if (container == null || container == undefined) return;
	var template = container.getElement('#GameGuaranteeRowTemplate');
	var contentHolder = container.getElement('#GameGuaranteeContent');
	var ggContent = container.getElement('.gameGuaranteePanel');
	contentHolder.innerHTML = "";
	container.setStyle("display", "none");
	var count = cart.Items.length;
    var orderHasGG = false;
    var hasGameGuarantees = false;
	for (var i = 0; i < count; i++)
	{
		var item = cart.Items[i];
		var addGameGuarantee = item.AddGameGuarantee;
		if (addGameGuarantee != null)
		{
		    hasGameGuarantees = true;
			container.setStyle("display", "block");
		    ggContent.setStyle("display", "block");
			var currentItem = template.clone();
			currentItem.getElement(".name").innerHTML = addGameGuarantee.Name;
			currentItem.getElement(".price").innerHTML = addGameGuarantee.Cost;
			currentItem.getElement(".addInput").addEvent('click', new Function('AjaxCart.AddGameGuarantee(this, \'' + addGameGuarantee.ProductSku + '\')'));
			//REMOVEcurrentItem.getElement(".addInput").setAttribute('onclick', 'AjaxCart.AddGameGuarantee(this, \'' + addGameGuarantee.ProductSku + '\')');
			currentItem.inject(contentHolder);
		}
		if (item.HasGameGuarantee == true) {
		     orderHasGG = true;
		}
	}
    if (orderHasGG) {
        if (hasGameGuarantees) {
            ggContent.setStyle("display", "block");        
        } else {
            ggContent.setStyle("display", "none");        
        }
        container.setStyle("display", "block");
    }
}

var RECOMMENDED_PRODUCTS_CONTAINER = 'RecommendedProductsContainer';

AjaxCart.RecommendedProductsExists = function()
{
	var container = $(RECOMMENDED_PRODUCTS_CONTAINER);
	if (container == null || container == undefined) return false;
	return true;
}


AjaxCart.UpdateRecommendedProducts = function(cart)
{
	var container = $(RECOMMENDED_PRODUCTS_CONTAINER);
	if (container == null || container == undefined) return;
	var template = container.getElement('#RecommendedProductsRowTemplate');
	var lastTemplate = container.getElement('#RecommendedProductsLastRowTemplate');
	var contentHolder = container.getElement('#RecommendedProductsContent');
	contentHolder.innerHTML = "";
	var count = cart.RecommendedProducts.length;
	for (var i = 0; i < count; i++)
	{
		var item = cart.RecommendedProducts[i];
		if (i == count - 1)
		{
			var currentItem = lastTemplate.clone();
		} else
		{
			var currentItem = template.clone();
		}
		//currentItem.getElement(".productLink").href = item.Url;
		currentItem.getElement(".name").innerHTML = "<a href=" + item.Url + ">" + item.Name + "</a>";
		currentItem.getElement(".platform").innerHTML = "<a href=" + item.Url + ">" + item.Platform + "</a>";
		currentItem.getElement(".price").innerHTML = "<a href=" + item.Url + ">" + item.Cost + "</a>";
		currentItem.getElement(".image").innerHTML = '<a href="' + item.Url + '"><img src="' + item.Image + '" title="' + item.Name + '" /></a>';

		//currentItem.getElement(".addInput").setAttribute('onclick', 'AjaxCart.AddItemNoMessage(this, \'' + item.Sku + '\')');
		//currentItem.getElement(".addtoCartButton").setAttribute('onclick', 'AjaxCart.AddItemNoMessage(this, \'' + item.Sku + '\')');
		currentItem.getElement(".addtoCartButton").addEvent('click', new Function('AjaxCart.AddItemNoMessage(this, \'' + item.Sku + '\')'));
		currentItem.inject(contentHolder);
	}
}

AjaxCart.SetAddMessage = function(text, description, total)
{
	var element = $(CART_POPUP_WINDOW);
	AjaxCart.HideContentWindows(element, "addContent");
	element.getElement('.addMessage').innerHTML = text;
	element.getElement('.description').innerHTML = description;
	element.getElement('.total').innerHTML = total;
	element.setStyle("display", "block");
	AjaxCart.DelayFadeTextWindow();

}

AjaxCart.SetErrorMessage = function(message, description)
{
	var element = $(CART_POPUP_WINDOW);
	AjaxCart.HideContentWindows(element, "errorContent");
	element.getElement('.errorMessage').innerHTML = message;
	element.getElement('.errorDescription').innerHTML = description;
	element.setStyle("display", "block");
	AjaxCart.DelayFadeTextWindow();
}

AjaxCart.ClosePopupWindow = function()
{
	clearTimeout(AjaxCart.Timeout);
	var element = $(CART_POPUP_WINDOW);
	element.setStyle("display", "none");
	return false;
}

AjaxCart.HideContentWindows = function(parentElement, activeId)
{
	var contentWindows = parentElement.getElements('.contentWindow');
	for (var c = 0; c < contentWindows.length; c++)
	{
		var contentWindow = contentWindows[c];
		var id = contentWindow.getAttribute("id");
		var style = (id == activeId) ? "block" : "none";
		contentWindow.setStyle("display", style);
	}
}

AjaxCart.Timeout = null;

AjaxCart.DelayFadeTextWindow = function()
{
	clearTimeout(AjaxCart.Timeout);
	AjaxCart.Timeout = setTimeout(AjaxCart.FadeTextWindow, TIME_TO_DELAY_FADE_TEXT_WINDOW);
}

AjaxCart.FadeTextWindow = function()
{
	clearTimeout(AjaxCart.Timeout);
	/*AjaxCart.ClosePopupWindow();*/
	//Need to look into this further: http://mootools.net/docs/core/Fx/Fx
	var element = $(CART_POPUP_WINDOW);  
	function Complete()
	{
		element.setStyle("display", "none");
		element.setStyle("opacity", 1);
	}
	/*if (element.Effect != undefined)
	{
		element.Effect.cancel();
	}*/
	element.Effect = new Fx.Morph(element, { onComplete: Complete, duration: DURATION_FADE_TEXT_WINDOW });
	element.Effect.start({ opacity: "0.01" });
}




AjaxCart.MoveTextWindow = function(element)
{
	clearTimeout(AjaxCart.Timeout);
	var curleft = element.clientWidth;
	var curtop = element.clientHeight;

	for (obj = element; obj != null; obj = obj.offsetParent)
	{
		curleft += obj.offsetLeft;
		curtop += obj.offsetTop;
	}

	var pageWith = (self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth));
	var textWinWidth = 360 + 30;

	if ((curleft + textWinWidth) > pageWith) curleft = (pageWith - textWinWidth);

	var textWin = $(CART_POPUP_WINDOW);
	textWin.setStyle('top', curtop);
	textWin.setStyle('left', curleft);
}



AjaxCart.AddItemNoMessage = function(box, sku)
{
	Root.Service.ShoppingCartService.AddCartItem(sku, AjaxCart.RecommendedProductsExists(), AjaxCart.UpdateWithNoMessage);
}

AjaxCart.AddItem = function(box, sku)
{
	AjaxCart.MoveTextWindow(box);
	Root.Service.ShoppingCartService.AddCartItem(sku, AjaxCart.RecommendedProductsExists(), AjaxCart.UpdateWithAddMessage);
}

AjaxCart.AddGameGuarantee = function(box, sku)
{
	Root.Service.ShoppingCartService.AddGameGuarantee(sku, AjaxCart.RecommendedProductsExists(), AjaxCart.UpdateWithNoMessage);
}


AjaxCart.UpdateItem = function(box, sku, quantity)
{
	if (box.value == quantity) return;
	AjaxCart.MoveTextWindow(box);
	Root.Service.ShoppingCartService.UpdateCartItem(sku, box.value, AjaxCart.RecommendedProductsExists(), AjaxCart.UpdateWithErrorMessage);
}

AjaxCart.RemoveItem = function(count, button, sku)
{
    Root.Service.ShoppingCartService.RemoveCartItem(sku, AjaxCart.RecommendedProductsExists(), AjaxCart.Update);
}


AjaxCart.Reload = function()
{
	Root.Service.ShoppingCartService.GetCart(AjaxCart.RecommendedProductsExists(), AjaxCart.Update);
}









var Coupon = {};

var COUPON_WRAPPER_ID = "OuterCouponWrapper";
var COUPON_ELEMENT_ID = "couponCode";


Coupon.Apply = function()
{
	var element = $(COUPON_ELEMENT_ID);
	Root.Service.ShoppingCartService.ApplyCoupon(element.value, Coupon.UpdateTotalAndCoupon)
}

Coupon.UpdateTotalAndCoupon = function(webShippingTotal)
{
	var couponContainer = $(COUPON_WRAPPER_ID);
	var errorMessageStyle = "";
	if (webShippingTotal.ValidCoupon)
	{
		couponContainer.getElement('.couponWrap').setStyle('display', 'none');
		couponContainer.getElement('.couponRedWrap').setStyle('display', 'block');
		//couponContainer.getElement('.CouponUsedName').innerHTML = webShippingTotal.CouponName;
		var CouponName = webShippingTotal.CouponName;
		couponContainer.getElement('.CouponUsedWrapper').innerHTML = "<div class=\"couponSaveImage\"><img src=\"/App_Assets/images/coupon-save.gif\" /></div><div class=\"couponTextWrap\"><div class=\"couponUsedName\"> Voucher: <span class=\"couponName\">" + CouponName + "</span></div><div class=\"couponUsedText\">Your voucher has been added to this order.<br /><span class=\"couponRemove\"><a href=\"javascript:void(0);\" OnClick=\"Coupon.HideCoupon()\">Remove Voucher</a></span></div></div>";
		errorMessageStyle = "none";
	}
	else
	{
		errorMessageStyle = "block";
	}
	couponContainer.getElement('.couponErrorWrap').setStyle('display', errorMessageStyle);
	Coupon.UpdateTotal(webShippingTotal);
}

Coupon.UpdateTotal = function(webShippingTotal)
{
	Shipping.UpdateTotals(webShippingTotal);
	var container = $('ShippingContainer');
	var invoiceWrappers = container.getElements('.CartDisplay');
	for (var i = 0; i < webShippingTotal.CartInvoices.length; i++)
	{
		var invoice = webShippingTotal.CartInvoices[i];
		var invoiceWrapper = invoiceWrappers[i];
		var discountColumnStyle = (invoice.HasProductDiscountCurrent) ? "block" : "none";

		invoiceWrapper.getElements('.header .discount')[0].setStyle("display", discountColumnStyle);

		var allDescriptions = invoiceWrapper.getElements('.description');
		for (var d = 0; d < allDescriptions.length; d++)
		{
			var descriptionCol = allDescriptions[d];
			if (invoice.HasProductDiscountCurrent)
			{
				descriptionCol.addClass('short_description');
			}
			else
			{
				descriptionCol.removeClass('short_description');
			}
		}

		var itemWrappers = invoiceWrapper.getElements('.itemContent');
		for (var ii = 0; ii < invoice.Items.length; ii++)
		{
			var item = invoice.Items[ii];
			var itemWrapper = itemWrappers[ii];

			var discountColumnText = (item.InvoiceHasProductDiscountCurrent) ? item.DiscountValue : "";
			var discountLineText = (item.InvoiceHasProductDiscountForFuture) ? item.DiscountValue : "";
			var discountLineStyle = (item.InvoiceHasProductDiscountForFuture) ? "inline" : "none";

			var discountColumn = itemWrapper.getElements('.discount')[0];
			discountColumn.setStyle("display", discountColumnStyle);
			discountColumn.innerHTML = discountColumnText;

			itemWrapper.getElements('.shippingFutureDiscount')[0].setStyle("display", discountLineStyle);
			itemWrapper.getElements('.discountForFutureShippingText')[0].innerHTML = discountLineText;
			itemWrapper.getElements('.subTotal')[0].innerHTML = item.SubTotal;
		}
	}
}

Coupon.StyleFromValue = function(value)
{
	return (value != "") ? "block" : "none";
}

Coupon.HideCoupon = function()
{
    var container = $('ShippingContainer');
    var couponWrap = container.getElement('.couponWrap');
    var couponRedWrap = container.getElement('.couponRedWrap');
    couponWrap.setStyle("display", "block");
    couponRedWrap.setStyle("display", "none");
    Root.Service.ShoppingCartService.RemoveCoupon(Coupon.UpdateTotal)    
}











Shipping = {};

Shipping.UpdateShipping = function(date, dropdown) {
	var value = dropdown.options[dropdown.selectedIndex].value;
	Root.Service.ShoppingCartService.UpdateShipping(date, value, Shipping.UpdateTotals);

	// if it is instore pickup
	var container = (dropdown.parentNode).parentNode;
	if (container.childNodes.length > 3) {
		var row = container.childNodes[3];
	}
	else {
		var row = container.childNodes[1];
	}

	if (value == '3') {
		if (row != null) { //shows stores row
			row.style.display = 'block';
			document.getElementById('ctl00_ctl00_cBodyContainer_cBodyContainer_sctShipping_rptOrders_ctl00_cbDeliveryInsurance').checked = false;
			document.getElementById('insurancerow').style.display = 'none';
			Root.Service.ShoppingCartService.UpdateDeliveryInsurance(date, false, Shipping.UpdateTotals);
		}
	}
	else {
		if (row != null) { //hides stores row
			row.style.display = 'none';
			document.getElementById('insurancerow').style.display = 'block';

		}
	}
}

Shipping.UpdateShippingRadioButton = function(date, e) {
    var value = e.value;
    Root.Service.ShoppingCartService.UpdateShipping(date, value, Shipping.UpdateTotals);

    if (value == '3') { // IS POPIS :(

        var row = e.id.replace("radShipping", "pnlInstore");
        var row = row.substring(0, row.length - 2);
        var insuranceCB = row.replace("pnlInstore", "cbDeliveryInsurance");
        var insurancePanel = row.replace("pnlInstore", "pnlInsurance");
        var StoreList_1 = e.id.replace("radShipping", "ddlStore");
        var StoreList = StoreList_1.substring(0, StoreList_1.length - 2);

        // sets the default closest store when the user doesnt select anything
        var dropdown = document.getElementById(StoreList);
        var value = dropdown.options[dropdown.selectedIndex].value;
        var text = dropdown.options[dropdown.selectedIndex].text;
        Root.Service.ShoppingCartService.UpdateInStorePickup(date, value, text, Shipping.UpdateTotals);

        if (row != null) { //shows stores row
            document.getElementById(row).style.display = 'block';
            document.getElementById(insuranceCB).checked = false;
            document.getElementById(insurancePanel).style.display = 'none';
            Root.Service.ShoppingCartService.UpdateDeliveryInsurance(date, false, Shipping.UpdateTotals);
        }
    }
    else { // NOT POPIS :)

        var row = e.id.replace("radShipping", "pnlInsurance");
        var row = row.substring(0, row.length - 2);
        var storerow = row.replace("pnlInsurance", "pnlInstore");

        if (row != null) { //hides stores row
            document.getElementById(row).style.display = 'block';
            document.getElementById(storerow).style.display = 'none';

        }
    }
}

Shipping.UpdateDeliveryInsurance = function(date, box)
{
	Root.Service.ShoppingCartService.UpdateDeliveryInsurance(date, box.checked, Shipping.UpdateTotals);
}

Shipping.UpdateInStorePickup = function(date, dropdown)
{
	var value = dropdown.options[dropdown.selectedIndex].value;	
	var text = dropdown.options[dropdown.selectedIndex].text;	
	Root.Service.ShoppingCartService.UpdateInStorePickup(date, value, text, Shipping.UpdateTotals);
}


Shipping.UpdateTotals = function(webShippingTotal)
{
	var container = $('ShippingContainer');
	container.getElement('.itemPrice').innerHTML = webShippingTotal.ItemTotalValue;
	var shippingColor = (webShippingTotal.ShippingRedText) ? "red" : "auto";
	var shippingPrice = container.getElement('.shippingPrice');
	shippingPrice.innerHTML = webShippingTotal.ShippingTotalValue;
	var redClassName = 'redText';
	if (webShippingTotal.ShippingRedText)
	{
		shippingPrice.addClass(redClassName);
	}
	else
	{
		shippingPrice.removeClass(redClassName);
	}

	container.getElement('.deliveryInsuranceWrapper').setStyle('display', Coupon.StyleFromValue(webShippingTotal.TotalDeliveryInsuranceValue));
	container.getElement('#deliveryInsurance').innerHTML = webShippingTotal.TotalDeliveryInsuranceValue;
	container.getElement('#shippingTotal').innerHTML = webShippingTotal.CompleteTotalValue;
}









var AjaxShippingCost = {};

AjaxShippingCost.DisplayEstimatedShippingCost = function(cartOrder)
{
	AjaxShippingCost.UpdateEstimatedShippingCost(cartOrder);
	Overlay.OpenWindow('EstimatedShippingCostContainer', true);
}

AjaxShippingCost.UpdateEstimatedShippingCost = function(cartOrder)
{
	var container = $('EstimatedShippingCostContainer');

	var postCodeNoDangerousGoods = cartOrder.PostCodeNoDangerousGoods;
	AjaxShippingCost.ToggleContainer(container, "#EstimatedShippingDetails", !postCodeNoDangerousGoods);
	AjaxShippingCost.ToggleContainer(container, "#EstimatedShippingRemoveDangerous", postCodeNoDangerousGoods);

	if (postCodeNoDangerousGoods == true)
	{
		var template = container.getElement('#EstimatedShippingRemoveDangerousRowTemplate');
		var contentHolder = container.getElement('#EstimatedShippingRemoveDangerousContent');
		contentHolder.innerHTML = "";

		for (var outerIndex = 0; outerIndex < cartOrder.CartInvoiceList.length; outerIndex++)
		{
			var order = cartOrder.CartInvoiceList[outerIndex];
			for (var innerIndex = 0; innerIndex < order.ItemsList.length; innerIndex++)
			{
				var item = order.ItemsList[innerIndex];
				if (item.IsDangerousGoods)
				{
					var currentItem = template.clone();
					currentItem.getElement(".name").innerHTML = item.Name;
					currentItem.id = 'removeTemplateId';
					currentItem.inject(contentHolder);
				}
			}

		}
	}
	else
	{
		var template = container.getElement('#EstimatedShippingCostOrderTemplate');
		var redTemplate = container.getElement('#EstimatedShippingCostOrderTemplateRed');
		var contentHolder = container.getElement('#EstimatedShippingCostOrderContent');
		contentHolder.innerHTML = "";

		var invoices = cartOrder.CartInvoiceList.length;
		var warningDisplay = (invoices <= 1) ? 'none' : 'block';
		if (invoices <= 1) container.getElement('.warning').setStyle('display', warningDisplay);
		for (var outerIndex = 0; outerIndex < invoices; outerIndex++)
		{
			//var currentItem = ((outerIndex % 2) > 0) ? template.clone() : redTemplate.clone();
			var currentItem = template.clone();
			var currentTime = new Date();
			var month = currentTime.getMonth() + 1;
			if (month < 10)
			{
				month = "0" + month;
			}
			var day = currentTime.getDate();
			var year = currentTime.getFullYear();
			var currentDate = day + "/" + month + "/" + year;

			var invoice = cartOrder.CartInvoiceList[outerIndex];
			var titleHtml = "Order " + (outerIndex + 1) + ": This order will ship ";
			titleHtml += (currentDate == invoice.InvoiceShipDateValue) ? "in 1-2 business days" : "when the items become available";
			currentItem.getElement(".title").innerHTML = titleHtml;

			var hideRegularPostage = (invoice.RegularPostage == 0);
			var hideExpressPostage = (invoice.HasDangerousGoods || invoice.ExpressPostage == 0);
			AjaxShippingCost.ToggleShipping(currentItem, invoice.RegularPostageFormatted, cartOrder.regularShippingString, hideRegularPostage, ".standardShipping", ".standardShippingPrice");
			AjaxShippingCost.ToggleShipping(currentItem, invoice.ExpressPostageFormatted, cartOrder.expressShippingString, hideExpressPostage, ".expressShipping", ".expressShippingPrice");
			if (hideExpressPostage) currentItem.getElement('.expressShippingRemoved').setStyle('display', 'block');
			var innerTemplate = container.getElement('#EstimatedShippingRowTemplate');
			var innerContentHolder = currentItem.getElement('.EstimatedShippingRowContent');
			innerContentHolder.innerHTML = "";

			for (var innerIndex = 0; innerIndex < invoice.ItemsList.length; innerIndex++)
			{
				var innerCurrentItem = innerTemplate.clone();
				var item = invoice.ItemsList[innerIndex];
				innerCurrentItem.getElement(".name").innerHTML = item.Name;
				if (!item.IsDangeriousGoods) innerCurrentItem.getElement(".noExpress").dispose();
				innerCurrentItem.id = 'removeInnerTemplateId';
				innerCurrentItem.inject(innerContentHolder);
			}
			currentItem.id = 'removeCurrentTemplateId';
			currentItem.inject(contentHolder);
		}

	}

}

AjaxShippingCost.ToggleContainer = function(element, control, display)
{
	var displayStyle = (display) ? 'block' : 'none';
	element.getElement(control).setStyle('display', displayStyle);
}



AjaxShippingCost.ToggleShipping = function(currentItem, value, shippingString, hide, wrapperClass, priceClass)
{
	if ((value == null) || (hide == true))
	{
		currentItem.getElement(wrapperClass).dispose();
	}
	else
	{
		currentItem.getElement(wrapperClass).innerHTML = shippingString;
		currentItem.getElement(priceClass).innerHTML = value;
	}
}

AjaxShippingCost.Show = function(containerPrefix)
{
	var element = document.getElementById(containerPrefix + "itxPostCode");
	Root.Service.ShoppingCartService.GetShortCartOrder(element.value, AjaxShippingCost.DisplayEstimatedShippingCost);
}

AjaxShippingCost.CancelOrderFinish = function(webCart)
{
	AjaxCart.Update(webCart);
	Overlay.CloseWindow();
}

AjaxShippingCost.RemoveDangerousUpdate = function(cartOrder)
{
	if (cartOrder.CartInvoiceList.length > 0)
	{
		AjaxShippingCost.UpdateEstimatedShippingCost(cartOrder);
	}
	else
	{
		Overlay.CloseWindow(); //TIMEOUT ON THIS??
	}
	AjaxCart.Reload();
}

AjaxShippingCost.RemoveDangerous = function()
{
	var element = $(POSTCODE_ELEMENT_ID);
	Root.Service.ShoppingCartService.RemoveDangerous(element.value, AjaxShippingCost.RemoveDangerousUpdate)
}


AjaxShippingCost.CancelOrder = function()
{
	Root.Service.ShoppingCartService.CancelOrder(AjaxCart.RecommendedProductsExists(), AjaxShippingCost.CancelOrderFinish)
}



	
		
// Due to NET using a single form for all forms, this makes certain the correct form is submitted
// by determining the form object that has focus and submitting the form by clicking the first button
// found after the user presses the enter key.

function submitFormByCorrectButton(e)
{
    var caller = getEventCaller(e);

    if (getEventKeyCode(e) == 13 && caller.type.toLowerCase() != "textarea")
    {
    	var cssClass = caller.className;
    	if (cssClass == "quantityInput")
    	{
    		var nextStepElement = $('cartClickNextStep');
    		window.location = nextStepElement.href;
    		return false;
    	}    		
    	
		
        var elements    = $('aspnetForm').getElementsByTagName('input');// $('aspnetForm').getElementsBySelector('SELECT', 'INPUT');         
        var callerFound = false;
        
        for (var i = 0; i < elements.length; i++) {
            var element = elements[i];
            var type    =  element.getAttributeNode('type').nodeValue//element.readAttribute("type");
            if (element.id == caller.id) { callerFound = true; }
            if (type)                    { type        = type.toLowerCase(); }
            
            if (callerFound && (type == "image" || type == "submit")) {
                buttonNotClicked = false;
                
                element.click();
                break;
            }
        }
        return false;
    }    
    return true;
}

function getEventKeyCode(e) {
    if (window.event) {
        return e.keyCode;
    } else if (e.which) {
        return e.which;
    }
}

function getEventCaller(e) {
    if (window.event) {
        return e.srcElement;
    } else if (e.which) {
        return e.target;
    }
}



Wishlist = {};
Wishlist.Add = function(image, productId)
{
	Root.Service.ShoppingCartService.AddToWishlist(productId);
	image.src = "/App_Assets/images/wishlist-alreadyIn.gif";
	image.onclick = Wishlist.RedirectToWishlist;
}

Wishlist.RedirectToLogin = function(page)
{
	window.location = "/myaccount/login.aspx?redirect=" + page;
}

Wishlist.RedirectToWishlist = function()
{
	window.location = "/myaccount/myWishlist.aspx";
}




AgeVerification = {};

AgeVerification.ShowWindow = function()
{
	Overlay.OpenWindow('AgeVerifyWindow', true);
}

AgeVerification.Under15 = function()
{
	Root.Service.ShoppingCartService.Under15(AjaxCart.RecommendedProductsExists(), AgeVerification.UpdateWindow);
}

AgeVerification.Over15 = function()
{
	Root.Service.ShoppingCartService.Over15(AjaxCart.RecommendedProductsExists(), AgeVerification.UpdateWindow);
}

AgeVerification.UpdateWindow = function(cart)
{
	Overlay.CloseWindow();
	AjaxCart.Update(cart);
}


function displayEstimatedShipping(containerPrefix)
{
	containerPrefix += "_";
	if (MyAccount.validateEstimatedShippingCost(containerPrefix))
	{
		MyAccount.showEstimatedShipping(containerPrefix);
	}
}











window.addEvent('domready',
function()
{
	AjaxCart.Reload();
});

