/*
	#################################################
	#           CLASSE JAVASCRIPT PRINCIPAL         #
	#    Auto: Thiago Silva (Pedreiro Digital)      #
	#          www.pedreirodigital.com.br           #       
	#################################################
*/

//variaveis
var Host;
var Root;
var Path;
var modulo;
var submodulo;
var error;
var mensagem;
var idAlbum = 0;
var IDAba;
var alvoConteudo;
var alvoSelecionado;
var inicio = 0;
var Data = new Date();

//classe javascript
var Util = function(_host,_modulo,_submodulo)
{	
	Root = _host + "modulos/sistema/";
	//endereço do painel
	Host = _host + 'modulos/'+_modulo+'/';
	//pegar caminho
	Path = _host;
	//definindo modulo
	modulo    = _modulo
	//definindo submodulo
	submodulo = _submodulo;
}

//função logar
Util.prototype.logar = function()
{
	//formulario
	form = document.getElementById('login');	
	//validar campos
	if(!form.usuario.value || !form.senha.value)
	{
		//alerta campo vazios
		objAlerta.config('Campos vazios','preencha os campos vazios e tente novamente!',200,'vermelho',false);
		objAlerta.alert('Util.prototype.ok()','','OK');
		objAlerta.exibir();
	}
	else
	{
		//preloading para carregar
		objAlerta.config('Carregando sistema','Carregando sistema',200,'azul',false);
		objAlerta.loading();
		objAlerta.exibir();
		
		//função logar
		objAjax.enviar(Root + 'logar.php','login',Util.prototype.retornoLogin)
	}
}

Util.prototype.getPais = function(nome)
{
	var form = document.getElementById('anunciante');
	for (var i=0; i<form.pais.length; i++)
	{
		if(form.pais[i].value == nome)
		{
			form.pais[i].selected = true;
		}
	}
}

Util.prototype.getEstado = function(id,id_ci)
{
	var form = document.getElementById('anunciante');
	for (var i=0; i<form.estado.length; i++)
	{
		if(form.estado[i].value == id)
		{
			form.estado[i].selected = true;
			setTimeout('Util.prototype.listarCidades('+form.estado[i].value+')',150);
			setTimeout('Util.prototype.selectCidades('+id_ci+')',250);
		}
	}
}

Util.prototype.ativar = function(id)
{
	var form = document.getElementById('anunciante');
	if(id == 'Brasil')
	{
		form.estado_txt.style.display = 'none';
		form.estado.style.display = 'block';
		form.cidade_txt.style.display = 'none';
		form.cidade.style.display = 'block';
	}
	else
	{
		form.estado_txt.style.display = 'block';
		form.estado.style.display = 'none';
		form.cidade_txt.style.display = 'block';
		form.cidade.style.display = 'none';
	}
}

Util.prototype.selectCidades = function(id)
{
	var form = document.getElementById('anunciante');
	for (var i=0; i<form.cidade.length; i++)
	{
		if(form.cidade[i].value == id)
		{
			form.cidade[i].selected = true;
		}
	}
}

Util.prototype.listarCidades = function(id)
{
	objAjax.executar('painel/modulos/anunciantes/cidades.php','id_estado='+id,Util.prototype.ReturnCombo)
	var objCombo = document.getElementById('cidade');
	objCombo.options[0].text = 'carregando..';
	objCombo.disabled = 'disabled';
}	

Util.prototype.ReturnCombo = function()
{
	if (xhReq.readyState == 4)
	{
		resposta = xhReq.responseXML;
		if (resposta)
		{			
			var obj = resposta.getElementsByTagName("dados");
			objUtil.limparCombo(document.getElementById('cidade'),1);
			var objCombo = document.getElementById('cidade');
			for(i=0; i<obj.length; i++)
			{
				var opcao = new Option(unescape(obj[i].getElementsByTagName('nome')[0].firstChild.nodeValue), obj[i].getElementsByTagName('id')[0].firstChild.nodeValue);
				objCombo.options[i] = opcao;
			}
			objCombo.disabled = '';
		}
	}
}

