/* Select */
(function($) {
	$.widget('ui.checkBox', {
		_init: function() {
			var that = this, opts = this.options;

			this.labels = $([]);

			this.checkedStatus = false;
			this.disabledStatus = false;

			if (navigator.appVersion.indexOf("MSIE 6") > -1) {
				this.radio = (this.element.attr("type") == "radio");
			} else {
				this.radio = (this.element.is(':radio'));
			}

			this.visualElement = $('<span />')
				.addClass(this.radio ? 'ui-radio' : 'ui-checkbox');

			if (opts.replaceInput) {
				this.element
					.after(this.visualElement[0])

					.bind('usermode', function(e) {
						(e.enabled &&
							that.destroy.call(that, true));
					});

				$(this.visualElement).parent()
					.bind('click', function(e) {
						(!this.disabledStatus && that.toggle.call(that, e));
						return false;
					});
			}

			this.element
				.bind('click.checkBox', $.bind(this, this.reflectUI))

			if (opts.addLabel) {
				this.labels = $('label[for=' + this.element.attr('id') + ']')
			}

			this.reflectUI({ type: 'initialReflect' });
		},
		_changeStateClassChain: function() {
			var stateClass = (this.checkedStatus) ? '-checked' : '',
				baseClass = 'ui-' + ((this.radio) ? 'radio' : 'checkbox') + '-state';

			stateClass += (this.disabledStatus) ? '-disabled' : '';

			if (stateClass) {
				stateClass = baseClass + stateClass;
			}

			function switchStateClass() {
				var classes = this.className.split(' '),
					found = false;
				$.each(classes, function(i, classN) {
					if (classN.indexOf(baseClass) === 0) {
						found = true;
						classes[i] = stateClass;
						return false;
					}
				});
				if (!found) {
					classes.push(stateClass);
				}

				this.className = classes.join(' ');
			}

			this.labels.each(switchStateClass);
			this.visualElement.each(switchStateClass);
		},
		destroy: function(onlyCss) {
			this.element.removeClass('ui-helper-hidden-accessible');
			this.visualElement.addClass('ui-helper-hidden');
			if (!onlyCss) {
				var o = this.options;
				this.element.unbind('.checkBox');
				this.visualElement.remove();
				this.labels
					.unbind('.checkBox')
			}
		},

		disable: function() {
			this.element[0].disabled = true;
			this.reflectUI({ type: 'manuallyDisabled' });
		},

		enable: function() {
			this.element[0].disabled = false;
			this.reflectUI({ type: 'manuallyenabled' });
		},

		toggle: function(e) {
			this.changeCheckStatus((this.element.attr('checked')) ? false : true, e);
		},

		changeCheckStatus: function(status, e) {
			if (e && e.type == 'click' && this.element[0].disabled) {
				return false;
			}

			if (navigator.appVersion.indexOf("MSIE 6") > -1) {
				this.element.get(0).checked = status;
			} else {
				this.element.attr({ 'checked': status });
			}

			this.reflectUI(e || {
				type: 'changeCheckStatus'
			});
		},

		propagate: function(n, e, _noGroupReflect) {
			if (!e || e.type != 'initialReflect') {
				if (this.radio && !_noGroupReflect) {
					$(document.getElementsByName(this.element.attr('name')))
						.checkBox('reflectUI', e, true);
				}
				return this._trigger(n, e, {
					options: this.options,
					checked: this.checkedStatus,
					labels: this.labels,
					disabled: this.disabledStatus
				});
			}
		},

		reflectUI: function(elm, e) {
			//prevent uncheck radio
			if (this.element.is(":radio") && !e && !this.element.attr("checked")) return false;

			var oldChecked = this.checkedStatus,
				oldDisabledStatus = this.disabledStatus;
			e = e ||
				elm;

			this.disabledStatus = this.element.attr('disabled');
			this.checkedStatus = this.element.attr('checked');

			if (this.disabledStatus != oldDisabledStatus || this.checkedStatus !== oldChecked) {
				this._changeStateClassChain();

				(this.disabledStatus != oldDisabledStatus &&
					this.propagate('disabledChange', e));

				(this.checkedStatus !== oldChecked &&
					this.propagate('change', e));

				if ($(this.element[0]).attr('propagate') != "false") {
					$('a.trigger', this.element[0].parentNode.parentNode.parentNode.parentNode.parentNode).text($(this.element[0].parentNode).text());
				}
			}
		}
	});
	$.ui.checkBox.defaults = {
		replaceInput: true,
		addLabel: true
	};
})(jQuery);

