// Different sections of code in this file have different copyright status
// Parts of this file are Copyright (C) 1999 Dan Steinman
// Available at http://www.dansteinman.com/dynapi/
// thanks to: Jesee Chisholm <JCHISHOLM@SENSORMATIC-VPD.com>
//Other copyrights noted where appropriate
//Anything not clearly marked otherwise is copyright (c) Creative Technology 2000.  All rights are reserved.
//This file manages with the hard-coded cookie called ct_basket, which has the format
// number_of_items | item_ordercode ^ quantity | item_ordercode ^ quantity (etc)

var vat_rate = 0.175;

function saveCookie(name,value) {
//	very crude - permanent cookie - use only for browser, VAT and country status
		var date = new Date();
		date.setHours(date.getHours()+1);
		//expires in 1 hour
		var expires = "; expires="+date.toGMTString();
 	document.cookie = name+"="+value+expires+"; path=/"
}

function readCookie(name) {
	var nameEQ = name + "="
	var ca = document.cookie.split(';')
	for(var i=0;i<ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length)
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length)
	}
	return null
}

//This section © 1998, Infohiway, Inc
// formats a number to two digits - not really a cookie feature but has to go in somewhere!
function currencystring(num) {
 string = "" + num;
 if (string.indexOf('.') == -1)
  return string + '.00';
 seperation = string.length - string.indexOf('.');
 if (seperation > 3)
  return string.substring(0,string.length-seperation+3);
 else if (seperation == 2)
  return string + '0';
 return string;
}
//end Infohighway bit


//------core cookie routines----------------------

function ct_saveCookie(value) {
		var date = new Date();
		date.setHours(date.getHours()+1);
		//expires in 1 hour
		var expires = "; expires="+date.toGMTString();
		var path = "; path=/";
	if (ExistCookie('ct_basket'))
	{ct_deleteCookie()
	}
		document.cookie = "ct_basket="+value+expires+path;
}

function ct_deleteCookie() {
//	This deletes the hard-coded ct_basket cookie
 var date = new Date();
 		date.setHours(date.getHours()-1);
//		var expires = "; expires="+date.toGMTString();
		//		webmonkey expires routine
		var expires="; expires=Fri, 13-Apr-1970 00:00:00 GMT";
		var path = "; path=/"
        document.cookie = "ct_basket=" + ";" + expires+path;
}



function ct_readCookie() {
//used by the three routines which get the number of products, and codes and quantities for each product
	var nameEQ = "ct_basket=";
	var ca = document.cookie.split(";")
	for(var i=0;i<ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length)
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length)
	}
//	alert("no ct_basket cookie");
	return null
}

function ShowAllCookies() {
	if (document.cookie == "") {
		document.write("There are no cookies here")
	}
	else {
		thisCookie = document.cookie.split("; ")
		for (i=0; i<thisCookie.length; i++) {
		document.write("Cookie name is '"+thisCookie[i].split("=")[0])
		document.write("', and the value is '"+thisCookie[i].split("=")[1]+"'<br>")
		}
	}
}

//ExistCookie function moved to common.js to facilitate browser check

//--------Shopping basket routines----------------

function ct_get_number_of_products() {
	var mycookie = ct_readCookie();
	var mycontents = mycookie.split('|');
//	alert(mycontents);
	return parseInt(mycontents[0]);
}

function ct_fill_product_array() {
	var my_temp_array;
		var mycontents = ct_readCookie().split('|');
		var number_of_products = ct_get_number_of_products();
		my_product_array = new Array(number_of_products+1);//item[0] is blank
		for (var i=1;i<(number_of_products+1) ; i++)	{
			my_temp_array = mycontents[i].split('^');
			my_product_array[i] = my_temp_array[0];
		}
		return my_product_array;
}

function ct_fill_quantity_array() {
	var my_temp_array;

		var mycontents = ct_readCookie().split('|');
		var number_of_products = ct_get_number_of_products();
		my_quantity_array = new Array(number_of_products+1);//item[0] is blank
		for (var i=1;i<(number_of_products+1) ; i++)	{
			my_temp_array = mycontents[i].split('^');
			my_quantity_array[i] = my_temp_array[1];
		}
		return my_quantity_array;
}

function ct_write_cookie_from_arrays(product_array, quantity_array) {
	var cookiestring = parseInt(product_array.length) - 1;//number of items is first item in string
	for (var i=1;i< product_array.length ;i++)
	{cookiestring += '|' + product_array[i] + '^' + quantity_array[i] 
	}
	ct_saveCookie(cookiestring);
}


//----These routines cross-reference order codes to pricelist data in products.js

function BasketItem(OrderCode,Description,Price, Shipping){
//Constructor for BasketItems - one per line of basket display
	this.OrderCode = OrderCode;
	this.Description = Description;
	this.Price = Price;
	this.Shipping = Shipping;
}

function ct_get_basket_item(order_code){
//returns a BasketItem according to order code provided.
	var i=1;
	while (ProductList[i].OrderCode != order_code) i++;
	myproduct = new BasketItem(ProductList[i].OrderCode,ProductList[i].Description,ProductList[i].Price,ProductList[i].Shipping);
	return myproduct
}

function get_total() {
//Returns total value of product order (ex VAT & carriage)
	var myproducts = ct_fill_product_array();
	var myquantities = ct_fill_quantity_array();
	var numitems = ct_get_number_of_products()
	var total = 0;
	for (var i=1;i<=numitems; i++) {
		myitem = ct_get_basket_item(myproducts[i]);
		total = total + (myquantities[i] * myitem.Price);
	}
	return total
}


