// JavaScript Document

/*********************************************************************
* Desc: Cookie Functions
* Author: wtavares
*********************************************************************/

// Cookies Methods
function setCookie(name, value, minutes, path, domain, secure) {
	var curCookie = name + "=" + escape(value) + ((minutes)?(";expires=" + ((new Date((new Date()).getTime() + parseInt(minutes)*60000)).toGMTString())):"") + ((path)?";path=" + path:"") + ((domain)?";domain=" + domain:"") + ((secure)?";secure":"");
	document.cookie = curCookie;
}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
	begin = dc.indexOf(prefix);
			if (begin != 0) return null;
	} else { begin += 2 }
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) { end = dc.length; }
	return unescape(dc.substring(begin + prefix.length, end));
}

/*********************************************************************
* Desc: Window Function
* Author: Rafael
*********************************************************************/

function floatbox(tit, msg, argWidth, argHeight) {
	box_floatbox = document.getElementById('floatbox');
	box_titulo = document.getElementById('floatbox_titulo');
	box_mensagem = document.getElementById('floatbox_mensagem');
    
    if(box_floatbox.style.display != 'block') {
		box_floatbox.style.display = 'block';
	}
    
	box_titulo.innerHTML = tit;
	box_mensagem.innerHTML = msg;
    
    if(argWidth){
        box_floatbox.width = argWidth+15;
        box_floatbox.style.width = argWidth+15+'px';
    }
	
	if(argHeight){
        box_mensagem.height = argHeight+15;
        box_mensagem.style.height = argHeight+15+'px';
    }
	
    xMoveTo(box_floatbox, 300, 100);
}

function fecha(div_id) {
	box = document.getElementById(div_id);
	box.style.display = 'none';
}

/*********************************************************************
* Desc: Filter Functions
* Author: wtavares
*********************************************************************/


/**
* DE QUEM Ë ESSA PORRA ??????????
**/
refresh_item = new Array();
function refreshPortlets() {
	for(i=0; i<refresh_item.length; i++) {
		refresh_item[i]();
	}
}

function toggleToolBox() {
	objTB = document.getElementById('toolbox');
	if (getCookie('toolbar') == 1) {
		objTB.style.display = 'none';
		mainReposition();
		setCookie('toolbar',"0",null,"/","","");
	} else {
		objTB.style.display = 'block';
		mainReposition();
		setCookie('toolbar',"1",null,"/","","");
	}
}

function mainReposition(){
	objTB = document.getElementById('toolbox');
	objMain = document.getElementById('main');
	objHeader = document.getElementById('header');
	objFooter = document.getElementById('footer');
	//objTB.style.top = xHeight(objHeader)+"px";
	//objMain.style.top = (xHeight(objHeader)+xHeight(objTB))+"px";
	//objFooter.style.top = (xHeight(objHeader)+xHeight(objTB)+xHeight(objMain))+"px";
}

function togleToolBox_copy() {
	id =  'toolbox';
	objTB = document.getElementById(id);
	if (getCookie('toolbar') == 1) {
//		xSlideTo(objTB, xLeft(objTB), 0, 150);
		objTB.style.visibility = 'hidden';
		objTB.style.position = 'absolute';
		setCookie('toolbar',"0",null,"/","","");
	} else {
		objTB.style.visibility = 'visible';
		objTB.style.position = 'relative';
//		xSlideTo(objTB, xLeft(objTB), 40, 500);
		setCookie('toolbar',"1",null,"/","","");
	}
}

function clearFilter() {
	arrElms = xGetElementsByClassName('display_button_selected');
	var url="?a=open:Filter:clearFilter,closeAfter&template=hollow";
	var xml = GetXmlHttpObject(
		function() {
			for (i=0; i<arrElms.length;i++) {
				arrElms[i].className = 'display_button';
			}            
            refreshPortlets();
		}
	);
	xml.open("GET", url , true);
	xml.send(null);	
	
    objFilter.clearETRList();
}

