function codigoSeguranca(){
	window.open("resources/popup/explicacaoCodigoSeguranca.htm" , "", "height=490 , width=445");			
}

function submitForm(event, idForm, idValor){
	if(event == 13)	{
			document.getElementById(idForm).submit();	
	}
}

var podeConsultar = true;
function submitFormLocalidade(event){
	if(event == 13 && podeConsultar == true)	{
		consultarPontosFidelidade();
	}
}

function listarCidades(selectUfs,cidadeSelecionada) {
	
	optionSelecionado = selectUfs.options[selectUfs.selectedIndex].value;
	
	if(optionSelecionado != ""){
		gebi("liCidades").innerHTML = '<span id="liCidades">Carregando...</span>';
		
		var args = 'siglaUf=' + optionSelecionado;
		
		if(cidadeSelecionada != null){
			args += "&codigoLocalidade="+cidadeSelecionada;
		}
		
		var httpRequest = createHttpRequest();
		
		httpRequest.onreadystatechange = function() {
			if (whenReady(httpRequest)) {
				gebi("liCidades").innerHTML = httpRequest.responseText;			
			}
		}
		
		httpRequest.open('POST', 'listarCidades.do', true);		
		httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");			
		httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
		httpRequest.setRequestHeader("Content-length", args.length);
		httpRequest.setRequestHeader("Connection", "close");		
		httpRequest.send(args);
	}	
}

/*
 * Funcoes da Grafia
 * Parametros:
 *  -
 *
 * USAGE:
 */
function TrocaDiv(idDiv){
	if (gebi('div_aberta')!=null &&gebi(idDiv)!=null) {
		document.getElementById(document.getElementById('div_aberta').value).style.display = 'none';
		document.getElementById(idDiv).style.display = 'block';
		document.getElementById('div_aberta').value = idDiv;
	}
}





/*
 * Funcao que testa se campos estao preenchidos
 * Parametros:
 *  - camposTestados: ids dos campos testados
 *
 * USAGE: -
 */
function testaCamposPreenchidos(camposTestados){
	preenchidos = true;
	for(i = 0;i < camposTestados.length; i++){
		campoTestado = document.getElementById(camposTestados[i]);			
		if(campoTestado != null && campoTestado.value == ""){		
			preenchidos = false;
			break;			
		}
	}
	return preenchidos;
}


/*
 * Funcao que retorna uma query string com os nomes e valores de campos de um formulario
 * Parametros:
 *  - idFormulario: id do formulario
 *
 * USAGE: -
 */
function buscaValoresFormulario(idFormulario){
	formulario = document.getElementById(idFormulario);
	inputsFormulario = formulario.getElementsByTagName("input");
	selectsFormulario = formulario.getElementsByTagName("select");
		
	retorno = "";
	if(inputsFormulario.length > 0){
		for(i=0; i < inputsFormulario.length; i++){
			inputFormulario = inputsFormulario[i];
			if(inputFormulario.type == "text"){
				retorno += inputFormulario.name+"="+inputFormulario.value+"&";
			}
		}
	}
	
	if(selectsFormulario.length > 0){
		for(i=0; i < selectsFormulario.length; i++){
			selectFormulario = selectsFormulario[i];
			retorno += selectFormulario.name+"="+selectFormulario.value+"&";
		}
	}
	
	return retorno
}


/*
 * Funcao que executa os scripts de uma pagina (e.g. AJAX)
 * Parametros:
 *  - texto: html em que se buscam os scripts
 *
 * USAGE: -
 */
function extraiScript(texto){
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<script', ini);
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);
            // executa o script
            eval(codigo);
        }
    }
}


/*
 * Funcoes genericas
 * Parametros:
 *  -
 *
 * USAGE:
 */
function trim (str) {

    return str.replace(/^\s+|\s+$/g, '') ;
}

function justNumbers (v) {

    return v.replace(/\D/g,"");
}



/*
 * Funcoes que pegam/setam a posicao do cursor
 * Parametros:
 *  - field: campo a ser validado
 *  - pos: posicao onde vai ser colocado o cursor
 *
 * USAGE: onfocus="formatAsCommaOnly(this)" onblur="formatAsPointOnly(this)"
 */
function getCaretPosition (field) {
    var caretPos = 0;
    
    //IE support
    if (document.selection) {
        field.focus();
        var range = document.selection.createRange();
        
        range.moveStart ('character', -field.value.length);
        
        caretPos = range.text.length;
    } else
    //Firefox support
    if (field.selectionStart || field.selectionStart == '0') {
        caretPos = field.selectionStart;
    } else {
        caretPos = -100;
    }
    
    return caretPos;
}

function setCaretPosition (field, pos) {
    if (pos<0) return;
    
    //IE support
    if (field.createTextRange) {
        var range = field.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    } else
    //Firefox support
    if (field.setSelectionRange) {
        field.focus();
        field.setSelectionRange(pos, pos);
    }
}
/*
 * Funcoes para testar e chamar o ajax para pontuar pela compra e convenio a vista
 * Parametros:
 *
 * USAGE: onclick="enviaCartaoFidelidade()"
 */
function enviaCartaoFidelidade(){
	var httpRequest = createHttpRequest();
	var valoresFormulario = "";
	pontuar =gebi("pontuarNumeroCartao");
	//testa se o campo de pontuar pela compra está habilitado e se o usuario preencheu o campo
	if(gebi("pontuarNumeroCartao") != null && 
		gebi("pontuarNumeroCartao").getAttribute("visivel")!= null && 
		gebi("pontuarNumeroCartao").getAttribute("visivel") == "true" && 
		gebi("pontuarNumeroCartao").value != null && 
		gebi("pontuarNumeroCartao").value != "" ){

		gebi("divRetornoPontuarCompra").innerHTML = 'Carregando...';	
		gebi("divRetornoPontuarCompra").style.display = '';		
		//pega o cartao digitado
		valoresFormulario = "&pontuarNumeroCartao="+gebi("pontuarNumeroCartao").value;
		var httpRequest = createHttpRequest();
		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {				
					gebi("divRetornoPontuarCompra").innerHTML = httpRequest.responseText;		
					extraiScript(httpRequest.responseText);							
				}		
			}
	}
	httpRequest.open('POST', "pontuarCompraAction.do", true);
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
	httpRequest.setRequestHeader("Content-length", valoresFormulario.length);
	httpRequest.setRequestHeader("Connection", "close");
	httpRequest.send(valoresFormulario);
	
}

function mudaSemValor(campo){
	if(campo.getAttribute("semValor") != null && campo.getAttribute("semValor") == "true"){
		campo.value = "";
		campo.setAttribute("semValor","false");
	}
}

function enviaConvenioVista(){
	var httpRequest = createHttpRequest();
	var valoresFormulario = "";
	//testa se o campo de convenio a vista está habilitado e se o usuario preencheu o campo
	if(gebi("convenioVistaNumeroCartao") != null && 
		gebi("convenioVistaNumeroCartao").getAttribute("visivel")!= null && 
		gebi("convenioVistaNumeroCartao").getAttribute("visivel") == "true" && 
		gebi("convenioVistaNumeroCartao").value != null && 
		gebi("convenioVistaNumeroCartao").value != "" ){

		gebi("divRetornoConvenioVista").innerHTML = 'Carregando...';	
		gebi("divRetornoConvenioVista").style.display = '';		
		//pega o cartao digitado
		valoresFormulario = "&convenioVistaNumeroCartao="+gebi("convenioVistaNumeroCartao").value;
		var httpRequest = createHttpRequest();

		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {				
					gebi("divRetornoConvenioVista").innerHTML = httpRequest.responseText;		
					recalculaCarrinhoOpcoesPagamento();	
					extraiScript(httpRequest.responseText);					
				}				
			}
	}
	httpRequest.open('POST', "convenioVistaAction.do", true);
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
	httpRequest.setRequestHeader("Content-length", valoresFormulario.length);
	httpRequest.setRequestHeader("Connection", "close");
	httpRequest.send(valoresFormulario);
}

function toDotString (value) { //Muda um valor para somente um ponto (toFloat)

    var num = value.toString();
    var commas = /\,/g;
    num = num.replace(commas,"\.");

    var fim = "";
    if (num.lastIndexOf(".")>=0) {
        var substart = num.substr(0, num.lastIndexOf("."));
        var subend = num.substr(num.lastIndexOf("."),num.length);
        var dots = /\./g;
        substart = substart.replace(dots,"");
        fim = ""+substart+subend;
    } else {
        fim = num;
    }	
    return fim*1;
}

function toCommaString (value) { //Muda o valor para somente uma virgula (money)
	
	var num = value.toString();
	var dots = /\./g;
    num = num.replace(dots,"\,");

    var fim = "";
    if (num.lastIndexOf(",")>=0) {
        var substart = num.substr(0, num.lastIndexOf(","));
        var subend = num.substr(num.lastIndexOf(","),num.length);
        var commas = /\,/g
        substart = substart.replace(commas,"");
        fim = ""+substart+subend;
    } else {
        fim = num;
    }
    
    return fim;
}


/*
 * Funcao que formata numeros para limitar casas decimais
 * Parametros:
 *  - value: valor a ser formatado
 *  - decplaces: numero de casas decimais (>=0)
 *
 * USAGE: someField.value = formatDecPlaces(someField.value,2);
 */
function formatDecPlaces (value, decplaces)
{
    if (decplaces>=0) {
        var str = "" + Math.round (eval(value)*Math.pow(10,decplaces));
		while (str.length<=decplaces) {
            str = "0"+str;
        }
        var decpoint = str.length - decplaces;
		if (decplaces<=0) {
            return str.substring(0,decpoint);
        } else {
            return str.substring(0,decpoint)+"."+str.substring(decpoint,str.length);
		}
    } else {
		return value;
    }
}


/*
 * Funcao que formata campos para limitar casas decimais
 * Parametros:
 *  - field: campo a ser formatado
 *  - decplaces: numero de casas decimais (>=0)
 *
 * USAGE: onblur = blurDecPlaces(someField,2);
 */
function blurDecPlaces (field, decplaces) {

	var value = ''+toDotString(field.value);
	var end;
	if (value.replace(/[\.\,]/g,'').length==0) {
		field.value = '';
		return;
	}
	if (decplaces>=0) {
		var str = "" + Math.round (eval(value)*Math.pow(10,decplaces));
		while (str.length<=decplaces){
			str = "0"+str;
		}
		var decpoint = str.length - decplaces;
		if (decplaces<=0){
			end = str.substring(0,decpoint);
		} else {
			end = str.substring(0,decpoint)+","+str.substring(decpoint,str.length);
		}
	} else {
		end = value;
	}
	field.value = end;
}	

function blurDecPlacesEmpty (field, decplaces) {
	
	if (field.value != "") {
		var value = '' + toDotString(field.value);
		var end;
		if (value.replace(/[\.\,]/g, '').length == 0) {
			field.value = '';
			return;
		}
		if (decplaces >= 0) {
			var str = "" + Math.round(eval(value) * Math.pow(10, decplaces));
			while (str.length <= decplaces) {
				str = "0" + str;
			}
			var decpoint = str.length - decplaces;
			if (decplaces <= 0) {
				end = str.substring(0, decpoint);
			}
			else {
				end = str.substring(0, decpoint) + "," + str.substring(decpoint, str.length);
			}
		}
		else {
			end = value;
		}
		field.value = end;
	}
}	


/*
 * Funcao auxiliar para autoformatacao de alguns campos
 * Parametros:
 *  - c:
 *
 * USAGE:
 */
function krLIMP (c) {
    while((cx=c.indexOf("-"))!=-1){
        c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf("/"))!=-1){
	c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf(","))!=-1){
    	c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf("."))!=-1){
	c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf("("))!=-1){
	c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf(")"))!=-1){
	c = c.substring(0,cx)+c.substring(cx+1);
    }
    while((cx=c.indexOf(" "))!=-1){
	c = c.substring(0,cx)+c.substring(cx+1);
    }
    return(c);
}
function formatNumeroDocumento(field,e,tipoCampo){
	
	var valor = field.value;
	var expressaoRegular = ""; 
	
	
	
	if(document.all){  
        var key = event.keyCode;      	 
    }else{  
        var key = e.which; 
		      
    }  
	
	testeTeclas = e.keyCode;
	charCode = e.charCode
	deleteKey = false;
	backspaceKey = false;
	moveKey = false;
	if (testeTeclas==46 && charCode==0) deleteKey = true;
    if (testeTeclas==8 && charCode==0) backspaceKey = true;
    if (((testeTeclas>=33 && testeTeclas<=40) || testeTeclas==9) && charCode==0) moveKey = true;
    
    if (deleteKey || backspaceKey || moveKey) {
		return true;
	}
	
	letra = String.fromCharCode(key);
	
	switch (tipoCampo) {       
        case 'ALFANUMÉRICO' : expressaoRegular = /[^a-zA-Z0-9]/; break;
        case 'ALFABÉTICO' : expressaoRegular = /[^a-zA-Z]/; break;
        case 'NUMÉRICO' : expressaoRegular = /[^0-9]/; break;
        case 'none' : return true; break;
        default : return true; break;
    }

    if (expressaoRegular.test(letra)) {    
   		return false;
    }else{    
    	return true;
    }
} 
function formatNumeroDocumentoBlur(field,e,tipoCampo){
	
	var valor = field.value;
	var expressaoRegular = ""; 
	
	if(document.all){  
        var key = event.keyCode;  
     
    }else{  
        var key = e.which;         
    }  
	letra = String.fromCharCode(key);
	
	switch (tipoCampo) {       
        case 'ALFANUMÉRICO' : expressaoRegular = /[^a-zA-Z0-9]/; break;
        case 'ALFABÉTICO' : expressaoRegular = /[^a-zA-Z]/; break;
        case 'NUMÉRICO' : expressaoRegular = /[^0-9]/; break;
        case 'none' : return true; break;
        default : return true; break;
    }
    
    if (expressaoRegular.test(letra)) {    
   		field.value = "";
    }
} 
/*
 * Formata campos de numeros a medida que o usuario preenche os valores
 * Parametros:
 * - field: campo a ser preenchido
 * - character: tecla pressionada
 *
 * USAGE: onkeypress="return formatNumbers(this, event)"
 */
function formatNumbers (field, event) {
	
	var myfield = field.value;
    
    var keyCode = event.keyCode;
    var charCode = event.charCode;
    
    var deleteKey = false;
    var backspaceKey = false;
    var moveKey = false;
    
    if (keyCode==46 && charCode==0) deleteKey = true;
    if (keyCode==8 && charCode==0) backspaceKey = true;
    if (((keyCode>=33 && keyCode<=40) || keyCode==9) && charCode==0) moveKey = true;
    
    var caretPos = getCaretPosition(field);

	if (deleteKey || backspaceKey || moveKey) {
		return true;
	}
	
	var tecla = charCode ? charCode : keyCode;
	
    if (tecla>=48 && tecla<=57) {
    	return true;
    }
    return false;
}


// testing...
/*
 * Formata o campo CEP a medida que o usuario preenche os valores
 * Parametros:
 * - field: campo a ser preenchido
 * - character: tecla pressionada
 *
 * USAGE: onkeypress="return formatCEP(this, event)"
 */
 
function formatCEP (field, event) {

    var myfield = field.value;
    
    var keyCode = event.keyCode;
    var charCode = event.charCode;
    
    var deleteKey = false;
    var backspaceKey = false;
    var moveKey = false;
    
    if (keyCode==46 && charCode==0) deleteKey = true;
    if (keyCode==8 && charCode==0) backspaceKey = true;
    if (((keyCode>=33 && keyCode<=40) || keyCode==9) && charCode==0) moveKey = true;
    
    var caretPos = getCaretPosition(field);

	var tecla = charCode ? charCode : keyCode;
	if (deleteKey || backspaceKey || moveKey) {
		return true;
	}
	
	
    
    //verifica se browser possui suporte a createRange como o Internet Explorer
    if(document.selection) {
 
	    var testRange = document.selection.createRange().text;
	    if((tecla>=48 && tecla<=57) && testRange.length > 0) {
	    	return true;
	    }
    } else {
   		if ((tecla>=48 && tecla<=57) && field.selectionStart < field.selectionEnd) {
	    	return true;
		} 
    }
   
	if (myfield.length>8) {
		return false;
	}
	
	

	if (tecla==45 || (tecla>=48 && tecla<=57)) {
	    if (tecla==45 && caretPos==5 && myfield.charAt(caretPos)!='-') {
	      	return true;
	    } else if (myfield.length>=5 && tecla!=45) {
	    	var index = caretPos>=5? 5 : 4;
	    	myfield = myfield.replace(/\-/g,'');
	       	myfield = myfield.substring(0,index)+'-'+myfield.substring(index,7);
	       	field.value = myfield;
	       	setCaretPosition(field,caretPos==5 ? caretPos+1 : caretPos);
	       	return true;
	    } else if ((tecla>=48 && tecla<=57)  || (tecla>=96 && tecla<=105)) {
	       	return true;
	    } 
	    return false;
	}
	return false;
}

/*
 * Forma o CEP ja digitado, quando lido na tela.
 - field: campo com o CEP
 */

function formatCEPFinal (field) {

	var myfield = field.value;
	
	myfield = myfield.substring(0,5)+'-'+myfield.substring(5,8);
	field.value = myfield;
	return true;
}

function formatZIP (field, event) { formatCEP (field, event) }


/*
 * Formata o campo telefone a medida que o usuario preenche os valores
 * Parametros:
 * - field: campo a ser preenchido
 * - character: tecla pressionada
 *
 * USAGE: onkeypress="return formatPhone (this,event);"
 */
function formatPhone (field, event) {

    var myfield = field.value;

    var keyCode = event.keyCode;
    var charCode = event.charCode;
    
    var deleteKey = false;
    var backspaceKey = false;
    var moveKey = false;
    
    if (keyCode==46 && charCode==0) deleteKey = true;
    if (keyCode==8 && charCode==0) backspaceKey = true;
    if (((keyCode>=33 && keyCode<=40) || keyCode==9) && charCode==0) moveKey = true;
    
    var tecla = charCode ? charCode : keyCode;
    if(document.selection) {
 
	    var testRange = document.selection.createRange().text;
	    if((tecla>=48 && tecla<=57) && testRange.length > 0) {
	    	return true;
	    }
    }
    else if ((tecla>=48 && tecla<=57) && field.selectionStart < field.selectionEnd) {
	    return true;
	}
	
    var caretPos = getCaretPosition(field);

	if (deleteKey || backspaceKey || moveKey) {
		return true;
	}
	
	if (myfield.length>10) {
		return false;
	}
	
	

	if (tecla==45 || (tecla>=48 && tecla<=57)) {
	    if ((tecla==45 && caretPos==4 && (myfield.charAt(3)!='-' || myfield.charAt(4)!='-')) ||
	    	(tecla==45 && caretPos==3 && (myfield.charAt(3)!='-' || myfield.charAt(4)!='-'))) {
	      	return true;
	    } else if (myfield.length>=3 && myfield.length<8 && tecla!=45) {
	    	var index = caretPos>=3 ? 3 : 2;
	    	myfield = myfield.replace(/\-/g,'');
	       	myfield = myfield.substring(0,index)+'-'+myfield.substring(index,myfield.length);
	       	field.value = myfield;
	       	setCaretPosition(field,caretPos==3 ? caretPos+1 : caretPos);
	       	return true;
	    } else if (myfield.length>=8 && tecla!=45) {
	    	var index = caretPos>=4 ? 4 : 3;
	    	myfield = myfield.replace(/\-/g,'');
	    	myfield = myfield.substring(0,index)+'-'+myfield.substring(index,myfield.length);
	    	field.value = myfield;
	    	setCaretPosition(field,caretPos==4 ? caretPos+1 : caretPos);
	    	return true;
	    } else if (tecla>=48 && tecla<=57) {
	       	return true;
	    }
	    return false;
	}
	return false;
}


/*
 * Formata o campo data a medida que o usuario preenche os valores
 * Parametros:
 * - field: campo a ser preenchido
 * - character: tecla pressionada
 *
 * USAGE: onkeypress="return formatDate (this,event);"
 */
function formatDate (field, event) {
    var myfield = field.value;

    var keyCode = event.keyCode;
    var charCode = event.charCode;
    
    var deleteKey = false;
    var backspaceKey = false;
    var moveKey = false;
    
    if (keyCode==46 && charCode==0) deleteKey = true;
    if (keyCode==8 && charCode==0) backspaceKey = true;
    if (((keyCode>=33 && keyCode<=40) || keyCode==9) && charCode==0) moveKey = true;
    
    var tecla = charCode ? charCode : keyCode;
    if(document.selection) {
 
	    var testRange = document.selection.createRange().text;
	    if((tecla>=48 && tecla<=57) && testRange.length > 0) {
	    	return true;
	    }
    }
    else if (tecla>=48 && tecla<=57 && field.selectionStart < field.selectionEnd) {
    	return true;
    }
    
    var caretPos = getCaretPosition(field);

	if (deleteKey || backspaceKey || moveKey) {
		return true;
	}
	
	if (myfield.length>9) {
		return false;
	}
	
	

	if (tecla==47 || (tecla>=48 && tecla<=57)) {
		if ((tecla==47 && caretPos==2) || //
			(tecla==47 && caretPos==5)) { //tecla = '/' e cursor no lugar certo
			myfield = myfield.replace(/(\/)/g,'');
	       	myfield = myfield.substring(0,2)+(caretPos==2 ? '' : '/')+ //this line: day
	       				(myfield.length>2 ? myfield.substring(2,4)+(myfield.length>4 ? (caretPos==5 ? '' : '/') : '') : '')+ //this line: month
	       				(myfield.length>4 ? myfield.substring(4,8) : '');//this line: year
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos);
	       	return true;
		} else if (tecla==47 && caretPos==1) { //tecla='/' e cursor no lugar da unidade do dia
	    	myfield = myfield.replace(/(\/)/g,'');
	       	myfield = '0'+myfield.substring(0,1)+ //this line: day
	       				(myfield.length>2 ? myfield.substring(1,3)+(myfield.length<4 ? '' : '/') : '')+ //this line: month
	       				(myfield.length>3 ? myfield.substring(3,7) : '');//this line: year
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos+1);
	       	return true;
		} else if (tecla==47 && caretPos==4) { //tecla='/' e cursor no lugar da unidade do mes
	    	myfield = myfield.replace(/(\/)/g,'');
	       	myfield = myfield.substring(0,2)+'/'+ //this line: day
	       				'0'+myfield.substring(2,3)+//this line: month
	       				(myfield.length>3 ? myfield.substring(3,7) : '');//this line: year
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos+1);
	       	return true;
		} else if (tecla>=48 && tecla<=57 && caretPos<myfield.length) { //cursor no meio
			var indexDay = caretPos<2 ? 1 : 2;
			var indexMonth = (caretPos<5 && caretPos>=2) || indexDay==1 ? 3 : 4;
			myfield = myfield.replace(/(\/)/g,'');
			myfield = myfield.substring(0,indexDay)+(myfield.length>indexDay ? '/' : '')+
	       				(myfield.length>=indexDay ? myfield.substring(indexDay,indexMonth)+(myfield.length>indexMonth ? '/' : '') : '')+ //this line: month
	       				(myfield.length>=indexMonth ? myfield.substring(indexMonth,7) : '');//this line: year
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos==2 || caretPos==5 ? caretPos+1 : caretPos);
	       	return true;
		} else if (tecla>=48 && tecla<=57) {
			myfield = myfield.replace(/(\/)/g,'');
			myfield = myfield.substring(0,2)+(myfield.length>=2 ? '/' : '')+
	       				(myfield.length>=2 ? (myfield.length<4 ? myfield.substring(2,4) : myfield.substring(2,4)+'/') : '')+ //this line: month
	       				(myfield.length>=4 ? myfield.substring(4,8) : '');//this line: year
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos+1);
	       	return true;
		}
		return false;
	}
	return false;
}
 

