/**
 * @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
@*/

/**
 * @requires jQuery
 */
$.fn.equalizeHeights = function(){
//	if(window.top == window.self) {
		return $(this).css('min-height', Math.max.apply(this, $(this).map(function(i,e){ return $(e).outerHeight(); }).get() ) );
//	} else {
//		return '0';
//	}
};

/**
 * @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/>").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-" + $(tab.content).attr("id");
					e.preventDefault();
					activateTab(tab);
				});
			});
			if ((document.location.hash == "#tab-" + $(tab.content).attr("id"))) {
				activateTab(tab);
			}
			tabs.push(tab);
		});
	}
	this.addClass("tabbed-module");
	createTabs(this);
};

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

/**
 * 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; $(oInput).css('color','#999'); }
			// 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
					$(this).css('color','#000');
				}
			});
			$(oInput).bind('blur', function() {
				// If the field is empty on blur, assign title to value
				if (!this.value.length) { this.value = this.title; $(this).css('color','#999'); }
			});
		}
	}
	return {
		init: init
	};
}();

/**
 * @requires jQuery
 * Add ARIA Landmark Roles
 */
NetR.addARIA = function() {
	function init() {
		$('#header').attr({role: 'banner'});
		$('#content-primary').attr({role: 'main'});
		$('#nav-main').attr({role: 'navigation'});
		$('#nav-sub').attr({role: 'navigation'});
		$('#content-secondary').attr({role: 'complementary'});
		$('#search').attr({role: 'search'});
		$('#footer').attr({role: 'contentinfo'});
	}
	return {
		init:init
	};
}();

/**
 * @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: '', // 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 {
					if (options.warning != null && options.warning.length > 0) {
						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
	};
} ();

/**
 * 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
 * Converts plain text to mailto links
 */
