//////////////////////////////////////////////////////////////////////////
// Global for brower version branching.
//////////////////////////////////////////////////////////////////////////
var agt=navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);
var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
            && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
            && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var is_nav2 = (is_nav && (is_major == 2));
var is_nav3 = (is_nav && (is_major == 3));
var is_nav4 = (is_nav && (is_major == 4));
var is_nav4up = (is_nav && (is_major >= 4));
var is_navonly = (is_nav && ((agt.indexOf(";nav") != -1) || (agt.indexOf("; nav") != -1)) );
var is_nav6 = (is_nav && (is_major == 5));
var is_nav6up = (is_nav && (is_major >= 5));
var is_gecko = (agt.indexOf('gecko') != -1);
var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie3    = (is_ie && (is_major < 4));
var is_ie4    = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
var is_ie4up  = (is_ie && (is_major >= 4));
var is_ie5    = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
var is_ie5_5  = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.5") !=-1));
var is_ie5up  = (is_ie && !is_ie3 && !is_ie4);
var is_ie5_5up =(is_ie && !is_ie3 && !is_ie4 && !is_ie5);
var is_ie6    = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
var is_ie6up  = (is_ie && !is_ie3 && !is_ie4 && !is_ie5 && !is_ie5_5);
var is_Mac	= (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
var is_IEmac= ((document.all)&&(is_Mac)) ? true : false;
    
if( !is_ie ) window.navigate = function(url) { window.location = url; } 

//////////////////////////////////////////////////////////////////////////
// General Function
//////////////////////////////////////////////////////////////////////////
function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}

//////////////////////////////////////////////////////////////////////////
// Body onload utility (supports multiple onload functions)
//////////////////////////////////////////////////////////////////////////
var gSafeOnload = new Array();

function SafeAddOnload(f)
{
	if (is_IEmac && is_ie4)  // IE 4.5 blows out on testing window.onload
	{
		window.onload = SafeOnload;
		gSafeOnload[gSafeOnload.length] = f;
	}
	else
	{
		if  (! window.onload)
			window.onload = SafeOnload;
		else
		if (window.onload != SafeOnload)
		{
			gSafeOnload[0] = window.onload;
			window.onload = SafeOnload;
		}		
		gSafeOnload[gSafeOnload.length] = f;
	}
}

function SafeOnload()
{
	for (var i=0;i<gSafeOnload.length;i++)
	{
	  if( typeof(gSafeOnload[i]) == "function" )
	  	gSafeOnload[i]();
	  else
	  if( typeof(gSafeOnload[i]) == "string" )
			eval(gSafeOnload[i]);
	}
}

//////////////////////////////////////////////////////////////////////////
// Body unload utility (supports multiple onload functions)
//////////////////////////////////////////////////////////////////////////
var gSafeOnUnload = new Array();
function SafeAddOnUnload(f)
{
	if (is_IEmac && is_ie4)  // IE 4.5 blows out on testing window.onload
	{
		window.onunload = SafeOnUnload;
		gSafeOnUnload[gSafeOnUnload.length] = f;
	}
	else 
	{
		if  (! window.onload)
			window.onunload = SafeOnUnload;
		else
		if (window.onunload != SafeOnUnload)
		{
			gSafeOnUnload[0] = window.onunload;
			window.onunload  = SafeOnUnload;
		}		
		gSafeOnUnload[gSafeOnUnload.length] = f;
	}
}

function SafeOnUnload()
{
	for (var i=0;i<gSafeOnUnload.length;i++)
	{
	  if( typeof(gSafeOnUnload[i]) == "function" )
	  	gSafeOnUnload[i]();
	  else
	  if( typeof(gSafeOnUnload[i]) == "string" )
			eval(gSafeOnUnload[i]);
	}
}

//////////////////////////////////////////////////////////////////////////
// Dialog / Popup Window
//////////////////////////////////////////////////////////////////////////
//function mpOpenMaximized(url)            { rwOpen("mpFullWindow",url); }  
//function mpOpenWindow(url,width,height,title,status)  { rwOpen("mpNormalWindow", url, width, height, title, status); }  
function mpOpenMaximized(url)            { rwOpenWindow(url, "mpFullWindow"); }  
function mpOpenWindow(url,width,height,title,status)  { rwOpenWindow(url, "mpNormalWindow", width, height, title, status); }  

