// JavaScript Document

/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 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
*
*/
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

function equalHeight(group) {
	var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}

 


/*** auto tuncate **/
(function($){
	/**
		 * Equal Heights Plugin
		 * Equalize the heights of elements. Great for columns or any elements
		 * that need to be the same size (floats, etc).
		 * 
		 * Version 1.0
		 * Updated 12/10/2008
		 *
		 * Copyright (c) 2008 Rob Glazebrook (cssnewbie.com) 
		 *
		 * Usage: $(object).equalHeights([minHeight], [maxHeight]);
		 * 
		 * Example 1: $(".cols").equalHeights(); Sets all columns to the same height.
		 * Example 2: $(".cols").equalHeights(400); Sets all cols to at least 400px tall.
		 * Example 3: $(".cols").equalHeights(100,300); Cols are at least 100 but no more
		 * than 300 pixels tall. Elements with too much content will gain a scrollbar.
		 * 
		 */

		(function($) {
			$.fn.equalHeights = function(minHeight, maxHeight) {
				tallest = (minHeight) ? minHeight : 0;
				this.each(function() {
					if($(this).height() > tallest) {
						tallest = $(this).height();
					}
				});
				if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
				return this.each(function() {
					$(this).height(tallest).css("overflow","auto");
				});
			}
		})(jQuery);
		
		(function($) {
			$.fn.equalRowHeight = function(minHeight, maxHeight) {
				var currentTallest = 0,
				currentRowStart = 0,
				rowDivs = new Array(),
				$el,
				topPosition = 0;
				
				this.each(function() {
					$el = $(this);
					topPostion = $el.position().top;

					if (currentRowStart != topPostion) {

					// we just came to a new row.  Set all the heights on the completed row
					for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
						rowDivs[currentDiv].height(currentTallest);
					}

					// set the variables for the new row
					rowDivs.length = 0; // empty the array
					currentRowStart = topPostion;
					currentTallest = $el.height();
					rowDivs.push($el);

					} else {

					// another div on the current row.  Add it to the list and check if it's taller
					rowDivs.push($el);
					currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);

					}

					// do the last row
					for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
					rowDivs[currentDiv].height(currentTallest);
					}

				});
			}
		})(jQuery);

	$.fn.truncate = function( max, settings ) {
		settings = $.extend( {
			chars: /\s/,
			trail: [ "...", "" ]
		}, settings );
		
		var ie = $.browser.msie;
		function fixIE( o ) {
			if ( ie ) {
				o.style.removeAttribute( "filter" );
			}
		}
		
		var parseSubChilds = function(element, maxLength) {
			var element = $(element),
				html = element.html()
					.replace(/ +/, ' ')
					.replace(/\r\n\t/,'')
					.replace(/^ +/, '')
					.replace(/ +$/, ''),
				childs, 
				b = true, i = 0, c = 0, count = 0;
			
			element.html(html);
			childs = element[0].childNodes;
			
			b = true;
			for (i=0; i < childs.length; i++) {
				if (!b) {
					element[0].removeChild(childs[i]);
					continue;
				}
				
				if (childs[i].nodeType == 3) {		//text node
					text = $(childs[i]).text().replace(/\s+/g,' ');
					c = text.length;
					if ( (count+c) > maxLength ) {
						text = text.substring(0, maxLength - count);
						text = text.substring(0, text.lastIndexOf(" "));
						childs[i].nodeValue = text;
						
						count += text.length;
						b = false;
					} else {
						count += c;
					}
				}
				else if (childs[i].nodeType == 1) {	//element node
					if (!parseSubChilds(childs[i], maxLength - count)) {
						text = $(childs[i]).text().replace(/\s+/g,' ');
						count += text.length;
						b = false;
					}
				}
			}
			return b;
		}

		var parseChilds = function(element, maxLength){
			var element = $(element);
			var childs = element.children();
			var count = 0, c = 0;
			var stop = false, s = true;
			
			for (i=0; i < childs.length; i++) {
				if (stop) {
					$(childs[i]).remove();
					continue;
				}
				
				c = $(childs[i]).text().replace(/\s+/g,' ').length;
				
				if ((count+c) > maxLength) {
					s = parseSubChilds(childs[i], maxLength - count);
					stop = true;
				}
				
				count +=c ;
			}
			
			if ( !stop && s ) {
				return false;
			} else {
				return true;
			}
		};
		
		
		return this.each( function() {
			var el = $(this),
				truncated = false,
				originalHTML = el.html(),
				ellipsisHTML = el.html();
				
			truncated = parseChilds(el, max);
			ellipsisHTML = el.html();
			
			if ( !truncated ) {
				return;
			}
			
			el.html($("<div />").addClass("truncate_less").append(el.html()).append(settings.trail[ 0 ]));
			
			$(".truncate_show", el).click(function(event) {
				if ( $(".truncate_more", el).length < 1) {
					el.append($("<div />").addClass("truncate_more").css("display", "none").append(originalHTML).append(settings.trail[ 1 ]));
					
					$(".truncate_hide", el).click(function(event) {
						$(".truncate_more", el).css( "background", "#fff" ).fadeOut( 0, function() {
							$(".truncate_less", el).css( "background", "#fff" ).fadeIn( 0, function() {
                                fixIE( this );
                                $(this).css( "background", "none" );
                            });
                            fixIE( this );
                        });
                        return false;
					});
				}
				
				
				$( ".truncate_less", el ).fadeOut( 0, function() {
                    $( ".truncate_more", el ).fadeIn( 0, function() {
                        fixIE( this );
                    });
                    fixIE( this );
                });
				
				
                $(".truncate_show", el).click( function() {
                    $( ".truncate_less", el ).css( "background", "#fff" ).fadeOut( 0, function() {
                        $( ".truncate_more", el ).css( "background", "#fff" ).fadeIn( 0, function() {
                            fixIE( this );
                            $(this).css( "background", "none" );
                        });
                        fixIE( this );
                    });
                    return false;
                });
                return false;
				
			});
		});
	};
})(jQuery);

