/**
* Shop JavaScript lib
* Product element handlers and client basket class
*
* @copyright turboShop copyright Digivate Limited 2000-2006
**/
var g_ProductsList = new Array();
var g_OutOfStockMessage = 'Out Of Stock';
var g_UserMadeAchange = false;

/**
* New client basket 05/2006
* only ported over add and update element so far
* Must have SHOP_USE_NEW_COOKIE_CART defined and set to 1 in sitconf
**/
function tsClientBasket() {
 	this.cart = 'cart';
	this.amountBasket = 'total'; // *** name of the cookie for the amount of the basket
	this.currencySymbol = (this.GetCookieVal('symbol')=='') ?  '£' : this.GetCookieVal('symbol');
	this.mode = 'add'; // one of add or amend
};

/**
 *	add an item to the client for pickup by the server
 *	@param itemprcd
 *	@param SKU
 *	@param qty quantity
 */
tsClientBasket.prototype.AddItem = function(Itemprcd,SKU, Itemqty){
 	if(this.mode =='amend')
	{
		if(this.Check(Itemprcd)) // item is ever in the basket
 		{
 			this.UpdateItem(Itemprcd,SKU,Itemqty);
		}
		else
		{	// new item
			items = this.GetCookieVal(this.cart);
			if(items!="") items+='#';
			items += Itemprcd + "|" + SKU + "|" + Itemqty;

			SetCookie( this.cart , items + this.info, '', CookiePath(), CookieDomain(), 0);
		}
	}
	else
	{
	 	// test to know if the product exists ever
	 	// Reading cookie
	 	if(this.Check(Itemprcd)) // item is ever in the basket
	 	{
	 		this.UpdateItem(Itemprcd,SKU,Itemqty);
		}
		else
		{	// new item
			 var items = this.GetCookieVal(this.cart);
			 if(items!="") items+="#";
			 items += Itemprcd + "|" + SKU + "|" + Itemqty;

			 SetCookie( this.cart , items, '', CookiePath(), CookieDomain(), 0);
		}
	}
};


/**
 *	@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
 */
tsClientBasket.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));
};

tsClientBasket.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].indexOf("|")))
		{
			return true;
		}
	}
	return false;
};


// @param Item
// @param Qty : quantity
tsClientBasket.prototype.UpdateItem = function(Itemprcd,SKU, Qty) {
	var buffer="";
	cartContent = this.GetCookieVal(this.cart);
	var 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)==Itemprcd)
		{
  			posq = items[i].substring(items[i].lastIndexOf("|")+1);


  			if(this.mode=="amend"){
				qty = parseInt(Qty);  // New quantity
  			} else {
  				qty = parseInt(posq)+parseInt(Qty);  // Add to existing quantity
  			}

			items[i]= Itemprcd + "|" + SKU + "|" + qty;
		}
		buffer += items[i] + "#";
	}
	buffer = buffer.substring(0,buffer.length -1);

	SetCookie( this.cart , buffer, '', CookiePath(), CookieDomain(), 0);
};




/**
* Shop module product element handlers
* Created: 06/05/2006
**/

function getItemsIdFromName(id){
	var parts = id.split('_');
	return parts[1];
}

function tsUpdateTotalBox(id){
	var itemId = getItemsIdFromName(id);
	var qty = 1;

	if (tsGetElementById('productqty_'+itemId)!=null)
	{
		if (tsGetElementById('productqty_'+itemId).value!='')
		{
			qty = parseInt(tsGetElementById('productqty_'+itemId).value);
		}
		else
		{
			//tsGetElementById('productqty_'+itemId).value = 1;
		}
	}

	/*if (qty<1)
	{
		tsGetElementById('productqty_'+itemId).value = 1;
		qty = 1;
	}*/

	if (tsGetElementById('productunitprice_'+itemId)!=null)
	{
		if (tsGetElementById('producttotal_'+itemId)!=null)
		{
			var unitprice = parseFloat(tsGetElementById('productunitprice_'+itemId).innerHTML);
			var total = unitprice*qty;
			tsGetElementById('producttotal_'+itemId).innerHTML = ts4NumberFormat(total);
		}
	}


}


