
/**
* Easing
*/
jQuery.extend({
	easing: {
		easein: function(x, t, b, c, d) {
			return c*(t/=d)*t + b; // in
		},
		easeout: function(x, t, b, c, d) {
			return -c*t*t/(d*d) + 2*c*t/d + b;
		},
		bounceout: function(x, t, b, c, d) {
			if ((t/=d) < (1/2.75)) {
				return c*(7.5625*t*t) + b;
			} else if (t < (2/2.75)) {
				return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
			} else if (t < (2.5/2.75)) {
				return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
			} else {
				return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
			}
		},		
		linear: function(x, t, b, c, d) {
			return c*t/d + b; //linear
		}
	}
});

/**
* Cookies
* $.cookie('the_cookie','value'); //to set
* $.cookie('the_cookie'); //to get
*/
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/** BGI Frame function - helps with zIndex issue in MSIE6 **/

(function($){

$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};

})(jQuery);


/*
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-03-27 16:29:43 -0500 (Tue, 27 Mar 2007) $
 * $Rev: 1601 $
 */

jQuery.fn._height = jQuery.fn.height;
jQuery.fn._width  = jQuery.fn.width;

/**
 * If used on document, returns the document's height (innerHeight)
 * If used on window, returns the viewport's (window) height
 * See core docs on height() to see what happens when used on an element.
 *
 * @example $("#testdiv").height()
 * @result 200
 *
 * @example $(document).height()
 * @result 800
 *
 * @example $(window).height()
 * @result 400
 *
 * @name height
 * @type Object
 * @cat Plugins/Dimensions
 */
jQuery.fn.height = function() {
	if ( this[0] == window )
		return self.innerHeight ||
			jQuery.boxModel && document.documentElement.clientHeight ||
			document.body.clientHeight;

	if ( this[0] == document )
		return Math.max( document.body.scrollHeight, document.body.offsetHeight );

	return this._height(arguments[0]);
};

/**
 * If used on document, returns the document's width (innerWidth)
 * If used on window, returns the viewport's (window) width
 * See core docs on height() to see what happens when used on an element.
 *
 * @example $("#testdiv").width()
 * @result 200
 *
 * @example $(document).width()
 * @result 800
 *
 * @example $(window).width()
 * @result 400
 *
 * @name width
 * @type Object
 * @cat Plugins/Dimensions
 */
jQuery.fn.width = function() {
	if ( this[0] == window )
		return self.innerWidth ||
			jQuery.boxModel && document.documentElement.clientWidth ||
			document.body.clientWidth;

	if ( this[0] == document )
		return Math.max( document.body.scrollWidth, document.body.offsetWidth );

	return this._width(arguments[0]);
};

