// JavaScript Document
/**
 * 
 * @param s
 * @return
 */
function encode_utf8( s )
{
  return unescape( encodeURIComponent( s ) );
}

/**
 * 
 * @return
 */
function exibe_acao()
{
	$.ajax({
		url: "ajax.php",
		type: 'post',
		cache: false,
		dataType: 'json',		
		data: {acao: 'exibe_acao'},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			alert(textStatus);
		},
		success: function(retorno)
		{
			
		}
	});	
}

/**
 * 
 * @param id
 * @return
 */
function desabilita_botao(id)
{
	$("#"+id).attr('Disabled', 'Disabled');
}

/**
 * 
 * @param id
 * @return
 */
function habilita_botao(id)
{
	$("#"+id).attr('Disabled', '');
}

/**
 * 
 * @param cep
 * @return
 */
function busca_cep(cep)
{
	if (cep != '')
	{
		var modelo = new RegExp(/\d{8}/);
		if(modelo.test(cep)==false)
		{
			alert('o cep digitado é inválido!');
		}
		else
		{	
			exibe_dialog_erro("Busca CEP", "Buscando, aguarde...", "OK", "fecha_dialog_erro()");
			$.ajax({
				url: "ajax.php",
				type: 'post',
				cache: false,
				dataType: 'json',		
				data: {acao: 'busca_cep', cep: cep},
				error: function(XMLHttpRequest, textStatus, errorThrown)
				{
					//alert(textStatus);
				},
				success: function(retorno)
				{
					$("#endereco").val(decode(retorno.endereco));
					$("#bairro").val(decode(retorno.bairro));
					$("#id_estado").val(retorno.id_estado);
					atualiza_cidades(retorno.id_estado, retorno.id_cidade);
				}
			});	
		}
	}
}

/**
 * 
 * @param modo
 * @return
 */
function exibe_aguarde(modo)
{
	$("#div_aguarde").dialog('destroy');
	$("#div_aguarde").dialog({ 
		modal: true,
		resizable: true,
		height: 200,
		width: 370
	});	
	$("#div_aguarde").dialog( 'option', 'position', 'center');
}

/**
 * 
 * @return
 */
function fecha_aguarde()
{
	$("#div_aguarde").dialog('close');
	$("#div_aguarde").dialog('destroy');
}

/**
 * 
 * @return
 */
function fecha_dialog()
{
	$("#div_dialog").dialog('close');
	$("#div_dialog").dialog('destroy');
}

/**
 * 
 * @return
 */
function fecha_dialog_erro()
{
	$("#div_dialog_erro").dialog('close');
	$("#div_dialog_erro").dialog('destroy');
}

function avancar(campo)
{
	$("#"+campo).focus();
}

function decode(str) {
     return unescape(str.replace(/\+/g, " "));
}

function atualiza_cidades(id_estado, id_cidade)
{
	$.ajax({
		url: "ajax.php",
		type: 'post',
		cache: false,
		dataType: 'html',		
		data: {acao: 'atualiza_cidades', id_estado: id_estado, id_cidade: id_cidade},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			//alert(textStatus);
		},
		success: function(retorno)
		{
			$("#td_cidades").html(decode(retorno));
			fecha_dialog_erro();
		}
	});	
}

function valida_pais(value)
{
	if(value == 'BR')
	{
		$("#id_estado_filtro").css('display', '');
		$("#id_cidade_filtro").css('display', '');
		$("#estado_filtro").css('display', 'none');
		$("#cidade_filtro").css('display', 'none');
	}else{
		$("#id_estado_filtro").css('display', 'none');
		$("#id_cidade_filtro").css('display', 'none');
		$("#estado_filtro").css('display', '');
		$("#cidade_filtro").css('display', '');
	}
}

function valida_pais_evento(value)
{
	if(value == 'BR')
	{
		$("#id_estado").css('display', '');
		$("#id_cidade").css('display', '');
		$("#estado").css('display', 'none');
		$("#cidade").css('display', 'none');
	}else{
		$("#id_estado").css('display', 'none');
		$("#id_cidade").css('display', 'none');
		$("#estado").css('display', '');
		$("#cidade").css('display', '');
	}
}

/**
 * 
 * @return
 */
function verifica_input()
{
	if($("#pais_filtro").val() == 'BR'){
		estado = $("#id_estado_filtro").val();
		cidade = $("#id_cidade_filtro").val();
	}else{
		estado = $("#estado_filtro").val();
		cidade = $("#cidade_filtro").val();
	}	
}

