$.ajaxSetup({ 
	cache: false
});

function alteraTema()
{
	if(confirm("Atencao: A pagina sera recarregada, dados nao salvos podem ser perdidos. Deseja Continuar?"))
	{
		$.post("../utilidades/Generica.php?acao=tema",$("#formTema :input[value][value!='.']").serialize(),function(data){
			location.reload();																										
		});
	}
}

$(document).ready(function(){
	try{
		$("button").hover(
			function(){ 
				$(this).addClass("ui-state-hover"); 
			},
			function(){ 
				$(this).removeClass("ui-state-hover"); 
			}
		);
		
		$.datepicker.setDefaults($.datepicker.regional['pt-BR']);
		$(".calendario").datepicker({
			showOn: 'button',
			buttonImage: '../imagens/calendario01.gif',
			buttonImageOnly: true
		});
		$('.calendario').mask("99/99/9999");
		
	}catch(erro){}
	$("#ui-datepicker-div").css("top", "-5000px");
});

;(function($){
	$.fn.exibeSenha = function(ph, options){
	
		var spinput = $(this);
		
		$.fn.exibeSenha.checker = function(cbid, inid){
			$('input[id="'+cbid+'"]').click(function(){
				if($(this).attr('checked')){
					$('input.'+inid).val(spinput.val()).attr('id', spinput.attr('id')).attr('name',spinput.attr('name'));
					$('input.'+inid).css('display', 'inline');
					spinput.css('display', 'none').removeAttr('id').removeAttr('name');
				}else{
					spinput.val($('input.'+inid).val()).attr('id', $('input.'+inid).attr('id')).attr('name', $('input.'+inid).attr('name'));
					spinput.css('display', 'inline');
					$('input.'+inid).css('display', 'none').removeAttr('id').removeAttr('name');
				}
			});
		}
		
		return this.each(function(){
			var def = { classname: 'class', name: 'password-input', text: 'Exibir Senha' };
			var spcbid = 'spcb_' + parseInt(Math.random() * 1000);
			var spinid = spcbid.replace('spcb_', 'spin_');
			if (spinput.attr('class') !== '') { var spclass = spinid+' '+spinput.attr('class'); }else{ var spclass = spinid; }
			if(typeof ph == 'object'){ $.extend(def, ph); }
			if(typeof options == 'object'){ $.extend(def, options); }
			var spname = def.name;
			// define the class name of the object
			if(def.classname==''){ theclass=''; }else{ theclass=' class="'+def.clasname+'"'; }
			// build the checkbox
			$(this).before('<input type="text" maxlength="60" value="" class="'+spclass+'" style="display: none;" />');
			var thecheckbox = '<label><input'+theclass+' type="checkbox" id="'+spcbid+'" name="'+spname+'" value="sp" />'+def.text+'</label>';
			// check if there is a request to place the checkbox in a specific placeholder. 
			// if not, place directly after the input.
			if(ph == 'object' || typeof ph == 'undefined'){ $(this).after(thecheckbox); }else{ $(ph).html(thecheckbox); }
			$.fn.exibeSenha.checker(spcbid, spinid);
			return this;
		});
	}
})
(jQuery);

function upload(formulario,elementosSeparadosPontoVirgula,metodoASerInvocadoDepoisAjax)
{
	var listaElementos = elementosSeparadosPontoVirgula.split(";");
	var ultimoElemento = listaElementos.length - 1;
	for(elemento in listaElementos)
	{
		$("#"+listaElementos[elemento]+"Upload").remove();
		$("#"+formulario).append("<input type=\"hidden\" id=\""+listaElementos[elemento]+"Upload\" name=\""+listaElementos[elemento]+"Upload\" />");
	}
	for(elemento in listaElementos)
	{
		uploadAjax(formulario,listaElementos[elemento],metodoASerInvocadoDepoisAjax,listaElementos[ultimoElemento]);
	}
}

function uploadAjax(formulario,elementoID,metodoASerInvocadoDepoisAjax,ultimoElemento)
{
	var imagemBinaria = {retorno: ""};
	$("#carregando")
	.ajaxStart(function(){
		$(this).show();
	})
	.ajaxComplete(function(){
		$(this).hide();
	});

	$.ajaxFileUpload
	(
		{
			url:'../utilidades/Upload.php?elemento='+elementoID,
			secureuri:false,
			fileElementId:elementoID,
			dataType: 'json',
			success: function (data, status)
			{
				if(typeof(data.error) != 'undefined')
				{
					if(data.error != '')
					{
						alert(data.error);
					}else
					{
							if(data.arquivoBinario != null)
							{
								$("#"+elementoID+"Upload").val(data.arquivoBinario);
							}
							if(data.listaArquivosBinario != null)
							{
								$("#"+elementoID+"Upload").val(data.listaArquivosBinario);
							}							
							if(elementoID == ultimoElemento)
							{
								setTimeout(metodoASerInvocadoDepoisAjax,1500);
							}
					}
				}
			},
			error: function (data, status, e)
			{
				alert(e);
			}
		}
	)
	return false;

}

function capturaCamposFile()
{
	var listaArquivos = "";
	var quantidadeArquivos = $("*:file").length;
	var i = 0;
	$("*:file").each(
		 function()
		 {
			 i = i + 1;
			 if(i<quantidadeArquivos)
			 {
				listaArquivos += this.id+";";
			 }
			 else
			 {
				listaArquivos += this.id;
			 }
		 }
	 );	
	return listaArquivos;
}

