function myXMLHttpRequest ()
{
	var xmlhttplocal;
	try {
		xmlhttplocal = new ActiveXObject ("Msxml2.XMLHTTP")}
	catch (e) {
		try {
			xmlhttplocal = new ActiveXObject ("Microsoft.XMLHTTP")
		}
		catch (E) {
			xmlhttplocal = false;
		}
  	}
	if (!xmlhttplocal && typeof XMLHttpRequest != 'undefined') {
		try {
			var xmlhttplocal = new XMLHttpRequest ();
		}
		catch (e) {
	  		var xmlhttplocal = false;
			alert ('couldn\'t create xmlhttp object');
		}
	}
	return (xmlhttplocal);
}

var mnmxmlhttp = Array ();
var mnmString = Array ();
var mnmPrevColor = Array ();
var responsestring = Array ();
var myxmlhttp = Array ();
var responseString = new String;
var xmlhttp = new myXMLHttpRequest ();

var tempX=-1;
var tempY=-1;
var user=0;


function menealo (user, id, htmlid, md5)
{
  	if (xmlhttp) {
		url = "menealo.php";
		content = "id=" + id + "&user=" + user + "&md5=" + md5;

		mnmxmlhttp[htmlid] = new myXMLHttpRequest ();
		if (mnmxmlhttp[htmlid]) {
		/*
			mnmxmlhttp[htmlid].open ("POST", url, true);
			mnmxmlhttp[htmlid].setRequestHeader ('Content-Type',
					   'application/x-www-form-urlencoded');
			mnmxmlhttp[htmlid].send (content);
		*/
			url = url + "?" + content;
			mnmxmlhttp[htmlid].open ("GET", url, true);
			mnmxmlhttp[htmlid].send (null);


			errormatch = new RegExp ("^ERROR:");
			target1 = document.getElementById ('mnms-' + htmlid);
			target2 = document.getElementById ('mnmlink-' + htmlid);
			mnmPrevColor[htmlid] = target2.style.backgroundColor;
			//target1.style.background = '#c00';
			target2.style.backgroundColor = '#0F678B';
			mnmxmlhttp[htmlid].onreadystatechange = function () {
				if (mnmxmlhttp[htmlid].readyState == 4) {
					mnmString[htmlid] = mnmxmlhttp[htmlid].responseText;
					if (mnmString[htmlid].match (errormatch)) {
						mnmString[htmlid] = mnmString[htmlid].substring (6, mnmString[htmlid].length);
						// myclearTimeout(row);
						// resetrowfull(row);
						alert (mnmString[htmlid]);
						changemnmvalues (htmlid, true);
					} else {
						changemnmvalues (htmlid, false);
					}
				}
			}
		} else {
			alert('Couldn\'t create XmlHttpRequest');
		}
	}
}

function changemnmvalues (id, error)
{
	split = new RegExp ("~--~");
	b = mnmString[id].split (split);
	target1 = document.getElementById ('mnms-' + id);
	target2 = document.getElementById ('mnmlink-' + id);
	if (error) {
		target2.innerHTML = "<span>ops...</span>";
		return false;
	}
	if (b.length <= 3) {
		target1.innerHTML = b[0];
		target2.style.backgroundColor = mnmPrevColor[id];
		target2.innerHTML = "<span>obrigado</span>";
	}
	return false;
}


function enablebutton (button, button2, target)
{
	var string = target.value;
	button2.disabled = false;
	if (string.length > 0) {
		button.disabled = false;
	} else {
		button.disabled = true;
	}
}

function checkfield (type, form, field)
{
	url = 'checkfield.php?type='+type+'&name=' + field.value;
	checkitxmlhttp = new myXMLHttpRequest ();
	checkitxmlhttp.open ("GET", url, true);
	checkitxmlhttp.onreadystatechange = function () {
		if (checkitxmlhttp.readyState == 4) {
		responsestring = checkitxmlhttp.responseText;
			if (responsestring == 'OK') {
				document.getElementById (type+'checkitvalue').innerHTML = '<span style="color:black">"' + field.value + 
						'": ' + responsestring + '</span>';
				form.submit.disabled = '';
			} else {
				document.getElementById (type+'checkitvalue').innerHTML = '<span style="color:red">"' + field.value + '": ' +
				responsestring + '</span>';
				form.submit.disabled = 'disabled';
			}
		}
	}
  //  xmlhttp.setRequestHeader('Accept','message/x-formresult');
  checkitxmlhttp.send (null);
  return false;
}

function report_problem(frm, user, id, md5 /*id, code*/) {
	if (frm.ratings.value == 0) {
		return;
	}
	if (frm.ratings.value == -99 && ! confirm("De certeza que quer apagar?") ) {
		frm.ratings.selectedIndex=0;
		return false;
	}
	if (frm.ratings.value != -99 && ! confirm("De certeza que quer denunciar?") ) {
		frm.ratings.selectedIndex=0;
		return false;
	}
	content = "id=" + id + "&user=" + user + "&md5=" + md5 + '&value=' +frm.ratings.value;
	url="problem.php?" + content;
	xmlhttp.open("GET",url,true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) {
			frm.ratings.disabled=true;
			alert(xmlhttp.responseText);
		}
  	}
	xmlhttp.send(null);
	return false;
}


