//Esta funo simula a funo trim para o javascript
//uma funo trim elimina os espaos em branco de uma variavel
String.prototype.trim = function() {
	var x = this;
	x = x.replace(/^\s*(.*)/, "$1");
	x = x.replace(/(.*?)\s*$/, "$1");
	return x;
}


function verificaOpcao(opcao){
	if(opcao == 10){
		document.getElementById("div_ficou_sabendo_outros").style.display = "";
	}else{
		document.getElementById("div_ficou_sabendo_outros").style.display = "none";	
	}
}

function isEmail(email){
	var reEmail1 = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	if(email != ""){
	    if (!reEmail1.test(email)) {
		    return false;
	    }else{
	        return true;
	    }
    }
    return false;
}

function verificaPT(){
	var frm = document.contato;
	var msg = "";
	var retValidacao = valicadao();
	
	if (retValidacao == false) msg = $('#formAlerts').html();
	
	var objConfEmail = false;
	for (var i=0;i<frm.length;i++) {
		if (frm.elements[i].id.substr(0,13) == "emaiConflTxt_"){
			objConfEmail = frm.elements[i];
		}
	}

	if (objConfEmail != false){
		if (document.getElementById("emailTxt").value.trim() != objConfEmail.value.trim()){
			msg += "- E-Mail de confirmação diferente.";

			$(objConfEmail).addClass("error");
			$(document.getElementById("labelConfEmail")).addClass("error");

			$('#formAlerts').html(msg)
							.css("backgroundColor", colorBgAlertError)
							.animate({backgroundColor:colorBgAlert}, "slow");
			retValidacao = false;
		}
		
	}

	return retValidacao;
}


function verificaES(){

	frm = document.cadastro;
	msg = "";
  
	if (frm.nome.value.trim()=="") msg += "Nombre es obligatorio;\n";
	if (frm.empresa.value.trim()=="") msg += "Empresa es obligatorio;\n";
	if (frm.telefone.value.trim()=="") msg += "Teléfono es obligatorio;\n";
	if (frm.email.value.trim()=="") msg += "Correo electrónico es obligatorio;\n";
	if(frm.email.value.trim() != "" && !isEmail(frm.email.value.trim())) msg += "Correo electrónico inválido;\n";
	if (frm.email2.value.trim() != frm.email.value.trim()) msg += "Confirme su correo electrónico!;\n";
	if (frm.pais.value.trim()=="") msg += "País es obligatorio;\n";
	if (frm.estado.value.trim()=="") msg += "Estado /Provincia / Departamento es obligatorio;\n";
	if (frm.cidade.value.trim()=="") msg += "Ciudad es obligatorio;\n";
	if (frm.cep.value.trim()=="") msg += "Código Postal es obligatorio;\n";
	if(frm.area_interesse.value == "") msg += "Área de interés es obligatorio;\n";

	if(frm.area_interesse.options[frm.area_interesse.selectedIndex].text.trim() == "Comercial"){
		if(frm.segmento.value == "") msg += "Segmento es obligatorio;\n";
	}
	
	tem_selecionado = false;
	outro_selecionado = false;	
	for(var i=1; i<=10; i++){
		if(document.getElementById("ficou_sabendo"+i) != null){
			if(document.getElementById("ficou_sabendo"+i).checked){
				tem_selecionado = true;
				if(i==10){
					outro_selecionado = true;	
				}	
			}
		}
	}
	if(!tem_selecionado) {
		msg += "Seleccione la manera en la que conoció Audaces;\n";
	} else if(outro_selecionado && document.getElementById("ficou_sabendo_outros").value==""){
		msg += "Seleccione la manera en la que conoció Audaces;\n";
	}
	
	if (msg != "") {
		alert("Campos con * son obligatorios:\n-------------------------\n"+msg);
		return false;
	}else{
		return true;
	}
			
}


function verificaEN(){

	frm = document.cadastro;
	msg = "";

	if (frm.nome.value.trim()=="") msg += "Name is mandatory;\n";
	if (frm.empresa.value.trim()=="") msg += "Company is mandatory;\n";
	if (frm.telefone.value.trim()=="") msg += "Phone is mandatory;\n";
	if (frm.email.value.trim()=="") msg += "Mail is mandatory;\n";
	if(frm.email.value.trim() != "" && !isEmail(frm.email.value.trim())) msg += "Invalid Mail;\n";
	if (frm.email2.value.trim() != frm.email.value.trim()) msg += "Mail and its confirmation are different!;\n";
	if (frm.pais.value.trim()=="") msg += "Country is mandatory;\n";
	if (frm.estado.value.trim()=="") msg += "State is mandatory;\n";
	if (frm.cidade.value.trim()=="") msg += "Ciudad es obligatorio;\n";
	if (frm.cep.value.trim()=="") msg += "City is mandatory;\n";
	if(frm.area_interesse.value == "") msg += "Zip-code is mandatory;\n";

	if(frm.area_interesse.options[frm.area_interesse.selectedIndex].text.trim() == "Comercial"){
		if(frm.segmento.value == "") msg += "Segmento is mandatory;\n";
	}
	
	tem_selecionado = false;
	outro_selecionado = false;	
	for(var i=1; i<=10; i++){
		if(document.getElementById("ficou_sabendo"+i) != null){
			if(document.getElementById("ficou_sabendo"+i).checked){
				tem_selecionado = true;
				if(i==10){
					outro_selecionado = true;	
				}	
			}
		}
	}
	if(!tem_selecionado) {
		msg += "Inform how do you was knowing for Audaces;\n";
	} else if(outro_selecionado && document.getElementById("ficou_sabendo_outros").value==""){
		msg += "Inform how do you was knowing for Audaces;\n";
	}
	
	if (msg != "") {
		alert("Plase check the following details:\n-------------------------\n"+msg);
		return false;
	}else{
		return true;
	}
			
}


