////////////////////////////////////////////////////////////////////////////////
// console.log workaround

try { console.log('console.log() available'); } catch(e) { console = { log: function(){} } };

///////////////////////////////////////////////////////////////////////////////
// HTML e interface

var UI = {};

///////////////////////////////////////////////////////////////////////////////
// Create and return extended HTML Element

UI.create = function(str){
	return $(document.createElement(str));
};

///////////////////////////////////////////////////////////////////////////////
// Print

UI.print = function(){
	window.print();
	return false;
};

///////////////////////////////////////////////////////////////////////////////
// Popup

UI.popup = function(a, w, h){
	var w = (w) ? w : 460;
	var h = (h) ? h : 480;
	var l = (screen.width - w) * 0.5;
	var t = (screen.height - h) * 0.5;
	var o = window.open(a.href, "popup", "width="+w+",height="+h+",left="+l+",top="+t+",menubar=no,location=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no,alwaysRaised=yes");
	o.focus();
	return false;
};

///////////////////////////////////////////////////////////////////////////////
// Accordion

UI.tableAccordion = Class.create();
UI.tableAccordion.prototype = {
	
	initialize: function(str){
		var el = $(str);
		if(el){ this.init(el) }
	},
	
	arr: [],
	
	init: function(el){
		var trs = el.getElementsBySelector('tr.toggler');
		for(var i=0, tr; tr=trs[i]; i++){
			this.verify(tr, i);
		}
	},
	
	verify: function(tr, i){
		var tr = $(tr).setProperty('toggler', i);
		var pane = tr.next();
		var info = { 'id': i, 'toggler': tr, 'pane': pane };
		this.arr[i] = info;
		
		this.createClose(pane, i);
		Event.observe(tr, 'click', this.toggle.bindAsEventListener(this));
		Event.observe(tr, 'mouseover', this.over.bindAsEventListener(this));
		Event.observe(tr, 'mouseout', this.out.bindAsEventListener(this));
	},
	
	toggle: function(ev){
		Event.stop(ev);
		var tr = Event.findElement(ev, 'tr');
		var i = tr.readAttribute('toggler');
		var pane = this.arr[i].pane;
		this._toggle(pane, tr);
	},
	
	_toggle: function(pane, tr){
		tr.toggleClassName('current');
		pane.toggleClassName('expanded');
	},
	
	createClose: function(pane, i){
		var td = pane.down('td');
		var a = UI.create('a').setProperties({'class':'close', 'href':'#', 'toggler': i}).setHTML('Fechar').injectInside(td);
		Event.observe(a, 'click', this.doClose.bindAsEventListener(this));
	},
	
	doClose: function(ev){
		Event.stop(ev);
		var a = Event.element(ev);
		var i = a.readAttribute('toggler');
		var pane = this.arr[i].pane;
		var toggler = this.arr[i].toggler;
		this._toggle(pane, toggler);
	},
	
	over: function(ev){
		Event.stop(ev);
		var tr = Event.findElement(ev, 'tr');
		tr.addClassName('over');
	},
	
	out: function(ev){
		Event.stop(ev);
		var tr = Event.findElement(ev, 'tr');
		tr.removeClassName('over');
	}
};

///////////////////////////////////////////////////////////////////////////////
// Accordion