/*
 * Formata o campo cpf quando perde o foco
 * Parametros:
 * - field: campo a ser preenchido
 *
 * USAGE: onblur="blurCPF (this);"
 */
function blurCPF (field) {
	
	if (field!=null) {
		var v = field.value;
		if (v.length >= 6) {
			v = v.replace(/[^0-9]/g,'');
			v = v.substring(0,11);
			if (v.length<11) {
				while (v.length!=11) {
					v = '0'+v;
				}
			}
			v = v.substring(0,3)+'.'+v.substring(3,6)+'.'+v.substring(6,9)+'-'+v.substring(9,11);
			field.value = v;
		}
	}
}


/*
 * Formata o campo cpf quando perde o foco
 * Parametros:
 * - field: campo a ser preenchido
 *
 * USAGE: onblur="blurCEP (this);"
 */
function blurCEP (field) {
	
	if (field!=null) {
		var v = field.value;
		v = v.replace(/[^0-9]/g,'');
		if (v.length == 8) {
			v = v.substring(0,5)+'-'+v.substring(5,8);
			field.value = v;
		}
	}
}
			

/*
 * Formata o campo cpf a medida que o usuario preenche os valores
 * Parametros:
 * - field: campo a ser preenchido
 * - character: tecla pressionada
 *
 * USAGE: onkeypress="return formatCPF (this,event);"
 */
function formatCPF (field, event) {
    var myfield = field.value;

    var keyCode = event.keyCode;
    var charCode = event.charCode;
    
    var deleteKey = false;
    var backspaceKey = false;
    var moveKey = false;
    var tecla = charCode ? charCode : keyCode;
    if(document.selection) {
 
	    var testRange = document.selection.createRange().text;
	    if((tecla>=48 && tecla<=57) && testRange.length > 0) {
	    	return true;
	    }
    }
    else if ((tecla>=48 && tecla<=57) && field.selectionStart < field.selectionEnd) {
    	return true;
    }
    
    if (keyCode==46 && charCode==0) deleteKey = true;
    if (keyCode==8 && charCode==0) backspaceKey = true;
    if (((keyCode>=33 && keyCode<=40) || keyCode==9) && charCode==0) moveKey = true;
    
    var caretPos = getCaretPosition(field);

	if (deleteKey || backspaceKey || moveKey) {
		return true;
	}
	
	if (myfield.length>13) {
		return false;
	}

	

	if (tecla==45 || tecla==46 || (tecla>=48 && tecla<=57)) {
		if (tecla==46 && (caretPos==3 || caretPos==7)) {
			myfield = myfield.replace(/[\.\-]/g,'');
	       	myfield = myfield.substring(0,3)+(caretPos==3 ? '' : '.')+
	       				(myfield.length>3 ? myfield.substring(3,6)+(myfield.length>6 ? (caretPos==7 ? '' : '.') : '') : '')+
	       				(myfield.length>6 ? myfield.substring(6,9)+(myfield.length>9 ? '-' : '') : '')+
	       				(myfield.length>9 ? myfield.substring(9,11) : '');
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos);
	       	return true;
		} else if (tecla==45 && caretPos==11) {
			myfield = myfield.replace(/[\.\-]/g,'');
	       	myfield = myfield.substring(0,3)+'.'+
	       				myfield.substring(3,6)+'.'+
	       				myfield.substring(6,9)+
	       				(myfield.length>9 ? myfield.substring(9,11) : '');
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos);
	       	return true;
		} else if (tecla>=48 && tecla<=57 && caretPos<myfield.length) {
			var index1 = caretPos<3 ? 2 : 3;
			var index2 = (caretPos>=3 && caretPos<7) || index1==2 ? 5 : 6;
			var index3 = (caretPos>=7 && caretPos<11) || index1==2 || index2==5 ? 8 : 9;
			var index4 = (caretPos>=11 && caretPos<14) || index1==2 || index2==5 || index3==8 ? 10 : 11
			myfield = myfield.replace(/[\.\-]/g,'');
	       	myfield = myfield.substring(0,index1)+(myfield.length>index1 ? '.' : '')+
	       				(myfield.length>index1 ? myfield.substring(index1,index2)+(myfield.length>index2 ? '.' : '') : '')+
	       				(myfield.length>index2 ? myfield.substring(index2,index3)+(myfield.length>index3 ? '-' : '') : '')+
	       				(myfield.length>index3 ? myfield.substring(index3,index4) : '');
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos==3 || caretPos==7 || caretPos==11 ? caretPos+1 : caretPos);
	       	return true;
		} else if (tecla>=48 && tecla<=57) {
			myfield = myfield.replace(/[\.\-]/g,'');
	       	myfield = myfield.substring(0,3)+(myfield.length>=3 ? '.' : '')+
	       				(myfield.length>3 ? myfield.substring(3,6)+(myfield.length>=6 ? '.' : '') : '')+
	       				(myfield.length>6 ? myfield.substring(6,9)+(myfield.length>=9 ? '-' : '') : '')+
	       				(myfield.length>9 ? myfield.substring(9,11) : '');
	       	field.value = myfield;
	       	setCaretPosition(field, caretPos+1);
	       	return true;
		}
		return false;		
	}
	return false;
}


/*
 * Formata campos de valor monetario a medida que o usuario preenche os valores
 * Parametros:
 * - field: campo a ser preenchido
 * - character: tecla pressionada
 *
 * USAGE: onkeypress="return formatPhone (this,event);"
 */
function formatMoney (field, event) {

    var myfield = field.value;

    var keyCode = event.keyCode;
    var charCode = event.charCode;
    
    var deleteKey = false;
    var backspaceKey = false;
    var moveKey = false;
    
    if (keyCode==46 && charCode==0) deleteKey = true;
    if (keyCode==8 && charCode==0) backspaceKey = true;
    if (((keyCode>=33 && keyCode<=40) || keyCode==9) && charCode==0) moveKey = true;
    
    var caretPos = getCaretPosition(field);

	if (deleteKey || backspaceKey || moveKey) {
		return true;
	}
	
	if (myfield.length>10) {
		return false;
	}

	var tecla = charCode ? charCode : keyCode;
	if(document.selection) {
 
	    var testRange = document.selection.createRange().text;
	    if((tecla>=48 && tecla<=57) && testRange.length > 0) {
	    	return true;
	    }
    }
    else if ((tecla>=48 && tecla<=57) && field.selectionStart < field.selectionEnd) {
    	return true;
    }

	if (tecla==44 || (tecla>=48 && tecla<=57)) {
		if (tecla==44 && myfield.replace(/\d/g,'').length==0 && myfield.length>0) {
			return true;
		} else if ((tecla>=48 && tecla<=57) && 
				   (myfield.length-(myfield.lastIndexOf(',')!=-1?myfield.lastIndexOf(','):100)<=2)) {
			return true;
		} else if ((tecla>=48 && tecla<=57) &&
				   (myfield.lastIndexOf(',')==-1 || caretPos<(myfield.lastIndexOf(',')+1))) {
			return true;
		}
		return false;
	}
	return false;
}


/*
 * Funcao que valida campos obrigatorios
 * Parametros:
 *  - field: campo a ser testado
 *  - name: nome do campo para a mensagem de erro
 *
 * USAGE: message += validateRequired (field, 'Cartao de Credito');
 */
function validateRequired (field, name) {
	if (field==null || field.value==null || field.value=='')
		return '<br />Campo "'+name+'" é obrigatório e não foi preenchido.';
	return '';
}
 

/*
 * Funcao que utiliza as outras funcoes de validacao para colorir o input
 * Parametros:
 *  - field: campo a ser testado
 *  - type: tipo de validacao
 *
 * USAGE: onblur="validateField(this, 'umtipo');
 */
function validateField (field, type) {

    var valid = true;
    var errors = '';
    switch (type) {
        case 'cep': errors = validateCEP(field.value); break;
        case 'email': errors = validateEmail(field.value); break;
        case 'name' : errors = validateName(field.value); break;
        case 'date' : errors = validateDate(field.value); break;
        case 'cpf' : valid = validateCPF(field.value); if (!valid) errors+='<br />CPF inválido.'; break;
        case 'user' : errors = validateUsername(field.value); break;
        case 'pass' : errors = validatePassword(field.value); break;
        case 'int' : errors = validateInteger(field.value); break;
        case 'cc' : errors = validateCreditCard(field.value); break;
        case 'ccdate' : errors = validateExpirationDate(field.value); break;
        case 'money' : errors = validateMoney(field.value); break;
        case 'age' : errors = validateAge(field.value); break;
        case 'phone' : errors = validatePhone(field.value); break;
        case 'ddd' : errors = validateDDD(field.value); break;
        case 'ALFANUMÉRICO' : errors = validateAlphanumerical(field.value); break; //alfanumericos
        case 'ALFABÉTICO' : errors = validateAlphabetical(field.value); break;
        case 'NUMÉRICO' : erros = validateInteger(field.value); break;
        case 'mesAno' : errors = validateMesAno(field); break;
        case 'horaMinuto' : errors = validaHora(field); break;
        case 'none' : break;         
        default : break;
    }

    if (errors.length>0) {
        field.style.borderColor='';
        alertaMensagem("Atenção!","Mensagem de Erro",errors);                
        field.value = '';
    } else {
        field.style.borderColor='';
    }
    
    return errors;
}

function validateMesAnoAtual(field, type,diaAtual,mesAtual,anoAtual){
	
	if(validateField(field, 'mesAno') == true){
		mes = parseInt(field.value.split("/")[0],10);
		ano = parseInt(field.value.split("/")[1],10);		
		if((ano < anoAtual) || (ano == anoAtual && mes < mesAtual)){
			field.style.borderColor='red';
			field.value = "";
			alertaMensagem("Atenção!","Mensagem de Erro",'Data anterior à data atual.');			
		}
	}	
}

function evaluateField (field, type) {

    var valid = true;
    var errors = '';
    switch (type) {
        case 'cep': errors = validateCEP(field.value); break;
        case 'email': errors = validateEmail(field.value); break;
        case 'name' : errors = validateName(field.value); break;
        case 'date' : errors = validateDate(field.value); break;
        case 'cpf' : valid = validateCPF(field.value); if (!valid) errors+='<br />CPF inválido.'; break;
        case 'user' : errors = validateUsername(field.value); break;
        case 'pass' : errors = validatePassword(field.value); break;
        case 'int' : errors = validateInteger(field.value); break;
        case 'cc' : errors = validateCreditCard(field.value); break;
        case 'ccdate' : errors = validateExpirationDate(field.value); break;
        case 'money' : errors = validateMoney(field.value); break;
        case 'age' : errors = validateAge(field.value); break;
        case 'phone' : errors = validatePhone(field.value); break;
        case 'ddd' : errors = validateDDD(field.value); break;
        case 'ALFANUMÉRICO' : errors = validateAlphanumerical(field.value); break; //alfanumericos
        case 'ALFABÉTICO' : errors = validateAlphabetical(field.value); break;
        case 'NUMÉRICO' : erros = validateInteger(field.value); break;
        case 'mesAno' : errors = validateMesAno(field); break;
        case 'horaMinuto' : errors = validaHora(field); break;
        case 'none' : break;
        default : break;
    }
    
    if (errors.length > 0 && arguments.length==3) {
    	return '<br />'+arguments[2];
    }
   	return errors;
}

function validateCPF (cpf) {
    
    var errors = '';
    
    if (cpf.length == 0) {
	return true;
    }
    
    var i;
    var c;
    var x = 0;
    var soma = 0;
    var dig1 = 0;
    var dig2 = 0;
    var texto = '';
    var numcpf1='';
    var numcpf = '';

    cpflimp = krLIMP(cpf);

    if (cpflimp.length != 11) {
        return false;
    } else if (cpflimp == '00000000000' || cpflimp == '11111111111' || cpflimp == '22222222222' || cpflimp == '33333333333') {
        return false;
    } else if (cpflimp == '44444444444' || cpflimp == '55555555555' || cpflimp == '66666666666') {
        return false;
    } else if (cpflimp == '77777777777' || cpflimp == '88888888888' || cpflimp == '99999999999' || cpflimp == '12345678909') {
        return false;
    } else {
        
        for (i = 0; i < cpf.length; i++) {
            c = cpf.substring(i,i+1);
            if (/\d/.test(c)) {
                numcpf = numcpf + c;
            }
        }

        if (numcpf.length != 11) {
            return false;
        }


        len = numcpf.length; x = len -1;
        for (var i=0; i <= len - 3; i++) {
            y = numcpf.substring(i,i+1);
            soma = soma + ( y * x);
            x = x - 1;
            texto = texto + y;
        }
        
        dig1 = 11 - (soma % 11);
        if (dig1 == 10) {
            dig1=0;
        }
        
        if (dig1 == 11) {
            dig1=0;
        }
        
        numcpf1 = numcpf.substring(0,len - 2) + dig1 ;
        x = 11;
        soma=0;
        for (var i=0; i <= len - 2; i++) {
            soma = soma + (numcpf1.substring(i,i+1) * x);
            x = x - 1;
        }
        
        dig2 = 11 - (soma % 11);
        if (dig2 == 10) dig2=0;
        if (dig2 == 11) dig2=0;
        if ((dig1 + "" + dig2) == numcpf.substring(len,len-2)) {
            return true;
        }
        return false;
    }
}

function validateDate (date) {

    var errors = '';
    
   	if (date.length==0)
   		return '';
    
    var dateRE = new RegExp('(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4})'); //dd/MM/yyyy
    
    if (!dateRE.test(date)){
        errors += '<br />Formato de data incorreto.';
        return errors;
    }
    
    var day = RegExp.$1;
    var month = RegExp.$2;
    var year = RegExp.$3;
    
    with (new Date(year, --month, day)) {
        if (!(getMonth()==month && getFullYear()==year)) {
            errors+='<br />Data inválida.';
            return errors;
        }
    }

    return errors;
}

function validateCEP (zip) {

    var errors = '';
    
    if (zip.length==0)
    	return '';
    
    var zipRE = new RegExp('^(?:\\d{5}\\-\\d{3})$'); //nnnnn-nnn
    
    if (!zipRE.test(zip)){
        errors += '<br />CEP inválido.';
        return errors;
    }
    
    return errors;
}

function validateZIP (cep) {

    return validateCEP(cep);
}

function validateUsername (username) {

    var errors = '';

   	if (username.length==0)
   		return '';
    
    var usernameRE = new RegExp('(?:[a-zA-Z0-9\\.\\_]+)');
    
    if (!usernameRE.test(username)){
        errors += 'Nome de usuário inválido.';
        return errors;
    }
    
    return errors;
}

function validatePassword (password) {

    var errors = '';

   	if (password.length==0)
   		return '';
    
    var passwordRE = new RegExp('([0-9]{0,8})');
    
    if (!passwordRE.test(password)){
        errors += 'Senha inválida.';
        return errors;
    }
    
    return errors;
}

function validateAge (age) {

    var errors = '';
    
    if (age.length==0)
    	return '';
    
    var ageRE = /^1?\d?\d$/
    
    if (!ageRE.test(age)) {
        errors += '<br />Idade inválida.';
        return errors;
    }
    
    return errors;
}

function validateInteger (integer) {

    var errors = '';
    
    if (integer.length==0)
    	return '';
    
    var integerRE = new RegExp('^(?:\\-?\\d*)$');
    
    if (!integerRE.test(integer)) {
        errors += '<br />Número inválido.';
        return errors;
    }
    
    return errors;
}

function validateExpirationDate (expireDate) {

    var errors = '';
    
    if (expireDate.length==0)
    	return '';

    var expireDateRE = new RegExp('(\\d{1,2})\\/(\\d{4})'); //MM/yyyy
    
    if (!expireDateRE.test(expireDate)){
        errors += '<br />Formato de data incorreto.';
        return errors;
    }
    
    var day = 1;
    var month = RegExp.$1;
    var year = RegExp.$2;
    
    with (new Date(year, --month, day)) {
        if (!(getMonth()==month && getFullYear()==year)) {
            errors+='<br />Data inválida.';
            return errors;
        }
    }

    return errors;
}

function validateCreditCard (creditCard) {

    var errors = '';
    
    if (creditCard.length==0)
    	return '';
    
    var checksum = 0;
    var x = 0;
    var s = '';
    var invCC;
    
    for (var i = 0; i < creditCard.length; i++) {
    	invCC[i] = creditCard[creditCard.length-i-1];
    }
    
    for (var i = 0; i < invCC.length; i++) {
        if (i%2!=0) {
            checksum += (creditCard.charAt(i)*1);
        } else {
            x = creditCard.charAt(i)*2;
            if (x >= 10) {
               s = x.toString();
               checksum += (s.charAt(0)*1) + (s.charAt(1)*1);
            } else {
                checksum += (x*1);
            }
        }
    }
    
    if (checksum%10!=0) {
        errors += '<br />Número de cartão de crédito inválido.';
        return errors;
    }
    return errors;
}

