$(document).ready(function() {

	$("#bannerPrehome").flash({ src: '/swf/prehome.swf', width: 250, height: 250, wmode: 'transparent', version: 8 });

	$("table.oddEven tr:even td").addClass('even');
	$("table.oddEven tr:odd td").addClass('odd');
	$("table#estPromocoes tr").each(function() { $(this).find('td:eq(1), th:eq(1)').addClass('data'); });
	$("table#estPromocoes tr th:eq(0)").css('text-align', 'left');

	$("#btnComunicar").click(function() {

		$txtNome = $("#txtNome");
		$txtEmail = $("#txtEmail");
		$txtDenuncia = $("#txtDenuncia");

		$inputStyle = "border: solid 1px #BABABA; width: 245px;";
		$inputStyleErro = "border: solid 1px #F00; width: 245px;";

		$resultado = true;

		if ($txtNome.val() == "") {
			$txtNome.attr("style", $inputStyleErro);
			$resultado = false;
		} else {
			$txtNome.attr("style", $inputStyle);
		}

		if ($txtEmail.val() == "") {
			$txtEmail.attr("style", $inputStyleErro);
			$resultado = false;
		} else {
			$txtEmail.attr("style", $inputStyle);
		}

		if ($txtDenuncia.val() == "") {
			$txtDenuncia.attr("style", "border: solid 1px #f00; width: 245px; height: 50px;")
			$resultado = false;
		} else {
			$txtDenuncia.attr("style", "border: solid 1px #BABABA; width: 245px; height: 50px;")
		}

		if ($resultado) {
			$("#hdnAcao").val("denunciar");

			$("#hdnAcao").val("denunciar");
			$("#hdnNome").val($txtNome.val());
			$("#hdnEmail").val($txtEmail.val());
			$("#hdnDenuncia").val($txtDenuncia.val());

			document.forms[0].submit();
		}

	});

	$("#lnkBaixarJPEG").click(function() {
		$("#hdnLarguraCartaz").val($("#divHtmlCartaz").width());
		$("#hdnAlturaCartaz").val($("#divHtmlCartaz").height());
	})

	$(".upper").keyup(function() {
		$val = $(this).val();
		$(this).val(replaceDiacritics($val.toUpperCase()));
	});

	$("table#estPesquisas tr").each(function() { $(this).find('td:last, th:last').addClass('last'); });

	$("a.addEndereco").live("click", function() {
		$number = $(".boxEnderecos .endereco:last").find("input").attr("id").split("[")[1].split("]")[0];
		$number++;
		$clone = $(".boxEnderecos .endereco:last").clone();
		$clone.attr({ id: "endereco" + $number });
		$($clone).find("input").val("");
		$(".boxEnderecos").append($clone);
		$(".boxEnderecos .endereco:last input").each(function() {
			$val = $(this).attr("id");
			$val = $val.replace(/([0-9]+)/gi, $number);
			$(this).attr({ id: $val, name: $val });
		});
		$("#hdnEnderecos").val($number);
		return false;
	});

	$("a.consultarEndereco").live("click", function() {
		$table = $(this).parent().parent().parent().parent();

		$cep_ini = $table.find(".cep_ini").val();
		$cep_end = $table.find(".cep_end").val();

		if ($cep_ini != null && $cep_ini != "" && $cep_end != null && $cep_end != "") {

			$cep = $cep_ini + $cep_end;

			$.ajax({
				type: "post",
				url: "/Site/ConsultaCepJSON.aspx",
				dataType: "json",
				data: "cep=" + $cep,
				success: function(json) {

					if (json.msg == 'error') {
						alert(json.errorMsg);
					} else {
						$count = 0;

						$($table).find("input").each(function() {

							$input = $(this);
							$id = $input.attr("id");							
							$key = $id.replace(/([\[\]0-9]+)/, "");	

							if (json[$key] != null) {
								$input.val(json[$key]);
								$count++;
							}
						});
					}

					//JSON Object
					//{
					//	"endereco":"ENDERECO",
					//	"numero":"NUMERO",
					//	"complemento":"COMPLEMENTO",
					//	"bairro":"BAIRRO",
					//	"cidade":"CIDADE",
					//	"estado":"ESTADO",
					//	"ddd":"DDD",
					//	"telefone":"TELEFONE"
					//}
				}
			});

		} else {
			alert("Informe o CEP!");
		}

		return false;
	});

	$("table#usuResultPromocoes tr:even").each(function() { $(this).find('td:eq(1)').addClass('descEven'); });
	$("table#usuResultPromocoes tr:odd").each(function() { $(this).find('td:eq(1)').addClass('descOdd'); });
	$("table#estEnderecos .item tr td:even").each(function() { $(this).addClass('tit'); });
	$("#faqContent h3:even").addClass('even');
	$("#faqContent h3:odd").addClass('odd');

	$("#faqContent h3").click(function() {
		$("#faqContent .accordion").slideUp();
		if ($(this).next().is(":visible")) {
			$(this).next().slideUp();
		} else {
			$(this).next().slideDown();
		}
	});

	$("#boxProdutos .bot a").toggle(function() {
		var el = $('#' + this.href.split('#')[1]);
		el.animate({ height: 258 }, { duration: 1000, easing: 'easeInOutExpo' });
		$(this).addClass("hover").blur();
		$("ul#prodDestaque").hide();
		$("ul#listaProdutos").show();
	}, function() {
		var el = $('#' + this.href.split('#')[1]);
		el.animate({ height: 42 }, { duration: 1000, easing: 'easeInOutExpo' });
		$(this).removeClass("hover").blur();
		$("ul#prodDestaque").show();
		$("ul#listaProdutos").hide();
	});

	$("a#lnkUnidadesParticipantes.usuarios").click(function() {
		tb_show('', '/Site/Usuarios/tbUnidadesParticipantes.aspx?keepThis=true&TB_iframe=true&width=520&height=420', false);
		return false;
	});

	$("a#lnkUnidadesParticipantes.empresas").click(function() {
		tb_show('', '/Site/Empresas/tbUnidadesParticipantes.aspx?keepThis=true&TB_iframe=true&width=520&height=420', false);
		return false;
	});

	$("a#lnkUnidadesParticipantes.estabelecimentos").click(function() {
		tb_show('', '/Site/Estabelecimentos/tbUnidadesParticipantes.aspx?keepThis=true&TB_iframe=true&width=520&height=420', false);
		return false;
	});

	$("#btnLocalizarCepUsuarios").click(function() {
		$("#hdnLocalizarCepUsuarios").val("True");
		window.document.forms["formIndiqueEstabelecimentoUsuarios"].submit();
	});

	$("#btnLocalizarCepEmpresas").click(function() {
		$("#hdnLocalizarCepEmpresas").val("True");
		window.document.forms["formIndiqueEstabelecimentoEmpresas"].submit();
	});

	$("#btnLocalizarCepEstabelecimentos").click(function() {
		$("#hdnLocalizarCepEstabelecimentos").val("True");
		window.document.forms["formIndiqueEstabelecimentos"].submit();
	});

	$("#btnFiltrarEnderecoEstabelecimentos").click(function() {
		$("#hdnFiltrarEnderecoEstabelecimentos").val("True");
		window.document.forms["formCadastroPromocaoEstabelecimentos"].submit();
	});

	$("#btnFiltrarEnderecoEmpresas").click(function() {
		$("#hdnFiltrarEnderecoEmpresas").val("True");
		window.document.forms["formCadastroPromocaoEmpresas"].submit();
	});

	$("input.autoTab").each(function(i) {
		var proximo = i + 1;
		$(this).keyup(function() {
			var me = $(this);
			var maxLen = me.attr("maxlength") || 5; //caso o campo não contenha este atributo
			if (me.val().length + 1 > maxLen) {
				var atuais = $("input.autoTab");
				var atual = atuais.eq(proximo); //só pra visualizar. Depois pó resumir
				atual.focus();
			}
		});
	});
	//$("table#estEnderecos, #aceitoContrato").cssCheckbox();
	$("table#estPesquisas tr, table#empPesquisas tr").each(function() { $(this).cssRadio(); });
	$("table#usuCadastro tr").each(function() { $(this).cssCheckbox(); });
	$("ul#prodDestaque").innerfade({ speed: 'fast', timeout: 3000, type: 'random' });


	$("input.cnpj1").mask("99999999999999");
	$(".png").ifixpng();
	$("input.cnpj").mask("99.999.999/9999-99");
	$("input.cpf").mask("999.999.999-99");
	$("input.data").mask("99/99/9999");
	// Validação de cpf:
	$('.cpf').blur(function() {
		var cpf = $(this).val();
		exp = /\.|\-/g
		cpf = cpf.toString().replace(exp, "");
		if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999") {
			$("#hdnCpfInvalido").val("true");
			return (false);
		}
		add = 0;

		for (i = 0; i < 9; i++) {
			add += parseInt(cpf.charAt(i)) * (10 - i);
		}
		rev = (11 - (add % 11));

		if (rev == 10 || rev == 11) {
			rev = 0;
		}

		if (rev != parseInt(cpf.charAt(9))) {
			$("#hdnCpfInvalido").val("true");
			return (false);
		}
		add = 0;

		for (i = 0; i < 10; i++) {
			add += parseInt(cpf.charAt(i)) * (11 - i);
		}
		rev = (11 - (add % 11));

		if (rev == 10 || rev == 11) {
			rev = 0;
		}

		if (rev != parseInt(cpf.charAt(10))) {
			$("#hdnCpfInvalido").val("true");
			return (false);
		}
		$("#hdnCpfInvalido").val("false");
		return (true);
	});
});