/* DropDown */
var dropDownActive	= false;

function dropDownOpen() {
	
	if(!dropDownActive){
		dropDownClose();
		dropDownActive = $(this);

		$(this.parentNode).addClass("drop-down-opened");
		$('div.drop-down-body',this.parentNode).slideDown("fast");
		$('div.drop-down-body',this.parentNode).bind('click', dropDownClose);

		var dropDownActiveBody = dropDownActive[0].parentNode;

		setTimeout(function() { $('a.trigger',dropDownActiveBody).bind('click', dropDownClose); },100);
	}
}

function dropDownClose() {
	if(dropDownActive){
		var dropDownActiveBody = dropDownActive[0].parentNode;
		$('div.drop-down-body',dropDownActiveBody).slideUp("fast",function() {
			$(dropDownActiveBody).removeClass("drop-down-opened");
		});
		$(dropDownActive).unbind('click', dropDownClose);
	}

	dropDownActive = false;
}

/* Messages */

function setMessage(message, type, delay) {

	// IE9 Temp Workaround

	if ($.browser.msie && $.browser.version.substr(0, 1) >= 9 && type == "error") {
		return false;
	} else {
		if ($("#messagebox").length == 0) $("div.column-content").prepend("<div id=\"messagebox\" class=\"messagebox messagebox-hidden\"></div>");
		$("#messagebox").html(message).addClass("messagebox-" + type).fadeIn("slow", function() {
			setTimeout(function() { $("#messagebox").fadeOut("slow"); }, delay || 5000);
		});

		if ($(window).scrollTop() > 180) {
			$.scrollTo("#messagebox", { duration: 1000, axis: 'y' });
		}
	}
}

function setCustomMessage(message, params){
	var options = {
		elementId: "messagebox",
		insertType: "prepend",
		type: "",
		delay: 5000,
		referenceElement: "div.column-content",
		showCallback: null,
		hideCallback: null,
		moveTop: true,
		cssRules: {}
	}
	
	$.extend(options, params);
	
	var boxId = "#" + options.elementId;
	
	//if !exists element create it
	if (typeof $()[options.insertType] == "function" && $(boxId).length == 0) {
		$(options.referenceElement)[options.insertType]( 
			$("<div/>").attr({
				"id": options.elementId,
				"class": "messagebox messagebox-hidden"
			})
		);
	}

	$(boxId)
		.css(options.cssRules)
		.html(message)
		.removeClass("messagebox-success messagebox-error")
		.addClass("messagebox-" + options.type)
		.fadeIn("slow", function() {
			if (options.moveTop) { $(document).scrollTop($('#messagebox').position().top); }

			if (typeof options.showCallback == "function") options.showCallback();

			setTimeout(function() {
				$(boxId).fadeOut("slow", function() {
					if (typeof options.hideCallback == "function") options.hideCallback();
				});
			}, options.delay);
		});
}

