/**
 * @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"/>').insertBefore($("."+options.panel_class+":first", that));
		if (options.wrap_tabs) {
			$(tabs_ul).wrap('<div class="m-tabs-wrap"/>');
		}
		if (options.before_tabs) {
			$('<p/>').text(options.before_tabs).attr("class", "structural").insertBefore(tabs_ul);
		}
		$(that).children("."+options.panel_class).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/>');
			if($(tab.content).hasClass("active")){ tab.link.parent().addClass("sel"); }
			$.each(['click'], function(i,e){
				tab.link[e](function(e){
					document.location.hash = "#" + $(tab.content).attr("id");
					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') + ", " + options.nextDate.replace(/\//g, "-").replace(/:00:00/g, ":00");
	      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) {
	var 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 () {
	/* Let everyone know we've got javascript enabled */
	$('body').addClass('js');

	if (typeof $.fn.prettyPhoto !== "undefined") {
		$("a[rel^='prettyPhoto']").prettyPhoto();
	}
	if (typeof $.fn.lightBox !== "undefined") {
		$('a.lightbox').prettyPhoto(); // Initialize old lightboxes as new, if they still exist somewhere
	}

	$('#tab-community').click(function () {
		// Collapse all other tabs
		var url = $(this).find("a").attr("href");
		$('#nav-main').addClass('loading');
		/* Method 1:
		$(this).prev().hide("fast", function(){
		// use callee so don't have to name the function
		$(this).prev().hide("fast", arguments.callee);
		if($(this).is(":first-child")) {
		document.location = url;
		}
		});
		Method 2: */
		$(this).siblings().hide(500, function () {
			document.location = url;
		});
		return false;
	});

	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,
					panel_class: 'm-c'
				});
			}
		});
	}
	/* Hide/Show comments */
	if ($('#blog-comments').length) {
		var comments = $('#blog-comments');
		var commentCount = comments.find('li').length;
		var commentLabel = "Kommentarer";
		if (commentCount > 1) {
			commentLabel = commentCount + " kommentarer";
		} else if (commentCount == 1) {
			commentLabel = "1 kommentar";
		}
		comments.hide();

		$('<a id="comment-link" href="#blog-comments">' + commentLabel + '</a>').appendTo($('#article-tools')).toggle(function () {
			comments.fadeIn(200);
			return false;
		}, function () {
			comments.hide();
			return false;
		});
		if (document.location.hash.indexOf("#error") != -1) {
			$('#comment-link').trigger('click');
		}
	}
	$('#content-secondary-2 .twtr-widget').before('<iframe src="http://www.facebook.com/plugins/likebox.php?id=119358364782551&amp;width=215&amp;connections=6&amp;stream=true&amp;header=false&amp;height=600" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:215px; height:600px;" allowTransparency="true"></iframe>');

});
/* Init on window ready (when images are loaded too) */
$(window).load(function() {
	NetR.Captions.init();
	$('a.ad').click(function(){
		var text = $(this).closest('.m').find('h2').text().replace(/ /g,'-');
		if (typeof pageTracker !== "undefined") {
			pageTracker._trackPageview("/annonser/" + text);
		}
	});
});