/**
 * 
 * @param campo
 * @return
 */
function valida_docs(campo)
{
	valida_data_nascimento();
	
	$.ajax({
		url: "ajax.php",
		type: 'post',
		cache: false,
		dataType: 'json',		
		data: {
			acao: 'valida_docs', 
			tipo_doc: $("input[name='tipo_doc'][checked!='']").val(), 
			pais: $("#pais_origem").val(), 
			data_nascimento:$("#data_nascimento").val() 
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			alert(textStatus);
		},
		success: function(retorno)
		{
			if(retorno.erro == 'OK')
			{
				if(retorno.msg != '')
				{
					alert(decode(retorno.msg));
					return;
				}
			}
			else
			{
				eval(campo+'_salvar()');	
			}
		}
	});
}

/**
 * 
 * @return
 */
function valida_data_nascimento()
{
	var data_nascimento = $("#dia_nasc").val() + '/' + $("#mes_nasc").val() + '/' + $("#ano_nasc").val();
	$("#data_nascimento").val(data_nascimento);
}

/**
 * 
 * @param acao_site
 * @return
 */
function redirecionar(acao_site)
{
	var url = "index.php?acao_site=" + acao_site;
	window.location = url;
}

/**
 * 
 * @param url
 */
function redirect(url)
{
	window.location = url;
}

/**
 * 
 * @param e
 * @returns
 */
function tecla(e){
	return unicode=e.keyCode? e.keyCode : e.charCode;
}

function proximoCampo(id_campo, id_proximo_campo){
	var campo = document.getElementById(id_campo);
	var proximo_campo = document.getElementById(id_proximo_campo);
	//alert("id_campo: " + id_campo);
	if(campo.type=='text'){
		var maximo=campo.getAttribute('maxlength');
		var tam_string=campo.value.length;	
		if(tam_string==maximo){
			proximo_campo.focus();
		}	
	}
}

/**
 * 
 * @param num
 * @return
 */
function formata_moeda(num) 
{
	if (num)
	{
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10)
		cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'+
		num.substring(num.length-(4*i+3));
		return (((sign)?'':'-') + '' + num + ',' + cents);
	}
	else
	{
		return '0,00';
	}
}

/**
 * 
 * @param num
 * @return
 */
function formata_numero(num) 
{
	if (num)
	{
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10)
		cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'+
		num.substring(num.length-(4*i+3));
		return (((sign)?'':'-') + '' + num);
	}
	else
	{
		return '0';
	}
}

/**
 * 
 * @param titulo
 * @param msg
 * @param funcao_ok
 * @param funcao_close
 * @return
 */
function exibe_dialog(titulo, msg, funcao_ok, funcao_close, w, h)
{
	$("#div_dialog").dialog('destroy');
	$("#div_dialog").html(decode(msg));
	$("#div_dialog").dialog({
		autoOpen: false,
		modal: true,
		title: titulo,
		resizable: true,
		buttons: {
			"OK": function() {
				if (funcao_ok)
				{
					$("#div_dialog").dialog('destroy');
					eval(funcao_ok);
				}
				else
				{
					$("#div_dialog").dialog('destroy');
				}
			}
		},
		close: function(event, ui) 
		{ 
			if (funcao_close)
			{
				$("#div_dialog").dialog('destroy');
				eval(funcao_close);
			}
		}
	});
	if (w)
	{
		$("#div_dialog").dialog( 'option', 'width', w);
	}
	if (h)
	{
		$("#div_dialog").dialog( 'option', 'height', h);
	}
	$("#div_dialog").dialog( 'option', 'position', 'center');
	$("#div_dialog").dialog('open'); 
}

/**
 * 
 * @param titulo
 * @param msg
 * @param funcao_ok
 * @param funcao_close
 * @return
 */
