
//jquery-plugins
/*!
 * jQuery blockUI plugin
 * Version 2.26 (09-SEP-2009)
 * @requires jQuery v1.2.3 or later
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007-2008 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to Amir-Hossein Sobhi for some excellent contributions!
 */

;(function($) {

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;

// 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.26; // 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:		'20%',
		left:		'35%',
		textAlign:	'center',
		color:		'#000',
		border:		'3px solid #aaa',
		backgroundColor:'#fff',
		cursor:		'wait',
		'min-width' : '550px'
	},
	
	// 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'
	},
	
	// 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 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;
	if (opts.theme && full) {
		var 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>';
		lyr3 = $(s);
	}
	else {
		lyr3 = full ? $('<div class="blockUI blockMsg blockPage" style="z-index:'+z+';display:none;position:fixed"></div>')
					: $('<div class="blockUI blockMsg blockElement" style="z-index:'+z+';display:none;position:absolute"></div>');
	}						   

	// 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);
	
	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) {
		if (opts.showOverlay)
			lyr2._fadeIn(opts.fadeIn);
		if (msg)
			lyr3.fadeIn(opts.fadeIn);
	}
	else {
		if (opts.showOverlay)
			lyr2.show();
		if (msg)
			lyr3.show();
	}

	// 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);
		$(data.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;
};

})(jQuery);
/**
* maxChar jQuery plugin
* @author Mitch Wilson
* @version 0.3.0
* @requires jQuery 1.3.2 (only version tested)
* @see http://mitchwilson.net/2009/08/03/new-jquery-plugin-maxchar/
* @param {Boolean}	debug				Specify whether to send message updates to the Firebug console. Default is false.
* @param {String}	indicator 			Specify alternate indicator element by id. Default is indicator created dynamically.
* @param {String}	label				Specify a default label displayed when input element is not in focus. Default is blank.
* @param {String}	pluralMessage 		Set the plural form of the remaining count message. Default is ' remaining'.
* @param {Number}	rate 				Set the update rate in milliseconds. Default is 200.
* @param {String}	singularMessage 	Set the singular form of the remaining count message. Default is ' remaining'.
* @param {String}	spaceBeforeMessage 	Set spacing in front of (to the left of) the indicator message. Default is ' '.
* @param {Boolean}	truncate			Truncate submitted value down to limit on form submit. Default is true.
* @description Enforces max character limit on any input or textarea HTML element and provides user feedback and many options. 
* New features added in 0.3.0 are: 
* 1) Feature change: Displays negative characters when past limit rather than truncating characters in form input.
* 2) New option: truncate - If true, on form submit truncates submitted value down specified by limit. Does not change (respects) user text in form field. Default is true.
* 3) Bug fixes: Fixed serveral issues related to removing over-the-limit characters in the form field.
*/

(function($){
	$.fn.maxChar = function(limit, options) {
		
		// Define default settings and override w/ options.	
		settings = jQuery.extend({
			debug: false,
			indicator: 'indicator',
			label: '',
			pluralMessage:' remaining',
			rate: 200,
			singularMessage: ' remaining',
			spaceBeforeMessage: ' ',
			truncate: true
		}, options);
		
		// Get maxChar target element.
		var target = $(this); // Must get target first, since it is used in setting other local variables.
		
		// Get settings.
		var debug = settings.debug;
		var indicatorId = settings.indicator;
		var label = settings.label;
		var pluralMessage = settings.pluralMessage;
		var rate = settings.rate;
		var singularMessage = settings.singularMessage;
		var spaceBeforeMessage = settings.spaceBeforeMessage;
		var truncate = settings.truncate;
		
		// Set additional local variables.
		var currentMessage = ''; // Current message to display to the user.
		var indicator = getIndicator(indicatorId); // Element to display count, messages and label.
		var limit = limit; // Character limit.
		var remaining = limit; // Characters remaining.
		var timer = null; // Timer to run update.
		
		// Initialize on page ready.
		if(label) {
			indicator.text(label);
		} else {
			// Call update once on code initialization to update view if text is already in textarea,
			// eg, if user relaoads page or hits back button and form textarea retains previoulsy entered text.
			update(limit);
		}
		
		// When user focuses on the target element, do the following.
		$(this).focus(function(){
			if(timer == null) {
				if(label) {
					indicator.fadeOut(function(){indicator.text('')}).fadeIn(function(){start()});					
				} else {
					start();
				}
			}
		});
		
		// When user removes focus from the target element, do the following.
		$(this).blur(function() {
			// Stop timer that updates count and the indicator message.
			stop();
			// Update view.
			if(label) {
				indicator.fadeOut(function(){indicator.text(label)}).fadeIn();
			}
		});
		
		function getIndicator(id){
			// Get indicator element in the dom.
			var indicator = $('#'+id);
			// If indicator element does not already exist in the dom, create it.
			if(indicator.length == 0) {
				target.after(spaceBeforeMessage + '<span id="'+id+'"></span>');
				indicator = $('#'+id)
			}
			// Return reference to indicator element.
			return indicator;
		}

		// Create helper functions.
		function log(message) {
			// Display 
			if(debug) {
				try {
					if(console) {
						console.log(message);
					}
				} catch(e) {
					// Do nothing on error.
				}
			}
		}
		
		// Start the timer that updates indicator.
		function start() {
			timer = setInterval(function(){update(limit)}, rate);
		}
		
		// Stop the timer that updates the indicator.
		function stop() {
			if(timer != null) {
				clearInterval(timer);
				timer = null;
			}
		}
		
		// Truncate submitted value down to limit on form submit.
		if(truncate) {
			var form_id = '#' + $(this).closest("form").attr("id");
			$(form_id).submit(function(){
				target.val(target.val().slice(0,limit));
			});
		}
		
		// Update the indicator.
		function update(limit){
			var remaining = limit - target.val().length;
			// Update remaining count and message.
			if(remaining == 1) {
				currentMessage = remaining + singularMessage;
			} else {
				currentMessage = remaining + pluralMessage;
			}
			// Update indicator.
			indicator.text(currentMessage);
			log(currentMessage);
		}
	};
})(jQuery);
/*
$.fn.extend({
    insertAtCaret: function(myValue){
    		if (document.selection) {
        this.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
        this.focus();
    		}
      else if (this.selectionStart || this.selectionStart == '0') {
        var startPos = this.selectionStart;
        var endPos = this.selectionEnd;
        var scrollTop = this.scrollTop;
        this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
        this.focus();
        this.selectionStart = startPos + myValue.length;
        this.selectionEnd = startPos + myValue.length;
        this.scrollTop = scrollTop;
      } else {
        this.value += myValue;
        this.focus();
      }
    }
})
*/

/*! 
 * a-tools 1.4.1
 * 
 * Copyright (c) 2009 Andrey Kramarev(andrey.kramarev[at]ampparit.com), Ampparit Inc. (www.ampparit.com)
 * Licensed under the MIT license.
 * http://www.ampparit.com/projects/a-tools/license.txt
 *
 * Basic usage:
 
    <textarea></textarea>
    <input type="text" />

    // Get current selection
    var sel = $("textarea").getSelection()
    
    // Replace current selection
    $("input").replaceSelection("foo");

    // Count characters
    alert($("textarea").countCharacters());

    // Set max length without callback function
    $("textarea").setMaxLength(7);

    // Set max length with callback function which will be called when limit is exceeded
    $("textarea").setMaxLength(10, function() {
        alert("hello")
    });

    // Removing limit:
    $("textarea").setMaxLength(-1);
    
    // Insert text at current caret position
    $("#textarea").insertAtCaretPos("hello");
    
    // Set caret position (1 = beginning, -1 = end)
    $("#textArea").setCaretPos(10);
    
    // Set Selection (1 = beginning)
    $("#textArea").setSelection(10,15);

 */
var caretPositionAmp; jQuery.fn.extend({getSelection:function(){var b=this.jquery?this[0]:this,a,c,f,h=0;b.onmousedown=function(){document.selection&&typeof b.selectionStart!="number"?document.selection.empty():window.getSelection().removeAllRanges()};if(document.selection){var d=document.selection.createRange(),e=0,i=0,g=0;if(b.value.match(/\n/g)!=null)h=b.value.match(/\n/g).length;if(d.text){f=d.text;if(typeof b.selectionStart=="number"){a=b.selectionStart;c=b.selectionEnd;if(a==c)return{start:a,end:c,text:d.text,length:c- a}}else{var j;a=b.createTextRange();c=a.duplicate();f=a.text;a.moveToBookmark(d.getBookmark());j=a.text;c.setEndPoint("EndToStart",a);if(f==j&&f!=d.text)return this;a=c.text.length;c=c.text.length+d.text.length}if(h>0)for(f=0;f<=h;f++){j=b.value.indexOf("\n",i);if(j!=-1&&j<a){i=j+1;e++;g=e}else if(j!=-1&&j>=a&&j<=c)if(j==a+1){e--;g--;i=j+1}else{i=j+1;g++}else f=h}if(d.text.indexOf("\n",0)==1)g+=2;a-=e;c-=g;return{start:a,end:c,text:d.text,length:c-a}}b.focus();if(typeof b.selectionStart=="number")a= b.selectionStart;else{d=document.selection.createRange();a=b.createTextRange();c=a.duplicate();a.moveToBookmark(d.getBookmark());c.setEndPoint("EndToStart",a);a=c.text.length}if(h>0)for(f=0;f<=h;f++){j=b.value.indexOf("\n",i);if(j!=-1&&j<a){i=j+1;e++}else f=h}a-=e;return{start:a,end:a,text:d.text,length:0}}else if(typeof b.selectionStart=="number"){a=b.selectionStart;c=b.selectionEnd;f=b.value.substring(b.selectionStart,b.selectionEnd);return{start:a,end:c,text:f,length:c-a}}else return{start:undefined, end:undefined,text:undefined,length:undefined}},replaceSelection:function(b){var a=this.jquery?this[0]:this,c,f;f=0;var h,d,e=0,i=0,g=a.scrollTop==undefined?0:a.scrollTop;if(document.selection&&typeof a.selectionStart!="number"){g=document.selection.createRange();if(typeof a.selectionStart!="number"){var j;d=a.createTextRange();h=d.duplicate();c=d.text;d.moveToBookmark(g.getBookmark());j=d.text;h.setEndPoint("EndToStart",d);if(c==j&&c!=g.text)return this}if(g.text){part=g.text;if(a.value.match(/\n/g)!= null)e=a.value.match(/\n/g).length;c=h.text.length;if(e>0)for(j=0;j<=e;j++){var k=a.value.indexOf("\n",f);if(k!=-1&&k<c){f=k+1;i++}else j=e}g.text=b;caretPositionAmp=h.text.length+b.length;d.move("character",caretPositionAmp);document.selection.empty();a.blur()}return this}else if(typeof a.selectionStart=="number"&&a.selectionStart!=a.selectionEnd){c=a.selectionStart;f=a.selectionEnd;a.value=a.value.substr(0,c)+b+a.value.substr(f);f=c+b.length;a.setSelectionRange(f,f);a.scrollTop=g;return this}return this}, setSelection:function(b,a){b=parseInt(b);a=parseInt(a);var c=this.jquery?this[0]:this;c.focus();if(typeof c.selectionStart!="number"){re=c.createTextRange();if(re.text.length<a)a=re.text.length+1}if(a<b)return this;if(document.selection){var f=0,h=0,d=0,e=0;if(typeof c.selectionStart!="number"){re.collapse(true);re.moveEnd("character",a);re.moveStart("character",b);re.select()}else if(typeof c.selectionStart=="number"){if(c.value.match(/\n/g)!=null)f=c.value.match(/\n/g).length;if(f>0)for(var i=0;i<= f;i++){var g=c.value.indexOf("\n",d);if(g!=-1&&g<b){d=g+1;h++;e=h}else if(g!=-1&&g>=b&&g<=a)if(g==b+1){h--;e--;d=g+1}else{d=g+1;e++}else i=f}b+=h;a+=e;c.selectionStart=b;c.selectionEnd=a}return this}else if(c.selectionStart){c.focus();c.selectionStart=b;c.selectionEnd=a;return this}},insertAtCaretPos:function(b){var a=this.jquery?this[0]:this,c,f,h,d,e,i,g=f=0,j=a.scrollTop==undefined?0:a.scrollTop;a.focus();if(document.selection&&typeof a.selectionStart!="number"){if(a.value.match(/\n/g)!=null)g= a.value.match(/\n/g).length;c=parseInt(caretPositionAmp);if(g>0)for(var k=0;k<=g;k++){var l=a.value.indexOf("\n",h);if(l!=-1&&l<=c){h=l+1;c-=1;f++}}}caretPositionAmp=parseInt(caretPositionAmp);a.onmouseup=function(){if(document.selection&&typeof a.selectionStart!="number"){a.focus();d=document.selection.createRange();e=a.createTextRange();i=e.duplicate();e.moveToBookmark(d.getBookmark());i.setEndPoint("EndToStart",e);caretPositionAmp=i.text.length}};if(document.selection&&typeof a.selectionStart!= "number"){d=document.selection.createRange();if(d.text.length!=0)return this;e=a.createTextRange();textLength=e.text.length;i=e.duplicate();e.moveToBookmark(d.getBookmark());i.setEndPoint("EndToStart",e);c=i.text.length;if(caretPositionAmp>0&&c==0){f=caretPositionAmp-f;e.move("character",f);e.select();d=document.selection.createRange();caretPositionAmp+=b.length}else if(!(caretPositionAmp>=0)&&textLength==0){d=document.selection.createRange();caretPositionAmp=b.length+textLength}else if(!(caretPositionAmp>= 0)&&c==0){e.move("character",textLength);e.select();d=document.selection.createRange();caretPositionAmp=b.length+textLength}else if(!(caretPositionAmp>=0)&&c>0){e.move("character",0);document.selection.empty();e.select();d=document.selection.createRange();caretPositionAmp=c+b.length}else if(caretPositionAmp>=0&&caretPositionAmp==textLength){if(textLength!=0){e.move("character",textLength);e.select()}else e.move("character",0);d=document.selection.createRange();caretPositionAmp=b.length+textLength}else{if(caretPositionAmp>= 0&&c!=0&&caretPositionAmp>=c){f=caretPositionAmp-c;e.move("character",f)}else caretPositionAmp>=0&&c!=0&&caretPositionAmp<c&&e.move("character",0);document.selection.empty();e.select();d=document.selection.createRange();caretPositionAmp+=b.length}d.text=b;a.focus();return this}else if(typeof a.selectionStart=="number"&&a.selectionStart==a.selectionEnd){h=a.selectionStart+b.length;c=a.selectionStart;f=a.selectionEnd;a.value=a.value.substr(0,c)+b+a.value.substr(f);a.setSelectionRange(h,h);a.scrollTop= j;return this}return this},setCaretPos:function(b){var a=this.jquery?this[0]:this,c,f=0,h=0,d;a.focus();if(parseInt(b)==0)return this;if(parseInt(b)>0){b=parseInt(b)-1;if(document.selection&&typeof a.selectionStart=="number"&&a.selectionStart==a.selectionEnd){if(a.value.match(/\n/g)!=null)f=a.value.match(/\n/g).length;if(f>0)for(var e=0;e<=f;e++){d=a.value.indexOf("\n",c);if(d!=-1&&d<=b){c=d+1;b=parseInt(b)+1}}}}else if(parseInt(b)<0){b=parseInt(b)+1;if(document.selection&&typeof a.selectionStart!= "number"){b=a.value.length+parseInt(b);if(a.value.match(/\n/g)!=null)f=a.value.match(/\n/g).length;if(f>0){for(e=0;e<=f;e++){d=a.value.indexOf("\n",c);if(d!=-1&&d<=b){c=d+1;b=parseInt(b)-1;h+=1}}b=b+h-f}}else if(document.selection&&typeof a.selectionStart=="number"){b=a.value.length+parseInt(b);if(a.value.match(/\n/g)!=null)f=a.value.match(/\n/g).length;if(f>0){b=parseInt(b)-f;for(e=0;e<=f;e++){d=a.value.indexOf("\n",c);if(d!=-1&&d<=b){c=d+1;b=parseInt(b)+1;h+=1}}}}else b=a.value.length+parseInt(b)}else return this; if(document.selection&&typeof a.selectionStart!="number"){c=document.selection.createRange();if(c.text!=0)return this;a=a.createTextRange();a.collapse(true);a.moveEnd("character",b);a.moveStart("character",b);a.select();caretPositionAmp=b;return this}else if(typeof a.selectionStart=="number"&&a.selectionStart==a.selectionEnd){a.setSelectionRange(b,b);return this}return this},countCharacters:function(){var b=this.jquery?this[0]:this;if(b.value.match(/\r/g)!=null)return b.value.length-b.value.match(/\r/g).length; return b.value.length},setMaxLength:function(b,a){this.each(function(){var c=this.jquery?this[0]:this,f=c.type,h,d;if(parseInt(b)<0)b=1E8;if(f=="text")c.maxLength=b;if(f=="textarea"||f=="text"){c.onkeypress=function(e){var i=c.value.match(/\r/g);d=b;if(i!=null)d=parseInt(d)+i.length;e=e||event;i=e.keyCode;h=document.selection?document.selection.createRange().text.length>0:c.selectionStart!=c.selectionEnd;if(c.value.length>=d&&(i>47||i==32||i==0||i==13)&&!e.ctrlKey&&!e.altKey&&!h){c.value=c.value.substring(0, d);typeof a=="function"&&a();return false}};c.onkeyup=function(){var e=c.value.match(/\r/g),i=0,g=0;d=b;if(e!=null){for(var j=0;j<=e.length;j++)if(c.value.indexOf("\n",g)<=parseInt(b)){i++;g=c.value.indexOf("\n",g)+1}d=parseInt(b)+i}if(c.value.length>d){c.value=c.value.substring(0,d);typeof a=="function"&&a();return this}}}else return this});return this}});

