$.ajaxSetup({
	type: 'POST',
	error: function () {
		eu.pageLoading(2, 'Tranfer error.');
	},
	dataType: 'json'
});

$().ajaxStart(function () {
	eu.pageLoading(1, '');
});

$().ajaxStop(function () {
	eu.pageLoading(0);
});

window.eu = {
	main_dir: '/',
	updateFreq: 30000,
	
	init_avatars: function (avatars_data) {
		if (!eu.avatar_bubble) {
			eu.avatar_bubble = {
				create_nodes: function() {
					this.node = $(document.createElement('table'))
						.addClass('ui-avatar-bubble')
						.hide();
					
					var tbody = document.createElement('tbody');
					
					var tr = document.createElement('tr');
					var td = document.createElement('td');
					td.className = 'ui-bt';
					tr.appendChild(td);
					td = document.createElement('td');
					td.className = 'ui-bt';
					tr.appendChild(td);
					td = document.createElement('td');
					td.className = 'ui-ctr png';
					tr.appendChild(td);
					tbody.appendChild(tr);
					
					tr = document.createElement('tr');
					td = document.createElement('td');
					td.className = 'ui-blr';
					tr.appendChild(td);
					var td = document.createElement('td');
					td.className = 'ui-content';
					var a = document.createElement('a');
					this.image = $(document.createElement('img'))
						.load($.hitch(this, function () {
								this.node.show();
								$(window).one('resize', $.hitch(this, this.hide));
								
								var bubblePop = $.hitch(this, function (e) {
									if (!$.eventIsOverEle(e, this.node)) {
										eu.avatar_bubble.hide();
										$(document).unbind('mouseover', bubblePop);
									};
								});
								
								setTimeout(function () { $(document).mouseover(bubblePop) });
							}))
						.addClass('ui-image')
						.appendTo(a);
					td.appendChild(a);
					this.content_node = document.createElement('div');
					td.appendChild(this.content_node);
					tr.appendChild(td);
					td = document.createElement('td');
					td.className = 'ui-blr';
					tr.appendChild(td);
					tbody.appendChild(tr);
					
					tr = document.createElement('tr');
					td = document.createElement('td');
					td.className = 'ui-cbl png';
					tr.appendChild(td);
					td = document.createElement('td');
					td.className = 'ui-bb';
					tr.appendChild(td);
					td = document.createElement('td');
					td.className = 'ui-cbr png';
					tr.appendChild(td);
					tbody.appendChild(tr);
					
					this.node.append(tbody);
					$('#docpane').append(this.node);
				},
				show: function (e) {
					this.e = e;
					
					if (e.target.src) {
						if (!this.node) this.create_nodes();
						
						var user_id = e.target.parentNode.className.substr(10);
						var user = eu.avatar_list[user_id];
						
						var docpane = $('#docpane')[0];
						var docpane_scroll = docpane.pageYOffset || docpane.scrollTop || 0;
						
						var target_offset = $(e.target).offset();
						
						this.node.css({
							top: (target_offset.top + docpane_scroll - docpane.offsetTop - 10) + 'px',
							left: target_offset.left - 10 + 'px'
						});
						
						$(this.image)
							.parent().attr('href', e.target.parentNode.href).end()
							.attr('src', e.target.src);						
						var c = '';
						
						if (user.is_listing_friend) {
							c += '<img src=\"' + eu.main_dir + 'images/icons/bullet_' + (user.is_online ? 'green' : 'red') + '.png\" class=\"icon\" width=\"16\" height=\"16\" />';
						}
						c += '<strong>' + user.user_name + '</strong>';
		
						if (user.status) c += '<p>... ' + user.status + '</p>';
						else if (user.tagline) c += '<p>' + user.tagline + '</p>';
							
						if (user.pc) c += '<p><em>Personality: ' + user.pc + '% like you</em></p>';
						
						if (!user.is_self && _user.is_logged_in) {
							c += '<div class="ui-menu">' +
								'<a href="' + eu.main_dir + user.homepage + '">Home Page</a> | ' +
								'<a href="javascript:;" onclick="new eu.handled_dialog(\'friends/dialog\',{user_id:' + user_id + '})">' +
									((user.is_contact) ? 'Settings' : 'Add friend') + '</a> | ' +
								'<a href="' + eu.main_dir + 'friends/block/' + user_id + '">' + ((user.is_blocked) ? 'Unblock' : 'Block') + '</a> | ' +
								'<a href="javascript:eu.im(' + user_id + ')">IM</a> | ' +
								'<a href="' + eu.main_dir + 'mail/box/write/message/' + user_id + '">Message</a> </div>';
						}
						
						$(this.content_node).html(c);
					}
				},
				hide: function () {
					this.node.hide();
					this.image.src = '';
				}
			}
		}
		
		eu.avatar_list = {};
		for (var i in avatars_data)
		{
			eu.avatar_list[i] = avatars_data[i];
			
			$('.useravatar' + i).mouseover($.hitch(eu.avatar_bubble, eu.avatar_bubble.show));
		}
	},
	update_avatar_data: function (user_id) {
		$.ajax({
			data: { request_user_id: user_id },
			url: eu.main_dir + 'friends/getavatardata',
			success: function (data) {
				eu.avatar_list[user_id] = data[user_id];
			}
		});
	},
	block_user: function (user_id) {
		if (confirm('Are you sure you want to block this person?')) {
			var block_error = function (error) {
				alert('Sorry, we could not change this user\'s blocking status, please try again later.');
			}
			
			$.ajax({
				data: { block_user_id: user_id },
				url: eu.main_dir + 'friends/blockuser',
				success: function () {
					eu.avatar_bubble.hide();
					eu.update_avatar_data(user_id);
				},
				error: block_error
			});
		}
	},
	
	alerts: {},
	alertHandler: function (data) {
		for (var x in data)
			eu.alert(data[x]);
	},
	alert: function (data) {
		if (!data.content) return;
		
		if (!eu.alertArea) {
			eu.alertArea = $(document.createElement('div'))
				.addClass('ui-alert-area')
				.appendTo(document.body);
		}
		if (!eu.alerts[data.id]) {
			eu.alerts[data.id] = data;
			
			function alertClick (e, callBack) {
				var id = e.target.parentNode.id.substr(5);
				eu.alertDismiss(id, callBack);
				$(e.target).parent().fadeOut('fast', function () {
					$(e.target).remove();
				});
			}
			
			$(document.createElement('div'))
				.addClass('ui-alert')
				.attr({id: 'alert' + data.id})
				.append($(document.createElement('a'))
					.attr({
						title:'Click to open',
						href:'javascript:;'
					})
					.addClass('ui-msg')
					.click(function (e) {
						alertClick(e, function () {
							window.location.href = data.href;
						});
					})
					.html(data.content))
				.append($(document.createElement('a'))
					.addClass('ui-close')
					.attr({'href': 'javascript:;'})
					.click(alertClick)
					.text('X'))
				.appendTo(eu.alertArea);
		}
	},
	alertDismiss: function (id, callBack) {
		var callBack = callBack ? callBack : function () {};
		
		$.ajax({
			url: eu.main_dir + 'scripts/util',
			data: {request: 'alert_dismiss', id: id},
			success: callBack
		});
	},
	
	updateToolbar: function () {
		$.ajax({
			url: eu.main_dir + 'scripts/util',
			data: {request: 'update'},
			success: function(data){
				eu.pageAction('update', data);
				setTimeout('eu.updateToolbar()', eu.updateFreq);
			}
		});
	},
	update_count_spans: function (cn, c) { $('.count_' + cn).html(c); },
	
	pageLoading: function (state, message) {
		message = (message) ? message : '';
		switch (state) {
		case 0: $('#pageloading').hide(); break;
		case 1: $('#pageloading').show(); break;
		case 2: $('#pageloadingimg').attr('src', '/images/error.gif'); break;
		}
		$('#pageloadingimg').attr('title', message);
	},
	
	statusSend: function (e) {
		if (e) e.preventDefault();
		$.ajax({
			url: eu.main_dir + 'scripts/util',
			data: {request:'status_change', status:$('#status_field').val()}
		});
		$('#status_tag').html($('#status_field').val());
		$('#status_view').show();
		$('#status_edit').hide();
	},
	statusEdit: function () {
		$('#status_view').hide();
		$('#status_edit').show();
	},
	
	handledDialogs: [],
	handled_dialog: function (handler, content, formNode, o) {
		this.n = eu.handledDialogs.length;
		eu.handledDialogs.push(this);
		
		o = o || {};
		
		this.request = function (params)
		{
			_this = this;
			
			if (!params.content) params.content = {};
			params.content._type = params.type;
			params.content._dialog_id = this.n;
			
			if (params.formNode) {
				$.each($(params.formNode).serializeArray(), function (k, v) {
					params.content[v.name] = v.value;
				});
			}
			
			function success (data) {
				if (data.beforeButtonPress) data.beforeButtonPress = eval(data.beforeButtonPress);
				if (data.buttonPress) data.buttonPress = eval(data.buttonPress);
				
				if (params.load) params.load(data);
				else if (params.update) $(params.update).html(data.content);
				else {
					//if (!data.buttons) data.buttons = {};
					_this.dialog.alter(data);
				}
				
				if (data.eval) eval(data.eval);
				if (data.done) {
					_this.dialog.hide();
					return;
				}
			}
			function error () {
				_this.dialog.alter({
					title: 'Error',
					content: 'Sorry, the dialog failed to load.  This could be a result of an error or a connection problem.  Please try again later.',
					width: 300,
					buttons: {Ok: 0}
				});
			}
			
			var use_iframe = false;
			if (params.formNode)
			{
				$(params.formNode).find("input[type='file']").each(function (i) {
					if ($(this).val()) use_iframe = true;
				});
			}
			
			if (use_iframe) {
				$.getScript(eu.main_dir + 'tp/jquery/jquery.form.js', $.hitch(this, function () {
					for (var i in params.content) {
						if ($(params.formNode).find("input[name='" + i + "']").length) continue;
						
						$(params.formNode).append($('<input type="hidden" />')
							.addClass('ui-generated')
							.attr({
								name: i,
								value: params.content[i]
							}));
					}
					
					$(params.formNode).ajaxSubmit({
						type: 'POST',
						url: eu.main_dir + handler + '?_ift=1',
						data: params.content,
						dataType: 'json',
						success: $.hitch(this, success),
						error: error,
						clearForm: false,
						resetForm: false,
						iframe: true
					});
				}));
				return;
			}
			
			$.ajax({
				data: params.content,
				url: eu.main_dir + handler,
				success: $.hitch(this, success),
				error: error
			});
		}
		
		this.dialog = $.prompt({title: 'Loading', content: 'Loading, please wait...', container: o.container || 'body'});
		
		this.request({type: 'init', content: content, formNode: formNode});
	},
	JSON_Responder: function (params) {
		if (!params) params = {};
		this.name = params.name;
		
		this.request = function (params) {
			function success (data) {
				$('.ui-generated', params.formNode).remove();
				
				if (!data) return;
					
				if (params.load) params.load(data);
				else if (data.content) $('#' + this.name).html(data.content);
				
				if (data.eval) eval(data.eval);
			}

			if (!params.content) params.content = {};
			params.content._type = params.type;
			params.content._responder = this.name;
			
			var use_iframe = false;
			if (params.formNode)
			{
				$(params.formNode).find("input[type='file']").each(function (i) {
					if ($(this).val()) use_iframe = true;
				});
			}
			
			if (use_iframe) {
				$.getScript(eu.main_dir + 'tp/jquery/jquery.form.js', $.hitch(this, function () {
					for (var i in params.content) {
						if ($(params.formNode).find("input[name='" + i + "']").length) continue;
						
						$(params.formNode).append($('<input type="hidden" />')
							.addClass('ui-generated')
							.attr({
								name: i,
								value: params.content[i]
							}));
					}
					
					$(params.formNode).ajaxSubmit({
						type: 'POST',
						url: window.location.href + (window.location.href.indexOf('?') == -1 ? '?' : '&') + '_ift=1',
						data: params.content,
						dataType: 'json',
						success: $.hitch(this, success),
						clearForm: false,
						resetForm: false,
						iframe: true
					});
				}));
				return;
			}

			if (params.formNode) {
				$.each($(params.formNode).serializeArray(), function (k, v) {
					params.content[v.name] = v.value;
				});
			}
			
			$.ajax({
				type: 'POST',
				dataType: 'json',
				data: params.content,
				url: window.location.href,
				success: $.hitch(this, success)
			});
		}
		
		if (params.init) {
			this.request({
				type: 'init',
				content: params.content,
				formNode: params.formNode
			});
		}
	},
	
	im: function (user_id) {
		var imwindow = window.open(eu.main_dir + 'chat/im/new/' + user_id,'','width=500,height=460,toolbar=0,resizable=1,directories=0,copyhistory=0,menubar=0,scrollbars=0,location=0,status=1');
	},
	im_join: function (id) {
		var imwindow = window.open(eu.main_dir + 'chat/im/connect/' + id,'','width=500,height=460,toolbar=0,resizable=1,directories=0,copyhistory=0,menubar=0,scrollbars=0,location=0,status=1');
	},
	
	pageAction: function (action, data) {
		if (action == 'load') {
			$(document).ready(function () {
				setTimeout('eu.updateToolbar()', eu.updateFreq);
				$('#statusform').submit(eu.statusSend);
			});
			if ($.browser.msie)
			{
				$().ready(function () {
					$('.ui-sf-nav').find('li,ul')
						.mouseover(function(){$(this).addClass('sfhover'); })
						.mouseout(function(){$(this).removeClass('sfhover'); })
				});
			}
			$('#docpane').ready(function() {
				$('#docpane').focus();
				function resize_layout () {$('#docpane').height((document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight) - $('#docpane').offset()['top']);}
				$(window).resize(resize_layout);
				resize_layout();
			});
		}
		
		$(document).ready(function () {
			for (var x in data.count) eu.update_count_spans(x, data.count[x]);
			
			eu.alertHandler(data.alerts);
		});
	},
	
	showLoginDialog: function () {
		eu.loginDialog = $.prompt({
			title: 'Login',
			content:
				'<div id="loginbox">' +
					'<div id="loginerror" class="ui-login-error error"></div>' +
					'<div id="loginform">' +
						'<table>' +
							'<tr><td align="right">Email:</td><td><input type="text" name="login[email]" accesskey="u" id="frmemail" class="logininput ui-login-email" /></td></tr>' +
							'<tr><td align="right"><label for="frmpassword">Password:</label></td>' +
							'<td><input type="password" name="login[password]" accesskey="p" id="frmpassword" class="logininput ui-login-password" /></td></tr>' +
							'<tr><td valign="top" colspan="2"><input type="checkbox" class="checkbox" name="login[autologin]" accesskey="a" id="frmautologin" checked="checked" />' +
							'<label for="frmautologin"> Remember Me</label></td></tr>' +
						'</table>' +
					'</div><br />' +
					'<a href="javascript:;" onclick="eu.loginDialogSwitchToLostPass();">Did you forget your password?</a><br /><br />' +
					'<a href="' + eu.main_dir + 'account/register">Not a Kuzoa Resident?</a>' + 
				'</div>' +
				'<div id="forgotpasswordbox" class="hidden">' +
					'<div id="forgotpassworderror" class="error"></div>' +
					'In order to get you your new password, we need the email address of the account.' +
					'<table><tr><td>Email:</td><td><input type="text" name="email" id="forgotpasswordemail" /></td></tr></table><br />' +
					'<a href="javascript:;" onclick="eu.loginDialogSwitchToLogin();">Ready to Log in?</a><br /><br />' +
					'<a href="' + eu.main_dir + 'account/register">Not a Kuzoa Resident?</a>' +
				'</div>',
			width: '270px',
			buttons: {Ok: 1, Cancel: 0},
			beforeButtonPress: function (a) {
				$('#loginerror').text('');
				$('#forgotpassworderror').text('');
				
				if (a == 1) {
					if ($('#frmemail').val() && $('#frmpassword').val()) login(a);
					else $('#loginerror').text('You must enter an email and a password.');
				} else if (a == 2) {
					if ($('#forgotpasswordemail').val()) login(a);
					else $('#forgotpassworderror').text('You must enter an email address.');
				}
				
				if (a) return false;
				else eu.loginDialog = null;
			},
			loaded: function () { $('#frmemail').focus(); }
		});
		
		function login (a) {
			if (a == 1) {
				eu.loginAction(eu.loginDialog.nodes.form);
			} else if (a == 2) {
				$.ajax({
					url: eu.main_dir + 'account/forgotpassword',
					data: eu.loginDialog.nodes.form.serialize(),
					success: function(data){
						if (data.success) eu.loginDialog.alter({content:data.message,buttons:{Ok:0}});
						else $('#forgotpassworderror').html(data.message);
					},
					error: function() { alert('Sorry there was an internal error, please try again later.'); }
				});
			}
		}
	},

	loginDialogSwitchToLogin: function () {
		$('#loginerror').html('');
		eu.loginDialog.alter({title:'Login',addButtons:{Ok:1}});
		$('#forgotpasswordbox').addClass('hidden');
		$('#loginbox').removeClass('hidden');
	},
	loginDialogSwitchToLostPass: function () {
		$('#loginbox').addClass('hidden');
		eu.loginDialog.alter({title:'Forgot your password?',addButtons:{Ok:2}});
		$('#forgotpasswordbox').removeClass('hidden');
	},
	loginDialogShowLostPass: function () {
		eu.showLoginDialog();
		eu.loginDialogSwitchToLostPass();
	},
	loginForm: function (e) {
		e.preventDefault();
		
		eu.loginAction($(e.target));
	},
	loginAction: function (form) {
		if (eu.loggingIn) return;
		eu.loggingIn = true;
		
		if (!form) form = eu.loginDialog.nodes.form;
		
		$.ajax({
			url: eu.main_dir + 'account/login',
			data: $(form).serialize(),
			success: function(data){
				eu.loggingIn = false;
				
				switch (data.status) {
				case 3:
					if (!eu.loginDialog) eu.showLoginDialog();
					
					var dialogForm = eu.loginDialog.nodes.form;
					dialogForm.find('.ui-login-error').html(data.error);
					
					if (form != dialogForm) {
						dialogForm.find('.ui-login-email').val(form.find('.ui-login-email').val());
						dialogForm.find('.ui-login-password').val(form.find('.ui-login-password').val());
					}
					break;
				default:
					var o = {
						title:'Logging In',
						content:'Please wait...',
						buttons: {}
					};
					if (eu.loginDialog) eu.loginDialog.alter(o);
					else $.prompt(o);
					
					window.location.href = data.redirect;
					break;
				}
			},
			error: function() { alert('Sorry there was an internal error while logging in, please try again later.'); }
		});
	}
};

