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

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

/**
 * 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
	};
	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 + ' ' + options.sHiddenClass;
			}
		}
	};
	/**
	* 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
		var arrInputs = $('input.' + options.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 ($(oInput).hasClass(options.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
			$(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
				}
			});
			$(oInput).bind('blur', function() {
				// If the field is empty on blur, assign title to value
				if (!this.value.length) { this.value = this.title; }
			});
		}
	}
	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).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).addClass("active");
	}
	/**
	 * Creates the neccessary markup for all tabs
	 * @private
	 */
	function createTabs(that){
		active_tab_suffix = $("<span></span>").attr("class", "structural").text(options.active_tab_suffix || " (visas nu)");
		tabs_ul = $("<ul class=\"m-tabs cf\"></ul>").insertAfter($(".m-h", that));
		if (options.wrap_tabs) {
			$(tabs_ul).wrap("<div class=\"m-tabs-wrap\"></div>");
		}
		if (options.before_tabs) {
			$("<p></p>").text(options.before_tabs).attr("class", "structural").insertBefore(tabs_ul);
		}
		$(that).children(".m-c").each(function(){
			var tab     = {};
			tab.content = this;
			tab.label   = $(".tab-label", this).text();
			tab.link    = $("<a href=\"#" + $(tab.content).attr("id") + "\"><em>" + tab.label +"</em></a>").addClass("tab-" + $(tab.content).attr("id"));
			tab.link.appendTo(tabs_ul).wrap("<li></li>");
			if($(tab.content).hasClass(".active")){ tab.link.parent().addClass("sel"); }
			$.each(['click'], function(i,e){
				tab.link[e](function(e){
					e.preventDefault();
					activateTab(tab);
				});
			});
			if ((document.location.hash == "#" + $(tab.content).attr("id"))) {
				activateTab(tab);
			}
			tabs.push(tab);
		});
	}
	this.addClass("tabbed-module");
	createTabs(this);
};

jQuery(document).ready(function () {
	NetR.JSTarget.init({
		val: 'new-window',
		warning: ''
	});
	NetR.InputPopulate.init();
	/**
	 * Init drop-down-menus in main navigation
	 */
	if(typeof $.fn.hoverIntent == 'function') {
		$('#nav-main .has-sub').parent().hoverIntent($.extend({
			sensitivity: 2,
			interval: 50,
			timeout: 200
		}, {}, {
			over: function() {
				var position = $(this).position();
				var top = position.top + $(this).height();
				$(this).find('ul').css('top',top+'px').css('z-index','999').slideDown(200); 
			},
			out: function() { $(this).find('ul').slideUp(200); }
		}));
	} else {
		$('#nav-main .has-sub').parent().hover(function() {
			var position = $(this).position();
			var top = position.top + $(this).height();
			$(this).find('ul').css('top',top+'px').css('z-index','999').slideDown(200); 
		}, function() {
			$(this).find('ul').slideUp(200);
		});
	}
	// Makes tabbed module out of search results
	if (typeof $.fn.makeTabbedModule !== "undefined") {
		$('#m-search').each(function() {
			if($(this).children('.m-c').length > 1) {
				$(this).children('.m-c:first').addClass("active");
				$(this).makeTabbedModule({
					wrap_tabs: false
				});
			}
		});
	}
	/**
	 * Hide comments and add toggle link for showing/hiding comments in blog
	 */
	$('#comments').each(function() {
		if(!window.location.href.match('#comment')) { //Do not hide if linked directly to comments
			$(this).find('h2,ol').hide();
			if($(this).find('ol').is(':hidden')) {
				var linkText = $(this).find('h2:first').html();
				var showText = 'Visa '+linkText.toLowerCase();
				var hideText = 'Dölj '+linkText.toLowerCase();
				var toggleLink = $('<a />').attr('href','#').addClass('comments').html(showText).toggle(
					function() {
						$('#comments h2,#comments ol').show();
						$(this).html(hideText);
						return false;
					},
					function() {
						$('#comments h2,#comments ol').hide();
						$(this).html(showText);
						return false;
					}
				);
				$(this).prev().append(toggleLink);			
			}
		}
	});
    /**
     * Show link to map on store pages
     */
    var storeContainer = $('.store-info:first');
    if ($(storeContainer).length) {
        var storeID = storeContainer.attr("id").split('-')[1];
        if (storeID != undefined) {
            $('.store-info #address').append('<p class="map-link"><a href="/hitta-hos-oss/index.html?storeid=' + storeID + '">Se på en karta</a> var i Kungsmässan vi finns.</p>');
            $('.map-link a:first').click(function () {
                var sOptions = 'menubar=no,toolbar=no,location=no,resizable=yes,scrollbars=yes,status=yes,width=830,height=800';
				window.open(this.href, '_blank', sOptions);
				return false;
            });
        }
    }
    /**
     * Show link to map on lunch pages
     */
    $('.restaurant').each(function () {
        var storeID = $(this).attr("id").split('-')[1];
        if (storeID != undefined) {
            $(this).find('.action:first').append('<li class="map-link"><a href="/hitta-hos-oss/index.html?storeid=' + storeID + '">Se på en karta</a> var i Kungsmässan vi finns.</li>');
            $(this).find('.map-link a:first').click(function () {
                var sOptions = 'menubar=no,toolbar=no,location=no,resizable=yes,scrollbars=yes,status=yes,width=830,height=800';
				window.open(this.href, '_blank', sOptions);
				return false;
            });
        }
    });
});