var carrinhoitems;
var carrinhovalor;

if (!Number.toFixed){
  // the function toFixed takes the # of decimal places to use
  Number.toFixed = function (x) {
       var temp = this;
       temp=Math.ceil(temp*Math.pow(10,x))/Math.pow(10,x);
       return temp;
  }

}

function valida_quant(obj){
	if (!isNaN((parseInt(obj.value)))&&(parseInt(obj.value).toString()==obj.value)&&(parseInt(obj.value)>0)){
		return true;
	}else{
		return false;
	}
}
function DeleteCarrinho (name) 
{
	SetCookie(name,' ');
}

function init_carrinho(){
	carrinhoitems=document.getElementById('totalitems');
	carrinhovalor=document.getElementById('totalvalor');
}
function getCookieVal (offset) {  
	var endstr = document.cookie.indexOf (";", offset);  

	if (endstr == -1) { endstr = document.cookie.length; }

	return unescape(document.cookie.substring(offset, endstr));

}

function GetCookie (name) {  

	var arg = name + "=";  

	var alen = arg.length;  

	var clen = document.cookie.length;  

	var i = 0;  
	while (i < clen) {    
		var j = i + alen;    
		if (document.cookie.substring(i, j) == arg) return getCookieVal (j);    
		i = document.cookie.indexOf(" ", i) + 1;    
		if (i == 0) break;   
	}  
	return null;
}



function SetCookie (name, value) {  
	var argv = SetCookie.arguments;  

	var argc = SetCookie.arguments.length;  

	var expires = (argc > 2) ? argv[2] : null;  

	var path = (argc > 3) ? argv[3] : null;  

	var domain = (argc > 4) ? argv[4] : null;  

	var secure = (argc > 5) ? argv[5] : false;  
	
	var i=0;
	while (value.length>0)
	{
		document.cookie = name + i +"=" + escape (value.substring(0,2500)) + 
		
		((path == null) ? ";path=/" : ("; path=" + path)) +  
		
		((domain == null) ? "" : ("; domain=" + domain)) +    
		
		((secure == true) ? "; secure" : "");
		i=i+1
		value=value.substring(2500,value.length)
	}

}

function readCookie(name){
	cookievalor = GetCookie(name+'0');
	i=1;
	cookieValue='';
	while (cookievalor!=null){
		cookieValue=cookieValue+cookievalor.substring(0,2500);
		cookievalor = GetCookie(name+i);
		i=i+1;
	}
	if (cookieValue.length>2){
	return cookieValue;
	}else{
	return '';
	}
}
				
function add_item(obj,cookiename,descricao,item,preco){
	
	if (!isNaN(obj.value)&&(obj.value!='')) {
		obj.value=parseInt(parseInt(obj.value)+1);
	}else{
		obj.value=1;
	}
	//add_bag(cookiename,descricao,item,obj.value,preco);

}

function sub_item(obj,cookiename,descricao,item,preco){
	if (!isNaN(obj.value)&&(obj.value!='')&&(obj.value>0)) {
		obj.value=parseInt(parseInt(obj.value)-1);
		/*if (obj.value==0){
			remove_bag(cookiename,item,preco);
		}else{
			add_bag(cookiename,descricao,item,obj.value,preco);
		}*/
	}else{
		obj.value=0;
	}
	
}