function loadBtnState() {
	arr = [['btnTests','boxTests'],
		   ['btnAccess','boxAccess'],
		   ['btnDate','boxDate'],
		   ['btnService','boxService'],
		   ['btnRegion','boxRegion'],
		   ['btnTestName','boxTestName'],
		   ['btnETR','boxETR']
           ];
	for (var i=0;i<arr.length;i++) {
		objElmt = document.getElementById(arr[i][1]);
		objBtn = document.getElementById(arr[i][0]);
		if (getCookie(arr[i][1]) == 1) {
			xShow(arr[i][1]);
			objElmt.style.position = 'relative';
			objBtn.className = 'button_disabled';
		}
	}		

	objTB = document.getElementById('toolbox');
	if (getCookie('toolbar') != 1) {
		objTB.style.visibility = 'hidden';
		objTB.style.position = 'absolute';
	} else {
		objTB.style.visibility = 'visible';
		objTB.style.position = 'relative';
	}
}
function loadBtnState2() {
	arr = [['btnTests','boxTests'],
		   ['btnAccess','boxAccess'],
		   ['btnDate','boxDate'],
		   ['btnTestName','boxTestName'],		   
		   ['btnService','boxService'],
		   ['btnRegion','boxRegion'],
		   ['btnETR','boxETR']];
	for (var i=0;i<arr.length;i++) {
		objElmt = document.getElementById(arr[i][1]);
		objBtn = document.getElementById(arr[i][0]);
		if (getCookie(arr[i][1]) == 1) {
//			xShow(arr[i][1]);
			objElmt.style.display = "inline";
			objElmt.style.position = 'relative';
			objBtn.className = 'button_disabled';
		}
	}
	objTB = document.getElementById('toolbox');
	objMain = document.getElementById('main');
	objHeader = document.getElementById('header');
	if (getCookie('toolbar') != 1) {
		objTB.style.display = 'none';
//		objTB.style.position = 'absolute';
		mainReposition();
	} else {
		objTB.style.display = 'block';
		mainReposition();
	}	
}

function setDateSessStart(cal, dt) {
	objLbl = document.getElementById('btnDateStart');
	objFld = document.getElementById('dtStart');
	objFld.value = dt;
	setFilterParamenter('dt_start', objFld.value, objLbl, 1)
//	cal.hide();
}

function unsetDateSessStart() {
	objLbl = document.getElementById('btnDateStart');
	document.getElementById('dtStart').value = '';
	setFilterParamenter('dt_start', 0, objLbl, 0)
	return;
}

function setDateStart(elmt) {
	objFld = document.getElementById('dtStart');
	if (!objFld.value) {
		objCalendarStart.showAtElement(elmt, 'Br');
	} else {
		unsetDateSessStart();
	}
}

function setDateSessEnd(cal, dt) {
	objLbl = document.getElementById('btnDateEnd');
	objFld = document.getElementById('dtEnd');
	objFld.value = dt;
	setFilterParamenter('dt_end', objFld.value, objLbl, 1)
//	cal.hide();
}

function unsetDateSessEnd() {
	objLbl = document.getElementById('btnDateEnd');
	document.getElementById('dtEnd').value = '';
	setFilterParamenter('dt_end', 0, objLbl, 0)
	return;
}

function setDateEnd(elmt1) {
	objFld = document.getElementById('dtEnd');
	if (!objFld.value) {
		objCalendarEnd.showAtElement(elmt1, 'Br');
	} else {
		unsetDateSessEnd();
	}
}	



function setFilterParamenter(type, value, elmt, chk, tp) {
	//Check button state to set the action to send (enable or disable param)
	
	if (tp!=3) {
		if (elmt && elmt.className=='display_button_selected') {
			chk = 0;	
		} else if(elmt){
			chk = 1;
		}
	} else {
		if (!value && elmt.className=='display_button_selected') {
			chk = 0;	
		} else if(elmt){
			chk = 1;
		}		
	}

	// if type of button is 1 set diferents values
	if (tp==1) {  // POG
		var fldOnline = document.getElementById("fldOnline");
		vOnline = fldOnline.value;
		if (vOnline=="1") {
			vOnline = 0;
			chkOnline = 0;
			fldOnline.value = 0;
			chk =1;
		} else {
			vOnline = 1;
			chkOnline = 1;
			fldOnline.value = 1;			
			chk =0;
		}
		var prmString = "'"+type+"':'"+vOnline+"':'"+chkOnline+"'";
		var classOff 	= 'button';
		var classOn 	= 'button_disabled';
	} else if (tp==2) {  // POG
		var fldOwner = document.getElementById("fldOwner");
		vOwner = fldOwner.value;
		if (vOwner=="1") {
			vOwner = 0;
			chkOwner = 0;
			fldOwner.value = 0;
			chk =1;
		} else {
			vOwner = 1;
			chkOwner = 1;
			fldOwner.value = 1;			
			chk =0;
		}
		var prmString = "'"+type+"':'"+vOwner+"':'"+chkOwner+"'";
		var classOff 	= 'button';
		var classOn 	= 'button_disabled';
	} else { 
		var prmString = "'"+type+"':'"+value+"':'"+chk+"'";
		var classOff 	= 'display_button';
		var classOn 	= 'display_button_selected';
	}

	//Set query string
	var url="?a=open:Filter:setFilterParameter:"+prmString+",closeAfter&template=hollow";
	var xml = GetXmlHttpObject(
		function() {
			try { // if the response not yet come, try until it comes. Yep its a POG
				var chkRem = xml.responseText;
			} catch (e) {}

			//Handle the server side return
			if (elmt && chkRem=="1") {
				elmt.className = classOn;
			} else if(elmt){
				elmt.className = classOff;
			}
		}
	);
	xml.open("GET", url , true);
	xml.send(null);
}
	
