var pixWnd = new Array;
var pixMaxZIndex = 9999; // TODO: achar o maior z-index

var ID_WND_NORMAL  = 0;
var ID_WND_ALERT   = 1;
var ID_WND_CONFIRM = 2;

var ID_WND_WARNING     = 0;
var ID_WND_ERROR       = 1;
var ID_WND_INFORMATION = 2;
var ID_WND_QUESTION    = 3;

var ID_WND_BTN_OK  = 0;
var ID_WND_BTN_YES = 1;
var ID_WND_BTN_NO  = 2;

var ID_WND_CHANGED_AUTO  = -1;
var ID_WND_CHANGED_FALSE = 0;
var ID_WND_CHANGED_TRUE  = 1;

var formulario;
var campo;
var pagina_retorno;
var returnFunction;
var Pergunta;
var PerguntaX;
var HabilitaPagina;
var Removeu;
var strChamaFuncao;

//------------------------------------------------------------------------------
// Propriedades alteráveis
//------------------------------------------------------------------------------
// Largura e altura inicial (pixWndAlert e pixWndConfirm)
var pixWndMsgDefaultWidth  = 350;
var pixWndMsgDefaultHeight = 150; // a altura é ajustada automaticamente de acordo com o texto

// Iframe Scrolling
var pixWndIframeScrolling  = "no"; // "no", "yes" ou "auto"

// Imagens
var pixWndImgBgHead        = "./imagens/pixwnd-bg-head.gif";
var pixWndImgIconeWnd      = null;                                //"./imagens/pixwnd-icone.gif";
var pixWndImgIconeMsg      = null;                                //"./imagens/pixwnd-icone.gif";
var pixWndImgClose         = null;                                //"./imagens/pixwnd-close.gif";
var pixWndImgLoading       = "./imagens/pixwnd-loading.gif";
var pixWndImgWarning       = "./imagens/pixwnd-information.gif"   //"./imagens/pixwnd-warning.gif";
var pixWndImgError         = "./imagens/pixwnd-information.gif"   //"./imagens/pixwnd-error.gif";
var pixWndImgInformation   = "./imagens/pixwnd-information.gif";
var pixWndImgConfirm       = "./imagens/pixwnd-confirm.gif";
var pixWndImgBgWarning     = "";                                  //"./imagens/pixwnd-bg-warning.gif";
var pixWndImgBgError       = "";                                  //"./imagens/pixwnd-bg-error.gif";
var pixWndImgBgInformation = "";                                  //"./imagens/pixwnd-bg-information.gif";
var pixWndImgBgConfirm     = "";                                  //"./imagens/pixwnd-bg-confirm.gif";
var pixWndImgBgBtn         = "./imagens/bot_ok_mai.gif";          //"./imagens/pixwnd-bg-btn-peq.jpg";

// Alerts e confirms (defaults)
var pixWndUseDefaultBrowserConfirm = false; // false: usa o confirm em forma de janela ao invés do confirm do browser
var pixWndMsgHasChanged            = "Os dados ainda não foram gravados.<br><br>Deseja realmente sair e abandonar as alterações realizadas?";
var pixWndLblOK                    = "";            //texto no botão
var pixWndLblYes                   = "";            //texto no botão
var pixWndLblNo                    = "";            //texto no botão
var pixWndCaptionAlertWarning      = "Aviso";
var pixWndCaptionAlertError        = "Erro";
var pixWndCaptionAlertInformation  = "Informação";
var pixWndCaptionConfirm           = "Confirmação";
var pixWndCaptionColor             = "white";
//------------------------------------------------------------------------------
// Fim das propriedades alteráveis
//------------------------------------------------------------------------------

var pixWndObjImgBgHead        = new Image();
var pixWndObjImgIconeWnd      = new Image();
var pixWndObjImgIconeMsg      = new Image();
var pixWndObjImgClose         = new Image();
var pixWndObjImgLoading       = new Image();
var pixWndObjImgWarning       = new Image();
var pixWndObjImgError         = new Image();
var pixWndObjImgInformation   = new Image();
var pixWndObjImgConfirm       = new Image();
var pixWndObjImgBgWarning     = new Image();
var pixWndObjImgBgError       = new Image();
var pixWndObjImgBgInformation = new Image();
var pixWndObjImgBgConfirm     = new Image();
var pixWndObjImgBgBtn         = new Image();

pixWndObjImgBgHead.src        = pixWndImgBgHead;
pixWndObjImgIconeWnd.src      = pixWndImgIconeWnd;
pixWndObjImgIconeMsg.src      = pixWndImgIconeMsg;
pixWndObjImgClose.src         = pixWndImgClose;
pixWndObjImgLoading.src       = pixWndImgLoading;
pixWndObjImgWarning.src       = pixWndImgWarning;
pixWndObjImgError.src         = pixWndImgError;
pixWndObjImgInformation.src   = pixWndImgInformation;
pixWndObjImgConfirm.src       = pixWndImgConfirm;
pixWndObjImgBgWarning.src     = pixWndImgBgWarning;
pixWndObjImgBgError.src       = pixWndImgBgError;
pixWndObjImgBgInformation.src = pixWndImgBgInformation;
pixWndObjImgBgConfirm.src     = pixWndImgBgConfirm;
pixWndObjImgBgBtn.src         = pixWndImgBgBtn;

var pixWndClickClose = false;

//------------------------------------------------------------------------------
// Funções "public"
//------------------------------------------------------------------------------
function pixWndOpen(width, height, url, caption, callback, validarClose, form, campos, pag_retorno)
{

formulario = form;
campo = campos;
pagina_retorno = pag_retorno;

	/*
	Cria uma janela e exibe um html (estático ou dinâmico) dentro dela

	Parâmetros:
	 width - largura da janela
	 height - altura da janela
	 url - url a ser carregada no iframe
	 caption - título da janela
	 callback - ação javascript caso o usuário feche pelo "X" (default: sem callback)
	 validarClose - determina se a janela deve, automaticamente, validar se algum campo de formulário foi alterado antes de fechar (default: true)
	*/

	var arrCallback = new Array("", "", "");
	if (callback)
	{
		arrCallback[ID_WND_BTN_OK] = callback;
	}

	if (validarClose == null)
	{
		validarClose = true;
	}

	var wnd = pixWndNew(width, height, caption, ID_WND_NORMAL, arrCallback, validarClose);

	// troca apenas o conteúdo da janela (diálogo)
	if (url)
	{
		wnd.replace(url);
	}

}