function validateEmail (email) {

    var errors = '';
    
    if (email.length==0)
    	return '';
    
    var emailRE = /\w+((-\w+)|(\.\w+)|(\_\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]{2,5}/;
    
    if (!emailRE.test(email)) {
        errors += '<br />E-mail inválido.';
        return errors;
    }
    return errors;
}

function validateName (name) {

    var errors = '';
    
    if (name.length==0)
    	return '';

    var nameRE = /.*/;
    
    if (!nameRE.test(name)) {
        errors += '<br />Nome inválido.';
        return errors;
    }
    return errors;
}

function validateDDD (ddd) {

    var errors = '';
    
    if (ddd.length==0)
    	return '';
    
    var dddRE = /^\d{2}$/;
    
    if (!dddRE.test(ddd)){
        errors += '<br />DDD inválido.';
        return errors;
    }
    
    return errors;
}

function validateDouble (number) {

    var errors = '';
    
    if (number.length==0)
    	return '';
    
    var doubleRE = /^\s*\-?\s*\d+(\.\d+)?$/
    
    if (!doubleRE.test(number)) {
        errors += '<br />Número inválido.';
        return errors;
    }
    return errors;
}

function validateMoney (money) {
    
    var errors = '';
    
    if (money.length==0)
    	return '';
    
    var moneyRE = /^\s*\d+(\,\d\d)?$/
    
    if (!moneyRE.test(money)) {
        errors += '<br />Valor em dinheiro inválido.';
        return errors;
    }
    return errors;
}

function validatePhone (phone) {

    var errors = '';
    
    if (phone.length==0)
    	return '';
    
    var phoneRE = /^\s*(\d{3,4})\-\d{4,}$/;
    
    if (!phoneRE.test(phone)) {
        errors += '<br />Telefone inválido.';
        return errors;
    }
    return errors;
}

function validateAlphanumerical (value) {

    var errors = '';
    
    if (value.length==0)
    	return '';
    
    var alphaBRE = /[^a-zA-Z0-9]/;
    
    if (!alphaNRE.test(value)) {
        errors += '<br />Campo de validação inválido.';
        return errors;
    }
    return errors;
}

function validateNumeroDocumento (value) {

    var errors = '';
    
    if (value.length==0)
    	return '';
    
    var apenasNumeros = /[0-9]/;
    
    if (apenasNumeros.test(value)) {
        errors += '<br />Campo de validação inválido.';
        return errors;
    }
    return errors;
}

function validateAlphabetical (value) {

    var errors = '';
    
    if (value.length==0)
    	return '';
    
    var alphaBRE = /[^a-zA-Z]/;    
    
    if (!alphaBRE.test(value)) {
        errors += '<br />Campo de validação inválido.';
        return errors;
    }
    return errors;
}



function checkAndSubmit() {

	var message = '';

	var a = Math.floor((arguments.length-1)/3);
	
	if (arguments.length<1) return;
	
	var formToSubmit = arguments[0];
	
	var fieldsToCheck = new Array(Math.floor((a-1)/3));
	
	var j = 1;
	for (var i = 0; i < a; i++) {
		fieldsToCheck[i] = new Array(3);
		fieldsToCheck[i][0] = arguments[j++];
		fieldsToCheck[i][1] = arguments[j++];
		fieldsToCheck[i][2] = arguments[j++];
	}

	for (var i = 0; i < fieldsToCheck.length; i++) {
		var field = document.getElementsByName(fieldsToCheck[i][0])[0];
		
		if ((field==null || trim(field.value)=='') && trim(fieldsToCheck[i][1])!='') {
			message += '<br />Campo \''+fieldsToCheck[i][1]+'\' não está preenchido.';
		} else {
			message += evaluateField(field, fieldsToCheck[i][2]);
		}
	}
		
	if (message.length>0) {
		alertaMensagem("Atenção!","Mensagem de Erro",message);				
	} else {
		document.forms[formToSubmit].submit();
  	}
}


/*
 * Funcao para comparar campos
 * Parametros:
 *  - fieldName1: nome do primeiro campo
 *  - fieldName2: nome do segundo campo
 *  - divName: nome da div com o texto de invalido
 *
 * USAGE: onblur="compareFields('campo1','campo2','txtCampo');"
 */
function compareFields (fieldName1, fieldName2, divName) {
	field1 =gebi(fieldName1);
	field2 =gebi(fieldName2);
	if (field1!=null && field2!=null && trim(field1.value)!='' && trim(field2.value)!='') {
		if (field1.value!=field2.value) {
			gebi(divName).style.display='block';
		} else {
			gebi(divName).style.display='none';
		}
	}
}


/*
 * Funcao para checar tamanho do campo
 * Parametros:
 *  - fieldName: nome do campo
 *  - divName: nome da div com o texto de invalido
 *
 * USAGE: onblur="checkSize('campo',6,'txtCampo');"
 */
function checkSize (fieldName, size, divName) {
	field =gebi(fieldName);
	if (field!=null && trim(field.value)!='') {
		if (field.value.length<size) {
			gebi(divName).style.display='block';
		} else {
			gebi(divName).style.display='none';
		}
	}
}


/*
 * Funcao para dar submit NO FORM DO CADASTRO DE CLIENTE
 * Parametros:
 *  - 
 *
 * USAGE: onclick="checkAndSubmitRegistration();"
 */
var alterarCepPressed = true;
function setAlterarCepPressed(value) {
	alterarCepPressed = value;
}


function validaDadosEnderecoClienteCompra() {
	var message = '';
	var val = '';
	var req = '';
	
	if (gebi('localidade') == null) {
		alertaMensagem("Atenção!","Mensagem de Erro",'Por favor, clique em "Verificar" antes de continuar.');		
		return;	
	}
	
	
	
	var logradouro =gebi('logradouro');
	if (logradouro.options != null){	
		if (logradouro.options[logradouro.selectedIndex].value=='') {
			req += '<br />Por favor, escolha uma opção do menu "Endereço".';
		}
	}
	
	
	
	
	val += evaluateField(gebi('cadastroClienteEnderecoNumero'),'int','Campo "Endereço - Número" inválido.');
	req += validateRequired(gebi('cadastroClienteEnderecoNumero'),'Endereço - Número');


//	val += evaluateField(gebi('cadastroClienteDdd'),'ddd','Campo "Telefone - DDD" inválido.');
//	req += validateRequired(gebi('cadastroClienteDdd'),'Telefone - DDD');

//	val += evaluateField(gebi('cadastroClienteTelefone'),'phone','Campo "Telefone " inválido.');
//	req += validateRequired(gebi('cadastroClienteTelefone'),'Telefone');
		
	message += val;
	message += req;
	if (message.length>0) {
		alertaMensagem("Atenção!","Mensagem de Erro",message);		
		return false;
	} 
	return true;
}

function mudaFormularioCliente(acao){
	gebi("formCliente").action = acao;
	gebi("formCliente").submit();
}

function validaDadosEnderecoCliente() {
	var message = '';
	var val = '';
	var req = '';
	
	if (gebi('localidade') == null) {
		alertaMensagem("Atenção!","Mensagem de Erro",'Por favor, clique em "Verificar" antes de continuar.');				
		return;	
	}
	
	
	
	var logradouro =gebi('logradouro');
	if (logradouro.options != null){	
		if (logradouro.options[logradouro.selectedIndex].value=='') {
			req += '<br />Por favor, escolha uma opção do menu "Endereço".';
		}
	}
	
	var cep1 = gebi('cadastroClienteCep1');
	var cep2 = gebi('cadastroClienteCep2');
	var cep = document.createElement("input");
	
	cep.value = cep1.value+'-'+cep2.value;
	
	val += evaluateField(cep,'cep','Campo "CEP" inválido.');
	req += validateRequired(cep,'CEP');
	
	
	val += evaluateField(gebi('cadastroClienteEnderecoNumero'),'int','Campo "Endereço - Número" inválido.');
	req += validateRequired(gebi('cadastroClienteEnderecoNumero'),'Endereço - Número');


	//val += evaluateField(gebi('cadastroClienteDdd'),'ddd','Campo "Telefone - DDD" inválido.');
//	req += validateRequired(gebi('cadastroClienteDdd'),'Telefone - DDD');

	//val += evaluateField(gebi('cadastroClienteTelefone'),'phone','Campo "Telefone " inválido.');
	//req += validateRequired(gebi('cadastroClienteTelefone'),'Telefone');
		
	message += val;
	message += req;
	if (message.length>0) {
		alertaMensagem("Atenção!","Mensagem de Erro",message);
		return false;
	} 
	return true;
}

function checkAndSubmitRegistration() {
	document.getElementById('botaoCadFinal').style.display = 'none';
	document.getElementById('carregandoDiv').style.display = 'block';
	var message = '';

	var val = '';
	var req = '';

	/*
	if (!alterarCepPressed) {
		alert('Por favor, atualize as informações de CEP antes de continuar.');
		return;	
	}
	
	
	if (gebi('erroLocalidade')!=null) {
		alert('Seu CEP não retornou nenhuma cidade.');
		return;
	}
	if (gebi('erroLogradouro')!=null) {
		alert('Seu CEP não retornou nenhum logradouro.');
		return;
	}
	*/
	val += evaluateField(gebi('nome'),'name','Campo "Nome" inválido.');
	req += validateRequired(gebi('nome'),'Nome');
	
	val += evaluateField(gebi('cpf'),'cpf','Campo "CPF" inválido.');
	req += validateRequired(gebi('cpf'),'CPF');
	
	val += evaluateField(gebi('dataNascimento'),'date','Campo "Data de Nascimento" inválido.');
	req += validateRequired(gebi('dataNascimento'),'Data de Nascimento');
	
	
	/*		
	var logradouro =gebi('logradouro');
	if (logradouro.options != null){	
		if (logradouro.options[logradouro.selectedIndex].value=='') {
			req += '\nPor favor, escolha uma opção do menu "Endereço".';
		}
	}
	*/
	/*
	var nasc =gebi('sexo');
	if (nasc.options[nasc.selectedIndex].value==-1) {
		req += '\nPor favor, escolha uma opção do menu "Sexo".';
	}
	*/
	
	var sexoM = gebi('sexoM');
	var sexoF = gebi('sexoF');
	if( sexoM.checked == false && sexoF.checked == false)
		req += '<br />Campo "Sexo" é obrigatório e não foi preenchido.';
	
	var senhaReq = validateRequired(gebi('senha'),'Senha');
	var confSenhaReq = validateRequired(gebi('confirmarSenha'),'Confirmar Senha');
	
	req += senhaReq;
	req += confSenhaReq;
	
	if (gebi('senha').value.length > 0 ) {  
	  var senhaVal = senhaReq=='' &&gebi('senha')!=null &&gebi('senha').value.length<6 ? '<br />Campo "Senha" deve ter no mínimo 6 caracteres.' : evaluateField(gebi('senha'),'pass','Campo "Senha" inválido.');
	  var confSenhaVal = confSenhaReq=='' &&gebi('confirmarSenha')!=null &&gebi('confirmarSenha').value.length<6 ? '<br />Campo "Confirmar Senha" deve ter no mínimo 6 caracteres.' : evaluateField(gebi('confirmarSenha'),'pass','Campo "Confirmar Senha" inválido.');
	  var senhaEq = (	senhaReq=='' && confSenhaReq=='' &&
					senhaVal=='' && confSenhaVal=='' &&
					gebi('senha').value!=gebi('confirmarSenha').value ) ? '<br />Campos "Senha" e "Confirmar Senha" não conferem.' : '';
	  val += senhaVal;
	  req += senhaReq;
	  val += confSenhaVal;
	  req += confSenhaReq;
	  message += senhaEq;
	}

	
	val += evaluateField(gebi('cadastroClienteDdd'),'ddd','Campo "Telefone - DDD" inválido.');
	req += validateRequired(gebi('cadastroClienteDdd'),'Telefone - DDD');

	val += evaluateField(gebi('cadastroClienteTelefone'),'phone','Campo "Telefone" inválido.');
	req += validateRequired(gebi('cadastroClienteTelefone'),'Telefone');
	
	/*
	val += evaluateField(gebi('cadastroClienteCep'),'cep','Campo "CEP" inválido.');
	req += validateRequired(gebi('cadastroClienteCep'),'CEP');
	
	
	val += evaluateField(gebi('cadastroClienteEnderecoNumero'),'int','Campo "Endereço - Número" inválido.');
	req += validateRequired(gebi('cadastroClienteEnderecoNumero'),'Endereço - Número');
	
		
	gebi('telefone2').value = trim(gebi('telefone2').value);gebi('dddTelefone2').value = trim(gebi('dddTelefone2').value);
	if (gebi('telefone2').value!='' ||gebi('dddTelefone1').value!='') {
		val += evaluateField(gebi('telefone2'),'phone','Campo "Telefone 2" inválido.');
		
		val += evaluateField(gebi('dddTelefone2'),'ddd','Campo "Telefone 2 - DDD" inválido.');
	}
	*/
	
	val += evaluateField(gebi("email"),'email','Campo E-mail');
	req += validateRequired(gebi('email'),'E-mail');
	if(gebi("email").value !=gebi("confirmarEmail").value){		
		val += "<br />Campos E-mail e Confirmar E-mail não conferem.";
	}
		
	req += validateRequired(gebi('confirmarEmail'),'Confirmar E-mail');
	
	var contador = parseInt(gebi("linkAdicionar").getAttribute("contadorEmails"));
	for (var i=1; i<contador; i++) {
		if((gebi("email"+i).value != "" ||gebi("confirmarEmail"+i).value != "")){
			val += evaluateField(gebi("email"+i),'email','Campo "E-mail Alternativo '+i+'" inválido.');
			val += evaluateField(gebi("confirmarEmail"+i),'email','Campo "Confirmar E-mail Alternativo '+i+'" inválido.');
			if(gebi("email"+i).value !=gebi("confirmarEmail"+i).value){
				val += '<br />Campos "E-mail Alternativo '+i+'" e "Confirmar E-mail '+i+'" não conferem. Se não deseja utilizá-los, por favor deixe-os em branco.';
			}			
		}
	};
	
	message += val;
	message += req;
	if (message.length>0) {
		alertaMensagem("Atenção!","Mensagem de Erro",message);		
		document.getElementById('botaoCadFinal').style.display = 'block';
		document.getElementById('carregandoDiv').style.display = 'none';
		gebi('nome').focus();
		return;	
	} else if (document.getElementById('countEnderecos').value == '0' && !validaDadosEnderecoCliente()) {
		document.getElementById('botaoCadFinal').style.display = 'block';
		document.getElementById('carregandoDiv').style.display = 'none';
		return;
	} else {
		document.forms['formCliente'].submit();
  	}

}

function validaEditarCliente() {
	document.getElementById('botaoCadFinal').style.display = 'none';
	document.getElementById('carregandoDiv').style.display = 'block';
	var message = '';

	var val = '';
	var req = '';

	/*
	if (!alterarCepPressed) {
		alert('Por favor, atualize as informações de CEP antes de continuar.');
		return;	
	}
	
	
	if (gebi('erroLocalidade')!=null) {
		alert('Seu CEP não retornou nenhuma cidade.');
		return;
	}
	if (gebi('erroLogradouro')!=null) {
		alert('Seu CEP não retornou nenhum logradouro.');
		return;
	}
	*/
	val += evaluateField(gebi('nome'),'name','Campo "Nome" inválido.');
	req += validateRequired(gebi('nome'),'Nome');
	
	val += evaluateField(gebi('cpf'),'cpf','Campo "CPF" inválido.');
	req += validateRequired(gebi('cpf'),'CPF');
	
	val += evaluateField(gebi('dataNascimento'),'date','Campo "Data de Nascimento" inválido.');
	req += validateRequired(gebi('dataNascimento'),'Data de Nascimento');
	
	
	/*		
	var logradouro =gebi('logradouro');
	if (logradouro.options != null){	
		if (logradouro.options[logradouro.selectedIndex].value=='') {
			req += '\nPor favor, escolha uma opção do menu "Endereço".';
		}
	}
	*/
	

  /*
  var nasc =gebi('sexo');
  if (nasc.options[nasc.selectedIndex].value==-1) {
    req += '\nPor favor, escolha uma opção do menu "Sexo".';
  }
  */
	  
  var sexoM = gebi('sexoM');
  var sexoF = gebi('sexoF');
  if( sexoM.checked == false && sexoF.checked == false)
    req += '<br />Campo "Sexo" é obrigatório e não foi preenchido.';
	
	var senhaReq = validateRequired(gebi('senha'),'Senha');
	var confSenhaReq = validateRequired(gebi('confirmarSenha'),'Confirmar Senha');
	
	req += senhaReq;
	req += confSenhaReq;
	
	if (gebi('senha').value.length > 0 ) {  
	  var senhaVal = senhaReq=='' &&gebi('senha')!=null &&gebi('senha').value.length<6 ? '<br />Campo "Senha" deve ter no mínimo 6 caracteres.' : evaluateField(gebi('senha'),'pass','Campo "Senha" inválido.');
	  var confSenhaVal = confSenhaReq=='' &&gebi('confirmarSenha')!=null &&gebi('confirmarSenha').value.length<6 ? '<br />Campo "Confirmar Senha" deve ter no mínimo 6 caracteres.' : evaluateField(gebi('confirmarSenha'),'pass','Campo "Confirmar Senha" inválido.');
	  var senhaEq = (	senhaReq=='' && confSenhaReq=='' &&
					senhaVal=='' && confSenhaVal=='' &&
					gebi('senha').value!=gebi('confirmarSenha').value ) ? '<br />Campos "Senha" e "Confirmar Senha" não conferem.' : '';
	  val += senhaVal;
	  req += senhaReq;
	  val += confSenhaVal;
	  req += confSenhaReq;
	  message += senhaEq;
	}
	
	val += evaluateField(gebi('cadastroClienteDdd'),'ddd','Campo "Telefone - DDD" inválido.');
	req += validateRequired(gebi('cadastroClienteDdd'),'Telefone - DDD');

	val += evaluateField(gebi('cadastroClienteTelefone'),'phone','Campo "Telefone" inválido.');
	req += validateRequired(gebi('cadastroClienteTelefone'),'Telefone');
	
	
	/*
	val += evaluateField(gebi('cadastroClienteCep'),'cep','Campo "CEP" inválido.');
	req += validateRequired(gebi('cadastroClienteCep'),'CEP');
	
	
	val += evaluateField(gebi('cadastroClienteEnderecoNumero'),'int','Campo "Endereço - Número" inválido.');
	req += validateRequired(gebi('cadastroClienteEnderecoNumero'),'Endereço - Número');


	
		
	gebi('telefone2').value = trim(gebi('telefone2').value);gebi('dddTelefone2').value = trim(gebi('dddTelefone2').value);
	if (gebi('telefone2').value!='' ||gebi('dddTelefone1').value!='') {
		val += evaluateField(gebi('telefone2'),'phone','Campo "Telefone 2" inválido.');
		
		val += evaluateField(gebi('dddTelefone2'),'ddd','Campo "Telefone 2 - DDD" inválido.');
	}
	*/
	
	val += evaluateField(gebi("email"),'email','Campo E-mail');
	req += validateRequired(gebi('email'),'E-mail');
	if(gebi("email").value !=gebi("confirmarEmail").value){		
		val += "<br />Campos E-mail e Confirmar E-mail não conferem.";
	}
		
	req += validateRequired(gebi('confirmarEmail'),'Confirmar E-mail');
	/*
	var contador = parseInt(gebi("linkAdicionar").getAttribute("contadorEmails"));
	for (var i=1; i<contador; i++) {
		if((gebi("email"+i).value != "" ||gebi("confirmarEmail"+i).value != "")){
			val += evaluateField(gebi("email"+i),'email','Campo "E-mail Alternativo '+i+'" inválido.');
			val += evaluateField(gebi("confirmarEmail"+i),'email','Campo "Confirmar E-mail Alternativo '+i+'" inválido.');
			if(gebi("email"+i).value !=gebi("confirmarEmail"+i).value){
				val += '\nCampos "E-mail Alternativo '+i+'" e "Confirmar E-mail '+i+'" não conferem. Se não deseja utilizá-los, por favor deixe-os em branco.';
			}			
		}
	};
	*/
	
	
	
	message += val;
	message += req;
	if (message.length>0) {
		alertaMensagem("Atenção!","Mensagem de Erro",message);
		document.getElementById('botaoCadFinal').style.display = 'block';
		document.getElementById('carregandoDiv').style.display = 'none';
		gebi('nome').focus();
		return;	
	} else {
		document.forms['formCliente'].submit();
  	}

}




/*
 * Funcao para dar submit NO FORM DE PAGAMENTO
 * Parametros:
 *  - 
 *
 * USAGE: onclick="checkAndSubmitPayment();"
 */
var buttonPressed = false;
var secButtonPressed = false;
function checkAndSubmitPayment() {

	pgto = $("[name=tipoPagamento]:checked").val();
	
	if (pgto==null || pgto=='-1' || pgto==-1) {
		alertaMensagem("Atenção!","Mensagem de Erro",'não foi selecionada nenhuma forma de pagamento.');		
		return;
	}
	
	var message = '';
	
	switch (pgto) {
		case '51' : //credito
			message = '';
			//message += evaluateField(gebi('creditoCodigoVerificacao'), 'int', 'crédito - Código de Verificação inválido.');
			//message += evaluateField(gebi('creditoNumeroCartao'),'cc','crédito - Número do cartão inválido.);
			//message += validateRequired(gebi('creditoCodigoVerificacao'), 'crédito - Código de Verificação');
			message += validateRequired(gebi('creditoNumeroCartao'), 'crédito - Número do cartão');
			
			if (message.length>0) {
				alertaMensagem("Atenção!","Mensagem de Erro",message);				
				return;
			}	
		
			if (!buttonPressed) {
				alertaMensagem("Atenção!","Mensagem de Erro",'Por favor clique em VALIDAR para confirmar os dados do cartão de crédito.');
				return;
			} else {
				var parcelas = document.getElementsByName('parcelas');
				var selected = false;
				if (parcelas!=null && parcelas.length>0) {
					for (var i = 0; i < parcelas.length; i++) {
						if (parcelas[i].checked) {
							selected = true;
						}
					}
				}
				if (parcelas==null || parcelas.length==0) {
					alertaMensagem("Atenção!","Mensagem de Erro",'Por favor clique em VALIDAR para confirmar os dados do cartão de crédito.');
					return;
				} else if (!selected) {		
					alertaMensagem("Atenção!","Mensagem de Erro",'não foi selecionada nenhuma parcela para o cartão de crédito.');	
					return;
				}
			}
			break;
		
		case '32' : //dinheiro
			message = '';
			message += evaluateField(gebi('dinheiroValorPagamento'), 'money', 'Dinheiro - Valor do Pagamento inválido.');
			
			var testeReq = validateRequired(gebi('dinheiroValorPagamento'), 'Dinheiro - Valor do Pagamento');
			message += testeReq;
			
			var troco = document.getElementById('dinheiroTroco');
			if ((troco==null || trim(''+troco.value)=='') && testeReq=='') {
				message += '<br />Dinheiro - Valor de pagamento menor que o valor da compra.';
			}
			
			if (message.length>0) {
				alertaMensagem("Atenção!","Mensagem de Erro",message);
				return;
			}			
			break;
			
		case '46' : //resgate
			message = '';
			message += evaluateField(gebi('resgateNumeroCartao'), 'int', 'Resgate - Número do cartão inválido.');
			message += evaluateField(gebi('resgateCampoValidacao'),'cpf', 'Resgate - Campo de validação inválido.');
			message += validateRequired(gebi('resgateNumeroCartao'), 'Resgate - Número do cartão');
			message += validateRequired(gebi('resgateCampoValidacao'), 'Resgate - Campo de validação');
			
			if (message.length>0) {
				alertaMensagem("Atenção!","Mensagem de Erro",message);				
				return;
			}
			
			if (!buttonPressed) {
				alertaMensagem("Atenção!","Mensagem de Erro",message);								
				return;
			} else {
				if (gebi('semSaldo')!=null &&gebi('semSaldo').value=='true') {
					alertaMensagem("Atenção!","Mensagem de Erro",'você não possui saldo para Resgate.Por favor, escolha outra opção de pagamento.');
					return;			
				} else if (gebi('resgateValor')==null) {
					alertaMensagem("Atenção!","Mensagem de Erro",'Houve um erro na requisição de seus dados para Resgate.Por favor confira as informações preenchidas.');					
					return;
				} else {
					message = '';
					message += evaluateField(gebi('resgateValor'),'money','Resgate - Valor para Resgate inválido.');
					message += validateRequired(gebi('resgateValor'), 'Resgate - Valor para Resgate');
					
					if (message.length>0) {
						alertaMensagem("Atenção!","Mensagem de Erro",message);		
						return;
					}
				}
			}
			break;
			
		case '36' : //convenio
			message = '';
			message += evaluateField(gebi('convenioPrazoNumeroCartao'),'int', 'Convênio a Prazo - Número do cartão inválido.');
			message += evaluateField(gebi('convenioPrazoSenha'),'pass', 'Convênio a Prazo - Senha inválida.');
			message += validateRequired(gebi('convenioPrazoNumeroCartao'), 'Convênio a Prazo - Número do cartão');
			message += validateRequired(gebi('convenioPrazoSenha'),'Convênio a Prazo - Senha');

			if (message.length>0) {
				alertaMensagem("Atenção!","Mensagem de Erro",message);							
				return;
			}
			if(gebi('semSaldo') != null &&gebi('semSaldo').value == "true"){
				alertaMensagem("Atenção!","Mensagem de Erro","Saldo insuficiente para esta compra utilizando o convênio informado.");								
				return;
			}
			
			if (gebi('convenioNumeroDoc')!= null &&gebi('convenioNumeroDoc').value == "") {
				alertaMensagem("Atenção!","Mensagem de Erro","Convênio a Prazo - Campo de validação inválido.");
				return;
			}
			
			if (gebi("produtosContemplados") != null &&gebi("produtosContemplados").value != "true") {
				alertaMensagem("Atenção!","Mensagem de Erro",'Por favor, há produtos em sua cesta não contemplados pelo seu convênio. Por favor, informe outro convênio ou escolha outra forma de pagamento.');
				return;
			} 
			
			break;
			
		case '49' :
			break;
			
		default:
			break;
	}
	
	var doisPgtos = false;	
	if (pgto=='46') {

		var totalDaCompra = parseFloat(gebi('precoTotal').value.replace(",","."));
		var valorDoResgate = parseFloat(gebi('resgateValor').value.replace(",","."));
		
		if (buttonPressed && valorDoResgate < totalDaCompra) {
			//Tem duas opcoes de pagamento
			doisPgtos = true;
		}
	} else if (pgto=='36') {
		var segPgto =gebi('necessitaSegundaFormaPagamento');
		if (buttonPressed && segPgto!=null && segPgto!='' && segPgto.value == "true") {
			doisPgtos = true;
		}		
	}
	
	if (doisPgtos) {
		var pgtoSec = null;
		var tipoPgtoSec = document.getElementById('tipoPagamentoSec');
		
		if (tipoPgtoSec!=null) {
			pgtoSec = tipoPgtoSec.options[tipoPgtoSec.selectedIndex].value;
		}
	
		if (pgtoSec==null || pgtoSec=='' || pgtoSec=='-1') {
			alertaMensagem("Atenção!","Mensagem de Erro",'não foi selecionada uma segunda forma de pagamento.');
			return;
		}
		
		switch (pgtoSec) {
			case '51' :
				message = '';
				//message += evaluateField(gebi('creditoCodigoVerificacaoSec'), 'int', 'crédito - Código de Verificação inválido.');
				//message += evaluateField(gebi('creditoNumeroCartaoSec'),'cc', 'crédito - Número do cartão inválido.');
				//message += validateRequired(gebi('creditoCodigoVerificacaoSec'), 'crédito - Código de Verificação');
				message += validateRequired(gebi('creditoNumeroCartaoSec'), 'crédito - Número do cartão');
				
				if (message.length>0) {
					alertaMensagem("Atenção!","Mensagem de Erro",message);	
					return;
				}	
			
				if (!secButtonPressed) {
					alertaMensagem("Atenção!","Mensagem de Erro",'Por favor clique em VALIDAR para confirmar os dados do cartão de crédito.');	
					return;
				} else {
					var parcelas = document.getElementsByName('parcelas');
					var selected = false;
					if (parcelas!=null && parcelas.length>0) {
						for (var i = 0; i < parcelas.length; i++) {
							if (parcelas[i].checked) {
								selected = true;
							}
						}
					}
					if (parcelas==null || parcelas.length==0) {
						alertaMensagem("Atenção!","Mensagem de Erro",'Por favor clique em VALIDAR para confirmar os dados do cartão de crédito.');												
						return;
					} else if (!selected) {	
						alertaMensagem("Atenção!","Mensagem de Erro",'não foi selecionada nenhuma parcela para o cartão de crédito.');		
						return;
					}
				}
				break;
			
			case '32' :
				message = '';
				message += evaluateField(gebi('dinheiroValorPagamentoSec'), 'money', 'Dinheiro - Valor do Pagamento inválido.');
				
				var testeReq = validateRequired(gebi('dinheiroValorPagamentoSec'), 'Dinheiro - Valor do Pagamento');
				message += testeReq;
				
				var troco = document.getElementById('dinheiroTrocoSec');
				if ((troco==null || trim(''+troco.value)=='') && testeReq=='') {
					message += '<br />Dinheiro - Valor de pagamento menor que o valor da compra.';
				}
				
				if (message.length>0) {
					alertaMensagem("Atenção!","Mensagem de Erro",message);	
					return;
				}			
				break;
				
			case '49' :
				break;
				
			default :
				break;
		
		}
	}
	/////////////////////////////////////////////////////
	//validacoes para os itens que necessitam de receita
	
	//busca os tipos de receitas, as datas das receitas e os CRMs dos mï¿½dicos
	var receitaTipoArray = document.getElementsByName("receitaTipo");	
	var datas = document.getElementsByName('dataReceita');
	var crm = document.getElementsByName('crmMedico');	
	
	//percorre os tipos de receitas dos itens
	for (var i=0; i < receitaTipoArray.length; i++) {
		//testa se a receita ï¿½ obrigatoria
		if(receitaTipoArray[i].value == "OBRIGATORIA"){
			erro = false;
			//testa se a data foi digitada e ï¿½ valida
			if(datas[i].value == "" || datas[i].value.length < 10){				
				message += "Data da receita obrigatória deve ser preenchida corretamente<br />";				
				erro = true;				
			}		
			//testa se o crm ï¿½ valido
			if(crm[i].value == ""){
				message += "CRM do médico obrigatório deve ser preenchido corretamente";				
				erro = true;				
			}
			if(erro == true){
				break;
			}
			//testa se a receita ï¿½ opcional
		}else if(receitaTipoArray[i].value == "OPCIONAL"){
					//testa se o usuario digitou a data e o crm corretamente ou se deixou em branco
					if((datas[i].value != "" && crm[i].value == "") || (datas[i].value == "" && crm[i].value != "") || (crm[i].value != "" && datas[i].value.length < 10)){
						message += "Data da receita e CRM do médico opcionais devem ser preenchidos corretamente ou deixados em branco";
						break;
					}
				}
	}
	/////////////////////////////////////////////////////
	
	if (message.length>0) {
		alertaMensagem("Atenção!","Mensagem de Erro",message);				
	} else {		
		return true;
  	}
}

/*
 * Funcao que testa se os itens necessï¿½rios para receita estáo corretos
 * Parametros:
 *  - 
 *
 * USAGE: onclick="testaReceita()"
*/
function testaReceita(){
	receitaTipoArray = document.getElementsByName("receitaTipo");
	crmMedicoArray = document.getElementsByName("crmMedico");
	estadoMedicoArray = document.getElementsByName("estadoMedico");
	dataReceitaArray = document.getElementsByName("dataReceita");
	
	var erro = false;
	var text;
	valoresFormulario = "";
	for(i = 0; i < receitaTipoArray.length; i++){
		valoresFormulario += "&receitaTipo="+receitaTipoArray[i].value+"&crmMedico="+crmMedicoArray[i].value+"&estadoMedico="+estadoMedicoArray[i].value+"&dataReceita="+dataReceitaArray[i].value;		
	}
	var httpRequest = createHttpRequest();

	httpRequest.onreadystatechange = function() {
		if (whenReady(httpRequest)) {

			qs = new QueryStringParser(httpRequest.responseText);

			if(qs.buscaParametro("erroReceita") == "false"){

				document.opcoesPagamento.submit();
			}
			else{
				alertaMensagem("Atenção!","Mensagem de Erro",qs.buscaParametro("erroTexto"));								
			}
		}					
	}

	httpRequest.open('POST', "testarReceitaAction.do", true);
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
	httpRequest.setRequestHeader("Content-length", valoresFormulario.length);
	httpRequest.setRequestHeader("Connection", "close");
	httpRequest.send(valoresFormulario);
}

function validaSeg() {
	if (document.getElementById('creditoCodigoVerificacao2') == null) {
		// a tela nao exibiu campo de codigo de seguranca
		return true;
	}
	cseg = document.getElementById('creditoCodigoVerificacao2');
	  
	var apenasNumeros = /[0-9]/;
	var apenasZeros = /^0+$/;
			
	if (cseg.value.length < 3 || !apenasNumeros.test(cseg.value) ||  apenasZeros.test(cseg.value)) {
		alertaMensagem("Atenção!","Mensagem de Erro",'Código de Segurança inválido');
		cseg.focus();
		return false;
	}
	return true;
}
/*
 * Funcao para submeter o formulï¿½rio de opï¿½ï¿½es de pagamento
 * Parametros:
 *  - 
 *
 * USAGE: onclick="submitOpcoesPagamento()"
*/
function submitOpcoesPagamento(){
	if (validaSeg()) {
		if(checkAndSubmitPayment()){
			testaReceita();
		}
	}	
}
/*
 * Funcao que seta os valores para a checagem do submit do pagamento
 * Parametros:
 *  - 
 *
 * USAGE: onclick="setButtonPressed(false)"
 */
function setButtonPressed(value) {

	buttonPressed = value;
	secButtonPressed = false;
	var segPgto =gebi('necessitaSegundaFormaPagamento');
	if (segPgto!=null) {
		segPgto.value = false;
	}
}

function setSecButtonPressed(value) {	
	secButtonPressed = value;
}


/*
 * Funcao que calcula o troco
 * Parametros:
 *  - pago: valor pago pelo cliente
 *  - total: valor total da compra
 *
 * USAGE: onblur="calculaTroco(30.00)"
 */
function calculaTroco(total) {
	total = total.replace(",",".");
	totalFloat = parseFloat(total);
	if(gebi('dinheiroValorPagamento') == null || evaluateField(gebi('dinheiroValorPagamento'),"money").length > 0){
		gebi('dinheiroTroco').value = "";
		gebi('dinheiroValorPagamento').value = "";
		alertaMensagem("Atenção!","Mensagem de Erro",'Por favor, informe um valor válido para pagamento.');
		return;
	}	
	var pagoFloat = parseFloat(gebi('dinheiroValorPagamento').value.replace(/[^0-9\,]/g,'').replace(",","."));
	if (pagoFloat<totalFloat ) {
		gebi('dinheiroTroco').value='';
		return;
	}
	
	gebi('dinheiroTroco').value = toCommaString(formatDecPlaces((pagoFloat-total)*1,2));
}


/*
 * Funcao que calcula o troco na forma de pagamento secundario
 * Parametros:
 *  - pago: valor pago pelo cliente
 *  - total: valor total da compra
 *
 * USAGE: onblur="calculaTrocoSec(30.00)"
 */
function calculaTrocoSec(total) {
	total = total.replace(",",".");
	totalFloat = parseFloat(total);
	if(gebi('dinheiroValorPagamentoSec') == null || evaluateField(gebi('dinheiroValorPagamentoSec'),"money").length > 0){
		gebi('dinheiroTrocoSec').value = "";
		gebi('dinheiroValorPagamentoSec').value = "";
		alertaMensagem("Atenção!","Mensagem de Erro",'Por favor, informe um valor válido para pagamento.');			
		return;
	}	
	
	var pagoFloat = parseFloat(gebi('dinheiroValorPagamentoSec').value.replace(/[^0-9\,]/g,'').replace(",","."));
	if (pagoFloat<totalFloat) {
		gebi('dinheiroTrocoSec').value='';
		return;
	}
	gebi('dinheiroTrocoSec').value = toCommaString(formatDecPlaces((pagoFloat-total)*1,2));
}


/*
 * Funcao que calcula o valor para resgate
 * Parametros:
 *  - pago: valor digitado pelo cliente
 *  - total: valor total da compra
 *  - max: limite de pontos do cliente
 *
 * USAGE: onblur="calculaResgate(this.value, 30.00, 50.00)"
 */
function calculaResgate(total,max) {	
	var valorResgateFloat = parseFloat(gebi('resgateValor').value.replace(",","."));
	var maxFloat = parseFloat(max.replace(",","."));
	var totalFloat = parseFloat(total.replace(",","."));
	if(valorResgateFloat > maxFloat){
		if(maxFloat > totalFloat){
			gebi('resgateValor').value = totalFloat.toFixed(2).replace(".",",");
		}else{
			gebi('resgateValor').value = maxFloat.toFixed(2).replace(".",",");
		}
	}else{
		if (valorResgateFloat > totalFloat) {
			gebi('resgateValor').value = totalFloat.toFixed(2).replace(".",",");
		} else {
			gebi('resgateValor').value = valorResgateFloat.toFixed(2).replace(".",",");
		}
	}
	return;
}


/*
 * Funcao que libera os campos na pagina de opcoes de pagamento
 * Parametros:
 *  - tipo: nome do tipo de pagamento que sera liberado. 'none' se for para desabilitar todos
 *
 * USAGE: onclick="liberaCampos('none');"
 */
function liberaCampos(tipo) {
	
	if (tipo!='credito' && tipo!='dinheiro' && tipo!='resgate' &&
		tipo!='convenioPrazo' && tipo!='boleto' && tipo!='none')
		return;
	
	if (tipo=='credito') {
		gebi('creditoCodigoVerificacao').removeAttribute('disabled');
		gebi('creditoMesExpiracao').removeAttribute('disabled');
		gebi('creditoAnoExpiracao').removeAttribute('disabled');
		gebi('creditoNumeroCartao').removeAttribute('disabled');
		var parcelas = document.getElementsByName('parcelas');
		for (var i = 0; i < parcelas.length; i++) {
			parcelas[i].disabled=false;
		}
	} else {
		gebi('creditoCodigoVerificacao').setAttribute('disabled','disabled');
		gebi('creditoMesExpiracao').setAttribute('disabled','disabled');
		gebi('creditoAnoExpiracao').setAttribute('disabled','disabled');
		gebi('creditoNumeroCartao').setAttribute('disabled','disabled');
		gebi('creditoCodigoVerificacao').value='';
		gebi('creditoCodigoVerificacao').style.borderColor=null;
		gebi('creditoNumeroCartao').value='';
		gebi('creditoNumeroCartao').style.borderColor=null;
		var parcelas = document.getElementsByName('parcelas');
		for (var i = 0; i < parcelas.length; i++) {
			parcelas[i].disabled=true;
			parcelas[i].checked=false;
		}
	}
	
	if (tipo=='dinheiro') {
		gebi('dinheiroValorPagamento').removeAttribute('disabled');
	} else {
		gebi('dinheiroValorPagamento').setAttribute('disabled','disabled');
		gebi('dinheiroValorPagamento').value='';
		gebi('dinheiroTroco').value='';
		gebi('dinheiroValorPagamento').style.borderColor=null;
	}
	
	if (tipo=='resgate') {
		gebi('resgateNumeroCartao').removeAttribute('disabled');
		gebi('resgateValor').removeAttribute('disabled');
		gebi('resgateCampoValidacao').removeAttribute('disabled');
	} else {
		gebi('resgateNumeroCartao').setAttribute('disabled','disabled');
		gebi('resgateValor').setAttribute('disabled','disabled');
		gebi('resgateCampoValidacao').setAttribute('disabled','disabled');
		gebi('resgateNumeroCartao').value='';
		gebi('resgateNumeroCartao').style.borderColor=null;
		gebi('resgateValor').value='';
		gebi('resgateValor').style.borderColor=null;
		gebi('resgateCampoValidacao').value='';
		gebi('resgateCampoValidacao').style.borderColor=null;
	}
	
	if (tipo=='convenioPrazo') {
		gebi('convenioPrazoNumeroCartao').removeAttribute('disabled');
		gebi('convenioPrazoSenha').removeAttribute('disabled');
		gebi('convenioPrazoCampoGenerico').removeAttribute('disabled');
	} else {
		gebi('convenioPrazoNumeroCartao').setAttribute('disabled','disabled');
		gebi('convenioPrazoSenha').setAttribute('disabled','disabled');
		gebi('convenioPrazoCampoGenerico').setAttribute('disabled','disabled');
		gebi('convenioPrazoNumeroCartao').value='';
		gebi('convenioPrazoNumeroCartao').style.borderColor=null;
		gebi('convenioPrazoSenha').value='';
		gebi('convenioPrazoSenha').style.borderColor=null;
		gebi('convenioPrazoCampoGenerico').value='';
		gebi('convenioPrazoCampoGenerico').style.borderColor=null;
	}
	
	if (tipo=='boleto') {
	
	} else {

	}
	
	if (tipo=='none') {
		return;
	}
}

function mostraComplementoBoleto(nome){
	
/*if(nome == 'boleto' || nome == 'boletoSec'){
		gebi('divComplementoBoleto').style.display = '';
		gebi('bgBoleto').style.display = '';
	}else{
		gebi('divComplementoBoleto').style.display = 'none';
		gebi('bgBoleto').style.display = 'none';
	}*/
}
/* 
 * Funcao que exibe e esconde os divs referentes as opï¿½ï¿½es de pagamento
 * Parametros:
 * 	- nome: nome do div a ser mostrado
 *

 * USAGE: 
 */
function mostraDiv(nome) {
	
	if (document.getElementById(nome)!=null) {
		var vista = (document.getElementById(nome).style.display == 'none') ? 'block' : 'none';
		document.getElementById(nome).style.display = vista;
		var segPgto =gebi('necessitaSegundaFormaPagamento');
		if (segPgto!=null) {
			segPgto.value = false;
		}
	}
	
	switch (nome) {
        case 'cartao':
			if (gebi(nome)!=null) {document.getElementById(nome).style.display = 'block';}
			if (gebi('tituloFormaPagamento')!=null) {document.getElementById('tituloFormaPagamento').style.display = 'block';}
			if (gebi('convenio')!=null) {document.getElementById('convenio').style.display = 'none';}
			if (gebi('boleto')!=null) {document.getElementById('boleto').style.display = 'none';}
			if (gebi('resgate')!=null) {document.getElementById('resgate').style.display = 'none';}
			if (gebi('dinheiro')!=null) {document.getElementById('dinheiro').style.display = 'none';}
			
			if (gebi('pgtoSec')!=null) {gebi('pgtoSec').style.display = 'none';}
			if (gebi('cartaoSec')!=null) {gebi('cartaoSec').style.display = 'none';}
			if (gebi('dinheiroSec')!=null) {gebi('dinheiroSec').style.display = 'none';}
			if (gebi('boletoSec')!=null) {gebi('boletoSec').style.display = 'none';}
			break;
        	
        case 'dinheiro':
			if (gebi(nome)!=null) {document.getElementById(nome).style.display = 'block';}
			if (gebi('tituloFormaPagamento')!=null) {document.getElementById('tituloFormaPagamento').style.display = 'block';}
			if (gebi('cartao')!=null) {document.getElementById('cartao').style.display = 'none';}
			if (gebi('boleto')!=null) {document.getElementById('boleto').style.display = 'none';}
			if (gebi('convenio')!=null) {document.getElementById('convenio').style.display = 'none';}
			if (gebi('resgate')!=null) {document.getElementById('resgate').style.display = 'none';}
			
			if (gebi('pgtoSec')!=null) {gebi('pgtoSec').style.display = 'none';}
			if (gebi('cartaoSec')!=null) {gebi('cartaoSec').style.display = 'none';}
			if (gebi('dinheiroSec')!=null) {gebi('dinheiroSec').style.display = 'none';}
			if (gebi('boletoSec')!=null) {gebi('boletoSec').style.display = 'none';}
			break;
			
  		case 'convenio':
			if (gebi(nome)!=null) {document.getElementById(nome).style.display = 'block';}
			if (gebi('tituloFormaPagamento')!=null) {document.getElementById('tituloFormaPagamento').style.display = 'block';}
			if (gebi('cartao')!=null) {document.getElementById('cartao').style.display = 'none';}
			if (gebi('boleto')!=null) {document.getElementById('boleto').style.display = 'none';}
			if (gebi('resgate')!=null) {document.getElementById('resgate').style.display = 'none';}
			if (gebi('dinheiro')!=null) {document.getElementById('dinheiro').style.display = 'none';}
			
			if (gebi('pgtoSec')!=null) {gebi('pgtoSec').style.display = 'none';}
			if (gebi('cartaoSec')!=null) {gebi('cartaoSec').style.display = 'none';}
			if (gebi('dinheiroSec')!=null) {gebi('dinheiroSec').style.display = 'none';}
			if (gebi('boletoSec')!=null) {gebi('boletoSec').style.display = 'none';}
			
			if(gebi("convenioPrazoNumeroCartao").value != null &&gebi("convenioPrazoNumeroCartao").value != "" &&gebi("convenioPrazoSenha").value != null &&gebi("convenioPrazoSenha").value != ""){
				buscarDadosConvenioPrazo();
			}
			break;
        	
        case 'boleto':
			if (gebi(nome)!=null) {document.getElementById(nome).style.display = 'block';}
			if (gebi('tituloFormaPagamento')!=null) {document.getElementById('tituloFormaPagamento').style.display = 'block';}
			if (gebi('cartao')!=null) {document.getElementById('cartao').style.display = 'none';}
			if (gebi('resgate')!=null) {document.getElementById('resgate').style.display = 'none';}
			if (gebi('convenio')!=null) {document.getElementById('convenio').style.display = 'none';}
			if (gebi('dinheiro')!=null) {document.getElementById('dinheiro').style.display = 'none';}
			
			if (gebi('pgtoSec')!=null) {gebi('pgtoSec').style.display = 'none';}
			if (gebi('cartaoSec')!=null) {gebi('cartaoSec').style.display = 'none';}
			if (gebi('dinheiroSec')!=null) {gebi('dinheiroSec').style.display = 'none';}
			if (gebi('boletoSec')!=null) {gebi('boletoSec').style.display = 'none';}
			break;
        	
        case 'resgate':
			if (gebi(nome)!=null) {document.getElementById(nome).style.display = 'block';}
			if (gebi('tituloFormaPagamento')!=null) {document.getElementById('tituloFormaPagamento').style.display = 'block';}
			if (gebi('cartao')!=null) {document.getElementById('cartao').style.display = 'none';}
			if (gebi('boleto')!=null) {document.getElementById('boleto').style.display = 'none';}
			if (gebi('convenio')!=null) {document.getElementById('convenio').style.display = 'none';}
			if (gebi('dinheiro')!=null) {document.getElementById('dinheiro').style.display = 'none';}
			
			if (gebi('pgtoSec')!=null) {gebi('pgtoSec').style.display = 'none';}
			if (gebi('cartaoSec')!=null) {gebi('cartaoSec').style.display = 'none';}
			if (gebi('dinheiroSec')!=null) {gebi('dinheiroSec').style.display = 'none';}
			if (gebi('boletoSec')!=null) {gebi('boletoSec').style.display = 'none';}
			
			if(gebi("resgateNumeroCartao") != null &&gebi("resgateNumeroCartao").value != "" &&gebi("resgateCampoValidacao") != null &&gebi("resgateCampoValidacao").value != ""){
				//mostrarLimiteResgate();
				setButtonPressed(true);
			}
			
			break;
			
        default:
			if (gebi('tituloFormaPagamento')!=null) {document.getElementById('tituloFormaPagamento').style.display = 'none';}
			if (gebi('resgate')!=null) {document.getElementById('resgate').style.display = 'none';}
			if (gebi('cartao')!=null) {document.getElementById('cartao').style.display = 'none';}
			if (gebi('boleto')!=null) {document.getElementById('boleto').style.display = 'none';}
			if (gebi('convenio')!=null) {document.getElementById('convenio').style.display = 'none';}
			if (gebi('dinheiro')!=null) {document.getElementById('dinheiro').style.display = 'none';}
			if (gebi('pgtoSec')!=null) {gebi('pgtoSec').style.display = 'none';}
			if (gebi('cartaoSec')!=null) {gebi('cartaoSec').style.display = 'none';}
			if (gebi('dinheiroSec')!=null) {gebi('dinheiroSec').style.display = 'none';}
			if (gebi('boletoSec')!=null) {gebi('boletoSec').style.display = 'none';}
        	break;
  	}
	mostraComplementoBoleto(nome);
	
}
function mudaOpcaoPagamentoPrimaria(nomeDiv){
	if(nomeDiv != "none"){
		recalculaCarrinhoOpcoesPagamento();
	}
}

/* 
 * Funcao que exibe e esconde os divs referentes as opï¿½ï¿½es de pagamento secundarias
 * Parametros:
 * 	- nome: nome do div a ser mostrado
 *
 * USAGE: 
 */
function mostraDivSec(nome) {

	if (document.getElementById(nome)!=null) {
		var vista = (document.getElementById(nome).style.display == 'none') ? 'block' : 'none';
		document.getElementById(nome).style.display = vista;
	}
	
	switch (nome) {
        case 'cartaoSec':
			if (gebi(nome)!=null) document.getElementById(nome).style.display = 'block';
			if (gebi('dinheiroSec')!=null) document.getElementById('dinheiroSec').style.display = 'none';
			if (gebi('boletoSec')!=null) document.getElementById('boletoSec').style.display = 'none';
			break;
        	
        case 'dinheiroSec':
			if (gebi(nome)!=null) document.getElementById(nome).style.display = 'block';
			if (gebi('cartaoSec')!=null) document.getElementById('cartaoSec').style.display = 'none';
			if (gebi('boletoSec')!=null) document.getElementById('boletoSec').style.display = 'none';
			break;
			
        case 'boletoSec':
			if (gebi(nome)!=null) document.getElementById(nome).style.display = 'block';
			if (gebi('cartaoSec')!=null) document.getElementById('cartaoSec').style.display = 'none';
			if (gebi('dinheiroSec')!=null) document.getElementById('dinheiroSec').style.display = 'none';
			break;
			
        default:
			if (gebi('cartaoSec')!=null) document.getElementById('cartaoSec').style.display = 'none';
        	if (gebi('dinheiroSec')!=null) document.getElementById('dinheiroSec').style.display = 'none';
			if (gebi('boletoSec')!=null) document.getElementById('boletoSec').style.display = 'none';
        	break;
  	}
  	mostraComplementoBoleto(nome);
}
/*
 * Funcao que pode mostras as divs de pontuar pela compra e de convenio a vista
 * Parametros:
 *  mostraPontuarCompra
 *  mostraConvenioVista
 *
 * USAGE: onclick="mostraDivPontuarCompraConvenioVista(true,false);"
 */
function mostraDivPontuarCompraConvenioVista(mostraPontuarCompra,mostraConvenioVista){
	//testa se deve ser exibido o div de pontuar pela compra
	if(mostraPontuarCompra=='true'){
//		gebi("blocoC").style.display="";
		gebi("divPontuarCompra").style.display = "";//mostra o div
		gebi("divPontuarCompraEnviar").style.display = "";//mostra de botao de enviar
		gebi("pontuarNumeroCartao").setAttribute("visivel","true");//muda atributo para testar depois se o campo deve estar preenchido ou nao
	}else{
		gebi("divPontuarCompra").style.display = "none";
		gebi("pontuarNumeroCartao").setAttribute("visivel","false");//muda atributo para testar depois se o campo deve estar preenchido ou nao
	}
	//if semelhante ao de cima, mas para o convenio a vista
	if(mostraConvenioVista=='true') {
//		gebi("blocoC").style.display="";
		gebi("divConvenioVista").style.display = "";
		gebi("divConvenioVistaEnviar").style.display = "";
		gebi("convenioVistaNumeroCartao").setAttribute("visivel","true");
	}else{
		gebi("divConvenioVista").style.display = "none";
		gebi("convenioVistaNumeroCartao").setAttribute("visivel","false");//muda atributo para testar depois se o campo deve estar preenchido ou nao
	}
	//teste para nao exibir o botao enviar
	if(mostraPontuarCompra == 'false' && mostraConvenioVista == 'false'){
//		gebi("blocoC").style.display="none";
		gebi("divConvenioVistaEnviar").style.display = "none";//mostra de botao de enviar
		gebi("divPontuarCompraEnviar").style.display = "none";//mostra de botao de enviar
	}
	
}

/*
 * Funcao que mostra a div do segundo tipo de pagamento
 * Parametros:
 *  -
 *
 * USAGE: conferirLimiteResgate();"
 */
function conferirLimiteResgate(valorCompra) {
	valorResgate =gebi("resgateValor").value;
	
	if (!buttonPressed) {
		alertaMensagem("Atenção!","Mensagem de Erro",'Por favor, valide suas informações de Resgate novamente.');			
		return;
	}
		
	if (valorResgate==null || valorResgate.value=='') {
		alertaMensagem("Atenção!","Mensagem de Erro",'Preencha o valor que deseja utilizar.');					
		return;
	}else {
		valorResgateFloat = parseFloat(gebi('resgateValor').value.replace(/[^0-9\,]/g,'').replace(",","."));		
		valorCompraFloat = parseFloat(valorCompra.replace(/[^0-9\,]/g,'').replace(",","."));
		if (valorResgateFloat < valorCompraFloat) {
			buscaSegundasFormasPagamento(valorCompraFloat,valorCompraFloat - valorResgateFloat);
			//gebi("valorTotalDinheiroSecHidden").value = valorCompra - valorResgateFloat;
			//gebi("valorTotalDinheiroSec").innerHTML = "R$ "+(valorCompra - valorResgateFloat);
			alertaMensagem("Atenção!","Compra",'Por favor, selecione uma segunda opção de pagamento.');			
		}else{
			alertaMensagem("Atenção!","Compra",'Valor atualizado com sucesso.');						
			if (gebi('pgtoSec')!=null) {gebi('pgtoSec').style.display = 'none';}
			if (gebi('cartaoSec')!=null) {gebi('cartaoSec').style.display = 'none';}
			if (gebi('dinheiroSec')!=null) {
				gebi('dinheiroSec').style.display = 'none';
				gebi('dinheiroValorPagamentoSec').value = "";
				gebi("valorTotalDinheiroSecHidden").value = "";
			}
			if (gebi('boletoSec')!=null) {gebi('boletoSec').style.display = 'none';}
		}
	}
}




function adicionarNovoEnderecoCliente() {
		var args= '';
		var httpRequest = createHttpRequest();
		
		
		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {
					var text = httpRequest.responseText;	
					document.getElementById('enderecoDiv').innerHTML = text ;
				}	
		}

		httpRequest.open('POST', 'adicionarNovoEnderecoCliente.do', true);
		httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
		httpRequest.setRequestHeader("Content-length", args.length);
		httpRequest.send(args);
	
}

