/******************************************************************************
* eshoputils.js                                                               *
* -------------                                                               *
*                                                                             *
* UTILITY FUNCTIONS FOR COOKIES AND SHOP ITEMS                                *
*                                                                             *
*******************************************************************************
*                                                                             *
* Copyright 2000-2002 Isotools, all right reserved                            *
*                                                                             *
******************************************************************************/

///////////////////////////////////////////////////////////////////////////////
// 
// COOKIE BASIC FUNCTIONS
//
function setCookie(CookieName, value, expires)
{
	document.cookie = CookieName + "=" + value + "; expires=" + expires.toGMTString() +  "; path=/";
}

function getCookie(CookieName)
{
	var search;
	search = CookieName + "=";
	offset = document.cookie.indexOf(search);
	if (offset != -1)
	{
		offset += search.length;
		end = document.cookie.indexOf(";", offset);
		if (end == -1)
			end = document.cookie.length;
		return document.cookie.substring(offset, end);
	}
	else
	{
		return "";
	}
}

function deleteCookie(CookieName)
{
	//cookieString=getCookie(CookieName);
	var exp = new Date();
	exp.setTime(exp.getTime() + (86400 * 1000 * 30));
	setCookie(CookieName,"", new Date(), exp);
}

function areCookiesEnabled()
{
	if (document.all) // if IE
	{
		if (window.navigator.cookieEnabled)
			return true;
	}
	else
	{
		var strTest = "#this is a test to know if cookie are enabled#";
		var exp = new Date();
		exp.setTime(exp.getTime() + (86400 * 1000 * 30));
		setCookie("testCookieEnabled",strTest,exp);
		var cookieTest = getCookie("testCookieEnabled");
		if (strTest == cookieTest)
			return true;
	}
	return false
}
//
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//
// UTILS FUNCTIONS
//
function isEmpty(s)
{   
	return ((s == null) || (s.length == 0));
}

function isNum(num)
{
	for (var i=0; i<num.length; i++)
	{
		var caractere = num.substring(i,i+1);
		if(caractere < "0" || caractere > "9")
		{
			return false;
		}
	}
	return true;
}

function round(Num)
{
	strNum = "" + Num;
	
	// round if needed
	if (strNum.indexOf('.') >= 0)
	{
		var parts = strNum.split('.');			
		
		var rightPart = parts[1];
		if (rightPart.length > 2)
		{
			strNum ="" + Math.round(Num*100)/100;
			
			if (strNum.indexOf('.') < 0)
			{
				strNum += ".00";
			}
			else
			{
				parts = strNum.split('.');			
				
				rightPart = parts[1];
				if (rightPart.length == 1)
					strNum += "0";
			}
		}
		else if (rightPart.length == 1)
			strNum += "0";
	}
	else
		strNum += ".00";

	return(strNum)
}

function replace (str, oldsubstr, newsubstr)
{
	newStr = new String(str);

	//var strRegExp = oldsubstr.replace(/[.?\\[\]*$+^(){}]/g, "\\$&");
	//var regExp = new RegExp(strRegExp, "g")
	//var newStr = str.replace(regExp, newsubstr);
	var regExp1 = new RegExp("[.?\\\\[\\]*$+^(){}]", "g");
	var strRegExp = oldsubstr.replace(regExp1, "\\$&");
	
	var regExp2 = new RegExp(strRegExp, "g");
	var strRes = newStr.replace(regExp2, newsubstr);
	
	return strRes;
}

function getPriceTTC(price, duty)
{
	var nPrice = parseFloat(price);
	var nDuty = parseFloat(duty);

	if ( isNaN(nPrice) || isNaN(nDuty))
		return -1;
	else
		return( nPrice*(1+(nDuty/100)) );
}

function getPriceHT(price, duty)
{
	var nPrice = parseFloat(price);
	var nDuty = parseFloat(duty);

	if ( isNaN(nPrice) || isNaN(nDuty))
		return -1;
	else
		return( nPrice/(1+(nDuty/100)) );
}

