/*---------------------------------------------------------
Portal do Humor - www.portaldohumor.com.br

JavaScript do site
Autor - Danilo Carneiro Dantas

Data da criação - 10 de Setembro de 2006
Data da última edição - 26 de Dezembro de 2006
---------------------------------------------------------*/

/*AjaxGet - Inicio*/ 
function ajaxGet(url,elemento_retorno,exibe_carregando)
{

    var ajax1 = pegaAjax();
    if(ajax1)
	{
        url = antiCacheRand(url)
        ajax1.onreadystatechange = ajaxOnReady
        ajax1.open("GET", url ,true);
        ajax1.setRequestHeader("Cache-Control", "no-cache");
        ajax1.setRequestHeader("Pragma", "no-cache");
        if(exibe_carregando){ put("Carregando ...")    }
        ajax1.send(null)
        return true;
    }
	else
	{
        return false;
    }
    function ajaxOnReady()
	{
        if (ajax1.readyState==4)
		{
            if(ajax1.status == 200){
                var texto=ajax1.responseText;
                if(texto.indexOf(" ")<0) texto=texto.replace(/\+/g," ");
                put(texto);
                extraiScript(texto);
            }else{
                if(exibe_carregando){put("Falha no carregamento. " + httpStatus(ajax1.status));}
            }
            ajax1 = null
        }
		else if(exibe_carregando)
		{
                put("Carregando ..." )
        }
    }
    function put(valor)
	{ 
        if((typeof(elemento_retorno)).toLowerCase()=="string")
		{ 
            if(valor!="Falha no carregamento")
			{
                eval(elemento_retorno + '= unescape("' + escape(valor) + '")')
            }
        }
		else if(elemento_retorno.tagName.toLowerCase()=="input")
		{
            valor = escape(valor).replace(/\%0D\%0A/g,"")
            elemento_retorno.value = unescape(valor);
        }
		else if(elemento_retorno.tagName.toLowerCase()=="select")
		{        
            select_innerHTML(elemento_retorno,valor)
        }
		else if(elemento_retorno.tagName)
		{
            elemento_retorno.innerHTML = valor;
        }    
    }
    function pegaAjax()
	{
        if(typeof(XMLHttpRequest)!='undefined')
		{
			return new XMLHttpRequest();
		}
        var axO=['Microsoft.XMLHTTP','Msxml2.XMLHTTP','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0'];
        for(var i=0;i<axO.length;i++)
		{
			try{ return new ActiveXObject(axO[i]);}catch(e){}
		}
        return null;
    }
    function httpStatus(stat)
	{
        switch(stat)
		{
            case 0: return "Erro desconhecido de javascript";
            case 400: return "400: Solicita&ccedil;&atilde;o incompreensível"; break;
            case 403: case 404: return "404: N&atilde;o foi encontrada a URL solicitada"; break;
            case 405: return "405: O servidor n&atilde;o suporta o m&eacute;todo solicitado"; break;
            case 500: return "500: Erro desconhecido de natureza do servidor"; break;
            case 503: return "503: Capacidade m&aacute;xima do servidor alcançada"; break;
            default: return "Erro " + stat + ". Mais informa&ccedil;&otilde;es em http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html"; break;
        }
    }
    function antiCacheRand(aurl)
	{
        var dt = new Date();
        if(aurl.indexOf("?")>=0)
		{
            return aurl + "&" + encodeURI(Math.random() + "_" + dt.getTime());
        }
		else{
		return aurl + "?" + encodeURI(Math.random() + "_" + dt.getTime());
		}
    }
}
function select_innerHTML(objeto,innerHTML)
{

    objeto.innerHTML = ""
    var selTemp = document.createElement("micoxselect")
    var opt;
    selTemp.id="micoxselect1"
    document.body.appendChild(selTemp)
    selTemp = document.getElementById("micoxselect1")
    selTemp.style.display="none"
    if(innerHTML.toLowerCase().indexOf("<option")<0)
	{
        innerHTML = "<option>" + innerHTML + "</option>"
    }
    innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span")
    selTemp.innerHTML = innerHTML
    for(var i=0;i<selTemp.childNodes.length;i++)
	{
        if(selTemp.childNodes[i].tagName)
		{
            opt = document.createElement("OPTION")
            for(var j=0;j<selTemp.childNodes[i].attributes.length;j++)
			{
                opt.setAttributeNode(selTemp.childNodes[i].attributes[j].cloneNode(true))
            }
            opt.value = selTemp.childNodes[i].getAttribute("value")
            opt.text = selTemp.childNodes[i].innerHTML
            if(document.all)
			{ 
                objeto.add(opt)
            }
			else
			{
                objeto.appendChild(opt)
            }                    
        }    
    }
    document.body.removeChild(selTemp)
    selTemp = null
}

