/**
* VARIÁVEIS GLOBAIS.
**/
var timeAlert = 0;  // TEMPO DE DURAÇÃO DO ALERTA NA TELA.
var interval;		// VARIÁVEL DO TIMER.
var alertIndex = 0; // ÍNDICE DE POSIÇÃO DA FILA DE ALERTAS.
var arrayFila = new Array(); // ARRAY DE FILA DE ALERTAS.

/**
* FUNÇÃO RESPONSÁVEL PELA EXIBIÇÃO DO ALERTA.
**/
function showQAlert(msg, pars){
	// ADICIONA O ALERTA NA FILA.
	arrayFila.push({message: msg, parameters: pars});

	// VERIFICA SE O ALERTA É O PRIMEIRO DA FILA.
	if(arrayFila.length == 1){
		myQAlert = new QAlert();
		myQAlert.definePars(msg, pars);
		myQAlert.defineElements();
		myQAlert.getAlert();

		alertIndex++;
	}
}

/**
* FUNÇÃO RESPONSAVEL PELO FECHAMENTO DO ALERTA.
**/
function closeAlert(nameDiv){
	fechaObjeto(nameDiv);
	showLayerCombos();

	// VERIFICA SE EXISTEM ALERTAS NA FILA.
	if(alertIndex < arrayFila.length){
		// EXIBE O PRÓXIMO ALERTA DA FILA.
		myQAlert = new QAlert();
		myQAlert.definePars(arrayFila[alertIndex].message, arrayFila[alertIndex].parameters);
		myQAlert.defineElements();
		myQAlert.getAlert();

		alertIndex++;
	}else{
		// LIMPA A FILA E O ÍNDICE DE POSIÇÃO DE ALERTAS.
		arrayFila = new Array();
		alertIndex = 0;
	}
}

/**
* FUNÇÃO QUE VERIFICA O CLIQUE DA TECLA "ESC".
**/
function escExec(nmDiv){
	if(window.event){
		var keyCode = window.event.keyCode;
		if(keyCode == 27)
			closeAlert(nmDiv);
	}
}

/**
* FUNÇÃO DE TIMER DO ALERTA.
**/
function timerQAlert(){
	timeAlert--;

	if($('txtTimer'))
		$('txtTimer').innerHTML = '( ' + timeAlert + ' )';

	if(timeAlert == 0){
		if($('divAlert'))
			closeAlert('divAlert');

		clearInterval(interval);
	}
}