function exibe_dialog2(titulo, msg, botao1, funcao1, botao2, funcao2, w, h)
{
	var dialog_buttons = {};
	dialog_buttons[botao1] = function()
	{ 
		if (funcao1)
		{
			//$("#div_dialog").dialog('destroy');
			eval(funcao1);
		}
		else
		{
			$("#div_dialog").dialog('destroy');
		};
	};
	if (botao2)
	{
		dialog_buttons[botao2] = function(){ 
			if (funcao2)
			{
				$("#div_dialog").dialog('destroy');
				eval(funcao2);
			}
			else
			{
				$("#div_dialog").dialog('destroy');
			};
		};
	}
	 	
	$("#div_dialog").dialog('destroy');
	$("#div_dialog").html(decode(msg));
	$("#div_dialog").dialog({
		autoOpen: false,
		modal: true,
		title: titulo,
		resizable: true,
		buttons: dialog_buttons,
		closeOnEscape: false,
		close: function(event, ui) 
		{ 
			$("#div_dialog").dialog('destroy');
		}
	});
	if (w)
	{
		$("#div_dialog").dialog( 'option', 'width', w);
	}
	if (h)
	{
		$("#div_dialog").dialog( 'option', 'height', h);
	}
	
	$("#div_dialog").dialog('option', 'position', 'center');
	$("#div_dialog").dialog('open'); 
}

/**
 * 
 * @param titulo
 * @param msg
 * @param funcao_ok
 * @param funcao_close
 * @return
 */
function exibe_dialog_kit_delivery(titulo, msg, botao1, funcao1, botao2, funcao2, w, h)
{
	var dialog_buttons = {};
	dialog_buttons[botao1] = function(){ 
		if (funcao1)
		{
			//$("#div_dialog").dialog('destroy');
			eval(funcao1);
		}
		else
		{
			$("#div_dialog").dialog('destroy');
		};
	};
	if (botao2)
	{
		dialog_buttons[botao2] = function(){ 
			if (funcao2)
			{
				$("#div_dialog").dialog('destroy');
				eval(funcao2);
			}
			else
			{
				$("#div_dialog").dialog('destroy');
			};
		};
	}
	 	
	$("#div_dialog").dialog('destroy');
	$("#div_dialog").html(decode(msg));
	$("#div_dialog").dialog({
		autoOpen: false,
		modal: true,
		title: titulo,
		resizable: true,
		buttons: dialog_buttons,
		closeOnEscape: false,
		close: function(event, ui) 
		{ 
			$("#div_dialog").dialog('destroy');
			if (funcao2)
			{
				eval(funcao2);
			}
		}
	});
	if (w)
	{
		$("#div_dialog").dialog( 'option', 'width', w);
	}
	if (h)
	{
		$("#div_dialog").dialog( 'option', 'height', h);
	}
	
	// css
	var titulo = $(".ui-widget-header");
	titulo.css("background-image", "none");
	titulo.css("background-color", "#EE7F00");
	titulo.css("background-image", "url(imagens/kit_delivery_dialog_titulo.png)");
	titulo.css("background-repeat", "no-repeat");
	titulo.css("border", "0px");
	titulo.css("height", "30px");
	
	$("#div_dialog").dialog('option', 'position', 'center');
	$("#div_dialog").dialog('open'); 
}

/**
 * 
 * @param titulo
 * @param msg
 * @param funcao_ok
 * @param funcao_close
 * @return
 */
function exibe_dialog_erro(titulo, msg, botao1, funcao1, botao2, funcao2, w, h)
{
	var dialog_buttons = {};
	dialog_buttons[botao1] = function(){ 
		if (funcao1)
		{
			//$("#div_dialog_erro").dialog('destroy');
			eval(funcao1);
		}
		else
		{
			$("#div_dialog_erro").dialog('destroy');
		};
	};
	if (botao2)
	{
		dialog_buttons[botao2] = function(){ 
			if (funcao2)
			{
				$("#div_dialog_erro").dialog('destroy');
				eval(funcao2);
			}
			else
			{
				$("#div_dialog_erro").dialog('destroy');
			};
		};
	}
	 	
	$("#div_dialog_erro").dialog('destroy');
	$("#div_dialog_erro").html(decode(msg));
	$("#div_dialog_erro").dialog({
		autoOpen: false,
		modal: true,
		title: titulo,
		resizable: true,
		buttons: dialog_buttons,
		closeOnEscape: false,
		close: function(event, ui) 
		{ 
			$("#div_dialog_erro").dialog('destroy');
		}
	});
	if (w)
	{
		$("#div_dialog_erro").dialog( 'option', 'width', w);
	}
	if (h)
	{
		$("#div_dialog_erro").dialog( 'option', 'height', h);
	}
	$("#div_dialog_erro").dialog('option', 'position', 'center');
	$("#div_dialog_erro").dialog('open'); 
}

/**
 * 
 * @param titulo
 * @param msg
 * @param funcao_ok
 * @param funcao_close
 * @return
 */
