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

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

// Init on document ready
$(document).ready(function() {
	NetR.InputPopulate.init();
	NetR.linkInfo.init();
	NetR.addARIA.init();
	NetR.JSTarget.init({
		val: 'new-window',
		warning: 'nytt fönster'
	});
	$('body').addClass('js'); // Add class to enable JS-specific styling
	$('#m-subscribe .hide').hide();
	$('#m-subscribe .toggle input').focus(function() {
		$('#m-subscribe .hide').slideDown(150);
	});

	$('.m-flow:first').prepend($('<div />').attr('id','movies').append($('<div />').addClass('movie-btns')));
	/* Initiate movies in flows */
	$('.m-flow .movie').each(function(i) {
		var self = $(this);
		self.hide().attr('id','movie-'+i);
		$('#movies').append(self);
		var closeLink = $('<a />').addClass('close').attr('href','#').html('St&auml;ng').click(function() {
			$(this).parent().hide(150);
			return false;
		});
		self.prepend(closeLink);
		var btnWrap = $('<div />').addClass('btn btn-2 btn-play');
		$('#movies .movie-btns').append(btnWrap);
		var movieImg = self.find('.movie-img');
		if(self.find('.old-movie').is('a')) {
			var openLink = $('<a />').attr('href',self.find('.old-movie').attr('href')).html('<span>'+self.find('h3').html()+'</span>').attr('target','_blank');
			var imgLink = $('<a />').attr('href',self.find('.old-movie').attr('href')).append(movieImg).attr('target','_blank');
		} else {
			var openLink = $('<a />').addClass('movie-open').attr('href','#movie-'+i).html('<span>'+self.find('h3').html()+'</span>');
			var imgLink = $('<a />').addClass('movie-open').attr('href','#movie-'+i).append(movieImg);
		}
		btnWrap.append(openLink);
		$('.m-flow .step:first .step-image').append(imgLink);
	});
	/* Initiate flows */
	$('.m-flow .m-c').each(function() {
		$('#content-primary .m-flow').prepend('<div class="m-h"><ul class="cf"><li class="prev"><a href="#">Föregående</a></li><li class="next"><a href="#">Nästa</a></li></ul></div>');
		$('#content-primary .m-flow .prev a').click(function() {
			var curStep = $(this).closest('.m-h').next().next().find('.step:visible');
			if(!$(curStep).is(':first-child')) {
				curStep.hide(300).prev().show(300);
				var selStep = $(this).closest('.m-h').find('.sel')[0];
				if(selStep) {
				    var selStepContent = $(selStep).find('strong').html();
				    $(selStep).removeClass('sel');
				    $(selStep).html(selStepContent);
				    $(selStep).prev().addClass('sel').wrapInner('<strong>');
				}
			}
			return false;
		});
		$('#content-primary .m-flow .next a').click(function() {
			var curStep = $(this).closest('.m-h').next().next().find('.step:visible');
			if(!$(curStep).is(':last-child')) {
				curStep.hide(300).next().show(300);
				var selStep = $(this).closest('.m-h').find('.sel')[0];
				if(selStep) {
				    var selStepContent = $(selStep).find('strong').html();
				    $(selStep).removeClass('sel');
				    $(selStep).html(selStepContent);
				    $(selStep).next().addClass('sel').wrapInner('<strong>');
				}
			}
			return false;
		});
		var self = $(this);
		self.find('.step').each(function(i) {
			// Generate buttons
			var stepNum = $('.step').length - 1; // Start page of flow is not counted
			var stepPage = $('<span />').addClass('step-page').html(i+' av '+stepNum);
			var btnNext = $('<div />').addClass('btn btn-2 last').html('<a href="#'+$(this).next('.step').attr('id')+'"><span>Nästa</span></a>');
			var btnPrev = $('<div />').addClass('btn btn-back last').html('<a href="#'+$(this).prev('.step').attr('id')+'" title="Tillbaka"><span><img src="/i/btn-back-arrows.png" alt="Tillbaka" /></span></a>');
			var btnClick = function() {
				var stepId = '#' + $(this).attr('href').split('#')[1];
				$(this).closest('.m-c').find('.step:visible').hide(300);
				$(stepId).show(300);
				var selStep = $(stepId).parent().prev().prev().find('.sel')[0];
				if(selStep) {
					var selStepContent = $(selStep).find('strong').html();
					$(selStep).removeClass('sel');
					$(selStep).html(selStepContent);
					$('#ind-'+stepId.split('#')[1]).addClass('sel').wrapInner('<strong>');
				}
				return false;
			};
			$(btnNext).find('a').click(btnClick);
			$(btnPrev).find('a').click(btnClick);
			if(i < $(this).siblings().length) $(this).find('.btn-area').append(btnNext);
			if(i > 0) {
				$(this).find('.btn-area').append(stepPage);
				$(this).find('.btn-area').append(btnPrev);
				
				var movieBtns = $('#movies .movie-btns').clone();
				$(this).find('.step-image').prepend(movieBtns);
			}
			// Generate steps in step indicator
			var stepInd = $('<li />').html('<span>'+(i+1)+'</span> '+$(this).find('h2:first').html()).attr('id','ind-'+$(this).attr('id'));
			if (i == 0) {
			    $(stepInd).addClass('sel');
			    $(stepInd).wrapInner('<strong>');
			}
			$(this).parent().parent().find('.m-h .next').before(stepInd);
		});
	});
	$('#movies .movie-btns').remove();
	$('.movie-open').click(function() {
		var id = '#' + $(this).attr('href').split('#')[1];
		//var player = document.getElementById('playerContainer-' + id.split('-')[1]);
		$(id).show(150);
		
		return false;
	});
	$('#splash .m-flow .btn-area:first .last span').html('Så här funkar det');
	
	/*
	The new splash screen
	*/
	$('#splash2 .movie-teaser .movie-content').each(function() {
		$(this).addClass('movie');
		var closeLink = $('<a />').addClass('close').attr('href','#').html('St&auml;ng').click(function() {
			$(this).parent().hide(150);
			return false;
		});
		$(this).prepend(closeLink).parent().find('.action-play').click(function() {
			$(this).parent().find('.movie-content').show(150);
			return false;
		});
	});
	if($('#splash2 .intro-movie-content').size()) {
		$('#splash2 .intro-movie-content').addClass('movie');
		var closeLink = $('<a />').addClass('close').attr('href','#').html('St&auml;ng').click(function() {
			$(this).parent().hide(150);
			return false;
		});
		$('#splash2 .intro-movie-content').prepend(closeLink);
		$('#splash2 .intro-movie-content').prev().find('a').click(function() {
			$('.intro-movie-content').show(150);
			pageTracker._trackEvent('filmer', 'introfilm');
			return false;
		});
	}
	$('#splash2 .feat-contents').addClass('js');
	$('#splash2 .feat-content').mouseenter(function() {
		$(this).addClass('active');
	}).mouseleave(function() {
		$(this).removeClass('active');
		splashtimer = setTimeout(function() {
			if(!$('#splash2 .feat-contents .active:visible').size()) {
				$('#splash2 .feat-content:visible').fadeOut(200);
			}
			clearTimeout(splashtimer);
		},200)
	});
	var splashtimer = 0;
	$('#splash2 .splash-feats a').mouseenter(function() {
		var id = $(this).attr('href').split('#')[1];
		$('#splash2 .feat-content').hide();
		$('#'+id).fadeIn(200).addClass('active');
	}).mouseleave(function() {
		var id = $(this).attr('href').split('#')[1];
		$('#'+id).removeClass('active')
		splashtimer = setTimeout(function() {
			if(!$('#splash2 .feat-contents .active').size()) {
				$('#splash2 .feat-content:visible').fadeOut(200);
			}
			clearTimeout(splashtimer);
		},200)
	}).click(function() { return false; });
	
	/*
	Pricing
	*/
	$('.price-add').each(function() {
		$(this).find('ul').hide();
		var heading = $(this).find('h3:first');
		var link = $('<a />').attr('href','#').html(heading.text()).click(function() {
			$(this).parent().next().slideToggle(100);
			return false;
		});
		heading.html(link);
	});
	
	// Trigger submit automatically when select new value in tour calendar
	$('#city-sel').change(function() {
		$(this).closest('form').submit();
	});
	$('.m-tourcal input:submit').hide();
});

// Init on window load
$(window).load(function() {
	/* Set consistent height on flow containers and hide them */
	$('.m-flow .m-c').each(function() {
		var steps = $(this).find('.step-wrap');
		var maxHeight = 0;
		for(i=0;i<steps.length;i++) {
			if($(steps[i]).height() > maxHeight)
				maxHeight = $(steps[i]).height();
		}
		$(steps).height(maxHeight);
		$(this).height($(this).find('.step').outerHeight());
		$(this).find('.step').each(function(i) {
			if(i > 0) $(this).hide();
		});
	});
	
	var teasercols = $('#splash2 .tc');
	if(teasercols.size()) {
		var tcheight = 0;
		for(var m=0;m<teasercols.length;m++) {
			if($(teasercols[m]).innerHeight() > tcheight) tcheight = $(teasercols[m]).innerHeight();
		}
		$('#splash2 .tc > div').css('min-height',(tcheight-14)+'px');
	}
});
