////////////////////////////////////////////////////
// DO NOT EDIT THIS FILE, EDIT DEF FILES THEN
// RUN http://www.sitename.com/turboshop/basket.php
// and save over this file
////////////////////////////////////////////////////
var giftIsSet = 0;

/**
 *	Constructor
 */
function Basket() {
 	this.cart = 'cart';
	this.lastitem = '';
	this.islastchange = true;
	this.amountBasket = 'total'; // *** name of the cookie for the amount of the basket
	this.info = ""; //";path=/another/";
	this.currencySymbol = (this.GetCookieVal('symbol')=='') ?  '£' : this.GetCookieVal('symbol');
   	this.multibuy = true;
		this.giftskew = 'giftskew';
};

/**
 *	a item is one element separated by 'cart=id|skew|price|qty#'  skew,skew,...
 *	@param itemid
 *	@param itemprice
 *	@itemskew list of the options separated by &
 *	@param qty quantity
 */
//php.cart.function.AddItem($prcd,$art, $num, $skew, $price,$extraInfo='',$gift=-1,$trigger='',$discountMessage='',$reduction=0) {

Basket.prototype.AddItem = function(Itemprcd,Item,Itemprice,Itemqty,Form)
{
	if (giftIsSet==1)
	{
		redirectPage('index.php?f=baskcode.php&addededgift=1');
		return true;
	}
 	if(!this.CheckQuantity(Itemqty,Form)) return false;
 	this.lastitem = Itemqty + ' * ';
 	var discountMessage = '';
 	var reduction = '';
 	var reductiontype = '';
 	var gift = 0;
 	var giftvalue = '';
 	var s= '';
 	var mult = '';
 	var reductionstring = '';
 	var desc = '';

 	if(Form.gift!=null)
	{
	  gift = Form.gift.value;
	}
/*
	if(Form.gifttrigger!=null)
	{
	  giftvalue = Form.gifttrigger.value;
	}
*/


   if(Form.itemdesc!=null)
	{
	  desc = escape(Form.itemdesc.value);
	}


	if(Form.disctext!=null)
	{
	  discountMessage = escape(Form.disctext.value);
	}

   if ((Form.discscheme!=null) && (Form.discscheme.value!='')) //record discount owner and link
   {
    var arr = Form.discscheme.value.split('#'); //{discaoff}#{disctype}#{discowner}#{disclink}
    reductionstring = arr[2]+':'+arr[3];
    //next params can be used to do javascript discounting.
    reductiontype = arr[1];
    reduction = parseFloat(arr[0]);
   }

  	if ((Form.multibuy!=null) && (Form.multibuy.value != '#'))
   {
          var mults = Form.multibuy.value.split('#');
          mult = mults[2];
   }

	if(Form.from!=null && Form.from.value=='amend')
	{

		if (this.SetAmountBasket(Itemprice,Itemqty,Form)==false) return (false)

		if(this.Check(Item+"|"+Itemprice)) // item is ever in the basket
 		{
 			this.UpdateItem(Itemprcd,Item,Itemprice,Itemqty,Form);
		}
		else
		{	// new item
			items = this.GetCookieVal(this.cart);
			if(items!="") items+='#';
			items += Item + "|" + Itemprice + "|" + Itemqty + '|' + Itemprcd + '|'+gift+'|'+giftvalue+'|'+discountMessage+'|'+reductionstring+'|'+mult+'|'+desc;
                     SetCookie( this.cart , items + this.info, '', CookiePath(), CookieDomain(), 0);
		}

window.location.href='index.php?f=baskcode.php&from=amend&pointer='+Form.pointer.value;


}
else
{
        if(!confirm('Add to basket?')) {
         this.islastchange = false;
         return false;
        }
if (this.SetAmountBasket(Itemprice,Itemqty,Form)==false) return false;

 	// test to know if the product exists ever
 	// Reading cookie

 	if(this.Check(Item+"|"+Itemprice)) // item is ever in the basket
 	{
 		this.UpdateItem(Itemprcd,Item,Itemprice,Itemqty,Form);
	}
	else
	{	// new item
		 items = this.GetCookieVal(this.cart);
		 if(items!="") items+="#";
		 items += Item + "|" + Itemprice + "|" + Itemqty + '|' + Itemprcd + '|'+gift+'|'+giftvalue+'|'+discountMessage+'|'+reductionstring+'|'+mult+'|'+desc;
		 SetCookie( this.cart , items + this.info, '', CookiePath(), CookieDomain(), 0);
	}
//alert(document.cookie);
  this.setgift(Form);
  return  true;
}
};