//------------------------------------------------------------------------------
function pixWndAlert(msg, caption, callback, idIcone, form, campos, pag_retorno)
{

	// Bruno Ponte.
	// resolução do problema quando já tiver uma caixa aberta,
	// não deixa abrir outra ao pressionar enter ou espaço.
	var wnd = pixWndGetCurrent();
	if(wnd != undefined){
		return false;
	}

	formulario = form;
	campo = campos;
	pagina_retorno = pag_retorno;

	/*
	Cria uma janela com um botão "OK", um ícone e uma mensagem.

	Parâmetros:
	 msg - mensagem a ser exibida. Pode conter trechos de html, como bold e quebra de linha
	 caption - título da janela
	 callback - ação javascript caso o usuário feche pelo "X" ou clique no botão "OK" (default: sem callback)
	 idIcone - imagem que será associada a mensagem (default: ID_WND_WARNING)
	  ID_WND_WARNING = 0
	  ID_WND_ERROR = 1
	  ID_WND_INFORMATION = 2
	*/

	if (idIcone == null)
	{
		idIcone = ID_WND_INFORMATION;
	}

	//caption default
	if (!caption)
	{
		switch (idIcone)
		{
			case ID_WND_WARNING:
				caption = pixWndCaptionAlertWarning;
				break;

			case ID_WND_ERROR:
				caption = pixWndCaptionAlertError;
				break;

			case ID_WND_INFORMATION:
				caption = pixWndCaptionAlertInformation;
				break;
		}
	}

	var arrCallback = new Array("", "", "");
	if (callback)
	{
		arrCallback[ID_WND_BTN_OK] = callback;
	}
	var wnd = pixWndNew(pixWndMsgDefaultWidth, pixWndMsgDefaultHeight, caption, ID_WND_ALERT, arrCallback, false);

	// Troca o conteúdo
	wnd.replaceAlert(msg, idIcone);

}

//------------------------------------------------------------------------------
function pixWndConfirm(msg, caption, callbackYes, callbackNo, form, campos, pag_retorno)
{

	formulario = form;
	campo = campos;
	pagina_retorno = pag_retorno;

	/*
	Cria uma janela com um botão "Sim", um "Não", um ícone e uma mensagem.

	Parâmetros:
	 msg - mensagem (pergunta) a ser exibida. Pode conter trechos de html, como bold e quebra de linha
	 caption - título da janela
	 callbackYes - ação javascript caso o usuário clique no botão "Sim" (default: sem callback)
	 callbackNo - ação javascript caso o usuário feche pelo "X" ou clique no botão "Não" (default: sem callback)
	*/

	if (!caption)

	{
		caption = pixWndCaptionConfirm;
	}

	var arrCallback = new Array("", "", "");

	if (callbackYes)
	{
		arrCallback[ID_WND_BTN_YES] = callbackYes;
	}
	if (callbackNo)
	{
		arrCallback[ID_WND_BTN_NO] = callbackNo;
	}

	var wnd = pixWndNew(pixWndMsgDefaultWidth, pixWndMsgDefaultHeight, caption, ID_WND_CONFIRM, arrCallback, false);

	// Troca o conteúdo
	wnd.replaceConfirm(msg);

}


// ----------------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------------- //

function pixWndInputBox(msg, caption, callbackYes, callbackNo, form, campos, pag_retorno, strQtdeDigitada) {

	// BRUNO PONTE. 08-12-2006.

	/*
	Cria uma janela com um botão "Sim", um "Não", um ícone, uma mensagem e uma caixa de texto.

	Parâmetros:
	 msg - mensagem (pergunta) a ser exibida. Pode conter trechos de html, como bold e quebra de linha
	 caption - título da janela
	 callbackYes - ação javascript caso o usuário clique no botão "Sim" (default: sem callback)
	 callbackNo - ação javascript caso o usuário feche pelo "X" ou clique no botão "Não" (default: sem callback)
	 form - nome do formulário que receberá o foco após ação javascript do botão Ok;
	 campos - nome do campo que receberá o foco após ação javascript do botão Ok;
	 pag_retorno - página que será executada após ação javascript do botão Ok;
	 strQtdeDigitada - quantidade anterior digitada, usado para caso queira que apareça no textbox. padrão é "".
	*/

	// Para usar a função 'somente_numeros' é necessário usar o arquivo util.js que possui a função.

	formulario = form;
	campo = campos;
	pagina_retorno = pag_retorno;

	if (!caption){
		caption = pixWndCaptionConfirm;
	}

	var arrCallback = new Array("", "", "");

	if (callbackYes){
		arrCallback[ID_WND_BTN_YES] = callbackYes;
	}

	if (callbackNo){
		arrCallback[ID_WND_BTN_NO] = callbackNo;
	}

	var wnd = pixWndNew(pixWndMsgDefaultWidth, pixWndMsgDefaultHeight, caption, ID_WND_CONFIRM, arrCallback, false);

	strQtdeDigitada = ""; //zerando o conteúdo inicial da caixa para padronizar. default é "".

	// Troca o conteúdo
	var caixa_texto = "<br> <FORM NAME=frmInputBox>";
	//caixa_texto = caixa_texto + "<Input TYPE='TEXT' NAME='QTDE' SIZE='35' MAXLENGTH='3' VALUE='" + strQtdeDigitada +  "' onKeyDown='return somente_numeros(this,event);' onKeyPress='dasabilita_enter(this,event);'>";
	caixa_texto = caixa_texto + "<Input TYPE='TEXT' NAME='QTDE' SIZE='35' MAXLENGTH='3' VALUE='" + strQtdeDigitada +  "' onKeyDown='return somente_numeros_inputbox(this,event);'>";

	msg = msg + "<center>" + caixa_texto + "</center>";
	wnd.replaceConfirm(msg);
}


function somente_numeros_inputbox(par,event)
{
	/*
  	Esta função retorna 'true' quando o caracter é numérico e false quando é não-numérico
	A chamada pela caixa de texto é: onKeyDown = 'return somente_numeros(this,event)'
	(0-9) -> Teclado: 48-57 ;
	NumPad: 96-105;
	BackSpace:8; Enter:13; Tab:9; End:35; Home:36; Shift:16;
	Setas: esq:37; cima:38; dir:39; baixo:40;
  	*/

	var x = event.keyCode;

  	//if (((x < 48) | (x > 57)) & ((x < 96) | (x > 105)) & ((x < 35) | (x > 40)) & (x != 8) & (x != 13) & (x != 9) & (x != 16))
  	if (((x < 48) | (x > 57)) & ((x < 96) | (x > 105)) & ((x < 35) | (x > 40)) & (x != 8) & (x != 9) & (x != 16))
	{
      		return false;
	}
	return true;
}

function dasabilita_enter(par,event) {

	//Bruno Ponte - 15/12/2006
	//função para desabilitar o enter do textbox, fazendo assim
	//com que o usuário seja obrigado a clicar no botão ok ou cancela.

	var tecla = event.keyCode;

	if ((tecla == 13)) {
		setTimeout(function(){window.location="javascript:void(0)"}, 1); // 0,5 segundo
		return false;
	}
}

function ativa_enter(form,funcaoValidacao,e,parametro) {

	//Bruno Ponte - 05/01/2007
	//verifica se enter foi pressionado e ativa seu submit.

	var tecla;

	if(window.event){ // Internet Explorer
		tecla = window.event.keyCode;
	} else if(e.keyCode) { // Netscape, Firefox e Opera
		tecla = e.keyCode;
	}

	if ((tecla == 13)) {
		if (eval(funcaoValidacao + "(parametro);") == true) {
			eval("document." + form + ".submit();");
		}
	}
}
// ----------------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------------- //



