(function($) {
	
	$.usertoolbar = {};
	$.usertoolbar.defaults = {
		minimized : false,
		iconized : false,
		header_sel : '.usrtb-header',
		user_sel : '.usrtb-user',
		actions_sel : '.usrtb-actions',
		mode : 'fixed',
		actions : []
	};
	
	$.fn.usertoolbar = function (options) {
		function UserToolbar(el, opts) {
			el.css({visibility: 'hidden'});
			var usrtb = this;
			var header = el.find(opts.header_sel).eq(0);
			var username = el.find(opts.user_sel).eq(0);
			var actions = el.find(opts.actions_sel).eq(0);
			
			// For animation purposes
			el.wrapInner("<div class='usrtb-wrapper' />");
			var wrapper = el.find('.usrtb-wrapper').eq(0);
			
			var drag = $("<div class='usrtb-drag' />").prependTo(el);
			var minimizeBtn = $("<a href='#' class='usrtb-minimizer' />")
				.attr('title', gettext("Minimizes or maximizes the toolbar"))
				.prependTo(el);
			var iconizerBtn = $("<a href='#' class='usrtb-iconizer' />")
				.attr('title', gettext("Toggle between icons view"))
				.appendTo(el);
			var newActionItems = [];
			
			// Privates
			
			// Animations
			var preAnimMinHeight = 0;
			var preAnimMinWidth = 0;
			var animMinimizeSpeed = 150;
			
			function animMinimize(speed) {
				iconizerBtn.stop(true, true);
				iconizerBtn.css('display', 'block');
				iconizerBtn.css('opacity', 1);
				iconizerBtn.animate({
						opacity: 0
					}, speed || animMinimizeSpeed, function () {
					iconizerBtn.css({
						opacity: '',
						display: ''
					});
				});
				
				wrapper.stop(true, true);
				preAnimMinWidth = wrapper.width();
				preAnimMinHeight = wrapper.height();
				wrapper.width(preAnimMinWidth);
				wrapper.height(preAnimMinHeight);
				wrapper.animate({
						height: '1px'
					}, speed || animMinimizeSpeed, function () {
					wrapper.width('');
					wrapper.height('');
					wrapper.css('display', '');
				});
			}
			function animRestore(speed) {
				iconizerBtn.stop(true, true);
				iconizerBtn.css('display', 'block');
				iconizerBtn.css('opacity', 0);
				iconizerBtn.animate({
						opacity: 1
					}, speed || animMinimizeSpeed, function () {
					iconizerBtn.css({
						opacity: '',
						display: ''
					});
				});
				
				wrapper.stop(true, true);
				wrapper.animate({
						height: preAnimMinHeight,
						width: preAnimMinWidth
					}, speed || animMinimizeSpeed, function () {
					wrapper.width('');
					wrapper.height('');
				});
			}
			
			var preAnimIconizeHeight = 0;
			var preAnimIconizeWidth = 0;
			var preAnimHeaderHeight = 0;
			var preAnimUsernameHeight = 0;
			var animIconizeSpeed = 150;
			
			function animIconize(speed) {
				preAnimHeaderHeight = header.height();
				preAnimUsernameHeight = username.height();
				
				header.css('display', 'block');
				username.css('display', 'block');
				header.slideUp(speed || animIconizeSpeed);
				username.slideUp(speed || animIconizeSpeed);
				
				wrapper.stop(true, true);
				preAnimIconizeWidth = wrapper.width();
				preAnimIconizeHeight = wrapper.height();
				wrapper.width(preAnimIconizeWidth);
				wrapper.animate({
						width: 24
					}, speed || animIconizeSpeed, function () {
					wrapper.css({width: '', height: ''});

					header.css({
						display: '',
						height: ''
					});
					username.css({
						display: '',
						height: ''
					});
				});
			}
			
			function animIconizeRest(speed) {
				header.css({
					display: 'block',
					height: 0,
					width: 1
				});
				username.css({
					display: 'block',
					height: 0,
					width: 1
				});
				header.animate({
					height: preAnimHeaderHeight,
					width: preAnimIconizeWidth
				}, speed || animIconizeSpeed);
				username.animate({
					height: preAnimUsernameHeight,
					width: preAnimIconizeWidth
				}, speed || animIconizeSpeed);

				wrapper.stop(true, true);
				el.width('auto');
				wrapper.width(wrapper.width());
				wrapper.height(wrapper.height());
				wrapper.css('overflow', 'hidden');
				wrapper.animate({
						width: preAnimIconizeWidth,
						height: preAnimIconizeHeight
					}, speed || animIconizeSpeed, function () {
					el.width('');
					wrapper.width('');
					wrapper.height('');
					wrapper.css('overflow', '');

					header.css({
						display: '',
						height: '',
						width: ''
					});
					username.css({
						display: '',
						height: '',
						width: ''
					});
				});
			}
			
			// Setters / getters
			
			function getMinimizeState() {
				return el.hasClass('usrtb-min');
			} 
			
			function setMinimizeState(setValue, speed) {
				usrtb.isMinimized = setValue;
				
				if (setValue) {
					animMinimize(speed);
					el.addClass('usrtb-min');
					return;
				}
				
				animRestore(speed);
				el.removeClass('usrtb-min');
			}
			
			function getIconizedState() {
				return el.hasClass('usrtb-icons');
			} 
			
			function setIconizedState(setValue, speed) {
				usrtb.isIconized = setValue;
				
				if (setValue) {
					animIconize(speed);
					el.addClass('usrtb-icons');	
					return;
				}
				
				animIconizeRest(speed);
				el.removeClass('usrtb-icons');	
			}
			
			function addAction(action) {
				var item = $("<li></li>");
				
				// Separator
				if (action == '-') {
					item.addClass('usract-sep');
					item.appendTo(actions);
					newActionItems.push(item);
					return item;
				}
				
				var btn = $("<a />").appendTo(item);
				
				// Normal action
				item.addClass("usract-" + action.classes)
					.addClass('usract');
				btn.attr('id', action.id || '');
				btn.attr('href', action.url || '#');
				btn.attr('title', action.title || '');
				btn.text(action.text);
				item.appendTo(actions);
				newActionItems.push(item);
				
				if (action.click)
					btn.click(function () {
						return action.click.call(action, item);
					});
				
				if (action.init)
					action.init.call(action, item);
					
				return item;
			}
			
			function getAnchored() {
				var anchored = [];
				
				// Get from classes
				if (el.hasClass('usrtb-right'))
					anchored.push('right');
				
				if (el.hasClass('usrtb-left'))
					anchored.push('left');

				if (el.hasClass('usrtb-top'))
					anchored.push('top');

				if (el.hasClass('usrtb-bottom'))
					anchored.push('bottom');
				
				// Defaults to top right
				if (!el.hasClass('usrtb-bottom usrtb-top'))
					anchored.push('top')
					
				if (!el.hasClass('usrtb-left usrtb-right'))
					anchored.push('right');
				
				return anchored.join(" ");
			}
			
			function anchorRelease() {
				// Set the position by top right
				var tl = el.offset();
				
				// Clear
				el.css($.extend({
					top: 'auto',
					left: 'auto',
					right: 'auto',
					bottom: 'auto'
				}, tl));
			}
			
			function convertTopLeft(x, y, anchor) {
				var w = $(window).width();
				var h = $(window).height();
				var pos = {top: y, left: x};
				
				if ($.inArray('bottom', anchor) != -1) {
					var elh = el.outerHeight();
					pos.bottom = h - y - elh;
					pos.top = 'auto';
				}
				
				if ($.inArray('right', anchor) != -1) {
					var elw = el.outerWidth();
					pos.right = w - x - elw;
					pos.left = 'auto';
				}
				
				return pos;
			}
			
			function setAnchorFromPos(x, y) {
				var w = $(window).width();
				var h = $(window).height();
				switch(opts.mode) {
					case 'fixed':
						var anchor = [];
						
						if (x >= w / 2)
							anchor.push('right')
						else
							anchor.push('left');
						
						if (y >= h / 2)
							anchor.push('bottom')
						else
							anchor.push('top');
						
						el.css(convertTopLeft(x, y, anchor));
							
						setAnchor(anchor.join(" "));
						break;
					default:
						throw 'Mode can be fixed only';
				}
			}
			
			function setAnchor(anchor) {
				if (anchor)
					usrtb.anchored = anchor;
					
				el.removeClass('usrtb-bottom usrtb-top usrtb-left usrtb-right');
				
				$.each(usrtb.anchored.split(" "), function () {
					el.addClass('usrtb-' + this);
				});
			}
			
			// Publics
			
			this.anchored = getAnchored();
			this.isMinimized = getMinimizeState();
			this.isIconized = getIconizedState();
				
			this.getConf = function() {
				return opts;
			};
				
			this.minimize = function(setValue, speed) {
				// minimize() means minimize, so true.
				if (typeof setValue == "undefined")
					setValue = true;
				
				setMinimizeState(setValue, speed);
			};
			
			this.iconize = function(setValue, speed) {
				// iconize() means iconize, so true.
				if (typeof setValue == "undefined")
					setValue = true;
				
				setIconizedState(setValue, speed);
			};
			
			// UI hooks
			
			var minimizeBtnClick = function () {
				usrtb.minimize(!usrtb.isMinimized);
				return false;
			};
			
			var iconizerBtnClick = function() {
				usrtb.iconize(!usrtb.isIconized);
				return false;
			};
			
			minimizeBtn.click(minimizeBtnClick);
			iconizerBtn.click(iconizerBtnClick);
			
			// Add dynamic actions
			if (opts.actions) {
				$.each(opts.actions, function(){
					addAction(this);
				});
			}
			
			// Extremely naive draggability
			var dragOffset = {top : 0, left: 0};
			var dragMouseMoveFn = function (e) {
				el.offset({
					top: e.pageY + dragOffset.top,
					left: e.pageX + dragOffset.left
				});
				return true;
			};
			
			drag.mousedown(function (e) {
				anchorRelease();
				var elo = el.offset();
				dragOffset = {
					top: elo.top - e.pageY,
					left: elo.left - e.pageX
				};
				el.get(0).onselectstart = function () { return false; };
				el.get(0).style.MozUserSelect = 'none';
				$(document).unbind('mousemove', dragMouseMoveFn);
				$(document).mousemove(dragMouseMoveFn);
				$(document).one('mouseup',function (e) {
					$(document).unbind('mousemove', dragMouseMoveFn);
					el.get(0).onselectstart = null;
					el.get(0).style.MozUserSelect = null;
					setAnchorFromPos(e.pageX + dragOffset.left, e.pageY + dragOffset.top);
					return false;
				});
				
				return false;
			});
			
			// Destructor
			var destroy = function () {
				// Remove handlers
				minimizeBtn.unbind('click', minimizeBtnClick);
				iconizerBtn.unbind('click', iconizerBtnClick);
				
				// Remove dynamically created actions
				$.each(newActionItems, function () {
					$(this).remove();
				});
			}
			
			// Defaults
			if (opts.minimized) {
				this.minimize(opts.minimized, -1);
			}
			
			if (opts.iconized) {
				this.iconize(opts.iconized, -1);
			}
			el.css({visibility: 'visible'});
		}
		
		return this.each(function (i) {
			var api = $(this).data("usertoolbar");
			
			if (!api) {
				var opts = $.extend(true, {}, $.usertoolbar.defaults, options);
				api = $(this).data('usertoolbar', new UserToolbar($(this), opts));
			} else {
				if (options) {
					// Modify existing options
					$.extend($(this).data("usertoolbar").getConf(), options);
				}
				return; // Already created, do nothing.
			}
		});
	};

})(jQuery);