UI.accordion = Class.create();
UI.accordion.prototype = {
	
	initialize: function(str){
		var el = $(str);
		if(el){ this.init(el) }
	},
	
	arr: [],
	
	init: function(el){
		var divs = el.getElementsBySelector('div.toggler');
		for(var i=0, div; div=divs[i]; i++){
			var a = div.down('a');
			this.verify(a, i);
		}
	},
	
	verify: function(a, i){
		var a = $(a).setProperty('toggler', i);
		var div = a.parentNode;
		var pane = div.next();
		var info = { 'id': i, 'toggler': a, 'pane': pane };
		this.arr[i] = info;
		
		//pane.hide();
		this.createClose(pane, i);
		Event.observe(a, 'click', this.toggle.bindAsEventListener(this));
	},
	
	toggle: function(ev){
		Event.stop(ev);
		var a = Event.element(ev);
		var i = a.readAttribute('toggler');
		var pane = this.arr[i].pane;
		this._toggle(pane, a);
	},
	
	_toggle: function(pane, a){
		a.toggleClassName('current');
		pane.toggleClassName('expanded');
		//Effect.toggle(pane, 'Blind', { duration: 0.25 });
	},
	
	createClose: function(pane, i){
		var a = UI.create('a').setProperties({'class':'close', 'href':'#', 'toggler': i}).setHTML('Fechar').injectInside(pane);
		Event.observe(a, 'click', this.doClose.bindAsEventListener(this));
	},
	
	doClose: function(ev){
		Event.stop(ev);
		var a = Event.element(ev);
		var i = a.readAttribute('toggler');
		var pane = this.arr[i].pane;
		var toggler = this.arr[i].toggler;
		this._toggle(pane, toggler);
	}
	
};

///////////////////////////////////////////////////////////////////////////////
// Tree menus

UI.tree = Class.create();
UI.tree.prototype = {
	
	initialize: function(str){
		this.id = str;
		var el = $(str);
		if(el){ this.init(el) }
	},
	
	init: function(el){
		var as = el.getElementsByTagName('a');
		for(var i=0, a; a=as[i]; i++){
			this.verify(a);
			this.expand(a);
		}
	},
	
	verify: function(a){
		var a = $(a);
		if(a.next('ul')){
			var div = UI.create('div').injectBefore(a);
			var toggler = UI.create('a').setProperties({'class':'plus', 'title':'Expandir'}).injectInside(div);
			a.injectInside(div);
			Event.observe(toggler, 'click', this.toggle.bindAsEventListener(this));
			
			if(a.className == 'current'){
				div.className = 'current';
			}
		}
		
		var li = a.up('li');
		if(li){
			if(!li.next('li')){
				li.addClassName('last');
			}
		}
	},
	
	toggle: function(ev){
		Event.stop(ev);
		var toggler = Event.element(ev);
		var div = toggler.parentNode;
		var ul = div.next('ul');
		toggler.className = (toggler.className == 'plus') ? 'minus' : 'plus';
		toggler.title = (toggler.title == 'Expandir') ? 'Esconder' : 'Expandir';
		ul.className = (ul.className == 'expanded') ? '' : 'expanded';
	},
	
	expand: function(a){
		if(a.className == 'current'){
			var ul = a.up('ul');
			if(!ul){ return; }
			if(ul.id != this.id){ ul.className = 'expanded'; }
	
			var div = ul.previous('div');
			if(!div){ return; }
	
			var toggler = div.down('a');
			if(!toggler){ return; }
			toggler.className = 'minus';
			toggler.title = 'Esconder';
		}
	}
	
};

///////////////////////////////////////////////////////////////////////////////
// Flash Titles

UI.flashTitles = Class.create();
UI.flashTitles.prototype = {
	
	initialize: function(arr){
		for(var i=0, obj; obj=arr[i]; i++){
			var selector = obj.selector;
			var color = obj.color;
			this.initSelector(selector, color, i);
		}
	},
	
	initSelector: function(selector, color, num){
		this.num = num;
		this.color = color;
		var els = $$(selector);
		for(var i=0, el; el=els[i]; i++){
			this.initElement(el, i);
		}
	},
	
	initElement: function(el, i){
		var num  = this.num * 100 + i;
		var id   = 'flashtitle' + num;
		var txt  = el.innerHTML;
		var size = el.getHeight();
		el.setHTML('<div id="'+id+'"></div>');
		var div = UI.create('div').setProperty('class', 'flashreplaced').setHTML(txt).injectInside(el);
		new UI.flashTitle(id, this.color, size, txt);
	}
	
};