function editarEndereco(codigoEndereco) {
		var args= 'codigoEndereco=' + codigoEndereco;
		var httpRequest = createHttpRequest();
		
		
		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {
					var text = httpRequest.responseText;	
					document.getElementById('enderecoDiv').innerHTML = text ;
					buscaLocalidades(document.getElementById('cadastroClienteCep').value);
				}	
		}

		httpRequest.open('POST', 'editarEnderecoCliente.do', true);
		httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
		httpRequest.setRequestHeader("Content-length", args.length);
		httpRequest.send(args);
	
}

function excluirEndereco(codigoEndereco) {
	if (confirm('você tem certeza que deseja excluir esse endereço?')) {
		document.getElementById('codigoEnderecoExclusao').value = codigoEndereco;
		document.formCliente.action = 'excluirEnderecoCliente.do';
		document.formCliente.submit();
	}
}

function adicionarEndereco() {
		var cep1 = gebi('cadastroClienteCep1');
		var cep2 = gebi('cadastroClienteCep2');
		
		
		cep = cep1.value+'-'+cep2.value;
		var args = "cadastroClienteCep=" + cep;
		args += "&identificadorEndereco=" + document.getElementById('identificadorEndereco').value;
		args += "&cadastroClienteEnderecoNumero=" + document.getElementById('cadastroClienteEnderecoNumero').value;
		args += "&cadastroClienteEnderecoComplemento=" + document.getElementById('cadastroClienteEnderecoComplemento').value;
		args += "&cadastroClienteDdd=" + document.getElementById('cadastroClienteDdd').value;
		args += "&cadastroClienteTelefone=" + document.getElementById('cadastroClienteTelefone').value;
		args += "&logradouro=" + document.getElementById('logradouro').value;
		args += "&localidade=" + document.getElementById('localidade').value;
		args += "&referencia=" + document.getElementById('referencia').value;
		var httpRequest = createHttpRequest();
		
		
		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {
					var text = httpRequest.responseText;
					document.getElementById('enderecoDiv').innerHTML = text ;
					extraiScript(text);
				}	
		}

		httpRequest.open('POST', 'adicionarEndereco.do', true);
		httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
		httpRequest.setRequestHeader("Content-length", args.length);
		httpRequest.send(args);
}