// checkboxes dropdown //
(function($){
	var _scrollbarWidth = null;
	
	function scrollbarWidth() {
			
		if ( _scrollbarWidth !== null ) {
			return _scrollbarWidth;
		}
		
		var div = $('<div style="width:100px;height:100px;overflow:hidden;position:absolute;top:-300px;left:-300px;"><div style="height:200px;"></div>');
		$('body').append(div);
		var w1 = $('div', div).innerWidth();
		div.css('overflow', 'auto');
		var w2 = $('div', div).innerWidth();
		div.remove();
		
		_scrollbarWidth = Math.max(w1 - w2, 17);
		
		return _scrollbarWidth;
	};
		
	var num = function(el, props) {
		var r = 0;
		$.each(props.split(/\s+/) || [], function(i,v){
			r += parseInt($(el).css(v)) || 0;
		});
		return r;
	}
	
	$.fn.checkboxesDropdown = function(options){
		var isMethodCall = (typeof options == "string"),
			args = Array.prototype.slice.call(arguments, 1);
			
		return this.each(function() {
			var instance = $(this).data("checkboxesDropdown");
			if (isMethodCall && instance && $.isFunction(instance[options])) {
				instance[options].apply(instance, args);
			} else if (!instance) {
				$(this).data("checkboxesDropdown", new $.checkboxesDropdown(this, options));
			}
		});
	};
	
	var checkboxesDropdown = $.checkboxesDropdown = function(element, options) {
		this.element = $(element);
		this.options = $.extend({}, $.checkboxesDropdown.defaults, options);
		this.init();
	};
	
	$.extend($.checkboxesDropdown.prototype, {
		init: function() {
			var self = this, w, isAllChecked = false, isNoneChecked = false, html = "",
				//save some styles
				oldPosition = this.element.css("position") || "static", 
				oldLeft = this.element.css("left") || "auto", 
				oldTop = this.element.css("top") || "auto",
				oldRight = this.element.css("right") || "auto", 
				oldBottom = this.element.css("bottom") || "auto";
				
			this.element.addClass("checkboxesDropdown-js");
			
			//is the base control has auto width
			this.autoWidth = ((this.element[0].style.width || "auto") == "auto");
			
			//is the base control is a multiple select ?
			this.isMultiple = (this.element[0].type === "select-multiple");
			
			//if the base control has auto width and NOT a multiple select, we don't need this
			if ( this.autoWidth && !this.isMultiple ) {
				return;
			}
			
			//hide original element
			this.element.css({
				position: "absolute",
				left: -5000,
				right:"auto",
				top:-5000,
				bottom:"auto",
				visibility: "hidden"
			});
			
			
			//create fake dropdown
			$.checkboxesDropdown.guid++;
			this.guid = "checkboxesDropdown_" + $.checkboxesDropdown.guid;
			this.fullSize = this.element.attr("checkboxes_dropdown_full_size") || 0;
			
			this.clone = $("<select name='" + this.guid + "' id='" + this.guid + "'><option value=''></option></select>").css({
				display: this.element.css("display"),
				width: this.element.css("width"),
				cssFloat: this.element.css("cssFloat"),
				fontSize: this.element.css("fontSize"),
				fontWeight: this.element.css("fontWeight"),
				lineHeight: this.element.css("lineHeight"),
				letterSpacing: this.element.css("letterSpacing"),
				color: this.element.css("color"),
				background: this.element.css("background"),
				border: this.element.css("border"),
				fontFamily: this.element.css("fontFamily"),
				marginLeft: this.element.css("marginLeft") || "0",
				marginTop: this.element.css("marginTop") || "0",
				marginRight: this.element.css("marginRight") || "0",
				marginBottom: this.element.css("marginBottom") || "0",
				paddingLeft: this.element.css("paddingLeft") || "0",
				paddingRight: this.element.css("paddingRight") || "0",
				paddingTop: this.element.css("paddingTop") || "0",
				paddingBottom: this.element.css("paddingBottom") || "0",
				position: oldPosition,
				left: oldLeft,
				top: oldTop,
				right: oldRight,
				bottom: oldBottom
			}).insertBefore(this.element);
			
			//create the popup checkboxes list
			this.dropdown = $("<div id='" + this.guid + "_dropdown' class='checkboxesDropdown-dropdown'></div>").appendTo("body");
			this.dropdownList = $("<div class='checkboxesDropdown-dropdown_list'></div>").appendTo(this.dropdown);
			
			if ( !this.isMultiple ) {
				this.dropdown.addClass("checkboxesDropdown-dropdown-single");
			}
			
			//cloned width
			this.cloneWidth = Math.ceil(this.clone.outerWidth(true));
			
			this.nothingSelectedText = this.options.nothingSelectedText;
			
			html = "";
			$("option", this.element).each(function(){
				var 
					optionId = self.isMultiple ? "checkboxesDropdown_" + (++$.checkboxesDropdown.guid) + "_option" : "",
					selected = this.selected ? "checked='checked'" : "",
					value = $(this).val() || "",
					isAll = (value.toLowerCase() == "all"),
					isNone = (value.toLowerCase() == "none"),
					className = isAll ? "class='checkAll'" : (isNone ? "class='uncheckAll'" : "");
				
				if (value == "") {
					self.nothingSelectedText = $.trim($(this).text());
					
				} else {
					if ( self.isMultiple ) {
						html += "<div class='checkboxesDropdown-dropdown_list_item'><label for='" + optionId + "'><input type='checkbox' name='" + optionId + "' id='" + optionId + "' value='" + $(this).val() + "' " + selected + " " + className + "> " + $.trim($(this).text()) + "</label></div>";
					} else {
						if ( this.selected ) {
							selected = "class='checkboxesDropdown-dropdown_list_item_checked'";
						}
						html += "<div class='checkboxesDropdown-dropdown_list_item'><label option_value='"+ $(this).val() +"' "+ selected +">" + $.trim($(this).text()) + "</label></div>";
					}
				}
				
				if ( this.selected && isAll && self.isMultiple ) {
					isAllChecked = true;
				}
				if ( this.selected && isNone && self.isMultiple ) {
					isNoneChecked = true;
				}
			});
			
			self.dropdownList.html(html);
			
			//'none' has top priority
			if ( isNoneChecked ) {
				$(":checkbox", self.dropdownList).not(".uncheckAll").removeAttr("checked");
			} else if ( isAllChecked ) {
				$(":checkbox", self.dropdownList).not(".uncheckAll").attr("checked", "checked");
			}
			
			this.dropdown_defWidth = this.fullSize ? "auto" : this.element.innerWidth() - num(this.element, "borderLeftWidth borderRightWidth paddingLeft paddingRight") - 2;
			this.dropdown.css({
				width: this.dropdown_defWidth,
				height: "auto",
				display: "none",
				fontFamily: this.element.css("fontFamily"),
				fontSize: this.element.css("fontSize"),
				fontWeight: this.element.css("fontWeight"),
				color: this.element.css("color")
			});
			
			this.updateResult();
			
			//events
			this.skipCheckboxChange = false;
			this.clone.bind("mousedown", $.proxy(this._onMouseDown, this));
			this.element.bind("change", $.proxy(this._onElementChange, this));
			
			if ( this.isMultiple ) {
				$(":checkbox", this.dropdownList).bind("change", $.proxy(this._onCheckboxChange, this));
			} else {
				$("label", this.dropdownList).bind("mousedown", $.proxy(this._onLabelMouseDown, this));
			}
			
			this.isOpen = false;
			
			$.checkboxesDropdown.bind_html_click();
			
			self = null;
		},
		
		_onElementChange: function(event) {
			var self = this, isAllChecked = false, isNoneChecked = false;
			if (!this.skipCheckboxChange) {
				this.skipCheckboxChange = true;
				
				$("option", this.element).each(function(){
					var val = $(this).val() || "",
						selected = this.selected ? "checked='checked'" : "",
						isAll = (val.toLowerCase() == "all"),
						isNone = (val.toLowerCase() == "none");
						
					if ( this.selected && isAll && !isNoneChecked ) {
						isAllChecked = true;
					}
					if ( this.selected && isNone ) {
						isNoneChecked = true;
						isAllChecked = false;
					}
					
					if (this.selected) {
						$(":checkbox[value='" + val + "']", self.dropdownList).attr("checked", "checked");
					} else {
						$(":checkbox[value='" + val + "']", self.dropdownList).removeAttr("checked");
					}
				});
				
				//'none' has top priority
				if ( isNoneChecked ) {
					$(":checkbox", this.dropdownList).not(".uncheckAll").removeAttr("checked");
				} else if ( isAllChecked ) {
					$(":checkbox", this.dropdownList).not(".uncheckAll").attr("checked", "checked");
				}
				
				this.updateResult();
				this.skipCheckboxChange = false;
			}
			
			self = null;
		},
		
		_onMouseDown: function(event) {
			var self = this;
			
			if (this.isOpen) {
				this.hide();
			} else {
				this.show();
			}
			
			self.clone.focus();
			window.setTimeout(function() {
				self.clone.blur();
				self = null;
			},0);
			
			event.preventDefault();
			event.stopPropagation();
			
			return false;
		},
		
		_onLabelMouseDown: function(event) {
			var label = $(event.target).closest("label");
			
			if ( !label.hasClass("checkboxesDropdown-dropdown_list_item_checked") ) {
				$("label", this.dropdownList).removeClass("checkboxesDropdown-dropdown_list_item_checked");
				label.addClass("checkboxesDropdown-dropdown_list_item_checked");
			}
			
			this.updateResult();
			
			event.preventDefault();
			
			$.checkboxesDropdown.hideCurrent();
			
			return false;
		},
		
		_onCheckboxChange: function(event) {
			if (!this.skipCheckboxChange) {
				this.skipCheckboxChange = true;
				
				if ( $(event.target).is(".uncheckAll") ) {
					if (event.target.checked) {
						$(":checkbox", this.dropdownList).not(".uncheckAll").removeAttr("checked");
					}
					
				} else if ( $(event.target).is(".checkAll") ) {
					if (event.target.checked) {
						$(":checkbox", this.dropdownList).attr("checked", "checked").filter(".uncheckAll").removeAttr("checked");
						
					} else {
						$(":checkbox", this.dropdownList).removeAttr("checked");
					}
					
				} else {
					if (event.target.checked) {
						if ($(":checkbox", this.dropdownList).not(".checkAll").length == $(":checkbox:checked", this.dropdownList).not(".checkAll").length) {
							$(":checkbox.checkAll", this.dropdownList).attr("checked", "checked");
						}
					} else {
						$(":checkbox.checkAll", this.dropdownList).removeAttr("checked");
					}
				}
				
				this.skipCheckboxChange = false;
				
				this.updateResult();
			}
		},
		
		show: function() {
			var 
				$window = $(window),
				windowW = $window.width(), 
				windowH = $window.height(), 
				scrollX = $window.scrollLeft(), 
				scrollY = $window.scrollTop(), 
				maxTop, maxRight, maxBottom, maxLeft,
				cloneHeight = this.clone.outerHeight(),
				offset = this.clone.offset(),
				left = offset.left,
				top = offset.top + cloneHeight,
				verticalScroll, 
				listW, listH, dropdownW, dropdownH, showW, showH,
				scrollW = scrollbarWidth();
				
			$.checkboxesDropdown.hideCurrent();
			
			this.offset = offset;
			
			this.dropdown.css({
				display: "block",
				visibility: "visible",
				width: this.dropdown_defWidth,
				height: "auto"
			});	
			
			listW = Math.ceil(this.dropdownList.width());
			listH = Math.ceil(this.dropdownList.height());
			
			verticalScroll = false;
			showW = dropdownW = Math.ceil(this.dropdown.outerWidth(true));
			showH = dropdownH = Math.ceil(this.dropdown.outerHeight(true));
			
			maxTop = offset.top - scrollY - this.options.topSpace;
			maxRight = windowW - (offset.left - scrollX);
			maxBottom = windowH - (offset.top + cloneHeight - scrollY) - this.options.topSpace;
			maxLeft = offset.left - scrollX;
			
			if ( maxTop > maxBottom ) {
				if ( dropdownH > maxTop ) {
					showH = maxTop;
				}
				top = offset.top - showH;
			} else {
				if ( dropdownH > maxBottom ) {
					showH = maxBottom;
				}
			}
			
			if ( showH < dropdownH ) {
				verticalScroll = true;
			}
			
			if ( verticalScroll ) {
				showH = showH - num(this.dropdown, "paddingTop paddingBottom marginTop marginBottom borderTopWidth borderBottomWidth");
				showW = showW + scrollW + 7;
			} else {
				showH = "auto";
			}
			
			if ( showW < this.cloneWidth ) {
				showW = this.cloneWidth;
				
			}
			
			this.dropdown.css({
				width: showW - num(this.dropdown, "paddingLeft paddingRight marginLeft marginRight borderLeftWidth borderRightWidth"),
				height: showH,
				left: left,
				top: top,
				display:"block",
				visibility:"visible"
			});
			
			this.isOpen = true;
			$.checkboxesDropdown.current =  this.element;
		},
		
		hide: function() {
			this.dropdown.hide();
			this.isOpen = false;
		},
		
		updateResult: function(){
			var values = [], texts = [], isAll = false, isNone = false, self = this, val;
			
			
			
			if ( this.isMultiple ) {
				
				$(":checkbox:checked", this.dropdownList).each(function(){
					val = $(this).val() || "";
					
					if ( val.toLowerCase() === "all" && !isNone ) {
						isAll = true;
						values = [ val ];
						texts = [ $.trim($(this).closest("label").text()) ];
						return false;
					} else if ( val.toLowerCase() === "all" ) {
						isNone = true;
						isAll = false;
						values = [ val ];
						texts = [ $.trim($(this).closest("label").text()) ];
						return false;
					} else {
						values.push( val );
						texts.push( $.trim($(this).closest("label").text()) );
					}
				});
				
			} else {
				val = $("label.checkboxesDropdown-dropdown_list_item_checked", this.dropdownList);
				
				if ( val.length ) {
					texts.push( $.trim($(val[0]).text()) );
					val = $(val[0]).attr("option_value") || "";
					values.push( val );
					
				} else {
					val = "";
					texts.push("");
					values.push("");
				}
				
				$("option[value='" + val + "']:eq(0)", this.element).get(0).selected = true;
			}
				
			if (values.length < 1 ) {
				$("option", this.clone).val("").text(this.nothingSelectedText);
				this.clone.attr("title", this.nothingSelectedText);
			} else {
				$("option", this.clone).val(values.join(", ")).text(texts.join(", "));
				this.clone.attr("title", texts.join(", "));
			}
				
			if ( this.isMultiple ) {
				$(":checkbox", this.dropdownList)
					.filter(":checked")
						.each(function(){
							if (this.checked) {
								$("option[value='" + this.value + "']", self.element).get(0).selected = true;
							} else {
								$("option[value='" + this.value + "']", self.element).get(0).selected = false;
							}
						})
						.closest("label").addClass("checkboxesDropdown-dropdown_list_item_checked")
					.end().end()
					.not(":checked").closest("label").removeClass("checkboxesDropdown-dropdown_list_item_checked");
					
			}
			
			
		}
	});
	
	$.extend($.checkboxesDropdown, {
		guid:1,
		defaults: {
			nothingSelectedText: "Select",
			bottomSpace: 16,
			topSpace: 16
		},
		
		current: null,
		currentDropdown: null,
		currentParent: null,
		
		bind_html_click: function() {
			$("html")
				.unbind("mousedown.checkboxesDropdown")
				.bind("mousedown.checkboxesDropdown", function(e) {
					if ( $(e.target).closest(".checkboxesDropdown-dropdown").length < 1) {
						$.checkboxesDropdown.hideCurrent();
					}
				});
				
			$.checkboxesDropdown.bind_html_click = $.noop;
		},
		
		hideCurrent: function() {
			if ( $.checkboxesDropdown.current ) {
				$.checkboxesDropdown.current.checkboxesDropdown("hide");
			}
			
			$.checkboxesDropdown.currentDropdown = $.checkboxesDropdown.currentParent = null;
			$.checkboxesDropdown.current = null;
		}
	});
	
	$(window).unload(function(){
		$.checkboxesDropdown.current = null;
	});
})(jQuery);

