var drupalThemePath = '/sites/all/themes/secondsworld/';
var drupalThemeImagePath = drupalThemePath + 'images/';
var arrayProductWarrantyCost = new Array();
var checkoutPostcode = '';
var checkoutSubtotal;
var checkoutShippingTotal;
var checkoutGST;
var checkoutOrderTotal;
var checkoutResponse = '';

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

function findOperatingSystem() {
	var OSName="unknown";
	if (navigator.appVersion.indexOf("Win")!=-1) OSName="windows";
	if (navigator.appVersion.indexOf("Mac")!=-1) OSName="mac";
	if (navigator.appVersion.indexOf("X11")!=-1) OSName="unix";
	if (navigator.appVersion.indexOf("Linux")!=-1) OSName="linux";
	
	return OSName;
}

function preLoadImages(imageArray) {
	for (var count = 0; count < imageArray.length; count++) {
		$('<img src="' + drupalThemeImagePath + imageArray[count] + '" />');
	}
}

/* Replaces an inputs value on focus and on blur
 * objSelector - input object
 * value - string Input Values default value
 */
function formDefaultValueReplace(objSelector, value) {
	if ($(objSelector).size() > 0) {
		$(objSelector).focus(function () {
			if ($(this).val() == value)
				$(this).val('');
		}).blur(function () {
			if ($(this).val() == '')
				$(this).val(value);
		});
	}
}

function imageHover(objSelector, imageName, imageHoverName) {
	if ($(objSelector).size() > 0) {
		$(objSelector).mouseover(function () {
			$(this).attr('src', drupalThemeImagePath + imageHoverName);
		}).mouseout(function () {
			$(this).attr('src', drupalThemeImagePath + imageName);
		});
	}
}

function imageHoverInit(imageArray) {
	var preLoadImageArray = new Array();
	for (var count = 0; count < imageArray.length; count++) {
		preLoadImageArray.push(imageArray[count][2]);
		imageHover(imageArray[count][0], imageArray[count][1], imageArray[count][2]);
	}
	
	preLoadImages(preLoadImageArray);
}

function formValidation () {
	if($.validator != undefined && $("#uc-cart-checkout-form").size() == 0 && $("#delivery-calculator").size() == 0) {
	
		$.validator.setDefaults({ 
			errorClass: "error",
			highlight: function(element, errorClass) {
			     $(element).addClass(errorClass);
			     $(element.form).find("label[for=" + element.id + "]")
			                    .addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
			     $(element).removeClass(errorClass);
			     $(element.form).find("label[for=" + element.id + "]")
				                 .removeClass(errorClass);
			},
			errorContainer: '.module-message',
   			errorLabelContainer: '.module-message ul',
   			wrapper: "li",
   			invalidHandler: function(form, validator) {
   				$('.module-node .module-message ul').empty(); 
   			}
		});
	}
	
	if ($('#webform-client-form-32').size() > 0) {
		if ($('#edit-submitted-subscriptions-yes').size() > 0) {
			$('#edit-submitted-subscriptions-yes').attr('checked', 'checked');
		}
		if ($('.module-node .module-message').size() == 0) {
			$('<div class="module-message"><div class="messages error"></div></div>').hide().insertAfter('.module-node .module-breadcrumb');
		}
		if ($('.module-node .module-message ul').size() == 0) {
			$('<ul></ul>').hide().appendTo('.module-node .module-message .error');
		}
		$('#webform-client-form-32').validate({
			errorClass: "label-error",
			errorContainer: '.module-message',
   			errorLabelContainer: '.module-message ul',
			rules: {
				'submitted[email]': {
					email: true
				}
			},
			messages: {
				'submitted[first_name]': 'Please fill in your <strong>First Name</strong>',
				'submitted[email]': 'Please fill in your valid <strong>Email Address</strong>',
				'submitted[contact_phone]': 'Please fill in your valid <strong>Phone Number</strong>',
				'submitted[regarding]': 'Please select an appropriate value for the <strong>Regarding</strong> field',
				'submitted[message]': 'Please fill in your <strong>Message</strong>'
			}
		});
	}
	
}

function searchFormInit() {
	formDefaultValueReplace($('.module-search .form-text'), 'Product Search');
}

function filterFormInit() {
	$('.module-product-filter select').change(function() {
		$('.module-product-filter form').submit();
	});
}

function forwardFormInit() {
	if($('#forward-form').size() > 0) {
		formDefaultValueReplace($('#forward-form-container #edit-yname'), 'Name');
		formDefaultValueReplace($('#forward-form-container #edit-yemail'), 'Email Address');
		formDefaultValueReplace($('#forward-form-container #edit-recipients'), 'Email Address');
		
		$.validator.addMethod("isDefaultValue", formIsDefault, "This field is required.");
		
		$('#forward-form').validate({
			errorClass: "label-error",
			highlight: function(element, errorClass) {
			     $(element).addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
			     $(element).removeClass(errorClass);
			},
			wrapper: '',
			errorPlacement: function(error, element) {
	     		error.appendTo( $('#forward-form .form-item:first') );
	   		},
			rules: {
				'yname': {
					required: true,
					isDefaultValue: 'Name'
				},
				'yemail': {
					email: true
				},
				'recipients': {
					email: true
				}
			},
			messages: {
				'yname': 'Please enter your <strong>Name</strong>',
				'yemail': 'Please enter your valid <strong>Email Address</strong>',
				'recipients': 'Please enter a valid <strong>Recipient Email Address</strong>'
			}
		});
	}
}

/*
function printButtonInit(objArray) {
	var objPrint = '<a href="#">Print</a>';
	objPrint = $(objPrint).addClass('link link-print').click(function () {
		window.print();
		return false;
	})
	$(objArray).each(function () {
		if ($(this).size() > 0) {
			var printClasses = $(this).attr('class').split(' ');
			var objPrintWithClass = $(objPrint).clone(true).addClass('link-print-' + printClasses[printClasses.length-1]);
			$('.module-node .module-breadcrumb').prepend(objPrintWithClass);
		}
	});
}
*/

function googleMapsInit () {
	if ($('.module-views-store_listing').size() > 0) {
		$("body").unload(GUnload());
	}
}

