var dp_char=".";
var ie=typeof(document.all)!="undefined";
var rsite_htmlElement=typeof(Element)!="undefined";

function padLeft(o,p,n) {
	o=""+o;
	while(o.length<n) o=p+o;
	return o;
}

function putClass(target,cn) {if (target.className.indexOf(cn)==-1) target.className+=" "+cn;}
function remClass(target,cn) {target.className=target.className.split(cn).join("");}

function format_ncd(src,ncd) {
	var n=parseFloat(src);
	if (isNaN(n)) n=0;
	src=""+n;
	var pt=src.indexOf(dp_char);//check for decimal point
	//alert(pt+src+1);
	if (pt==-1) {//had no decimal point
		src+=dp_char;
		pt=src.indexOf(dp_char);
	}
	while((pt+ncd+1)>src.length) src+="0";//add zeroes while needed
	src=src.substr(0,pt+ncd+1);//truncate if needed
	return src;
}

function format_euros(src) {return format_ncd(src,2)+" €";}

function format_data(d) {
	return ""+d.getFullYear()+"/"+padLeft(d.getMonth()+1,"0",2)+"/"+padLeft(d.getDate(),"0",2);
}

function getPosition(o,e) {return getPos(o,[0,0],e);}
function getPos(o,p,element) {
	if (!element) alert("RS-DEBUG utils.js, no element given");
	if (o==element.capImg.offsetParent) return p;
	p[0]+=o.offsetLeft;
	p[1]+=o.offsetTop;
	if (o.offsetParent) {
		//alert((o.offsetParent)+": "+o.offsetParent.tagName);
		p=getPos(o.offsetParent,p);
	}
	return p;
}

function getScrollingPosition()
{
	position = [
		document.body.scrollLeft,
		document.body.scrollTop
	];
	return position;
}

/*function posItem(foto,p) {
	//alert('posItem');
	//foto.filters[0].apply();
	var s=getScrollingPosition();
	foto.style.left=window.event.x+p[0]+s[0];
	foto.style.top=window.event.y+p[1]+s[1];
	foto.style.display='block';
	foto.style.visibility='visible';
	//foto.filters[0].play();
	//window.status=window.event.y;
}*/
function posItem(foto,p) {
	//alert('posItem');
	//foto.filters[0].apply();
	var s=getScrollingPosition();
	foto.style.left=window.event.x+p[0]+s[0];
	foto.style.top=window.event.y+p[1]+s[1];
	foto.style.display='block';
	foto.style.visibility='visible';
	//foto.filters[0].play();
	//window.status=window.event.y;
}

function scanDown(o) {
	if (o) {
		/*for(var i=o.firstChild;i;i=i.nextSibling) {
			switch(i.className) {
            case "protoblock":
				info_pane.innerHTML+="<hr/>PROTOTYPE"+i.innerHTML;
				//i.style.display="none";
				break;
			case "ctrlbox":
				info_pane.innerHTML+="<hr/>CTRLBOX"+i.innerHTML;
				//i.style.display="none";
				break;
			}
		}*/
		if (o.genCfg) {
			try {
				//alert(""+o+": "+o.tagName+" "+o.className);
				var p=document.getElementById("info_pane");
				if (p) p.innerHTML+=o.genCfg();
			} catch(e) {
				alert("genCfg block, utils.js: "+e.message);
				throw(e);
			}
		}
		//if (typeof(o.prentNode!="undefined"))
		scanDown(o.parentNode);
	}
}

function setClass(o,c) {
	o.className=c+(c==""?"":" regular")+" zz_mcbfix";
	if (o.mountBehaviors) o.mountBehaviors();
}

function imgClick(o) {
	//alert("imgClick! ");
	//alert(o.name+"->"+site.getNode(o.name).text);
	//o.document.create
	if (editing&&o.className.indexOf("inpress_img_uponclick")!=-1) {
		tempSelection=document.body.createControlRange();
		tempSelection.add(o);
		tempSelection.select();
		if (piclib_toolbar.style.display=="none") togPicLib();
	} else {
                //alert(o.src);
		if (ie)
			fotoView(site.getNode(o.name).text,'Foto');
		else {
                    if (o.src.indexOf("img.php")!=-1) {//simply open the file, FF and GCh dont respect content type
                        var src=o.src.substr(o.src.indexOf("img=")+4);
                        if (src.indexOf("&")!=-1)
                            src=src.substr(0,src.indexOf("&"));
                        //alert(src);
                        window.open("/"+src);
                    } else
                        window.open(o.src);
                }
	}
}