/* NICE SELECT Plugin */
/*
* jQuery NICE SELECT Plugin 
* v2.0 (100% rewritten)
*
* replaces regular "select" elements with totally customizable html ui components
*/
(function($) {
	$.fn.niceSelect = function(options) {
		return this.each(function() {
			return new NiceSelect(this, options);
		});
	}
	// plugin defaults
	$.fn.niceSelect.defaults = {
		selectedClass: "selected", //class for the selected item
		overClass: "over", //class for hover items
		virtualInputClass: "nice_select", //class for the textfield item that displays the selected value
		lastClass: "last", //class for the last element of the list
		selectCallback: null, //callback function | equivalend to "onchange" in html | @params: 1 - JSON obj containing value and text 2 - the UL jquery object targeted
		openCallback: null, //callback function | executed when the user clicks on the virtual select and the list of options are opened  | @params: 1 - The textbox placeholder for select 2 - the UL jquery object targeted
		doQuery: true,
		forceSelection: true
	};

	var NiceSelect = function(el, options) {
		this.options = $.extend({}, $.fn.niceSelect.defaults, options);
		this.el = $(el);
		if (this.el.get(0).tagName.toLowerCase() != "select") return;
		this.el.attr("nice-select", true);
		this.id = this.el.attr("id");
		this.name = this.el.attr("name");
		this.expanded = false;
		this.queryDelay = null;
		this.initialize();
	};

	NiceSelect.prototype = {
		initialize: function() {
			this.build();
			this.events();
		},

		build: function() {
			this.queryDelay = null;
			this.closeDelay = null;
			this.scrolling = false;

			this.value = this.el.after('<input type="hidden" class="nice-select" name="' + this.name + '" id="' + this.id + '" value="' + this.el.val() + '" />').next();
			this.value.css("display", "none");
			this.value.data("niceSelect", this);
			this.wrapper = this.value.parents("div").eq(0);

			var selectedText = "";
			if (this.el.get(0)) {
				if (this.el.get(0).options.length > 0) {
					selectedText = this.el.get(0).options[this.el.get(0).selectedIndex].text;
				}
			}
			this.el.before('<span class="select ' + this.el.attr("class") + '"><input type="text" style="' + this.el.attr("style") + '" id="Select_' + this.id + '" rel="' + this.el.val() + '" value="' + selectedText + '" /></span>');
			this.el.hide();
			this.input = $("#Select_" + this.id);
			this.span = this.input.parent();
			if ($.browser.msie && parseInt($.browser.version) <= 7) {
				this.span.css("z-index", 2000 - $("input.nice-select").length);
			}

			this.defaultOption = null;
			var opts_obj = document.createElement("UL");
			var option = null;
			for (var i = 0; i < this.el[0].options.length; i++) {
				option = document.createElement("LI");
				$(option).attr("rel", this.el[0].options[i].value);
				$(option).html(this.el[0].options[i].text);
				if (i == this.el[0].options.length - 1)
					$(option).addClass(this.options.lastClass);
				if ($(option).attr("rel") == this.el.val())
					$(option).addClass(this.options.selectedClass);
				opts_obj.appendChild(option);
			}

			this.input.after(opts_obj);
			this.ul = $(opts_obj);
			this.ul.wrap("<div class='select-list'></div>");
			this.ul.attr("rel", this.id);
			this.list = this.span.children("div.select-list");
			this.items = $("li", opts_obj);

			this.dropdown = this.input.before("<div class=\"dropdown\"></div>").prev();
			if (!this.options.forceSelection) {
				this.input.val("").attr("rel", "");
				this.value.val("");
				this.items.filter("." + this.options.selectedClass).removeClass(this.options.selectedClass);
			}

			this.el.remove();
		},

		listEvents: function() {
			var $this = this;

			// List Events
			var onchange = this.onchange = this.el.attr("onchange");
			this.items.unbind("hover").unbind("click");
			this.items.hover(
				function() { $(this).addClass($this.options.overClass); },
				function() { $(this).removeClass($this.options.overClass); }
			).click(function(e) {
				var item = $(this);
				clearTimeout(this.closeDelay);
				var previous = {
					"text": $this.input.val(),
					"value": $this.value.val()
				};
				$this.input.val(item.text());
				$this.value.val(item.attr("rel"));
				$this.items.removeClass($this.options.selectedClass);
				item.addClass($this.options.selectedClass);
				$this.collapse();
				if ($this.options.selectCallback != null) {
					var arguments = [{ text: item.html(), value: item.attr("rel"), "previous": previous }, item.parent()];
					$this.options.selectCallback.apply($this, arguments);
				}
				if (onchange) onchange.call();
				return false;
			});
		},

		events: function() {
			var $this = this;

			// List Events
			var onchange = this.onchange = this.el.attr("onchange");
			this.items.hover(
				function() { $(this).addClass($this.options.overClass); },
				function() { $(this).removeClass($this.options.overClass); }
			).click(function(e) {
				var item = $(this);
				clearTimeout(this.closeDelay);
				$this.input.val(item.text());
				$this.value.val(item.attr("rel"));
				$this.items.removeClass($this.options.selectedClass);
				item.addClass($this.options.selectedClass);
				$this.collapse(true);
				return false;
			});

			// Input Events
			this.input.keyup(function(e) {
				clearTimeout(this.queryDelay);
				var code = e.which || e.keyCode;
				var key = $.keyOf($.ui.keyCode, code);
				key = key || String.fromCharCode(code).toLowerCase();
				switch (key) {
					case 'UP':
						$this.previous();
						break;
					case 'DOWN':
						$this.next();
						break;
					case 'ENTER':
						$this.collapse(true);
						break;
					case 'ESCAPE':
					case 'DELETE':
					case 'BACKSPACE':
						clearTimeout(this.queryDelay);
						$this.cancel();
						break;
					default:
						if (key.length == 1 && !e.ctrlKey) $this.doQuery();
						else clearTimeout(this.queryDelay);
				}
			}).keydown(function(e) {
				var code = e.which || e.keyCode;
				var key = $.keyOf($.ui.keyCode, code);
				key = key || String.fromCharCode(code).toLowerCase();
				if (key == 'TAB') {
					$this.list.css("display", "none");
					$this.collapse(true);
				}
			}).focus(function(e) {
				if ($this.options.doQuery) {
					$this.input.select();
				} else {
					setTimeout(function() {
						$this.input.selectRange($this.input.val().length, $this.input.val().length);
					}, 20);
				}
			}).blur(function(e) {
				clearTimeout($this.closeDelay);
				if (!$this.options.doQuery) return;
				this.closeDelay = setTimeout(function() {
					if ($this.scrolling) {
						$this.input.focus();
						$this.input.selectRange($this.input.val().length, $this.input.val().length);
						$this.scrolling = false;
					} else $this.collapse();
				}, 200);
			});

			this.span.click(function(e) {
				if (!$this.expanded) {
					$this.input.focus();
				}
				$this.toggle();
			});

			this.ul.mousedown(function(e) {
				$this.scrolling = true;
			}).mouseup(function(e) {
				$this.scrolling = false;
			});

		},

		doQuery: function(delay) {
			var $this = this;
			clearTimeout(this.queryDelay);
			if (!this.options.doQuery) return;
			this.queryDelay = setTimeout(function() {
				var matched = false, match = $this.input.val();
				if (match.length >= 2) {
					var found = [];
					$("li", $this.ul).each(function() {
						var item = $(this);
						matched = (match.toLowerCase() == item.text().substring(0, match.length).toLowerCase());
						item.css('display', matched ? 'block' : 'none');
						if (matched) found.push(item);
					});
					if (found.length > 0) {
						$this.items.removeClass($this.options.selectedClass);
						found[0].addClass($this.options.selectedClass);
						$this.wrapper.removeClass("control-select-scroll");
						if ($this.ul.height() > $this.list.height()) $this.wrapper.addClass("control-select-scroll");
						$this.input.val(found[0].text());
						$this.input.selectRange(match.length, found[0].text().length);
						$this.value.val(found[0].attr("rel"));
						$this.ensureVisible(found[0]);
					} else {
						$this.cancel();
					}
				} else {
					$this.cancel();
				}

			}, delay || 350);
		},

		forceSelection: function(doCallback) {
			clearTimeout(this.queryDelay);
			var selectedItem = this.list.find("li." + this.options.selectedClass);
			var match = this.input.val();
			var like = { found: [], matched: false };
			var exact = { found: [], matched: false };
			this.items.each(function() {
				var item = $(this);
				like.matched = (match.toLowerCase() == item.text().substring(0, match.length).toLowerCase());
				exact.matched = (match == item.text());
				if (like.matched) like.found.push(item);
				if (exact.matched) exact.found.push(item);
			});
			if (exact.found[0]) {
				this.select(exact.found[0], doCallback);
			} else {
				var forced = like.found[0] || selectedItem;
				this.select(this.options.forceSelection ? forced : match, doCallback);
			}
		},

		ensureVisible: function(el) {
			if (!el.get(0)) return;
			if (!this.expanded) this.list.css({ 'display': 'block', 'visibility': 'hidden' });
			var itemPos = el.position().top + this.ul.scrollTop() - 2;
			if (el.position().top < 0) this.ul.scrollTo(el.get(0));
			if (itemPos > this.ul.height() + this.ul.scrollTop() - el.height()) this.ul.scrollTo(itemPos - this.ul.height() + el.height() + 10);
			if (!this.expanded) this.list.css({ 'display': 'none', 'visibility': 'visible' });
		},

		previous: function() {
			this.expand();
			var current = $("li." + this.options.selectedClass, this.list);
			var prev = current.prevAll("li:visible:first");
			if (prev.get(0)) this.select(prev);
		},

		next: function() {
			this.expand();
			var current = $("li." + this.options.selectedClass, this.list);
			var next = current.nextAll("li:visible:first");
			if (next.get(0)) this.select(next);
		},

		select: function(item, doCallback) {
			var current = $("li." + this.options.selectedClass, this.list);
			current.removeClass(this.options.selectedClass);
			if (typeof item == "object") {
				item.addClass(this.options.selectedClass);
				this.input.val(item.text());
				this.value.val(item.attr("rel"));
				this.ensureVisible(item);
				if (doCallback && this.options.selectCallback != null) {
					var arguments = [{ text: item.html(), value: item.attr("rel") }, item.parent()];
					this.options.selectCallback.apply(this, arguments);
				} else if (doCallback && this.onchange != null) {
					this.onchange.call();
				}
			} else if (typeof item == "string") {
				this.input.val(item);
				this.value.val(item);
			}
		},

		cancel: function() {
			this.items.css('display', 'block');
			this.wrapper.removeClass("control-select-scroll");
			if (this.ul.height() > this.list.height()) this.wrapper.addClass("control-select-scroll");
			this.ensureVisible(this.list.find("li.selected"));
		},

		toggle: function() {
			if (!this.expanded) {
				this.expand();
			} else {
				this.collapse();
			}
		},

		expand: function() {
			if (this.expanded || this.items.length == 0) return;
			this.expanded = true;
			this.items.css("display", "block");
			this.list.width(this.input.width() + 33);
			this.wrapper.addClass("control-select-opened");

			var $this = this;
			$this.wrapper.removeClass("control-select-scroll");
			this.list.slideDown(100, function() {
				if ($this.ul.height() > $this.list.height()) $this.wrapper.addClass("control-select-scroll");
				$this.ensureVisible($this.list.find("li.selected"));
			});

			if (this.list.css("display") != "none" && this.options.openCallback != null) {
				var arguments = [this.input, this.items];
				this.options.openCallback.apply(this, arguments);
			}
		},

		collapse: function(doCallback) {
			this.forceSelection(doCallback);
			if (!this.expanded) return;
			this.expanded = false;
			this.wrapper.removeClass("control-select-opened");
			this.list.children("ul").slideUp(100, function() {
				$(this).parent().hide();
				$(this).show();
			});
		},

		setAutoComplete: function(value) {
			this.input.attr("readonly", value ? "" : "readonly");
			this.options.doQuery = value;
			if (value) return;
			this.dropdown.css("width", "100%");
			var $this = this;
			$(document).click(function(e) {
				var target = e.target || e.originalTarget;
				if ($this.expanded && target != $this.dropdown.get(0) && target != $this.input.get(0)) {
					$this.collapse();
				}
			});
		},

		reset: function() {
			this.select(this.defaultOption);
		},

		removeOption: function(value) {
			var option = this.ul.find("li[rel= " + value + "]");

			if (option.hasClass(".selected") || this.ul.find("li").length == 1) {
				this.unselect();
			}
			option.remove();

			this.updateList();
		},

		updateList: function() {
			var $this = this;

			var options = [];
			this.ul.find("li").each(function(i, li) {
				li = $(li);
				options.push($("<li/>").attr({ "rel": li.attr("rel") }).text(li.text()).get(0));
			});

			this.items = $([]);
			if (options.length > 0) {
				$.each(options, function(i, el) {
					$this.items.push(el);
				});

				this.ul.find("li").removeClass(this.options.lastClass);
				this.ul.find("li:last").addClass(this.options.lastClass);
				this.listEvents();
			}
		},

		unselect: function() {
			this.input.val("");
			this.value.val("");
			this.ul.find("li.selected").removeClass("selected");
		},

		append: function(list) {
			var $this = this;

			$.each(list, function(i, li) {
				var option = $("<li/>").attr({ "rel": li.value }).text(li.text);
				if ($this.items.length == 0) {
					$this.defaultOption = option;
					$this.ul.prepend(option);
				} else {
					$this.items.filter(":last").after(option);
				}
				$this.items.push(option.get(0));
			});

			$this.ul.find("li:last-child").addClass($this.options.lastClass);
			$this.listEvents();

			if ($(this.items).filter(".selected").length == 0 && $this.options.forceSelection) {
				$this.input.val($this.defaultOption.text());
				$this.value.val($this.defaultOption.attr("rel"));
			}
		},

		clearList: function() {
			this.items.remove();
			this.items = $([]);
			this.input.val("");
			this.value.val("");
			return this;
		}
	}

})(jQuery);