function add_bag(cookiename,descricao,item,quantidade,preco,seccao,rev,ref){
	cookieValue=readCookie(cookiename);
	cookieValue=cookieValue.replace('#,#','\',\'');

	if ((cookieValue==void(0))||(cookieValue=='')){
		totalItems=1;
		totalValor=parseInt(quantidade)*parseFloat(preco);
		totalValor=totalValor.toFixed(2);
		itemsArray=[item+'##'+descricao+'##'+quantidade+'##'+preco+'##'+seccao+'##'+ref];
	}else{
		cookieValueArray=cookieValue.split('#&#');
		totalItems=parseInt(cookieValueArray[0]);
		totalValor=parseFloat(cookieValueArray[1]);
		totalValor=totalValor.toFixed(2);
		eval('itemsArray='+cookieValueArray[2]);

		if ((indice=checkItem(item,seccao,itemsArray))>-1){
			oldvalor=itemsArray[indice];
			oldvalorarray=oldvalor.split('##');
			diferenca=parseFloat((parseFloat(quantidade)-parseFloat(oldvalorarray[2])))*parseFloat(preco);
			totalValor=parseFloat(totalValor.toString())+parseFloat(diferenca.toString());
			totalValor=totalValor.toFixed(2);
			itemsArray[indice]=item+'##'+descricao+'##'+quantidade+'##'+preco+'##'+seccao+'##'+ref;
			
		}else{
			itemsArray[itemsArray.length]=item+'##'+descricao+'##'+quantidade+'##'+preco+'##'+seccao+'##'+ref;
			totalItems=parseInt(totalItems)+1;
			totalValor=parseFloat(totalValor)+(parseFloat(quantidade)*parseFloat(preco));
			totalValor=totalValor.toFixed(2);
		}
	}
	cookieValue=totalItems+'#&#'+totalValor+'#&#[\'';
	for (i=0;i<itemsArray.length;i++){
		cookieValue=cookieValue+itemsArray[i]+'#,#'
	}
	cookieValue=cookieValue.substring(0,cookieValue.length-3)
	cookieValue=cookieValue+'\']#&#'+rev;
	carrinhoitems.value=totalItems;
	carrinhovalor.value=totalValor;
	SetCookie(cookiename,cookieValue);
	
}

function remove_bag(cookiename,item,seccao,preco){
	cookieValue=readCookie(cookiename);
cookieValue=cookieValue.replace('#,#','\',\'');
	if ((cookieValue==void(0))||(cookieValue=='')){
		totalItems=0;
		totalValor=0;
		itemsArray=[];
	}else{
		cookieValueArray=cookieValue.split('#&#');
		totalItems=parseInt(cookieValueArray[0]);
		totalValor=parseFloat(cookieValueArray[1]);
		eval('itemsArray='+cookieValueArray[2]);
		if ((indice=checkItem(item,seccao,itemsArray))>-1){
			oldvalor=itemsArray[indice];
			oldvalorarray=oldvalor.split('##');
			diferenca=(-parseFloat(oldvalorarray[2]))*parseFloat(preco);
			totalValor=parseFloat(totalValor)+parseFloat(diferenca);
			totalValor=totalValor.toFixed(2);
			totalItems=totalItems-1
			itemsArrayNew=new Array();
			j=0;
			for (i=0;i<itemsArray.length;i++)
			{
				if (i!=indice){			
					itemsArrayNew[j]=itemsArray[i];
					j++;
				}
			}
			itemsArray=itemsArrayNew;
		}
	}
	if (totalItems==0){
		cookieValue=' ';
	}else{
		cookieValue=totalItems+'#&#'+totalValor+'#&#[\'';
		for (i=0;i<itemsArray.length;i++){
			cookieValue=cookieValue+itemsArray[i]+'#,#'
		}
		cookieValue=cookieValue.substring(0,cookieValue.length-3)
		cookieValue=cookieValue+'\']';
	}
	carrinhoitems.value=totalItems;
	carrinhovalor.value=totalValor;
	
	SetCookie(cookiename,cookieValue);
	
}

function checkItem(item,seccao,itemarray){
	for (i=0;i<itemarray.length;i++){
		valor=itemarray[i];
		valorarray=valor.split('##');
		if (item==valorarray[0] && seccao==valorarray[4]){
			return i;
		}
	}
	return -1;
}

