/*Funções principais para o site da Mundo Estranho 2008/2009 */


function clearSearch(query) {
	var clKeys = new Array("a","e","é","o","as","os","de","do","da","dos","das","nos","nas","que","qual","quais","quem","com","como","se","pode","são","uma","umas","feito","fazer","fazendo","faz","ate","apos","desde","para","em","por","entre","sobre","sob","dele","deles","dela","delas","vai","vao","vão","um","uma","uns","umas");
	var clPont = new Array("?",",",".","!");
	query = query.toLowerCase();
	for (var k=0;k<clPont.length;k++) {
		query = eval('query.replace(/\\'+clPont[k]+'/g, "")');
	}
	
	var clVar = query.split(" ");
	
	var cleared = "";
	for(var i=0;i<clVar.length;i++) {
		KeyCut = false;
		for(var j=0;j<clKeys.length;j++) {
			if (clVar[i] == clKeys[j]) { KeyCut = true; };
		}
		if (KeyCut != true) { cleared += clVar[i] + " " };
	}
	return cleared;
}

var hits = 8;
function fontSize(action, container){
	container = typeof(container) != 'undefined' ? container : '#pergunta'; 
	var hitIncrease = 0;
	var hitDecrease = 0;
	
	var pegaTodos = {pega : function(maiorDeTodos){
		var filho;
		
		$(maiorDeTodos).children().each(function(i){
			filho = $(this);
			
			$fs = parseInt($(filho).css('font-size'));
			if (action == 'plus' && hits > 0) { 
				$fs += 1;
				hitDecrease = 1;
			} else if (action == 'minus' && hits < 8) {
				$fs -= 1;
				hitIncrease = 1;
			}
			$(filho).css('font-size', $fs);
			
			if ($(filho).children().length != 0) {
				pegaTodos.pega($(filho));
			}
		});
	}};

	pegaTodos.pega($(container));
	if (hitIncrease == 1)hits+=1;
	else if (hitDecrease == 1)hits-=1;
}


$(document).ready(function(){
	// onHide : fade the window out, remove overlay after fade.
	var myClose = function(hash){
		hash.w.fadeOut('3000', function(){
			hash.o.remove();
			
		});
	};
	var openInIframe = function(hash){
		var newWidth = 0, newHeight = 0, newLeft = 0, newTop = 0;
		var $trigger = $(hash.t);
		var $modal = $(hash.w);
		var myUrl = $trigger.attr('href');
		var myTitle = $trigger.attr('title');
		var $modalContent = $("iframe", $modal);
		
		$modalContent.html('').attr('src', myUrl);
		//let's use the anchor "title" attribute as modal window title
		$('#jqmTitleText').text(myTitle);
		
		myUrl = (myUrl.lastIndexOf("#") > -1) ? myUrl.slice(0, myUrl.lastIndexOf("#")) : myUrl;
		var queryString = (myUrl.indexOf("?") > -1) ? myUrl.substr(myUrl.indexOf("?") + 1) : null;
		
		if (queryString != null && typeof queryString != 'undefined') {
			var queryVarsArray = queryString.split("&");
			for (var i = 0; i < queryVarsArray.length; i++) {
				if (unescape(queryVarsArray[i].split("=")[0]) == 'width') {
					var newWidth = queryVarsArray[i].split("=")[1];
				}
				if (escape(unescape(queryVarsArray[i].split("=")[0])) == 'height') {
					var newHeight = queryVarsArray[i].split("=")[1];
				}
			}
			// let's run through all possible values: 90%, nothing or a value in pixel
			if (newHeight != 0) {
				if (newHeight.indexOf('%') > -1) {
					newHeight = Math.floor(parseInt($(window).height()) * (parseInt(newHeight) / 100));
				}
				var newTop = Math.floor(parseInt($(window).height() - newHeight) / 2);
			}
			else {
				newHeight = $modal.height();
			}
			if (newWidth != 0) {
				if (newWidth.indexOf('%') > -1) {
					newWidth = Math.floor(parseInt($(window).width() / 100) * parseInt(newWidth));
				}
				var newLeft = Math.floor(parseInt($(window).width() / 2) - parseInt(newWidth) / 2);
				
			}
			else {
				newWidth = $modal.width();
			}
			// do the animation so that the windows stays on center of screen despite resizing
			$modal.jqmShow().animate({
				width: newWidth,
				height: newHeight,
				top: newTop,
				left: newLeft,
				marginLeft: 0
			}, 2000);
		}
		
		else {
			// don't do animations
			$modal.jqmShow();
		}
	}
	
	//thickbox replacement
	$('#modalWindow').jqm({
		modal: true,
		trigger: '.thickbox',
		target: '#jqmContent',
		onHide: myClose,
		onShow: openInIframe
	});
	
});


