var isNS4 = (document.layers) ? true : false;
var isIE4 = (document.all && !document.getElementById) ? true : false;
var isIE5 = (document.all && document.getElementById) ? true : false;
var isNS6 = (!document.all && document.getElementById) ? true : false;

var supplierAlertMsg = new Array();

function supplierAlert() {
    //alert('Informamos que as encomendas de mobiliário cujo pagamento seja autorizado entre as 13h do dia 18 de Maio e as 13h do dia 25 de Maio, serão entregues, excepcionamelmente, nos dias 13 e 14 de Junho.');
    //for (i = 0; i < supplierAlertMsg.length; i++ && supplierAlertMsg[i].charAt(0) != '?') {
    //    if (typeof(supplierAlertMsg[i]) != "undefined" && supplierAlertMsg[i] != '') { 
	//			alert('Informamos que as encomendas de mobiliário cujo pagamento seja autorizado entre as 13h do dia 18 de Maio e as 13h do dia 25 de Maio, serão entregues, excepcionamelmente, nos dias 13 e 14 de Junho.');    
    //    }
    //}
}

function setProductPositions (ord) {	
	var node = document.getElementById('prodList');
	if(!node) return;
	
	var nodeTemp, nodeSep;
	for (var i = 0; i < numProd; i++) {
		nodeTemp = document.getElementById(orderArray[ord][i]);
		
		node.removeChild(nodeTemp);
		node.appendChild(nodeTemp);
	}
    

    if(ord == 0) {
        document.getElementById('descriptionOrd').className='descOrdSel';
        document.getElementById('priceOrd').className='priOrd';
    } else {
        document.getElementById('descriptionOrd').className='descOrd';
        document.getElementById('priceOrd').className='priOrdSel';
    }
}

function showProducts() {
    var node = document.getElementById('productListMain');
    if ( node != null ) {
        node.style.visibility = 'visible';
    }
}

function setCookie(name, value, expire) {
    document.cookie = name + "=" + escape(value) + ((expire == null) ? "" : ('; expires=' + expire.toGMTString()));
}

function defineMode() {
    var ordem = getCookie('ordenacao');
 
    if ( typeof(ordem) != 'undefined') {
        setProductPositions(ordem);
    }
    showProducts();        
}

function getCookie(Name) {
    var search = Name + '=';
    
    if (document.cookie.length > 0) {
         offset = document.cookie.indexOf(search);
         if (offset != -1) {
            offset += search.length;
            end = document.cookie.indexOf(';', offset);
            if (end == -1) {
                end = document.cookie.length;
            }
            return unescape(document.cookie.substring(offset, end));
        }
    }
}

function getCookieParent(Name) {
    var search = Name + '=';
    var cookieParent = window.parent.document.cookie;

    if (cookieParent.length > 0) {
         offset = cookieParent.indexOf(search);

         if (offset != -1) {
            offset += search.length;
            end = cookieParent.indexOf(';', offset);
            if (end == -1) {
                end = cookieParent.length;
            }
            return unescape(cookieParent.substring(offset, end));
        }
    }
}

function gotoUrl (mode) {
    if ( mode == 1 ) {
        window.location = urlWithImg
    } else {
        window.location = urlWithOutImg
    }
}

function submitForm(action, target, id, validateFunc) {	  
  
    var form = document.getElementById(id);
    validate = false;
    
    if (submitForm.arguments.length > 3) {
        validate = true;
    }

    if( (!validate || (validate && (validateFunc != '' && eval(validateFunc + '(form)')))) && validateForm(id) ) {
	form.action = action;    
	form.target = target;        	
    form.submit();        	

    //if (validateFunc=='valFormQuantitiesFloat')
     //   form["quantity(1)"].value='';
    }
}

function submitToFav(action, target, id, validateFunc) {	  
	var form = document.getElementById(id);
	
/*	for ( var i = 0; i < form.productOrder.length; i++ ) {
		if ( form.productOrder[i].checked == true ) {
			o = prodOrderArray[i];
			alert(form.addToFav[i].value);
		}
	}           
*/	
	if ( validateFunc != '' && typeof(validateFunc) != 'undefined' ) {
		submitForm(action, target, id, validateFunc);
	} else {
		submitForm(action, target, id);
	}

 	cleanCheckBoxes(form.productOrder);
}

