
var posicaoMouseX;
var posicaoMouseY;
var instanciasObjetosClicaveis = Array();
var instancia_objeto_clicavel_menuaberto;
var PASTA_OBJETO_CLICAVEL = 'biblioteca/objeto_clicavel/';

function pegarCoordMouse(e) {
	if (!e) var e = window.event;
	var IE = (document.all ? true : false);
	if (IE) {
		posicaoMouseX = e.clientX + posicaoScrollLeft();
		posicaoMouseY = e.clientY + posicaoScrollTop();
	} else {  // grab the x-y pos.s if browser is NS
		posicaoMouseX = e.pageX
		posicaoMouseY = e.pageY
	}  
	// catch possible negative values in NS4
	if (posicaoMouseX < 0){posicaoMouseX = 0}
	if (posicaoMouseY < 0){posicaoMouseY = 0}  
}
function posicaoScrollTop() {
	var scrOfY = 0;
	if(typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
	}
	return scrOfY;
}
function posicaoScrollLeft() {
	var scrOfX = 0;
	if(typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfX = document.documentElement.scrollLeft;
	}
	return scrOfX;
}
function alturaInternaJanela() {
	var myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myHeight = document.body.clientHeight;
	}
	return myHeight;
}
function larguraInternaJanela() {
	var myWidth = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
	}
	return myWidth;
}


