
function insertAfter(element, siblingNode) {
	if (element && siblingNode) {
		if (siblingNode.nextSibling) {
			siblingNode.parentNode.insertBefore(element, siblingNode.nextSibling);
		} else {
			siblingNode.parentNode.appendChild(element);
		}
	}
}

/* BEGIN: TablePager */
function TablePager(id, numRowsInitial, numRowsReveal) {

	var table = document.getElementById(id);
	var tbody = table.getElementsByTagName("tbody")[0];
	var rows = tbody.getElementsByTagName("tr");
	var position = numRowsInitial;

	for (var i=0; i<rows.length; i++) {
		if (i >= numRowsInitial) {
			var row = rows[i];
			row.style.display = "none";
		}
	}

	if (rows.length > numRowsInitial) {

		var p = document.createElement("p");
		var a = document.createElement("a");

		a.innerHTML = "Vis flere kampanjer...";
		a.href = "#more";
		a.onclick = function() {
			for (var i=0; i<numRowsReveal; i++) {
				var row = rows[i+position];
				if (row) {
					row.style.display = "";
					row.title = position;
				}
				position++;

				if (position >= rows.length) {
					this.style.display = "none";
				}

			}
			return false;
		};

		p.appendChild(a);

		insertAfter(p, table);

	}

}

/* BEGIN: Link Checker */
function checkAllLinks() {

	var types = {
		"txt" : "Tekstfil",
		"prn" : "Tekstfil / PRN",
		"rtf" : "Rikt tekstformat",
		"doc" : "Microsoft Word 97-2003",
		"docx" : "Microsoft Word 2007 eller nyere",
		"xls" : "Microsoft Excel 97-2003 dokument",
		"xlsx" : "Microsoft Excel 2007 eller nyere",
		"ppt" : "Microsoft PowerPoint 97-2003 dokument",
		"pptx" : "Microsoft PowerPoint 2007 eller nyere",
		"pdf" : "Adobe PDF-dokument",
		"eps" : "Adobe Illustrator / Encapsulated PostScript-dokument",
		"tif" : "TIFF Tagged Image File Format"
	};

	function replaceElement(el, tag, content) {
		var name = el.nodeName.toLowerCase();
		if (name === "img") {
			el.src = "/Templates/Styles/link_error.png";
		} else if (name === "a") {
			el.innerHTML = content;
		}
		el.title = content;
	}

	function getExtension(href) {
		var i = href.lastIndexOf(".");
		return (i !== -1) ? href.substring(i+1).toLowerCase() : "";
	}

	function checkElements(els, tag, content) {
		for (var i=0; i<els.length; i++) {
			var el = els[i];
			var href = (el.href||el.src||"").toString();
			if (href.indexOf("file://") === 0) {
				replaceElement(el, tag, content.replace(/\{href\}/g, href));
			} else if (el.href) {
				var ext = getExtension(href);
				if (ext && el.className.indexOf("link-ignore") === -1) {
					el.className += " link-" + ext;
					var title = types[ext]||"";
					if (title) el.title = title;
				}
			}
		}
	}

	var msg = "Den lokale lenken '{href}' er ugyldig her";

	checkElements(document.getElementsByTagName("a"), "span", msg);
	checkElements(document.getElementsByTagName("img"), "span", msg);

}