handled_dialog = eu.handled_dialog;
pageLoading = eu.pageLoading;

/*
 * jQuery Impromptu
 * By: Trent Richardson [http://trentrichardson.com]
 * Version 1.2
 * Last Modified: 11/21/2007
 * 
 * Copyright 2007 Trent Richardson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
jQuery.extend({	
	ImpromptuDefaults: {
		prefix:'ui-dialog',
		buttons:{ Cancel:0 },
		hideClose: false,
		loaded:function(){},
		beforeButtonPress:function(){return true;},
		buttonPress:function(){},
		formSubmit:function(e){e.preventDefault();},
		container:'body',
		opacity:0.5,
		overlaySpeed:'slow',
		promptSpeed:'fast',
		show:'fadeIn'
	},
	SetImpromptuDefaults: function(o){jQuery.ImpromptuDefaults = jQuery.extend({},jQuery.ImpromptuDefaults,o);},
	prompt: function(o){
		o = jQuery.extend({},jQuery.ImpromptuDefaults,o);
		
		function handle_o () {
			if (o.beforeButtonPress && !jQuery.isFunction(o.beforeButtonPress)) o.beforeButtonPress = eval(o.beforeButtonPress);
			if (o.buttonPress && !jQuery.isFunction(o.buttonPress)) o.buttonPress = eval(o.buttonPress);
		}
		handle_o();
		
		var ie6 = (jQuery.browser.msie && jQuery.browser.version < 7);	
		var b = jQuery(o.container);	
		
		//ie6 calculation functions
		var getfoffset = function(){ return (document.documentElement.scrollTop || document.body.scrollTop) + 'px'; };
		var getjoffset = function(){ return (document.documentElement.scrollTop || document.body.scrollTop) + Math.round(15 * (document.documentElement.offsetHeight || document.body.clientHeight) / 100) + 'px'; };
		var ie6scroll = function(){ fade.css({ top: getfoffset() }); n['box'].css({ top: getjoffset() }); };
		
		if(ie6) jQuery(window).scroll(ie6scroll); // ie6, add a scroll event to fix position:fixed
		
		if (!b.data('ImpromptuFade')) {
			if ($.browser.msie) var fade = $('<div>');
			else var fade = $('<iframe>').attr('frameborder', 0);
			
			fade
				.addClass(o.prefix + '-fade')
				.css({
					position: 'absolute',
					height: '100%',
					width: '100%',
					top: (ie6)? getfoffset():0,
					left: 0,
					right: 0,
					bottom: 0,
					zIndex: 998,
					opacity: 0,
					border: 0
				})
				.fadeTo(o.overlaySpeed, o.opacity);
			
			b.data('ImpromptuOldPosition', b.css('position'))
				.css('position', 'relative');
			b.prepend(fade).data('ImpromptuFade', fade);
		}
		
		var fade = b.data('ImpromptuFade');
		fade.data('ImpromptuCount', (fade.data('ImpromptuCount') ? fade.data('ImpromptuCount') : 0) + 1);
		
		if (fade.data('ImpromptuCount') > 1) {
			var siblings = fade.siblings('.' + o.prefix);
			siblings.each(function () {
				$(this).css('zIndex', fade.css('zIndex') - siblings.length + $(this).data('ImpromptuID'));
			});
		}
		
		var n = {};
		
		if (!o.hideClose)
		{
		n['closeButton'] = $(document.createElement('a'))
			.addClass(o.prefix + '-close-button')
			.attr('href', 'javascript:;')
			//.css('zIndex', 1000)
			.click($.hitch(this, function (e) {
				buttonPress(null, 0);
			}))
			.text('x');
		}
		n['title'] = $(document.createElement('div'))
			.addClass(o.prefix + '-title')
			.html(o.title);
		n['msg'] = $(document.createElement('div'))
			.addClass(o.prefix + '-message');
		n['buttons'] = $(document.createElement('div'))
			.addClass(o.prefix + '-buttons');
		n['cont'] = $(document.createElement('div'))
			.addClass(o.prefix + '-container')
			.append(n['title']);
		if (!o.hideClose) {
			n['cont'].append(n['closeButton']);
		}
		n['cont']
			.append(n['msg'])
			.append(n['buttons'])
			.append($(document.createElement('div')).css('clear', 'both'));
		if (!o.noForm)
		{
			n['form'] = $(document.createElement('form'))
				.submit(o.formSubmit)
				.append(n['cont']);
		}
		n['box'] = $(document.createElement('div'))
			.addClass(o.prefix)
			.append(n['form'] ? n['form'] : n['cont'])
			.css({
				position: 'absolute',
				zIndex: 999
			})
			.data('ImpromptuID', fade.data('ImpromptuCount'));
		if (ie6) {
			n['box'].data('ImpromptuHiddenEles',
				b.find('select:visible')
					.not(n['box'].find('select'))
					.css('visibility', 'hidden'));
		}
		if (o.width) n['box'].width(o.width);
		
		b.prepend(n['box']);
		n['msg'].html(o.content ? o.content : '');
		load_buttons();
		
		position(true);
		n['box'][o.show](o.promptSpeed, o.loaded);
		$(window).resize(position);
		
		function hide () {
			if (ie6) {
				n['box'].data('ImpromptuHiddenEles')
					.css('visibility', 'visible');
			}
			
			n['box'].remove();

			if (ie6) jQuery(window).unbind('scroll', ie6scroll); //ie6, remove the scroll event
			
			var fade = $(o.container).data('ImpromptuFade');
			fade.data('ImpromptuCount', fade.data('ImpromptuCount') - 1);
			
			if (!fade.data('ImpromptuCount')) {
				fade.fadeOut(o.overlaySpeed, function() {
					$(this).remove();
					
					$(o.container)
						.css('position', $(o.container).data('ImpromptuOldPosition'))
						.data('ImpromptuFade', '');
				});
			} else {
				var max;
				fade.siblings('.' + o.prefix).each(function () {
					if (!max) max = $(this);
					else if (max.css('zIndex') < $(this).css('zIndex')) max = $(this);
				});
				max.css('zIndex', 999);
			}
		}
		
		function buttonPress (e, clicked) {
			var clicked = clicked != null ? clicked : o.buttons[jQuery(this).text()];
						
			if (o.beforeButtonPress(clicked) != false){
				hide();	
				
				o.buttonPress(clicked);
			}
			
			$(window).unbind('resize', position);
		}
		
		function load_buttons () {
			n['buttons'].html('');
			jQuery.each(o.buttons,function(k,v){
				n['buttons'].append($(document.createElement('button'))
					.attr({name: 'button'+ k, id: o.prefix + '-button' + k, value: v})
					.html(k)
					.click(buttonPress));
			}) ;
		}
		
		function position (hide) {
			n['box'].hide();
			n['box'].css({
				top: ((b.height() / 2) - (n['box'].height() / 2)) + 'px',
				left: ((b.width() / 2) - (n['box'].width() / 2)) + 'px',
				display: hide == true ? 'none' : ''
			});
		}
		
		return {
			o: o,
			nodes: n,
			alter: function (ao) {
				if (ao.title) {n['title'].html(ao.title); delete ao.title;};
				var initWidth = n['box'].width();
				if (ao.content) {n['msg'].html(ao.content); delete ao.content;}
				if (ao.buttons || ao.addButtons) {
					if (ao.buttons) o.buttons = ao.buttons;
					else if (ao.addButtons) $.extend(o.buttons, ao.addButtons);
					load_buttons();
				}
				if (ao.width) n['box'].width(ao.width);
				$.extend(o, ao);
				position();
				handle_o();
			},
			hide: hide
		};
	},
	eventIsOverEle: function (e, ele) {
		var on = false;
		var target = e.target;
		ele = ele[0];
		
		do {
			if (target == ele) {
				on = true;
				break;
			}
			target = target.parentNode;
			
		} while (target);
		
		return on;
	},
	hitch: function() {
		var _obj = arguments[0] || this;
		var _func = arguments[1] || null;
		var _args = $.grep(arguments, function(v, i) {
			return i > 1;
		});
		
		return function() {
			var _args2 = [];
			$.grep(arguments, function(v, i) {_args2.push(v);});
			
			return _func.apply(_obj, _args2.concat(_args));
		};
	}
});
jQuery.fn.extend({
	prompt: function (o) {
		this.each(function () {
			var opts = jQuery.extend({container: this}, o);
			$.prompt(opts);
		});
		return this;
	}
});


if (typeof(window['dojo']) != "undefined") {
	dojo.require("dojo.debug.Firebug");
	dojo.require("dojo.event.*");
	dojo.require("dojo.widget.Dialog");
	
	eu.dialog = function (params) {
		var showing = false;
		var dialogNode = document.createElement('div');
		var dialogContainerNode = document.createElement('div');
		dialogContainerNode.id = 'dialogcontainer';
		var dialogCloseNode = document.createElement('a');
		dialogCloseNode.id = 'dialogclose';
		dialogCloseNode.innerHTML = 'X';
		var dialogTitleNode = document.createElement('h2');
		var dialogContentNode = document.createElement('div');
		dialogContentNode.id = 'dialogcontent';
		dialogNode.appendChild(dialogContainerNode);
		dialogContainerNode.appendChild(dialogCloseNode);
		dialogContainerNode.appendChild(dialogTitleNode);
		dialogContainerNode.appendChild(dialogContentNode);
		document.body.appendChild(dialogNode);
		
		this.dialogWidget = dojo.widget.createWidget('Dialog', {
			widgetId: 'dialog',
			bgColor: '#000000',
			bgOpacity: '0.6',
			toggle: 'fade',
			toggleDuration: '400',
			blockDuration: '175',
			executeScripts: true,
			scriptScope: this
		}, dialogNode);
		
		this.dialogCotentWidget = dojo.widget.createWidget('ContentPane', {
			widgetId: 'dialogcontentpane',
			executeScripts: true
		}, dialogContentNode);
		
		this.dialogCotentWidget.onLoad = dojo.lang.hitch(this, function () {
			this.dialogWidget.placeDialog();
		});
		
		this.setUrl = function (url)
		{ this.dialogCotentWidget.setUrl(url); }
	
		this.setParams = function (params) {
			if (params.width)
				dialogContentNode.style.width = params.width;
			if (params.height)
				dialogContentNode.style.height = params.height;
			if (params.title)
				dialogTitleNode.innerHTML = params.title;
			if (params.content)
				this.dialogCotentWidget.setContent(params.content);
		}
		
		this.setParams(params);
		
		this.onLoad = function (func)
		{ this.dialogWidget.onLoad = func; }
		
		this.placeDialog = function ()
		{ this.dialogWidget.placeDialog(); }
		
		this.show = function () {
			if (!this.showing) {
				this.dialogWidget.show();
				this.dialogWidget.domNode.style.display = '';
				this.setCloseControl(dojo.byId('dialogclose'));
				this.showing = true;
			}
		}
		this.hide = function () {
			if (this.showing) {
				this.dialogWidget.domNode.style.display = 'none';
				this.dialogWidget.hide();
				this.dialogCotentWidget.destroy();
				this.dialogWidget.destroy();
				var underlays = dojo.html.getElementsByClass('dialogUnderlay');
				for (var x = 0; x < underlays.length; x++) {
					dojo.dom.removeNode(underlays[x]);
				}
				this.showing = false;
			}
		}
		this.setCloseControl = function(node) { dojo.event.connect(node, 'onclick', this, 'hide'); }
		this.setShowControl = function(node) { dojo.event.connect(node, 'onclick', this, 'show'); }
	};
}