/* Create NetR namespace */
if(typeof NetR == "undefined"){ var NetR = {}; }

/*
 * Get or set min-height (or height if browser is IE6-)
 */
jQuery.fn.minHeight = function(size) {
	// Explorer versions prior to IE7 needs to have height instead of min-height
	var type = (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7)  ? "height" : "min-height";
	if (size == undefined) {
		// Get min-height for the first element
		return this.css(type);
	} else {
		// Set the min-height on all elements (default to pixels if value is unitless)
		this.css(type, size.toString().match(/^\d+$/) ? size + "px" : size);
		return this;
	}
};

/*
* Justify columns
*/
jQuery.fn.justifyTeaserGroup = function() {
	jQuery(this).each(function(){
		var maxHeight = 0;
		// Get the height of the highest element
		jQuery(".m-c", this).each(function(){
			var height, t = $(this);
			t.minHeight(0);
			height = t.outerHeight() + t.siblings(".m-h").outerHeight();
			if (height > maxHeight) {
				maxHeight = height;
			}
		});
		// Set min-height for all elements
		jQuery(".m-c", this).each(function(){
			var t = $(this);
			t.minHeight(maxHeight - t.siblings(".m-h").outerHeight());
		});
	});
	return this;
};

/**
 * @requires jQuery
 * Finds all links with the supplied combination of attribute and value
 * and sets their target attribute to '_blank' to open a new window.
 * An image can be used instead of plain text.
 */
NetR.JSTarget = function() {
	var options = {
		att: 'class', // The attribute to look for
		val: 'non-html', // The value that triggers a new window
		warning: 'new window', // Text that is appended to the link
		image: null, // The URL for an image that is used instead of plain text
		imageLinkClass: 'nw-image', // Class added to links that contain images
		hiddenClass: 'structural' // Class added to the image
	};
	if ($("html").attr("xml:lang") == "sv") {
		options['warning'] = 'nytt fönster'; // Text that is appended to the link
	}

	/**
	* Initialization
	*/
	function init(opts) {
		// If options were supplied, apply them to the option Object.
		options = $.extend(options, opts || {});
		var oWarning;
		var oRegExp = new RegExp("(^|\\s)" + options.val + "(\\s|$)");
		$('a').each(function() {
			var oImage, oSpeakItSpan, el;
			if ((options.att == 'class') && (oRegExp.test(this.className)) || (oRegExp.test(this.getAttribute(options.att)))) {
				if (options.image) {
					oImage = document.createElement('img');
					oImage.src = options.image;
					oImage.setAttribute('alt', options.warning);
					oImage.className = options.hiddenClass;
					this.appendChild(oImage);
					$(this).addClass(options.imageLinkClass);
					this.setAttribute('title', options.warning);
				} else {
					oSpeakItSpan = $(this).children('.insipio_generator');
					if (oSpeakItSpan.size()) {
						// This page is loaded into the SpeakIt interface, i.e. it has a lot of junk spans
						// So, we need to work with the link's inner span instead of the link itself
						el = oSpeakItSpan;
					} else {
						el = $(this);
					}
					if (el.text().match(/\)\s*$/)) {
						el.text(el.text().replace(/\)\s*$/, ', ' + options.warning + ')'));
					} else {
						el.text(el.text() + ' (' + options.warning + ')');
					}
				}
				this.target = '_blank';
			}
		});
		oWarning = null;
		oImage = null;
	}
	return {
		init: init
	};
} ();

/**
 * @requires jQuery
 * Add article functions, e.g., 'Print' or 'Tell a friend'.
 */
document.articleFunctions = function() {
	var ul;
	function getUl() {
		if (!ul) {
			var funcs = $('.article-functions');
			if (funcs.length) {
				ul = $('ul', funcs);
				if (!ul.length) {
					ul = $('<ul></ul>').appendTo(funcs);
				}
			}
		}
		return ul;
	}
	/**
 	 * Add an item
	 * @param  options  Object  An object with options
	 */
	function addItem(options) {
		var li, a;
		options = jQuery.extend({
			// Link text
			text: '',
			// Link (or li) class
			className: '',
			// Link (or li) id
			id: '',
			// Callback to execute on click
			callback: null,
			// An element to append the link to, bypassing the regular ul
			insertInto: null
		}, options || {});
		
		if (getUl() || options.insertInto) {
			// Create link
			a = $('<a href="#"></a>');
			a.text(options.text);
			a.click(options.callback);
			if (!options.insertInto) {
				// If no insertInto-element is specified,
				// append the link to an li and add it to the ul
				li = $('<li>');
				// Add class and id to the li
				li.attr({
					'class': options.className,
					'id': options.id
				});
				a.appendTo(li);
				li.appendTo(ul);
			} else {
				// Add class and id to the link
				a.attr({
					'class': options.className,
					'id': options.id
				});
				a.appendTo($(options.insertInto));
			}
		}
	}
	return {
		addItem: addItem
	};
}();