function showInlineThickbox(contentId, width, height) {
	if (contentId == null || contentId == "undefined") {
		alert("Informe o id que possui o content a ser exibido.");
		return;
	}

	if (width == null || width == "undefined")
		width = 383;

	if (height == null || height == "undefined")
		height = 280;

	tb_show('', '#TB_inline?modal=true&width=' + width + '&height=' + height + '&inlineId=' + contentId, false);
}

function termosLegais() {
	tb_show('', 'tbTermosLegais.aspx?keepThis=true&TB_iframe=true&width=350&height=180&modal=true', false);
}

function uploadLogo() {
	tb_show('', 'tbUploadLogo.aspx?keepThis=true&TB_iframe=true&width=450&height=250&modal=true', false);
}


/* EXEMPLO DE UTILIZAÇÃO:
No evento onkeyup adicionar - checkLen(this,this.value);
O campo precisa ter maxlength para haver o salto para o proximo campo
*/
function checkLen(x, y) {
	if (y.length == x.maxLength) {
		var next = x.tabIndex + 1;
		alert(next);
		if (next < document.forms['form1'].length) {
			document.forms['form1'].elements[next].focus()
		}
	}
}

function replaceDiacritics(s) {
	var s;

	var diacritics = [
		/[\300-\306]/g, /[\340-\346]/g, // A, a
		/[\310-\313]/g, /[\350-\353]/g, // E, e
		/[\314-\317]/g, /[\354-\357]/g, // I, i
		/[\322-\330]/g, /[\362-\370]/g, // O, o
		/[\331-\334]/g, /[\371-\374]/g,  // U, u
		/[\321]/g, /[\361]/g, // N, n
		/[\307]/g, /[\347]/g, // C, c
	];

	var chars = ['A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u', 'N', 'n', 'C', 'c'];

	for (var i = 0; i < diacritics.length; i++) {
		s = s.replace(diacritics[i], chars[i]);
	}
	return s;
}