function googleMapsStore (intStoreID, strAddress) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map-store" + intStoreID));
		var geocoder = new GClientGeocoder();
		
		geocoder.getLatLng(strAddress, function(point) {
      		if (!point) {
        		alert(address + " not found");
      		} else {
		        map.setCenter(point, 13);
		        var marker = new GMarker(point);
		        map.addOverlay(marker);
		        map.setUIToDefault();
		      }
    	});
  	}
}

function cartHoverInit () {
	var imageArray = new Array();
	
	if ($("#cart-form-buttons").size() > 0) {
		imageArray.push(Array('#edit-update', 'button-update-cart.gif', 'button-update-cart-hover.gif'))
		imageArray.push(Array('#edit-checkout', 'button-checkout.gif', 'button-checkout-hover.gif'))
		imageArray.push(Array('#edit-continue-shopping', 'button-continue-shopping.gif', 'button-continue-shopping-hover.gif'))
		imageHoverInit(imageArray);
	}
}

function cartFormInit () {
	if ($("#cart-form-buttons").size() > 0) {
	
		var imageArray = new Array();
	
		imageArray.push('#edit-update');
		imageArray.push('#edit-checkout');
		imageArray.push('#edit-continue-shopping');
		
		for (var count = 0; count < imageArray.length; count++) {
			var button = $('<button type="button" id="button-' + 
							$(imageArray[count]).attr("id") + 
							'"><span>' + 
							$(imageArray[count]).attr("value") + 
							'</span></button>').click(function(imageArray) {
								$('#' + $(this).attr("id").replace(/button-/, '')).trigger('click');
							})
			$(imageArray[count]).after($(button));
		}

	}
}

function addToCartFormInit () {
	if ($('.button-add-to-cart').size() > 0) {
		var imageArray = new Array();
		
		imageArray.push(Array('.button-add-to-cart', 'button-add-to-cart.gif', 'button-add-to-cart-hover.gif'))
		imageHoverInit(imageArray);
		
		//get warranty cost for seconds type
		
		productWarrantyCost($('.add_to_cart .form-radio:checked').next('.option-price').text().replace('$', '').replace(',', ''), $('.add_to_cart .form-radio:checked').val());
		
		$('.add_to_cart .form-radio').click(function () {
			if (arrayProductWarrantyCost[$(this).val()] != null)
				showProductWarrantyCost(arrayProductWarrantyCost[$(this).val()]);
			else
				productWarrantyCost($(this).next('.option-price').text().replace('$', '').replace(',', ''), $(this).val());
			
		});
	}
}

function productWarrantyCost (productCost, attributeNo) {
	
	$.ajaxSync({
		type: 'POST',
		url: '/product/warranty/' + productNID +  '/1/' + productCost,
		dataType: 'json',
		success: function(response){
			arrayProductWarrantyCost[attributeNo] = response.cost;
			showProductWarrantyCost(arrayProductWarrantyCost[attributeNo]);
 		},
 		error: function(XMLHttpRequest, textStatus, errorThrown){
			showProductWarrantyCost('Calculated when added to cart');
 		}
	});
}

function showProductWarrantyCost(cost) {
	$('.add_to_cart #edit-attributes-2-wrapper .product-warranty-price').text(cost);
}