/*
Elastic for textarea growth
*/
(function(jQuery){jQuery.fn.extend({elastic:function(){var mimics=['paddingTop','paddingRight','paddingBottom','paddingLeft','fontSize','lineHeight','fontFamily','width','fontWeight'];return this.each(function(){if(this.type!='textarea'){return false;}
var $textarea=jQuery(this),$twin=jQuery('<div />').css({'position':'absolute','display':'none','word-wrap':'break-word'}),lineHeight=parseInt($textarea.css('line-height'),10)||parseInt($textarea.css('font-size'),'10'),minheight=parseInt($textarea.css('height'),10)||lineHeight*3,maxheight=parseInt($textarea.css('max-height'),10)||Number.MAX_VALUE,goalheight=0,i=0;if(maxheight<0){maxheight=Number.MAX_VALUE;}
$twin.appendTo($textarea.parent());var i=mimics.length;while(i--){$twin.css(mimics[i].toString(),$textarea.css(mimics[i].toString()));}
function setHeightAndOverflow(height,overflow){curratedHeight=Math.floor(parseInt(height,10));if($textarea.height()!=curratedHeight){$textarea.css({'height':curratedHeight+'px','overflow':overflow});}}
function update(){var textareaContent=$textarea.val().replace(/&/g,'&amp;').replace(/  /g,'&nbsp;').replace(/<|>/g,'&gt;').replace(/\n/g,'<br />');var twinContent=$twin.html();if(textareaContent+'&nbsp;'!=twinContent){$twin.html(textareaContent+'&nbsp;');if(Math.abs($twin.height()+lineHeight-$textarea.height())>3){var goalheight=$twin.height()+lineHeight;if(goalheight>=maxheight){setHeightAndOverflow(maxheight,'auto');}else if(goalheight<=minheight){setHeightAndOverflow(minheight,'hidden');}else{setHeightAndOverflow(goalheight,'hidden');}}}}
$textarea.css({'overflow':'hidden'});$textarea.keyup(function(){update();});$textarea.live('input paste',function(e){setTimeout(update,250);});update();});}});})(jQuery);
	
/*
Carousel - front page test
*/
(function($){$.fn.tinycarousel=function(options){var defaults={start:1,display:1,axis:'x',controls:true,pager:false,interval:false,intervaltime:3000,animation:true,duration:1000,callback:null};var options=$.extend(defaults,options);var oSlider=$(this);var oViewport=$('.viewport',oSlider);var oContent=$('.overview',oSlider);var oPages=oContent.children();var oBtnNext=$('.next',oSlider);var oBtnPrev=$('.prev',oSlider);var oPager=$('.pager',oSlider);var iPageSize,iSteps,iCurrent,oTimer,bForward=true,bAxis=options.axis=='x';return this.each(function(){initialize();});function initialize(){iPageSize=bAxis?$(oPages[0]).outerWidth(true):$(oPages[0]).outerHeight(true);var iLeftover=Math.ceil(((bAxis?oViewport.outerWidth():oViewport.outerHeight())/(iPageSize*options.display))-1);iSteps=Math.max(1,Math.ceil(oPages.length/options.display)-iLeftover);iCurrent=Math.min(iSteps,Math.max(1,options.start))-2;oContent.css(bAxis?'width':'height',(iPageSize*oPages.length));move(1);setEvents();}
function setButtons(){if(options.controls){oBtnPrev.toggleClass('disable',!(iCurrent>0));oBtnNext.toggleClass('disable',!(iCurrent+1<iSteps));}}
function setEvents(){if(options.controls&&oBtnPrev.length>0&&oBtnNext.length>0){oBtnPrev.click(function(){move(-1);return false;});oBtnNext.click(function(){move(1);return false;});}if(options.pager&&oPager.length>0){oPager.click(setPager);}}
function setPager(oEvent){var oTarget=oEvent.target;if($(oTarget).hasClass('pagenum')){iCurrent=parseInt(oTarget.rel)-1;move(1);}return false;}
function setPagerActive(){if(options.pager){var oNumbers=$('.pagenum',oPager);oNumbers.removeClass('active');$(oNumbers[iCurrent]).addClass('active');}}
function setTimer(bReset){if(options.interval&&!bReset){clearInterval(oTimer);oTimer=window.setInterval(function(){bForward=iCurrent+1==iSteps?false:iCurrent==0?true:bForward;move(bForward?1:-1,true);},options.intervaltime);}}
function move(iDirection,bTimerReset){if(iCurrent+iDirection>-1&&iCurrent+iDirection<iSteps){iCurrent+=iDirection;var oPosition={};oPosition[bAxis?'left':'top']=-(iCurrent*(iPageSize*options.display));oContent.animate(oPosition,{queue:false,duration:options.animation?options.duration:0,complete:function(){if(typeof options.callback=='function')options.callback.call(this,oPages[iCurrent],iCurrent);}});setButtons();setPagerActive();setTimer(bTimerReset);}}};})(jQuery);