// defText
(function($){
	$.fn.defText = function(options){
		var isMethodCall = (typeof options == "string"),
			args = Array.prototype.slice.call(arguments, 1);
			
		return this.each(function() {
			var instance = $(this).data("defText");
			if (isMethodCall && instance && $.isFunction(instance[options])) {
				instance[options].apply(instance, args);
			} else if (!instance) {
				$(this).data("defText", new $.defText(this, options));
			}
		});
	};
	
	var defText = $.defText = function(element, options) {
		this.element = $(element);
		this.options = $.extend(true, {},$.defText.defaults, options);
		this.init();
	};
	
	$.extend($.defText.prototype, {
		init: function() {
			var element = this.element[0],
				frm = (typeof element.form !== "undefined") ? $(element.form) : $("body");
			
			if ( typeof element.name === "undefined" ) return;
			if ( typeof element.name === "" && !element.nodeName == "SELECT" ) return;
			
			var defInputName = "_default_" + element.name, defInput, defValue;
				
			
			defInput = $(":input[name='" + defInputName + "']", frm);
			
			
			if ( defInput.length ) {
				defValue = defInput.val();
			} else {
				defValue = element.value;
			}
			
			if ( defValue == "" && !element.nodeName == "SELECT" ) return;
			
			
			$(element).bind("focus", function(){
				if (element.value == defValue) { 
					element.value = ""; 
				}
			});
			$(element).bind("blur", function(){
				
				if (element.value == "") { 
					element.value = defValue; 
					$(element).removeClass("defText_changed");
				}
			});
			$(element).bind("keyup change", function(){
				if (element.value == defValue) { 
					$(element).removeClass("defText_changed");
				} else {
					$(element).addClass("defText_changed");
				}				
			});
			
			$(element).unbind("defTextInputUpdate").bind("defTextInputUpdate", function(){
				if (element.value == defValue) { 
					$(element).removeClass("defText_changed");
				} else {
					$(element).addClass("defText_changed");
				}
			});
			
			$(element).trigger("defTextInputUpdate");
		}
	});
	
	
	$.extend($.defText, {
		defaults: { }
	});
})(jQuery);;