function getCounterValue(price, counterValueRate)
{
	var nPrice = parseFloat(price);
	var nCounterValueRate = parseFloat(counterValueRate);

	if ( isNaN(nPrice) || isNaN(nCounterValueRate))
		return -1;
	else
		return( nPrice*nCounterValueRate );
}

function applyReductions(price, reduction)
{
	var nPrice = parseFloat(price);
	var reductions = reduction.split("%");
	
	if ( isNaN(nPrice) )
		return -1;
	else
	{
		var i;
		for (i=reductions.length-1 ; i>=0 ; i--)
		{
			var nReduc = parseFloat(reductions[i]);
			if ( isNaN(nReduc) )
				continue;
			nPrice = nPrice*(1-(nReduc/100));
		}
		return nPrice;
	}
}

var SHIPPING_DUTY_AMOUNT            = 0;
var DUTY_AMOUNT                 	= 0;
var TOTAL                           = 0;
var TOTAL_TTC                      	= 0;
var TOTAL_HT                        = 0;
var SHIPPINGCOST_AMOUNT				= 0;
var TOTAL_TO_PAY                 	= 0;
var SHIPPINGTOTAL_HT				= 0;
var SHIPPINGTOTAL_TTC				= 0;


function calculateTotal(items, cookieName)
{
	SHIPPING_DUTY_AMOUNT = 0;
	DUTY_AMOUNT			 = 0;
	TOTAL				 = 0;
	TOTAL_TTC			 = 0;
	TOTAL_HT			 = 0;
	SHIPPINGCOST_AMOUNT	 = 0;
	TOTAL_TO_PAY		 = 0;
	SHIPPINGTOTAL_HT	 = 0;
	SHIPPINGTOTAL_TTC	 = 0;

	var debugString = "";
	
	// CALC TOTAL DUTY AMOUNT;
	var i;
	for(i=0; i<items.length; i++)
	{
		var item = items[i];
		var price = parseFloat(item.quantity)*parseFloat(round(item.getUnitPrice(priceMode)));
		TOTAL += parseFloat(price);
		if (priceMode == "HT")
		{
			DUTY_AMOUNT += parseFloat(parseFloat(getPriceTTC(price, item.duty)) - parseFloat(price));
		}
		else
		{
			DUTY_AMOUNT += parseFloat(parseFloat(price) - parseFloat(getPriceHT(price, item.duty)));
		}
	}
	DUTY_AMOUNT = round(DUTY_AMOUNT);
	// CALC TOTAL TTC AND TOTAL HT
	if ( (priceDisplay == "HT") && (priceMode == "HT") )
	{
		TOTAL_HT = round(TOTAL);
		TOTAL_TTC = round(parseFloat(TOTAL) + parseFloat(DUTY_AMOUNT));
	}
	else if ( (priceDisplay == "HT") && (priceMode == "TTC") )
	{
		TOTAL_HT = round(parseFloat(TOTAL) - parseFloat(DUTY_AMOUNT));
		TOTAL_TTC = round(TOTAL);
	}
	else if ( (priceDisplay == "TTC") && (priceMode == "TTC") )
	{
		TOTAL_TTC = round(TOTAL);
	}
	else if ( (priceDisplay == "TTC") && (priceMode == "HT") )
	{
		TOTAL_TTC = round(parseFloat(TOTAL) + parseFloat(DUTY_AMOUNT));
	}
	
	// CALC SHIPPINGCOSTS AMOUNT
	var shippingCostCookieName = cookieName + "DeliveryArea";
	var currentArea = getCookie(shippingCostCookieName);
	if (currentArea == "" && shippingCosts.length >= 1)
		setShippingCosts(shippingCostCookieName, shippingCosts[0].zone, false);
	
	if (shippingCosts.length > 1)
	{
		for(i=0; i<shippingCosts.length ; i++)
		{
			var shippingCostOption = shippingCosts[i];
			var nFreeBeyond = parseFloat(shippingCostOption.freeBeyond);

			if (currentArea == unescape(shippingCostOption.zone))
			{
				if ( !isNaN(nFreeBeyond) && nFreeBeyond > 0)
				{
					if ( parseFloat(TOTAL_TTC) < parseFloat(shippingCostOption.freeBeyond) )
						SHIPPINGCOST_AMOUNT = round(shippingCostOption.amount);
				}
				else
					SHIPPINGCOST_AMOUNT = round(shippingCostOption.amount);
			}
		}
	}
	else if (shippingCosts.length == 1)
	{
		var nFreeBeyond = parseFloat(shippingCosts[0].freeBeyond);
		
		if ( !isNaN(nFreeBeyond) && nFreeBeyond > 0)
		{
			if ( parseFloat(TOTAL_TTC) < parseFloat(shippingCosts[0].freeBeyond) )
				SHIPPINGCOST_AMOUNT = round(shippingCosts[0].amount);
		}
		else
			SHIPPINGCOST_AMOUNT = round(shippingCosts[0].amount);
	}
	if (priceMode == "HT") {
		SHIPPING_DUTY_AMOUNT = round(parseFloat(SHIPPINGCOST_AMOUNT) * shippingDuty * 0.01);
	} else {
		SHIPPING_DUTY_AMOUNT = round(parseFloat(SHIPPINGCOST_AMOUNT)*(1.0 - 1.0 / (1.0 + shippingDuty* 0.01)));		
	}
	// CALC TOTAL TTC AND TOTAL HT
	if ( (priceDisplay == "HT") && (priceMode == "HT") )
	{
		SHIPPINGTOTAL_HT = round(SHIPPINGCOST_AMOUNT);
		SHIPPINGTOTAL_TTC = round(parseFloat(SHIPPINGCOST_AMOUNT) + parseFloat(SHIPPING_DUTY_AMOUNT));
	}
	else if ( (priceDisplay == "HT") && (priceMode == "TTC") )
	{
		SHIPPINGTOTAL_HT = round(parseFloat(SHIPPINGCOST_AMOUNT) - parseFloat(SHIPPING_DUTY_AMOUNT));
		SHIPPINGTOTAL_TTC = round(SHIPPINGCOST_AMOUNT);
		SHIPPINGCOST_AMOUNT = SHIPPINGTOTAL_HT;
	}
	else if ( (priceDisplay == "TTC") && (priceMode == "TTC") )
	{
		SHIPPINGTOTAL_TTC = round(SHIPPINGCOST_AMOUNT);
	}
	else if ( (priceDisplay == "TTC") && (priceMode == "HT") )
	{
		SHIPPINGTOTAL_TTC = round(parseFloat(SHIPPINGCOST_AMOUNT) + parseFloat(SHIPPING_DUTY_AMOUNT));
		SHIPPINGCOST_AMOUNT = SHIPPINGTOTAL_TTC;
	}



	// TOTAL TO PAY
	TOTAL_TO_PAY = round(parseFloat(TOTAL_TTC) + parseFloat(SHIPPINGTOTAL_TTC));

	return debugString;
}
//
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//
// ITEM COOKIE FUNCTIONS
//
function isItemSet (itemID, cookieName)
{
	var cookie = getCookie(cookieName);
	var items = cookie.split('#');
	
	var i = 0;
	while (i < items.length)
	{
		var tmp = items[i].split('$');
		if (tmp[1] == escape(itemID) )
			return true;
		
		i++;
	}
	return false;
}

