/**
 * @fileoverview Global functions
 */
/**
 * Hack to reduce background image flickering in IE 6
 */
/*@cc_on
	@if (@_jscript_version == 5.6)
		try {
			document.execCommand("BackgroundImageCache", false, true);
		} catch(err) {}
	@end
@*/

/* Create NetR namespace */
if(typeof NetR == "undefined"){ var NetR = {}; }

/**
 * @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: 'new-window', // The value that triggers a new window
		widthPrefix: 'w', // Prefixes for width and height (e.g. w400 h400)
		heightPrefix: 'h',
		warning: ' (Nytt fönster)', // 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
	};
	/**
	* Initialization
	*/
	function init(opts) {
		// If options were supplied, apply them to the option Object.
		for (var key in opts) {
			if (options.hasOwnProperty(key)) {
				options[key] = opts[key];
			}
		}
		var oWarning, oImage;
		var reAtt = new RegExp("(^|\\s)" + options.val + "(\\s|$)");
		var reWidth = new RegExp("(^|\\s)" + options.widthPrefix + "([0-9]+)(\\s|$)");
		var reHeight = new RegExp("(^|\\s)" + options.heightPrefix + "([0-9]+)(\\s|$)");
		$('a').each(function () {
			var sAttVal;
			if (options.att == 'class') {
				sAttVal = this.className;
			} else {
				sAttVal = this.getAttribute(options.att);
			}
			if (reAtt.test(sAttVal)) {
				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 {
					oWarning = document.createElement("em");
					oWarning.appendChild(document.createTextNode(options.warning));
					this.appendChild(oWarning);
				}
				// If width and height values exist, open a sized window
				if (reWidth.test(sAttVal) && reHeight.test(sAttVal)) {
					$(this).click(function () {
						var sOptions = 'menubar=yes,toolbar=no,location=yes,resizable=yes,scrollbars=yes,status=yes,width=' + reWidth.exec(sAttVal)[2] + ',height=' + reHeight.exec(sAttVal)[2];
						window.open(this.href, '_blank', sOptions);
						return false;
					});
				}
				this.target = '_blank';
			}
		});
		oWarning = null;
		oImage = null;
	}
	return {
		init: init
	};
}();

/**
 * Copy the value of an input field's title attribute to its value attribute.
 * Clear the input field on focus if its value is the same as its title.
 * Repopulate the input field on blur if it is empty.
 * Hide the input field's associated label if it has one.
 * @requires jQuery
 */
NetR.InputPopulate = function() {
	var options = {
		sInputClass: 'populate', // Class name for input elements to autopopulate
		sHiddenClass: 'structural', // Class name that gets assigned to hidden label elements
		sHideLabelClass: 'hidelabel' // If the input has this className, its label is hidden
	};
	function hideLabel(sId) {
		var arrLabels = document.getElementsByTagName('label');
		var iLabels = arrLabels.length;
		var oLabel;
		for (var i=0; i<iLabels; i++) {
			oLabel = arrLabels[i];
			if (oLabel.htmlFor == sId) {
				oLabel.className = oLabel.className + ' ' + options.sHiddenClass;
			}
		}
	};
	/**
	* Initialization
	*/
	function init(opts) {
		// If options were supplied, apply them to the option Object.
		for (var key in opts) {
			if (options.hasOwnProperty(key)) {
				options[key] = opts[key];
			}
		}
		// Find all input elements with the given className
		var arrInputs = $('input.' + options.sInputClass);
		var iInputs = arrInputs.length;
		var oInput;
		for (var i=0; i<iInputs; i++) {
			oInput = arrInputs[i];
			// Make sure it's a text input
			if (oInput.type != 'text') { continue; }
			// Hide the input's label
			if ($(oInput).hasClass(options.sHideLabelClass)) { hideLabel(oInput.id); }
			// If value is empty and title is not, assign title to value
			if ((oInput.value == '') && (oInput.title != '')) { oInput.value = oInput.title; }
			// Add event handlers for focus and blur
			$(oInput).bind('focus', function() {
				// If value and title are equal on focus, clear value
				if (this.value == this.title) {
					this.value = '';
					this.select(); // Make input caret visible in IE
				}
			});
			$(oInput).bind('blur', function() {
				// If the field is empty on blur, assign title to value
				if (!this.value.length) { this.value = this.title; }
			});
		}
	}
	return {
		init: init
	};
}();

