/* Desenvolvido por Guilherme Augusto Madaleno - zatec@ymail.com */
	/* Variáveis */
	
	var bigZCounter = 0;
	var callBack;
	var menuHover = "";
	var message = "";
	var milisec = 0;
	var seconds = 60;
	var searchQuery;
	var timer;
	var message = "";
	var warning = "";
	
	/* Solicitações de boletos */
	
	$.billingRequest = function ()
	{
		var d = prompt("Por favor, digite o código HASH informado no cabeçalho de seu boleto:");
		if (d)
			document.location = 'http://www.zatecus.com/billingrq=' + d;	
		else
			alert("É preciso informar o código HASH para solicitar uma segunda via!");	
	};
	
	/* Abre um Cookie específico */
	
	$.openCookie = function (cookie_name)
	{
		var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)');
		if (results)
			return results[2];
		else
			return null;
	};
	
	/* Função para abrir cliente em janela externa */
	
	$.openExternal = function(url) 
	{
		url = url.replace("http://", "");
		var rand = Math.floor(Math.random()*9999);
		var external = window.open('http://www.zatecus.com/external=' + url, 'zatecusWindow' + rand);
		return false;
	};
	
	/* Função para detectar o problemático Internet Explorer */
	
	$.isNotIETrash = function ()
	{
		var rv = -1;
		if (navigator.appName == 'Microsoft Internet Explorer')
		{
			var ua = navigator.userAgent;
			var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
			if (re.exec(ua) != null) rv = parseFloat( RegExp.$1 );
		}
		if (rv == -1) return true;
	};
	
	/* Função para exibição de mensagens de alerta */
	
	$.message = function(msgText, callBackFn, msgSound)
	{
		var audioFile = (msgSound) ? "http://www.zatecus.com/sounds//msg.ogg" : "http://www.zatecus.com/sounds//error.ogg";
		if ($.isNotIETrash())
		{
			var audioElement = document.createElement('audio');
			audioElement.setAttribute('src', audioFile);				
			audioElement.play();	
		}
		$('body #msg #text').html(msgText);
		callBack = (callBackFn) ? callBackFn : false;
		$.blockUI
		({ 
			message: $('#msg'), 
			fadeIn: 100,
			overlayCSS:
			{ 
				backgroundColor: '#ffffff',
				opacity: 0.9,
				cursor: 'default'
			}, 
			css: 
			{ 
				border: 'none',
				margin: 0,
				padding: 0,
				backgroundColor: '#ffffff'
			}
		});
	};
	
	/* Para fechar mensagens */
	
	$.messageClose = function (callBack)
	{
		$.unblockUI();
		if (callBack)
		{
			if (typeof callBack == 'function')
			{
				callBack.call(this);
			}
			callBack = "";
		}
	};
	
	/* Exibe balão de mensagens para ratings */

	$.balloon = function (text)
	{
		$('div#balloon div').html(text);
		$('div#balloon').fadeIn(200);
		timer = setInterval(function()
		{
			$('div#balloon').fadeOut(200);
			clearTimeout(timer);
		}, 5000);
	};
	
	/* Recolhe o endereço de IP */
	
	$.searchShortcuts = function (callBackFn)
	{
		searchQuery = $('input#search').val();
		if (searchQuery)
		{
			searchQuery = searchQuery.toLowerCase();
			switch (searchQuery)
			{
				default:
					document.location = 'http://www.zatecus.com/search=' + searchQuery;
				break;
				case 'boleto':
				case 'boletos':
				case 'segunda via':
					var c = confirm ("Deseja solicitar uma segunda via de seu boleto?");
					if (c)
						$.billingRequest();
					else
						document.location = 'http://www.zatecus.com/search=' + searchQuery;
				break;
				case 'ip':
				case 'IP':
					var c = confirm ("Deseja saber seu IP?");
					if (c)
					{
						$.ajax
						({
							type: "POST",
							url: "http://www.zatecus.com/ip.json",
							data: '',
							dataType: "json",
							error: function (XMLHttpRequest, textStatus, errorThrown)
							{
								alert("Ops! Não consegui pegar seu IP! =(");
							},
							success: function (callBack)
							{
								if (callBack)
								{
									if (callBack.msg == 'limit_reached')
									{
										$.message('Desculpe, mas voc&ecirc; n&atilde;o pode mais fazer isso!');
									}
									else
									{
										$.message('Seu endere&ccedil;o de IP:<br /><br /><input type="text" class="fields" style="width: 120px;" value="' + callBack.ip + '" />', false, true);
									}
								}
								else
								{
									$.message('Ocorreu um erro ao pegar seu IP!');
									$("input#search").attr('value', '');
									$("input#search").select();
								}
							}
						});
					}
					else
					{
						document.location = 'http://www.zatecus.com/search=' + searchQuery;	
					}
				break;
			}
		}
		else
		{
			$(this).focus();	
		}
	};
	
	/* Faz um simples countdown */
	
	$.countDown = function ()
	{
		if (milisec<=0)
		{ 
			milisec=9;
			seconds-=1; 
		} 
		if (seconds<=-1)
		{ 
			milisec=0;
			seconds+=1; 
		} 
		else 
			milisec-=1;
		$('span#countDown').html(seconds + "." + milisec);
		setTimeout("$.countDown();",100);
	};
	
	/* Função para remover acentos (by Álister) */
	
	$.removeAccents = function (strAccents)
	{
		strAccents = strAccents.split('');
		strAccentsOut = new Array();
		strAccentsLen = strAccents.length;
		var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž!?@#$%¨&*()+={}[]^~<>:;\'"\\/`´|,.';
		var accentsOut = ['A','A','A','A','A','A','a','a','a','a','a','a','O','O','O','O','O','O','O','o','o','o','o','o','o','E','E','E','E','e','e','e','e','e','C','c','D','I','I','I','I','i','i','i','i','U','U','U','U','u','u','u','u','N','n','S','s','Y','y','y','Z','z','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''];
		for (var y = 0; y < strAccentsLen; y++) 
		{
			if (accents.indexOf(strAccents[y]) != -1) 
			{
				strAccentsOut[y] = accentsOut[accents.indexOf(strAccents[y])];
			}
			else
				strAccentsOut[y] = strAccents[y];
		}
		strAccentsOut = strAccentsOut.join('');
		return strAccentsOut;
	};
	
	/* Função de BBCode (by eu mesmo) */
	
	$.miniBB = function (id, bblink)
	{
		var BBCodes = 
		{
			b: 			'[b]%[/b]',
			i: 			'[i]%[/i]',
			u: 			'[u]%[/u]',
			p: 			'[p]%[/p]',
			h1: 		'[h1]%[/h1]',
			h2: 		'[h2]%[/h2]',
			h3: 		'[h3]%[/h3]',
			h4: 		'[h4]%[/h4]',
			h5: 		'[h5]%[/h5]',
			h6: 		'[h6]%[/h6]',
			js: 		'[js]%[/js]',
			html: 		'[html]%[/html]',
			php: 		'[php]%[/php]',
			xml: 		'[xml]%[/xml]',
			css: 		'[css]%[/css]',
			url: 		'[url=@]%[/url]',
			img: 		'[img=@]',
			youtube: 	'[youtube=@]',
			vimeo: 		'[vimeo=@]',
			flash: 		'[flash=@]',
			hr:			'[hr]',
			br:			'[br]'
		};
		var BBType, textarea, selected, ie_selected, replaced, value = '';
		id = id.replace('#');
		$(bblink).click(function()
		{	
			BBType = this.href.split('#').pop();
			if (BBCodes[BBType])
			{
				textarea = document.getElementById(id.split('#').pop());
				if (document.selection)
				{
					ie_selected = document.selection.createRange();
					selected = ie_selected.text;
				}
				else
				{
					selected = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
				}
				switch (BBType)
				{
					default:
						replaced = BBCodes[BBType].replace('%', selected);
					break;
					case 'url':
						value = prompt ("Digite a URL para o link:", "http://");
						if (!value) value = '';
						replaced = BBCodes[BBType].replace('@', value);
						replaced = replaced.replace('%', selected);
					break;
					case 'br':
					case 'hr':
						replaced = selected + BBCodes[BBType];
					break;
					case 'img':
						value = prompt ("Digite a URL para a imagem:", "http://");
						if (!value) value = '';
						replaced = selected + BBCodes[BBType].replace('@', value);
					break;
					case 'youtube':
					case 'vimeo':
					case 'flash':
						value = prompt ("Digite a URL:", "http://");
						if (!value) value = '';
						replaced = selected + BBCodes[BBType].replace('@', value);
					break;
				}
				if (document.selection)
				{
					if (ie_selected.text)
						ie_selected.text = replaced;
					else
						textarea.value = textarea.value + replaced;
				}
				else
				{
					textarea.value = textarea.value.substring(0, textarea.selectionStart) + replaced + textarea.value.substring(textarea.selectionEnd, textarea.value.length);					
				}		
			}
			textarea.focus();
			return false;
		});
	};

	$(document).ready(function() 
	{
	
		/* Otimização para SEO (você está sendo logado, mané!) */
	
		if ($('p#kwd').html())
		{
			$('p#kwd').html('');
		}
		
		/* Exibe mensagens */
		
		if (warning && !message)
		{
			if ($.openCookie ('ztUser_warning') != 'done')
			{
				$.message(warning, false, true);
				document.cookie = 'ztUser_warning=done; expires=Tue, 07 Feb 12 18:23:01 -0200;';
			}
		}
		else if (message && !warning)
		{
			$.message(message, false, true);
		}
		else if (message && warning)
		{
			if ($.openCookie ('ztUser_warning') != 'done')
			{
				$.message(message, function()
				{
					$.message(warning, false, true);
					document.cookie = 'ztUser_warning=done; expires=Tue, 07 Feb 12 18:23:01 -0200;';
				}, true);
			}
			else
			{
				$.message(message, false, true);
			}
		}
		
		/* Ações para caixa de buscas */
		
		$("input#search").focus(function()
		{
			if($(this).val() == 'Pesquisar por...')
				$(this).attr('value', '');
			$(this).css('color', '#666');
		});
		
		$("input#search").blur(function()
		{
			if($(this).val() == '')
				$(this).attr('value', 'Pesquisar por...');
			$(this).css('color', '#DDD');
		});

		/* Funções para botão de busca */
	
		$("input#searchStart").click(function()
		{  
			searchQuery = $("input#search").val();
			if (searchQuery && searchQuery != 'Pesquisar por...')
				$.searchShortcuts(function()
				{
					if (this)
						prompt("Seu endereço de IP:", this.value);
					else
						alert("Ops! Não consegui pegar seu IP! =(edd");
					$("input#search").attr('value', '');
					$("input#search").select();
				});
			else
				$(this).focus();
		});
		
		/* Funções para início de busca ao pressionar tecla ENTER*/
		
		$("input#search").keypress(function(e) 
		{
			if(e.keyCode == 13) 
			{
				searchQuery = $(this).val();
				if (searchQuery && searchQuery != 'Pesquisar por...')
				{
					$.searchShortcuts(function()
					{
						if (this)
						{
							prompt("Seu endereço IP:", this.value);
						}
						else
							alert("Ops! Não consegui pegar seu IP! =(edd");
						$("input#search").attr('value', '');
						$("input#search").select();
					});
					$(this).attr('value', '');
				}
				else
					$(this).focus();
			}
		});

		/* Tooltip */
	
		$("a[rel='tooltip']").tooltip
		({  
			track: true, 
			delay: 200, 
			showURL: false, 
			fade: 100 
		});
		
		/* Tooltip para imagens */
		
		$("a#tooltip2").tooltip
		({  
			delay: 1000, 
			showURL: false, 
			bodyHandler: function() 
			{ 
				return $("<img/>").attr("src", $(this).attr('rel')); 
			} 
		});
		
		/* Ações quando o mouse passar por cima de algum "zatecus" */
		
		if ($.isNotIETrash())
		{
			$("span#zAction, li#logo img").hover(function()
			{
				$(this).css('opacity', 0.5);
				$("div#bigz").css('opacity', 0.4);
			}, function ()
			{
				$(this).css('opacity', 1);
				$("div#bigz").animate
				({
					opacity: 0.3
				}, 200);
			});	
		}
		else
		{
			$("div#bigz").hide();
		}
				
		/* Instruções para o BIGZ */
		
		if ($.isNotIETrash())
		{
			if ($.openCookie ('ztUser_bigz') != 'over')
			{
				$("div#bigz").hover(function ()
				{
					if (bigZCounter == 20)
					{
						$.message("Rá! Acabou a brincadeira com o Z...", function ()
						{
							$("div#bigz").fadeOut(500);
							document.cookie = 'ztUser_bigz=over; expires=Tue, 07 Feb 12 18:23:01 -0200;';
						}, true);
					}
					else
					{
						bigZCounter = bigZCounter + 1;	
					}
					
					$(this).animate
					({
						left: '+=40',
						opacity: 1
					}, 200);
				},
				function () 
				{
					$(this).animate
					({
						left: '-220',
						opacity: 0.3
					}, 200);
				});
			}
			else
			{
				$("div#bigz").hide();
			}
		}
		else
		{
			$("div#bigz").css('opacity', 1);
		}
		
		
		/* Para redirecionar quando clicado no BIGZ */
		
		if ($.isNotIETrash())
		{
			$("div#bigz").click(function ()
			{
				$(this).animate
				({
					left: '-120'
				}, 100, function()
				{
					document.location = "http://www.zatecus.com/index.html";
				});
			});
		}
		
		/* Para fechar blockUIs */
		
		$('a#billingInputOpen').click(function() 
		{ 
			$.billingInput();
		});
		
		/* Para verificar se boleto existe */
		
		$('a#billingView').click(function() 
		{ 
			$.billingInput(true);
		}); 
		
		/* Ações para menu principal */
		
		if ($.isNotIETrash())
		{
			$('div#menu li').hover(function()
			{
				if ($(this).attr('class') != 'active')
				{
					$(this).children().children().animate
					({
						width: 'toggle'
					}, 100);	
					$(this).children().children().css('backgroundImage', $(this).css('backgroundImage').replace('off', 'on'));
				}
			},function()
			{
				if ($(this).attr('class') != 'active')
				{
					$(this).children().children().animate
					({
						width: 'toggle'
					}, 300);	
				}
			});	
		}
		else
		{
			$('div#menu li').hover(function()
			{
				if ($(this).attr('class') != 'active')
				{
					$(this).children().children().show();
					$(this).children().children().css('backgroundImage', $(this).css('backgroundImage').replace('off', 'on'));
				}
			},function()
			{
				if ($(this).attr('class') != 'active')
				{
					$(this).children().children().hide();	
				}
			});	
		}
		
		
		/* Para fechar blockUIs */
		
		$('#close').click(function() 
		{ 
			$.messageClose(callBack);
			return false; 
		}); 
		
		/* Para fechar balões */
		
		$('#balloon').click(function() 
		{ 
			$(this).fadeOut(100);
			clearTimeout(timer);
		}); 
		
		/* Abre um site externo em janela */
		
		$('a[rel=external]').click(function() 
		{ 
			$.openExternal(this.href);
			return false;
		});
		
		/* Carrega elementos do cookie em formulários */

		if ($.isNotIETrash())
		{
			$('#logo img, #rss img').hover(function() 
			{ 
				$(this).css('opacity', 0.2);
				$(this).animate
				({
					opacity: 0.7
				}, 100);
			}, function()
			{
				$(this).animate
				({
					opacity: 1
				}, 100);
			}); 
		}
		
		/* Monta listas de páginas */
		
		if ($('span#pageList a').size())
		{
			var pageSelected = "";
			$('span#pageList a').each(function()
			{
				pageSelected = (currentPage == $(this).html()) ? 'selected="selected"' : '';
				$('div#pageSelect select').append('<option ' + pageSelected + ' value="' + $(this).attr('href') + '">' + $(this).html() + '</option>');
			});
		}
		
	});
	