function clock(){
		var element = document.getElementById('contentWrapper');
                if (element != null) { element.style.visibility='hidden'; }
                document.getElementById('waitingDiv').style.display='block';
		document.getElementById('waitingDiv').innerHTML="<img src='/img/watchme.gif' border=0><p>O seu pedido est&aacute; a ser submetido, por favor aguarde um momento...</p>";
		top.location='#fullSite';
}


function submitFormProductList(action, target, id, item, validateFunc) {	  
    var form = document.getElementById(id);
    form.actionType.value= item;

    if ( validateFunc != '' && typeof(validateFunc) != "undefined" ) {
    	submitForm(action, target, id, validateFunc);
    } else {
    	submitForm(action, target, id);
    }
}

function countNumBytes(strValue, fieldName, maxBytesBD) {
	var max_size = strValue.length;
	var cont = 0;
	var contNumBytes = 0;

	while (cont<max_size) {

		ch = strValue.charCodeAt(cont);

		if (ch<=0x7f) {
			contNumBytes = contNumBytes +1;
		}
		else if (ch<=0x3ff) {
			contNumBytes = contNumBytes +2;
		}
		else if (ch<=0xffff) {
			contNumBytes = contNumBytes +3;
		}
		else {
			contNumBytes = contNumBytes +4;
		}			
			
		cont++;
	}
	
	if (contNumBytes>maxBytesBD) {
		return 'Por favor rectifique o número de caracteres introduzidos no campo ' + fieldName + '. O limite máximo de caracteres é de' + maxBytesBD + '.\nNota: Cada caracter acentuado equivale a 2 unidades. Outro tipo de símbolos equivalem a 3 unidades. Caso contrário equivale a 1 unidade.\n\n';
	} else
		return '';
}

function submitFormPzn(altarray){
	  var i;
	  var alerttext = '';
	  var errFocus;
	  var elt;
	  if (altarray != '' && typeof(validateFunc) != "undefined" ) {
		  
		  for( i=0; i<altarray.length; i++ ){
		    elt = altarray[i];
			alerttext += countNumBytes( document.forms[elt[0]][elt[1]].value,elt[2],elt[3]);
			errFocus = altarray[i];
		  }
	  }
	  if(alerttext != '') {
		alert(alerttext);
		errFocus.focus()
		return false;
	  }
	  	
	  return true;
}

function submitFormProductListDetail(action, target, id, item, validateFunc, altarray) {	  
    var form = document.getElementById(id);
	
    form.actionType.value= item;

	if (submitFormPzn(altarray)) {
			
	    if ( validateFunc != '' && typeof(validateFunc) != "undefined" ) {
	    	submitForm(action, target, id, validateFunc);
	    } else {
	    	submitForm(action, target, id);
	    }
    }
}

function submitFormShopList(action, target, id, validateFunc) {	  
    var form = document.getElementById(id);
    submitForm(action, target, id, validateFunc);
    form.itemToAddOrder.value='';
}

function submitRemoveShopListItem(action, target, id, item) {	  
    var form = document.getElementById(id);
    form.itemOrder.value= item;
    submitForm(action, target, id);
    form.itemOrder.value='';
}

function submitPayType(action, id) {	  
    clock();
    submitForm(action, '_top', id);

}

function setItemToAddOrder(id, value) {
    var form = document.getElementById(id);    
    form.itemToAddOrder.value = value;
}


function incrValue (order) {
    var prod = document.getElementById('quantity' + order);
    if ( prod.value == "" )
    	prod.value = 0;
    if (cb_parseInt(prod.value) < 0) {
        prod.value = 0;   
    } else if (cb_parseInt(prod.value) >= 9999) {
    	prod.value = 9999;
    } else {
        prod.value = cb_parseInt(prod.value) + 1;
    }    
}

function decrValue (order) {
    var prod = document.getElementById('quantity' + order);
    if ( prod.value == "" )
    	prod.value = 0;
    if (cb_parseInt(prod.value) <= 0) {
        prod.value = 0;   
    } else {
        prod.value = cb_parseInt(prod.value) - 1;
    }    
}