jQuery(function () {
	var $ = jQuery;
	
	$.usertoolbar.defaults.actions.push('-');
	
	$.usertoolbar.defaults.actions.push({
		text : gettext('Browser FX'),
		title : gettext("Toggle the browser effects"),
		classes : 'jqfx',
		click : function (item) {
			$.fx.off = !$.fx.off;
			item.toggleClass('no-fx', $.fx.off);
			return false;
		},
		init : function (item) {
			item.toggleClass('no-fx', !!$.fx.off);
		}
	});
	
	$.usertoolbar.defaults.actions.push({
		text : gettext('Admin buttons'),
		title : gettext("Toggle the admin button visibility"),
		classes : 'adminbox',
		adminboxes : true,
		click : function (item) {
			this.adminboxes = !this.adminboxes;
			if (!this.adminboxes) {
				$(".adminbox").hide();
			} else {
				$(".adminbox").show();
			}
			item.toggleClass('no-adb', !this.adminboxes);
			return false;
		},
		init : function (item) {
			item.toggleClass('no-adb', !this.adminboxes);
		}
	});
	
	$("#logoutbtn").overlayDialog({
        width: 300,
        height: 80,
        success_pathnames: ['/logout'],
        successHandlers: '',
        onSuccess: function () {
            // Wait a sec and reload a page
            setTimeout(function () {
                window.location.reload();
            }, 1000);
        }
    });
	$("#usersbtn").overlayDialog({ height: 500 });
	$("#profilebtn").overlayDialog({
        height: 500
    });
	$("#usertoolbar").usertoolbar();
});