var gDialogs = new Array();
//var dialogWin  = new Object()
function openWindow(url, title, width, height, resizable, location, menubar, toolbar, status, scrollbars) 
{
    mpOpenWindow(url, width, height, title, status);
}

function openPopUpWindow(url, title, width, height, resizable, location, menubar, toolbar, status, scrollbars) 
{
	var dialogWin  = new Object();
	for (var i=0;i < gDialogs.length;i++) 
		if( gDialogs[i].name == title ) { dialogWin = gDialogs[i]; break; }
	
	 if (!dialogWin.win || (dialogWin.win && dialogWin.win.closed)) 
	 {
		  // Initialize properties of the modal dialog object.
		  dialogWin.returnedValue = ""
		   
		  //dialogWin.args = args
		  dialogWin.url		= url
		  dialogWin.width	= width
		  dialogWin.height	= height
		
		  features = "resizable=" + resizable + ",location=" + location + ",menubar=" + menubar + ",toolbar=" + toolbar + ",status=" + status + ",scrollbars=" + scrollbars;
		  		
		  // Keep name unique so Navigator doesn't overwrite an existing dialog.
		  if( title == "" )
			dialogWin.name = (new Date()).getSeconds().toString().replace(/ /g, "_");
		  else
		    dialogWin.name = title.replace(/ /g, "_");
		
		  // Assemble window attributes and try to center the dialog.
		  if (is_nav4) 
		  {
			// Center on the main window.
			dialogWin.left = window.screenX + ((window.outerWidth - dialogWin.width) / 2)
			dialogWin.top = window.screenY +  ((window.outerHeight - dialogWin.height) / 2)
			var attr = "screenX=" + dialogWin.left + ",screenY=" + dialogWin.top + ",width=" +	dialogWin.width + ",height=" + dialogWin.height + "," + features
		} 
		else 
	  	{
			// The best we can do is center in screen.
	   		dialogWin.left = (screen.width - dialogWin.width) / 2
	   		dialogWin.top = (screen.height - dialogWin.height) / 2
	   		var attr = "left=" + dialogWin.left + ",top=" +	dialogWin.top + ",width=" + dialogWin.width + ",height=" + dialogWin.height + "," + features
	  	}
	
	  	// Generate the dialog and make sure it has focus.
	  	dialogWin.win=window.open(dialogWin.url, dialogWin.name , attr)
	  	if( dialogWin.win == null ) 
	  	{
	  		alert("POP Bloqueado. Por favor habilite-o em seu browser")
	  	}
	  	else
	  	{
	        try {
			    dialogWin.win.name = dialogWin.win.name.replace(/ /g, "_");
		    }
		    catch(e) {
			    
		    }  		  	    	  	    
	  		dialogWin.win.focus();	  		
	  		gDialogs[gDialogs.length] = dialogWin;
	  	}
	} 
 	else 
 		dialogWin.win.focus()
 		
}

function findMainWindow()
{
  var p = self;
  while( 1 )
  {
    if( (p == p.parent && p.parent == p.parent.parent) ) break;

    p = p.parent;
  }
  return p;
}

//////////////////////////////////////////////////////////////////////////
// Print
//////////////////////////////////////////////////////////////////////////
function printFrame(frame, onfinish) {
  if ( is_nav ) {
     if ( !frame ) window.print(); else frame.print();
     return;
  }
  if ( ! frame ) frame = window;
  if ( frame.document.readyState != "complete" )
  {   
      if ( !confirm("O documento a ser impresso ainda não terminou de ser carregado! Proceder com a impressão?") )
      {
         if ( onfinish ) onfinish();
         return;
      }
  }
  if ( is_ie5up ) {
    /* focus handling for this scope is IE5Beta workaround, should be gone with IE5 RTM. */
    var focused = document.activeElement; 
    frame.focus();
    frame.self.print();
    if ( onfinish ) onfinish();
    if ( focused && !focused.disabled ) focused.focus();
    return;
  }
  // fake print() for IE4.x
  if ( is_ie4 ) 
  {
	window.print = printFrame;

	var eventScope = printGetEventScope(frame);
	var focused = document.activeElement;

	window.printHelper = function() {
		execScript("on error resume next: printWB.ExecWB 6, 1", "VBScript");
		printFireEvent(frame, eventScope, "onafterprint");
		printWB.outerHTML = "";
		if ( onfinish ) onfinish();
		if ( focused && !focused.disabled ) focused.focus();
		window.printHelper = null;
	}
	document.body.insertAdjacentHTML("beforeEnd",
		"<object id=\"printWB\" width=0 height=0 \
		classid=\"clsid:8856F961-340A-11D0-A96B-00C04FD705A2\"></object>");

	printFireEvent(frame, eventScope, "onbeforeprint");
	frame.focus();
	window.printHelper = printHelper;
	setTimeout("window.printHelper()", 0);
  }
}

