﻿var ALERT_TITLE = "Atenção";
var ALERT_BUTTON_TEXT = "Ok";

objFocus = new Object()
var urlRetornoAlert = "";
var retornoConfirm = ""
objFocus = null;
var historyBack = false;


//painelctrl
urlTemp = location.href.substring(0,location.href.indexOf('?') + 1);
if( urlTemp.split("/")[3] != "paineladm")
{
	if(document.getElementById) {
		window.alert = function(txt) {
			createCustomAlertSite(txt);
		}
		window.confirm = function(txt) {
			createCustomConfirmSite(txt);
		}
		
	}
	$(window).resize(function() {
			 	
		if( $("#caixaAlertaJavascript").length > 0 )
		{
			$("#caixaAlertaJavascript").hide()
			wleft = ( parseInt(dimensoesTela().split("x")[0]) - parseInt($("#caixaAlertaJavascript").width() ) ) / 2	
			$("#caixaAlertaJavascript").css("left",wleft)
			setTimeout(function(){
				widthFundo = dimensoesTela().split("x")[0] + "px"
				heightFundo = dimensoesTela().split("x")[1] + "px"	
				$(".fundoOpaco").animate({       
					height: heightFundo,
					width: widthFundo
				}, 200,function(){
					$("#caixaAlertaJavascript").animate( {'opacity':'show'},'normal')	
				});					
			},500)
			
			
			
		} 
		
		
		else
		{
			if( $(".fundoOpaco").length > 0 )
			{
				
				widthFundo = dimensoesTela().split("x")[0] + "px"
				heightFundo = dimensoesTela().split("x")[1] + "px"	
				$(".fundoOpaco").animate({       
					height: heightFundo,
					width: widthFundo
				}, 200 );	
				
			} 
		}
		
	});
}
else
{
	if(document.getElementById) {
		window.alert = function(txt) {
			createCustomAlert(txt);
		}
		window.confirm = function(txt) {
			createCustomConfirm(txt);
		}
	}
}

function avisoCarrega(txtMensagem){
	
	$("#fundoCompra").remove();
	$("#caixaAlertaJavascript").remove();
	
	incluirFundo('fundoCompra','');
	
	str	= "<div id='caixaAlertaJavascript'>"
	str += "<div id='topoAlertFalse'>&nbsp;</div>"
	str += "<div id='textoAlert'>"+ txtMensagem +"</div>"
	str += "<div id='rodapeAlert'><img src='imagens/loading_2.gif'></div>"      
	str += "</div>"
	
	$(str).appendTo("body").hide();
	wleft = ( parseInt(dimensoesTela().split("x")[0]) - parseInt($("#caixaAlertaJavascript").width() ) ) / 2	
	
	$("#caixaAlertaJavascript").css("left",wleft)
	$("#caixaAlertaJavascript").animate( {'opacity':'show'},'slow')
}

function createCustomAlertSite(paramTxt) {
	
	
	incluirFundo('fundoOpacoAlert','')	
	$("#caixaAlertaJavascript").remove()
	txt = new String(paramTxt)
	vetTxt = txt.split("|")
	
	if( vetTxt.length==1 || vetTxt[0] != "true")
	{
		var txtMensagem = vetTxt.length
		if( vetTxt.length==1 )
		{
			txtMensagem = txt	
		}
		else
		{
			txtMensagem = vetTxt[1]
		}
		
		str	= "<div id='caixaAlertaJavascript'>"
		str += "<div id='topoAlertFalse'>&nbsp;</div>"
        str += "<div id='textoAlert'>"+ txtMensagem +"</div>"
        str += "<div id='rodapeAlert'><button class='ok' id='btnFechar' alt='OK'></button></div>"      
		str += "</div>"	
	}
	else
	{
		str	= "<div id='caixaAlertaJavascript'>"
		str += "<div id='topoAlertTrue'>&nbsp;</div>"
        str += "<div id='textoAlert'>"+ vetTxt[1] +"</div>"
        str += "<div id='rodapeAlert'><button id='btnFechar' class='fechar' alt='Fechar'></button></div>"      
		str += "</div>"	
	}
	$(str).appendTo("body").hide()
	
	$("#btnFechar").click(function(){ $("#fundoOpacoAlert").remove();$("#caixaAlertaJavascript").remove();removeCustomAlert() })
	wleft = ( parseInt(dimensoesTela().split("x")[0]) - parseInt($("#caixaAlertaJavascript").width() ) ) / 2	
	
	$("#caixaAlertaJavascript").css("left",wleft)
	$("#caixaAlertaJavascript").animate( {'opacity':'show'},'slow')
	$("#btnFechar").focus()
	
	
	
}
function createCustomAlert(txt) {
	
	d = document;

	if(d.getElementById("modalContainer")) return;

	incluirFundo('fundoOpacoAlert','')	
	

	mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
	mObj.id = "modalContainer";
	mObj.style.height = d.documentElement.scrollHeight + "px";
	
	
	alertObj = mObj.appendChild(d.createElement("div"));
	alertObj.id = "alertBox";
	
	alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
	alertObj.style.visiblity="visible";

	h1 = alertObj.appendChild(d.createElement("h1"));
	h1.appendChild(d.createTextNode(ALERT_TITLE));

	msg = alertObj.appendChild(d.createElement("p"));
	imgAlert = alertObj.appendChild(d.createElement("img"));
	imgAlert.src = "imagens/icon_alert.jpg"
	imgAlert.id = "imgAlert"
	msg.appendChild(d.createTextNode(txt));
	msg.innerHTML = txt;

	btn = alertObj.appendChild(d.createElement("a"));
	btn.id = "closeBtn";
	btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));


	btn.href = "#";
	btn.focus();
	btn.onclick = function() { removeCustomAlert();return false; }

	alertObj.style.display = "block";
	
	
}

