var init = function()
{
	$('input, select, textarea').each(function(){
		var o = $(this);
		var meta = o.metadata();
		
		//mascara
		if(meta.mask)
		{
			o.mask(meta.mask);
		}
		
		//focus
		if(meta.focus)
		{
			o.focus();
		}
		
		//watermark
		if(meta.watermark)
		{
			var cor = (o.css('color') ? o.css('color') : "#666666");			
			o.Watermark(meta.watermark, cor);
		}
		
		//alphanumeric
		if(meta.alphanumeric)
		{			
			o.alphanumeric();
		}
		
		//numeric
		if(meta.numeric)
		{			
			o.numeric();
		}
		
		//alpha
		if(meta.alpha)
		{			
			o.alpha();
		}
	});
};


/**
 * TRAVAR TEXTO
**/
function TravarTexto(o, qtd, lbl)
{
    if(o.value.length <= qtd)
    {
        document.getElementById(lbl).innerHTML = (qtd - o.value.length);
    }
    else
    {
        o.value = o.value.substr(0, qtd);
   }
}


/**
 * MOVENEXT
**/
function MoveNext(field, nextFieldID)
{
	if(field.tagName.toLowerCase() == "input" && 
	(field.type.toLowerCase() == "text" || field.type.toLowerCase() == "password"))
	{
		if(field.value.replace("_", "").length >= field.maxLength)
  		{
  			document.getElementById(nextFieldID).focus();
		}
	}
	else
	{
		document.getElementById(nextFieldID).focus();
	}
}


/**
 * MUDAR PAIS
**/
function MudarPais(o)
{
	if(o.value == 'Brasil')
	{
		$("#lblUF, #lblCidade").show();
		$("#ddlUF, #txtCidade").val("").show();
		MoveNext(o, 'ddlUF');
		
	}
	else
	{
		$("#lblUF, #lblCidade").hide();
		$("#ddlUF, #txtCidade").val("").hide();
	}
	
}


/**
 * MUDAR PAIS - PJ
**/
function MudarPaisPJ(o)
{
	if(o.value == 'Brasil')
	{
		$("#lblCEP, #spanCEP, #subCEP").show();
		MoveNext(o, 'txtCEP');
		$("#txtCEP").val("").unmask().mask("99999-999");
		
	}
	else
	{
		$("#lblCEP, #spanCEP, #subCEP").hide();
		MoveNext(o, 'ddlTipoLogradouro');
		$("#txtCEP").val("").unmask();
	}
	
}


/**
 * MUDAR CARGO
**/
function MudarCargo(o)
{
	if(o.value == 'LTE=')
	{
		$("#txtCargoOutro").val("").show();
		MoveNext(o, 'txtCargoOutro');
	}
	else
	{
		$("#txtCargoOutro").val("").hide();
		MoveNext(o, 'txtPessoaJuridicaOutro');
	}
}

/**
 * MUDAR CLIENTE
**/
function MudarCliente(o)
{
	if(o.value == 'LTE=')
	{
		$("#txtClienteOutro").val("").show();
		MoveNext(o, 'txtClienteOutro');
	}
	else
	{
		$("#txtClienteOutro").val("").hide();
		MoveNext(o, 'txtNome');
	}
}


/**
 * MUDAR PESSOA JURÍDICA
**/
function MudarPessoaJuridica(o)
{
	if(o.value == 'LTE=')
	{
		$("#txtPessoaJuridicaOutro").val("").show();
		MoveNext(o, 'txtPessoaJuridicaOutro');
	}
	else
	{
		$("#txtPessoaJuridicaOutro").val("").hide();
		MoveNext(o, 'txtTelefoneComercialDDD');
	}
}