/* BEGIN: SemanticSearch */
var SemanticSearch = function(searchField, searchResults, searchResultsWrapper, searchUrl) {
	var self = this;
	this.$currentMarked = undefined;
	this.currentMarkedIndex = -1;
	this.minLetters = 3;
	this.hasListPress = false;
	this.searchUrl = searchUrl;
	this.$searchField = $(searchField);
	this.$searchResultsWrapper = $(searchResultsWrapper);
	this.$searchResults = $(searchResults);
	this.$resultsList;
	//this.$searchResults.hide();
	this.$searchResultsWrapper.hide();
	this.searchDelay;
	this.searchDelayTime = 500;
	self.$searchField.unbind("change keyup", self.inputCheck);
	self.$searchField.unbind("change keydown", self.keyNavCheck);
	this.focusSearch = function(event) {
		//console.log("focus");
		self.$searchField.bind("change keyup", self.inputCheck);
		self.$searchField.bind("change keydown", self.keyNavCheck);
		self.inputCheck();
	};
	this.unfocusSearch = function(event) {
		if (!self.hasListPress) {
			//console.log("unfocus");
			self.$searchField.unbind("change keyup", self.inputCheck);
			self.$searchField.unbind("change keydown", self.keyNavCheck);
			self.$searchResultsWrapper.hide();
		}
	};
	this.inputCheck = function(event) {
		//console.log(event);
		if (typeof event == "undefined" || (event.which != 13 && event.which != 38 && event.which != 40)) {
			var fieldContent = self.$searchField.val();
			clearInterval(self.searchDelay);
			if (fieldContent.length >= self.minLetters) {
				self.searchDelay = setInterval(function() {
					self.doSearch(fieldContent);
				}, self.searchDelayTime);
			}
			else if (fieldContent.length < self.minLetters) {
				self.$searchResultsWrapper.hide();
			}
		}
	};
	this.keyNavCheck = function(event) {
		//console.log("KEY: " + event.which);
		switch (event.which) {
			case 13:
				// ENTER
				if (typeof self.$currentMarked != "undefined") {
					window.location = $("a", self.$currentMarked).attr("href");
					event.preventDefault()
				}
				break;
			case 38:
				//console.log("UP");
				if (self.currentMarkedIndex > 0) {
					self.currentMarkedIndex--;
				}
				if (typeof self.$currentMarked != "undefined") {
					self.$currentMarked.removeClass("marked");
				}
				self.$currentMarked = $(self.$resultsList.get(self.currentMarkedIndex));
				if (typeof self.$currentMarked != "undefined") {
					self.$currentMarked.addClass("marked");
				}
				break;
			case 40:
				//console.log("DOWN");
				if (self.currentMarkedIndex < self.$resultsList.length - 1) {
					self.currentMarkedIndex++;
				}
				if (typeof self.$currentMarked != "undefined") {
					self.$currentMarked.removeClass("marked");
				}
				self.$currentMarked = $(self.$resultsList.get(self.currentMarkedIndex));
				if (typeof self.$currentMarked != "undefined") {
					self.$currentMarked.addClass("marked");
				}
				break;
		}
	};
	this.doSearch = function(searchString) {
		clearInterval(self.searchDelay);
		//console.log("Search: " + searchString);
		self.$searchResults.load(self.searchUrl + searchString, self.resultCallback);
	};
	this.resultCallback = function(responseText, textStatus, XMLHttpRequest) {
		//console.log("SEARCH RETURNED: \nResponseText: " + responseText + "\nTextStatus: " + textStatus + "\nXMLHttpRequest: " + XMLHttpRequest);
		if (typeof self.$resultsList != "undefined") {
			self.$resultsList.unbind("mouseover", self.mouseHover);
		}
		self.$currentMarked = undefined;
		self.currentMarkedIndex = -1;
		self.$resultsList = $("li", self.$searchResults);
		if (self.$resultsList.length > 0) {
			self.$searchResultsWrapper.show();
			self.$resultsList.bind("mouseover", self.mouseHover);
		}
	};
	this.mouseHover = function(event) {
		if (self.$currentMarked !== event.currentTarget) {
			if (typeof self.$currentMarked != "undefined") {
				self.$currentMarked.removeClass("marked");
			}
			self.$currentMarked = $(event.currentTarget);
			self.$currentMarked.addClass("marked");
			self.currentMarkedIndex = -1;
		}
	};
	this.$searchField.focus(this.focusSearch);
	this.$searchField.focusout(this.unfocusSearch);
	this.$searchResultsWrapper.mousedown(function() {
		self.hasListPress = true;
	});
	//this.$searchResultsWrapper.mouseup(function () { self.hasListPress = false; });
};

/* BEGIN: ProductScaling */
var ProductScaling = function(productContainer) {
	var self = this;
	this.$productContainer = $(productContainer);
	this.$products = $("li", this.$productContainer);
};
ProductScaling.prototype.scaleTo = function(e) {
	var scaleStep = e.selectedStep;
	var self = e.data;
	var scaleFactor;
	switch (scaleStep) {
		case 0:
			scaleFactor = 6;
			break;
		case 1:
			scaleFactor = 4;
			break;
		case 2:
			scaleFactor = 3;
			break;
		case 3:
			scaleFactor = 2;
			break;
		case 4:
			scaleFactor = 1;
			break;
	}
	var scaleSize = Math.floor((self.$productContainer.width() - (20 * (scaleFactor - 1))) / scaleFactor);
	//console.log("new width : " + scaleWidth);
	var $img = $("img", self.$products);
	var scaleRatio = scaleSize / $img.width();
	self.$products.stop().animate({ width: scaleSize, height: self.$products.height() * scaleRatio }, 450, "easeOutQuart");
	$img.stop().animate({ width: scaleSize, height: $img.height() * scaleRatio }, 450, "easeOutQuart");
	/*
	$(".image", self.$products).stop().animate({width: scaleSize, height: $(".image", self.$products).height() * scaleRatio}, 450, "easeOutQuart");
	$(".body", self.$products).stop().animate({width: scaleSize, height: $(".body", self.$products) * scaleRatio}, 450, "easeOutQuart");
	*/
};