// Ajax contact form
var pos; // variable for posting information

function loadXMLPosDoc(url,posData) {
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        pos = new XMLHttpRequest();
        pos.onreadystatechange = processPosChange;
        pos.open("POST", url, false);
		pos.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        pos.send(posData);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        pos = new ActiveXObject("Microsoft.XMLHTTP");
        if (pos) {
            pos.onreadystatechange = processPosChange;
            pos.open("POST", url, false);
			pos.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            pos.send(posData);
        }
    }
}

function grabPosXML (tagName) {
return pos.responseXML.documentElement.getElementsByTagName(tagName)[0].childNodes[0].nodeValue;
}

function processPosChange() {
    // page loaded "complete"
    if (pos.readyState == 4) {
        // page is "OK"
        if (pos.status == 200) {
			if ( grabPosXML("posStatus") == 'NOTOK' ) { 
				alert('Nao consegui enviar o email. Tente mais tarde, se faz favor');
			}
		}
	}
}

// -- thumbs

function show (id) {
	document.getElementById(id).style.display='';
}

function hide (id) {
	document.getElementById(id).style.display='none';
}

// --- Clicks ---

function click(id,user)
{
    http = new myXMLHttpRequest ();
	aux=id.replace(/link(\d+)/,'$1');
    http.open('get', 'click.php?id='+aux+'&user='+user+'&x='+tempX+'&y='+tempY);
    http.send(null);
}

function clickall(ref,user)
{
    http = new myXMLHttpRequest ();
	aux=ref.replace(/http:\/\/domelhor.net\/(.+)$/,'$1');
    http.open('get', 'click.php?id=&user='+user+'&x='+tempX+'&y='+tempY+'&dest='+aux);
    http.send(null);
}

function init() {
    if (!document.getElementsByTagName){ return; }
    var anchors = document.getElementsByTagName('a');

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];
			
		var id = String(anchor.getAttribute('id'));
		if  (id.match(/link(\d+)/)) { // links na história
			anchor.style.backgroundColor='#fcfcfc';
  			if (document.all) { // if browser is IE
				anchor.onclick=function() { click(this.id,user); };
			} else {
				anchor.setAttribute("onclick","click('"+id+"',user);");
			}
		} else { // outros links
		        var id2 = escape(String(anchor.getAttribute('href')));
			//if (!id2.match(/^javascript/)) { 
  				if (document.all) { // if browser is IE
					anchor.onclick=function() { clickall(this.href,user); };
				} else {
					anchor.setAttribute("onclick","clickall('"+id2+"',user);");
				}
			//}
		}
	}
	if (!document.all) document.captureEvents(Event.MOUSEDOWN)
	document.onmousedown = getMouseXY;
}	

function getMouseXY(e) {
  if (document.all) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  
  return true
}


function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;

    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.opacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}

function quiz_vote(user,quiz,value) {
    if (xmlhttp) {
        url = "libs/quiz_vote.php";
        content = "id=" + quiz + "&user=" + user + "&value=" + value;

        url = url + "?" + content;

        xmlhttp.open ("GET", url, true);
        xmlhttp.send (null);

        if (document.getElementById("votetext") != null)
			document.getElementById("votetext").innerHTML="<p>a processar voto...</p>";
		else {
        	if (document.getElementById("quizresults") != null)
				document.getElementById("quizresults").innerHTML="<p>a processar voto...</p>";
		}

        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4) {
                results = xmlhttp.responseText;

                res = results.split("~");
                if (document.getElementById("votetext") != null)
                    document.getElementById("votetext").innerHTML=res[0];

                if (document.getElementById("quizresults") != null)
                    document.getElementById("quizresults").innerHTML=res[1];

			}
		}
	}
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function closevote(num,container,votewindow,area)
{
	name="domelhor"+area+"_voto"+num;

	if (!readCookie(name)) {
		createCookie(name,"Sim",8);
	}
	changeOpac(100,container);
	document.getElementById(votewindow).style.display='none';
}


function center(id)
{
    scr=windowSize();
    divid=document.getElementById(id);
    divid.style.display='';
    var IpopLeft = (scr[0] - divid.offsetWidth)/2;
    var IpopTop = (scr[1] - divid.offsetHeight)/2;

    divid.style.left=IpopLeft + document.body.scrollLeft+"px";
    divid.style.top=IpopTop + document.body.scrollTop+"px";
}

function windowSize()
{
    var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }

    return [myWidth,myHeight];
}

