/*******************
VOTES FUNCTIONS
BASIC FUNCTIONS
************************************/
var update_voters = false;
var IE = /*@cc_on!@*/false;

function menealo(user, id, htmlid, md5)
{
	var url = base_url + "backend/menealo.php";
	var content = "id=" + id + "&user=" + user + "&md5=" + md5 + "&" + Math.random();
	url = url + "?" + content;
	disable_vote_link(id, "...", '#808080');

	$.get(url, {},  
		 function(html) {
			if (/^ERRO:/.test(html)) {
				html = html.substring(6, html.length);
				parseAnswer(htmlid, true, html);
				updateVoters(id);
			} else {
				// Just a warning, do nothing
				if (/^WARN:/.test(html)) {
					alert(html);
				} else {
					parseAnswer (htmlid, false, html);
					updateVoters(id);
				}
			}
		}
	);
}

function menealo_comment(user, id, value)
{
	var url = base_url + "backend/menealo_comment.php";
	var content = "id=" + id + "&user=" + user + "&value=" + value;
	var myid = 'comment-'+id;
	url = url + "?" + content;
	$.get(url, {}, 
		 function(html) {
			if (/^ERRO:/.test(html) || /^WARN:/.test(html)) {
				html = html.substring(6, html.length);
				alert(html);
			} else {
				vote_karma_image = html.split(",");
				votes = parseInt(vote_karma_image[0]);
				karma = parseInt(vote_karma_image[1]);
				image = vote_karma_image[2];
				$('#vc-'+id).html(votes);
				$('#vk-'+id).html(karma+" ");
				if (image.length > 0) {
					$('#c-votes-'+id).html('<img src="'+image+'"/>');
				}
			}
		}
	);
}

function menealo_post(user, id, value)
{
	var url = base_url + "backend/menealo_post.php";
	var content = "id=" + id + "&user=" + user + "&value=" + value;
	var myid = 'comment-'+id;
	url = url + "?" + content;
	$.get(url, {}, 
		 function(html) {
			if (/^ERRO:/.test(html) || /^WARN:/.test(html)) {
				html = html.substring(6, html.length);
				alert(html);
			} else {
				vote_karma_image = html.split(",");
				votes = parseInt(vote_karma_image[0]);
				karma = parseInt(vote_karma_image[1]);
				image = vote_karma_image[2];
				$('#vc-'+id).html(votes);
				$('#vk-'+id).html(karma+" ");
				if (image.length > 0) {
					$('#c-votes-'+id).html('<img src="'+image+'"/>');
				}
			}
		}
	);
}


function disable_problem_form(id) {
	$('#problem-' + id).hide();
}

function disable_vote_link(id, mess, background) {
if(IE){
	$('#a-va-' + id).html('<a href="#">'+mess+'</a>');
}else{
//document.getElementById("a-va-"+id).innerHTML="<a href=#>"+mess+"</a>";
//return;
//alert($('#a-va-' + id).html());
	$('#a-va-' + id).hide(); // IE
	$('#a-va-' + id).html('<span>'+mess+'</span>');
	$('#a-va-' + id).css('backgroundColor', background);
	$('#a-va-' + id).show('fast'); // IE
}
}

function parseAnswer (id, error, server_answer)
{
	answer = server_answer.split("~");
	linkid = answer[0];
	if (error || answer.length  != 5  || id != linkid) {
		alert(server_answer);
		disable_vote_link(id, "ops...", '#FF9B00');
		disable_problem_form(id);
		return false;
	}
	votes = answer[1];
	negatives = answer[2];
	karma = answer[3];
	value = answer[4];
	updateLinkValues(id, votes, negatives, karma, value);
	return false;
}