// Date picker calendar
(function($){var bm='datepick';function Datepick(){this._uuid=new Date().getTime();this._curInst=null;this._keyEvent=false;this._disabledInputs=[];this._datepickerShowing=false;this._inDialog=false;this.regional=[];this.regional['']={clearText:'Clear',clearStatus:'Erase the current date',closeText:'Close',closeStatus:'Close without change',prevText:'<Prev',prevStatus:'Show the previous month',prevBigText:'<<',prevBigStatus:'Show the previous year',nextText:'Next>',nextStatus:'Show the next month',nextBigText:'>>',nextBigStatus:'Show the next year',currentText:'Today',currentStatus:'Show the current month',monthNames:['January','February','March','April','May','June','July','August','September','October','November','December'],monthNamesShort:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],monthStatus:'Show a different month',yearStatus:'Show a different year',weekHeader:'Wk',weekStatus:'Week of the year',dayNames:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],dayNamesShort:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],dayNamesMin:['Su','Mo','Tu','We','Th','Fr','Sa'],dayStatus:'Set DD as first week day',dateStatus:'Select DD, M d',dateFormat:'mm/dd/yy',firstDay:0,initStatus:'Select a date',isRTL:false,showMonthAfterYear:false,yearSuffix:''};this._defaults={useThemeRoller:false,showOn:'focus',showAnim:'show',showOptions:{},duration:'normal',buttonText:'...',buttonImage:'',buttonImageOnly:false,alignment:'bottom',autoSize:false,defaultDate:null,showDefault:false,appendText:'',closeAtTop:true,mandatory:false,hideIfNoPrevNext:false,navigationAsDateFormat:false,showBigPrevNext:false,stepMonths:1,stepBigMonths:12,gotoCurrent:false,changeMonth:true,changeYear:true,yearRange:'-10:+10',changeFirstDay:false,showOtherMonths:false,selectOtherMonths:false,highlightWeek:false,showWeeks:false,calculateWeek:this.iso8601Week,shortYearCutoff:'+10',showStatus:false,statusForDate:this.dateStatus,minDate:null,maxDate:null,numberOfMonths:1,showCurrentAtPos:0,rangeSelect:false,rangeSeparator:' - ',multiSelect:0,multiSeparator:',',beforeShow:null,beforeShowDay:null,onChangeMonthYear:null,onHover:null,onSelect:null,onClose:null,altField:'',altFormat:'',constrainInput:true};$.extend(this._defaults,this.regional['']);this.dpDiv=$('<div style="display: none;"></div>')}$.extend(Datepick.prototype,{version:'3.7.0',markerClassName:'hasDatepick',_mainDivId:['datepick-div','ui-datepicker-div'],_mainDivClass:['','ui-datepicker '+'ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'],_inlineClass:['datepick-inline','ui-datepicker-inline ui-datepicker '+'ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'],_multiClass:['datepick-multi','ui-datepicker-multi'],_rtlClass:['datepick-rtl','ui-datepicker-rtl'],_appendClass:['datepick-append','ui-datepicker-append'],_triggerClass:['datepick-trigger','ui-datepicker-trigger'],_dialogClass:['datepick-dialog','ui-datepicker-dialog'],_promptClass:['datepick-prompt','ui-datepicker-prompt'],_disableClass:['datepick-disabled','ui-datepicker-disabled'],_controlClass:['datepick-control','ui-datepicker-header '+'ui-widget-header ui-helper-clearfix ui-corner-all'],_clearClass:['datepick-clear','ui-datepicker-clear'],_closeClass:['datepick-close','ui-datepicker-close'],_linksClass:['datepick-links','ui-datepicker-header '+'ui-widget-header ui-helper-clearfix ui-corner-all'],_prevClass:['datepick-prev','ui-datepicker-prev'],_nextClass:['datepick-next','ui-datepicker-next'],_currentClass:['datepick-current','ui-datepicker-current'],_oneMonthClass:['datepick-one-month','ui-datepicker-group'],_newRowClass:['datepick-new-row','ui-datepicker-row-break'],_monthYearClass:['datepick-header','ui-datepicker-header '+'ui-widget-header ui-helper-clearfix ui-corner-all'],_monthSelectClass:['datepick-new-month','ui-datepicker-month'],_monthClass:['','ui-datepicker-month'],_yearSelectClass:['datepick-new-year','ui-datepicker-year'],_yearClass:['','ui-datepicker-year'],_tableClass:['datepick','ui-datepicker-calendar'],_tableHeaderClass:['datepick-title-row',''],_weekColClass:['datepick-week-col','ui-datepicker-week-col'],_weekRowClass:['datepick-days-row',''],_weekendClass:['datepick-week-end-cell','ui-datepicker-week-end'],_dayClass:['datepick-days-cell',''],_otherMonthClass:['datepick-other-month','ui-datepicker-other-month'],_todayClass:['datepick-today','ui-state-highlight'],_selectableClass:['','ui-state-default'],_unselectableClass:['datepick-unselectable','ui-datepicker-unselectable ui-state-disabled'],_selectedClass:['datepick-current-day','ui-state-active'],_dayOverClass:['datepick-days-cell-over','ui-state-hover'],_weekOverClass:['datepick-week-over','ui-state-hover'],_statusClass:['datepick-status','ui-datepicker-status'],_statusId:['datepick-status-','ui-datepicker-status-'],_coverClass:['datepick-cover','ui-datepicker-cover'],setDefaults:function(a){extendRemove(this._defaults,a||{});return this},_attachDatepick:function(a,b){if(!a.id)a.id='dp'+(++this._uuid);var c=a.nodeName.toLowerCase();var d=this._newInst($(a),(c=='div'||c=='span'));var e=($.fn.metadata?$(a).metadata():{});d.settings=$.extend({},b||{},e||{});if(d.inline){d.dpDiv.addClass(this._inlineClass[this._get(d,'useThemeRoller')?1:0]);this._inlineDatepick(a,d)}else this._connectDatepick(a,d)},_newInst:function(a,b){var c=a[0].id.replace(/([:\[\]\.\$])/g,'\\\\$1');return{id:c,input:a,cursorDate:this._daylightSavingAdjust(new Date()),drawMonth:0,drawYear:0,dates:[],inline:b,dpDiv:(!b?this.dpDiv:$('<div></div>')),siblings:$([])}},_connectDatepick:function(a,b){var c=$(a);if(c.hasClass(this.markerClassName))return;var d=this._get(b,'appendText');var e=this._get(b,'isRTL');var f=this._get(b,'useThemeRoller')?1:0;if(d){var g=$('<span class="'+this._appendClass[f]+'">'+d+'</span>');c[e?'before':'after'](g);b.siblings=b.siblings.add(g)}var h=this._get(b,'showOn');if(h=='focus'||h=='both')c.focus(this._showDatepick);if(h=='button'||h=='both'){var i=this._get(b,'buttonText');var j=this._get(b,'buttonImage');var k=$(this._get(b,'buttonImageOnly')?$('<img/>').addClass(this._triggerClass[f]).attr({src:j,alt:i,title:i}):$('<button type="button"></button>').addClass(this._triggerClass[f]).html(j==''?i:$('<img/>').attr({src:j,alt:i,title:i})));c[e?'before':'after'](k);b.siblings=b.siblings.add(k);k.click(function(){if($.datepick._datepickerShowing&&$.datepick._lastInput==a)$.datepick._hideDatepick();else $.datepick._showDatepick(a);return false})}c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp);if(this._get(b,'showDefault')&&!b.input.val()){b.dates=[this._getDefaultDate(b)];this._showDate(b)}this._autoSize(b);$.data(a,bm,b)},_autoSize:function(d){if(this._get(d,'autoSize')&&!d.inline){var e=new Date(2009,12-1,20);var f=this._get(d,'dateFormat');if(f.match(/[DM]/)){var g=function(a){var b=0;var c=0;for(var i=0;i<a.length;i++){if(a[i].length>b){b=a[i].length;c=i}}return c};e.setMonth(g(this._get(d,(f.match(/MM/)?'monthNames':'monthNamesShort'))));e.setDate(g(this._get(d,(f.match(/DD/)?'dayNames':'dayNamesShort')))+20-e.getDay())}d.input.attr('size',this._formatDate(d,e).length)}},_inlineDatepick:function(a,b){var c=$(a);if(c.hasClass(this.markerClassName))return;c.addClass(this.markerClassName);$.data(a,bm,b);b.cursorDate=this._getDefaultDate(b);b.drawMonth=b.cursorDate.getMonth();b.drawYear=b.cursorDate.getFullYear();if(this._get(b,'showDefault'))b.dates=[this._getDefaultDate(b)];$('body').append(b.dpDiv);this._updateDatepick(b);b.dpDiv.width(this._getNumberOfMonths(b)[1]*$('.'+this._oneMonthClass[this._get(b,'useThemeRoller')?1:0],b.dpDiv)[0].offsetWidth);c.append(b.dpDiv);this._updateAlternate(b)},_dialogDatepick:function(a,b,c,d,e){var f=this._dialogInst;if(!f){var g='dp'+(++this._uuid);this._dialogInput=$('<input type="text" id="'+g+'" style="position: absolute; width: 1px; z-index: -1"/>');this._dialogInput.keydown(this._doKeyDown);$('body').append(this._dialogInput);f=this._dialogInst=this._newInst(this._dialogInput,false);f.settings={};$.data(this._dialogInput[0],bm,f)}extendRemove(f.settings,d||{});b=(b&&b.constructor==Date?this._formatDate(f,b):b);this._dialogInput.val(b);this._pos=(e?(isArray(e)?e:[e.pageX,e.pageY]):null);if(!this._pos){var h=document.documentElement.scrollLeft||document.body.scrollLeft;var i=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[(document.documentElement.clientWidth/2)-100+h,(document.documentElement.clientHeight/2)-150+i]}this._dialogInput.css('left',(this._pos[0]+20)+'px').css('top',this._pos[1]+'px');f.settings.onSelect=c;this._inDialog=true;this.dpDiv.addClass(this._dialogClass[this._get(f,'useThemeRoller')?1:0]);this._showDatepick(this._dialogInput[0]);if($.blockUI)$.blockUI(this.dpDiv);$.data(this._dialogInput[0],bm,f)},_destroyDatepick:function(a){var b=$(a);if(!b.hasClass(this.markerClassName)){return}var c=$.data(a,bm);$.removeData(a,bm);if(c.inline)b.removeClass(this.markerClassName).empty();else{$(c.siblings).remove();b.removeClass(this.markerClassName).unbind('focus',this._showDatepick).unbind('keydown',this._doKeyDown).unbind('keypress',this._doKeyPress).unbind('keyup',this._doKeyUp)}},_enableDatepick:function(b){var c=$(b);if(!c.hasClass(this.markerClassName))return;var d=$.data(b,bm);var e=this._get(d,'useThemeRoller')?1:0;if(d.inline)c.children('.'+this._disableClass[e]).remove().end().find('select').attr('disabled','');else{b.disabled=false;d.siblings.filter('button.'+this._triggerClass[e]).each(function(){this.disabled=false}).end().filter('img.'+this._triggerClass[e]).css({opacity:'1.0',cursor:''})}this._disabledInputs=$.map(this._disabledInputs,function(a){return(a==b?null:a)})},_disableDatepick:function(b){var c=$(b);if(!c.hasClass(this.markerClassName))return;var d=$.data(b,bm);var e=this._get(d,'useThemeRoller')?1:0;if(d.inline){var f=c.children('.'+this._inlineClass[e]);var g=f.offset();var h={left:0,top:0};f.parents().each(function(){if($(this).css('position')=='relative'){h=$(this).offset();return false}});c.prepend('<div class="'+this._disableClass[e]+'" style="'+'width: '+f.width()+'px; height: '+f.height()+'px; left: '+(g.left-h.left)+'px; top: '+(g.top-h.top)+'px;"></div>').find('select').attr('disabled','disabled')}else{b.disabled=true;d.siblings.filter('button.'+this._triggerClass[e]).each(function(){this.disabled=true}).end().filter('img.'+this._triggerClass[e]).css({opacity:'0.5',cursor:'default'})}this._disabledInputs=$.map(this._disabledInputs,function(a){return(a==b?null:a)});this._disabledInputs.push(b)},_isDisabledDatepick:function(a){return(!a?false:$.inArray(a,this._disabledInputs)>-1)},_getInst:function(a){try{return $.data(a,bm)}catch(err){throw'Missing instance data for this datepicker';}},_optionDatepick:function(a,b,c){var d=this._getInst(a);if(arguments.length==2&&typeof b=='string'){return(b=='defaults'?$.extend({},$.datepick._defaults):(d?(b=='all'?$.extend({},d.settings):this._get(d,b)):null))}var e=b||{};if(typeof b=='string'){e={};e[b]=c}if(d){if(this._curInst==d){this._hideDatepick(null)}var f=this._getDateDatepick(a);extendRemove(d.settings,e);this._autoSize(d);extendRemove(d,{dates:[]});var g=(!f||isArray(f));if(isArray(f))for(var i=0;i<f.length;i++)if(f[i]){g=false;break}if(!g)this._setDateDatepick(a,f);if(d.inline)$(a).children('div').removeClass(this._inlineClass.join(' ')).addClass(this._inlineClass[this._get(d,'useThemeRoller')?1:0]);this._updateDatepick(d)}},_changeDatepick:function(a,b,c){this._optionDatepick(a,b,c)},_refreshDatepick:function(a){var b=this._getInst(a);if(b){this._updateDatepick(b)}},_setDateDatepick:function(a,b,c){var d=this._getInst(a);if(d){this._setDate(d,b,c);this._updateDatepick(d);this._updateAlternate(d)}},_getDateDatepick:function(a){var b=this._getInst(a);if(b&&!b.inline)this._setDateFromField(b);return(b?this._getDate(b):null)},_doKeyDown:function(a){var b=$.datepick._getInst(a.target);b.keyEvent=true;var c=true;var d=$.datepick._get(b,'isRTL');var e=$.datepick._get(b,'useThemeRoller')?1:0;if($.datepick._datepickerShowing)switch(a.keyCode){case 9:$.datepick._hideDatepick(null,'');break;case 13:var f=$('td.'+$.datepick._dayOverClass[e],b.dpDiv);if(f.length==0)f=$('td.'+$.datepick._selectedClass[e]+':first',b.dpDiv);if(f[0])$.datepick._selectDay(f[0],a.target,b.cursorDate.getTime());else $.datepick._hideDatepick(null,$.datepick._get(b,'duration'));break;case 27:$.datepick._hideDatepick(null,$.datepick._get(b,'duration'));break;case 33:$.datepick._adjustDate(a.target,(a.ctrlKey?-$.datepick._get(b,'stepBigMonths'):-$.datepick._get(b,'stepMonths')),'M');break;case 34:$.datepick._adjustDate(a.target,(a.ctrlKey?+$.datepick._get(b,'stepBigMonths'):+$.datepick._get(b,'stepMonths')),'M');break;case 35:if(a.ctrlKey||a.metaKey)$.datepick._clearDate(a.target);c=a.ctrlKey||a.metaKey;break;case 36:if(a.ctrlKey||a.metaKey)$.datepick._gotoToday(a.target);c=a.ctrlKey||a.metaKey;break;case 37:if(a.ctrlKey||a.metaKey)$.datepick._adjustDate(a.target,(d?+1:-1),'D');c=a.ctrlKey||a.metaKey;if(a.originalEvent.altKey)$.datepick._adjustDate(a.target,(a.ctrlKey?-$.datepick._get(b,'stepBigMonths'):-$.datepick._get(b,'stepMonths')),'M');break;case 38:if(a.ctrlKey||a.metaKey)$.datepick._adjustDate(a.target,-7,'D');c=a.ctrlKey||a.metaKey;break;case 39:if(a.ctrlKey||a.metaKey)$.datepick._adjustDate(a.target,(d?-1:+1),'D');c=a.ctrlKey||a.metaKey;if(a.originalEvent.altKey)$.datepick._adjustDate(a.target,(a.ctrlKey?+$.datepick._get(b,'stepBigMonths'):+$.datepick._get(b,'stepMonths')),'M');break;case 40:if(a.ctrlKey||a.metaKey)$.datepick._adjustDate(a.target,+7,'D');c=a.ctrlKey||a.metaKey;break;default:c=false}else if(a.keyCode==36&&a.ctrlKey)$.datepick._showDatepick(this);else c=false;if(c){a.preventDefault();a.stopPropagation()}b.ctrlKey=(a.keyCode<48);return!c},_doKeyPress:function(a){var b=$.datepick._getInst(a.target);if($.datepick._get(b,'constrainInput')){var c=$.datepick._possibleChars(b);var d=String.fromCharCode(a.keyCode||a.charCode);return b.ctrlKey||(d<' '||!c||c.indexOf(d)>-1)}},_doKeyUp:function(a){var b=$.datepick._getInst(a.target);if(b.input.val()!=b.lastVal){try{var c=($.datepick._get(b,'rangeSelect')?$.datepick._get(b,'rangeSeparator'):($.datepick._get(b,'multiSelect')?$.datepick._get(b,'multiSeparator'):''));var d=(b.input?b.input.val():'');d=(c?d.split(c):[d]);var e=true;for(var i=0;i<d.length;i++){if(!$.datepick.parseDate($.datepick._get(b,'dateFormat'),d[i],$.datepick._getFormatConfig(b))){e=false;break}}if(e){$.datepick._setDateFromField(b);$.datepick._updateAlternate(b);$.datepick._updateDatepick(b)}}catch(a){}}return true},_possibleChars:function(a){var b=$.datepick._get(a,'dateFormat');var c=($.datepick._get(a,'rangeSelect')?$.datepick._get(a,'rangeSeparator'):($.datepick._get(a,'multiSelect')?$.datepick._get(a,'multiSeparator'):''));var d=false;for(var e=0;e<b.length;e++)if(d)if(b.charAt(e)=="'"&&!lookAhead("'"))d=false;else c+=b.charAt(e);else switch(b.charAt(e)){case'd':case'm':case'y':case'@':c+='0123456789';break;case'D':case'M':return null;case"'":if(lookAhead("'"))c+="'";else d=true;break;default:c+=b.charAt(e)}return c},_doMouseOver:function(a,b,c){var d=$.datepick._getInst($('#'+b)[0]);var e=$.datepick._get(d,'useThemeRoller')?1:0;$(a).parents('tbody').find('td').removeClass($.datepick._dayOverClass[e]).end().end().addClass($.datepick._dayOverClass[e]);if($.datepick._get(d,'highlightWeek'))$(a).parent().parent().find('tr').removeClass($.datepick._weekOverClass[e]).end().end().addClass($.datepick._weekOverClass[e]);if($(a).text()){var f=new Date(c);if($.datepick._get(d,'showStatus')){var g=($.datepick._get(d,'statusForDate').apply((d.input?d.input[0]:null),[f,d])||$.datepick._get(d,'initStatus'));$('#'+$.datepick._statusId[e]+b).html(g)}if($.datepick._get(d,'onHover'))$.datepick._doHover(a,'#'+b,f.getFullYear(),f.getMonth())}},_doMouseOut:function(a,b){var c=$.datepick._getInst($('#'+b)[0]);var d=$.datepick._get(c,'useThemeRoller')?1:0;$(a).removeClass($.datepick._dayOverClass[d]).removeClass($.datepick._weekOverClass[d]);if($.datepick._get(c,'showStatus'))$('#'+$.datepick._statusId[d]+b).html($.datepick._get(c,'initStatus'));if($.datepick._get(c,'onHover'))$.datepick._doHover(a,'#'+b)},_doHover:function(a,b,c,d){var e=this._getInst($(b)[0]);var f=$.datepick._get(e,'useThemeRoller')?1:0;if($(a).hasClass(this._unselectableClass[f]))return;var g=this._get(e,'onHover');var h=(c?this._daylightSavingAdjust(new Date(c,d,$(a).text())):null);g.apply((e.input?e.input[0]:null),[(h?this._formatDate(e,h):''),h,e])},_showDatepick:function(b){b=b.target||b;if($.datepick._isDisabledDatepick(b)||$.datepick._lastInput==b)return;var c=$.datepick._getInst(b);var d=$.datepick._get(c,'beforeShow');var e=$.datepick._get(c,'useThemeRoller')?1:0;extendRemove(c.settings,(d?d.apply(b,[b,c]):{}));$.datepick._hideDatepick(null,'');$.datepick._lastInput=b;$.datepick._setDateFromField(c);if($.datepick._inDialog)b.value='';if(!$.datepick._pos){$.datepick._pos=$.datepick._findPos(b);$.datepick._pos[1]+=b.offsetHeight}var f=false;$(b).parents().each(function(){f|=$(this).css('position')=='fixed';return!f});if(f&&$.browser.opera){$.datepick._pos[0]-=document.documentElement.scrollLeft;$.datepick._pos[1]-=document.documentElement.scrollTop}var g={left:$.datepick._pos[0],top:$.datepick._pos[1]};$.datepick._pos=null;c.dpDiv.css({position:'absolute',display:'block',top:'-1000px'});$.datepick._updateDatepick(c);c.dpDiv.width($.datepick._getNumberOfMonths(c)[1]*$('.'+$.datepick._oneMonthClass[e],c.dpDiv).width());g=$.datepick._checkOffset(c,g,f);c.dpDiv.css({position:($.datepick._inDialog&&$.blockUI?'static':(f?'fixed':'absolute')),display:'none',left:g.left+'px',top:g.top+'px'});if(!c.inline){var h=$.datepick._get(c,'showAnim')||'show';var i=$.datepick._get(c,'duration');var j=function(){$.datepick._datepickerShowing=true;var a=$.datepick._getBorders(c.dpDiv);c.dpDiv.find('iframe.'+$.datepick._coverClass[e]).css({left:-a[0],top:-a[1],width:c.dpDiv.outerWidth(),height:c.dpDiv.outerHeight()})};if($.effects&&$.effects[h])c.dpDiv.show(h,$.datepick._get(c,'showOptions'),i,j);else c.dpDiv[h](i,j);if(i=='')j();if(c.input[0].type!='hidden')c.input.focus();$.datepick._curInst=c}},_updateDatepick:function(a){var b=this._getBorders(a.dpDiv);var c=this._get(a,'useThemeRoller')?1:0;a.dpDiv.empty().append(this._generateHTML(a)).find('iframe.'+this._coverClass[c]).css({left:-b[0],top:-b[1],width:a.dpDiv.outerWidth(),height:a.dpDiv.outerHeight()});var d=this._getNumberOfMonths(a);if(!a.inline)a.dpDiv.attr('id',this._mainDivId[c]);a.dpDiv.removeClass(this._mainDivClass[1-c]).addClass(this._mainDivClass[c]).removeClass(this._multiClass.join(' ')).addClass(d[0]!=1||d[1]!=1?this._multiClass[c]:'').removeClass(this._rtlClass.join(' ')).addClass(this._get(a,'isRTL')?this._rtlClass[c]:'');if(a.input&&a.input[0].type!='hidden'&&a==$.datepick._curInst)$(a.input).focus()},_getBorders:function(c){var d=function(a){var b=($.browser.msie?1:0);return{thin:1+b,medium:3+b,thick:5+b}[a]||a};return[parseFloat(d(c.css('border-left-width'))),parseFloat(d(c.css('border-top-width')))]},_checkOffset:function(a,b,c){var d=this._get(a,'alignment');var e=this._get(a,'isRTL');var f=a.input?this._findPos(a.input[0]):null;var g=document.documentElement.clientWidth;var h=document.documentElement.clientHeight;if(g==0)return b;var i=document.documentElement.scrollLeft||document.body.scrollLeft;var j=document.documentElement.scrollTop||document.body.scrollTop;var k=f[1]-(this._inDialog?0:a.dpDiv.outerHeight())-(c&&$.browser.opera?document.documentElement.scrollTop:0);var l=b.top;var m=b.left;var n=f[0]+(a.input?a.input.outerWidth():0)-a.dpDiv.outerWidth()-(c&&$.browser.opera?document.documentElement.scrollLeft:0);var o=(b.left+a.dpDiv.outerWidth()-i)>g;var p=(b.top+a.dpDiv.outerHeight()-j)>h;if(d=='topLeft'){b={left:m,top:k}}else if(d=='topRight'){b={left:n,top:k}}else if(d=='bottomLeft'){b={left:m,top:l}}else if(d=='bottomRight'){b={left:n,top:l}}else if(d=='top'){b={left:(e||o?n:m),top:k}}else{b={left:(e||o?n:m),top:(p?k:l)}}b.left=Math.max((c?0:i),b.left-(c?i:0));b.top=Math.max((c?0:j),b.top-(c?j:0));return b},_findPos:function(a){while(a&&(a.type=='hidden'||a.nodeType!=1)){a=a.nextSibling}var b=$(a).offset();return[b.left,b.top]},_hideDatepick:function(a,b){var c=this._curInst;if(!c||(a&&c!=$.data(a,bm)))return false;var d=this._get(c,'rangeSelect');if(d&&c.stayOpen)this._updateInput('#'+c.id);c.stayOpen=false;if(this._datepickerShowing){b=(b!=null?b:this._get(c,'duration'));var e=this._get(c,'showAnim');var f=function(){$.datepick._tidyDialog(c)};if(b!=''&&$.effects&&$.effects[e])c.dpDiv.hide(e,$.datepick._get(c,'showOptions'),b,f);else c.dpDiv[(b==''?'hide':(e=='slideDown'?'slideUp':(e=='fadeIn'?'fadeOut':'hide')))](b,f);if(b=='')this._tidyDialog(c);var g=this._get(c,'onClose');if(g)g.apply((c.input?c.input[0]:null),[(c.input?c.input.val():''),this._getDate(c),c]);this._datepickerShowing=false;this._lastInput=null;c.settings.prompt=null;if(this._inDialog){this._dialogInput.css({position:'absolute',left:'0',top:'-100px'});this.dpDiv.removeClass(this._dialogClass[this._get(c,'useThemeRoller')?1:0]);if($.blockUI){$.unblockUI();$('body').append(this.dpDiv)}}this._inDialog=false}this._curInst=null;return false},_tidyDialog:function(a){var b=this._get(a,'useThemeRoller')?1:0;a.dpDiv.removeClass(this._dialogClass[b]).unbind('.datepick');$('.'+this._promptClass[b],a.dpDiv).remove()},_checkExternalClick:function(a){if(!$.datepick._curInst)return;var b=$(a.target);var c=$.datepick._get($.datepick._curInst,'useThemeRoller')?1:0;if(!b.parents().andSelf().is('#'+$.datepick._mainDivId[c])&&!b.hasClass($.datepick.markerClassName)&&!b.parents().andSelf().hasClass($.datepick._triggerClass[c])&&$.datepick._datepickerShowing&&!($.datepick._inDialog&&$.blockUI))$.datepick._hideDatepick(null,'')},_adjustDate:function(a,b,c){var d=this._getInst($(a)[0]);this._adjustInstDate(d,b+(c=='M'?this._get(d,'showCurrentAtPos'):0),c);this._updateDatepick(d);return false},_gotoToday:function(a){var b=$(a);var c=this._getInst(b[0]);if(this._get(c,'gotoCurrent')&&c.dates[0])c.cursorDate=new Date(c.dates[0].getTime());else c.cursorDate=this._daylightSavingAdjust(new Date());c.drawMonth=c.cursorDate.getMonth();c.drawYear=c.cursorDate.getFullYear();this._notifyChange(c);this._adjustDate(b);return false},_selectMonthYear:function(a,b,c){var d=$(a);var e=this._getInst(d[0]);e.selectingMonthYear=false;var f=parseInt(b.options[b.selectedIndex].value,10);e['selected'+(c=='M'?'Month':'Year')]=e['draw'+(c=='M'?'Month':'Year')]=f;e.cursorDate.setDate(Math.min(e.cursorDate.getDate(),$.datepick._getDaysInMonth(e.drawYear,e.drawMonth)));e.cursorDate['set'+(c=='M'?'Month':'FullYear')](f);this._notifyChange(e);this._adjustDate(d)},_clickMonthYear:function(a){var b=this._getInst($(a)[0]);if(b.input&&b.selectingMonthYear&&!$.browser.msie)b.input.focus();b.selectingMonthYear=!b.selectingMonthYear},_changeFirstDay:function(a,b){var c=this._getInst($(a)[0]);c.settings.firstDay=b;this._updateDatepick(c);return false},_selectDay:function(a,b,c){var d=this._getInst($(b)[0]);var e=this._get(d,'useThemeRoller')?1:0;if($(a).hasClass(this._unselectableClass[e]))return false;var f=this._get(d,'rangeSelect');var g=this._get(d,'multiSelect');if(f)d.stayOpen=!d.stayOpen;else if(g)d.stayOpen=true;if(d.stayOpen){$('.datepick td',d.dpDiv).removeClass(this._selectedClass[e]);$(a).addClass(this._selectedClass[e])}d.cursorDate=this._daylightSavingAdjust(new Date(c));var h=new Date(d.cursorDate.getTime());if(f&&!d.stayOpen)d.dates[1]=h;else if(g){var j=-1;for(var i=0;i<d.dates.length;i++)if(d.dates[i]&&h.getTime()==d.dates[i].getTime()){j=i;break}if(j>-1)d.dates.splice(j,1);else if(d.dates.length<g){if(d.dates[0])d.dates.push(h);else d.dates=[h];d.stayOpen=(d.dates.length!=g)}}else d.dates=[h];this._updateInput(b);if(d.stayOpen)this._updateDatepick(d);else if((f||g)&&d.inline)this._updateDatepick(d);return false},_clearDate:function(a){var b=$(a);var c=this._getInst(b[0]);if(this._get(c,'mandatory'))return false;c.stayOpen=false;c.dates=(this._get(c,'showDefault')?[this._getDefaultDate(c)]:[]);this._updateInput(b);return false},_updateInput:function(a){var b=this._getInst($(a)[0]);var c=this._showDate(b);this._updateAlternate(b);var d=this._get(b,'onSelect');if(d)d.apply((b.input?b.input[0]:null),[c,this._getDate(b),b]);else if(b.input)b.input.trigger('change');if(b.inline)this._updateDatepick(b);else if(!b.stayOpen){this._hideDatepick(null,this._get(b,'duration'));this._lastInput=b.input[0];if(typeof(b.input[0])!='object')b.input.focus();this._lastInput=null}return false},_showDate:function(a){var b='';if(a.input){b=(a.dates.length==0?'':this._formatDate(a,a.dates[0]));if(b){if(this._get(a,'rangeSelect'))b+=this._get(a,'rangeSeparator')+this._formatDate(a,a.dates[1]||a.dates[0]);else if(this._get(a,'multiSelect'))for(var i=1;i<a.dates.length;i++)b+=this._get(a,'multiSeparator')+this._formatDate(a,a.dates[i])}a.input.val(b)}return b},_updateAlternate:function(a){var b=this._get(a,'altField');if(b){var c=this._get(a,'altFormat')||this._get(a,'dateFormat');var d=this._getFormatConfig(a);var e=this.formatDate(c,a.dates[0],d);if(e&&this._get(a,'rangeSelect'))e+=this._get(a,'rangeSeparator')+this.formatDate(c,a.dates[1]||a.dates[0],d);else if(this._get(a,'multiSelect'))for(var i=1;i<a.dates.length;i++)e+=this._get(a,'multiSeparator')+this.formatDate(c,a.dates[i],d);$(b).val(e)}},noWeekends:function(a){return[(a.getDay()||7)<6,'']},iso8601Week:function(a){var b=new Date(a.getTime());b.setDate(b.getDate()+4-(b.getDay()||7));var c=b.getTime();b.setMonth(0);b.setDate(1);return Math.floor(Math.round((c-b)/86400000)/7)+1},dateStatus:function(a,b){return $.datepick.formatDate($.datepick._get(b,'dateStatus'),a,$.datepick._getFormatConfig(b))},parseDate:function(e,f,g){if(e==null||f==null)throw'Invalid arguments';f=(typeof f=='object'?f.toString():f+'');if(f=='')return null;g=g||{};var h=g.shortYearCutoff||this._defaults.shortYearCutoff;h=(typeof h!='string'?h:new Date().getFullYear()%100+parseInt(h,10));var j=g.dayNamesShort||this._defaults.dayNamesShort;var k=g.dayNames||this._defaults.dayNames;var l=g.monthNamesShort||this._defaults.monthNamesShort;var m=g.monthNames||this._defaults.monthNames;var n=-1;var o=-1;var p=-1;var q=-1;var r=false;var s=function(a){var b=(x+1<e.length&&e.charAt(x+1)==a);if(b)x++;return b};var t=function(a){s(a);var b=(a=='@'?14:(a=='!'?20:(a=='y'?4:(a=='o'?3:2))));var c=new RegExp('^\\d{1,'+b+'}');var d=f.substring(w).match(c);if(!d)throw'Missing number at position '+w;w+=d[0].length;return parseInt(d[0],10)};var u=function(a,b,c){var d=(s(a)?c:b);for(var i=0;i<d.length;i++){if(f.substr(w,d[i].length)==d[i]){w+=d[i].length;return i+1}}throw'Unknown name at position '+w;};var v=function(){if(f.charAt(w)!=e.charAt(x))throw'Unexpected literal at position '+w;w++};var w=0;for(var x=0;x<e.length;x++){if(r)if(e.charAt(x)=="'"&&!s("'"))r=false;else v();else switch(e.charAt(x)){case'd':p=t('d');break;case'D':u('D',j,k);break;case'o':q=t('o');break;case'w':t('w');break;case'm':o=t('m');break;case'M':o=u('M',l,m);break;case'y':n=t('y');break;case'@':var y=new Date(t('@'));n=y.getFullYear();o=y.getMonth()+1;p=y.getDate();break;case'!':var y=new Date((t('!')-this._ticksTo1970)/10000);n=y.getFullYear();o=y.getMonth()+1;p=y.getDate();break;case"'":if(s("'"))v();else r=true;break;default:v()}}if(w<f.length)throw'Additional text found at end';if(n==-1)n=new Date().getFullYear();else if(n<100)n+=(h==-1?1900:new Date().getFullYear()-new Date().getFullYear()%100-(n<=h?0:100));if(q>-1){o=1;p=q;do{var z=this._getDaysInMonth(n,o-1);if(p<=z)break;o++;p-=z}while(true)}var y=this._daylightSavingAdjust(new Date(n,o-1,p));if(y.getFullYear()!=n||y.getMonth()+1!=o||y.getDate()!=p)throw'Invalid date';return y},ATOM:'yy-mm-dd',COOKIE:'D, dd M yy',ISO_8601:'yy-mm-dd',RFC_822:'D, d M y',RFC_850:'DD, dd-M-y',RFC_1036:'D, d M y',RFC_1123:'D, d M yy',RFC_2822:'D, d M yy',RSS:'D, d M y',TICKS:'!',TIMESTAMP:'@',W3C:'yy-mm-dd',_ticksTo1970:(((1970-1)*365+Math.floor(1970/4)-Math.floor(1970/100)+Math.floor(1970/400))*24*60*60*10000000),formatDate:function(e,f,g){if(!f)return'';g=g||{};var h=g.dayNamesShort||this._defaults.dayNamesShort;var i=g.dayNames||this._defaults.dayNames;var j=g.monthNamesShort||this._defaults.monthNamesShort;var k=g.monthNames||this._defaults.monthNames;var l=g.calculateWeek||this._defaults.calculateWeek;var m=function(a){var b=(r+1<e.length&&e.charAt(r+1)==a);if(b)r++;return b};var n=function(a,b,c){var d=''+b;if(m(a))while(d.length<c)d='0'+d;return d};var o=function(a,b,c,d){return(m(a)?d[b]:c[b])};var p='';var q=false;if(f)for(var r=0;r<e.length;r++){if(q)if(e.charAt(r)=="'"&&!m("'"))q=false;else p+=e.charAt(r);else switch(e.charAt(r)){case'd':p+=n('d',f.getDate(),2);break;case'D':p+=o('D',f.getDay(),h,i);break;case'o':p+=n('o',(f.getTime()-new Date(f.getFullYear(),0,0).getTime())/86400000,3);break;case'w':p+=n('w',l(f),2);break;case'm':p+=n('m',f.getMonth()+1,2);break;case'M':p+=o('M',f.getMonth(),j,k);break;case'y':p+=(m('y')?f.getFullYear():(f.getFullYear()%100<10?'0':'')+f.getFullYear()%100);break;case'@':p+=f.getTime();break;case'!':p+=f.getTime()*10000+this._ticksTo1970;break;case"'":if(m("'"))p+="'";else q=true;break;default:p+=e.charAt(r)}}return p},_get:function(a,b){return a.settings[b]!==undefined?a.settings[b]:this._defaults[b]},_setDateFromField:function(a){var b=this._get(a,'dateFormat');var c=this._get(a,'rangeSelect');var d=this._get(a,'multiSelect');a.lastVal=(a.input?a.input.val():'');var e=a.lastVal;e=(c?e.split(this._get(a,'rangeSeparator')):(d?e.split(this._get(a,'multiSeparator')):[e]));a.dates=[];var f=this._getFormatConfig(a);for(var i=0;i<e.length;i++)try{a.dates[i]=this.parseDate(b,e[i],f)}catch(event){a.dates[i]=null}for(var i=a.dates.length-1;i>=0;i--)if(!a.dates[i])a.dates.splice(i,1);if(c&&a.dates.length<2)a.dates[1]=a.dates[0];if(d&&a.dates.length>d)a.dates.splice(d,a.dates.length);a.cursorDate=new Date((a.dates[0]||this._getDefaultDate(a)).getTime());a.drawMonth=a.cursorDate.getMonth();a.drawYear=a.cursorDate.getFullYear();this._adjustInstDate(a)},_getDefaultDate:function(a){return this._restrictMinMax(a,this._determineDate(a,this._get(a,'defaultDate'),new Date()))},_determineDate:function(i,j,k){var l=function(a){var b=new Date();b.setDate(b.getDate()+a);return b};var m=function(a){try{return $.datepick.parseDate($.datepick._get(i,'dateFormat'),a,$.datepick._getFormatConfig(i))}catch(e){}var b=(a.toLowerCase().match(/^c/)?$.datepick._getDate(i):null)||new Date();var c=b.getFullYear();var d=b.getMonth();var f=b.getDate();var g=/([+-]?[0-9]+)\s*(d|w|m|y)?/g;var h=g.exec(a.toLowerCase());while(h){switch(h[2]||'d'){case'd':f+=parseInt(h[1],10);break;case'w':f+=parseInt(h[1],10)*7;break;case'm':d+=parseInt(h[1],10);f=Math.min(f,$.datepick._getDaysInMonth(c,d));break;case'y':c+=parseInt(h[1],10);f=Math.min(f,$.datepick._getDaysInMonth(c,d));break}h=g.exec(a.toLowerCase())}return new Date(c,d,f)};j=(j==null?k:(typeof j=='string'?m(j):(typeof j=='number'?(isNaN(j)||j==Infinity||j==-Infinity?k:l(j)):j)));j=(j&&(j.toString()=='Invalid Date'||j.toString()=='NaN')?k:j);if(j){j.setHours(0);j.setMinutes(0);j.setSeconds(0);j.setMilliseconds(0)}return this._daylightSavingAdjust(j)},_daylightSavingAdjust:function(a){if(!a)return null;a.setHours(a.getHours()>12?a.getHours()+2:0);return a},_setDate:function(a,b,c){b=(!b?[]:(isArray(b)?b:[b]));if(c)b.push(c);var d=a.cursorDate.getMonth();var e=a.cursorDate.getFullYear();a.dates=(b.length==0?[]:[this._restrictMinMax(a,this._determineDate(a,b[0],new Date()))]);a.cursorDate=(b.length==0?new Date():new Date(a.dates[0].getTime()));a.drawMonth=a.cursorDate.getMonth();a.drawYear=a.cursorDate.getFullYear();if(this._get(a,'rangeSelect')){if(b.length>0)a.dates[1]=(b.length<1?a.dates[0]:this._restrictMinMax(a,this._determineDate(a,b[1],null)))}else if(this._get(a,'multiSelect'))for(var i=1;i<b.length;i++)a.dates[i]=this._restrictMinMax(a,this._determineDate(a,b[i],null));if(d!=a.cursorDate.getMonth()||e!=a.cursorDate.getFullYear())this._notifyChange(a);this._adjustInstDate(a);this._showDate(a)},_getDate:function(a){var b=(!a.inline&&a.input&&a.input.val()==''?null:(a.dates.length?a.dates[0]:null));if(this._get(a,'rangeSelect'))return(b?[a.dates[0],a.dates[1]||a.dates[0]]:[null,null]);else if(this._get(a,'multiSelect'))return a.dates.slice(0,a.dates.length);else return b},_generateHTML:function(a){var b=new Date();b=this._daylightSavingAdjust(new Date(b.getFullYear(),b.getMonth(),b.getDate()));var c=this._get(a,'showStatus');var d=this._get(a,'initStatus')||' ';var e=this._get(a,'isRTL');var f=this._get(a,'useThemeRoller')?1:0;var g=(this._get(a,'mandatory')?'':'<div class="'+this._clearClass[f]+'"><a href="javascript:void(0)" '+'onclick="jQuery.datepick._clearDate(\'#'+a.id+'\');"'+this._addStatus(f,c,a.id,this._get(a,'clearStatus'),d)+'>'+this._get(a,'clearText')+'</a></div>');var h='<div class="'+this._controlClass[f]+'">'+(e?'':g)+'<div class="'+this._closeClass[f]+'"><a href="javascript:void(0)" '+'onclick="jQuery.datepick._hideDatepick();"'+this._addStatus(f,c,a.id,this._get(a,'closeStatus'),d)+'>'+this._get(a,'closeText')+'</a></div>'+(e?g:'')+'</div>';var j=this._get(a,'prompt');var k=this._get(a,'closeAtTop');var l=this._get(a,'hideIfNoPrevNext');var m=this._get(a,'navigationAsDateFormat');var n=this._get(a,'showBigPrevNext');var o=this._getNumberOfMonths(a);var p=this._get(a,'showCurrentAtPos');var q=this._get(a,'stepMonths');var r=this._get(a,'stepBigMonths');var s=(o[0]!=1||o[1]!=1);var t=this._getMinMaxDate(a,'min',true);var u=this._getMinMaxDate(a,'max');var v=a.drawMonth-p;var w=a.drawYear;if(v<0){v+=12;w--}if(u){var x=this._daylightSavingAdjust(new Date(u.getFullYear(),u.getMonth()-(o[0]*o[1])+1,u.getDate()));x=(t&&x<t?t:x);while(this._daylightSavingAdjust(new Date(w,v,1))>x){v--;if(v<0){v=11;w--}}}a.drawMonth=v;a.drawYear=w;var y=this._get(a,'prevText');y=(!m?y:this.formatDate(y,this._daylightSavingAdjust(new Date(w,v-q,1)),this._getFormatConfig(a)));var z=(n?this._get(a,'prevBigText'):'');z=(!m?z:this.formatDate(z,this._daylightSavingAdjust(new Date(w,v-r,1)),this._getFormatConfig(a)));var A='<div class="'+this._prevClass[f]+'">'+(this._canAdjustMonth(a,-1,w,v)?(n?'<a href="javascript:void(0)" onclick="jQuery.datepick._adjustDate(\'#'+a.id+'\', -'+r+', \'M\');"'+this._addStatus(f,c,a.id,this._get(a,'prevBigStatus'),d)+'>'+z+'</a>':'')+'<a href="javascript:void(0)" onclick="jQuery.datepick._adjustDate(\'#'+a.id+'\', -'+q+', \'M\');"'+this._addStatus(f,c,a.id,this._get(a,'prevStatus'),d)+'>'+y+'</a>':(l?' ':(n?'<label>'+z+'</label>':'')+'<label>'+y+'</label>'))+'</div>';var B=this._get(a,'nextText');B=(!m?B:this.formatDate(B,this._daylightSavingAdjust(new Date(w,v+q,1)),this._getFormatConfig(a)));var C=(n?this._get(a,'nextBigText'):'');C=(!m?C:this.formatDate(C,this._daylightSavingAdjust(new Date(w,v+r,1)),this._getFormatConfig(a)));var D='<div class="'+this._nextClass[f]+'">'+(this._canAdjustMonth(a,+1,w,v)?'<a href="javascript:void(0)" onclick="jQuery.datepick._adjustDate(\'#'+a.id+'\', +'+q+', \'M\');"'+this._addStatus(f,c,a.id,this._get(a,'nextStatus'),d)+'>'+B+'</a>'+(n?'<a href="javascript:void(0)" onclick="jQuery.datepick._adjustDate(\'#'+a.id+'\', +'+r+', \'M\');"'+this._addStatus(f,c,a.id,this._get(a,'nextBigStatus'),d)+'>'+C+'</a>':''):(l?' ':'<label>'+B+'</label>'+(n?'<label>'+C+'</label>':'')))+'</div>';var E=this._get(a,'currentText');var F=(this._get(a,'gotoCurrent')&&a.dates[0]?a.dates[0]:b);E=(!m?E:this.formatDate(E,F,this._getFormatConfig(a)));var G=(k&&!a.inline?h:'')+'<div class="'+this._linksClass[f]+'">'+(e?D:A)+'<div class="'+this._currentClass[f]+'">'+(this._isInRange(a,F)?'<a href="javascript:void(0)" onclick="jQuery.datepick._gotoToday(\'#'+a.id+'\');"'+this._addStatus(f,c,a.id,this._get(a,'currentStatus'),d)+'>'+E+'</a>':(l?' ':'<label>'+E+'</label>'))+'</div>'+(e?A:D)+'</div>'+(j?'<div class="'+this._promptClass[f]+'"><span>'+j+'</span></div>':'');var H=parseInt(this._get(a,'firstDay'),10);H=(isNaN(H)?0:H);var I=this._get(a,'changeFirstDay');var J=this._get(a,'dayNames');var K=this._get(a,'dayNamesShort');var L=this._get(a,'dayNamesMin');var M=this._get(a,'monthNames');var N=this._get(a,'beforeShowDay');var O=this._get(a,'showOtherMonths');var P=this._get(a,'selectOtherMonths');var Q=this._get(a,'showWeeks');var R=this._get(a,'calculateWeek')||this.iso8601Week;var S=this._get(a,'weekStatus');var T=(c?this._get(a,'dayStatus')||d:'');var U=this._get(a,'statusForDate')||this.dateStatus;var V=this._getDefaultDate(a);for(var W=0;W<o[0];W++){for(var X=0;X<o[1];X++){var Y=this._daylightSavingAdjust(new Date(w,v,a.cursorDate.getDate()));G+='<div class="'+this._oneMonthClass[f]+(X==0&&!f?' '+this._newRowClass[f]:'')+'">'+this._generateMonthYearHeader(a,v,w,t,u,Y,W>0||X>0,f,c,d,M)+'<table class="'+this._tableClass[f]+'" cellpadding="0" cellspacing="0"><thead>'+'<tr class="'+this._tableHeaderClass[f]+'">'+(Q?'<th'+this._addStatus(f,c,a.id,S,d)+'>'+this._get(a,'weekHeader')+'</th>':'');for(var Z=0;Z<7;Z++){var bn=(Z+H)%7;var bo=(!c||!I?'':T.replace(/DD/,J[bn]).replace(/D/,K[bn]));G+='<th'+((Z+H+6)%7<5?'':' class="'+this._weekendClass[f]+'"')+'>'+(!I?'<span'+this._addStatus(f,c,a.id,J[bn],d):'<a href="javascript:void(0)" onclick="jQuery.datepick._changeFirstDay(\'#'+a.id+'\', '+bn+');"'+this._addStatus(f,c,a.id,bo,d))+' title="'+J[bn]+'">'+L[bn]+(I?'</a>':'</span>')+'</th>'}G+='</tr></thead><tbody>';var bp=this._getDaysInMonth(w,v);if(w==a.cursorDate.getFullYear()&&v==a.cursorDate.getMonth())a.cursorDate.setDate(Math.min(a.cursorDate.getDate(),bp));var bq=(this._getFirstDayOfMonth(w,v)-H+7)%7;var br=(s?6:Math.ceil((bq+bp)/7));var bs=this._daylightSavingAdjust(new Date(w,v,1-bq));for(var bt=0;bt<br;bt++){G+='<tr class="'+this._weekRowClass[f]+'">'+(Q?'<td class="'+this._weekColClass[f]+'"'+this._addStatus(f,c,a.id,S,d)+'>'+R(bs)+'</td>':'');for(var Z=0;Z<7;Z++){var bu=(N?N.apply((a.input?a.input[0]:null),[bs]):[true,'']);var bv=(bs.getMonth()!=v);var bw=(bv&&!P)||!bu[0]||(t&&bs<t)||(u&&bs>u);var bx=(this._get(a,'rangeSelect')&&a.dates[0]&&bs.getTime()>=a.dates[0].getTime()&&bs.getTime()<=(a.dates[1]||a.dates[0]).getTime());for(var i=0;i<a.dates.length;i++)bx=bx||(a.dates[i]&&bs.getTime()==a.dates[i].getTime());var by=bv&&!O;G+='<td class="'+this._dayClass[f]+((Z+H+6)%7>=5?' '+this._weekendClass[f]:'')+(bv?' '+this._otherMonthClass[f]:'')+((bs.getTime()==Y.getTime()&&v==a.cursorDate.getMonth()&&a.keyEvent)||(V.getTime()==bs.getTime()&&V.getTime()==Y.getTime())?' '+$.datepick._dayOverClass[f]:'')+(bw?' '+this._unselectableClass[f]:' '+this._selectableClass[f])+(by?'':' '+bu[1]+(bx?' '+this._selectedClass[f]:'')+(bs.getTime()==b.getTime()?' '+this._todayClass[f]:''))+'"'+(!by&&bu[2]?' title="'+bu[2]+'"':'')+(bw?'':' onmouseover="'+'jQuery.datepick._doMouseOver(this,\''+a.id+'\','+bs.getTime()+')"'+' onmouseout="jQuery.datepick._doMouseOut(this,\''+a.id+'\')"'+' onclick="jQuery.datepick._selectDay(this,\'#'+a.id+'\','+bs.getTime()+')"')+'>'+(by?' ':(bw?bs.getDate():'<a>'+bs.getDate()+'</a>'))+'</td>';bs.setDate(bs.getDate()+1);bs=this._daylightSavingAdjust(bs)}G+='</tr>'}v++;if(v>11){v=0;w++}G+='</tbody></table></div>'}if(f)G+='<div class="'+this._newRowClass[f]+'"></div>'}G+=(c?'<div style="clear: both;"></div><div id="'+this._statusId[f]+a.id+'" class="'+this._statusClass[f]+'">'+d+'</div>':'')+(!k&&!a.inline?h:'')+'<div style="clear: both;"></div>'+($.browser.msie&&parseInt($.browser.version,10)<7&&!a.inline?'<iframe src="javascript:false;" class="'+this._coverClass[f]+'"></iframe>':'');a.keyEvent=false;return G},_generateMonthYearHeader:function(a,b,c,d,e,f,g,h,i,j,k){var l=this._daylightSavingAdjust(new Date(c,b,1));d=(d&&l<d?l:d);var m=this._get(a,'changeMonth');var n=this._get(a,'changeYear');var o=this._get(a,'showMonthAfterYear');var p='<div class="'+this._monthYearClass[h]+'">';var q='';if(g||!m)q+='<span class="'+this._monthClass[h]+'">'+k[b]+'</span>';else{var r=(d&&d.getFullYear()==c);var s=(e&&e.getFullYear()==c);q+='<select class="'+this._monthSelectClass[h]+'" '+'onchange="jQuery.datepick._selectMonthYear(\'#'+a.id+'\', this, \'M\');" '+'onclick="jQuery.datepick._clickMonthYear(\'#'+a.id+'\');"'+this._addStatus(h,i,a.id,this._get(a,'monthStatus'),j)+'>';for(var t=0;t<12;t++){if((!r||t>=d.getMonth())&&(!s||t<=e.getMonth()))q+='<option value="'+t+'"'+(t==b?' selected="selected"':'')+'>'+k[t]+'</option>'}q+='</select>'}if(!o)p+=q+(g||!m||!n?' ':'');if(g||!n)p+='<span class="'+this._yearClass[h]+'">'+c+'</span>';else{var u=this._get(a,'yearRange').split(':');var v=0;var w=0;if(u.length!=2){v=c-10;w=c+10}else if(u[0].charAt(0)=='+'||u[0].charAt(0)=='-'){v=c+parseInt(u[0],10);w=c+parseInt(u[1],10)}else{v=parseInt(u[0],10);w=parseInt(u[1],10)}v=(d?Math.max(v,d.getFullYear()):v);w=(e?Math.min(w,e.getFullYear()):w);p+='<select class="'+this._yearSelectClass[h]+'" '+'onchange="jQuery.datepick._selectMonthYear(\'#'+a.id+'\', this, \'Y\');" '+'onclick="jQuery.datepick._clickMonthYear(\'#'+a.id+'\');"'+this._addStatus(h,i,a.id,this._get(a,'yearStatus'),j)+'>';for(;v<=w;v++){p+='<option value="'+v+'"'+(v==c?' selected="selected"':'')+'>'+v+'</option>'}p+='</select>'}p+=this._get(a,'yearSuffix');if(o)p+=(g||!m||!n?' ':'')+q;p+='</div>';return p},_addStatus:function(a,b,c,d,e){return(b?' onmouseover="jQuery(\'#'+this._statusId[a]+c+'\').html(\''+(d||e)+'\');" '+'onmouseout="jQuery(\'#'+this._statusId[a]+c+'\').html(\''+e+'\');"':'')},_adjustInstDate:function(a,b,c){var d=a.drawYear+'/'+a.drawMonth;var e=a.drawYear+(c=='Y'?b:0);var f=a.drawMonth+(c=='M'?b:0);var g=Math.min(a.cursorDate.getDate(),this._getDaysInMonth(e,f))+(c=='D'?b:0);a.cursorDate=this._restrictMinMax(a,this._daylightSavingAdjust(new Date(e,f,g)));a.drawMonth=a.cursorDate.getMonth();a.drawYear=a.cursorDate.getFullYear();if(d!=a.drawYear+'/'+a.drawMonth)this._notifyChange(a)},_restrictMinMax:function(a,b){var c=this._getMinMaxDate(a,'min',true);var d=this._getMinMaxDate(a,'max');b=(c&&b<c?new Date(c.getTime()):b);b=(d&&b>d?new Date(d.getTime()):b);return b},_notifyChange:function(a){var b=this._get(a,'onChangeMonthYear');if(b)b.apply((a.input?a.input[0]:null),[a.cursorDate.getFullYear(),a.cursorDate.getMonth()+1,this._daylightSavingAdjust(new Date(a.cursorDate.getFullYear(),a.cursorDate.getMonth(),1)),a])},_getNumberOfMonths:function(a){var b=this._get(a,'numberOfMonths');return(b==null?[1,1]:(typeof b=='number'?[1,b]:b))},_getMinMaxDate:function(a,b,c){var d=this._determineDate(a,this._get(a,b+'Date'),null);var e=this._getRangeMin(a);return(c&&e&&(!d||e>d)?e:d)},_getRangeMin:function(a){return(this._get(a,'rangeSelect')&&a.dates[0]&&!a.dates[1]?a.dates[0]:null)},_getDaysInMonth:function(a,b){return 32-new Date(a,b,32).getDate()},_getFirstDayOfMonth:function(a,b){return new Date(a,b,1).getDay()},_canAdjustMonth:function(a,b,c,d){var e=this._getNumberOfMonths(a);var f=this._daylightSavingAdjust(new Date(c,d+(b<0?b:e[0]*e[1]),1));if(b<0)f.setDate(this._getDaysInMonth(f.getFullYear(),f.getMonth()));return this._isInRange(a,f)},_isInRange:function(a,b){var c=this._getRangeMin(a)||this._getMinMaxDate(a,'min');var d=this._getMinMaxDate(a,'max');return((!c||b>=c)&&(!d||b<=d))},_getFormatConfig:function(a){return{shortYearCutoff:this._get(a,'shortYearCutoff'),dayNamesShort:this._get(a,'dayNamesShort'),dayNames:this._get(a,'dayNames'),monthNamesShort:this._get(a,'monthNamesShort'),monthNames:this._get(a,'monthNames')}},_formatDate:function(a,b,c,d){if(!b)a.dates[0]=new Date(a.cursorDate.getTime());var e=(b?(typeof b=='object'?b:this._daylightSavingAdjust(new Date(b,c,d))):a.dates[0]);return this.formatDate(this._get(a,'dateFormat'),e,this._getFormatConfig(a))}});function extendRemove(a,b){$.extend(a,b);for(var c in b)if(b[c]==null||b[c]==undefined)a[c]=b[c];return a};function isArray(a){return(a&&a.constructor==Array)};$.fn.datepick=function(a){var b=Array.prototype.slice.call(arguments,1);if(typeof a=='string'&&(a=='isDisabled'||a=='getDate'||a=='settings'))return $.datepick['_'+a+'Datepick'].apply($.datepick,[this[0]].concat(b));if(a=='option'&&arguments.length==2&&typeof arguments[1]=='string')return $.datepick['_'+a+'Datepick'].apply($.datepick,[this[0]].concat(b));return this.each(function(){typeof a=='string'?$.datepick['_'+a+'Datepick'].apply($.datepick,[this].concat(b)):$.datepick._attachDatepick(this,a)})};$.datepick=new Datepick();$(function(){$(document).mousedown($.datepick._checkExternalClick).find('body').append($.datepick.dpDiv)})})(jQuery);(function($){$.datepick.regional['en-GB']={clearText:'Clear',clearStatus:'Erase the current date',closeText:'Done',closeStatus:'Close without change',prevText:'Prev',prevStatus:'Show the previous month',prevBigText:'<<',prevBigStatus:'Show the previous year',nextText:'Next',nextStatus:'Show the next month',nextBigText:'>>',nextBigStatus:'Show the next year',currentText:'Today',currentStatus:'Show the current month',monthNames:['January','February','March','April','May','June','July','August','September','October','November','December'],monthNamesShort:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],monthStatus:'Show a different month',yearStatus:'Show a different year',weekHeader:'Wk',weekStatus:'Week of the year',dayNames:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],dayNamesShort:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],dayNamesMin:['Su','Mo','Tu','We','Th','Fr','Sa'],dayStatus:'Set DD as first week day',dateStatus:'Select DD, M d',dateFormat:'dd/mm/yy',firstDay:1,initStatus:'Select a date',isRTL:false,showMonthAfterYear:false,yearSuffix:''};$.datepick.setDefaults($.datepick.regional['en-GB']);})(jQuery);

