var UI={};
var CONFIG={};
/*
(function(){
	alert(9);
})();*/
var HWD=0;
var BODY;
var ZINDEX=100;
var GLOBAL_ID=200;

var WINDOW=window.top; while(WINDOW.top != WINDOW.top.top){ WINDOW=WINDOW.top};
var oFocus=null;

function $(id /*string*/)
{	
 	var e = document.getElementById(id);
	return e ? (e.ELEMENT ? e.ELEMENT : e) : null;
}

String.prototype.replaceAll = function (token, newtoken){
	var s=this;
	while (s.indexOf(token)>=0)
	  s=s.split(token).join(newtoken);
	return s;
}

var Browser = new Object();
Browser.initialize = function()
{
  var dav=navigator.appVersion;
  var dua=navigator.userAgent;
  var geckoPos=dua.indexOf("Gecko");

  this.OS = new Object();
	this.OS.ver = parseFloat(dav);
	this.OS.mac = dav.indexOf("Macintosh") >= 0;
	this.OS.win = dav.indexOf("Windows") >= 0;
	this.OS.linux = dav.indexOf("X11") >= 0; /* could also be Solaris or something, but it's the same browser*/

  this.opera = dua.indexOf("Opera") >= 0;
	this.khtml = (dav.indexOf("Konqueror") >= 0)||(dav.indexOf("Safari") >= 0);
	this.safari = dav.indexOf("Safari") >= 0;
	this.mozilla = (geckoPos >= 0)&&(!this.khtml);
	this.ie = ((document.all)&&(!this.opera))?true:false;
	this.ie50 = this.ie && dav.indexOf("MSIE 5.0")>=0;
	this.ie55 = this.ie && dav.indexOf("MSIE 5.5")>=0;
	this.ie60 = this.ie && dav.indexOf("MSIE 6.0")>=0;
	this.ie70 = this.ie && dav.indexOf("MSIE 7.0")>=0;
	this.gecko = (dua.indexOf("Gecko") != -1);
  if (this.mozilla) this.geckoVersion = dua.substring(geckoPos + 6, geckoPos + 14); /* gecko version is YYYYMMDD*/
};Browser.initialize();

/************************************************************************************
	DOM Object
	Cria elementos HTML dinamicamente
************************************************************************************/
var DOM={
	create:function(e /*html element*/, css /*css code*/, cls /* css class*/)
	{
		var el=document.createElement(e);
		if (css) el.style.cssText=css;
		if (cls) el.className=cls;
		el.window=window;
		return el;
	},
	remove:function(e)
	{
		if (e.ondestroy)
			e.ondestroy();
		
		try
		{
			e.parentNode.removeChild(e);
			delete e;
		}
		catch(_e){}
	},
	table:function(rows, cols, css, cls)
	{
		var r,i=0,j,tb=DOM.create('TABLE', css, cls);
		while (i<rows)
		{
			r=tb.insertRow(i++);
			for (j=0; j<cols; j++)
				r.insertCell(j);
		};
		tb.border=0;
		tb.cellPadding=0;
		tb.cellSpacing=0;
		return tb;
	},
  parentWidget:function(e)
  {  
    while (e)
    {
      if (e.isWidget) return e;		
      e=e.parentNode;
    }
    return e;
  },
  getDocument:function(el)
  {
    var e=el.parentNode; //Debug.clear();
    while (e)
    {
      if (e.nodeName=='#document')
        return e;
      e = e.parentNode;
    }
    return null;
  },
  getIframeByWindow:function(win)
  {
    if (win==win.parent) return null;
    var i=0,q=win.parent.frames.length;
    while (i<q)
    {
      if (win.parent.frames[i]==win) 
        return win.parent.frames[i].frameElement;
      i++;
    }
    return null;
  },
  roundBorder:function(el,cls,flag)
  {
    el.innerHTML ='<div class="'+cls+'-0">'+
                    '<div class="'+cls+'-1"></div>'+
                    '<div class="'+cls+'-2"></div>'+
                    '<div class="'+cls+'-3"></div>'+
                    '<div class="'+cls+'-4"></div>'+
                  '</div>';
    el.borders = Array(el.firstChild.childNodes[0], el.firstChild.childNodes[1], el.firstChild.childNodes[2], el.firstChild.childNodes[3]);
    return el;
  }
};