/**
 * Returns the inner height value (without border) for the first matched element.
 * If used on document, returns the document's height (innerHeight)
 * If used on window, returns the viewport's (window) height
 *
 * @example $("#testdiv").innerHeight()
 * @result 800
 *
 * @name innerHeight
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.innerHeight = function() {
	return this[0] == window || this[0] == document ?
		this.height() :
		this.css('display') != 'none' ?
		 	this[0].offsetHeight - (parseInt(this.css("borderTopWidth")) || 0) - (parseInt(this.css("borderBottomWidth")) || 0) :
			this.height() + (parseInt(this.css("paddingTop")) || 0) + (parseInt(this.css("paddingBottom")) || 0);
};

/**
 * Returns the inner width value (without border) for the first matched element.
 * If used on document, returns the document's Width (innerWidth)
 * If used on window, returns the viewport's (window) width
 *
 * @example $("#testdiv").innerWidth()
 * @result 1000
 *
 * @name innerWidth
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.innerWidth = function() {
	return this[0] == window || this[0] == document ?
		this.width() :
		this.css('display') != 'none' ?
			this[0].offsetWidth - (parseInt(this.css("borderLeftWidth")) || 0) - (parseInt(this.css("borderRightWidth")) || 0) :
			this.height() + (parseInt(this.css("paddingLeft")) || 0) + (parseInt(this.css("paddingRight")) || 0);
};

/**
 * Returns the outer height value (including border) for the first matched element.
 * Cannot be used on document or window.
 *
 * @example $("#testdiv").outerHeight()
 * @result 1000
 *
 * @name outerHeight
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.outerHeight = function() {
	return this[0] == window || this[0] == document ?
		this.height() :
		this.css('display') != 'none' ?
			this[0].offsetHeight :
			this.height() + (parseInt(this.css("borderTopWidth")) || 0) + (parseInt(this.css("borderBottomWidth")) || 0)
				+ (parseInt(this.css("paddingTop")) || 0) + (parseInt(this.css("paddingBottom")) || 0);
};

/**
 * Returns the outer width value (including border) for the first matched element.

 * Cannot be used on document or window.
 *
 * @example $("#testdiv").outerWidth()
 * @result 1000
 *
 * @name outerWidth
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.outerWidth = function() {
	return this[0] == window || this[0] == document ?
		this.width() :
		this.css('display') != 'none' ?
			this[0].offsetWidth :
			this.height() + (parseInt(this.css("borderLeftWidth")) || 0) + (parseInt(this.css("borderRightWidth")) || 0)
				+ (parseInt(this.css("paddingLeft")) || 0) + (parseInt(this.css("paddingRight")) || 0);
};

/**
 * Returns how many pixels the user has scrolled to the right (scrollLeft).
 * Works on containers with overflow: auto and window/document.
 *
 * @example $("#testdiv").scrollLeft()
 * @result 100
 *
 * @name scrollLeft
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.scrollLeft = function() {
	if ( this[0] == window || this[0] == document )
		return self.pageXOffset ||
			jQuery.boxModel && document.documentElement.scrollLeft ||
			document.body.scrollLeft;

	return this[0].scrollLeft;
};

/**
 * Returns how many pixels the user has scrolled to the bottom (scrollTop).
 * Works on containers with overflow: auto and window/document.
 *
 * @example $("#testdiv").scrollTop()
 * @result 100
 *
 * @name scrollTop
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.scrollTop = function() {
	if ( this[0] == window || this[0] == document )
		return self.pageYOffset ||
			jQuery.boxModel && document.documentElement.scrollTop ||
			document.body.scrollTop;

	return this[0].scrollTop;
};

/**
 * Returns the location of the element in pixels from the top left corner of the viewport.
 *
 * For accurate readings make sure to use pixel values for margins, borders and padding.
 *
 * @example $("#testdiv").offset()
 * @result { top: 100, left: 100, scrollTop: 10, scrollLeft: 10 }
 *
 * @example $("#testdiv").offset({ scroll: false })
 * @result { top: 90, left: 90 }
 *
 * @example var offset = {}
 * $("#testdiv").offset({ scroll: false }, offset)
 * @result offset = { top: 90, left: 90 }
 *
 * @name offset
 * @param Object options A hash of options describing what should be included in the final calculations of the offset.
 *                       The options include:
 *                           margin: Should the margin of the element be included in the calculations? True by default.
 *                                   If set to false the margin of the element is subtracted from the total offset.
 *                           border: Should the border of the element be included in the calculations? True by default.
 *                                   If set to false the border of the element is subtracted from the total offset.
 *                           padding: Should the padding of the element be included in the calculations? False by default.
 *                                    If set to true the padding of the element is added to the total offset.
 *                           scroll: Should the scroll offsets of the parent elements be included in the calculations?
 *                                   True by default. When true, it adds the total scroll offsets of all parents to the
 *                                   total offset and also adds two properties to the returned object, scrollTop and
 *                                   scrollLeft. If set to false the scroll offsets of parent elements are ignored.
 *                                   If scroll offsets are not needed, set to false to get a performance boost.
 * @param Object returnObject An object to store the return value in, so as not to break the chain. If passed in the
 *                            chain will not be broken and the result will be assigned to this object.
 * @type Object
 * @cat Plugins/Dimensions
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
jQuery.fn.offset = function(options, returnObject) {
	var x = 0, y = 0, elem = this[0], parent = this[0], absparent=false, relparent=false, op, sl = 0, st = 0, options = jQuery.extend({ margin: true, border: true, padding: false, scroll: true }, options || {});
	do {
		x += parent.offsetLeft || 0;
		y += parent.offsetTop  || 0;

		// Mozilla and IE do not add the border
		if (jQuery.browser.mozilla || jQuery.browser.msie) {
			// get borders
			var bt = parseInt(jQuery.css(parent, 'borderTopWidth')) || 0;
			var bl = parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0;

			// add borders to offset
			x += bl;
			y += bt;

			// Mozilla removes the border if the parent has overflow property other than visible
			if (jQuery.browser.mozilla && parent != elem && jQuery.css(parent, 'overflow') != 'visible') {
				x += bl;
				y += bt;
			}
			
			// Mozilla does not include the border on body if an element isn't positioned absolute and is without an absolute parent
			if (jQuery.css(parent, 'position') == 'absolute') absparent = true;
			// IE does not include the border on the body if an element is position static and without an absolute or relative parent
			if (jQuery.css(parent, 'position') == 'relative') relparent = true;
		}

		if (options.scroll) {
			// Need to get scroll offsets in-between offsetParents
			op = parent.offsetParent;
			do {
				sl += parent.scrollLeft || 0;
				st += parent.scrollTop  || 0;

				parent = parent.parentNode;

				// Mozilla removes the border if the parent has overflow property other than visible
				if (jQuery.browser.mozilla && parent != elem && parent != op && jQuery.css(parent, 'overflow') != 'visible') {
					x += parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0;
					y += parseInt(jQuery.css(parent, 'borderTopWidth')) || 0;
				}
			} while (op && parent != op);
		} else
			parent = parent.offsetParent;

		if (parent && (parent.tagName.toLowerCase() == 'body' || parent.tagName.toLowerCase() == 'html')) {
			// Safari and IE Standards Mode doesn't add the body margin for elments positioned with static or relative
			if ((jQuery.browser.safari || (jQuery.browser.msie && jQuery.boxModel)) && jQuery.css(elem, 'position') != 'absolute') {
				x += parseInt(jQuery.css(parent, 'marginLeft')) || 0;
				y += parseInt(jQuery.css(parent, 'marginTop'))  || 0;
			}
			// Mozilla does not include the border on body if an element isn't positioned absolute and is without an absolute parent
			// IE does not include the border on the body if an element is positioned static and without an absolute or relative parent
			if ( (jQuery.browser.mozilla && !absparent) || 
			     (jQuery.browser.msie && jQuery.css(elem, 'position') == 'static' && (!relparent || !absparent)) ) {
				x += parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0;
				y += parseInt(jQuery.css(parent, 'borderTopWidth'))  || 0;
			}
			break; // Exit the loop
		}
	} while (parent);

	if ( !options.margin) {
		x -= parseInt(jQuery.css(elem, 'marginLeft')) || 0;
		y -= parseInt(jQuery.css(elem, 'marginTop'))  || 0;
	}

	// Safari and Opera do not add the border for the element
	if ( options.border && (jQuery.browser.safari || jQuery.browser.opera) ) {
		x += parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0;
		y += parseInt(jQuery.css(elem, 'borderTopWidth'))  || 0;
	} else if ( !options.border && !(jQuery.browser.safari || jQuery.browser.opera) ) {
		x -= parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0;
		y -= parseInt(jQuery.css(elem, 'borderTopWidth'))  || 0;
	}

	if ( options.padding ) {
		x += parseInt(jQuery.css(elem, 'paddingLeft')) || 0;
		y += parseInt(jQuery.css(elem, 'paddingTop'))  || 0;
	}

	// Opera thinks offset is scroll offset for display: inline elements
	if (options.scroll && jQuery.browser.opera && jQuery.css(elem, 'display') == 'inline') {
		sl -= elem.scrollLeft || 0;
		st -= elem.scrollTop  || 0;
	}

	var returnValue = options.scroll ? { top: y - st, left: x - sl, scrollTop:  st, scrollLeft: sl }
	                                 : { top: y, left: x };

	if (returnObject) { jQuery.extend(returnObject, returnValue); return this; }
	else              { return returnValue; }
};

/**
* AUTOCOMPLETE
*/