function valFormQuant(form) {
    
    quant = form["quantity(1)"];  
           
    if(quant.value != '' && !isPositiveInteger(quant.value)) {        
        alert("Quantidade inválida.");
        quant.focus();
        return false;   
    }
    
    if (quant.value == '') {
        quant.value = 1;   
    }

    if (cb_parseInt(quant.value) < cb_parseInt(form.minOrder.value) ) {
        alert("Quantidade abaixo do limite mínimo (" + form.minOrder.value + " unidades)");   
        quant.focus();
        return false;
    }
    
    if (cb_parseInt(quant.value) > cb_parseInt(form.maxOrder.value)) {
        alert("Quantidade acima do limite máximo (" + form.maxOrder.value + " unidades).");   
        quant.focus();
        return false;
    }
         
    return true;
}
//catalogo2
function valFormQuantitiesFloat(form) {
	var quantF = form["quantity(1)"];  

	if (quantF!="undefined") {
		if ((quantF.value == 0) && (quantF.value != '') && !isPositiveFloat(parseFloat(quantF.value))) {
	        alert("Quantidade inválida.");
	        quantF.focus();
			return false;
		}
		
		if (quantF.value == ''){
			quantF.value = 1;
		}
		
		if ( parseFloat(quantF.value) < parseFloat(form.minOrder.value) ) {
	        alert("Quantidade abaixo do limite mínimo (" + parseFloat(form.minOrder.value) + " unidades)");   
	        quantF.focus();
	        return false;
	    }
	    
	    if ( parseFloat(quantF.value) > parseFloat(form.maxOrder.value)) {
	        alert("Quantidade acima do limite máximo (" + parseFloat(form.maxOrder.value) + " unidades).");   
	        quantF.focus();
	        return false;
	    }
	}
	
	
	
	return true;
}

function isInvalidSel(form, value) {
    // check invalid from quantity input + item order value
    var quantity = document.getElementById('quantity' + value);    
    return (quantity.value == -1);        
}

function valShopListSel (form, object) {    
    if (typeof(object.length)=="undefined") {
    	return !isInvalidSel(form, object.value);
    }
    for (var i = 0; i < object.length; i++) {
    	if (object[i].checked==true && isInvalidSel(form, object[i].value))
            return false;
    }    
    return true;
}

function valMaxMinOrder (form) {
    var errors = '';
    var singleProd = false; 
    var validate = false;
    var check = form.productOrder;    
    for (var i = 0; i < prodOrderArray.length; i++) {
	if (form.itemToAddOrder.value != '') {
		o = form.itemToAddOrder.value;
		singleProd = true;
		validate = true;
	} else {
		o = prodOrderArray[i];
		if (typeof(check.length)=="undefined") {
			validate = check.checked;
		} else {
			for (var j = 0; j < check.length; j++) {
				if (check[j].value == o) {
			    	validate = check[j].checked;
			    	break;
			    }  				
			}
		}
	}			    	
        min = cb_parseInt(minOrderArray[o]);
        max = cb_parseInt(maxOrderArray[o]);
        name = prodNameArray[o];
        var q = document.getElementById('quantity' + o);	       
        value = q.value;

        if (validate && value != '' && !isPositiveInteger(value)) {
            errors += '\n' + 'A quantidade do produto ' + name + ' é inválida.';       
            validate = false;   
        }          
        if (validate) {        
	        if (value == '') {
	        	value = 1;
	        }	        	        
	        if (cb_parseInt(value) < min) {
	        	errors += '\n' + 'A quantidade do produto ' + name + ' está abaixo do limite mínimo (' + min + ' unidades).';
	        }
	        if (cb_parseInt(value) > max) {
	        	errors += '\n' + 'A quantidade do produto ' + name + ' está acima do limite máximo (' + max + ' unidades).';
	        }
        }        
        if (singleProd) {
        	break;
        }
    }    
    if (errors == '') {
    	return true;
    } else {
    	if (singleProd) {
	    	form.itemToAddOrder.value = '';
    	}	    
    	alert(errors);
    	return false;
    }	    
}	