function updateLinkValues (id, votes, negatives, karma, value) {

	if ($('#a-votes-' + id).html() != votes) {
		if (IE) {
			$('#a-votes-' + id).html(votes);
		} else {
			$('#a-votes-' + id).hide();
			$('#a-votes-' + id).html(votes);
			$('#a-votes-' + id).fadeIn('slow');
			if (votes==1) 
				$('#t-' + id).html("voto");
			else 
				$('#t-' + id).html("votos");
			$('#t-' + id).fadeIn('slow');
		}
	}

	$('#a-neg-' + id).html(negatives);
	$('#a-karma-' + id).html(karma+" ");

	if (value > 0) {
		disable_vote_link(id, "obrigado", '#808080'); // obrigado
		disable_problem_form(id);
	} else if (value < 0) {
		disable_vote_link(id, ":-(", '#808080');
		disable_problem_form(id);
	}
	return false;
}

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

function checkfield (type, form, field)
{
	var url = base_url + 'backend/checkfield.php?type='+type+'&name=' + encodeURIComponent(field.value);
	$.get(url, {}, 
		 function(html) {
			if (html == 'OK') {
				$('#'+type+'checkitvalue').html('<span style="color:black">"' + encodeURI(field.value) + '": ' + html + '</span>');
				form.submit.disabled = '';
			} else {
				$('#'+type+'checkitvalue').html('<span style="color:red">"' + encodeURI(field.value) + '": ' + html + '</span>');
				form.submit.disabled = 'disabled';
			}
		}
	);
	return false;
}

function check_checkfield(fieldname, mess) {
	field = document.getElementById(fieldname);
	if (field && !field.checked) {
		alert(mess);
		// box is not checked
		return false;
	}
}

function check_registerform(frm) {
	if (frm.username.value.length<3) {
		alert('Nome de utilizador tem de ter pelo menos 3 caracteres!');
		frm.username.focus();
		return false;
	}
    var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
    var regex = new RegExp(emailReg);

	if (!frm.email.value.length || !regex.test(frm.email.value)) {
		alert('Email inválido!');
		frm.email.focus();
		return false;
	}

	if (frm.password.value.length<5) {
		alert('Senha muito curta. Deve ter pelo menos 5 caracteres!');
		frm.password.focus();
		return false;
	}

	if (frm.password.value!=frm.password2.value) {
		alert('Senhas não coincidem!');
		frm.password.focus();
		return false;
	}

	if (!frm.acceptlegal.checked) {
		alert('Tem de aceitar as condições de uso!');
		frm.acceptlegal.focus();
		return false;
	}

	return true;
}

function report_problem(frm, user, id, md5 /*id, code*/) {
	if (frm.ratings.value == 0)
		return;
	if (! confirm("¿Seguro que desea reportarlo?") ) {
		frm.ratings.selectedIndex=0;
		return false;
	}
	var content = "id=" + id + "&user=" + user + "&md5=" + md5 + '&value=' +frm.ratings.value;
	var url=base_url + "backend/problem.php?" + content;
	$.get(url, {}, 
		 function(html) {
			if (/^ERRO:/.test(html)) {
				html = html.substring(6, html.length);
				parseAnswer(id, true, html);
			} else {
				parseAnswer(id, false, html);
				updateVoters(id);
			}
		}
	);
	return false;
}

function updateVoters(id) {
	if (update_voters) {
		get_votes('meneos.php', 'voters', 'voters-container',1, id);
	}
}

// Get voters by Beldar <beldar.cat at gmail dot com>
// Generalized for other uses (gallir at gmail dot com)
function get_votes(program,type,container,page,id) {
	var url = base_url + 'backend/'+program+'?id='+id+'&p='+page+'&type='+type;
	$('#'+container).load(url);
}

// See http://www.shiningstar.net/articles/articles/javascript/dynamictextareacounter.asp?ID=AW
function textCounter(field,cntfield,maxlimit) {
	if (field.value.length > maxlimit)
	// if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	// otherwise, update 'characters left' counter
	else
		cntfield.value = maxlimit - field.value.length;
}


/**************************************
Tooltips functions
***************************************/
/**
  Stronglky modified, onky works with DOM2 compatible browsers.
  	Ricardo Galli
  From http://ljouanneau.com/softs/javascript/tooltip.php
 */