/* BEGIN: Tooltip */
function Tooltip(items, tooltip) {
	var self = this;
	this.items = $(items);
	this.tooltips = $(tooltip, this.items);
	this.items.hover(
		function(e) { $(this).addClass("hover"); },
		function(e) { $(this).removeClass("hover"); }
	);
	this.show = function(el, e) {
		this.hide();
		$(el).css({ top: e.pageY, left: e.pageX }).show();
		return false;
	};
	this.hide = function() {
		this.tooltips.hide();
		return false;
	};
	this.items.click(
		function(e) {
			return self.show($(tooltip, this), e);
		}
	);
	this.tooltips.click(
		function(e) {
			return false;
		}
	);
	$("a", this.tooltips).click(
		function() {
			self.hide();
			if (this.className.indexOf("close-button") == -1) window.open(this.href);
			return false;
		}
	);
	$(document).keypress(
		function(e) {
			if (e.keyCode == 27) self.hide();
		}
	);
	$(document).click(
		function() {
			self.hide();
		}
	);
}

/* BEGIN: MainMenu */
var MainMenu = function(el) {
	var self = this;
	this.$menuItems = $(el);
	this.overAnim = function() {
		var active = $("a.active .hover");
		var other = $(".hover", this);
		active.stop().animate({ opacity: 0 }, 250);
		other.stop().animate({ opacity: 1 }, 250);
		$(">ul", this).show();
	};
	this.outAnim = function() {
		var active = $("a.active .hover");
		var other = $(".hover", this);
		$(">ul", this).hide();
		other.stop().animate({ opacity: 0 }, 250);
		active.stop().animate({ opacity: 1 }, 250);
	};
	$(el).hover(this.overAnim, this.outAnim);
	$(el + " .level-1").click(function() { this.blur(); return false; });
	$(el + " .level-1").css({ cursor: "default" });
	$(el + " .hover").css({ opacity: 0 });
	$(el + " .active .hover").css({ opacity: 1 });
	$(el + " .hover").css({ display: 'block' });
};

/* BEGIN: Slider */
var Slider = function (slider, dragger, steps, lessBtn, moreBtn){
	var self = this;

	// events
	// variables
	this.steps = steps - 1;
	this.stepSize = Math.ceil($(dragger).parent().width() / (steps-1));
	this.selectedStep = -1;

	this.$slider = $(slider);
	this.$dragger = $(dragger);

	// private methods

	this.dragRelease = function(event, ui){

		var currPos =  self.$dragger.position().left;
		var stepPos;
		var selNow;

		for(var i=0;i<self.steps;i++)
		{
			if(currPos > (i*self.stepSize) && currPos < ((i+1)*self.stepSize))
			{
				if(currPos < ((i*self.stepSize)+(self.stepSize*.5)))
				{
					stepPos = Math.floor(i*self.stepSize);
					selNow = i;
				}
				else
				{
					stepPos = Math.floor((i+1)*self.stepSize);
					selNow = i+1;
				}

				break;
			}
		}
		self.setCurrentStep(selNow);
		self.$dragger.stop().animate({left: stepPos}, 450, "easeOutQuart");
	};

	$(dragger).mouseover(function(){$(this).addClass("hand");});
	$(dragger).mouseout(function(){$(this).removeClass("hand");});

	if(typeof lessBtn !== "undefined")
	{
		this.$lessBtn = $(lessBtn);
		this.$lessBtn.bind("click", {self: this}, this.prevStep);
	}

	if(typeof moreBtn !== "undefined")
	{
		this.$moreBtn = $(moreBtn);
		this.$moreBtn.bind("click", {self: this}, this.nextStep);
	}

	$(dragger).draggable({ axis: 'x', cursor: 'pointer', stop: this.dragRelease, distance: 10, containment: 'parent'});
};

