var IE=true;
var ElementIsVisible=false;
var objToHide = "";
var visibleObject = "";
var imgBorderText = "";
var imgBorderTitle = "";
var start = false;
var wToComp = 0;
var http_request = false;

if(!document.all || navigator.appName == "Opera")IE=false;
	
function PopNews(page, name, myWidth, myHeight, x, y) {
	popWind=window.open(page,name,"width=" + myWidth + ",height=" + myHeight + ",left=" + x + ",top=" + y + ",screenX=" + x + ",screenY=" + y + ",toolbar=no,status=no,scrollbars=no,location=no,menubar=no,directories=no,resizable=no");
	if(popWind.opener == null) {
		popWind.opener = window;
	}
	else {
		popWind.focus();
	}
	window.opener = popWind;
}

function PopUp(page, myWidth, myHeight) {
	newWind=window.open(page,"popUp","width="+myWidth+",height="+myHeight+",toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,directories=no,resizable=no");
	if(newWind.opener == null) {
		newWind.opener = window;
	}
	else {
		newWind.focus();
	}
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function showFriend(){
	try{document.getElementById("dAmigo").style.display = "block";}catch(e){}
	try{document.getElementById("escreva").style.display = "none";}catch(e){}
	try{document.getElementById("commentas").style.display = "none";}catch(e){}
}

function showWrite(){
	try{document.getElementById("dAmigo").style.display = "none";}catch(e){}
	try{document.getElementById("escreva").style.display = "block";}catch(e){}
	try{document.getElementById("commentas").style.display = "none";}catch(e){}
}

function showComment(){
	try{document.getElementById("dAmigo").style.display = "none";}catch(e){}
	try{document.getElementById("escreva").style.display = "none";}catch(e){}
	try{document.getElementById("commentas").style.display = "block";}catch(e){}
}


function checkform(obj){
	var nameRule = /^\s+|\s+$/i;
	var rules = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

	switch(obj.name){
		case "frmAmigo":
			if (obj.nome.value.replace(nameRule, "") != "" && obj.nomeTo.value.replace(nameRule, "") !=""){
				if(rules.test(obj.emailFrom.value) && rules.test(obj.emailTo.value)){
					return true;
				}else
					alert("Um dos endereços de e-mail não é válído!");
			}else
				alert("Os campos nome, e-mail, nome do destinatário, e-mail do destinatário são obrigatórios!")
			break;
		case "frmNos":
			if (obj.titulo.value.replace(nameRule, "") != "" && obj.texto.value.replace(nameRule, "") !="" && obj.assinatura.value.replace(nameRule, "") !=""){
				if(rules.test(obj.email.value)){
					return true;
				}else
					alert("O endereço de e-mail não é válído!");
			}else
				alert("Todos os campos são obrigatórios!")
			break;
		case "frmComment":
			if (obj.titulo.value.replace(nameRule, "") != "" && obj.texto.value.replace(nameRule, "") !="" && obj.assinatura.value.replace(nameRule, "") !="" && obj.localidade.value.replace(nameRule, "") !=""){
				if(rules.test(obj.email.value)){
					obj.assinatura.disabled = false;
					return true;
				}else
					alert("O endereço de e-mail não é válído!");
			}else
				alert("Todos os campos são obrigatórios!")
			break;
	}
	return false;
}

function validarString(obj){
	var i, r, re, str, atLeast;
	var strArr = new Array();
	str = obj.q.value;
	strArr = str.split(" ");
	str = "";
	atLeast = false;
	for(i=0; i < strArr.length; i++) {
		str += strArr[i] + " ";
		if(strArr[i].length > 2) atLeast = true;
	}
	if(!atLeast) {
		alert("Para realizar uma pesquisa deve escrever pelo menos uma palavra com três caracteres!");
		return false;
	}else{
		return true;
	}
}

function hide(id){
	try{
		for(i=1;i<11;i++){
			var obj = document.getElementById("comentaTexto"+i);
			if(i == id)
				obj.style.display = "block";
			else
				obj.style.display = "none";
		}
	}catch(e){
		return;
	}
}

function go(){
	document.location.reload();
}

function MM_changeProp(objName,x,theProp,theValue) { //v6.0
  var obj = MM_findObj(objName);
  if (obj && (theProp.indexOf("style.")==-1 || obj.style)){
    if (theValue == true || theValue == false)
      eval("obj."+theProp+"="+theValue);
    else eval("obj."+theProp+"='"+theValue+"'");
  }
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function validarSubmit(idCanal, id) {
	var retorno = false;
	var resposta;
	frm = document.forms.frmVotacao;
	if (frm.respostas.checked)
		retorno = true;
	else {
		for (x = 0; x < frm.respostas.length; x++)
			if (frm.respostas[x].checked) {
				retorno = true;
				resposta = frm.respostas[x].value;
			}
	}
	if (retorno == false) {
		alert ("Por favor, selecione uma resposta.");
	}
	else {
		PopUp('http://www.publico.clix.pt/inquerito.asp?idCanal='+idCanal+'&id='+id+'&resposta='+resposta,545,305)
	}
}

function checkAnswer(obj){
	if (obj.respostas.checked)
		retorno = true;
	else {
		for (x = 0; x < obj.respostas.length; x++)
			if (obj.respostas[x].checked) {
				return true;
			}
	}
}


function doPostBAck(){
	MM_changeProp('confirmaInquerito','','style.display','none','DIV');
	PopNews("http://www.publico.clix.pt/inquerito.asp", "Inquerito", 545, 325);
	document.frmVotacao.Votar.disabled = true;
	document.frmVotacao.action="inquerito.asp";
	document.frmVotacao.target="Inquerito";
	document.frmVotacao.submit();
}

function doPostBAck2(id){
	MM_changeProp('confirmaInquerito'+id,'','style.display','none','DIV');
	PopNews("http://www.publico.clix.pt/inquerito.asp", "Inquerito", 545, 325);
	var obj = document.getElementById("frmVotacao"+id);
	obj.Votar.disabled = true;
	obj.action="inquerito.asp";
	obj.target="Inquerito";
	obj.submit();
}

function doPostBAckwScroll(){
	MM_changeProp('confirmaInquerito','','style.display','none','DIV');
	PopNews2("http://www.publico.clix.pt/inquerito.asp", "Inquerito", 545, 325);
	document.frmVotacao.Votar.disabled = true;
	document.frmVotacao.action="inquerito.asp";
	document.frmVotacao.target="Inquerito";
	document.frmVotacao.submit();
}

function PopNews2(page, name, myWidth, myHeight, x, y) {
	popWind=window.open(page,name,"width=" + myWidth + ",height=" + myHeight + ",left=" + x + ",top=" + y + ",screenX=" + x + ",screenY=" + y + ",toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,directories=no,resizable=no");
	if(popWind.opener == null) {
		popWind.opener = window;
	}
	else {
		popWind.focus();
	}
	window.opener = popWind;
}

function aboutSite(){
	//alert("Hello!");
}

//Added by CL06
function mkGETReq(url, parameters) {
	url=url.replace("&amp;", "&");
	parameters=parameters.replace("&amp;", "&");

//	http_request = false;
    if (window.XMLHttpRequest) {
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/html');
         }
    } else if (window.ActiveXObject) {
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
     }
	  if (!http_request) {
         return false;
     } 
	http_request.onreadystatechange = alertContents;
	http_request.open('GET', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
}
function alertContents() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			result = http_request.responseText;
         } else {
         }
	}
}