function tooltipsInit () {
	if ($('.link-tooltip, .link-text-tooltip').size() > 0) {
		
		var tooltipHTML = '';
		
		if($.browser.msie && ($.browser.version == '6.0')){
			tooltipHTML += '<iframe id="tooltip-iframe"></iframe>';
		}
		tooltipHTML += '<div id="tooltip"><div id="tooltip-header"></div><div id="tooltip-content"></div><div id="tooltip-footer"></div></div>';
		
		$('body').append(tooltipHTML);
		
		var preLoadImageArray = new Array();
		
		preLoadImageArray.push('tooltip-bg.gif');
		preLoadImageArray.push('tooltip-top-bg.gif');
		preLoadImageArray.push('tooltip-bottom-bg.gif');
		
		preLoadImages(preLoadImageArray);

		$('.link-tooltip, .link-text-tooltip').each(function() {
			$(this).mouseover(function () {
				
				var toolTip = $('#' + $(this).attr('href').replace(/#/, ''));
				var toolTipPosition = findPos($(this).get(0));
				
				$('#tooltip-content')
					.empty()
					.html($('#' + $(this).attr('href').replace(/#/, '') + ' .tooltip-content').html());
				
				var toolTipPositionTopOffset = 6;
				var toolTipPositionLeftOffset = 8;
				
				var toolTipPositionLeft = toolTipPosition[0] - $('#tooltip').width() + toolTipPositionLeftOffset;
				var toolTipPositionTop = toolTipPosition[1] - $('#tooltip').height() + toolTipPositionTopOffset;
				
				if ($.browser.msie && ($.browser.version == '6.0')) {
					$('#tooltip-iframe')
						.css('left', toolTipPositionLeft)
						.css('top', toolTipPositionTop)
						.css('height', $('#tooltip').height())
						.show();
				}
				
				$('#tooltip')
					.css('left', toolTipPositionLeft)
					.css('top', toolTipPositionTop)
					.show();
				
				return false;
			}).mouseout(function () {
				if ($.browser.msie && ($.browser.version == '6.0')) {
					$('#tooltip-iframe').hide();
				}
				$('#tooltip').hide();
				return false;
			});
		})
	}	
}

function formIsDefault (value, element, params) {
	if (value == params)
		return false;
	else 
		return true;
}

function subscribeFormInit() {
	if ($('.module-block-5 #subscribe-form').size() > 0) {
		formDefaultValueReplace($('.module-block-5 #subscribe-form #edit-name'), 'Name');
		formDefaultValueReplace($('.module-block-5 #subscribe-form #edit-email'), 'Email Address');
		
		$.validator.addMethod("isDefaultValue", formIsDefault, "This field is required.");
		
		$('.module-block-5 #subscribe-form').validate({
			errorClass: "label-error",
			highlight: function(element, errorClass) {
			    // $(element).addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
			     //$(element).removeClass(errorClass);
			},
   			wrapper: '',
   			errorPlacement: function(error, element) {
	     		error.prependTo( $('.module-block-5 #subscribe-form') );
	   		},
			rules: {
				'name': {
					required: true,
					isDefaultValue: 'Name'
				},
				'email': {
					required: true,
					email: true
				}
			},
			messages: {
				'name':'Please fill in your <strong>Name</strong>',
				'email': 'Please enter a valid <strong>Email</strong>'
			}
		});
	}
}

function deliveryCalculatorInit () {
	if ($('.module-node-product .product-details').size() > 0 && $('.button-call-us').size() <= 0 ) {
		$('.module-node-product .product-details').append('<a href="#" class="link-delivery-calculator">Check Delivery Cost</a>');
			
		var tooltipHTML = '';
		
		if($.browser.msie && ($.browser.version == '6.0')){
			tooltipHTML += '<iframe id="delivery-calculator-iframe"></iframe>';
		}
		
		tooltipHTML += '<div id="delivery-calculator"><div id="delivery-calculator-header"></div><div id="delivery-calculator-content"><div id="delivery-calculator-content-container">';
		tooltipHTML += '<a class="close">Reset</a><h3 class="heading">Delivery Calculator</h3>';
		tooltipHTML += '</div></div><div id="delivery-calculator-footer"></div></div>';
		
		$('body').append(tooltipHTML);
		
		var preLoadImageArray = new Array();
		
		preLoadImageArray.push('delivery-calculator-bg.gif');
		preLoadImageArray.push('delivery-calculator-top-bg.gif');
		preLoadImageArray.push('delivery-calculator-bottom-bg.gif');
		
		preLoadImages(preLoadImageArray);

		$('.link-delivery-calculator').click(function () {
			var formHTML = '';
			
			$('#delivery-calculator').removeClass('loading');
									
			formHTML += '<form id="delivery-calculator-form" method="post" action=""><fieldset><legend>Calculate Delivery Cost for this Product</legend>';
			formHTML += '<label>Your Postcode <input type="text" id="delivery-postcode-input" name="delivery-postcode" maxlength="4" /></label><button type="submit">Search</button></fieldset></form>';
			
			if ($('#delivery-calculator-form').size() == 0) {
				$('#delivery-calculator-content-container').append(formHTML);
			}
			
			$('#delivery-calculator-result').remove();
			
			$('#delivery-calculator .close').click(function () {
				if ($.browser.msie && ($.browser.version == '6.0')) {
					$('#delivery-calculator-iframe').hide();
				}
				
				$('#delivery-calculator').hide();
				$('#delivery-calculator-result').remove();
				
				if ($('#delivery-calculator-form').size() == 0) {
					$('#delivery-calculator-content-container').append(formHTML);
				}
			})
					
			if ($.validator != undefined) {
				
				$('#delivery-calculator-form').validate({
					focusInvalid: false,
					errorClass: "error",
					highlight: function(element, errorClass) {
					     $(element).addClass(errorClass);
					     $(element.form).find('label[for=' + element.id + ']:not([generated=true])')
					     	.addClass('error');
					},
					unhighlight: function(element, errorClass) {
					     $(element).removeClass(errorClass);
					     $(element.form).find('.form-item label[for=' + element.id + ']:not([generated=true])')
						 	.removeClass('error');
					},
	   				wrapper: '',
	   				errorPlacement: function(error, element) {
	     				error.appendTo( $('#delivery-calculator-form') );
	   				},
					rules: {
						'delivery-postcode': {
							minlength: 3,
							maxlength: 4,
							required: true,
							digits: true
						}
					},
					messages: {
		         		'delivery-postcode': 'Please enter a valid postcode'
					},
					submitHandler: function(form) {
				   		postcode = $(form).find('#delivery-postcode-input').val();
				   		
				   		$.ajaxSync({
							type: 'POST',
							url: '/product/shipping/' + productNID +  '/' + postcode,
							dataType: 'json',
							success: function(response){
								$('#delivery-calculator-form').remove();
								if (response.error)
									$('#delivery-calculator-content-container').append('<p id="delivery-calculator-result">' + response.errorMessages + '</p>');
								else
									$('#delivery-calculator-content-container').append('<p id="delivery-calculator-result">Base estimated delivery cost of this product to <strong>' + postcode + '</strong> is <strong>' + response.extras.none.shipping + '</strong>.</p>');
								
					 		},
					 		error: function(XMLHttpRequest, textStatus, errorThrown){
							//	$('#delivery-calculator-form').remove();
								//$('#delivery-calculator-content-container').append('<p id="delivery-calculator-result"><strong>The Delivery Cost to your postcode could not be calculated. Please try again.</strong>.</p>');
					 		}
						});
						
						return false;
				    }
				});
				
				$('#delivery-calculator-form').ajaxSend(function(evt, request, settings){
				  	$('#delivery-calculator-form').empty();
				    $('#delivery-calculator').addClass('loading');
				});
			}
			
			var delivery = $('#' + $(this).attr('href').replace(/#/, ''));
			var deliveryPosition = findPos($('.link-delivery-calculator').get(0));
			
			var deliveryPositionTopOffset = 6;
			var deliveryPositionLeftOffset = 8;
			
			var deliveryPositionLeft = deliveryPosition[0] - $('#delivery-calculator').width() + deliveryPositionLeftOffset;
			var deliveryPositionTop = deliveryPosition[1] - $('#delivery-calculator').height() + deliveryPositionTopOffset;
			
			$('#delivery-calculator')
				.css('left', deliveryPositionLeft)
				.css('top', deliveryPositionTop)
				.show();
			
			if ($.browser.msie && ($.browser.version == '6.0')) {
				$('#delivery-calculator-iframe')
					.css('left', deliveryPositionLeft)
					.css('top', deliveryPositionTop)
					.css('height', $('#delivery-calculator').height())
					.show();
			}
			
			$('#delivery-postcode-input').focus();
			
			return false;
		});
	}
	
}

function productListingInit() {
	$('.view-content-product-listing .product-listing li:last, .view-content-search .product-listing li:last').addClass('last');
}

function productDetailsInit() {
	if ($('.module-node-product .product-information .product-tabs').size() > 0) {
		$('.module-node-product .product-information .product-tabs').tabs();
	}
}

function convertStringToFloat (str) {
	return parseFloat(str.replace('$', '').replace(',', ''));
}

function calculateGSTComponent (total) {
	return (parseFloat(total / 11));
}

function displayFormattedNumber (str) {
	
	var wholeNum = '';
	var formattedNumber = '';
	var strArray = parseFloat(str).toFixed(2).toString().split('.');
	
	var wholeNumbers = strArray[0];
	
	if (wholeNumbers.length > 3) {
		//reverse string
		var reversedWholeNumbers = wholeNumbers.split('').reverse();
		
		//add in , seperator for evert thousand
		var split = ',';
		
		for (var count = 1; count <= reversedWholeNumbers.length; count++) {
			formattedNumber += reversedWholeNumbers[count-1];
			if (reversedWholeNumbers[count] != undefined && count % 3 == 0)
				formattedNumber += split;
		}
		
		//reverse string
		wholeNumbers = formattedNumber.split('').reverse().join('');
	}
	
	//add in decimal value
	if (strArray.length > 1)
		 wholeNumbers += '.' + strArray[1];

	return '$' + wholeNumbers;
}

function disableEnterKey(e)
{
     var key;
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox
          
     if(key == 13)
          return false;
     else
          return true;
}

function displayCheckoutShipping(response, showMessage) {

	if (showMessage)
		$('#uc-cart-checkout-form .delivery-calculator-message').remove();

	if (response.error) {
		$('#edit-panes-seconds-delivery-delivery-postal-code-wrapper').after('<p class="delivery-calculator-message delivery-calculator-error">' + response.errorMessages + '</p>');
		$('#seconds_totals-pane .review-shipping-total td').addClass('error').text( 'Postcode Required' );
		$('#seconds_totals-pane .review-gst-total td').text( displayFormattedNumber(checkoutGST) );
		$('#seconds_totals-pane .order-total td').text( displayFormattedNumber(checkoutOrderTotal) );		
	} else {
		if (showMessage && response.infoMessages != '')
			$('#edit-panes-seconds-delivery-delivery-postal-code-wrapper').after('<p class="delivery-calculator-message delivery-calculator-success">' + response.infoMessages + '</p>')
		else if (showMessage)
			$('#edit-panes-seconds-delivery-delivery-postal-code-wrapper').after('<p class="delivery-calculator-message delivery-calculator-success">Your delivery charge has been calculated below.</p>')
			
		var newSubtotal = '';
		var newShipping = '';
		var newGST = '';
		var newOrderTotal = '';
		
		if (response.shippingOptions) {
			if ( $('#edit-panes-seconds-shipping-two-man:checked').size() == 1 && $('#edit-panes-seconds-shipping-delivery-window:checked').size() == 1 ) {
				newSubtotal = response.extras.all.subtotal;
				newShipping = response.extras.all.shipping;
				newGST = response.extras.all.gst;
				newOrderTotal = response.extras.all.total;
			} else if ($('#edit-panes-seconds-shipping-two-man:checked').size() == 1) {
				newSubtotal = response.extras.two_man.subtotal;
				newShipping = response.extras.two_man.shipping;
				newGST = response.extras.two_man.gst;
				newOrderTotal = response.extras.two_man.total;
			} else if ($('#edit-panes-seconds-shipping-delivery-window:checked').size() == 1 ) {
				newSubtotal = response.extras.delivery_window.subtotal;
				newShipping = response.extras.delivery_window.shipping;
				newGST = response.extras.delivery_window.gst;
				newOrderTotal = response.extras.delivery_window.total;
			} else {
				newSubtotal = response.extras.none.subtotal;
				newShipping = response.extras.none.shipping;
				newGST = response.extras.none.gst;
				newOrderTotal = response.extras.none.total;
			}
			
			sIFR.replace(futura, {
				  selector:	'#uc-cart-checkout-form legend',
				  css: [
				  	'.sIFR-root { color: #0053a0; text-transform: uppercase; font-size: 14px; }',
				  	'a { color: #0053a0; }',
				    'a:link { color: #0053a0; }',  
				    'a:hover { color: #0053a0; }'  
				  ],
				  ratios: [8, 1.41, 10, 1.33, 14, 1.31, 16, 1.26, 20, 1.27, 24, 1.26, 25, 1.24, 26, 1.25, 35, 1.24, 49, 1.23, 54, 1.22, 55, 1.23, 74, 1.22, 75, 1.21, 79, 1.22, 80, 1.21, 81, 1.22, 89, 1.21, 90, 1.22, 1.21],
				  tuneHeight: -8,
				  transparent: true
			});
		} else {
			newSubtotal = response.extras.none.subtotal;
			newShipping = response.extras.none.shipping;
			newGST = response.extras.none.gst;
			newOrderTotal = response.extras.none.total;
			
			$('#seconds_shipping-pane, .hr-shipping').hide();
		}
		
		//fixes rendering issue in IE7.0
		if ($.browser.msie && ($.browser.version == '7.0'))
			$('#edit-panes-seconds-payment-payment-details-cc-cvv-wrapper .link-tooltip').css('position', 'static').css('position', 'relative');
		
		$('#seconds_totals-pane .review-subtotal td').text(newSubtotal);;
		$('#seconds_totals-pane .review-shipping-total td').text(newShipping).removeClass('error');
		$('#seconds_totals-pane .review-gst-total td').text(newGST);
		$('#seconds_totals-pane .order-total td').text(newOrderTotal);
		
	}

}

function deliveryOptionsInit () {
  $('#edit-panes-seconds-delivery-options-local-store-wrapper').hide();
  
  if ($('#uc-cart-checkout-form').size() > 0) {
    $('#seconds_delivery_options-pane input[type="radio"]').click(function() {
      checkoutCalculateShipping(true, true)
    });
  }
}

function checkoutCalculateShipping (showMessage, forceCalculation) {
	
	if (forceCalculation || checkoutPostcode != $('#edit-panes-seconds-delivery-delivery-postal-code').val()) {
		checkoutPostcode = $('#edit-panes-seconds-delivery-delivery-postal-code').val();
				
		$('#uc-cart-checkout-form .delivery-calculator-message').remove();
		var queryString = 'postcode=' + $('#edit-panes-seconds-delivery-delivery-postal-code').val();
		queryString += '&subtotal=' + checkoutSubtotal;
		$('#uc-cart-checkout-form #edit-panes-seconds-delivery-delivery-postal-code-wrapper').addClass('loading');
		
		if ($('#seconds_delivery_options-pane input[type="radio"]:checked').val() == 'localpickup') {
		  $('#edit-panes-seconds-delivery-options-local-store-wrapper').show();
		  shippingUrl = '/cart/checkout/pickup/cost';
		}
		else {
		  $('#edit-panes-seconds-delivery-options-local-store-wrapper').hide();
		  shippingUrl = '/cart/checkout/shipping/cost';
		}
		
		$.ajaxSync({
			type: 'POST',
			url: shippingUrl,
			data: queryString,
			dataType: 'json',
			success: function(response){
				
				$('#uc-cart-checkout-form #edit-panes-seconds-delivery-delivery-postal-code-wrapper').removeClass('loading');
				checkoutResponse = response;
				displayCheckoutShipping(response, showMessage);
				
	 		}
		});
	}
	
}

function checkoutInit() {
	
	if ($("#uc-cart-checkout-form").size() > 0) {
		
		preLoadImages(Array('loading-indicator-blue.gif'));
		
		checkoutSubtotal = convertStringToFloat($('#seconds_totals-pane .review-subtotal td').text());
		
		checkoutShippingTotal = 0;
		if ($('#seconds_totals-pane .review-shipping-total td').text().toLowerCase() != 'postcode required') 
			checkoutShippingTotal = convertStringToFloat($('#seconds_totals-pane .review-shipping-total td').text().replace('$', '').replace(',', ''))
		
		checkoutGST = convertStringToFloat($('#seconds_totals-pane .review-gst-total td').text().replace('$', '').replace(',', '')) - calculateGSTComponent(checkoutShippingTotal);
		checkoutOrderTotal = convertStringToFloat($('#seconds_totals-pane .order-total td').text().replace('$', '').replace(',', '')) - checkoutShippingTotal;

		var spanRequired = $('<span title="This field is required." class="form-required">*</span>');
		var divHR = '<div class="hr"><hr /></div>'; 
		$('#seconds_delivery_options-pane, #seconds_shipping-pane, #seconds_totals-pane, #seconds_comments-pane').before(divHR);
		$('#seconds_shipping-pane').prev('div.hr').addClass('hr-shipping');
		$('#uc-cart-checkout-form .button-back-to-cart').addClass('cancel');
		
		//Disable form submit when Enter Key is Pressed
		$('#seconds_customer-pane .form-text, #seconds_customer-pane button,' + 
		  '#seconds_returning_customer-pane .form-text').keypress(function(e) {
			return disableEnterKey(e);
		});
		
		//wrap account-fieldset divs around account panes
		if ($('#seconds_customer-pane #edit-panes-seconds-customer-primary-email-wrapper').size() > 0) {
			$('#seconds_customer-pane').wrap('<div class="account-fieldset account-fieldset-' + $('#seconds_customer-pane').attr('id') + '"><div class="account-fieldset-outer"></div></div>');
		}
		if ($('#seconds_returning_customer-pane').size() > 0) {
			$('#seconds_returning_customer-pane').wrap('<div class="account-fieldset account-fieldset-' + $('#seconds_returning_customer-pane').attr('id') + '"><div class="account-fieldset-outer"></div></div>');
			$('#seconds_returning_customer-pane .button-login-and-prefill').addClass('cancel');
		}
		
		if ($('#seconds_customer-pane').size() > 0 && $('body').hasClass('logged-out')) {
		
			var labelCreateAccount = $('<div id="edit-panes-seconds-customer-create-account-wrapper" class="form-item"><label><input type="checkbox" id="create-online-account" name="create-online-account" value="yes" /> Create an Online Account</label></div>');
			
			//create customer info pane
			var fieldsetCustomerInfo = $('<fieldset id="seconds_customer-info-pane"><legend>Customer Information</legend>' +
						'<p class="seconds_edit-customer"><strong>E-mail address:</strong> <span></span>&nbsp;(<a href="#seconds_customer-pane" id="seconds_edit-customer-info">edit</a>)</p>' +
						'<p class="seconds_create-account"><strong>Create new account online:</strong> <span></span></p>' +
						'</fieldset>');
					
			$('#seconds_delivery-pane').before($(fieldsetCustomerInfo));
					
			//create the continue button on the New Customer Information Pane
			var buttonContinue = $('<button type="button" id="button-continue" name="seconds_account-continue"><span>Continue</span></button>').click(function () {
				
				//Remove old error messages
				if ($('.module-message .messages').size() > 0)
					$('.module-message .messages').remove();
				
				var newAccountDetailsValid = true;
				var createAccount = 'No';
				
				//check all new account information is supplied
				if (!$("#uc-cart-checkout-form").validate().element("#edit-panes-seconds-customer-primary-email"))
					newAccountDetailsValid = false;

				if ($('#create-online-account').is(':checked')) {
					createAccount = 'Yes';
					if (!$("#uc-cart-checkout-form").validate().element("#edit-panes-seconds-customer-new-account-pass"))
						newAccountDetailsValid = false;
					if (!$("#uc-cart-checkout-form").validate().element("#edit-panes-seconds-customer-new-account-pass-confirm"))
						newAccountDetailsValid = false;
				}
				
				if (newAccountDetailsValid) {
					
					//Add details to customer info pane
					$('#seconds_customer-info-pane .seconds_edit-customer span').text($('#edit-panes-seconds-customer-primary-email').val());
					$('#seconds_customer-info-pane .seconds_create-account span').text(createAccount);
					
					$('body').removeClass('logged-out').addClass('logged-in');
					
					if (checkoutResponse.shippingOptions)
							$('#seconds_shipping-pane, #uc-cart-checkout-form .shipping-hr').show();
					
					$('#seconds_returning_customer-pane .button-login-and-prefill').attr('disabled', 'disabled');
					
					$('#seconds_edit-customer-info').click(function () {
						$('body').removeClass('logged-in').addClass('logged-out');
						
						$('#seconds_returning_customer-pane .button-login-and-prefill').removeAttr('disabled');
						
						if (checkoutResponse.shippingOptions)
							$('#seconds_shipping-pane, #uc-cart-checkout-form .shipping-hr').hide();
					}); 
					
					if (findOperatingSystem() != 'win') {
						//replace fieldset headings
						sIFR.replace(futura, {
						  selector:	'#uc-cart-checkout-form legend',
						  css: [
						  	'.sIFR-root { color: #0053a0; text-transform: uppercase; font-size: 14px; }',
						  	'a { color: #0053a0; }',
						    'a:link { color: #0053a0; }',  
						    'a:hover { color: #0053a0; }'  
						  ],
						  ratios: [8, 1.41, 10, 1.33, 14, 1.31, 16, 1.26, 20, 1.27, 24, 1.26, 25, 1.24, 26, 1.25, 35, 1.24, 49, 1.23, 54, 1.22, 55, 1.23, 74, 1.22, 75, 1.21, 79, 1.22, 80, 1.21, 81, 1.22, 89, 1.21, 90, 1.22, 1.21],
						  tuneHeight: -8,
						  transparent: true
						});
					}
				}
			});
			
			//Adds required asterisks to the password fields on the New Customer Information pane
			$('#seconds_customer-pane #edit-panes-seconds-customer-new-account-pass-wrapper label').append($(spanRequired).clone());
			$('#seconds_customer-pane #edit-panes-seconds-customer-new-account-pass-confirm-wrapper label').append($(spanRequired).clone());
			
			//Adds the "Create Account" and "Continue" button to the New Customer Information pane
			$('#seconds_customer-pane fieldset').before(labelCreateAccount).after(buttonContinue);
	
			$('#seconds_customer-pane #create-online-account').click(function () {
				if ($(this).is(':checked')) {
					$('#seconds_customer-pane fieldset').show();
				} else {
					$('#seconds_customer-pane fieldset').hide();
					$("#uc-cart-checkout-form").validate().element("#edit-panes-seconds-customer-new-account-pass");
					$("#uc-cart-checkout-form").validate().element("#edit-panes-seconds-customer-new-account-pass-confirm");
				}
				
			});
			
		}
		
		if($.validator != undefined) {
		
			$('#uc-cart-checkout-form').validate({
				errorClass: "label-error",
				wrapper: 'li',
				highlight: function(element, errorClass) {
				     $(element).addClass(errorClass);
				     $(element.form).find('label[for=' + element.id + ']:not([generated=true])')
				     	.addClass('error');
				},
				unhighlight: function(element, errorClass) {
				     $(element).removeClass(errorClass);
				     $(element.form).find('.form-item label[for=' + element.id + ']:not([generated=true])')
					 	.removeClass('error');
				},
				errorPlacement: function(error, element) {
					var parentElement = element;
					var isFieldset = false;
					while (!isFieldset) {
						parentElement = $(parentElement).parent();
						
						if ($(parentElement).is('fieldset') && $(parentElement).attr('id') != null && $(parentElement).attr('id') != '')
							isFieldset = true;
					}
					if ($(parentElement).children('div.error').size() == 0) 
						$(parentElement).children('legend').after('<div class="error"><ul></ul></div>');
						
     				error.appendTo( $(parentElement).children('div.error').children('ul') );
   				},
				rules: {
					'panes[seconds_customer][primary_email]': {
						email: true
					},
					'panes[seconds_customer][new_account][pass]': {
						required: {
	         				depends: function(element) {
	           				return $('#create-online-account').is(':checked')
	         				}
	         			},
	         			minlength: 6
	         		},
					'panes[seconds_customer][new_account][pass_confirm]': {
						required: {
	         				depends: function(element) {
	           				return $('#create-online-account').is(':checked')
	         				}
	         			},
	         			equalTo: "#edit-panes-seconds-customer-new-account-pass"
	         		},
	         		'panes[seconds_delivery][delivery_postal_code]': {
	         			required: true,
	         			digits: true,
	         			maxlength: 4,
	         			minlength: 3
	         		},
	         		'panes[seconds_billing][billing_first_name]': {
	         			required: {
	         				depends: function(element) {
	           				return !$('#edit-panes-seconds-billing-copy-address').is(':checked')
	         				}
	         			}
	         		},
	         		'panes[seconds_billing][billing_last_name]': {
	         			required: {
	         				depends: function(element) {
	           				return !$('#edit-panes-seconds-billing-copy-address').is(':checked')
	         				}
	         			}
	         		},
	         		'panes[seconds_billing][billing_street1]': {
	         			required: {
	         				depends: function(element) {
	           				return !$('#edit-panes-seconds-billing-copy-address').is(':checked')
	         				}
	         			}
	         		},
	         		'panes[seconds_billing][billing_postal_code]': {
	         			required: true,
	         			digits: true,
	         			maxlength: 4,
	         			minlength: 4,
	         			required: {
	         				depends: function(element) {
	           				return !$('#edit-panes-seconds-billing-copy-address').is(':checked')
	         				}
	         			}
	         		},
	         		'panes[seconds_billing][billing_street2]': {
	         			required: {
	         				depends: function(element) {
	           				return !$('#edit-panes-seconds-billing-copy-address').is(':checked')
	         				}
	         			}
	         		},
	         		'panes[seconds_billing][billing_city]': {
	         			required: {
	         				depends: function(element) {
	           				return !$('#edit-panes-seconds-billing-copy-address').is(':checked')
	         				}
	         			}
	         		},
	         		'panes[seconds_billing][billing_zone]': {
	         			required: {
	         				depends: function(element) {
	           				return !$('#edit-panes-seconds-billing-copy-address').is(':checked')
	         				}
	         			}
	         		},
	         		'panes[seconds_billing][billing_phone]': {
	         			required: {
	         				depends: function(element) {
	           				return !$('#edit-panes-seconds-billing-copy-address').is(':checked')
	         				}
	         			}
	         		},
	         		'panes[seconds_payment][payment_details][cc_number]': {
	         			digits: true,
	         			minlength: 13,
	         			maxlength: 16
	         		},
	         		'panes[seconds_payment][payment_details][cc_cvv]': {
	         			digits: true,
	         			minlength: 3,
	         			maxlength: 4
	         		}
				},
				messages: {
					'panes[seconds_customer][primary_email]': 'Please fill in your valid <strong>Email Address</strong>',
					'panes[seconds_customer][new_account][pass]': {
						required: 'Please fill in a new <strong>password</strong>',
						minlength: 'Your <strong>password</strong> must be at least <strong>6 characters</strong> in length'
	         		},
	         		'panes[seconds_customer][new_account][pass_confirm]': {
						required: 'Please fill in a the confirm <strong>password</strong>',
	         			equalTo: 'Please make sure your <strong>passwords match</strong>'
	         		},
	         		'panes[seconds_delivery][delivery_first_name]': 'Please enter your <strong>First Name</strong>',
	         		'panes[seconds_delivery][delivery_last_name]': 'Please enter your <strong>Last Name</strong>',
	         		'panes[seconds_delivery][delivery_street1]': 'Please enter your <strong>Street Address</strong>',
	         		'panes[seconds_delivery][delivery_postal_code]': 'Please enter a valid <strong>Postcode</strong>',
	         		'panes[seconds_delivery][delivery_street2]': 'Please enter your <strong>Suburb</strong>',
	         		'panes[seconds_delivery][delivery_city]': 'Please enter your <strong>City</strong>',
	         		'panes[seconds_delivery][delivery_zone]': 'Please select a <strong>State</strong>',
	         		'panes[seconds_delivery][delivery_phone]': 'Please enter in your <strong>Contact Number</strong>',
	         		'panes[seconds_billing][billing_first_name]': 'Please enter your First Name',
	         		'panes[seconds_billing][billing_last_name]': 'Please enter your <strong>Last Name</strong>',
	         		'panes[seconds_billing][billing_street1]': 'Please enter your <strong>Street Address</strong>',
	         		'panes[seconds_billing][billing_postal_code]': 'Please enter a valid <strong>Postcode</strong>',
	         		'panes[seconds_billing][billing_street2]': 'Please enter your <strong>Suburb</strong>',
	         		'panes[seconds_billing][billing_city]': 'Please enter your <strong>City</strong>',
	         		'panes[seconds_billing][billing_zone]': 'Please select a <strong>State</strong>',
	         		'panes[seconds_billing][billing_phone]': 'Please enter in your <strong>Contact Number</strong>',
	         		'panes[seconds_payment][payment_details][cc_owner]': 'Please enter your <strong>Name</strong> as it appears on your Credit Card',
	         		'panes[seconds_payment][payment_details][cc_type]': 'Please select your <strong>Credit Card Type</strong>',
	         		'panes[seconds_payment][payment_details][cc_number]': 'Please enter your <strong>Credit Card Number</strong>', 
	         		'panes[seconds_payment][payment_details][cc_cvv]': 'Please enter your <strong>Credit Card Verification Code</strong>',
	         		'panes[seconds_comments][terms]': 'Please accept the 2nds World <strong>Terms and Conditions</strong> to place your order'
				}
			});
			
			$('#uc-cart-checkout-form .button-proceed-to-order-submission').click(function () {
				//return $('#uc-cart-checkout-form').validate().form();
			});
		}
		
		if ($('#seconds_delivery-pane').size() > 0) {
			if ($('#edit-panes-seconds-delivery-delivery-postal-code').val() != '') {
				checkoutCalculateShipping(false);
			}
			$('#edit-panes-seconds-delivery-delivery-postal-code').blur( function () {
			
				if ($("#uc-cart-checkout-form").validate().element("#edit-panes-seconds-delivery-delivery-postal-code")) 
					checkoutCalculateShipping(true);

			});
		}
		
		if ($('#seconds_billing-pane').size() > 0) {
			$('#seconds_billing-pane #edit-panes-seconds-billing-copy-address').attr('checked', 'checked');
			
			$('#seconds_billing-pane #edit-panes-seconds-billing-copy-address').click(function () {
				if ($(this).is(':checked')) {
					//Revalidate the seconds billing state dropdown as it is not being unhighlighted by default
					$("#uc-cart-checkout-form").validate().element("#edit-panes-seconds-billing-billing-zone");
					$('#seconds_billing-pane div.error, #seconds_billing-pane #billing-fields-container').hide();
				} else {
					$('#seconds_billing-pane div.error,#seconds_billing-pane #billing-fields-container').show();
				}
			});
			
			$('#seconds_billing-pane .form-item label:gt(0):not([for=edit-panes-seconds-billing-billing-company])').append($(spanRequired).clone());
			$('#seconds_billing-pane .form-item input:gt(0):not([id=edit-panes-seconds-billing-billing-company]), ' +
			  '#seconds_billing-pane .form-item select').addClass('required');
			//edit-panes-seconds-billing-copy-address
		}
		
		if ($('#seconds_shipping-pane').size() > 0) {			
			$('#edit-panes-seconds-shipping-two-man, #edit-panes-seconds-shipping-delivery-window').click(function () {
				displayCheckoutShipping(checkoutResponse, false);
			})
		}
		
		if ($('#seconds_payment-pane').size() > 0) {
			$('#seconds_payment-pane .form-radios input:first').attr('checked', 'checked');
			var cvvTooltip = '<div id="tooltip-cvv" class="tooltip tooltip-cvv"><div class="tooltip-header"></div><div class="tooltip-content">';
			cvvTooltip += '<h3 class="heading">Credit Card Verification</h3><p>The CVV is a three digit number found on the back of your credit card below the magnetic strip on the right hand side. This number is required by our secure payment gateway to process your order.</p>';
			cvvTooltip += '</div><div class="tooltip-footer"></div></div>';
			
			$('#edit-panes-seconds-payment-payment-details-cc-cvv-wrapper label').append('<span href="#tooltip-cvv" class="link-tooltip"><span><span>More</span></span></span>');
			$('#edit-panes-seconds-payment-payment-details-cc-cvv-wrapper').after(cvvTooltip);
			
			//Turn off autocomplete to storing of credit card
			$('#edit-panes-seconds-payment-payment-details-cc-owner').attr('autocomplete', 'off');
			$('#edit-panes-seconds-payment-payment-details-cc-number').attr('autocomplete', 'off');
			$('#edit-panes-seconds-payment-payment-details-cc-cvv').attr('autocomplete', 'off');
			$('#edit-panes-seconds-payment-payment-details-cc-exp-month').attr('autocomplete', 'off');
			$('#edit-panes-seconds-payment-payment-details-cc-exp-year').attr('autocomplete', 'off'); 
		}
	
		//If an email address is pre-filled by drupal then... 
		if ($("#edit-panes-seconds-customer-primary-email").val() != '') {
			$('#uc-cart-checkout-form fieldset:not([id=seconds_customer-info-pane]):not([id=seconds_shipping-pane]), #uc-cart-checkout-form #checkout-form-bottom').show().css('display', 'block');
			$('#uc-cart-checkout-form .hr:not([class=hr-shipping])').show().css('display', 'block');
			$('#seconds_customer-pane #button-continue').hide();
		}
	
		var imageArray = new Array(); 
		imageArray.push(Array('#uc-cart-checkout-form .button-back-to-cart', 'button-back-to-cart.gif', 'button-back-to-cart-hover.gif'))
		imageArray.push(Array('#uc-cart-checkout-form .button-proceed-to-order-submission', 'button-proceed-to-order-submission.gif', 'button-proceed-to-order-submission-hover.gif'))
		imageArray.push(Array('#uc-cart-checkout-form .button-calculate-shipping', 'button-calculate-shipping.gif', 'button-calculate-shipping-hover.gif'))
		imageArray.push(Array('#uc-cart-checkout-form .button-login-and-prefill', 'button-login-and-prefill.gif', 'button-login-and-prefill-hover.gif'))
		imageHoverInit(imageArray);
	}
			
}

function reviewInit () {
	if ($('#uc-cart-checkout-review-form').size() > 0) {
		var imageArray = new Array(); 
		imageArray.push(Array('#uc-cart-checkout-review-form .button-back-to-order-details', 'button-back-to-order-details.gif', 'button-back-to-order-details-hover.gif'))
		imageArray.push(Array('#uc-cart-checkout-review-form .button-submit-order', 'button-submit-order.gif', 'button-submit-order-hover.gif'))
		imageHoverInit(imageArray);
	}
}

function scrollerInit () {
	if ($('.module-views-banners_front').length) {
  	$('.module-views-banners_front .module-content').scroller({
  		slide: '.node',
  		animation: 'slide',
			hover: true
  	});
  	var leftLength = 350;
  	var scrollerLength = $('.module-views-banners_front .scroller-control').length - 3;
  	if (scrollerLength > 1) {
  		leftLength -= (scrollerLength-1) * 5;
  	}
  	$('.module-views-banners_front .scroller-controls').css('margin-left', leftLength+'px');
		$('.module-views-banners_front .scroller-control-prev, .module-views-banners_front .scroller-control-next').css('top', '-116px');
  }
}

function floatingBanner() {
    // wraps the two floater blocks within a div
    $('.module-block-5, .module-block-7').wrapAll('<div class="floater"></div>');
    
    // floats the subscribe to newsletter block
    $('.floater').floatingbanner({ie6: true});
    
    // fixes IE redraw bug where the subscribe to newsletter email and name appears in the wrong position
    $('.floater .form-text').css('top', '3px');
}

function validateEmail(elementValue){
   var emailPattern = /^.*@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   return emailPattern.test(elementValue);
 }


function xboxCompInit() {
    if ($('#subscribe-form-xbox').length) {
        $('#subscribe-form-xbox #xbox-name').focus(function () {
            if ($(this).val() == 'Name' || $(this).val() == 'Please enter your name') {
                $(this).val('');
            }
        }).blur(function () {
            if ($(this).val() == '') {
                $(this).val('Name');
            }
        });
        $('#subscribe-form-xbox #xbox-email').focus(function () {
            if ($(this).val() == 'Email Address' || $(this).val() == 'Please enter a valid email') {
                $(this).val('');
            }
        }).blur(function () {
            if ($(this).val() == '') {
                $(this).val('Email Address');
            }
        });
        $('#subscribe-form-xbox').submit(function () {
            var errors = false;
            if ($('#subscribe-form-xbox #xbox-name').val() == '' || $('#subscribe-form-xbox #xbox-name').val() == 'Name' || $('#subscribe-form-xbox #xbox-name').val() == 'Please enter your name') {
                $('#subscribe-form-xbox #xbox-name').val('Please enter your name').addClass('error');
                errors = true;
            }
            if ($('#subscribe-form-xbox #xbox-email').val() == '' || $('#subscribe-form-xbox #xbox-email').val() == 'Email Address' || $('#subscribe-form-xbox #xbox-email').val() == 'Please enter a valid email' || !validateEmail($('#subscribe-form-xbox #xbox-email').val())) {
                $('#subscribe-form-xbox #xbox-email').val('Please enter a valid email').addClass('error');
                errors = true;
            }
            return !errors;
        });
    }
}

// Order review progress meter on submit [SEC-129]
function orderReviewInit() {
    if ($('#order-submit-top').length) {
        $('#order-submit-top').prepend('<input type="image" alt="Submit Order" src="/sites/all/themes/secondsworld/images/button-submit-order.gif" title="Submit Order" id="button-submit-order-top" class="button-submit-order" name="submit_button">');
                
        $('#uc-cart-checkout-review-form .button-submit-order').click(function () {
          $('.order-review').addClass('order-submit-loading');
        });
        
        $('#button-submit-order-top').click(function () {
            $('.order-review').addClass('order-submit-loading');
            $('#uc-cart-checkout-review-form .button-submit-order').trigger('click');
        });
    }
}


function tableInit(){
  $('table').each(function () {
    $("thead tr:visible").find("th:first").addClass("first");
    $("thead tr:visible").find("th:last").addClass("last");
    
    $("tbody tr:visible").find("td:last").addClass("last");
    $('tbody tr:visible:odd', $(this)).addClass('even');
    $('tbody tr:visible:even', $(this)).addClass('odd');
  });
}

function shareLinks(){    
    if(typeof(stLight) != 'undefined'){
      var switchTo5x=true;
      stLight.options({publisher:'2abb94ad-c173-447e-99e8-6576f99cd2ae'});
    }
}

$(document).ready(function () {
  shareLinks();
  tableInit();
	orderReviewInit();
	scrollerInit();
	searchFormInit();
	filterFormInit();
	forwardFormInit();
	googleMapsInit();
	cartFormInit();
	addToCartFormInit();
	deliveryCalculatorInit();
	productListingInit();
	productDetailsInit();
	deliveryOptionsInit();
	checkoutInit();
	reviewInit();
	tooltipsInit();
	formValidation();	
	subscribeFormInit();
	//printButtonInit(Array($('.view-product-listing'), $('.view-search'), $('.module-node-product'), $('.order-review')));
	preLoadImages(Array('loading.gif'));
    floatingBanner();
    xboxCompInit();
	$('a[rel=external]').attr('target', '_blank');
});

