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

/**
 * Truncates text by word.
 */
TruncateMe = function(el) {
	var chars = 75;
	if (el) {
		el.each(function(){
			/* Find paragraphs in element */
			var p = $(this).find("p");
			var oldtext = p.text();
			if (oldtext.length > chars) {
				var trunc;
				/* Truncate the text and make sure we don't truncate in the middle of a word */
				trunc = oldtext.substring(0, chars);
				trunc = trunc.replace(/\w+$/, '');
				trunc += '…';
//				trunc += '<a href="#">…<\/a>';
				p.html(trunc);
//			    p.html(trunc).find("a").css("display","inline").click(function(){
//					$(this).parent().text(oldtext);
//					return false;
//				});
			}
		});
	}
};

/**
 * Insert navigation buttons for the jCarousel Lite when there are more than a certain number of products.
 */
function addCarousel(max, next, prev) {
	var sMaxProducts = max ? max : 6;
	var oProductList = $(".jcarousel");
	oProductList.find("li:first").addClass("sel");
	var sNoOfProducts = $("ul", oProductList).children().length; /* number of products in list */
	var sSelProductId = $("li.sel", oProductList) ? $("li.sel", oProductList).attr("id") : null; /* id of selected product */
	var sSelProduct = sSelProductId ? $("li", oProductList).index( $("#"+sSelProductId) ) : null; /* number in list of selected product */
	var sNext = next ? next : "Next";
	var sPrev = prev ? prev : "Previous";
	if(sNoOfProducts > sMaxProducts) {
		if(sSelProduct > (sMaxProducts - 1)) {
			var sOverflow = sNoOfProducts - sMaxProducts; /* number of product off-list */
			sSelProduct -= sOverflow;
		}
		$(".jcarousel").before('<button class="jcarousel-prev" title="'+sPrev+'">'+sPrev+'</button>');
		$(".jcarousel").after('<button class="jcarousel-next" title="'+sNext+'">'+sNext+'</button>');
		if(sSelProduct <= 0) {
			$(".jcarousel-prev").addClass("disabled");
		}
	}
	$(".jcarousel").jCarouselLite({
		start: sSelProduct,
		visible: sMaxProducts,
		scroll: 1,
		animation: "fast",
		speed: 200,
		circular: false,
		btnNext: ".jcarousel-next",
		btnPrev: ".jcarousel-prev"
    });
}

// Init on document ready
$(document).ready(function() {
	NetR.linkInfo.init();
	NetR.addARIA.init();
	NetR.JSTarget.init({
		val: 'new-window'
	});
	NetRInputPopulate.init(); // Populate input fields
	// NetR.addPrintLink.init({
	// 	linkText: 'Skriv ut sidan'
	// });
	/* Truncate long info */
	TruncateMe($(".product"));
	$(".article-list > li:nth-child(odd)").addClass("even");
	$("legend").each(function(){
		var legend = $(this);
		legend.html("<span>"+legend.text()+"</span>");
	});
});