var CSS={
	_exist:{},
	Class:
	{
		add:function(el, cls)
		{
			var s=el.className;
			s+='';
			s=s.replaceAll(cls, '');
			s=s+' '+cls;
			s=s.replaceAll('  ', ' ');
			el.className=s;
			return s;
		},
		remove:function(el, cls)
		{
			var s=''+el.className;
			s=s.replaceAll(cls, '');
			el.className=s;
			return s;
		}
	},
	include:function(file)
	{
		if ( CSS._exist[file] )
			return CSS._exist[file];
		
		var url = WINDOW.uri + 'jfw/theme/' + ( THEME._name ? THEME._name : 'default' ) + '/' + file;
		var css = document.createElement('link');		
		css.setAttribute('rel', 'stylesheet');
		css.setAttribute('type', 'text/css');
		css.setAttribute('href', URL.addParam( url, 'nocache', SYS.ID()));
		CSS._exist[file]=css;
		
		//chrome e safari só funcionam com a tag <link... css > dentro do head
		document.getElementsByTagName('head')[0].appendChild(css);		
		return css;
	}
};

var URL={
	addParam:function(url, p, v)
	{
		var i=url.indexOf('?',0), c='';		
		url += (i<0)?'?':'&';
		url += (p+'='+v);
		return url;
	},
	getFile:function(path, flag) //se flag=true, retira a extensão
	{
		var i=path.lastIndexOf('?'); if (i>=0) path = path.substring(0,i); /*retira os parâmetros ?a=xx*/
		if (flag) {i=path.lastIndexOf('.'); if (i>=0) path = path.substring(0,i);} /*retira a extensão;*/
		i=path.lastIndexOf('/'); if (i>=0) path = path.substring(i+1); /*retira o path*/
		return path;
	},
	getPath:function(path)
	{
		var i=path.lastIndexOf('?'); if (i>=0) path = path.substring(0,i); /*retira os parâmetros ?a=xx*/
		i=path.lastIndexOf('/'); if (i>=0) path = path.substring(0,i); /*retira o path*/
		return path.replace('file:///', '');
	},
	getContents:function( url )
	{
    var req = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    if (!req) throw new Error('XMLHttpRequest not supported');
    
    req.open("GET", url, false);
    req.send(null);
    
    return req.responseText;
	}
};

var THEME={
	_name:'default'
};