jQuery.autocomplete = function(input, options) {
	// Create a link to self
	var me = this;

	// Create jQuery object for input element
	var $input = $(input).attr("autocomplete", "off");

	// Apply inputClass if necessary
	if (options.inputClass) $input.addClass(options.inputClass);

	// Create results
	var results = document.createElement("div");
	// Create jQuery object for results
	var $results = $(results);
	$results.hide().addClass(options.resultsClass).css("position", "absolute");
	if( options.width > 0 ) $results.css("width", options.width);

	// Add to body element
	$("body").append(results);

	input.autocompleter = me;

	var timeout = null;
	var prev = "";
	var active = -1;
	var cache = {};
	var keyb = false;
	var hasFocus = false;
	var lastKeyPressCode = null;

	// flush cache
	function flushCache(){
		cache = {};
		cache.data = {};
		cache.length = 0;
	};

	// flush cache
	flushCache();

	// if there is a data array supplied
	if( options.data != null ){
		var sFirstChar = "", stMatchSets = {}, row = [];

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( typeof options.url != "string" ) options.cacheLength = 1;

		// loop through the array and create a lookup structure
		for( var i=0; i < options.data.length; i++ ){
			// if row is a string, make an array otherwise just reference the array
			row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

			// if the length is zero, don't add to list
			if( row[0].length > 0 ){
				// get the first character
				sFirstChar = row[0].substring(0, 1).toLowerCase();
				// if no lookup array for this character exists, look it up now
				if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
				// if the match is a string
				stMatchSets[sFirstChar].push(row);
			}
		}

		// add the data items to the cache
		for( var k in stMatchSets ){
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			addToCache(k, stMatchSets[k]);
		}
	}

	$input
	.keydown(function(e) {
		// track last key pressed
		lastKeyPressCode = e.keyCode;
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 9:  // tab
			case 13: // return
				if( selectCurrent() ){
					// make sure to blur off the current field
					$input.get(0).blur();
					e.preventDefault();
				}
				break;
			default:
				active = -1;
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function(){onChange();}, options.delay);
				break;
		}
	})
	.focus(function(){
		// track whether the field has focus, we shouldn't process any results if the field no longer has focus
		hasFocus = true;
	})
	.blur(function() {
		// track whether the field has focus
		hasFocus = false;
		hideResults();
	});

	hideResultsNow();

	function onChange() {
		// ignore if the following keys are pressed: [del] [shift] [capslock]
		if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
		var v = $input.val();
		if (v == prev) return;
		prev = v;
		if (v.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			requestData(v);
		} else {
			$input.removeClass(options.loadingClass);
			$results.hide();
		}
	};

 	function moveSelect(step) {

		var lis = $("li", results);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass("ac_over");

		$(lis[active]).addClass("ac_over");

		// Weird behaviour in IE
		// if (lis[active] && lis[active].scrollIntoView) {
		// 	lis[active].scrollIntoView(false);
		// }

	};

	function selectCurrent() {
		var li = $("li.ac_over", results)[0];
		if (!li) {
			var $li = $("li", results);
			if (options.selectOnly) {
				if ($li.length == 1) li = $li[0];

			} else if (options.selectFirst) {
				li = $li[0];
			}
		}
		if (li) {
			selectItem(li);
			return true;
		} else {
			return false;
		}
	};

	function selectItem(li) {
		if (!li) {
			li = document.createElement("li");
			li.extra = [];
			li.selectValue = "";
		}
		var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
		input.lastSelected = v;
		prev = v;
		$results.html("");
		$input.val(v);
		hideResultsNow();
		if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
	};

	// selects a portion of the input string
	function createSelection(start, end){
		// get a reference to the input element
		var field = $input.get(0);
		if( field.createTextRange ){
			var selRange = field.createTextRange();
			selRange.collapse(true);
			selRange.moveStart("character", start);
			selRange.moveEnd("character", end);
			selRange.select();
		} else if( field.setSelectionRange ){
			field.setSelectionRange(start, end);
		} else {
			if( field.selectionStart ){
				field.selectionStart = start;
				field.selectionEnd = end;
			}
		}
		field.focus();
	};

	// fills in the input box w/the first match (assumed to be the best match)
	function autoFill(sValue){
		// if the last user key pressed was backspace, don't autofill
		if( lastKeyPressCode != 8 ){
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + unescape(sValue.substring(prev.length)));
			// select the portion of the value not typed by the user (so the next character will erase)
			createSelection(prev.length, sValue.length);
		}
	};

	function showResults() {
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = findPos(input);
		// either use the specified width, or autocalculate based on form element
		var iWidth = (options.width > 0) ? options.width : $input.width();
		// reposition
		$results.css({
			width: parseInt(iWidth) + "px",
			top: (pos.y + input.offsetHeight) + "px",
			left: pos.x + "px"
		}).show();
	};

	function hideResults() {
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 5000);
	};

	function hideResultsNow() {
		if (timeout) clearTimeout(timeout);
		$input.removeClass(options.loadingClass);
		if ($results.is(":visible")) {
			$results.hide();
		}
		if (options.mustMatch) {
			var v = $input.val();
			if (v != input.lastSelected) {
				selectItem(null);
			}
		}
	};

	function receiveData(q, data) {
		if (data) {
			$input.removeClass(options.loadingClass);
			results.innerHTML = "";

			// if the field no longer has focus or if there are no matches, do not display the drop down
			if( !hasFocus || data.length == 0 ) return hideResultsNow();

			if ($.browser.msie) {
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				$results.append(document.createElement('iframe'));
			}
			results.appendChild(dataToDom(data));
			// autofill in the complete box w/the first match as long as the user hasn't entered in more data
			if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
			showResults();
		} else {
			hideResultsNow();
		}
	};

	function parseData(data) {
		if (!data) return null;
		var parsed = [];
		var rows = data.split(options.lineSeparator);
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data) {
		var ul = document.createElement("ul");
		var num = data.length;

		// limited results to a max number
		if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

		for (var i=0; i < num; i++) {
			var row = data[i];
			if (!row) continue;
			var li = document.createElement("li");
			if (options.formatItem) {
				li.innerHTML = unescape(options.formatItem(row, i, num));
				li.selectValue = unescape(row[0]);
			} else {
				li.innerHTML = unescape(row[0]);
				li.selectValue = unescape(row[0]);
			}
			var extra = null;
			if (row.length > 1) {
				extra = [];
				for (var j=1; j < row.length; j++) {
					extra[extra.length] = row[j];
				}
			}
			li.extra = extra;
			ul.appendChild(li);
			$(li).hover(
				function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
				function() { $(this).removeClass("ac_over"); }
			).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
		}
		return ul;
	};

	function requestData(q) {
		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		// recieve the cached data
		if (data) {
			receiveData(q, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data);
				addToCache(q, data);
				receiveData(q, data);
			});
		// if there's been no data found, remove the loading class
		} else {
			$input.removeClass(options.loadingClass);
		}
	};

	function makeUrl(q) {
		var url = options.url + "?q=" + encodeURI(q);
		for (var i in options.extraParams) {
			url += "&" + i + "=" + encodeURI(options.extraParams[i]);
		}
		return url;
	};

	function loadFromCache(q) {
		if (!q) return null;
		if (cache.data[q]) return cache.data[q];
		if (options.matchSubset) {
			for (var i = q.length - 1; i >= options.minChars; i--) {
				var qs = q.substr(0, i);
				var c = cache.data[qs];
				if (c) {
					var csub = [];
					for (var j = 0; j < c.length; j++) {
						var x = c[j];
						var x0 = x[0];
						if (matchSubset(x0, q)) {
							csub[csub.length] = x;
						}
					}
					return csub;
				}
			}
		}
		return null;
	};

	function matchSubset(s, sub) {
		if (!options.matchCase) s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	this.flushCache = function() {
		flushCache();
	};

	this.setExtraParams = function(p) {
		options.extraParams = p;
	};

	this.findValue = function(){
		var q = $input.val();

		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		if (data) {
			findValueCallback(q, data);
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data)
				addToCache(q, data);
				findValueCallback(q, data);
			});
		} else {
			// no matches
			findValueCallback(q, null);
		}
	}

	function findValueCallback(q, data){
		if (data) $input.removeClass(options.loadingClass);

		var num = (data) ? data.length : 0;
		var li = null;

		for (var i=0; i < num; i++) {
			var row = data[i];

			if( row[0].toLowerCase() == q.toLowerCase() ){
				li = document.createElement("li");
				if (options.formatItem) {
					li.innerHTML = options.formatItem(row, i, num);
					li.selectValue = row[0];
				} else {
					li.innerHTML = row[0];
					li.selectValue = row[0];
				}
				var extra = null;
				if( row.length > 1 ){
					extra = [];
					for (var j=1; j < row.length; j++) {
						extra[extra.length] = row[j];
					}
				}
				li.extra = extra;
			}
		}

		if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
	}

	function addToCache(q, data) {
		if (!data || !q || !options.cacheLength) return;
		if (!cache.length || cache.length > options.cacheLength) {
			flushCache();
			cache.length++;
		} else if (!cache[q]) {
			cache.length++;
		}
		cache.data[q] = data;
	};

	function findPos(obj) {
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		return {x:curleft,y:curtop};
	}
}