var timerRefresh = setTimeout("go()", 300000);

function changeSize(obj, value){
	try{
		elements = obj.split(",");
		for(i=0;i<elements.length;i++)
			document.getElementById(elements[i]).style.fontSize = (parseInt(document.getElementById(elements[i]).style.fontSize) + value) + 'px';
	}catch(e){
		//alert(e.description);
	}
}

function changeCommentSize(obj, value){
	var objs = document.getElementsByName(obj)
	try{
		for(i=0;i<objs.length;i++)
			objs[i].style.fontSize = (parseInt(objs[i].style.fontSize) + value) + 'px';
	}catch(e){
		//alert(e.description);
	}
}

function setIncenter(who, where, picSize){
	var objWho = document.getElementById(who);
    var objWhere = document.getElementById(where);

    var whereWidth = objWhere.offsetWidth;
    var whereHeight = objWhere.offsetHeight;

    var pos = getPos(objWhere);
    objWho.style.left = pos.x+(whereWidth/2)-(picSize/2)+'px';
    objWho.style.top = pos.y-(whereHeight/2)-(picSize/2)+'px';
}

function checkEventKey(e, obj){
	if(e.keyCode==13)
		return false;
}

function getPos(anchorname) {
	var coord = new Object();
	var x=0;
	var y=0;
	var isElement = false;
	var sLayer = false;
	if (document.getElementById || document.all){ 
		isElement = true; 
	}else if (document.layers){ 
		sLayer = true; 
	}

	if (isElement){
		x = getPosLeft(anchorname);
		y = getPosTop(anchorname);
		h = anchorname.offsetHeight;
		y += h;
	}else if (sLayer){
		var found=0;
		for (var i=0; i<document.anchors.length; i++) {
			if (document.anchors[i].name == anchorname) {
				found=1;
				break;
			}
		}
		if (found == 0) {
			coord.x=0; coord.y=0; return coord;
		}
		x = document.anchors[i].x;
		y = document.anchors[i].y;
	}else{
		x = 0;
		y = 0;
	}
	coord.x = x;
	coord.y = y;
	return coord;
}

