// JavaScript Document
// number formatting function
// copyright Stephen Chapman 24th March 2006, 22nd August 2008
// permission to use this function is granted provided
// that this copyright notice is retained intact

function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) {
	var x = Math.round(num * Math.pow(10,dec));
	if (x >= 0) n1=n2='';
	var y = (''+Math.abs(x)).split('');
	var z = y.length - dec; 
	if (z<0) z--; 
	for(var i = z; i < 0; i++) y.unshift('0'); 
	if (z<0) z = 1; 
	y.splice(z, 0, pnt); 
	if(y[0] == pnt) y.unshift('0'); 
	while (z > 3) {
		z-=3; 
		y.splice(z,0,thou);
	}
	var r = curr1+n1+y.join('')+n2+curr2;
	return r;
}

function check_ie(form) {    
	var rv = -1; // Return value assumes failure.    
	if (document.all && navigator.appName == 'Microsoft Internet Explorer') {        
		var ua = navigator.userAgent;
		var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");        
		if (re.exec(ua) != null) rv = parseFloat(RegExp.$1);    
	
		if ( rv>'5.00') {
			var formulario=document.getElementById(form);
			formulario.submit();
		} else {
			alert('As nossas desculpas: a funcionalidade pedida está optimizada \r\n para funcionar apenas com o Internet Explorer 6.0 ou superior.');
		}
	} else {
		alert('As nossas desculpas: a funcionalidade pedida está optimizada \r\n para funcionar apenas com o Internet Explorer');
	}
	
}
function check_js() {
	if(document.getElementById('hd_js')) {
		document.getElementById('hd_js').value=1;
	}

}
function check_options() {
	entrega=false;
	pagamento=false;
	if (typeof(document.final.rb_entrega.length)=="undefined") {
		if (document.final.rb_entrega.checked==true){
			entrega=true;
		}
	} else {
		for (i=0;i<document.final.rb_entrega.length;i++){
			if (document.final.rb_entrega[i].checked==true){ // se estiver entrega seleccionada
				entrega=true;
				break ;
			}
		}
	}
	if (typeof(document.final.rb_pagamento.length)=="undefined") {
		if (document.final.rb_pagamento.checked==true){
			pagamento=true;
		}
	} else {
		for (i=0;i<document.final.rb_pagamento.length;i++){
			if (document.final.rb_pagamento[i].checked==true){
				pagamento=true;
				break ;//exist for loop, as target acquired.
			}
		}
	}
	if ((entrega==false) || (pagamento==false)) {
		alert('Tem que seleccionar Pagamento e Entrega');
	} else {
		document.final.submit();
	}
	
}
function change_pag(id,cobr) {
	var entrega=false;
	var cobranca=false;
	var rb_selected=id;
	var id=false;
	valtotal=total_value.value;
	valportes='0.00';
	if (typeof(document.final.rb_entrega.length)=="undefined") {
		if (document.final.rb_entrega.checked==true){
			id=document.final.rb_entrega.value;
			entrega=true;
		}
	} else {
		for (i=0;i<document.final.rb_entrega.length;i++){
			if (document.final.rb_entrega[i].checked==true){ // se estiver entrega seleccionada
				entrega=true;
				if (document.final.rb_entrega[i].value !=2) { // Se entrega não for levantar
					id=document.final.rb_entrega[i].value;
					break ;
				}
			}
		}
	}
	
	if (rb_selected==2) { // se estiver cobrança seleccionada
		cobranca=true;
		hd_cobranca.value=cobr;
		//alert(hd_cobranca.value);
	}
	
	//-
	if (entrega==true) { // Tipo de entrega seleccionado
		if (id!=false) { // Tipo de entrega não é levantar nas instalaçôes
			valportes=document.getElementById('hdportes['+id+']').value;
			valportes=parseFloat(valportes).toFixed(2);
			
			if (cobranca==true) { // se estiver cobrança seleccionada
				valportes=(parseFloat(valportes) + parseFloat(cobr)).toFixed(2);
				/*val_prodportes=document.getElementById('hdprodportes').value;
				if (val_prodportes!="") {
					valportes=(parseFloat(valportes) + parseFloat(val_prodportes)).toFixed(2);
				}*/
				// alert(document.final.rb_entrega[i].value);
			} else { // Cobrança não foi seleccionada
				
				///val_prodportes=document.getElementById('hdprodportes').value;
				//if (val_prodportes!="") {
					//valportes=(parseFloat(valportes) + parseFloat(val_prodportes)).toFixed(2);
				//}
				//alert(valportes);
				
				// --------------------------------------
				//divportes.innerHTML=valportes+' €';
				//currency_total= (parseFloat(valportes) + parseFloat(valtotal)).toFixed(2);
				//currency_total=formatNumber(currency_total,2,'.',',','','','-','');
				//currency_total=currency_total.replace(",",".");
				//sptotal.innerHTML=currency_total;
			
			}
			divportes.innerHTML=valportes+' €';
			currency_total= (parseFloat(valportes) + parseFloat(valtotal)).toFixed(2);
			currency_total=formatNumber(currency_total,2,'.',',','','','-','');
			//currency_total=currency_total.replace(",",".");
			sptotal.innerHTML=currency_total;
		} else { // // Tipo de entrega é levantar nas instalaçôes
			valportes='0.00';
			divportes.innerHTML=valportes+' €';
			currency_total=  parseFloat(valtotal).toFixed(2);
			currency_total=formatNumber(currency_total,2,'.',',','','','-','');
			//currency_total=currency_total.replace(",",".");
			sptotal.innerHTML=currency_total;
		}

		
		document.frm_print.btn_imprimir.disabled=false;
		hide_total.style.visibility="visible";
		text_entrega.style.display="none";
		document.final.total_portes.value=valportes;
		document.getElementById('print_portes').value=valportes;
	} else { // Tipo de entrega não foi selecccionado
		divportes.innerHTML='0.00 €';
		//currency_total= (parseFloat(valportes) + parseFloat(valtotal)).toFixed(2);
		//currency_total=currency_total.replace(",",".");
		//currency_total=formatNumber(currency_total,2,'.',',','','','-','');
		//sptotal.innerHTML=currency_total;
				
	}

	//alert(document.final.total_portes.value);
	
}
function change_portes(id,cobr) {
	var pagamento=false;
	var cobranca=false;
	//var rb_selected=id;
	//var id=false;
	if (document.getElementById('hdportes['+id+']'))	{ // Verificação inicial se existe hdportes
		if (typeof(document.final.rb_pagamento.length)=="undefined") {
			if (document.final.rb_pagamento.checked==true){
				pagamento=true;
			}
		} else {
			for (i=0;i<document.final.rb_pagamento.length;i++){
				if (document.final.rb_pagamento[i].checked==true){
					if (document.final.rb_pagamento[i].value==2) { // Se tipo de pagamento for com cobrança
						cobranca=true;
						var rb_selected=document.final.rb_pagamento[i].value;
						// hd_cobranca.value=cobr;
						//alert(rb_selected);
					}
					pagamento=true;
					break ;//exist for loop, as target acquired.
				}
			}
		}
		
		if (pagamento==true) { // Tipo de pagamento seleccionado
			if (id!=2) { // Ss entrega não for ao balcão
				valportes=document.getElementById('hdportes['+id+']').value;
				if (cobranca==true) { // Se for com cobrança
					
					valportes=(parseFloat(valportes) + parseFloat(cobr)).toFixed(2);
					
				} else {
					valportes=formatNumber(valportes,2,'.','.','','','-','');
				}
				/*val_prodportes=document.getElementById('hdprodportes').value;
					if (val_prodportes!="") {
						valportes=(parseFloat(valportes) + parseFloat(val_prodportes)).toFixed(2);
					}*/
				//alert(valportes);

				
				
				if (document.getElementById('inside_min')) {
					
					inside_min.innerHTML=(parseFloat(valportes) + parseFloat(valtotal)).toFixed(2);
				}
				hide_total.style.visibility="visible";
				text_entrega.style.display="none";
				//alert(valportes.tofixed(2));
				 
			} else { // Entrega é ao balcão
				valportes='0.00';
				text_entrega.style.display="none";
				hide_total.style.visibility="visible";
				if (document.getElementById('inside_min')) {
					inside_min.innerHTML=valtotal;
				}
				/*document.getElementById('print_portes').value='0.00';
				document.getElementById('print_total').value=parseFloat(valtotal).toFixed(2);
				valor_min.style.visibility="visible";*/
				
				

			}
			
			
			valtotal=total_value.value;
			currency_total= (parseFloat(valportes) + parseFloat(valtotal)).toFixed(2);
			currency_total=formatNumber(currency_total,2,'.',',','','','-','');
			//currency_total=currency_total.replace(",",".");
			sptotal.innerHTML=currency_total;
			divportes.innerHTML=valportes+' €';
			
			
			document.frm_print.btn_imprimir.disabled=false;
			document.final.total_portes.value=valportes;
			document.getElementById('print_portes').value=valportes;
			document.getElementById('print_total').value=parseFloat(valtotal).toFixed(2);
		}
	}
}
function message_stock() {
	alert('Produto indisponível - Seremos breves');	
}
function changeall (imagefile,description) {

	var art_args=imagefile.split(';');
	var art_count=art_args.length;

	if (art_args.length > 2){
		if (art_count==3) {
			if (art_args[2]==1) { // Só tem Imagem
				if ((document.getElementById('sel_opcao2') && sel_opcao2.options.selectedIndex>0) || (!document.getElementById('sel_opcao2'))) {
				document.getElementById('btn_add').disabled=false;
				}
				document.getElementById('hidpre').value=art_args[0];
				document.getElementById('oppvp').innerHTML=art_args[0];
				var image=document.getElementById('artimage');
				image.src=art_args[1];
				image.setAttribute('onclick',function() {MM_openBrWindow('detalhe.php?art=4769','windetails','scrollbars=yes,resizable=yes,width=500,height=500') });
			}
			if (art_args[2]==2) { // Só tem preço
				if ((document.getElementById('sel_opcao2') && sel_opcao2.options.selectedIndex>0) || (!document.getElementById('sel_opcao2'))) {
				document.getElementById('btn_add').disabled=false;
				}
				document.getElementById('hidpre').value=art_args[1];
				document.getElementById('oppvp').innerHTML=art_args[1];
			}
			
		}
		if (art_count==4) {
			if (art_args[3]==12) { // Tem imagem e Preço
				if ((document.getElementById('sel_opcao2') && sel_opcao2.options.selectedIndex>0) || (!document.getElementById('sel_opcao2'))) {
				document.getElementById('btn_add').disabled=false;
				}
				var image=document.getElementById('artimage');
				image.src=art_args[1];
				image.setAttribute('onclick',function() {MM_openBrWindow('detalhe.php?art=4769','windetails','scrollbars=yes,resizable=yes,width=500,height=500') });
				document.getElementById('hidpre').value=art_args[2];
				document.getElementById('oppvp').innerHTML=art_args[2];
			}
		}
		
	} else {
		
		if (art_args[0]!='0.00') {
		document.getElementById('oppvp').innerHTML=art_args[0];
		document.getElementById('hidpre').value=art_args[0];
		} else {
			document.getElementById('oppvp').innerHTML='&nbsp;&nbsp;&nbsp;';
			document.getElementById('hidpre').value=art_args[0];
		}
		document.getElementById('btn_add').disabled=true;
	}
	
}