function load_bag(formName,cookiename,fieldname){
	cookieValue=readCookie(cookiename);
cookieValue=cookieValue.replace('#,#','\',\'');
	if ((cookieValue==void(0))||(cookieValue=='')){
		totalItems=0;
		totalValor=0;
		itemsArray=[];
	}else{
		cookieValueArray=cookieValue.split('#&#');
		totalItems=parseInt(cookieValueArray[0]);
		totalValor=parseFloat(cookieValueArray[1]);
		totalValor=totalValor.toFixed(2);
		eval('itemsArray='+cookieValueArray[2]);
		for (i=0;i<itemsArray.length;i++){
			valorarray=itemsArray[i].split('##');
			for(j=0; j<document[formName].elements.length; j++){
				nome=document[formName].elements[j].name;
				if ((indice=nome.indexOf(fieldname,0))!=-1){
					numero=nome.substring(indice+fieldname.length,nome.length);
					if (numero==valorarray[0]) {
						document[formName].elements[j].value=valorarray[2];
						
					}
				}
				
			}	
		}

	}	
}

function load_bagvalues(cookiename,objtotal,objitem){
	cookieValue=readCookie(cookiename);
cookieValue=cookieValue.replace('#,#','\',\'');
	if ((cookieValue==void(0))||(cookieValue=='')){
		totalItems=0;
		totalValor=0;
		itemsArray=[];
	}else{
		cookieValueArray=cookieValue.split('#&#');
		totalItems=parseInt(cookieValueArray[0]);
		totalValor=parseFloat(cookieValueArray[1]);
		totalValor=totalValor.toFixed(2);
	}
	objitem.value=totalItems;
	objtotal.value=totalValor;
}
function substitui(texto,car1,car2){
var i;

while((i=texto.indexOf(car1))>=0){
	texto=texto.slice(0,i)+car2+texto.slice(i+1,texto.length)
}
return texto;
}

function createRequestObjectEnc(){
	var request_o_enc; //declare the variable to hold the object.
	try {
		request_o_enc = new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			request_o_enc = new ActiveXObject("Microsoft.XMLHTTP");
		}catch(E){
			//xmlhttp = false; // esta linha é que dava problema com firefox
			request_o_enc = new XMLHttpRequest();
		} 
	}
	return request_o_enc; //return the object
}