//all-pages.js

	var day = new Array(7);
	day[0]  = 'Sunday';
	day[1]  = 'Monday';
	day[2]  = 'Tuesday';
	day[3]  = 'Wednesday';
	day[4]  = 'Thursday';
	day[5]  = 'Friday';
	day[6]  = 'Saturday';

	var short_day = new Array(7);
	short_day[0]  = 'Sun';
	short_day[1]  = 'Mon';
	short_day[2]  = 'Tue';
	short_day[3]  = 'Wed';
	short_day[4]  = 'Thu';
	short_day[5]  = 'Fri';
	short_day[6]  = 'Sat';
	
	var month = new Array(12);
	month[0]  = 'January';
	month[1]  = 'February';
	month[2]  = 'March';
	month[3]  = 'April';
	month[4]  = 'May';
	month[5]  = 'June';
	month[6]  = 'July';
	month[7]  = 'August';
	month[8]  = 'September';
	month[9]  = 'October';
	month[10] = 'November';
	month[11] = 'December';
	
	var short_month = new Array(12);
	short_month[0]  = 'Jan';
	short_month[1]  = 'Feb';
	short_month[2]  = 'Mar';
	short_month[3]  = 'Apr';
	short_month[4]  = 'May';
	short_month[5]  = 'Jun';
	short_month[6]  = 'Jul';
	short_month[7]  = 'Aug';
	short_month[8]  = 'Sep';
	short_month[9]  = 'Oct';
	short_month[10] = 'Nov';
	short_month[11] = 'Dec';
	
	var max_right = 0;
	
