/*------------------------------------------------------------------------------
	FUNÇÃO PARA LIMPAR ITENS DE UM LISTBOX
------------------------------------------------------------------------------*/

jQuery.fn.clearbox = function() 
{
	return this.each(function() {
	
		for (i=this.options.length-1; i>=0; i--)
		{
			this.options[i] = null;
		}
		
	});
};

/*------------------------------------------------------------------------------
	FUNÇÃO PARA SELECIONAR UM DETERMINADO ITEM DO COMBO
------------------------------------------------------------------------------*/

jQuery.fn.select = function(mode,i) 
{
	var i;
	var mode;
	return this.each(function() {
	
		switch(mode) 
		{
			case 'on': this.options[i].selected = true; break;
			case 'off': this.options[i].selected = false; break;
		}
		
	});
};

/*------------------------------------------------------------------------------
	FUNÇÃO PARA HABILITAR OU DESABILITAR CAMPOS DO FORM
------------------------------------------------------------------------------*/

jQuery.fn.disable = function(mode) 
{
	var mode = mode || 'on';
	return this.each(function() {
	
		switch(mode) 
		{
			case 'on': this.disabled = true; break;
			case 'off': this.disabled = false; break;
			case 'toggle': this.disabled = !this.disabled; break;
		}
		
	});
};

/*------------------------------------------------------------------------------
	FUNÇÃO PARA PREENCHER CAMPOS DO TIPO RADIO E CHECKBOX
------------------------------------------------------------------------------*/

jQuery.fn.check = function(mode) 
{
	var mode = mode || 'on';
	return this.each(function() {
	
		switch(mode) 
		{
			case 'on': this.checked = true; break;
			case 'off': this.checked = false; break;
			case 'toggle': this.checked = !this.checked; break;
		}
		
	});
};


/*------------------------------------------------------------------------------
	PREPARA O DOCUMENTO, SE CARREGADO PODE EXECUTAR AS FUNÇÕES
------------------------------------------------------------------------------*/