//função retorno login verificar e validar
Util.prototype.retornoLogin = function()
{
	//verfica retornos do ajax
	if (xhReq.readyState == 4)
	{
		//recebe os dados do xml
		resposta = xhReq.responseXML;
		//verificar se o arquivo e xml
		if (resposta)
		{
			//pegar os do xml
			obj = resposta.getElementsByTagName('dados');
			//retorno o erro do xml
			error = parseInt(obj[0].getElementsByTagName('msg')[0].firstChild.nodeValue);
			
			switch(error)
			{
				case 0:
					mensagem = 'Usuário inválido ou não esta cadastrado!';
				break;
				case 1:
					mensagem = 'Usuário encontra-se bloqueiado no momento!';
				break;
				case 2:
					mensagem = '';
				break;
				case 3:
					mensagem = 'Senha inválida tente novamente!';
				break;
			}
			
			if(error != 2)
			{
				//alerta campo vazios
				objAlerta.config('Atenção',mensagem,200,'vermelho',false);
				objAlerta.alert('Util.prototype.ok()','','OK');
				objAlerta.exibir();
			}
			else
			{
				window.location = 'index.php'
			}
		}
		else 
		{ 
			//alerta campo vazios
			objAlerta.config('Erro no sistema','não foi posivél abrir o <b>modúlo</b>!',200,'vermelho',false);
			objAlerta.alert('Util.prototype.ok()','','OK');
			objAlerta.exibir();
		}
	}
}

//função logout
Util.prototype.logout = function()
{
	//alerta campo vazios
	objAlerta.config('Atenção','Deseja sair do sistema agora?',200,'vermelho',true);
	objAlerta.alert('Util.prototype.encerrar()','Util.prototype.cancelar()','SIM|NÂO');
	objAlerta.exibir();
}

Util.prototype.encerrar = function()
{
	//função sair
	objAjax.executar(Root + 'logout.php','',Util.prototype.sair);
}
Util.prototype.sair = function()
{
	//verfica retornos do ajax
	if (xhReq.readyState == 4)
	{
		//recebe os dados do xml
		resposta = xhReq.responseXML;
		//verificar se o arquivo e xml
		if (resposta)
		{
			window.location = 'index.php';
		}
		else 
		{ 
			//alerta campo vazios
			objAlerta.config('Erro no sistema','não foi posivél abrir o <b>modúlo</b>!',200,'vermelho',false);
			objAlerta.alert('Util.prototype.ok()','','OK');
			objAlerta.exibir();
		}
	}
}

Util.prototype.entrar = function()
{
	var W = 1024;
	var H = 768;
	window.open("index.php","","width="+W+",heigth="+H+",left=0,top=0");
}

Util.prototype.cancelar = function()
{
	document.getElementById('alerta').innerHTML 	  = '';
	document.getElementById('mascara').style.display  = 'none';
	document.getElementById('alerta').style.display   = 'none';
}

Util.prototype.ok = function()
{
	document.getElementById('alerta').innerHTML 	  = '';
	document.getElementById('mascara').style.display  = 'none';
	document.getElementById('alerta').style.display   = 'none';
}