/**
 * MUDAR PERFIL DE ATUAÇÃO
**/
function MudarPerfilAtuacao(o)
{
	//MODELO FATURAMENTO
	$("#tdModeloFaturamento").hide();
	$("#ddlModeloFaturamento").val("");
	$("#tdModeloFaturamentoAmbos").hide();
	$("#txtPercentualCompraVenda").val("");
	$("#txtPercentualFaturamentoDireto").val("");
	
	//LINHA PRODUTO
	$("#tdLinhaProduto").hide();
	$("#ddlLinhaProduto").val("");
	
	//MARCA
	$("#tdMarca").hide();
	$("#ddlMarca").val("");
	
	//SERVIÇO
	$("#tdServico").hide();
	$("#ddlServico").val("");
	
	//DISTRIBUIDOR
	$("#tdDistribuidor").hide();
	$("#ddlDistribuidor").val("");
	
	//OPERADORA
	$("#tdOperadora").hide();
	$("#ddlOperadora").val("");
	
	
	if(o.value == 'LTE=')
	{
		$("#txtPerfilAtuacaoOutro").val("").show();
		MoveNext(o, 'txtPerfilAtuacaoOutro');
	}
	else
	{
		var chave = $("option[@value*=" + o.value + "]", o).attr("rel");
		
		if(chave)
		{
			
			//MODELO FATURAMENTO
			if(chave in arModeloFaturamento)
			{
				$("#tdModeloFaturamento").show();
			}
			
			//LINHA PRODUTO
			$("#tdLinhaProduto").show();
			var n = $("#ddlLinhaProduto").html('<option value="">Carregando...</option>').attr("disabled", "disabled");
			$("option", n).removeAttr("selected");
			$.get(((typeof Admin != undefined) ? "linhaproduto.php" : "../cadastre-se/linhaproduto.php"), {chave:chave}, function(dados){
				n.html(dados).removeAttr("disabled");
				$("option", n).removeAttr("selected");
			});
			
			//MARCA
			if(chave in arMarca)
			{
				$("#tdMarca").show();
			}
			
			//SERVIÇO
			if(chave in arServico)
			{
				$("#tdServico").show();
			}
			
			//DISTRIBUIDOR
			if(chave in arDistribuidor)
			{
				$("#tdDistribuidor").show();
			}
			
			//OPERADORA
			if(chave in arOperadora)
			{
				$("#tdOperadora").show();
			}
		}
		
		$("#txtPerfilAtuacaoOutro").val("").hide();
		MoveNext(o, 'txtNomeFantasia');
	}
}


/**
 * MUDAR MODELO DE FATURAMENTO
**/
function MudarModeloFaturamento(o)
{
	if(o.value == 'Ambos')
	{
		$("#tdModeloFaturamentoAmbos").show();
		$("#txtPercentualCompraVenda").val("");
		$("#txtPercentualFaturamentoDireto").val("");
		MoveNext(o, 'txtPercentualCompraVenda');
	}
	else
	{
		$("#tdModeloFaturamentoAmbos").hide();
		$("#txtPercentualCompraVenda").val("");
		$("#txtPercentualFaturamentoDireto").val("");
		MoveNext(o, 'ddlFaturamentoBruto');
	}
}


/**
 * EMPREGA ATUALMENTE SIM
**/
function EmpregadoAtualmenteSim()
{
	$("#divInformacoesProfissionais").show();
	$("#ddlCargo").focus();
	$("input, select", $("#divInformacoesProfissionais")).val("");
	$("#txtTelefoneComercialDDD").val("").unmask().mask("99");
	$("#txtTelefoneComercialNumero").val("").unmask().mask("99999999");
}


/**
 * EMPREGA ATUALMENTE NÃO
**/
function EmpregadoAtualmenteNao()
{
	$("#divInformacoesProfissionais").hide();
	$("input, select", $("#divInformacoesProfissionais")).val("");
	$("#txtTelefoneComercialDDD").val("").unmask();
	$("#txtTelefoneComercialNumero").val("").unmask();
}


/**
 * MODELO ANO FISCAL
**/
function ModeloAnoFiscal(o)
{
	if(!o.checked)
	{
		$("#tdModeloAnoFiscal").show();
		$("select", $("#tdModeloAnoFiscal")).val("");
		$("#ddlModeloAnoFiscalInicio").focus();
	}
	else
	{
		$("#tdModeloAnoFiscal").hide();
		$("select", $("#tdModeloAnoFiscal")).val("");
	}
}


/**
 * MUDAR EMPRESA
**/
function MudarEmpresa(o)
{
	if(o.value.length > 1)
	{
		var n = $("#ddlPessoaJuridica").html('<option value="">Carregando...</option>').attr("disabled", "disabled");
		$.get(((typeof Admin != undefined) ? "empresa.php" : "../cadastre-se/empresa.php"), {nome:o.value}, function(dados){
			n.html('<option value="">Procure sua empresa aqui</option>' + dados + '<option value="LTE=">Não encontrei</option>').removeAttr("disabled");
			$("option", n).removeAttr("selected");
		});
	}
}


/**
 * MUDAR EMPRESA DROP
**/
function MudarEmpresaDrop(o)
{
	if(o.value == 'LTE=')
	{
		$("#tbEloCadeia").show();
		$("#ddlEloCadeia").val("");
		MoveNext(o, 'ddlEloCadeia');
	}
	else
	{
		$("#tbEloCadeia").hide();
		$("#ddlEloCadeia").val("");
		MoveNext(o, 'txtTelefoneComercialDDD');
	}
}