UI.flashTitle = Class.create();
UI.flashTitle.prototype = {
	
	initialize: function(id, color, size, txt){
		txt    = txt.replace('&', '%26');
		var h  = size * 1.3;
		var so = new SWFObject("flash/flashtitle.swf", id, "100%", h, "8", "#ffffff");
		so.addParam("wmode", "transparent");
		so.addVariable("paramFontColor", color);
		so.addVariable("paramFontSize", size);
		so.addVariable("paramText", txt);
		so.write(id);
	}
	
};

///////////////////////////////////////////////////////////////////////////////
// Thickbox 2.1
// Copyright (c) 2006, 2007 Cody Lindley (http://www.codylindley.com)
// Adapted to Prototype by Eduardo Omine / 2007

UI.box = {

	duration: 0.75,
	opacity: 0.75,
	titleHeight: 0,

	// Initialize links
	init: function(){
		var as = $$('a');
		as.each(UI.box.verify);
	},

	// Add event according to link's "rel" attribute
	verify: function(a){
		a = $(a);
		var rel = a.readAttribute('rel');
		if(rel && a.href){
			if(rel.substr(0,8) == 'framebox'){
				Event.observe(a, 'click', UI.box.frameClick);
			} else if(rel == 'closebox'){
				Event.observe(a, 'click', UI.box.closeClick);
			}
		}
	},
	
	// Click on close button
	closeClick: function(event){
		Event.stop(event);
		UI.box.remove('box_iframe');
	},

	// Click on frame link
	frameClick: function(event){
		Event.stop(event);
		UI.box.frameStart(Event.findElement(event, 'a'));
	},

	// Start framebox
	frameStart: function(a){
		var s = $(a).readAttribute('rel').split(' ');
		var w = (s.length > 1) ? s[1] : 0;
		var h = (s.length > 2) ? s[2] : 0;
		UI.box.frameShow(a.href, a.title, w, h);
	},

	// Build framebox
	frameShow: function(str, title, w, h){
		var overlay = UI.box.createOverlay();
		var div = $('box_iframe');
		if(!div){
			var txt = 'Fechar';
			var div = UI.create('div').setProperties({'id':'box_iframe', 'class':'box_window'}).injectInside(document.body);
			var a = UI.create('a').setHTML(txt).setProperties({'href':'#', 'title': txt, 'id':'box_close'}).injectInside(div);
			var iframe = UI.create('iframe').setProperties({'id':'box_iframe1', 'frameborder':'0', 'scrolling':'no', 'src':str}).injectInside(div);
			a.onclick = function(){
				return UI.box.remove('box_iframe');
			}

			var h1 = h - UI.box.titleHeight;
			if(w > 0){
				div.style.width = w + 'px';
				iframe.style.width = w + 'px';
			}
			if(h > 0){
				div.style.height = h + 'px';
				iframe.style.height = h1 + 'px';
			}
		}
		div.style.display = 'block';
		UI.box.overlaySize();
		UI.box.position(div);
		window.scroll(0, 0);
		window.onresize = function(){
			UI.box.overlaySize();
			UI.box.position(div);
		};
		window.onscroll = function(){
			UI.box.position(div);
		};
	},

	// Create iframe to hide <select>s on IE
	createOverlay: function(){
		var overlay = $('box_overlay');
		if(!overlay){
			if(!UI.khtml){
				var iframe = UI.create('iframe').setProperty('id','box_hideSelect').injectInside(document.body);
			}
			var overlay = UI.create('div').setProperty('id','box_overlay').injectInside(document.body);
			overlay.onclick = function(){
				UI.box.remove('box_iframe');
			}
		}
		overlay.setStyle({'opacity': 0.1}); // IE bug
		new Effect.Opacity('box_overlay', {
			duration: UI.box.duration,
			from: 0,
			to: UI.box.opacity
		});
		return overlay;
	},

	// Remove framebox **from inside the iframe**
	remove: function(div){
		var overlay = $('box_overlay');
		overlay.onclick = null;
		window.onresize = null;
		window.onscroll = null;
		new Effect.Opacity('box_overlay', {
			duration: UI.box.duration,
			from: UI.box.opacity,
			to: 0
		});
		setTimeout(UI.box.removeCallback, UI.box.duration + 250);
		$(div).remove();
		return false;
	},

	// Remove overlays
	removeCallback: function(){
		var overlay = $('box_overlay');
		if(overlay){
			overlay.remove();
		}
		if(!UI.khtml){
			$('box_hideSelect').remove();
		}
	},

	// Position framebox
	position: function(div){
		var b = $(div);
		if(b){
			var pageSize = UI.box.getPageSize();
			var pageWidth = pageSize[0];
			var winWidth = pageSize[2];
			var boxWidth = b.getWidth();
			var l = (boxWidth > winWidth) ? "0" : winWidth/2 - boxWidth/2;
			b.setStyle({
				'left': l + 'px'
			});
		}
	},

	// Calculate overlay size
	overlaySize: function(){
		var pageSize = UI.box.getPageSize();
		var w = $(document.body).getWidth();
		$('box_overlay').setStyle({
			'height': pageSize[1] + 'px',
			'width': w + 'px'
		});
		if(!UI.khtml){
			$('box_hideSelect').setStyle({
				'height': pageSize[1] + 'px',
				'width': w + 'px'
			});
		}
	},

	// Method to be called from the framebox page
	// Automatically adapt framebox's size
	autoSize: function(){
		var p = window.parent;
		var f0 = p.$('box_iframe');
		var f1 = p.$('box_iframe1');
		if(f0 && f1){
			var pageSize = UI.box.getPageSize();
			var w = pageSize[0];
			var h = pageSize[1];
			var ww = $(p.document.body).getWidth();
			var l = (w > ww) ? "0" : ww/2 - w/2;
			f0.setStyle({
				'height': h + UI.box.titleHeight + 'px',
				'left': l + 'px',
				'width': w + 'px'
			});
			f1.setStyle({
				'height': h + 'px',
				'width': w + 'px'
			});
		}
	},

	// Get page size
	// Core code from - quirksmode.com
	// Edit for Firefox by pHaez
	getPageSize: function(){
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}

		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else {
			pageHeight = yScroll;
		}

		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){
			pageWidth = windowWidth;
		} else {
			pageWidth = xScroll;
		}

		var pageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return pageSize;
	}
};

