/* Checkout Javascript */

/**
 * Required Elements - array
 *
 * @var array List of required form elements
 */
var required=new Array();
var originalRequired=new Array;

/* Load-time stuff */
$(document).ready(function() {
	//Add the handlers
	$('input.quantity').bind("keypress",function(e){
		//This validates the keypress - only numbers or control keys allowed
		if ((String.fromCharCode(e.which) >="0" && String.fromCharCode(e.which) <=9) || e.which<32){
			return true;
		} else {
			return false;
		}
	});
	$('input.quantity').bind("keyup",updatePricing);
	$('#paymentMethodCheque').bind("click",updatePricing);
	$('#paymentMethodPaypal').bind("click",updatePricing);
	$('#countryCode').bind("change",updatePricing);
	$('#countryCodeDelivery').bind("change",updatePricing);
	$('#deliverySameAsBilling').bind("change",updatePricing);	
	
	//Work out the required fields
	calculateRequiredFields(true);	

	//Hide the delivery address if necessary
	toggleDeliveryDisplay();
	
	//Disable the payment buttons
	togglePaymentButtons();

});


/**
 * Update the pricing
 */
function updatePricing() {
	//Set the cursor to wait for the main area
	$('#containerOuter').css('cursor','wait');
	
	//What's the payment method
	var usePaypal="";
	if ($('#paymentMethodPaypal').attr('checked')) {
		usePaypal="paypal/1/";
		$('#paymentButton').val("Buy Now by PayPal or Credit Card");
		$('#paypalNote').hide();
	} else {
		$('#paymentButton').val("Buy Now by Sterling Cheque");
		$('#paypalNote').show();
	}
	
	//What's the delivery country?
	var countryCodeDeliveryActual = $('#countryCodeDelivery').val();
	if($('#deliverySameAsBilling').attr('checked')) {
		countryCodeDeliveryActual = $('#countryCode').val();
		
		//Update the country name and drop down.
		$('#staticCountryName').html($('#countryCode option:selected').text());
		$('#countryCodeChange').val(countryCodeDeliveryActual);
	} else {
		//Update the country name and drop down.
		$('#staticCountryName').html($('#countryCodeDelivery option:selected').text());
		$('#countryCodeChange').val(countryCodeDeliveryActual);
	}	
	
	//Hide the top edit stuff
	cancelCountryChange();
	
	//Get the quantities via ajax
	var ajaxUrl="/ajax/Prices/pins/"+$('#pinQuantity').val()+"/bottles/"+$('#bottleQuantity').val()+"/"+usePaypal+"countryCodeDelivery/"+countryCodeDeliveryActual+"/";
	var pricingInfo=$.ajax({
		type: "GET",
		url: ajaxUrl,
		cache: false,
		success: function(html) {
			//Set cursor back to normal
			$('#containerOuter').css('cursor','auto');
			
			var prices=html.split(",",12);
			
			var bottlePrice=prices[0];
			var pinPrice=prices[1];
			var bottleTotal=prices[2];
			var pinTotal=prices[3];
			var subTotal=prices[4];
			var carriage=prices[5];
			var total=prices[6];
			var carriageMethod=prices[7];
			var bottleDiscount=prices[8];
			var bottleDiscountRate=parseInt(prices[9]);
			var paypalSupplement=prices[10];
			var carriageNotes=prices[11];

			//Work out the formatting of the quantities
			bottleQuantity=$('#bottleQuantity').val();
			if (!bottleQuantity) bottleQuantity="0";
			pinQuantity=$('#pinQuantity').val();
			if (!pinQuantity) pinQuantity="0";
			
			//Work out the bottle discount string
			if (bottleDiscountRate>0) {
				bottleDiscount+=" ("+bottleDiscountRate+"%)";	
			}
			
			//Are we using paypal?
			if ($('#paymentMethodPaypal').attr('checked')) {
				$('#paypalRow').show();
			} else {
				$('#paypalRow').hide();	
			}
			
			//Now update the totals table
			$('.bottleCost').html(bottlePrice)
			$('.bottleQuantity').html(bottleQuantity);
			$('.bottleDiscount').html(bottleDiscount);
			$('.bottleTotal').html(bottleTotal);
			$('.pinCost').html(pinPrice)
			$('.pinQuantity').html(pinQuantity);
			$('.pinTotal').html(pinTotal);
			$('.subTotal').html(subTotal);
			$('.carriageMethod').html(carriageMethod);
			$('.carriage').html(carriage);
			$('.total').html(total);
			$('.payPalTotal').html(paypalSupplement);
			
			//And the paypal table
			$('#paypalShipping').val(carriage);
			$('#paypalAmount').val(subTotal);
			
			//Possibly enable the buy buttons if the total was previously zero, or disable them
			togglePaymentButtons();
			
			//Update the carriage notes
			$('.carriageNotes').html(carriageNotes);
			if (carriageNotes) {
				$('#carriageNotesRow').show();
			} else {
				$('#carriageNotesRow').hide();	
			}
			
		}
	});
}