function changeItemOptionValue(cookieName, itemID, optionName, valueName, bReload)
{
	optionName = unescape(optionName);
	valueName = unescape(valueName);

	var cookie = getCookie(cookieName);
	var tmpCook = '';
	var items = cookie.split('#');
	var i = 0;
	while(i < items.length)
	{
		var tmp = items[i].split('$');
		if (( tmp[1] != escape(itemID)) )
			tmpCook += items[i]+'#';
		else
		{
			var item = new ShopItem();
			item.makeFromCookieString(items[i]);
			var j;
			for(j=0 ; j<item.options.length ; j++)
			{
				var option = item.options[j];
				if (option.name == optionName)
				{
					if (option.bMultiSel == true)
					{
						var k;
						for (k=0 ; k<option.values.length ; k++)
						{
							var value = option.values[k];
							if (value.name == valueName)
								value.selected = !value.selected;
						}
					}
					else
					{
						var k;
						for (k=0 ; k<option.values.length ; k++)
						{
							var value = option.values[k];
							if (value.name == valueName)
								value.selected = true;
							else if (value.selected == true)
								value.selected = false;
						}
					}
				}
			}
			tmpCook += item.dumpCookieString();
		}
		i++;
	}
	
	var exp = new Date();
	exp.setTime(exp.getTime() + (86400 * 1000 * 30));
	setCookie(cookieName,tmpCook, exp);
	
	if (bReload == true)
		window.location.reload();
}

