Effect.DefaultOptions.duration = '0.4';

if (Prototype.Browser.IE) Prototype.Browser[window.XMLHttpRequest ? 'IE7' : 'IE6'] = true;

window.windowOnload = new Array();

var app = 
{
	debug: true,
	
	strings: {
		err_timeout: 'I was unable to reach the server. Please try again shortly.',
		err_fatal: 'A fatal error has occurred. Please try again shortly.'
	},
	
	clearOnFocus: function(input)
	{
		input.value = '';
		input.onfocus = function() {};
	},
		
	jsonLoad: function(url, params, callback, errorCallback, loading)
	{
		var timeout;
		var preventLoading = false; // PREVENT RACE CONDITION

		new Ajax.Request(
			url,
			{
				method: 'get', 
				parameters: params,
				onLoading: function() {					
					timeout = setTimeout(
						function() { 
							if (preventLoading) return; 
							if (loading) loading.show();
						}, 150);						
				},
				onComplete: function(req) {
					preventLoading = true;
					clearTimeout(timeout);
					if (loading) loading.hide();					

					//var json;
					try {
						var json = req.responseText.evalJSON(true);					    
						//json = eval('(' + req.responseText + ')');
					} catch (e) { 
						if (errorCallback) errorCallback();
						return; 
					}

					if (req.responseText == '[]') json = {};
					if (!json)
					{
						if (errorCallback) errorCallback();
						return;
					}
					
					if (callback) callback(json);
				},
				onException: function() {
					preventLoading = true;
					clearTimeout(timeout);
					if (loading) loading.hide();					
					if (errorCallback) errorCallback();
				},
				onFailure: function() {
					preventLoading = true;
					clearTimeout(timeout);
					if (loading) loading.hide();					
					if (errorCallback) errorCallback();				
				}
			});
		
		return true;
	},
		
	blockLoad: function(block, element, url, callback, errorCallback, insertion, loading)
	{
		if (!$(element))
			return false;

		var timeout;
		var preventLoading = false; // PREVENT RACE CONDITION

		new Ajax.Updater(
			element,
			url,
			{
				method: 'get', 
				parameters: { block: block },
				evalScripts: true,
				insertion: insertion,
				onLoading: function() {
					timeout = setTimeout(
						function() { 
							if (preventLoading) return; 
							if (loading) loading.show();
						}, 150);
				},
				onComplete: function(req, json) {
					preventLoading = true;
					clearTimeout(timeout);
					if (loading) loading.hide();
					if (callback) callback(json);
				},
				onException: function() {
					preventLoading = true;
					clearTimeout(timeout);
					if (loading) loading.hide();					
					if (errorCallback) errorCallback();
				},
				onFailure: function() {
					preventLoading = true;
					clearTimeout(timeout);		
					if (loading) loading.hide();							
					if (errorCallback) errorCallback();				
				}
			});
		
		return true;
	},
	
	clipboard: function(input)
	{
		if (!input) return;

		if (!$('clipboard'))
		{
			var div = document.createElement('div');
			div.id = 'clipboard';
			document.body.appendChild(div);			
		}

		var so;

		if (Prototype.Browser.Gecko)
		{
			so = new SWFObject('/img/_clipboard.swf', 'so_clipboard', 0, 0, "8");		    
		}
		else
		{
			so = new SWFObject('/img/_clipboard.swf', 'so_clipboard', 1, 1, "8");
			so.addParam("salign", "lt");
			so.addParam("wmode", "transparent"); 		    
		}
		
		so.addVariable('clipboard', encodeURIComponent(input.value));
		so.write('clipboard');		
	},
	
	hover: function(event, x, className)
	{
		if(event.relatedTarget != x.firstChild) 
		{
			x.className = className;
		}
	},

	unhover: function(event, x, className)
	{
		if(event.relatedTarget != x) 
		{
			x.className = className;
		}
	},
	
	selectHide: function()
	{
		// Z-INDEX IS BROKEN FOR SELECTS IN IE6		
		if (Prototype.Browser.IE6)
		{
			var elements = document.getElementsByTagName('select');
		    for (var i=0; i<elements.length; i++)
	        	elements[i].style.visibility = 'hidden';
		}		
	},
	
	selectShow: function()
	{
		// Z-INDEX IS BROKEN FOR SELECTS IN IE6
		if (Prototype.Browser.IE6)
		{
			var elements = document.getElementsByTagName('select');
		    for (var i=0; i<elements.length; i++)
	        	elements[i].style.visibility = 'visible';
		}		
	}
}