/**
 * Creates a link that triggers the browser's window.print function.
 */
NetR.addPrintLink = function () {
	var options = {
		targetEl: 'content-primary', // Id of the element the link is appended to
		linkText: 'Skriv ut sidan',
		linkId: 'print-link'
	};
	/**
	* Initialization
	*/
	function init(opts) {
		// If options were supplied, apply them to the option Object.
		for (var key in opts) {
			if (options.hasOwnProperty(key)) {
				options[key] = opts[key];
			}
		}
		var oTarget = document.getElementById(options.targetEl);
		if (!oTarget) {return;}
		if (!window.print) {return;}
		var oLink = document.createElement('a');
		oLink.id = options.linkId;
		oLink.href = '#';
		oLink.appendChild(document.createTextNode(options.linkText));
		oLink.onclick = function() {
			window.print();
			return false;
		};
		oTarget.appendChild(oLink);
	}
	return {
		init: init
	};
}();

/**
 * @requires jQuery
 * @class Module with tabbed content
 */
$.fn.makeTabbedModule = function(options){
	var options = options || {};
	var tabs = [];
	var active_tab_suffix;
	var tabs_ul;
	/**
	 * Activates a given tab
	 * @param {Object} tab A tab from the this.tabs array
	 */
	function activateTab(tab){
		$(tabs).each(function(){
			$(this.link).parent().removeClass("sel");
			$(this.content).removeClass("active");
		});
		tabs_ul.attr("class", $(tab.content).attr("id") + "-active m-tabs cf");
		$(tab.link).append(active_tab_suffix);
		$(tab.link).parent().addClass("sel");
		$(tab.content).addClass("active");
	}
	/**
	 * Creates the neccessary markup for all tabs
	 * @private
	 */
	function createTabs(that){
		active_tab_suffix = $("<span></span>").attr("class", "structural").text(options.active_tab_suffix || " (visas nu)");
		tabs_ul = $("<ul class=\"m-tabs cf\"></ul>").insertAfter($(".m-h", that));
		if (options.wrap_tabs) {
			$(tabs_ul).wrap("<div class=\"m-tabs-wrap\"></div>");
		}
		if (options.before_tabs) {
			$("<p></p>").text(options.before_tabs).attr("class", "structural").insertBefore(tabs_ul);
		}
		$(that).children(".m-c").each(function(){
			var tab     = {};
			tab.content = this;
			tab.label   = $(".tab-label", this).text();
			tab.link    = $("<a href=\"#" + $(tab.content).attr("id") + "\"><em>" + tab.label +"</em></a>").addClass("tab-" + $(tab.content).attr("id"));
			tab.link.appendTo(tabs_ul).wrap("<li></li>");
			if($(tab.content).hasClass(".active")){ tab.link.parent().addClass("sel"); }
			$.each(['click'], function(i,e){
				tab.link[e](function(e){
					e.preventDefault();
					activateTab(tab);
				});
			});
			if ((document.location.hash == "#" + $(tab.content).attr("id"))) {
				activateTab(tab);
			}
			tabs.push(tab);
		});
	}
	this.addClass("tabbed-module");
	createTabs(this);
};

/* Countdown script based on http://github.com/seaofclouds/is-it-blank-yet/tree/master 
 * @param nextDate Date in YYYY/MM/DD HH:MM format
 */
