// 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.15;

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 FOR UK ONLY - needs multiplying 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;
	}
	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;
//		alert(myproducts);
//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);
//					alert('product '+myproducts[i] + ' quantity ' + myquantities[i]);
					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 products.js
	var querystring = ct_readCookie();
	var targetURL = target_page+'?'+ querystring;
checkout=window.open(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;
	setVAT(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 setcountryindex(index){
	saveCookie('countryindex',index)
}

function chargeVAT(){
	saveCookie('ct_VAT','true');
}

function unchargeVAT() {
	saveCookie('ct_VAT', 'false')
}

function getVATstatus(){
	var chargeVAT = readCookie('ct_VAT');
	if (chargeVAT == 'true') {return true} else {return false}
}

function setVAT(mycountry, myindex){
//writes VAT cookie according to EC status of country string, and countryindex cookie by myindex 
//	var mycountry = optionbox.options[index].text;
//	alert(index);
//	alert(mycountry);
//	alert('country='+mycountry + '  index=' + myindex);
	setcountryindex(myindex);
	var local_VAT = false;
	var old_VAT = getVATstatus();
	var ECCountries = new Array('Austria','Belgium', 'Cyprus', 'Denmark','Estonia','Finland','France','Germany','Greece','Hungary','Ireland','Italy','Latvia','Lithuania','Luxembourg','Malta','Netherlands','Portugal','Spain','Sweden','UK', 'Czech Republic', 'Slovak Republic', 'Slovenia','Poland', 'Romania', 'Bulgaria');
//		alert('!'+mycountry+'!');

	for (var i=0; i<ECCountries.length ;i++ ){
		if (ECCountries[i] == mycountry) {
		local_VAT=true}
	}
	if (local_VAT) {chargeVAT()} else {unchargeVAT()};
//	if (local_VAT != old_VAT){
//		location=location //reload
//	}
}



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


function testbutton() {
//creates fake shopping trolley contents
	var number_of_products = '4';
	var products;
	products = '|wm_01^2|wm_03^8|bm_01^16|lm_01^1';
	ct_saveCookie(number_of_products + products);
}

function product_alert(){

	var myproducts = ct_fill_product_array();
	alert(myproducts);
}

function quantity_alert(){

	var myquantities = ct_fill_quantity_array();
	alert(myquantities);
}

function numitems_alert() {
	var my_numitems = ct_get_number_of_products();
	alert(my_numitems);
}


function ct_read_cookie_alert(){
	var contents = ct_readCookie();
	alert(contents);

}

function test_writingfromarrays () {
	var myproducts = ct_fill_product_array();
	var myquantities = ct_fill_quantity_array();
	ct_write_cookie_from_arrays(myproducts,myquantities);
}

function test_ct_buy_button(code,quantity){
	ct_buy_button(code, quantity);

}

function test_showdoccookie(){
	var mycookie=document.cookie;
	alert(mycookie);
}

function show_total(){
	var a=get_total();
	alert('Total is £' + currencystring(a));
}