// static vars
Slider.STEP_SELECTED = "sliderStepSelected";
// public methods
Slider.prototype.getSteps = function()
{
	return this.steps + 1;
};
Slider.prototype.setCurrentStep = function(stepNr)
{
	if(stepNr<=this.steps && stepNr>=0 && this.selectedStep != stepNr)
	{
		this.selectedStep = stepNr;
		var stepPos = Math.floor(stepNr*this.stepSize);
		this.$dragger.stop().animate({left: stepPos}, 450, "easeOutQuart");
		var e = jQuery.Event(Slider.STEP_SELECTED);
		e.selectedStep = this.selectedStep;
		this.$slider.trigger(e);
	}
	return this.selectedStep;
};
Slider.prototype.getBindable = function()
{
	return this.$slider;
};
Slider.prototype.getCurrentStep = function()
{
	return this.selectedStep;
};
Slider.prototype.nextStep = function(e)
{
	var self = e.data.self;
	if(self.selectedStep<self.steps)
	{
		self.setCurrentStep(self.selectedStep+1);
	}
	return self.selectedStep;
};
Slider.prototype.prevStep = function(e)
{
	var self = e.data.self;
	if(self.selectedStep>0)
	{
		self.setCurrentStep(self.selectedStep-1);
	}
	return self.selectedStep;
};
Slider.prototype.destroy = function(){
	if(typeof this.$lessBtn !== "undefined")
	{
		this.$lessBtn.unbind("click", this.prevStep);
	}

	if(typeof this.$moreBtn !== "undefined")
	{
		this.$moreBtn.unbind("click", this.nextStep);
	}

	this.$dragger.unbind("mouseover");
	this.$dragger.unbind("mouseout");
};

/* BEGIN: FooterNews */
var FooterNews = function(newsContainer, prevBtn, nextBtn) {
	var self = this;
	this.currentItem = 0;
	this.$newsContainer = $(newsContainer);
	this.$prevBtn = $(prevBtn);
	this.$nextBtn = $(nextBtn);
	this.$items = this.$newsContainer.children("li");
	this.$items.each(function(index) {
		var $item = $(this);
		if (index != 0)
			$item.css({ opacity: .5 });
	});
	this.totalItems = this.$items.length - 1;
	this.$prevBtn.addClass("disabled");
	if (this.$items.length == 1)
		this.$nextBtn.addClass("disabled");
	// Mouse over/out functions
	this.nextItem = function(event) {
		$prev = $(self.$items[self.currentItem]);
		$prev.stop().animate({ opacity: .5 });
		self.currentItem++;
		if (self.currentItem >= self.totalItems) {
			self.currentItem = self.totalItems;
			self.$nextBtn.addClass("disabled");
		}
		else {
			if (self.$nextBtn.hasClass("disabled"))
				self.$nextBtn.removeClass("disabled");
			if (self.currentItem != 0)
				self.$prevBtn.removeClass("disabled");
		};
		var $current = $(self.$items[self.currentItem]);
		$current.stop().animate({ opacity: 1 }, 300);
		self.$newsContainer.stop().animate({ left: "-" + $current.position().left }, 600, "easeOutQuart");
		event.preventDefault();
	}
	this.prevItem = function(event) {
		$prev = $(self.$items[self.currentItem]);
		$prev.stop().animate({ opacity: .5 });
		self.currentItem--;
		if (self.currentItem <= 0) {
			self.currentItem = 0;
			self.$prevBtn.addClass("disabled");
		}
		else {
			if (self.currentItem != self.totalItems)
				self.$nextBtn.removeClass("disabled");
			if (self.$prevBtn.hasClass("disabled"))
				self.$prevBtn.removeClass("disabled");
		}
		var $current = $(self.$items[self.currentItem]);
		$current.stop().animate({ opacity: 1 }, 300);
		self.$newsContainer.stop().animate({ left: "-" + $current.position().left }, 600, "easeOutQuart");
		event.preventDefault();
	}
	// Bind mouse-events to elements
	this.$prevBtn.click(this.prevItem);
	this.$nextBtn.click(this.nextItem);
};