var SYS={
  isSelectText:true,
	/* trava a janela com uma mensagem */
	wait:function(flag, s)
	{
		var t = $('_wait');
		if ( !t )
		{
			t=document.body.appendChild( DOM.table(1,1,false,'wait-table' ) );
			t.id = '_wait';
			t.rows[0].cells[0].align='center';
			t.rows[0].cells[0].innerHTML = '<div class="IE-wait-div"><span class="wait-span" id="_wait1">Conteúdo.</span></div></td></tr></table>';		
		}
			
		t.style.zIndex = ++ZINDEX;
		t.style.display= flag?'':'none';
		$('_wait1').innerHTML=s;
	},
	rect:function(el)
	{		
		var l=0, t=0, w=el.offsetWidth, h=el.offsetHeight;
		
		if (el.offsetParent)
		{
			while (el)
			{
				l += el.offsetLeft;
				t += el.offsetTop;
				el = el.offsetParent;				
			}
		}
		
		return {left:l,top:t,width:w,height:h}
	},
	rectEx:function(el)
	{
		var l=0, t=0, w=el.offsetWidth, h=el.offsetHeight;
		
		if (el.offsetParent)
		{
			while (el)
			{
				l += el.offsetLeft-el.scrollLeft;
				t += el.offsetTop-el.scrollTop;
				el = el.offsetParent;			
			}
		}
		
		return {left:l,top:t,width:w,height:h}
	},
  include:function(file) //FF, IE, NN, Chrome, Opera, Safari
	{
		var h = document.getElementsByTagName('head')[0];
		var f = URL.getFile( file, true );
		var i, c, s, u;
			
		if (!URL._includes)
			URL._includes={};
		  
		//verifica se foi incluido
		for (i in URL._includes)
			if ( i == f )	return;
		
    u = URL.addParam( WINDOW.uri + 'jfw/' + file, 'nocache', SYS.ID() );
    
		s = document.createElement('script');
		s.setAttribute('type', 'text/javascript');
		s.setAttribute('language', "JavaScript");
		s.setAttribute('src', u);
    
    h.appendChild(s);
		
		URL._includes[f]=true;					
	},
	require:function(file) //FF, IE, NN, Chrome, Opera, Safari
	{
		var h = document.getElementsByTagName('head')[0];
		var f = URL.getFile( file, true );
		var i, c, s, u;
			
		if (!URL._includes)
			URL._includes={};
		
		//verifica se foi incluido
		for (i in URL._includes)
			if ( i == f )	return;
    
    u = URL.addParam( WINDOW.uri + 'jfw/' + file, 'nocache', SYS.ID() );
    
		s = document.createElement('script');
		s.setAttribute('type', 'text/javascript');
		s.setAttribute('language', "JavaScript");
		
    c = URL.getContents( u );
    (Browser.ie || Browser.opera) ? s.text = c : s.appendChild(document.createTextNode(c));
    
		h.appendChild(s);
		
		URL._includes[f]=true;					
	},
	GC:function()
	{
		if (!document.body) return;
		BODY = document.body;
		for (var i=0; i<BODY.childNodes.length; i++)
			if (BODY.childNodes[i].hwd)
				try
				{
					if (BODY.childNodes[i].hwd != BODY.childNodes[i].iframe.hwd)
					{
						DOM.remove( BODY.childNodes[i] );
						i--;
					}
				}
				catch(_e)
				{
					DOM.remove( BODY.childNodes[i] );
					i--;
				}
	},
	ID:function()
	{
		var d = new Date();		
		return 'id' + (WINDOW.GLOBAL_ID++) + d.getTime();
	},
	enableSelection:function(el, flag)
	{
		CONFIG.selection=flag;
		el.style.MozUserSelect=flag?'':'none';
    //el.style.KhtmlUserSelect=flag?'':'none';
    //el.style.UserSelect=flag?'':'none';
    return flag;
	},
	frameByWindow:function(win)
	{
		if (win==win.parent) return null;
		for (var i=0; i<win.parent.frames.length; i++)
			if (win.parent.frames[i]==win)
			{
				win.parent.frames[i].frameElement.parentWindow=win.parent;
				return win.parent.frames[i].frameElement;
			}
		return null;
	},
  setFocus:function(el) //passa o foco para um elemento qualquer widget ou dom
  {
    /*
      Se pode receber o foco com o tecla tab, passa o foco, caso contrário
      tenta retornar o foco para o objeto que estava com o foco anteriormente.
    */
    if (el.tabIndex>=0)
    {
      //DEBUG.write('WINDOW.oFocus = ' + WINDOW.oFocus);
      
      //se já tem o foco, impede que perca pra ele mesmo, só o IE
      if (Browser.ie && WINDOW.oFocus == el)
        el.noblur=true;
      
      el.focus();      
    }
    else
    {
      DEBUG.write('não pode receber foco');
      if (WINDOW.oFocus)
      {
        var e=WINDOW.oFocus;
        setTimeout(function(){e.focus();},1);
      }
    }
  }
};