$(document).ready(function(){
	
	if ($('#fp-pic-mover').length > 0) {
		
		$('#fp-pic-mover').find('.viewport').css('height', picMoverHeight);
		
		$('#fp-pic-mover').find('li').each(function() {
			$(this).css('height', picMoverHeight);
		});
		
		$('#fp-pic-mover').tinycarousel({ pager: false, controls: false, duration: 3000, intervaltime: 10000, interval: true });
		$('#fp-slider-code').tinycarousel({ pager: true, controls: false, duration: 3000, intervaltime: 10000, interval: true, axis: 'x' });
		
	} else if ($('#fp-slider-code').length > 0) { // my plane mad at the minute
		$('#fp-slider-code').tinycarousel({ pager: true, controls: false, interval: false, axis: 'x' });
	}
	
	// Menu
	if ($('ul#tabs').length > 0) {
		max_right = $('ul#tabs').offset().left + $('ul#tabs').outerWidth();
	}
	
	function hide_sub_menu(obj) {
		$(obj).find('ul.sub-links').slideUp('slow');
	}
	
	$('li.main-link').hover(
		function() {
			if ($(this).find('ul.sub-links').length == 1) {
				var ul_pos   = $(this).closest('ul#tabs').offset();
				var li_pos   = $(this).offset();
				var pos_top  = ul_pos.top + $(this).closest('ul#tabs').outerHeight() - $(window).scrollTop();
				var pos_left = li_pos.left;
				var pos_right = pos_left + $(this).find('ul.sub-links').outerWidth();
				
				// Make sure it does not overhang the edge of the main content box
				if (pos_right > max_right) {
					pos_left = max_right - $(this).find('ul.sub-links').outerWidth();
				}
				
				$(this).find('ul.sub-links').css('top', pos_top);
				$(this).find('ul.sub-links').css('left', pos_left);
				$(this).find('ul.sub-links').slideDown('fast');
			}
		}, function() {
			var obj = $(this);
			var t = setTimeout(function(){$(obj).find('ul.sub-links').css('display', 'none');}, 250);
			
		}
	);
	
	$('li.sub-link').hover(
		function() {
			if ($(this).find('ul.third-tier-links').length == 1) {
				var li_pos   = $(this).offset();
				var pos_top  = li_pos.top - (1 + $(window).scrollTop());
				var pos_left = li_pos.left + $(this).outerWidth();
				var pos_right = pos_left + $(this).find('ul.third-tier-links').outerWidth();
				
				// Make sure it does not overhang the edge of the main content box
				if (pos_right > max_right) {
					pos_left = li_pos.left - $(this).outerWidth();
				}
				
				$(this).find('ul.third-tier-links').css('top', pos_top);
				$(this).find('ul.third-tier-links').css('left', pos_left);
				$(this).find('ul.third-tier-links').slideDown('fast');
			}
		}, function() {
			var obj = $(this);
			var t = setTimeout(function(){$(obj).find('ul.third-tier-links').css('display', 'none');}, 250);
			
		}
	);
	// Login form
	$('#login-link').click(function() {
		$.blockUI({ message: $('#login-form'),
					css: { 
	            		border: '3px solid #8B91AB'
	            		}  });
	            		
		return false;
	});
	
	$('div#login-form form').submit(function() {
		if (valid_login_form()) {
			var ajax_msg = 'username='+escape($('[name="username"]').val())+'&pm-pass-submit='+escape($('[name="pm-pass-submit"]').val());
			
		} else {
			return false;
		}
	});
	
	$('.as-link').live('mouseover', function() {
		$(this).css({'cursor':'pointer'});
	});
	
	$('.as-link').live('mouseout', function() {
		$(this).css({'cursor':'auto'});
	});
	
	// Textarea styling code
	$('.style-post').hover(
		function() {
			$(this).css({'cursor':'pointer'}); //'background-color': '#D3D9E2'
		},
		function() {
			$(this).css({'cursor':'auto'});
		}
	);
	
	// Textarea styling code
	$('.smiley-select').hover(
		function() {
			$(this).css({'cursor':'pointer'}); //'background-color': '#D3D9E2'
		},
		function() {
			$(this).css({'cursor':'auto'});
		}
	);
	
	// Bold text
	$('.style-bold').click(function() {
		var input_textarea = $(this).closest('div').find('textarea.style-input');
		var sel_text       = input_textarea.getSelection().text;
		
		if ((sel_text == '') || (sel_text == undefined)) {
			alert('Please select the text within your post that you would like to make bold and then hit this button again.');
			return false;
		}
		
		input_textarea.replaceSelection('[b]'+sel_text+'[/b]');
		return true;
	});
	
	// Italic text
	$('.style-italic').click(function() {
		var input_textarea = $(this).closest('div').find('textarea.style-input');
		var sel_text       = input_textarea.getSelection().text;
		
		if ((sel_text == '') || (sel_text == undefined)) {
			alert('Please select the text within your post that you would like to make italic and then hit this button again.');
			return false;
		}
		
		input_textarea.replaceSelection('[i]'+sel_text+'[/i]');
		return true;
	});
	
	// Plane Mad Photo
	$('.style-pmpic').click(function() {
		$(this).closest('div').find('div.pmpic').slideDown('slow');
		$(this).parent().find('[name="pmpic"]').focus();
	});
	
	// Plane Mad Rejected Photo
	$('.style-rejpic').click(function() {
		$(this).closest('div').find('div.rejpic').slideDown('slow');
		$(this).parent().find('[name="rejectpic"]').focus();
	});
	
	// Other hosted Photo
	$('.style-hostpic').click(function() {
		$(this).closest('div').find('div.hostpic').slideDown('slow');
		$(this).parent().find('[name="urlpic"]').focus();
	});
	
	// Video
	$('.style-vid').click(function() {
		$(this).closest('div').find('div.vid').slideDown('slow');
		$(this).parent().find('[name="video"]').focus();
	});
	
	// Descriptive Link
	$('.style-link').click(function() {
		$(this).closest('div').find('div.link').slideDown('slow');
		$(this).parent().find('[name="link-url"]').focus();
	});
	
	// Smileys
	$('.style-smiley').click(function() {
		$(this).closest('div').find('div.smiley').slideDown('slow');
	});
	
	$('.smiley-select').click(function() {
		
		var code = '';
		
		switch ($(this).attr('alt')) {
			case 'happy':
				code = ':)';
			break;
			
			case 'sad':
				code = ':(';
			break;
			
			case 'off topic':
				code = ':-ot';
			break;
			
			case 'sorry':
				code = ':-sorry';
			break;
			
			case 'ban':
				code = ':-ban';
			break;
			
			case 'censored':
				code = ':-censored';
			break;
			
			case 'big grin':
				code = ':D';
			break;
			
			case 'cry':
				code = ':\'(';
			break;
			
			case 'shocked':
				code = ':o';
			break;
			
			case 'confused':
				code = ':S';
			break;
			
			case 'angry':
				code = ':@';
			break;
			
			case 'tongue out':
				code = ':P';
			break;
			
			case 'rolling eyes':
				code = '8-)';
			break;
			
			case 'laughing':
				code = ':L';
			break;
		}
		
		$(this).parent().parent().find('textarea.style-input').insertAtCaretPos(code);
	});
	
	$('.shortcut-submit').click(function(){
		
		var textarea_value = '';
		//$(this).parent().find('.shortcut-input').focus();
		
		switch ($(this).attr('name')) {
			// Plane Mad photo gallery pic
			case 'sbt-pmpic':
				var photo_id = $(this).parent().find('[name="pmpic"]').val();
				
				if (photo_id == '') {
					alert('Please enter a photo ID. The ID can be found above the photograph in our photo gallery.');
					return false;
				}
				
				textarea_value = '[photo='+photo_id+']';
			break;
			
			// Plane Mad rejected pic
			case 'sbt-rejectpic':
				var photo_id = $(this).parent().find('[name="rejectpic"]').val();
				
				if (photo_id == '') {
					alert('Please enter a photo ID. The ID can be found in the rejection e-mail you received.');
					return false;
				}
				
				textarea_value = '[reject='+photo_id+']\n';
			break;
			
			// Externally hosted image
			case 'sbt-urlpic':
				var pic_url = $(this).parent().find('[name="urlpic"]').val();
				
				if (pic_url == '') {
					alert('Please enter the URL of the photo you would like to embed into the post.');
					return false;
				}
				
				var place     = $(this).parent().find('input:radio[name="place"]:checked').val();
				var placeCode = (place == 'center') ? '' : ':'+place;
				
				textarea_value = '[img'+placeCode+']http://'+pic_url+'[/img]';
			break;
			
			// Video
			case 'sbt-video':
				var vid_url = $(this).parent().find('[name="video"]').val();
				
				if (vid_url == '') {
					alert('Please enter the URL of the video you would like to embed into the post.');
					return false;
				}
				
				textarea_value = 'http://'+vid_url+'\n';
			break;
			
			// Descriptive Link
			case 'sbt-link':
				var link_url  = $(this).parent().find('[name="link-url"]').val();
				var link_desc = $(this).parent().find('[name="link-desc"]').val();
				
				if (vid_url == '') {
					alert('Please enter the URL and description for the link you would like to include in your post.');
					return false;
				}
				
				textarea_value = '[link=http://'+link_url+']'+link_desc+'[/link]\n';
			break;
		}
		
		$(this).parent().parent().find('textarea.style-input').insertAtCaretPos(textarea_value);
		cancel_shortcut($(this));
		return true;
	});

	
	// All cancels
	$('.shortcut-cancel').click(function() {
		cancel_shortcut($(this));
	});
	
	// To cancel all shortcuts
	function cancel_shortcut(input_obj) {
		input_obj.parent().find('.shortcut-input').val('');
		input_obj.closest('div').slideUp('slow');
	}
	
	// Show the preview
	$('.preview-button').click(function() {
		
		$(this).after('<div id="preview-wait">'+wait_img+'</div>');		
		var input_text = $(this).closest('form').find('.style-input').val();
		
		if (input_text == '') {
			alert('Please enter a message before clicking preview.');
			return false;
		}
		
		var msg_el     = $(this).closest('div').find('.post-preview');
		$(msg_el).find('.preview-text').html(wait_img_code);
				
        submit_ajax('msg='+escape(input_text), $(msg_el).find('.preview-text'), 'http://www.plane-mad.com/preview-post.php');
	});
	
	$('.preview-close').click(function() {
		$.unblockUI();
	});
	
	$('.preview-submit').click(function() {
		$.unblockUI();
		$(this).closest('form').submit();
	});
	
	// Radio / Checkbox button highlighting
	$('input:checked').each(function() {
		var tag_id = $(this).attr('id');
		$(this).parent().find('label[for="'+tag_id+'"]').addClass('bold');
	});
	
	$('input:radio').click(function() {
		highlight_selected($(this));
	});
	
	$('input:checkbox').click(function() {
		highlight_selected($(this));
	});
	
	// Pop-up close button
	$('.pop-close').attr('title','Close this window').click($.unblockUI);

	// PM Links
	$('.pm-link').live('click', function() {
		
		if ($(this).attr('title') == 'Send new PM') {
			$('div#new-pm-form').find('div#find-user').removeClass('invisible');
			$('span#new-pm-header').html('Send New PM');
		} else {
			// User specific PM
			
			var user = $(this).attr('title').replace("PM ", "");
			
			$('#new-pm-username').val(user);
			$('#new-pm-header').html('Private Message '+user);
			
			var msg_title    = '';
			
			//Not user specific
			if ($(this).closest('#pm-container').find('.pm-title').length > 0) {
				
				var msg_title_el = $(this).closest('#pm-container').find('.pm-title');
				
				if (msg_title_el.html().match('Re:') != null) {
					msg_title = msg_title_el.html();
				} else {
					msg_title = 'Re: '+msg_title_el.html();
				}
				
				$('#pm-user-form').find('[name="subject"]').val(msg_title);
			}
		}
		
		$.blockUI({ message: $('#new-pm-form'),
					css: { border: '1px solid #8395ad',
							'-moz-border-radius': '3px',
							'-webkit-border-radius': '3px'
						 }
				}); 
				
		return false; // cancel any links
	});

	$('.edit-link').click(function() {
		var clicked_el = $(this);
		
		if (clicked_el.closest('div.edit-master').find('div.current-text:first').length > 0) {
			clicked_el.closest('div.edit-master').find('div.current-text:first').slideUp('slow', function() {
				clicked_el.closest('div.edit-master').find('div.edit-box:first').slideDown('slow', function() {
				
				if (clicked_el.closest('div.edit-master').find('.spot-sel-map').length > 0) {
					start_edit_map(clicked_el.closest('div.edit-master').find('.spot-sel-map'));
				}
			
				});
			});
		} else {
			clicked_el.closest('div.edit-master').find('div.edit-box:first').slideDown('slow');
		}
		
		return false;
	});
	
	$('[name="edit-cancel"]').click(function() {
		var clicked_el = $(this);
		
		if (clicked_el.closest('div.edit-master').find('div.current-text:first').length > 0) {
			clicked_el.closest('div.edit-master').find('div.edit-box:first').slideUp('slow', function() {
				clicked_el.closest('div.edit-master').find('div.current-text:first').slideDown('slow');
			});
		} else {
			clicked_el.closest('div.edit-master').find('div.edit-box:first').slideUp('slow');
		}
	});
	
	$('a.airline-pulldown').click(function() {
		$('div#common-menus').find('select[name="airline"]').clone().insertAfter(this);
	});
	
	$('#pm-find-user').click(function() {
		
		var div_container = $(this).closest('div#find-user');
		var submit_data   = 'action=find-user&query='+div_container.find('[name="find-user"]').val();
		
		div_container.find('#pm-find-user').addClass('invisible');
		div_container.find('div.find-user-results').html(wait_img_small);
		
		submit_ajax(submit_data, div_container, '');
	});
	
	$('img.sec-expand').click(function() {
		var outer_box = $(this).closest('div.box');
		
		$(this).addClass('invisible');
		outer_box.find('img.sec-collapse').removeClass('invisible');
		outer_box.find('div.sec-content').slideDown('slow');
	});
	
	$('img.sec-collapse').click(function() {
		var outer_box = $(this).closest('div.box');
		
		$(this).addClass('invisible');
		outer_box.find('img.sec-expand').removeClass('invisible');
		outer_box.find('div.sec-content').slideUp('slow');
	});
	
	$('li.tab-link').live('click', function() {
		if ($(this).hasClass('tab-active')) {
			return true;
		}
		
		var main_tab_div = $(this).closest('div.tabs');
		
		main_tab_div.find('div.tab-content').each(function() {
			if (!$(this).hasClass('invisible')) {
				$(this).addClass('invisible');
			}
		});
		
		main_tab_div.find('li.tab-link').each(function() {
			if ($(this).hasClass('tab-active')) {
				$(this).removeClass('tab-active');
			}
		});
		
		var show_content_id = $(this).find('span').attr('class');
		$(this).closest('div.tabs').find('div#'+show_content_id).removeClass('invisible');
		$(this).addClass('tab-active');
	});
	
	$('form.mail-list').submit(function() {
		var problems = '';
		
		if ($(this).find('[name="pm-mail-e-mail"]').val() == '') {
			problems += 'Please enter your e-mail address\n';
			$(this).find('[name="pm-mail-e-mail"]').addClass('submit-error');
		}
		
		if (($(this).find('[name="name"]').length == 1) && ($(this).find('[name="name"]').val() == '')) {
			problems += 'Please enter a name\n';
			$(this).find('[name="name"]').addClass('submit-error');
		}
		
		if ((!$(this).find('[name="daily"]').is(':checked')) && (!$(this).find('[name="weekly"]').is(':checked'))) {
			problems += 'Please choose at least one mail list\n';
			$(this).find('[name="daily"]').addClass('submit-error');
			$(this).find('[name="weekly"]').addClass('submit-error');
		}
		
		if (problems != '') {
			alert(problems);
			return false;
		} else {
			return true;
		}
	});
	
	$('form#contact-form').submit(function() {
		var problem = '';
		
		if ($(this).find('[name="name"]').val() == '') {
			problem += 'Please enter a name\n';
			$(this).find('[name="name"]').addClass('submit-error');
		}
		
		if ($(this).find('[name="email"]').val() == '') {
			problem += 'Please enter an e-mail address\n';
			$(this).find('[name="email"]').addClass('submit-error');
		}
		
		if ($(this).find('[name="message"]').val() == '') {
			problem += 'Please enter a message to send\n';
			$(this).find('[name="message"]').addClass('submit-error');
		}
		
		if (problem != '') {
			alert(problem);
			return false;
		} else {
			return true;
		}
	});
	
	// pre load image for please wait
	pic1 = new Image(34,34); 
	pic1.src = 'http://www.plane-mad.com/pictures/please-wait.gif';
	
	pic2 = new Image(16,11); 
	pic2.src = 'http://www.plane-mad.com/pictures/please-wait-small.gif';

	// Auto submit AJAX forms
    $('form').bind('submit', function (e) {
    	return submitForm($(this));
	});
	
	$('span.screen-edit-link').click(function() {
		var master   = $(this).closest('div.edit-master');
		var editType = master.find('[name="edit-type"]').val();
		var editVal  = master.find('[name="edit-value"]').val();
		var menuObj  = master.find('div.pulldown-menu');
		
		switch (editType) {
			case 'airline':
				insertPulldown('airline', menuObj, editVal, false);
			break;
			
			case 'aircraft':
				insertPulldown('aircraft', menuObj, editVal, false);
			break;
			
			case 'airport':
				insertPulldown('airport', menuObj, editVal, false);
			break;
		}
	});
	
	if ($('[name="date-taken"]').length > 0) {
		$('[name="date-taken"]').datepick();
	}
	
	$('div.pulldowninsert').each(function() {
		var showError = ($(this).find('[name="insert-error"]').val() == 'true') ? true : false;
		var errMes    = ($(this).find('[name="insert-err-mes"]').length == 1) ? $(this).find('[name="insert-err-mes"]').val() : '';
		insertPulldown($(this).find('[name="insert-type"]').val(), $(this), $(this).find('[name="insert-value"]').val(), showError, errMes);
	});
	
	$('input[name="site-search-type"]').click(function() {
		var searchType = $(this).val();
		var formAction, formMethod, textName;
		
		switch(searchType) {
			case 'plane-mad':
				formAction = 'http://www.plane-mad.com/site-search.html';
				formMethod = 'get';
				textName   = 'q';
			break;
			
			case 'photo':
				formAction = 'http://www.plane-mad.com/aviation-photos/search/page1.html';
				formMethod = 'post';
				textName   = 'search-query';
			break;
			
			case 'guides':
				formAction = 'http://www.plane-mad.com/airport-spotting-guides/search.html';
				formMethod = 'post';
				textName   = 'search-q';
			break;
			
			case 'weather':
				formAction = 'http://www.plane-mad.com/airport-weather/search.html';
				formMethod = 'post';
				textName   = 'search-q';
			break;
			
			case 'airlines':
				formAction = 'http://www.plane-mad.com/airlines/';
				formMethod = 'post';
				textName   = 'q';
				$('form#cse-search-box').find('input[name="search-field"]').val('name');
			break;
			
			case 'forums':
				formAction = 'http://www.plane-mad.com/forums/search.html';
				formMethod = 'post';
				textName   = 'search-term';
				$('form#cse-search-box').find('input[name="search-field"]').val('post');
			break;
		}
		
		$('form#cse-search-box').attr('Action', formAction); // Must be capital A - jQuery bug
		$('form#cse-search-box').attr('method', formMethod);
	
		$('input#search-query').attr('name', textName);
	});
	
	if ($('#hotel-checkin').length > 0) {
		$('#hotel-checkin').datepick({dateFormat: $.datepick.ATOM});
		$('#hotel-checkout').datepick({dateFormat: $.datepick.ATOM});
	}
	
	$('form#airport-hotel-search').submit(function() {
		return validateHotelForm($(this));
	});
});

	function insertPulldown(name, objToInsert, selectedVal, showError, errorMessage) {
		var newMenu = $('div#hidden-pulldown').find('select[name="'+name+'"]').clone();
		objToInsert.html(newMenu);
		objToInsert.find('select[name="'+name+'"]').val(selectedVal);
		
		if (showError) {
			objToInsert.find('select[name="'+name+'"]').addClass('error');
			
			if (errorMessage != '') {
				objToInsert.find('select[name="'+name+'"]').after('<br /><b class="red">'+errorMessage+'</b>');
			}
		}
		
	}

	function ajax_success(obj, msg) {
		// forum full message fetching
		$('#preview-wait').remove();
		
		if ($(obj).hasClass('prev-msg')) {
			show_full_msg(obj, msg);
		} else if ($(obj).hasClass('forum-posts-link')) {
			//alert('no post links');
			show_all_msgs(obj, msg);
		} else if ($(obj).hasClass('preview-text')) {
			$(obj).html(msg.full_post);
			
			$.blockUI({ message: $(obj).closest('div.post-preview'),
					css: { 
	            		'border': '3px solid #8B91AB',
	            		'height': '80%',
	            		'overflow': 'auto',
	            		'top': '10%',
	            		'width': '674px'
	            		}  });
	            
		} else if ($(obj).is('#user-avail-res')) {
			$(obj).html(msg.msg);
			
			if (msg.success == 'false') {
				input_error($('[name="register-username"]'));
				$('[name="register-username"]').focus();
			}
		} else if ($(obj).hasClass('screen-info')) {
			show_change_photo(obj, msg);
		} else if ($(obj).is('div.discuss-form')) {
			show_add_screener_comments(obj, msg);
		} else if ($(obj).is('#box-private-messages')) {
			show_pm_request(obj, msg);
		} else if ($(obj).is('div.mypm-section-code')) {
			show_new_mypm_data(obj, msg);
		} else if ($(obj).hasClass('mypm-add-section')) {
			show_new_mypm_section(obj, msg);
		} else if ($(obj).is('div#find-user')) {
			show_find_user(obj, msg);
		} else if (($(obj).hasClass('pm-inbox')) || ($(obj).hasClass('pm-msg'))) {
			show_del_msgs(obj, msg);
		} else if ($(obj).hasClass('photo-table')) {
			show_add_album(obj, msg);
		} else if ($(obj).hasClass('edit-album-pic')) {
			show_album_img(obj, msg);
		} else if ($(obj).hasClass('photo-correction')) {
			show_correction_res(obj, msg);
		} else if ($(obj).is('#comment-section')) {
			show_comment_page(obj, msg);	
		} else if ($(obj).hasClass('tag-suggestion')) {
			show_tag_suggest_res(obj, msg);
		} else if ($(obj).hasClass('hp-edit-form')) {
			showHpEditSuccess(obj, msg);
		} else if ($(obj).is('img.hp-del')) {
			showHpDelSuccess(obj, msg);	
		} else if ($(obj).is('ul.add-section')) {
			showHpAddSuccess(obj, msg);	
		} else if ($(obj).is('#guide-spot-code')) {
			showGuideSpots(obj, msg);
		} else if ($(obj).is('div.comments-show')) {
			showCommentsPage(obj, msg);
		} else if ($(obj).is('div.left-column')) {
			mpmSettingsSave(obj, msg);
		} else if ($(obj).is('input#airport-icao')) {
			updateMovements(msg);
		}
		
		//alert($(submitted_form).attr('class'));
	}
	
	// return an ajax submittable string of all name value pairs of a form
	function getFormValues(theForm) {
		var postData = '';
		var i        = 0;
		
		theForm.find(':input').each(function (i) {
			if (($(this).attr('type') == 'radio') || ($(this).attr('type') == 'checkbox')) {
				if ($(this).is(':checked')) {
					if (i != 0) {
						postData += '&';
					}
					
					postData += this.name+'='+escape(this.value);
				}
			} else {
				if (i != 0) {
					postData += '&';
				}
				
				// concat {inputName}={inputValue} to our string
				postData += this.name+'='+escape(this.value);
			}
			
			i++;
		});
		
		return postData;
	}
	
	function get_just_num(text_string) {
		return text_string.replace(/[^0-9]+/g, "");
	}
	
	function highlight_selected(obj) {
		var name   = obj.attr('name');
		var obj_id = obj.attr('id');
		
		// For each input with the same name unbold any existing selections
		$(obj).closest('div.box').find(':input[type="radio"]').each(function() {
			var el_id = $(this).attr('id');
			
			if (!$(this).is(':checked')) {
				$(this).parent().find('label[for="'+el_id+'"]').removeClass('bold');
			} else {
				$(this).parent().find('label[for="'+el_id+'"]').addClass('bold');
			}
		});
		
		$(obj).closest('div.box').find(':input[type="checkbox"]').each(function() {
			var el_id = $(this).attr('id');
			
			if (!$(this).is(':checked')) {
				$(this).parent().find('label[for="'+el_id+'"]').removeClass('bold');
			} else {
				$(this).parent().find('label[for="'+el_id+'"]').addClass('bold');
			}
		});
	}
	
	function input_error(obj) {
		obj.addClass('submit-error');
	}
	
	function close_login() {
		$.unblockUI();
	}
	
	function login_response(submitted_form, responseData) {
		$('div#login-results').html(responseData.msg);
		
		if (responseData.success == 'true') {
			location.reload();
		}
	}
	
	function reset_form(submitted_form) {
		$(submitted_form).find('input[type="text"],textarea').each(function() {
			var attr_name = $(this).attr('name');
			
			if (($(submitted_form).find('[name="'+attr_name+'-keep"]').length == 0) || (!$(submitted_form).find('[name="'+attr_name+'-keep"]').is(':checked'))) {
				$(this).val('');
			}
		});
	
	/*
	$(submitted_form).find('input[type="text"]').val('');
	$(submitted_form).find('textarea').val('');
	*/
	}

	function selected_text() {
	
		var user_selection;
		
		if (window.getSelection){
			user_selection = window.getSelection();
		} else if (document.selection) {
			user_selection = document.selection.createRange().text;
		}
		
		return user_selection;
	}
	
	function send_user_pm_reset() {
		$.unblockUI();
		$('#pm-user-form').find('[name="subject"]').val('');
		$('#pm-user-form').find('[name="message"]').val('');
		$('#pm-user-form').find('div.results').html('');
	}
	
	function send_user_pm_response(submitted_form, responseData) {
				
		if (responseData.success == 'true') {
			submitted_form.find('div.results').html(responseData.result);
			
			var t = setTimeout("send_user_pm_reset()", 2000);
		} else {
			submitted_form.find('div.results').html(responseData.result);
		}
	}
	
	function set_cookie(cookie_name, cookie_val, expiredays) {
		if (navigator.cookieEnabled) {
			var exdate=new Date();
			exdate.setDate(exdate.getDate()+expiredays);
			
			document.cookie=cookie_name+ "=" +escape(cookie_val)+ ";expires="+exdate.toUTCString();
		}
	}
	
	function show_find_user(obj, msg) {
		/*
		if (msg.success == 'true') {
			
		} else {
		}
		*/
		obj.find('div.find-user-results').html(msg.output);
		obj.find('#pm-find-user').removeClass('invisible');
	}
	
	function hideSearch() {
		$('div#site-search-form').slideUp('slow');
	}
	
	function show_search() {
		var ul_pos   = $('ul#tabs').offset();
		var pos_top  = ul_pos.top + $('ul#tabs').outerHeight() - $(window).scrollTop();
		var pos_left = ul_pos.left + $('ul#tabs').outerWidth() - $(window).scrollLeft();
		pos_left     = pos_left - $('div#site-search-form').outerWidth();
		//alert(pos_left +' '+pos_top);
		$('div#site-search-form').css('top', pos_top);
		$('div#site-search-form').css('left', pos_left);
		$('div#site-search-form').slideDown('slow');
	}
	
	function submit_ajax(submit_data, obj, action) {
		if (action == '') {
			action = location.href;
		}
		
		 $.ajax({
			  type: "POST",
			  url: action,
			  dataType: "json",
			  data : submit_data,
			  success: function(msg){
			  	ajax_success(obj, msg);
			   },
	           error: function(request, textStatus, errorThrown){
	           		alert(request+' '+textStatus+' '+errorThrown);
				}
			});
	}
	
	function validate_new_pm(submitted_form) {
		if (!submitted_form.find('div#find-user').hasClass('invisible')) {
			$(submitted_form).find('div#find-user').find(':input').each(function (i) {
			
				if (($(this).attr('type') == 'radio') || ($(this).attr('type') == 'checkbox')) {
					if ($(this).is(':checked')) {
						$(submitted_form).find('#new-pm-username').val(this.value);
					}
				} else if (($(this).attr('type') != 'button') && (!$(this).is('[name="find-user"]'))) {
					if (this.value != '') {
						$(submitted_form).find('#new-pm-username').val(this.value);
					}
				}
			});
		}
		
		var error_desc = '';
		
		if ($(submitted_form).find('#new-pm-username').val() == '') {
			error_desc += 'You need to specify a user to send the message to.\n';
		}
		
		if ($(submitted_form).find('[name="subject"]').val() == '') {
			error_desc += 'You need to specify a subject.\n';
		}
		
		if ($(submitted_form).find('[name="message"]').val() == '') {
			error_desc += 'You need to specify a message.\n';
		}
		
		if (error_desc == '') {
			return true;
		} else {
			alert(error_desc);
			return false;
		}
	}
	
	function valid_login_form() {
		var username   = $('[name="username"]').val();
		var login_pass = $('[name="pm-pass-submit"]').val();
		var errors     = '';
		
		if (username == '') {
			errors += 'Please enter a username.\n';
		}
		
		if (!valid_password(login_pass)) {
			errors += 'The password you entered is invalid.\n';
		}
		
		if (errors == '') {
			return true;
		} else {
			alert(errors);
			return false;
		}
	}
	
	function valid_email(email) {
		var emailRegex = new RegExp('^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$');

		return emailRegex.test(email);
	}
	
	function valid_password(pass) {
		if ((pass.length < 6) || (pass.length > 20)) {
			return false;
		} else {
			return true;
		}
	}
	
	//ajax-autosubmit
	// if a form is required to be ajax submitted by default then add the ID here
	var ajaxSubmitForms = new Array('pm-user-form', 'create-album', 'edit-photo-form', 'suggest-tags-form', 'correct-reg', 'airline-edit', 'poll-vote', 'hp-post', 'screeners-choice', 'new-movement');
	var ajaxExclude     = new Array('movements-airport', 'cse-search-box', 'airport-hotel-search');
	var ajaxAllForms    = false;
	var wait_img        = '<img src="http://www.plane-mad.com/pictures/please-wait.gif" alt="Please Wait" /> Loading';
	var wait_img_small  = '<img src="http://www.plane-mad.com/pictures/please-wait-small.gif" alt="Please Wait" /> Loading';
	var wait_img_code   = '<div class="center wait">'+wait_img+'</div>';

	
	/**
	* Find out whether the form is required to be submitted by an ajax request or not
	* @param string formId - HTML form tag id attribute of the form submitted
	* @return boolean true if the form is required to be submitted by ajax, false if not
	*/
	function ajaxSubmit(submitted_form) {
		var numForms   = ajaxSubmitForms.length;
		var i = 0;
		var j = 0;
		
		if (($(submitted_form).is('.comments')) || ($(submitted_form).is('.lhr-rwy')) || ($(submitted_form).is('div#login-form form')) || ($(submitted_form).hasClass('edit-photo-form')) || ($(submitted_form).hasClass('sug-del-comment'))) {
			return true;
		}
		
		// exclude forms
		while (j < numForms) {
			if (ajaxExclude[j] == submitted_form.attr('id')) {
				return false;
			}
			
			j++;
		}
		
		if (ajaxAllForms) {
			return true;
		}
		
		while (i < numForms) {
			if (ajaxSubmitForms[i] == submitted_form.attr('id')) {
				return true;
			}
			
			i++;
		}
		
		return false;
	}
	
	/**
	* Function to be run upon a successful response from the ajax request
	* Add a case statement for each form andthe actions to carry out from the ajax response
	* @param string formId - HTML form tag id attribute of the form submitted
	* @param array responseData - data received from the ajax request - array of values as set withn the PHP script
	*/
	function showAjaxRepsonse(submitted_form, responseData) {
		
		if ($(submitted_form).hasClass('comments')) {
			comments_response(submitted_form, responseData);
		} else if (submitted_form.hasClass('forum-post-edit')) {
			show_post_edit(submitted_form, responseData);
		} else if (submitted_form.hasClass('delete-comment')) {
			show_comment_delete(submitted_form, responseData);
		} else if (submitted_form.hasClass('delete-post')) {
			show_post_delete(submitted_form, responseData);
		} else if ((submitted_form.hasClass('spot-edit')) || (submitted_form.hasClass('guide-notes')) || (submitted_form.hasClass('guide-links')) || (submitted_form.hasClass('guide-freq')) || (submitted_form.hasClass('airline-edit'))) {
			spot_edit_result(submitted_form, responseData);
		} else if (submitted_form.hasClass('lhr-rwy')) {
			show_lhr_rwys(submitted_form, responseData);
		} else if ($(submitted_form).is('div#login-form form')) {
			login_response(submitted_form, responseData);
		} else if (submitted_form.hasClass('report-post')) {
			show_post_report(submitted_form, responseData);
		} else if (submitted_form.hasClass('approve-post')) {
			show_post_report(submitted_form, responseData); // same functions as approve
		} else if ($(submitted_form).is('#pm-user-form')) {
			send_user_pm_response(submitted_form, responseData);
		} else if (submitted_form.hasClass('del-screen-pic')) {
			if (responseData.success == 'true') {
				$(submitted_form).closest('table.photo-table').fadeOut('slow');
			} else {
				$(submitted_form).find('div.results').html(responseData.output);
			}
			
			return;
		} else if (submitted_form.hasClass('form-link-remove')) {
			favLinkRemove(submitted_form, responseData);
			return;
		} else if (submitted_form.is('#poll-vote')) {
			addPollVote(submitted_form, responseData);
		} else if (submitted_form.is('#new-movement')) {
			movementResponse(submitted_form, responseData, 'add');
		} else if (submitted_form.is('.movement-del')) {
			movementResponse(submitted_form, responseData, 'del');
		} else if (submitted_form.is('.edit-movement')) {
			movementResponse(submitted_form, responseData, 'edit');
		}
		
			//alert(responseData.output);
		switch (submitted_form.attr('id')) {
			case 'data-upload':
				$(submitted_form).find('div.results').html(responseData.output);
				reset_upload_form();
			break;
			
			case 'mod-move-forum':
				move_forum(submitted_form, responseData);
			break;
			
			case 'topic-reply':
				show_new_post(submitted_form, responseData);
			break;
			
			case 'create-album':
				create_album_response(submitted_form, responseData);
			break;
			
			case 'edit-photo-form':
				correct_info_results(submitted_form, responseData);
			break;
			
			case 'suggest-tags-form':
				suggest_tags_results(submitted_form, responseData);
			break;
			
			case 'correct-reg':
				correct_reg_info_res(submitted_form, responseData);
			break;
						
			case 'hp-post':
				showHpPostSuccess(submitted_form, responseData);
			break;
			
			case 'banner-settings':
				pmbGetBanner();
				// Want output to go on as well
			// Default behaviour - output - output within the a tag containing class="results" within the submitted form
			default: 
				$(submitted_form).find('div.results').html(responseData.output);
			break;
		
		}
		
		$('.wait').remove();
		$('.ajax-remove').removeClass('invisible');
		return true;
	}
	
	/**
	* Submit the form as an ajax reuest if required and if the form values entered are valid
	* @param string formId - HTML for element id attribute of the form being submitted
	* @return boolean true if the form needs to be submitted as a normal http post request rather than an ajax request
	* @return boolean false if the form should not be submitted as a normal http request
	*/
	function submitForm(submitted_form) {
	
    	// If this form is not required to be autosubmitted then return true so that normal http post request is made instead
    	if (!ajaxSubmit(submitted_form)) {
    		return true;
    	}
    	
    	//alert ('form autosubmitted');
    	// If form values are invalid then return false so that the form is not submitted
    	if (!validateForm(submitted_form)) {
    		return false;
    	}
    	
    	$(submitted_form).find('.ajax-remove').addClass('invisible');
    	$(submitted_form).find('.ajax-remove').after(wait_img_code);
    	
    	// If an action is entered them submit form to that page - otherwise submit form to current page
    	if ($(submitted_form).attr('action') == '') {
    		var submitUrl = location.href;
    	} else {
    		var submitUrl = $(submitted_form).attr('action');
    	}
    	   
    	var postData = '';
    	var j        = 0;
    	    	
    	// for each input type (jQuery input matches against all input, textarea, select and button elements)
    	// build a query string based on the name and values of the form elements
		$(submitted_form).find(':input').each(function (i) {
			
			if (($(this).attr('type') == 'radio') || ($(this).attr('type') == 'checkbox')) {
				if ($(this).is(':checked')) {
					if (j != 0) {
						postData += '&';
					}
					
					postData += this.name+'='+escape(this.value);
				}
			} else {
				if (j != 0) {
					postData += '&';
				}
				
				// concat {inputName}={inputValue} to our string
				postData += this.name+'='+escape(this.value);
			}
			
			j++;
	      });
		
		// Post an ajax request to the current page URL, repsonse type to be JSON and submit the query string built above
		// On success run the showAjaxRepsonse() method, on failure show alert with errors (NEEDS CHANGING BEFORE GOING LIVE)
		$.ajax({
           type: 'POST',
           dataType: 'json',
           url: submitUrl,
           data: postData,
           success: function(response){
				showAjaxRepsonse(submitted_form, response);
			},
           error: function(request, textStatus, errorThrown){
				//alert(request.status+' '+textStatus+' '+errorThrown+' '+request.responseText);
				$('.wait').remove();
				$('.ajax-remove').removeClass('invisible');
			}
           });
           
		// required to prevent form from submitting
		return false;
	}
	
	/*
	* Validate the form which is attempting to be submitted
	* To validate a form add a case statement in this function. Forms without a case statement require no validation
	* @param string id - HTML form tag id attribute of the form being submitted
	* @return boolean true if the form is valid, false if not
	*/
	function validateForm(submitted_form) {
		
		if ($(submitted_form).is('.comments')) {
			return validate_comment_form(submitted_form);
		}
		
		if (submitted_form.hasClass('delete-post')) {
			return confirm('Are you sure you want to delete this post?');
		}
		
		if (submitted_form.hasClass('lhr-rwy')) {
			$('#lhr-rwy-wait').html(wait_img_code);
		}
		
		if (submitted_form.hasClass('del-screen-pic')) {
			return confirm('Are you sure you want to delete this picture from the queue?');
		}
		
		if ($(submitted_form).is('div#login-form form')) {
			return valid_login_form();
		} else if (submitted_form.is('.edit-movement')) {
			return validateMovementForm(submitted_form);
		}
		
		switch(submitted_form.attr('id')) {
			case 'new-movement':
				return validateMovementForm(submitted_form);
			break;
			
			case 'data-upload':
				return upload_success;
			break;
			
			case 'topic-reply':
				return validate_reply();
			break;
			
			case 'pm-user-form':
				return validate_new_pm(submitted_form);
			break;
			
			case 'create-album':
				return validate_album(submitted_form);
			break;
			
			default:
				return true;
			break;
		}
	}
	
	function validateHotelForm(submittedForm) {
		var errors = '';
		
		if ($(submittedForm).find('[name="checkin"]').val() == '') {
			errors += 'Please enter a check-in date.\n';
			$(submittedForm).find('[name="checkin"]').addClass('submit-error');
		}
		
		if ($(submittedForm).find('[name="checkout"]').val() == '') {
			errors += 'Please enter a check-out date.\n';
			$(submittedForm).find('[name="checkout"]').addClass('submit-error');
		}
		
		if (!validMySQLDate($(submittedForm).find('[name="checkin"]').val())) {
			errors += 'Check-in date must be in the format yyyy-mm-dd.\n';
			$(submittedForm).find('[name="checkin"]').addClass('submit-error');
		}
		
		if (!validMySQLDate($(submittedForm).find('[name="checkout"]').val())) {
			errors += 'Check-out date must be in the format yyyy-mm-dd.\n';
			$(submittedForm).find('[name="checkout"]').addClass('submit-error');
		}
		
		if (errors == '') {
			return true;
		} else {
			alert(errors);
			return false;
		}
	}
	
	function validMySQLDate(submittedDate) {
		var pattern = new RegExp('^[0-9]{4}\-[0-9]{2}\-[0-9]{2}$');
		return pattern.test(submittedDate);
	}
	
	function urlString(name) {
		var newName = name.toLowerCase();
		newName = newName.replace(/ +/, '-');
		newName = newName.replace(/[^a-z0-9\(\)\-\_]/, '');
		
		return newName;
	}