$().ready(function(){

	
	//BUSCA CIDADES DO ESTADO SELECIONADO
	//FUNÇÃO PARA BUSCA DE CIDADES
	//
	$("select[@name=estado]").change(function(){
		$('select[@name="cidade[]"]').html('<option value="">Carregando lista de Cidades</option>');
			$.post('../acoes.php?acao=busca_cidades_grupo', { estado : $(this).val() }, function(resposta) { $('select[@name="cidade[]"]').html('<option value="">'+resposta+'</option>'); }
		);
	});
	
	
	
	//BUSCA OS EQUIPAMENTOS DE ACORDO COM O GRUPO
	//FUNÇÃO PARA RETORNAR NOME DOS EQUIPAMENTOS
	//
	$("select[@name='grupo']").change(function(){
			$('select[@name="equipamento"]').html('<option value="">Carregando lista de Equipamentos</option>');
			$.post('../acoes.php?acao=busca_equipamento', { grupo : $(this).val(), comoutros : $('input[@name="comoutros"]').val() }, function(resposta) { $('select[@name="equipamento"]').html('<option value="">'+resposta+'</option>'); });
	});
	
	//BUSCA AS CORTESIAS DE ACORDO COM A CATEGORIA
	//
	$("select[@name='categoria']").change(function(){
			$('select[@name="cortesia"]').html('<option value="">Carregando lista de Cortesias</option>');
			$.post('../acoes.php?acao=busca_cortesia', { id : $(this).val() }, function(resposta) { $('select[@name="cortesia"]').html('<option value="">'+resposta+'</option>'); });
	});
	
	
	
	//SELECIONA O VALOR E RETORNA O RESULTADO
	//FUNÇÃO PARA RETORNAR O VALOR DO PRODUTO NA PROPOSTA
	//
	$("select[@name='tipo_valor']").change(function(){
			$('input[@name="valor"]').val('Aguarde...');
			$.post('../acoes.php?acao=busca_preco_equipamento', { id : $('select[@name="equipamento"]').val(), tipo : $(this).val() }, function(resposta) { $('input[@name="valor"]').val(resposta); });
	});
	
	
	
	//SE FOR OUTRO EQUIPAMENTO MOSTRA CAMPO
	//RETORNA INPUT PARA DIGITAR O EQUIPAMENTO DESCONTINUADO
	//
	$("select[@name='equipamento']").change(function(){
		if ($(this).val() == "1000")
		{
			$("input[@name='outro_equipamento']").disable('off');			
		}
		else
		{
			$("input[@name='outro_equipamento']").disable('on');
			$("input[@name='outro_equipamento']").val("");	
		}
	});
	
	
	
	//BUSCA CONTATOS POR TELEFONE
	//FUNÇÃO PARA CONTROLE DE AÇÕES
	//
	$("select[@name='tipo_realizado']").change(function(){
		
		if ($("input[@name='tipo']").val() == 1)
		{
			if ($("select[@name='tipo_realizado']").val() == "Representante") 
			{
				var texto = "Carregando lista de Representantes"; 
				var url = "busca_usuarios&nivel=3";
				
				$("input[@name='contato']").disable('on');
				$("input[@name='contato']").val("");
				
				$("input[@name='funcao']").disable('on');
				$("input[@name='funcao']").val("");
			}
			else if ($("select[@name='tipo_realizado']").val() == "Cliente") 
			{
				var texto = "Carregando lista de Clientes";
				var url   = "busca_clientes";
				
				$("input[@name='contato']").disable('off');
				$("input[@name='funcao']").disable('off');
			}
			else if ($("select[@name='tipo_realizado']").val() == "Técnico (Interno)")
			{
				var texto = "Carregando lista de Técnicos Internos";
				var url   = "busca_usuarios&nivel=4";	
				
				$("input[@name='contato']").disable('on');
				$("input[@name='contato']").val("");
				
				$("input[@name='funcao']").disable('on');
				$("input[@name='funcao']").val("");
			}
			else if ($("select[@name='tipo_realizado']").val() == "Técnico (Externo)")
			{
				var texto = "Carregando lista de Técnicos Externos";
				var url   = "busca_usuarios&nivel=6";	
				
				$("input[@name='contato']").disable('on');
				$("input[@name='contato']").val("");
				
				$("input[@name='funcao']").disable('on');
				$("input[@name='funcao']").val("");
			}
			
			$('select[@name="para"]').html('<option value="">'+texto+'</option>');
			$.post('../acoes.php?acao='+url, { comoutros: $('input[@name="comoutros"]').val(), usuario: $('input[@name="usuario_id"]').val(), usuario_nivel: $('input[@name="usuario_nivel"]').val() }, function(resposta) { $('select[@name="para"]').html('<option value="">'+resposta+'</option>'); });
		}
		
		if ($("input[@name='tipo']").val() == 3)
		{
			if (($("select[@name='tipo_realizado']").val() == "Proposta") || ($("select[@name='tipo_realizado']").val() == "Pedido"))	
			{
				$("select[@name='feira']").select('on',0);
				$("select[@name='feira']").disable('on');
				$("input[@name='assunto']").disable('on');
				$("input[@name='assunto']").val("");
			}
			else if ($("select[@name='tipo_realizado']").val() == "Feira / Eventos") 
			{
				$("input[@name='assunto']").disable('off');
				$("select[@name='feira']").disable('off');
				$('select[@name="feira"]').html('<option value="">Carregando lista de Feiras/Eventos</option>');
				$.post('../acoes.php?acao=busca_feiras', function(resposta) { $('select[@name="feira"]').html('<option value="">'+resposta+'</option>'); });	
			}
			else
			{
				$("select[@name='feira']").select('on',0);
				$("select[@name='feira']").disable('on');
				$("input[@name='assunto']").disable('off');		
			}			
		}
	});	
	
	
	//SE TIPO FOR TÉCNICO E EXTERNO ABRE CAMPO
	//FUNÇÃO PARA CONTROLE DE AÇÕES POR TELEFONE
	//
	$("select[@name='para']").change(function(){
		if (($(this).val() == "1000") || ($("select[@name='tipo_realizado']").val() == "Cliente"))
		{
			$("input[@name='contato']").disable('off');
		}
		else
		{
			$("input[@name='contato']").disable('on');
			$("input[@name='contato']").val("");
		}
	});
	
	
	//BUSCA ACOMPANHANTES DE VISITAS
	//FUNÇÃO PARA CONTROLE DE AÇÕES
	//
	$("select[@name='visita_feita_com']").change(function(){
		
		if (($("input[@name='tipo']").val() == "recado"))
		{
			var texto = "Carregando lista de Cadastrados";
		}
		else
		{
			var texto = "Carregando lista de Acompanhantes";
		}
		
		var url   = "busca_usuarios&nivel="+$(this).val();	
		
		$('select[@name="acompanhante"]').html('<option value="">'+texto+'</option>');
		$.post('../acoes.php?acao='+url, function(resposta) { $('select[@name="acompanhante"]').html('<option value="">'+resposta+'</option>'); });	
	});	
	
	
	//RETORNA SE O CLIENTE É ESTRANGEIRO OU BRASILEIRO
	//FUNÇÃO PARA CLIENTES
	//
	$("select[@name='tipo_cliente']").change(function(){
		if ($(this).val() == "Brasil")	
		{
			$("select[@name='estado']").disable('off');
			
			$("input[@name='estado_estrangeiro']").disable('on');
			$("input[@name='estado_estrangeiro']").val("");
			
			$("input[@name='cidade_estrangeiro']").disable('on');
			$("input[@name='cidade_estrangeiro']").val("");
			
			$("select[@name='pais']").disable('on');
			$("select[@name='pais']").select('on',0);
			
		}
		else if ($(this).val() == "Exterior") 
		{
			$("select[@name='estado']").disable('on');
			$("select[@name='estado']").select('on',0);
			$("input[@name='cidade']").val("");
			
			$("input[@name='estado_estrangeiro']").disable('off');
			$("input[@name='cidade_estrangeiro']").disable('off');
			$("select[@name='pais']").disable('off');
		}
	});	

	
	
	//HABILITA CAMPO DE DESCRIÇÃO SE FOR OUTRA CORTESIA
	//FUNÇÃO PARA CORTESIAS
	//
	$("select[@name='categoria_cortesia']").change(function(){
		if ($(this).val() == 3)	
		{
			$("textarea[@name='outros']").disable('off');		
			$("input[@name='cortesia']").disable('on');
			$("input[@name='cortesia']").val("");
		}
		else
		{
			$("textarea[@name='outros']").disable('on');
			$("textarea[@name='outros']").val("");
			$("input[@name='cortesia']").disable('off');		
		}
	});	
	
	
	
	//HABILITA CAMPOS SE NIVEL FOR 2 OU 3
	//FUNÇÃO PARA USUÁRIOS
	//
	$("select[@name='nivel']").change(function(){
		
		if (($(this).val() == 2) || ($(this).val() == 3))
		{
			$("input[@name='area_atuacao']").disable('off');
		}
		else
		{
			$("input[@name='area_atuacao']").disable('on');
		}
	});
	
	
	//RETORNA DE ONDE VEIO O CLIENTE
	//FUNÇÃO PARA OBTER DADOS DO CLIENTE
	//
	$("select[@name='local']").change(function(){
				
		if ($(this).val() == "Brasil")
		{
			$("select[@name='estado']").disable('off');
			$("select[@name='cidade[]']").disable('off');
			$("select[@name='pais']").disable('on');
			
			$("select[@name='pais']").select('on',0);
			
			var campos = "";
			
			$('#divCamposExterior').css({display: "none"});
			$('#divCamposExterior').html(campos);
		}
	
		if ($(this).val() == "Exterior")
		{
			$("select[@name='pais']").disable('off');
			$("select[@name='estado']").disable('on');
			$("select[@name='cidade[]']").disable('on');
			
			$("select[@name='estado']").select('on',0);
			$("select[@name='cidade[]']").clearbox();
			
			var campos = "";
			campos = campos + '<table width="100%" border="0" cellpadding="0" cellspacing="0">';
			campos = campos + '<tr>';
			campos = campos + '<td width="280">Estado:</td>';
			campos = campos + '<td width="20" hieght="20"></td>';
			campos = campos + '<td width="280">Cidade:</td>';
			campos = campos + '</tr>';
			campos = campos + '<td><input name="ext_estado" type="text" id="ext_estado" style="width:280px;" value="" maxlength="100"></td>';
			campos = campos + '<td></td>';
			campos = campos + '<td><input name="ext_cidade" type="text" id="ext_cidade" style="width:280px;" value="" maxlength="150"></td>';
			campos = campos + '</tr>';
			campos = campos + '</table>';
			
			$('#divCamposExterior').css({display: "block"});
			$('#divCamposExterior').html(campos);
		}
	
	});
	
	
	//RETORNA ENDEREÇO E TELEFONE DO CLIENTE
	//FUNÇÃO PARA OBTER DADOS DO CLIENTE
	//
	$("select[@name='cliente']").change(function(){
			$('textarea[@name="dados"]').val('Aguarde...');
			$.post('../acoes.php?acao=busca_clientes_dados', { id : $(this).val() }, function(resposta) { $('textarea[@name="dados"]').val(resposta); });
	});

	
});