/**
 *	Pops up message to inform user they have triggered a promotion
 *	@param oItemprice - full item cost
 *	@param Form - item form
 */

var shownpromotions = 0; //global prom switch to stop alert poping up more than once!

function DiscountCostTotal(oTotalPrice, Form)
{
   var reduction = 0.00;
   //discounts can not be displyed as discount may depend on other items in the server cart the client cart (this) cannot read!
   return reduction;
/*	old prom calc code draft ... may need later
	var multinfo = '';
 	var reductiontype = '';
 	var dTotalPrice = 0.00;
 	dTotalPrice = parseFloat(oTotalPrice);
   if(Form.disctype!=null) reductiontype = Form.disctype.value;
   // to do ********** do calc **************
   if(Form.discaoff!=null) reduction = parseFloat(Form.discaoff.value);

   if ((Form.multibuy!=null) && (Form.multibuy.value != ''))
   {
     multinfo = Form.multibuy.value;
     if (multinfo[1])
     return reduction;
   }

   if ((reductiontype != '') && (reduction > 0))
   {
     if(reductiontype=='£')
	  {
					dTotalPrice = this.TSRound(oTotalPrice-reduction, 2);
	  }
	  else if(reductiontype=='@')
	  {
		 			dTotalPrice = this.TSRound(reduction, 2);
	  }
	  else
	  {
	  				dTotalPrice = this.TSRound(oTotalPrice*(100-reduction)/100, 2);
     }
     reduction = this.TSRound(parseInt(oTotalPrice) - dTotalPrice, 2);
   }
   return reduction;*/
}

/**
 *	@param offset: name of the variable in the cookie
 *	@result : the value of the variable in the cookie
 *	@date 12/01/00
 *	@author Olivier Ricard
 */
Basket.prototype.GetCookieVal = function (offset)
{
	offset = offset + "=";
	var posstr=document.cookie.indexOf (offset);
	if (posstr==-1) 	return "";
	var endstr = document.cookie.indexOf(";",posstr);
	if(endstr==-1) endstr=document.cookie.length;
	return unescape(document.cookie.substring(posstr+offset.length, endstr));
};

Basket.prototype.Check = function(Art)
{
	elements = this.GetCookieVal(this.cart);

	items = elements.split("#");
	for(var i=0;i<items.length;i++)
	{
		if(Art==items[i].substring(0,items[i].lastIndexOf("|")))
		{
			return true;
		}
	}
	return false;
};


// @param Item
// @param Qty : quantity
Basket.prototype.UpdateItem = function(Itemprcd,Item, Price, Qty,Form) {
	var buffer="";
	cartContent = this.GetCookieVal(this.cart);
	items = cartContent.split("#");
	for(var i=0;i<items.length;i++)
	{
		pos = items[i].indexOf("|");
		pos = items[i].indexOf("|",pos+1);
		if(items[i].substring(0,pos)==Item) {
  			posq = items[i].substring(items[i].lastIndexOf("|")+1);
  			if(Form.from!=null){
  				if(Form.from.value=="amend"){
					qty = parseInt(Qty);  // New quantity
  				}else {
  					qty = parseInt(posq)+parseInt(Qty);  // New quantity
  				}
  			}else{
  				qty = parseInt(posq)+parseInt(Qty);  // New quantity
  			}
			items[i]= items[i].substring(0,pos) + "|" + Price + "|" + qty + '|' + Itemprcd;
		}
		buffer += items[i] + "#";
	}
	buffer = buffer.substring(0,buffer.length -1);
	SetCookie( this.cart , buffer, '', CookiePath(), CookieDomain(), 0);
};

// Give the last product
// Not used still
// To customize with the name of the html file
// Id : 0 <=> Added
// Id : 1 <=> Deleted
// Id : 2 <=> Amended
Basket.prototype.LastChange = function(Itemdesc,Id) {
	if(this.islastchange==false) return false;
	parent.lastItemChanged = this.lastitem + Itemdesc;
	if(typeof Id == "undefined") Id=0;
	switch(Id){
		case 0: parent.lastItemChanged += " added";		break;
		case 1: parent.lastItemChanged += " removed";		break;
		case 2: parent.lastItemChanged += " updated";		break;
		case 3: parent.lastItemChanged  = " Empty Basket";	break;
		default:parent.lastItemChanged  = "";			break;
	}

	return true;
};

