/**
 * Removes filter after fading in IE to avoid cleartype bugs
 */
(function($) {
	if (jQuery.browser.msie) {
		$.fn.fadeIn = function(speed, callback) {
			return this.animate({opacity: "show"}, speed, function() {
				if (!jQuery.support.opacity) {
					this.style.removeAttribute("filter");
				}
				if (callback !== undefined) {
					callback.call(this);
				}
			});
		};
		$.fn.fadeOut = function(speed, callback) {
			return this.animate({opacity: "hide"}, speed, function() {
				if (!jQuery.support.opacity) {
					this.style.removeAttribute("filter");
				}
				if (callback !== undefined) {
					callback.call(this);
				}
			});
		};
	}
})(jQuery);


var ApotekHjartat = 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() {
			ApotekHjartat.addAnchors.init([
				{ element: ".teaser", include: ["P", "IMG"] },
				{ element: ".search-result LI", include: ["P", "IMG"] },
				{ element: ".pharmacy-search-result LI", include: ["P", "IMG"] },
				{ element: ".campaign", include: [".offer"], add: false },
				{ element: ".campaign-teaser", include: [".offer"], add: false },
				{ element: ".offers-teaser", include: ["P"] },
				{ element: ".job-teaser", include: ["P"] },
				{ element: ".customer-service-teaser", include: ["P"] },
				{ element: ".contact-teaser", include: ["P"] },
				{ element: "#header .shop-teaser", include: ["P", "IMG"] },
				{ element: ".bloggers LI", include: ["H3", "IMG", "P"] }
			]);
			ApotekHjartat.chapters.init();
			ApotekHjartat.corners.init([
				{ element: "#main-content DIV.issues", top: "H2", bottom: ".content" },
				{ element: "#main-content DIV.article .share", top: "H2", bottom: ".content" },
				{ element: "#main-content DIV.article .facts", top: "H2", bottom: ".content" },
				{ element: "#main-content DIV.article .chapters", top: "H2", bottom: ".content" },
				{ element: "#main-content DIV.form", top: "self", bottom: "self" },
				{ element: "#main-content DIV.poll", top: "self", bottom: "self" },
				{ element: "#body DIV.tabbed-teaser", bottom: "DIV" },
				{ element: "#main-content DIV.search-form", bottom: ".content" },
				{ element: "#main-content DIV.pharmacy-header", bottom: ".content" },
				{ element: "#additional-content DIV.contact-teaser", bottom: ".content" },
				{ element: "#main-content DIV.article-1177", bottom: "self" },
				{ element: "#main-content DIV.contact-form", bottom: "self" },
				{ element: "#main-content DIV.section-header", bottom: "self" }
			]);
			ApotekHjartat.categoryTree.init([
				{ element: ".link-list-1177", trigger: "H3 A" }
			]);
			ApotekHjartat.tabbedTeaser.init();
			ApotekHjartat.slideshow.init();
			ApotekHjartat.campaign.init();
			ApotekHjartat.popups.init([
				{ element: ".pharmacy-information .additional-content", content: ".adr", trigger: "h3" },
				{ element: ".products li", content: ".additional-info" }
			]);
			ApotekHjartat.poll.init();
			ApotekHjartat.nestedList.init();
			ApotekHjartat.pharmacyMap.init();
			ApotekHjartat.mapGuide.init();
			ApotekHjartat.proxyForms.init([".newsletter-teaser"]);
			ApotekHjartat.getTickerData.init();
			ApotekHjartat.hijack.init();
			ApotekHjartat.chatLoader.init();
			ApotekHjartat.externalLinks.init();
			ApotekHjartat.fixDisqus.init();
			ApotekHjartat.contactForm.init();
			ApotekHjartat.carousel.init([
				{ element: ".event UL", navigation: true }
			]);
			ApotekHjartat.commentsCount.init();
		}
	};
}();