/* placeholder */
(function($){
	$.fn.placeholder = function(options){
		var isMethodCall = (typeof options == "string"),
			args = Array.prototype.slice.call(arguments, 1);
			
		return this.each(function() {
			var instance = $(this).data("placeholder");
			if (isMethodCall && instance && $.isFunction(instance[options])) {
				instance[options].apply(instance, args);
			} else if (!instance) {
				$(this).data("placeholder", new $.placeholder(this, options));
			}
		});
	};
	
	var placeholder = $.placeholder = function(element, options) {
		this.element = $(element);
		this.options = $.extend(true, {},$.placeholder.defaults, options);
		this.init();
	};
	
	$.extend($.placeholder.prototype, {
		init: function() {
			if ( typeof $.support.placeholder === "undefined" ) {
				$.support.placeholder = false;
				test = document.createElement('input');
				if('placeholder' in test) $.support.placeholder = true;
				test = null;
			}
			
			if ( !$.support.placeholder ) {
				
				
				$(':text', this.element)
					.focus(function () {
						if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
							$(this).val('').removeClass('hasPlaceholder');
						}
					})
					.blur(function () {
						if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
							$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
						}
					});
				
				$(':text', this.element).blur();
				
				this.element.submit(function () {
					$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
				});
			}
		}
	});
	$.extend($.placeholder, {
		defaults: {}
	});
})(jQuery);