function changeItemQuantity (cookieName, itemID, newQuantity, bReload)
{
	if (isNaN(parseInt(newQuantity)))
	{
		alert(thesaurus.shop_numberOnly);
		return;
	}

	var cookie = getCookie(cookieName);

	var tmpCook = '';
	var items = cookie.split('#');
	var i = 0;
	while(i < items.length)
	{
		if (items[i] != "") 
		{
			var tmp = items[i].split('$');
			
			if ( (tmp[1] != escape(itemID)) )
			{
				tmpCook += (items[i] + "#");
			}
			else
			{
				if (parseInt(newQuantity) > 0)
				{
					var item = new ShopItem();
					item.makeFromCookieString(items[i]);
					item.quantity = parseInt(newQuantity);
					tmpCook += item.dumpCookieString();
				}
			}
		}
		i++;
	}

	var exp = new Date();
	exp.setTime(exp.getTime() + (86400 * 1000 * 30));
	setCookie(cookieName,tmpCook, exp);
	
	if (bReload == true)
		window.location.reload();
}

function deleteItem (itemName, itemID, cookieName, bReload)
{
	var confirmDelete = thesaurus.shop_confirmDelete1 + itemName + thesaurus.shop_confirmDelete2;
	if ( confirm(confirmDelete) )
	{
		var cookie = getCookie(cookieName);
		var tmpCook = '';
		var items = cookie.split('#');
		var i = 0;
		while(i < items.length)
		{
			var tmp = items[i].split('$');
			if ( (tmp[1] != escape(itemID))  )
				tmpCook += items[i]+'#';
		
			i++;
		}
		var exp = new Date();
		exp.setTime(exp.getTime() + (86400 * 1000 * 30));
		setCookie(cookieName,tmpCook, exp);
		
		if (bReload == true)
			window.location.reload();
	}
}

function addItem(cookieName, item)
{
	//test if cookie option is enable
	if (areCookiesEnabled())
	{
		if ( isItemSet(item.id ,cookieName) )
			alert(thesaurus.shop_alreadyHere);
		else
		{
			var cookie = getCookie(cookieName);
			var cookieString = item.dumpCookieString();
			cookie += cookieString;
			var exp = new Date();
			exp.setTime(exp.getTime() + (86400 * 1000 * 30));
			setCookie(cookieName,cookie,exp);
			alert(thesaurus.shop_itemAdded1 + item.name + thesaurus.shop_itemAdded2);
			return true;
		}
	}
	else
	{
		alert(thesaurus.shop_cookieDisabled);
		return false;
	}
}

function getItems(cookieName)
{
	var cookie = getCookie(cookieName);
	var items = new Array();

	if(cookie == "")
		return;

	// get items from basket
	var strItems = cookie.split('#');
	var i;
	for (i=0 ; i<strItems.length ; i++)
	{
		var item = new ShopItem();
		if (strItems[i] == "" || strItems[i] == null)
			continue;
		item.makeFromCookieString(strItems[i]);
		items[items.length] = item;
	}

	return items;
}

function setShippingCosts(shippingCostCookieName, area, bReload)
{
	var currentArea = getCookie(shippingCostCookieName);
	if (currentArea != area)
	{
		var exp = new Date();
		exp.setTime(exp.getTime() + (86400 * 1000 * 30));
		setCookie(shippingCostCookieName,area, exp);

		if (bReload == true)
			window.location.reload();
	}
}

function shopGetQuantity(id)
{
	var input = document.getElementById("qty" + id);
	if(input == null) {
		return "1";
	} 
	var qty = parseInt(input.value, 10);
	if(isNaN(qty) || qty < 1) return "1";
	return "" + qty;
}
//
///////////////////////////////////////////////////////////////////////////////