function objetoClicavel() {
	
	
	// CONFIGURAÇÕES: =================================================================
	var selecionado_backgroundColor = '#0481D5';
	var selecionado_color			= '#FFFFFF';
	var mouseover_backgroundColor	= '#F3F8FC';
	this.evento_onclick_padrao		= 'detalhamento';
	
	// ATRIBUTOS: =====================================================================
	this.id_elemento_html;
	this.id;
	// Atributos de Menu:
	this.menus_desabilitados 	= Array();
	this.qtd_itens_menu 		= 0;
	this.itemMenu 				= Array();
	this.estadosite_menu 			= 'fechado';
	this.altura_item_menu 		= 23;	 // altura de cada item de menu com uma linha
	this.padding_bottom_menu 	= 20;
	this.padding_right_menu 	= 10;
	this.largura_menu 			= 200;

	// EVENTOS SETADOS CASO A CASO: ==================================================
	this.onClick		= null;
	this.onMouseOver	= null;
	this.onMouseOut		= null;
	this.onContextMenu	= null;

	// ===============================================================================
	// MÉTODOS:	======================================================================
	// ===============================================================================

	this.inicializar 		= inicializar;
	this.exibirMenu 		= exibirMenu;
	this.adicionarItemMenu 	= adicionarItemMenu;
	this.eventoBodyClick 	= eventoBodyClick;
	this.ocultarMenu 		= ocultarMenu;
	this.capturarTeclaEsc	= capturarTeclaEsc;
	this.exibirAguarde		= exibirAguarde;

	
	function inicializar(id_elemento_html, id_base, nome_instancia) {

		// SETAR VARIÁVEIS DENTRO DO OBJETO: =========================================
		this.id_elemento_html 			= id_elemento_html;
		this.id_base					= id_base;
		this.nome_instancia 			= nome_instancia;
		this.elemento_html 				= document.getElementById(this.id_elemento_html);
		if(!this.elemento_html) {
			alert('Não foi encontrado a DIV com id "' + this.id_elemento_html + '".');
		}
		// EVENTO ONCLICK: ===========================================================
		if(this.onClick) {
			this.elemento_html.onclick 		= this.onClick;
		} 
		// EVENTO ONCONTEXTMENU: =====================================================
		if(this.onContextMenu) {
			this.elemento_html.oncontextmenu = this.onContextMenu;
		} else {
			this.elemento_html.oncontextmenu = function() { return false; }
		}
		// EVENTO MOUSEOVER: =========================================================
		_funcao = '';
		if(mouseover_backgroundColor) {
			_funcao += 'if(' + this.nome_instancia + '.estadosite_menu == "fechado") { ';
			_funcao += 'document.getElementById("' + this.id_elemento_html + '").style.backgroundColor = "' + mouseover_backgroundColor + '"; ';
			_funcao += '}';
		}
		if(typeof(this.onMouseOver) == 'function') {
			_funcao += this.nome_instancia + '.onMouseOver()';
		}
		if(_funcao != '') {
			this.elemento_html.onmouseover = new Function(_funcao);
		}
		// EVENTO MOUSEOUT: ==========================================================
		_funcao = '';
		if(mouseover_backgroundColor) {
			_funcao += 'if(' + this.nome_instancia + '.estadosite_menu == "fechado") { ';
			_funcao += 	'document.getElementById("' + this.id_elemento_html + '").style.backgroundColor = ""; ';
			_funcao += '}';
		}
		if(typeof(this.onMouseOut) == 'function') {
			_funcao += this.nome_instancia + '.onMouseOut()';
		}
		if(_funcao != '') {
			this.elemento_html.onmouseout = new Function(_funcao);
		}

		// COLOCAR NA ARRAY QUE CONTÉM TODOS NOMES DE INSTÂNCIAS: =====================
		instanciasObjetosClicaveis.push(this);

		// INICIAR VERIFICAÇÃO DA POSIÇÃO DO MOUSE: ===================================
		var IE = (document.all ? true : false);
		if (!IE) {
			document.captureEvents(Event.MOUSEMOVE)
		}
		document.onmousemove = pegarCoordMouse;
	}

	function exibirMenu() {
		// DEIXAR O ELEMENTO COM COR DE SELECIONADO:
		if(selecionado_backgroundColor) {
			this.elemento_html.style.backgroundColor 	= selecionado_backgroundColor;
			this.elemento_html.style.color				= selecionado_color;
		}
		instancia_objeto_clicavel_menuaberto = this;

		// APAGAR A COR E SETAR COMO FECHADO TODOS OS OUTROS:
		for(i=0; i<instanciasObjetosClicaveis.length; i++) {
			if(instanciasObjetosClicaveis[i] != this) {
				instanciasObjetosClicaveis[i].elemento_html.style.backgroundColor = '';
				instanciasObjetosClicaveis[i].elemento_html.style.color = '';
				instanciasObjetosClicaveis[i].estadosite_menu = 'fechado';
			}
		}
		
		// CRIAR ELEMENTO DIV, CASO PRECISE:
		if(!document.getElementById('div_contextMenu')) {
			elementoMenu = document.createElement('div');
			elementoMenu.setAttribute('id', 'div_contextMenu');
			elementoMenu.setAttribute('className', 'contextMenu');	// pra internet explorer
			elementoMenu.setAttribute('class', 'contextMenu');	// pra firefox
			document.body.appendChild(elementoMenu);
		} else {
			elementoMenu = document.getElementById('div_contextMenu');
		}
		altura_menu = this.qtd_itens_menu * this.altura_item_menu;
		
		if(this.estadosite_menu == 'fechado') {
			// MONTAR O MENU:
			elementoMenu.innerHTML = '';
			for(i=0; i<this.qtd_itens_menu; i++) {
				// VERIFICAR SE ELE ESTÁ ATIVO PRA ESTA INSTÂNCIA:
				_exibir_menu = true;
				for(ii=0; ii<this.menus_desabilitados.length; ii++) {
					if(this.itemMenu[i]['label'] == this.menus_desabilitados[ii]) {
						_exibir_menu = false;
						break;
					}
				}
				if(_exibir_menu) {
					if(this.itemMenu[i]['url_imagem']) {
						this.itemMenu[i]['elemento_html'].innerHTML = '<img src="' + this.itemMenu[i]['url_imagem'] + '" border="0" class="contextMenu_icone_item" >';
					} else {
						this.itemMenu[i]['elemento_html'].innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;';
					}

					this.itemMenu[i]['elemento_html'].innerHTML += this.itemMenu[i]['label'];
					this.itemMenu[i]['elemento_html'].setAttribute('class', 'contextMenu_item');
					this.itemMenu[i]['elemento_html'].setAttribute('className', 'contextMenu_item');
					elementoMenu.appendChild(this.itemMenu[i]['elemento_html']);
					document.getElementById('div_contextMenu').style.display = 'block';
				}
			}
			// POSICIONAR MENU:
			// verificar se a posição Y do mouse + altura_menu não excede o final da tela:
			posicaoMouseYRelativa = posicaoMouseY - posicaoScrollTop();
			posicaoMouseXRelativa = posicaoMouseX - posicaoScrollLeft();
			if(posicaoMouseYRelativa + altura_menu > alturaInternaJanela()) {
				posicaoMenuY = posicaoScrollTop() + alturaInternaJanela() - altura_menu - this.padding_bottom_menu;
			} else {
				posicaoMenuY = posicaoMouseY;
			}
			if(posicaoMouseXRelativa + this.largura_menu > larguraInternaJanela()) {
				posicaoMenuX = posicaoScrollLeft() + larguraInternaJanela() - this.largura_menu - this.padding_right_menu;
			} else {
				posicaoMenuX = posicaoMouseX;
			}
			document.getElementById('div_contextMenu').style.left = posicaoMenuX + 'px';
			document.getElementById('div_contextMenu').style.top = posicaoMenuY + 'px';
			// OUTROS ESTILOS:
			document.getElementById('div_contextMenu').style.width = this.largura_menu + 'px';
			document.getElementById('div_contextMenu').style.display = 'block';
			// DEFINIR ONCLICK NO BODY PARA FECHAR MENU SE CLICAR FORA:
			this.bodyonclick_original = document.body.onclick;
			document.body.onclick = new Function(this.nome_instancia + '.eventoBodyClick(); ');
			// CAPTURAR TECLA ESC:
			this.windowonkeypress_original = window.onkeypress;
			this.documentbodyonkeypress_original = document.body.onkeypress;
			document.body.onkeypress 	= new Function('e', this.nome_instancia + '.capturarTeclaEsc(e); ');	// Internet Explorer
			window.onkeypress 			= new Function('e', this.nome_instancia + '.capturarTeclaEsc(e); ');		// Firefox

			// SETAR VALORES:
			this.estadosite_menu = 'aberto';
			this.permissao_bodyclick = false;
		} else {
			this.ocultarMenu();
		}
		// RETORNAR false PRA NÃO EXIBIR CONTEXT MENU DO BROWSER:
		return false;
	}

	function adicionarItemMenu(label, nome_funcao, icone) {
		this.qtd_itens_menu++;
		indice = this.qtd_itens_menu-1;

		// COLOCAR DE ITEM DE MENU NA ARRAY:
		this.itemMenu[indice] = Array();
		this.itemMenu[indice]['label'] 			= label;
		this.itemMenu[indice]['elemento_html'] 	= document.createElement("a");
		this.itemMenu[indice]['elemento_html'].href = "javascript:; ";

		// EVENTO ONCLICK DO ITEM DE MENU:
		if(!nome_funcao) {
			if(typeof(this.nome_funcao_pronta[label]) != "string") {
				alert('Não existe uma função pronta para "' + label + '" (ou ela não foi declarada em "funcoes_prontas.js")');
				return;
			}
			nome_funcao = this.nome_funcao_pronta[label];
		}
		if(!icone) {
			if(typeof(this.icone_funcao_pronta[label]) != "string") {
				alert('Não existe um ícone para "' + label + '" (ou ela não foi declarada em "funcoes_prontas.js")');
				return;
			}
			icone = this.icone_funcao_pronta[label];
		}
		// MONTAR FUNÇÃO:
		_funcao  = 'instancia_objeto_clicavel_menuaberto.ocultarMenu(); ';
		_funcao += 'instancia_objeto_clicavel_menuaberto.exibirAguarde(); ';
		_funcao += 'instancia_objeto_clicavel_menuaberto.' + nome_funcao + '(); ';
		_funcao += 'return false; ';
		this.itemMenu[indice]['elemento_html'].onclick = new Function(_funcao);
		// URL E PRELOAD DO ÍCONE:
		if(icone) {
			this.itemMenu[indice]['url_imagem'] = RAIZ_SITE + PASTA_OBJETO_CLICAVEL + 'icone_' + icone + '.gif';
			// PRELOAD DO ÍCONE:
			iconePreload = new Image();
			iconePreload.src = this.itemMenu[indice]['url_imagem'];
		}
		// SETAR EVENTO ONCONTEXTMENU DO objetoClicavel, SE FOR O PRIMEIRO ITEM: 
		if(indice == 0) {
			_str_funcao = this.nome_instancia + '.exibirMenu(); ';
			_str_funcao += 'return false;'
			this.elemento_html.oncontextmenu = new Function(_str_funcao);
			// EVENTO ONCLICK, CASO NÃO TENHA SIDO ESPECIFICADO:
			if(!this.onClick) {
				if(this.evento_onclick_padrao == 'detalhamento') {
					_str_funcao  = 'document.location = "detalhamento.php?' + this.nome_id_base + '=' + this.id_base + '";';
					_str_funcao += 'preloaderPagina.exibir(); ';
				}
				this.elemento_html.onclick = new Function(_str_funcao);
			}
		}
	}

	function eventoBodyClick() {
	
		if(this.permissao_bodyclick) {
			this.ocultarMenu();
			// BODYONCLICK E KEYPRESS:
			document.body.onclick 		= this.bodyonclick_original;
			window.onkeypress 			= this.windowonkeypress_original;
			document.body.onkeypress 	= this.documentbodyonkeypress_original;
		} else {
			this.permissao_bodyclick = true;
		}
	}
	
	function ocultarMenu() {
		elementoMenu.style.display = 'none';
		document.body.onclick = this.bodyonclick_original;
		this.permissao_bodyclick = false;
		this.estadosite_menu = 'fechado';
		this.elemento_html.style.backgroundColor = '';
		this.elemento_html.style.color = '';
	}
	
	function capturarTeclaEsc(e) {
		var intKey = 0;
		e = ((window.event) ? event : e);
		charcode = ((e.keyCode) ? e.keyCode: e.charCode);
		if(charcode == 27) {
			this.ocultarMenu();
		}
	}
	
	function exibirAguarde() {
		if(typeof(preloaderPagina) == 'object') {
			preloaderPagina.exibir();
		}
	}
	
}