//------------------------------------------------------------------------------
function pixWndClose(callback, validarClose)
{

	/*
	Fecha a janela corrente e, opcionalmente, executa uma ação javascript

	Parâmetros:
	 callback - ação javascript a ser executada antes do fechamento da janela (default: sem callback)
	 validarClose - determina se a janela deve, automaticamente, validar se algum campo de formulário foi alterado antes de fechar (default: o valor atribuído no pixWndOpen)
	*/

	var wnd = pixWndGetCurrent();

	if (validarClose == null)
	{
		if (wnd)
		{
			validarClose = wnd.isValidarClose();
		}
		else
		{
			validarClose = false;
		}

	}

	if (validarClose && wnd.isChanged())
	{
		if (pixWndUseDefaultBrowserConfirm)
		{
			if (confirm(pixWndMsgHasChanged))
			{
				pixWndCloseAux(callback);
			}
		}
		else
		{
			var callbackAux = "setTimeout(function(){pixWndCloseAux(" + (callback ? "'" + callback + "'" : "") + ")}, 100)";
			pixWndConfirm(pixWndMsgHasChanged, pixWndCaptionConfirm, callbackAux, null,"frm","txtNome", "");
		}
	}
	else
	{
		pixWndCloseAux(callback);

	}
}

//------------------------------------------------------------------------------
function pixWndIsChanged(formName, deslocamento)
{


	/*
	Retorna true se algum campo de formulário da janela foi alterado pelo usuário

	Parâmetros:
	 formName - apenas este form será validado, senão todos serão
	 deslocamento - deslocamento em relação a janela corrente (o default é 0);
	*/

	var wnd = pixWndGetCurrent(deslocamento);
	if (wnd)
	{
		return wnd.isChanged(formName);
	}
	else
	{
		return false;
	}
}

//------------------------------------------------------------------------------
function pixWndSetChanged(forceChanged)
{


	/*
	Força o status de janela alterada pelo usuário

	Parâmetros:
	 forceChanged - o programdor pode "forçar" flag de janela alterada
	  ID_WND_CHANGED_AUTO = -1
	  ID_WND_CHANGED_FALSE = 0
	  ID_WND_CHANGED_TRUE = 1
	*/

	var wnd = pixWndGetCurrent();
	if (wnd)
	{
		wnd.setChanged(forceChanged);
	}
}

//------------------------------------------------------------------------------
function pixWndCallbackSetFocus(formName, fieldName, selectField, deslocamento)
{


	/*
	Retorna uma chamada javascript para setfocus para ser repassada como callback de pixWndAlert ou pixWndConfirm

	Parâmetros:
	 formName - nome do form
	 fieldName - nome do campo
	 selectField - true "pinta" o campo selecionando-o (o default é false)
	 deslocamento - deslocamento em relação a janela corrente (o default é -1);
	*/



	if (selectField == null)
	{
		selectField = false;
	}
	if (!deslocamento)
	{
		deslocamento = -1; // janela anterior
	}

	var myDocument;

	if (pixWnd.length == 0)
	{
		// Não tem janela, então setará o foco diretamente no campo
		myDocument = "document";

	}
	else
	{
		// Tem janela, então setará o foco indiretamente através do iframe
		var iframeName = pixWndGetNomeIframe(pixWnd.length + deslocamento);
		var myDocument = "(document.all ? window.frames[\"" + iframeName + "\"].document : document.getElementById(\"" + iframeName + "\").contentDocument)";
	}

	//teste Bruno - setando o foco
	//alert(myDocument + "." + formName + "." + fieldName)
	//alert (myDocument + "." + formName + "." + fieldName + ".focus()")   //document.catalogo.txtnome.focus()

	//teste Bruno
	var campo
	campo = (myDocument + "." + formName + "." + fieldName)

	if (formName != "") {
		return pixWndSetFocus(campo, selectField );
	}
	//

	//return "pixWndSetFocus('" + myDocument + "." + formName + "." + fieldName + "', " + selectField + ")";

}

//------------------------------------------------------------------------------
function pixWndGet(deslocamento)
{

	/*
	Retorna o "contexto" do iframe, permitindo que funções e campos da janela sejam acessados.

	Parâmetros:
	 deslocamento - deslocamento em relação a janela corrente (o default é 0);
	*/

	var wnd = pixWndGetCurrent(deslocamento);
	if (wnd && (wnd.getTipo() == ID_WND_NORMAL))
	{
		return wnd.getIFrameContext();
	}
	else
	{
		return null;
	}
}

//------------------------------------------------------------------------------
function pixWndOnload(deslocamento)
{

	/*
	Inicializa os campos dos forms da janela. Esse método é chamado automaticamente quando o onload da página do iframe é completado.

	O programador pode chamar esse método para reinicialar os valores iniciais. Ex: quando itens de combos são selecionados após o carregamento da tela (valores padrão).

	Parâmetros:
	 deslocamento - deslocamento em relação a janela corrente (o default é 0);
	*/

	if (!deslocamento)
	{
		deslocamento = 0;
	}

	var wnd = null;

	// Procura uma janela a partir da atual com deslocamento (despreza pixWndAlert e pixWndConfirm)
	for (var i = (pixWnd.length - 1 + deslocamento); i >= 0; i--)
	{
		var wnd = pixWnd[i];

		if (wnd && (wnd.getTipo() == ID_WND_NORMAL))
		{
			break;
		}
	}

	if (wnd && (wnd.getTipo() == ID_WND_NORMAL))
	{
		wnd.onload();
	}
}

//------------------------------------------------------------------------------
// Funções "private"
//------------------------------------------------------------------------------
function pixWndOnKeyDown(e)
{

	var wnd = pixWndGetCurrent();
	if (wnd)
	{
		wnd.onKeyDown(e);
	}
}

//------------------------------------------------------------------------------
function onPixWndMouseDown(e)
{

	var wnd = pixWndGetCurrent();
	if (wnd)
	{
		wnd.onMouseDown(e);
	}
}

//------------------------------------------------------------------------------
function onPixWndMouseMove(e)
{

	var wnd = pixWndGetCurrent();
	if (wnd)
	{
		wnd.onMouseMove(e);
	}
}

//------------------------------------------------------------------------------
function onPixWndMouseUp(e)
{

	var wnd = pixWndGetCurrent();
	if (wnd)
	{
		wnd.onMouseUp(e);
	}
}

//------------------------------------------------------------------------------
function pixWndNew(width, height, caption, wndType, arrCallback, validarClose)
{

	// Nova "janela"
	var id = pixWnd.length;

	var wnd = new PixWindow(id, width, height, wndType, arrCallback, validarClose);

	// Guarda no array de janelas
	pixWnd[id] = wnd;

	// Exibe a janela
	wnd.show(caption, "");

	return wnd;

}

//------------------------------------------------------------------------------
function pixWndGetCurrent(deslocamento)
{

	if (!deslocamento)
	{
		deslocamento = 0;
	}
	return pixWnd[pixWnd.length - 1 + deslocamento];
}

//------------------------------------------------------------------------------
function pixWndGetPrevious()
{

	return pixWnd[pixWnd.length - 2];
}

//------------------------------------------------------------------------------
function pixWndSetFocus(callback, selectField)
{


	if (callback)
	{
		var obj = eval(callback);
		if (obj)
		{
			try
			{
				obj.focus();

				if (selectField)
				{
					obj.select();
				}

			} catch(err){}
		}
	}
}

//------------------------------------------------------------------------------
function pixWndCloseAux(callback)
{


	var wnd = pixWndGetCurrent();

	if (wnd)
	{
		// Habilita campos que haviam sido desabilitados (proteção na página anterior)
		wnd.habilitaCampos(true);
	}

	// Avalia callback
	if (callback != null && callback != "")
	{
		eval(callback);
	}

	if (wnd)
	{
		// Fecha a janela
		wnd.close();
		//var t=setTimeout("wnd.close();",5000)
	}

	// Remove do array
	pixWnd.pop();
	//var z=setTimeout("pixWnd.pop();",5000)

}

