/**
 * @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
 * Toggles answers in FAQ lists.
 */
NetR.toggleFAQ = function() {
	$('ul.faq .answer').addClass('hidden');
	$('ul.faq h3.question').wrapInner('<a href="#"></a>').click(function(e) {
		e.preventDefault();
		$('ul.faq .answer').addClass('hidden');
		$('ul.faq li').removeClass('open');
		$(this).parents('li').toggleClass('open').find('.answer').toggleClass('hidden');
	});
};

/**
 * @requires jQuery
 * Toggles treatment before/after images lists.
 */
NetR.toggleTreatmentImages = function() {
	$('ul.treatment-images .case-info').addClass('hidden');
	$('ul.treatment-images h3.case').wrapInner('<a href="#"></a>').click(function(e) {
		e.preventDefault();
		$('ul.treatment-images .case-info').addClass('hidden');
		$('ul.treatment-images li').removeClass('open');
		$(this).parents('li').toggleClass('open').find('.case-info').toggleClass('hidden');
	});
};

/**
 * @requires jQuery
 * Toggle images in multi-teaser modules.
 */
NetR.multiTeaser = function () {
	var config = {
		sTeaserList: '#multi-teaser ul', // Selector for teaser list
		sImageContainer: '#multi-teaser #images', // Selector for image container
		sItemPrefix: 'teaser-', // List item id prefix
        sHiddenClass: 'hidden', // Hidden class name
        sSelectedClass: 'sel', // Selected class name
        sJSClass: 'js-on' // Class name to indicate that JavaScript is available
	};
	/**
	* Initialization
	*/
	function init(opts) {
		// If options were supplied, apply them to the option Object.
		for (var key in opts) {
			if (config.hasOwnProperty(key)) {
				config[key] = opts[key];
			}
		}
		var oList = $(config.sTeaserList)[0];
		var oImages = $(config.sImageContainer)[0];
		if (!oImages || !oList) { return; }
		$(oImages).addClass(config.sJSClass);
        $(oList).find('li a').each(function() {
            var $$ = $(this);
            var oImageCont = $(oImages).find("." + $$.parent().attr("id"));
            var oImage = $(oImageCont).find("img")[0];
            // Make the image clickable
            $(oImage).bind("click", function() {
                document.location.href = $$.attr("href");
            });
            $$.bind("mouseover focus", function(e) {
                if (!$$.parent().hasClass(config.sSelectedClass)) {
                    $$.parent().addClass(config.sSelectedClass).siblings().removeClass(config.sSelectedClass);
                    $(oImageCont).siblings("." + config.sSelectedClass).removeClass(config.sSelectedClass).fadeOut("slow");
                    $(oImageCont).appendTo($(oImages)).fadeIn("slow").addClass(config.sSelectedClass);
                }
            });
        });
        // Move the selected image last
		$(oImages).children("div." + config.sSelectedClass).appendTo($(oImages));
		// Hide the other images
		$(oImages).children("div:not(." + config.sSelectedClass + ")").hide();
		// Remove the hidden class used for JS off
		$(oImages).children("div").removeClass(config.sHiddenClass);
	}
	return {
		init: init
	};
}();

// Init on document ready
$(document).ready(function() {
	$('body').addClass('js'); /* let the css know we have javascript enabled */
	// Activate FAQ toggle
	NetR.toggleFAQ();
	// Activate before/after images toggle
	NetR.toggleTreatmentImages();
	NetR.linkInfo.init();
	NetR.addARIA.init();
	NetR.JSTarget.init({
		val: 'new-window',
		warning: ''
	});
	NetR.activateEmailLinks.init();
	NetR.multiTeaser.init();
	// NetR.addPrintLink.init({
	//	linkText: 'Skriv ut sidan'
	// });
	// Initialise date pickers
	if (jQuery().datepicker) {
		$('input.datepicker').datepicker({
			showOn: 'button',
			buttonImageOnly: false,
			buttonImage: '/i/icons/calendar.gif',
			buttonText: 'Välj från kalender'
		});
	}
	
	if ($('#start-teaser').size()) {
		$('#start-teaser .teaser-pager').newspager({
			delay: 15000,
			pagingevent: "mouseover",
			prevnext: false,
			paging: true,
			effect: "dissolve"
		});
	}
});