// create the tooltip object
function tooltip(){}

// setup properties of tooltip object
tooltip.id="tooltip";
tooltip.main=null;
tooltip.offsetx = 10;
tooltip.offsety = 10;
tooltip.shoffsetx = 8;
tooltip.shoffsety = 8;
tooltip.x = 0;
tooltip.y = 0;
tooltip.tooltipShadow=null;
tooltip.tooltipText=null;
tooltip.title_saved='';
tooltip.saveonmouseover=null;
tooltip.timeout = null;
tooltip.active = false;

tooltip.cache = new JSOC();

tooltip.ie = (document.all)? true:false;		// check if ie
if(tooltip.ie) tooltip.ie5 = (navigator.userAgent.indexOf('MSIE 5')>0);
else tooltip.ie5 = false;
tooltip.dom2 = ((document.getElementById) && !(tooltip.ie5))? true:false; // check the W3C DOM level2 compliance. ie4, ie5, ns4 are not dom level2 compliance !! grrrr >:-(




/**
* Open ToolTip. The title attribute of the htmlelement is the text of the tooltip
* Call this method on the mouseover event on your htmlelement
* ex :  <div id="myHtmlElement" onmouseover="tooltip.show(this)"...></div>
*/

tooltip.show = function (event, text) {
      // we save text of title attribute to avoid the showing of tooltip generated by browser
	if (this.dom2  == false ) return false;
	if (this.tooltipShadow == null) {
		this.tooltipShadow = document.createElement("div");
		this.tooltipShadow.setAttribute("id", "tooltip-shadow");
		document.body.appendChild(tooltip.tooltipShadow);

		this.tooltipText = document.createElement("div");
		this.tooltipText.setAttribute("id", "tooltip-text");
		document.body.appendChild(this.tooltipText);
	}
	this.saveonmouseover=document.onmousemove;
	document.onmousemove = this.mouseMove;
	this.mouseMove(event); // This already moves the div to the right position
	this.setText(text);
	this.tooltipText.style.visibility ="visible";
	this.tooltipShadow.style.visibility ="visible";
	this.active = true;
	return false;
}


tooltip.setText = function (text) {
	tooltip.tooltipShadow.style.width = 0+"px";
	tooltip.tooltipShadow.style.height = 0+"px";
	this.tooltipText.innerHTML=text;
	setTimeout('tooltip.setShadow()', 1);
	return false;
}

tooltip.setShadow = function () {
	tooltip.tooltipShadow.style.width = tooltip.tooltipText.clientWidth+"px";
	tooltip.tooltipShadow.style.height = tooltip.tooltipText.clientHeight+"px";
}


/**
* hide tooltip
* call this method on the mouseout event of the html element
* ex : <div id="myHtmlElement" ... onmouseout="tooltip.hide(this)"></div>
*/
tooltip.hide = function (event) {
	if (this.dom2  == false) return false;
	document.onmousemove=this.saveonmouseover;
	this.saveonmouseover=null;
	if (this.tooltipShadow != null ) {
		this.tooltipText.style.visibility = "hidden";
		this.tooltipShadow.style.visibility = "hidden";
		this.tooltipText.innerHTML='';
	}
	this.active = false;
}



// Moves the tooltip element
tooltip.mouseMove = function (e) {
   // we don't use "this", but tooltip because this method is assign to an event of document
   // and so is dreferenced

	if (tooltip.ie) {
		tooltip.x = event.clientX;
		tooltip.y = event.clientY;
	} else {
		tooltip.x = e.pageX;
		tooltip.y = e.pageY;
	}
	tooltip.moveTo( tooltip.x +tooltip.offsetx , tooltip.y + tooltip.offsety);
}