Util.prototype.Aba = function(_obj)
{
	var  IDAba;
	
	if(_obj.id == undefined)
	{
		IDAba = 'aba_' + _obj;
	}
	else
	{
		IDAba = _obj.id;
	}
	
	var Abas = Array('novo','galeria','categoriad','subcategoriad');

	for(i=0; i<Abas.length; i++)
	{
		if(IDAba == "aba_" +i)
		{
			switch(Abas[i])
			{
				case "usuarios":
					objAjax.include(Host + 'listar_user.php','','usuarios');
				break;
				case "grupos":
					objAjax.include(Host + 'grupos.php','','grupos');
				break;
				default:
			}
			
			if(document.getElementById("aba_" +i))
			{
				document.getElementById(Abas[i]).style.display = 'block';
				document.getElementById("aba_" +i).style.background = '#FFFFFF';
				document.getElementById("aba_" +i).style.borderBottom = '#FFFFFF solid 1px';
			}
		}
		else
		{
			if(document.getElementById("aba_" +i))
			{
				document.getElementById(Abas[i]).style.display = 'none';
				document.getElementById("aba_" +i).style.background = '#E5E5E5';
				document.getElementById("aba_" +i).style.borderBottom = '#666666 solid 1px';
			}
		}
	}
}

Util.prototype.AbaIdi = function(_obj)
{
	var  IDIdi;
		
	if(_obj.id == undefined)
	{
		IDIdi = 'idi_' + _obj.id;
	}
	else
	{
		IDIdi = _obj.id;
	}
	
	document.getElementById("idiomas").value = _obj.title;
	
	var Idiomas = Array('pt','en');
	for(i=0; i<Idiomas.length; i++)
	{
		if(IDIdi == "idi_" +i)
		{
			document.getElementById("idi_" +i).style.background = '#FFFFFF';
			document.getElementById("idi_" +i).style.borderBottom = '#FFFFFF solid 1px';
		}
		else
		{
			document.getElementById("idi_" +i).style.background = '#E5E5E5';
			document.getElementById("idi_" +i).style.borderBottom = '#666666 solid 1px';
		}
	}
}

Util.prototype.AbaIdiEdit = function(_idi)
{
	document.getElementById("idiomas").value = _idi;
	
	var Idiomas = Array('pt','en');
	for(i=0; i<Idiomas.length; i++)
	{
		if(Idiomas[i] == _idi)
		{
			document.getElementById("idi_" +i).style.background = '#FFFFFF';
			document.getElementById("idi_" +i).style.borderBottom = '#FFFFFF solid 1px';
		}
		else
		{
			document.getElementById("idi_" +i).style.background = '#E5E5E5';
			document.getElementById("idi_" +i).style.borderBottom = '#666666 solid 1px';
		}
	}
}

Util.prototype.tipoNews = function(tipo)
{
	 switch(tipo)
	 {
	 	case 0:
			document.getElementById("novo").style.display = 'block';
			document.getElementById("massa").style.display = 'none';
		break;
		case 1:
			document.getElementById("novo").style.display = 'none';
			document.getElementById("massa").style.display = 'block';
		break;
		default:
			document.getElementById("novo").style.display = 'none';
			document.getElementById("massa").style.display = 'none';
		break;
	 }
}

Util.prototype.setAlbum = function(_obj)
{
	Util.prototype.Aba(1);
	idAlbum = _obj.id;
	objAjax.include(Root + 'fotos/listar.php','id='+idAlbum+'&modulo='+modulo,'album');
}

Util.prototype.atualizarAlbum = function()
{
	objAjax.include(Root + 'fotos/listar.php','id='+idAlbum+'&modulo='+modulo,'album');
}

Util.prototype.limparCombo = function(combo,inicio){
    var tamanho = combo.options.length;
    for (i=tamanho-1;i>=inicio;i--)
        combo.remove(i) ;
}

Util.prototype.addListValor = function (texto,value,destino) {
	dest 	= 	document.getElementById(destino);
	txt 	=	texto;
	valor 	= 	value;
	dest.options[dest.length] = new Option(txt,valor);
}

//funcao adicionar a lista
Util.prototype.addList = function(origem,destino,limite) {
	dest 	= 	document.getElementById(destino);
	orig	=	document.getElementById(origem);
	if (orig.value == '') {
		alert('Por favor preencha o campo para adicionar a lista.');
		return false;
	}
	else {
		if (limite == '' || dest.length < limite) {
			txt 	=	orig.value;
			valor 	= 	orig.value;
			dest.options[dest.length] = new Option(txt,valor);
			orig.value = '';
		}
		else {
			alert('Este campo permite no máximo '+limite+' ítens');
		}
	}
}

