UnidMonet = "&#128;";	//Euro

//////////////////////////////////////////////////////////////////////////////////////////////

ChekOutToolTip = "Concluir encomenda";
CancelCartToolTip = "Remover todos os artigos do carrinho de compras";
RemoveItemToolTip = "Remover";
ChangeQttToolTip = "Alterar quantidade";
ViewCartToolTip = "Ver os produtos seleccionados por si";
ProdImagToolTip = "Clique para ver mais informações";
QttToolTip = "Quantidade a comprar";
AddToCartToolTip = "Adicionar ao carrinho de compras";

//////////////////////////////////////////////////////////////////////////////////////////////


SmallWindowName = "SmallWindowIris";
SmallWindow = null;

AddedWindowName = "AddedIris";
AddedWindow = null; 



function AddProduct(ref, title, image, link, price, description, no_stock)
{
	pl[pl.length] = new Product(ref, title, image, link, price, description, no_stock);
}




function Update()
{
	Orders = LoadOrders();

	Items = 0;
	Custo = 0;
	for(i = 0; i < Orders.length; i++)
	{
		Items += Orders[i].Qtt;
		Custo += Orders[i].Price * Orders[i].Qtt;
	}
	str = "" + Items + " item" + (Items!=1? "s" : "") + " / " + Custo + UnidMonet;
	document.getElementById('Carrinho').innerHTML = str;


	setTimeout("Update()", 500);
}

function AddToCartN(num)
{
	str = document.forms[num].elements[0].value;

	if(parseInt(str) != str)
	{
		alert("Por favor introduza uma quantidade válida!");
		document.forms[num].elements[0].focus();
		return;
	}

	if(pl[num].NoStock == 1)
	{
		alert("Artigo esgotado!");
		return;
	}

	var NewOrder = new Order();
	NewOrder.Make(pl[num], parseInt(str));
	

	Orders = LoadOrders();
	
	AddOrder(Orders, NewOrder);

	SaveOrders(Orders);


	if((getCookie("CartOpen") == "1") || (SmallWindow != null && !SmallWindow.closed))
	{	
		OpenCart();
	}
	else
	{
		AddedWindow = OpenCenteredWindow("../loja/added.htm", AddedWindowName, 350, 130);
		AddedWindow.focus();
	}
}

function AddToCart(num)
{
	if(pl[num].NoStock == 1)
	{
		alert("Artigo esgotado!");
		return;
	}


	var NewOrder = new Order();
	NewOrder.Make(pl[num], 1);


	Orders = LoadOrders();
	
	AddOrder(Orders, NewOrder);

	SaveOrders(Orders);


	if((getCookie("CartOpen") == "1") || (SmallWindow != null && !SmallWindow.closed))
	{	
		OpenCart();
	}
	else
	{
		AddedWindow = OpenCenteredWindow("../loja/added.htm", AddedWindowName, 350, 130);
		AddedWindow.focus();
	}
}



function Pagar(same_window)
{
	if(Orders.length == 0)
	{
		alert("O seu carrinho ainda está vazio!")
		return;
	}

	EndShopping(same_window);
}




function OpenCenteredWindow(url, name, w, h, param)
{
	settings = '';

	if(screen.width && screen.height)
	{
		LeftPos = (screen.width-w)/2; 
		TopPos = (screen.height-h)/2; 
		settings = 'height=' + h + ',width=' + w + ',top=' + TopPos + ',left=' + LeftPos;	
	}
	else
		settings = 'height=' + h + ',width=' + w;

	if(param != "")
		settings += ',' + param;		

	return (window.open(url, name, settings));
}

//////////////////////////////////////////////////////////////////////////////////////////////

function Product(ref, title, image, link, price, description, no_stock)
{
	this.Ref = ref;
	this.Title = title;
	this.Image = image;
	this.Link = link;
	this.Price = price;
	this.Description = description;
	this.NoStock = no_stock;
}

function Order(ref, title, link, price, qtt)
{
	this.Ref = ref;
	this.Title = title;
	this.Link = link;
	this.Price = price;
	this.Qtt = (qtt == null ? 1 : qtt);
}

new Order("", "", "", 0, 0);

function MakeOrder(prod, qtt)
{
	this.Ref = prod.Ref;
	this.Title = prod.Title;
	this.Link = prod.Link;
	this.Price = prod.Price;
	this.Qtt = qtt;	
}

function Order2Strings()
{
	ret = new Array(this.Ref, this.Title, this.Link, this.Price + '', this.Qtt + '');
	return (ret);
}

Order.prototype.Strings = Order2Strings;
Order.prototype.Make = MakeOrder;

function Strings2Orders(StrArray)
{
	var ret = new Array();
	
	for(i = 0; i < StrArray.length; i += 5)
	{
		ret[i/5] = new Order(StrArray[i], StrArray[i+1], StrArray[i+2], parseFloat(StrArray[i+3]), parseInt(StrArray[i+4]));
	}

	return (ret);
}

function EqualProductOrder(Order1, Order2)
{
	if((Order1.Ref == Order2.Ref) && (Order1.Title == Order2.Title) &&
	   (Order1.Link == Order2.Link)	&& (Order1.Price == Order2.Price))
		return true;
	else
		return false;
}

//////////////////////////////////////////////////////////////////////////////////////////////

function OpenCart()
{
	SmallWindow = OpenCenteredWindow("../loja/cart.htm", SmallWindowName, 620, 360, "scrollbars=yes,resizable=yes");
	SmallWindow.focus();

//	var now = new Date();
//	fixDate(now);		// fix the bug in Navigator 2.0, Macintosh
//	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
//	setCookie("CartOpen", "1", now, "/");
}