jQuery.fn.autocomplete = function(url, options, data) {

   // Make sure options exists
   options = typeof(options) != 'undefined' ? options : {};

   // Set url as option
   options.url = url;
   // set some bulk local data
   options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

   // Set default values for required options
   options.inputClass = typeof(options.inputClass) != 'undefined' ? options.inputClass : "ac_input";
   options.resultsClass = typeof(options.resultsClass) != 'undefined' ? options.resultsClass : "ac_results";
   options.lineSeparator = typeof(options.lineSeparator) != 'undefined' ? options.lineSeparator : "\n";
   options.cellSeparator = typeof(options.cellSeparator ) != 'undefined' ? options.cellSeparator : "|";
   options.minChars = typeof(options.minChars) != 'undefined' ? options.minChars : 1;
   options.delay = typeof(options.delay) != 'undefined' ? options.delay : 400;
   options.matchCase = typeof(options.matchCase) != 'undefined' ? options.matchCase : 0;
   options.matchSubset = typeof(options.matchSubset) != 'undefined' ? options.matchSubset : 1;
   options.matchContains = typeof(options.matchContains) != 'undefined' ? options.matchContains : 0;
   options.cacheLength = typeof(options.cacheLength) != 'undefined' ? options.cacheLength : 1;
   options.mustMatch = typeof(options.mustMatch) != 'undefined' ? options.mustMatch : 0;
   options.extraParams = typeof(options.extraParams) != 'undefined' ? options.extraParams : {};
   options.loadingClass = typeof(options.loadingClass) != 'undefined' ? options.loadingClass : "ac_loading";
   options.selectFirst = typeof(options.selectFirst) != 'undefined' ? options.selectFirst : false;
   options.selectOnly = typeof(options.selectOnly) != 'undefined' ? options.selectOnly : false;
   options.maxItemsToShow = typeof(options.maxItemsToShow) != 'undefined' ? options.maxItemsToShow : -1;
   options.autoFill = typeof(options.autoFill) != 'undefined' ? options.autoFill : false;
   options.width = typeof(options.width) != 'undefined' ? parseInt(options.width, 10) : 0;

   this.each(function() {
      var input = this;
      new jQuery.autocomplete(input, options);
   });

   // Don't break the chain
   return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
	return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e){
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};



/**
* Helper function to write the correct search fields via AJAX
*/
function writeSearchField(task,changeThis,newValue,updateId) {
  var time = new Date();
	var t = time.getTime();
	$.ajax({
			url: "my_includes/searchajaxv3.php?task="+task+"&"+changeThis+"="+newValue+"&t="+t,
			success: function(html) {
			  $("#"+updateId).empty().prepend(html);
			}
	});
}
function writeSearchFieldJSON(task,changeThis,newValue,updateId) 
{
	var aid=$("#aid_selector").val();
	if (aid=="")
		aid=$("#aid_current").val();
	var data="&cid=" + $("#cid_selector").val() + "&aid=" + aid + "&tid=" +  $("#tid_selector").val() + "&p_type=" + $("#typ_selector").val() ;
	doSearchAjax(data);
}

function doSearchAjax(data)
{
  var time = new Date();
	var t = time.getTime();

	//url: "my_includes/searchajaxv3.php?task=doSearch&"+changeThis+"="+newValue+"&t="+t + data,
	$.ajax({
			url: "my_includes/searchajaxv3.php?task=doSearch&t="+t + data,	
			success: function(j) {
				var json=$.parseJSON(j);
				var ctrl="";
				if ($("#aid_selector").val()=="" || $("#aid_selector").val()=="0")
					ctrl="#aid_selector";
				else if ($("#tid_selector").val()=="" || $("#tid_selector").val()=="0")
					ctrl="#tid_selector";
			
				$(ctrl).removeAttr("disabled").html("");
				$(ctrl).append($("<option>",{value:''}).text("Any area"));
				$.each(json.locations,function(i,l){
					$(ctrl).append($("<option>",{value:l.id}).text(l.name));
				});
					
				ctrl="#typ_selector";
				if (json.types.length>0)
				{
					currType=$("#typ_selector").val();
					$(ctrl).removeAttr("disabled").html("");
					
					$(ctrl).append($("<option>",{value:''}).text("Any type"));
					$.each(json.types,function(i,l){
						if (currType==l.id)
							$(ctrl).append($("<option>",{value:l.id,selected:true}).text(l.name));
						else
							$(ctrl).append($("<option>",{value:l.id}).text(l.name));
					});
				}
				
				var chtml="";
				if ($("select[name='cid']").val()!="0")
				{
					chtml="<div id=\"search_count_num\">"+json.count+"</div>";
					if (json.count == "1") {
						chtml=chtml+"Matching Property";
					} else {
						chtml=chtml+"Matching Properties";
					}
				}
				$("div#searchCount").empty().prepend(chtml);
			}
	});
}


/**
* Change the listing type
*/
function changeSearch(changeThis, newValue) {
  
	var form = document.searchForm;

	//Start the progress animation
	showAnimation();

  //Show Map Area
	if (form.cid.selectedIndex != 0) {
		if (changeThis == "cid" || changeThis == "aid" || changeThis == "tid") {
			if(!document.getElementById("mapmap")) {
				$("#main_content").prepend('<div id="mapmap"></div>');
				$("#mapmap").animate({height:440},1000,"easeout");
				loadmap(changeThis, newValue);
				if (changeThis == "tid" && newValue != "0") {
					//var wait = setTimeout("showExpandedSearch("+newValue+");",1000);
				}
				/*$("#mci").fadeOut(1000,function() {
					if ($("#mapmap").length>0)
						$("#mapmap").append("<div>"+getTextStr("_WHERE_ARE_MY_RESULTS")+"</div>");																					 
				});*/
				$("#mci").hide();
				$("#mapmap").append("<div>"+getTextStr("_WHERE_ARE_MY_RESULTS")+"</div>");																					 
			}
		}
	} else {
		$("#mapmap").animate({height:0},1000,"easeout",function() {
		  $("#mapmap").remove();  
		});
	}
	
	/**
	* Load map initially
	*/
	function loadmap(changeThis, newValue) 
	{
		newValue = newValue;
		changeThis = changeThis;
     
		if (newValue == "0") 
		{
			if (changeThis == "aid") 
			{
            newValue = form.cid.value;
			} 
			else if (changeThis == "tid") 
			{
            newValue = form.aid.value;
			}
		}
		 

		$.ajax({
						 
			  url: "my_includes/searchajaxv2.php?task=loadMap",
				success: function(html) {

			$("#mapmap").prepend(html);
			$("#mapmap").css({backgroundColor: "#ffffff"});
					//Load map
					map = new YMap(document.getElementById('maparea'));
					map.setMapType(YAHOO_MAP_REG);
					map.addPanControl(); 
					map.addZoomLong(); 
					map.disableKeyControls();
					
					getMapCoordinates(newValue);

		  }
		});

	}
	
	//Changing listing type?
	if (changeThis == 'l_type') {
		
		//Unhide the beds/bath/pool if they have been hidden
		//document.getElementById('bedBathPool').style.display = "block";

		//Disable fields
		form.cid.options[0] = new Option (" ","0");
		form.cid.selectedIndex = 0;
		form.cid.disabled = true;

		form.aid.options[0] = new Option (" ","0");
		form.aid.disabled = true;
		form.aid.selectedIndex = 0;
    
		if (form.tid) {
			form.tid.options[0] = new Option (" ","0");
			form.tid.disabled = true;
			form.tid.selectedIndex = 0;
    }
		
		form.p_type.options[0] = new Option (" ","0");
		form.p_type.disabled = true;
		form.p_type.selectedIndex = 0;

		form.price.options[0] = new Option (" ","0");
		form.price.disabled = true;
		form.price.selectedIndex = 0;

		form.beds.options[0] = new Option (" ","0");
		form.beds.disabled = true;
		form.beds.selectedIndex = 0;

		form.baths.options[0] = new Option ("","0");
		form.baths.disabled = true;
		form.baths.selectedIndex = 0;


    if (newValue != "0") {
			//Write the search fields
			writeSearchField('writeCountrySelector',changeThis,newValue,'selectCountry');
			writeSearchField('writePropertyTypeSelector',changeThis,newValue,'selectPropertyType');
			writeSearchField('writePriceSelector',changeThis,newValue,'selectPrice');
			writeSearchField('writeBedsSelector',changeThis,newValue,'selectBeds');
			writeSearchField('writeBathsSelector',changeThis,newValue,'selectBaths');
			//writeSearchField('writePoolSelector',changeThis,newValue,'selectPool');
		}
		
		
		
	} 
	
	//Changing Country?
	if (changeThis == 'cid') {
		//Disable the area and town selector temporarily
		form.aid.selectedIndex = 0;
		form.aid.disabled = true;
		if (form.tid) {
			form.tid.selectedIndex = 0;
			form.tid.disabled = true;
		}
		hideExpandedSearch(0);
		removeAllMapMarkers();
		if (newValue != "0") {
//			writeSearchFieldJSON('writeAreaSelector',changeThis,newValue,'selectArea');
			getMapCoordinates(newValue);
		}
		
	}
	
	//Changing Area?
	if (changeThis == 'aid') {
		//Disable the town selector temporarily
		if (form.tid) {
			form.tid.disabled = true;
			form.tid.selectedIndex = 0;
        }
		hideExpandedSearch(0);
		removeAllMapMarkers();
		//Make sure an area was selected
		if (newValue != "0") {
			//writeSearchFieldJSON('writeTownSelector',changeThis,newValue,'selectTown');
		} else {
			getMapCoordinates(form.cid.value);
		}
	}
	//Changing Town?
	if (changeThis == 'tid') {
//		writeSearchFieldJSON('writeTownUpdate',changeThis,newValue,'selectTown');
//		selectTown(newValue);
		
	}
	
	
	writeSearchFieldJSON('',changeThis,newValue,'selectTown');
	
	//Changing Property Type
	if (changeThis == 'p_type') {
		//Did we change to garage or land?
		if (newValue == "3" || newValue == "4") {
			form.beds.selectedIndex = 0;
			form.baths.selectedIndex = 0;
			document.getElementById('bedBathPool').style.display = "none";
		} else {
			//document.getElementById('bedBathPool').style.display = "block";
		}
		$("#typ_selector option").removeAttr("selected");
		$("#typ_selector option[value=" + newValue + "]").attr("selected","selected");
	}
}