function validateChar(e,what,text,textlength) {
	//Returns true or false, depending on whether this char was valid or not for "what"
	
	//Get character code
	if(e && e.which){ //get event object reference and code property for each browser
		e = e;
		characterCode = e.which;
	} else {
		e = event
		characterCode = e.keyCode
	} 

	//Choose the character set and check if we need to do an ajax request
	var characters="";

	if (what=='NoWhitespace') {
		//Anything but a space
		//Return a value based on whether this was in the list, or we have exceeded the length
		if (String.fromCharCode(characterCode)==" " ||text.length>=textlength) {
			//Whitespace - don't allow
			return false;
		} else {
			//No whitespace
			return true;
		}
	} else {
		if (what=='chars' || what=='domain') {
			//Host Name
			characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-";
		} else if (what=='email') {
			//Email Address
			characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&'*+-/=?^_`{|}~.@";
		} else if (what=='AlphaNumeric') {
			//Alpha numeric
			characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
		} else if (what=='AlphaNumericStrict') {
			//Alpha numeric
			characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		} else if (what=='StrictUsername') {
			//Alpha numeric
			characters="abcdefghijklmnopqrstuvwxyz0123456789";
		} else if (what=='Phone') {
			//A mobile number
			characters="0123456789 ";
		} else if (what=='Number') {
			//A card number or CVV2 code - no spaces, or number of days
			characters="0123456789";
		} else if (what=='Float') {
			//A discount % - could be a float
			characters="0123456789.";
		} else if (what=='Date') {
			//A date
			characters="0123456789/";
		}
	
		//Return a value based on whether this was in the list, or we have exceeded the length
		if ((characters.indexOf(String.fromCharCode(characterCode))<0 && characters!="") || text.length>=textlength) {
			//Not found
			return false;
		} else {
			//Found
			return true;
		}
	}
}

/**
 * Toggle display of delivery address
 */
function toggleDeliveryDisplay() {
	//First, get the state of the tickbox
	if ($('#deliverySameAsBilling').attr('checked')) {
		//Make the delivery fields not required
		$('tr.delivery').removeClass('required');
		
		//Hide the delivery fields - it's the same
		$('tr.delivery').hide();
		
		
	} else {
		//Make the delivery fields required
		
		//Go through each field seeing if there is a delivery field for it
		for (i=0;i<originalRequired.length;i++) {
			var objField=$('#'+originalRequired[i]+"Delivery");	
			if (objField.length) {
				//This is a valid delivery field. Add the required class to it.
				objField.parent().parent().addClass('required');
			}
		}
						
		//Show the delivery fields
		$('tr.delivery').show();
	}
	
	//Work out the required fields because they have changed
	calculateRequiredFields();	

	//Update the pricing
	updatePricing();
	
}

/**
 * Submit an order
 *
 * @param string The payment method (currently 'paypal' or 'cheque')
 */
function submitOrder() {
	//Double-check that everything's filled in
	if (checkForm()) {
		//OK to submit the order - ask for confirmation
		
		if (confirm("By clicking Buy Now you are committing yourself to your purchase valued at £"+$('#grandTotal').html()+", whatever your payment method.\n\nDo you want to continue?")) {
		
			//Work out the payment method
			if ($('#paymentMethodPaypal').attr('checked')) {
				paymentMethod="paypal";
			} else {
				paymentMethod="cheque";
			}
	
			//First, we must place the order, putting it on hold
			placeOrder(paymentMethod);
		}		
	}
}