app.loading = Class.create();

app.loading.prototype =
{
	initialize: function(width, height)
	{
		this.overlay = $('overlay');
		this.loading = $('loading');
		
		this.width = width || 48;
		this.height = height || 48;

		this.so = new SWFObject(
			'/img/spinner.swf',
			'so_spinner',
			this.width, this.height, "8", "#ffffff", true);
		this.so.addParam("salign", "lt");	
		this.so.addParam("wmode", "transparent");
		this.so.write('loading');
	},

	set: function(x)
	{
		this.x = x;
				
		// Workaround Firefox Mac bug with opacity and Flash transparency
		if (window.mac && Prototype.Browser.Gecko)
		{
			this.x.descendants().each(function(x) { x.setOpacity('') });
			this.overlay.style.background = 'url(/img/whitey.png)';
		}
		else
		{
			this.overlay.setOpacity('0.5');				
		}
		this.overlay.style.position = 'absolute'; // FORCE SAFARI
		Position.clone(this.x, this.overlay);
		this.loading.style.left = (parseInt(this.overlay.style.left,10) + (parseInt(this.overlay.style.width,10) / 2 - this.width / 2)) + 'px';
		this.loading.style.top = (parseInt(this.overlay.style.top,10) + (parseInt(this.overlay.style.height,10) / 2 - this.height / 2)) + 'px';		
	},

	show: function()
	{
		this.overlay.show();
		this.loading.show();
	},

	hide: function()
	{
		this.loading.hide();
		new Effect.Fade('overlay', {duration:0.3});
	}
}

app.lightbox = Class.create();

app.lightbox.prototype =
{
	initialize: function(content, width, height, before, after, callback)
	{
		this.overlay = $('pageoverlay');
		this.lightbox = $('lightbox');
		this.content = $(content);
		
		this.width = width;
		this.height = height;
		
		this.before = before;
		this.after = after;
		
		this.lightbox.update('');
		this.lightbox.appendChild(this.content);
		this.content.show();		
	},
	
	show: function(onClose)
	{
		this.onClose = onClose;
		
		if (this.before)
			this.before();
			
		// POSITION FIXED IS BROKEN IN IE6		
		if (this.overlay.getStyle('position') == 'absolute')
		{
			this.overlay.setStyle({
				width: (document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollWidth : document.body.offsetWidth) + 'px', 
				height: (document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight) + 'px'
			});			
		}
				
		var x = Math.round(((window.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth)) - this.width) / 2);
		var y = Math.round(((window.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight)) - this.height) / 2);

		// SAFARI HAS PROBLEMS WITH OVERFLOW AUTO AND FIXED POSITIONING
		if (Prototype.Browser.WebKit)
			this.lightbox.setStyle({position: 'absolute'});

		// POSITION FIXED IS BROKEN IN IE6
		if (this.lightbox.getStyle('position') == 'absolute')
		{
			x += (window.pageXOffset || (document.documentElement.scrollLeft || document.body.scrollLeft));
			y += (window.pageYOffset || (document.documentElement.scrollTop || document.body.scrollTop));

			app.selectHide();
		}

		this.lightbox.setStyle({left: (x > 0 ? x : 0) + 'px', top: (y > 0 ? y : 0) + 'px'});

		var obj = this;		
		
		new Effect.Parallel([new Effect.Appear(this.overlay, {from: 0.0, to: 0.8, duration: 0.3, sync:true}),	
							new Effect.Appear(this.lightbox, {from: 0.0, to: 0.999999, duration: 0.3, sync:true})],
							{afterFinish: function()
								{
									/* obj.overlay.onclick = function() { obj.hide(); }.bindAsEventListener(this); */
									obj.lightbox.setOpacity('');
								}
							});
	},
	
	hide: function()
	{
		var obj = this;		
		
		new Effect.Parallel([new Effect.Fade(this.overlay, {from: 0.8, to: 0.0, duration: 0.3, sync:true}),	
							new Effect.Fade(this.lightbox, {from: 0.999999, to: 0.0, duration: 0.3, sync:true})],
							{afterFinish: function()
								{
									obj.overlay.onclick = function() { };
									obj.lightbox.setOpacity('');
																		
									app.selectShow();
									
									if (obj.onClose)
										obj.onClose();
									
									if (obj.after)
										obj.after();
								}
							});		
	},
	
	top: function(y)
	{
		var cur = parseInt(this.lightbox.getStyle('top'),10);
		if (!y) return cur;
		
		this.lightbox.setStyle({top: (cur + y) + 'px'});
		return (cur + y);
	}
}

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 = encodeURIComponent(name) + '=' + encodeURIComponent(value) + expire + '; path=/');
	},
	
	get: function(name)
	{
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + encodeURIComponent(name) + '=([^;\\s]*)'));
		return (cookie ? decodeURI(cookie[2]) : 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');
	}
};