function createCustomConfirm(txt) {
	
	d = document;

	if(d.getElementById("modalContainer")) return;

	mObjAux = document.createElement("div")
	
	incluirFundo('fundoOpacoAlert','')
	
	
	mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
	mObj.id = "modalContainer";
	mObj.style.height = d.documentElement.scrollHeight + "px";
	
	
	alertObj = mObj.appendChild(d.createElement("div"));
	alertObj.id = "alertBox";
	if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
	alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
	alertObj.style.visiblity="visible";

	h1 = alertObj.appendChild(d.createElement("h1"));
	h1.appendChild(d.createTextNode(ALERT_TITLE));

	msg = alertObj.appendChild(d.createElement("p"));

	imgAlert = alertObj.appendChild(d.createElement("img"));
	imgAlert.src = "imagens/icon_alert.jpg"
	imgAlert.id = "imgAlert"
	msg.appendChild(d.createTextNode(txt));
	msg.innerHTML = txt;

	btn = alertObj.appendChild(d.createElement("a"));
	btn.id = "closeBtn";
	btn.style.left = "70px"
	btn.appendChild(d.createTextNode("Sim"));
	btn.href = "#";
	btn.focus();
	btn.onclick = function() { removeCustomConfirm(true); }
	
	btn = alertObj.appendChild(d.createElement("a"));
	btn.id = "cancelBtn";
	btn.appendChild(d.createTextNode("Não"));
	btn.href = "#";
	btn.focus();
	btn.onclick = function() { removeCustomConfirm(false); }

	alertObj.style.display = "block";
	
	
}

function createCustomConfirmSite(txt) 
{
	
	incluirFundo('fundoOpacoAlert','')	
	$("#caixaAlertaJavascript").remove()
	
		
	str	= "<div id='caixaAlertaJavascript'>"
	str += "<div id='topoAlertConfirm'>&nbsp;</div>"
	str += "<div id='textoAlert'>"+ txt +"</div>"
	str += "<div id='rodapeAlert'><button class='sim' id='btnSim' alt='Sim'></button><button class='nao' id='btnNao' alt='Não></button></div>"      
	str += "</div>"	
	
	$(str).appendTo("body").hide()
	
	$("#btnSim").click(function(){ $("#fundoOpacoAlert").remove();$("#caixaAlertaJavascript").remove();removeCustomConfirm(true); })
	$("#btnNao").click(function(){ $("#fundoOpacoAlert").remove();$("#caixaAlertaJavascript").remove();removeCustomConfirm(false); })
	wleft = ( parseInt(dimensoesTela().split("x")[0]) - parseInt($("#caixaAlertaJavascript").width() ) ) / 2	
	
	$("#caixaAlertaJavascript").css("left",wleft)
	$("#caixaAlertaJavascript").animate( {'opacity':'show'},'slow')
	$("#btnFechar").focus()
	
}