function changeimg (imagefile,description) {
	var art_args=imagefile.split(';');
	var art_count=art_args.length;
	if (art_args.length > 1){
		if (art_args[1]!=0) {
			if ((document.getElementById('sel_opcao1') && sel_opcao1.options.selectedIndex>0) || (!document.getElementById('sel_opcao1'))) {
				document.getElementById('btn_add').disabled=false;
			}
			var image=document.getElementById('artimage');
			image.src=art_args[0];
		}
	} else {
		if (art_args[0]==0) {
			document.getElementById('btn_add').disabled=true;
		} else {
			if ((document.getElementById('sel_opcao1') && sel_opcao1.options.selectedIndex>0) || (!document.getElementById('sel_opcao1'))) {
				document.getElementById('btn_add').disabled=false;
			}
		}
	}
}

function actualiza_nome(nomeartigo) {
	/*if (document.getElementById('sel_opcao2')) {
		alert('teste');
	}*/
		
	var op2=0;
	if (document.getElementById('sel_opcao2')) {
		if (sel_opcao2.options.selectedIndex>0) {
			op2=1;
		}
	}
	if (document.getElementById('sel_opcao1')) {
		if (sel_opcao1.options.selectedIndex>0) {
			if (op2==0) {
				document.getElementById('nome_art').value=nomeartigo+' '+sel_opcao1.options[sel_opcao1.selectedIndex].innerHTML;
			} else {
				document.getElementById('nome_art').value=nomeartigo+' '+sel_opcao1.options[sel_opcao1.selectedIndex].innerHTML+' '+sel_opcao2.options[sel_opcao2.selectedIndex].innerHTML;
			}
		}
	}
	
	if (document.getElementById('nome_art')) {
		alert(document.getElementById('nome_art').value);
	}

}
function vertical() { 
var navItems = document.getElementById("nav").getElementsByTagName("li"); 
for (var i=0; i< navItems.length; i++) { 
if(navItems[i].className == "submenu") { 
navItems[i].onmouseover=function() {this.getElementsByTagName('ul')[0].style.display="block";this.style.backgroundColor = "#CC0000";} 
navItems[i].onmouseout=function() {this.getElementsByTagName('ul')[0].style.display="none";this.style.backgroundColor = "#CC0000";} 
} 
} 

} 
function horizontal() { 

var navItems = document.getElementById("barra").getElementsByTagName("li"); 

for (var i=0; i< navItems.length; i++) { 
if((navItems[i].className == "menuvertical") || (navItems[i].className == "submenu")) 
{ 
if(navItems[i].getElementsByTagName('ul')[0] != null) 
{ 
navItems[i].onmouseover=function() {this.getElementsByTagName('ul')[0].style.display="block";this.style.backgroundColor = "#99CCFF";} 
navItems[i].onmouseout=function() {this.getElementsByTagName('ul')[0].style.display="none";this.style.backgroundColor = "#0099FF";} 
} 
} 
} 

} 

