/* ####################################################################
							 Global Variables
#################################################################### */

var cartFull         	 = false;  // Shopping Cart Status
var zone	     	 = 5;	   // Postal / VAT Zone
var country	     	 = 0;	   // Country Code
var discount	     	 = 0;	   // Value of any discount
var discountUsed     	 = false;  // Discount Status
var discountProcessed 	 = false;  // Discount Processed Status, True Once the Discount has been added to PayPal
var promoCode	      	 = "0000"; // Promo Code from Form
var totalPostage         = 0;	   // Total Postage Value of order
var maxUKPostage     	 = 8.00;   // Max Value of Postage to UK Address
var maxWorldPostage  	 = 12.00;  // Max Value of World Postage Address, e.g. NOT UK
var UKPostageHandling 	 = 3.00;   // UK Postage Handling Charge, only charged once per orders
var WorldPostageHandling = 2.50;   // World Postage Handling Charge, only charged once per orders
var xmlhttp;			   // Holds the XML over HTTP Object to call the Server PHP

/* ####################################################################
 Responds to 'Add to Cart' Buttons
 Note: Custom Field - "country:UK,Goods:£50,Handling??
#################################################################### */

function addItem (userItemName,userItemNumber,userItemPrice,userItemWeight)
{
	if (zone == 5)
	{
	alert ("Please Select Your Country!");
	}
	else
	{
		
		var paypalString;          			// where to build the PayPal string

		var winpar = "width=600,height=400,scrollbars,location,resizable,status";
		var paypalUrl = "https://www.paypal.com/cgi-bin/webscr" + "?cmd=_cart";
		var business = "&business=sales%40modelrailwayelectronics.com";

		var addToCart	= "&add=1";
		var quantity	= "&quantity=1";
		var itemName	= "&item_name=" + escape (userItemName);
		var itemNumber  = "&item_number=" + escape (userItemNumber);
		var itemPrice	= "&amount=" + formatPrice(userItemPrice);
		var backColour	= "&cs=1";
		var imageUrl	= "&image_url=http%3a//www.modelrailwayelectronics.com/images/logo.gif";
		var currencyCode = "&currency_code=GBP";
		var returnUrl	= "&return=http%3a//www.modelrailwayelectronics.com/order/success.htm";
		var cancelUrl	= "&cancel_return=http%3a//www.modelrailwayelectronics.com/order/cancel.htm";
		var handling	= "&handling=" + formatPrice(0.00);
		var discountUrl = "&discount_amount=" + discount;
			

// ########################Europe (Non-EU)#############################

		cartFull = true;
		switch (zone)
		{

// ########################Zone1 (Rest of World)#######################

		case "1" :

			if (totalPostage == 0)	
			{
				var taxRate  = "&tax=0.00";
				var handlingCart = "&handling_cart=" + formatPrice(WorldPostageHandling);
				var shipSingle  = "&shipping=" + formatPrice(userItemWeight);
				var shipExtra  = "&shipping2=" + formatPrice(userItemWeight);
				totalPostage = WorldPostageHandling;
				totalPostage = totalPostage + userItemWeight;
			}
			else
			{
				if (totalPostage < maxWorldPostage)
				{
					totalPostage = totalPostage + userItemWeight;
					if(totalPostage > maxWorldPostage)
					{
						var cut = totalPostage - maxWorldPostage;
						userItemWeight = (userItemWeight) - cut;
					}
					var taxRate  = "&tax=0.00";
					var handlingCart = "&handling_cart=" + formatPrice(WorldPostageHandling);
					var shipSingle  = "&shipping=" + formatPrice(userItemWeight);
					var shipExtra  = "&shipping2=" + formatPrice(userItemWeight);	
				}
				else
				{
					var taxRate  = "&tax=0.00";
					var handlingCart = "&handling_cart=" + formatPrice(WorldPostageHandling);
					var shipSingle  = "&shipping=0.00";
					var shipExtra  = "&shipping2=0.00";
					
				}
			}
			break;

// ########################(Zone 3) United Kingdom##############################

		case "3" :

			if (totalPostage == 0)	
			{
				var taxRate  = "&tax=0.00";
				var handlingCart = "&handling_cart=" + formatPrice(UKPostageHandling);
				var shipSingle  = "&shipping=" + formatPrice(userItemWeight);
				var shipExtra  = "&shipping2=" + formatPrice(userItemWeight);
				totalPostage = UKPostageHandling;
				totalPostage = totalPostage + userItemWeight;
			}
			else
			{
				if (totalPostage < maxUKPostage)
				{
					totalPostage = totalPostage + userItemWeight;
					if(totalPostage > maxUKPostage)
					{
						var cut = totalPostage - maxUKPostage;
						userItemWeight = userItemWeight - cut;
					}
					var taxRate  = "&tax=0.00";
					var handlingCart = "&handling_cart=" + formatPrice(UKPostageHandling);
					var shipSingle  = "&shipping=" + formatPrice(userItemWeight);
					var shipExtra  = "&shipping2=" + formatPrice(userItemWeight);	
				}
				else
				{
					var taxRate  = "&tax=0.00";
					var handlingCart = "&handling_cart=" + formatPrice(UKPostageHandling);
					var shipSingle  = "&shipping=0.00";
					var shipExtra  = "&shipping2=0.00";
					
				}
			}
			break;
		}

// ########################Call Paypal#################################

	paypalString = paypalUrl + addToCart + business + quantity +
						itemName + itemPrice + taxRate + currencyCode + itemNumber +
						imageUrl + backColour + handlingCart +
						shipSingle + shipExtra + returnUrl + cancelUrl + discountUrl;

	if(discountUsed == true)
	{
		if((discount != 0) && (discountProcessed == false))
		{
			discount = 0;
			discountProcessed = true;
		}
	}

	window.open (paypalString, "paypal", winpar);
	}
}

