$(function()
{
	$("#Telefone").mask("9999-9999");
	$("#DDDTelefone").mask("(99)");
	$("#Celular").mask("9999-9999");
	$("#DDDCelular").mask("(99)");
	$("#Cep").mask("99999999");
	
	$('#TicketMedio').keypress(function()
	{
		FormatarParaMoeda(this, 2);
	});
	
	/*$('#FluxoMensal').keypress(function()
	{
		FormataCampo(this, event,'Numero');
	});*/

});


function Validator()
{
	todosCamposValidos = true;

	$('#mainform').find('input.required').each(function()
	{
		if($(this).val() == '')
		{
			alert('Campo de ' + $(this).attr('alert') + ' obrigatório.');

			todosCamposValidos = false;

			$(this).focus();

			return false;
		}
		//verificando pra tipo e-mail
		if($(this).attr('email') == 1)
		{
			//if(!(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/.test($(this).val())))
			if(!(/^\w+(\.\w+)?@\w{2,}\.\w{2,}/.test($(this).val())))
			{
				alert('E-mail inválido.');

				todosCamposValidos = false;

				$(this).focus();
	
				return false;
			}
		}
		
		//verificando pra checkbox
		if($(this).attr('checkbox') == 1 && $(this)[0].checked==false)
		{
			alert('Campo de ' + $(this).attr('alert') + ' obrigatório.');

			todosCamposValidos = false;

			$(this).focus();

			return false;
		}
		
	});

	if(todosCamposValidos)
	{
		$('#mainform').submit();
		return true;
	}
	
}



function FormataNumeroMoeda(cur, e, len, casas)
{
	n='__0123456789';
	d=cur.value;
	l=d.length;
	r='';
	
   //alert(e);

   if (e.keyCode == 13 || e.keyCode == 8 || e.keyCode == 0 || e.keyCode == 9)
        return true;  // Enter backspace ou FN qualquer um que não seja alfa numerico    */

    if(casas==0)
        return true;

	if (l > 0)
	{
		//arazena o valor anterior que estava digitado
		z=d.substr(0,l-1);

		//pega somente os numeros do campo
		s='';
		a=2;
		for (i=0; i < l; i++)
		{
			c=d.charAt(i);
			if (n.indexOf(c) > a)
			{
				a=1;
				s+=c;
			};
		};

		//não permite digitar numero superior a len
		l=s.length;
		t=len-1;
		if (l > t)
		{
			l=t;
			s=s.substr(0,t);
		};
		//coloca a quantidade de casas
		if (l > casas)
			r=s.substr(0,l-casas)+','+s.substr(l-casas,casas);
		else
		{
			if(casas == 2)
			{
				if (l == 1)
					r='0,0'+s;
				else if (l == 2)
					r='0,'+s;
			}
			else if(casas == 3)
			{
				if (l == 1)
					r='0,00'+s;
				else if (l == 2)
					r='0,0'+s;
				else if (l == 3)
					r='0,'+s;
			}
			else if(casas == 4)
			{
				if (l == 1)
					r='0,000'+s;
				else if (l == 2)
					r='0,00'+s;
				else if (l == 3)
					r='0,0'+s;
				else if(l == 4)
					r='0,'+s;
			}
			else if(casas == 5)
			{
				if (l == 1)
					r='0,0000'+s;
				else if (l == 3)
					r='0,00'+s;
				else if (l == 2)
					r='0,000'+s;
				else if(l == 4)
					r='0,0'+s;
				else if(l == 5)
					r='0,'+s;
			}

		};
		if (r == '')
		{
			r='0,';
			for (aa=0; aa < casas; aa++)
				r=r+"0";
		}
		else
		{
			l=r.length;
			if (l > casas+4)
			{
				j=l%3;
				w=r.substr(0,j);
				wa=r.substr(j,l-j-(casas+4));
				wb=r.substr(l-(casas+4),(casas+4));
				if (j > 0)
					w+='.';
				k=(l-j)/3-2;
				for (i=0; i < k; i++)
					w+=wa.substr(i*3,3)+'.';
				r=w+wb;
			};
		};
   };
   if (r.length <= len)
    cur.value=r;
   else
    cur.value=z;

	return true;
}


function FormatarParaMoeda(objcampo, casasDecimais)
{
	if(/MSIE/.test(navigator.userAgent))
	{
		objcampo.onkeyup 	= function onkeyup()	{ FormataNumeroMoeda(objcampo, event, 10, casasDecimais) };
		objcampo.onblur 	= function onblur()		{ FormataNumeroMoeda(objcampo, event, 10, casasDecimais) };
		objcampo.onkeydown 	= function onkeydown()	{ FormataNumeroMoeda(objcampo, event, 10, casasDecimais) };
	}
	else
	{
		objcampo.onkeyup 	= function onkeyup(event)	{ FormataNumeroMoeda(objcampo, event, 10, casasDecimais) }; 
		objcampo.onblur 	= function onblur(event)	{ FormataNumeroMoeda(objcampo, event, 10, casasDecimais) };
		objcampo.onkeydown 	= function onkeydown(event)	{ FormataNumeroMoeda(objcampo, event, 10, casasDecimais) };
	}
}

function FormataCampo(Campo, e, Tipo)
{
    var key 		= '';
    var strCheck 	= '0123456789';
    var aux 		= '';
    var whichCode 	= (e.keyCode) ? e.keyCode : e.which;

	//variaveis dos tipos de formatação
	var tamanhoTelefone = 10;
	var tamanhoCpf      = 11;
	var tamanhoCnpj     = 14;
	var tamanhoData     = 8;

    if (whichCode == 13 || whichCode == 8 || whichCode == 0 || whichCode == 9)
	{
        return true;  // Enter backspace ou FN qualquer um que não seja alfa numerico
	}

	key = String.fromCharCode(whichCode);

    if(strCheck.indexOf(key) == -1)
	{
        return false;  //NÃO E VALIDO
	}

	//excessão para tipo numero
	if(Tipo == 'Numero')
	{
		aux = Campo.value;
		return aux;
	}

	aux = RemoveFormatacao(Campo.value);

	if(aux.length >= parseInt(eval("tamanho" + Tipo)))
	{
		return false;    //impede de digitar um valor maior que o tipo definido
	}

	aux += key;

	Campo.value = eval(Tipo + "_Format('" + aux + "')");

    return false;
}

function findCep(baseurl)
{
	widthToFix 	= 0;

	if(!widthToFix)
	{
		widthToFix = $('#CodigoFilial').width() + 4;
	}

	$.ajax({
		type:   'POST',
		url:    baseurl+"combos.php?combo=CEP&cep=" + $('#Cep').val(),		
		global: false,

		success: function(msg)
		{
			content = msg.split('§');

			$('#Endereco').val(content[0]);
			$('#Bairro').val(content[1]);
			$('#CodigoFilial').val(content[3]).select;

			
			//LoadCities(content[2], content[3]);

			delete msg;
		}
	});
}

function LoadCities(baseurl, estado)
{
	$('#cidade').empty().append('<option value="0">Carregando...</option>');
	$('#cidade').width('104px').load(baseurl+"combos.php?combo=CIDADES&CodigoEstado=" + estado);
}

function LoadCidadeEstado(baseurl, estado)
{
	$('#Cidade').empty().append('<option value="0">Carregando...</option>');
	$('#Cidade').width('343px').load(baseurl+"combos.php?combo=CIDADESESTADOS&CodigoEstado=" + estado);
}