function mostrarFormasEntrega(cep) {
		var args = "cep=" + cep;
		//var args = "cadastroClienteCep=" + document.getElementById('cadastroClienteCep').value;
		//args += "&identificadorEndereco=" + document.getElementById('identificadorEndereco').value;
		var httpRequest = createHttpRequest();
		
		
		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {
					var text = httpRequest.responseText;
					document.getElementById('divFormasEntrega').innerHTML = text ;
					// deixa selecionada a primeira forma de entrega
					if(document.getElementById('radioEntrega1') != null){
					// deixa selecionada a primeira forma de entrega
						var tipoEntrega = document.getElementById('radioEntrega1').value;
						var valorEntrega = document.getElementById('valorEntrega1').value;
						var prazoEntrega = document.getElementById('prazoEntrega1').value;
						mudarTipoEntrega(tipoEntrega,valorEntrega,prazoEntrega);
					}
					document.getElementById('divFormasEntrega').setAttribute("carregando","false");
				}	
		}
		
		document.getElementById('divFormasEntrega').innerHTML = "Carregando...";
		document.getElementById('divFormasEntrega').setAttribute("carregando","true");
		
		httpRequest.open('POST', 'mostrarFormasEntrega.do', true);
		httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
		httpRequest.setRequestHeader("Content-length", args.length);
		httpRequest.send(args);
}

function escolheEndereco(logradouro,enderecoComplemento,numeroEndereco,contador,codigoEndereco) {
	gebi('codigoEndereco').value = codigoEndereco;
}

function mudarTipoEntrega(tipoEntrega,valorEntrega,prazoEntrega) {
	document.getElementById('tipoEntrega').value = tipoEntrega;
	document.getElementById('valorEntrega').value = valorEntrega;
	document.getElementById('prazoEntrega').value = prazoEntrega;
}

function visualizarDescrProdutoAvancada(codigoItem, action){
	document.getElementById('codigoItem').value = codigoItem;
	document.produto.action = action;
	document.produto.submit();
}

function mudaSelectOpcoesPagamento(valor){
	if (valor == true) {
		$("[name=tipoPagamento]:checked").attr("disabled","disabled");		
	}else{
		$("[name=tipoPagamento]:checked").attr("disabled",null);
	}
	
}

function mudaSelectOpcoesPagamentoSecundaria(valor){
	if (valor == true) {
		gebi('tipoPagamentoSec').setAttribute("disabled","disabled");
	}else{
		gebi('tipoPagamentoSec').removeAttribute("disabled");
	}
	
}

/* AJAX
 * Funcao que mostra a div do limite de resgate
 * Parametros:
 *  -
 *
 * USAGE: mostrarLimiteResgate();"
 */
function mostrarLimiteResgate() {

	var cpfField =gebi('resgateCampoValidacao');
	var cartaoField =gebi('resgateNumeroCartao');
	var campoCartaoConvenioVista =gebi('convenioVistaNumeroCartao');
	
	var cpf = cpfField!=null ? trim(cpfField.value) : null;
	var cartao = cartaoField!=null ? trim(cartaoField.value) : null;
	
	if (cpfField!=null && cartaoField!=null && trim(''+cpf).length!=0 && trim(''+cartao).length!=0 &&
		evaluateField(cpfField,'cpf').length==0 && evaluateField(cartaoField,'int').length==0) {
		var httpRequest = createHttpRequest();

		var args = 'resgateNumeroCartao='+cartao.replace(/[^0-9]/g,'')+
				   '&resgateCPF='+cpf.replace(/[^0-9\.]/g,'')+
				   '&tipoDados=resgate';
		if(campoCartaoConvenioVista != null && campoCartaoConvenioVista.value.charAt( 0 ) != 'D'){
			args += "&numeroCartaoConvenioVista="+campoCartaoConvenioVista.value; 
		}
		
		document.getElementById('divValorResgate').innerHTML = "Carregando...";
		document.getElementById('divValorResgate').style.display = 'block';
		mudaSelectOpcoesPagamento(true);
		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {
					mudaSelectOpcoesPagamento(false);
					document.getElementById('divValorResgate').innerHTML = httpRequest.responseText;
					document.getElementById('divValorResgate').style.display = 'block';
					extraiScript(httpRequest.responseText);
				}
			}

		
		
		//if (gebi('pgtoSec')!=null) {gebi('pgtoSec').style.display = 'none';}
		//if (gebi('cartaoSec')!=null) {gebi('cartaoSec').style.display = 'none';}
		//if (gebi('dinheiroSec')!=null) {gebi('dinheiroSec').style.display = 'none';}
		//if (gebi('boletoSec')!=null) {gebi('boletoSec').style.display = 'none';}
		
		httpRequest.open('POST', 'buscarDadosPagamento.do', true);
		httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
		httpRequest.setRequestHeader("Content-length", args.length);
		httpRequest.setRequestHeader("Connection", "close");
		httpRequest.send(args);
	}
}


/* AJAX
 * Funcao que pega os dados para convenio a prazo
 * Parametros:
 *  -
 *
 * USAGE: buscarDadosConvenioPrazo();"
 */
function buscarDadosConvenioPrazo() {
	
	var cartaoField =gebi('convenioPrazoNumeroCartao');
	var senhaField =gebi('convenioPrazoSenha');	
	if (cartaoField.getAttribute("erro") != null && cartaoField.getAttribute("erro") == "false") {
		if (cartaoField != null && senhaField != null &&
		trim('' + cartaoField.value) != '' &&
		trim('' + senhaField.value) != '' &&
		evaluateField(cartaoField).length == 0 &&
		evaluateField(senhaField).length == 0) {		
		var args = 'prazoNumeroCartao=' + (cartaoField.value).replace(/[^0-9]/g, '') +
			'&prazoSenha=' +
			(senhaField.value).replace(/[^0-9]/g, '') +
			'&tipoDados=convenioPrazo';		
			gebi('divDadosConvenio').innerHTML = "Carregando...";
			gebi('divDadosConvenio').style.display = 'block';			
			mudaSelectOpcoesPagamento(true);
			var httpRequest = createHttpRequest();
			httpRequest.onreadystatechange = function(){
				if (whenReady(httpRequest)) {
					mudaSelectOpcoesPagamento(false);
					document.getElementById('divDadosConvenio').innerHTML = httpRequest.responseText;
					document.getElementById('divDadosConvenio').style.display = 'block';
					extraiScript(httpRequest.responseText);
					//testa se necessita de uma segunda forma de pagamento					
					if (gebi('necessitaSegundaFormaPagamento') != null &&gebi('necessitaSegundaFormaPagamento').value == "true") {
						//busca as formas
						buscaSegundasFormasPagamento();
						//gebi('pgtoSec').style.display = 'block';
						//testa se a forma eh para taxa de entrega, senao eh segunda forma para produtos nao contemplados					
						if (gebi('formaPagamentoTaxaEntrega') != null) {
							alertaMensagem("Atenção!","Compra",'Por favor, preencha o campo de validação e, em seguida, selecione uma segunda opção de pagamento para a tele-entrega.');											
						}
						else {
							alertaMensagem("Atenção!","Compra",'Por favor, preencha o campo de validação e, em seguida, selecione uma segunda opção de pagamento para a tele-entrega.');
						}
					}
					recalculaCarrinhoOpcoesPagamento();
				}
			}
			
			
			
			httpRequest.open('POST', 'buscarDadosPagamento.do', true);
			httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpRequest.setRequestHeader('encoding', 'ISO-8859-1');
			httpRequest.setRequestHeader("Content-length", args.length);
			httpRequest.setRequestHeader("Connection", "close");
			httpRequest.send(args);
			
		}
		else {
			alertaMensagem("Atenção!",'Mensagem de Erro','Por favor, preencha os campos "Número do cartão" e "Senha".');						
		}
	}else{
		alertaMensagem("Atenção!","Mensagem de Erro",'Por favor, informe seu cartão corretamente.');
	}
}


/* AJAX
 * Funcao que busca as segundas formas de pagamento
 * Parametros:
 *  -
 *
 * USAGE: buscaSegundasFormasPagamento();"
 */
function buscaSegundasFormasPagamento(valorTotal, valorNaoContemplado){
	gebi('pgtoSec').innerHTML = "Carregando..."	;
	gebi('pgtoSec').style.display = '';	
	var httpRequest = createHttpRequest();
	
	formaPagamentoSelecionada = $("[name=tipoPagamento]:checked").val();
	var args = 'codigoFormaPagamento='+formaPagamentoSelecionada;	
	
		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {
					gebi('pgtoSec').innerHTML = httpRequest.responseText;
					gebi('pgtoSec').style.display = '';
					
					if (gebi('cartaoSec')!=null) {gebi('cartaoSec').style.display = 'none';}
					if (gebi('dinheiroSec')!=null) {gebi('dinheiroSec').style.display = 'none';}
					if (gebi('boletoSec')!=null) {gebi('boletoSec').style.display = 'none';}	
					
					formaPagamentoSelecionadaObjeto = $("[name=tipoPagamento]:checked");	
					if(formaPagamentoSelecionadaObjeto.attr("nomeDiv") != null && formaPagamentoSelecionadaObjeto.attr("nomeDiv") == "resgate")	{					
						mudaValoresRecalculoCarrinho((valorTotal+"").replace(/[^0-9\.]/g,'').replace(".",","),(valorNaoContemplado+"").replace(/[^0-9\.]/g,'').replace(".",","));
					}
				}
			}
	
			   
	httpRequest.open('POST', 'buscarSegundasFormasPagamento.do', true);
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
	httpRequest.setRequestHeader("Content-length", args.length);
	httpRequest.setRequestHeader("Connection", "close");
	httpRequest.send(args);
}


/* AJAX
 * Funcao que busca as cidades de um estado
 * Parametros:
 *  -
 *
 * USAGE: buscarLocalidades();"
 */
function buscarLocalidades() {

	var ufField =gebi('estados');
	var ufSigla = ufField.options[ufField.selectedIndex].value;
	if (ufField!=null && ufSigla!=-1) {
		gebi('divCidades').innerHTML = 'Carregando...';
		gebi('divCidades').style.display="block";
		
		if(gebi('divBairros') != null){
			gebi('divBairros').style.display = "none";
		}
		
		var args = 'method=buscarLocalidades&uf='+ufSigla;
		
		var httpRequest = createHttpRequest();

		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {
					gebi('divCidades').innerHTML = httpRequest.responseText;
					gebi('divCidades').style.display="block";
					extraiScript(httpRequest.responseText);	
				}
			}

		httpRequest.open('POST', 'localizarFilial.do', true);
		httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
		httpRequest.setRequestHeader("Content-length", args.length);
		httpRequest.setRequestHeader("Connection", "close");
		httpRequest.send(args);
	}
}


/* AJAX
 * Funcao que busca as filiais de uma cidade
 * Parametros:
 *  -
 *
 * USAGE: buscarLocalidades();"
 */
function buscarFiliais() {

	var cidadeField =gebi('cidadesLocal');
	var cidadeCode = cidadeField.options[cidadeField.selectedIndex].value;
	if (cidadeField!=null && cidadeCode!=-1) {
		gebi('divFiliais').innerHTML = 'Carregando...';
		gebi('divFiliais').style.display="block";
		
		var args = 'method=buscarFiliais&local='+cidadeCode;
		
		var httpRequest = createHttpRequest();
		
		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {
					gebi('divFiliais').innerHTML = httpRequest.responseText;
					gebi('divFiliais').style.display="block";
					extraiScript(httpRequest.responseText);	
				}
			}
		
		
		httpRequest.open('POST', 'localizarFilial.do', true);
		httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
		httpRequest.setRequestHeader("Content-length", args.length);
		httpRequest.setRequestHeader("Connection", "close");
		httpRequest.send(args);
	}
}

