//////////////////////////////////////////////////////////////////////////////////////////
// Verifica Browsers
//////////////////////////////////////////////////////////////////////////////////////////
var browser_name = navigator.userAgent
if(browser_name.indexOf("Chrome") > 0){var browser_name = "Chrome"; var ver = navigator.userAgent; var thestart = parseFloat(ver.indexOf("Chrome/"))+7; var theend = parseFloat(ver.indexOf("Safari"))-1; var browser_version = ver.substring(thestart,theend);}
else if(browser_name.indexOf("Firefox") > 0) {var browser_name = "Firefox"; var ver = navigator.userAgent; var thestart = parseFloat(ver.indexOf("Firefox/"))+1; var browser_version = ver.substring(thestart+7);}
else if(browser_name.indexOf("MSIE") > 0) {var browser_name = "Internet Explorer"; var ver = navigator.appVersion; var thestart = parseFloat(ver.indexOf("MSIE"))+1 ;var browser_version = parseFloat(ver.substring(thestart+4,thestart+7)); }
else if(browser_name.indexOf("Safari") > 0) {var browser_name = "Safari"; var ver = navigator.userAgent; var thestart = parseFloat(ver.indexOf("Version/"))+8; var theend = parseFloat(ver.indexOf("Safari"))-1; var browser_version = ver.substring(thestart,theend); }
else {var browser_name = navigator.appName; var browser_version = navigator.appVersion;}
setCookie("user[browser_name]",browser_name,30);
setCookie("user[browser_version]",browser_version,30);
//if(browser_name = "Internet Explorer" && browser_version == 6) window.location.href="browser_error.php";	
//////////////////////////////////////////////////////////////////////////////////////////
// Ferramentas de Cookie
//////////////////////////////////////////////////////////////////////////////////////////
function getCookie(c_name){if (document.cookie.length>0) {c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1){ c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start,c_end));}}return "";}
function checkCookie(name) {value=getCookie(name); if (value!=null && value!="") alert('Cookie Criado: '+value+'!'); else alert('Cookie não foi criado');}
function setCookie(c_name,value,expiredays){var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toUTCString());}
//////////////////////////////////////////////////////////////////////////////////////////
// JQUERY USER INTERFACE
//////////////////////////////////////////////////////////////////////////////////////////
$(function() {
	// Calendario
	$("#calendar, #calendarFrom, #calendarTo" ).datepicker({
		showOn: "button",
		buttonText: "Escolha a Data",
		dayNames: ["Segunda","Terça","Quarta","Quinta","Sexta","Sábado","Domingo"],
		dayNamesMin: ["Seg","Ter","Qua","Qui","Sex","Sab","Dom"],
		monthNames: ["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],
		monthNamesShort: ["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"],
		buttonImage: "../images/icons/calendar.png",
		nextText: "",
		prevText: "",
		dateFormat: "yy-mm-dd",
		buttonImageOnly: true
	});
	// Caixa de Diálogo
	$( "#dialog" ).dialog({
		autoOpen: false,
		resizable: false,
		show: 'blind',
		hide: 'blind',
		height: 140,
		modal: true,
		draggable: false,
		buttons: {
			Ok: function() {
				$( this ).dialog( "close" );
			}
		}
	});
	$( "#alert" ).dialog({
		autoOpen: false,
		resizable: false,
		draggable: false,
		height: 90,
		modal: true
	});
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Popups
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function jPopup(id,width,height,title,xtra){

	if($("#"+id)) $("#"+id).remove();
	var NewDiv = document.createElement('div');
		NewDiv.id = id;
		$('#body').append(NewDiv);
		
	$( "#"+id).dialog({
		autoOpen: false,
		resizable: false,
		show: 'blind',
		hide: 'blind',
		width: width,
		height: height,
		modal: true,
		draggable: false,
		title: title,
		buttons: {
			'Fechar': function() {$( this ).dialog( "close" );}
		}
	});
	$.ajax({
		url: "popup/"+id+".php?xtra="+xtra,
		type: 'GET',
		cache: false,
		success: function(result) {
			$( "#"+id ).dialog( "open" );
			if(result) $( "#"+id ).html(result);
			else $( "#"+id ).html('<br/><br/><span class="ui-icon ui-icon-cancel" style="float:left; margin:-1px 7px 0px 0;"></span>Popup não retornou nenhuma informação');
		},
		error: function(xhr,status,error) {
			$( "#"+id ).dialog( "open" );
			$( "#"+id ).html('<br/><br/><span class="ui-icon ui-icon-cancel" style="float:left; margin:-1px 7px 0px 0;"></span>Página Não Encontrada');
		}
	});
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MENU HORIZONTAL
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function MenuLeftOver(){
	var position = $("#MenuSlider").css('margin-left');
	position = position.replace('px','');
	position = parseInt(position);
	clock = setInterval(function(){
		$("#MenuSlider").css({'margin-left':position+"px"})
		position+=1
		if(position >= 0) MenuLeftOut();
	},10)
}
function MenuLeftOut(){
	var position = $("#MenuSlider").css('margin-left');
	position = position.replace('px','');
	position = parseInt(position);
	if(position < 0) {
		position = position + 10;
		$("#MenuSlider").animate({'margin-left': position+"px"},350)
	}
	clearInterval(clock);
}
function MenuRightOver(){
	var position = $("#MenuSlider").css('margin-left');
	position = position.replace('px','');
	position = parseInt(position);
	var vMax = ($("#MenuSlider").width())-($("#MenuContainer").width());
	vMax = parseInt(vMax);
	clock = setInterval(function(){
			$("#MenuSlider").css({'margin-left':position+"px"})
			position-=1
			if(position == '-'+vMax ) MenuRightOut();
	},10)
}
function MenuRightOut(){
	var position = $("#MenuSlider").css('margin-left');
	position = position.replace('px','');
	position = parseInt(position);
	var vMax = ($("#MenuSlider").width())-($("#MenuContainer").width());
	vMax = parseInt(vMax);
	if(position > '-'+vMax) {
		position = position - 10;
		$("#MenuSlider").animate({'margin-left': position+"px"},350)
	}
	clearInterval(clock);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// LOGIN
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$(function(){

	$('#LoginResult').removeClass( "ui-state-error" );
	$( "#formLogin" ).dialog('destroy');
	
	var user = $('#user'), pwd = $('#pwd');

	$( "#formLogin" ).dialog({ 
		autoOpen: false,
		resizable: false,
		height: 325,
		modal: true,
		draggable: false,
		title: 'Acesso à Área Restrita',
		buttons: {
			"Entrar": function() {
				$('#LoginResult').removeClass( "ui-state-error" );
				$('#LoginResult').html( "" );				
				if(user.val() || pwd.val()){
					$.ajax({
						url: "ajax/login.php?user="+user.val()+"&pwd="+pwd.val(),
						type: 'GET',
						cache: false,
						success: function(result) {
							result = result.split('|');
							if(result[0] == 'false') {
								$('#LoginResult').addClass("ui-state-error");
								$('#LoginResult').html('<span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: .3em;\"></span> <strong>Usuário ou senha inválido.</strong>');
								user.val( "" );
								pwd.val( "" );
								user.focus();
							}
							else {
								$( "#formLogin" ).dialog( "close" );
								setCookie('Login',result[1],30);
								setCookie('CEP',result[2].replace('-',''),30);
								location.reload();
							}
						}
					});
				}
				else {
					$('#LoginResult').addClass("ui-state-error");
					$('#LoginResult').html('<span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: .3em;\"></span> <strong>Formulário em branco.</strong>');
					user.focus();
				}
			},
			'Fechar': function() {$( this ).dialog( "close" );}
		},
		close: function() {
			user.val( "" );
			pwd.val( "" );
			$('#LoginResult').removeClass( "ui-state-error" );
			$('#LoginResult').html( "" );
		}
	});
	$('#openerLogin').click(function() {
		$( "#formLogin" ).dialog( "open" );
	 });
									 
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// LIGHTBOX
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$(function(){$("a[rel]").overlay({effect: 'apple', mask: '#FFF'});});
$(function(){$("a[name=lightbox]").fancyZoom({scaleImg: true});});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Esconder objeto
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function hide(id) {
	if ($("#"+id).is(":hidden")) $("#"+id).slideDown("slow");		
	else {
		if(id == "popup") $("#"+id).slideUp("slow",removeDiv);			
		else $("#"+id).slideUp("slow");		
	}
}
function show(id) {
	if ($("#"+id).is(":hidden")) $("#"+id).slideDown(5000);		
	else $("#"+id).slideUp("slow");		
}
function removeDiv() {	
	oldDiv = document.getElementById("popup");	
	document.getElementById("popups").removeChild(oldDiv);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Validador de Formulários
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function validador(obj,excl) {
	
	var erro = '<span style="color: #990000"><img src="images/icons/erro.gif" align="absmiddle" /><b>&nbsp; Os campos em vermelho estão incorretos</b></span>';
	var excl = excl.split('|');
	var callback = true;
	var ask = false;
	// Varre todos os campos do formulário
	for(i=0; i<obj.length; i++) {
		for(a=0; a<excl.length; a++) if(obj[i].name == excl[a] || obj[i].name == undefined) ask = true;
		if(!ask) {
			// Colore os campos com a cor inicial do formulário			
			if(document.getElementById('lb'+obj[i].name)) document.getElementById('lb'+obj[i].name).style.color="#333";
			
			// Verifica se campo obrigatório está vazio
			if(!obj[i].value) {
				//alert(obj[i].name);
				document.getElementById('callback').innerHTML = erro;
				if(document.getElementById('lb'+obj[i].name)) document.getElementById('lb'+obj[i].name).style.color="#FF0000";
				callback = false;
			}
			else{
				// Valida campos com preenchimento limitado
				if(
				   (obj[i].name == 'ddd' || obj[i].name == 'dddFone' || obj[i].name == 'dddFax' || obj[i].name == 'dddCel') ||
				   (obj[i].name == 'telefone' || obj[i].name == 'fax' || obj[i].name == 'celular')||
				   (obj[i].name == 'cep') ||
				   (obj[i].name == 'estado' || obj[i].name == 'uf')||
				   (obj[i].name == 'senha' || obj[i].name == 'comfSenha')
				   ){
					if(obj[i].value.length < obj[i].maxLength){
						document.getElementById('callback').innerHTML = erro;
						if(document.getElementById('lb'+obj[i].name)) document.getElementById('lb'+obj[i].name).style.color="#FF0000";
						callback = false;
					}
				}
				// Valida E-mail
				else if(obj[i].name == 'email'){
					resposta = Verifica_Email(obj[i].value);
					if(resposta) {
						document.getElementById('callback').innerHTML = erro;
						if(document.getElementById('lb'+obj[i].name)) document.getElementById('lb'+obj[i].name).style.color="#FF0000";
						callback = false;
					}
				}
				// Valida CNPJ
				else if(obj[i].name == 'cnpj') {
					strCNPJ = obj[i].value;
					r = Verifica_CNPJ(strCNPJ);
					if(r){
						document.getElementById('callback').innerHTML = erro;
						if(document.getElementById('lb'+obj[i].name)) document.getElementById('lb'+obj[i].name).style.color="#FF0000";
						callback = false;
					}
				}
			}
		}
		ask = false;
	}
	return callback;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Muda o Focus
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function focusTo(from,to){
	var key = event.which;
	var maxLength = $('input[name='+from.name+']').attr('maxlength');	
	var length = ($('input[name='+from.name+']').val().length);
	if(length == maxLength) $('input[name='+to+']').focus();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MASCARA DE FORMULÁRIOS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}
function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}
function soNumeros(v){
    return v.replace(/\D/g,"")
}
function Telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    //v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}
function cpf(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}
function CEP(v){
    v=v.replace(/\D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}
function cnpj(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}
function site(v){
    //Esse sem comentarios para que você entenda sozinho ;-)
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// VALIDADORES DE FORMULÁRIOS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

///// CPF
function Verifica_CPF(campo) {
	var CPF = campo;
	CPF=CPF.replace(/\D/g,"");
	
	var POSICAO, I, SOMA, DV, DV_INFORMADO;
	var DIGITO = new Array(10);
	DV_INFORMADO = CPF.substr(9, 2);
	
	for (I=0; I<=8; I++) {
	  DIGITO[I] = CPF.substr( I, 1);
	}
	
	POSICAO = 10;
	SOMA = 0;
	
	for (I=0; I<=8; I++) {
		SOMA = SOMA + DIGITO[I] * POSICAO;
		POSICAO = POSICAO - 1;
	}
	
	DIGITO[9] = SOMA % 11;
	
	if (DIGITO[9] < 2) DIGITO[9] = 0;
	else DIGITO[9] = 11 - DIGITO[9];
	
	POSICAO = 11;
	SOMA = 0;
	
	for (I=0; I<=9; I++) {
		SOMA = SOMA + DIGITO[I] * POSICAO;
		POSICAO = POSICAO - 1;
	}
	
	DIGITO[10] = SOMA % 11;
	
	if (DIGITO[10] < 2) DIGITO[10] = 0;
	else DIGITO[10] = 11 - DIGITO[10];
	
	DV = DIGITO[9] * 10 + DIGITO[10];
	if (DV != DV_INFORMADO) return "CPF Inválido";
}
///// CNPJ
function Verifica_CNPJ(campo) {
	strCNPJ = campo;
	ERRO = '';
	
	if (strCNPJ.length < 18) ERRO = "CNPJ Inválido"; 
	
	strCNPJ = strCNPJ.replace(/\D/g,"");
	
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	
	for (z=0; z<12; z++){
		a[z] = strCNPJ.charAt(z);
		b += a[z] * c[z+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 ((strCNPJ.charAt(12) != a[12]) || (strCNPJ.charAt(13) != a[13]))	ERRO = "CNPJ Inválido";

	return ERRO;
}

///// E-mail
function Verifica_Email(campo) {
	var email = campo;
	var emailFilter=/^.+@.+\..{2,}$/;
	var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/;
	if(!(emailFilter.test(email))||email.match(illegalChars)) return 'E-mail Incorreto';	
}