function getSelectedItemSkus(itemId)
{
	var skus = '';
	var selindx = -1;

	for(var i=0; i<9; i++)
	{
		if (tsGetElementById('options_'+itemId+'_option'+i)!=null)
		{
			selindx = tsGetElementById('options_'+itemId+'_option'+i).selectedIndex;
			if (selindx>-1)
			{
				skus += tsGetElementById('options_'+itemId+'_option'+i).options[selindx].value;
			}
		}
		else if (tsGetElementById('chck'+i+'Value')!=null)
		{
			skus += '_'+tsGetElementById('chck'+i+'Value').value;
		}
	}


	return skus;
}

function tsUpdateUnitPriceBox(id)
{
	var itemId = getItemsIdFromName(id);

	var skus = getSelectedItemSkus(itemId);

	if (tsGetElementById('productunitprice_'+itemId)!=null)
	{

		if (g_ProductsList && g_ProductsList['_'+itemId+skus]!=null)
		{
			var cost = getExtraCost()+parseFloat(g_ProductsList['_'+itemId+skus]['Price']);
			tsGetElementById('productunitprice_'+itemId).innerHTML = ''+ts4NumberFormat(cost)+'';
		}
	}

	tsUpdateTotalBox(id);
}

function tsUpdateStockStatus(id)
{
	var itemId = getItemsIdFromName(id);
	//var skus = '';
	var skus = getSelectedItemSkus(itemId);
	var selindx = -1;

	/*for(var i=0; i<9; i++)
	{
		if (tsGetElementById('options_'+itemId+'_option'+i)!=null)
		{
			selindx = tsGetElementById('options_'+itemId+'_option'+i).selectedIndex;
			if (selindx>-1)
			{
				skus += tsGetElementById('options_'+itemId+'_option'+i).options[selindx].value;
			}
		}
	}*/

	//alert(skus);

	if (tsGetElementById('stockstatus_'+itemId)!=null)
	{

		if (g_ProductsList && g_ProductsList['_'+itemId+skus]!=null)
		{
			tsGetElementById('stockstatus_'+itemId).innerHTML = g_ProductsList['_'+itemId+skus]['Stock Message'];
		}
		else
		{
			if  (g_OutOfStockMessage!='')
			{
				tsGetElementById('stockstatus_'+itemId).innerHTML = g_OutOfStockMessage;
			}
			else
			{
				tsGetElementById('stockstatus_'+itemId).innerHTML = 'Out Of Stock';
			}
		}

		onStockUpdated(tsGetElementById('stockstatus_'+itemId).innerHTML);
	}

	tsUpdateUnitPriceBox(id);
}


function tsQntyPlus(id, min)
{
	var itemId = getItemsIdFromName(id);



	var qtyboxId = 'productqty_'+itemId;


	if (tsGetElementById(qtyboxId)!=null)
	{
		if (tsGetElementById(qtyboxId).value=='')
		{
			tsGetElementById(qtyboxId).value = 1;
		}
		var q = parseInt(tsGetElementById(qtyboxId).value);
		if (q=='NaN')
		{
			q = min;
		}
		else
		{
			q = q+1;
			if (q>9999) q = 9999;
		}

		tsGetElementById(qtyboxId).value = q;

		g_UserMadeAchange = true;

		tsUpdateTotalBox(id);
	}
}

function tsQntyMinus(id, min)
{
	var itemId = getItemsIdFromName(id);
	var qtyboxId = 'productqty_'+itemId;

	if (tsGetElementById(qtyboxId)!=null)
	{
		if (tsGetElementById(qtyboxId).value=='')
		{
			tsGetElementById(qtyboxId).value = 1;
		}

		var q = parseInt(tsGetElementById(qtyboxId).value);
		if (q=='NaN')
		{
			q = min;
		}
		else
		{
			q = q-1;
			if (q<min) q = min;
		}

		tsGetElementById(qtyboxId).value = q;

		g_UserMadeAchange = true;
		tsUpdateTotalBox(id);
	}
}