function partilhar(id,anonimo)
{
	var obj=document.getElementById('p-'+id);
	if (!obj) return;

	if (obj.style.display=='') {
		obj.style.display="none";
		return;
	}

	if (anonimo) {
			var aux="<fieldset>Para enviar esta mat&eacute;ria tem de primeiro <a href=login.php><strong>entrar</strong></a> ou <a href=register.php><strong>registar-se</strong></a><br>Note-se que o registo &eacute; gratuito e demora apenas alguns segundos.<br><strong>At&eacute; j&aacute;!</strong><br><br><input type=button onclick='document.getElementById(\"p-"+id+"\").style.display=\"none\"' value='Fechar'></fieldset>";
			} else {
		//var email="okedoke@okok.pt";
		//var nome="jaquim manel";
    			var aux=document.getElementById('partilhar').innerHTML;
    			aux=aux.replace(/%ID%/g,id);
    			//aux=aux.replace('%EMAIL%',email);
    			//aux=aux.replace('%NOME%',nome);
			}

	obj.innerHTML=aux;
	obj.style.display='';
}

function enviar(frm)
{
    var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
    var regex = new RegExp(emailReg);

	if (!frm.destino1.value.length && !frm.destino2.value.length && !frm.destino3.value.length) {
		document.getElementById('p-'+frm.artigo.value).style.display='none';
		return true;
	}

    if (frm.destino1.value.length && !regex.test(frm.destino1.value)) {
        alert('Email 1 invalido!');
        frm.destino1.focus();
        return false;
    }
    if (frm.destino2.value.length && !regex.test(frm.destino2.value)) {
        alert('Email 2 invalido!');
        frm.destino2.focus();
        return false;
    }
    if (frm.destino3.value.length && !regex.test(frm.destino3.value)) {
        alert('Email 3 invalido!');
        frm.destino3.focus();
        return false;
    }
	document.getElementById('p-'+frm.artigo.value).style.display='none';

	//var num=0;
	//if (frm.destino1.value.length) num++;
	//if (frm.destino2.value.length) num++;
	//if (frm.destino3.value.length) num++;
	//if (num!=1) alert("Obrigado. Foram enviados "+num+" emails");
	//else alert("Obrigado. Foi enviado um email");

    url="partilhar.php?id=" + frm.artigo.value + "&email1=" + frm.destino1.value + "&email2=" + frm.destino2.value + "&email3=" + frm.destino3.value + "&mensagem="+escape(frm.mensagem.value);

    xmlhttp.open("GET",url,true);
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4) {
			alert(xmlhttp.responseText);
        }
    }
    xmlhttp.send(null);
	return true;

}

function updatestatus()
{
    xmlhttp=new myXMLHttpRequest ();
    xmlhttp.open ('GET', 'novos.php?horas='+update_time, true);
    xmlhttp.send (null);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            res=xmlhttp.responseText.split("|||");
            results = parseInt(res[0]);
            if (results && document.getElementById('status') != null) {
                if (results>1) letra='s'; else letra='';
                if (results<=12) {
                    var dig=new Array("um","dois","três","quatro","cinco","seis","sete","oito","nove","dez","onze","doze");
                    results=dig[results-1];
                };

                document.getElementById('status').style.display='';
                document.getElementById('status').innerHTML='<p><a href=\"'+update_url+'\">Há <strong>'+results+'</strong> resultado'+letra+' novo'+letra+'. Clique para o'+letra+' ver.</p>';
            }

            if (typeof html!="undefined" && typeof res[1] != 'undefined') {
                html[0]=res[1];
                html[1]=res[2];
                html[2]=res[3];
                html[3]=res[4];
            }
        }
    }

    update_minutes();
}

function favorito(root,id,title){
	var url = "http://domelhor.net"+root+"story.php?id="+id;

	if (document.all) { // IE Favorite
		window.external.AddFavorite( url, title);
	} else if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if(window.opera && window.print) { // Opera Hotlist
        	var mbm = document.createElement('a');
        	mbm.setAttribute('rel','sidebar');
        	mbm.setAttribute('href',url);
        	mbm.setAttribute('title',title);
        	mbm.click();
	}
}

function update_minutes()
{	
	elems=getElementsByClass("minutos",null,"span")
	for (i=0; i<elems.length; i++) {
		var str=new String(elems[i].innerHTML);
		var num=0;

		if (str.match(/^poucos/)) num=1;
		else if (str.match(/^\d+ min/)) num=parseInt(str.substr(0,2))+1;
		else if (str.match(/^\d+ h/)) {
			num=parseInt(str.substr(0,2))*60;
			if ((pos=str.indexOf(" e "))>1) 
				num=num+parseInt(str.substr(pos+3,2));
			num=num+1;
		}
		if (!num) continue;

		if (num==1) elems[i].innerHTML="1 minuto";
		else if (num<60) elems[i].innerHTML=num+" mins";
		else {
			var mins=(num%60);
			var hr=parseInt(num/60);

			var hs="";
			if (hr>1) hs="s";
			var ms="";
			if (mins>1) ms="s";

			if (mins)
				elems[i].innerHTML=hr+" hr"+hs+" e "+mins+" min"+ms;
			else {
				if (hr<24)
					elems[i].innerHTML=hr+" hora"+hs;
				else
					elems[i].innerHTML="1 dia";
			}
		}
	}
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}