function removeCustomAlert() {
	if( document.getElementById("modalContainer") )
	{
		document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
	}
	$("#fundoOpacoAlert").remove()
	
	if(objFocus != null && objFocus != "" && objFocus !='nulo')
	{
		objFocus.focus();	
	}
	else
	{
		if( urlRetornoAlert != "")
		{
			location.href=urlRetornoAlert;	
		}
		else
		{
			if( historyBack )
			{
				history.back()	
			}
		}
	}
}
var retornoConfirm = false
function removeCustomConfirm(ret) {
	retornoConfirm = retornoConfirm
	if( document.getElementById("modalContainer") )
	{
		document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
	}
	$("#fundoOpacoAlert").remove()
	if( ret == true )
	{	
		if(objFocus != null && objFocus != "" && objFocus !='nulo')
		{
			objFocus.submit();	
		}
		else
		{
			if( urlRetornoAlert != "")
			{
				location.href=urlRetornoAlert;	
			}
		}
	}
	else
	{
		objFocus = null		
		urlRetornoAlert = ""
	}
}
function incluirFundo(idFundo,corFundo)
{
	$("#"+idFundo).remove()
	$("<div id='" + idFundo + "' class='fundoOpaco'>&nbsp;</div>").appendTo("body")	
	objF = document.getElementById(idFundo)
	objF.style.width = dimensoesTela().split("x")[0] + "px"
	objF.style.height = dimensoesTela().split("x")[1] + "px"
	if( corFundo != "")
	{
		$("#" + idFundo).css("background",corFundo)	
	}
} 
 
 
 function validaCPF(cpf) {
		
		 erro = new String;
		 cpf = cpf.substring(0,11)
		 if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificação do CPF! \n\n";
		 var nonNumbers = /\D/;
		 if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";
		 if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
				 erro += "Número de CPF inválido!"
	   }
	   var a = [];
	   var b = new Number;
	   var c = 11;
	   for (i=0; i<11; i++){
			   a[i] = cpf.charAt(i);
			   if (i < 9) b += (a[i] * --c);
	   }
	   if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
	   b = 0;
	   c = 11;
	   for (y=0; y<10; y++) b += (a[y] * c--);
	   if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
	   if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
			   erro +="Digito verificador com problema!";
	   }
	   if (erro.length > 0){
			   //alert(erro);
			   return false;
	   }
	   return true;
}



function validaCNPJ(CNPJ) {
  erro = new String;
  if (CNPJ.length < 18) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";
  if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
  if (erro.length == 0) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";
  }
  //substituir os caracteres que nao sao numeros
  if(document.layers && parseInt(navigator.appVersion) == 4){
  x = CNPJ.substring(0,2);
  x += CNPJ.substring(3,6);
  x += CNPJ.substring(7,10);
  x += CNPJ.substring(11,15);
  x += CNPJ.substring(16,18);
  CNPJ = x; 
  } else {
  CNPJ = CNPJ.replace(".","");
  CNPJ = CNPJ.replace(".","");
  CNPJ = CNPJ.replace("-","");
  CNPJ = CNPJ.replace("/","");
  }
  var nonNumbers = /\D/;
  if (nonNumbers.test(CNPJ)) erro += "A verificacao de CNPJ suporta apenas numeros! \n\n"; 
  var a = [];
  var b = new Number;
  var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
  for (i=0; i<12; i++){
  a[i] = CNPJ.charAt(i);
  b += a[i] * c[i+1];
  }
  if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
  b = 0;
  for (y=0; y<13; y++) {
  b += (a[y] * c[y]); 
  }
  if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
  if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
  erro +="Digito verificador com problema!";
  }
  if (erro.length > 0){
  //alert(erro);
  return false;
  } else {
 // alert("CNPJ valido!");
  }
  return true;
}

