/*
*
*	JavaScript Document
*
*	Data:				00/00/0000
*	Descricao:			Arquivo com as funções globais do projeto
*	Autor:				Marcelo Casinha
*	E-mail: 			marcelo@gadbrivia.com.br
	
*	Observacoes:		USE ESTE ARQUIVO SOMENTE PARA FUNÇÕES GENÉRICAS APLICÁVEIS A MAIS DE UMA ENTIDADE (EF) 
*
*/

// Funcao para inserir _blank em links externos
function ExternoLink() 
{
	$("a[rel=external]").attr("target", "_blank");
}
// Funcao para inserir _blank em links externos
function RetornoLink() 
{
	$("a[rel=back]").click( function(){ history.back(); return false });
}
// Funcao para inserir funcao de imprimir nos links
function ImprimirLink() 
{
	$("a[rel=print]").click( function(){ print(); })
}
// Funcao para inserir funcao de adicionar aos favoritos nos links
function FavoritoLinks()
{
	$("a[rel=bookmark]").click( function(){
		if (document.all) window.external.AddFavorite(window.location.href, document.title);
		else if (window.sidebar) window.sidebar.addPanel(document.title, window.location.href, "")
	});
}

// Ajax para carregar as UnidadesFederativas
function CarregarUnidadeFederativa(paisID, objeto)
{
	if(paisID == '')
	{
		return false;
	}
	// Exibe a mensagem de Carregando...
	objeto.html('<option value="" >'+FORM_CARREGANDO+'</option>');
	
	// Executa a consulta em ajax	
	$.ajax(
	{
		type: "POST",
		url: CAMINHO_ABSOLUTO  + "unidade-federativa/carregar-unidade-federativa",
   		data: 
   		{
   			PaisID: paisID
   		},
   		success: function(retorno)
   		{
   			// Limpa o combo
   			objeto.html('');
   			objeto.append('<option value="" >'+FORM_SELECIONE+'</option>');
    		eval('var colecaoUnidadeFederativa = ' + retorno);
    		
    		// Caso a coleção seja valida, popula o combo
    		if(colecaoUnidadeFederativa != undefined)
    		{
    			
	    		for(var contador = 0;contador < colecaoUnidadeFederativa.length; contador ++)
	    		{
	    			objeto.append('<option value="' + colecaoUnidadeFederativa[contador].UnidadeFederativaID + '" >' + colecaoUnidadeFederativa[contador].Nome + '</option>');
	    		}
    		}
    		// Caso contrario, exibe a mensagem "Nenhum registro encontrado"
    		else
    		{
    			objeto.html('<option value="" >'+FORM_NENHUM_REGISTRO+'</option>');
    		}
   		}
	});	
}

// Ajax para carregar as UnidadesFederativas
function CarregarMunicipio(unidadeFederativaID, objeto)
{
	if(unidadeFederativaID == '')
	{
		return false;
	}
	// Exibe a mensagem de Carregando...
	objeto.html('<option value="" >'+FORM_CARREGANDO+'</option>');
	$('#selCidade-items').html('');
	selects[objeto.attr("id")].render();
	
	
	// Executa a consulta em ajax	
	$.ajax(
	{
		type: "POST",
		url: CAMINHO_ABSOLUTO  + "municipio/carregar-municipio",
   		data: 
   		{
   			UnidadeFederativaID: unidadeFederativaID
   		},
   		success: function(retorno)
   		{
   		
   		
/*
   			if($("#selMunicipioID").is(".custom-select"))
			{
				$("#selMunicipioID").prev().remove();
				selects[$("#selMunicipioID").attr("id")] = new $.ComboBox({id:$("#selMunicipioID").attr("id"),size:30});
				selects[$("#selMunicipioID") .attr("id")].render();
			}
*/
   			// Limpa o combo
   			objeto.html('');
   			objeto.append('<option value="" >'+FORM_SELECIONE+'</option>');
    		eval('var colecaoMunicipio = ' + retorno);
    		
    		// Caso a coleção seja valida, popula o combo
    		if(colecaoMunicipio != undefined)
    		{
    			
	    		for(var contador = 0;contador < colecaoMunicipio.length; contador ++)
	    		{
	    			objeto.append('<option value="' + colecaoMunicipio[contador].MunicipioID + '" >' + colecaoMunicipio[contador].Nome + '</option>');
	    		}
    		}
    		// Caso contrario, exibe a mensagem "Nenhum registro encontrado"
    		else
    		{
    			objeto.html('<option value="" >'+FORM_NENHUM_REGISTRO+'</option>');
    		}
    		selects[$('#selMunicipioID').attr("id")].render();
   		}
	});	
}