// Print helpers
function printFireEvent(frame, obj, name) {
  var handler = obj[name];
  switch ( typeof(handler) ) {
    case "string": frame.execScript(handler); break;
    case "function": handler();
  }
}

function printGetEventScope(frame) {
  var frameset = frame.document.all.tags("FRAMESET");
  if ( frameset.length ) return frameset[0];
  return frame.document.body;
}

//////////////////////////////////////////////////////////////////////////
// MPLS :: CHAT
//////////////////////////////////////////////////////////////////////////
function checkFrames() { }

function getRootPath()
{
	var pathName = window.location.pathname;
	if( pathName.length > 1 ) 
	{
		p = pathName.indexOf("/",1);
		if( p >= 0 ) return pathName.substr(0,p+1)
	}
	return "/";
}

function goChat(roomID, nicknameID, isModerate, isAdmin, logged)
{
	var selectObject= document.getElementById(roomID);
	var textObject	= document.getElementById(nicknameID);
	if( selectObject && textObject )
	{
		var room = selectObject.options[selectObject.selectedIndex].value;
		var nickname = textObject.value;
		loadIFrameContent("chatFrame",  getRootPath() + "Web/Collab/Chat/gochat.aspx?room=" + room + "&roomName=" + room + "&nickname=" + nickname + "&admin=" + isAdmin + "&moderate=" + isModerate + "&logged=" + logged);
	}
}
function goChatDirect(room, nickname, isModerate, isAdmin, logged)
{
	loadIFrameContent("chatFrame", getRootPath() + "Web/Collab/Chat/gochat.aspx?room=" + room + "&roomName=" + room + "&nickname=" + nickname + "&admin=" + isAdmin + "&moderate=" + isModerate + "&logged=" + logged);
}

//////////////////////////////////////////////////////////////////////////
// MPLS :: Load
//////////////////////////////////////////////////////////////////////////
function checkFrames() { }

function waitAndRedirect(seconds, url)
{
	var r = "redirectUrl('" + url + "')";
	setTimeout(r, seconds*1000);
}
function redirectUrl(url)
{
	document.location.replace(url);
}
function loadFrameContent(frame, url)
{
	document.frames[frame].document.location.replace(url);
}
function loadIFrameContent(frame, url)
{
	var frameObj = document.getElementById(frame);
	if( frameObj )	    frameObj.src = url;
	else        	    alert('Cannot find frame:' + frame);
}

//////////////////////////////////////////////////////////////////////////
// MPLS :: Focus
//////////////////////////////////////////////////////////////////////////
function FirstFocus_FindFirst()
{
	for( var j = 0; j < document.forms.length; j++ ) {
		var theForm = document.forms[j];
		for (var i = 0; i < theForm.length; i++)
		{
			if (	theForm.elements[i].type == "text"			|| 
	   				theForm.elements[i].type == "password"		|| 
	   				theForm.elements[i].type == "button"		|| 
	   				theForm.elements[i].type == "submit"		|| 
	   				theForm.elements[i].type == "checkbox"	    || 
	   				theForm.elements[i].type == "select-one"	|| 
					theForm.elements[i].type == "select-multiple")
			{
				if( theForm.elements[i].disabled  == undefined  || theForm.elements[i].disabled  == false )
				{
					if( theForm.elements[i].AutoFocus == undefined || theForm.elements[i].AutoFocus == true )
					{
    				    var _CtrlToFocus=theForm.elements[i]; 
                        window.setTimeout( function (){try {_CtrlToFocus.focus(); }catch (e){}}, 200);
						break;
					}
				}
			}
		}
	}
}
function FirstFocus_Focus(id, name)  {
	var targetControl = FirstFocus_FindControl( id, name );
	if ( targetControl != null && targetControl.focus ) {
		try
		{
			targetControl.focus();
		}
		catch(err)
		{
		}
	}
}
function FirstFocus_FindControl( id, name ) {
	if ( typeof(document.getElementById) != "undefined" ) {
		var focusControl = document.getElementById(id);
		if ( focusControl != null ) {
			return focusControl;
		}
	}
	for( var i = 0; i < document.forms.length; i++ ) {
		var theForm = document.forms[i];
		var focusControl = theForm[name];
		if ( focusControl != null ) {
			return focusControl;
		}
	}
	return null;
}

