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

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

NetR.switch_campaign = function (e) {
	$('#campaign-nav li a').removeClass('active');
	e.addClass('active');
	var nav_item = e.attr('id').match('[0-9].*');
	var bgPos = 75 + (nav_item - 1) * 175;
	if(!$('#campaign-image-' + nav_item).is('.active')) {
		
		$('#campaign-nav').css('background-position', bgPos + 'px' + ' 0');
		$('.campaign-image').stop(false,true).fadeOut(300, function(){
			$('.campaign-image').removeClass('active');
		});
		$('#campaign-image-' + nav_item).stop(false,true).fadeIn(300, function(){
			$('#campaign-image-'+nav_item).addClass('active');
		});
	}
};
$(function () {
	if ($('#campaign-image').length) {
		// Add ARIA attributes
		$('#campaign-image').attr('aria-live', 'assertive'); // Make the image container a live region
		$('#campaign-nav li a').attr('aria-controls','campaign-image'); // Make the nav update the live region
		//Switch campaign on hover
		$('#campaign-nav li a').hover(function(){
			NetR.switch_campaign($(this));
		});

		//Switch campaign on focus
		$('#campaign-nav li a').bind('focus',function(){
			NetR.switch_campaign($(this));
		});

		$('.campaign-image:not(.active)').css('z-index', 0);
		$('.campaign-image.active').css('z-index', 10);

		var nav_item = $('.campaign-image.active').attr('id').match('[0-9].*');
		var bgPos = 75 + (nav_item - 1) * 175;
		$('#campaign-nav').css('background-position', bgPos + 'px' + ' 0');
	}
});

/**
 * @fileoverview Global functions
 */

/* 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
 */
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 and iterate through them
		$('input.' + options.sInputClass).each(function () {
			var input = $(this);
			// Make sure it's a text input
			if (input.attr('type') === 'text') {
				// Hide the input's label
				if (input.hasClass(options.sHideLabelClass)) { 
					$('label[for=' + input.attr('id') + ']').addClass(options.sHiddenClass);
				}
				// Get the text to populate the input field with
				input._placeholderText = input.attr('title') || $('label[for=' + input.attr('id') + ']').text();
				// If value is empty and the placeholder text is not, assign the placeholder text to value
				if (input.val() == '') {
					input.val(input._placeholderText);
				}
				// Add event handlers for focus and blur
				input.focus(function() {
					// If value and title are equal on focus, clear value
					if (input.val() == input._placeholderText) {
						input.val('');
						input.select(); // Make input caret visible in IE
					}
				});
				input.blur(function() {
					// If the field is empty on blur, assign placeholder text to value
					if (input.val() === '') { input.val(input._placeholderText); }
				});
				//Clear any populated values before submitting the form
				$(input.get(0).form).submit(function() {
					if (input.val() === input._placeholderText) {
						input.val('');
					}
				});
			}
		});
	}
	return {
		init: init
	};
}();

// Init on document ready
$(document).ready(function() {
	$('body').addClass('js');
	if (jQuery().supersleight) {
		$('#logo, #campaign .bg').supersleight();
	}
	NetR.InputPopulate.init();
	NetR.linkInfo.init();
	NetR.addARIA.init();
	// NetR.addPrintLink.init({
	//	linkText: 'Skriv ut sidan'
	// });
	$('#featured').tabs();
	// Add a class name to every second row of destination tables
	$('table.destinations tbody tr:even').addClass('odd');
	// Initialise image gallery
	if (jQuery().ariaLightbox) {
		var lightbox = $("#image-gallery").ariaLightbox({
			imageArray: "a.gallery-1",
			altText: function() {
				return $(this).find("img").attr("alt");
			},
			descText: function() {
				return $(this).find("img").attr("title");
			},
			prevText: "Föregående bild",
			nextText: "Nästa bild",
			pictureText: "Bild",
			ofText: "av",
			closeText: "Stäng (Esc)",
			useDimmer: true,
			pos: "auto",
			animationSpeed: "fast",
			titleText: $("#content-primary h1:first").text(),
			makeHover: false,
			em: false
		});
	}
	$('body[class!="layout-1 js"] #content-primary').prepend('<div id="page-tools" class="addthis_toolbox addthis_default_style"><a class="addthis_button_print"></a><a class="addthis_button_email"></a><a class="addthis_button_twitter"></a><a class="addthis_button_facebook"></a><a class="addthis_button_facebook_like"></a></div>').find('h1:first').addClass('no-margin');
	// Initialise datepickers
	if (jQuery().datepicker) {
		$('.datepicker input').datepicker({
			inline: true,
			onClose: function(dateText, inst) {
				// Sync date values on close
				if (dateText != '') {
					if (inst.id == 'startdate') {
						var endDate = $('.cup-search #enddate');
						if ((endDate.val() != '') && (dateText > endDate.val())) {
							endDate.val(dateText);
						}
					}
					if (inst.id == 'enddate') {
						var startDate = $('.cup-search #startdate');
						if ((startDate.val() != '') && (dateText < startDate.val())) {
							startDate.val(dateText);
						}
					}
				}
			}
		});
	}
	// // Sync start and end dates in cup search
	// $('.cup-search #startdate').blur(function () {
	// 	console.log($(this).attr('value'));
	// 	if ($(this).val() > $('.cup-search #startdate').val()) {
	// 		$('.cup-search #startdate').val($(this).val());
	// 	}
	// });
});