// Função que auxilia na visualização de campos conforme o pais
function VisualizarCamposRegiao(parametro, classePrimaria, classeSecundaria)
{
	switch(parametro)
	{
		case 1: // Brasil
			$('.' + classePrimaria).show()
			$('.' + classeSecundaria).hide()
			$('input:not(:checkbox,:radio,:password).' + classeSecundaria).val('');
			$('select.' + classeSecundaria).val('');
			$('textarea.' + classeSecundaria).val('');
			$('input:checkbox.' + classeSecundaria).removeAttr('checked');
			$('input:radio.' + classeSecundaria).removeAttr('checked');
			break;
		case 2: // Estrangeiro
			$('.' + classePrimaria).hide()
			$('.' + classeSecundaria).show()
			$('input:not(:checkbox,:radio,:password).' + classePrimaria).val('');
			$('select.' + classePrimaria).val('');
			$('textarea.' + classePrimaria).val('');
			$('input:checkbox.' + classePrimaria).removeAttr('checked');
			$('input:radio.' + classePrimaria).removeAttr('checked');
			break;
		default: // Reseta todos os campos
			$('.' + classePrimaria).show()
			$('.' + classeSecundaria).hide()
			$('input:not(:checkbox,:radio,:password).' + classePrimaria + ', input:not(:checkbox,:radio,:password).' + classeSecundaria).val('');
			$('select.' + classePrimaria + ', select.' + classeSecundaria).val('');
			$('textarea.' + classePrimaria + ', textarea.' + classeSecundaria).val('');
			$('input:checkbox.' + classePrimaria).removeAttr('checked');
			$('input:radio.' + classePrimaria).removeAttr('checked');
			$('input:checkbox.' + classeSecundaria).removeAttr('checked');
			$('input:radio.' + classeSecundaria).removeAttr('checked');
			break;
	}
}

// Função que declara os eventos change paises, estados e cidades.
function DelcararVizualizarPaisEstadoCidade()
{
	// Carregar os Estados de Acordo com os países
	$('#selPaisID').change(function() 
	{
		var paisID = $(this).val();
		if(paisID == CONSTANTE_PAIS_BRASIL_ID)
		{
			CarregarUnidadeFederativa(paisID, $('#selUnidadeFederativaID'));
			VisualizarCamposRegiao(1,'nacional','internacional');
			$('#txtMunicipioExterior').parent('li').addClass('menor');
		}
		else if(paisID != CONSTANTE_PAIS_BRASIL_ID && paisID != '')
		{
			VisualizarCamposRegiao(2,'nacional','internacional');
			$('#txtMunicipioExterior').parent('li').removeClass('menor');
		}
		else
		{
			VisualizarCamposRegiao(null,'nacional','internacional');
			$('#txtMunicipioExterior').parent('li').addClass('menor');
		}
		/*
		$(".custom-select").each(function() {
        	selects[$(this).attr("id")].render();
	    });
	    */
	});
	
	//Carregar as Cidades de Acordo com os estados
	$('#selUnidadeFederativaID').change(function() 
	{
		var unidadeFederativaID = $(this).val();
		CarregarMunicipio(unidadeFederativaID, $('#selMunicipioID'));
		
		if($('.passo-1').length > 0 )
	    {
			setTimeout(function()
			{
		    	selects[$('#selMunicipioID').attr("id")].render();
		      	$('#selMunicipioID-items').children('li:eq(0)').hide();
		      	$('#selMunicipioID-items') .children('li:eq(1)').hide();
			},1000);
		}
	});
}

// Função que atribui mascasrás atrávez de classes CSS
function DeclararMascaras()
{
	$('input.data, input.cep, input.telefone, input.cpf, input.cnpj').unbind();
	$('input.data').mask('99/99/9999');
	$('input.cep').mask('99999-999');
	$('input.telefone').mask('(99) 9999-9999');
	$('input.cpf').mask('999.999.999-99');
	$('input.cnpj').mask('999.999.999/9999-99');
	$('input.numero').numeric();
}