function buscarFiliaisBairro(codigoLocalidade) {

	var bairrosField =gebi('bairrosLocal');
	var bairroCode = bairrosField.options[bairrosField.selectedIndex].value;
	if (bairroCode!=null && bairroCode != "-1") {
		gebi('divFiliais').innerHTML = 'Carregando...';
		gebi('divFiliais').style.display="block";
		
		var args = 'method=buscarFiliaisBairro&codigoBairro='+bairroCode+"&local="+codigoLocalidade;
		
		var httpRequest = createHttpRequest();
		
		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {
					gebi('divFiliais').innerHTML = httpRequest.responseText;
					gebi('divFiliais').style.display="block";
					extraiScript(httpRequest.responseText);	
				}
			}
		
		
		httpRequest.open('POST', 'localizarFilial.do', true);
		httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
		httpRequest.setRequestHeader("Content-length", args.length);
		httpRequest.setRequestHeader("Connection", "close");
		httpRequest.send(args);
	}
}

function buscarBairros() {

	var cidadeField =gebi('cidadesLocal');
	var cidadeCode = cidadeField.options[cidadeField.selectedIndex].value;
	if (cidadeField!=null && cidadeCode!=-1) {
		gebi('divBairros').innerHTML = 'Carregando...';
		gebi('divBairros').style.display="block";
		
		var args = 'method=buscarBairros&local='+cidadeCode;
		
		var httpRequest = createHttpRequest();
		
		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {
					gebi('divBairros').innerHTML = httpRequest.responseText;
					gebi('divBairros').style.display="block";
					extraiScript(httpRequest.responseText);	
				}
			}
		
		
		httpRequest.open('POST', 'localizarFilial.do', true);
		httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
		httpRequest.setRequestHeader("Content-length", args.length);
		httpRequest.setRequestHeader("Connection", "close");
		httpRequest.send(args);
	}
}






function buscarProdutosBuscaAvancada() {
/*
	if(document.getElementById('categoriaSubCategoria3') != null && document.getElementById('categoriaSubCategoria3').value != '-1') {
		document.buscarAvancada.categoriaPesquisa.value = 'categoriaSubCategoria3';
		document.buscarAvancada.codigoCategoriaBusca.value = document.getElementById('categoriaSubCategoria3').value;
		buscarProdutosBuscaAvancadaAjax('listagem');
		//document.buscarAvancada.submit();
	} else if(document.getElementById('categoriaSubCategoria2') != null && document.getElementById('categoriaSubCategoria2').value != '-1') {
		document.buscarAvancada.categoriaPesquisa.value = 'categoriaSubCategoria2';
		document.buscarAvancada.codigoCategoriaBusca.value = document.getElementById('categoriaSubCategoria2').value;
		buscarProdutosBuscaAvancadaAjax('listagem');
		//document.buscarAvancada.submit();
	} else if(document.getElementById('categoriaSubCategoria1') != null && document.getElementById('categoriaSubCategoria1').value != '-1'){
		document.buscarAvancada.categoriaPesquisa.value = 'categoriaSubCategoria1';
		document.buscarAvancada.codigoCategoriaBusca.value = document.getElementById('categoriaSubCategoria1').value;
		buscarProdutosBuscaAvancadaAjax('listagem');
		//document.buscarAvancada.submit();
	} else if(document.getElementById('categoriaGrupo') != null && document.getElementById('categoriaGrupo').value != '-1') {
		document.buscarAvancada.categoriaPesquisa.value = 'categoriaGrupo';
		document.buscarAvancada.codigoCategoriaBusca.value = document.getElementById('categoriaGrupo').value;
		buscarProdutosBuscaAvancadaAjax('listagem');
		//document.buscarAvancada.submit();
	} else {
		alert('Selecione uma categoria para efetuar a busca');
	}
*/
   var l = gebi("selectLojas");
   var lojaSelecionada = l.options[l.selectedIndex].value;
   var categoriasDaLoja = gebi(lojaSelecionada);
   
   if (categoriasDaLoja != null)
    var categoriaSelecionada = categoriasDaLoja.options[categoriasDaLoja.selectedIndex].value;

  if (gebi("selectMarca") != null && gebi("selectMarca").value != ''){
//    gebi("categoriaPesquisa").value = "categoriaSubCategoria2";
    gebi("codigoCategoriaBusca").value = gebi("selectMarca").value;
    gebi("subCategoriaSelecionada").value = gebi("selectMarca").value;
  } else if (gebi("selectFiltro") != null && gebi("selectFiltro").value != ''){
//    gebi("categoriaPesquisa").value = "categoriaSubCategoria1";
    gebi("codigoCategoriaBusca").value = gebi("selectFiltro").value;
    gebi("subCategoriaSelecionada").value = gebi("selectFiltro").value;
  } else if (categoriasDaLoja != null && categoriasDaLoja.style.display == "block" && categoriaSelecionada != ''){
//    gebi("categoriaPesquisa").value = "categoriaGrupo";
    gebi("codigoCategoriaBusca").value = categoriaSelecionada;
    gebi("subCategoriaSelecionada").value = categoriaSelecionada;
  } else {
	  alertaMensagem("Atenção!",'Mensagem de Erro','Selecione uma categoria para efetuar a busca');
	  	
    return;
  }
  
  gebi("listagemProdutos").innerHTML = 'Carregando...';
  gebi("listagemProdutos").style.display = 'block';
  
  var httpRequest = createHttpRequest();
  var args = '';
  
  args = 'codigoCategoriaBusca='+ document.getElementById('codigoCategoriaBusca').value;
  args += '&paginaAtual='+ document.getElementById('paginaAtual').value;

  itensPagina = document.getElementById('itensPorPagina');
  if(itensPagina != null) {
    itensPagina.options[itensPagina.selectedIndex]
    args += '&itensPorPagina='+ itensPagina.options[itensPagina.selectedIndex].value;
  }
  
  args += '&categoriaSelecionada=' + document.getElementById('categoriaSelecionada').value; 
  
  httpRequest.onreadystatechange = function() {
	  if (whenReady(httpRequest)) {
		  document.getElementById('listagemProdutos').innerHTML = httpRequest.responseText;
	  }
  }
  httpRequest.open('POST', 'buscarAvancadaAjax.do', true);
  
  if (args!=null && args.length>0) {  
    httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
    httpRequest.setRequestHeader("Content-length", args.length);
    httpRequest.setRequestHeader("Connection", "close");
    httpRequest.send(args);
  }else{  
    httpRequest.setRequestHeader("Content-length", 0);
    httpRequest.send("");
  }
}


function buscaAvancada() {
	
	document.busca.action='buscarAvancada.do';
	document.busca.urlSessao.value=location.href;
	document.busca.submit();
}
function validaCEP (zip) {

    
    
    if (zip.length == 0) {
		return false;
	}else {
		var zipRE = new RegExp('^(?:\\d{5}\\-\\d{3})$'); //nnnnn-nnn
		if (!zipRE.test(zip)) {
		
			return true;
		}
		else {
			return false;
		}
	}
   
}

/* AJAX
 * Funcao que busca os nomes e valores dos campos de um formulario (montando uma query string), testa se certos campos estap preenchidos, chama uma action por ajax e preenche um div com o retorno do jsp chamado pela action
 * Parametros: (hï¿½ um numero variavel de parametros, que sao os	 campos testados, por isso os parametros sao obtidos via o "arguments")
 *  - arguments[0]: id da div que serï¿½ exibida e preenchida
 *  - arguments[1]: id do formulario de onde serï¿½o obtidos os campos
 *  - arguments[2]: action chamada por ajax
 *  - arguments[3]: mensagem de erro quando hï¿½ campos não preenchidos
 *  - arguments[4..n] : ids campos que devem estar preenchidos
 *
 * USAGE: href="javascript:testaCamposMostraDiv('divParcelas','opcoesPagamento','parcelasCartaoCredito.do','creditoCodigoVerificacao','creditoNumeroCartao');"
 */
function testaCamposMostraDiv(){	
//	mudarDisplayBotao("validar", false);	
	arguments.shift = Array.prototype.shift;
	idDiv = arguments.shift();
	idFormulario = arguments.shift();
	actionChamada = arguments.shift();
	mensagemErro = arguments.shift();

	valoresFormulario = buscaValoresFormulario(idFormulario);
	
	if(testaCamposPreenchidos(arguments)){		
		document.getElementById(idDiv).style.display = '';
		document.getElementById(idDiv).innerHTML = "Carregando...";
				
		httpRequest = createHttpRequest();
		
		if(idDiv == "divParcelas"){
			mudaSelectOpcoesPagamento(true);
		}else{
			mudaSelectOpcoesPagamentoSecundaria(true);
		}
		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {					
					if(idDiv == "divParcelas"){						
						mudaSelectOpcoesPagamento(false);
					}else{						
						mudaSelectOpcoesPagamentoSecundaria(false);
					}						
					var text = httpRequest.responseText;					
					gebi(idDiv).innerHTML = text;					
					gebi(idDiv).style.display = '';					
					extraiScript(text);					
				}
			}
		httpRequest.open('POST', actionChamada, true);
		httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
		httpRequest.setRequestHeader("Content-length", valoresFormulario.length);
		httpRequest.setRequestHeader("Connection", "close");
		httpRequest.send(valoresFormulario);
//		mudarDisplayBotao("validar", true);
	}else{
//		mudarDisplayBotao("validar", true);
		document.getElementById(idDiv).style.display = 'none';
		alertaMensagem("Atenção!",'Mensagem de Erro',mensagemErro);				
	}

}


/* AJAX
 * Funcao que busca od logradouros com base em uma localidade
 * Parametros:
 *
 * USAGE: href="javascript:buscaLogradouros()"
 */
function buscaLogradouros(){
	var localidade =gebi('localidade');	
		
	if (localidade != null && localidade != "") {
		gebi("divLogradouro").innerHTML = "<p><span>Endereço</span><label>Carregando...</label></p>";
		args = 'codigoLocalidade='+localidade.value;
	
		var httpRequest = createHttpRequest();
		
		httpRequest.onreadystatechange = function() {
				if (whenReady(httpRequest)) {
					gebi('divLogradouro').innerHTML = httpRequest.responseText;
					extraiScript(httpRequest.responseText);
				}
			}
	
		httpRequest.open('POST', 'consultarLogradourosAction.do', true);		
		httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");			
		httpRequest.setRequestHeader('encoding','ISO-8859-1'); 

		httpRequest.setRequestHeader("Content-length", args.length);
		httpRequest.setRequestHeader("Connection", "close");		
		httpRequest.send(args);
	}else{
		gebi("divLogradouro").innerHTML = "<p><span>Endereço</span><strong>Nenhuma cidade selecionada</strong></p>";
	}
}



/* AJAX
 * Funcao que busca a quantidade de pontos do cliente
 * Parametros:
 *
 * USAGE: href="javascript:consultarPontosFidelidade()"
 */

function visualizarPedido(numero){
	
	if (numero!=null){
		$("#numero").val(numero);
		$("#visualizarPedidoForm").submit();
	}
	

} 
 
 function mudarDisplayBotao(idBotao, status){	
 	if(status == false){
		gebi(idBotao).style.display = "none";
// 		document.getElementById(idBotao).style.display = "none";
 	}else{
 		gebi(idBotao).style.display = "";
 	}
 }
 
function consultarPontosFidelidade() {

	var cartaoField =gebi('numero');
	var cpfField =gebi('cpf');
	var cartaoFieldRetorno = cartaoField.value;
	cartaoField.value = cartaoField.value.replace(/\D/g,"");
	var args = null;
	
	if (cartaoField.value == "" || cartaoField.value.length < 16 ) {
		alertaMensagem("Atenção!",'Mensagem de Erro','Por favor, informe o número do cartão com 16 dígitos.');
			cartaoField.focus();
	}else if (cpfField.value == "" ||!validateCPF(cpfField.value.replace(/\D/g,""))){
		alertaMensagem("Atenção!",'Mensagem de Erro','Por favor, informe seu CPF corretamente.');
			cpfField.focus();
		}else {
	
			if (cartaoField != null && evaluateField(cartaoField, 'int').length == 0) {
				args = 'cartao=' + cartaoField.value+'&cpf='+cpfField.value;
				
				gebi('pontos').innerHTML = 'Carregando...';
				gebi('linkConsultarFidelidade').style.display = "none";
				podeConsultar = false;
				
				var httpRequest = createHttpRequest();
				//mudarDisplayBotao("consultar2", false);
				httpRequest.onreadystatechange = function(){
					if (whenReady(httpRequest)) {
						//	mudarDisplayBotao("consultar2",true);
						gebi('pontos').innerHTML = httpRequest.responseText;
						gebi('linkConsultarFidelidade').style.display = "";
						podeConsultar = true;
					}
					
				}
				
				httpRequest.open('POST', 'ajaxConsultarFidelidade.do', true);
				if (args != null && args.length > 0) {
					httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
					httpRequest.setRequestHeader("referer", "/ajaxConsultarFidelidade.do");
					httpRequest.setRequestHeader('encoding', 'ISO-8859-1');
					httpRequest.setRequestHeader("Content-length", args.length);
					httpRequest.setRequestHeader("Connection", "close");
					httpRequest.send(args);
				}
				else {
					httpRequest.setRequestHeader("Content-length", 0);
					httpRequest.send("");
				}
				
			}
			cartaoField.value = cartaoFieldRetorno;
	}
}


/* AJAX
 * Funcao que recalcula o carrinho na tela de compra
 * Parametros:
 *
 * USAGE: href="javascript:recalculaCarrinhoOpcoesPagamento()"
 */
function recalculaCarrinhoOpcoesPagamento(){
	var httpRequest = createHttpRequest();
	
	var queryString = "";	

	crmMedicoArray = document.getElementsByName("crmMedico");
	estadoMedicoArray = document.getElementsByName("estadoMedico");
	dataReceitaArray = document.getElementsByName("dataReceita");

	for(i = 0; i < crmMedicoArray.length; i++){
		queryString += "&crmMedico="+crmMedicoArray[i].value+"&estadoMedico="+estadoMedicoArray[i].value+"&dataReceita="+dataReceitaArray[i].value;		
	}
	
	gebi('divCarrinhoOpcoesPagamento').innerHTML = "Carregando...";
	
	formaPagamentoSelecionadaObjeto = $("[name=tipoPagamento]:checked");	
	if(formaPagamentoSelecionadaObjeto.attr("nomeDiv") != null && (formaPagamentoSelecionadaObjeto.attr("nomeDiv") == "dinheiro" || formaPagamentoSelecionadaObjeto.attr("nomeDiv") == "boleto" || formaPagamentoSelecionadaObjeto.attr("nomeDiv") == "cartao"))	{
		queryString += "&semConvenio=true";
	}
	
	httpRequest.onreadystatechange = function() {
			if (whenReady(httpRequest)) {
				texto = httpRequest.responseText;
				gebi('divCarrinhoOpcoesPagamento').innerHTML = texto;
				extraiScript(texto);
			}
		}
		
	httpRequest.open('POST', 'recalcularCarrinhoOpcoesPagamentoAction.do', true);	
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
	httpRequest.setRequestHeader("Content-length", queryString.length);
	httpRequest.setRequestHeader("Connection", "close");
	httpRequest.send(queryString);
}
function mudaValoresRecalculoCarrinho(valorTotal,valorNaoContemplado){
	valorTotalFloat = parseFloat(valorTotal.replace(/[^0-9\,]/g,'').replace(",","."));
	valorNaoContempladoFloat = parseFloat(valorNaoContemplado.replace(/[^0-9\,]/g,'').replace(",","."));
	
	if($("[name=tipoPagamento]:checked").attr('nomeDiv') == "dinheiro"){
		//recalcula dinheiro
		gebi("valorTotalDinheiroHidden").value = valorTotalFloat;
		gebi("valorTotalDinheiro").innerHTML = "R$ "+valorTotalFloat.toFixed(2).replace(".",",");
		if(gebi('dinheiroValorPagamento') != null &&gebi('dinheiroValorPagamento').disabled == true){
			gebi('dinheiroValorPagamento').disabled = false;			
		}
		calculaTroco(valorTotal);
	}
	if(gebi("tipoPagamentoSec") != null){
		//recalcula dinheiro secundario		
		gebi("valorTotalDinheiroSecHidden").value = valorNaoContempladoFloat;
		gebi("valorTotalDinheiroSec").innerHTML = "R$ "+valorNaoContempladoFloat.toFixed(2).replace(".",",");;
		if(gebi('dinheiroValorPagamentoSec') != null &&gebi('dinheiroValorPagamentoSec').disabled == true){
			gebi('dinheiroValorPagamentoSec').disabled = false;						
		}
		calculaTrocoSec(valorNaoContemplado);		
	}
	

	if(gebi('divValorNaoContemplado') != null){
		gebi("divValorNaoContemplado").innerHTML = "R$ "+valorNaoContempladoFloat.toFixed(2).replace(".",",");;
	}	
}


/* AJAX
 * Funcao para alterar o cep da sessao
 * Parametros:
 *
 * USAGE: href="javascript:alterarCep()"
 */
var cont = 0;
function alterarCep() {
	var cepField1 = gebi('input_cep1');
	var cepField2 = gebi('input_cep2');

	var cepField = document.createElement("input");
	cepField.value = cepField1.value+"-"+cepField2.value;
	var args = null;
		
		//ajaxRequest('execute',{novoCep:cepField});
		
		args = 'novoCep='+cepField.value;
	
		var httpRequest = createHttpRequest();
		
		httpRequest.onreadystatechange = function() {			
				if (whenReady(httpRequest)) {
					texto = httpRequest.responseText;
					extraiScript(texto);
					window.location.reload();					
				}
			}	
		httpRequest.open('POST', 'alterarCep.do', true);
		
		if (args!=null && args.length>0) {
			
			httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
			httpRequest.setRequestHeader("Content-length", args.length);
			httpRequest.setRequestHeader("Connection", "close");
			httpRequest.send(args);
			
		}else{			
			httpRequest.setRequestHeader("Content-length", 0);
			httpRequest.send("");
		}
}


/* AJAX
 * Funcao que checa se o request esta pronto
 * Parametros:
 *  - httpRequest: request utilizado
 *
 * USAGE: httpRequest.onreadystatechange = function() { if(whenReady(httpRequest)) { return; } }
 */

function whenReady(httpRequest){
	if (httpRequest.readyState == 4) {		
		if (httpRequest.status == 200) {
			//the function is ready to be processed			
    	 	return true;
		} else {
			
			return false;
		}
	} else {
		return false;
	}
}


/* AJAX
 * Funcao que cria um novo request, cross browser compatible
 * Parametros:
 * 	-
 *
 * USAGE: var httpRequest = createHttpRequest();
 */
function createHttpRequest()
{
   
	var xmlHttp;
	try  {
	  // Firefox, Opera 8.0+, Safari
	  xmlHttp=new XMLHttpRequest();
	}catch (e){
	  // Internet Explorer
	  try{
	    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	  }catch (e){
	    try{
	     	 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	     }catch (e){
	    	 alertaMensagem("Atenção!",'Mensagem de Erro','Erro: seu browser não suporta a tecnologia Ajax.');	    	 			      
		     return false;
	      }
		}
	}
  	return xmlHttp;
   
}

function QueryStringParser(queryString) { 
	//array que conterï¿½ o hashmap nome-valor
	this.parametrosArray = new Object();
	//seta funcao que busca a string
	this.buscaParametro = queryStringBusca;
		
	if (queryString == null){
		return;
	}
		
	parametrosQueryString = queryString.split('&') 

	for(i = 0; i < parametrosQueryString.length; i++) {
		var valor = "";
		var parametroSplit = parametrosQueryString[i].split('=');
		var nome = unescape(parametroSplit[0]);

		if (parametroSplit.length == 2)
			valor = unescape(parametroSplit[1]);
		else
			valor = nome
		
		this.parametrosArray[nome] = valor;
	}
}

function queryStringBusca(chave, padrao) {	
	if (padrao == null){
		padrao = null;
	}
	
	var valor = this.parametrosArray[chave];
	if (valor == null) {
		valor = padrao;
	}
	
	return valor;
}

/* AJAX
 * Funcao que busca o bairro com base em um logradouro
 */
function buscarBairroEndEntrega(codigoLogradouro) {
	
	var args = 'logradouro=' + codigoLogradouro;
	
	gebi("divBairro").innerHTML = '<p><span>Bairro:</span><label>Carregando...</label></p>';
	
	var httpRequest = createHttpRequest();
	
	httpRequest.onreadystatechange = function() {
		if (whenReady(httpRequest)) {
			gebi("divBairro").innerHTML = httpRequest.responseText;			
		}
	}
	
	httpRequest.open('POST', 'buscarBairroEnderecoEntrega.do', true);		
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");			
	httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
	httpRequest.setRequestHeader("Content-length", args.length);
	httpRequest.setRequestHeader("Connection", "close");		
	httpRequest.send(args);
}


/* AJAX
 * Funcao que busca as localidades com base em um CEP
 */
function buscaLocalidades(cep){
	var args = 'cep='+cep;
	gebi("divLocalidade").innerHTML = "<p><span>Cidade:</span><label>Carregando...</label></p><p><span>Estado:</span><label>Carregando...</label></p>";
	gebi("cadastroClienteCep").value=cep.substring(0,5)+'-'+cep.substring(5,8);
	var httpRequest = createHttpRequest();
	
	httpRequest.onreadystatechange = function() {
		if (whenReady(httpRequest)) {
			gebi("divLocalidade").innerHTML = httpRequest.responseText;			
			buscaLogradouros(cep);
		}
	}
	
	httpRequest.open('POST', 'consultarLocalidadesAction.do', true);		
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");			
	httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
	httpRequest.setRequestHeader("Content-length", args.length);
	httpRequest.setRequestHeader("Connection", "close");		
	httpRequest.send(args);
		
}

function submitCadastrarClienteCarrinho(acao) {
	document.login.action = acao;
	document.login.submit();
}

/**
 * Funï¿½ï¿½es utilizadas para exibiï¿½ï¿½o e manipulaï¿½ï¿½o do painel de busca simples
 */