// Move the tooltip element
tooltip.moveTo = function (xL,yL) {
	if (this.ie) {
		xL +=  document.documentElement.scrollLeft;
		yL +=  document.documentElement.scrollTop;
	}
	if (this.tooltipText.clientWidth > 0  && document.documentElement.clientWidth > 0 && xL > document.documentElement.clientWidth * 0.55) {
		xL = xL - this.tooltipText.clientWidth - 2*this.offsetx;
	}
	this.tooltipText.style.left = xL +"px";
	this.tooltipText.style.top = yL +"px";
	xLS = xL + this.shoffsetx;
	yLS = yL + this.shoffsety;
	this.tooltipShadow.style.left = xLS +"px";
	this.tooltipShadow.style.top = yLS +"px";
}

// Show the content of a given comment
tooltip.c_show = function (event, type, element, link) {
      // we save text of title attribute to avoid the showing of tooltip generated by browser
	if (this.dom2  == false ) return false;
	if (type == 'id') {
		target_text = 'comment-' + element;
		target_author = 'cauthor-'+element;
		target = document.getElementById(target_text);
		author_target = document.getElementById(target_author);
		if (! target || ! author_target)  {
			this.ajax_delayed(event,'get_comment_tooltip.php',element+"&link="+link);
			return;
		}
		text = '<strong>'+author_target.innerHTML+'</strong><br/>'+target.innerHTML;
	} else if (type == 'order') {
		this.ajax_delayed(event,'get_comment_tooltip.php',element+"&link="+link);
		return;
	} else {
		text = element;
	}
	return this.show(event, text);
}


tooltip.clear = function (event) {
	if (this.timeout != null) {
		clearTimeout(this.timeout);
		this.timeout = null;
	}
	this.hide(event);
}

tooltip.ajax_delayed = function (event, script, id, maxcache) {
	maxcache = maxcache || 600000; // 10 minutes in cache
	if (this.active) return false;
	if ((object = this.cache.get(script+id)) != undefined) {
		tooltip.show(event, object[script+id]);
	} else {
		this.show(event, '<img src=imagens/ajaxcinza.gif> momento...'); // Translate this to your language: it's "loading..." ;-)
		this.timeout = setTimeout("tooltip.ajax_request('"+script+"', '"+id+"', "+maxcache+")", 100);
	}
}

tooltip.ajax_request = function(script, id, maxcache) {
	var url = base_url + 'backend/'+script+'?id='+id;
	tooltip.timeout = null;
	$.ajax({
		url: url,
		dataType: "html",
		success: function(html) {
			tooltip.cache.set(script+id, html, {'ttl':maxcache});
			tooltip.setText(html);
		}
	});
}

/************************
Simple format functions
**********************************/
/*
  Code from http://www.gamedev.net/community/forums/topic.asp?topic_id=400585
  strongly improved by Juan Pedro López for http://meneame.net
  2006/10/01, jotape @ http://jplopez.net
*/

function applyTag(id, tag) {
	obj = document.getElementById(id);
	if (obj) wrapText(obj, tag, tag);
}

function wrapText(obj, tag) {
	if(typeof obj.selectionStart == 'number') {
		// Mozilla, Opera and any other true browser
		var start = obj.selectionStart;
		var end   = obj.selectionEnd;

		if (start == end || end < start) return false;
		obj.value = obj.value.substring(0, start) +  replaceText(obj.value.substring(start, end), tag) + obj.value.substring(end, obj.value.length);
	} else if(document.selection) {
		// Damn Explorer
		// Checking we are processing textarea value
		obj.focus();
		var range = document.selection.createRange();
		if(range.parentElement() != obj) return false;
		if (range.text == "") return false;
		if(typeof range.text == 'string')
	        document.selection.createRange().text =  replaceText(range.text, tag);
	} else
		obj.value += text;
}

function replaceText(text, tag) {
		text = text.replace(/(^|\s)[\*_]([^\s]+)[\*_]/gm, '$1$2')
		text = text.replace(/([^\s]+)/gm, tag+"$1"+tag)
		return text;
}


// This function report the ajax request to stats trackers
// Only known how to do it with urchin/Google Analytics
// See http://www.google.com/support/analytics/bin/answer.py?answer=33985&topic=7292
function reportAjaxStats(page) {
	return; // Slow down
	if (window.urchinTracker) {
		urchinTracker(page+'.ajax'); 
	}
}