$.keyOf = function(hash, value) {
	for (var key in hash) {
		if (hash.hasOwnProperty(key) && hash[key] === value) return key;
	}
	return null;
};

$.fn.selectRange = function(start, end) {
	return this.each(function() {
		if (this.setSelectionRange) {
			this.focus();
			this.setSelectionRange(start, end);
		} else if (this.createTextRange) {
			var range = this.createTextRange();
			range.collapse(true);
			range.moveEnd('character', end);
			range.moveStart('character', start);
			range.select();
		}
	});
};

String.prototype.startsWith = function(prefix) {
	return (this.substr(0, prefix.length) === prefix);
};

String.prototype.endsWith = function(suffix) {
	return (this.substr(this.length - suffix.length) === suffix);
};

/* Label Insite */
function setLabelInside(scope) {
	if(scope.length>0) {

		var arrInputs = $("div.control-label-inside span.input-text input",scope[0]);

		for(var i=0,n;n=arrInputs[i];i++){
			if( $(n).val() != "" ) {
				$(n).parent().parent().addClass("control-content");
			}
			
			$(n).focus(function () {
				$(this).parent().parent().addClass("control-focused");
				$(this).parent().parent().addClass("control-content");
			}).blur(function () {
				$(this).parent().parent().removeClass("control-focused");
				if( $(this).val() == "" ) {
					$(this).parent().parent().removeClass("control-content");
				}
			});
			
		}
	}
}