//cancela o menu de contexto no IE
document.oncontextmenu=function()
{
  //return CONFIG.contextmenu;
};

//Não permite selecionar arrastando o mouse, só no IE
document.onselectstart = function()
{
  //return false;//CONFIG.selection;
};

document.onmousedown=function(evt)
{
	evt=evt?evt:window.event;
  var e=evt.target?evt.target:evt.srcElement;	
	var el=DOM.parentWidget(e);
  
  /*
    IE => não recebe o foco com o mouse, independente do valor de tabIndex (recebe com tab)
    FF, Chrome => recebe o foco com o mouse, mesmo com tabIndex = -1 (só não recebe com tab);
    Mais um problema: se for widget que estiver com o foco, não deve perder para um
                      objeto que tenha tabIndex=-1;
  */
  
  if (el)
  {
    if (Browser.ie)
    { //passa o foco para o elemento com tabIndex > -1
      if (el.tabIndex>-1) setTimeout(function(){el.focus();}, 1);
    }
    else
      //não deixa passar o foco com tabIndex = -1
      if (el.tabIndex==-1) return false;
    return SYS.isSelectText;
  }
  
  
  //DEBUG.write(SYS.isSelectText);
  
   //não permite selecionar texto
  
  /*
  if ( !Sys.jpopup_mousedown && 
			 !window.iframe.cancelHidePopups)
	       Sys.hidePopups();	//Sys.jpopup_show=Sys.jpopup_mousedown=null;
	//e=Dom.getParentWidget(e);	if (e) Sys.setFocus(e); 
	return !(!Sys.selection || evt.button==2 && CONFIG.contextmenu);
  */
};
/*
document.onmouseup=function(evt)
{
  if (Drag.target) Drag.mouseup(evt);
}*/

window.onerror=function(msg, url, line)
{
	if (CONFIG.debug)
  {
	  var m = ('Run time error: ' + msg + '\nFile: ' + url + '\nLine: ' + line);
	  Debug.write('<span style="color:red">'+m+'</span>');
	}
};

window.onunload=function()
{
	//Sys.onChildFrameUnLoad(window);
};

window.onload=function()
{	
	/*BODY = document.body;	
  BODY.scroll='no'; //retira as barras de rolagem, no IE
  BODY.style.cssText='padding:0;margin:0';
*/
  window.iframe=SYS.frameByWindow(window);
	if (window.iframe)
	{		
		window.iframe.window=window;
		window.hwd = window.iframe.hwd = WINDOW.HWD++;
		//window.popupWindow = window.iframe.isPopupContent ? window.iframe.popupElement : null;
	}
		
	WINDOW.SYS.GC();
	
  setTimeout(function()
	{
		if (window.oninitialize) window.oninitialize();
		if (window.iframe) 
		{			
			if (window.iframe.oninitialize) 
				window.iframe.oninitialize();
			else if (window.iframe.attributes['oninitialize'])
				window.iframe.parentWindow.eval(window.iframe.attributes['oninitialize'].value);
		}
	},10);  
};

//encontra a url inicial. ex: http://www.endereco.com/form/arq.php = http://www.endereco.com/
//alert('WINDOW.jfwpath = ' + WINDOW.jfwpath);
if ( !WINDOW.jfwpath )
{
	//WINDOW.jfwpath = URL.getPath( WINDOW.location + '' );
	//alert('WINDOW.jfwpath = ' + WINDOW.jfwpath);	
	/*
	SYS.require('config.js');
	if (!WINDOW.path);
		WINDOW.path = URL.getPath( WINDOW.location + '' );
	*/
};

//carrega o css do engine
/*CSS.include('engine.css');

SYS.include('http.js');
SYS.include('event.js');
SYS.include('drag.js');
SYS.include('widget.js');
SYS.include('popup.js');
SYS.include('effect.js');

SYS.include('debug.js');
*/