function getPosLeft (el) {
	pos = el.offsetLeft;
	while ((el = el.offsetParent) != null)
		pos += el.offsetLeft; 
	return pos;
}

function getPosTop (el) {
	pos = el.offsetTop;
	while((el = el.offsetParent) != null)
		pos += el.offsetTop; 
	return pos;
}

function showImage(src, imgIDContainer){
	//var Dialog  = document.getElementById("dialog")
	//Dialog.style.display='block';
	//Dialog.style.height = document.body.clientHeight + "px";
	//Dialog.style.width = document.body.clientWidth + "px";
	wToComp = 0;
	showObjectInMiddle("TableImages");
	//var Element = document.getElementById("TableImages");
	//Element.style.display='block';
	//setElementPos("TableImages");
	loadImage(src, "TableImages", imgIDContainer);
	if(objToHide!='')workObject(objToHide,'hidden');
	clearTimeout(timerRefresh);
}

function loadImage(url, target, imgIDContainer) 
{
	target = document.getElementById(target);
	var myImg = new Image();
	myImg.style.visibility = "hidden";
	myImg.onload = function()
	{	
		document.getElementById(imgIDContainer).src = myImg.src;
		target.style.height = document.getElementById("TableComImagem").offsetHeight+"px"; //myImg.height+"px";
		target.style.width = document.getElementById("TableComImagem").offsetWidth+"px"; //myImg.width+"px";
		document.getElementById("imageContainer").style.height= myImg.height+"px";
		//setElementPos(target);
		showObjectInMiddle("TableImages");
		setTimeout("recall()",1000)
	}
	myImg.onerror = function(){hideME();}
	myImg.onabort = function(){hideME();}
	myImg.src = url;
}

function recall(){
	showObjectInMiddle("TableImages");
}

function hideME(){
	var Element = document.getElementById("TableImages");
	Element.style.display = 'none';
	//Element.style.backgroundImage = "";
	//document.getElementById('imgLoading').style.display='block';
	setElementPos("TableImages");
	document.getElementById("dialog").style.display = 'none';
	ElementIsVisible = false;
	if(objToHide!='')workObject(objToHide,'hidden');
	var timerRefresh = setTimeout("go()", 300000);
}

function alignDiv(){
	//if(ElementIsVisible)
		//setElementPos(document.getElementById("TableImages"));
	if(visibleObject!='')
		showObjectInMiddle(visibleObject);
}

function keyPressHandler(e) {
	var kC  = (window.event) ? event.keyCode : e.keyCode;
	var Esc = (window.event) ? 27 : e.DOM_VK_ESCAPE;
	if(kC==Esc)
    	if (ElementIsVisible)
    		hideME();
    	if (visibleObject!="")
    		hideObject();
}

function workObject(hidObject,what){
	var objs = hidObject.split(',');
	for(i=0;i<objs.length-1;i++)
		try{document.getElementById(objs[i]).style.visibility=what;}catch(e){};
}

function doRefresh(){
	timerRefresh = setTimeout("go()", 300000);	
}

function endRequest( sender, e ) {
    if( e.get_error() ){
        alert("NÃ£o foi possÃ­vel efectuar o seu pedido.\nPor favor tente de novo");
        e.set_errorHandled( true );
    }
}

function changeFont(what, to){
	if(what=='Title'){
		document.getElementById('title').style.fontFamily = to;
		document.getElementById('title1').style.fontFamily = to;	
	}else{
		document.getElementById('Text').style.fontFamily = to;
		document.getElementById('Text1').style.fontFamily = to;		
		document.getElementById('link').style.fontFamily = to;
		document.getElementById('link1').style.fontFamily = to;
	}
}

function changeColor(what, to){
	if(what=='Title'){
		document.getElementById('title').style.color = to;
		document.getElementById('title1').style.color = to;
		document.getElementById('link').style.color = to;
		document.getElementById('link1').style.color = to;
	}else{
		document.getElementById('Text').style.color = to;
		document.getElementById('Text1').style.color = to;		
	}
}