//
// MV
//
function mostratab(id,num,total) {

	num=num+1;
	for (f=1;f<=total;f++) {
		if (f==num) {
			document.getElementById(id+f).style.display='';
			document.getElementById('t'+id+f).style.display='';
		} else {
			document.getElementById(id+f).style.display='none';
			document.getElementById('t'+id+f).style.display='none';
		}
	}
}

function showtab(id,num,total) {
	for (f=1;f<=total;f++) {
		if (f==num) {
			document.getElementById(id+f).style.display='';
			document.getElementById('t'+id+f).className='seleccionado';
		} else {
			document.getElementById(id+f).style.display='none';
			document.getElementById('t'+id+f).className='';
		}
	}
}


// Alert functions

function listAlert(user) {
   	var url = base_url + "backend/alerts.php" + "?action=list&user=" + user + "&" + Math.random();
	$.get(url, {}, function(html) {
        if (/^ERRO:/.test(html)) {
        	alert(html);
		} else {
            if (/^WARN:/.test(html))
                 alert(html);
            else document.getElementById('alert-container').innerHTML=html;
        }
	});
}

function deleteAlert(user,id) {
	if (!confirm('Confirma apagamento do alerta?')) return;

	document.getElementById('alert-container').innerHTML="<img src=imagens/ajax.gif> momento...";
   	var url = base_url + "backend/alerts.php" + "?action=del&id=" + id + "&user=" + user;
	$.get(url, {}, function(html) {
        if (/^ERRO:/.test(html)) {
        	alert(html);
		} else {
            if (/^WARN:/.test(html))
                 alert(html);
            else document.getElementById('alert-container').innerHTML=html;
        }
	});
}

function editAlert(user,id) {
   	var url = base_url + "backend/alerts.php" + "?action=edit&id=" + id + "&user=" + user;
	$.get(url, {}, function(html) {
        if (/^ERRO:/.test(html)) {
        	alert(html);
		} else {
            if (/^WARN:/.test(html))
                 alert(html);
            else {
				answer = html.split("~");
				frm=document.forms['alert_form'];
				frm.id.value=answer[0];
				setChecked(frm.freq,answer[1]);
				setChecked(frm.type,answer[2]);
				document.getElementById('alert_parameter').style.display=answer[3];
				frm.parameter.value=answer[4];
			}
        }
	});
}

function newAlert(user,frm) {
	document.getElementById('alert-container').innerHTML="<img src=imagens/ajax.gif> momento...";
   	var url = base_url + "backend/alerts.php" + "?action=new&user=" + user + "&id=" + frm.id.value + "&freq=" + getCheckedValue(frm.freq) + "&type=" + getCheckedValue(frm.type) + "&parameter=" + encodeURIComponent(frm.parameter.value) + "&" + Math.random();
   	//var url = base_url + "backend/alerts.php" + "?action=new&user=" + user + "&id=" + frm.id.value + "&freq=" + getCheckedValue(frm.freq) + "&type=" + getCheckedValue(frm.type) + "&parameter=" + frm.parameter.value;

	aux=frm.alert_submit.value;
	frm.alert_submit.value="moento...";
	frm.alert_submit.disabled=true;

	$.get(url, {}, function(html) {
        if (/^ERRO:/.test(html)) {
        	alert(html);
		} else {
            if (/^WARN:/.test(html))
                 alert(html);
            else {
				listAlert(user,1);
			}
        }
		frm.alert_submit.disabled=false;
		frm.alert_submit.value='Criar Alerta';
		document.getElementById('alert_parameter').style.display='none';
		frm.parameter.value='';
		unsetChecked(frm.type);
		unsetChecked(frm.freq);
	});
}


function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}

function unsetChecked(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if (!i) radioObj[i].checked=true; else radioObj[i].checked=false;
}
}

function setChecked(radioObj,set) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if (i==set) radioObj[i].checked=true; else radioObj[i].checked=false;
}
}


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);
}