//Function to change town
function selectTown(tid) {

	removeAllMapMarkers();

	if (tid == "0") {
		//any town - hide the expanded search
		hideExpandedSearch(0);
		$("#es_again").remove();
		$("#tid_selector").css({width: '185px'});
	} else {
		
		//Load expanded Search
		//showExpandedSearch(tid);
		
		//Place marker on map
		$.ajax({
				url: "my_includes/searchajaxv2.php?task=getMapCoordinates&link_id="+tid,
				success: function(html) {
					var arrCordinates = html.split(':');
					addMapMarker(tid,arrCordinates[1],arrCordinates[0]);
				}
		});
		
		/*//Add a hit to the chosen town
		$.ajax({
			url: "my_includes/searchajaxv2.php?task=addHit&link_id="+tid
		});*/
		
	}

}

function submitSearch() {
	if (document.forms['searchForm'].l_type.selectedIndex != 0) {
		document.forms['searchForm'].submit();
	}

}

function updateSearchCount () {

	//Collect variables from the form
	var l_type = document.searchForm.l_type.value;
	var cid = document.searchForm.cid.value;
	if (cid+""=="")
	{
		$("div#searchCount").animate({opacity: 'hide'},100).empty().prepend(html).fadeIn("slow");
		return;
	}
	var aid = document.searchForm.aid.value;
	if (document.searchForm.tid) {
  	var tid = document.searchForm.tid.value;
	} else {
	  var tid = "0";
	}
	var p_type = document.searchForm.p_type.value;
	var price = document.searchForm.price.value;
	var beds = document.searchForm.beds.value;
	var baths = document.searchForm.baths.value;
	
	$.ajax({
			url: "my_includes/searchajaxv3.php?task=countSearch&l_type="+l_type+"&cid="+cid+"&aid="+aid+"&tid="+tid+"&p_type="+p_type+"&price="+price+"&beds="+beds+"&baths="+baths+"&pool=&offplan=",
			success: function(html) {
																$("div#searchCount").animate({opacity: 'hide'},100).empty().prepend(html).fadeIn("slow");
																
															}
	});


}


/**
* Shows/hides the map
*/
function toggleMap() {
	
	if ($("div#mapcontainer").css("display") == "none") {
		//Show
		$("div#mapcontainer").show();
		$("div#mapcontainer").animate({height:361},800,"easeout", function() {
                                                                   	 $("span#showHideTxt").empty().prepend(getTextStr("_HIDE_MAP"));
																																			 });
		$("div#maparea").animate({height:361},800,"easeout");

  } else {
		//Hide
		$("div#mapcontainer").animate({height:0},800,"easeout",function() {
		                                                                 $("div#mapcontainer").hide();																															 
                                                                   	 $("span#showHideTxt").empty().prepend(getTextStr("_SHOW_MAP"));
    });
		$("div#maparea").animate({height:0},800,"easeout");

  }

}

/**
* Gets a text string from php in the correct language
*/
function getTextStr(c) {

	var html = $.ajax({
	url: "index2.php?option=com_property&no_html=1&task=getTextStr&constant="+c,
	async: false
	}).responseText;
  
  return html;

}

/**
* Displays a pin on the map
*/
function addMapMarker() {

	var id = arguments[0];
	var lat = arguments[1];
	var long = arguments[2];
	var imgSrc = arguments[3];
	
	var myPoint = new YGeoPoint(lat,long);

  if (document.getElementById(id)) {
    map.removeMarker(id);
	}

	if (!imgSrc) {
		imgSrc = "http://www.medhead.com/images/medhead/green_dot.gif";
	}
	
	var myImage = new YImage();
	myImage.src = imgSrc;
	myImage.size = new YSize(16,16);
	myImage.offsetSmartWindow = new YCoordPoint(0,0);
	myImage.offset =  new YCoordPoint(0,16)
	var marker = new YMarker(myPoint,myImage,id+"");
	
	YEvent.Capture(marker,EventsList.MouseClick,function() { toggleTid(id) });

	map.addOverlay(marker);
	
}

function removeMapMarker() {

	var id = arguments[0];
  if (document.getElementById(id)) {
    map.removeMarker(id);
	}
	
}

function removeAllMapMarkers() {
	
	//Remove all map markers
	if ( typeof ( map ) != "undefined" ) {
		map.removeMarkersAll();
	}
	
}

