
/**
 * Arquivo da classe InternalWindow. 
 * Responsável em abrir janelas internas dentro da página. 
 *
 * @author	Humberto Sales da Silva
 * @version 1.0
 *
 */



document.write('<SCRIPT language=JavaScript src="/PSV/Comum/Scripts/Cliente/DragIFrame/dragiframe.js"></SCRIPT>');
document.write('<DIV id="DIVInternalWindow"></DIV>');				



var __IWLayoutHTML = '';

var InternalWindow = function(name, width, height, title, content, url){
	
	//Propriedades		
	this.name = name;
	this.width = width || '300';
	this.height = height || '200';	
	this.url = url || '';
	this.displayErrors = true;
	this.title = title || 'Aqui fica o título';
	this.content = content || 'Aqui fica o conteúdo da <b>janela</b>.';
	this.objWindow = null;	//Objeto Janela
	this.objIFrame = null;	//Objeto IFrame que é esta janela
	this.layoutProcessedHTML = null;
	this.urlLayout = '/PSV/Comum/Scripts/Cliente/InternalWindow_1.0/InternalWindowLayout.asp';
	this.preNameIW = 'IW';
	this.alreadyCreate = false;
	this.icon = '/PSV/Imagens/Icones/16x16/ico16_sistema.gif';

	this.strStyle = ' Style="PADDING-LEFT: 3px;'
		+  'FONT-SIZE: 11px;'
		+  'COLOR: #000000;'
		+  'BACKGROUND-REPEAT: no-repeat;'
		+  'LINE-HEIGHT: 18px;'
		+  'TEXT-DECORATION: none;'
		+  'FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif;'	
		+  'position: absolute;'
		+  'scrolling: no;'
		+  'display: none;"';
	
	//Eventos
	//this.OnError		= null ;	// function( source, errorNumber, errorDescription )
	
}

InternalWindow.prototype.create = function(){
	//Validações
	if ( !this.name || this.name.length == 0 )
	{
		this._ThrowError( 701, 'Você precisa especificar um nome para o objeto InternalWindow.' ) ;
		return ;
	}
	if (this.alreadyCreate){
		//this._ThrowError( 702, 'Esta InternalWindow já foi criada.' ) ;
		return ;	
	}
	
	if (document.readyState.toLowerCase() == 'loading'){
		this._ThrowError( 702,'A InternalWindow só pode ser criada após a página ter sido carregada.' ) ;
		return ;	
	}
	this.alreadyCreate = true;
	
	DIVInternalWindow.insertAdjacentHTML("beforeEnd", '<iframe id=\''+ this.preNameIW + this.name + '\''
		+ ' frameborder=0 scrolling=no'
		+ ' topMargin=0 leftMargin=0'
		+ ' bottomMargin=0 rightMargin=0'
		+ ' name=\'' + this.preNameIW + this.name + '\' '
		+ this.strStyle
		+ ' width=' + this.width 
		+ ' height=' +  this.height 
		+ ' ></iframe>');	

	//	+ ' allowTransparency=false ' //-> BUG: Se usar o combo fica por cima.

	
	//Captando os objetos
	this.objWindow = eval(this.preNameIW + this.name);
	this.objIFrame = document.getElementById(this.preNameIW + this.name);
	
	//Igualando o opener da janela ao parent da janela
	//this.objWindow.opener = this.objWindow.parent;
	
	
	
	//Atualizando a janela (processando)
	this.refresh();

	
	

}



	



InternalWindow.prototype.refresh = function(){

	//Validações
	if (!this.alreadyCreate){
		this._ThrowError( 703, 'A InternalWindow ainda não foi criada.' ) ;
		return ;	
	}
	
	//this.objWindow.document.close();
	this.objWindow.document.open();
	this.objWindow.document.write('<p align="right" style="FONT-FAMILY: Verdana, Arial; FONT-SIZE: 11px;"><b>Carregando... por favor, aguarde!</b></p>');
	this.objWindow.document.close();

	/*	
	######## ESTA TRAVANDO no document.close()
	... Verificar para nova versão!!! ######
		
	
	EM NOVA VERSAO SUBSTITUIR ISTO TUDO PARA USAR XML COM XSL
	
	//Verificando se o layout já foi carregado
	if (__IWLayoutHTML == ""){
	
		//Carregando o layout
		var IWhttp  = new ActiveXObject("Microsoft.XMLHttp");
		IWhttp.open("POST",this.urlLayout,false);
		IWhttp.send(); //BUG: Esta usando o cache as vezes.
	

		//Validações
		if (IWhttp.status != 200 )
		{
			this._ThrowError( IWhttp.status, 'Ocorreu um erro enquanto o layout da InternalWindow estava sendo carregado.' ) ;
			return ;
		}
	
		__IWLayoutHTML = IWhttp.responseText;
	}
	
	if (this.url != '') {
		//Processando o Layout
		this.layoutProcessedHTML = __IWLayoutHTML
			.replace(/\[TITLE\]/g,this.title)
			.replace(/\[CONTENT\]/g,'<iframe name="content' + this.preNameIW + this.name + '" width="100%" height="100%" src="' + this.url + '" scrolling="auto" frameborder="0" allowTransparency="true" topmargin="0" leftmargin="0" rightmargin="0" bottommargin="0" ></iframe>')
			.replace(/\[ICON\]/g,this.icon)
			.replace(/\[FRAME_NAME\]/g,this.preNameIW + this.name);
			

	}else{
	
		//Processando o Layout
		this.layoutProcessedHTML = __IWLayoutHTML
			.replace(/\[TITLE\]/g,this.title)
			.replace(/\[CONTENT\]/g,this.content)
			.replace(/\[ICON\]/g,this.icon)
			.replace(/\[FRAME_NAME\]/g,this.preNameIW + this.name);
	}
	

	
	
	//Escrevendo na janela
	this.objWindow.document.open();
	this.objWindow.document.write(this.layoutProcessedHTML);
	this.objWindow.document.close();	
	
	
	if (this.url != ''){
		
		this.objWindow.frames.item('content' + this.preNameIW + this.name).opener = this.objWindow.parent;
	}

	*/		
	
	this.objWindow.document.location.href = 
			this.urlLayout + '?TITLE=' + this.title
			+ '&CONTENT=' + this.content
			+ '&ICON=' + this.icon
			+ '&FRAME_NAME=' + this.preNameIW + this.name
			+ '&URL=' + this._URLEncode(this.url);
	
}