/*
 * jQuery Watermark plugin
 * Version 0.9 (17-JUL-2009)
 * @requires jQuery v1.2.3 or later
 *
 * Examples at: http://mario.ec/projects/jqwatermark/
 * Copyright (c) 2009 Mario Estrada
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */

(function($) {
	$.fn.watermark = function(text, css_options) {
		css = $.extend({
			color: '#999',
			left: 4
		}, css_options);

		return this.each(function() {
			var input_marked = $(this);
			var label_text = text || $(this).attr('title');
			var watermark_label = $('<span class="watermark">' + label_text + '</span>');

			var height = $(this).outerHeight();

			checkVal($(this).val(), watermark_label);

			watermark_label.click(function() {
				$(this).next().focus();
			})

			if( !$(this).prev().hasClass("watermark") ) {
				$(this).before(watermark_label).focus(function() {
					checkVal($(this).val(), watermark_label);
					watermark_label.addClass("watermark-active");
				}).blur(function() {
					checkVal($(this).val(), watermark_label);
					watermark_label.removeClass("watermark-active");
				}).keydown(function(e) {
					$(watermark_label).hide();
				});
			}
		});
	};

	var checkVal = function(val, elem) {
		if ($.trim(val) == '') $(elem).show().next().val("");
		else $(elem).hide();
	};

})(jQuery);

