// Globals

Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE") + 5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE") + 5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;

// Modifiers

if (!Number.prototype.toThousands) Number.prototype.toThousands = function() {
	var n = this.toString();
	while (n.match(/^(.*\d)(\d{3}(\.|,|$).*$)/)) n = n.replace(/^(.*\d)(\d{3}(\.|,|$).*$)/, '$1,$2');
	return n;
}

if (!String.prototype.splitLine) String.prototype.splitLine = function(n) {
	var b = ''; 
	var s = this;
	while (s.length > n) {
		var c = s.substring(0, n);
		var d = c.lastIndexOf(' ');
		var e = c.lastIndexOf('\n');
		if (e != -1) d = e; 
		if (d == -1) d = n; 
		b += c.substring(0,d) + '\n';
		s = s.substring(d+1);
	}
	return b + s;
}

// Autocomplete

var Autocomplete = Class.create({

	initialize: function(element, url) {

		this.options = Object.extend({
			busyClass: 'autocomplete_text_busy',
			defaultClass: 'autocomplete_text',
			minChars: 3,
			offsetLeft: 0,
			offsetTop: 0,
			setWidth: true,
			target: 'Suggestions'
		}, arguments[2] || {});

		if ($(element) != null) {
	
			$(element).addClassName(this.options.defaultClass);
	
			new Ajax.Autocompleter(element, this.options.target, url, {
			    minChars: this.options.minChars,
				callback: this._callback.bind(this),
				onHide: this._hide.bind(this),
				onShow: this._show.bind(this),
				afterUpdateElement: this._update
			});
		}

	},

	_callback: function(element, value) {

		if (!$(this.options.target).visible())
			$(element)
				.removeClassName(this.options.defaultClass)
				.addClassName(this.options.busyClass);

		return value.replace(/^(\w)*=/gi, 'q=');
	},

	_hide: function(element, options) {
	
		$(options).hide();
	
		$(element)
			.removeClassName(this.options.busyClass)
			.addClassName(this.options.defaultClass);
	},

	_show: function(element, options) {

		var containerLeft = 0,
			containerTop = 0;

		if (Prototype.Browser.IE8) {
			containerLeft = $(options).cumulativeScrollOffset()[0] - this.options.offsetLeft;
			containerTop = $(options).cumulativeScrollOffset()[1] - this.options.offsetTop;
		} else if (Prototype.Browser.IE && !Prototype.Browser.IE8) {
			containerLeft = 0;
			containerTop = 0;
		}

		if (!options.style.position || options.style.position == 'absolute') {
			options.style.position = 'absolute';
			Element.clonePosition(options, element, {
				offsetLeft: containerLeft,
				offsetTop: element.offsetHeight + containerTop,
				setHeight: false,
				setWidth: this.options.setWidth
			});
		}

		$(options).show();

		$(element)
			.removeClassName(this.options.busyClass)
			.addClassName(this.options.defaultClass);
	},
		
	_update: function(element, selected) {

		if ($(selected).onselect != null) {
			eval($(selected).onselect.toString().replace(/this./, '$(element).').replace(/^([\s\S])*{/, '').replace(/\}$/, ''));
		}

	}

});

var $ready = Element.observe.curry(window, 'load');

// Onload

$ready( function() {

	// searchTextbox

	$$('.searchTextbox')
		.invoke('observe', 'focus', function() { if ($F(this).toLowerCase() == 'search this site') $(this).setValue(''); })
		.invoke('observe', 'blur', function() { if ($F(this).strip() == '') $(this).setValue('Search this site'); });
		
	$('searchForm').onbeforevalidate = function() {
		if ($F(this.q).toLowerCase() == 'search this site') $(this.q).setValue('');
	}

	$('searchForm').onaftervalidate = function() {
		if ($F(this.q).strip() == '') $(this.q).setValue('Search this site');
	}

	// AddThis!

	$$('#bookmark_addthis')
		.invoke('observe', 'mouseover', function() { if (typeof(addthis_open) != 'undefined') return addthis_open(this, '', '[URL]', '[TITLE]'); })
		.invoke('observe', 'mouseout', function() { if (typeof(addthis_close) != 'undefined') return addthis_close(); })
		.invoke('observe', 'click', function() { if (typeof(addthis_sendto) != 'undefined') return addthis_sendto(); });

});