/**
 * Show/hide the payment buttons
 */
function togglePaymentButtons() {
	if ($('#acceptTerms').attr('checked') && $('#paypalAmount').val()>0) {
		//Enable them
 		$('.button').attr('disabled',false);
	} else {
		//Disable them	
 		$('.button').attr('disabled',true);
	}	
}

/**
 * Process the PayPal payment
 *
 * @param int The order ID
 * @param int The subtotal
 * @param int The carriage
 */
function processPayPalPayment(orderId,subTotal,carriage) {
	//So here we fill in the paypal form

	//Compose item name
	var itemName="";
	if ($('#bottleQuantity').val()) {
		itemName+=$('#bottleQuantity').val()+" x Fine Tip Glue Applicator With Pin";
	}
	if ($('#pinQuantity').val()) {
		if (itemName) itemName+=", ";
		itemName+=$('#pinQuantity').val()+" x Replacement Pin";
	}
	
	$('#paypalInvoice').val(orderId);
	$('#paypalShipping').val(carriage);
	$('#paypalCancel_return').val($('#baseWebsiteUrl').val()+"buy-now.html?cancel="+orderId+"&uniqueId="+$('#uniqueId').val());
	$('#paypalNotify_url').val($('#baseWebsiteUrl').val()+"ajax/NotifyPayment/orderId/"+orderId+"/");
	$('#paypalReturn').val($('#baseWebsiteUrl').val()+"Confirmation/orderId/"+orderId+"/");
	$('#paypalItem_name').val(itemName);	
	$('#paypalAmount').val(subTotal);
	$('#paypalAddress1').val($('#address1').val());
	$('#paypalAddress2').val($('#address2').val());
	$('#paypalCity').val($('#city').val());
	$('#paypalCounty').val($('#county').val());
	$('#paypalCountry').val($('#countryCode').val());
	$('#paypalFirst_name').val($('#firstName').val());
	$('#paypalLast_name').val($('#lastName').val());
	$('#paypalNight_phone_b').val($('#tel').val());
	$('#paypalZip').val($('#postcode').val());
// 	$('#paypalEmail').val($('#email').val());
	
	//Disable the submit buttons
	$('.button').attr('disabled',true);

	//Now it's populated, submit to paypal
  	$('#paypal').submit();
	
}

/**
 * Place the order via AJAX
 */
function placeOrder(paymentMethod) {
	//Compose order and send via ajax
	var order=new Object();
	order['bottleQuantity']=$('#bottleQuantity').val();
	order['pinQuantity']=$('#pinQuantity').val();
	order['title']=$('#title').val();
	order['firstName']=$('#firstName').val();
	order['lastName']=$('#lastName').val();
	order['address1']=$('#address1').val();
	order['address2']=$('#address2').val();
	order['city']=$('#city').val();
	order['county']=$('#county').val();
	order['postcode']=$('#postcode').val();
	order['countryCode']=$('#countryCode').val();
	order['tel']=$('#tel').val();
	order['email']=$('#email').val();
	order['deliverySameAsBilling']=$('#deliverySameAsBilling').attr('checked');
	order['titleDelivery']=$('#titleDelivery').val();
	order['firstNameDelivery']=$('#firstNameDelivery').val();
	order['lastNameDelivery']=$('#lastNameDelivery').val();
	order['address1Delivery']=$('#address1Delivery').val();
	order['address2Delivery']=$('#address2Delivery').val();
	order['cityDelivery']=$('#cityDelivery').val();
	order['countyDelivery']=$('#countyDelivery').val();
	order['postcodeDelivery']=$('#postcodeDelivery').val();
	order['countryCodeDelivery']=$('#countryCodeDelivery').val();
	order['notes']=$('#notes').val();
	order['acceptTerms']=$('#acceptTerms').attr('checked');
	order['uniqueId']=$('#uniqueId').val();
	order['paymentMethod']=paymentMethod;
	order['orderSourceId']=$('#orderSourceId').val();
	
	//Send it
	$.post("/ajax/Order/", order,
		  function(data){
		    //This is run when the order post is returned
		    var dataItems=data.split("|",6);
		    var orderId=parseInt(dataItems[0]);
		    var subTotal=parseFloat(dataItems[1]);
		    var carriage=parseFloat(dataItems[2]);
		    var paypalSupplement=parseFloat(dataItems[3]);
		    var paypalTotal=0;
		    if (paymentMethod=='paypal') paypalTotal=paypalSupplement;
		    
		    var total=parseFloat(dataItems[4]);
		    var errorMessage=dataItems[5];
		   
		    //Check out the totals
		    var test1=Math.round((subTotal+carriage+paypalTotal)*100);
		    var test2=Math.round(total*100);
		  
		    //	-- uncomment next line for testing --
// 		    alert("SubTotal: "+subTotal+" Carriage: "+carriage+" Paypal: "+paypalSupplement+" Total: "+total);
  
		    //Did we get a valid order id?
		    if (!orderId) {
					alert("A problem occurred with your order. The error message was:\n"+errorMessage);
					return;
				}

	    	//Are they paying for it now?
				if (paymentMethod=='paypal') {
					//If the payment method is PayPal, we need to let paypal handle the payment side of things
					processPayPalPayment(orderId,Math.round((subTotal*100)+(paypalSupplement*100))/100,carriage);
				} else {
					//Generate a return page
 					document.location.href=$('#baseWebsiteUrl').val()+"Confirmation/orderId/"+orderId+"/";
				}
		   
	  });

	
}