// Delay Plugin for jQuery
// - http://www.evanbot.com
// - © 2008 Evan Byrne

jQuery.fn.delay = function(time, func) {
	this.each(function() {
		setTimeout(func, time);
	});
	return this;
};

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
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;
	}
};

/* Force Numbers Mask */
jQuery.fn.forceNumericOnly = function() {
	return this.each(function() {
		jQuery(this).keydown(function(e) {
			var key = e.charCode || e.keyCode || 0;
			// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
			return (
				key == 8 || 
				key == 9 ||
				key == 46 ||
				(key >= 37 && key <= 40) ||
				(key >= 48 && key <= 57) ||
				(key >= 96 && key <= 105));
		})
	})
};

/* Truncate String */
(function($) {

	$.fn.extend({

		widthTruncate: function(options) {
			var defaults = {
				width: 'auto',
				after: '...'
			};

			options = $.extend(defaults, options);

			return this.each(function() {
				if (options.width == 'auto') {
					truncateWidth = $(this).width() - 8;
				} else {
					truncateWidth = options.width
				}
				if ($(this).width() > truncateWidth) {
					var smaller_text = $(this).text();
					$(this).html('<span id="truncateWrapper" style="display:inline;">' + options.after + '</span>');
					i = 1;
					while ($('#truncateWrapper').width() < truncateWidth) {
						$('#truncateWrapper').html(smaller_text.substr(0, i) + options.after);
						i++;
					}
					$(this).html($('#truncateWrapper').html());
				}
			});
		},

		heightTruncate: function(options) {
			var defaults = {
				height: 'auto',
				after: '...'
			};

			options = $.extend(defaults, options);

			return this.each(function() {
				var truncateHeight = (options.height == 'auto') ? $(this).height() : options.height;
				var text = $(this).text(),
					wrapper = $("<span>").css({ "display": "inline" }).html(text);
				$(this).html(wrapper);
				if (wrapper.height() > truncateHeight) {
					var i = 0;
					wrapper.empty();
					while (i <= text.length && wrapper.height() <= truncateHeight) {
						i++;
						wrapper.html(text.substr(0, i) + options.after);
					}
					wrapper.html(text.substr(0, i - 2) + options.after);
				}
				$(this).html(wrapper.html());
			});
		}

	});

})(jQuery);