///////////////////////////////////////////////////////////////////////////////
// Prototype.js extension
// Code from Mootools

UI.properties = {
	'class': 'className', 'for': 'htmlFor', 'colspan': 'colSpan', 'rowspan': 'rowSpan',
	'accesskey': 'accessKey', 'tabindex': 'tabIndex', 'maxlength': 'maxLength',
	'readonly': 'readOnly', 'frameborder': 'frameBorder', 'value': 'value',
	'disabled': 'disabled', 'checked': 'checked', 'multiple': 'multiple', 'selected': 'selected'
};

Element.addMethods({

	setMany: function(el, method, pairs){
		for (var key in pairs) el[method](key, pairs[key]);
		return el;
	},

	setProperty: function(el, property, value){
		el = $(el);
		var index = UI.properties[property];
		if (index) el[index] = value;
		else el.setAttribute(property, value);
		return el;
	},

	setProperties: function(el, obj){ return el.setMany('setProperty', obj) },

	setHTML: function(el, str){
		el.innerHTML = str;
		return el;
	},

	inject: function(el, container, where){
		container = $(container);
		switch(where){
			case 'before':
				container.parentNode.insertBefore(el, container);
				break;
			case 'after':
				var next = container.next();
				if (!next) container.parentNode.appendChild(el);
				else container.parentNode.insertBefore(el, next);
				break;
			case 'top':
				var first = container.firstChild;
				if (first){
					container.insertBefore(el, first);
					break;
				}
			default:
				container.appendChild(el);
		}
		return el;
	},

	injectBefore: function(el, container){ return el.inject(container, 'before') },

	injectAfter: function(el, container){ return el.inject(container, 'after') },

	injectInside: function(el, container){ return el.inject(container, 'bottom') },

	injectTop: function(el, container){ return el.inject(container, 'top') }

});
