/**
 * Template JS for standard pages
 */

(function($)
{
	/* block UI */
	if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
	alert('blockUI requires jQuery v1.2.3 or later!  You are using v' + $.fn.jquery);
	return;
	}
	
	$.fn._fadeIn = $.fn.fadeIn;
	
	var noOp = function() {};
	
	// this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle
	// retarded userAgent strings on Vista)
	var mode = document.documentMode || 0;
	var setExpr = $.browser.msie && (($.browser.version < 8 && !mode) || mode < 8);
	var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent) && !mode;
	
	// global $ methods for blocking/unblocking the entire page
	$.blockUI   = function(opts) { install(window, opts); };
	$.unblockUI = function(opts) { remove(window, opts); };
	
	// convenience method for quick growl-like notifications  (http://www.google.com/search?q=growl)
	$.growlUI = function(title, message, timeout, onClose) {
		var $m = $('<div class="growlUI"></div>');
		if (title) $m.append('<h1>'+title+'</h1>');
		if (message) $m.append('<h2>'+message+'</h2>');
		if (timeout == undefined) timeout = 3000;
		$.blockUI({
			message: $m, fadeIn: 700, fadeOut: 1000, centerY: false,
			timeout: timeout, showOverlay: false,
			onUnblock: onClose, 
			css: $.blockUI.defaults.growlCSS
		});
	};
	
	// plugin method for blocking element content
	$.fn.block = function(opts) {
		return this.unblock({ fadeOut: 0 }).each(function() {
			if ($.css(this,'position') == 'static')
				this.style.position = 'relative';
			if ($.browser.msie)
				this.style.zoom = 1; // force 'hasLayout'
			install(this, opts);
		});
	};
	
	// plugin method for unblocking element content
	$.fn.unblock = function(opts) {
		return this.each(function() {
			remove(this, opts);
		});
	};
	
	$.blockUI.version = 2.33; // 2nd generation blocking at no extra cost!
	
	// override these in your code to change the default behavior and style
	$.blockUI.defaults = {
		// message displayed when blocking (use null for no message)
		message:  '<h1>Please wait...</h1>',
	
		title: null,	  // title string; only used when theme == true
		draggable: true,  // only used when theme == true (requires jquery-ui.js to be loaded)
		
		theme: false, // set to true to use with jQuery UI themes
		
		// styles for the message when blocking; if you wish to disable
		// these and use an external stylesheet then do this in your code:
		// $.blockUI.defaults.css = {};
		css: {
			padding:	0,
			margin:		0,
			width:		'30%',
			top:		'40%',
			left:		'35%',
			textAlign:	'center',
			color:		'#000',
			border:		'3px solid #aaa',
			backgroundColor:'#fff',
			cursor:		'wait'
		},
		
		// minimal style set used when themes are used
		themedCSS: {
			width:	'30%',
			top:	'40%',
			left:	'35%'
		},
	
		// styles for the overlay
		overlayCSS:  {
			backgroundColor: '#000',
			opacity:	  	 0.6,
			cursor:		  	 'wait'
		},
	
		// styles applied when using $.growlUI
		growlCSS: {
			width:  	'350px',
			top:		'10px',
			left:   	'',
			right:  	'10px',
			border: 	'none',
			padding:	'5px',
			opacity:	0.6,
			cursor: 	'default',
			color:		'#fff',
			backgroundColor: '#000',
			'-webkit-border-radius': '10px',
			'-moz-border-radius':	 '10px',
			'border-radius': 		 '10px'
		},
		
		// IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w
		// (hat tip to Jorge H. N. de Vasconcelos)
		iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',
	
		// force usage of iframe in non-IE browsers (handy for blocking applets)
		forceIframe: false,
	
		// z-index for the blocking overlay
		baseZ: 1000,
	
		// set these to true to have the message automatically centered
		centerX: true, // <-- only effects element blocking (page block controlled via css above)
		centerY: true,
	
		// allow body element to be stetched in ie6; this makes blocking look better
		// on "short" pages.  disable if you wish to prevent changes to the body height
		allowBodyStretch: true,
	
		// enable if you want key and mouse events to be disabled for content that is blocked
		bindEvents: true,
	
		// be default blockUI will supress tab navigation from leaving blocking content
		// (if bindEvents is true)
		constrainTabKey: true,
	
		// fadeIn time in millis; set to 0 to disable fadeIn on block
		fadeIn:  200,
	
		// fadeOut time in millis; set to 0 to disable fadeOut on unblock
		fadeOut:  400,
	
		// time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
		timeout: 0,
	
		// disable if you don't want to show the overlay
		showOverlay: true,
	
		// if true, focus will be placed in the first available input field when
		// page blocking
		focusInput: true,
	
		// suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
		applyPlatformOpacityRules: true,
		
		// callback method invoked when fadeIn has completed and blocking message is visible
		onBlock: null,
	
		// callback method invoked when unblocking has completed; the callback is
		// passed the element that has been unblocked (which is the window object for page
		// blocks) and the options that were passed to the unblock call:
		//	 onUnblock(element, options)
		onUnblock: null,
	
		// don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
		quirksmodeOffsetHack: 4
	};
	
	// private data and functions follow...
	
	var pageBlock = null;
	var pageBlockEls = [];
	
	function install(el, opts) {
		var full = (el == window);
		var msg = opts && opts.message !== undefined ? opts.message : undefined;
		opts = $.extend({}, $.blockUI.defaults, opts || {});
		opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
		var css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
		var themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {});
		msg = msg === undefined ? opts.message : msg;
	
		// remove the current block (if there is one)
		if (full && pageBlock)
			remove(window, {fadeOut:0});
	
		// if an existing element is being used as the blocking content then we capture
		// its current place in the DOM (and current display style) so we can restore
		// it when we unblock
		if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
			var node = msg.jquery ? msg[0] : msg;
			var data = {};
			$(el).data('blockUI.history', data);
			data.el = node;
			data.parent = node.parentNode;
			data.display = node.style.display;
			data.position = node.style.position;
			if (data.parent)
				data.parent.removeChild(node);
		}
	
		var z = opts.baseZ;
	
		// blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
		// layer1 is the iframe layer which is used to supress bleed through of underlying content
		// layer2 is the overlay layer which has opacity and a wait cursor (by default)
		// layer3 is the message content that is displayed while blocking
	
		var lyr1 = ($.browser.msie || opts.forceIframe) 
			? $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>')
			: $('<div class="blockUI" style="display:none"></div>');
		var lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
		
		var lyr3, s;
		if (opts.theme && full) {
			s = '<div class="blockUI blockMsg blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+z+';display:none;position:fixed">' +
					'<div class="ui-widget-header ui-dialog-titlebar blockTitle">'+(opts.title || '&nbsp;')+'</div>' +
					'<div class="ui-widget-content ui-dialog-content"></div>' +
				'</div>';
		}
		else if (opts.theme) {
			s = '<div class="blockUI blockMsg blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+z+';display:none;position:absolute">' +
					'<div class="ui-widget-header ui-dialog-titlebar blockTitle">'+(opts.title || '&nbsp;')+'</div>' +
					'<div class="ui-widget-content ui-dialog-content"></div>' +
				'</div>';
		}
		else if (full) {
			s = '<div class="blockUI blockMsg blockPage" style="z-index:'+z+';display:none;position:fixed"></div>';
		}			
		else {
			s = '<div class="blockUI blockMsg blockElement" style="z-index:'+z+';display:none;position:absolute"></div>';
		}
		lyr3 = $(s);
	
		// if we have a message, style it
		if (msg) {
			if (opts.theme) {
				lyr3.css(themedCSS);
				lyr3.addClass('ui-widget-content');
			}
			else 
				lyr3.css(css);
		}
	
		// style the overlay
		if (!opts.applyPlatformOpacityRules || !($.browser.mozilla && /Linux/.test(navigator.platform)))
			lyr2.css(opts.overlayCSS);
		lyr2.css('position', full ? 'fixed' : 'absolute');
	
		// make iframe layer transparent in IE
		if ($.browser.msie || opts.forceIframe)
			lyr1.css('opacity',0.0);
	
		//$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
		var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
		$.each(layers, function() {
			this.appendTo($par);
		});
		
		if (opts.theme && opts.draggable && $.fn.draggable) {
			lyr3.draggable({
				handle: '.ui-dialog-titlebar',
				cancel: 'li'
			});
		}
	
		// ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
		var expr = setExpr && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
		if (ie6 || expr) {
			// give body 100% height
			if (full && opts.allowBodyStretch && $.boxModel)
				$('html,body').css('height','100%');
	
			// fix ie6 issue when blocked element has a border width
			if ((ie6 || !$.boxModel) && !full) {
				var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
				var fixT = t ? '(0 - '+t+')' : 0;
				var fixL = l ? '(0 - '+l+')' : 0;
			}
	
			// simulate fixed position
			$.each([lyr1,lyr2,lyr3], function(i,o) {
				var s = o[0].style;
				s.position = 'absolute';
				if (i < 2) {
					full ? s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"')
						 : s.setExpression('height','this.parentNode.offsetHeight + "px"');
					full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"')
						 : s.setExpression('width','this.parentNode.offsetWidth + "px"');
					if (fixL) s.setExpression('left', fixL);
					if (fixT) s.setExpression('top', fixT);
				}
				else if (opts.centerY) {
					if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
					s.marginTop = 0;
				}
				else if (!opts.centerY && full) {
					var top = (opts.css && opts.css.top) ? parseInt(opts.css.top) : 0;
					var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
					s.setExpression('top',expression);
				}
			});
		}
	
		// show the message
		if (msg) {
			if (opts.theme)
				lyr3.find('.ui-widget-content').append(msg);
			else
				lyr3.append(msg);
			if (msg.jquery || msg.nodeType)
				$(msg).show();
		}
	
		if (($.browser.msie || opts.forceIframe) && opts.showOverlay)
			lyr1.show(); // opacity is zero
		if (opts.fadeIn) {
			var cb = opts.onBlock ? opts.onBlock : noOp;
			var cb1 = (opts.showOverlay && !msg) ? cb : noOp;
			var cb2 = msg ? cb : noOp;
			if (opts.showOverlay)
				lyr2._fadeIn(opts.fadeIn, cb1);
			if (msg)
				lyr3._fadeIn(opts.fadeIn, cb2);
		}
		else {
			if (opts.showOverlay)
				lyr2.show();
			if (msg)
				lyr3.show();
			if (opts.onBlock)
				opts.onBlock();
		}
	
		// bind key and mouse events
		bind(1, el, opts);
	
		if (full) {
			pageBlock = lyr3[0];
			pageBlockEls = $(':input:enabled:visible',pageBlock);
			if (opts.focusInput)
				setTimeout(focus, 20);
		}
		else
			center(lyr3[0], opts.centerX, opts.centerY);
	
		if (opts.timeout) {
			// auto-unblock
			var to = setTimeout(function() {
				full ? $.unblockUI(opts) : $(el).unblock(opts);
			}, opts.timeout);
			$(el).data('blockUI.timeout', to);
		}
	};
	
	// remove the block
	function remove(el, opts) {
		var full = (el == window);
		var $el = $(el);
		var data = $el.data('blockUI.history');
		var to = $el.data('blockUI.timeout');
		if (to) {
			clearTimeout(to);
			$el.removeData('blockUI.timeout');
		}
		opts = $.extend({}, $.blockUI.defaults, opts || {});
		bind(0, el, opts); // unbind events
		
		var els;
		if (full) // crazy selector to handle odd field errors in ie6/7
			els = $('body').children().filter('.blockUI').add('body > .blockUI');
		else
			els = $('.blockUI', el);
	
		if (full)
			pageBlock = pageBlockEls = null;
	
		if (opts.fadeOut) {
			els.fadeOut(opts.fadeOut);
			setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut);
		}
		else
			reset(els, data, opts, el);
	};
	
	// move blocking element back into the DOM where it started
	function reset(els,data,opts,el) {
		els.each(function(i,o) {
			// remove via DOM calls so we don't lose event handlers
			if (this.parentNode)
				this.parentNode.removeChild(this);
		});
	
		if (data && data.el) {
			data.el.style.display = data.display;
			data.el.style.position = data.position;
			if (data.parent)
				data.parent.appendChild(data.el);
			$(el).removeData('blockUI.history');
		}
	
		if (typeof opts.onUnblock == 'function')
			opts.onUnblock(el,opts);
	};
	
	// bind/unbind the handler
	function bind(b, el, opts) {
		var full = el == window, $el = $(el);
	
		// don't bother unbinding if there is nothing to unbind
		if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
			return;
		if (!full)
			$el.data('blockUI.isBlocked', b);
	
		// don't bind events when overlay is not in use or if bindEvents is false
		if (!opts.bindEvents || (b && !opts.showOverlay)) 
			return;
	
		// bind anchors and inputs for mouse and key events
		var events = 'mousedown mouseup keydown keypress';
		b ? $(document).bind(events, opts, handler) : $(document).unbind(events, handler);
	
	// former impl...
	//	   var $e = $('a,:input');
	//	   b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
	};
	
	// event handler to suppress keyboard/mouse events when blocking
	function handler(e) {
		// allow tab navigation (conditionally)
		if (e.keyCode && e.keyCode == 9) {
			if (pageBlock && e.data.constrainTabKey) {
				var els = pageBlockEls;
				var fwd = !e.shiftKey && e.target == els[els.length-1];
				var back = e.shiftKey && e.target == els[0];
				if (fwd || back) {
					setTimeout(function(){focus(back)},10);
					return false;
				}
			}
		}
		// allow events within the message content
		if ($(e.target).parents('div.blockMsg').length > 0)
			return true;
	
		// allow events for content that is not being blocked
		return $(e.target).parents().children().filter('div.blockUI').length == 0;
	};
	
	function focus(back) {
		if (!pageBlockEls)
			return;
		var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
		if (e)
			e.focus();
	};
	
	function center(el, x, y) {
		var p = el.parentNode, s = el.style;
		var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
		var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
		if (x) s.left = l > 0 ? (l+'px') : '0';
		if (y) s.top  = t > 0 ? (t+'px') : '0';
	};
	
	function sz(el, p) {
		return parseInt($.css(el,p))||0;
	};

	
	/**
	 * List of functions required to enable template effects/hacks
	 * @var array
	 */
	var templateSetup = new Array();
	
	/**
	 * Add a new template function
	 * @param function func the function to be called on a jQuery object
	 * @param boolean prioritary set to true to call the function before all others (optional)
	 * @return void
	 */
	$.fn.addTemplateSetup = function(func, prioritary)
	{
		if (prioritary)
		{
			templateSetup.unshift(func);
		}
		else
		{
			templateSetup.push(func);
		}
	};
	
	/**
	 * Call every template function over a jQuery object (for instance : $('body').applyTemplateSetup())
	 * @return void
	 */
	$.fn.applyTemplateSetup = function()
	{
		var max = templateSetup.length;
		for (var i = 0; i < max; ++i)
		{
			templateSetup[i].apply(this);
		}
		
		return this;
	};
	
	// Common (mobile and standard) template setup
	$.fn.addTemplateSetup(function()
	{
		// Collapsible fieldsets
		this.find('fieldset.collapse, .fieldset.collapse').toggleFieldsetOpen().removeClass('collapse');
		
		// Equalize tab content-blocks heights
		this.find('.tabs.same-height, .side-tabs.same-height, .mini-tabs.same-height, .controls-tabs.same-height').equalizeTabContentHeight();
		
		// Update tabs
		this.find('.js-tabs').updateTabs();
		
		// Input switches
		this.find('input[type=radio].switch, input[type=checkbox].switch').hide().after('<span class="switch-replace"></span>').next().click(function() {
			$(this).prev().click();
		});
		this.find('input[type=radio].mini-switch, input[type=checkbox].mini-switch').hide().after('<span class="mini-switch-replace"></span>').next().click(function() {
			$(this).prev().click();
		});
	});
	
	// Document initial setup
	$(document).ready(function()
	{
		// Collapsible fieldsets
		$('fieldset legend > a, .fieldset .legend > a').live('click', function(event)
		{
			$(this).toggleFieldsetOpen();
			event.preventDefault();
		});
		
		// Template setup
		$(document.body).applyTemplateSetup();
		
		// Tabs links behaviour
		$('.js-tabs a[href^="#"]').live('click', function(event)
		{
			event.preventDefault();
			
			// If hashtag enabled
			if ($.fn.updateTabs.enabledHash)
			{
				// Retrieve hash parts
				var element = $(this);
				var hash = $.trim(window.location.hash || '');
				if (hash.length > 1)
				{
					// Remove hash from other tabs of the group
					var hashParts = hash.substring(1).split('&');
					var dummyIndex;
					while ((dummyIndex = $.inArray('', hashParts)) > -1)
					{
						hashParts.splice(dummyIndex, 1);
					}
					while ((dummyIndex = $.inArray('none', hashParts)) > -1)
					{
						hashParts.splice(dummyIndex, 1);
					}
					element.parent().parent().find('a[href^="#"]').each(function(i)
					{
						var index = $.inArray($(this).attr('href').substring(1), hashParts);
						if (index > -1)
						{
							hashParts.splice(index, 1);
						}
					});
				}
				else
				{
					var hashParts = [];
				}
				
				// Add current tab to hash (not if default)
				var defaultTab = getDefaultTabIndex(element.parent().parent());
				if (element.parent().index() != defaultTab)
				{
					hashParts.push(element.attr('href').substring(1));
				}
				
				// If only one tab, add a empty id to prevent document from jumping to selected content
				if (hashParts.length == 1)
				{
					hashParts.unshift('');
				}
				
				// Put hash, will trigger refresh
				window.location.hash = (hashParts.length > 0) ? '#'+hashParts.join('&') : '#none';
			}
			else
			{
				var li = $(this).closest('li');
				li.addClass('current').siblings().removeClass('current');
				li.parent().updateTabs();
			}
		});
		
		// Listener
		$(window).bind('hashchange', function()
		{
			$(document.body).find('.js-tabs').updateTabs();
		});
		
	});
	
	/**
	 * Get tab group default tab
	 */
	function getDefaultTabIndex(tabGroup)
	{
		var defaultTab = tabGroup.data('defaultTab');
		if (defaultTab === null || defaultTab === '')
		{
			var firstTab = tabGroup.children('.current:first');
			defaultTab = (firstTab.length > 0) ? firstTab.index() : 0;
			tabGroup.data('defaultTab', defaultTab);
		}
		
		return defaultTab;
	};
	
	/**
	 * Update tabs
	 */
	$.fn.updateTabs = function()
	{
		// If hashtags enabled
		if ($.fn.updateTabs.enabledHash)
		{
			var hash = $.trim(window.location.hash || '');
			var hashParts = (hash.length > 1) ? hash.substring(1).split('&') : [];
		}
		else
		{
			var hash = '';
			var hashParts = [];
		}
		
		// Check all tabs
		var hasHash = (hashParts.length > 0);
		this.each(function(i)
		{
			// Check if already inited
			var tabGroup = $(this);
			var defaultTab = getDefaultTabIndex(tabGroup);
			
			// Look for current tab
			var current = false;
			if ($.fn.updateTabs.enabledHash)
			{
				if (hasHash)
				{
					var links = tabGroup.find('a[href^="#"]');
					links.each(function(i)
					{
						var linkHash = $(this).attr('href').substring(1);
						if (linkHash.length > 0)
						{
							var index = $.inArray(linkHash, hashParts);
							if (index > -1)
							{
								current = $(this).parent();
								return false;
							}
						}
					});
				}
			}
			else
			{
				current = tabGroup.children('.current:first');
			}
			
			// If none found : get the default tab
			if (!current)
			{
				current = tabGroup.children(':eq('+defaultTab+')');
			}
			
			if (current.length > 0)
			{
				// Display current tab content block
				hash = $.trim(current.children('a').attr('href').substring(1));
				if (hash.length > 0)
				{
					// Hide others
					var tabContainer;
					current.siblings().removeClass('current').children('a').each(function(i)
					{
						var hash = $.trim($(this).attr('href').substring(1));
						if (hash.length > 0)
						{
							tabContainer = $('#'+hash);
							
							// Hide if visible
							if (tabContainer.is(':visible'))
							{
								tabContainer.trigger('tabhide').hide();
							}
							// Or init if first round
							else if (!tabContainer.data('tabInited'))
							{
								tabContainer.trigger('tabhide');
								tabContainer.data('tabInited', true);
							}
						}
					});
					
					// Highlight current
					current.addClass('current');
					tabContainer = $('#'+hash);
					
					// Show if hidden
					if (tabContainer.is(':hidden'))
					{
						tabContainer.show().trigger('tabshow');
					}
					// Or init if first round
					else if (!tabContainer.data('tabInited'))
					{
						tabContainer.trigger('tabshow');
						tabContainer.data('tabInited', true);
					}
				}
			}
		});
		
		return this;
	};
	
	/**
	 * Indicate whereas JS tabs hashtag is enabled
	 * @var boolean
	 */
	$.fn.updateTabs.enabledHash = true;
	
	/**
	 * Equalize tab content blocks heights
	 */
	$.fn.equalizeTabContentHeight = function()
	{
		var i;
		var g;
		var maxHeight;
		var tabContainers;
		var block;
		var blockHeight;
		var marginAdjustTop;
		var marginAdjustBot;
		var first;
		var last;
		var firstMargin;
		var lastMargin;
		
		// Process in reverse order to equalize sub-tabs first
		for (i = this.length-1; i >= 0; --i)
		{
			// Look for max height
			maxHeight = -1;
			tabContainers = [];
			this.eq(i).find('a[href^="#"]').each(function(i)
			{
				var hash = $.trim($(this).attr('href').substring(1));
				if (hash.length > 0)
				{
					block = $('#'+hash);
					if (block.length > 0)
					{
						blockHeight = block.outerHeight()+parseInt(block.css('margin-bottom'));
						
						// First element top-margin affects real height
						marginAdjustTop = 0;
						first = block.children(':first');
						if (first.length > 0)
						{
							firstMargin = parseInt(first.css('margin-top'));
							if (!isNaN(firstMargin) && firstMargin < 0)
							{
								marginAdjustTop = firstMargin;
							}
						}
						
						// Same for last element bottom-margin
						marginAdjustBot = 0;
						last = block.children(':last');
						if (last.length > 0)
						{
							lastMargin = parseInt(last.css('margin-bottom'));
							if (!isNaN(lastMargin) && lastMargin < 0)
							{
								marginAdjustBot = lastMargin;
							}
						}
						
						if (blockHeight+marginAdjustTop+marginAdjustBot > maxHeight)
						{
							maxHeight = blockHeight+marginAdjustTop+marginAdjustBot;
						}
						
						tabContainers.push([block, marginAdjustTop]);
					}
				}
			});
			
			// Setup height
			for (g = 0; g < tabContainers.length; ++g)
			{
				tabContainers[g][0].height(maxHeight-parseInt(tabContainers[g][0].css('padding-top'))-parseInt(tabContainers[g][0].css('padding-bottom'))-parseInt(tabContainers[g][0].css('margin-bottom'))-tabContainers[g][1]);
				
				// Only the first tab remains visible
				if (g > 0)
				{
					tabContainers[g][0].hide();
				}
			}
		}
		
		return this;
	};
	
	/**
	 * Display the selected tab (apply on tab content-blocks, not tabs, ie: $('#my-tab').showTab(); )
	 */
	$.fn.showTab = function()
	{
		this.each(function(i)
		{
			$('a[href="#'+this.id+'"]').trigger('click');
		});
		
		return this;
	};
	
	/**
	 * Add a listener fired when a tab is shown
	 * @param function callback any function to call when the listener is fired.
	 * @param boolean runOnce if true, the callback will be run one time only. Default: false - optional
	 */
	$.fn.onTabShow = function(callback, runOnce)
	{
		if (runOnce)
		{
			var runOnceFunc = function()
			{
				callback.apply(this, arguments);
				$(this).unbind('tabshow', runOnceFunc);
			}
			this.bind('tabshow', runOnceFunc);
		}
		else
		{
			this.bind('tabshow', callback);
		}
		
		return this;
	};
	
	/**
	 * Add a listener fired when a tab is hidden
	 * @param function callback any function to call when the listener is fired.
	 * @param boolean runOnce if true, the callback will be run one time only. Default: false - optional
	 */
	$.fn.onTabHide = function(callback, runOnce)
	{
		if (runOnce)
		{
			var runOnceFunc = function()
			{
				callback.apply(this, arguments);
				$(this).unbind('tabhide', runOnceFunc);
			}
			this.bind('tabhide', runOnceFunc);
		}
		else
		{
			this.bind('tabhide', callback);
		}
		
		return this;
	};
	
	/**
	 * Insert a message into a block
	 * @param string|array message a message, or an array of messages to inserted
	 * @param object options optional object with following values:
	 * 		- type: one of the available message classes : 'info' (default), 'warning', 'error', 'success', 'loading'
	 * 		- position: either 'top' (default) or 'bottom'
	 * 		- animate: true to show the message with an animation (default), else false
	 * 		- noMargin: true to apply the no-margin class to the message (default), else false
	 */
	$.fn.blockMessage = function(message, options)
	{
		var settings = $.extend({}, $.fn.blockMessage.defaults, options);
		
		this.each(function(i)
		{
			// Locate content block
			var block = $(this);
			if (!block.hasClass('block-content'))
			{
				block = block.find('.block-content:first');
				if (block.length == 0)
				{
					block = $(this).closest('.block-content');
					if (block.length == 0)
					{
						return;
					}
				}
			}
			
			// Compose message
			var messageClass = (settings.type == 'info') ? 'message' : 'message '+settings.type;
			if (settings.noMargin)
			{
				messageClass += ' no-margin';
			}
			var finalMessage = (typeof message == 'object') ? '<ul class="'+messageClass+'"><li>'+message.join('</li><li>')+'</li></ul>' : '<p class="'+messageClass+'">'+message+'</p>';
			
			// Insert message
			if (settings.position == 'top')
			{
				var children = block.find('h1, .h1, .block-controls, .block-header, .wizard-steps');
				if (children.length > 0)
				{
					var lastHeader = children.last();
					var next = lastHeader.next('.message');
					while (next.length > 0)
					{
						lastHeader = next;
						next = lastHeader.next('.message');
					}
					var messageElement = lastHeader.after(finalMessage).next();
				}
				else
				{
					var messageElement = block.prepend(finalMessage).children(':first');
				}
			}
			else
			{
				var children = block.find('.block-footer:last-child');
				if (children.length > 0)
				{
					var messageElement = children.before(finalMessage).prev();
				}
				else
				{
					var messageElement = block.append(finalMessage).children(':last');
				}
			}
			
			if (settings.animate)
			{
				messageElement.expand();
			}
		});
		
		return this;
	};
	
	// Default config for the blockMessage function
	$.fn.blockMessage.defaults = {
		type: 'info',
		position: 'top',
		animate: true,
		noMargin: true
	};
	
	/**
	 * Remove all messages from the block
	 * @param object options optional object with following values:
	 * 		- only: string or array of strings of message classes which will be removed
	 * 		- except: string or array of strings of message classes which will not be removed (ignored if 'only' is provided)
	 * 		- animate: true to remove the message with an animation (default), else false
	 */
	$.fn.removeBlockMessages = function(options)
	{
		var settings = $.extend({}, $.fn.removeBlockMessages.defaults, options);
		
		this.each(function(i)
		{
			// Locate content block
			var block = $(this);
			if (!block.hasClass('block-content'))
			{
				block = block.find('.block-content:first');
				if (block.length == 0)
				{
					block = $(this).closest('.block-content');
					if (block.length == 0)
					{
						return;
					}
				}
			}
			
			var messages = block.find('.message');
			if (settings.only)
			{
				if (typeof settings.only == 'string')
				{
					settings.only = [settings.only];
				}
				messages.filter('.'+settings.only.join(', .'));
			}
			else if (settings.except)
			{
				if (typeof settings.except == 'string')
				{
					settings.except = [settings.except];
				}
				messages.not('.'+settings.except.join(', .'));
			}
			
			if (settings.animate)
			{
				messages.foldAndRemove();
			}
			else
			{
				messages.remove();
			}
		});
		
		return this;
	};
	
	// Default config for the blockMessage function
	$.fn.removeBlockMessages.defaults = {
		only: false,				// string or array of strings of message classes which will be removed
		except: false,				// except: string or array of strings of message classes which will not be removed (ignored if only is provided)
		animate: true				// animate: true to remove the message with an animation (default), else false
	};
	
	/**
	 * Fold an element
	 * @param string|int duration a string (fast, normal or slow) or a number of millisecond. Default: 'normal'. - optional
	 * @param function callback any function to call at the end of the effect. Default: none. - optional
	 */
	$.fn.fold = function(duration, callback)
	{
		this.each(function(i)
		{
			var element = $(this);
			var marginTop = parseInt(element.css('margin-top'));
			var marginBottom = parseInt(element.css('margin-bottom'));
			
			var anim = {
				'height': 0,
				'paddingTop': 0,
				'paddingBottom': 0
			};
			
			// IE8 and lower do not understand border-xx-width
			// http://forum.jquery.com/topic/ie-invalid-argument
			if (!$.browser.msie || $.browser.version > 8)
			{
				// Border width is not set to 0 because it does not allow fluid movement 
				anim.borderTopWidth = '1px';
				anim.borderBottomWidth = '1px';
			}
			
			// Detection of elements sticking to their predecessor
			var prev = element.prev();
			if (prev.length === 0 && parseInt(element.css('margin-bottom'))+marginTop !== 0)
			{
				anim.marginTop = Math.min(0, marginTop);
				anim.marginBottom = Math.min(0, marginBottom);
			}
			
			// Effect
			element.stop(true).css({
				'overflow': 'hidden'
			}).animate(anim, {
				'duration': duration,
				'complete': function()
				{
					// Reset properties
					$(this).css({
						'display': 'none',
						'overflow': '',
						'height': '',
						'paddingTop': '',
						'paddingBottom': '',
						'borderTopWidth': '',
						'borderBottomWidth': '',
						'marginTop': '',
						'marginBottom': ''
					});
					
					// Callback function
					if (callback)
					{
						callback.apply(this);
					}
				}
			});
		});
		
		return this;
	};
	
	/*
	 * Expand an element
	 * @param string|int duration a string (fast, normal or slow) or a number of millisecond. Default: 'normal'. - optional
	 * @param function callback any function to call at the end of the effect. Default: none. - optional
	 */
	$.fn.expand = function(duration, callback)
	{
		this.each(function(i)
		{
			// Init
			var element = $(this);
			element.css('display', 'block');
			
			// Reset and get values
			element.stop(true).css({
				'overflow': '',
				'height': '',
				'paddingTop': '',
				'paddingBottom': '',
				'borderTopWidth': '',
				'borderBottomWidth': '',
				'marginTop': '',
				'marginBottom': ''
			});
			var height = element.height();
			var paddingTop = parseInt(element.css('padding-top'));
			var paddingBottom = parseInt(element.css('padding-bottom'));
			var marginTop = parseInt(element.css('margin-top'));
			var marginBottom = parseInt(element.css('margin-bottom'));
			
			// Initial and target values
			var css = {
				'overflow': 'hidden',
				'height': 0,
				'paddingTop': 0,
				'paddingBottom': 0
			};
			var anim = {
				'height': height,
				'paddingTop': paddingTop,
				'paddingBottom': paddingBottom
			};
			
			// IE8 and lower do not understand border-xx-width
			// http://forum.jquery.com/topic/ie-invalid-argument
			if (!$.browser.msie || $.browser.version > 8)
			{
				var borderTopWidth = parseInt(element.css('border-top-width'));
				var borderBottomWidth = parseInt(element.css('border-bottom-width'));
				
				// Border width is not set to 0 because it does not allow fluid movement 
				css.borderTopWidth = '1px';
				css.borderBottomWidth = '1px';
				anim.borderTopWidth = borderTopWidth;
				anim.borderBottomWidth = borderBottomWidth;
			}
			
			// Detection of elements sticking to their predecessor
			var prev = element.prev();
			if (prev.length === 0 && parseInt(element.css('margin-bottom'))+marginTop !== 0)
			{
				css.marginTop = Math.min(0, marginTop);
				css.marginBottom = Math.min(0, marginBottom);
				anim.marginTop = marginTop;
				anim.marginBottom = marginBottom;
			}
			
			// Effect
			element.stop(true).css(css).animate(anim, {
				'duration': duration,
				'complete': function()
				{
					// Reset properties
					$(this).css({
						'display': '',
						'overflow': '',
						'height': '',
						'paddingTop': '',
						'paddingBottom': '',
						'borderTopWidth': '',
						'borderBottomWidth': '',
						'marginTop': '',
						'marginBottom': ''
					});
					
					// Callback function
					if (callback)
					{
						callback.apply(this);
					}
					
					// Required for IE7 - don't ask me why...
					if ($.browser.msie && $.browser.version < 8)
					{
						$(this).css('zoom', 1);
					}
				}
			});
		});
		
		return this;
	};
	
	/**
	 * Remove an element with folding effect
	 * @param string|int duration a string (fast, normal or slow) or a number of millisecond. Default: 'normal'. - optional
	 * @param function callback any function to call at the end of the effect. Default: none. - optional
	 */
	$.fn.foldAndRemove = function(duration, callback)
	{
		$(this).fold(duration, function()
		{
			// Callback function
			if (callback)
			{
				callback.apply(this);
			}
			
			$(this).remove();
		});
		
		return this;
	}
	
	/**
	 * Remove an element with fading then folding effect
	 * @param string|int duration a string (fast, normal or slow) or a number of millisecond. Default: 'normal'. - optional
	 * @param function callback any function to call at the end of the effect. Default: none. - optional
	 */
	$.fn.fadeAndRemove = function(duration, callback)
	{
		this.animate({'opacity': 0}, {
			'duration': duration,
			'complete': function()
			{
				// No folding required if the element has position: absolute (not in the elements flow)
				if ($(this).css('position') == 'absolute')
				{
					// Callback function
					if (callback)
					{
						callback.apply(this);
					}
					
					$(this).remove();
				}
				else
				{
					$(this).slideUp(duration, function()
					{
						// Callback function
						if (callback)
						{
							callback.apply(this);
						}
						
						$(this).remove();
					});
				}
			}
		});
		
		return this;
	};
	
	/**
	 * Open/close fieldsets
	 */
	$.fn.toggleFieldsetOpen = function()
	{
		this.each(function()
		{
			/*
			 * Tip: if you want to add animation or do anything that should not occur at startup closing, 
			 * check if the element has the class 'collapse':
			 * if (!$(this).hasClass('collapse')) { // Anything that sould no occur at startup }
			 */
			
			// Change
			$(this).closest('fieldset, .fieldset').toggleClass('collapsed');
		});
		
		return this;
	};
	
	/**
	 * Add a semi-transparent layer in front of an element
	 */
	$.fn.addEffectLayer = function(options)
	{
		var settings = $.extend({}, $.fn.addEffectLayer.defaults, options);
		
		this.each(function(i)
		{
			var element = $(this);
			
			// Add layer
			var refElement = getNodeRefElement(this);
			var layer = $('<div class="loading-mask"><span>'+settings.message+'</span></div>').insertAfter(refElement);
			
			// Position
			var elementOffset = element.position();
			layer.css({
				top: elementOffset.top+'px',
				left: elementOffset.left+'px'
			}).width(element.outerWidth()).height(element.outerHeight());
			
			// Effect
			var span = layer.children('span');
			var marginTop = parseInt(span.css('margin-top'));
			span.css({'opacity':0, 'marginTop':(marginTop-40)+'px'});
			layer.css({'opacity':0}).animate({'opacity':1}, {
				'complete': function()
				{
					span.animate({'opacity': 1, 'marginTop': marginTop+'px'});
				}
			});
		});
		
		return this;
	};
	
	/**
	 * Retrieve the reference element after which the layer will be inserted
	 * @param HTMLelement node the node on which the effect is applied
	 * @return HTMLelement the reference node
	 */
	function getNodeRefElement(node)
	{
		var element = $(node);
		
		// Special case
		if (node.nodeName.toLowerCase() == 'document' || node.nodeName.toLowerCase() == 'body')
		{
			var refElement = $(document.body).children(':last').get(0);
		}
		else
		{
			// Look for the reference element, the one after which the layer will be inserted
			var refElement = node;
			var offsetParent = element.offsetParent().get(0);
			
			// List of elements in which we can add a div
			var absPos = ['absolute', 'relative'];
			while (refElement && refElement !== offsetParent && !$.inArray($(refElement.parentNode).css('position'), absPos))
			{
				refElement = refElement.parentNode;
			}
		}
		
		return refElement;
	}
	
	// Default params for the loading effect layer
	$.fn.addEffectLayer.defaults = {
		message: 'Please wait...'
	};
	
	/**
	 * jQuery load() method wrapper : add a visual effect on the load() target
	 * Parameters are the same as load()
	 */
	$.fn.loadWithEffect = function()
	{
		//Close page specific menu
		if($('#control-bar').css('display')!='none') { $('#control-bar').fold('slow'); }
		
		$.blockUI({ 
				css: { 
				border: 'none', 
				padding: '15px', 
				backgroundColor: '#000', 
				'-webkit-border-radius': '10px', 
				'-moz-border-radius': '10px', 
				opacity: .5, 
				color: '#fff' 
				} 
		}); 
		
		// Rewrite callback function
		var target = this;
		var callback = false;
		var args = $.makeArray(arguments);
		var index = args.length;
		if (args[2] && typeof args[2] == 'function')
		{
			callback = args[2];
			index = 2;
		}
		else if (args[1] && typeof args[1] == 'function')
		{
			callback = args[1];
			index = 1;
		}
		
		// Custom callback
		args[index] = function(responseText, textStatus, XMLHttpRequest)
		{
			
			// If success
			if (textStatus == 'success' || textStatus == 'notmodified')
			{
				// Initial callback
				if (callback)
				{
					callback.apply(this, arguments);
				}
				
				$.unblockUI();
				
			}
			else
			{
				$.unblockUI();
			}
		};
		
		// Redirect to jQuery load
		$.fn.load.apply(target, args);
		
		return this;
	};
	
	// Default texts for the loading effect layer
	$.fn.loadWithEffect.defaults = {
		message: 'Loading...',
		errorMessage: 'Error while loading',
		retry: 'Retry',
		cancel: 'Cancel'
	};
	
	/**
	 * Enable any button with workaround for IE lack of :disabled selector
	 */
	$.fn.enableBt = function()
	{
		$(this).attr('disabled', false);
		if ($.browser.msie && $.browser.version < 9)
		{
			$(this).removeClass('disabled');
		}
	}
	
	/**
	 * Disable any button with workaround for IE lack of :disabled selector
	 */
	$.fn.disableBt = function()
	{
		$(this).attr('disabled', true);
		if ($.browser.msie && $.browser.version < 9)
		{
			$(this).addClass('disabled');
		}
	}
	
})(jQuery);
