$(document).ready(function() {

	// Confirm clicks
	$(".confirmClick").click( function() { 
		if ($(this).attr('title')) {
			var question = 'Are you sure you want to ' + $(this).attr('title').toLowerCase() + '?';
		} else {
			var question = 'Are you sure you want to do this action?';
		}
		if ( confirm( question ) ) {
			window.location.href = this.src;
		} else {
			return false;
		}
	});

	////// CART CONTENTS ////////
	
	$("#cartContents .quantity").change( function() {
		$('#estimateShippingOpen').unbind();
		$('#estimateShippingOpen').click( function() {
			alert("Please click 'update cart' first to update your new quantities");
			return false;
		});
	});
	
	// Estimate Shipping - if your looking for code that modifies see the view shipping/estimate.php
	if (typeof jQuery.jqm != 'undefined') {
		$('#estimateShipping').jqm({ajax: '@href', trigger: '#estimateShippingOpen'});
	}
	

	////// CHECKOUT ////////
	$('#viewMyOrder').click( function () {
		$('#cartContents').slideToggle('slow');
	});
	
	
	////// CHECKOUT - STEP 1 ////////
	$('#email_check').submit( function () {
		var url = $('#email_check').attr('action');
		var email_address = $('#email_check input[@name=email_address]').val();
		// Check email address format
		if (checkEmail(email_address,'Email address format incorrect')) {
			// Set the loading image
			var loadingImage = $('#email_check input[@name=loadingImage]').val();
			$('#emailAddressCheck').hide();
			$('#emailAddressLoading').show();
			$.post(url, { email: email_address },
			  function(data){
				$('#emailAddressLoading').hide();
				if (data==1) {
					// Email exists
					$('#loginOptions').slideDown();
				} else {
					// New account
					$('#email_check').hide();
					$('#accountDetails input[@name=email]').val(email_address);
					$('#accountDetails').slideDown();
				}
			});
		}
		return false;
	});
	
	$('#admin_check').submit( function() {
		//$('#email_check').hide();
		//$('#accountDetails input[@name=email]').val(email_address);
		$('#accountDetails').slideDown();
		return false;
	});
	
	$('#step1 #changeEmailAddress').click( function() {
		$('#email_check').show();
		$('#accountDetails input[@name=email]').val('');
		$('#accountDetails').slideUp();
		$('#emailAddressCheck').show();
	});
	
	$('#step1 #useBillingAddress').click( function() {
		var checked = $(this).attr('checked');
		if(! checked) {
			$('#step1 #shippingAddressDetails').slideDown();
		} else {
			$('#step1 #shippingAddressDetails').slideUp();
		}
	});
	

	////// CHECKOUT - STEP 2 ////////
	
	// Check if there already is a selected shipping type
	if ($('input[@name=shipping_PK][@checked]').val()) {
		$('#choosePayments').slideDown();
		update_payment_total($('input[@name=shipping_PK][@checked]').val());
	}
	// Update total
	$('input[@name=shipping_PK]').click( function() {
		$('#choosePayments').slideDown();
		update_payment_total($(this).val());
	});
	// Validate
	if (typeof jQuery.validator != 'undefined') {
		$("#do_step2").validate({
			event: "keyup",
			errorElement: "em",
			errorPlacement: function(error, element) {
				error.appendTo( '#shippingError' );
			},
			rules: {
				shipping_PK: "required"
			},
			messages: {
				shipping_PK: "You need to choose a shipping option."
			}
		});
	}
	
	
	////// ORDER ////////
	
	// DO PAYMENT
	if (typeof jQuery.validator != 'undefined') {
		$('#do_choose_payment').validate({
			event: "keyup",
			errorElement: "em",
			errorPlacement: function(error, element) {
				error.appendTo( '#paymentChooseError' );
			},
			rules: {
				payment_PK: "required"
			},
			messages: {
				payment_PK: "You need to choose a payment method."
			}
		});
	}
	
	// 
	$('#do_process_payment_form').submit( function () {
		$('#process_payment_submitBox').hide();
		$('#process_payment_submitLoading').show();	
	});
	
});

// Used in ajax view
function cleanPrice(price) {
	newPrice = price.replace('$','');
	newPrice = newPrice.replace(',','');
	newPrice = parseFloat(newPrice);
	return newPrice;
}

function update_payment_total(pk) {
	$('#continueCheckout').show();
	$('#paymentOrderTotalBox').hide();
	$('#paymentOrderTotalBox').slideDown();
	var shippingAmount = $('input[@name=shippingType_amount_' + pk + ']').val();
	var itemTotal = $('#paymentItemTotal').val();
	var totalAmount = cleanPrice(shippingAmount) + cleanPrice(itemTotal);
	$('#paymentOrderTotal').html('$' + number_format(totalAmount,2,'.',','));
}


function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)    
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "," : dec_point;
    var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function checkEmail(value,theError) {
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(value)) { return true; } else { alert(theError); return false; }
}