function showFilterBox(id, btn) {
	objElmt = document.getElementById(id);
	objBtn = document.getElementById(btn);
	act = objElmt.style.visibility;		
	if (act=='hidden') {
		xShow(id);
		objElmt.style.position = 'relative';
		objBtn.className = 'button_disabled';
		setCookie(id,"1",null,"/","","");
	} else {
		xHide(id);
		objElmt.style.position = 'absolute';
		objBtn.className = 'button';			
		setCookie(id,"0",null,"/","","");
	}

}

function showFilterBox2(id, btn) {
	objElmt = document.getElementById(id);
	objBtn = document.getElementById(btn);
	act = objElmt.style.display;		
	if (act=='none') {
//		xShow(id);
		objElmt.style.display = 'inline';
//		objElmt.style.position = 'relative';
		objBtn.className = 'button_disabled';
		setCookie(id,"1",null,"/","","");
		mainReposition();
	} else {
//		xHide(id);
		objElmt.style.display = 'none';
//		objElmt.style.position = 'absolute';
		objBtn.className = 'button';			
		setCookie(id,"0",null,"/","","");
		mainReposition();
	}

}


/*********************************************************************
* Desc: Misc Functions
* Author: wtavares
*********************************************************************/


function URLEncode( plaintext )  //Referência:       http://www.albionresearch.com/misc/urlencode.php
{
    plaintext = plaintext+"";
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	//var plaintext = document.URLForm.F1.value;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function URLDecode( encoded )  //Referência:       http://www.albionresearch.com/misc/urlencode.php
{
    encoded = encoded+"";
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   //var encoded = document.URLForm.F2.value;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};

function loading(bool) {
	document.getElementById('div_load').style.visibility = bool ? 'visible' : 'hidden';
}


/*********************************************************************
* Desc: xml cross-browser XPath function
* Author: Internet
*********************************************************************/
function xPath(oNodes, sXPath){
    /*
    xPath function by Charles Toepfer: toepfer_c@hotmail.com 
    use: 'resulting xml dom' = xPath('xml dom object', 'xpath string');
    */
    if(oNodes){
        if(window.XMLHttpRequest){ 
            try{
                var oXpe = new XPathEvaluator();
                var oNsResolver = oXpe.createNSResolver(oNodes.ownerDocument == null ? oNodes.documentElement : oNodes.ownerDocument.documentElement);
                var oResult = oXpe.evaluate(sXPath, oNodes, oNsResolver, 0, null);
                var aFound = [];
                var oRes;
                while (oRes = oResult.iterateNext()){
                    aFound.push(oRes);
                }
                return aFound;
            }catch (e){
                alert(e.description);
            }
        }else{
            try{
                oNodes.setProperty ("SelectionLanguage", "XPath")
                var oSelectedNode = oNodes.documentElement.selectNodes(sXPath);
                return oSelectedNode;
            }catch(e){
                alert(e.description);
            }
        }
    }
}





/*** Animated Window Box ***/

winBox = new Array();
function showFloatBox(box_id, w, h) {
	
	if (!box_id) { return false; }
	
	var varBoxId = box_id;
	var varStartTop = 50;
	var varStartLeft = 50;
	var varTargetTop = 100;
	var varTargetLeft = 600;
	var varStartWidth = 20;
	var varStartHeight = 20;
	var varTargetWidth = w;
	var varTargetHeight = h;
	var objAnim = new xAnimation(varBoxId);

	//Set Position
	xMoveTo(varBoxId, varStartTop, varStartLeft);
	xResizeTo(varBoxId, varStartWidth, varStartHeight);	
	xZIndex(varBoxId, 200);

	//Set sequence animation
	var seqFloatBox = new xSequence([
		[0, xDisplay, [varBoxId, 'block'] ],
		[0, xMoveTo, [varBoxId+'Resize', varTargetWidth-xWidth(varBoxId+'Resize')-15, varTargetHeight-xHeight(varBoxId+'Resize')-15] ],		
		[0, xMoveTo, [varBoxId+'Maximize', varTargetWidth-xWidth(varBoxId+'Maximize')-15, 0] ],				
		[0, xMoveTo, [varBoxId+'Close', varTargetWidth-(xWidth(varBoxId+'Maximize')+xWidth(varBoxId+'Close')+34), 0] ],						
		[500, xSlideTo, [varBoxId, varTargetLeft, varTargetTop, 500] ],
		[700, xAniSize, [objAnim, varStartWidth, varTargetHeight, 500, 2] ],
		[700, xAniSize, [objAnim, varTargetWidth, varTargetHeight, 500, 2] ],
		[-1, null, null]
	]);
	//do the animation
	seqFloatBox.run();
	winBox[varBoxId] = new xFenster(varBoxId, varStartTop, varStartLeft, varBoxId+'Bar', varBoxId+'Resize', varBoxId+'Maximize');

}

function hideFloatBox(box_id) {

	if (!box_id) { return; }
	var varBoxId = box_id;
	
	var visibility = 'visible';	
	
	if (!winBox[varBoxId]) { return; }

	var varBoxId = box_id;
	var varStartTop = 50;
	var varStartLeft = 50;
	var varTargetTop = 210;
	var varTargetLeft = 330;
	var varStartWidth = 20;
	var varStartHeight = 20;
	var varTargetWidth = xWidth(varBoxId);
	var varTargetHeight = xHeight(varBoxId);
	var objAnim = new xAnimation(varBoxId);


	//Set sequence animation
	var seqFloatBox = new xSequence([
		[0, xSlideTo, [varBoxId, varTargetLeft, varTargetTop, 500]],
		[500, xAniSize, [objAnim, varStartWidth, varTargetHeight, 500, 2] ],								 
		[500, xAniSize, [objAnim, varStartWidth, varStartHeight, 500, 2] ],
		[500, xSlideTo, [varBoxId, varStartLeft, varStartTop, 500] ],
		[500, xDisplay, [varBoxId, 'none'] ],
		[-1, null, null]
	]);
	//do the animation
	seqFloatBox.run();
	
	if(document.getElementById('movies_allmovies_combo')) {
		document.getElementById('movies_allmovies_combo').style.visibility = visibility;
	}	
	if(document.getElementById('sidebar_allstars')) {
		document.getElementById('sidebar_allstars').style.visibility = visibility;
	}
	
	xZIndex(varBoxId, 1);
		
}

/*** Open Image Box ***/
function openImage(img, title, winBox) {
	var vImgSrc = img;
	var vBoxId = winBox;
	var vTitle = title;
	var boxContent 	= vBoxId+'Content';
	var boxBar		= vBoxId+'Bar';
	
	myImage = new Image();
	myImage.src = vImgSrc;
	w = myImage.width + 10;
	if( w == 10 ){
		w = 392;
	}
	h = myImage.height + 15;
	if( h == 15 ){
		h = 562;
	}
	
	var stringTagImage = '<img src="'+vImgSrc +'" border="0" style="margin:-13px 0px 0px -1px;"/>';
	
	document.getElementById(boxContent).innerHTML = stringTagImage;
	document.getElementById(boxBar).innerHTML = vTitle;
	
	switch_select_visibility('hidden');
	
	showFloatBox(vBoxId, w, h);
}

function switch_select_visibility(visibility) {
	
	if(document.getElementById('movies_allmovies_combo')) {
		document.getElementById('movies_allmovies_combo').style.visibility = visibility;
	}	
	
	if(document.getElementById('sidebar_allstars')) {
		document.getElementById('sidebar_allstars').style.visibility = visibility;
	}
}

function noPermission(){
	window.location = '?p=8';
}