function EndShopping(same_window)
{
	if(same_window)
		window.location = "../loja/?pagar/";
	else
	{
		JanelaPagar = window.open("../loja/?pagar/", "IrisPagar");
		JanelaPagar.focus();
		window.close();

//		SmallWindow = OpenCenteredWindow("/loja/checkout.htm", SmallWindowName, 420, 360, "scrollbars=yes,resizable=yes");
//		SmallWindow.focus();
	}
}

function CancelCart()
{
	if (window.confirm("Tem a certeza que quer remover todos os produtos do seu carrinho de compras?")) 
	{
		deleteCookie("Cart", "/");
		return true;
	}

	return false;
}

function SaveOrders(Orders)
{
	var cook = new String();

	for(i = 0; i < Orders.length; i++)
		cook += CodeStringArray(Orders[i].Strings());

	
	var now = new Date();
	fixDate(now);		// fix the bug in Navigator 2.0, Macintosh
	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	setCookie("Cart", cook, now, "/");
}

function LoadOrders()
{
	str = getCookie("Cart");
	var Orders = new Array();

	if(str != null)
		Orders = Strings2Orders(DecodeStringArray(str));

	return Orders;
}

function AddOrder(Orders, NewOrder)
{
	for(i = 0; i < Orders.length; i++)
		if(EqualProductOrder(Orders[i], NewOrder))
		{
			Orders[i].Qtt += NewOrder.Qtt;
			return;
		}

	Orders[Orders.length] = NewOrder;
}

//////////////////////////////////////////////////////////////////////////////////////////////

function ArrayRemove(array, elemento)	//elemento comeca em 0
{
	if(elemento >= array.length)
		return;

	for(i = elemento; i < array.length - 1; i++)
		array[i] = array[i+1];

	array.length --;
}

//////////////////////////////////////////////////////////////////////////////////////////////


//This function rounds the amount and checks if it is NaN (Not a Number)
function Cent(amount) {
// returns the amount in the .99 format 
    amount -= 0;
    amount = (Math.round(amount*100))/100;
    return (amount == Math.floor(amount)) ? amount + '.00' : (  (amount*10 == Math.floor(amount*10)) ? amount + '0' : amount);
}

//////////////////////////////////////////////////////////////////////////////////////////////

function WriteStartJavaScript(documento)
{
	documento.write("<SCRIPT LANGUAGE=\"JavaScript\">");
}

function WriteEndJavaScript(documento)
{
	documento.write("</s" + "cript>");
}

//////////////////////////////////////////////////////////////////////////////////////////////

var HexChars = "0123456789ABCDEF";

function Dec2HexByte(DecVal)
{
	var Dig1 = DecVal % 16;
	var Dig2 = (DecVal-Dig1) / 16;
	return (HexChars.charAt(Dig2)+HexChars.charAt(Dig1));
}

function Dec2HexWord(DecVal)
{
	var Byte1 = DecVal % 0xFF;
	var Byte2 = (DecVal-Byte1) / 0xFF;
	return (Dec2HexByte(Byte2)+Dec2HexByte(Byte1));
}

function StrCode(str)
{
	var sRet = "";
	var i;
	var c;
	var l = str.length;   

	for (i = 0; i < l; i++) 
	{
		c = str.charCodeAt(i);
		if ( ((c >= 48) && (c <= 57)) ||
			  ((c >= 65) && (c <= 87)) ||	//XYZ
			  ((c >= 97) && (c <= 122)) )
		{
			sRet += String.fromCharCode(c);
		}
		else
		{
			if(c <= 0xFF)
				sRet += "Z" + Dec2HexByte(c);
			else
				sRet += "Y" + Dec2HexWord(c);
		}
	}

	return sRet;
}

function ParamCode()
{
	var args = ParamCode.arguments; 

	var sRet = "";
	var i;
	var l = args.length;

	for (i=0; i<l; i++)
		sRet += StrCode(args[i])+"X";

	return sRet;
}

function CodeStringArray(astr)
{
	var sRet = "";
	var i;
	var l = astr.length;

	for (i=0; i<l; i++)
		sRet += StrCode(astr[i])+"X";

	return sRet;
}

function Hex2DecByte(HexVal)
{
	return (HexChars.indexOf(HexVal.charAt(0))*16 + HexChars.indexOf(HexVal.charAt(1)));
}

function Hex2DecWord(HexVal)
{
	return (Hex2DecByte(HexVal.substring(0,2))*0xFF + Hex2DecByte(HexVal.substring(2)));
}

function DecodeStringArray(str)
{
	var args = new Array();
	var k = 0;

	var s = "";
	var c;
	var l = str.length;   
	var i = 0;

	while(i < l)
	{
		c = str.charAt(i);
		switch (c)
		{
		   case 'Z': 
				s += String.fromCharCode(Hex2DecByte(str.substring(i+1, i+3)));
				i+=3;
      		break;

		   case 'Y': 
				s += String.fromCharCode(Hex2DecWord(str.substring(i+1, i+5)));
				i+=5;
		      break;

			case 'X':
				args[k] = s;
				s = "";
				k++;
				i++;
				break;

	   	default : 
				s += c;
				i++;
		} 
	}

	return args;
}

//////////////////////////////////////////////////////////////////////////////////////////////

// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function setCookie(name, value, expires, path, domain, secure)
{
	var curCookie = name + "=" + escape(value) +
   		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
  	document.cookie = curCookie;
}

// name - name of the desired cookie
// * return string containing value of specified cookie or null if cookie does not exist
function getCookie(name)
{
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);

	if (begin == -1) 
	{
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
  	} 
	else
		begin += 2;

	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
		end = dc.length;
  	
	return unescape(dc.substring(begin + prefix.length, end));
}

// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function deleteCookie(name, path, domain)
{
	if (getCookie(name)) 
	{
		document.cookie = name + "=" + 
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"
function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}