InternalWindow.prototype.open = function(url, name, width, height){
	//Validações
	if (!this.alreadyCreate){
		this._ThrowError( 703, 'A InternalWindow ainda não foi criada.' ) ;
		return ;	
	}
	
	this.name = name;
	this.url = url;
	this.width =width;
	this.height =width;
	
	this.resize();
	this.refresh();

	
}

InternalWindow.prototype.setIcon = function(icon){

		this.icon= icon;
}

InternalWindow.prototype.getIcon = function(){

		return this.icon;
}


InternalWindow.prototype.getWindow = function(){

		return this.objWindow;
}


InternalWindow.prototype.getIFrame = function(){

		return this.objIFrame;
}


InternalWindow.prototype.setTitle = function(title){
	this.title = title;
	this.refresh();
}

InternalWindow.prototype.getTitle = function(){
	return this.title;
}

InternalWindow.prototype.setContent = function(content){
	this.content = content;
	this.refresh();
}

InternalWindow.prototype.getContent = function(){
	return this.content;
	
}


InternalWindow.prototype.setURL = function(url){
	this.url = url;
	this.refresh();
}

InternalWindow.prototype.getURL = function(){
	return this.url;
}

InternalWindow.prototype.goToCenter = function(){
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;

		var xc = (aw - this.width) / 2;
		var yc = (ah - this.height) / 2;
    
		this.objIFrame.style.top = yc + window.document.body.scrollTop - 100;
		this.objIFrame.style.left = xc + window.document.body.scrollLeft;    
}

InternalWindow.prototype.setTop = function(value){
	//Validações
	if (!this.alreadyCreate){
		this._ThrowError( 703, 'A InternalWindow ainda não foi criada.' ) ;
		return ;	
	}
	this.objIFrame.style.top = value;
}

InternalWindow.prototype.setLeft = function(value){
	//Validações
	if (!this.alreadyCreate){
		this._ThrowError( 703, 'A InternalWindow ainda não foi criada.' ) ;
		return ;	
	}
	this.objIFrame.style.left = value;
}

InternalWindow.prototype.setVisible = function(visible){

	//Validações
	if (!this.alreadyCreate){
		this._ThrowError( 703, 'A InternalWindow ainda não foi criada.' ) ;
		return ;	
	}
	
	if (visible) {
		this.objIFrame.style.display = 'inline';
		
		//Exibe no centro da tela se não tiver setado valor inicial
		if (this.objIFrame.style.top == '')	{
			this.goToCenter();}

		/*
		if (window.event != null){
			//Exibe onde o mouse esta clicado.
			this.objIFrame.style.top = window.event.y;
			this.objIFrame.style.left = window.event.x;
			
			
		}
		*/
		try{
			//Setando configuracao do dragIFrame
			bringSelectedIframeToTop(true);
			
			//Coloca ela no topo no momento que for criada.
			this.objIFrame.style.zIndex=this.objIFrame.document.DIF_highestZIndex++;
			
			}catch(e){			
		}

	}else{
		this.objIFrame.style.display = 'none';
	}
}

InternalWindow.prototype.getVisible = function(){

		return(this.objIFrame.style.display == 'inline');
}

InternalWindow.prototype.setWidth = function(width){

		this.width = width;
		this.resize();
}

InternalWindow.prototype.getWidth = function(){

		return this.width;
}

InternalWindow.prototype.setHeight = function(height){

		this.height = height;
		this.resize();
}

InternalWindow.prototype.getHeight = function(){

		return this.height;
}

InternalWindow.prototype.resize = function(){
	//Validações
	if (!this.alreadyCreate){
		this._ThrowError( 703, 'A InternalWindow ainda não foi criada.' ) ;
		return ;	
	}	
	
	this.objIFrame.style.width = this.width;
	this.objIFrame.style.height = this.height;
}

InternalWindow.prototype._ThrowError = function( errorNumber, errorDescription )
{
	this.ErrorNumber		= errorNumber ;
	this.ErrorDescription	= errorDescription ;

	if ( this.displayErrors )
	{
		if (document.readyState.toLowerCase() == 'loading'){
			document.write('<div style="COLOR: #ff0000">');
			document.write('[ InternalWindow Error ' + this.ErrorNumber + ': ' + this.ErrorDescription + ' ]' ) ;
			document.write('</div>' );		
		}else{
			document.body.innerHTML += '<div style="COLOR: #ff0000">'  ;
			document.body.innerHTML += '[ InternalWindow Error ' + this.ErrorNumber + ': ' + this.ErrorDescription + ' ]'  ;
			document.body.innerHTML +=  '</div>'  ;
		}
		
	}
}



InternalWindow.prototype._sleep = function(time)
{
	var d = new Date();
	while((new Date()).getSeconds()-d.getSeconds()<time){
		// Do nothing :( There is no special JavaScript function to wait for awhile
	};
}


// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresarch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// ====================================================================
InternalWindow.prototype._URLEncode = function(urlForEncode)
{
	// 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 = urlForEncode;
	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;
};