//funcao remover da lista
Util.prototype.remList = function(origem) {
	orig	=	document.getElementById(origem);
	if(orig.value == '')
	{
		//alerta campo vazios
		objAlerta.config('Atenção','Selecione uma resposta para remover?',200,'vermelho',false);
		objAlerta.alert('Util.prototype.cancelar()','','OK');
		objAlerta.exibir();
	}
	else
	{
		orig.options[orig.selectedIndex] = null;
	}
}

Util.prototype.ampliarFotoMask = function(foto,legenda,largura,altura)
{
	document.getElementById('fotoCaixa').innerHTML 	  = '<div style="cursor:pointer;" onclick="Util.prototype.Close()">Fechar</div><div><img src="'+foto+'"></div><div id="caixa_legenda">'+legenda+'</div><div style="clear:both;"></div>';
	document.getElementById('fotoCaixa').style.width  = largura+'px';
	n_altura = parseInt(altura) + 30;
	window.scroll(0,0);
	document.getElementById('fotoCaixa').style.height 	 = n_altura +'px';
	document.getElementById('fotoCaixa').style.margin  = "-"+ altura/2 + "px 0 0 -" + largura/2 + "px";
	document.getElementById('mascara').style.display   = '';
	document.getElementById('fotoCaixa').style.display = '';
}

Util.prototype.Close = function()
{
	document.getElementById('fotoCaixa').innerHTML 		 = '';
	document.getElementById('mascara').style.display = 'none';
	document.getElementById('fotoCaixa').style.display 	 = 'none';
}

Util.prototype.getPaginacao = function(_folha,_limite)
{
	folha = _folha;
	limite = _limite;
}

//paginação
Util.prototype.paginar = function(folha,limite,tipo,funcao)
{
	var anterior = document.getElementById("ant");
	var proximo  = document.getElementById("pro");
	var dados = document.getElementById("dados");
	dados.innerHTML = '<img src="images/loader.gif" hspace="5" align="absmiddle" />Carregando...';
	if(tipo == false)
	{
		inicio--;
		proximo.disabled = false;
		proximo.style.background = 'url(images/titulo_preto.gif)';
		if(inicio <= 0)
		{
			inicio = 0;
			anterior.disabled = true;
			anterior.style.background = 'url(images/titulo_cinza.gif)';
		}
	}
	else if(tipo == true	)
	{
		inicio++;
		anterior.disabled = false;
		anterior.style.background = 'url(images/titulo_preto.gif)';
		if(inicio >= (limite-1))
		{
			inicio = limite-1;
			proximo.disabled = true;
			proximo.style.background = 'url(images/titulo_cinza.gif)';
		}
	}
	document.getElementById("navegacao").innerHTML = (inicio+1)+" / "+limite;
	funcao.prototype.listar(inicio);
}

Util.prototype.pegaRevista = function (id,_alvo,selecionado) 
{
	alvoRevista = _alvo;
	alvoSelecionado = selecionado;
	Util.prototype.reseta(alvoRevista);
	if (id != '0') 
	{
		objAjax.executar('modulos/menus/lista_menus.php','id='+id,Util.prototype.exibirMenus);
	}
}

Util.prototype.exibirMenus = function() 
{
	if (xhReq.readyState == 4) 
	{
		Util.prototype.limparCombo(document.getElementById(alvoRevista),0);
		
		if (xhReq.responseXML) 
		{
			obj = xhReq.responseXML.getElementsByTagName('dados');
			for (i =0; i < obj.length; i++) 
			{
				id 		= obj[i].getElementsByTagName('id')[0].firstChild.nodeValue;
				nome 	= unescape(obj[i].getElementsByTagName('nome')[0].firstChild.nodeValue);
				Util.prototype.addCombo(id,nome,document.getElementById(alvoRevista));
				
				if(alvoSelecionado == id)
				{
					document.getElementById(alvoRevista)[i].selected = true;
				}
				
			}
			document.getElementById(alvoRevista).disabled = false;
		}
	}
}