// FOR AJAX TIMEOUT

function callInProgress (xmlhttp)
{
	switch (xmlhttp.readyState)
	{
		case 1: case 2: case 3:
			return true;
			break;
		// Case 4 and 0
		default:
			return false;
			break;
	}
}

var allowErrorAlerts = true;

function showFailureMessage()
{
	if (allowErrorAlerts)
	{
		allowErrorAlerts = false;
		alert(app.strings.err_timeout);
		allowErrorAlerts = true;
	}
	Element.hide('overlay');
	Element.hide('loading');
}

function showFatalMessage(e)
{
	if (allowErrorAlerts)
	{
		allowErrorAlerts = false;
		alert(app.strings.err_fatal+(app.debug ? '\n\n'+e.message : ''));
		allowErrorAlerts = true;
	}
	Element.hide('overlay');
	Element.hide('loading');
}

// Register global responders that will occur on all AJAX requests

Ajax.Responders.register({
	onCreate: function(request)
	{
		request['timeoutId'] = window.setTimeout(
			function()
			{
				// If we have hit the timeout and the AJAX request is active, abort it and let the user know
				if (callInProgress(request.transport))
				{
					request.transport.abort();
					if (request.url.indexOf('quiet=1') == -1)					
						showFailureMessage();
					// Run the onFailure method if we set one up when creating the AJAX object
					if (request.options['onFailure'])
					{
						request.options['onFailure'](request.transport, request.json);
					}
				}
			},
			30000 // 30 seconds
		);
	},
	onComplete: function(request)
	{		
		// Clear the timeout, the request completed ok
		window.clearTimeout(request['timeoutId']);
	},
	onException: function(request, e)
	{
		// Clear the timeout
		window.clearTimeout(request['timeoutId']);
		request.transport.abort();
		
		if (e.name == "NS_ERROR_NOT_AVAILABLE")
		{
			return false;
		}
		showFatalMessage(e);
	}
});

String.prototype.__trim = function()
{
    return this.replace(/^\s*|\s*$/g,'');
}

function popWindow(event,x,width,height,title)
{	
	Event.stop(event);
	
	if (!title) title = 'togoPop';
	args = "width=" + (width) + "," 
	+ "height=" + (height) + "," 
	+ "location=0," 
	+ "menubar=0,"
	+ "resizable=1,"
	+ "scrollbars=1,"
	+ "status=1," 
	+ "titlebar=0,"
	+ "toolbar=0,"
	+ "hotkeys=0";
	window.open(x.href,title,args);
}

// DISABLE DELETE = BACK IN BROWSER

function __disableBackspace(event)
{
	var keycode = event.charCode ? event.charCode : event.keyCode;

	if (keycode && (keycode == 8) && !(Event.element(event) && Event.element(event).value))
		Event.stop(event);
}

document.onkeydown = __disableBackspace.bindAsEventListener(this);
document.onkeypress = __disableBackspace.bindAsEventListener(this);

// OS DETECT

window.win = ( navigator.appVersion.indexOf( 'Win' ) != -1 );
window.mac = ( navigator.appVersion.indexOf( 'Mac' ) != -1 );
window.lin = ( navigator.userAgent.indexOf( 'Linux' ) != -1 );

// ENABLE BACKGROUND IMAGE CACHE

if (Prototype.Browser.IE6) try {document.execCommand("BackgroundImageCache", false, true);} catch (e){}; 

// CLIENT TIMEZONE
var TZ = new Date().getTimezoneOffset();