/**
* CLASSE DE ALERTAS DO QUALITOR.
**/
function QAlert(){
	// PARÂMETROS DO OBJETO.
	this.nameDiv      = 'divAlert'; // NOME DA DIV DE ALERTA.
	this.message      = ''; 		// MENSAGEM DO ALERTA.
	this.messageUrl   = false; 		// DEFINE QUE A MENSAGEM É UMA URL DE UM ARQUIVO REQUEST. (USA AJAX.UPDATER).
	this.modal        = true; 		// JANELA AUXILIAR COMO MODAL NA TELA.
	this.close        = true; 		// OPÇÃO DE FECHAR NA DIV.
	this.width        = 350; 		// LARGURA DA DIV.
	this.height       = 100; 		// ALTURA DA DIV.
	this.maxHeight    = 300;		// ALTURA MAXIMA DA DIV
	this.type         = 'information';  // TIPO DE MENSAGEM DO ALERTA. DETERMINA O ÍCONE E BOTÕES DA DIV.
	this.icon         = 'qualitor.gif'; // ÍCONE DA DIV.
	this.image        = ''; 		// IMAGEM DO ALERTA.
	this.title        = ''; 		// TÍTULO DA JANELA DE ALERTA.
	this.funOk        = ''; 		// FUNÇÃO A SER EXECUTADA PELA BOTÃO OK.
	this.funYes       = ''; 		// FUNÇÃO A SER EXECUTADA PELO BOTÃO YES.
	this.funNo        = ''; 		// FUNÇÃO A SER EXECUTADA PELO BOTÃO NO.
	this.buttons      = ''; 		// STRING DOS BOTÕES DA DIV.
	this.buttonFocus  = ''; 		// BOTÃO DE FOCO AO ABRIR O ALERTA.
	this.cancelButton = false; 		// FORÇAR EXIBIÇÃO DO BOTÃO "CANCELAR".

	/**
	* DEFINE OS VALORES DOS PARÂMETROS.
	**/
	this.definePars = function(msg, pars){
		this.message = msg;

		if(pars){
			if(pars.msgUrl == true) this.messageUrl = true;
			if(pars.time > 0){
				timeAlert = pars.time;
				interval = window.setInterval('timerQAlert()', 1000);
			}
			if(pars.modal == false) this.modal = false;
			if(pars.close == false) this.close = false;
			if(pars.width) this.width = pars.width;
			if(pars.height) this.height = pars.height;
			if(pars.maxHeight) this.maxHeight = pars.maxHeight;
			if(pars.type) this.type = pars.type;
			if(pars.icon) this.icon = pars.icon;
			if(pars.image) this.image = pars.image;
			if(pars.title) this.title = pars.title;
			if(pars.funOk) this.funOk = pars.funOk;
			if(pars.funYes) this.funYes = pars.funYes;
			if(pars.funNo) this.funNo = pars.funNo;
			if(pars.buttonFocus) this.buttonFocus = pars.buttonFocus;
			if(pars.cancelButton == true) this.cancelButton = true;
		}

		hiddenLayerCombos();
	},

	/**
	* CRIA A DIV DE ALERTA.
	**/
	this.getAlert = function()	{
		layerIndex++;

		if(this.modal){
			if($('divDesabilitaTela'))
				$('divDesabilitaTela').style.zIndex = layerIndex;
			else
				desabilitaTela();
		}

		// Configurações especiais para alerta de erro do sistema.
		if(this.type == 'systemerror') {
			this.width = 450;
			this.close = false;
		}

		// CRIA O ELEMENTO DIV NA TELA.
		var body = document.getElementsByTagName('body')[0];
		var div = document.createElement('div');
		div.id = this.nameDiv;
		div.style.width = this.width;
		div.style.height = this.height;
		div.className = "DIVALERT";
		div.style.zIndex = layerIndex;

		body.appendChild(div);

		// CENTRALIZA A DIV NA TELA.
		centralizaObjeto(this.nameDiv, this.width, this.height);

		// VERIFICA SE O CONTEÚDO DA DIV VIRÁ DE UMA URL.
		if(this.messageUrl)
			new Ajax.Updater({success: this.nameDiv}, this.message, {evalScripts: true});
		else{
			$(this.nameDiv).innerHTML = this.getBarra() + this.getBody();
			
			if($(this.buttonFocus))
				$(this.buttonFocus).focus();
		}
	},

	/**
	* DEFINE OS ELEMENTOS DA DIV DE ALERTA.
	**/
	this.defineElements = function(){
		switch(this.type){
			case 'information' :
				var typeTitle = QLabel[8];
				var typeImage = 'information.gif';
				var typeButtons = this.createButton('btnOK', 'ok', this.funOk);
				var typeButtonFocus = 'btnOK';
				break;

			case 'critical' :
			case 'systemerror' :
				var typeTitle = QLabel[9];
				var typeImage = 'qcritical.gif';
				var typeButtons = this.createButton('btnOK', 'ok', this.funOk);
				var typeButtonFocus = 'btnOK';
				break;

			case 'exclamation' :
				var typeTitle = QLabel[10];
				var typeImage = 'qexclamation.gif';
				var typeButtons = this.createButton('btnOK', 'ok', this.funOk);
				var typeButtonFocus = 'btnOK';
				break;

			case 'help' :
				var typeTitle = QLabel[11];
				var typeImage = 'help.gif';
				var typeButtons = this.createButton('btnOK', 'ok', this.funOk);
				var typeButtonFocus = 'btnOK';
				break;

			case 'confirm' :
				var typeTitle = QLabel[12];
				var typeImage = 'qconfirm.gif';
				var typeButtons  = this.createButton('btnYES', 'yes', this.funYes);
					typeButtons += this.createButton('btnNO', 'no', this.funNo);

				if(this.cancelButton)
					typeButtons += this.createButton("btnCancel", "cancel", "", "");

				var typeButtonFocus = "btnYES";
				break;
		}

		// DEFINE OS VALORES DOS ELEMENTOS, DANDO PRIORIDADE PARA OS INFORMADOS POR PARÂMETRO.
		if(this.title == '')
			this.title = typeTitle;

		if(this.image == '')
			this.image = typeImage;

		if(typeButtons)
			this.buttons = typeButtons;

		if(this.buttonFocus == '')
			this.buttonFocus = typeButtonFocus;
	},

	/**
	* CRIA O BOTÃO.
	**/
	this.createButton = function(name, type, funClick){
		var strButton = '<button name="' + name + '" id="' + name + '" class="BUTTON" style="height:16px;" onmouseover="this.className = \'BUTTONOVER\';" onmouseout="this.className = \'BUTTON\';" onkeypress="escExec(\'' + this.nameDiv + '\');" onclick="closeAlert(\'' + this.nameDiv + '\'); ' + funClick + '">';
		strButton += '<font style="margin-left:3px; margin-right:3px;">' + this.getButtonLabel(type) + '</font>';
		strButton += '</button>';
		return strButton;
	},

	/**
	* RETORNA O LABEL DE UM BOTÃO.
	**/
	this.getButtonLabel = function(type){
		switch(type){
			case 'ok' : return 'OK';
			case 'yes' : return QLabel[0];
			case 'no' : return QLabel[1];
			case 'cancel' : return QLabel[2];
		}
	},

	/**
	* RETORNA O HTML DA BARRA DE TÍTULO DA DIV.
	**/
	this.getBarra = function(){
		var strRetorno = '<table width="100%" cellpadding="0" cellspacing="0" class="WINDOWHEADER" onmousedown="dragStart(event, this.parentNode.id)">';
		strRetorno += '<tr>';

		// ÍCONE.
		strRetorno += '<td width="20" height="20" align="center">';
		strRetorno += '<img src="' + pathWeb + '/framework/images/default/16/' + this.icon + '" class=\"WINDOWICON\" alt="" />';
		strRetorno += '</td>';

		// TÍTULO.
		strRetorno += '<td width="100%" height="20" alt="" />';
		strRetorno += '<font class="WINDOWTITLE">' + this.title + '</font>';

		// VERIFICA SE O ALERT POSSUI CRONÔMETRO.
		if (timeAlert > 0) {
			strRetorno += ' <font class="COLORLABEL" id="txtTimer">( ' + timeAlert + ' )</font>';
		}

		strRetorno += '</td>';

		// CLOSE.
		strRetorno += '<td width="45" height="20" align="right">';

		// VERIFICA O PARÂMETRO CLOSE.
		if (this.close) {
			strRetorno += '<img src="' + pathWeb + '/framework/images/default/general/btn_close.gif" id="btnCloseWindow' + layerIndex + '" class="WINDOWCLOSE" onmouseover="setObjectImage(this, \'general/btn_close_over.gif\');" onmouseout="setObjectImage(this, \'general/btn_close.gif\');" onclick="closeAlert(\'' + this.nameDiv + '\');" alt="' + QLabel[79] + '" title="' + QLabel[79] + '" />';
		}

		strRetorno += '</td>';
		strRetorno += '</tr>';
		strRetorno += '</table>';

		return strRetorno;
	},

	/**
	* RETORNA O HTML DO CORPO DA DIV.
	**/
	this.getBody = function(){
		var strRetorno = '';
		strRetorno += '<table width="100%" height="' + (this.height - 20) + '" cellpadding="0" cellspacing="0" class="WINDOWCONTENT">';
		strRetorno += '<tr>';
		strRetorno += '<td width="100%">';
		
		strRetorno += '<table class="ALERTCONTENT">';
		strRetorno += '<tr>';

		// ÍCONE DE CONTEXTO.
		strRetorno += '<td width="45" height="37" align="center" valign="top">';
		strRetorno += '<img src="' + pathWeb + '/framework/images/default/32/' + this.image + '" style="margin-top:5px;" alt="" />';
		strRetorno += '</td>';

		// MENSAGEM.
		strRetorno += '<td class="COLORLABEL" height="37" style="padding:5px;">' + '<div style="height:expression(this.scrollHeight > '+(this.maxHeight)+' ? \''+(this.maxHeight)+'px\' : \'auto\'); max-height:'+(this.maxHeight)+'px; overflow:auto;">' + this.message + '</div>' + '</td>';
		strRetorno += '<td class="WINDOWSIDE">&nbsp;</td>';
		strRetorno += '</tr>';
			
		// BOTÕES
		strRetorno += '<tr>';
		strRetorno += '<td height="100%" colspan="2" align="center" style="padding:5px;">' + this.buttons + '</td>';
		strRetorno += '</tr>';
		
		strRetorno += '</table>';
		
		strRetorno += '</td>';
		strRetorno += '</tr>';
		
		strRetorno += '<tr><td class="WINDOWFOOTER" colspan="4">&nbsp;</td></tr>';
		strRetorno += '</table>';

		return strRetorno;
	}
}