Util.prototype.pegaConteudo = function (id,_alvo) 
{
	alvoConteudo = _alvo;
	Util.prototype.reseta(alvoConteudo);
	if (id != '0') 
	{
		objAjax.executar('modulos/conteudos/lista_conteudo.php','id='+id,Util.prototype.exibirConteudos);
	}
}

Util.prototype.exibirConteudos = function() 
{
	if (xhReq.readyState == 4) 
	{
		Util.prototype.limparCombo(document.getElementById(alvoConteudo),0);
		if (xhReq.responseXML) 
		{
			obj = xhReq.responseXML.getElementsByTagName('dados');
			for (i =0; i < obj.length; i++) 
			{
				id 		= obj[i].getElementsByTagName('id')[0].firstChild.nodeValue;
				titulo 	= unescape(obj[i].getElementsByTagName('nome')[0].firstChild.nodeValue);
				Util.prototype.addCombo(id,titulo,document.getElementById(alvoConteudo));
			}
			document.getElementById(alvoConteudo).disabled = false;
		}
	}
}

Util.prototype.reseta = function(alvo) 
{
	Util.prototype.limparCombo(document.getElementById(alvo),0);
	document.getElementById(alvo).disabled = true;
}

Util.prototype.limparCombo = function(combo,inicio)
{
	var tamanho=combo.options.length;
	for (i=tamanho-1;i>=inicio;i--)
		combo.remove(i) ;
}

Util.prototype.addCombo = function(valor,texto,combo) {
	var opcao = new Option(texto, valor);
    combo.options[combo.length] = opcao;
}

Util.prototype.DataHora = function(formato)
{
	var Dia               = Data.getDate();
	var Mes               = Data.getMonth();
	var Ano               = Data.getFullYear();
	
	var Hora              = Data.getHours();
	var Minuto            = Data.getMinutes();
	var Segundo           = Data.getSeconds();
	var Meses              = Array(1,2,3,4,5,6,7,8,9,10,11,12);
	
	var d                 = Dia        <= 9 ? '0' + Dia        : Dia;
	var m                 = Meses[Mes] <= 9 ? '0' + Meses[Mes] : Meses[Mes];
	var a                 = Ano;
	
	var h                 = Hora       <= 9 ? '0' + Hora       : Hora;
	var i                 = Minuto     <= 9 ? '0' + Minuto     : Minuto;
	var s                 = Segundo    <= 9 ? '0' + Segundo    : Segundo;	
	
	var letras            = new String(formato);
	var numeros           = new String();
	var separadores       = '';
	
	for(var j=0; j<letras.length; j++)
	{
		if(letras.search(":")!=-1)
		{
			if(letras.charAt(j)!=":")
			{
				numeros += letras.charAt(j).replace(letras[j],eval(letras[j]));
				if(numeros.length > 1)
				{
					numeros += ":";
				}
			}
		}
		else if((letras.search("/")!=-1))
		{
			if((letras.charAt(j)!="/"))
			{
				numeros += letras.charAt(j).replace(letras[j],eval(letras[j]));
				if(numeros.length > 1)
				{
					numeros += "/";
				}
			}
		}
		else if((letras.search("-")!=-1))
		{
			if((letras.charAt(j)!="-"))
			{
				numeros += letras.charAt(j).replace(letras[j],eval(letras[j]));
				if(numeros.length > 1)
				{
					numeros += "-";
				}
			}
		}
	}
	
	return numeros.substr(0,(numeros.length-1));
}

Util.prototype.lembrarSenha = function() 
{
	window.location = '?modulo=lembrar_senha';
}