function validaFormGeral(id){
	if(id != "")
		obj = $("#"+id + " .obrigatorio")
	else
		obj = $(".obrigatorio")
	
	for (i=0;i<obj.length;i++){
		if(obj[i].value == "" && obj[i].type != "radio" && obj[i].type != "checkbox"){
			/*
			if( $("input[name='text_select_selectApartamento']") ){
				if( $("input[name='text_select_selectDayUseHoras']").value != "" || $("input[name='text_select_selectDayUseQuarto']").value != "" )
					return true;
				else{
					alert("Preencha o campo "+obj[i].title);
					objFocus = obj[i]				
					return false	
				}
				break;
			}
			else if( $("input[name='text_select_selectDayUseHoras']") || $("input[name='text_select_selectDayUseQuarto']") ){
				if( $("input[name='text_select_selectApartamento']").value != "")
					return true;
				else{
					alert("Preencha o campo "+obj[i].title);
					objFocus = obj[i]				
					return false	
				}
			}
			else{
				alert("Preencha o campo "+obj[i].title)	
				objFocus = obj[i]				
				return false	
				break;
			}*/
			alert("Preencha o campo "+obj[i].title)	
			objFocus = obj[i]				
			return false	
			break;
		}
		
		if( obj[i].type == "radio" || obj[i].type == "checkbox"){			
			if( $("input[name='" + obj[i].name + "']:checked").length ==0 ){
				alert("Selecione - "+obj[i].title)
				objFocus = obj[i]				
				return false	
				break;		
			}
		}
	}
	
	if (validaEmails(id) == false){
		return false
	}

	if (validaDatas() == false){
		return false
	}

	if (validaValorFloat() == false){
		return false
	}
	/*
	if( $("input[name='cpf']").length > 0)
	{
		if( $("input[name='cpf']").val() != "")
		{
			var wcpf = $("input[name='cpf']").val()
			wcpf = wcpf.replace(".","")
			wcpf = wcpf.replace(".","")
			wcpf = wcpf.replace(".","")
			wcpf = wcpf.replace("-","")	
			
			if( validaCPF(wcpf)	== false )
			{
				objFocus = $("input[name='cpf']")
				alert("CPF inválido, digite novamente")
				return false;
			}
		}
	}
	if( $("input[name='cnpj']").length > 0)
	{
		if( $("input[name='cnpj']").val() != "")
		{
			var wcpf = $("input[name='cnpj']").val()
						
			if( validaCNPJ(wcpf) == false )
			{
				objFocus = $("input[name='cpf']")
				alert("CNPJ inválido, digite novamente")
				return false;
			}
		}
	}
	if ( ( $("input[name='senha2']").length > 0 ||  $("input[name='senhac']").length > 0) && ( $("#senha").length > 0 ))
	{							
		var senhaConf = "";
		if( $("input[name='senha2']").length > 0)
		{
			senhaConf = $("input[name='senha2']").val()
		}
		else
		{
			senhaConf = $("input[name='senhac']").val()	
		}
		
		if( senhaConf != $("#senha").val() )
		{
			objFocus = $("#senha")
			alert("Senhas não correspondem, digite novamente");
			return false;
		}
	}*/	
	
	if( tipo_arq(id) == false ){
		return false	
	}
	
	return true
}

function validaFormCli(id){	
	if( validaFormGeral(id) ){	
		if( $("#ddd_telefone").val() != "" && $("#telefone").val() != ""){
			return true	
		}
		else{
			if( $("#ddd_celular").val() == "" || $("#celular").val() == ""){
				objFocus = $("#" + id)
				alert("Preencha o campo Telefone Residencial ou Telefone Celular")
				return false;
			}
		}		
	}
	else
		return false	
}

function validaEmails(id){
	if(id != "")
		obj = $("#"+id + " .obrigatorio")
	else
		obj = $(".obrigatorio")	

	for (i=0;i<obj.length;i++){
		if (obj[i]){
			if( (obj[i].alt == "email") && (obj[i].value != "") ){
				if (validaEmail(obj[i].value) == false){
					alert("E-mail inválido");
					objFocus = obj[i]
					return false
					break;
				}
			}
		}
	}

	return true;
}

function validaValorFloat(){
	obj = document.getElementsByTagName("input");
	for (i=0;i<obj.length;i++)	{		
		if (obj[i]){
			if( (obj[i].alt == "valor") && (obj[i].value != "") ){
				if (isFloat(obj[i].value) == false){
					objFocus = obj[i]
					alert("Valor inválido");
					return false
					break;
				}
			}
			
		}
	}
	return true;
}

function validaData(data){
	var expre =	/^(0?[1-9]|[12]\d|3[01])\/(0?[1-9]|1[0-2])\/(19|20)?\d{2}$/;
	if (expre.test(data) == false){
		return false;
	}
	return true
}