/* ####################################################################
							View the PayPal shopping cart (Alan)
Note: 	All Paypal Global Variables must be Initalised Already!
#################################################################### */

function CallViewCart ()
{
	var paypalString;          			// where to build the PayPal string
	var winpar = "width=600,height=400,scrollbars,location,resizable,status";
	var paypalUrl = "https://www.paypal.com/cgi-bin/webscr" + "?cmd=_cart";
	var displayCart = "&display=1";
	var business = "&business=sales%40modelrailwayelectronics.com";
	var imageUrl = "&image_url=http%3a//www.modelrailwayelectroincs.com/Images/logo.gif";
	var backColour = "&cs=1";

	paypalString = paypalUrl + displayCart + imageUrl + backColour + business;
	window.open (paypalString, "paypal", winpar);
}

/* ####################################################################
							Format Price/Cost -> x.xx
#################################################################### */

function formatPrice (inputPrice)
{
	var outputPrice = "0.00";

	outputPrice = escape (inputPrice * 1.0 + 0.005); 	// add and put back to string
	outputPrice = outputPrice.substring (0, outputPrice.indexOf (".") + 3);
														// lop off extra
	return outputPrice;											// Returns Formatted String
}


/* ####################################################################
							Responds to Select Country
	Note: 0 - Europe (Non EU)
			1 - Zone1 (Americas, Middle East, India, SE Asia, Hong Kong)
			2 - Zone2 (Rest of World)
			3 - UK (United Kingdom and Northern Ireland)
			4 - Europe (EU Excluding UK)
			5 - None Zone Selected!
#################################################################### */

function SelCountry (temp)
{
	if (cartFull == true)
	{
		document.frmCountry.lstSelCountry[country].selected = true;
		alert ("Cannot Change Country while order is in progress!" +
		"\n If you need to change your country Please Clear the" +
		"\n Cart and restart your order.");
	}
	else
	{
		zone = temp.value; 					// Set 'zone' to 'temp'
		country = temp.index;
	}
}

/* ####################################################################
	Validate Discount Code
	Note: 	All Paypal Global Variables must be Initalised Already!
#################################################################### */

function GetXmlHttpObject()
{
	if (window.XMLHttpRequest)
  	{
  		// code for IE7+, Firefox, Chrome, Opera, Safari
  		return new XMLHttpRequest();
  	}
	
	if (window.ActiveXObject)
  	{
  		// code for IE6, IE5
		return new ActiveXObject("Microsoft.XMLHTTP");
  	}
	return null;
}


function loadXMLDoc(temp)
{
	var promoCode = temp.value;
	var url="/sysbin/validatediscount.php?discount_code=" + promoCode;
	delete xmlhttp;
	xmlhttp=GetXmlHttpObject();
	if (xmlhttp==null)
  	{
  		alert ("Your browser does not support XMLHTTP!");
  		return;
  	}
	xmlhttp.onreadystatechange=stateChanged;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}

function stateChanged()
{
	if (xmlhttp.readyState==4)
  	{
  		if (xmlhttp.status==200)
    		{
			var position = xmlhttp.responseText.indexOf("Discount_Code=");
			if(position !=-1)
			{
				position = position + 14;
				var length = position + 13;
				code_check = xmlhttp.responseText.substring(position, length);
			}

			position = xmlhttp.responseText.indexOf("Server_Time=");
			if(position !=-1)
			{
				position = position + 12;
				length = position + 8;
				server_time = xmlhttp.responseText.substring(position, length);
			}

			position = xmlhttp.responseText.indexOf("Valid=");
			if(position !=-1)
			{
				position = position + 6;
				length = position + 4;
				valid = xmlhttp.responseText.substring(position, length);
			}

			position = xmlhttp.responseText.indexOf("Value=");
			if(position !=-1)
			{
				position = position + 6;
				length = position + 5;
				value = xmlhttp.responseText.substring(position, length);
			}

			if(valid=="TRUE")
			{
				discount = value;
				discountUsed = true;
				discountProcessed = false;
				alert("Discount Code Accepted");
			}
			else
			{
				alert("Error Unknown Discount Code");				
			}
    		}
  		else
    		{
    			alert("Problem retrieving XML data:" + xmlhttp.statusText);
    		}
  	}
}