function exibe_dialog_erro_kit_delivery(titulo, msg, botao1, funcao1, botao2, funcao2, w, h)
{
	var dialog_buttons = {};
	dialog_buttons[botao1] = function(){ 
		if (funcao1)
		{
			//$("#div_dialog_erro").dialog('destroy');
			eval(funcao1);
		}
		else
		{
			$("#div_dialog_erro").dialog('destroy');
		};
	};
	if (botao2)
	{
		dialog_buttons[botao2] = function(){ 
			if (funcao2)
			{
				$("#div_dialog_erro").dialog('destroy');
				eval(funcao2);
			}
			else
			{
				$("#div_dialog_erro").dialog('destroy');
			};
		};
	}
	 	
	$("#div_dialog_erro").dialog('destroy');
	$("#div_dialog_erro").html(decode(msg));
	$("#div_dialog_erro").dialog({
		autoOpen: false,
		modal: true,
		title: titulo,
		resizable: true,
		buttons: dialog_buttons,
		closeOnEscape: false,
		close: function(event, ui) 
		{ 
			$("#div_dialog_erro").dialog('destroy');
		}
	});
	if (w)
	{
		$("#div_dialog_erro").dialog( 'option', 'width', w);
	}
	if (h)
	{
		$("#div_dialog_erro").dialog( 'option', 'height', h);
	}
	
	// css
	var titulo = $(".ui-widget-header");
	titulo.css("background-image", "none");
	titulo.css("background-color", "#EE7F00");
	titulo.css("background-image", "url(imagens/kit_delivery_dialog_titulo.png)");
	titulo.css("background-repeat", "no-repeat");
	titulo.css("border", "0px");
	titulo.css("height", "30px");
	
	$("#div_dialog_erro").dialog('option', 'position', 'center');
	$("#div_dialog_erro").dialog('open'); 
}

/**
 * 
 * @param cpf
 * @return
 */
function valida_cpf(cpf) 
{	
	if (cpf == '')
	{
		return true;
	}
 	erro = new String;
	if (cpf.length < 11) erro += "São necessários 11 digitos para verificação do CPF! \n\n"; 
	var nonNumbers = /\D/;
	if (nonNumbers.test(cpf)) erro += "A verificação de CPF suporta apenas numeros! \n\n"; 
	if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
			 erro += "Número de CPF inválido!";
   	}
   	var a = [];
   	var b = new Number;
   	var c = 11;
   	for (i=0; i<11; i++){
		   a[i] = cpf.charAt(i);
		   if (i < 9) b += (a[i] * --c);
   	}
   	if ((x = b % 11) < 2) { a[9] = 0; } else { a[9] = 11-x; }
   	b = 0;
   	c = 11;
   	for (y=0; y<10; y++) b += (a[y] * c--); 
   	if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
   	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
		   erro +="Digito verificador do CPF incorreto";
   	}
   	if (erro.length > 0){
		//alert(erro);
		  return false;
   }
   return true;
}

/**
 * 
 * @param data
 * @return
 */
function valida_data(data) 
{   
	//Parameters are calendar Year,Month,Day
	var moFlag = 0;
	var dyFlag = 0;
	var arDate = data.split('/');
	var dy = arDate[0];
	var mo = arDate[1];
	var yr = arDate[2];
	var date = data;
	var nDate = new Date();  // current date (local)
	var nowTime = nDate.getTime();  // current time (UTC)
	var thenTime = Date.UTC(yr, mo-1, dy);  // specified time (UTC)
	var thisYear = nDate.getFullYear();
	var thisMonth = nDate.getMonth();
	var thisDay = nDate.getDate();
	if (date.length == 0) 
	{
		return;
	}
	if (date.length < 10)
	{
		return false;
	}
	if (dy<1 || dy>31)
	{
		return false;
	} 
	else
	{
		dyFlag=1;
	}
	if (dy>30 && (mo == 2 || mo==4 || mo==6 || mo==9 || mo==11)) 
	{
		return false;
	} 
	else 
	{
		dyFlag=1;
	}
	if (dy>29 && mo==2) 
	{
		return false;
	} 
	else 
	{
		dyFlag=1;
	}
	if ((mo == 2 && dy == 29)  && ((yr%4 != 0) || (yr%100 == 0 && yr%400 != 0))) 
	{
		return false;
	} 
	else 
	{
		dyFlag=1;
	}
	if (mo<1 || mo>12) 
	{
		return false;
	}
	else 
	{
		return true;
	}
}	