/* URL Encode */
$.extend({
	URLEncode: function (c) {
		var o = '';
		var x = 0;
		c = c.toString();
		var r = /(^[a-zA-Z0-9_.]*)/;
		while (x < c.length) {
			var m = r.exec(c.substr(x));
			if (m != null && m.length > 1 && m[1] != '') {
				o += m[1];
				x += m[1].length;
			} else {
				if (c[x] == ' ') o += '+';
				else {
					var d = c.charCodeAt(x);
					var h = d.toString(16);
					o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
				}
				x++;
			}
		}
		return o;
	},
	URLDecode: function (s) {
		var o = s;
		var binVal, t;
		var r = /(%[^%]{2})/;
		while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
			b = parseInt(m[1].substr(1), 16);
			t = String.fromCharCode(b);
			o = o.replace(m[1], t);
		}
		return o;
	}
});

/* cssProperty */
$.support.cssProperty = (function() {
	function cssProperty(p, rp) {
		var b = document.body || document.documentElement,
	s = b.style;

		// No css support detected
		if (typeof s == 'undefined') { return false; }

		// Tests for standard prop
		if (typeof s[p] == 'string') { return rp ? p : true; }

		// Tests for vendor specific prop
		v = ['Moz', 'Webkit', 'Khtml', 'O', 'Ms'],
	p = p.charAt(0).toUpperCase() + p.substr(1);
		for (var i = 0; i < v.length; i++) {
			if (typeof s[v[i] + p] == 'string') { return rp ? (v[i] + p) : true; }
		}
	}

	return cssProperty;
});