function delLibImg(id) {
	if (confirm("Apagar esta imagem da livraria?"))
		navigate("imgDel.asp?img=/pic_lib/img[@id='"+id+"']","_self");
}

function fotoView(i,title) {
	//alert("fotoView "+i);
	if(!title) title="";
	var info=site.imgInfo(i);
	//alert(""+info.xml);
	var x=parseInt(info.selectSingleNode("//x").text);
	var y=parseInt(info.selectSingleNode("//y").text);
	var scr="0";
    if (x>777||y>577) {
        y+=18;
        x+=18;
        scr="1";
    }
	//alert(x+","+y);
	window.open(auxPath+'/site/imgView.asp?title='+title+'&amp;src='+i,'_blank','width='+x+' height='+y+' toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars='+scr+',resizable=0')
}

function fotoPrint(i,title) {
	//alert("printing "+i);
	if(!title) title="image preview/print";
	var info=site.imgInfo(i);
	//alert(""+info.xml);
	var x=parseInt(info.selectSingleNode("//x").text);
	var y=25+parseInt(info.selectSingleNode("//y").text);
	var scrl=x>600||y>400;
	if (scrl) {x+=20;y+=20;}
	x+=10;y+=4;
	//alert(x+","+y);
	window.open(auxPath+'/site/imgPrint.asp?title='+title+'&amp;src=../'+i,'_blank','width='+x+' height='+y+' toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars='+(scrl?'1':'0')+',resizable=0')
}

function makeNode(text) {
	var doc;
	if (window.ActiveXObject) {
		doc=new ActiveXObject("Microsoft.XMLDOM");
		doc.async="false";
		doc.loadXML(text);
	} else {// code for Mozilla, Firefox, Opera, etc.
		var parser=new DOMParser();
		doc=parser.parseFromString(text,"text/xml");
	}// documentElement always represents the root node
	return doc.documentElement;
}

function togDisplay(element) {if (!ie) element.style.display=element.style.display=='none'?'':'none';}

//isto porque necessitamos de varias funções a executar no 'page onload'
var startups=new Array();
//aqui avaliamos um array de 'onloads' concorrentes
function pageStart() {
    //montras();
    for(s in startups)
        try {
            if (typeof(startups[s])=="string") eval(startups[s])
            else startups[s]();
        } catch(e) {
            if (editing) {
                alert("ERRO: "+e+" \nin "+typeof(startups[s])+" \n"+startups[s]);
                throw(e);
            }
        }
}

function togBody(o) {
    //alert((!ie)&&o&&o.lastChild&&o.lastChild.previousSibling);
    if (!ie&&o&&o.lastChild&&o.lastChild.previousSibling) {
        var t=o.lastChild.previousSibling;
        //alert(t);
        t.style.display=(t.style.display=='none'?'':'none');
    }
}

//scroller helpper functions --------------------------------------------------------------
	document.onmousemove = getMouseXY;
	var mouse_x=0;
	var mouse_y=0;

	function getx(e) {
		var left = 0;

		if (e.offsetParent) {
			while (e.offsetParent) {
				left += e.offsetLeft
				e = e.offsetParent;
			}
		} else if (e.x)
			left += e.x;

		return left;
	}

	function gety(e) {
		var top = 0;

		if (e.offsetParent) {
			while (e.offsetParent) {
				top += e.offsetTop
				e = e.offsetParent;
			}
		} else if (e.y)
			top += e.y;

		return top;
	}

	function getMouseXY(m){
		//window.status="getMouseXY(m)";
		if (!document.bopdy) return;

  		if (ie)	{
			 var tmpX = event.clientX;
  			 var tmpY = event.clientY;
			}
 		else 	{
  			 var tmpX = m.pageX;
			 var tmpY = m.pageY;
  			}
		if (!document.body.scrollTop)
			{
			 var l = document.documentElement.scrollLeft;
			 var t = document.documentElement.scrollTop;
			}
		else 	{
			 var l = document.body.scrollLeft;
			 var t = document.body.scrollTop;
			}
		mouse_x=tmpX + l;
		mouse_y=tmpY + t;
		return {"x":mouse_x,"y":mouse_y};
  	}