// Check if the quantity if qty>0
// Customize with the name of the frames
Basket.prototype.CheckQuantity = function(Qty,Form) {
	if(Qty>0 && isNaN(Qty)==false) {
		this.islastchange = true;
		return true;
	}
	this.islastchange = false;
	alert("Sorry, you must enter a positive quantity!");
	Form.qty.value = 1;
	Form.unitcost.value  = Form.unitcost.defaultValue;
	Form.totalcost.value  = Form.totalcost.defaultValue;
	if (isNaN(Form.totalcost.value.charAt(0)))
	{
		Form.total.value  = Form.totalcost.value;
	}
	else
	{
		Form.total.value  = this.currencySymbol + Form.totalcost.value;
	}
	return false;
};

Basket.prototype.Reset = function () {
// this function will be assured by the server
	return;
};

Basket.prototype.Destroy = function () {
	return;
};


// Used in the checkout template for the amend  and the removal
// To Modify
Basket.prototype.LastChangeCheckout = function (Form,Obj) {
	pos=Obj.name.indexOf("_");
	if( pos!= -1){
		buton   = Obj.name.substring(0,pos);
		pointer = Obj.name.substring(pos+1);
		for(var i=0;i<Form.length;i++) {
			if("qnty_"+ pointer == Form.elements[i].name) k=i;
			if("itemdesc_"+ pointer == Form.elements[i].name) j=i;
		}
		if(Form.elements[k].value>0 && isNaN(Form.elements[k].value)==false){
			itemdesc = Form.elements[k].value;
			itemdesc += "" + Form.elements[j].value;	//desc
			if(pointer!="" && buton=="remove") 	this.LastChange(itemdesc,1);
			if(pointer!="" && buton=="update") 	this.LastChange(itemdesc,2);
		} else {
			if(Form.elements[k].value==0) {		// *** We remove the item
				itemdesc = Form.elements[k].value;
				if(pointer!="" && buton=="update") 	this.LastChange(itemdesc,1);
			} else {
				Form.elements[k].value = Form.elements[k].defaultValue;
				return false;
			}
		}
	} else {
		buton = Obj.name;
		if(buton =="reset")   			this.LastChange("",3);
	}
	return true;
};

/**
 *	This function returns the basket total including discount if the promtions module is on
 */
Basket.prototype.BasketAmount = function()
{
	var cookieamount = this.GetCookieVal(this.amountBasket);
   if (cookieamount == '') cookieamount = '0.00|0.00';
   var arr = cookieamount.split('|');
   return arr[0];

};

/**
 *	This function returns the basket total without any disounts
 */
Basket.prototype.BasketAmountWithNoDiscounts = function()
{
	var cookieamount = this.GetCookieVal(this.amountBasket);
   if (cookieamount == '') cookieamount = '0.00|0.00';
   var arr = cookieamount.split('|');
   return arr[1];
};


/**
 *	This function is called just when we want to amend the basket. the customer comes from 'checkout'
 *  and these values are only needed by the php script - this func is not needed!
 */
Basket.prototype.Mode = function (pointer) {
	//document.cookie = "from=amend;pointer=";  <-- creates error
	return true;
};

Basket.prototype.SetAmountBasket = function (cost,quantity,form) {
   var amount = this.BasketAmount();
   var amountWithoutDiscounts = this.BasketAmountWithNoDiscounts();

	   if(form.from!=null)
	  {
 			if(form.from.value=='amend')
 			{
 				prevQty = form.qty.defaultValue;
 				form.qty.defaultValue = quantity;
 				quantity = quantity-prevQty;
 				if(isNaN(quantity)) quantity=0;
 			}
 		}
 		if(amount=='') amount = 0;

 		amount = parseFloat(amount,2) + cost*quantity ;

 		amount = this.TSRound(amount,2);
 		if (amount>100000) {
 			alert('Sorry this product can be added as your order will be over £100000.00.\n\nPlease remove some items.\n');
 			return false;
 		}

		SetCookie( this.amountBasket , parseFloat(amount,2) + '|' + amountWithoutDiscounts+ this.info, '', CookiePath(), CookieDomain(), 0);

	this.RefreshBasket();
   return true;
};

