/*
	
	Mt. Hood Meadows Global Javascript Functions
	Paul Farning - ISITE Design

*/

// jquery no conflict. use $j or jQuery outside of ready function,
// HOOD global
var $j = jQuery.noConflict(),
	HOOD = {};

// sIFR 3
// activated with jQuery plugin to transform to uppercase characters
HOOD.linux = navigator.platform.indexOf("Linux") == -1;
if(typeof sIFR != "undefined" && HOOD.linux) {
	var geometric = { src: '/Layouts/Skihood/Resources/flash/Geometric231BT.swf' };
	sIFR.activate(geometric);
}

// jQuery document ready
jQuery(function($) {

	// make sure .net's Sys object is available before trying to use it
	HOOD.sys = typeof Sys == "undefined" ? false : true;

	// activate sifr
	$("#lead h1").activateSIFR();

	// JS enabled
	$('html').addClass('js');

	// For Safari (#primary button's)
	if ($.browser.safari) { $('html').addClass('sf'); }

	// For IE
	if ($.browser.msie) {

		// make rounded corners
		roundIE();

		// ie7 and below
		if (parseInt($.browser.version) <= 7) {
			// prevent z-index collision of season pass nav item and events dropdown
			$('#nav li#nav-eventsteams').bind('mouseenter mouseleave', function(e) {
				var selector = $('#nav-seasonpassesstore a.current').length ? '#nav-seasonpassesstore,#nav' : '#nav-seasonpassesstore';
				$(selector)[((e.type == 'mouseenter') ? 'add' : 'remove') + 'Class']('trimheight');
			});

			// dropdowns -- js to help ie7 as well with dropdown on focused item
			$('#nav>li').bind('mouseenter mouseleave', function(e) { $(this)[((e.type == 'mouseenter') ? 'add' : 'remove') + 'Class']('drop'); });
		} // if <= ie7

		// additional IE6 fixes in initIE6() triggered via conditional comments in html

	} // if ie

	// label to default, lowercase -- form removed
	// $('#footer .signup input.text').inputSetter(1);

	// keyboard access to dropdowns
	$('#nav a').bind('focus blur', function(e) { $(this).parents("li")[((e.type == 'focus') ? 'add' : 'remove') + 'Class']('drop'); });

	// simple tabs
	$('.tabs').IX_Tabs();

	// set up homepage rotator
	if ($('body.page-home').length) { $('.page-home #lead').rotate(); }

	// stripe tables	
	$('div#primary div.rte tbody').each(function() {
		$('tr:odd', this).addClass("alt");
		if ($('tr', this).length == 1) { $('tr', this).addClass("alt") }
	});

	// tooltips
	$('.help').tooltip();

	// align buttons
	singleAlign();

	// this event handler is run when ASP.NET AJAX completes an AJAX request.
	if (HOOD.sys) {
		Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(function(sender, args) {
			var postbackSourceID = args.get_postBackElement().id
			
			// handle scrolls to #content on ajax postbacks. .noscroll on the postback element will disable this.
			HOOD.dontScrollPostback = $(".noscroll #" + postbackSourceID + ", #" + postbackSourceID + ".noscroll").length > 0;
			
			HOOD.explicitScrollTargetID = $(".scrollto #" + postbackSourceID + ", #" + postbackSourceID + ".scrollto").closest(".scrollto").attr("rel");	
		});

		Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(s, args) {

			// keep the width of the top headline bar correct during async cart operations
			if ($(".nav .cart ol li").length > 0)
				$("body").removeClass("no-secondary-nav");
			else $("body").addClass("no-secondary-nav");

			// jump back to content after ajax request in cart
			if ($('.page-cart').length && !HOOD.dontScrollPostback) { $.scrollTo($('#content'), 800); }
			
			if (HOOD.explicitScrollTargetID) {
				var element = $("#" + HOOD.explicitScrollTargetID); // make sure the scroll target exists after the postback completes
				if (element.length > 0)
					$.scrollTo(element, 800);
			}

			// re-tooltip
			$('.help').tooltip();

			// re-align wizard go back and next buttons
			singleAlign();
			
			// re-external
			$('a[href^=http://]').not('a.thickbox').not('[href*=' + window.location.host + ']').bind('click', openExternal);

			if (args.get_error() != undefined) {
				alert("We're sorry, there was a problem with the page you requested.\n\nWe've sent an email to the site administrators with some information about what happened. Please try again later - we'll be working on fixing it right away!");
			}

		});
	}

	// jump to validation errors
	$('div#primary .btn-validate').live('click', function() {
		if (typeof Page_IsValid != 'undefined') {
			setTimeout(function() {
				if (!Page_IsValid) {
					$.scrollTo($('fieldset li span.error:visible:first').parents('li'), 0);
				}
			}, 40);
		}
	});

	// thickbox confirm dialogs	
	if (!($.browser.msie && parseInt($.browser.version) < 7)) {
		$('button.tb-confirm').live('click', tbConfirm);
		$('a.tb-canceler').click(function() {
			tb_remove();
			return false;
		});
		$('a.tb-confirmer').click(function() {
			HOOD.$confirmtarget.data("confirmed", true);
			HOOD.$confirmtarget.trigger("click");
			return false;
		});
	}

	// external windows
	$('a[href^=http://]').not('a.thickbox').not('[href*=' + window.location.host + ']').bind('click', openExternal);

	// photo video terms
	$('.upload-photo .checkradio a.terms').live('click', function() { $(this).parents('li').find('.view-scroll').toggle(); return false; });

});                       // document ready