// Emoticons

var field=null;

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function popicon(text,id)
{
	field=document.getElementById(text);

	pos=findPos(id);	

	document.getElementById('emoticons').style.left=pos[0]+"px";
	document.getElementById('emoticons').style.top=pos[1]+id.height+"px";
	document.getElementById('emoticons').style.display='';
}

function addicon(text)
{
	field.value+=text+" ";
	closeicon();
}

function closeicon()
{
	field=null;
	document.getElementById('emoticons').style.display='none';
}

function popdenuncia(id,user,link,user2)
{
	if (!confirm("Confirma envio de denuncia do comentario?")) return;
 $.ajax({
   type: 'POST',
   url: 'backend/denuncia.php',
   data: 'id='+id+'&user='+user+'&link='+link+'&user2='+user2,
   success: function(msg){
	 if (msg.match("Erro")) alert(msg);
	 else alert("Obrigado pela denuncia!");
   }
 });
}

// Retrieve the rendered height of an element
function getHeight(obj)  {
    var elem = obj;
    var result = 0;
    if (elem.offsetHeight) {
        result = elem.offsetHeight;
    } else if (elem.clip && elem.clip.height) {
        result = elem.clip.height;
    } else if (elem.style && elem.style.pixelHeight) {
        result = elem.style.pixelHeight;
    }
    return parseInt(result);
}

function popvideos(text,id)
{
    field=document.getElementById(text);

	obj=document.getElementById(id);
    pos=findPos(obj);

    //document.getElementById('linkdata').className='';
    //document.getElementById('linkjornada').className='';
    //document.getElementById('linkepoca').className='';
    //document.getElementById('linkclube').className='';
	//obj.className='tabvideos-this';	
	//obj.className='popupselect';	

    //document.getElementById('linkdata').style.color="#000";
    document.getElementById('linkjornada').style.color="#000";
    document.getElementById('linkepoca').style.color="#000";
    document.getElementById('linkclube').style.color="#000";
    //obj.style.color="#FFF";
    //document.getElementById('linkjornada').className='';
    //document.getElementById('linkepoca').className='';
    //document.getElementById('linkclube').className='';

    document.getElementById(text).style.left=pos[0]-5+"px";
    document.getElementById(text).style.top=pos[1]+getHeight(obj)+"px";

    document.getElementById('jornada').style.display='none';
    document.getElementById('epoca').style.display='none';
    document.getElementById('clube').style.display='none';
    document.getElementById(text).style.display='';

	if (document.getElementById("videowindow") != null)
		changeOpac(25,"videowindow");
}


 $("a").click(function(){
   alert("Thanks for visiting!");
 });

/* outclicks */
function clickout(id, url) {
    var url = base_url + "backend/out.php" + "?id=" + id + "&url=" + url + "&" + Math.random();
    $.get(url, {}, function(html) {
        if (/^ERRO:/.test(html)) {
            alert(html);
        } else {
            if (/^WARN:/.test(html))
                 alert(html);
            else {
                answer = html.split("~");
				//location.href=answer[0];
				var newWindow = window.open(answer[0], '_blank');
				newWindow.focus();
            }
        }
    });
}

/* Animation for last votes/last comments */

function animation()
{
    for (f=1;f<=posvote;f++) {
        if (f<=posvote) {
            num=status+f-1;
            if (num>=13) num=13;
            document.getElementById('lastvote'+f).style.backgroundColor=animation_colors[num];
        }
    }

    for (f=1;f<=poscom;f++) {
        if (f<=poscom) {
            num=status+f-1;
            if (num>=13) num=13;
            document.getElementById('lastcom'+f).style.backgroundColor=animation_colors[num];
        }
    }
    delay=150;
    status++;

    if (status<13) animating = setTimeout('animation()',delay);
    else animating=0;
    return true;
}