var HttpEnc;
function getImage(url,idprod,idseccao){
	showtrail('../../../images/loading.gif','1',160);
	url += (url.indexOf("?") === -1)?"?":"&";
	url += "ridcache="+Math.random();
	url += "&idprod="+idprod;
	url += "&idseccao="+idseccao;
	httpEnc=createRequestObjectEnc();	
	httpEnc.open('GET', url,true);
	httpEnc.setRequestHeader('Content-Type', 'text/html; charset=ISO-8859-1');
	httpEnc.onreadystatechange = function(){
				if(httpEnc.readyState == 4|| httpEnc.readyState=="complete"){
					var response = httpEnc.responseText;
					showtrail(response,'1',160);
					httpEnc.close;
				}
			};
	httpEnc.send(null);
}
function createAllTable(){
	var htmlTable;
	leCookie();
	
	htmlTable='<form name="encomendarapida" id="encomendarapida" method="GET">';
	htmlTable=htmlTable+'<table width="100%" cellspacing="0" cellpadding="0" border="0">';
	htmlTable=htmlTable+'<input type="hidden" id="totalitems" name="totalitems" value="0" />'
	htmlTable=htmlTable+'<input type="hidden" id="totalvalor" name="totalvalor" value="0" />';
	htmlTable=htmlTable+'<tr>';
	htmlTable=htmlTable+'<td class="titulo_laranja" align="center"><img src="../../../images/lupa.gif" border="0"/></td>';
	htmlTable=htmlTable+'<td class="titulo_laranja" align="center">Referência</td>';
	htmlTable=htmlTable+'<td class="titulo_laranja" align="center">Descritivo</td>';
	htmlTable=htmlTable+'<td class="titulo_laranja" align="center">Quantidade</td>';
	htmlTable=htmlTable+'<td class="titulo_laranja" align="center">Valor</td>';
	htmlTable=htmlTable+'<td class="titulo_laranja" align="center">Adicionar</td>';
	htmlTable=htmlTable+'<td class="titulo_laranja" align="center">Total</td>';
	htmlTable=htmlTable+'</tr>';
	htmlTable=htmlTable+'<tr>';
	htmlTable=htmlTable+'<td colspan="7" class="linha_laranja" style="height:10px;">&nbsp;</td>';
	htmlTable=htmlTable+'</tr>';
	htmlTable=htmlTable+createProductsTable();
	htmlTable=htmlTable+'<tr>';
	htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center">&nbsp;</td>';
	htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center"><input type="text" class="texto" name="aref" id="aref" value=""/></td>';
	htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center">&nbsp;</td>';
	htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center"><input type="text" class="texto" name="aquant" id="aquant" value="1"/></td>';
	htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center">&nbsp;</td>';
	htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center"><div id="acidionar" class="adicionar_laranja" style="cursor:pointer;" onclick="if(ValidaQuant(\'aquant\') && ValidaRef(\'aref\')){AddRef(\'enc_functions.asp?action=addbag\',document.getElementById(\'aref\').value,document.getElementById(\'aquant\').value);}">Adicionar</div></td>';
	htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center">&nbsp;</td>';
	htmlTable=htmlTable+'</tr>';
	htmlTable=htmlTable+'</tr>';
	htmlTable=htmlTable+'<td colspan="7" style="height:20px;">&nbsp;</td>';
	htmlTable=htmlTable+'</tr>';
	htmlTable=htmlTable+'</tr>';
	htmlTable=htmlTable+'<td colspan="6" class="sombra_laranja">&nbsp;</td>';
	htmlTable=htmlTable+'<td class="texto" align="center"><input type="text" id="totalt" name="totalt" class="texto" readonly value="'+totalValor+'"/> &euro;</td>';
	htmlTable=htmlTable+'</tr>';
	htmlTable=htmlTable+'<tr>';
	htmlTable=htmlTable+'<td colspan="7" class="linha_laranja" style="height:10px;">&nbsp;</td>';
	htmlTable=htmlTable+'</tr>';
	htmlTable=htmlTable+'</table>';
	htmlTable=htmlTable+'</form>';
	
	document.getElementById('div_enc_rpd').innerHTML = htmlTable;
}
function createProductsTable(){
	var htmlTable = '';
	leCookie();
	
	if (totalItems==0){
	
		htmlTable=htmlTable+'';
	}else{
	

		for (i=0;i<itemsArray.length;i++){
			valor=itemsArray[i].split('##')
			htmlTable=htmlTable+'<tr>';
			htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center"><img src="../../../images/lupa_branca.gif" style="padding:0px;margin:0px;cursor:pointer;" onMouseOver="getImage(\'enc_functions.asp?action=getimage\',\''+valor[0]+'\',\''+valor[4]+'\',\'div_enc_rpd_wait\')" onMouseOut="hidetrail();"/></td>';
			htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center" id="tdref_'+valor[0]+'_'+valor[4]+'">'+valor[5]+'</td>';
			htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center">'+valor[1]+'</td>';
			htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center"><input name="quant'+valor[0]+'_'+valor[4]+'" type="text" class="texto" value="'+valor[2]+'"></td>';			
			htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center">'+parseFloat(valor[3]).toFixed(2)+'&euro;</td>';   
			htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center"><button type=button style="border:0;background-color:#ffffff;" onclick="javascript:init_carrinho();if (valida_quant(this.form.quant'+valor[0]+'_'+valor[4]+')){add_bag(\'lislabel\',\''+valor[1]+'\',\''+valor[0]+'\',this.form.quant'+valor[0]+'_'+valor[4]+'.value,\''+valor[3]+'\',\''+valor[4]+'\',\'\',\''+valor[5]+'\');this.form.total'+valor[0]+'_'+valor[4]+'.value=(this.form.quant'+valor[0]+'_'+valor[4]+'.value*'+eval(valor[3])+').toFixed(2);leCookie();this.form.totalt.value=totalValor;if (totalItems==0){createAllTable();}}else{alert(\'Insira uma quantidade num&eacute;rica superior a 0.\')};" /><img src="../../../images/v.gif" border="0" style="cursor:pointer;"></button> <button type=button style="border:0;background-color:#ffffff;" onclick="javascript:init_carrinho(\'this.carrinho\');remove_bag(\'lislabel\',\''+valor[0]+'\',\''+valor[4]+'\',\''+valor[3]+'\');this.form.quant'+valor[0]+'_'+valor[4]+'.value=\'0\';this.form.total'+valor[0]+'_'+valor[4]+'.value=(this.form.quant'+valor[0]+'_'+valor[4]+'.value*'+valor[3]+').toFixed(2);leCookie();this.form.totalt.value=totalValor;if (totalItems==0){createAllTable();}" /><img src="../../../images/x.gif" border="0" style="cursor:pointer;"></button></td>';		
			htmlTable=htmlTable+'<td class="texto" style="padding-top:3px;" align="center"><input class=texto name="total'+valor[0]+'_'+valor[4]+'" type="text" readonly value="'+parseFloat(valor[2]*valor[3]).toFixed(2)+'" >&nbsp;&euro;</td>';
			htmlTable=htmlTable+'</tr>';
		}
	}
	
	return htmlTable;
}
var requestObject;
function AddRef(url,ref,quant){
	 //declare the variable to hold the object.
	try {
		requestObject = new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			requestObject = new ActiveXObject("Microsoft.XMLHTTP");
		}catch(E){
			//xmlhttp = false; // esta linha é que dava problema com firefox
			requestObject = new XMLHttpRequest();
		} 
	}
	
	url += (url.indexOf("?") === -1)?"?":"&";
	url += "ridcache="+Math.random();
	url += "&ref="+ref;
	url += "&quant="+quant;
	
	requestObject.open('GET', url,true);
	requestObject.setRequestHeader('Content-Type', 'text/html; charset=ISO-8859-1');
	requestObject.onreadystatechange = function(){
				if(requestObject.readyState == 4 || requestObject.readyState=="complete"){
					var response = requestObject.responseText;
					if (response == 'error' || response == ''){
						alert('A Referência que introduziu não existe!');
					}else{
						var arrayAddBag = response.split('<==>');
						if (arrayAddBag[0]!='' && arrayAddBag[1]!='' && arrayAddBag[2]!='' && arrayAddBag[3]!='' && arrayAddBag[04]!='' && arrayAddBag[5]!='' && arrayAddBag[6]!='' && arrayAddBag[7]!=''){
							add_bag(arrayAddBag[0],arrayAddBag[1],arrayAddBag[2],arrayAddBag[3],arrayAddBag[4],arrayAddBag[5],arrayAddBag[6],arrayAddBag[7]);
							createAllTable();
						}else{
							alert('Ocorreu um erro ao adicionar o produto ao carrinho! \n Pedimos desculpa pelo incomodo!');
						}
					}
					requestObject.close;
				}
			};
	requestObject.send(null);
	
}
function ValidaQuant(TextboxId){
	var message = '';
	if (document.getElementById(TextboxId).value==''){
		document.getElementById(TextboxId).value='1';
	}
	if (IsNumeric(document.getElementById(TextboxId).value)==false){
		message = 'Na quantidade só pode introduzir algarismos!';
	}

	if (message!=''){
		alert(message);
		return false;
	}else{
		return true;
	}
}
function ValidaRef(TextboxId){
	var message = '';
	if (document.getElementById(TextboxId).value==''){
		message = 'Tem que escrever uma referência.';
	}

	if (message!=''){
		alert(message);
		return false;
	}else{
		return true;
	}
}
function IsNumeric(sText)
{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1) 
         {
			IsNumber = false;
         }
      }
   return IsNumber;
   
}
