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

/**
 * 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
 */
var NetRInputPopulate = function() {
	var sInputClass = 'populate'; // Class name for input elements to autopopulate
	var sHiddenClass = 'structural'; // Class name that gets assigned to hidden label elements
	var 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 + ' ' + sHiddenClass;
			}
		}
	}
	// Main function
	return {
		init:function() {
			// Find all input elements with the given className
			var arrInputs = jQuery('input.' + 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 (jQuery(oInput).hasClass(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
				jQuery(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
					}
				});
				jQuery(oInput).bind('blur', function() {
					// If the field is empty on blur, assign title to value
					if (!this.value.length) { this.value = this.title; }
				});
			}
		}
	};
}();

/**
 * 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: '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
	};
}();

/**
 * 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
	};
}();

$.fn.fadeToggle = function(speed, easing, callback) { 
    return this.animate({opacity: 'toggle'}, speed, easing, callback); 
};

// Init on document ready
$(document).ready(function() {
	NetR.addARIA.init();
	NetR.JSTarget.init({
		val: 'new-window'
	});
	NetRInputPopulate.init(); // Populate input fields
	NetR.linkInfo.init(); // Remove this (and correlating function) after deploying
	// Start page mega navigation/splash
	$("#nav-start > ul > li").bind("mouseover",function(){
		var self = $(this);
		var splash = $("#splash");
		self.siblings().removeClass("sel");
		self.addClass("sel");
		splash.attr("class",self.attr("class"));
	});
	// Hide buttons and activate shortcuts-dropdowns
	$("#shortcuts form").each(function(){
		var self = $(this);
		self.find(".submit-area").hide();
		self.find("select").change(function() {
			if($(this).val() != '#')
				$(this.form).submit();
		});
	});
	$('<li id="translate-me"><a href="#">Translate</a></li>').find("a").click(function(){
		var offset = $(this).offset();
		$(".gadget:last").css("top",offset.top - 10).css("left",offset.left - 50).fadeIn(500, function(){
			setTimeout('$(".gadget:last").fadeOut()', 8000);
		});
		return false;
	}).end().appendTo('#nav-supp ul');
	$(".layout-1 #search").prepend('<div id="translate-me"><a href="#">Translate</a></div>').find("a").click(function(){
		var offset = $(this).offset();
		$(".gadget:last").css("top",offset.top - 10).css("left",offset.left - 50).fadeIn(500, function(){
			setTimeout('$(".gadget:last").fadeOut()', 8000);
		});
		return false;
	});
	$(".newsletter form").submit(function(){
		if (this.pf_Email.value.length > 255) {
			alert("Ange som mest 255 tecken i fältet \"E-postadress\".");
			this.pf_Email.focus();
			return false;
		}
		if (this.pf_Email.value == "") {
			alert("Ange en e-postadress i fältet \"E-postadress\".");
			this.pf_Email.focus();
			return false;
		}
		if (this.pf_Email.value.length < 7) {
			alert("Ange minst 7 tecken i fältet \"E-postadress\".");
			this.pf_Email.focus();
			return false;
		}
		pf_Email = this.pf_Email.value;
		at = pf_Email.indexOf("@");
		lastat = pf_Email.lastIndexOf("@");
		dot = pf_Email.lastIndexOf(".");
		if(at < 1 || at != lastat || dot < at) {
			alert("Din e-postadress är inte rätt skriven. Försök igen.");
			return false;
		}
	});
	// NetR.addPrintLink.init({
	// 	linkText: 'Skriv ut sidan'
	// });
});
/* Init on window ready (when images are loaded too) */
$(window).load(function() {
	$('a.lightbox').lightBox(); // Initialize lightbox
});