function get_data()
{
    if (animating>0) clearTimeout(animating);

	myxml=myXMLHttpRequest();
    if (myxml) {
        url="backend/get_votes.php?lastvote="+lastvote+"&lastcom="+lastcom+"&"+Math.random();
        myxml.open ("GET", url, true);
        myxml.send (null);

        myxml.onreadystatechange = function () {
            if (myxml.readyState == 4) {
                results = myxml.responseText;
                res=results.split("~");
                if (res[1]>0) {
                    status=0;
                    lastvote=res[0];
                    posvote=res[1];
                    document.getElementById('lastvotes').innerHTML=res[2];
                    animating = setTimeout('animation()',1000);
                }
                if (res[3]>0) {
                    lastcom=res[3];
                    poscom=res[4];
                    document.getElementById('lastcom').innerHTML=res[5];
                    if (!animating) animating = setTimeout('animation()',1000);
                }
            }
        }
    	temporizador = setTimeout('get_data()',15000);
    }
}


function cmtvalido(id)
{
	if (id.length<4) {
		alert('Comentario deve ter pelo menos 4 caracteres');
		return false;
	}
	if (id.length>2000) {
		alert('Comentario deve ter menos de 2000 caracteres');
		return false;
	}
	return true;
}


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 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 quiz_vote(user,quiz,value) {
    if (xmlhttp=myXMLHttpRequest()) {
        var url = "backend/quiz_vote.php?id=" + quiz + "&user=" + user + "&value=" + value;

        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="<table><tr><td alidn=center><img src=imagens/ajax.gif width=28 height=28 align=absmiddle> momento...</td></tr></table>";
		}

        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4) {
                results = xmlhttp.responseText;
//alert("quiz!"+res[1]);
				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 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 closevote(num,container,votewindow)
{
    name="indy_voto"+num;

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

function closeeurovote(num,container,votewindow)
{
    name="indy_euro"+num;

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


function closevideo(id)
{
    document.getElementById(id).style.display='none';
	if (document.getElementById("videowindow") != null)
		changeOpac(100,"videowindow");
}

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 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";

	if ((IpopTop + document.body.scrollTop)>120)
		divid.style.top=IpopTop + document.body.scrollTop+"px";
	else
		divid.style.top="120px";
}

function shareit(id)
{

	if (document.getElementById('share-'+id).style.display!='none') {
		$('div.share-'+id+':visible').slideUp('');
		return;
	}

	var aux=document.getElementById('share').innerHTML;
	aux=aux.replace('LINKID',id);

	document.getElementById('share-'+id).innerHTML=aux.replace("div.share:","div.share-"+id+":");

	$('div.share-'+id).show('slow').slideDown('slow');
}

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

    if (!frm.senderemail.value.length || !regex.test(frm.senderemail.value)) {
        alert('Email inválido!');
        frm.senderemail.focus();
        return false;
    }

    if (!frm.receiveremail.value.length || !regex.test(frm.receiveremail.value)) {
        alert('Email inválido!');
        frm.receiveremail.focus();
        return false;
    }

	$.get('partilhar.php?id='+id+'&sendername='+frm.sendername.value+'&senderemail='+frm.senderemail.value+'&receivername='+frm.receivername.value+'&receiveremail='+frm.receiveremail.value+'&message='+escape(frm.message.value),'',function(data) { alert(data); $('div.share-'+id+':visible').slideUp(''); });
}


function dimensionar(divs)
{
    var x=0;

    for (var f=0;f<divs.length;f++) {
        var elem = document.getElementById(divs[f]);
        if (!elem) continue;
        var disp=elem.style.display;
        if (disp=='none') {
            elem.style.display='';
            x=elem.offsetHeight;
            elem.style.display='none';
        } else x=elem.offsetHeight;
        if (x>max) max=x;
    }

    //var elem = document.getElementById(divs[0]);
    //if (!elem) return;
    //if (max!=elem.offsetHeight) elem.style.height=max+'px';

    for (f=0;f<divs.length;f++) {
        var elem = document.getElementById(divs[f]);
        if (!elem) continue;
        if (max!=elem.offsetHeight) {
             elem.style.height=max+'px';
        }
    }
}


