/**
 * @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 = {}; }

/**
 * Display an alert dialog when inactive links are clicked.
 */
NetR.linkInfo = function() {
	var sInfoText = 'Denna länk är inte aktiv i prototypen.';
	function init() {
		var links = document.getElementsByTagName('a');
		var re = /inactive|^netrp-/;
		var oLink;
		for (var i=0, l=links.length; i<l; i++) {
			oLink = links[i];
			/* The second parameter is needed for IE to return the actual value of the href attribute */
			if (re.test(oLink.getAttribute('href',2))) {
				oLink.onclick = function() {
					alert(sInfoText);
					return false;
				};
			}
		}
	}
	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
	};
}();

/**
 * @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).hide().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).fadeIn(300, function(){
			$(this).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(i){
			var tab	 = {};
			tab.content = this;
			tab.label   = $(".tab-label", this).text();
			tab.link	= $('<a href="#tab-' + $(tab.content).attr("id") + '"><em>' + tab.label + '</em></a>').addClass('tab-' + $(tab.content).attr("id"));
			tab.link.css({
				'position':'relative',
				'outline':'0',
				'z-index':tab.link.length+1-i
			}).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);
};


// Init on document ready
$(document).ready(function() {
	// Splash functions
	var wrapperheight_orig = $('#splash').height() / 2;
	var pagination = '<div id="splash-pager"><a href="#" id="page-prev">▲</a><a href="#" id="page-next">▼</a></div>';
	$.fn.extend({
		centerMe: function() {
			return this.each(function() {
				var top = (this.offsetTop) / 2;
				var wrapperheight = wrapperheight_orig - ($(this).height() / 2);
				var newpos = top - (wrapperheight / 2);
				$('#splash').animate({scrollTop: top + newpos - wrapperheight + 'px'}, 600, 'easeInOutQuad');
			});
		}
	});
	$('#splash').after(pagination).find('.wrap div:first').addClass('current');
	$('#splash > div').css('height',function(){
		return $(this).parent().css('height');
	});
	$('#page-prev').css('visibility','hidden');
	$('#splash-pager a').click(function() {
		$('#page-prev,#page-next').css('visibility','visible');
		if ($(this).is('#page-next')) {
			$('#splash .current').removeClass('current').next().centerMe().addClass('current');
			if($('#splash .current').is(':last-child')) {
				$('#page-next').css('visibility','hidden');
			}
		} else {
			$('#splash .current').removeClass('current').prev().centerMe().addClass('current');
			if($('#splash .current').is(':first-child')) {
				$('#page-prev').css('visibility','hidden');
			}
		}
		return false;
	});
	
	// Tabs (Multi-teaser) on home page
	// Initialise tabs
	var $tabcontainer = $('#multi-teaser');
	if ($tabcontainer.length && ($tabcontainer.find('.tab').length > 1) && jQuery().simpleTabs) {
		var tabs = $tabcontainer.simpleTabs({
			wrapperClass: 'tabs-content',
			currentClass: 'sel',
			tabhead: '.tab > h2',
			tabheadClass: 'structural',
			tabbody: '.tab',
			tabsListClass: 'tab-nav',
			fx: 'show',
			fxspeed: 'normal',
			syncheights: true,
			clickableTabbody: true
		});
	}
	
	// Create a dropdown menu to swap between e.g. room images
	$('.image-toggler').each(function() {
		var self = $(this);
		if(self.find('img').size() > 1) {
			var menu = $('<select name="image"/>').bind('change', function() {
				self.find('img').hide().end().find('img:eq('+$(this).val()+')').show();
			});
			$(this).find('img').map(function(i) {
				menu.append('<option value="'+i+'">'+$(this).attr('alt')+'</option>');
			});
			self.prepend($('<form action="#"/>').append(menu));
			self.find('img:gt(0)').hide();
		}
	});

	// Set width for image captions based on image width
	$('span.caption').each(function () {
		var caption = $(this);
		var img = caption.children('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() + 150);
				/*if(caption.hasClass('left') || caption.hasClass('left-dec')) {
					caption.css('margin-right', '-150px');
				} else if(caption.hasClass('right') || caption.hasClass('right-dec')) {
					caption.css('margin-left', '-150px');
				}*/
			});
			// Reset src
			img.attr('src', src);
		}
	});

	// 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) {
				if (document.location.hash.indexOf("#tab-")) {
					$(this).children('.m-c:last').addClass('active');
				}
				$(this).makeTabbedModule({
					wrap_tabs: false,
					panel_class: 'm-c'
				});
			}
		});
	}

	/* Open the last accordion div by default */
	$('.accordion').each(function () {
		$('.m:first', this).addClass('sel');
		var acc = new NetR.Accordion($(this));
	});

	if (typeof $.fn.prettyPhoto !== "undefined") {
		$('.share-email').each(function(i){
			var self = $(this);
			var url = self.attr('href').split('#')[0] || self.attr('href');
			var area = self.attr('href').split('#')[1] || 'content-primary';
			$('<div id="temp-'+area+'"/>').load(url + ' #' + area, function(){
				self.attr('href','#temp-'+area).prettyPhoto();
			}).hide().appendTo('body');
		});
	}

	/* Enable click on whole list item on campaigns */
	$('#m-campaigns li').css('cursor','pointer').click(function(){
		document.location.href = $(this).find('a:first').attr('href');
	});

	NetR.linkInfo.init();
	NetR.addARIA.init();
	NetR.JSTarget.init({
		val: 'new-window',
		warning: ''
	});
	NetR.activateEmailLinks.init();
});