/* Ajax Setup */
$.ajaxSetup({
	cache: false
});

var BrowserSelector = {
	initialize: function() {
		if (!!document.documentElement.className.match(/js/g)) return false;
		
		var u = navigator.userAgent,
			ua = u.toLowerCase(),
			is = function(t) {
				return ua.indexOf(t) > -1;
			},
			g = 'gecko',
			w = 'webkit',
			s = 'safari',
			o = 'opera',
			h = document.documentElement,
			b = [(!(/opera|webtv/i.test(ua)) && /msie\s(\d)/.test(ua)) ? ('ie ie' + RegExp.$1) : is('firefox/4') ? g + ' ff ff4' : is('firefox/2') ? g + ' ff2' : is('firefox/3.5') ? g + ' ff3 ff3_5' : is('firefox/3') ? g + ' ff3' : is('gecko/') ? g : is('opera') ? o + (/version\/(\d+)/.test(ua) ? ' ' + o + RegExp.$1 : (/opera(\s|\/)(\d+)/.test(ua) ? ' ' + o + RegExp.$2 : '')) : is('konqueror') ? 'konqueror' : is('chrome') ? w + ' chrome' : is('iron') ? w + ' iron' : is('applewebkit/') ? w + ' ' + s + (/version\/(\d+)/.test(ua) ? ' ' + s + RegExp.$1 : '') : is('mozilla/') ? g : '', is('j2me') ? 'mobile' : is('iphone') ? 'iphone' : is('ipod') ? 'ipod' : is('mac') ? 'mac' : is('darwin') ? 'mac' : is('webtv') ? 'webtv' : is('win') ? 'win' : is('freebsd') ? 'freebsd' : (is('x11') || is('linux')) ? 'linux' : '', 'js'];
		c = b.join(' ');
		h.className += ' ' + c;
		$("html").addClass(c);
	}
};

$(document).ready(function() {
	BrowserSelector.initialize();
});


/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) return "";

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

/*
 * jQuery Text Overflow v0.7
 *
 * Licensed under the new BSD License.
 * Copyright 2009-2010, Bram Stein
 * All rights reserved.
 */
(function(c){var b=document.documentElement.style,d=("textOverflow" in b||"OTextOverflow" in b),a=function(f,i){var h=0,e=[],g=function(j){var l=0,k;if(h>i){return}for(l=0;l<j.length;l+=1){if(j[l].nodeType===1){k=j[l].cloneNode(false);e[e.length-1].appendChild(k);e.push(k);g(j[l].childNodes);e.pop()}else{if(j[l].nodeType===3){if(h+j[l].length<i){e[e.length-1].appendChild(j[l].cloneNode(false))}else{k=j[l].cloneNode(false);k.textContent=c.trim(k.textContent.substring(0,i-h));e[e.length-1].appendChild(k)}h+=j[l].length}else{e.appendChild(j[l].cloneNode(false))}}}};e.push(f.cloneNode(false));g(f.childNodes);return c(e.pop().childNodes)};c.extend(c.fn,{textOverflow:function(g,e){var f=g||"&#x2026;";if(!d){return this.each(function(){var l=c(this),m=l.clone(),p=l.clone(),k=l.text(),h=l.width(),n=0,o=0,j=k.length,i=function(){if(h!==l.width()){l.replaceWith(p);l=p;p=l.clone();l.textOverflow(g,false);h=l.width()}};l.after(m.hide().css({position:"absolute",width:"auto",overflow:"visible","max-width":"inherit"}));if(m.width()>h){while(n<j){o=Math.floor(n+((j-n)/2));m.empty().append(a(p.get(0),o)).append(f);if(m.width()<h){n=o+1}else{j=o}}if(n<k.length){l.empty().append(a(p.get(0),n-1)).append(f)}}m.remove();if(e){setInterval(i,200)}})}else{return this}}})})(jQuery);