function selectAllOptions(selStr)
{
  var selObj = document.getElementById(selStr);
  selObj.multiple=true;
  for (var i=0; i<selObj.options.length; i++) {
    selObj.options[i].selected = true;
  }
}
function fechar(texto,wind)
{
	document.getElementById(texto).style.display="none";
	if (wind) {
	document.getElementById(wind).style.display="inline";
	}
}
function ver_mais(texto,wind)
{
	
	document.getElementById(texto).style.display="block";
	document.getElementById(wind).style.display="inline";
	
	
}
function enable_ch(btn)
{
	var ob_btn=new Object;
	ob_btn=document.getElementById(btn);
	ob_btn.disabled=false;
}
function remove_cat(remform)
{
	var elOptNew = document.createElement('option');
	var elSel = document.getElementById('list_add[]');
	var freeSel=document.getElementById('list_free');
	var selIndex = document.getElementById('list_add[]').selectedIndex;

	
			elOptNew.text = elSel.options[selIndex].text;
			elOptNew.value = elSel.options[selIndex].value;
		  try {
			freeSel.add(elOptNew, null); // standards compliant; doesn't work in IE
			elSel.remove(selIndex);
			document.getElementById[remform].btn_remove.disabled=true;

		  }
		  catch(ex) {
			  
			freeSel.add(elOptNew); // IE only
			elSel.remove(selIndex);
			document.getElementById(remform).btn_remove.disabled=true;
			
		  }

}
function add_cat(form)
{
	var elOptNew = document.createElement('option');
	var elSel = document.getElementById('list_add[]');
	var freeSel=document.getElementById('list_free');
	var selIndex = document.getElementById('list_free').selectedIndex;

	
			elOptNew.text = freeSel.options[selIndex].text;
			elOptNew.value = freeSel.options[selIndex].value;
		  try {
			elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
			freeSel.remove(selIndex);
			document.getElementById(form).btn_change.disabled=true;

		  }
		  catch(ex) {
			  
			elSel.add(elOptNew); // IE only
			freeSel.remove(selIndex);
			document.getElementById(form).btn_change.disabled=true;
			
		  }
	
}