//------------------------------------------------------------------------------
function pixWndCloseInterno(idBotao, clickIconeClose)
{


	var wnd = pixWndGetCurrent();
	var callback = "";
	pixWndClickClose = clickIconeClose;

	if (wnd)
	{
		callback = wnd.getCallback(idBotao)
	}

	pixWndClose(callback);
}

//---------------------------------------------------
function pixWndGetNomeIframe(id)
{

	return "pixwnd-iframe" + id;
}


//------------------------------------------------------------------------------
// Class PixWindow
//------------------------------------------------------------------------------
function PixWindow(id, pWidth, pHeight, wndType, arrCallback, validarClose)
{

	var width = pWidth;
	var height = pHeight;

	var frames = new PixFrames();
	var ifr = null;
	var dlg = null;
	var divMove = null;
	var isModal = false;

	var isIE = document.all;

	var dragOffsetX;
	var dragOffsetY;

	// Salva os eventos
	var evtFuncMouseUp = document.onmouseup;
	var evtFuncMouseMove = document.onmousemove;
	if (pixWndImgClose != null)
	{
		var evtFuncKeyDown = document.onkeydown;
	}

	// forms e campos do iframe (controle de alteração)
	var forms;

	// programdor pode "forçar" flag de janela alterada
	var forceChanged = ID_WND_CHANGED_AUTO;

	//--------------------------------------------------------------------------
	this.show = function(caption)
	{

		// Guarda todos os frames da página
		frames.addFrames();

		// Desabilita campos (proteção na página anterior)
		this.habilitaCampos(false);

		// Protege a página anterior
		isModal = true;
		this.doModal(true);

		// Exibe o diálogo
		dlg = getElementoDiv(caption);
		document.body.appendChild(dlg);

		// Iframe para proteger os selects e flash (o select fica por cima da div que protege a página anterior e, portanto, fica clicável.)
		// No firefox não protege o flash e não precisa para os selects, então não inclui porque gera o problema de não mostrar o cursor nos campos
		if (isIE)
		{
			ifr = getElementoIFrame(dlg);
			document.body.appendChild(ifr);
		}

		// Evento para fechar a janela com "esc" (primeira janela)
		//if (id == 0 && pixWndImgClose != null)
		//{
		//	document.onkeydown = this.onKeyDown;
		//}

		pixMaxZIndex++;
	}

	//--------------------------------------------------------------------------
	this.doModal = function(tornarModal)
	{

		if (!isModal)
		{
			return;
		}

		// Protege a página anterior
		for (var i = 0; i < frames.size(); i++)
		{
			var doc = (id == 0 ? frames.getDoc(i) : document);

			if (tornarModal)
			{
				// Guarda e inclui no html
				if (frames.isOpaco(i))
				{
					var pag = getElementoPaginaAnterior(doc);
					frames.setPag(i, pag);
					doc.body.appendChild(pag);
				}
			}
			else
			{
				// Remove do html
				if (frames.isOpaco(i))
				{
					doc.body.removeChild(frames.getPag(i));
				}
			}
		}

		if (!tornarModal)
		{
			isModal = false;
		}
	}

	//--------------------------------------------------------------------------
	this.habilitaCampos = function(habilitar)
	{

		// habilita os campos das páginas anteriores que haviam sido desabilitados
		for (var i = 0; i < frames.size(); i++)
		{
			// Campos
			var campos = frames.getCampos(i);
			if (campos)
			{
				for (var j = 0; j < campos.length; j++)
				{
					switch (campos[j].type)
					{
						case "text":
						case "password":
						case "file":
						case "textarea":
						case "checkbox":
						case "radio":
						case "select-one":
						case "select-multiple":
						{
							campos[j].disabled = !habilitar;
						}
					}
				}
			}

			// Links
			var links = frames.getLinks(i);
			if (links)
			{
				for (var j = 0; j < links.length; j++)
				{
					{
						var pixLink = links[j];
						var objLink = pixLink.obj;

						if (habilitar)
						{
							// Retorna os valores originais
							objLink.href = pixLink.href;
							objLink.onclick = pixLink.onclick;
						}
						else
						{
							// "Desabilita" o link
							objLink.href = "javascript:void(0)";
							objLink.onclick = "return false";

						}
					}
				}
			}
		}
	}

	//--------------------------------------------------------------------------


	this.close = function()
	{

		// Remove janela
		document.body.removeChild(dlg);

		// Remove iframe
		if (isIE)
		{
			document.body.removeChild(ifr);
		}


		// Remove evento para fechar a janela com "esc" (primeira janela)
		if (id == 0 && pixWndImgClose != null)
		{
			document.onkeydown = evtFuncKeyDown;
		}

		// Retira proteções da página anterior
		this.doModal(false);

	}

	//--------------------------------------------------------------------------
	this.replace = function(url)
	{
		getIFrameObj().src = url;
	}

	//--------------------------------------------------------------------------
	this.getIFrameContext = function()
	{
		return window.frames[pixWndGetNomeIframe(id)];
	}

	//--------------------------------------------------------------------------
	this.replaceAlert = function(msg, idIcone)
	{

		var html;
		switch (idIcone)
		{
			case ID_WND_WARNING:
				html = getHtmlMsg(ID_WND_WARNING).replace("#msg#", msg);
				break;

			case ID_WND_ERROR:
				html = getHtmlMsg(ID_WND_ERROR).replace("#msg#", msg);
				break;

			case ID_WND_INFORMATION:
				html = getHtmlMsg(ID_WND_INFORMATION).replace("#msg#", msg);
				break;
		}

		html = html.replace("#callbackOK#", getCallback(ID_WND_BTN_OK));

		replaceContent(html);
		ajustaAlturaWnd();

		// botão default (OK)
		var btn = document.getElementById("pixWndBtn" + ID_WND_BTN_OK);
		//btn.focus() //joga o foco no botão de ok
	}

	//--------------------------------------------------------------------------
	this.replaceConfirm = function(msg)
	{

		var html = getHtmlMsg(ID_WND_QUESTION).replace("#msg#", msg);
		html = html.replace("#callbackYes#", getCallback(ID_WND_BTN_YES));
		html = html.replace("#callbackNo#", getCallback(ID_WND_BTN_NO));

		replaceContent(html);
		ajustaAlturaWnd();

		// botão default (NO) - este botão receberá o foco
		//var btn = document.getElementById("pixWndBtn" + ID_WND_BTN_NO);
		//btn.focus() //joga o foco no botão de cancela

		// teste retirar depois as 2 linhas abaixo
		// botão default (OK)
		//alert("passou");
		var btn = document.getElementById("pixWndBtn" + ID_WND_BTN_NO);
		//btn.focus() //joga o foco no botão de ok

	}

	//------------------------------------------------------------------------------
	function getHtmlMsg(idIcone)
	{

		var myHeight = pixWndMsgDefaultHeight - (document.all ? 26 : 22);  //26:22
		var myImg;
		var myBgImg;

		switch(idIcone)
		{
			case ID_WND_WARNING:
				myImg = pixWndImgWarning;
				myBgImg = pixWndImgBgWarning;
				break;

			case ID_WND_ERROR:
				myImg = pixWndImgError;
				myBgImg = pixWndImgBgError;
				break;

			case ID_WND_INFORMATION:
				myImg = pixWndImgInformation;
				myBgImg = pixWndImgBgInformation;
				break;

			case ID_WND_QUESTION:
				myImg = pixWndImgConfirm;
				myBgImg = pixWndImgBgConfirm;
				break;
		}


		//Posição do Botão. Bruno Ponte
		var containerAlert = ""
			+ "width:" + (isIE ? 100 : 99) + "%;" //padrão 100%
			+ "height:" + myHeight + "px;"
			+ "background: url(" + myBgImg + ") no-repeat;"
			+ "margin:1px;" //padrão 4px
			+ "padding: 0 2px;" //padrão 2px      + (isIE ? 2 : -20) +
			+ "text-align: left;";

		var imgAlert = ""
			+ "float:left;"
			+ "margin: 20px 0 0 1px;"
			+ "_margin: 22px 0 0 0;";  // BrunoPonte - altura do ícone. padrão é 20px

		var classTexto = ""
			+ "float:left;"
			+ "width:89%;" //BrunoPonte - largura do texto mostrado na tela. padrão 80%
			+ "margin: 0 auto;"
			+ "padding: 20px 0 20px 0;" // 40 - 30 é o padrão.
			+ "font: 12px/16px verdana, arial, sans-serif;";

		var classTextoP = ""
			+ "font-size:11px;"
			+ "text-align:center;" //alinhamento do texto apresentado na tela. center é o padrão
			+ "padding:0 5px;"
			+ "margin:0;"
			+ "height:auto;";

		var classClear = ""
			+ "clear:both;"
			+ "height:.1em;"
			+ "font-size:.1em;"
			+ "line-height:.1em;";

		var classRight = ""
			+ "display:block;"
			+ "float:right;";


		var classBt = ""
			+ "display: block;"
			+ "color: #666;"
			+ "height: 23px;"
			+ "line-height: 20px;"
			+ "font-family:verdana, arial, sans-serif;"
			+ "font-size:11px;"
			+ "font-weight: bold;"
			+ "text-align: center;"
			+ "text-decoration: none;"
			+ "border-bottom: 0px solid #666;"
			+ "border-right: 0px solid #666;"
			+ "padding: 0 3px;" //3 default
			+ "margin: 0;"
			+ "white-space: nowrap;"   //pixWndImgBgBtn
			+ "background: url(" + pixWndImgBgBtn + ") repeat-x;"
			+ "width:" + (isIE? 35 : 28) + "px;" //35 IE, 28 Firefox ..Bruno 26/09/2007


		var html = "";
		html += "<div id='" + getNomeDivMsgContainer() + "' style='" + containerAlert + "'>";
		//html += "<table><tr><td>ss</td></tr></table>";
		html += "  <img src='" + myImg + "' width='30' height='26' alt='' style='" + imgAlert + "'>";
		html += "  <div id='" + getNomeDivMsgTexto() + "' style='" + classTexto + "'>";
		html += "    <p style='" + classTextoP + "'>#msg#</p>";
		html += "  </div><br style='" + classClear + "' />";

	//teste bruno
	if (pagina_retorno == "")
	{
		pagina_retorno = "javascript:void(0)";
	}



		var htmlBtn = "<p style='" + classTextoP + classRight + "'><a id='pixWndBtn#idBotao#' style='" + classBt + "' href='" + pagina_retorno + "' onclick=\"pixWndCloseInterno(#idBotao#, false)\;pixWndCallbackSetFocus(formulario,campo, true, -1)\;strChamaFuncao\">#btn#</a></p>";
		//var htmlBtn = "<p style='" + classTextoP + classRight + "'><a id='pixWndBtn#idBotao#' style='" + classBt + "' href='" + pagina_retorno + "'  onclick=\pixWndCloseInterno"(#idBotao#, false)\;pixWndCallbackSetFocus(formulario,campo, true, -1)\">#btn#</a></p>";
		//var htmlBtn = "<p style='" + classTextoP + classRight + "'><a id='pixWndBtn#idBotao#' style='" + classBt + "' href='" + pagina_retorno + "'>#btn#</a></p>";
		//var htmlBtn = "<p style='" + classTextoP + classRight + "'><a id='pixWndBtn#idBotao#' style='" + classBt + "' href='" + pagina_retorno + "'  onclick='return true'>#btn#</a></p>";

		if (idIcone == ID_WND_QUESTION)
		{
			var btNo = htmlBtn.replace("#btn#", pixWndLblNo);
			btNo = btNo.replace(/\#idBotao\#/g, ""+ID_WND_BTN_NO);

			//troca a imagem e largura do segundo botão de ok por cancela.
			btNo = btNo.replace("bot_ok_mai.gif", "bot.cancela.gif");
			btNo = btNo.replace("width:" + (isIE ? 35 : 28) + "px;", "width:" + (isIE ? 70 : 64) + "px;");
			btNo = btNo.replace(pagina_retorno, "javascript:void(0)"); //botao 'cancela' nao possuirá função

			html += btNo;

			var btYes = htmlBtn.replace("#btn#", pixWndLblYes);
			btYes = btYes.replace(/\#idBotao\#/g, ""+ID_WND_BTN_YES);
			html += btYes;

		}
		else
		{
			var btOK = htmlBtn.replace("#btn#", pixWndLblOK);
			btOK = btOK.replace(/\#idBotao\#/g, ""+ID_WND_BTN_OK);
			html += btOK;
		}

		html += "<br style='" + classClear + "' />";
		html += "</div>";

		return html;
	}

	//--------------------------------------------------------------------------
	this.getDlg = function()
	{
		return dlg;
	}

	//---------------------------------------------------
	this.onMouseDown = function(e)
	{

		document.onmouseup = this.onMouseUp;
		document.onmousemove = this.onMouseMove;

		dragOffsetX = e.clientX - numberFromCSS(dlg.style.left);
		dragOffsetY = e.clientY - numberFromCSS(dlg.style.top);

		if (isIE && !e)
		{
			e = window.event;
		}
		eventConsume(e);
	}

	//---------------------------------------------------
	this.onKeyDown = function(e)
	{


		if (isIE && !e)
		{
			e = window.event;
		}

		if (e && e.keyCode == 27)
		{
			var callback = getCallback().replace(/&quot;/g, "\"");
			pixWndClose(callback);
		}
	}

	//---------------------------------------------------
	this.onMouseMove = function(e)
	{

		if (pixWndClickClose)
		{
			document.onmousemove = evtFuncMouseMove;
			document.onmouseup = evtFuncMouseUp;
			pixWndClickClose = false;
			return;
		}

		if (isIE && !e)
		{
			e = window.event;
		}

		// Move com o botão pressionado (drag)
		if ((isIE && e.button == 1) || (!isIE && (e.button == 65535 || e.button == 0)))
		{
			document.body.style.cursor = "move";
			protegeIFrame(true);

			// Reposiciona
			dlg.style.left = (e.clientX - dragOffsetX) + "px";;
			dlg.style.top = (e.clientY - dragOffsetY) + "px";;

			if (isIE)
			{
				ifr.style.left = dlg.style.left;
				ifr.style.top = dlg.style.top;
			}
		}
		eventConsume(e);
	}

	//---------------------------------------------------
	this.onMouseUp = function(e)
	{

		document.onmousemove = evtFuncMouseMove;
		document.onmouseup = evtFuncMouseUp;
		pixWndClickClose = false;

		document.body.style.cursor = "default";
		protegeIFrame(false);

		if (isIE && !e)
		{
			e = window.event;
		}

		eventConsume(e);
	}

	//---------------------------------------------------
	this.onload = function()
	{
		// Desliga "carregando"
		var divMsg = document.getElementById(getNomeDivContent() + "-msg");
		if (divMsg)
		{
			divMsg.innerHTML = "";
			divMsg.style.display = "none";
		}

		// buscar forms
		if (validarClose)
		{
			try
			{
				var doc = (isIE? this.getIFrameContext().document : getIFrameObj().contentDocument);
				forms = new PixForms(doc);
			}
			catch (err)
			{
				validarClose = false;
			}
		}

		// Parar o status de loading do browser
		try{location.replace("javascript:void(0)")}catch(err){};
	}

	//--------------------------------------------------------------------------
	this.setChanged = function(pForceChanged)
	{
		forceChanged = pForceChanged;
	}


	//---------------------------------------------------
	this.isValidarClose = function()
	{
		return validarClose;
	}

	//---------------------------------------------------
	this.isChanged = function(formName)
	{
		switch(forceChanged)
		{
			case ID_WND_CHANGED_FALSE:
				return false;

			case ID_WND_CHANGED_TRUE:
				return true;

			case ID_WND_CHANGED_AUTO:
			default:
				try
				{
					return forms.isChanged(formName);
				}
				catch (err)
				{
					return false;
				}

		}
	}

	//---------------------------------------------------
	this.getTipo = function()
	{
		return wndType;
	}

	//---------------------------------------------------
	function getNomeDivHeader()
	{
		return "pixwnd-div-header" + id;
	}

	//---------------------------------------------------
	function getNomeDivContent()
	{
		return "pixwnd-div-content" + id;
	}

	//---------------------------------------------------
	function getNomeDivMsgContainer()
	{
		return "pixwnd-div-msg-container" + id;
	}

	//---------------------------------------------------
	function getNomeDivMsgTexto()
	{
		return "pixwnd-div-msg-texto" + id;
	}

	//---------------------------------------------------
	function getNomeImgClose()
	{
		return "pixwnd-img-close" + id;
	}

	//---------------------------------------------------
	function ajustaAlturaWnd()
	{

		// Busca os elementos
		var divContent = document.getElementById(getNomeDivContent());
		var divContainer = document.getElementById(getNomeDivMsgContainer());
		var divTexto = document.getElementById(getNomeDivMsgTexto());
		var novaHeight = divTexto.offsetHeight + (isIE ? 51 : 47);

		// Esconde para redimensionar
		dlg.style.display = "none";
		if (isIE)
		{
			ifr.style.display = "none";
		}

		// Redimensiona e reposiciona o dlg
		dlg.style.height = novaHeight + "px";
		dlg.style.top = (((document.body.clientHeight - novaHeight) / 2) + document.body.scrollTop) + "px";

		// Redimensiona e reposiciona o diálogo
		divContent.style.height = (novaHeight - (isIE ? 24 : 20)) + "px";
		divContainer.style.height = divContent.style.height;

		// Redimensiona e reposiciona o iframe
		if (isIE)
		{
			ifr.style.left = dlg.style.left;
			ifr.style.top = dlg.style.top;
			ifr.style.height = dlg.style.height;
			ifr.style.top = dlg.style.top;
		}

		// Mostra novamente
		dlg.style.display = "inline";
		if (isIE)
		{
			ifr.style.display = "inline";
		}
	}

	//---------------------------------------------------
	this.getCallback = function(idBotao)
	{
		return getCallback(idBotao);
	}

	//---------------------------------------------------
	function getCallback(idBotao)
	{

		var callback = "";

		if (!idBotao)
		{
			switch (wndType)
			{
				case ID_WND_NORMAL:
				case ID_WND_ALERT:
					idBotao = ID_WND_BTN_OK;
					break;
				case ID_WND_CONFIRM:
					idBotao = ID_WND_BTN_NO;
					break;
			}
		}

		if (arrCallback[idBotao])
		{
			callback = arrCallback[idBotao];
		}

		return callback;
	}

	//---------------------------------------------------
	function protegeIFrame(param)
	{

		if (wndType == ID_WND_NORMAL)
		{
			if (param)
			{
				if (!divMove)
				{
					divMove = getElementoDivMove(dlg);
					dlg.appendChild(divMove);
				}
			}
			else
			{
				if (divMove)
				{
					dlg.removeChild(divMove);
					divMove = null;
				}
			}
		}
	}

	//--------------------------------------------------------------------------
	function getIFrameObj()
	{
		return document.getElementById(pixWndGetNomeIframe(id));
	}

	//--------------------------------------------------------------------------
	function replaceContent(content)
	{
		var obj = document.getElementById(getNomeDivContent());
		obj.innerHTML = content;
	}

	//--------------------------------------------------------------------------
	function getElementoPaginaAnterior(doc)
	{

		var obj = doc.createElement("div");
		obj.style.position = "absolute";
		obj.style.display = "inline";
		obj.style.border = 0;
		obj.style.zIndex = ++pixMaxZIndex;

		if (pixWnd.length == 1)
		{
			// Primeiro diálogo: protege a página toda
			obj.style.top = 0;
			obj.style.left = 0;
			obj.style.width = document.body.scrollWidth + "px";
			obj.style.height = document.body.scrollHeight + "px";
		}
		else
		{
			// Segundo diálogo em diante: protege apenas o diálogo anterior
			var dlgAnterior = pixWndGetPrevious().getDlg();
			obj.style.top = dlgAnterior.style.top;
			obj.style.left = dlgAnterior.style.left;
			obj.style.width = (isIE ? dlgAnterior.style.width : (numberFromCSS(dlgAnterior.style.width) + 4) + "px");
			obj.style.height = (isIE ? dlgAnterior.style.height : (numberFromCSS(dlgAnterior.style.height) + 4) + "px");
		}

		var html = "<div style='"
			+ " position:absolute;"
			+ " display:inline;"
			+ " border:0;"
			+ " z-index:" + (pixMaxZIndex - 1) + ";"
			+ " background-color:#ffffff;"
			+ " top:0;"
			+ " left:0;"
			+ " width:" + obj.style.width + ";"
			+ " height:" + obj.style.height + ";";
		if (isIE)
		{
			html += " filter:alpha(opacity=50);";
		}

		html += " -moz-opacity:.50; opacity:.50;"
			 + "'></div>";

		obj.innerHTML = html;

		return obj;
	}

	//--------------------------------------------------------------------------
	function getElementoIFrame(div)
	{

		var obj = document.createElement("iframe");

		obj.style.position = "absolute";
		obj.style.display  = "inline";
		obj.style.border   = 0;
		obj.style.padding  = 0;
		obj.style.zIndex   = div.style.zIndex - 1;
		obj.style.top      = div.style.top;
		obj.style.left     = div.style.left;
		obj.style.width    = div.style.width;
		obj.style.height   = div.style.height;

		return obj;
	}

	//--------------------------------------------------------------------------
	function getElementoDiv(caption)
	{

		var headerHeight = 20;
		var mainHeight = height - headerHeight - (isIE ? 4 : 0);
		var imgWidth = 16;
		var imgHeight = 16;

		var obj = document.createElement("div");
		obj.style.position = "absolute";
		obj.style.display = "inline";
		obj.style.border = "2px solid";
		obj.style.borderStyle = "outset";
		obj.style.padding = 0;
		obj.style.zIndex = ++pixMaxZIndex;
		obj.style.backgroundColor = "#FFF0F5";
		obj.style.top = (((document.body.clientHeight - height) / 2) + document.body.scrollTop) + "px";
		obj.style.left = (((document.body.clientWidth - width) / 2) + document.body.scrollLeft) + "px";
		obj.style.width = width + "px";
		obj.style.height = height + "px";

		var header = "<div id='" + getNomeDivHeader() + "' onmousedown='onPixWndMouseDown(event);' align='left' style='"
			+ " position:absolute;"
			+ " display:block;"
			+ " border:0;"
			+ " background:#ffc0cb;"  //cor de fundo do cabeçalho
			//+ " background: url(" + pixWndImgBgHead + ") repeat-x;"
			+ " top:0;"
			+ " left:0;"
			+ " width:" + (isIE ? width - 4 : width) + "px;"
			+ " height:" + headerHeight + "px;"
			+ "'>";

		var leftCaption = 2;

		var imgIcone = (wndType == ID_WND_NORMAL ? pixWndImgIconeWnd : pixWndImgIconeMsg);

		if (imgIcone != null)
		{
			leftCaption += imgWidth;
			header += "<img style='"
				+ " position:absolute;"
				+ " top:2px;"
				+ " left:2px;"
				+ " background:url(" + imgIcone + ") no-repeat;"
				+ "' src='" + imgIcone + "' width=" + imgWidth + " height=" + imgHeight + " border=0 vspace=0 hspace=0>";
		}

		header += "<label style='"
			+ " position:absolute;"
			+ " white-space: nowrap;"
			+ " top:1;"
			+ " left:" + leftCaption + "px;"
			+ " color:" + pixWndCaptionColor + ";"
			+ " font:13px verdana, arial, sans-serif;"
			+ " font-weight:bold;"
			+ " '>&nbsp;" + caption + "</label>";

		if (pixWndImgClose != null)
		{
			header += "<img id='" + getNomeImgClose() + "' style='"
				+ " position:absolute;"
				+ " cursor:hand;"
				+ " top:2;"
				+ " left:" + (width - imgWidth - (isIE ? 6 : 2)) + "px;"
				+ " background:url(" + pixWndImgClose + ") no-repeat;"
				+ "' src='" + pixWndImgClose + "' onmousedown=\"this.style.cursor='default'; pixWndCloseInterno(" + (wndType == ID_WND_CONFIRM ? ID_WND_BTN_NO : ID_WND_BTN_OK) + ", true);\" width=" + imgWidth + " height=" + imgHeight + " border=0 vspace=0 hspace=0>";
		}

		header += "</div>";

		var main = "<div id='" + getNomeDivContent() + "' style='"
			+ " width:" + (isIE ? width - 4 : width) + "px;"
			+ " height:" + mainHeight + "px;"
			+ " position:absolute;"
			+ " display:block;"
			+ " border:0;"
			+ " top:" + (headerHeight) + "px;"
			+ " left:0;"
			+ "'><div id='" + getNomeDivContent() + "-msg' style='display:block; position:absolute; top:0; left:0;'>" + getImgLoading() + "</div>"

			+ "<iframe id='" + pixWndGetNomeIframe(id) + "' name='" + pixWndGetNomeIframe(id) + "' frameborder=0 scrolling='" + pixWndIframeScrolling + "' style='"
			+ " width:" + (isIE ? width - 4 : width) + "px;"
			+ " height:" + mainHeight + "px;"
			+ "' onload='pixWndOnload();'"
			+ "></iframe>";
			+ "</div>";

		obj.innerHTML = header + main;

		return obj;
	}

	//--------------------------------------------------------------------------
	function getElementoDivMove(div)
	{

		var obj = document.createElement("div");

		obj.style.position = "absolute";
		obj.style.display  = "inline";
		obj.style.border   = 0;
		obj.style.padding  = 0;
		obj.style.zIndex   = ++pixMaxZIndex;
		obj.style.top      = 21;
		obj.style.left     = 0;
		obj.style.width    = (numberFromCSS(div.style.width) - 4) + "px";
		obj.style.height   = (numberFromCSS(div.style.height) - 25) + "px";

		return obj;
	}

	//---------------------------------------------------
	function getImgLoading()
	{

		var headerHeight = 20;
		var left = (width - pixWndObjImgLoading.width) / 2;
		var top  = ((height - headerHeight - pixWndObjImgLoading.height) / 2);

		return "<img src='" + pixWndImgLoading + "' style='position:absolute; left:" + left + "px; top:" + top + "px;'>";
	}

	//---------------------------------------------------
	function numberFromCSS(numStr)
	{

		var ret = numStr;
		if (typeof numStr == 'string')
		{
			if (numStr.length > 2)
			{
				// Verifica as duas últimas posições ("px" em css, etc)
				if (isNaN(numStr.substring(numStr.length - 2, numStr.length)))
				{
					ret = numStr.substring(0, numStr.length - 2);
				}
			}
		}
		return Number(ret);
	}

	//---------------------------------------------------
	function eventConsume(e)
	{

		if (!e)
		{
			return;
		}

		if (e.stopPropagation)
		{
			e.stopPropagation();
			e.preventDefault();
		}
		else if (e.cancelBubble)
		{
			e.cancelBubble = true;
			e.returnValue  = false;
		}
	}

	//--------------------------------------------------------------------------
	function PixFrames()
	{

		var frames = new Array();

		//----------------------------------------------------------------------
		this.addFrames = function()
		{

			if (pixWnd.length == 1)
			{
				// Primeira janela, então protege todos os documents
				var arrDocs = new Array();

				// Busca os frames da janela
				var arrFrames = top.document.getElementsByTagName("frame");
				if (arrFrames.length > 0)
				{
					// Varre os frames e guarda os documents
					for (var i = 0; i < arrFrames.length; i++)
					{
						if (isIE)
						{
							arrDocs[arrDocs.length] = top.frames[i].document;
						}
						else
						{
							arrDocs[arrDocs.length] = arrFrames[i].contentDocument;
						}
					}
				}
				else
				{
					// Único documento
					arrDocs[arrDocs.length] = top.document;
				}

				// Varre os documents
				for (var i = 0; i < arrDocs.length; i++)
				{
					var doc = arrDocs[i];

					// Guarda document
					this.add(doc, true);
				}
			}
			else
			{
				// Segunda janela em diante, então busca a anterior

				var wnd = pixWnd[pixWnd.length - 2];

				if (wnd && (wnd.getTipo() == ID_WND_NORMAL))
				{
					var nomeIFrame = pixWndGetNomeIframe(pixWnd.length - 2);
					var doc = (isIE? window.frames[nomeIFrame].document : document.getElementById(nomeIFrame).contentDocument);

					this.add(doc, true);
				}
			}
		}

		//----------------------------------------------------------------------
		this.add = function(pDoc, opaco)
		{

			// Guarda o doc
			var frame = new PixFrame();
			frame.add(pDoc, opaco);
			frames[frames.length] = frame;

			// Recursão para os iframes do document
			var arrIframes = pDoc.getElementsByTagName("iframe");
			for (var j = 0; j < arrIframes.length; j++)
			{
				var docIframe;
				if (isIE)
				{
					docIframe = pDoc.frames[j].document;
				}
				else
				{
					docIframe = arrIframes[j].contentDocument;
				}
				this.add(docIframe, false);
			}
		}

		//----------------------------------------------------------------------
		this.size = function()
		{
			return frames.length;
		}

		//----------------------------------------------------------------------
		this.getDoc = function(i)
		{
			return frames[i].getDoc();
		}

		//----------------------------------------------------------------------
		this.setPag = function(i, pPag)
		{
			frames[i].setPag(pPag);
		}

		//----------------------------------------------------------------------
		this.getPag = function(i)
		{
			return frames[i].getPag();
		}

		//----------------------------------------------------------------------
		this.isOpaco = function(i)
		{
			return frames[i].isOpaco();
		}

		//----------------------------------------------------------------------
		this.getCampos = function(i)
		{
			return frames[i].getCampos();
		}

		//----------------------------------------------------------------------
		this.getLinks = function(i)
		{
			return frames[i].getLinks();
		}

		//----------------------------------------------------------------------
		function PixFrame()
		{

			var doc = null;
			var pag = null;
			var opaco = true;
			var campos = new Array();
			var links = new Array();

			//----------------------------------------------------------------------
			this.add = function(pDoc, pOpaco)
			{

				doc = pDoc;
				opaco = pOpaco;

				// Guarda apenas os campos que estavam habilitados
				if (doc)
				{
					this.guardaElementos(doc.getElementsByTagName("select"));
					this.guardaElementos(doc.getElementsByTagName("input"));
					this.guardaElementos(doc.getElementsByTagName("textarea"));
					this.guardaElementos(doc.getElementsByTagName("a"));
				}
			}

			//----------------------------------------------------------------------
			this.guardaElementos = function(arr)
			{

				for (var i = 0; i < arr.length; i++)
				{
					switch (arr[i].type)
					{
						case "text":
						case "password":
						case "file":
						case "textarea":
						case "checkbox":
						case "radio":
						case "select-one":
						case "select-multiple":
						{
							if (arr[i] && !arr[i].disabled)
							{
								campos[campos.length] = arr[i];
							}
							break;
						}
						default: // links
						{
							if (((arr[i].href != null) && (arr[i].href != "undefined") &&  (arr[i].href != "javascript:void(0)"))
							 || ((arr[i].onclick != null) && (arr[i].onclick != "undefined") && (arr[i].onclick != "return false")))
							{
								var link = new PixLink(arr[i])
								links[links.length] = link;
							}
							break;
						}
					}
				}
			}

			//----------------------------------------------------------------------
			this.getDoc = function()
			{
				return doc;
			}

			//----------------------------------------------------------------------
			this.getPag = function()
			{
				return pag;
			}

			//----------------------------------------------------------------------
			this.setPag = function(pPag)
			{
				pag = pPag;
			}

			//----------------------------------------------------------------------
			this.isOpaco = function()
			{
				return opaco;
			}

			//----------------------------------------------------------------------
			this.getCampos = function()
			{
				return campos;
			}

			//----------------------------------------------------------------------
			this.getLinks = function()
			{
				return links;
			}
		}
	}

	//--------------------------------------------------------------------------
	function PixForms(pDoc)
	{

		var doc = pDoc;
		var forms = new Array();

		// Busca os forms
		var arrForms = doc.getElementsByTagName("form");
		for (var i = 0; i < arrForms.length; i++)
		{
			forms[forms.length] = new PixForm(pDoc, arrForms[i]);
		}

		//--------------------------------------------------------------------------
		this.isChanged = function(formName)
		{
			var changed = false;

			for (var i = 0; i < forms.length; i++)
			{
				var form = forms[i];
				var validar = true;

				if (formName)
				{
					if (formName != form.name)
					{
						validar = false;
					}
				}

				if (validar)
				{
					changed = form.isChanged();
				}

				if (changed)
				{
					break;
				}
			}

			return changed;
		}

		//--------------------------------------------------------------------------
		function PixForm(pDoc, pForm)
		{
			var doc = pDoc;
			var form = pForm;
			var fields = new Array();

			this.name = form.name;
			this.id = form.id;

			// Busca os campos
			var arrElements = form.elements;
			for (var i = 0; i < arrElements.length; i++)
			{
				// Atributos do campo
				var pixField = new PixField();
				pixField.name = arrElements[i].name;
				pixField.id = arrElements[i].id;
				pixField.type = arrElements[i].type;

				switch (arrElements[i].type)
				{
					case "text":
					case "password":
					case "file":
					case "textarea":
					{
						pixField.value = arrElements[i].value;
						break;
					}
					case "checkbox":
					{
						pixField.checked = arrElements[i].checked;
						break;
					}
					case "radio":
					{
						pixField.value = arrElements[i].value;
						pixField.checked = arrElements[i].checked;
						break;
					}
					case "select-one":
					{
						pixField.selected = arrElements[i].selectedIndex;
						break;
					}
					case "select-multiple":
					{
						var arrSelected = new Array();
						for(j = 0; j < arrElements[i].options.length; j++)
						{
							if (arrElements[i].options[j].selected)
							{
								arrSelected[arrSelected.length] = j;
							}
						}
						pixField.selected = arrSelected;
						break;
					}
				}

				// Guarda o campo
				fields[fields.length] = pixField;
			}

			//--------------------------------------------------------------------------
			this.isChanged = function()
			{
				var changed = false;

				for (var i = 0; i < fields.length; i++)
				{
					var pixField = fields[i];
					var formField = null;

					if (pixField.name)
					{
						formField = eval("doc." + form.name + "." + pixField.name);
					}
					else if (pixField.id)
					{
						formField = doc.getElementById(pixField.id);
					}

					if (formField)
					{
						switch (pixField.type)
						{
							case "text":
							case "password":
							case "file":
							case "textarea":
							{
								if (pixField.value != formField.value)
								{
									changed = true;
								}
								break;
							}
							case "checkbox":
							{
								if (pixField.checked != formField.checked)
								{
									changed = true;
								}
								break;
							}
							case "radio":
							{
								// neste caso, formField tem um array de "radio"
								for(j = 0; j < formField.length; j++)
								{
									if ((pixField.value == formField[j].value) && (pixField.checked != formField[j].checked))
									{
										changed = true;
									}
								}
								break;
							}
							case "select-one":
							{
								if (pixField.selected != formField.selectedIndex)
								{
									changed = true;
								}
								break;
							}
							case "select-multiple":
							{
								var arrSelected = new Array();
								for(j = 0; j < formField.options.length; j++)
								{
									if (formField.options[j].selected)
									{
										arrSelected[arrSelected.length] = j;
									}
								}
								if (pixField.selected.toString() != arrSelected.toString())
								{
									changed = true;
								}
								break;
							}
						}
						if (changed)
						{
							break;
						}
					}
				}
				return changed;
			}
		}

		//--------------------------------------------------------------------------
		function PixField()
		{
			this.name = null;
			this.id = null;
			this.type = null;
			this.value = null;
			this.checked = null;
			this.selected = null;
		}
	}

	//--------------------------------------------------------------------------
	function PixLink(pObj)
	{
		this.obj = pObj;
		this.href = pObj.href;
		this.onclick = pObj.onclick;
	}


}


