/* 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){
			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) {
	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
	}
	
	$.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)
		.html(message)
		.removeClass("messagebox-success messagebox-error")
		.addClass("messagebox-" + options.type)
		.fadeIn("slow", function() {
			if(typeof options.showCallback == "function") options.showCallback();
			
			setTimeout(function() { 
				$(boxId).fadeOut("slow", function(){
					if(typeof options.hideCallback == "function") options.hideCallback();	
				}); 
			}, options.delay);
		});

	if ($(window).scrollTop() > 180) {
	    $.scrollTo(boxId, { duration: 1000, axis: 'y' });
	}
}

/* NICE SELECT Plugin */
/*
* jQuery NICE SELECT Plugin 
* v1.0
* Author: Dragos Badea (bedeabza@gmail.com)
* v2.0 (100% rewritten)
* Author: Guilherme Dupont
*
* 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
	};

	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.queryeDelay = 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.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);
			}

			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.list = this.span.children("div.select-list");
			this.items = $("li", opts_obj);

			this.dropdown = this.input.before("<div class=\"dropdown\"></div>").prev();

			this.el.remove();
		},

		events: function() {
			var $this = this;

			// List Events
			var 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();
				if ($this.options.selectCallback != null) {
					var arguments = [{ text: item.html(), value: item.attr("rel") }, item.parent()];
					$this.options.selectCallback.apply(this, arguments);
				}
				if (onchange) onchange.call();
				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();
						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();
				}
			}).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) {
				$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() {
			clearTimeout(this.queryDelay);
			var selectedItem = this.list.find("li." + this.options.selectedClass);
			var matched = false, match = this.input.val();
			var found = [];
			this.items.each(function() {
				var item = $(this);
				matched = (match.toLowerCase() == item.text().substring(0, match.length).toLowerCase());
				if (matched) found.push(item);
			});
			var forced = found[0] || selectedItem;
			this.items.removeClass(this.options.selectedClass);
			forced.addClass(this.options.selectedClass);
			this.input.val(forced.text());
			this.value.val(forced.attr("rel"));
			this.ensureVisible(forced);
		},

		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)) {
				current.removeClass(this.options.selectedClass);
				prev.addClass(this.options.selectedClass);
				this.input.val(prev.text());
				this.value.val(prev.attr("rel"));
				this.ensureVisible(prev);
			}
		},

		next: function() {
			this.expand();
			var current = $("li." + this.options.selectedClass, this.list);
			var next = current.nextAll("li:visible:first");
			if (next.get(0)) {
				current.removeClass(this.options.selectedClass);
				next.addClass(this.options.selectedClass);
				this.input.val(next.text());
				this.value.val(next.attr("rel"));
				this.ensureVisible(next);
			}
		},

		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) 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() {
			this.forceSelection();
			if (!this.expanded) return;
			this.expanded = false;
			this.wrapper.removeClass("control-select-opened");
			this.list.slideUp(100);
		},

		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();
				}
			});
		}

	}

})(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();
		}
	});
};

/* 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 === undefined ? $(this).attr('title') : 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();
			})

			$(this).before(watermark_label).focus(function() {
				checkVal($(this).val(), watermark_label);
				watermark_label.animate({ opacity : 0.4}, 250);
			}).blur(function(){
				checkVal($(this).val(), watermark_label);
				watermark_label.animate({ opacity : 1}, 250);
			}).keydown(function(e){
				$(watermark_label).hide();
			});
		});
	};
	
	checkVal = function(val, elem) {
		if(val == '') $(elem).show();
		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;
	}
};