//Funcao para validar email
function ValidarEmail(email){
    var expressao = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(email) == "string")
    {
    	if(expressao.test(email))
    	{ 
    		return true; 
    		}
    }
    else if(typeof(email) == "object")
    {
            if(expressao.test(email.value))
            { 
            	return true; 
            }
    }
    else
    {
    	return false;
    }
}

function LimitaTamanho(campo, limite){
    valor = eval("document.forms[0]."+campo+".value");
    limite = parseInt(limite);
    if(valor.length > limite){
        erroValue = ("O Valor máximo do campo é "+limite+" caracteres.");
        return false;
    }
    return true;
}

function LimitarTxa(campo, limite)
{
	campo.keyup(function()
	{
		if ( $(this).val().length > limite )
		{
			$(this).val( $(this).val().substring(0,limite) );
		}
	});
}


//variavel usada para instanciar selects customizados
var selects = new Object();

// Função para iniciar as demais
$(document).ready(function() 
{

	// Shadows
	$('.shadow').textShadow();
	
	var usuarioDefualt = $('#txtUsuario').val();
	var senhaDefault = $('#txtSenha').val();
	
	$('#txtUsuario').live("focus", function()
	{
		if( $('#txtUsuario').val() == usuarioDefualt && $('#txtSenha').val() == senhaDefault)
		{
			$('#txtUsuario').val('');
			$('.senha').html('');
			$('.senha').html('<input type="password" id="txtSenha" maxlength="128" name="txtSenha" value=""/>');
		}
	});
	
	$('#txtSenha').live("focus", function()
	{
		if( $('#txtUsuario').val() == usuarioDefualt && $('#txtSenha').val() == senhaDefault)
		{
			$('#txtUsuario').val('');
			$('.senha').html('');
			$('.senha').html('<input type="password" id="txtSenha" maxlength="128" name="txtSenha" value=""/>');
			$('#txtSenha').focus();
		}
	});
	
	//HOVER MENU 
	$('.li-pai').hover(function () 
	{
		$('.li-pai').children('div').hide();
		$('.li-pai').find('a').removeClass('ativo');
		$(this).children('ul').show();
		$(this).find('a').addClass('ativo');
		$(this).children('div').show();		
	},
	function ()
	{
		$(this).children('ul').hide();
		if(!($(this).hasClass('produtos'))){
			$('#menu-global .li-pai').find('a').removeClass('ativo');
		}
		$(document).click(function(){
			$('#menu-global li.produtos').children('div').hide();
			$('#menu-global li.produtos').find('a').removeClass('ativo');
		});
		
		if( $('#txtUsuario').val() == '' && $('#txtSenha').val() == '')
		{
			$('#txtUsuario').val(usuarioDefualt);
			$('.senha').html('');
			$('.senha').html('<input type="text" id="txtSenha" name="txtSenha" value="'+senhaDefault+'"/>');
			$('#frmLogin').find('.msg-erro').html('');
		}
	});
	
	//formulario de login (ajax, validacao, login e logout)
	if( $('#frmLogin').length > 0 )
	{
		$('#frmLogin').submit(function(evento)
		{
			evento.preventDefault(); 
			
			if( $('#txtUsuario').val() == '' || $('#txtUsuario').val() == usuarioDefualt )
			{
				$('.msg-erro').html(MSG32.replace('{CAMPO}',usuarioDefualt));
			}
			else if( !ValidarEmail($('#txtUsuario').val()) )
			{
				$('.msg-erro').html(MSG27.replace('{CAMPO}',usuarioDefualt));
				erros = true;
			}
			else if( $('#txtSenha').val() == '' || $('#txtSenha').val() == senhaDefault )
			{
				$('.msg-erro').html(MSG32.replace('{CAMPO}',senhaDefault));
			}	
			else
			{
				$('.msg-erro').html('');
				$.ajax(
				{
					type: "POST",
					url: CAMINHO_ABSOLUTO + "produtos/login",
		   			data: 
		   			{
		   				Email: $('#txtUsuario').val(),
		   				Senha: $('#txtSenha').val()
		   			},
		   			success: function(retorno)
		   			{
		     			if(retorno == "ok")
		     			{
		     				window.location.href = CAMINHO_ABSOLUTO;
		     			}
		     			else
		     			{
		     				$('#frmLogin').find('.msg-erro').html(MSG11);
		     			}		
		   			}
		   		});	
			}
		});	
	}
	
	//link para deslogar
	$('.lk-sair').click(function() 
	{
		$.ajax(
		{
			url: CAMINHO_ABSOLUTO + "produtos/logout",
   			success: function(retorno)
   			{
     			if( retorno == 'ok')
     			{
     				window.location.href = CAMINHO_ABSOLUTO;
     			}			
   			}
   		});	
	});
	
	
	//thickbox Recuperar Senha
	if( $('#frmEmail').length > 0 )
	{
		var emailDefault = $('#txtEmail').val();
		
		$('#txtEmail').focus(function() 
		{
			if( $('#txtEmail').val() == emailDefault )
			{
				$('#txtEmail').val('');
			}
		});
		
		$('#txtEmail').blur(function() 
		{
			if( $('#txtEmail').val() == '' )
			{
				$('#txtEmail').val(emailDefault);
			}
		});
		
		$('#btnRecuperarSenha').click(function() 
		{
			if( !ValidarEmail($('#txtEmail').val()) )
			{
				$('.msg-erro').html(MSG27.replace('{CAMPO}','email'));
				return false;
			}
			else
			{
				$.ajax(
				{
					type: "POST",
					url: CAMINHO_ABSOLUTO + "produtos/esqueci-senha",
					async: false,
		   			data: 
		   			{
		   				Email: $('#txtEmail').val()
		   			},
		   			success: function(retorno)
		   			{
		   				var email = $('#txtEmail').val();
		   				$('.mensagem').children().hide();
		     			if( retorno == true )
		     			{
		     				$('.mensagem').children().addClass('msg-sucesso').removeClass('msg-erro');
		     				$('.mensagem').children().html(MSG09.replace('{EMAILDESTINO}',email));
		     				$('.mensagem').children().show('slow');
		     				$('#btnRecuperarSenha').hide('slow');
		     				$('.lk-cancelar').animate({marginLeft: '257px'}, 1000,"linear", function(){$('.lk-cancelar').addClass('lk-fechar-esqueci-senha').removeClass('lk-cancelar')});
		     			}
		     			else
		     			{
		     				$('.msg-erro').html(MSG10.replace('{EMAILDESTINO}',email));
		     				$('.msg-erro').show('slow');
		     				return false;
		     			}	
		   			}
		   		});	
			}
		});
	}
	/* < menu de produtos no topo > */
	$('li.produtos').hover(function () 
	{ 
		produtoDestaque = new Object;
		produtoDestaque.img = $('.produto-detalhe .produto-detalhe-img').attr('src');
		produtoDestaque.legenda = $('.produto-detalhe .produto-detalhe-legenda').html();		
	},
	function ()
	{
		$('.produto-detalhe .produto-detalhe-legenda').html(produtoDestaque.legenda);
		$('.produto-detalhe .produto-detalhe-img').attr('src',produtoDestaque.img);
	});	
	
	$('.lk-produto-menu').hover(function()
	{
		var legenda = $(this).prev().html();
		var imagem = CAMINHO_IMAGEM_PRODUTO_MINIATURA_MENU + $(this).prev().prev().html();
		
		$('.produto-detalhe .produto-detalhe-legenda').html(legenda);
		$('.produto-detalhe .produto-detalhe-img').attr('src',imagem);
	}); 
	
	// Links
	$('.lista-produtos li').click(function(){
		var href = $(this).find('a:first').attr('href');
		window.parent.location = href;
	});
	
	// Adiciona classe a cada 4 lis no menu produtos
	var quantidade = 0;
	$('.sub-menu-produtos .lista-produtos').each(function()
	{
		quantidade = quantidade + 1;
		if( quantidade == 5 )
		{
			$(this).addClass('clear');
			quantidade = 1;
		}
	});
	/* < /menu de produtos no topo > */
	
	
	//Inicia select customizáveis
	$(".custom-select").each(function() 
	{
		selects[$(this).attr("id")] = new $.ComboBox({id:$(this).attr("id"),size:30});
		selects[$(this).attr("id")].render();
	});
		
	ExternoLink(); // Funcao para inserir _blank em links externos
	RetornoLink(); // Funcao para inserir função de retorno no link
	ImprimirLink(); // Funcao para inserir função de imprimir no link
	FavoritoLinks(); // Funcao para inserir função de adicionar aos favoritos no link
	DeclararMascaras(); // Funcao para Declarar as máscaras
	DelcararVizualizarPaisEstadoCidade(); // Função que declara os eventos change paises, estados e cidades.
	
});