//////////////////////////////////////////////////////////////////////////
// Box/Screen functions
//////////////////////////////////////////////////////////////////////////

function getTop(obj)
{
   return( obj.offsetParent==null ? obj.offsetTop : obj.offsetTop+getTop(obj.offsetParent) );
}
function centerPanel(panel, refArea)
{
	if( panel && refArea )
	{
		panel.style.left = (refArea.offsetWidth - panel.offsetWidth) / 2
		panel.style.top  = getTop(refArea);
	}
}
function hidePanel(panel)
{
	if( panel ) panel.style.display="none";
}
function showPanel(panel)
{
	if( panel ) panel.style.display="block";
}
function hideShowPanel(panel)
{
	if( panel )
	{
		if( panel.style.display=="block" ) 
			panel.style.display = "none";
		else
			panel.style.display = "block";
	}
}
function hideShowPanelById(id)
{
	obj = document.getElementById(id);
	hideShowPanel(obj);
}
function ToogleGR(id)
{
	obj = document.getElementById("td"+id);
	lit = document.getElementById("sp"+id);
	if( obj )
	{
		if( obj.style.display == 'none' )
		{
			obj.style.display = ''; 
			lit.innerHTML= "-";
		}
		else 
		{
			obj.style.display = 'none';
			lit.innerHTML= "+";
		}
	}
}
//////////////////////////////////////////////////////////////////////////
// Janela Eventos
//////////////////////////////////////////////////////////////////////////
function supressPx(valor)
{
	pospx= valor.indexOf("px")
	return( parseInt(valor.substr(0,pospx)) )
}