function addFav(){
	var url = location.href;
	var title = document.title;

	if (window.sidebar) {
		window.sidebar.addPanel(title, url,'');
	} else if (window.opera && window.print) {
		var mbm = document.createElement('a');
		mbm.setAttribute('rel','sidebar');
		mbm.setAttribute('href',url);
		mbm.setAttribute('title',title);
		mbm.click();
	} else if (document.all) { 
		window.external.AddFavorite(url, title);
	}
	return;
}




moveContent = function(nameDivOas, nameDivOasDisplay) {
	var elemDivOas = document.getElementById(nameDivOas);
	var elemDivOasDisplay = document.getElementById(nameDivOasDisplay);
	if(elemDivOasDisplay != null){
		elemDivOasDisplay.appendChild(elemDivOas);
		elemDivOas.style.display='block';
	}
}

function criaPalavras() {
	var divpalavras = document.getElementById('mais_buscadas');
	var rWords = new Array("anal","sexo oral","maior vagina domundo" )
	var totalResultados = 25;
	var linkPalavrasList = '';
	for(var i=0;i<statistics.length;i++) {
		var pThis = true;
		for(var j=0;j<rWords.length;j++) {
			if (statistics[i].q.indexOf(rWords[j]) != -1) {
				pThis = false;
			}
		}
		
		if (pThis == true) {
			while (statistics[i].q.substring(statistics[i].q.length-1) == " ") {
				statistics[i].q = statistics[i].q.slice(0,(statistics[i].q.length -1));
			}
			if(statistics[i].p <= totalResultados){
				linkPalavrasList = linkPalavrasList +
				'<a href="http://supermundo.abril.com.br/busca/?qu='+escape(statistics[i].q)+'">'+
				'<span class="pos-'+ statistics[i].p +'">'+statistics[i].q+
				'</span></a> ';
			}
		}
	}
	divpalavras.innerHTML = linkPalavrasList;
}


function getBusca() {
	var KWstr = document.getElementsByName('keywords')[0].content;
	KWArr = KWstr.split(',');
	KWAll = ''
	for (i in KWArr) {
		if (KWArr[i] != "" && KWArr[i] != " "){ 
			KWAll += KWArr[i] + "+";
		}
	}
	KWAll = KWAll.replace(/ /ig, "");
	KWMon = KWAll.split('');
	KWAll = '';
	for (i in KWMon) { 
		if (i < (KWMon.length-1)) {
			KWAll += KWMon[i];
		}
	}
	document.getElementById('direitaR3').innerHTML = '';
	
		$.get("http://mundoestranho.abril.com.br/fast/mundoestranho/resultHtml.servlet?busca="+KWAll+"&Keywords="+KWAll+"&qu="+KWAll+"&ao=1&rd=0&ao=1&rpf_navigation:enabled=true&rpf_navigation:navigators&tipo=abril&num=10&on=5&in=10&outputCharEnc=UTF-8&keywordCharEnc=UTF-8&Partner=abril_br_xml_buscaabril&mkt=br&adultFilter=clean&sexfilter=1&si=mundoestranho",
		  function(data){
			$("#PergRelRes").html(data);
			moveContent("getRel", "direitaR3");
		  });	
}


function getCookieVal (offset) 
{
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
	   endstr = document.cookie.length;
	   return unescape(document.cookie.substring(offset, endstr));
}

function ChkUser(cod) {
	if (GetCookie('usuario') != null) {
		CodU = GetCookie('usuario').split(';');
		if (CodU[0] == cod) {
			return true;
		} else {
			location.replace('http://'+location.hostname+location.pathname);
			return false
		}
	} else {
		location.replace('http://'+location.hostname+location.pathname);
		return false
	}
}

function GetCookie (name) {
	 var arg = name + "=";
	 var alen = arg.length;
	 var clen = document.cookie.length;
	 var i = 0;

	 while (i < clen) {           
	  var j = i + alen;									   
	  if (document.cookie.substring(i, j) == arg)s
		  return getCookieVal (j);
		  i = document.cookie.indexOf(" ", i) + 1;
	  if (i == 0) 
		  break; 
	 }
	 return null;
}

function ValidaTicket() {
	username = GetCookie('usuario');
	ticket = GetCookie('ticket');

	if ((username == null) && (ticket == null)) { 
		return false;
	} 
	if (location.search=="") {
	UData = username.split(';');
	location.replace(window.location+'?ps='+UData[0]+'pQ&nM='+UData[1].replace(/\+/ig,' ')+'&mt='+UData[2]);
	}
	return true;
}