/**
* Toggles extra towns to/from the search
*/
function toggleTid(link_id, lat, long) {

	var selObj = document.searchForm.tid;
	var curTid = selObj.value;
	
  for(i = 0; i < selObj.length; i++) 	{
	  if(selObj.options[i].value == curTid) {
			if (selObj.options[i].value.indexOf(link_id) == -1) {
				//Add
  			selObj.options[i].value = curTid+","+link_id;
				$("li#li_"+link_id+" a").css({fontWeight: "bold"});
				$("li#li_"+link_id).css({listStyleImage: "url(../../../images/medhead/small_green_dot.gif)"});
				//Add Hit
				$.ajax({
			  	  		url: "my_includes/searchajaxv2.php?task=addHit&link_id="+link_id
     		  	  });
				//Add Map Marker
				$.ajax({
						url: "my_includes/searchajaxv2.php?task=getMapCoordinates&link_id="+link_id,
						success: function(html) {
							var arrCordinates = html.split(':');
							addMapMarker(link_id,arrCordinates[1],arrCordinates[0]);
						}
				});

				
			} else {
				//Remove
				var strToFind = ","+link_id;
				selObj.options[i].value = curTid.replace(strToFind,"");
				$("li#li_"+link_id+" a").css({fontWeight: "normal"});
				$("li#li_"+link_id).css({listStyleImage: "url(../../../images/medhead/arrow_bullet.gif)"});
				removeMapMarker(link_id);


      }
		}
  }
	
	
	

}


/**
* toggles visibility of the expaned search area
*/
function hideExpandedSearch(tid) {
  
	var speed = 600;
	
	$("div#expandedSearchBar").empty();
	$("div#expandedSearchBar").animate({width:0},speed,"easeout",function() {
    $("div#expandedSearchBar").remove();
		if (tid != "0") {
		  addExpandSearchButton();
		}
	});																
	$("div#mapmap").animate({width:662},speed,"easeout");
	$("div#mapcontainer").animate({width:660},speed,"easeout");
	
	if (typeof map == "object") {
		mapSize = new YSize(660, 361);
		map.resizeTo(mapSize);
	}

  if (tid != "0") {
		$.cookie("hideExpandSearch","1",{ expires: 7 });
	}

}
	
function showExpandedSearch(tid) {	
	
  var speed = 600;
	
	//create
	if( $("#expandedSearchBar").size() == "0") {
		$("div.moduletableSearch").prepend('<div id="expandedSearchBar"></div>');
		$("div#expandedSearchBar").animate({width:220},speed,"easeout");																
		$("select#tid_selector").css({width: "185px"});
		$("div#es_again").remove();
	}

	$("div#mapmap").animate({width:452},speed,"easeout");
	$("div#mapcontainer").animate({width:450},speed,"easeout");

  if (typeof map == "object") {
		mapSize = new YSize(450, 361);
		map.resizeTo(mapSize);
	}

  getExpandedTidList(tid);

	//Place marker on map
	$.ajax({
			url: "my_includes/searchajaxv2.php?task=getMapCoordinates&link_id="+tid,
			success: function(html) {
				var arrCordinates = html.split(':');
				addMapMarker(tid,arrCordinates[1],arrCordinates[0]);
			}
	});

}



//Fill the expanded search
function getExpandedTidList(tid) {
	/*
		$("div#expandedSearchBar").empty().prepend('<br /><br /><img src="/images/medhead/progress.gif" width="16" height="16" style="margin-left:65px;">');
    $.ajax({
				url: "my_includes/searchajaxv2.php?task=writeExpandedSearch&tid="+tid,
				success: function(html) {
														$("div#expandedSearchBar").empty().prepend(html);
													}
		});
		*/
}

//Add button next to town selector to expand search
function addExpandSearchButton() {
	/*tid = document.searchForm.tid.value;
	$("div#es_again").remove();
	$("select#tid_selector").css({width: "163px"});
	$("select#tid_selector").after('<div id="es_again"><img src="images/medhead/expand_search.gif" width="18" height="19" alt="+"></div>');
	$("div#es_again").bind("click", function() {
		                                       $.cookie("hideExpandSearch",null);
                                           //showExpandedSearch(tid+"");
																					 });
																					 */
}


/**
* Show Animation when Search is working
*/
function showAnimation() {
	document.getElementById('searchCount').innerHTML = '<img src="/images/medhead/progress_search.gif" width="32" height="32">';
}


/**
* Use Ajax to retrieve coordinates for the selected area/town
*/

function getMapCoordinates(link_id) {
  
	if(link_id != "0") {

        $.ajax({
            url: "my_includes/searchajaxv2.php?task=getMapCoordinates&link_id="+link_id,
            success: function(html) {
                var arrCordinates = html.split(':');
                centerMapOnGivenCoordinate( arrCordinates[0], arrCordinates[1], arrCordinates[2] );
            }
        });
		
	}

}

//Take the cordinates and send them to Yahoo map
function centerMapOnGivenCoordinate(lon, lat, distance) {
	
	if (map) {
		var myPoint = new YGeoPoint(lat,lon);
		map.drawZoomAndCenter(myPoint, distance);
	}
}

/**
* Javascript used throughout the site
*/



//Submit the logout form
function submitLogout() {
	document.logoutForm.submit();
}

//Toggle emailPage to friend
function toggleEmailPageDiv() {
	
	if ($("#ePageForm_cont").css("height") == "0px") {
		$("#ePageForm_cont").animate({height: 230},500,"easeout")
		$.ajax({
				url: "index2.php?option=com_property&no_html=1&task=ajaxShowEmailPage",
				success: function(html) {
														$("#ePageForm_cont").prepend(html);
													}
		});
	} else {
		$("#ePageForm_cont").animate({height: 0},500,"easeout",function() {
                                                                         $("#ePageForm_cont").empty();
																																				});
	}

}


//Check form and send email via AJAX
function sendPageLink() {
	
  document.getElementById("emailPageButton").innerHTML = "<img src=\"images/medhead/progress.gif\" width=\"16\" height=\"16\" style=\"\">";

  var form = document.emailPageForm;
  
	var sender_name = form.sender_name.value;
	var sender_email = form.sender_email.value;
	var receiver_name = form.receiver_name.value;
	var receiver_email = form.receiver_email.value;
	var page_url = escape(window.location.href);

	$.ajax({
		url: "index2.php?option=com_property&no_html=1&task=ajaxSendEmailPage&sender_name="+sender_name+"&sender_email="+sender_email+"&receiver_name="+receiver_name+"&receiver_email="+receiver_email+"&page_url="+page_url,
		success: function(html) {
													$("#ePageForm_cont").empty().prepend(html);
		  										}
	});
	
}





/**
* jQuery
*/

$(document).ready( function() {
  
	$("a#loginLink").bind("click", toggleLogin);
	$("a#closeLogin").bind("click", toggleLogin);


});

/* Toggle Div visibility */

function toggleDiv() {
  if ($("#showHide").css("display") == "none") {
		$('#showHide').show(300);
	} else {
	  $('#showHide').hide(300);
	}

}

/* Toggle Login Div */

function toggleLogin() {
  if ($("div#headerDiv").css("display") == "none") {
		$("div#headerDiv").animate({height: 128}, 1000, "bounceout", function() {
																								$('#mod_login_username').focus();
																							 });
	} else {
		$("div#headerDiv").slideUp(300, function() {
																								$("div#headerDiv").css({height:"0"});
																							 });
	}

}