function showObjectInMiddle(who){
	if(start){
		var wHeigth = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight;
		if(objToHide!='')workObject(objToHide,'hidden');
		document.getElementById(who).style.visible = 'hidden';
		document.getElementById(who).style.display = 'block';

		var Dialog  = document.getElementById("dialog")
		Dialog.style.display='block';
		Dialog.style.height = document.body.clientHeight>= wHeigth ? document.body.clientHeight + "px" : wHeigth + "px";
		
		if(document.body.clientWidth>990)
			Dialog.style.width = document.body.clientWidth + "px";
		else
			Dialog.style.width = "994px";
		setInMiddleOfPage(who)
		visibleObject = who;	
		document.getElementById(who).style.visible = '';
		return true;
	}else
		return false;
}

function setElementPos(Element){
	var Dialog  = document.getElementById("dialog")
	Dialog.style.display='block';
	Dialog.style.height = document.body.clientHeight + "px";
	
	if(document.body.clientWidth>990)
		Dialog.style.width = document.body.clientWidth + "px";
	else
		Dialog.style.width = "994px";
		
	var Element = document.getElementById("TableImages");
	objh = parseFloat(Element.style.height)/2;
	objw = parseFloat(Element.style.width)/2+40;
	
	sTop = document.body.scrollTop || document.documentElement.scrollTop;
	if(IE)
		Element.style.top = (document.documentElement.offsetHeight/2 - objh) + (sTop-100) + "px";
	else
		Element.style.top = window.innerHeight/2 - objh + (sTop-100) +  "px";
				
	Element.style.left = Math.floor( Math.round( ( document.documentElement.offsetWidth/2 ) + document.body.scrollLeft ) - objw ) + 'px';		
	ElementIsVisible=true;
}

function setInMiddleOfPage(who){		
	var Element = document.getElementById(who);
	
	objh = parseFloat(Element.offsetHeight)/2;
	objw = parseFloat(Element.offsetWidth)/2+wToComp;
	
	sTop = document.body.scrollTop || document.documentElement.scrollTop;
	if(IE)
		Element.style.top = (document.documentElement.offsetHeight/2 - objh) + (sTop) + "px";
	else
		Element.style.top = window.innerHeight/2 - objh + (sTop) +  "px";
				
	Element.style.left = Math.floor( Math.round( ( document.documentElement.offsetWidth/2 ) + document.body.scrollLeft ) - objw ) + 'px';		
}

function hideObject(){
	if (visibleObject != ""){
		var Element = document.getElementById(visibleObject);
		Element.style.display = 'none';
		//setElementPos("TableImages");
		document.getElementById("dialog").style.display = 'none';
		visibleObject = "";
		if(objToHide!='')workObject(objToHide,'');
		var timerRefresh = setTimeout("go()", 300000);
	}
	wToComp = 0;
}

function changeBorderText(obj, tipo){
	selectedObj = eval("imgBorder"+tipo);
	if (selectedObj!=""){
		document.getElementById(selectedObj).style.borderColor = "";
		document.getElementById(selectedObj).style.borderWidth = "0";
	}
	obj.style.borderColor='red';
	obj.style.borderWidth=2;
	if(tipo=='Title')
		imgBorderTitle = obj.id;
	else
		imgBorderText = obj.id;
}

function checkPosFromObject(){
/*	var scrollSize;
	if (navigator.appName == "Microsoft Internet Explorer")
		scrollSize = document.body.scrollTop || document.documentElement.scrollTop;
	else
		scrollSize = window.pageYOffset;
	try{
		var windowSize = document.body.clientHeight<document.documentElement.clientHeight ? document.body.clientHeight : document.documentElement.clientHeight;
		if (windowSize+scrollSize >= document.getElementById(objName).offsetTop){
			var myImg = new Image();
			myImg.style.visibility = "hidden";
			myImg.src = "http://195.23.4.85/teste.asp";
		}else
	    	setTimeout('checkPosFromObject()', 500);
	}catch(e){}*/
}

function checkMaxLength(obj, maxSize){
	if(obj.value.length>maxSize)
		obj.value = obj.value.substring(0, maxSize);
	document.getElementById("actualN").innerHTML = maxSize-obj.value.length;
}

function setCounter(id, Origin, type, section, title) {
    if (!isNaN(id)) {
        if (!document.getElementById("statPic")) {
            var pic1 = new Image(1, 1);
            pic1.id = "statPic";
        }else{
		var pic1 = document.getElementById("statPic");
	}
        var params = "&id=" + id + "&Origin=" + Origin + "&type=" + type + "&section=" + section + "&title=" + title + "&url=" + escape(document.location.href);
        pic1.src = "http://www.publico.clix.pt/includes/lib/statistics.aspx?" + params;
    }
}