function add_cat1()
{
  if (document.getElementById("list_free")) {
	  var cat=document.getElementById("list_free");
	  var options=cat.getElementsByTagName("option"); //pega a lista de options do select
	  var sely=document.getElementById("list_add");
	  var opty=sely.document.getElementsByTagName("option");
	  sely.createElement('option'); //cria um novo elemento option
	  sely.text="Teste";
	  sely.value="Teste";
	  
  alert('Ok');
  }
}
function active_button(but,textbox,flag) {

	if (but!="") {
		document.getElementById(but).disabled=false;
	}
	if (textbox=="txtemail" && document.getElementById('txtemail')) {
		document.getElementById('txtemail').value="";
	}
	if (textbox=="txt_telefone" && document.getElementById('txt_telefone')) {
		document.getElementById('txt_telefone').value="";
	}
	if (textbox=="passcliente" && document.getElementById('passcliente')) {
		document.getElementById('passcliente').value="";
	}
	if (textbox=="ncliente" && document.getElementById('ncliente')) {
		document.getElementById('ncliente').value="";
	}
	if (textbox=="pesq" && document.getElementById('pesq')) {
		document.getElementById('pesq').value="";
	}

}
function Runwebdesign()
{
	document.write('<object classid="clsid:d27cdb6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab# version=6,0,29,0 "width="380" height="125" align="top" >\n');	
	document.write('<param name="movie" value="imagens/sist/webdesign.swf" />\n');
	document.write('</object>\n');
}
function run_work()
{
	document.write('<object classid="clsid:d27cdb6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab# version=6,0,29,0 "width="400" height="250" align="top" >\n');	
	document.write('<param name="movie" value="imagens/sist/work.swf" />\n');
	document.write('</object>\n');
}
function MM_setTextOfTextfield(objName,x,newText) { //v3.0
  var obj = MM_findObj(objName); if (obj) obj.value = newText;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

// Google Maps
var map; 
function initialize() {
  if (GBrowserIsCompatible() && document.getElementById("map")) {
   var map = new GMap(document.getElementById("map"));
	  map.setMapType(G_NORMAL_MAP);

	 var mt = map.getMapTypes();
mt[0].getMaximumResolution = function() {return 17;}
mt[0].getMinimumResolution = function() {return 11;}
	map.addControl(new GLargeMapControl()); 
	map.addControl(new GMapTypeControl()); 
	var center = new GLatLng(38.75679615075573, -9.242083579301834);
	map.setCenter(center, 15);
	GEvent.addListener(map, "moveend", function() {  var center = map.getCenter();  document.getElementById("message").innerHTML = 'Coordenadas Centro do mapa: <br>'+center.toString();});
	var marker = new GMarker(center);
	map.addOverlay(marker);
  }
}