//////////////////////////////////////////////////////////////////////////
// YAF SCRIPTS
//////////////////////////////////////////////////////////////////////////
function yaf_popit(menuName) 
{
	var evt = getEvent(window.event);
	var target,newmenu;

	if(!document.getElementById) {
		throw('ERROR: missing getElementById');
		return false;
	}
	
	if(evt.srcElement)
		target = evt.srcElement;
	else if(evt.target)
		target = evt.target;
	else {
		throw('ERROR: missing event target');
		return false;
	}
	
	newmenu = document.getElementById(menuName);

	if(window.themenu && window.themenu.id!=newmenu.id)
		yaf_hidemenu();

	window.themenu = newmenu;
	if(!window.themenu.style) {
		throw('ERROR: missing style');
		return false;
	}

	if(themenu.style.visibility == "hidden") {
		var x = yaf_left(target);
		// Make sure the menu stays inside the page
		// offsetWidth or clientWidth?!?
		if(document.documentElement) {
			if(x + themenu.offsetWidth>document.documentElement.offsetWidth - 20)
				x += target.offsetWidth - themenu.offsetWidth;
		}

		themenu.style.left = x;
		themenu.style.top = yaf_top(target);
		themenu.style.visibility = "visible";
		themenu.style.zIndex = 100;
	} else {
		yaf_hidemenu();
	}

	return false;
}
function yaf_mouseover() 
{
	var evt = getEvent(window.event);
	if(evt.srcElement) {
		evt.srcElement.style.cursor = "hand";
	} else if(evt.target) {
		evt.target.style.cursor = "pointer";
	}
}
function mouseHover(cell,hover) 
{
	if(hover) {
		cell.className = "BoxContent";
		try {
			cell.style.cursor = "pointer";
		}
		catch(e) {
			cell.style.cursor = "hand";
		}
	} else {
		cell.className = "BoxContentBackground";
	}
}
function yaf_hidemenu() 
{
	if(window.themenu) {
		window.themenu.style.visibility = "hidden";
		window.themenu = null;
	}
}
function getEvent(eventobj) 
{
	if(eventobj.stopPropagation) {
		eventobj.stopPropagation();
		eventobj.preventDefault();
		return eventobj;
	} else {
		window.event.returnValue = false;
		window.event.cancelBubble = true;
		return window.event;
	}
}
function yaf_left(obj) 
{
	var x = 0;
	while(obj) {
		x += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return x;
}
function yaf_top(obj) 
{
	var y = obj.offsetHeight;
	while(obj) {
		y += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return y;
}
document.onclick = yaf_hidemenu;
if(document.addEventListener) document.addEventListener("click",function(e){window.event=e;},true);
if(document.addEventListener) document.addEventListener("mouseover",function(e){window.event=e;},true);

//////////////////////////////////////////////////////////////////////////
// Save Box State
//////////////////////////////////////////////////////////////////////////
function collapsablePanelSaveState(controlID, state ) 
{
    if( controlID.lastIndexOf('_') > -1 )
        controlID = controlID.substr(controlID.lastIndexOf('_')+1, controlID.length)
        
    var cookieInfo = getCookie(_boxStateCookieName);
    if( cookieInfo == null ) cookieInfo = "|";

    var p1 = cookieInfo.indexOf(controlID);

    if( state && p1 < 0) // Coloca
    {
        cookieInfo = cookieInfo + controlID + "|";
    	setCookie(_boxStateCookieName, cookieInfo, getExpirationDate(1));
    }
    else if( !state && p1 > -1) // Retira
    {
        var p2 = p1 + controlID.length;
        var ll = cookieInfo.length - p2;
        cookieInfo = cookieInfo.substr(0,p1);
        if( p2 > 0 ) cookieInfo += cookieInfo.substr(p2+1, ll)
    	setCookie(_boxStateCookieName, cookieInfo, getExpirationDate(1));
    }
}

function saveBoxState() 
{
	var cookieInfo = "";

	for (i = 0; i < _boxSaveArr.length ; i++) {

        var p = CollapsablePanel_Find(_boxSaveArr[i]);
        if( p )
        {
            if( ! p.Collapsed ) cookieInfo = cookieInfo + "|" + _boxSaveArr[i]
        }
	}

	setCookie(_boxStateCookieName, cookieInfo, getExpirationDate(1));
}

//////////////////////////////////////////////////////////////////////////
// Cookie Functions
//////////////////////////////////////////////////////////////////////////
function setCookie(cookieName, value, expires) {
	cookieInfo = cookieName + "=" + escape(value) + ";expires=" + expires + ";path=/";
	document.cookie = cookieInfo;  
	return document.cookie;
}
function getExpirationDate(days){
	today = new Date();
	today.setTime(Date.parse(today) + (days * 60 * 60 * 24 * 100));
	return  today.toUTCString();
}
function getCookie(cookieName){
	var aCookie = document.cookie.split("; ");
	for (var i=0; i < aCookie.length; i++)
	{
		var aCrumb = aCookie[i].split("=");
		if (cookieName == aCrumb[0]) 
		{
    		return unescape(aCrumb[1]);
    	}
	}
	return null;

}

///////////////////////////////////////////////////////////////////////
///// Validate TEXTBOX 
///// HOW TO USE IT:
/////   textbox1.Attributes.Add("onkeypress","maxOnKeyPress(this,TAMANHO);")
/////   textbox1.Attributes.Add("onkeyup","maxOnKeyUp(this,TAMANHO);")
///////////////////////////////////////////////////////////////////////

function maxOnKeyPress(obj, max)
{
    if (obj.value.length == max){
        event.returnValue = false; 
    } 
} 

function maxOnKeyUp(obj, max) 
{ 
   if (obj.value.length > max){
      obj.value = obj.value.substr(0,max); 
   }
}
///////////////////////////////////////////////////////////////////////


function centerDivToWin(dialogWin)
{
		// Assemble window attributes and try to center the dialog.
		if (is_nav4) 
		{
			// Center on the main window.
			dialogWin.style.left = window.screenX + ((window.outerWidth  - dialogWin.style.width) / 2)
			dialogWin.style.top  = window.screenY + ((window.outerHeight - dialogWin.style.height) / 2)
		} 
		else 
	  	{
			// The best we can do is center in screen.
	   		dialogWin.style.left = (screen.width - supressPx(dialogWin.style.width)) / 2
	   		dialogWin.style.top = (screen.height - supressPx(dialogWin.style.height)) / 2
	   	}
}