/**
 * Check the form is filled in correctly
 */
function checkForm() {
	//Iterate through the list of elements finding if they are filled in
	var missing=new Array();
	
	for (i=0;i<required.length;i++) {
		objField=$('#'+required[i]);
		if (objField.attr('type')=='text') {
			if (!$.trim(objField.val())) {
				missing.push(required[i]);
			}
		} else if (objField.attr('type')=='checkbox') {
			if (!objField.attr('checked')) {
				missing.push(required[i]);
			}
		} else if (objField.attr('type')=='select-one') {
			if (!objField.val()) {
				missing.push(required[i]);
			}	
		}
	}

	//Have we got missing fields?
	if (missing.length) {
		//Now warn the user that he must complete the fields
		var message="You must complete the following fields:\n\n";
		for (i=0;i<missing.length;i++) {
			//Find the field name
			message+=" - ";
			if (missing[i].match("Delivery")) message+="Delivery ";
			message+=$('#'+missing[i]+"Label").html()+"\n";
		}
		alert(message);
		return false;	
	} else {
		//Fine
		return true;
	}
}

/**
 * Work out the required fields
 *
 * @param bool Also set the original save fields
 */
function calculateRequiredFields(saveOriginal) {
	var formFields=$('#details input');
	
	//Iterate through them, see if they are required
	required=new Array();
	for (i=0; i<formFields.length; i++) {
		if ($(formFields[i]).parent().parent().hasClass('required')) {
			required.push($(formFields[i]).attr("id"));
			if (saveOriginal) originalRequired.push($(formFields[i]).attr("id"));
		}
	}
	required.push("orderSourceId");
	if (saveOriginal) originalRequired.push("orderSourceId");

}


/**
 * Show the country change options on the basket summary
 *
 * @return bool False to stop the link from firing
 */
function showCountryChange() {
	//Hide the static stuff and show the editable stuff
	$('#staticCountry').hide();
	$('#editableCountry').show();
	return false;
}

/**
 * Cancel a country change
 *
 * @return bool False to stop the link from firing
 */
function cancelCountryChange() {
	//Hide the editable stuff and show the static stuff
	$('#editableCountry').hide();
	$('#staticCountry').show();
	return false;
}

/**
 * Update the delivery country from the top link
 *
 * @return bool False to stop the link from firing
 */
function updateCountry() {
	if($('#deliverySameAsBilling').attr('checked')) {
		//Update the first country and the second
		$('#countryCode').val($('#countryCodeChange').val());
		$('#countryCodeDelivery').val($('#countryCodeChange').val());
	} else {
		//Update the second
		$('#countryCodeDelivery').val($('#countryCodeChange').val());
	}

	//Update the pricing
	updatePricing();
	
	return false;
}