//catalogo2
function valMaxMinOrderFloat (form) {
    var errors = '';
    var singleProd = false; 
    var validate = false;
    var check = form.productOrder;    
    for (var i = 0; i < prodOrderArray.length; i++) {
	if (form.itemToAddOrder.value != '') {
		o = form.itemToAddOrder.value;
		singleProd = true;
		validate = true;
	} else {
		o = prodOrderArray[i];
		if (typeof(check.length)=="undefined") {
			validate = check.checked;
		} else {
			for (var j = 0; j < check.length; j++) {
				if (check[j].value == o) {
			    	validate = check[j].checked;
			    	break;
			    }  				
			}
		}
	}			    	
        min = parseFloat(minOrderArray[o]);
        max = parseFloat(maxOrderArray[o]);
        name = prodNameArray[o];
        q = document.getElementById('quantity' + o);	       
        value = q.value;

        if (validate && value != '' && !isPositiveFloat(parseFloat(value))) {
            errors += '\n' + 'A quantidade do produto \"' +name + '\" é inválida.';       
            validate = false;   
        }          
        if (validate) {        
	        if (value == '') {
	        	value = 1;
	        }	        	        
	        if (parseFloat(value) < min) {
	        	errors += '\n' + 'A quantidade do produto \"' + name + '\" está abaixo do limite mínimo (' + min + ' unidades).';
	        }
	        if (parseFloat(value) > max) {
	        	errors += '\n' + 'A quantidade do produto \"' + name + '\" está acima do limite máximo (' + max + ' unidades).';
	        }
        }        
        if (singleProd) {
        	break;
        }
    }    
    if (errors == '') {
    	return true;
    } else {
    	if (singleProd) {
	    	form.itemToAddOrder.value = '';
    	}	    
    	alert(errors);
    	return false;
    }	    
}	

function valShopCartMaxMinOrder (form) {
    var errors = '';    
    var validate = true;    
    for (var i = 0; i < prodOrderArray.length; i++) {
	o = prodOrderArray[i];
        min = cb_parseInt(minOrderArray[o]);
        max = cb_parseInt(maxOrderArray[o]);
        name = prodNameArray[o];
        var q = document.getElementById('quantity' + o);	       
        value = q.value;  
        if (value == '' || value == 0) {
            validate = false;
        }        
        if (validate && value != '' && !isPositiveInteger(value)) {
            errors += '\n' + 'A quantidade do produto ' + name + ' é inválida.';       
            validate = false;   
        }        	                
        if (validate) {	        
            if (cb_parseInt(value) < min) {
            	errors += '\n' + 'A quantidade do produto ' + name + ' está abaixo do limite mínimo (' + min + ' unidades).';
            }
            if (cb_parseInt(value) > max) {
            	errors += '\n' + 'A quantidade do produto ' + name + ' está acima do limite máximo (' + max + ' unidades).';
            }
        }        
        validate = true;
    }    
    if (errors == '') {
    	return true;
    } else {
    	alert(errors);
    	return false;
    }	    
}	

//catalogo2
function valShopCartMaxMinOrderFloat (form) {
	var errors = '';    
    var validate = true;    
    for (var i = 0; i < prodOrderArray.length; i++) {
	o = prodOrderArray[i];
        min = parseFloat(minOrderArray[o]);
        max = parseFloat(maxOrderArray[o]);
        name = prodNameArray[o];
        q = document.getElementById('quantity' + o);	       
        value = q.value;  
        if (value == '' || value == 0) {
            validate = false;
        }        
        if (validate && value != '' && !isPositiveFloat(parseFloat(value))) {
            errors += '\n' + 'A quantidade do produto \"' + name + '\" é inválida.';       
            validate = false;   
        }        	                
        if (validate) {	        
            if (parseFloat(value) < min) {
            	errors += '\n' + 'A quantidade do produto \"' + name + '\" está abaixo do limite mínimo (' + min + ' unidades).';
            }
            if (parseFloat(value) > max) {
            	errors += '\n' + 'A quantidade do produto \"' + name + '\" está acima do limite máximo (' + max + ' unidades).';
            }
        }        
        validate = true;
    }    
    if (errors == '') {
    	return true;
    } else {
    	alert(errors);
    	return false;
    }	    
}	