function enviarPrm() {
	if (GetCookie('usuario') == null) {
		ValidaTicket();
	}
	var frm = document.comentarioForm;
	if (frm.txt.value == '') {
		alert('Preencha o campo com sua resposta.');
		return;
	}
	if (posted == "DONE" && frm.txt.value == '') {
	} else {
		if (frm.txt.value != '') {
			frm.texto.value = html2entities(frm.txt.value);
			document.comentarioForm.submit();
			var posted = "DONE";
		}
	}
}		

function enviarConcatenado(a,b,c) {
	frm = eval('document.'+a);
	msn = eval('frm.'+b+'.value');
	txt = eval('frm.'+c+'.value');

	if (msn == '' || txt == '') {
		alert('Preencha todos os campos.');
		return;
	} else {
		if (msn != '' || txt != '') {
			frm.texto.value = '<b>MSN:</b> ' + html2entities(msn) + ' <br><b>Mensagem:</b> ' + html2entities(txt);
			frm.submit();
		}
	}
}


function Busca(form) {
	Vbusca = form.cp_busca.value;
	if (Vbusca == '' || Vbusca == 'busque aqui') {
		alert('Preencha a busca com termos válidos');
		return false;
	} else {
		clBusca = clearSearch(Vbusca);
		form.busca.value = clBusca;
		form.Keywords.value = clBusca;
		form.qu.value = Vbusca;
		form.action = '/busca';
		return true
	}
}

function mudaPagina(pNovaPagina){
	
	var re = /pg=[0-9]+/;
	var url = location.href;
	
	if((url).indexOf("pg=") >= 0) {
		window.location.replace(url.replace(re, 'pg='+pNovaPagina));
		
	} else {
		
		if (url.indexOf("?") >= 0) {
			window.location.replace(url + '&pg='+ pNovaPagina);
			
		} else {
			window.location.replace(url + '?pg='+ pNovaPagina);
		}
	}
}

function html2entities(str) {
	var keys = 		new Array("&", " ", "¡", "¢", "£", "¤", "¥", "¦", "§", "¨", "©", "ª", "«", "¬", "­", "®", "¯", "°", "±", "²", "³", "´", "µ", "¶", "·", "¸", "¹", "º", "»", "¼", "½", "¾", "¿", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "û", "ü", "ý", "þ", "ÿ", "\"", "<", ">");
    var values = 	new Array("&amp;", "&nbsp;", "&iexcl;", "&cent;", "&pound;", "&curren;", "&yen;", "&brvbar;", "&sect;", "&uml;", "&copy;", "&ordf;", "&laquo;", "&not;", "&shy;", "&reg;", "&macr;", "&deg;", "&plusmn;", "&sup2;", "&sup3;", "&acute;", "&micro;", "&para;", "&middot;", "&cedil;", "&sup1;", "&ordm;", "&raquo;", "&frac14;", "&frac12;", "&frac34;", "&iquest;", "&Agrave;", "&Aacute;", "&Acirc;", "&Atilde;", "&Auml;", "&Aring;", "&AElig;", "&Ccedil;", "&Egrave;", "&Eacute;", "&Ecirc;", "&Euml;", "&Igrave;", "&Iacute;", "&Icirc;", "&Iuml;", "&ETH;", "&Ntilde;", "&Ograve;", "&Oacute;", "&Ocirc;", "&Otilde;", "&Ouml;", "&times;", "&Oslash;", "&Ugrave;", "&Uacute;", "&Ucirc;", "&Uuml;", "&Yacute;", "&THORN;", "&szlig;", "&agrave;", "&aacute;", "&acirc;", "&atilde;", "&auml;", "&aring;", "&aelig;", "&ccedil;", "&egrave;", "&eacute;", "&ecirc;", "&euml;", "&igrave;", "&iacute;", "&icirc;", "&iuml;", "&eth;", "&ntilde;", "&ograve;", "&oacute;", "&ocirc;", "&otilde;", "&ouml;", "&divide;", "&oslash;", "&ugrave;", "&uacute;", "&ucirc;", "&uuml;", "&yacute;", "&thorn;", "&yuml;", "&quot;", "&lt;", "&gt;");
   
	for(var i=0; i < keys.length; i++) {
		if(values[i] != "&nbsp;") {
			str = eval('str.replace(/'+keys[i]+'/g, "'+values[i]+'")');
		}
	}
	return str;
}


//######################################
//Validação da Busca da SuperMundo
//######################################
buscaSuperMundo = function(obj, path){
url = path;		
dest = document.getElementById("qu").value;
	if(dest == 'DIGITE AQUI O QUE VOCÊ PROCURA' || dest == ""){
		alert('Preencha a busca com termos válidos');
		return false;
	}else{
		location.href = url + "?qu=" + escape(dest);
		return false;
	}
} 