/**
 * PESQUISA CEP
**/
function PesquisaCEP(o)
{
	var value = o.value.replace("_", "").replace("-", "");
	if(value.length < 8)
	{
		return false;
	}
	
	//carergando
	$("#lblCEPCarregando").show();
	$("#lblCEPNaoEncontrado").hide();
	
	//busca cep
	$.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep=" + value, function(){
		
		$("#lblCEPCarregando").hide();
		
		if(resultadoCEP ["resultado"] == "1")
		{
			$("#ddlTipoLogradouro").val(unescape(resultadoCEP ["tipo_logradouro"]));
			$("#txtLogradouro").val(unescape(resultadoCEP ["logradouro"]));
			$("#txtBairro").val(unescape(resultadoCEP ["bairro"]));
			$("#txtCidade").val(unescape(resultadoCEP ["cidade"]));
			$("#txtUF").val(unescape(resultadoCEP ["uf"]));
			$("#txtNumero").focus();
		}
		else
		{
			$("#lblCEPNaoEncontrado").show();
			$("#ddlTipoLogradouro").focus();
		}
	});
}


/**
 * SALA DE DISCUSSÃO
**/
var SalaDiscussao = {
	
	iInterval : 0,
	
	id : null,
	
	pg : 0,
	 
	Init : function(id){
		
		var o = this;
		
		o.id = id;
		
		$(document).ready(function(){
			o.Start();
		});
	},
	
	Start : function(){
		
		var o = this;
		
		o.LoadMessage();
			
		o.iInterval = setInterval(function(){
			
			o.LoadMessage();
			
		}, 5000);
	},
	
	LoadMessage : function(){
		$('#divMensagem').load("mensagens.php?id=" + this.id + "&pg=" + this.pg);
	},
	
	Anterior : function(){
		this.pg--;
		this.LoadMessage();
	},
	
	Proxima : function(){
		this.pg++;
		this.LoadMessage();
	}
}


function findSWF(movieName) {
	if (window.document[movieName]) {
  		return window.document[movieName];
  	}
  	if (navigator.appName.indexOf("Microsoft Internet")==-1){
	    if (document.embeds && document.embeds[movieName]){
      		return document.embeds[movieName];
		} 
  	}
  	else{
	    return document.getElementById(movieName);
  	}
}


/**
 * CHAT
**/
var Chat = {
	
	ID : null,
	
	URL : null,
	
	iInterval: null,
	
	Init: function(ID, URL){
		
		var o = this;
		
		o.ID = ID;
		o.URL = URL;
		
		$(document).ready(function(){
			o.Start();
			o.Resize();
		});
		
		$(window).resize(o.Resize);
	},
	
	Resize: function(){
		var h = (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.offsetHeight;
		$(".scroll").css("height", (525 - (861 - h)) + "px");
		$(".participantes .scrollUsuario").css("height", (655 - (861 - h)) + "px");
	},
	
	Start: function(){
		
		var o = this;
	
		o.Load();
		o.Scrolling();
			
		o.iInterval = setInterval(function(){
			
			o.Load();
			
		}, 5000);
	},
	
	Load: function(){
		this.GetMessage();
		this.GetUsers();
	},
	
	GetMessage: function(){
		var o = this;
		$.get("chatmensagens.php", {id: o.ID}, function(dados){
			if(dados == "-1"){
				window.location.href = o.URL;
			}else{
				$('#divMensagem').html(dados);
				o.Scrolling();
			}
		});
		
	},
	
	GetUsers: function(){
		var o = this;
		$.get("chatparticipantes.php", {id: o.ID}, function(dados){
			if(dados == "-1"){
				window.location.href = o.URL;
			}else{
				$('#divUsuario').html(dados);
			}
		});
	},
	
	Scrolling: function(){
		if($("#cbRolagem").get(0).checked && $('#divMensagem').html())
		{
			var divOffset = $('#divMensagem').offset().top;
			var pOffset = $('#divMensagem p:last').offset().top;
			var pScroll = pOffset - divOffset;
			$('#divMensagem').animate({scrollTop: '+=' + pScroll + 'px'}, 1000);
		}  
	},
	
	AddMessage: function(){
		var msg = $("#txtMensagem").val();
		if(msg)
		{
			$.get("chatadd.php", {id: this.ID, msg: msg}, function(dados){
				if(dados == "-1"){
					window.location.href = o.URL;
				}
			});
			$("#txtMensagem").val("").focus();
		}
	},
	
	Bloquear: function(usuarioid){
		if(confirm("Deseja realmente bloquear esse usuário ?")){
			$.get("chatbloquear.php", {id: this.ID, usuarioid: usuarioid}, function(dados){
				if(dados == "-1"){
					window.location.href = o.URL;
				}
			});
		}
	},
	
	RemoveMessage: function(mensagemid){
		if(confirm("Deseja realmente remover essa mensagem ?")){
			$.get("chatremovermensagem.php", {id: this.ID, mensagemid: mensagemid}, function(dados){
				if(dados == "-1"){
					window.location.href = o.URL;
				}
			});
		}
	}
};