function hscroller(o) {
	o.behavior='scroll';
	window.status='';
	var p=(o.clientWidth/2-(mouse_x-getx(o)))/10;
	//window.status=getx(o);
	if (p>0) {
		o.direction="right";
		o.scrollAmount=p;
	} else {
		o.direction="left";
		o.scrollAmount=-p;
	}
}

//css type multiplexer - TODO, improve this method to gain better CSS support
function cssMatch(o,sel) {
	//alert("cssMatch "+o.nodeName+" is \""+sel+"\"");
	if (!o) return false;
	switch(sel.substr(0,1)) {
	case ".":
				return o.className&&o.className.indexOf(sel.substr(1))!=-1;
				break;
	case "#":
				return o.id&&o.id==sel.substr(1);
				break;
	default:
				return o.nodeName==sel.toUpperCase();
	}
}

//css space delimiter multiplexer
//trace this element and ancestors against css selector
//returns first match or null
//if fn is given fn is called for every match and search goes on <-- is this usefull?
//if self is true, the first element MUST match the clause <-- this is uselful when forward-walking a search with this tracer as criteria, avoids double hit
function cssTrace(o,sel,fn,self) {
	if (!o) return null;
	var s=sel.split(" ");
	var c=s.pop();
	if (cssMatch(o,c)) {
		if (s.length==0) {
				if (fn) fn(o);
				return o;
		} else
				return cssTrace(o,s.join(" "),fn,false)?o:null;
	} else {
		//alert("no match here... downfall")
		if (self) return null;
		return cssTrace(o.parentNode,sel,fn,false);
	}
}



//make chrome, safari, firefox xpath compatible with IE, NOT TESTED YET
if (!ie) {
	if (!Element.prototype.selectSingleNode)
		Element.prototype.selectSingleNode = function (sXPath) {
			var oEvaluator = new XPathEvaluator();
			var oResult = oEvaluator.evaluate(sXPath, this, null,
				XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			if (oResult != null) {
				return oResult.singleNodeValue;
			} else {
				return null;
			}
		}

	if (!Element.prototype.selectNodes)
		Element.prototype.selectNodes = function (sXPath) {
			var oEvaluator = new XPathEvaluator();
			var oResult = oEvaluator.evaluate(sXPath, this, null,
				XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
			var aNodes = new Array;
			if (oResult != null) {
				var oElement = oResult.iterateNext();
				while(oElement) {
					aNodes.push(oElement);
					oElement = oResult.iterateNext();
				}
			}
			return aNodes;
		};
		//alert("->"+document.selectSingleNode("//*[contains(@class,'inpress_content')]"));
}

//rsite function chaining
if (rsite_htmlElement) {
	//overlarp given function with this, IE8, Chrome, FF
	//suportada no IE8 em strict mode
	Function.prototype.overlap=function(fn) {
		var t=this;
		return fn?function() {
				t(arguments);
				fn(arguments);
		}:t;
	}

	//chain this function after given fn
	Function.prototype.chain=function(fn) {
		var t=this;
		return fn?function() {//function passed by value!!!! so this is not working
				fn(arguments);
				t(arguments);
		}:t;
	}
} else {
	//overlarp given function with this
	Function.prototype.overlap=function(fn) {
		var t=this;
		return fn?function() {
					t(arguments[0],arguments[2],arguments[3],arguments[3],arguments[4],arguments[5],arguments[6],arguments[7],arguments[8],arguments[9]);
					fn(arguments[0],arguments[2],arguments[3],arguments[3],arguments[4],arguments[5],arguments[6],arguments[7],arguments[8],arguments[9]);
		}:t;
	}

	//chain this function after given
	Function.prototype.chain=function(fn) {
		var t=this;
		return fn?function() {
					fn(arguments[0],arguments[2],arguments[3],arguments[3],arguments[4],arguments[5],arguments[6],arguments[7],arguments[8],arguments[9]);
					t(arguments[0],arguments[2],arguments[3],arguments[3],arguments[4],arguments[5],arguments[6],arguments[7],arguments[8],arguments[9]);
		}:t;
	}
}