ApotekHjartat.commentsCount = function() {
	var publicKey = "4YJRh881hZOHvuboTKzAuk3xHNlQ6GhSEiykeDlfaFVbfPsZLlVvvh0TPRgLCbkn";
	var endPoint = "http://disqus.com/api/3.0/threads/details.jsonp";
	var DOMReady = function() {
		$("a.post-comments").each(function() {
			var $self = $(this);
			var forum = $self.attr("disqus-shortname");
			var id = $self.attr("data-disqus-identifier");
			if (typeof forum != "undefined" && typeof id != "undefined") {
				var url = endPoint + "?thread:ident=" + id + "&forum=" + forum + "&api_key=" + publicKey + "&callback=?";
				$.getJSON(url, function(data) {
					if (typeof data != "undefined" && typeof data.response != "undefined" && typeof data.response.posts != "undefined") {
						if (data.response.posts > 0) {
							$self.html(data.response.posts + " kommentarer");
						}
					}
				});
			}
		});
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}();


ApotekHjartat.getTickerData = function() {
	var n = 5;
	var DOMReady = function() {
		var tickers = 0;
		$(".ticker").each(function() {
			var tickerElm = $(this);
			var userName = (tickerElm.find("a")[0].href).substr(19);
			var url = "http://twitter.com/status/user_timeline/" + userName + ".json?trim_user=true&callback=?";
			$.getJSON(url,
				function(data) {
					if (data.length > 0) {
						var tickerListId = "ticker-list-" + tickers;
						var str = "<ul id=\"" + tickerListId + "\" style=\"display: none;\">";
						for (var i = 0, l = Math.min(data.length, n); i < l; i++) {
							if (data[i]["in_reply_to_user_id"] === null) {
								str += "<li><a rel=\"external\" href=\"http://twitter.com/" + userName + "/status/" + data[i]["id_str"] + "\">" + data[i]["text"] + "</a></li>";
							}
						}
						str += "</ul>";
						tickerElm.find(".content").append(str);
						tickerElm.find(".source").fadeOut("fast", function() {
							tickerElm.addClass("ticker-loaded");
							$("#" + tickerListId).fadeIn();
							ApotekHjartat.ticker.start({ 
								id: tickerListId
							});
						});
						tickers++;
					}
				}
			);
		});
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}();


ApotekHjartat.ticker = function() {
	var easing = "easeInOutQuad";
	var duration = 1500;
	var interval = 4000;
	var step = function(id) {
		var ul = $("#" + id);
		if (!ul.data("over")) {
			var elm = $($(ul).children("li")[0]);
			elm.animate( 
				{ marginLeft: "-=" + elm.outerWidth() },
				ul.data("duration"),
				ul.data("easing"),
				function() {
					this.parentNode.appendChild(this);
					$(this).css("marginLeft", "0px"); 
					setTimer(id);
				}
			);	
		} else {
			setTimer(id);
		}
	};
	var setTimer = function(id) {
		$("#" + id).data("timer", setTimeout( function() { step(id); }, $("#" + id).data("interval")));
	};
	return {
		start: function(args) {
			var tickerList = $("#" + args.id);
			args.easing ? tickerList.data("easing", args.easing) : tickerList.data("easing", easing) ;
			args.duration ? tickerList.data("duration", args.duration) : tickerList.data("duration", duration) ;
			args.interval ? tickerList.data("interval", args.interval) : tickerList.data("interval", interval) ;

			var totalLength = 0;
			tickerList.children("li").each(function() {	totalLength += $(this).outerWidth(); });
			tickerList.width(totalLength + 5);
			
			if (args.onReady) {	args.onReady();	}
			setTimer(args.id);

			$("#" + args.id + " li a").live("mouseover", function() {
				tickerList.data("over", true);
				return false;
			});
			$("#" + args.id + " li a").live("mouseout", function() {
				tickerList.data("over", false);
				return false;
			});
		}
	};
}();



/**
 * Hijacking
 */
ApotekHjartat.hijack = function() {
	var DOMReady = function() {
		var $el = $("#ajax-product-list");
		if ($el.length > 0) {
			var url = jQuery.trim($el.html());
			if (url.length > 0) {
				$.get(url, function(data) {
					var $productList = $(data).find(".product-list");
					if ($productList.length > 0) {
						$el.html($(data).find(".product-list").html());
						$el.fadeIn();
					}
				});
			}
		}
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}();


/**
 * proxy form handling
 */
ApotekHjartat.proxyForms = function() {
	var handleSubmit = function(selector) {
		var url = $(selector + " .submit-url").html();
		var proxyForm = $("<form action=\"" + url + "\" method=\"post\" style=\"position: absolute; left: -9999px;\"></form>");
		$("form").before(proxyForm.append($(selector).html()));
		var n = 0;
		var proxyInputs = proxyForm.find("input");
		$(selector + " input").each(function() {
			proxyInputs[n].value = this.value;
			n++;
		});
		proxyForm.trigger("submit");
	};
	return {
		init: function(selectors) {
			for (var i = 0, l = selectors.length; i < l; i++) {
				var selector = selectors[i];
				$(selector + " input[type=submit]").live("click", function(e) {
					e.preventDefault();
					handleSubmit(selector);
				});
				$(selector + " input").live("keydown", function(e) {
					var code = (e.keyCode ? e.keyCode : e.which);
					if (code == 13) {
						e.preventDefault();
						handleSubmit(selector);
					}
				});
			}
		}
	};
}();


/**
 * Category tree
 */
ApotekHjartat.categoryTree = function() {
	var options;
	
	var DOMReady = function() {
		for (var i = 0, ln = options.length; i < ln; i++) {
			$self = $(options[i].element);
			$self.find(options[i].trigger).live("click", function(e) {
				e.preventDefault();
				$li = $(this).parent().parent();
				if ($li.hasClass("selected")) {
					$li.removeClass("selected");
				} else {
					$li.addClass("selected");
				}
			});
		}
	};
	return {
		init: function(initOptions) {
			options = initOptions;
			$(document).ready(DOMReady);
		}
	};
}();


/**
 * Chapters
 */
ApotekHjartat.chapters = function() {
	var chapters = [];
	
	var dictionary = {
		"letters": "àáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŕ_ /?,.",
		"encoded": "aaaaaaaceeeeiiiidnoooooouuuyybyr---_--"
	};

	var encode = function(str) {
		var tmp = [];
		str = str.toLowerCase();
		for (var 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 = [];
		$(".article-1177 .article-content .chapter > H2").each(function(i) {
			var $self = $(this);
			var text = jQuery.trim($self.html());
			if (text !== "") {
  			ids[i] = encode(text);
  			$self.attr("id", ids[i]);
  			chapters.push({ "id": ids[i], "text": text });
			} else {
			  $self.remove();
			}
		});
		if (chapters.length >= 2) {
			var content = [];
			content.push("<div class=\"chapters\">");
			content.push("<h2>Innehåll</h2>");
			content.push("<div class=\"content\"><ul>");
			for (var i = 0, ln = chapters.length; i < ln; i++) {
				content.push("<li><a href=\"#" + chapters[i].id + "\">" + chapters[i].text + "</a></li>");
			}
			content.push("</ul></div>");
			content.push("</div>");
			$(".article-related .share").after(content.join(""));
		}
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}();


/**
 * Adds rounded corner (for IE8 and below)
 */
ApotekHjartat.corners = function() {
	var options;
	
	var DOMReady = function() {
		for (var i = 0, ln = options.length; i < ln; i++) {
			$self = $(options[i].element);
			$self.addClass("rounded-corners");
			if (options[i].top) {
				$topContainer = options[i].top != "self" ? $self.find(options[i].top) : $self;		
				$topContainer.append("<span class=\"rounded-top\"></span>");
			}
			if (options[i].bottom) {
				$bottomContainer = options[i].bottom != "self" ? $self.find(options[i].bottom) : $self;
				$bottomContainer.append("<span class=\"rounded-bottom\"></span>");			
			}
		}
	};
	return {
		init: function(initOptions) {
			/*@cc_on
			if (@_jscript_version < 9) {
				options = initOptions;
				$(document).ready(DOMReady);		
			}
			@*/
		}
	};
}();


/**
 * Map
 */
ApotekHjartat.map = function() {
	var options = {
		zoom: 16,
		mapTypeControl: false
	};
	var mapStyle = [ 
		{ 
			featureType: "poi", 
			elementType: "all", 
			stylers: [ 
				{ visibility: "off" } 
			] 
		},
		{ 
			featureType: "road.arterial", 
			elementType: "all", 
			stylers: [
				{ saturation: -90 },
				{ lightness: 30 },
				{ hue: "#a19589" }
			] 
		},
		{ 
			featureType: "road.highway", 
			elementType: "all", 
			stylers: [
				{ saturation: -90 },
				{ lightness: 30 },
				{ hue: "#a19589" }
			] 
		},
		{ 
			featureType: "landscape", 
			elementType: "geometry", 
			stylers: [ 
				{ visibility: "simplified" }, 
				{ saturation: 30 }, 
				{ lightness: 0 }, 
				{ hue: "#a19589" } 
			] 
		},
		{ 
			featureType: "landscape.man_made", 
			elementType: "all", 
			stylers: [ 
				{ visibility: "off" } 
			] 
		} 
	];
	return {
		create: function($el, coords, zoom) {
			if (coords) {
				$el.parent().append("<span class=\"rounded-top\"></span>");
				$el.parent().append("<span class=\"rounded-bottom\"></span>");
				options.center = coords;
				options.navigationControlOptions = {
					style: google.maps.NavigationControlStyle.SMALL,
					position: google.maps.ControlPosition.TOP_RIGHT
				};
				if (zoom) {
					options.zoom = zoom;
				}
				map = new google.maps.Map($el.get(0), options);
				map.mapTypes.set("simple", new google.maps.StyledMapType(mapStyle, { map: map }));
				map.setMapTypeId("simple");
				return map;
			}
			return null;
		},
		addMarker: function(map, coords, title, icon) {
			var marker = new google.maps.Marker({
				position: coords, 
				map: map, 
				title: title,
				icon: "/static/img/" + icon
			});
			return marker;
		}
	};
}();


/**
 * Pharmacy map
 */
ApotekHjartat.pharmacyMap = function() {
	var map = null;
	var DOMReady = function() {
		var lat = $("#pharmacy-lat");
		if (lat.length > 0) {
			try {
				var long = $("#pharmacy-long");
				var coords = new google.maps.LatLng(parseFloat(lat.text()), parseFloat(long.text()));
				var mapContainer = $(".pharmacy-map .content");
				map = ApotekHjartat.map.create(mapContainer, coords);
				ApotekHjartat.map.addMarker(map, coords, "Apotek Hjärtat", "icon-pharmacy.png");
			} catch(error) {}
		}
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}();


/* Map guide */
ApotekHjartat.mapGuide = function() {
	var map = null;
	var overlay = null;
	var mapOffsetLeft = 0;
	var mapOffsetTop = 0;
	var activeMarker = null;
	var inactiveMarker = null;

	var createMarker = function(lat, lon, url, name) {
		var marker = ApotekHjartat.map.addMarker(map, new google.maps.LatLng(lat, lon), name);
		marker.setIcon(inactiveMarker);
		google.maps.event.addListener(marker, "mouseover", function() {
			this.setIcon(activeMarker);
			var point = overlay.getProjection().fromLatLngToContainerPixel(marker.getPosition());
			var $self = $(this);
			var offset = $self.offset();
			$popup = $("#map-popup");
			$popup.find("span").html(name);
			$popup.css({
				"left": Math.floor(point.x - $popup.outerWidth() / 2 + 4),
				"top": Math.floor(point.y - $popup.outerHeight() + mapOffsetTop - 18)
			});
			$popup.show();
		});

		google.maps.event.addListener(marker, "mouseout", function() {
			this.setIcon(inactiveMarker);
			$popup.hide();
		});

		google.maps.event.addListener(marker, "click", function() {
			window.location.href = url;
		});
	};

	var DOMReady = function() {
		var $map = $("#map-guide-map");
		if ($map.length > 0) {
			var options = [];
			var $a = $(".map-guide .link-list a");
			options.push("<option>Välj land</option>");
			$a.each(function() {
				options.push("<option value=\"" +  this.href + "\">" + this.innerHTML + "</option>");			
			});
			
			$img = $map.find("h2 img");
			$img.wrap("<fieldset></fieldset>");
			$select = $("<select id=\"map-locactions\">" + options.join("") + "</select>");
			$img.after($select);
			$img.wrap("<label for=\"map-locactions\"></label>");
			$select.change(function() {
				window.location.href = this.options[this.selectedIndex].value;
			});

			map = ApotekHjartat.map.create($map.find(".content"), new google.maps.LatLng(23, 0), 2);
			
			overlay = new google.maps.OverlayView();
			overlay.draw = function() {};
			overlay.setMap(map);

			$popup = $("<div id=\"map-popup\" class=\"popup-small\"><div class=\"content\"><span></span></div></div>");			
			$("body").append($popup);
			var offset = $map.offset();
			mapOffsetLeft = offset.left;
			mapOffsetTop = offset.top;
			$popup.hide();
						
			$(".map .content DIV").live("mouseover", function() {
				if (this.title && this.style.backgroundImage.length > 0) {
					this.title = "";
				}
			});
			
			activeMarker = new google.maps.MarkerImage("/static/img/icon-mapguide-over.png");
			inactiveMarker = new google.maps.MarkerImage("/static/img/icon-mapguide.png");

			var url = ApotekHjartat.getClassNameValue($map.get(0), "url-");
			$.ajax({
				type: "GET",
				dataType: "xml",
				url: unescape(url),
				success: function (xml) {
					var points = xml.getElementsByTagName("point");
					for (var i = 0, ln = points.length; i < ln; i++) {
						createMarker(points[i].getAttribute("latitude"), points[i].getAttribute("longitude"), points[i].getAttribute("URL"), points[i].getAttribute("name"));
					}
				}
			});
		}
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}();


/**
 * Tabbed teaser
 */
ApotekHjartat.tabbedTeaser = function() {
	var triggerClass = "tabbed-teaser";
	var tabsClass = "tabs";
	var partClass = "tabbed-teaser-content";
	var partTag = "div";
	var currentClass = "selected";
	var tabBoxes = 0;
	
	var DOMReady = function() {
		$("." + triggerClass).each(function() {
			var $tabBox = $(this);
			$tabBox.attr("id", triggerClass + "-" + tabBoxes);
			tabBoxes = tabBoxes + 1;

			var $tabs = $tabBox.find("." + tabsClass + " li");
			var $tabContent = $tabBox.find(partTag);
			$tabContent.eq(0).show();

			$tabBox.find("." + tabsClass + " a").live("click", function(e) {
			
				e.preventDefault();
				
				var no;	
				try {
					no = parseInt(this.href.substring(this.href.lastIndexOf("-") + 1, this.href.length), 10) - 1;
				} catch (error) {}

				if (typeof(no) !== "undefined") {
					$tabs.each(function() {
						$(this).removeClass(currentClass);
					});
					$tabs.eq(no).addClass(currentClass);
					$tabContent.each(function() {
						$(this).hide();
					});
					$tabContent.eq(no).show();
				}
			});
		});
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}();


/**
 * Popup
 * Displays a popup containing the content of the element on mouseover of the trigger element.
 * @param {object} An associative array of triggers and content elements:
 *	element (mandatory) The parent element. 
 *	content (mandatory) The inner element containing the content. 
 *	trigger (optional, default is element) The trigger element also gets the class "target-popup".
 */
ApotekHjartat.popups = function() {
	var options;

	var DOMReady = function() {
		for (var i = 0, ln = options.length; i < ln; i++) {
			$trigger = $(options[i].element + (options[i].trigger ? " " + options[i].trigger : ""));
			$trigger.addClass("target-popup"); // @todo elements with no content still get this class
			$trigger.data("popup-element", options[i].element);
			$trigger.data("popup-content", options[i].content);
		}
		$(".target-popup").live("mouseover", function() {
			var $self = $(this);
			if (!$self.data("popup-init")) {
				$self.data("popup-init", true);
				var $content = $self.closest($self.data("popup-element")).find($self.data("popup-content"));
				if ($content.length > 0) {
					var offset = $self.position();
					$self.data("popup-left", offset.left);
					$self.data("popup-top", offset.top);
					$self.data("popup-content", $content.html());
				} else {
					$self.data("popup-content", null);
				}
			}
			var content = $self.data("popup-content");
			if (content) {
				ApotekHjartat.popups.show($self.data("popup-left"), $self.data("popup-top"), content);
			}
		});
		$(".target-popup").live("mouseout", function(e) {
			if ($(e.relatedTarget).closest("#popup").length === 0) {
				ApotekHjartat.popups.hide();
			}
		});
		$("#popup").live("mouseout", function(e) {
			if ($(e.relatedTarget).closest("#popup").length === 0) {
				ApotekHjartat.popups.hide();
			}
		});
	};
	return {
		show: function(x, y, content) {
			$popup = $("#popup");
			if ($popup.length === 0) {
				$popup = $("<div id=\"popup\"></div>");
				$("body").append($popup);
			}
			$popup.html("<div class=\"content\">" + content + "</div>");
			$popup.css("left", x);
			$popup.css("top", y - $popup.outerHeight());
			$popup.show();
		},
		hide: function() {
			$("#popup").hide();
		},
		init: function(initOptions) {
			options = initOptions;
			$(document).ready(DOMReady);
		}
	};
}();


/**
 * Poll
 * Handles polls (submitting, switching, etc)
 */
ApotekHjartat.poll = function() {
	var DOMReady = function() {
		ApotekHjartat.poll.addBars($(".poll"), false);
	};
	return {
		addBars: function($poll, animate) {
			$poll.find(".poll-results li p").each(function() {
				$self = $(this);
				var stat = $self.html().trim().replace(/(\d*).*/, "$1");
				$self.wrapInner("<span></span>");
				var $span = $("<span class=\"stat-bar\"></span>");
				$self.prepend($span);
				if (animate) {
					$span.animate({ width: 2 * stat }, {
						duration: 750,
						step: function() {
							$self = $(this);
							$self.next().html(Math.round(($self.width() / 2)) + " %");
						}
					});				
				} else {
					$span.css("width", 2 * stat);
				}
			});
		},
		init: function() {
			$(document).ready(DOMReady);
			$(".poll .show-results, .poll .show-question").live("click", function() {
				$target = $(this.href.replace(/.*\#(.*)/, "#$1"));
				$(this).parent().fadeOut("fast", function() {
					$target.fadeIn("fast");
				});
				return false;
			});
			$(".poll input[type=radio]").live("click", function() {
				$poll = $(this).closest(".poll-question");
				$poll.find("input[type=submit]").trigger("click");
			});
		}
	};
}();


/**
 * Slideshow
 */
ApotekHjartat.slideshow = function() {
	var DOMReady = function() {
		$(".slideshow").each(function() {
			var $slideshow = $(this);
			var width = $slideshow.width();
			$slideshow.width(width);
			var $ul = $slideshow.children();
			$ul.css("overflow", "hidden");
			var $li = $ul.children("li");
			$li.css("visibility", "visible");
			$ul.width(width * $li.length);
			$nav = $("<div class=\"navigation\"></div>");
			$previous = $("<a href=\"\" class=\"previous\">Föregående bild</a>");
			$next = $("<a href=\"\" class=\"next\">Nästa bild</a>");
			$nav.append($previous).append($next);
			$slideshow.append($nav);
			$slideshow.find(".next").live("click", function() {
				ApotekHjartat.slideshow.slide($slideshow, 1);
				return false;
			});
			$slideshow.find(".previous").live("click", function() {
				ApotekHjartat.slideshow.slide($slideshow, -1);
				return false;
			});
		});
	};
	return {
		slide: function($slideshow, direction) {
			if (!$slideshow.data("working")) {
				$slideshow.data("working", true);
				if (direction > 0) {
					$li = $slideshow.find("li:first-child");
					$nextCaption = $li.next().find(".caption");
					$nextCaption.hide();
					$li.animate({ "marginLeft": -$li.width() }, {
						duration: 200,
						complete: function() {
							$nextCaption.fadeIn();
							$li.parent().append($li);
							$li.css("marginLeft", 0);
							$slideshow.data("working", false);
						}
					});			
				} else {
					$li = $slideshow.find("li:last-child");
					$li.css("marginLeft", -$li.width());
					$li.parent().prepend($li);
					$nextCaption = $li.find(".caption");
					$nextCaption.hide();
					$li.animate({ "marginLeft": 0 }, {
						duration: 200,
						complete: function() {
							$nextCaption.fadeIn();
							$slideshow.data("working", false);
						}
					});	
				}
			}
		},
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}();


/**
 * Campaign
 */
ApotekHjartat.campaign = function() {
	var delay = 5000;
	var speed = 1000;
	var DOMReady = function() {
		$(".campaign-carousel").each(function() {
			var $slideshow = $(this);
			var $ul = $slideshow.children();
			var $li = $ul.children("li");
			if ($li.length > 1) {
				$li.each(function(i) {
					var $self = $(this);
					$self.css({
						"top": 0,
						"left": 0
					});
					if (i > 0) {
						$self.css({
							"position": "absolute",
							"display": "none"
						});
					}
				});
				$nav = $("<div class=\"navigation\"></div>");
				$previous = $("<a href=\"\" class=\"previous\">Föregående bild</a>");
				$next = $("<a href=\"\" class=\"next\">Nästa bild</a>");
				$nav.append($previous).append($next);
				$slideshow.append($nav);
				$slideshow.find(".next").click(function(e) {
					ApotekHjartat.campaign.click(e, $slideshow, 1);
				});
				$slideshow.find(".previous").click(function(e) {
					ApotekHjartat.campaign.click(e, $slideshow, 1);
				});
				
				$slideshow.mouseover(function() {
					stopAuto($slideshow);
				});
				
				$slideshow.mouseout(function(e) {
					if ($(e.relatedTarget).closest(".campaign-carousel").length === 0) {
						startAuto($slideshow);
					}
				});
				
				startAuto($slideshow);
			}
		});
	};
	startAuto = function($slideshow) {	
		var autoplay = setInterval(function() {
			ApotekHjartat.campaign.slide($slideshow, 1);				
		}, delay);
		$slideshow.data("campaign-autoplay", autoplay);
	};
	stopAuto = function($slideshow) {
		var autoplay = $slideshow.data("campaign-autoplay");
		if (autoplay) {
			clearInterval(autoplay);
			$slideshow.data("campaign-autoplay", null);
		}
	};
	return {
		click: function(e, $slideshow, direction) {
			e.preventDefault();
			ApotekHjartat.campaign.slide($slideshow, direction);
		},
		slide: function($slideshow, direction) {
			$slideshow.height($slideshow.height());
			if (direction > 0) {
				$current = $slideshow.find("li:first-child");
				$current.fadeOut(speed, function() {
					$current.css("position", "absolute");
					$current.parent().append($current);
				});
				$next = $current.next();
				$next.fadeIn(speed, function() {
					$next.css("position", "relative");
				});
			} else {
				$current = $slideshow.find("li:first-child");
				$next = $slideshow.find("li:last-child");
				$next.parent().prepend($next);
				$current.css("display", "block");
				$current.fadeOut(speed, function() {
					$current.css("position", "absolute");				
				});
				$next.fadeIn(speed, function() {
					$next.css("position", "relative");				
				});
			}
		},
		init: function() {
			$(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.
 */
ApotekHjartat.addAnchors = function() {	
	var selectors = "";
	return {
		init: function(settings) {
			if (settings) {
				for (var 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;
							for (var 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);									
										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");
										}
									});
								}
							}
						}
					}
				}
			}
		}
	};
}();


/**
 * Nested List
 */
ApotekHjartat.nestedList = function() {
	foldOut = function($ul, $li) {
		$ul.hide();
		$li.addClass("opened");
		$ul.slideDown({ duration: 300, easing:"easeInOutQuad", complete:function() {
			$ul.css("display", "");
		}});			
	};
	
	return {
		init: function() {
			$(".nested-list H3 A").live("click", function() {
				$self = $(this);
				$li = $self.closest("li");
				if ($li.hasClass("opened")) {
					$li.removeClass("opened");
				} else {
					$li.closest(".link-list").find(".opened").removeClass("opened");
					$ul = $li.find("ul");
					if ($ul.length === 0) {
						// @todo add loader
						var url = ApotekHjartat.getClassNameValue(this, "url-");
						if (url.length > 0) {
							$.getJSON(unescape(url), function(data) {
								if (data.response.status == "ok") {
									if (typeof(data.response.value) != "undefined") {
										$ul = $("<ul></ul>");
										for (var i = 0, ln = data.response.value.length; i < ln; i++) {
											$ul.append("<li><a href=\"" + data.response.value[i].url + "\">" + data.response.value[i].name + "</a></li>");
										}
										$li.append($ul);
										foldOut($ul, $li);
									}
								}
							});
						}
					} else {
						foldOut($ul, $li);
					}
				}
				return false;
			});
		}
	};
}();


/* Checks for the chat link and displays a proper message for it */
ApotekHjartat.chatLoader = function() {
	return {
		waitForChat: function() {
			var $el = $("#chat-parent");
			var $img = $el.find("IMG");
			if ($img.length > 0) {
				var text = "Chatta med oss";
				if ($img.attr("src").indexOf("closed") > 0) {
					text = $el.find(".closed-text").html();
				}
				$img.after("<br/>" + text);
			} else {
				setTimeout(ApotekHjartat.chatLoader.waitForChat, 100);
			}
		},
		init: function() {
			var $chat = $("#chat");
			$chat.parent().attr("id", "chat-parent");
			if ($chat.length > 0) {
				ApotekHjartat.chatLoader.waitForChat();
			}
		}
	};
}();


/* Handles external links */
ApotekHjartat.externalLinks = function() {
	return {
		init: function() {
			$("a[rel*=external]").live("click", function() {
				window.open($(this).attr("href"));
				return false;
			});
		}
	};
}();


/* Fixes some minor issues with Disqus "recent comments" */
ApotekHjartat.fixDisqus = function() {
	var DOMReady = function() {
		$("#recentcomments .dsq-widget-item, .blog .dsq-widget-item").each(function() {
			var elm = $(this);
			var article = elm.find(".dsq-widget-meta a");
			var articleTitle = article.html();
			var articleUrl = article.attr("href");
			var commentText = elm.find("span").html();
			if (articleTitle.length > 30) {
				articleTitle = jQuery.trim(articleTitle.substring(0,25)) + "...";
			}
			elm.html("<a href=\"" + articleUrl + "#comments\">&quot;" + commentText + "&quot; <span>" + articleTitle + "</span></a>");
		});
		/* Only show blog-comments if there are any */
		($(".blog").find(".dsq-widget-item").length > 0) ? $(".blog-comments").show() : false;
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}();


/**
 * Generic carousel function
 * @param {object} An associative array of elements and options
 *	element (mandatory) The ul to make a carousel of
 *  enumerate (optional) Enumerates the carousel and updates it on change
 *  easing (optional, default swing) The easing to use for 
 *  delay (optional, default 200ms) The time each change takes
 *	randomStart (optional) Starts the carousel at a random element
 *  navigation (optional) Display backwards and forward navigation elements
 *  centerNavigation (optional) Centers the navigation vertically
 *  clickToChange (optional) Moves the carousel forward when it is clicked
 *  beforeChange (optional) A function that get called before each change is performed
 *  afterChange (optional) A function that get called before each change is performed
 */
ApotekHjartat.carousel = function() {
	var options;
	var defaults = {
		easing: "swing",
		delay: 200
	};
	var navigationInitialized = false;
	var change = function($carousel, delta) {
		if (!$carousel.data("working")) {
			var options = $carousel.data("options");
			$carousel.data("working", true);
			if (options.beforeChange) {
				options.beforeChange.call($carousel, delta);
			}
			if (delta > 0) {
				$li = $carousel.find("li:first-child");
				$li.animate({ "marginLeft": -$carousel.data("width") }, {
					easing: options.easing,
					duration: options.delay,
					complete: function() {
						$carousel.append($li);
						$li.css("marginLeft", 0);
						if (options.afterChange) {
							options.afterChange.call($carousel, delta);
						}
						$carousel.data("working", false);
					}
				});
			} else {
				$li = $carousel.find("li:last-child");
				$li.css("marginLeft", -$carousel.data("width"));
				$carousel.prepend($li);
				$li.animate({ "marginLeft": 0 }, {
					easing: options.easing,
					duration: options.delay,
					complete: function() {
						if (options.afterChange) {
							options.afterChange.call($carousel, delta);
						}
						$carousel.data("working", false);
					}
				});	
			}
			if (options.enumerate) {
				enumerate($carousel, delta);
			}
		}
	};
	var enumerate = function($carousel, update) {
		var no = $carousel.data("no") + update;
		var noOfLis = $carousel.data("noOfLis");
		if (no >= noOfLis) {
			no = 0;
		} else if (no < 0) {
			no = noOfLis - 1;
		}
		$carousel.data("no", no);
		$("#" + $carousel.attr("id") + "-enumeration").html((no + 1) + " av " + noOfLis);
	};
	var DOMReady = function() {
		var noOfCarousels = 0;
		for (var i = 0, ln = options.length; i < ln; i++) {
			$(options[i].element).each(function() {
				var cOptions = jQuery.extend({}, defaults, options[i]);
				$ul = $(this);
				var carouselId = "carousel-" + noOfCarousels;
				$ul.attr("id", carouselId);
				$li = $ul.find("li");
				var noOfLis = $li.length;
				var width = $ul.width();
				$ul.css("overflow", "hidden");
				$ul.width(width * noOfLis);
				$li.css({
					"float": "left",
					"display": "block",
					"visibility": "visible",
					"overflow": "hidden"
				});
				$li.width(width - parseInt($li.css("paddingLeft"), 10) - parseInt($li.css("paddingRight"), 10));
				$parent = $("<div class=\"carousel\"></div>");
				$parent.width(width);
				$parent.css({
					"overflow": "hidden",
					"position": "relative"
				});
				$ul.wrap($parent);
				$parent = $ul.parent();
				var startNo = 1;
				if (cOptions.randomStart) {
					startNo = Math.floor(Math.random() * noOfLis);
					for (var j = 0; j < startNo; j++) {
						$ul.append($li.get(j));
					}
				}
				$ul.data("noOfLis", noOfLis);
				$ul.data("width", width);
				$ul.data("no", startNo);
				$ul.data("options", cOptions);
				if (cOptions.enumerate) {
					$parent.after("<p class=\"carousel-enumeration\" id=\"" + carouselId + "-enumeration\"></p>");
					enumerate($ul, startNo);
				}
				if (cOptions.clickToChange) {
					$ul.css("cursor", "pointer");
					$ul.click(function(e) {
						change($(this), 1);
						e.preventDefault();
						this.blur();
					});
				}
				if (cOptions.navigation) {
					$navigation = $("<div class=\"carousel-navigation\"><a href=\"\" class=\"previous\">Föregående</a><a href=\"\" class=\"next\">Nästa</a></div>");
					$navigation.data("carousel", "#" + carouselId);
					$parent.after($navigation);
					if (!navigationInitialized) {
						$(".carousel-navigation A").live("click", function() {
							var $self = $(this);
							this.blur();
							var $carousel = $($self.closest(".carousel-navigation").data("carousel"));
							if ($self.hasClass("next")) {
								change($carousel, 1);
							} else if ($self.hasClass("previous")) {
								change($carousel, -1);
							}
							return false;
						});
						if (cOptions.centerNavigation) {
							$(window).load(function() {
								var height = $ul.height();
								$li.height(height);
							});
							$navigation.find("A").each(function() {
								var $self = $(this);
								$self.css("top", "50%");							
								$self.css("marginTop", -Math.round($self.outerHeight() / 2));
							});
						}
						navigationInitialized = true;				
					}
				}
				noOfCarousels++;
			});
		}
	};
	return {
		init: function(initOptions) {
			options = initOptions;
			$(document).ready(DOMReady);
		}
	};
}();


/* Contact form validation */
ApotekHjartat.contactForm = function() {
	var addError = function($field, message) {
		$error = $field.next();
		if (!$field.data("has-error")) {
			$error = $("<span class=\"error\"></span>");
			$field.after($error);
		}
		$error.html("<span>" + message + "</span>");
		return false;
	};
	
	var removeError = function($field) {
		if ($field.data("has-error")) {
			$field.next().remove();
			$field.unbind("keyup");
			$field.data("has-error", false);
		}
	};
	
	var validate = function($field, type) {
		var validates = true;
		var value = $field.attr("value");
		if (jQuery.trim(value).length == 0) {
			validates = addError($field, "Du har glömt att fylla i detta fält");
		} else if (type) {
			if (type == "email" && value.search(/(\w|\.|\-)+\@(\w|\.|\-)+\.[a-z]{2,6}$/)) {
				validates = addError($field, "Var vänlig kontrollera din e-epostadress");				
			}
		}
		if (validates) {
			removeError($field);
		} else {
			if (!$field.data("has-error")) {
				$field.data("has-error", true);
				$field.keyup(function() {
					validate($(this), type);
				});
			}
		}
		return validates;
	};
	
	return {
		init: function() {
			$(".contact-form input[type=submit]").live("click", function() {
				var validates = true;
				validates = validate($(".contact-form textarea"));
				validates = validate($(".contact-form input[type=text]"), "email") && validates;
				return validates;
			});
		}
	};
}();


jQuery.extend( jQuery.easing, {
	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;
	}
});


ApotekHjartat.init();