function verificaSelecionado(obj){
	var labelSegmento = document.getElementById("labelSegmento");
	if(obj.options[obj.selectedIndex].text.trim() == "Comercial"){
		labelSegmento.className = "val_noEmpty";
		labelSegmento.style.fontWeight = "bold";
		labelSegmento.innerHTML = labelSegmento.innerHTML + " *";
	}else{
		labelSegmento.className = "";
		labelSegmento.style.fontWeight = "normal";
		labelSegmento.innerHTML = "Segmento";
	}
}


var ajax = null;
function InicializaAjax(){
  //verifica se o browser tem suporte a ajax
   try {
		 ajax = new ActiveXObject("Microsoft.XMLHTTP");
	  } 
	  catch(e) {
		 try {
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
		 }
		 catch(ex) {
			try {
			   ajax = new XMLHttpRequest();
			}
			catch(exc) {
			   alert("Esse browser não tem recursos para uso do Ajax");
			   ajax = null;
			}
		 }
	  }
  return ajax;
}

function carregaCidades(objCidade, uf) {
  ajax = InicializaAjax();
  
  //se tiver suporte ajax
  if(ajax) {
	 //deixa apenas o elemento 1 no option, os outros são excluídos
	 objCidade.options.length = 1;
	 
	 idOpcao  = objCidade.options[0];
	 
	 ajax.open("POST", "xml_cidades.php", true);
	 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	 
	 ajax.onreadystatechange = function() {

		//enquanto estiver processando...emite a msg de carregando
		if(ajax.readyState == 1) {
		   idOpcao.innerHTML = "Carregando...";   
		}
		//após ser processado - chama função processXML que vai varrer os dados
		if(ajax.readyState == 4 ) {
		   if(ajax.responseXML) {
			  processXML(ajax.responseXML, objCidade);
		   }else{
			   //caso não seja um arquivo XML emite a mensagem abaixo
			   idOpcao.innerHTML = "";
		   }
		}
	 }

	 var params = "uf="+uf;
	 //alert("params: "+params);
	 ajax.send(params);
  }
}

function processXML(objResponseXML, objCidade){
  //pega a tag largura
  var dataArray   = objResponseXML.getElementsByTagName("cidade");
  
  //total de elementos contidos na tag largura
  if(dataArray.length > 0) {
	 //percorre o arquivo XML paara extrair os dados
	 for(var i = 0 ; i < dataArray.length ; i++) {
		var item = dataArray[i];
		//contéudo dos campos no arquivo XML
		var cidade    =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
		idOpcao.innerHTML = "Por favor, selecione.";
		idOpcao.value = ""
		
		//cria um novo option dinamicamente  
		var novo = document.createElement("option");
		//atribui um ID a esse elemento
		novo.setAttribute("id", "opcoes");
		//atribui um valor
		novo.value = cidade;
		//atribui um texto
		novo.text  = cidade;
		//finalmente adiciona o novo elemento
		objCidade.options.add(novo);
	 }
	 
  }else{
	//caso o XML volte vazio, printa a mensagem abaixo
	 idOpcao.innerHTML = "Selecione o estado";
  }	  
}

function mudaPais(obj){
	if (obj.options[obj.selectedIndex].value == "BR"){
		document.getElementById("cidadeTxt").style.display = "none";
		document.getElementById("ufTxt").style.display = "none";
		document.getElementById("cidadeSel").style.display = "";
		document.getElementById("ufLst").style.display = "";
		document.getElementById("cidadeSel").disabled = false;
		document.getElementById("ufLst").disabled = false;
		document.getElementById("cidadeLbl").setAttribute("for","cidadeSel");
		document.getElementById("ufLbl").setAttribute("for","ufLst");
		$("#cidadeLbl").attr("for", "cidadeSel"); //IE 8 não mudava via javascript
		$("#ufLbl").attr("for", "ufLst"); //IE 8 não mudava via javascript

	} else {
		document.getElementById("cidadeTxt").style.display = "";
		document.getElementById("ufTxt").style.display = "";
		document.getElementById("cidadeSel").style.display = "none";
		document.getElementById("ufLst").style.display = "none";
		document.getElementById("cidadeSel").disabled = true;
		document.getElementById("ufLst").disabled = true;
		document.getElementById("cidadeLbl").setAttribute("for","cidadeTxt");
		$("#cidadeLbl").attr("for", "cidadeTxt"); //IE 8 não mudava via javascript
		$("#ufLbl").attr("for", "ufTxt"); //IE 8 não mudava via javascript
	}
}