document.domain = 'berghs.se';

var Berghs = (function() {
	return {
		/**
		 * Returns a prefixed class name from an element without the prefix
		 * (ie returns "dynamicData" from .value-holder-dynamicData).
		 * Can be used for specifying settings etc in class names.
		 * @param {Object} el
		 * @param {Object} prefix
		 */
		getClassNameValue: function(el, prefix) {
			var ret = new RegExp(".*" + prefix + "(.*?)(?:\\s|$).*").exec(el.className);
			if (ret) {
				return ret[1];
			}
			return null;
		},

		/**
		 *	Initialize
		 */
		init: function() {
			window.isActive = true;
			$(window).live("focus", function() { this.isActive = true; });
			$(window).live("blur", function() { this.isActive = false; });
			
			Berghs.addAnchors.init([
				{ element: ".people-list", include: ["LI"], add: false },
				{ element: ".page-menu .pick-student", include: ["LI"], add: false },
				{ element: ".course-list", include: ["LI"], add: false },
				{ element: ".blog .entry", include: ["IMG"], add: false },
				{ element: ".editorial-teasers .teaser", include: ["IMG"], add: false },
				{ element: ".open-class-teaser .class", include: ["IMG", "SPAN"], add: false },
				{ element: ".messages", include: ["IMG"], add: false },
				{ element: ".vcalendar .vevent", include: [".dtstart"], add: false },
				{ element: ".calendar-list .vevent", include: [".dtstart"], add: false },
				{ element: ".help-information", include: ["H2", "P"], add: false }
			]);
			Berghs.carousel.init([
				{ element: ".blog .vcalendar UL", navigation: true, addMargin: 25 },
				{ element: ".course-article .vcalendar UL", navigation: true, addMargin: 25 },
				{ element: ".messages UL", navigation: true, autoplay: true, easing: "easeInOutSine", delay: 600, autoplayDelay: 7000 }
			]);
			$(".page-menu .pick-student ul").carousel({
				visible: 5,
				scroll: 1,
				speed: 200,
				navigation: true
			});

			Berghs.chapters.init();
			Berghs.disqus.init();
			Berghs.external.init();
			Berghs.formLogin.init();
			Berghs.mediaImage.init();
			Berghs.sitesearch.init([
				{ element: "#header form input" }
			]);
			Berghs.toggler.init([
				{ element: ".page-menu-options .toggle-classes", target: ".page-menu .pick-class" },
				{ element: ".page-menu-options .toggle-students", target: ".page-menu .pick-student" },
				{ element: ".apply .gray-button", target: "#order-info" }
			]);
			Berghs.share.init();
			Berghs.twitterList.init([
				{ element: ".editorial-teasers .twitter-list", amount: 1 },
				{ element: ".student-profile .twitter-list", amount: 3 }
			]);
			Berghs.waiaria.init([
				{ element: ".blog", roles: ["main"] },
				{ element: ".article", roles: ["main"] },
				{ element: ".extra", roles: ["complementary"] },
				{ element: ".menu UL", roles: ["navigation"] },
				{ element: ".service UL", roles: ["navigation"] },
				{ element: ".page-menu", roles: ["navigation"] }
			]);
			Berghs.classList.init();
			Berghs.courses.init();
			Berghs.iframeFix.init();
			Berghs.formHandling.init();
		}
	};
}());