function tsUpdateStockHandler(e)
{
	var theTarget = tsGetEventRecordTarget(e);

	tsUpdateStockStatus(theTarget.name);
}


function tsGetQty(itemId)
{
	var qty = 1;
	var qtyboxId = 'productqty_'+itemId;

	if (tsGetElementById(qtyboxId)!=null)
	{
		if (tsGetElementById(qtyboxId).value=='')
		{
			tsGetElementById(qtyboxId).value = 1;
		}
		qty= parseInt(tsGetElementById(qtyboxId).value);
		if (qty<0) qty=0;
	}

	return qty;
}

function tsAddItem(itemId, popupText, stayOnPage)
{
	var skus = '';
	var prcd = '';
	var qty = tsGetQty(itemId);
	var itemSKU = getSelectedItemSkus(itemId);
	var sm = '';

	if (g_ProductsList !=null && g_ProductsList['_'+itemId+itemSKU]!=null)
	{
		prcd = g_ProductsList['_'+itemId+itemSKU]['Product Code'];
		skus = g_ProductsList['_'+itemId+itemSKU]['SKU'];
		sm = g_ProductsList['_'+itemId+itemSKU]['Stock Message'];
	}

	if (!onBeforeAddItem(prcd, skus, sm, qty))
	{
		return;
	}

	if (prcd=='')
	{
		alert('Build Error: Cannot locate items product code in tsAdditem');
	}
	else
	{
		if (popupText!='')
		{
			alert(popupText);
		}

		if (stayOnPage)
		{
			var basket = new tsClientBasket();
			if (itemSKU!='' && prcd.indexOf(itemSKU)>-1)
			{
				itemSKU = '';
			}
			basket.AddItem(prcd, itemSKU, qty);
		}
		else //add to basket using global b turboShop parameter
		{
			var href = 'index.php?b='+escape(prcd)+'&qty='+qty;

			if (skus!='')
			{
				href += '&sku='+skus;
			}

			var httproot = ''
			if (rootdir!=null) httproot = rootdir;

			var extras = extraBasketInfo();
			if (extras!='' && extras.substr(0,1)!='&') extras = '&'+extras;

			document.location.href = httproot+href+extras;
		}
	}
}

function tsConfrimAddItem(itemId, popupText, stayOnPage)
{
	if (confirm(popupText)==true)
	{
		tsAddItem(itemId, '', stayOnPage)
	}
}

function tsAddItemReload(itemId)
{
	var skus = '';
	var prcd = '';
	var qty = tsGetQty(itemId);
	var itemSKU = getSelectedItemSkus(itemId);
	var sm = '';

	if (g_ProductsList !=null && g_ProductsList['_'+itemId+itemSKU]!=null)
	{
		prcd = g_ProductsList['_'+itemId+itemSKU]['Product Code'];
		skus = g_ProductsList['_'+itemId+itemSKU]['SKU'];
		sm = g_ProductsList['_'+itemId+itemSKU]['Stock Message'];
	}

	if (!onBeforeAddItem(prcd, skus, sm, qty))
	{

		return;
	}

	if (prcd=='')
	{
		alert('Build Error: Cannot locate items product code in tsAdditem');
	}
	else
	{

		var href = 'index.php?ssm=basket&act=add&prcd='+escape(prcd)+'&qty='+qty;

		if (skus!='')
		{
			href += '&sku='+skus;
		}

		var httproot = ''
		if (rootdir!=null) httproot = rootdir;

		var extras = extraBasketInfo();
		if (extras!='' && extras.substr(0,1)!='&') extras = '&'+extras;
		var nocacheDate = new Date()

		document.location.href = httproot+href+extras+'&redirect='+escape('p='+escape(prcd)+'&nocache='+
			escape(nocacheDate.getTime()));

	}
}




/**
* Update costs using unitcost from product array and an custom costs via getExtraCost
* @param string id name with product random code
**/
function tsUpdateItem(id)
{
	g_UserMadeAchange = true;
	tsUpdateUnitPriceBox(id);
}