var abaClick = '';

function gebi(sObjId) {
	return document.getElementById(sObjId);
}



function setCategoria(sCategoria) {
	gebi('categoria').value = sCategoria;
}

function Trim(str) {
	return str.replace(/^\s+|\s+$/g,"");
}

function validaPesquisar(){
	oBusca =gebi('termoPesquisa');
	var termo = Trim(oBusca.value);
	
	if (termo == null || termo == 'Procure por palavra-chave ou nome do produto' || termo.length < 3) {
		alertaMensagem("Atenção!",'Mensagem de Erro','Para que a busca possa ser efetuada devem ser informados pelo menos 3 caracteres!');				
		return false;
	} else {		
		return true;
	}
}
function pesquisar() {
	oBusca =gebi('termoPesquisa');
	if (oBusca.value.length < 3) {
		alertaMensagem("Atenção!",'Mensagem de Erro','Para que a busca possa ser efetuada devem ser informados pelo menos 3 caracteres!');				
	} else {
		gebi('buscaForm').submit()
	}
}

function vaiParaPagina(pagina) {
	document.formListagemProdutos.paginaAtual.value = pagina;	
	document.formListagemProdutos.submit();
}

function vaiParaLetra(letra) {
	document.formListagemProdutos.letraAtual.value = letra;
	document.formListagemProdutos.paginaAtual.value = '1';	
	document.formListagemProdutos.submit();
}

function vaiParaPaginaAvancada(pagina) {
	document.getElementById('paginaAtual').value = pagina;
	
	
	buscarProdutosBuscaAvancada();
	//document.buscarAvancada.submit();
}




function excluirCarrinho(iCarrinhoId) {
	oCarrinhoId =gebi('oCarrinhoId');
	oCarrinhoId.value = iCarrinhoId;
	
	var oFormCarrinho =gebi('oFormCarrinho');
	oFormCarrinho.action = 'excluirCarrinho.do';
	oFormCarrinho.submit();
}


function visualizarCarrinho(iCarrinhoId) {
	oCarrinhoId =gebi('oCarrinhoId');
	oCarrinhoId.value = iCarrinhoId;
	
	var oFormCarrinho =gebi('oFormCarrinho');
	oFormCarrinho.action = 'recarregarCarrinho.do';
	oFormCarrinho.submit();
}

/**
 * Novo menu
*/
function ativaAba(aba){
	local = document.getElementById(aba);
	
	if(aba == 'boxLojas'){
		document.getElementById('boxProdutos').className = '';
		document.getElementById('boxProdutosAba').innerHTML = '<a href="javascript://" onclick="ativaAba(\'boxProdutos\')">Produtos</a>';
		document.getElementById('boxLojasAba').innerHTML = 'Lojas';
	}else{
		document.getElementById('boxLojas').className = '';
		document.getElementById('boxLojasAba').innerHTML = '<a href="javascript://" onclick="ativaAba(\'boxLojas\')">Lojas</a>';
		document.getElementById('boxProdutosAba').innerHTML = 'Produtos';
	}
	
	local.className = 'Ativo';
}
			
				


function funcaoSubmit(){
	document.formLinkBanner.submit();	
}

function getQueryStringParameters(){
  var params = {};
  var url = location.toString();
  var queryStringStart = url.indexOf('?');
  if(queryStringStart>-1){
    var queryString = url.substr(queryStringStart+1);
    var tmpParams = queryString.split('&');
    var tmpStr;
    for(var i=0;i<tmpParams.length;i++){
      tmpStr = tmpParams[i].split('=');
      params[tmpStr[0]] = tmpStr[1];
    }
  }
  return params;
}
			
function listagemProdutos(codigoCategoria, descricaoCategoria,codigoCategoriaPrimeiroPaiValido) {
	document.formListagemProdutos.paginaAtual.value = '1'; 
	document.formListagemProdutos.codigoCategoria.value = codigoCategoria;
	document.formListagemProdutos.descricaoCategoria.value = descricaoCategoria;	
	var divcaminho = document.getElementById('dynamicpath');
	strcaminho = divcaminho.innerHTML;
	document.formListagemProdutos.caminhoMenu.value = strcaminho;
	if(codigoCategoriaPrimeiroPaiValido != null && codigoCategoriaPrimeiroPaiValido != ""){
		document.formListagemProdutos.codigoCategoriaVoltar.value = codigoCategoriaPrimeiroPaiValido
	}
	document.formListagemProdutos.codigoCategoriaTopo.value = codigoCategoria;
	if(gebi("lancamentos") != null){
		gebi("lancamentos").value = "";
	}
	document.formListagemProdutos.submit();
}
	

/*----------------------------------------------------------------------------
Formataï¿½ï¿½o para qualquer mascara
-----------------------------------------------------------------------------*/
function formatar(src, mask, event){
  
  if(formatNumbers(src,event)) {
	  var i = src.value.length;
	  var saida = mask.substring(0,1);
	  var texto = mask.substring(i)
	if (texto.substring(0,1) != saida)
	  {
	    src.value += texto.substring(0,1);
	  }
	  
	  return true;
  } else {
  	return false;
  }
  
}


function trim(str){
	str=str.replace(/\s+/g," ");
	str=str.replace(/^ /,"");
	str=str.replace(/ $/,"");
	return str;
}

/*
 * Valida a numero de cartao do convenio a prazo
 */
 function validaConvenioPrazo(campo){
 	valor = campo.value;
 	var erros = false;
    var mensagem = "";
	 
	if(valor == "") {
		campo.setAttribute("erro","true");
	}else{
		if(valor.length < 16){
			erros = true;
			mensagem = "Por favor, digite o número de cartão com 16 digitos.";
		}
		 
		var apenasNumeros = /[0-9]/;
	    
	    if (!apenasNumeros.test(valor)) {
	         erros = true;
		   	 mensagem = "Por favor, digite o número de cartão corretamente.";
	    }
	  
	    if(erros == true){
	    	alertaMensagem("Atenção!",'Mensagem de Erro',mensagem);	
			campo.setAttribute("erro","true");
		}else{
			campo.setAttribute("erro","false");
		}
	}
     	
    
 }
 
 function viewDivEsqueciSenha() {
	gebi('email2').value = gebi('email').value;
 	gebi('esqueci_senha_box').style.display = '';
 	gebi('login_box').style.display = 'none';
 }
 function viewDivLogin() {
 	gebi('login_box').style.display = '';
 	gebi('esqueci_senha_box').style.display = 'none';
 }
 
 function viewDivLoginLayer() {
 	gebi('loginLayerForm').style.display = '';
 	gebi('esqueci_senha_box').style.display = 'none';
 }
 function viewDivEsqueciSenhaLayer() {
	gebi('email2').value = gebi('email').value;
 	gebi('esqueci_senha_box').style.display = '';
 	gebi('loginLayerForm').style.display = 'none';
 }
 
 
 function formatarTelefone(field) {
 	
 	var telefone = field.value;
 	var telefoneComFormat = '';
 	var tamanho = telefone.length;
 	
 	if(tamanho > 0) { 
	 	if(tamanho < 6) {
	 		alertaMensagem("Atenção!",'Mensagem de Erro','Telefone inválido');
	 	} else if(telefone.indexOf("-") < 0){
		 	telefone = telefone.replace("-","");
		 	telefoneComFormat = telefone.substring(0,4);
		 	telefoneComFormat += '-';
		 	telefoneComFormat += telefone.substring(4,tamanho); 
		 	
		 	field.value = telefoneComFormat;
	 	}
 	}
 }
 
 function maxLength(textAreaField, limit) {
	var ta = document.getElementById(textAreaField);
	
	if (ta.value.length > limit) {
		ta.value = ta.value.substring(0, limit);
	}
}





function adicionarEmailAlternativo(){	
	atributo = parseInt(gebi("linkAdicionar").getAttribute("contadorEmails"));	
	if (atributo <= 2) {
		gebi("emailAlternativo" + atributo).style.display = '';
		atributo++;
		gebi("linkAdicionar").setAttribute("contadorEmails", atributo);
		if(atributo > 2){
			gebi("linkAdicionar").style.display = "none";
		}
	}else{
		gebi("linkAdicionar").style.display = "none";
		
	}
}
function adicionarTelefoneAlternativo(){
	atributo = parseInt(gebi("linkAdicionarTelefone").getAttribute("contadorTelefones"));	
	if (atributo <= 2) {
		gebi("telefoneAlternativo" + atributo).style.display = '';
		atributo++;
		gebi("linkAdicionarTelefone").setAttribute("contadorTelefones", atributo);
		if(atributo > 2){
			gebi("linkAdicionarTelefone").style.display = "none";
		}
	}else{
		gebi("linkAdicionarTelefone").style.display = "none";		
	}
}

function mudaDisplay(idCampo,valorDisplay){
	gebi(idCampo).style.display = valorDisplay;
}

function limparCamposEndereco(){
	gebi("cadastroClienteCep").value = "";
	gebi("identificadorEndereco").value = "";
	gebi("cadastroClienteEnderecoNumero").value = "";
	gebi("cadastroClienteEnderecoComplemento").value = "";
	//gebi("cadastroClienteDdd").value = "";
	//gebi("cadastroClienteTelefone").value = "";
	gebi("referencia").value = "";
	if(gebi("logradouro") != null){
		gebi("logradouro").value = "";	
	}
	if(gebi("localidade") != null){
		gebi("localidade").value = "";	
	}
	gebi("divLogradouro").innerHTML = "";
	gebi("divBairro").innerHTML = "";
	gebi("divLocalidade").innerHTML = "<ul><li>Cidade*</li><li class=\"font2 padB\"></li><li>Estado*</li><li class=\"font2 padB\"></li></ul>";
}

function limparCampos() {
	gebi('faleConoscoForm').reset();
	
}
		
function submitThis() {
	nome =gebi('nome');
	email =gebi('email');
	assunto =gebi('assunto');
	mensagem =gebi('mensagem');
	
	if (nome!=null && nome.value!='' && email!=null && email.value!='' && mensagem!=null && mensagem.value!='' &&
		assunto!=null && assunto.options[assunto.selectedIndex].value!='-1') {
		
		var mensagem = '';
		mensagem += evaluateField(nome,'name');
		mensagem += evaluateField(email,'email');
		
		if (mensagem.length<=0) {				
		
			document.forms['faleConoscoForm'].submit();
			return;
		} else {
			alertaMensagem("Atenção!",'Mensagem de Erro',mensagem);
			return;
		}
	} else {
		alertaMensagem("Atenção!",'Mensagem de Erro','Por favor, preencha os campos obrigatórios.');				
		return;
	}	
}

function testaCamposObrigatorios(formulario){
	
	inputsFormulario = formulario.getElementsByTagName("input");
	selectsFormulario = formulario.getElementsByTagName("select");
	
	erro = false;
	retorno = "Os seguintes campos são obrigatórios e devem ser preenchidos:<br />";
	if(inputsFormulario.length > 0){
		for(i=0; i < inputsFormulario.length; i++){
			inputFormulario = inputsFormulario[i];
			if(inputFormulario.type == "text" && inputFormulario.getAttribute("nomeValidacaoObrigatoria") != null && inputFormulario.getAttribute("nomeValidacaoObrigatoria") != ""){
				if(inputFormulario.value == "" || inputFormulario.style.borderLeftColor == "red"){
					erro = true;
					retorno += inputFormulario.getAttribute("nomeValidacaoObrigatoria")+";<br />";
				}				
			}
		}
	}
	
	if(selectsFormulario.length > 0){
		for(i=0; i < selectsFormulario.length; i++){
			selectFormulario = selectsFormulario[i];
			if(selectFormulario.getAttribute("nomeValidacaoObrigatoria") != null && selectFormulario.getAttribute("nomeValidacaoObrigatoria") != "" ){
				if(selectFormulario.options[selectFormulario.selectedIndex].value == "" ){
					erro = true;
					retorno += selectFormulario.getAttribute("nomeValidacaoObrigatoria")+";<br />";
				}
			}			
		}
	}
	if(erro == true){
		alertaMensagem("Atenção!",'Mensagem de Erro',retorno);
		return false;
	}else{
		return true;
	}
	
}

function validaFormEtapa1(formulario){
	if(gebi("cidade") != null){
		gebi("cidade").setAttribute("nomeValidacaoObrigatoria","Cidade");
	}
	return testaCamposObrigatorios(formulario);
}

function validaFormEtapa3(formulario){
	valorSelecionadoGrau =gebi("grauInstrucao").options[gebi("grauInstrucao").selectedIndex].value;
	if(valorSelecionadoGrau == '4' || valorSelecionadoGrau == '6' || valorSelecionadoGrau == '8'){		
		gebi("serieSemestre").setAttribute("nomeValidacaoObrigatoria","Grau de Instrução");
	}else{		
		gebi("serieSemestre").setAttribute("nomeValidacaoObrigatoria",null);
	}
	return testaCamposObrigatorios(formulario);
}