Basket.prototype.RefreshBasket = function()
{

   var amount = this.BasketAmount();

	var agt=navigator.userAgent.toLowerCase();
	var plat=navigator.platform.toLowerCase();
	var IE   = (agt.indexOf('ie')!=-1);
	var ver = navigator.appVersion.toLowerCase();

	if(IE==true) {
		// In all IE browsers version 4+ the document.all object was added to the DOM
		// This appplies to both MAC and Windows versions.
		document.all.basket_text.value = this.GetCurrency(amount);
	} else {
		// If only netscape was so simple
		// MAC verions of Netscape and versions 4.7 and below on Windows require a reference to the layers array
		// Whereas windows versions since 4.7 can reference the form object directly
		//old version ->> document.layers['top'].document.forms['basket_status'].basket_text.value = this.GetCurrency(amount);
		document.forms['basket_status'].basket_text.value = this.GetCurrency(amount);
	}
};

 	Basket.prototype.TSRound = function(numbr,dec) {
   //new code below 28/08/01 3:54PM pad.
	var str= String(numbr);
	var jj = 0;
	var newstr='';
	var alist = str.split('.');

	if (alist.length > 1)
	{
	    newstr=alist[0];
	    var s=alist[1];
	    if (s.length > dec) {//round off to nearest penny
	      var dp1  = parseInt(s.substr(0,dec));
	      var dp2 = parseInt(s.substr(dec,1));

	      if (dp2 > 5) {
	       if (dp1 < 99) {
	        jj = dp1+1;
	        s = jj;
	        }
	        else { //carry one
	         jj = parseInt(newstr)+1;
	         newstr = jj;
	         s = '00';
	         }
	      } else s = dp1;
	    }

	    if (s.length == 1) s = s+'0';
	    newstr += '.'+s;
	} else newstr = str + '.00';
	return newstr;
};

Basket.prototype.GetCurrency = function (nb) {
	var s = '' + nb;
	pos = s.indexOf('.');
	if(pos==-1) pos=s.length;
	int1 = s.substr(0,pos);
	if(int1=='') int1=0;
	dec1 = s.substr(pos+1,2);
	if(dec1=='') dec1='00';
	if(dec1!='' && dec1.length == 1) dec1 = dec1 + '0';
	result = int1 + '.' + dec1;
	return this.currencySymbol + result;
};

Basket.prototype.setgift = function (form) {

   if ((form.gift.value=='1') || (form.gift.value==1))
   {
     giftIsSet = 1;
     redirectPage('index.php?f=baskcode.php&addededgift=1');
     return 1;
   }

	if ((form.hasgift != 'undefined') && (form.hasgift.value!='#'))
	{
		var info = new Array();
		var prcd = form.itemprcd.value;

		info = form.hasgift.value.split('#');
		if ((info[1]!='') && (info[0]!=''))
		{
			if ((info[1] == 'addtobasket') || (info[1] == 'displaybasket'))
			{
			   if (info[2]!='')
			   {
			     if (info[1] != 'displaybasket')
			     {
			        if (confirm('You are eligible for a free gift. Would you like this added to your bag')==false) return true;
			     }
			   	var discountMessage = escape(info[4]);
				 	var reduction = '';
				 	var reductiontype = '';
 					var mult = '';
 					var reductionstring = '';
 					var desc = escape(info[3]);
			   	var gift = 1;
     				var giftvalue = prcd;
     				var items = this.GetCookieVal(this.cart);
		         if(items!="") items+="#";
	  				items += info[2] + "||" + '0.00' + "|" + 1 + '|' + info[0] + '|'+gift+'|'+giftvalue+'|'+discountMessage+'|'+reductionstring+'|'+mult+'|'+desc;
	  				//cart cookie layout  #pointer 0| sku 1|cost 2| qty 3 | prcd 4 | is gift 5 | trigger 6 | disc message 7 | reduction 8 | multibuy info 9 | item desc
	  				SetCookie( this.cart , items + this.info, '', CookiePath(), CookieDomain(), 0);

				 if (info[1] == 'displaybasket')
				 {
				 	redirectPage('index.php?f=baskcode.php&addededgift=1');
				 	return true;
				 }
			   }
			}
			else
			{
				if(info[1]==1)
				{
					redirectPage('index.php?f=itemdetl.php&p='+info[0]+'&gift=1&trigger='+prcd);
				}
				else
				{
					redirectPage('baskcode.php');
				}
			}
		}
}
		return true;
};


/**
 *	Location redirect on 1 millsec timer - fixes unknown bug with using window.location within basket class
 *	@param string href to redrect from site root
 *	@param Form - item form
 */
function redirectPage(href)
{
 setTimeout("exitNow('"+href+"')", 1);
}

function exitNow(href)
{
 window.location.href = href;// = ''+href;
 return 1;
}

//get decimal numbers from a sting
function getNumber(s)
{
	var str = '';
	var c = '';
	for(var i=0; i<s.length; i++)
	{
		c = s.substr(i, 1);
		if ((isNaN(c)==false) || (c=='.')) str += c;
	}
	if (str=='') str = '0.00';
	return str;
}