//O array de campos deve ser preenchido da seguinte forma:   Nome do Campo:Descricao do Campo:Tipo do Campo;
//Tipos de validações possiveis
//data
//email
//cpf

function validaCampos(arrayCampos)
{  
	listaCampos = arrayCampos.split(";");
	for(campo in listaCampos)
	{
		campoAtual = listaCampos[campo].split(":");	
		campo = campoAtual[0];
		descricaoCampo = campoAtual[1]; 
		tipoCampo = campoAtual[2];
		
		switch(tipoCampo)
		{
			case "data":
				var expReg = /^((((0?[1-9]|1\d|2[0-8])\/(0?[1-9]|1[0-2]))|((29|30)\/(0?[13456789]|1[0-2]))|(31\/(0?[13578]|1[02])))\/((19|20)?\d\d))$|((29\/0?2\/)((19|20)?(0[48]|[2468][048]|[13579][26])|(20)?00))$/;
			break;
			case "email":
				var expReg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,3})+$/;
			break;
			case "cpf":
				var expReg = "";
				var cpf = validaCPF($("#"+campo).val());	
			break;
		}
		if(tipoCampo == "cpf" && $("#"+campo).val() != "" && !cpf || tipoCampo != "cpf" && $("#"+campo).val() != "" && expReg.exec($("#"+campo).val()) == null)
		{
			alert(descricaoCampo + " invalido(a).");
			return false;
		}
		else
		{
			return true;
		}
	}	
}

function validaCPF(numeroCPF)
{
   var cpf = numeroCPF;
   var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
   if(!filtro.test(cpf)){
	 return false;
   }
   
   cpf = remove(cpf, ".");
   cpf = remove(cpf, "-");
    
   if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
	  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  cpf == "88888888888" || cpf == "99999999999"){
	  return false;
   }

   soma = 0;
   for(i = 0; i < 9; i++)
   	 soma += parseInt(cpf.charAt(i)) * (10 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(9))){
	 return false;
   }
   soma = 0;
   for(i = 0; i < 10; i ++)
	 soma += parseInt(cpf.charAt(i)) * (11 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(10))){
	 return false;
   }
   return true;		
}

function remove(str, sub) {
	i = str.indexOf(sub);
	r = "";
	if (i == -1) return str;
	r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
	return r;
}

function geraCampos(quantidade,idDivCampos,gerarDescricao)
{
	var camposGerados = '<input type=\"hidden\" id=\"edtQuantidadeImg\" name=\"edtQuantidadeImg\" value=\"'+$("#"+quantidade).val()+'\" />';
	$("#"+idDivCampos).html('');
	for(i = 1; i<=$("#"+quantidade).val(); i++)
	{
		if(!gerarDescricao)
		{
			mod = i%2;
			if(mod == 0)
			{
				nomeCampo = "img"+i;
				camposGerados += "<input type=\"file\" id=\""+nomeCampo+"\" name=\""+nomeCampo+"\" style=\"float: left; width: 350px; margin-right: 10px; margin-top: 5px;\" class=\"ui-state-campos\" />";
			}
			else
			{
				camposGerados += "<input type=\"file\" id=\""+nomeCampo+"\" name=\""+nomeCampo+"\" style=\"float: left; width: 350px; margin-top: 5px;\" class=\"ui-state-campos\" />";
			}
		}
		else
		{
				nomeCampo = "img"+i;
				nomeDescricao = "edtDescricaoImg"+i;
				camposGerados += "<input type=\"file\" id=\""+nomeCampo+"\" name=\""+nomeCampo+"\" width=\"350\" style=\"width: 350px; margin-right: 10px; margin-top: 5px;\" class=\"ui-state-campos\" /><input type=\"text\" id=\""+nomeDescricao+"\" name=\""+nomeDescricao+"\" style=\"width: 350px; margin-top: 5px;\" class=\"ui-state-campos\" />";			
		}
	}
	$("#"+idDivCampos).html(camposGerados);
}

function formataData(idObjeto)
{
	return $.datepicker.formatDate('dd/mm/yy',$("#"+idObjeto).datepicker("getDate"));
}

function limpaCampoPesquisa(objeto,texto)
{
	if($("#"+objeto).val() == texto)
	{
		$("#"+objeto).val('');
	}
}

function resetaCampoPesquisa(objeto,texto)
{
	if($("#"+objeto).val() == '')
	{
		$("#"+objeto).val(texto);		
	}
}

function validaPesquisa(objeto,texto)
{
	if($("#"+objeto).val() == texto)
	{
		alert('Por favor informe o que você deseja encontrar...');
		return false;
	}
	else
	{
		pesquisa(objeto);
	}
}

function pesquisa(valorPesquisa)
{
	window.location = 'pesquisa.php?busca='+$("#"+valorPesquisa).val();
}

function saudacao()
{
	hoje = new Date();
	hora = hoje.getHours();
	if(hora >= 1 && hora < 12)
	{
		return "Bom dia";
	}
	else if(hora >= 12 && hora < 18)
	{
		return "Boa tarde";
	}
	else
	{
		return "Boa noite";
	}
}

function shadowBox() {

    Shadowbox.setup("a.exibeImagem", {
        gallery:        "Imagens",
        continuous:     true,
        counterType:    "skip"
    });
}