/**
* Amend item in servers cart
* @param string id - the product random code
**/
function tsAmendItem(itemId, pointer, from)
{
	var skus = '';
	var prcd = '';
	var qty = tsGetQty(itemId);
	var itemSKU = getSelectedItemSkus(itemId);
	var sm = '';

	if (g_ProductsList !=null && g_ProductsList['_'+itemId+itemSKU]!=null)
	{
		prcd = g_ProductsList['_'+itemId+itemSKU]['Product Code'];
		skus = g_ProductsList['_'+itemId+itemSKU]['SKU'];
		sm = g_ProductsList['_'+itemId+itemSKU]['Stock Message'];
	}

	if (!onBeforeAmendItem(prcd, skus, sm, qty))
	{
		return;
	}

	if (prcd=='')
	{
		alert('Build Error: Cannot locate items product code in tsAmendItem');
	}
	else
	{
		var href = 'index.php?ssm=basket&act=amend&prcd='+prcd+'&qty='+qty+'&pointer='+pointer+'&returnto='+escape(from);

		if (skus!='')
		{
			href += '&sku='+skus;
		}

		var httproot = ''
		if (rootdir!=null) httproot = rootdir;

		var extras = extraBasketInfo();
		if (extras!='' && extras.substr(0,1)!='&') extras = '&'+extras;

		document.location.href = httproot+href+extras;

	}
}

function tsPlusButtonHandler(e)
{
	var theTarget = tsGetEventRecordTarget(e);
	var min = 1;

	if (tsGetElementById(theTarget.id+'_min')!=null)
	{
		min = parseInt(tsGetElementById(theTarget.id+'_min').value);
	}
	tsQntyPlus(theTarget.id, min);

}

function tsMinusButtonHandler(e)
{

	var theTarget = tsGetEventRecordTarget(e);
	var min = 1;

	if (tsGetElementById(theTarget.id+'_min')!=null)
	{
		min = parseInt(tsGetElementById(theTarget.id+'_min').value);
	}

	tsQntyMinus(theTarget.id, min);
}

function tsQtyDropdownChange(e)
{
	var theTarget = tsGetEventRecordTarget(e);
	var index = theTarget.selectedIndex;
	var qty = 1;

	if (index>-1)
	{
		qty = theTarget.options[index].value;
	}

	var itemId = getItemsIdFromName(theTarget.id);
	var qtyboxId = 'productqty_'+itemId;

	if (tsGetElementById(qtyboxId)!=null)
	{
		tsGetElementById(qtyboxId).value = qty;
	}

	g_UserMadeAchange = true;
	tsUpdateTotalBox(qtyboxId);
}

function tsUpdateTotalHandler(e)
{
	var theTarget = tsGetEventRecordTarget(e);
	var min = 1;
	tsUpdateTotalBox(theTarget.id);
}

////////////////////////////////////////////////////////////////////////////////////
// Custom methods to override is custom-shop.js if required
//
// Besure shop.js is is called before custon-shop.js
/////


/**
* Should redefine in custom-shop.js to override
* @return void - not used
**/
function onStockUpdated(newmessage)
{

}

/**
* must return true or false.  If false the item will not be added to the basket
* Use to check stock message and return false if out of stock
*
* Should redefine in custom-shop.js to override for custom actions
* @return boolean
**/
function onBeforeAddItem(prcd, sku, stockMessage, qty)
{

	return true;
}

/**
* must return true or false.  If false the item will not be amended and
* the user will remian on the current page
*
* Should redefine in custom-shop.js to override for custom actions
* @return boolean
**/
function onBeforeAmendItem(prcd, sku, stockMessage, qty)
{

	return true;
}

/**
* Allows extra url parameters to be sent to basket when b= is called by
* tsAddItem.  These can then be processed by overridiing the TBasketSubmodule
* message_additem method in a child class.
*
* Should redefine in custom-shop.js to override
* @return string
**/
function extraBasketInfo()
{
	return '';
}

/**
* Allows you to add extra costs to unitcost total.  Called when item is update via call to tsUpdateItem or one
* of the standard components are called (i.e qty box)
*
* Should redefine in custom-shop.js to override
* @return float
**/
function getExtraCost()
{
	return 0.00;
}