Berghs.formHandling = (function() {
	var DOMReady = function() {
		$("#order-info").validate({
			submitHandler: function(form) {
				$("#order-info input[type=submit]").attr("disabled", "disabled");
				$.post(
					form.action, 
					$(form).serialize(), 
					function(data) {
						// -- REMOVE IF JSON RESPONSE HAVE BEEN FIXED --
						var data = data.substr(1);
						var data = data.substring(0, data.length-1);
						// ---------------------------------------------
						var data = eval("(" + data + ")");
						if (typeof data !== "undefined") {
							if (data.response.status === "ok") {
								$("#order-info input[type=submit]").attr("disabled", "");
								$("#order-info").html("<h2>Tack!</h2><p>" + data.response.message + "</p>");
							}
						}
					}
				);
			}
		});
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}());


Berghs.iframeFix = (function() {
	return {
		init: function() {
			if ($.browser.mozilla) {
				$(document).ready(function() {
					var $iframes = $("iframe");
					if ($iframes.length > 1) {
						$iframes.bind("load.fix", function() {
							$(this).unbind("load.fix");
							this.contentWindow.location.href = this.src;
						});
					}
				});
			}
		}
	};
})();


Berghs.scroller = (function() {
	var timer = null;
	var getScrollX = function() { return (document.all) ? document.body.scrollLeft : window.pageXOffset; };
	var getScrollY = function() { return(document.all) ? document.body.scrollTop : window.pageYOffset; };
	var getObjPos = function(elm, c){
		var x = y = 0;
		while (elm.offsetParent) { x += elm.offsetLeft; y += elm.offsetTop; elm = elm.offsetParent; }
		return ((c == "x") ? x : y);
	};
	var scroll = function(x, y){
		var scrollx = getScrollX(); var scrolly = getScrollY(); 
		if (Math.abs(scrollx-x) <= 1 && Math.abs(scrolly-y) <= 1) {
			window.scrollTo(x,y);
		} else {
			window.scrollTo(parseInt(scrollx + (x - scrollx) / 2),parseInt(scrolly + (y - scrolly) / 2));
			if (scrollx != getScrollX() || scrolly != getScrollY()) {
				timer = setTimeout(function () { scroll(x, y); }, 70);
			} else {
				window.scrollTo(x, y);
			}
		}
	};
	return {
		scrollTo: function(obj, padding){
			if (typeof padding === "undefined") { padding = 0; }
			scroll(0, getObjPos(obj) - padding);
			return false;
		}
	};
}());


Berghs.chapters = (function() {
	var chapters = [];
	
	var dictionary = {
		"letters": "àáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŕ_ /?,.:;",
		"encoded": "aaaaaaaceeeeiiiidnoooooouuuyybyr---_----"
	};
	
	var uriEncode = function(str) {
		var i;
		var tmp = [];
		str = str.toLowerCase();
		str = str.replace("&amp;", "");
		str = str.split("");
		for (i = 0; i < str.length;	i++) {
			var index = dictionary.letters.indexOf(str[i]);
			if (index > 0) {
				var letter = dictionary.encoded[index];
				if (letter !== "_") {
					tmp[i] = letter;				
				}
			} else {
				tmp[i] = str[i];			
			}
		}
		return tmp.join("");
	};
	
	var DOMReady = function() {
		var ids = [];
		var text;
		
		var h2s = $(".course-article .article-body > h2");
		
		if (h2s.length >= 2 ) {
			h2s.each(function(i) {
				var $self = $(this);
				text = $self.html();
				ids[i] = uriEncode(text);
				var wrapper = $("<div class=\"chapter\" id=\"" + ids[i] + "\"></div>");
				wrapper.append($self.nextUntil("h2"));
				wrapper.prepend("<h2>" + text + "</h2>");
				$self.after(wrapper);
				$self.remove();
				chapters.push({ "id": ids[i], "text": text });
			});

			var menu = [];
			menu.push("<div class=\"chapters\">");
			menu.push("<div class=\"content\"><ul>");
			var i;
			for (i = 0, ln = chapters.length; i < ln; i++) {
				menu.push("<li><a href=\"#" + chapters[i].id + "\">" + chapters[i].text + "</a></li>");
			}
			menu.push("</ul></div>");
			menu.push("</div>");
			$(".article-body").prepend(menu.join(""));
			$(".chapters a").live("click", function(e) {
				e.preventDefault();
				var $self = $(this);
				var $parent = $self.parent();
				if(!$parent.hasClass("selected")) {
					$parent.siblings().removeClass("selected");
					$parent.addClass("selected");
					var href = $self.attr("href");
					//var id = href.substring(1, href.length);
					var id = href.replace(/.*#(.+)/gi, "$1");
					var $current = $(".article-body .current").eq(0);
					$current.fadeOut(100, function() {
						$current.removeClass("current");
						$("#" + id).addClass("current").fadeIn(300);
					});	
				}
				$self.blur();
			});
			$(".chapter").eq(0).addClass("current").show();
			$(".chapters li:first-child").addClass("selected");
		}
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}());

Berghs.disqus = (function() {
	var keys = {
		"berghssoc": "SDWnBcGWmW3HW4cJQWpluxa16L6iyvUzIEm0vNH1XPcVnD3vXR8xsEbygr4vAg4k",
		"berghsopenclass": "rgbEoj90Q6HI5YiAKx4dqVbKU6vPZMDkCCUW8HZTJItWJCTvRHmay8QgZn4qWCcd"
	};
	var commentsCountEndPoint = "http://disqus.com/api/3.0/threads/details.jsonp";
	var recentCommentsEndPoint = "http://disqus.com/api/3.0/posts/list.jsonp";
	var defaultForum = "berghssoc";
	var DOMReady = function() {
		$("a.comment-count").each(function() {
			var $self = $(this);
			var forum = Berghs.getClassNameValue(this, "forum-");
			if (forum === null) { forum = defaultForum; }
			var id = $self.attr("data-disqus-identifier");
			if (typeof id !== "undefined") {
				var url = commentsCountEndPoint + "?thread:ident=" + id + "&forum=" + forum + "&api_key=" + keys[forum] + "&callback=?";
				$.getJSON(url, function(data) {
					if (typeof data !== "undefined" && typeof data.response !== "undefined" && typeof data.response.posts !== "undefined") {
						if (data.response.posts > 0) {
							if ($self.closest(".article-info").length > 0) {
								var noOfComments = parseInt(data.response.posts, 10);
								$self.html(noOfComments + " " + (noOfComments == 1 ? "kommentar" : "kommentarer") + ".");								
								$self.css("display", "inline");
							} else {
								$self.html(data.response.posts);
								$self.css("display", ($.browser.msie && $.browser.version <= 7) ? "inline" : "inline-block");
							}
						}
					}
				});
			}
		});
		$("#recent-comments").each(function() {
			var $self = $(this);
			var forum = Berghs.getClassNameValue(this, "forum-");
			if (forum === null) { forum = defaultForum; }
			var limit = 3;
			var url = recentCommentsEndPoint + "?forum=" + forum + "&related=thread&limit=" + limit + "&api_key=" + keys[forum] + "&callback=?";
			$.getJSON(url, function(data) {
				if (typeof data !== "undefined" && typeof data.response !== "undefined") {
					if (data.response.length > 0) {
						var html = "<ul>";
						for (i = 0, l = data.response.length; i < l; i++) {
							html += "<li><a href=\"" + data.response[i].url + "\">" + "<span>" + data.response[i].author.name + ":</span> " + data.response[i].message + "</a></li>";
						}
						html += "</ul>";
						$self.html(html);
					}
				}
			});
		});
		
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}());

Berghs.external = (function() {
	var DOMReady = function() {
		$("a[rel=external]").live("click", function(e) {
			e.preventDefault();
			window.open(this);
			}).attr("title", function() {
			var title = $(this).attr("title");
			if(title === "") {
				$(this).attr("title", "Öppnas i ett nytt fönster");
			} else {
				$(this).attr("title", "Öppnas i ett nytt fönster – " + title);
			}
		}); 
	};

	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}());

Berghs.formLogin = (function() {
	var DOMReady = function() {
		$(".form-login label").each(function() {
			var $self = $(this);
			$self.next("input").focus(function() {
				$self.hide();
			});
			$self.next("input").blur(function() {
				if($(this).attr("value") === "") {
					$self.show();
				}
			});
		});
	};
	
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}());

Berghs.mediaImage = (function() {
	var mediaImages = 0;
	var addPlayButton = function(container, img) {
		var css = {
			"position": "absolute",
			"top": "0px",
			"left": "0px",
			"height": img.height + "px",
			"width": img.width + "px"
		};
		var imgSpan = $("<span></span>").css(css).attr("id", "media-image-" + mediaImages).addClass("media-image-cover");
		container.append(imgSpan);
		mediaImages++;
	};
	
	var DOMReady = function() {
		$(".has-video").each(function() {
			var $self = $(this);
			var img = $self.find("img").get(0);
			if(img.complete) {
				addPlayButton($self, img);
			} else {
				$(img).bind("load", function() {
					addPlayButton($self, img);
				});
			}
		});
	};
	
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}());

Berghs.sitesearch = function() {
	var options;
	var defaultText = [];
	var tmpText = [];
	var DOMReady = function() {
		$(options).each(function(i) {
			var $s = $(this.element);
			defaultText[i] = $s.attr("value");
			$s.live("focus", function() {
				tmpText[i] = $(this).attr("value");
				if(tmpText[i] === defaultText[i]) {
					$s.attr("value", "");
				}
			});
			$s.live("blur", function() {
				if($(this).attr("value") === ""){
					$s.attr("value", defaultText[i]);
				}
			});
		}); 
	};

	return {
		init: function(initOptions) {
			options = initOptions;
			$(document).ready(DOMReady);
		}
	};
}();


Berghs.toggler = (function() {
	var options;
	var show = function($el) {
		$el.slideDown(150, function() {
			var elmPos = $el.offset();
			var elmHeight = $el.outerHeight();
			var viewPortHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight;
			var scrollTop = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
			if ((viewPortHeight + scrollTop) < elmPos.top + elmHeight/2) {
				Berghs.scroller.scrollTo($el.get(0), 40);
			}
		});
	};
	var hide = function($el, $trigger) {
		$el.slideUp(150);
		if ($trigger) {
			$trigger.removeClass("toggle-open").addClass("toggle-closed");
		}
	};
	var DOMReady = function() {
		for (i = 0, ln = options.length; i < ln; i++) {
			$(options[i].element).each(function() {
				$(options[i].target).hide();				
				$(this).bind("click", {options: options[i]}, function(e) {
					var $self = $(this);
					e.preventDefault();
					var target = e.data.options.target;
					var $target = $(target);
					if ($self.hasClass("toggle-open")) {
						hide($target, $self);
					} else {
						$self.removeClass("toggle-closed").addClass("toggle-open");
						$self.siblings(".toggle-open").each(function() {
							$(this).removeClass("toggle-open");
							hide($(this.hash));
						});
						show($target);
					}
					$self.blur();
					return false;
				});
			});
		}
	};
	return {
		init: function(initOptions) {
			options = initOptions;
			$(document).ready(DOMReady);
		}
	};
}());


Berghs.share = (function() {
	var show = function($el) {
		$el.fadeIn(150, function() {
			$el.find("input[type=text]").get(0).focus();
		});
		$el.data("isVisible", true);
	};
	var hide = function($el) {
		$el.data("isVisible", false);
		$el.fadeOut(150, function() {
			$el.find(".content").show();
			$el.find(".message").remove();
		});
		var $document = $(document);
		$document.unbind("click.share");
		$document.unbind("keydown.share");
	};
	return {
		init: function() {
			$(".form-article-share .button").live("click", function(e) {
				e.preventDefault();
				var $self = $(this);
				var $form = $("#skicka-artikeln");
				if ($form.data("isVisible")) {
					hide($form);
					return;
				}
				if (!$form.data("initialized")) {
					$form.data("initialized", true);
					$form.submit(function() {
						$.post(this.action, $form.serialize(), function(data) {
							var data = eval("(" + data + ")");
							$form.find("fieldset").append("<div class=\"message\"><p>" + data.response.message + "</p><a href=\"\" class=\"button target-close\">Stäng</a></div>");
							$form.find(".content").hide();
						});
						return false;
					});
				}
				var position = $self.position();
				$form.css({
					"position": "absolute",
					"left": position.left + $self.width() + 17 + "px",
					"top": position.top + $self.height() - 34 + "px"
				});
				var $document = $(document);
				$document.bind("click.share", function(e) {
					if ($(e.target).closest("#skicka-artikeln").length == 0) {
						hide($form);
						return false;
					}
				});
				$document.bind("keydown.share", function(e) {
					if (e.keyCode == 27) {
						hide($form);
						return false;
					}
				});
				show($form);
				$self.blur();
				return false;
			});
		}
	};
}());


Berghs.iframes = (function() {
	return {
		onLoad: function(iframe) {
			var $self = $(iframe);
			$self.height($self.contents().find("body").outerHeight());
		}
	};
}());


Berghs.twitterList = (function() {
	var options;
	var tweets;
	
	//Parse Twitter created_at value into friendly time format; relative time; time ago
	var K = function () {
	    var a = navigator.userAgent;
	    return {
	        ie: a.match(/MSIE\s([^;]*)/)
	    };
	};
	var H = function (a) {
	    var b = new Date();
	    var c = new Date(a);
	    if (K.ie) {
			c = Date.parse(a.replace(/( \+)/, ' UTC$1'));
	    }
	    var d = b - c;
	    var e = 1000,
	        minute = e * 60,
	        hour = minute * 60,
	        day = hour * 24,
	        week = day * 7;
	    if (isNaN(d) || d < 0) {
	        return "";
	    }
	    if (d < e * 7) {
	        return "right now";
	    }
	    if (d < minute) {
	        return Math.floor(d / e) + " seconds ago";
	    }
	    if (d < minute * 2) {
	        return "about 1 minute ago";
	    }
	    if (d < hour) {
	        return Math.floor(d / minute) + " minutes ago";
	    }
	    if (d < hour * 2) {
	        return "about 1 hour ago";
	    }
	    if (d < day) {
	        return Math.floor(d / hour) + " hours ago";
	    }
	    if (d > day && d < day * 2) {
	        return "yesterday";
	    }
	    if (d < day * 365) {
	        return Math.floor(d / day) + " days ago";
	    } else {
	        return "over a year ago";
	    }
	};
	
	var DOMReady = function() {
		for (i = 0, ln = options.length; i < ln; i++) {
			var amount;
			$(options[i].element).each(function() {
				var $self = $(this);
				amount = options[i].amount;
				var url = $self.find("a")[0].href;
				var userName = url.substr(url.lastIndexOf(".com/") + ".com/".length);
				var q = "http://twitter.com/status/user_timeline/" + userName + ".json?trim_user=true&include_rts=true&callback=?";
				$.getJSON(q, function(data) {
					var html = "";
					var j = 0;
					if (data.length > 0) {
						html += "<ul>";
						for (j = 0, l = amount; j < l; j++) {
							if (data[j].in_reply_to_user_id === null) {
								data[j].text = data[j].text.replace(/(^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))/i, function(url) {
									return " <a href=\"" + url + "\">" + (url.length > 30 ? url.substr(0, 30) + "..." : url) + "</a>";
								});
								html += "<li>" + data[j].text + "<span class=\"source\">" + H(data[j].created_at) + " via " + $("<div/>").html(data[j].source).text() + "</span></li>";
							}
						}
					}
					
					// Extra for basic empty protection
					if(html == '<ul>') {
						if (data.length > 0) {
							for (j = 0, l = 2; j < l; j++) {
								if (data[j].in_reply_to_user_id === null) {
									data[j].text = data[j].text.replace(/(^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))/i, function(url) {
										return " <a href=\"" + url + "\">" + (url.length > 30 ? url.substr(0, 30) + "..." : url) + "</a>";
									});
									html += "<li>" + data[j].text + "<span class=\"source\">" + H(data[j].created_at) + " via " + $("<div/>").html(data[j].source).text() + "</span></li>";
								}
							}
						}
					}
					
					html += "</ul>";
					var loc = document.location.href;
					if(loc.search('/en/') > 0) {
						html += "<a href=\"" + url + "\" class=\"more\" rel=\"external\">More tweets</a>";
					} else {
						html += "<a href=\"" + url + "\" class=\"more\" rel=\"external\">Fler tweets</a>";
					}
					if(j > 0) {
						$self.append(html);
					}					
				});
			});
		}
	};
	return {
		init: function(initOptions) {
			options = initOptions;
			$(document).ready(DOMReady);
		}	
	};
}());


/**
 * Adds anchors (using the first found anchor in the element as a source) around an
 * element's inner elements when hovered. Also Sets a class of "hover" on the 
 * parent element when its children are being hovered.
 * @param {object} An associative array of elements and their inner items to anchor
 *	element (mandatory) The parent element. 
 *	include (mandatory) The inner element to be anchored. 
 *	add (optional, default is true) Makes the included elements clickable instead of added anchors.
 */
Berghs.addAnchors = (function() {	
	var selectors = "";
	return {
		init: function(settings) {
			if (settings) {
				var i;
				for (i = 0, ln = settings.length; i < ln; i++) {
					if (settings[i].element) {
						if (settings[i].include) {
							var selector = settings[i].element;
							selectors += (selectors.length > 0 ? "," : "") + selector;
							var j;
							for (j = 0, ln2 = settings[i].include.length; j < ln2; j++) {
								if (settings[i].add === false) {
									$(selector + " " + settings[i].include[j]).live("click", function() {
										var $self = $(this);
										if($(settings[2].element).attr("class") == 'course-list' || $(settings[0].element).attr("class") == 'people-list'  || $(settings[1].element).attr("class") == 'pick-student') {
											//alert($self.find("a").attr("href"));
											if( ($('.people-list').attr('class') != "undefined" && $('.people-list').attr('class') != undefined ) || ( $('#content > .course-list').attr('class') != "undefined" && $('#content > .course-list').attr('class') != undefined) || ($('.pick-student').attr('class') != "undefined" && $('.pick-student').attr('class') != undefined ) ) {
												window.location = $self.find("a").attr("href");
											} else {
												window.location = $self.closest(selectors).find("a").attr("href");
											}
										} else {
											window.location = $self.closest(selectors).find("a").attr("href");
										}
										return false;
									});
								} else {
									$(selector + " " + settings[i].include[j]).live("mouseover", function() {
										var $self = $(this);
										var $linkParent = $self.data("linkParent");
										if (!$linkParent || typeof($linkParent) === "undefined") {
											$linkParent = $self.closest(selectors);
											if ($linkParent.length > 0) {
												$self.data("linkParent", $linkParent);
												var href = $linkParent.find("a").attr("href");
												if (href !== null && typeof href !== "undefined") {
													$a = $("<a href=\"" + href + "\" class=\"added-anchor\"></a>");
													if (!this.innerHTML) {
														if (this.parentNode.tagName !== "A") {
															$self.before($a);
															$a.wrapInner($self);
														}
													} else {
														$self.contents().each(function() {
															if (this.tagName !== "A") {
																$self = $(this);
																if (jQuery.trim($self.text()).length > 0) {
																	$self.wrap($a);
																}
															}
														});
													}
												}										
											}
										}
										if ($linkParent) {
											$linkParent.addClass("hover");
										}
									});
									$(selector + " " + settings[i].include[j]).live("mouseout", function() {
										var $linkParent = $(this).data("linkParent");
										if ($linkParent !== null) {
											$linkParent.removeClass("hover");
										}
									});
								}
							}
						}
					}
				}
			}
		}
	};
}());


/**
 * Generic carousel function
 * @param {object} An associative array of elements and options
 *	element (mandatory) The ul to make a carousel of
 *  easing (optional, default swing) The easing that's used for each change 
 *  delay (optional, default 200ms) The time each change takes
 *  navigation (optional) Adds backward and forward navigation elements
 *  numericalNavigation (optional) Add numerical navigation elements
 *  clickToChange (optional) Moves the carousel forward when it is clicked
 *  autoplay (optional) Moves the carousel forward continuously
 *  autoplayDelay (optional, default 2500ms) The delay between each automatical move
 *  load (optional) A function that get called when the carousel is generated
 *  beforeChange (optional) A function that get called before each change is performed
 *  afterChange (optional) A function that get called before each change is performed
 */
Berghs.carousel = function() {
	var options;
	var defaults = {
		easing: "swing",
		delay: 200,
		autoplayDelay: 2500
	};
	var navigationInitialized = false;
	var change = function($carousel, delta) {
		if (delta == 0) {
			return;
		}
		if (!$carousel.data("working")) {
			var options = $carousel.data("options");
			$carousel.data("working", true);
			if (options.beforeChange) {
				options.beforeChange.call($carousel, delta);
			}
			var $children = $carousel.children();
			if (delta > 0) {
				$carousel.animate({ "marginLeft": -delta * $carousel.data("width") }, {
					easing: options.easing,
					duration: options.delay,
					complete: function() {
						for (var i = 0; i < delta; i++) {
							$li = $children.eq(0);
							$carousel.append($li);						
						}
						$carousel.css("marginLeft", 0);
						if (options.afterChange) {
							options.afterChange.call($carousel, delta);
						}
						$carousel.data("working", false);
					}
				});
			} else {
				for (var i = 0; i < Math.abs(delta); i++) {
					$li = $children.eq($children.length-1);
					$carousel.prepend($li);
				}
				$carousel.css("marginLeft", delta * $carousel.data("width"));
				$carousel.animate({ "marginLeft": 0 }, {
					easing: options.easing,
					duration: options.delay,
					complete: function() {
						if (options.afterChange) {
							options.afterChange.call($carousel, delta);
						}
						$carousel.data("working", false);
					}
				});
			}

			var no = $carousel.data("no") + delta;
			var noOfChildren = $carousel.data("noOfChildren");
			if (no >= noOfChildren) {
				no = 0;
			} else if (no < 0) {
				no = noOfChildren - 1;
			}
			$carousel.data("no", no);
			
			if (options.numericalNavigation) {
				var $navigation = $carousel.parent().siblings(".carousel-navigation").children();
				$navigation.removeClass("selected");
				$($navigation[no + (options.navigation ? 1 : 0)]).addClass("selected");			
			}
		}
	};

	var updateHeight = function($carousel, height) {
		$carousel.children().each(function() {
			var $self = $(this);
			if (height > $self.height()) {
				$self.height(height);
			}
		});
	};
	
	var updateWidth = function($carousel, width) {
		$carousel.width(width * $carousel.data("noOfChildren"));
		$carousel.children().width(width);
		$carousel.parent().width(width);
		$carousel.data("width", width);
	};
	
	var startAutoplay = function($carousel) {
		var id = setInterval(function() {
			change($carousel, 1);
		}, $carousel.data("options").autoplayDelay);
		$carousel.data("autoplay", id);
	};
	
	var stopAutoplay = function($carousel) {
		clearInterval($carousel.data("autoplay"));
	};

	var removeAutoplay = function($carousel) {
		stopAutoplay($carousel);
		$carousel.unbind("mouseover").unbind("mouseout");
	};

	var DOMReady = function() {
		var noOfCarousels = 0;
		for (var i = 0, ln = options.length; i < ln; i++) {
			$(options[i].element).each(function() {
				var $carousel = $(this);
				$li = $carousel.children();
				var noOfChildren = $li.length;
				if ($carousel.closest(".carousel").length > 0 || noOfChildren < 2) {
					return;
				}
				$carousel.data("no", 0);
				var cOptions = jQuery.extend({}, defaults, options[i]);
				$carousel.data("options", cOptions);

				var carouselId = "carousel-" + noOfCarousels;
				$carousel.attr("id", carouselId);
				$carousel.css("overflow", "hidden");
				$carousel.data("noOfChildren", noOfChildren);
				
				$parent = $("<div class=\"carousel\"></div>");
				$parent.css({
					"overflow": "hidden",
					"position": "relative"
				});
				$carousel.wrap($parent);
				$parent = $carousel.parent();
				updateWidth($carousel, $carousel.width());
				$li.css({
					"float": "left",
					"display": "block",
					"visibility": "visible"
				});
				updateHeight($carousel, $carousel.height());
				
				var widthSet = false;
				$carousel.find("img").load(function() {
					var $self = $(this);
					var $carousel = $self.closest(".carousel").children("ul");
					var $li = $carousel.children();
					if (!widthSet) {
						if (this.width > $li.width()) {
							$li.width("auto");
							if($li.width() != 0) {
								updateWidth($carousel, $li.width());
							}							
						}
						widthSet = true;			
					}
					$li.height("auto");
					updateHeight($carousel, $li.height());
				});
				
				/* TOUCH */
				if ($.fn.swipe) {
					$carousel.swipe({
						swipeLeft: function() { 
							change($carousel, 1);
						},
	 					swipeRight: function() {
	 						change($carousel, -1);
	 					},
	 					triggerOnce: true
		 			});
		 		}

				if (cOptions.clickToChange) {
					$carousel.css("cursor", "pointer");
					$carousel.click(function(e) {
						change($(this), 1);
						e.preventDefault();
						this.blur();
					});
				}
				if (cOptions.navigation || cOptions.numericalNavigation) {
					$navigation = $("<ul class=\"carousel-navigation\"></ul>");
					if (cOptions.navigation) {
						$navigation.append("<li><a href=\"\" class=\"previous\">Föregående</a></li>");
					}
					if (cOptions.numericalNavigation) {
						for (var j = 0; j < noOfChildren; j++) {
							var $a = $("<li><a href=\"\">" + (j + 1) + "</a></li>");
							if (j == 0) {
								$a.addClass("selected");
							}
							$navigation.append($a);
						}
					}
					if (cOptions.navigation) {
						$navigation.append("<li><a href=\"\" class=\"next\">Nästa</a></li>");
					}
					$carousel.parent().after($navigation);
					if (!navigationInitialized) {
						$(".carousel-navigation A").live("click", function() {
							var $self = $(this);
							this.blur();
							var $carousel = $self.closest(".carousel-navigation").siblings(".carousel").children();
							if ($carousel.data("options").autoplay) {
								removeAutoplay($carousel);
							}
							if ($self.hasClass("next")) {
								change($carousel, 1);
							} else if ($self.hasClass("previous")) {
								change($carousel, -1);
							} else {
								change($carousel, parseInt($.trim($self.html()), 10) - $carousel.data("no") - 1);
							}
							return false;
						});
						navigationInitialized = true;				
					}
				}
				if (cOptions.autoplay) {
					$carousel.bind("mouseover", function() {
						stopAutoplay($(this));
					});
					$carousel.bind("mouseout", function() {
						startAutoplay($(this));
					});
					startAutoplay($carousel);
				}
				if (cOptions.load) {
					cOptions.load.call($carousel);
				}
				
				noOfCarousels++;
			});
		}
	};
	return {
		init: function(initOptions) {
			options = initOptions;
			$(document).ready(DOMReady);
		}
	};
}();


Berghs.courses = (function() {
	var getHash = function(filters) {
		var hash = [];
		for (var key in filters) {
			if (jQuery.isArray(filters[key]) && filters[key].length > 0) {
				hash = hash.concat(filters[key]);
			}
		}
		return hash.join(",");
	}
	var filter = function($list) {
		var $items = $list.find("li");
		var noOfVisibleItems = $items.length;
		$("#note").remove();
		var filters = $list.data("filters");
		if ($list.data("noOfFilters") > 0) {
			$items.each(function() {
				var $self = $(this);
				var isVisible = true;
				for (var key in filters) {
					if (jQuery.isArray(filters[key]) && filters[key].length > 0) {
						var hasClass = false;
						for (var i = 0, ln = filters[key].length; i < ln; i++) {
							if ($self.hasClass(filters[key][i])) {
								hasClass = true;
								break;
							}
						}
						isVisible = hasClass && isVisible;
						if (!isVisible) {
							break;
						}
					}
				}
				if (isVisible) {
					$self.fadeIn(400);
				} else {
					$self.hide();
					noOfVisibleItems--;
				}
			});
		} else {
			$items.fadeIn(400);
		}
		if (noOfVisibleItems === 0) {
			var loc = document.location.href;
			if(loc.search("/en/") > 0) {
				$list.append("<p id=\"note\">Unfortunately, we have no courses or educations that suit your selection. But if there is an education we lack, we would really like to know! <a href=\"\">Tell us!</a></p>");
			} else {
				$list.append("<p id=\"note\">Tyvärr har vi inga kurser eller utbildningar som passar ditt urval. Men om det är en utbildning vi saknar vill vi jättegärna veta! <a href=\"\">Tipsa om dina önskemål!</a></p>");
			}
		}
	};
	var DOMReady = function() {
		var $list = $(".course-list");
		if ($list.length > 0) {
			$(".filter a").live("click", function() {
				var $self = $(this);
				var filters = $list.data("filters");
				var noOfFilters = $list.data("noOfFilters");
				if (!noOfFilters) {
					noOfFilters = 0;
				}
				if (!filters) {
					filters = [];
				}
				var filterId = $self.closest(".filter").attr("id");
				if (!filters[filterId]) {
					filters[filterId] = [];
				}
				var $parent = $self.closest("li");
				if ($parent.hasClass("selected")) {
					$parent.removeClass("selected");
					filters[filterId].splice(jQuery.inArray($self.attr("className"), filters[filterId]), 1);
					$self.blur();
					noOfFilters--;
				} else {
					$parent.addClass("selected");
					filters[filterId].push($self.attr("class"));
					noOfFilters++;
				}
				$list.data("filters", filters);
				$list.data("noOfFilters", noOfFilters);
				filter($list);
				window.location.hash = noOfFilters > 0 ? getHash(filters) : " ";
				return false;
			});
			
			if (window.location.hash) {
				var filters = [];
				var $filters = $(".filter");
				var noOfFilters = 0;
				var hashFilters = window.location.hash.substring(1).split(",");
				for (var i = 0, ln = hashFilters.length; i < ln; i++) {
					if (jQuery.trim(hashFilters[i]).length > 0) {
						var $filter = $filters.find("." + hashFilters[i]);
						if ($filter.length > 0) {
							var filterId = $filter.closest(".filter").attr("id");
							if (!filters[filterId]) {
								filters[filterId] = [];
							}
							$filter.parent().addClass("selected");
							filters[filterId].push(hashFilters[i]);
							noOfFilters++;
						}					
					}
				}
				$list.data("noOfFilters", noOfFilters);
				$list.data("filters", filters);
				window.location.hash = noOfFilters > 0 ? getHash(filters) : " ";
				filter($list);
			}
		}
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}());


Berghs.waiaria = (function() {
	var options;
	var DOMReady = function() {
		var i;
		for (i = 0, ln = options.length; i < ln; i++) {
			$(options[i].element).each(function() {
				$self = $(this);
				$self.attr("role", options[i].roles.join(" "));
			});
		}
	};

	return {
		init: function(initOptions) {
			options = initOptions;
			$(document).ready(DOMReady);
		}
	};
}());


Berghs.classList = (function() {
	return {
		init: function() {
			$(".open-class-list ul li").mouseenter(function() {
				var $topic = $(this).find(".topic");
				if (!$topic.data("height")) {
					$topic.css({
						visibility: "hidden",
						display: "block",
						position: "absolute"
					});
					var height = $topic.outerHeight();
					$topic.data("height", height).height(0);
					$topic.css({
						visibility: "visible",
						position: "relative",
						overflow: "hidden"
					});
				}
				var options = {height: $topic.data("height")};
				if ($.browser.msie && $.browser.version <= 7) {
					options["marginBottom"] = 0;
				}
				$topic.animate(options, {
					duration: 100
				});
			}).mouseleave(function() {
				var $topic = $(this).find(".topic");
				var options = {height: 0};
				if ($.browser.msie && $.browser.version <= 7) {
					options["marginBottom"] = -$topic.data("height");
				}
				$topic.animate(options, {
					duration: 100
				});
			});
		}
	};
}());


Array.prototype.remove = function(s) {
	for(i = 0, l = this.length; i < l; i++) {
		if (s === this[i]) {
			this.splice(i, 1);
			break;
		}
	}
};



/**
 * Swipe
 * 
 * Swipe functionality for touch devices
 * @param {object} An associative array of options
 *	swipeLeft (optional) Function to be called when the user swipes left 
 *	swipeRight (optional) Function to be called when the user swipes right 
 *	treshold (optional, default x: 20, y: 20) x, y swipe treshold
 *  triggerOnce (optional, default false) cancels the event directly after it has been triggered once
 *
 */
if (typeof window.ontouchstart !== "undefined") {
	(function($){
		$.fn.swipe = function(options) {
			if (!this) {
				return false;				
			}
			
			var defaults = {
				threshold: {
					x: 20,
					y: 20
				},
				swipeLeft: function() {},
				swipeRight: function() {},
				triggerOnce: false
			};
			
			var options = $.extend(defaults, options);
			
			return this.each(function() {
				var $self = $(this);
				
				var start = {
					x: 0,
					y: 0
				};
				
				var isMoving = false;
				
				function touchStart(e){
					if (e.targetTouches.length === 1) {
						start.x = e.targetTouches[0].pageX;
						start.y = e.targetTouches[0].pageY;
						this.addEventListener("touchmove", touchMove, false);
						isMoving = true;
					}
				}
				
				function touchEnd(){
					this.removeEventListener("touchmove", touchMove);
					isMoving = false;
				}
				
				function touchMove(e){
					if (isMoving) {
						var dx = start.x - e.touches[0].pageX;
						var dy = start.y - e.touches[0].pageY;
						if (Math.abs(dx) >= options.threshold.x && Math.abs(dy) < options.threshold.y) {
							e.preventDefault();
							if (dx > 0) {
								options.swipeLeft.call(this);
							} else {
								options.swipeRight.call(this);
							}
							if (options.triggerOnce) {
								isMoving = false;
							}
						}
					}
				}
				
				this.addEventListener("touchstart", touchStart, false);
			});
		};
	})(jQuery);
}


/**
 * Carousel
 * 
 * Generic carousel function that wraps around jCarouselLite (required)
 * Removes the need for wrapping html structures and also constructs navigation links if necessary.
 * Options are the same as for jCarouselLite
 * Extra options:
 * navigation (boolean, optional) Create backward and forward navigation elements
 */
(function($) {
	var noOfCarousels = 0;
	var carouselClassName = "__carousel";
	$.fn.carousel = function(options) {
		return this.each(function() {
			var $self = $(this);
			var $children = $self.children();
			var noOfChildren = $children.length;
			var minimumNoOfChildren = options.scroll || 1;
			if (noOfChildren > minimumNoOfChildren) {
				var id = "carousel-" + noOfCarousels;
				$self.wrap("<div id=\"" + id + "\" class=\"" + carouselClassName + "\"></div>");
				if (options.navigation) {
					var $navigation = $("<ul id=\"" + id + "-navigation\" class=\"carousel-navigation\"></ul>");
					if (options.navigation) {
						$navigation.append("<li><a href=\"#\" class=\"previous\">&larr;</a></li>");
						options.btnPrev = "#" + id + "-navigation .previous";
						$navigation.append("<li><a href=\"#\" class=\"next\">&rarr;</a></li>");
						options.btnNext = "#" + id + "-navigation .next";
					}
					$self.parent().after($navigation);
					if ($.fn.swipe) {
						$self.swipe({
							swipeLeft: function() {
								$navigation.find(".next").click();										
							},
							swipeRight: function() {
								$navigation.find(".previous").click();										
							},
							triggerOnce: true
						});
					}
				}
				$("#" + id).jCarouselLite(options);
				noOfCarousels++;
			}
		});
	};
}(jQuery));

/**
 * jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget.
 * @requires jQuery v1.2 or above
 *
 * http://gmarwaha.com/jquery/jcarousellite/
 *
 * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 1.0.1
 * Note: Requires jquery 1.2 or above from version 1.0.1
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(6($){$.1g.1w=6(o){o=$.1f({r:n,x:n,N:n,17:q,J:n,L:1a,16:n,y:q,u:12,H:3,B:0,k:1,K:n,I:n},o||{});8 G.R(6(){p b=q,A=o.y?"15":"w",P=o.y?"t":"s";p c=$(G),9=$("9",c),E=$("10",9),W=E.Y(),v=o.H;7(o.u){9.1h(E.D(W-v-1+1).V()).1d(E.D(0,v).V());o.B+=v}p f=$("10",9),l=f.Y(),4=o.B;c.5("1c","H");f.5({U:"T",1b:o.y?"S":"w"});9.5({19:"0",18:"0",Q:"13","1v-1s-1r":"S","z-14":"1"});c.5({U:"T",Q:"13","z-14":"2",w:"1q"});p g=o.y?t(f):s(f);p h=g*l;p j=g*v;f.5({s:f.s(),t:f.t()});9.5(P,h+"C").5(A,-(4*g));c.5(P,j+"C");7(o.r)$(o.r).O(6(){8 m(4-o.k)});7(o.x)$(o.x).O(6(){8 m(4+o.k)});7(o.N)$.R(o.N,6(i,a){$(a).O(6(){8 m(o.u?o.H+i:i)})});7(o.17&&c.11)c.11(6(e,d){8 d>0?m(4-o.k):m(4+o.k)});7(o.J)1p(6(){m(4+o.k)},o.J+o.L);6 M(){8 f.D(4).D(0,v)};6 m(a){7(!b){7(o.K)o.K.Z(G,M());7(o.u){7(a<=o.B-v-1){9.5(A,-((l-(v*2))*g)+"C");4=a==o.B-v-1?l-(v*2)-1:l-(v*2)-o.k}F 7(a>=l-v+1){9.5(A,-((v)*g)+"C");4=a==l-v+1?v+1:v+o.k}F 4=a}F{7(a<0||a>l-v)8;F 4=a}b=12;9.1o(A=="w"?{w:-(4*g)}:{15:-(4*g)},o.L,o.16,6(){7(o.I)o.I.Z(G,M());b=q});7(!o.u){$(o.r+","+o.x).1n("X");$((4-o.k<0&&o.r)||(4+o.k>l-v&&o.x)||[]).1m("X")}}8 q}})};6 5(a,b){8 1l($.5(a[0],b))||0};6 s(a){8 a[0].1k+5(a,\'1j\')+5(a,\'1i\')};6 t(a){8 a[0].1t+5(a,\'1u\')+5(a,\'1e\')}})(1x);',62,96,'||||curr|css|function|if|return|ul|||||||||||scroll|itemLength|go|null||var|false|btnPrev|width|height|circular||left|btnNext|vertical||animCss|start|px|slice|tLi|else|this|visible|afterEnd|auto|beforeStart|speed|vis|btnGo|click|sizeCss|position|each|none|hidden|overflow|clone|tl|disabled|size|call|li|mousewheel|true|relative|index|top|easing|mouseWheel|padding|margin|200|float|visibility|append|marginBottom|extend|fn|prepend|marginRight|marginLeft|offsetWidth|parseInt|addClass|removeClass|animate|setInterval|0px|type|style|offsetHeight|marginTop|list|jCarouselLite|jQuery'.split('|'),0,{}));



/**
 * jQuery Validation Plugin 1.8.0
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2011 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function(c){c.extend(c.fn,{validate:function(a){if(this.length){var b=c.data(this[0],"validator");if(b)return b;b=new c.validator(a,this[0]);c.data(this[0],"validator",b);if(b.settings.onsubmit){this.find("input, button").filter(".cancel").click(function(){b.cancelSubmit=true});b.settings.submitHandler&&this.find("input, button").filter(":submit").click(function(){b.submitButton=this});this.submit(function(d){function e(){if(b.settings.submitHandler){if(b.submitButton)var f=c("<input type='hidden'/>").attr("name",
b.submitButton.name).val(b.submitButton.value).appendTo(b.currentForm);b.settings.submitHandler.call(b,b.currentForm);b.submitButton&&f.remove();return false}return true}b.settings.debug&&d.preventDefault();if(b.cancelSubmit){b.cancelSubmit=false;return e()}if(b.form()){if(b.pendingRequest){b.formSubmitted=true;return false}return e()}else{b.focusInvalid();return false}})}return b}else a&&a.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing")},valid:function(){if(c(this[0]).is("form"))return this.validate().form();
else{var a=true,b=c(this[0].form).validate();this.each(function(){a&=b.element(this)});return a}},removeAttrs:function(a){var b={},d=this;c.each(a.split(/\s/),function(e,f){b[f]=d.attr(f);d.removeAttr(f)});return b},rules:function(a,b){var d=this[0];if(a){var e=c.data(d.form,"validator").settings,f=e.rules,g=c.validator.staticRules(d);switch(a){case "add":c.extend(g,c.validator.normalizeRule(b));f[d.name]=g;if(b.messages)e.messages[d.name]=c.extend(e.messages[d.name],b.messages);break;case "remove":if(!b){delete f[d.name];
return g}var h={};c.each(b.split(/\s/),function(j,i){h[i]=g[i];delete g[i]});return h}}d=c.validator.normalizeRules(c.extend({},c.validator.metadataRules(d),c.validator.classRules(d),c.validator.attributeRules(d),c.validator.staticRules(d)),d);if(d.required){e=d.required;delete d.required;d=c.extend({required:e},d)}return d}});c.extend(c.expr[":"],{blank:function(a){return!c.trim(""+a.value)},filled:function(a){return!!c.trim(""+a.value)},unchecked:function(a){return!a.checked}});c.validator=function(a,
b){this.settings=c.extend(true,{},c.validator.defaults,a);this.currentForm=b;this.init()};c.validator.format=function(a,b){if(arguments.length==1)return function(){var d=c.makeArray(arguments);d.unshift(a);return c.validator.format.apply(this,d)};if(arguments.length>2&&b.constructor!=Array)b=c.makeArray(arguments).slice(1);if(b.constructor!=Array)b=[b];c.each(b,function(d,e){a=a.replace(RegExp("\\{"+d+"\\}","g"),e)});return a};c.extend(c.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",
validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:c([]),errorLabelContainer:c([]),onsubmit:true,ignore:[],ignoreTitle:false,onfocusin:function(a){this.lastActive=a;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass);this.addWrapper(this.errorsFor(a)).hide()}},onfocusout:function(a){if(!this.checkable(a)&&(a.name in this.submitted||!this.optional(a)))this.element(a)},
onkeyup:function(a){if(a.name in this.submitted||a==this.lastElement)this.element(a)},onclick:function(a){if(a.name in this.submitted)this.element(a);else a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(a,b,d){c(a).addClass(b).removeClass(d)},unhighlight:function(a,b,d){c(a).removeClass(b).addClass(d)}},setDefaults:function(a){c.extend(c.validator.defaults,a)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",
url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:c.validator.format("Please enter no more than {0} characters."),minlength:c.validator.format("Please enter at least {0} characters."),rangelength:c.validator.format("Please enter a value between {0} and {1} characters long."),
range:c.validator.format("Please enter a value between {0} and {1}."),max:c.validator.format("Please enter a value less than or equal to {0}."),min:c.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){function a(e){var f=c.data(this[0].form,"validator");e="on"+e.type.replace(/^validate/,"");f.settings[e]&&f.settings[e].call(f,this[0])}this.labelContainer=c(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&
this.labelContainer||c(this.currentForm);this.containers=c(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var b=this.groups={};c.each(this.settings.groups,function(e,f){c.each(f.split(/\s/),function(g,h){b[h]=e})});var d=this.settings.rules;c.each(d,function(e,f){d[e]=c.validator.normalizeRule(f)});c(this.currentForm).validateDelegate(":text, :password, :file, select, textarea",
"focusin focusout keyup",a).validateDelegate(":radio, :checkbox, select, option","click",a);this.settings.invalidHandler&&c(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)},form:function(){this.checkForm();c.extend(this.submitted,this.errorMap);this.invalid=c.extend({},this.errorMap);this.valid()||c(this.currentForm).triggerHandler("invalid-form",[this]);this.showErrors();return this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);
return this.valid()},element:function(a){this.lastElement=a=this.clean(a);this.prepareElement(a);this.currentElements=c(a);var b=this.check(a);if(b)delete this.invalid[a.name];else this.invalid[a.name]=true;if(!this.numberOfInvalids())this.toHide=this.toHide.add(this.containers);this.showErrors();return b},showErrors:function(a){if(a){c.extend(this.errorMap,a);this.errorList=[];for(var b in a)this.errorList.push({message:a[b],element:this.findByName(b)[0]});this.successList=c.grep(this.successList,
function(d){return!(d.name in a)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){c.fn.resetForm&&c(this.currentForm).resetForm();this.submitted={};this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(a){var b=0,d;for(d in a)b++;return b},hideErrors:function(){this.addWrapper(this.toHide).hide()},
valid:function(){return this.size()==0},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{c(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(a){}},findLastActive:function(){var a=this.lastActive;return a&&c.grep(this.errorList,function(b){return b.element.name==a.name}).length==1&&a},elements:function(){var a=this,b={};return c([]).add(this.currentForm.elements).filter(":input").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&
a.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in b||!a.objectLength(c(this).rules()))return false;return b[this.name]=true})},clean:function(a){return c(a)[0]},errors:function(){return c(this.settings.errorElement+"."+this.settings.errorClass,this.errorContext)},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=c([]);this.toHide=c([]);this.currentElements=c([])},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers)},
prepareElement:function(a){this.reset();this.toHide=this.errorsFor(a)},check:function(a){a=this.clean(a);if(this.checkable(a))a=this.findByName(a.name).not(this.settings.ignore)[0];var b=c(a).rules(),d=false,e;for(e in b){var f={method:e,parameters:b[e]};try{var g=c.validator.methods[e].call(this,a.value.replace(/\r/g,""),a,f.parameters);if(g=="dependency-mismatch")d=true;else{d=false;if(g=="pending"){this.toHide=this.toHide.not(this.errorsFor(a));return}if(!g){this.formatAndAdd(a,f);return false}}}catch(h){this.settings.debug&&
window.console&&console.log("exception occured when checking element "+a.id+", check the '"+f.method+"' method",h);throw h;}}if(!d){this.objectLength(b)&&this.successList.push(a);return true}},customMetaMessage:function(a,b){if(c.metadata){var d=this.settings.meta?c(a).metadata()[this.settings.meta]:c(a).metadata();return d&&d.messages&&d.messages[b]}},customMessage:function(a,b){var d=this.settings.messages[a];return d&&(d.constructor==String?d:d[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(arguments[a]!==
undefined)return arguments[a]},defaultMessage:function(a,b){return this.findDefined(this.customMessage(a.name,b),this.customMetaMessage(a,b),!this.settings.ignoreTitle&&a.title||undefined,c.validator.messages[b],"<strong>Warning: No message defined for "+a.name+"</strong>")},formatAndAdd:function(a,b){var d=this.defaultMessage(a,b.method),e=/\$?\{(\d+)\}/g;if(typeof d=="function")d=d.call(this,b.parameters,a);else if(e.test(d))d=jQuery.format(d.replace(e,"{$1}"),b.parameters);this.errorList.push({message:d,
element:a});this.errorMap[a.name]=d;this.submitted[a.name]=d},addWrapper:function(a){if(this.settings.wrapper)a=a.add(a.parent(this.settings.wrapper));return a},defaultShowErrors:function(){for(var a=0;this.errorList[a];a++){var b=this.errorList[a];this.settings.highlight&&this.settings.highlight.call(this,b.element,this.settings.errorClass,this.settings.validClass);this.showLabel(b.element,b.message)}if(this.errorList.length)this.toShow=this.toShow.add(this.containers);if(this.settings.success)for(a=
0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight){a=0;for(b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass)}this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return c(this.errorList).map(function(){return this.element})},showLabel:function(a,
b){var d=this.errorsFor(a);if(d.length){d.removeClass().addClass(this.settings.errorClass);d.attr("generated")&&d.html(b)}else{d=c("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(a),generated:true}).addClass(this.settings.errorClass).html(b||"");if(this.settings.wrapper)d=d.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();this.labelContainer.append(d).length||(this.settings.errorPlacement?this.settings.errorPlacement(d,c(a)):d.insertAfter(a))}if(!b&&this.settings.success){d.text("");
typeof this.settings.success=="string"?d.addClass(this.settings.success):this.settings.success(d)}this.toShow=this.toShow.add(d)},errorsFor:function(a){var b=this.idOrName(a);return this.errors().filter(function(){return c(this).attr("for")==b})},idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(a){var b=this.currentForm;return c(document.getElementsByName(a)).map(function(d,e){return e.form==
b&&e.name==a&&e||null})},getLength:function(a,b){switch(b.nodeName.toLowerCase()){case "select":return c("option:selected",b).length;case "input":if(this.checkable(b))return this.findByName(b.name).filter(":checked").length}return a.length},depend:function(a,b){return this.dependTypes[typeof a]?this.dependTypes[typeof a](a,b):true},dependTypes:{"boolean":function(a){return a},string:function(a,b){return!!c(a,b.form).length},"function":function(a,b){return a(b)}},optional:function(a){return!c.validator.methods.required.call(this,
c.trim(a.value),a)&&"dependency-mismatch"},startRequest:function(a){if(!this.pending[a.name]){this.pendingRequest++;this.pending[a.name]=true}},stopRequest:function(a,b){this.pendingRequest--;if(this.pendingRequest<0)this.pendingRequest=0;delete this.pending[a.name];if(b&&this.pendingRequest==0&&this.formSubmitted&&this.form()){c(this.currentForm).submit();this.formSubmitted=false}else if(!b&&this.pendingRequest==0&&this.formSubmitted){c(this.currentForm).triggerHandler("invalid-form",[this]);this.formSubmitted=
false}},previousValue:function(a){return c.data(a,"previousValue")||c.data(a,"previousValue",{old:null,valid:true,message:this.defaultMessage(a,"remote")})}},classRuleSettings:{required:{required:true},email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(a,b){a.constructor==String?this.classRuleSettings[a]=b:c.extend(this.classRuleSettings,
a)},classRules:function(a){var b={};(a=c(a).attr("class"))&&c.each(a.split(" "),function(){this in c.validator.classRuleSettings&&c.extend(b,c.validator.classRuleSettings[this])});return b},attributeRules:function(a){var b={};a=c(a);for(var d in c.validator.methods){var e=a.attr(d);if(e)b[d]=e}b.maxlength&&/-1|2147483647|524288/.test(b.maxlength)&&delete b.maxlength;return b},metadataRules:function(a){if(!c.metadata)return{};var b=c.data(a.form,"validator").settings.meta;return b?c(a).metadata()[b]:
c(a).metadata()},staticRules:function(a){var b={},d=c.data(a.form,"validator");if(d.settings.rules)b=c.validator.normalizeRule(d.settings.rules[a.name])||{};return b},normalizeRules:function(a,b){c.each(a,function(d,e){if(e===false)delete a[d];else if(e.param||e.depends){var f=true;switch(typeof e.depends){case "string":f=!!c(e.depends,b.form).length;break;case "function":f=e.depends.call(b,b)}if(f)a[d]=e.param!==undefined?e.param:true;else delete a[d]}});c.each(a,function(d,e){a[d]=c.isFunction(e)?
e(b):e});c.each(["minlength","maxlength","min","max"],function(){if(a[this])a[this]=Number(a[this])});c.each(["rangelength","range"],function(){if(a[this])a[this]=[Number(a[this][0]),Number(a[this][1])]});if(c.validator.autoCreateRanges){if(a.min&&a.max){a.range=[a.min,a.max];delete a.min;delete a.max}if(a.minlength&&a.maxlength){a.rangelength=[a.minlength,a.maxlength];delete a.minlength;delete a.maxlength}}a.messages&&delete a.messages;return a},normalizeRule:function(a){if(typeof a=="string"){var b=
{};c.each(a.split(/\s/),function(){b[this]=true});a=b}return a},addMethod:function(a,b,d){c.validator.methods[a]=b;c.validator.messages[a]=d!=undefined?d:c.validator.messages[a];b.length<3&&c.validator.addClassRules(a,c.validator.normalizeRule(a))},methods:{required:function(a,b,d){if(!this.depend(d,b))return"dependency-mismatch";switch(b.nodeName.toLowerCase()){case "select":return(a=c(b).val())&&a.length>0;case "input":if(this.checkable(b))return this.getLength(a,b)>0;default:return c.trim(a).length>
0}},remote:function(a,b,d){if(this.optional(b))return"dependency-mismatch";var e=this.previousValue(b);this.settings.messages[b.name]||(this.settings.messages[b.name]={});e.originalMessage=this.settings.messages[b.name].remote;this.settings.messages[b.name].remote=e.message;d=typeof d=="string"&&{url:d}||d;if(this.pending[b.name])return"pending";if(e.old===a)return e.valid;e.old=a;var f=this;this.startRequest(b);var g={};g[b.name]=a;c.ajax(c.extend(true,{url:d,mode:"abort",port:"validate"+b.name,
dataType:"json",data:g,success:function(h){f.settings.messages[b.name].remote=e.originalMessage;var j=h===true;if(j){var i=f.formSubmitted;f.prepareElement(b);f.formSubmitted=i;f.successList.push(b);f.showErrors()}else{i={};h=h||f.defaultMessage(b,"remote");i[b.name]=e.message=c.isFunction(h)?h(a):h;f.showErrors(i)}e.valid=j;f.stopRequest(b,j)}},d));return"pending"},minlength:function(a,b,d){return this.optional(b)||this.getLength(c.trim(a),b)>=d},maxlength:function(a,b,d){return this.optional(b)||
this.getLength(c.trim(a),b)<=d},rangelength:function(a,b,d){a=this.getLength(c.trim(a),b);return this.optional(b)||a>=d[0]&&a<=d[1]},min:function(a,b,d){return this.optional(b)||a>=d},max:function(a,b,d){return this.optional(b)||a<=d},range:function(a,b,d){return this.optional(b)||a>=d[0]&&a<=d[1]},email:function(a,b){return this.optional(b)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(a)},
url:function(a,b){return this.optional(b)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(a)},
date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a))},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(a)},number:function(a,b){return this.optional(b)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},creditcard:function(a,b){if(this.optional(b))return"dependency-mismatch";if(/[^0-9-]+/.test(a))return false;var d=0,e=0,f=false;a=a.replace(/\D/g,"");for(var g=a.length-1;g>=
0;g--){e=a.charAt(g);e=parseInt(e,10);if(f)if((e*=2)>9)e-=9;d+=e;f=!f}return d%10==0},accept:function(a,b,d){d=typeof d=="string"?d.replace(/,/g,"|"):"png|jpe?g|gif";return this.optional(b)||a.match(RegExp(".("+d+")$","i"))},equalTo:function(a,b,d){d=c(d).unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){c(b).valid()});return a==d.val()}}});c.format=c.validator.format})(jQuery);
(function(c){var a={};if(c.ajaxPrefilter)c.ajaxPrefilter(function(d,e,f){e=d.port;if(d.mode=="abort"){a[e]&&a[e].abort();a[e]=f}});else{var b=c.ajax;c.ajax=function(d){var e=("port"in d?d:c.ajaxSettings).port;if(("mode"in d?d:c.ajaxSettings).mode=="abort"){a[e]&&a[e].abort();return a[e]=b.apply(this,arguments)}return b.apply(this,arguments)}}})(jQuery);
(function(c){!jQuery.event.special.focusin&&!jQuery.event.special.focusout&&document.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.handle.call(this,e)}c.event.special[b]={setup:function(){this.addEventListener(a,d,true)},teardown:function(){this.removeEventListener(a,d,true)},handler:function(e){arguments[0]=c.event.fix(e);arguments[0].type=b;return c.event.handle.apply(this,arguments)}}});c.extend(c.fn,{validateDelegate:function(a,
b,d){return this.bind(b,function(e){var f=c(e.target);if(f.is(a))return d.apply(f,arguments)})}})})(jQuery);

jQuery.extend(jQuery.validator.messages, {
	required: "Detta f&auml;lt &auml;r obligatoriskt.",
	maxlength: jQuery.validator.format("Du f&aring;r ange h&ouml;gst {0} tecken."),
	minlength: jQuery.validator.format("Du m&aring;ste ange minst {0} tecken."),
	rangelength: jQuery.validator.format("Ange minst {0} och max {1} tecken."),
	email: "Ange en korrekt e-postadress.",
	url: "Ange en korrekt URL.",
	date: "Ange ett korrekt datum.",
	dateISO: "Ange ett korrekt datum (&ARING;&ARING;&ARING;&ARING;-MM-DD).",
	number: "Ange ett korrekt nummer.",
	digits: "Ange endast siffror.",
	equalTo: "Ange samma v&auml;rde igen.",
	range: jQuery.validator.format("Ange ett v&auml;rde mellan {0} och {1}."),
	max: jQuery.validator.format("Ange ett v&auml;rde som &auml;r st&ouml;rre eller lika med {0}."),
	min: jQuery.validator.format("Ange ett v&auml;rde som &auml;r mindre eller lika med {0}."),
	creditcard: "Ange ett korrekt kreditkortsnummer."
});

/* Easing */
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	/*swing: function (x, t, b, c, d) {
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},*/
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	}/*,
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}*/
});

Berghs.init();