/*
@author: remy sharp / http://remysharp.com
@params:
feedback - the selector for the element that gives the user feedback. Note that this will be relative to the form the plugin is run against.
hardLimit - whether to stop the user being able to keep adding characters. Defaults to true.
useInput - whether to look for a hidden input named 'maxlength' instead of the maxlength attribute. Defaults to false.
words - limit by characters or words, set this to true to limit by words. Defaults to false.
@license: Creative Commons License - ShareAlike http://creativecommons.org/licenses/by-sa/3.0/
@version: 1.2
@changes: code tidy via Ariel Flesler and fix when pasting over limit and including \t or \n
*/

(function($) {

	$.fn.maxlength = function(settings) {

		if (typeof settings == 'string') {
			settings = { feedback: settings };
		}

		settings = $.extend({}, $.fn.maxlength.defaults, settings);

		function length(el) {
			var parts = el.value;
			if (settings.words)
				parts = el.value.length ? parts.split(/\s+/) : { length: 0 };
			return parts.length;
		}

		return this.each(function() {
			var field = this,
        	$field = $(field),
        	$form = $(field.form),
			//limit = settings.useInput ? $form.find('input[name=maxlength]').val() : $field.attr('maxlength'),
        	limit = settings.useInput ? $form.find('input[name=maxlength]').val() : $field.metadata().maxlength,
        	$charsLeft = $form.find(settings.feedback);

			function limitCheck(event) {
				var len = length(this),
        	    exceeded = len >= limit,
        		code = event.keyCode;

				if (!exceeded)
					return;

				switch (code) {
					case 8:  // allow delete
					case 9:
					case 17:
					case 36: // and cursor keys
					case 35:
					case 37:
					case 38:
					case 39:
					case 40:
					case 46:
					case 65:
						return;

					default:
						return settings.words && code != 32 && code != 13 && len == limit;
				}
			}

			var updateCount = function() {
				var len = length(field),
            	diff = limit - len;

				$charsLeft.html(diff || "0");

				// truncation code
				if (settings.hardLimit && diff < 0) {
					field.value = settings.words ?
					// split by white space, capturing it in the result, then glue them back
            		field.value.split(/(\s+)/, (limit * 2) - 1).join('') :
            		field.value.substr(0, limit);

					updateCount();
				}
			};

			$field.keyup(updateCount).change(updateCount);
			if (settings.hardLimit) {
				$field.keydown(limitCheck);
			}

			updateCount();
		});
	};

	$.fn.maxlength.defaults = {
		useInput: false,
		hardLimit: true,
		feedback: '.charsLeft',
		words: false
	};

})(jQuery);