function validateForm (id) {
	nameSub = ""
	var form = document.getElementById(id);

	for (var i=0; i < form.length; i++) {
		// validacao dos subprodutos
		if ( form.elements[i].name.search("subproduct") >= 0 && form.elements[i].name != nameSub ) {
			nameSub = form.elements[i].name;
			if ( form.elements[i].type == "radio" || form.elements[i].type == "checkbox" ) {
				if ( typeof(form[nameSub].length) != "undefined" && form[nameSub].length != null ) {
					checked = false;
					for ( var j=0; j < form[nameSub].length; j++ ) {
						if ( !checked ) {
							checked = form[nameSub][j].checked;
						}
					}
				} else {
					checked = form[nameSub].checked;
				}
				if ( !checked ) {
					alert("Indique a opção pretendida.");
					return false;
				}
			}
		}
		
		// validacao dos atributos de personalizacao
		if ( form.elements[i].name.search("pznAttribute") >= 0 && form.elements[i].name != nameSub ) {
			nameSub = form.elements[i].name;
			if ( typeof(form[nameSub].length) != "undefined" && form[nameSub].length != null ) {
				checked = false;
				option = ""
				for ( var j=0; j < form[nameSub].length; j++ ) {
					if ( !checked ) {
						checked = form[nameSub][j].checked;
						option = form[nameSub][j].value;
					}
				}
				if ( !checked ) {
					alert("Erro: O produto tem de ser totalmente personalizado!");
					return false;
				}
			} else {
				checked = form[nameSub].checked;
				option = form[nameSub].value;
			}
			if ( checked ) {
				id = nameSub.substring(nameSub.indexOf("(")+1, nameSub.indexOf(")"));
				tipo = form["pznType(" + id + "_" + option + ")"].value;
				if ( tipo == "I" && form["pznFileURL(" + id + ")"].value == "" ) {
					if ( form["pznFile" + id + "_" + option].value == "" ) {
						alert("Erro: Tem de inserir um ficheiro para submissão!");
						return false;					
					}
				}
				if ( tipo == "T" ) {
					if ( form["pznText(" + id + "_" + option + ")"].value == "" ) {
						alert("Erro: Tem de inserir um texto!");
						form["pznText(" + id + "_" + option + ")"].focus();
						return false;					
					}				
				}
			}
		}
	}
	return true;
}

function doNotificationAction(msg, action) {  
	var cookieIsLoggedOn = getCookie('isloggedon');

    if ((typeof(isLoggedOn) != "undefined" && !isLoggedOn) || typeof(cookieIsLoggedOn)=="undefined") {
        alert(msg);
    } else {
        openChild ('',action,'warningEmail', 250, 110, 'no', 'no', 'no', 'no', 'no', 0);
    }   
}

function doNotificationAnonymous(action) {  
    openChild ('',action,'warningEmail', 380, 200, 'no', 'no', 'no', 'no', 'no', 0);
}

function validateNotificationAnonymous(form) { 
    var name = form.name.value;
    if (name == null || name == '') {
        alert('Introduza o seu nome.');
        return false;
    }
    var email = form.email.value;
    if (!validateEmail(email)) {
        alert('O email é inválido.');
        return false;
    }
    return true;
}

function doNotificationActionParent(msg, action) {  
	//for popUps like subProductdetail         
	var cookieIsLoggedOn = getCookieParent('isloggedon');

    if ((typeof(isLoggedOn) != "undefined" && !isLoggedOn) || typeof(cookieIsLoggedOn)=="undefined") {
        alert(msg);
    } else {
        openChild ('',action,'warningEmail', 250, 110, 'no', 'no', 'no', 'no', 'no', 0);
    }   
}

function goBack() {
/*	window.location = document.referrer;	*/
	history.go(-1);
}


function openPayConfirmPopUps() { 
//	window.open('http://www.portugalacep.org/scep/formularios.htm', 'SCEP', 'directories=no,height=460,width=780,hotkeys=no,location=no,menubar=no,personalbar=no,resizable=no,scrollbars=no,status=no,titlebar=no,toolbar=no');
//	return false;
} 

function changeQuantity(qtdEl, id, originalQtd) {
    if (qtdEl.value != originalQtd && qtdEl.className != 'qtdChanged') {
        qtdEl.className = 'qtdChanged';
        document.getElementById('btContinue').className = 'hide';
        document.getElementById('btRefresh').className = 'btPri';
        
        document.getElementById('price'+id).className = 'hide';
        document.getElementById('bt'+id).className = 'btPri';

    }
}


function verifyCheaperPriceSubProduct(formId, link) {
    var form = document.getElementById(formId);
    
    var subProdRadio = form["subproduct(1)"]
    
    for (var j = 0; j < subProdRadio.length; j++) {
	    if (subProdRadio[j].checked) {
		    link.href = link.href + '&order='+subProdRadio[j].value;
		    return true;
	    }
	}
    alert('Indique a opção pretendida.');
    return false;
}