NetR.activateEmailLinks = function () {
	var options = {
		emailClass: 'hidden-email', // Class name for elements that contain an optional name and an obfuscated email address
		textClass: 'email-text', // Optional text to be used as the visible link text
		addressClass: 'email-address', // The obfuscated email adress (entity encoded, decimal or hexadecimal)
		salt: 'INGEN_SPAM_' // Optional prefix to further reduce the risk of spam bots picking up addresses
	};
	/**
	* 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];
			}
		}
		$('.' + options.emailClass).each(function () {
			var textElem = $(this).find('.' + options.textClass + ':first');
			var addressElem = $(this).find('.' + options.addressClass + ':first');
			if ($(addressElem).length) {
				var textText = addressText = $(addressElem).text();
				if ($(textElem).length) {
					textText = $(textElem).text();
				}
				$(this).html('<a href="mailto:' + addressText.replace(options.salt,"") + '">' + textText.replace(options.salt,"") + '</a>');
			}
		});
	}
	return {
		init: init
	};
}();

/* 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(elm, options) {
	var options = options || {};
	var countdown_elm = $('#'+elm).length ? $('#'+elm) : $(".countdown:first").closest('.m');
	countdown_elm.attr('aria-live', 'off');
	var countdown_d = 0;
	var countdown_timenow = 0;
	var countdown_targetdate = Date.parse(options.nextDate);
	var remain = 0;
	function update() {
		countdown_d = new Date();
		countdown_timenow = countdown_d.getTime();
		remain = Math.floor((countdown_targetdate-countdown_timenow)/1000);
		if (remain < 0 ) {
	      	countdown_elm.find('span:first').html(options.startMsg).addClass('started');
	      	countdown_elm.find('ul').remove();
	      	clearInterval(timer);
	    } else {
	    	var d = (Math.floor(remain/86400))%86400;
	    	var h = (Math.floor(remain/3600))%24;
	    	var m = (Math.floor(remain/60))%60;
	    	countdown_elm.find('.day strong').html(d < 10 ? '0'+d : d);
	    	countdown_elm.find('.hour strong').html(h < 10 ? '0'+h : h);
	    	countdown_elm.find('.minute strong').html(m < 10 ? '0'+m : m);
	    }
	}
	var timer = setInterval(function() {
	   update();
	}, 30000);
	//update();
};

/* AddThis social sharing links
 * @param services Array
 */
NetR.addShareThis = function(opts) {
	var options = {
		headingLevel: '2',
		headingText: 'Dela denna sida med dina vänner:',
		services: []
	};
	for (var key in opts) {
		if (options.hasOwnProperty(key)) {
			options[key] = opts[key];
		}
	}
	var $share = $("#share");
	var l = options.services.length;
	if ($share.length && (l > 0)) {
		$share.append('<h' + options.headingLevel + '>' + options.headingText + '</h' + options.headingLevel + '>');
		for (var i=0; i<l; i++) {
			$share.append('<span class="st_' + options.services[i][0] + '_large" title="' + options.services[i][1] + '"></span>');
		}
	}
};

// Init on document ready
$(document).ready(function() {
	// 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'
				});
			}
		});
	}
	NetR.InputPopulate.init();
	NetR.JSTarget.init({
		val: 'new-window'
	});
	NetR.addARIA.init();
	// NetR.addPrintLink.init({
	//	linkText: 'Skriv ut sidan'
	// });
	NetR.activateEmailLinks.init();
	// Initialise date pickers
	if (jQuery().datepicker) {
		$('input.datepicker').datepicker({
			showOn: 'button',
			buttonImageOnly: false,
			buttonImage: '/massramverk/i/icons/calendar.gif',
			buttonText: 'Välj från kalender'
		});
	}
	$('.article-list > li:even, tbody tr:even, .search-results > li:even').addClass('odd');
	$('.error-message').addClass('animate');
	// External links
	$('.externals').delegate('a','click',function(){
		$(this).attr('target','_blank');
	});
	// Set width for image captions based on image width
	$('span.caption').each(function () {
		var caption = $(this);
		var img = caption.find('img');
		var src;
		if (img.length && !caption.hasClass('fullwidth') && !caption.hasClass('fullwidth-dec')) {
			// Save src
			src = img.attr('src');
			// Reset src, otherwise the load event will fire instantly
			img.attr('src', '');
			// Set load event observer
			img.bind('load', function (e) {
				caption.css('width', img.outerWidth());
			});
			// Reset src
			img.attr('src', src);
		}
	});
});

$(window).load(function() {
	$('.article-list h2').each(function() {
		var self = $(this);
		if(self.find('img').length) {
			var w = $('img', this).outerWidth();
			self.siblings().css('margin-left',w);
		}
	});
	$('.m-h img + h2 a').each(function() {
		var href = $(this).attr('href');
		$(this).parent().prev().wrap('<a href="'+href+'"/>');
	});
	$('.row').each(function(){
		var self = $(this);
		if(self.parents('#content-secondary').length && (self.find('.ticker').length || self.find('.pager').length)) {
			self.find('.ticker .m, .pager .m').equalizeHeights().closest('.col').css('min-height',function() {
				return $(this).find(':first-child').outerHeight(true);
			});
		} else if(self.parents('#content-primary').length) {
			self.find('.ticker:only-child').css('min-height',function() {
				return $(this).find('.ticker').outerHeight(true);
			});
			self.find('.m').equalizeHeights();
			// Set min-height if only one ticker column (to avoid jumping browser window)
			if(self.hasClass('cols-1') && self.has('.ticker')) {
				self.css('min-height',function() {
					return $(this).find('.m').height();
				});
			}
		}
		self.find('.m').css('outline-color',function(){
			return $(this).css('background-color');
		});
	});
	$('a.ad').click(function(){
		var text = $(this).closest('.m').find('h2').text().replace(/ /g,'-');
		if (typeof _gaq !== 'undefined') {
			_gaq.push(['_trackPageview', '/annonser/' + text]);
		}
	});
});