// application logic

// rounded corners for IE
var roundIE = function(){
	$j('button,a.btn').not(".rounded").wrapInner('<span class="l"></span>').append('<span class="r"></span>').addClass("rounded");
	// and after .net ajax requests
	if(HOOD.sys) { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(roundIE); }
};

// ie6 specifics trigger from conditional comment
var initIE6 = function() {

	//add class to buttons 
	$j('button').hover(
		function() { $j(this).addClass('over'); },
		function() { $j(this).removeClass('over'); }
	);

	// old browser
	$j('body').prepend('<div class="browser-notice"><p>Hi! Looks like you are using an old browser. Things may look a little off around here. For a better internet experience, consider <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx">upgrading your browser</a> or <a href="http://www.alternativebrowseralliance.com/browsers.html">trying a new one</a>.</p></div>');
	$j('html').addClass('ie6');	
	
}

var singleAlign = function(){
	if($j('.wizard-nav').length && $j('.wizard-nav table td').length == 1) {
		$j('.wizard-nav table td').css("text-align","right");
	}	
};

// thickbox style confirm dialog
var tbConfirm = function() {	
	HOOD.$confirmtarget = jQuery(this);
	if(HOOD.$confirmtarget.data("confirmed")) {
		tb_remove();
		//eval(HOOD.$confirmtarget.attr("href"));
		return true;
	} else {
		var block = HOOD.$confirmtarget.attr("rel");		
		tb_show("a",'TB_inline?height=200&amp;width=450&amp;inlineId='+block+'&modal=true');
		return false;
	}
};

// external windows
var openExternal = function(){
	var extwin = window.open($j(this).attr("href"), "_blank");
	if (extwin) {
		if (extwin.focus) extwin.focus();
		return false;
	}
	extwin = null;
	return false;
};