function extraiScript(texto)
{

    var ini = 0;
    
    while (ini!=-1)
	{
     
        ini = texto.indexOf('<script', ini);
		
        if (ini >=0)
		{
			
            ini = texto.indexOf('>', ini) + 1;
			
            var fim = texto.indexOf('</script>', ini);
			
            codigo = texto.substring(ini,fim);
			
			
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}
/* AjaxGet - Fim*/

function ajaxInit()
{
	var xmlhttp;
	try 
	{
		xmlhttp = new XMLHttpRequest();
	}
	catch(ee)
	{
		try
		{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			try 
			{
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(E)
			{
				xmlhttp = false;
			}
		}
	}
	return xmlhttp;
}
function indique()
{
	window.open('?mod=indicar','indique','scrollbars=yes,toolbar=no,status=0,resizable=no,width=350,height=410');
}
function indique2(id)
{
	window.open('?page=' + id + '&mod=indicar','indique','scrollbars=yes,toolbar=no,status=0,resizable=no,width=350,height=410');
}
function museu(numero)
{
	window.open('?v='+ numero +'','museu','scrollbars=yes,toolbar=no,status=0,resizable=yes,width=770,height=550');
}
function comentar()
{
	window.open('?mod=comment','museu','scrollbars=yes,toolbar=no,status=0,resizable=no,width=350,height=500');
}
function new_window(pag)
{
	window.open(''+ pag +'','PortalDoHumor');
}
function pdh_search()
{
	if(document.buscaf.palavra.value.length > 0)
	{
		//document.getElementById("buscasubmit").disabled = false;
		ajaxGet('/script/autosearch.php?ugl=' + document.buscaf.palavra.value +'',document.getElementById("bldx"),false);
	}	
	else
	{
		document.getElementById("bldx").innerHTML = '&nbsp;';	
	}
}
function pdh_search2(pav)
{
	document.buscaf.palavra.value = pav;
	document.getElementById("bldx").innerHTML = '&nbsp;';
}
function votacao_conteudo()
{
	var nota = 0;
	var opcoes = document.getElementsByName('voto');
	for (i = 0; i < opcoes.length; i++)
	{
		opcao = opcoes.item(i);
		if (opcao.checked)
		{
			nota = opcao.value;
		}
	}
	
	if(!nota)
	{
		window.alert("É tão difícil assim marcar uma opção?!"); 
	}

	else if ((nota != 2) && (nota != 4) && (nota != 6) && (nota != 8) && (nota != 10))
	{
		window.alert("Olha a fraude...");
	}
	
	else
	{
		ajaxGet('?nota=' + nota + '',document.getElementById("msg"),true);	
		setTimeout("ajaxGet('?mod=stats',document.getElementById('vopt'),false)",500);
		document.getElementById("vw").innerHTML = '';	
	}
}
function pdh_clear_boletim()
{
	if (document.boletimform.email.value == 'Digite seu e-mail aqui, pô!')
	{
		document.boletimform.email.value = '';
	}
}
function pdh_bol_sub()
{
	if(document.boletimform.email.value == 'Digite seu e-mail aqui, pô!' || !document.boletimform.email.value)
	{
		alert("Custa digitar o e-mail?!");
	}
	else
	{
		ajax = ajaxInit();
		if (ajax)
		{
			ajax.open("GET", '/script/boletim.php?mod=cadastrar&email=' + document.boletimform.email.value + '', true);
			ajax.onreadystatechange = function ()
			{
				if (ajax.readyState == 4)
				{
		            if (ajax.status == 200)
					{
						if(ajax.responseText == "1")
						{
							alert("Você digitou um e-mail inválido.");
						}
						else if(ajax.responseText == "2")
						{
							alert("Você já está cadastrado em nosso boletim. Caso não esteja recebendo nossos e-mails, contate a administração pelo e-mail contato@portaldohumor.com.br.");
						}
						else if(ajax.responseText == "3")
						{
							alert("Você já está cadastrado em nosso boletim, mas não ativou seu cadastro. Cheque seu e-mail e clique no link de ativação que foi reenviado para você. É possivel que nosso e-mail tenha caído na pasta lixo eletrônico ou spam de seu provedor.");
						}
						else if(ajax.responseText == "4")
						{
							alert("Você foi cadastrado com sucesso. Clique no link de confirmação que acabamos de enviar para seu e-mail. É possivel que nosso e-mail tenha caído na pasta lixo eletrônico ou spam de seu provedor. Obrigado!");
						}
						else if(ajax.responseText == "5")
						{
							alert("Proteção anti-flood ativada. Aguarde alguns segundos e tente novamente.");
						}
						else
						{
							alert("Erro de sistema.");
							new_window('/script/boletim.php?mod=cadastrar&email=' + document.boletimform.email.value + '');
						}
						
						ajaxGet('?mod=bolr',document.getElementById("boletim_js"),false);
					}
				}
				else
				{
					document.getElementById("boletim_js").innerHTML = '<br /><img src="/tpl/img/loading.gif" alt="" /> Carregando...';
				}
			}
			ajax.send(null);
		}
	}
}
function pdh_enq_sub()
{
	var voto = 0;
	var opcoes = document.getElementsByName('voto');
	for (i = 0; i < opcoes.length; i++)
	{
		opcao = opcoes.item(i);
		if (opcao.checked)
		{
			voto = opcao.value;
		}
	}
	
	if(voto)
	{
		ajax = ajaxInit();
		if (ajax)
		{
			ajax.open("GET", '/script/enquete.php?opcao=' + voto +'', true);
			ajax.onreadystatechange = function ()
			{
				if (ajax.readyState == 4)
				{
		            if (ajax.status == 200)
					{
						if(ajax.responseText == "1")
						{
							alert("Obrigado por votar!");
						}
						else if(ajax.responseText == "0")
						{
							alert("Desculpe, você já votou.");
						}
						else
						{
							alert("Erro de sistema.");
							new_window('/script/enquete.php?opcao=' + voto +'');
						}
					}
					ajaxGet('?mod=reloadenquete',document.getElementById("enquete_js"),false);
				}
				else
				{
					document.getElementById("enquete_js").innerHTML = '<br /><img src="/tpl/img/loading.gif" alt="" /> Carregando...';
				}
			}
			ajax.send(null);
		}
	}
	else
	{
		alert("É tão difícil assim marcar uma opção?!");
	}
}
/*function pdh_enabled(id)
{
	document.getElementById(id).disabled = false;
}*/
function ProcessarMenu()
{
	var links = document.getElementById("menudiv").getElementsByTagName('li');
	var trocaClass = 0;
	for(var x = 0; x < links.length; x++)
	{
		trocaClass = (trocaClass == 0) ? 1 : 0;
		if(trocaClass && !links[x].className)
		{
			links[x].className = 'ml';
		}
	}
	document.getElementById("palavra").setAttribute("autocomplete","off");
}

function Set_Cookie(name,value,expires,path,domain,secure) {
         var cookieString = name + "=" +escape(value) +
            ( (expires) ? ";expires=" + expires     : "") +
            ( (path) ? ";path=" + path : "")     +
            ( (domain) ? ";domain=" + domain : "")     +
            ( (secure) ? ";secure" : "");    
         document.cookie = cookieString;
     } 
	 
	 function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );

  if ( results )
    return ( unescape ( results[1] ) );
  else
    return null;
}

function closeorkut()
{
	if(get_cookie('PdhOrktClose') == '1')
	{
		var value = '2';
	}
	else
	{
		var value = '1';
	}
	document.getElementById("orkutpromo").style.display="none";
	Set_Cookie('PdhOrktClose',value,'','/');
}