// Miscellaneous

function goto() {
	var querystring = '';
	if (arguments.length > 0) querystring = 'fuseaction=' + arguments[0];
	if (arguments.length > 1) for (var i = 1; i < arguments.length; i++) querystring += '&' + arguments[i];
	location.search = querystring;
}

function selectRow(e) {

	var trigger = Event.element(e);
	if (trigger.tagName == 'INPUT') return false;

	var thisrow = Event.element(e);
	while (thisrow.tagName != 'TR') thisrow = thisrow.parentNode;
	$(thisrow).addClassName('TableRow_Selected');

	if (trigger.tagName == 'A') return false;
	else if (trigger.up().select('A').length > 0) {
		if (trigger.up().select('A')[0].onclick) trigger.up().select('A')[0].onclick();
		else window.location.href = trigger.up().select('A')[0].href;
		return false;
	}
}

function IsPopupBlocker() {

	var oWin = window.open ('', 'testpopupblocker', 'width=100,height=50,top=5000,left=5000');

	if (oWin == null || typeof(oWin) == "undefined") return true;
	else {
		oWin.close();
		return false;
	}

}

function pos() {
	var win = '1020,600';
	return {
		w: win.split(',')[0],
		h: win.split(',')[1],
		x: parseInt((document.viewport.getWidth() - win.split(',')[0]) / 2),
		y: parseInt((document.viewport.getHeight() - win.split(',')[1]) / 2)
	}
	
}

// Form elements

function checkLength(event, limit) {

	var element = Event.element(event); 
	var key = event.which || event.keyCode;

	if ((limit <= element.value.length) &&
		(key != Event.KEY_UP) && (key !=  Event.KEY_DOWN) && (key != Event.KEY_LEFT) && (key !=  Event.KEY_RIGHT) && 
		(key != Event.KEY_PAGEUP) && (key !=  Event.KEY_PAGEDOWN) &&(key != Event.KEY_HOME) && (key !=  Event.KEY_END) && 
		(key != Event.KEY_TAB) && (key !=  Event.KEY_RETURN) &&	(key != Event.KEY_ESC) &&
		(key != Event.KEY_BACKSPACE) && (key != Event.KEY_DELETE)
	) return false;
	else return true;
} 

function documentFormsInit() {

	$A(document.forms).each(function(form) {

		// Browser inconsistency fix

		if (!Prototype.Browser.IE) {

			for (var i = 0; i < form.elements.length; i++) 
				if (form.elements[i].type == 'checkbox') $(form.elements[i]).setStyle({ 'margin': '3px 3px 4px 4px' }); 
				else if (form.elements[i].type == 'radio') $(form.elements[i]).setStyle({ 'margin': '3px 3px 4px 4px' }); 
				else if (form.elements[i].type == 'textarea') $(form.elements[i]).rows = $(form.elements[i]).rows - 1; 

		}

	});

}

// Onload

Event.observe(window, 'load', function() { 

	documentFormsInit();


});

// Cookie

var Cookie = {
	set: function(name, value, daysToExpire) {
		var expire = '';
		if (daysToExpire != undefined) {
			var d = new Date();
			d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
			Expire = '; expires=' + d.toGMTString();
		}
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
	},
	get: function(name) {
		var cookie = document.cookie.match(new RegExp(escape(name) + '=([^;(\\s)]*);', 'gi'));
		var value = cookie[0].split('=')[1].length > 0 ? cookie[0].split('=')[1].substring(0, cookie[0].split('=')[1].length - 1) : '';
		return (cookie ? unescape(value) : null);
	},
	erase: function(name) {
		var cookie = Cookie.get(name) || true;
		Cookie.set(name, '', -1);
		return cookie;
	},
	accept: function() {
		if (typeof navigator.cookieEnabled == 'boolean') {
			return navigator.cookieEnabled;
		}
		Cookie.set('_test', '1');
		return (Cookie.erase('_test') === '1');
	}
};
