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

// Extensions to jQuery
(function ($) {
	$.extend($.fn, {
		getLabel: function() {
			var label;
			if (this.is('input, select, textarea') && this.attr('id')) {
				label = $('label[for=' + this.attr('id') + ']');
				return label;
			}
		}
	});
})(jQuery);

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

/**
 * Display an alert dialog when inactive links are clicked. Remove before launch.
 */
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
 * Load different search result pages depending on user input. Remove before launch.
 */
NetR.moduleSearchNavigate = function() {
	var config = {
		sFormId:'sort-search',
		sTextfieldId:'wastetype',
		URLs:{
			'lysrör':'scenario-sort-guide.html'
		}
	};
	/**
	 *
	 */
	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 oForm = document.getElementById(config.sFormId);
		if (!oForm) { return; }
		var oField = document.getElementById(config.sTextfieldId);
		if (!oField) { return; }
		$(oField.form).submit(function() {
			for (var key in config.URLs) {
				if (key == oField.value.toLowerCase()) {
					document.location.href = config.URLs[key];
					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
		fileLinkClass: 'file' // Class for links to non-HTML documents
	};
	/**
	* 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) {
						if ($(this).hasClass(options.fileLinkClass)) {
							$(this).attr('title', function() {
								return this.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
	};
} ();

/**
 * @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: '' // 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
 * 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).find("div." + config.sSelectedClass).appendTo($(oImages));
		// Hide the other images
		$(oImages).find("div:not(." + config.sSelectedClass + ")").hide();
		// Remove the hidden class used for JS off
		$(oImages).find("div").removeClass(config.sHiddenClass);
	}
	return {
		init: init
	};
}();

/**
 * @requires jQuery
 * Displays help text associated with radio buttons
 */
NetR.radioHelp = function () {
	var options = {
		containerId: 'container-help',
		hiddenClass: 'hidden'
	};
	var activeHelp;
	function toggleHelp() {
		helpText = this.parentNode.getElementsByTagName('p');
		if (activeHelp) {
			for (i = 0; i < activeHelp.length; i++) {
				activeHelp[i].style.display = 'none';
			}
		}
		for (i = 0; i < helpText.length; i++) {
			helpText[i].style.display = '';
		}
		activeHelp = helpText;
	}
	/**
	* 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 oContainer = document.getElementById('container-help');
		if (!oContainer) { return; }
		inputs = oContainer.getElementsByTagName('input');
		n_inputs = inputs.length;
		onechecked = false;
		for (i = 0; i < n_inputs-2; i++)
			if (inputs[i].type=='radio')
				if (inputs[i].checked) {
					onechecked = true;
				}
		if (!onechecked) {
			inputs[0].checked = true;
		}
		for (i = 0; i < n_inputs-2; i++) { /* -2 for avoiding submit button and last help text */
			if (inputs[i].type=='radio') {
				if (!inputs[i].checked) {
					helpTexts = inputs[i].parentNode.getElementsByTagName('p');
					for (j = 0; j < helpTexts.length; j++) {
						helpTexts[j].style.display = 'none';
					}
				} else {
					activeHelp = inputs[i].parentNode.getElementsByTagName('p');				
				}
				inputs[i].onclick=toggleHelp;
			}
		}
	}
	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
	};
	/**
	* 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
		$('input[type="text"].' + options.sInputClass).each(function() {
			// Hide the input's label
			var input = $(this);
			if ($(this).hasClass(options.sHideLabelClass)) {
				$('label#' + $(this).attr('id')).addClass(options.sHiddenClass);
			}
			// If value is empty and title is not, assign title to value
			if (($(this).attr("value") == '') && ($(this).attr("title") != '')) {
				$(this).attr("value", $(this).attr("title"));
			}
			// Add event handlers for focus and blur
			$(this).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).bind('blur', function() {
				// If the field is empty on blur, assign title to value
				if (!this.value.length) { this.value = this.title; }
			});
			$($(this).get(0).form).submit(function() {
				// Make sure the form isn't submitted with the title text as value
				if (input.attr("value") == input.attr("title")) {
					input.attr("value", '');
				};
			});
		});
	}
	return {
		init: init
	};
}();

/**
 * Rating tool
 * @requires jQuery
 */
NetR.RatingTool = function (fieldset) {
	var t = this;

	this.activeRating = 0;

	this.elements = {};
	this.elements.oldFieldset = fieldset;
	this.elements.col = $('<div class="col col-1 large rating-tool"></div>');
	this.elements.label = $('<div class="label">' + this.elements.oldFieldset.find('legend').html() + '</div>');
	this.elements.votes = this.elements.oldFieldset.find('p.votes');

	this.elements.starContainer = $('<div class="star-container"></div>');
	this.elements.starLinks = [];
	this.elements.oldFieldset.find('input[type=radio]').each(function (i) {
		var radio = $(this),
			starLink = $('<a href="/"><span class="structural">Ranka detta ' + radio.getLabel().text() + '</span></a>');
		starLink.mouseover(function () {
			t.showRating(0.5 * (i + 1));
		});
		starLink.click(function (e) {
			e.preventDefault();
			t.setRating(0.5 * (i + 1));
		});
		t.elements.starContainer.append(starLink);
		t.elements.starLinks.push(starLink);
	});

	this.elements.starContainer.mouseleave(function () {
		t.showRating(t.activeRating);
	});

	this.elements.oldFieldset.hide();
	this.elements.oldFieldset.after(this.elements.col.append(this.elements.label).append(this.elements.starContainer).append(this.elements.votes));
};
NetR.RatingTool.prototype = {
	showRating: function (value) {
		this.elements.starContainer.css('backgroundPosition', '0 -' + (16 * (value / 0.5)) + 'px');
	},
	setRating: function (value) {
		this.showRating(value);
		this.elements.oldFieldset.find('input[type=radio][value=' + value + ']').attr('checked', true);
		this.activeRating = value;
	}
};

/**
 * Creates a link that triggers the browser's window.print function.
 */
(function($) {
	$.fn.initArticleTools = function(settings) {
		var config = {
			linkText: 'Skriv ut sidan',
			linkClass: 'print-link',
			container: $('.page-tools').size() ? $('.page-tools') : '<div class="page-tools"></div>'
		};
		if (settings) $.extend(config, settings);
		this.each(function() {
			if (config.container != "") {
				var container = $(config.container);
			}
			var link = $('<a href="#" class="' + config.linkClass + '">' + config.linkText + '</a>');
			link.click(function() {
				window.print();
				return false;
			});
			if (container) {
				container.prepend(link);
				$(this).append(container);
			} else {
				$(this).append(link);
			}
			container.find('a.send-feedback').click(function (e) {
				var a = $(this);
				var url = a.attr('href').replace(/#.+$/, '');
				var panelId = a.attr('href').split('#')[1];
				var panel = $('#'+panelId).size() ? $('#'+panelId) : $('<div class="panel" id="'+panelId+'"/>').appendTo(a.parent());
				e.preventDefault();
				if (!panel.hasClass('loaded')) {
					a.addClass('loading');
					$.ajax({
						url: url,
						async: false,
						method: 'get',
						success: function (data) {
							panel.append($(data).find('#'+panelId).children());
							closeLink = panel.find('a.close');
							closeLink.click(function (e) {
								e.preventDefault();
								$('html,body').animate({scrollTop: $(document).height() - panel.outerHeight() - $(window).height() - 50}, 'fast');
								panel.css('opacity', 1).animate({opacity:0}, 'fast', function(){
									panel.slideUp('fast');
								});
							});
							var ratingTool = new NetR.RatingTool(panel.find('fieldset.rating'));
							panel.addClass('loaded').css('opacity', 0).animate({opacity:1}, 'fast', function(){
								panel.slideDown('fast');
							});
							a.removeClass('loading');
							panel.find('form').submit(function() {
								var messagebox = $(this).find('textarea');
								if (messagebox.val() == "") {
									alert("Du måste skriva något i meddelanderutan också");
									messagebox.focus();
									return false;
								}
							});
						}
					});
				} else {
					panel.css('opacity', 0).animate({opacity:1}, 'fast', function(){
						panel.slideDown('fast');
					});
				}
			});
		});
		return this;
	};
})(jQuery);

// Init on document ready
$(document).ready(function() {
	NetR.InputPopulate.init();
/* START Remove before launch */
	// NetR.linkInfo.init();
	// NetR.moduleSearchNavigate.init();
/* END Remove before launch */

	NetR.addARIA.init();
	NetR.JSTarget.init({
		val: 'new-window',
		warning: 'Nytt fönster'
	});
	NetR.activateEmailLinks.init();
	NetR.multiTeaser.init();
	NetR.radioHelp.init();

	$("body:not(.layout-1, .layout-4) #content-primary").initArticleTools();
});