(function($){var ColorPicker=function(){var ids={},inAction,charMin=65,visible,tpl='<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',defaults={eventName:'click',onShow:function(){},onBeforeShow:function(){},onHide:function(){},onChange:function(){},onSubmit:function(){},color:'ff0000',livePreview:true,flat:false},fillRGBFields=function(hsb,cal){var rgb=HSBToRGB(hsb);$(cal).data('colorpicker').fields.eq(1).val(rgb.r).end().eq(2).val(rgb.g).end().eq(3).val(rgb.b).end();},fillHSBFields=function(hsb,cal){$(cal).data('colorpicker').fields.eq(4).val(hsb.h).end().eq(5).val(hsb.s).end().eq(6).val(hsb.b).end();},fillHexFields=function(hsb,cal){$(cal).data('colorpicker').fields.eq(0).val(HSBToHex(hsb)).end();},setSelector=function(hsb,cal){$(cal).data('colorpicker').selector.css('backgroundColor','#'+HSBToHex({h:hsb.h,s:100,b:100}));$(cal).data('colorpicker').selectorIndic.css({left:parseInt(150*hsb.s/100,10),top:parseInt(150*(100-hsb.b)/100,10)});},setHue=function(hsb,cal){$(cal).data('colorpicker').hue.css('top',parseInt(150-150*hsb.h/360,10));},setCurrentColor=function(hsb,cal){$(cal).data('colorpicker').currentColor.css('backgroundColor','#'+HSBToHex(hsb));},setNewColor=function(hsb,cal){$(cal).data('colorpicker').newColor.css('backgroundColor','#'+HSBToHex(hsb));},keyDown=function(ev){var pressedKey=ev.charCode||ev.keyCode||-1;if((pressedKey>charMin&&pressedKey<=90)||pressedKey==32){return false;}var cal=$(this).parent().parent();if(cal.data('colorpicker').livePreview===true){change.apply(this);}},change=function(ev){var cal=$(this).parent().parent(),col;if(this.parentNode.className.indexOf('_hex')>0){cal.data('colorpicker').color=col=HexToHSB(fixHex(this.value));}else if(this.parentNode.className.indexOf('_hsb')>0){cal.data('colorpicker').color=col=fixHSB({h:parseInt(cal.data('colorpicker').fields.eq(4).val(),10),s:parseInt(cal.data('colorpicker').fields.eq(5).val(),10),b:parseInt(cal.data('colorpicker').fields.eq(6).val(),10)});}else{cal.data('colorpicker').color=col=RGBToHSB(fixRGB({r:parseInt(cal.data('colorpicker').fields.eq(1).val(),10),g:parseInt(cal.data('colorpicker').fields.eq(2).val(),10),b:parseInt(cal.data('colorpicker').fields.eq(3).val(),10)}));}if(ev){fillRGBFields(col,cal.get(0));fillHexFields(col,cal.get(0));fillHSBFields(col,cal.get(0));}setSelector(col,cal.get(0));setHue(col,cal.get(0));setNewColor(col,cal.get(0));cal.data('colorpicker').onChange.apply(cal,[col,HSBToHex(col),HSBToRGB(col)]);},blur=function(ev){var cal=$(this).parent().parent();cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus')},focus=function(){charMin=this.parentNode.className.indexOf('_hex')>0?70:65;$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');$(this).parent().addClass('colorpicker_focus');},downIncrement=function(ev){var field=$(this).parent().find('input').focus();var current={el:$(this).parent().addClass('colorpicker_slider'),max:this.parentNode.className.indexOf('_hsb_h')>0?360:(this.parentNode.className.indexOf('_hsb')>0?100:255),y:ev.pageY,field:field,val:parseInt(field.val(),10),preview:$(this).parent().parent().data('colorpicker').livePreview};$(document).bind('mouseup',current,upIncrement);$(document).bind('mousemove',current,moveIncrement);},moveIncrement=function(ev){ev.data.field.val(Math.max(0,Math.min(ev.data.max,parseInt(ev.data.val+ev.pageY-ev.data.y,10))));if(ev.data.preview){change.apply(ev.data.field.get(0),[true]);}return false;},upIncrement=function(ev){change.apply(ev.data.field.get(0),[true]);ev.data.el.removeClass('colorpicker_slider').find('input').focus();$(document).unbind('mouseup',upIncrement);$(document).unbind('mousemove',moveIncrement);return false;},downHue=function(ev){var current={cal:$(this).parent(),y:$(this).offset().top};current.preview=current.cal.data('colorpicker').livePreview;$(document).bind('mouseup',current,upHue);$(document).bind('mousemove',current,moveHue);},moveHue=function(ev){change.apply(ev.data.cal.data('colorpicker').fields.eq(4).val(parseInt(360*(150-Math.max(0,Math.min(150,(ev.pageY-ev.data.y))))/150,10)).get(0),[ev.data.preview]);return false;},upHue=function(ev){fillRGBFields(ev.data.cal.data('colorpicker').color,ev.data.cal.get(0));fillHexFields(ev.data.cal.data('colorpicker').color,ev.data.cal.get(0));$(document).unbind('mouseup',upHue);$(document).unbind('mousemove',moveHue);return false;},downSelector=function(ev){var current={cal:$(this).parent(),pos:$(this).offset()};current.preview=current.cal.data('colorpicker').livePreview;$(document).bind('mouseup',current,upSelector);$(document).bind('mousemove',current,moveSelector);},moveSelector=function(ev){change.apply(ev.data.cal.data('colorpicker').fields.eq(6).val(parseInt(100*(150-Math.max(0,Math.min(150,(ev.pageY-ev.data.pos.top))))/150,10)).end().eq(5).val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX-ev.data.pos.left))))/150,10)).get(0),[ev.data.preview]);return false;},upSelector=function(ev){fillRGBFields(ev.data.cal.data('colorpicker').color,ev.data.cal.get(0));fillHexFields(ev.data.cal.data('colorpicker').color,ev.data.cal.get(0));$(document).unbind('mouseup',upSelector);$(document).unbind('mousemove',moveSelector);return false;},enterSubmit=function(ev){$(this).addClass('colorpicker_focus');},leaveSubmit=function(ev){$(this).removeClass('colorpicker_focus');},clickSubmit=function(ev){var cal=$(this).parent();var col=cal.data('colorpicker').color;cal.data('colorpicker').origColor=col;setCurrentColor(col,cal.get(0));cal.data('colorpicker').onSubmit(col,HSBToHex(col),HSBToRGB(col));},show=function(ev){var cal=$('#'+$(this).data('colorpickerId'));cal.data('colorpicker').onBeforeShow.apply(this,[cal.get(0)]);var pos=$(this).offset();var viewPort=getViewport();var top=pos.top+this.offsetHeight;var left=pos.left;if(top+176>viewPort.t+viewPort.h){top-=this.offsetHeight+176;}if(left+356>viewPort.l+viewPort.w){left-=356;}cal.css({left:left+'px',top:top+'px'});if(cal.data('colorpicker').onShow.apply(this,[cal.get(0)])!=false){cal.show();}$(document).bind('mousedown',{cal:cal},hide);return false;},hide=function(ev){if(!isChildOf(ev.data.cal.get(0),ev.target,ev.data.cal.get(0))){if(ev.data.cal.data('colorpicker').onHide.apply(this,[ev.data.cal.get(0)])!=false){ev.data.cal.hide();}$(document).unbind('mousedown',hide);}},isChildOf=function(parentEl,el,container){if(parentEl==el){return true;}if(parentEl.contains){return parentEl.contains(el);}if(parentEl.compareDocumentPosition){return!!(parentEl.compareDocumentPosition(el)&16);}var prEl=el.parentNode;while(prEl&&prEl!=container){if(prEl==parentEl)return true;prEl=prEl.parentNode;}return false;},getViewport=function(){var m=document.compatMode=='CSS1Compat';return{l:window.pageXOffset||(m?document.documentElement.scrollLeft:document.body.scrollLeft),t:window.pageYOffset||(m?document.documentElement.scrollTop:document.body.scrollTop),w:window.innerWidth||(m?document.documentElement.clientWidth:document.body.clientWidth),h:window.innerHeight||(m?document.documentElement.clientHeight:document.body.clientHeight)};},fixHSB=function(hsb){return{h:Math.min(360,Math.max(0,hsb.h)),s:Math.min(100,Math.max(0,hsb.s)),b:Math.min(100,Math.max(0,hsb.b))};},fixRGB=function(rgb){return{r:Math.min(255,Math.max(0,rgb.r)),g:Math.min(255,Math.max(0,rgb.g)),b:Math.min(255,Math.max(0,rgb.b))};},fixHex=function(hex){var len=6-hex.length;if(len>0){var o=[];for(var i=0;i<len;i++){o.push('0');}o.push(hex);hex=o.join('');}return hex;},HexToRGB=function(hex){var hex=parseInt(((hex.indexOf('#')>-1)?hex.substring(1):hex),16);return{r:hex>>16,g:(hex&0x00FF00)>>8,b:(hex&0x0000FF)};},HexToHSB=function(hex){return RGBToHSB(HexToRGB(hex));},RGBToHSB=function(rgb){var hsb={};hsb.b=Math.max(Math.max(rgb.r,rgb.g),rgb.b);hsb.s=(hsb.b<=0)?0:Math.round(100*(hsb.b-Math.min(Math.min(rgb.r,rgb.g),rgb.b))/hsb.b);hsb.b=Math.round((hsb.b/255)*100);if((rgb.r==rgb.g)&&(rgb.g==rgb.b))hsb.h=0;else if(rgb.r>=rgb.g&&rgb.g>=rgb.b)hsb.h=60*(rgb.g-rgb.b)/(rgb.r-rgb.b);else if(rgb.g>=rgb.r&&rgb.r>=rgb.b)hsb.h=60+60*(rgb.g-rgb.r)/(rgb.g-rgb.b);else if(rgb.g>=rgb.b&&rgb.b>=rgb.r)hsb.h=120+60*(rgb.b-rgb.r)/(rgb.g-rgb.r);else if(rgb.b>=rgb.g&&rgb.g>=rgb.r)hsb.h=180+60*(rgb.b-rgb.g)/(rgb.b-rgb.r);else if(rgb.b>=rgb.r&&rgb.r>=rgb.g)hsb.h=240+60*(rgb.r-rgb.g)/(rgb.b-rgb.g);else if(rgb.r>=rgb.b&&rgb.b>=rgb.g)hsb.h=300+60*(rgb.r-rgb.b)/(rgb.r-rgb.g);else hsb.h=0;hsb.h=Math.round(hsb.h);return hsb;},HSBToRGB=function(hsb){var rgb={};var h=Math.round(hsb.h);var s=Math.round(hsb.s*255/100);var v=Math.round(hsb.b*255/100);if(s==0){rgb.r=rgb.g=rgb.b=v;}else{var t1=v;var t2=(255-s)*v/255;var t3=(t1-t2)*(h%60)/60;if(h==360)h=0;if(h<60){rgb.r=t1;rgb.b=t2;rgb.g=t2+t3}else if(h<120){rgb.g=t1;rgb.b=t2;rgb.r=t1-t3}else if(h<180){rgb.g=t1;rgb.r=t2;rgb.b=t2+t3}else if(h<240){rgb.b=t1;rgb.r=t2;rgb.g=t1-t3}else if(h<300){rgb.b=t1;rgb.g=t2;rgb.r=t2+t3}else if(h<360){rgb.r=t1;rgb.g=t2;rgb.b=t1-t3}else{rgb.r=0;rgb.g=0;rgb.b=0}}return{r:Math.round(rgb.r),g:Math.round(rgb.g),b:Math.round(rgb.b)};},RGBToHex=function(rgb){var hex=[rgb.r.toString(16),rgb.g.toString(16),rgb.b.toString(16)];$.each(hex,function(nr,val){if(val.length==1){hex[nr]='0'+val;}});return hex.join('');},HSBToHex=function(hsb){return RGBToHex(HSBToRGB(hsb));};return{init:function(options){options=$.extend({},defaults,options||{});if(typeof options.color=='string'){options.color=HexToHSB(options.color);}else if(options.color.r!=undefined&&options.color.g!=undefined&&options.color.b!=undefined){options.color=RGBToHSB(options.color);}else if(options.color.h!=undefined&&options.color.s!=undefined&&options.color.b!=undefined){options.color=fixHSB(options.color);}else{return this;}options.origColor=options.color;return this.each(function(){if(!$(this).data('colorpickerId')){var id='collorpicker_'+parseInt(Math.random()*1000);$(this).data('colorpickerId',id);var cal=$(tpl).attr('id',id);if(options.flat){cal.appendTo(this).show();}else{cal.appendTo(document.body);}options.fields=cal.find('input').bind('keydown',keyDown).bind('change',change).bind('blur',blur).bind('focus',focus);cal.find('span').bind('mousedown',downIncrement);options.selector=cal.find('div.colorpicker_color').bind('mousedown',downSelector);options.selectorIndic=options.selector.find('div div');options.hue=cal.find('div.colorpicker_hue div');cal.find('div.colorpicker_hue').bind('mousedown',downHue);options.newColor=cal.find('div.colorpicker_new_color');options.currentColor=cal.find('div.colorpicker_current_color');cal.data('colorpicker',options);cal.find('div.colorpicker_submit').bind('mouseenter',enterSubmit).bind('mouseleave',leaveSubmit).bind('click',clickSubmit);fillRGBFields(options.color,cal.get(0));fillHSBFields(options.color,cal.get(0));fillHexFields(options.color,cal.get(0));setHue(options.color,cal.get(0));setSelector(options.color,cal.get(0));setCurrentColor(options.color,cal.get(0));setNewColor(options.color,cal.get(0));if(options.flat){cal.css({position:'relative',display:'block'});}else{$(this).bind(options.eventName,show);}}});},showPicker:function(){return this.each(function(){if($(this).data('colorpickerId')){show.apply(this);}});},hidePicker:function(){return this.each(function(){if($(this).data('colorpickerId')){$('#'+$(this).data('colorpickerId')).hide();}});},setColor:function(col){if(typeof col=='string'){col=HexToHSB(col);}else if(col.r!=undefined&&col.g!=undefined&&col.b!=undefined){col=RGBToHSB(col);}else if(col.h!=undefined&&col.s!=undefined&&col.b!=undefined){col=fixHSB(col);}else{return this;}return this.each(function(){if($(this).data('colorpickerId')){var cal=$('#'+$(this).data('colorpickerId'));cal.data('colorpicker').color=col;cal.data('colorpicker').origColor=col;fillRGBFields(col,cal.get(0));fillHSBFields(col,cal.get(0));fillHexFields(col,cal.get(0));setHue(col,cal.get(0));setSelector(col,cal.get(0));setCurrentColor(col,cal.get(0));setNewColor(col,cal.get(0));}});}};}();$.fn.extend({ColorPicker:ColorPicker.init,ColorPickerHide:ColorPicker.hide,ColorPickerShow:ColorPicker.show,ColorPickerSetColor:ColorPicker.setColor});})(jQuery)