$(function(){
	$('.scrolled').jScrollPane();
	
	$('.widget-gallery').each(function(){
		var gal = $(this);
		
		$("a.gallery", gal).click(function(e){
			e.preventDefault();
			gal.find('a.gallery').removeClass('active');
			$(this).addClass('active');
			
			var title = $(this).attr('title');
			var text = $(this).find('img').attr('alt');
			var src = $(this).attr('rel');
			var href =  $(this).attr('href');
			
			gal.find('.gallery-large-img img').attr('src',src);
			gal.find('.gallery-large-img .gallery-item-link').attr('href',href);
			gal.find('.gallery-large-img .gallery-item-title').text(title);
			gal.find('.gallery-large-img .gallery-item-text').text(text);
			
			return false;
		});
	});
	
	$('.widget-gallery a.gallery').click(function(e){
		e.preventDefault();
		var gallery = $(this).closest('.widget-gallery');
		gallery.find('a.gallery').removeClass('active');
		$(this).addClass('active');
		var title = $(this).attr('title');
		var text = $(this).find('img').attr('alt');
		var src = $(this).attr('rel');
		var href =  $(this).attr('href');
		
		gallery.find('.gallery-large-img img').attr('src',src);
		gallery.find('.gallery-large-img .gallery-item-link').attr('href',href);
		gallery.find('.gallery-large-img #gallery-item-title').text(title);
		gallery.find('.gallery-large-img #gallery-item-text').text(text);
		return false;
	});
	
	$('#joinmail').click(function(){
		//suki
		/*
		var widget_content = $(this).closest('.widget-content');

		if(widget_content.hasClass('expanded')){
			$('.joinmailform').slideToggle(function(){
				widget_content.removeClass('expanded');
			});
		}else{
			widget_content.addClass('expanded');
			$('.joinmailform').slideToggle();
		}
		*/
		
		//suki
		showPopup('joinmailpopup', {
			opacity:0.8,
			modal:true
		});
		return false;
	})
	
	//suki
	$(":input", "form").filter(".defText").defText();
	
	$("select.checkboxesDropdown").checkboxesDropdown();
	$(".checkboxesDropdown select").checkboxesDropdown();
	$(".lessmore").truncate( 350, {
		chars: /\s/,
		trail: ["<p><a href='#' class='truncate_show'>More</a></p>", "<p><a href='#' class='truncate_hide'>Less</a></p>"]
	});
	
	//zoom button
	$(".zoom-button").popup();
	
	$('.GF_GetStarted #fieldset_2 .gfield_contains_required .ginput_container').append('<span class="mandatory">*</span>');
	$('.GF_Whitepapers .gfield_contains_required .ginput_container').append('<span class="mandatory">*</span>');
	
	/** player **/
	if ( typeof $.fn.SwaggPlayer !== "undefined" && typeof window.testimonial_track_data !== "undefined" ) {
		
		/* genenerate this from php */
		/*
		window.testimonial_track_data = {
			111: {
				"artist": "Dr. John Cutrone, Trueview MRI Centers of Bellflower, CA",
				"url": "http://atlantis.kom/wp-content/uploads/2011/11/Burgess-Testimonial.mp3",
				"title": "Song 1",
				"thumb":"images/median.jpg"
			
			},
			222: {
				"url": "http://atlantis.kom/wp-content/uploads/2011/11/Burgess-Testimonial.mp3",
				"artist": "Atlantis.kom Mandi Kleman, Stamford, CT",
				"title": "Song 1",
				"thumb":"images/median.jpg"
			
			},
			333: {
				"artist": "Kelvin Kulp, Veterinary Diagnostic Imaging and Cytopathology, Clackamas, OR",
				"url": "sound/1.mp3",
				"title": "Song 1",
				"thumb":"images/median.jpg"
			
			},
			444: {
				"url": "sound/2.mp3",
				"artist": "Richard, Birmingham, AL",
				"title": "Song 1",
				"thumb":"images/median.jpg"
			
			},
			555: {
				"artist": "Rebecca Gilbert, Spine & Brain Neurosurgical Center in Lexington, KY",
				"url": "sound/1.mp3",
				"title": "Song 1",
				"thumb":"images/median.jpg"
			
			},
			666: {
				"url": "sound/2.mp3",
				"artist": "Dr. John Cutrone. Trueview MRI Centers of Bellflower, CA",
				"title": "Song 1",
				"thumb":"images/median.jpg"
			
			},
			777: {
				"artist": "Amy Kelly, Englewood, New Jersey",
				"url": "sound/1.mp3",
				"title": "Song 1",
				"thumb":"images/median.jpg"
			
			}
		};
		*/
		//
		window.testimonial_track_current = -1;
		window.testimonial_track_playing = false;
		window.testimonial_track_auto = null;
		
		
		window.testimonial_track_data_map = {};
		window.testimonial_tracks = [];
		
		idx = 1;
		$.each(window.testimonial_track_data, function(i, v) {
			window.testimonial_track_data_map[i] = idx++;
			window.testimonial_tracks.push( $.extend({}, v) );
		});
		
		
		$('#swagg-player').SwaggPlayer({
			data: window.testimonial_tracks,
			buttonsDir:"images/swagg/",
			onPause: function(){
				$('#swagg-player .play-button').removeClass("play-button-paused");
			},
			onPlay: function(){
				$('#swagg-player .play-button').addClass("play-button-paused");
			},
			onResume: function(){
				$('#swagg-player .play-button').addClass("play-button-paused");
				
			},
			onFinish: function() {
				$('#swagg-player .play-button').removeClass("play-button-paused");
				window.testimonial_track_playing = false;
			}
		});
		
		$('#swagg-player .play-button').click(function(){
			if ( window.testimonial_track_auto ) {
				window.clearTimeout(window.testimonial_track_auto);
			}
			
			if ( window.testimonial_track_playing ) {
				window.swaggPlayerApi.controller.play('playlink click', window.testimonial_track_current-1);
			} else {
				window.swaggPlayerApi.playback.playTrack(window.testimonial_track_current);
				window.testimonial_track_playing = true;
			}
			return false;
		});
		
		$(".play").click(function(){
			if ( window.testimonial_track_auto ) {
				window.clearTimeout(window.testimonial_track_auto);
			}
			
			var track = parseInt($(this).attr("data_track"),10) || 0;
			
			track = (typeof window.testimonial_track_data_map[track] !== "undefined") ? window.testimonial_track_data_map[track] : 0;
			
			if ( track > 0 ) { 
				window.testimonial_track_current = track;
				showPopup('playerpopup');
				$("#playerpopup .title").text(window.testimonial_tracks[track-1].artist);
			}
			return false;
		});
		
		$('#playerpopup').bind("popupHide", function(){
			if ( window.testimonial_track_auto ) {
				window.clearTimeout(window.testimonial_track_auto);
			}
			
			window.testimonial_track_current = 0;
			window.testimonial_track_playing = false;
			$('#swagg-player .play-button').removeClass("play-button-paused");
			window.swaggPlayerApi.controller.stopMusic(window.swaggPlayerApi.currSong);
			
		});
		
		$('#playerpopup').bind("popupShow", function(){
			if ( window.testimonial_track_auto ) {
				window.clearTimeout(window.testimonial_track_auto);
			}
			window.testimonial_track_auto = window.setTimeout(function(){
				if ( !window.testimonial_track_playing ) {
					window.swaggPlayerApi.playback.playTrack(window.testimonial_track_current);
					window.testimonial_track_playing = true;
				}
			},1000);
		});
	}
	
	//testimonial listing same height
	$(".testimonials").each(function(){
		/*
		var items = $(".item", this),
			H, h, item;
		
		H = 0;
		for ( var i = 0, n = items.length; i < n; i+=2 ) {
			H = 0;
			for ( var j = i; j < n, j < (i+2); j++ ) {
				h = $("blockquote", $(items[j])).height();
				H = Math.max(H, h);
			}
			for ( var j = i; j < n, j < (i+2); j++ ) {
				$("blockquote", items[j]).height(H);
			}
		}
		*/
	});
	
	
	
	
	$('.testimonials blockquote').equalRowHeight();
	$('.category-blocks .cat-block').equalRowHeight();
	/*
	var currentTallest = 0,
	currentRowStart = 0,
	rowDivs = new Array(),
	$el,
	topPosition = 0;
	
	$('.testimonials blockquote').each(function() {
		$el = $(this);
		topPostion = $el.position().top;

		if (currentRowStart != topPostion) {

		// we just came to a new row.  Set all the heights on the completed row
		for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
			rowDivs[currentDiv].height(currentTallest);
		}

		// set the variables for the new row
		rowDivs.length = 0; // empty the array
		currentRowStart = topPostion;
		currentTallest = $el.height();
		rowDivs.push($el);

		} else {

		// another div on the current row.  Add it to the list and check if it's taller
		rowDivs.push($el);
		currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);

		}

		// do the last row
		for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
		rowDivs[currentDiv].height(currentTallest);
		}

	});
	*/
	//menu
	$("#topnav").each(function(){
		var 
			nav = $(this),
			equipment_parent = $(".topmenu-buyequipment", nav),
			equipment_submenu = $(".buy-equipment-subnav", nav)
			;
			
		$("#menu-main-nav>li>.subnav", this).not(".buy-equipment-subnav").each(function(){
			
			var P = $(this).parent(),
				W = P.outerWidth(),
				p = $(this).outerWidth(true) - $(this).width(),
				w = $(this).outerWidth();
				
			//console.debug(P);
			//console.debug(W, w, p);
			
			if ( w < W ) {
				$(this).width(W - p);
			}
		});
			
		if ( equipment_parent.length && equipment_submenu.length ) {
			equipment_submenu.appendTo(equipment_parent);
		}
	});
	
	//
	//tabs-selector
	if ( $.browser.msie && $.browser.version < 8 ) {
		$(".tabs-selector").each(function(){
			var el = $(this),
				tabs = $(">li", el),
				availW = el.width(),
				usedW = 0,
				widths = [],
				s, d, w, i, n;
				
			tabs.each(function(){
				usedW += $(this).outerWidth(true);
				widths.push($(this).width());
			});
			
			d = s = availW - usedW;
			s = Math.floor(s / tabs.length);
			
			for ( i = 0, n = widths.length; i < n; i++ ) {
				widths[i] += s;
				d -= s;
			}
			
			i = 0;
			while ( d !== 0 ) { 
				if ( d > 0 ) {
					widths[i]++;
					d--;
				} else if ( d < 0 ) {
					widths[i]--;
					d++;
				}
				i++;
			}
			
			i = 0;
			tabs.each(function(){
				$(this).width(widths[i]);
				i++;
			});
		});
	}
	
	/* home page slides */
	$(".slider").each(function(){
		var element = $(this),
			navs = $(".slide-control a", this),
			slides = $(".slide", this),
			slide=0,
			time_delay=5000,
			slide_timeout = null,
			change_slide=true;	//set true to turn on auto slide
		
		function next_slide(){
			slide++;
			
			if ( slide > slides.length-1 ) {
				slide = 0;
			}
			
			$(navs[slide]).click();
			
			if ( change_slide ) {
				set_next_slide_timeout();
			}
		}
		
		function set_next_slide_timeout() {
			clear_next_slide_timeout();
			slide_timeout = window.setTimeout(next_slide,time_delay);
		}
		
		function clear_next_slide_timeout() {
			if ( slide_timeout ) {
				window.clearTimeout(slide_timeout);
			}
			slide_timeout = null;
		}
		
		navs.click(function(){
			var n = parseInt($(this).html(),10) || 0;
			
			if ( n < 1 ) {
				return false;
			}
			
			navs.removeClass('active');
			$(this).addClass('active');
			$('.slide-holder>div.slide', element).hide();
			$('#slide-'+n).fadeIn('slow');
			slide=n-1;
			
			if ( change_slide ) {
				set_next_slide_timeout();
			}
			
			return false;
		});

		if ( change_slide ) {
			set_next_slide_timeout();
		}
	});
});

