	/*
	VALIDAÇÕES.JS
	TODAS AS VALIDAÇÕES SÃƒO FEITAS UTILIZANDO A BIBLIOTECA LIVEVALIDATION
	
	COMO USAR:
	- A função inicializaValidacoesForm deve ser chamada após o carregamento da página, recebendo o id do formulário como parâmetro
	- Adicionar a classe OBRIGATORIO ao campo que precisa ter validação de PRESENÇA
		Se o MESMO campo OBRIGATÓRIO precisar de outras validações, adicionar outras classes, exemplo:
		* email: valida formato de e-mail
		* confirmacao_senha: valida se o valor é equilavente ao valor do campo cujo id é senha
		* numero: valida se o valor é numérico
		* imagem: valida o formato do arquivo adicionado
	- Para campos NÃO OBRIGATÓRIOS, adicionar somente as classes ESPECÍFICAS para outras validações, como detalhado acima (email, numero, etc)
	*/

	var live_validation_options = { validMessage: " ", onlyOnSubmit: true }
	var obrigatorio_LV, email_LV, confirmacao_senha_LV, numero_LV, imagem_LV, cpf_LV, cnpj_LV;
	
	function inicializaValidacoesForm( id_form ){

		if( id_form != "" )
			id_form = "#"+id_form
		
		$( id_form+" .obrigatorio" ).each(function(){
		
			obrigatorio_LV = new LiveValidation(this, live_validation_options);
			obrigatorio_LV.add(Validate.Presence, {failureMessage: "Preencha o campo "+this.title+"."});
			
			if ( $(this).hasClass("email") ){
				obrigatorio_LV.add(Validate.Email, {failureMessage: "E-mail inválido."});
				
				if ( $(this).hasClass("unico") )
					obrigatorio_LV.add(
						Validate.Custom, 
						{against: function(value, args){return validaUnicidade(value, args.campo)}, args: {campo: "email"}, failureMessage: this.title+" já cadastrado."}
					);
			}

			if ( $(this).hasClass("confirmacao_senha") )
				obrigatorio_LV.add(Validate.Confirmation, {match: 'senha', failureMessage: "As senhas não são iguais."});
				
			if ( $(this).hasClass("numero") )
				obrigatorio_LV.add(Validate.Numericality, {notANumberMessage: "Valor inválido."});
				
			if ( $(this).hasClass("imagem") )
				obrigatorio_LV.add(Validate.Format, {pattern: "/\.(jpeg|jpg|gif|swf)$/i", failureMessage: "Arquivo inválido."});

			if ( $(this).hasClass("cpf") )
				obrigatorio_LV.add(Validate.Custom, {against: function(value){return validaCPF(value)}, failureMessage: "CPF inválido."});
				
			if ( $(this).hasClass("cnpj") )
				obrigatorio_LV.add(Validate.Custom, {against: function(value){return validaCNPJ(value)}, failureMessage: "CNPJ inválido."});
				
		});
		
		$( id_form+" .email:not(.obrigatorio)" ).each(function(){
			email_LV = new LiveValidation(this, live_validation_options);
			email_LV.add(Validate.email_LV, {failureMessage: "E-mail inválido."})
		});
		
		$( id_form+" .confirmacao_senha:not(.obrigatorio)" ).each(function(){
			confirmacao_senha_LV = new LiveValidation(this, live_validation_options);
			confirmacao_senha_LV.add(Validate.Confirmation, {match: 'senha', failureMessage: "As senhas não são iguais."})
		});
		
		$( id_form+" .numero:not(.obrigatorio)" ).each(function(){
			numero_LV = new LiveValidation(this, live_validation_options);
			numero_LV.add(Validate.Numericality, {notANumberMessage: "Valor inválido."})
		});
		
		$( id_form+" .imagem:not(.obrigatorio)" ).each(function(){
			imagem_LV = new LiveValidation(this, live_validation_options);
			imagem_LV.add(Validate.Format, {pattern: /^.*.(png|jpg|bmp|gif|jpeg|swf)$/i, failureMessage: "Arquivo inválido."})
		});
		
		$( id_form+" .cpf:not(.obrigatorio)" ).each(function(){
			cpf_LV = new LiveValidation(this, live_validation_options);
			cpf_LV.add(Validate.Custom, {against: function(value){return validaCPF(value)}, failureMessage: "CPF inválido."})
		});
		
		$( id_form+" .cnpj:not(.obrigatorio)" ).each(function(){
			cnpj_LV = new LiveValidation(this, live_validation_options);
			cnpj_LV.add(Validate.Custom, {against: function(value){return validaCNPJ(value)}, failureMessage: "CNPJ inválido."})
		});
		
		/*
		if (validaDatas() == false)	{
			return false
		}		
		if (validaValorFloat() == false) {
			return false
		}*/
	}

	function validaUnicidade( valor, campo ){
		var retorno = $.ajax({
			url: "valida_unicidade.asp?valor="+valor+"&campo="+campo,
			dataType: "text",
			type: "get",
			async:	false			
		}).responseText;
		
		if ( retorno=="false" )
			return false;
		
		return true;
	}
	
	function validaCPF( cpf ) {		
		/*	substitui (por expressão regular) os . e - por string vazia, pra retornar somente números
			\D = find a non-digit character
			g  = perform a global match (find all matches rather than stopping after the first match)
		*/
		cpf = cpf.replace(/\D/g,"")
		
		// precisa ter 11 dígitos
		if ( cpf.length < 11 ) return false;
			
		if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
			return false;		

		// validação dos números do cpf
		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])){ return false; }
		
		return true;
	}

	function validaCNPJ( cnpj ) {
		/*	substitui (por expressão regular) os . e - e / por string vazia, pra retornar somente números
			\D = find a non-digit character
			g  = perform a global match (find all matches rather than stopping after the first match)
		*/
		cnpj = cnpj.replace(/\D/g,"")
		
		// precisa ter 14 dígitos
		if ( cnpj.length < 14 ) return false;
		
		// validação dos números do cnpj
		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])){
			return false;
		}
		
		return true;
	}
	
	
	
	
	/*
	CUSTOM ALERTS
	*/	
	
	var ALERT_TITLE = "Atenção";
	var ALERT_BUTTON_TEXT = "Ok";

	objFocus = new Object()
	var urlRetornoAlert = "";
	var retornoConfirm = ""
	objFocus = null;
	var historyBack = false;


	//painelctrl
	/* alert customizado */

	urlTemp = location.href.substring(0,location.href.indexOf('?') + 1);
	//if( urlTemp.split("/")[3] != "paineladm"){
	if ( urlTemp.match(/\/paineladm\//) == null ){
		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 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 class='alert-a'>"
			str += "<img src='imagem/logo-alert.png' width='126' height='45' alt='' class='logo-alert'>"
			str += "<h1>"+ txtMensagem +"</h1>"
			str += "<a href='#'><img src='imagem/bt-voltar.png' id='btnFechar' width='79' height='29' alt='Voltar' title='Voltar'></a>"
			str += "</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 class='alert-a'>"
			str += "<img src='imagem/logo-alert.png' width='126' height='45' alt='' class='logo-alert'>"
			str += "<h1>"+ vetTxt[1] +"</h1>"
			str += "<a href='#'><img src='imagem/bt-voltar.png' id='btnFechar' width='79' height='29' alt='Voltar' title='Voltar'></a>"
			str += "</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)	
		}
	} 