/* BEGIN: HelplineMenu */
function HelplineMenu(menuContainer, menuHeader, subContainer, menuItems) {
	// Setup HelplineMenu
	//console.log("HelplineMenu initialize!");
	var self = this;
	this.isOpen = false;
	this.$menuContainer = $(menuContainer);
	this.$menuHeader = $(menuHeader);
	this.$subContainer = $(subContainer);
	this.$menuItems = $(menuItems);
	if (!jQuery.support.opacity) {
		var itemHeight = $(self.$menuItems.get(0)).outerHeight();
		self.$subContainer.css({ top: -(self.$subContainer.outerHeight() + itemHeight) });
	}
	// Animate in menu
	this.$menuContainer.css({ zIndex: -1 });
	this.$menuContainer.show();
	var endPos = this.$menuContainer.position().left;
	this.$menuContainer.css({ left: endPos - this.$menuContainer.outerWidth() });
	this.$menuContainer.stop().animate({ left: endPos }, 800, "easeInOutQuart");
	this.$subContainer.css({ zIndex: -1 });
	// Mouse over/out functions
	this.overAnim = function() {
		if (!self.isOpen) {
			self.isOpen = true;
			self.$subContainer.show();
			$(self.$menuItems.get().reverse()).each(function(index) {
				$(this).css({ position: "relative", top: ($(this).height() * index), display: "block" });
				$(this).stop().animate({ top: 0 }, (150 * index), "easeOutQuart");
			});
		}
	}
	this.outAnim = function() {
		if (self.isOpen) {
			self.isOpen = false;
			self.$menuItems.each(function(index) {
				$(this).stop();
				$(this).css({ position: "relative", top: ($(this).height() * index), display: "none" });
			});
			self.$subContainer.hide();
		}
	}
	this.overItemAnim = function() {
		if (jQuery.support.opacity) {
			this.menuHover.stop().fadeTo(300, 1);
		}
	}
	this.outItemAnim = function() {
		if (jQuery.support.opacity) {
			this.menuHover.stop().fadeTo(500, 0);
		}
	}
	goToLink = function() {
		window.location = $("a", this).attr("href");
	}
	// Bind mouse-events to elements
	this.$menuItems.each(function(index) {
		this.menuHover = $("span", this);
		//$(this).mouseover(self.overItemAnim);
		//$(this).mouseout(self.outItemAnim);
		$(this).click(goToLink);
	});
	this.$menuHeader.menuItems = this.$menuItems;
	this.$menuHeader.mouseover(this.overAnim);
	this.$menuHeader.mouseleave(this.outAnim);
};

/* BEGIN: Accordion */
var Accordion = function(accContainer) {
	//console.log("Accordion");
	var self = this;
	this.$accContainer = $(accContainer);
	this.$headers = $("h2.group", this.$accContainer);
	this.$headers.addClass("handIcon");
	//this.$accItems = $(".listing", this.$accContainer);
	var twCalc = new TextWidthCalc();
	this.openClose = function(target, self) {
		var $header = $(target);
		var $item = $header.parent(".accordion");
		var $content = $header.next(".accordionContent");
		var $paging = $item.next(".PagingContainer");
		/*
		console.log($item);
		console.log($header);
		console.log($content);
		console.log($paging);
		*/
		if ($item.hasClass("isClosed")) {
			//console.log("setting OPEN");
			$item.removeClass("isClosed");
			if ($paging.length > 0) {
				$paging.show();
			}
			$content.show();
			var $innerContent = $($content.children().get(0));
			//var $innerContent = $content.find("ul.listing")
			$content.stop().animate({ height: ($innerContent.outerHeight() + 2) }, 400, "easeOutQuart");
		}
		else {
			//console.log("setting CLOSED");
			if ($paging.length > 0) {
				$paging.hide();
			}
			$content.stop().animate({ height: 0 }, 400, "easeOutQuart", function() { $content.hide(); $item.addClass("isClosed"); });
		}
	};
	this.$headers.bind("click", { self: this }, this.openCloseAnswer);
};
Accordion.prototype.openCloseAnswer = function(e) {
	var self = e.data.self;
	self.openClose(e.currentTarget, self);
};
var TextWidthCalc = function() { };
TextWidthCalc.prototype.calc = function(text, maxWidth, testHolder) {
	var $testHolder = $(testHolder);
	$testHolder.append('<div id="Test" style="position: absolute;visibility: hidden;height: auto;width: auto;"></div>');
	var $test = $("#Test");
	var fits = false;
	var tmpText = text;
	$test.text(text);
	if ($test.width() > maxWidth) {
		while (fits == false) {
			if ($test.width() <= maxWidth) {
				fits = true;
				tmpText = tmpText.substr(0, tmpText.length - 3) + "...";
			}
			else {
				tmpText = tmpText.substr(0, tmpText.length - 1);
				$test.text(tmpText);
			}
		}
	}
	$testHolder.remove("#Test");
	function removeNL(s) {
		r = "";
		for (i = 0; i < s.length; i++) {
			if (s.charAt(i) != '\n' &&
				s.charAt(i) != '\r') {
				r += s.charAt(i);
			}
			else {
				//console.log("#" + i + " control character: " + s.charCodeAt(i));
				r += " ";
			}
		}
		return r;
	}
	return removeNL(tmpText);
};
/* END: Accordion */