function isNumeric(valor)
{
   	var valor_text;
    var vetor;
    var cont;

    valor_text = valor;
    vetor = "";
    cont = 0;    

    for(var i = 0; i < valor_text.length; i++)
    {
  		if (valor_text.charCodeAt(i) < 43 || valor_text.charCodeAt(i) > 58)
	  	{
		  vetor = vetor + valor_text.charAt(i);
		  cont++;
	 	}
	}
    
    if(cont == 0)
    {
  		return true;    
    }
    else
    {
  		return false;
    }
}
function validaEmail(email)
{
	
	var reTipo = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	return reTipo.test(email);

}
function validaData(data)
{
	var expre =	/^(0?[1-9]|[12]\d|3[01])\/(0?[1-9]|1[0-2])\/(19|20)?\d{2}$/;
	if (expre.test(data) == false)
	{
		return false
	}	
	return true;
}

function validaCont()
{
	if (validaFormGeral() == false)
	{
		return false;
	}
	if (document.getElementById("mensagem").value == "")
	{
		alert("Preencha o campo Mensagem");
		document.getElementById("mensagem").focus();
		return false;
	}
}
function validaDatas()
{
	
	obj = document.getElementsByTagName("input");
	for (i=0;i<obj.length;i++)
	{		
		if (obj[i])
		{
			if( (obj[i].value != "") && (obj[i].alt == "data") )
			{
				if( validaData(obj[i].value) == false)
				{
					alert(obj[i].title + " inválida")
					objFocus = obj[i]
					return false
					break;
				}
			}

		}
	}
	return true;
	
}

function tipo_arq(id)
{
	if( id != "")
	{
		obj = $("#" + id + " input[type='file']")	
	}
	else
	{
		obj = $("input[type='file']")		
	}
	var obrigatorio = ""
	var cont = 0; 
	if( obj.length > 0 )
	{
		for(i=0;i<obj.length;i++)
		{
			if( obj[i].alt != "")
			{
				opcoes = obj[i].alt	
				vetOpcoes = opcoes.split(";")
				if( obrigatorio == "")
				{
					obrigatorio = vetOpcoes[1]	
				}
				
				if (obj[i].value != "" )
				{		
					if(  obj[i].value.length <= 200 )
					{
						wfoto = obj[i].value
						indice = wfoto.indexOf(".");
						indice = indice + 1; 
						
						if( wfoto.substring(wfoto.length-5,wfoto.length-4) == "." )
						{
							wfoto =  wfoto.substring(wfoto.length-4,wfoto.length)	
						}
						else
						{
							wfoto = wfoto.substring(wfoto.length-3,wfoto.length)
						}
						
						wfoto = wfoto.toLowerCase();
						
						vetExtensao = vetOpcoes[0].split("|")
						erro = true
						for(y=0;y<vetExtensao.length;y++)
						{
							if(wfoto == vetExtensao[y])
							{
								erro = false		
							}
						}
						if (erro == true)
						{
							alert(obj[i].title + " - extensão não permitida");
							objFocus = obj[i]
							return false;
							break;
							
						}
						
						cont = parseInt(cont) + 1;
					}
					else
					{
						alert("Atenção, arquivo "+ i +" - nome com tamanho superior ao permitido(200 caracteres)");	
						objFocus = obj[i]
						return false;
						break;
					}
				}
				
			}
		}
		
		if (obrigatorio == "S")
		{
			if (cont <= 0 )
			{
				objFocus = obj[i];
				alert("Nenhum arquivo inserido");			
				return false
			}
			return true
		}
	}
	return true
}

function verSelecaoCep()
{
	obj = document.getElementById("formFinaliza");
	objGratis = document.getElementById("gratis");
	if(objGratis || !obj)
	{
		document.getElementById("formFinaliza").submit();
	}
	else
	{
		if( document.getElementById("insCalcFrete") )
		{
			obj = document.getElementById("insCalcFrete").getElementsByTagName("input");
			
			if(document.getElementById("freteCalculado").value == "S")
			{
				retorno = false
				for(i=0;i<obj.length;i++)
				{
					if( (obj[i].name == "opcaofrete") && (obj[i].checked))
					{
						retorno = true
						break;
					} 
				}
				if (retorno)
				{
					document.getElementById("formFinaliza").submit();
				}
				else
				{
					objFocus = $("#freteCalculado")
					alert("Selecione tipo de frete desejado")
					
				}
			}
			else
			{
				objFocus = $("#freteCalculado")
				alert("Selecione tipo de frete desejado.")	
				
			}
		}
		else
		{
			objFocus = document.getElementById("formFinaliza")
			alert("Calcule o frete")		
		}
	}
}