NetR.countDown = function (options) {
	var options = options || {};
	var countdownContainer = document.getElementById("countdown");
	if (!countdownContainer) { return; }
	countdownContainer.setAttribute('aria-live', 'off');
	var countdown_d = new Date();
	var countdown_timenow = countdown_d.getTime();
	var countdown_targetdate = Date.parse(options.nextDate);
	var countdown_timeleft = Math.floor((countdown_targetdate-countdown_timenow)/1000);
	function countdown(remain,messages) {
	  var
	    countdown = document.getElementById("countdown"),
	    timer = setInterval( function () {
	      var day = (Math.floor(remain/86400))%86400;
	      var hour = (Math.floor(remain/3600))%24;
	      var minute = (Math.floor(remain/60))%60;
	      var second = (Math.floor(remain/1))%60;
	      countdown.innerHTML = (day > 0 ? "<span class='countdown_day'><strong>" + day + "</strong> " + _('days') + "</span> " : "") + (hour > 0 ? "<span class='countdown_hour'><strong>" + hour + "</strong> " + _('hours') + "</span> " : "") + (minute > 0 ? "<span class='countdown_minute'><strong>" + minute + "</strong> " + _('minutes') + "</span> " : "") + (second > 0 ? "<span class='countdown_second'><strong>" + second + "</strong> " + _('seconds') + "</span> " : "") + _('daysleft');
	      if (--remain < 0 ) { 
	        clearInterval(timer); 
	        document.body.id = "yes"; 
	      } else {
	        document.body.id = "no"; 
	      }
	    },1000);          
	}
	countdown(countdown_timeleft, {86400: _('startstomorrow')});
}

/* Modified, vertical version of http://www.gcmingati.net/wordpress/wp-content/lab/jquery/newsticker/jq-liscroll/jquery.li-scroller.1.0.js
 * Changes include:
 * - WAI ARIA support (role: presentation) which makes screen reader ignore the countdown
 * - Pausing accessible from the keyboard
 */
$.fn.liScroll = function(settings) {
		settings = $.extend({
			travelocity: 0.02
		}, settings);
		return this.each(function(){
				var $strip = $(this);
				$strip.addClass("newsticker");
				var stripHeight = 0;
				var $mask = $strip.wrap('<div class="mask"></div>');
				var $tickercontainer = $strip.parent().wrap('<div class="tickercontainer" role="presentation"></div>');
				var containerHeight = $strip.parent().parent().height(); //a.k.a. 'mask' height
				$strip.find("li").each(function(i){
					stripHeight += $(this, i).height();
				});
				$strip.height(stripHeight);
				var defTiming = stripHeight/settings.travelocity;
				var totalTravel = stripHeight+containerHeight;		
				function scrollnews(spazio, tempo){
					$strip.animate({top: '-='+ spazio}, tempo, "linear", function(){$strip.css("top", containerHeight); scrollnews(totalTravel, defTiming);});
				}
				scrollnews(totalTravel, defTiming);
				$strip.find("a").focus(function(){
					$strip.stop();
				});
				$strip.hover(function(){
					$(this).stop();
				},
				function(){
					var offset = $(this).offset();
					var residualSpace = offset.left + stripHeight;
					var residualTime = residualSpace/settings.travelocity;
					scrollnews(residualSpace, residualTime);
				});
		});	
};

/**
 * @requires jQuery
 * Sets caption widths to that of its (first) containing image
 */
NetR.Captions = function () {
	function init() {
		$(".caption").each(function(){
			var self = $(this);
			var w = self.find('img').width();
			self.css("width", w);
		});
	}
	return {
		init: init
	};
}();

/* Init on document ready */
$(document).ready(function() {
	NetR.JSTarget.init({
		val: 'new-window',
		warning: ''
	});
	NetR.InputPopulate.init();
	NetR.addPrintLink.init({
		targetEl: 'article-tools',
		linkText: _('printpage')
	});
	// Temp solution as long as IE6 is still around..
	$(".teaser-cols").each(function() {
		$(this).find(".teaser + .teaser").css("float","right");
	});
	// Makes tabbed modules out of modules with more than one module content area inside
	if (typeof $.fn.makeTabbedModule !== "undefined") {
		$('.m').each(function() {
			if($(this).children('.m-c').length > 1) {
				$(this).children('.m-c:first').addClass("active");
				$(this).makeTabbedModule({
					wrap_tabs: false
				});
			}
		});
	}
});
/* Init on window ready (when images are loaded too) */
$(window).load(function() {
	NetR.Captions.init();
	$('a.lightbox').lightBox(); // Initialize lightbox
});