/* ----- License and Acknowledgements ----------------------------------- */
/*
	This software is licensed under the CC-LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
	
	activateActiveX v1.0 (published 7 May 2006)
	onDomReady v1.0 (published 7 May 2006) is based on the following works:
		- brothercake's domFunction <http://www.brothercake.com/site/resources/scripts/domready/>
		- Dave Rolsky's DOM.Ready <http://www.openjsan.org/doc/a/au/autarch/DOM/Ready/0.14/lib/DOM/Ready.html>
*/

// ARRAY EXTENSIONS
if (!Array.prototype.push) Array.prototype.push = function() {
	for (var i=0; i<arguments.length; i++) this[this.length] = arguments[i];
	return this.length;
}

Array.prototype.find = function(value, start) {
	start = start || 0;
	for (var i=start; i<this.length; i++)
		if (this[i]==value) return i;
	return -1;
}

Array.prototype.has = function(value) {
	return this.find(value)!==-1;
}

// FUNCTIONAL
function map(list, func) {
	var result = [];
	func = func || function(v) {return v};
	for (var i=0; i < list.length; i++) result.push(func(list[i], i, list));
	return result;
}

function filter(list, func) {
	var result = [];
	func = func || function(v) {return v};
	map(list, function(v) { if (func(v)) result.push(v) } );
	return result;
}

function isUndefined(v) { var undef; return v===undef }

// DOM
var DOM = {
	
	getElem: function(elem) {
		if (document.getElementById) {
			if (typeof elem == "string") {
				elem = document.getElementById(elem)
				if (elem===null) return false //throw 'cannot get element: element does not exist'
			} else if (typeof elem != "object") 
				return false //throw 'cannot get element: invalid datatype'
		} else 
			return false //throw 'cannot get element: unsupported DOM'
		return elem
	},
	
	hasClass: function(elem, className) { 
		return DOM.getElem(elem).className.split(' ').has(className) 
	},
	
	getElementsByClass: function(className, tagName, parentNode) {
		parentNode = !isUndefined(parentNode)? DOM.getElem(parentNode) : document;
		if (isUndefined(tagName)) tagName = '*'
		return filter(parentNode.getElementsByTagName(tagName),
			function(elem) { return DOM.hasClass(elem, className) })
	},
	
	listen: function(event, elem, func) {
		elem = DOM.getElem(elem)
		if (elem) {
			if (elem.addEventListener)  // W3C DOM
				elem.addEventListener(event,func,false)
			else if (elem.attachEvent)  // IE DOM
				elem.attachEvent('on'+event, function(){ func(new W3CDOMEvent(elem)) } )
			else 
				return false //throw 'cannot add event listener'
		}
	},
	
	mlisten: function(event, elem_list, func) { 
		map(elem_list, function(elem) { DOM.listen(event, elem, func) }) 
	},
	
	cancelEvent: function(e) { e.preventDefault() },
	
	onDomReady: function(f) {
		var t = setInterval( function() {
			if (typeof document.getElementsByTagName != "undefined" && typeof document.getElementById != "undefined" && (document.getElementsByTagName( "body" )[0] != null || document.body != null))
				f(); clearInterval(t);
		}, 250 );
	}

}

function W3CDOMEvent(currentTarget) {
	this.currentTarget  = currentTarget
	this.preventDefault = function() { window.event.returnValue = false }
	return this
}

// FAKE MOUSEOVER
var FakeMouseOver = {
	assign: function(elem, classe) {
		if ((elem = DOM.getElem(elem))) {
			DOM.listen('mouseover', elem, function() { elem.className += " " + classe })
			DOM.listen('focus', elem, function() { elem.className += " " + classe })
			DOM.listen('mouseout', elem, function() { elem.className = elem.className.replace(classe, "") })
			DOM.listen('blur', elem, function() { elem.className = elem.className.replace(classe, "") })
		}
	},
	mAssign: function(elem_list, classe) { 
		map(elem_list, function(elem) { FakeMouseOver.assign(elem, classe) }) 
	}
}