(function($) {

	// activate sifr
	$.fn.activateSIFR = function(selector)	 {
		return this.each(function(){								  
			var tmp = $(this).html().toUpperCase();
			$(this).html(tmp);
			if(HOOD.linux) {
				sIFR.replace(geometric, {
					selector: selector || '#lead h1',
					css: '.sIFR-root { background-color: transparent; color: #000000; }',
					wmode: 'transparent',
					repaintOnResize: true
				});
			}
		});	
	}; // sifr

	// rotate
	$.fn.rotate = function(options) {

		if(!HOOD.features && typeof HOOD.features !== "object") {		
			$('.nav-rotate').remove();
			return this;		
		}
		var opts = $.extend({}, $.fn.rotate.defaults, options),
			current = 0,
			total = HOOD.features.length,
			tmpl = '<div class="lead-item setup" style="background-image:url(<%=image%>);"><div class="wrapper"><h1><%=title%></h1><div class="content"><p><%=content%></p></div><div class="nav-lead"></div></div></div>',
			btn = '<a class="btn" href="<%=url%>"><span class="l"><%=text%></span><span class="r"></span></a>',
			nav = '<div class="nav-rotate"><ul><li class="arrow-previous"><a class="btn-arrow ir" href="#">Previous</a></li><li class="arrow-next"><a class="btn-arrow ir" href="#">Next</a></li></ul><span class="pages"><%=current%> of '+total+'</span></div>';

		for(j=1;j<total;j++) {		
			var built = tmpl.replace(/<%=image%>/g,HOOD.features[j].image.replace(/\s/g,"%20")).replace(/<%=title%>/g,HOOD.features[j].title).replace(/<%=content%>/g,HOOD.features[j].content),
				links = "",
				arrows = nav.replace(/<%=current%>/g,j+1);			
				
			$.each(HOOD.features[j].links,function(i){
				if(HOOD.features[j].links[i].url!=null) {
					links += btn.replace(/<%=url%>/g,HOOD.features[j].links[i].url).replace(/<%=text%>/g,HOOD.features[j].links[i].text);														 
				}
			});				
			$(built).find('.nav-lead').append(links).append(arrows).end().appendTo('#lead');		
		}
		
		$("#lead h1").activateSIFR();	
		// poll to check all h1's are replaced, then do hide and final setup
		// needs to wait on sifr to be sure it is successfull
		var hidepoll = setInterval(function() {
			if($("#lead h1").not(".sIFR-replaced").length == 0 || sIFR.ua.flash == false || sIFR.ua.linux) {
				clearInterval(hidepoll);
				$("#lead .lead-item").not(":first").hide().removeClass("setup");
			}
		}, 100);
		
		var cycle = function(e) {			
			current = $(e.target).parents('.arrow-previous').length ? current += -1 : current += 1;
			current = current < 0 ? total-1 : current == total ? 0 : current;			
			var $hide = $("#lead .lead-item:visible");			
			$("#lead .lead-item:visible").fadeOut("slow")
			$("#lead .lead-item").eq(current).fadeIn("slow");			
		};
			
		HOOD.rotate = setInterval(function(){ $('#lead').trigger('rotate'); },7000);

		for(var i=0,length = HOOD.features.length; i<length; i++) {
			$("<img>").attr("src", HOOD.features[i].image.replace(/\s/g,"%20"));
		}
		
		return this.each(function(){
			$('a.btn-arrow',$(this)).live('click',function(e) { clearInterval(HOOD.rotate); cycle(e); return false; });
			$('#lead').bind('rotate',function(e) { cycle(e); return false; });
		});
		
	}; // rotate
	
})(jQuery);

// jQuery plugins
// inputSetter
jQuery.fn.inputSetter = function(lower) {	
	return this.each(function() {
		var $input = jQuery(this),
			$label = jQuery("label[for='"+$input.attr("id")+"']"),
			labeltext = lower && lower==1 ? $label.text().toLowerCase() : $label.text();
		$label.hide();	
		$input.val(labeltext);		
		$input.focus(function() { if (this.value == labeltext) { this.value = ""; }	})
			  .blur(function() { if (!this.value.length) { this.value = labeltext; } });		
	});
};
// simple tabs
jQuery.fn.IX_Tabs = function() {	
	return this.each(function() {
		var $container = jQuery(this), 
			$tabs = jQuery('a', this),
	 		panes = new Array();
		$tabs.each(function () {
			var $this = jQuery(this);		
			var pane = $this.attr('href');
		 	panes.push(pane);
			$this.bind('click', function(){
				jQuery(panes.join(",")).hide();
				$container.find('.active').removeClass('active');
				$this.parent('li').addClass('active');
				jQuery(pane).show();
				return false;
			});
		});
		var $default = jQuery('a.default',$container).length ? jQuery('a.default',$container) : jQuery('a:first',$container);
		$default.click();
	});
};

// IE6 fixes
// make sure IE has the abbr and acronym tag
if(document.all){
	document.createElement("abbr");
	document.createElement("acronym");
}
// prevent IE6 flicker
try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}