/**
 * Paging
 */
(function ($) {

	var Pager = function (el, options) {
		this.options = $.extend({
			number: 10,          // Number of links to show
			hideClass: 'hidden', // Classname to add to hide links
			togglerClass: 'toggler',
			togglerHideClass: 'toggler-hide',
			togglerShowClass: 'toggler-show',
			togglerTextShow: 'Visa fler', // Text to show on toggler when links are hidden
			togglerTextHide: 'Dölj' // Text to show on toggler when links are shown
		}, options || {});
		this.container = $(el);
		this.hidden = false;
		// Get all 'a's and 'em's above the specified number
		this.pageLinks = $('> *:not(span):gt(' + (this.options.number - 1) + ')', this.container);
		// Don't hide links if the current page would be hidden
		if (this.pageLinks.length && !this.pageLinks.is('em')) {
			this.hideLinks();
			this.addToggler();
		}
	};
	Pager.prototype = {
		hideLinks: function () {
			var opt = this.options;
			if (this.pageLinks.length) {
				this.pageLinks.addClass(opt.hideClass);
				this.hidden = true;
			}
		},
		addToggler: function () {
			var t = this,
			    toggler,
			    opt = this.options;
			toggler = $('<a href="#" class="' + opt.togglerClass + ' ' + opt.togglerShowClass + '">' + this.options.togglerTextShow + '</a>');
			toggler.click(function (e) {
				e.preventDefault();
				if (t.hidden) {
					t.pageLinks.removeClass(opt.hideClass);
					toggler.text(opt.togglerTextHide);
					toggler.removeClass(opt.togglerShowClass);
					toggler.addClass(opt.togglerHideClass);
					t.hidden = false;
				} else {
					t.pageLinks.addClass(opt.hideClass);
					toggler.text(opt.togglerTextShow);
					toggler.removeClass(opt.togglerHideClass);
					toggler.addClass(opt.togglerShowClass);
					t.hidden = true;
				}
			});
			this.container.append(toggler);
		}
	};

	$.fn.hidePageLinks = function (options) {
		return this.map(function () {
			new Pager(this, options);
		});
	};
	
	$.fn.addPagerTabs = function () {
		return this.each(function () {
			var navigation, lis = [], selClass = 'sel', sel = false;
			
			function activateItem (item) {
				if (sel) {
					$(sel).removeClass(selClass);
					$(sel.paging).addClass('hidden');
				}
				$(item).addClass(selClass);
				$(item.paging).removeClass('hidden');
				sel = item;
			}
			
			$(this).addClass('multiple-pager-js');
			navigation = $('<ul class="nav cf"></ul>');
			$('h2', this).addClass('structural').after(navigation);
			$('.paging h3', this).each(function () {
				var link, li;
				$(this).addClass('structural');
				li = $('<li></li>');
				li.paging = this.parentNode;
				$(li.paging).addClass('hidden');
				lis.push(li);
				sel = $(li.paging).hasClass(selClass) ? li : false;
				link = $('<a href="#' + $(this).attr('id') + '">' + $(this).text() + '</a>');
				link.click(function (e) {
					e.preventDefault();
					activateItem(li);
				});
				navigation.append(li.append(link));
			});
			activateItem(sel || lis[0]);
		});
	};
	
})(jQuery);

jQuery(function() {
	NetR.JSTarget.init({
		val: 'new-window|file'
	});

	document.articleFunctions.addItem({
		text: 'Skriv ut sidan',
		className: 'print', 
		callback: function(e) {
			e.preventDefault();
			window.print();
		}
	});
	var tell = $('#tell-a-friend');
	if (tell.length) {
		if (window.location.hash != '#tell-a-friend-form') {
			tell.addClass('hidden');
		}
		document.articleFunctions.addItem({
			text: 'Tipsa en vän', 
			className: 'tell-a-friend',
			callback: function(e) {
				e.preventDefault();
				tell.removeClass('hidden');
				window.location.hash = '#tell-a-friend';
			}
		});
	}
	
	// Hide last paging links
	$('.paging:not(.year-paging):not(.alpha-paging) p').hidePageLinks();
	
	// Make multiple pagers tabbable
	$('.multiple-pager').addPagerTabs();
	
	// Set equal heights on teaser rows (delay to allow images to load)
	setTimeout(function () {
		$(".prio-teasers").justifyTeaserGroup();
		$(window).resize(function(){
			$(".prio-teasers").justifyTeaserGroup(); 
		});
	}, 100);
	
});