// POPUP
var Popup = {
	_POPUP_FEATURES: '',
	raw: function(url, target, features) {
		if (isUndefined(features)) features = Popup._POPUP_FEATURES
		if (isUndefined(target)) target= '_blank'
		var theWindow = window.open(url, target, features)
		theWindow.focus()
		//return theWindow
	},
	'link': function(src, features) {
		return Popup.raw(src.getAttribute('href'), src.getAttribute('rel') || '_blank', features);
	},
	'event': function(e) { 
		Popup.link(e.currentTarget); e.preventDefault() 
	},
	eventFeatures: function(features) {
		return function(e) { Popup.link(e.currentTarget, features); e.preventDefault() }
	},
	'close': function(e) { e.preventDefault(); window.close() }
}

// GERAL
var Geral = {
	blnSendForm: false,
	voltarPagina: function(e) { e.preventDefault(); window.history.back() },
	paginaAtual: function(pagina) { 
		sPagina = window.location.href.substr(window.location.href.lastIndexOf("/") + 1).toLowerCase()
		if (pagina) 
			return eval('/' + pagina + '/.test(sPagina)')
		else 
			return sPagina
	}, 
	preventClick: function(e) { 
		if (Geral.blnSendForm) { 
			alert('O formulário já está sendo processado. Por favor, aguarde alguns instantes.'); 
			e.preventDefault() 
		} else
			Geral.blnSendForm = true
	},
	imagemNoticia: function() {
		map(DOM.getElementsByClass('l-imagens', 'ul', 'ct-principal'), function(el) {
			DOM.mlisten('click', 
				el.getElementsByTagName('a'), 
				Popup.eventFeatures('width=520,height=480,top=' + ((screen.height - 480) / 2) + ',left=' + ((screen.width - 520) / 2) + ',scrollbars=0,location=0,statusbar=0,menubar=0')
			)
		})
	},
	
	iniciar: function() {

		// Ações para todas as páginas (exceto para pop-ups)
		if (!Geral.paginaAtual('popup')) {
			
			// aplica mouseover (ie) no menu superior
			if ((o = DOM.getElem('ct-menu')))
				FakeMouseOver.mAssign(filter(o.getElementsByTagName('li'), function(elem) { return elem.parentNode.parentNode.getAttribute('id') == 'ct-menu' }), 'over')
			
			// abre links com classe "externo" em nova janela
			DOM.mlisten('click', DOM.getElementsByClass('externo', 'a'), Popup.event)

			// abre links com classe "parecer" em nova janela, sem barra de localização
			DOM.mlisten('click', DOM.getElementsByClass('parecer', 'a'), Popup.eventFeatures('location=0,menubar=1,resizable=1,scrollbars=1,status=1,titlebar=1,toolbar=1'))

		} 
		
		// Ações para páginas de formulários que enviam dados para banco ou por e-mail
		if (Geral.paginaAtual('servicos_indicadores_demo_form.asp') || Geral.paginaAtual('atendimento.asp') || Geral.paginaAtual('premio_inscricao.asp') || Geral.paginaAtual('_premio_inscricao.asp'))
			// previne o usuário de enviar os dados dos formulários + de uma vez
			DOM.mlisten('submit', document.getElementsByTagName('form'), Geral.preventClick)
			
		// Ações para página servicos_indicadores_demo
		if (Geral.paginaAtual('servicos_indicadores_demo.asp'))
			DOM.listen('click', 
				DOM.getElem('demonstracao').getElementsByTagName('a')[0], 
				Popup.eventFeatures('width=' + screen.width + ',height=' + screen.width + ',top=0,left=0')
			)
		
		// Ações para páginas de classificados
		if (Geral.paginaAtual('empregos') || Geral.paginaAtual('maquinas'))
			if ((o = DOM.getElem('l-classificados')))
				DOM.mlisten('click', 
					o.getElementsByTagName('a'), 
					Popup.eventFeatures('width=520,height=480,top=' + ((screen.height - 480) / 2) + ',left=' + ((screen.width - 520) / 2) + ',scrollbars=0,location=0,statusbar=0,menubar=0')
				)
		
	}
}

DOM.listen('load', window, Geral.iniciar)