function validaFormEtapa4(formulario){
	emprego1 =gebi("emprego1");
	if(emprego1.checked == false){
		document.getElementById("nomeEmpresa1").setAttribute("nomeValidacaoObrigatoria","Nome da Empresa");
		document.getElementById("dataAdmissao1").setAttribute("nomeValidacaoObrigatoria","Data de Admissão");
		document.getElementById("dataDemissao1").setAttribute("nomeValidacaoObrigatoria","Data de Demissão");
		document.getElementById("tarefasRealizadas1").setAttribute("nomeValidacaoObrigatoria","Tarefas Realizadas");
		document.getElementById("motivoSaida1").setAttribute("nomeValidacaoObrigatoria","Motivo da Saída");
		document.getElementById("cargoInicial1").setAttribute("nomeValidacaoObrigatoria","Cargo Inicial");
		document.getElementById("cargoFinal1").setAttribute("nomeValidacaoObrigatoria","Cargo Final");
		document.getElementById("setorInicial1").setAttribute("nomeValidacaoObrigatoria","Setor Inicial");
		document.getElementById("setorFinal1").setAttribute("nomeValidacaoObrigatoria","Setor Final");
		document.getElementById("dddEmpresa1").setAttribute("nomeValidacaoObrigatoria","DDD Empresa");
		document.getElementById("telefoneEmpresa1").setAttribute("nomeValidacaoObrigatoria","Telefone Empresa");
		document.getElementById("salarioInicial1").setAttribute("nomeValidacaoObrigatoria","Salário Inicial");
		document.getElementById("salarioFinal1").setAttribute("nomeValidacaoObrigatoria","Salário Final");
		document.getElementById("contatoEmpresa1").setAttribute("nomeValidacaoObrigatoria","Contato na Empresa");		
		for ( var contador = 2; contador <= 3; contador++) {
			valores = document.getElementById("nomeEmpresa"+contador).value+
			document.getElementById("dataAdmissao"+contador).value+
			document.getElementById("dataDemissao"+contador).value+
			document.getElementById("tarefasRealizadas"+contador).value+
			document.getElementById("motivoSaida"+contador).value+
			document.getElementById("cargoInicial"+contador).value+
			document.getElementById("cargoFinal"+contador).value+
			document.getElementById("setorInicial"+contador).value+
			document.getElementById("setorFinal"+contador).value+
			document.getElementById("dddEmpresa"+contador).value+
			document.getElementById("telefoneEmpresa"+contador).value+
			document.getElementById("salarioInicial"+contador).value+
			document.getElementById("salarioFinal"+contador).value+
			document.getElementById("contatoEmpresa"+contador).value
			
			if(valores != ""){
				document.getElementById("nomeEmpresa"+contador).setAttribute("nomeValidacaoObrigatoria","Nome da Empresa");
				document.getElementById("dataAdmissao"+contador).setAttribute("nomeValidacaoObrigatoria","Data de Admissão");
				document.getElementById("dataDemissao"+contador).setAttribute("nomeValidacaoObrigatoria","Data de Demissão");
				document.getElementById("tarefasRealizadas"+contador).setAttribute("nomeValidacaoObrigatoria","Tarefas Realizadas");
				document.getElementById("motivoSaida"+contador).setAttribute("nomeValidacaoObrigatoria","Motivo da Saída");
				document.getElementById("cargoInicial"+contador).setAttribute("nomeValidacaoObrigatoria","Cargo Inicial");
				document.getElementById("cargoFinal"+contador).setAttribute("nomeValidacaoObrigatoria","Cargo Final");
				document.getElementById("setorInicial"+contador).setAttribute("nomeValidacaoObrigatoria","Setor Inicial");
				document.getElementById("setorFinal"+contador).setAttribute("nomeValidacaoObrigatoria","Setor Final");
				document.getElementById("dddEmpresa"+contador).setAttribute("nomeValidacaoObrigatoria","DDD Empresa");
				document.getElementById("telefoneEmpresa"+contador).setAttribute("nomeValidacaoObrigatoria","Telefone Empresa");
				document.getElementById("salarioInicial"+contador).setAttribute("nomeValidacaoObrigatoria","Salário Inicial");
				document.getElementById("salarioFinal"+contador).setAttribute("nomeValidacaoObrigatoria","Salário Final");
				document.getElementById("contatoEmpresa"+contador).setAttribute("nomeValidacaoObrigatoria","Contato na Empresa");	
			}else{
				document.getElementById("nomeEmpresa"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("dataAdmissao"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("dataDemissao"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("tarefasRealizadas"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("motivoSaida"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("cargoInicial"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("cargoFinal"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("setorInicial"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("setorFinal"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("dddEmpresa"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("telefoneEmpresa"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("salarioInicial"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("salarioFinal"+contador).setAttribute("nomeValidacaoObrigatoria","");
				document.getElementById("contatoEmpresa"+contador).setAttribute("nomeValidacaoObrigatoria","");	
			}
		}
	}else{
		for ( var contador = 1; contador <= 3; contador++) {
			document.getElementById("nomeEmpresa"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("dataAdmissao"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("dataDemissao"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("tarefasRealizadas"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("motivoSaida"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("cargoInicial"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("cargoFinal"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("setorInicial"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("setorFinal"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("dddEmpresa"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("telefoneEmpresa"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("salarioInicial"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("salarioFinal"+contador).setAttribute("nomeValidacaoObrigatoria","");
			document.getElementById("contatoEmpresa"+contador).setAttribute("nomeValidacaoObrigatoria","");	
			
			document.getElementById("nomeEmpresa"+contador).value = "";
			document.getElementById("dataAdmissao"+contador).value = "";
			document.getElementById("dataDemissao"+contador).value = "";
			document.getElementById("tarefasRealizadas"+contador).value = "";
			document.getElementById("motivoSaida"+contador).value = "";
			document.getElementById("cargoInicial"+contador).value = "";
			document.getElementById("cargoFinal"+contador).value = "";
			document.getElementById("setorInicial"+contador).value = "";
			document.getElementById("setorFinal"+contador).value = "";
			document.getElementById("dddEmpresa"+contador).value = "";
			document.getElementById("telefoneEmpresa"+contador).value = "";
			document.getElementById("salarioInicial"+contador).value = "";
			document.getElementById("salarioFinal"+contador).value = "";
			document.getElementById("contatoEmpresa"+contador).value = "";
		}
		
	}
	
	return testaCamposObrigatorios(formulario);
}

/* AJAX
 * Funcao que realiza o aviseme
 */
function aviseMe(codigoItem,excluirProduto){
	var args = 'codigoItem='+codigoItem;
	
	if (document.getElementById('aviseMeNome' + codigoItem) != null) {
		args += '&nomeCliente=' + (document.getElementById('aviseMeNome' + codigoItem).value);
	}
	if (document.getElementById('aviseMeEmail' + codigoItem) != null) {
		args += '&emailCliente=' + document.getElementById('aviseMeEmail' + codigoItem).value;
	}
	if(excluirProduto != null && excluirProduto == true){
		args += '&excluirItemCodigo='+codigoItem;
	}
	var httpRequest = createHttpRequest();
	
	httpRequest.onreadystatechange = function() {
		if (whenReady(httpRequest)) {
			var resposta = httpRequest.responseText;			
			extraiScript(resposta);
			
		}
	}

	httpRequest.open('POST', 'aviseMe.do?'+args, true);		
	//httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");			
	//httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
	//httpRequest.setRequestHeader("Content-length", args.length);
	//httpRequest.setRequestHeader("Connection", "close");		
	httpRequest.send(args);
		
}

function popupCentralizado(url,windowName, popupWidth, popupHeight) {
	var left = screen.width / 2 - popupWidth / 2;
	var top = screen.height / 2 - popupHeight / 2;
	window.open(url,windowName, 'left=' + left + ', top=' + top + ', width=' + popupWidth + ', height=' + popupHeight + ', location=no, menubar=no, resizable=no, scrollbars=no, status=no, toolbar=no');
	
}
function indiqueAmigo(codigoItem) {
	var args = 'codigoItem=' + codigoItem;
	popupCentralizado('indiqueAmigo.do?' + args,'indiqueAmigoWindow',425,590);
	
}

function enviarIndiqueAmigo() {
	var msg = '';
	
	if (document.formEnviarIndiqueAmigo.emailAmigo.value == '') {
		msg += 'Por favor, entre com o email do seu amigo.<br />';
	}
	
	if (msg != '') {
		alertaMensagem("Atenção!",'Mensagem de Erro',msg);
	}
	else {
		document.formEnviarIndiqueAmigo.submit();
	}
}

function cepTab() {
	var div =gebi('seucep_info');
	var btn =gebi('seucep');
	
	if (div.style.display=='none') {
		div.style.display = '';
		btn.style.display = 'none';
		gebi("seucepaux").style.display = "";
	} else {
		div.style.display = 'none';
		btn.style.display = '';
		gebi("seucepaux").style.display = "none";
	}
	
}
function novoEndereco(){
	gebi("telefoneHidden").value =gebi("telefone").options[gebi("telefone").selectedIndex].value;
	gebi("formTelefone").submit();

}

function submeteFormularioComentario(){	
	if(gebi("texto").value == ""){
		alertaMensagem("Atenção!",'Mensagem de Erro','Por favor, preencha o campo Comentário');
		document.inserirComentarioProdutoForm.submit();
	}

}

function novaJanela(url,nomeJanela) {
	var nw = window.open(url,nomeJanela);
}
function testaTamanhoTexto(elementTextarea){	
	tamanhoMaximo = parseInt(elementTextarea.getAttribute("maxlength"));
	if(tamanhoMaximo >= elementTextarea.value.length){
		elementTextarea.value = elementTextarea.value.substring(0,tamanhoMaximo-1)
	}
}

function validaData(DATA,vdia,vmes,vano) {
    var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
    var msgErro = 'Formato inválido de data.';
    var vdt = new Date();

    
    if (DATA.value == '') {
    return true; 
    }
    
    if ((DATA.value.match(expReg)) && (DATA.value!='')){
            var dia = DATA.value.substring(0,2);
            var mes = DATA.value.substring(3,5);
            var ano = DATA.value.substring(6,10);
            if((mes==4 && dia > 30) || (mes==6 && dia > 30) || (mes==9 && dia > 30) || (mes==11 && dia > 30)){
            	alertaMensagem("Atenção!",'Mensagem de Erro','Data inválida. O mês especificado contém 30 dias.');            	            		
                DATA.focus();
                DATA.value = "";
                return false;
            } else{ 
                if(ano%4!=0 && mes==2 && dia>28){
                	alertaMensagem("Atenção!",'Mensagem de Erro','Data inválida. O mês especificado contém 28 dias.');                       
                    DATA.focus();
                    DATA.value = "";
                    return false;
                } else{ 
                    if(ano%4==0 && mes==2 && dia>29){
                    	alertaMensagem("Atenção!",'Mensagem de Erro','Data inválida. O mês especificado contém 29 dias.');                                               
                        DATA.focus();
                        DATA.value = "";
                        return false;
                    } else{ 
                        if ((ano < vano) || (ano == vano && mes < vmes) || (ano == vano && mes == vmes && dia < vdia)) {
                        	alertaMensagem("Atenção!",'Mensagem de Erro','Data inválida. Data informada é anterior a atual.');                                                   
                            DATA.focus();
                            DATA.value = "";
                            return false;
                        }else{  
                             return true;
                        } 
                    } 
                }
            }                      
    } else {
    	alertaMensagem("Atenção!",'Mensagem de Erro',msgErro);
        DATA.focus();
        DATA.value = "";
        return false;
    } 
}


function setarCampoHidden(id,valor){
	gebi(id).value = valor;
}

function limpaCampos(valor){
valor.focus;
valor.value = "";
}


/*
 * Formata um campo de hora (HH:mm) a medida que o usuario preenche os valores
 * Parametros:
 * - field: campo a ser preenchido
 * - event: evento
 *
 * USAGE: onkeypress="return formatTime(this,event);"
 */
function formatTime(field, event){
    var myfield = field.value;

    var keyCode = event.keyCode;
    var charCode = event.charCode;
    
    var deleteKey = false;
    var backspaceKey = false;
    var moveKey = false;
    
    if (keyCode==46 && charCode==0) deleteKey = true;
    if (keyCode==8 && charCode==0) backspaceKey = true;
    if (((keyCode>=33 && keyCode<=40) || keyCode==9) && charCode==0) moveKey = true;
    
    var tecla = charCode ? charCode : keyCode;
    
    if(document.selection) { 
      var testRange = document.selection.createRange().text;
      if((tecla>=48 && tecla<=57) && testRange.length > 0) {
        return true;
      }
    }else if (tecla>=48 && tecla<=57 && field.selectionStart < field.selectionEnd) {
      return true;
    }
    
    var caretPos = getCaretPosition(field);

    if (deleteKey || backspaceKey || moveKey) {
        return true;
    }
    
    var len = myfield.length;
    if(len>4){
      return false;
    }
    
    var chr = String.fromCharCode(tecla);
    
    if(chr==':' || (tecla>=48 && tecla<=57)){
      myfield = myfield.replace(/:/g,'');
      if(chr==':' && caretPos==2) { //tecla = ':' e cursor no lugar certo
        field.value = myfield.substring(0,2)+(caretPos==2 ? '' : ':')+
                     (myfield.length>2 ? myfield.substring(2,4) : '');
        setCaretPosition(field, caretPos);
        return true;
      }else if (chr==':' && caretPos==1) { //tecla=':' e cursor no lugar da unidade da hora
        field.value = '0'+myfield.substring(0,1)+
                      (myfield.length>2 ? myfield.substring(1,3) : '');
        setCaretPosition(field, caretPos+1);
        return true;
      }else if (tecla>=48 && tecla<=57 && caretPos<len) { //cursor no meio
        var indexHour = caretPos<2 ? 1 : 2;
        field.value = myfield.substring(0,indexHour)+(myfield.length>indexHour ? ':' : '')+
                      myfield.substring(indexHour,3);
        setCaretPosition(field, caretPos==2 ? caretPos+1 : caretPos);
        return true;
      }else if (tecla>=48 && tecla<=57) {
        field.value = myfield.substring(0,2)+(myfield.length>=2 ? ':' : '')+
                     (myfield.length>=2 ? myfield.substring(2,4) : '');
        setCaretPosition(field, caretPos+1);
        return true;
      }
      return false;
    }
    return false;
}


function validaHora(timeStr) {
	
	var timePat = /^((\d)|(0\d)|(1\d)|(2[0-3]))\:((\d)|([0-5]\d))$/;
	var errors = '';
	
	var matchArray = timeStr.value.match(timePat);
	if (matchArray == null) {	
	timeStr.value = "";
	errors += 'O formato da Hora nao é válido.';
	return errors;
	}
	hour = matchArray[1];
	minute = matchArray[2];	
	if (hour < 0  || hour > 23) {	
	timeStr.value = "";
	errors += 'A hora deve ser entre 0 e 23';
	return errors;
	}	
	if (minute<0 || minute > 59) {
	
	timeStr.value = "";
	errors += 'Os minutos devem ser entre 0 e 59.';
	return errors;
	}
	return "";
}

/*
 * Formata um campo de mes/ano (mm:yyyy) a medida que o usuario preenche os valores
 * Parametros:
 * - field: campo a ser preenchido
 * - event: evento
 *
 * USAGE: onkeypress="return formatMonthYear(this,event);"
 */
function formatMonthYear(field, event){
    var myfield = field.value;

    var keyCode = event.keyCode;
    var charCode = event.charCode;
    
    var deleteKey = false;
    var backspaceKey = false;
    var moveKey = false;
    
    if (keyCode==46 && charCode==0) deleteKey = true;
    if (keyCode==8 && charCode==0) backspaceKey = true;
    if (((keyCode>=33 && keyCode<=40) || keyCode==9) && charCode==0) moveKey = true;
    
    var tecla = charCode ? charCode : keyCode;
    
    if(document.selection) { 
      var testRange = document.selection.createRange().text;
      if((tecla>=48 && tecla<=57) && testRange.length > 0) {
        return true;
      }
    }else if (tecla>=48 && tecla<=57 && field.selectionStart < field.selectionEnd) {
      return true;
    }
    
    var caretPos = getCaretPosition(field);

    if (deleteKey || backspaceKey || moveKey) {
        return true;
    }
    
    var len = myfield.length;
    if(len>6){
      return false;
    }
    
    var chr = String.fromCharCode(tecla);
    
    if(chr=='/' || (tecla>=48 && tecla<=57)){
      myfield = myfield.replace(/\//g,'');
      if(chr=='/' && caretPos==2) { //tecla = '/' e cursor no lugar certo
        field.value = myfield.substring(0,2)+(caretPos==2 ? '' : '/')+
                     (myfield.length>2 ? myfield.substring(2,4) : '');
        setCaretPosition(field, caretPos);
        return true;
      }else if (chr=='/' && caretPos==1) { //tecla='/' e cursor no lugar da unidade do mes
        field.value = '0'+myfield.substring(0,1)+
                      (myfield.length>2 ? myfield.substring(1,3) : '');
        setCaretPosition(field, caretPos+1);
        return true;
      }else if (tecla>=48 && tecla<=57 && caretPos<len) { //cursor no meio
        var indexMonth = caretPos<2 ? 1 : 2;
        field.value = myfield.substring(0,indexMonth)+(myfield.length>indexMonth ? '/' : '')+
                      myfield.substring(indexMonth,5);
        setCaretPosition(field, caretPos==2 ? caretPos+1 : caretPos);
        return true;
      }else if (tecla>=48 && tecla<=57) {
        field.value = myfield.substring(0,2)+(myfield.length>=2 ? '/' : '')+
                     (myfield.length>=2 ? myfield.substring(2,6) : '');
        setCaretPosition(field, caretPos+1);
        return true;
      }
      return false;
    }
    return false;
}

function validateMesAno (date) {

	var RegExp = /^((0[1-9])|10|11|12)\/\d{4}$/;
	
	if(RegExp.test(date.value) == false){
		date.value = "";
		var errors ='Data inválida.';
		return errors;
	}
	return true;     	
}


function valor_maximo(max,id){
	if(gebi(id).value == "" || parseInt(gebi(id).value) == 0){
		gebi(id).value = "1";
	}else if(gebi(id).value <= max)
		return true;
	else{
		gebi(id).value = "1";
		alertaMensagem("Atenção!",'Mensagem de Erro','quantidade maior que a desejada.');				
		return false;
	}
}

function checkAll() { 
	   for (var i=0;i<document.emailListaPresente.elements.length;i++) {
	     var x = document.emailListaPresente.elements[i];
	     if (x.name == 'emailConvidado') { 
	    	 x.checked = true;
	     } 
	   } 
} 




function validaNewsletter() {
  
  var codigo =gebi("codigo"); 
  var dataEnvio =gebi("dataEnvio"); 
  var horaEnvio =gebi("horaEnvio"); 
  var arquivo =gebi("arquivo")

  var msg = ""; 
  
  msg += validateRequired(gebi('tituloNewsletter'),'Título da Newsletter');
  msg += validateRequired(gebi('dataEnvio'),'Data para envio');
  msg += validateRequired(gebi('horaEnvio'),'Hora para envio');
  if (codigo.value == null || codigo.value == "")
    msg += validateRequired(gebi('arquivo'),'Arquivo');
  msg += validateRequired(gebi('grupos'),'Grupos');

  //Valida a data/hora:
  if (validateRequired(gebi('dataEnvio'),'Data para envio') != "" && validateRequired(gebi('horaEnvio'),'Hora para envio') != "") {
    var dataAtual = new Date();
  
    var diaEnvio = dataEnvio.value.substr(0,2);
    var mesEnvio = dataEnvio.value.substr(3,2);
    var anoEnvio = dataEnvio.value.substr(6,7);
    var horEnvio = horaEnvio.value.substr(0,2);
    var minEnvio = horaEnvio.value.substr(3,2);
  
    var dataEnvio = new Date(anoEnvio, mesEnvio-1, diaEnvio, horEnvio, minEnvio, 0);
    
    if(dataEnvio < dataAtual) 
      msg += "<br />Data/Hora de envio não pode ser anterior à data/hora atual.";
  }    
  //Valida o tipo de arquivo
  if (codigo.value == null || codigo.value == "")
    if(arquivo.value.toLowerCase().indexOf('.zip') == -1)
      msg += "<br />O arquivo deve ser do tipo .zip";
  
  if (msg != "") {
	  alertaMensagem("Atenção!",'Mensagem de Erro',msg);	  	    
		return false;
  }
  
  return true;
}

function validaEmail(field) {
  var msg = validateEmail(field.value);
  
  if (msg != '') {
	alertaMensagem("Atenção!",'Mensagem de Erro',msg);  	
    field.focus();
    return false;
  }   
  
  return true;
}

function addEmail(field) {
  var emails =gebi("mailBox");

  if (field.value == '') {
	alertaMensagem("Atenção!",'Mensagem de Erro','Informe o e-mail.');
    field.focus();
    return false;
  }

  if (validaEmail(field)) 
    emails.options[emails.length] = new Option(field.value,field.value,false,false);
    field.value = "";   
}

function removeEmail() {
  var emails =gebi("mailBox");
  if (emails.selectedIndex != -1) 
    while (emails.selectedIndex != -1) {
      emails.options[emails.selectedIndex] = null
    }
  else{
	  alertaMensagem("Atenção!",'Mensagem de Erro','Selecione o e-mail que deseja excluir');
  }
}

function enviarEmailsTeste(){
  if (gebi("emails").length > 0) {
   gebi("method").value = "enviaEmailsTeste";
   gebi("adicionarNewsletterForm").submit();
  }
  else
	  alertaMensagem("Atenção!",'Mensagem de Erro','Nenhum e-mail foi informado.');
}

function submeteFormularioBuscaListaPresente(){
	if(gebi("nomeMae").value == "" &&gebi("dataCadastro").value == "" &&gebi("nomeBebe").value == "" &&gebi("local").value == ""){
		alertaMensagem("Atenção!",'Mensagem de Erro','Por favor, preencha pelo menos um dos campos.');
	}else{
		document.buscarListaPresentes.submit();
	}
}

function submeteFormulariocadastraListaPresente(){
	
	if(gebi("nomeMae").value == "" ||gebi("nomeListaPresente").value == "" ||gebi("dataHoraEvento").value == "" ||gebi("horaEventoAux").value == "" || (gebi("tipoEnderecoNovo").checked == true &&  (gebi("logradouro") == null ||gebi("logradouro").value == "" ||gebi("numero") == null ||gebi("numero").value == "" ||gebi("localidade") == null ||gebi("localidade").value == "")) ){
		alertaMensagem("Atenção!",'Mensagem de Erro','Por favor, preencha os campos obrigatórios.');
	}
	else{
		document.cadastrarListaPresentes.submit();
	}
}

function mostraCamposEmail(contador,acao){
	if(acao == "EDITAR"){
		gebi("nome"+contador).style.display = "";
		gebi("email"+contador).style.display = "";
		gebi("salvar"+contador).style.display = "";
		gebi("cancelar"+contador).style.display = "";
		gebi("editar"+contador).style.display = "none";
		gebi("excluir"+contador).style.display = "none";
		gebi("nomeAtual"+contador).style.display = "none";
		gebi("emailAtual"+contador).style.display = "none";
	}
	if(acao == "CANCELAR"){
		gebi("nome"+contador).style.display = "none";
		gebi("email"+contador).style.display = "none";
		gebi("salvar"+contador).style.display = "none";
		gebi("cancelar"+contador).style.display = "none";
		gebi("editar"+contador).style.display = "";
		gebi("excluir"+contador).style.display = "";
		gebi("nomeAtual"+contador).style.display = "";
		gebi("emailAtual"+contador).style.display = "";
	}
}


function salvaEmail(codigoEmail,contador){
	gebi("nomeAtualizado").value =gebi("novoNome"+contador).value;
	gebi("emailAtualizado").value =gebi("novoEmail"+contador).value;
	gebi("codigoEmail").value = codigoEmail;
	gebi("atualizarEmailListaPresente").submit();
}

function ajaxRequest(method,aditionalParameters,onEndCallback){
	  var httpRequest;
	  try{
	    // Browsers
	    httpRequest = new XMLHttpRequest();
	  }catch(e){
	    // IE
	    try{
	      httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
	    }catch(e){
	      try{
	        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
	      }catch(e){
	    	  alertaMensagem("Atenção!",'Mensagem de Erro','Erro: Seu navegador não suporta a tecnologia Ajax.');	    	
	        return false;
	      }
	    }
	  }
	  
	  var url = location.href;
	  var baseEnd = url.indexOf('?');
	  if(baseEnd == -1){
	    baseEnd = url.indexOf('#');
	    if(baseEnd == -1){
	      baseEnd = url.length;
	    }
	  }
	  url = url.substring(0,baseEnd);
	  
	  var parameters = 'method='+method;
	  for(var i in aditionalParameters){
	    parameters+= '&'+i+'='+escape(aditionalParameters[i]);
	  }
	  
	  httpRequest.open('POST',url,true);
	  httpRequest.onreadystatechange = function(){
	    if(httpRequest.readyState == 4){
	      if(httpRequest.status == 200){
	        try{
	          eval(httpRequest.responseText);
	        }catch(e){
	          //document.write(httpRequest.responseText);
	        	alertaMensagem("Atenção!",'Mensagem de Erro','Erro: A requisição não foi atendida corretamente.'+httpRequest.responseText.replace("'","\'",'g'));	        	
	        }
	        if(onEndCallback){
	          onEndCallback();
	        }
	      }else{
	    	  alertaMensagem("Atenção!",'Mensagem de Erro','Erro: A requisição não pôde ser atendida.');    	  	        
	      }
	    }
	  };
	  httpRequest.setRequestHeader('Content-type','application/x-www-form-urlencoded');
	  httpRequest.setRequestHeader('encoding','ISO-8859-1');
	  httpRequest.setRequestHeader('Connection','close');
	  httpRequest.send(parameters);
	  return true;
}

function closeLayer(){
	
		var args = null;
			
			args = 'fecharLayer=true';			
				
			var httpRequest = createHttpRequest();
			
			httpRequest.onreadystatechange = function() {			
					if (whenReady(httpRequest)) {
						texto = httpRequest.responseText;					
						extraiScript(texto);
						window.location.reload();					
					}
				}	
			httpRequest.open('POST', 'splash.do', true);
			
			if (args!=null && args.length>0) {
				
				httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
				httpRequest.setRequestHeader("Content-length", args.length);
				httpRequest.setRequestHeader("Connection", "close");
				httpRequest.send(args);
				
			}else{			
				httpRequest.setRequestHeader("Content-length", 0);
				httpRequest.send("");
			}
}

function buscaCategoriasLoja(){
  var l = gebi("selectLojas");
  var c = document.getElementsByName("selectCategoria");
  
  for (i = 0; i < c.length; i++) {
    c[i].selectedIndex = 0;
    if(c[i].id == l.options[l.selectedIndex].value) {
      c[i].style.display = 'block';
    } else
      c[i].style.display = 'none';
      
  }
  
  gebi("filtros").style.display = 'none';
  gebi("marcas").style.display = 'none';
  gebi("paginaAtual").value = 1;
  
  gebi('categoriaSelecionada').value= l.options[l.selectedIndex].value;

  if (l.options[l.selectedIndex].value == '')
    gebi("categorias").style.display = 'none';
  else
    gebi("categorias").style.display = 'block';
    
}

function buscaFiltrosDaCategoria(idLoja){
  var categoriasDaLoja = gebi(idLoja);
  var categoriaSelecionada = categoriasDaLoja.options[categoriasDaLoja.selectedIndex].value;

  if (categoriaSelecionada == '') {
	  gebi("marcas").style.display = 'none';
	  gebi("filtros").style.display = 'none';
    return;
  }
  gebi("paginaAtual").value = 1;
  gebi("marcas").style.display = 'none';
  gebi("filtros").innerHTML = '<div class="selecione_text">3. Selecione o filtro que será utilizado</div><label>Carregando...</label>';
  gebi("filtros").style.display = 'block';
  var args="";

  gebi("subCategoriaSelecionada").value = categoriaSelecionada;

  args = 'categoriaGrupo=' + categoriaSelecionada;
  args += '&categoria=null';

  var httpRequest = createHttpRequest();
  httpRequest.onreadystatechange = function() {
    if (whenReady(httpRequest)) {
      gebi("filtros").innerHTML = httpRequest.responseText;     
    }
  }
  
  httpRequest.open('POST', 'buscarCategoriasBuscaAvancada.do', true);    
  httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");      
  httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
  httpRequest.setRequestHeader("Content-length", args);
  httpRequest.setRequestHeader("Connection", "close");    
  httpRequest.send(args);
    
}

function buscarMarcasDaCategoria(){
  var filtro = gebi("selectFiltro");
  var filtroSelecionado = filtro.options[filtro.selectedIndex].value;

  if(filtroSelecionado == ''){
    gebi("marcas").style.display = 'none';
    return;
  }
  gebi("subCategoriaSelecionada").value = filtroSelecionado;
  gebi("paginaAtual").value = 1;
  gebi("marcas").innerHTML = '<div class="selecione_text">3. Selecione a marca</div><label>Carregando...</label>';
  gebi("marcas").style.display = 'block';
  
  args = 'categoriaSubCategoria1=' + filtroSelecionado;
  args += '&categoria=null&categoriaGrupo=null';
  
  var httpRequest = createHttpRequest();
  httpRequest.onreadystatechange = function() {
    if (whenReady(httpRequest)) {
      gebi("marcas").innerHTML = httpRequest.responseText;     
    }
  }
  
  httpRequest.open('POST', 'buscarCategoriasBuscaAvancada.do', true);    
  httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");      
  httpRequest.setRequestHeader('encoding','ISO-8859-1'); 
  httpRequest.setRequestHeader("Content-length", args);
  httpRequest.setRequestHeader("Connection", "close");    
  httpRequest.send(args);
}

function adicionarConvidado(){
  var req = '';
  
  req += validateRequired(gebi('novoNome'),'Nome');
  req += validateRequired(gebi('novoEmail'),'Email');
  
  if (req.length>0) {
	  alertaMensagem("Atenção!",'Mensagem de Erro',req);	  
    return;
  } 
  document.emailListaPresente.submit()
}




function validaLoginLayerForm(){
  email = $("#email").val(); 
  senha = $("#senha").val();
  msg = '';

  if (email == '' || senha == '')
    msg += "Informe seu e-mail e senha";

	if (msg != '') {
		$("#retornoLogin").html(msg);
		return false;       
	}else{
		try {
			pageTracker._trackPageview("/loginLayer.do?utm_source=LAYER&utm_medium=LINK&utm_campaign=LOGIN"); 
		} catch (e) {
			// TODO: handle exception
		}		
	}
}

function redirect(loc){
	window.location = loc;
}

function listaProdutosSuperGuia(categorias){
	if (categorias.options[categorias.selectedIndex].value != '') {
		$("#nomeCategoria").val(categorias.options[categorias.selectedIndex].getAttribute("descricao"));
		$("#codigoCorCategoria").val(categorias.options[categorias.selectedIndex].getAttribute("codigoCorCategoria"));
		$("#categoriaSuperGuiaForm").submit();
	}
	
}