////////////////////////////////////////////////////////////////////////////////
// console.log workaround

try { console.log('console.log() available'); } catch(e) { console = { log: function(){} } };

////////////////////////////////////////////////////////////////////////////////
// Common

var common = {
	lang: 'pt'
};

////////////////////////////////////////////////////////////////////////////////
// Localization

var words = {
	pt: { toClose: 'Fechar' },
	en: { toClose: 'Close' },
	es: { toClose: 'Cerrar' }
};

///////////////////////////////////////////////////////////////////////////////
// HTML e interface

var UI = {};

///////////////////////////////////////////////////////////////////////////////
// Properties

UI.ua = navigator.userAgent.toLowerCase();
UI.khtml = /khtml|safari|webkit/.test(UI.ua);
UI.opera = /opera/.test(UI.ua);

///////////////////////////////////////////////////////////////////////////////
// Create and return extended HTML Element

UI.create = function(str){
	return $(document.createElement(str));
};

///////////////////////////////////////////////////////////////////////////////
// Sticky footer

UI.footer = {

	timer: 0,
	bodyHeight: 0,

	init: function(){
		UI.footer.setBodyHeight();
		UI.footer.set();
		window.onresize = UI.footer.set;
	},

	set: function(){
		UI.timer = 0;
		UI.timer = setTimeout(UI.footer.timeout, 100);
	},
	
	timeout: function(){
		var h = UI.footer.getWindowHeight();
		var d = h - UI.footer.bodyHeight;
		console.log(UI.footer.bodyHeight, h, d);
		
		if(d < 0){ d = 0; }
		$('wprefooter').setStyle({ 'marginTop': d + 'px' });
		UI.timer = 0;
	},
	
	setBodyHeight: function(){
		UI.footer.bodyHeight = $('wrapper').getHeight();
	},
	
	getWindowHeight: function(){
		return UI.box.getPageSize()[3];
	}

};

///////////////////////////////////////////////////////////////////////////////
// Help tooltips

UI.help = {

	 // Initialize links
	init: function(){
		var aa = $$('a.zoom');
		aa.each(UI.help.verify);
	},
	
	// Initialize tooltips
	verify: function(a){
		a = $(a);
		new Effect.Tooltip(a, a.next());
	}
};

///////////////////////////////////////////////////////////////////////////////
// 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 aa = $$('a');
		aa.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 = words[common.lang].toClose;
			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 i = $("theimage");
			if(i){
				var wi = i.getWidth() + 40;
				w = wi;
			}
			///
			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');
	}

});

///////////////////////////////////////////////////////////////////////////////
// Effect.Tooltip 
// Nick Stakenburg
// http://www.illustate.com/playground/scriptaculous/tooltip/

Effect.Tooltip = Class.create();
Object.extend(Object.extend(Effect.Tooltip.prototype, Effect.Base.prototype), {
	initialize: function(element, content) {
		this.element = $(element);
		this.content = $(content);
		var options = Object.extend({
			offset: {'x':0, 'y':14}
		}, arguments[2] || {});
		this.start(options);
	},

	setup: function() {
		this.element.observe('mousemove', this.showTip.bindAsEventListener(this));
		this.element.observe('mouseout', this.hideTip.bindAsEventListener(this));
	},

	showTip: function(event){
		this.positionTip(event);
		this.content.setStyle({ 'display':'block' });
	},

	hideTip: function(){
		this.content.setStyle({ 'display':'none' });
	},

	positionTip: function(event){
		var offsets = {'x': this.options.offset['x'],'y': this.options.offset['y']};
		var mouse = {'x': Event.pointerX(event), 'y': Event.pointerY(event)};
		var page = {'x':this.viewportSize()['x'], 'y':this.viewportSize()['y']};
		var tip = {'x': mouse['x'] + this.options.offset['x'] + this.content.getWidth(), 'y' : mouse['y'] + this.options.offset['y'] + this.content.getHeight()};

		if(tip['x']>page['x']) { offsets['x'] = 0-(this.content.getWidth() + this.options.offset['x']); }
		if(tip['y']>page['y']) { offsets['y'] = 0-(this.content.getHeight() + this.options.offset['y']); }

		this.content.setStyle({
			left: mouse['x'] + offsets['x'] + 'px',
			top: mouse['y'] + offsets['y'] + 'px'
		});
	},

	viewportSize : function(){
		if (self.innerHeight) return {'x': self.innerWidth, 'y': self.innerHeight};
		else if (document.documentElement && document.documentElement.clientHeight)
		return {'x': document.documentElement.clientWidth, 'y': document.documentElement.clientHeight};
		else if (document.body) return {'x': document.body.clientWidth, 'y': document.body.clientHeight};
	}
});