function get_shipping() {
//Returns total shipping multiplied by shipping overseas factors in 
	var myproducts = ct_fill_product_array();
	var myquantities = ct_fill_quantity_array();
	var numitems = ct_get_number_of_products()
	var total = 0;
	for (var i=1;i<=numitems; i++) {
		myitem = ct_get_basket_item(myproducts[i]);
		total = total + (myquantities[i] * myitem.Shipping);
	}
	return total * get_shipping_factor() //factors in Products.js, code in design.js
}

function get_VAT() {
	if (getVATstatus()){
		thisVAT = (get_total() + get_shipping()) * vat_rate; //VAT rate at top of this file
	}
	else {(thisVAT=0)}
	return thisVAT
}

function get_grand_total() {
	var grandtotal = get_total() + get_shipping() + get_VAT();
	return grandtotal
}

function ct_delete_button(itemnumberthing){
	var myproducts = ct_fill_product_array();		//fill arrays with existing basket info
	var myquantities = ct_fill_quantity_array();
	var itemnumber = parseInt(itemnumberthing);
	for (var i=itemnumber;i < myproducts.length ;i++) //now move down each item above the one to be deleted
		{	myproducts[i] = myproducts[i+1];
			myquantities[i] = myquantities[i+1];
		}
	myproducts.length = myproducts.length - 1;  //truncate the size of the arrays
	myquantities.length = myquantities.length - 1;
	if (myproducts.length == 1) {
		alert('That was the last item in your basket');
		ct_deleteCookie(); //if deleted item was last in basket, delete cookie
		}
		else {
			ct_write_cookie_from_arrays(myproducts, myquantities);//finally write the cookie and refresh the page
		}
	alert ('Item Deleted');
//	window.location.reload();
	location=location
}

function ct_buy_button(order_code, quantity){
	if (ct_readCookie() == null) {					//If no cookie yet
		ct_saveCookie(0);							//set a bodge cookie with value 0
		}
		var myproducts = ct_fill_product_array();		//fill arrays with existing basket info
		var myquantities = ct_fill_quantity_array();
		var num_products = ct_get_number_of_products();
		var added = false;
//If basket already contains item code, increment its quantity...
		for (var i=0;i<myproducts.length;i++) {//
			if (myproducts[i] == order_code) {
					myquantities[i] = parseInt(myquantities[i]) + parseInt(quantity);
					added = true
				}
			}	
//Else add new item
		if (!added)	{
			var newindex = num_products + 1;
			myproducts[newindex] = order_code;				//add new product info
			myquantities[newindex] = quantity;
		}
		ct_write_cookie_from_arrays(myproducts, myquantities); //and write the cookie back again
		alert('Item added to basket - thankyou!');
}

//function checkout() {
//	var target_page = order_form;//URL of secure order form - stored in design.js
//	var querystring = ct_readCookie();
//	var targetURL = target_page+'?'+ querystring;
//checkout=window.open(targetURL);
//}
function checkout() {
	var target_page = order_form;//URL of secure order form - stored in design.js
	var querystring = ct_readCookie();
	var targetURL = target_page+'?'+ querystring;
//checkout=window.open(targetURL);
	window.location=targetURL;
}

//-------Secure server side stuff-----------------

function checkin() {
//interprets querystring, converts back to secure server's own cookie, sets default country & VAT, redirects to checkout page
	var querystring = window.location.search;
	querystring = querystring.substr(1); //strip leading ?
	ct_saveCookie(querystring);				//and save to a local cookie
	var countryindex = defaultcountryindex;//default country set in design.js
	var countryvalue = defaultcountryvalue;
	setcountrycookies(countryvalue,countryindex);
	location = "checkout.htm"; //and refresh the display
}

function getcountryindex(){
	var myindex = defaultcountryindex;//set in design.js
	if (ExistCookie('countryindex'))
	{myindex = readCookie('countryindex');
//	alert('country ' + myindex + ' from cookie');
	}
	else {
//	alert('country ' + myindex + 'from default');
	}
return myindex;
}




function setcountrycookies(mycountry, myindex){
//called onchange by country list, sets cookies for country index and name, read by get_shipping_factor() &  getVATstatus() below
	saveCookie('countryindex',myindex);
	saveCookie('countryname',mycountry);
}


function getVATstatus(){//returns true if countryname cookie is in EC list
	var chargeVAT = false;
	var mycountry = readCookie('countryname');
	var ECCountries = new Array('Austria','Belgium','Denmark','Finland','France','Germany','Greece','Ireland','Italy','Luxembourg','Netherlands','Portugal','Spain','Sweden','UK');

	for (var i=0; i<ECCountries.length ;i++ ){
		if (ECCountries[i] == mycountry) {
		chargeVAT=true}
		}
	return chargeVAT;

}

function get_shipping_factor(){
			var shipping_factor=0;
			//reads the countryindex cookie, which defaults to defaultcountryindex
			mycountry=getcountryindex();
			if (mycountry == 0){ //shouldn't ever be 0
				alert('Error - cannot calculate shipping factor - no country cookie');
				return 0
			}
			else {
				if (mycountry==195){shipping_factor = 1;}//UK
				else {
					if (getVATstatus()){shipping_factor=shipping_ec;}//Other EC countries - cheat by using VAT routine
					else {
						if (mycountry==198 || mycountry==37){shipping_factor=shipping_us}//USA or Canada
						else {
							if (mycountry==101 || mycountry==12 || mycountry==139){shipping_factor=shipping_aus} //Australia, NZ, Japan
							else {shipping_factor = shipping_other}
							 }
						  }
					 }
			    }
		return shipping_factor
}




//-----testing stuff - remove before release --------------------

