
//component isolation
(function($) {
	function BookingWidget() {
		this.rangeOpen = true;
		this.arrDate = new Date();
		this.arrDate.setDate(this.arrDate.getDate() + 1);
		this.depDate = new Date();
		this.depDate.setDate(this.arrDate.getDate() + 1);
	};
	BookingWidget.prototype.updateDateFields = function(selectedDate) {
		if (this.rangeOpen) {
			this.arrDate = selectedDate;
			this.depDate = new Date(this.arrDate); //pass by val and set to same day then increment 1 day
			this.depDate.setDate(this.arrDate.getDate() + 1);
			this.rangeOpen = false;
		}
		else {
			if (selectedDate < this.arrDate) {
				this.depDate = this.arrDate;
				this.arrDate = selectedDate;
			}
			else if (selectedDate > this.arrDate) {
				//do nothing if ==
				this.depDate = selectedDate;
			}
			this.rangeOpen = true;
		}
		this.fillDateFields();
	};
	BookingWidget.prototype.fillDateFields = function() {
		$("#arrw").html(this.formatMonth(this.arrDate.getMonth()) + '/' + this.arrDate.getDate() + '/' + this.arrDate.getFullYear());
		$("#depw").html(this.formatMonth(this.depDate.getMonth()) + '/' + this.depDate.getDate() + '/' + this.depDate.getFullYear());
	};
	/*BookingWidget.prototype.fillDateFields = function() {
		$("input#arr").val(this.formatMonth(this.arrDate.getMonth()) + '/' + this.arrDate.getDate() + '/' + this.arrDate.getFullYear());
		$("input#dep").val(this.formatMonth(this.depDate.getMonth()) + '/' + this.depDate.getDate() + '/' + this.depDate.getFullYear());
	};*/
	BookingWidget.prototype.hilightRange = function(date) {
		if ((date >= this.arrDate) && (date <= this.depDate)) {
			return [true, 'ui-datepicker-range'];
		}
		else return [true, ''];
	};
	BookingWidget.prototype.formatMonth = function(mIndex) {
		return mIndex + 1;
	};
	BookingWidget.prototype.getUrl = function(baseUrl) {
		var arrDate = this.arrDate;
		var depDate = this.depDate;
		var ad = $('#ad option:selected').val();
		var ch = $('#ch option:selected').val();

		var y = arrDate.getFullYear();
		var m = this.formatMonth(arrDate.getMonth());
		var d = arrDate.getDate();
		var one_day = 86400000;
		var timeDiff = depDate.getTime() - arrDate.getTime();
		var days = Math.ceil(timeDiff / one_day);

		return baseUrl + '/#/sun-valley-lodge/' + y + "/" + m + "/" + d + "/" + days + "/" + ad + "/" + ch;
	};

	//bind instance to dom
	window.bookingWidget = new BookingWidget();
	return (window.bookingWidget);
})(jQuery);

$(document).ready(function() {
	var tabsFull = $('ul.tabs.fulldoc');
	if (tabsFull.length > 0) {
		$('li a', tabsFull).each(function(i, o) {
			$(o).attr("href", "javascript:void(null)");
		});

		$('li a.tab', tabsFull).click(function() {
			$('#tabs_container .tabs > li.active').removeClass('active');
			$('#tabs_container .tabIsolatedRight.active').removeClass('active');
			$(this).closest('.tabLeft').addClass('active');
			$(this).closest('.tabIsolatedRight').addClass('active');
			$('#tabs_container > .tabbed_content > div.active').removeClass('active');
			$(this.rel).addClass('active');
			//$.address.value(this.rel.substring(1)); //update to do a replace so as not to wipe out parms below l3
			var curTab = getTabUrlFragment($.address.path());
			var curFragment = $.address.value(); //might be something other than a tab
			if ((curFragment.length > 0) && (curTab.length > 0)) {
				$.address.value($.address.value().replace(curTab, this.rel.substring(1)));
			}
			else if (curFragment.length > 0) {
				$.address.value(this.rel.substring(1) + curFragment);
			}
			else {
				$.address.value(this.rel.substring(1));
			}
		});

		$.address.externalChange(function() {
			var _address = $.address.path();
			if (_address != '/') {
				var _rel = '#' + _address.substring(1);
				var _tS = _rel.indexOf('/', 0); //look for fragment variables below l3 and ignore them
				if (_tS > -1) _rel = _rel.substring(0, _tS);
				$('#tabs_container .tabs > li.active').removeClass('active');
				$('#tabs_container .tabIsolatedRight.active').removeClass('active');
				$('a[rel=' + _rel + ']', tabsFull).closest('.tabLeft').addClass('active');
				$('a[rel=' + _rel + ']', tabsFull).closest('.tabIsolatedRight').addClass('active');
				$('#tabs_container > .tabbed_content > div.active').removeClass('active');
				$(_rel).addClass('active');
			}
			else {
				//go to first tab with / on back button, etc
				$('#tabs_container .tabs > li.active').removeClass('active');
				$('.tabLeft', tabsFull).filter(':first').addClass('active');
				$('#tabs_container > .tabbed_content > div.active').removeClass('active');
				var _rel = $('a', tabsFull).filter(':first').attr('rel');
				$(_rel).addClass('active');
			}
		});
	}
	else {
		//look for fragment markup and reassign hrefs to go to top level js powered nav
		var tabsFragment = $('ul.tabs.fragment');
		if (tabsFragment.length > 0) {
			$('li a', tabsFragment).each(function(i, o) {
				var tabUrl = $(o).attr("href");
				var idx = tabUrl.lastIndexOf('/');
				var slug = tabUrl.substring(idx);
				var baseUrl = tabUrl.substring(0, idx);
				$(o).attr("href", baseUrl + "#" + slug);
			});
		}
	}

	$('.collapsible > .header > a').click(function() {
		var header = $(this).parent();
		if (header.hasClass('expanded')) {
			header.removeClass('expanded');
			header.siblings('.content-collapsible').removeClass('expanded');
			header.siblings('.closeBottom').addClass('collapsed');
		}
		else {
			header.addClass('expanded');
			header.siblings('.content-collapsible').addClass('expanded');

			if (header.siblings('.closeBottom').length < 1) {
				header.parent().append('<a href="javascript:void(null)" class="closeBottom">[close]</a>');
				//must define .closeBottom click handler inline here b/c such doesn't exist at time of $(document).ready
				header.siblings('.collapsible .closeBottom').click(function() {
					if ($(this).siblings('.content-collapsible').hasClass('expanded')) {
						$(this).siblings('.content-collapsible').removeClass('expanded');
						$(this).siblings('.header').removeClass('expanded');
						$(this).addClass('collapsed');
					}
				});
			}
			else {
				header.siblings('.closeBottom').removeClass('collapsed');
			}
		}
	});

	// Alternate Vertical Tabs
	$('.v-tab-container').each(function(i, o) {
		$('.v-tabs a.v-tab', o).click(function() {
			$('.v-tabs > li.active', o).removeClass('active');
			$(this).parent().addClass('active');
			$('div.active', o).removeClass('active');
			$(this.rel).addClass('active');
		});
	});

	$('.v-tab-container .v-tabs a.v-tab').each(function(i, o) {
		$(o).attr("href", "javascript:void(null)");
	});
	$('.v-tab-container > div.content').each(function(i, o) {
	});

	//searchbox events
	$('#searchboxSubmit').click(function() {
		var searchString = $("#searchboxInput").val();
		window.location.href = encodeForSearchPage(searchString);
	});
	$("#searchboxInput").live("keypress", function(e) {
		if (e.keyCode == 13) {
			var searchString = $("#searchboxInput").val();
			window.location.href = encodeForSearchPage(searchString);
		}
	});
	$("#searchboxSubmit").live("keypress", function(e) {
		if (e.keyCode == 13) {
			var searchString = $("#searchboxInput").val();
			window.location.href = encodeForSearchPage(searchString);
		}
	});

	//pin sidebar when scrolling
	//attempted to unroll switch statement but different conditions persisted beyond document.ready so not reliable
	if ($(window).height() > $('#rightSidebar').height()) {
		var rightSidebarPositionTop = ($('#rightSidebar').position().top - 15); //added margin
		var rightSidebarHeight = ($('#rightSidebar').outerHeight()); //added margin
		//var footerPositionTop = $('#footerGroup').position().top + 515;
		$(window).scroll(function() {
			var scrollPos = getPageScroll()[1]
			if (rightSidebarPositionTop < scrollPos) {
				$('#sidebarFloater').addClass('sidebarFloat');
			}
			else $('#sidebarFloater').removeClass('sidebarFloat');
		});
	}

	//begin booking widget
	$("#calendar").datepicker({
		onSelect: function(dateText, inst) {
			var selectedDate = new Date(Date.parse(dateText));
			bookingWidget.updateDateFields(selectedDate);
		},
		beforeShowDay: hilightRangeLocal
	});

	bookingWidget.fillDateFields();

	function hilightRangeLocal(date) {
		return bookingWidget.hilightRange(date);
	}
/*    $("#arr").datepicker({
		onSelect: function(dateText, inst) {
			arrDate = new Date(Date.parse(dateText));
			depDate = new Date(arrDate); //pass by val and set to same day then increment 1 day
			depDate.setDate(arrDate.getDate() + 1);
			bookingWidget.arrDate = arrDate;
			bookingWidget.depDate = depDate;
			bookingWidget.fillDateFields();
			//$("#dep").datepicker("minDate", arrDate);
			$("#calendar").datepicker("setDate", depDate)
		}
	});
	$("#dep").datepicker({
		onSelect: function(dateText, inst) {
			depDate = new Date(Date.parse(dateText));
			bookingWidget.depDate = depDate;
			bookingWidget.fillDateFields();
			$("#calendar").datepicker("setDate", depDate)
		}
	});*/

	$('#roomSearch').click(function() {
		//window.location.href = bookingWidget.getUrl("/trip-planner/lodging");
		//return false;
		setTimeout(function(){ window.location = bookingWidget.getUrl("/trip-planner/lodging"); }, 0);
	});
	//end booking widget

	var blogEntries = $('#blogEntries > .blogEntry');
	var maxIndex = blogEntries.length - 1;
	var index = 0;
	// only show the first image, hide the rest
	blogEntries.hide().filter(':first').show();
	blogEntries.removeClass("hidden");

	$('#blogWidgetL2').everyTime(15000, function() {
		rotateBlogEntries();
	}, 0);

	function rotateBlogEntries() {
		var prevIndex = index;
		if (index == maxIndex) index = 0;
		else index++;

		blogEntries.eq(prevIndex).hide('slide', { direction: "up" }, 2500);
		blogEntries.eq(index).show('slide', { direction: "down" }, 2500);
	}

	$('#comboWidgetL1 .tab').click(function() {
		$('#comboWidgetL1 > .header > a.active').removeClass('active');
		$(this).addClass('active');
		$('#comboWidgetL1 > .content').removeClass('active');
		$(this.rel).addClass('active');
	});

	var camWrapper = $('#comboWidgetL1 > #pnl3 .cams > .webcams > .cam');
	var cMaxIndex = camWrapper.length - 1;
	var camIndex = 0;
	// only show the first image, hide the rest
	camWrapper.hide().filter(':first').show();

	$('#pnl3 a.navLeft').click(function() {
		var prevIndex = camIndex;
		if (camIndex == 0) camIndex = cMaxIndex;
		else camIndex--;
		swapWebcam(camIndex, prevIndex);
	});

	$('#pnl3 a.navRight').click(function() {
		var prevIndex = camIndex;
		if (camIndex == cMaxIndex) camIndex = 0;
		else camIndex++;
		swapWebcam(camIndex, prevIndex);
	});

	function swapWebcam(camIndex, prevIndex) {
		camWrapper.css('z-index', 4);
		camWrapper.eq(camIndex).css('z-index', 5);
		camWrapper.eq(camIndex).fadeIn(300, function() {
			camWrapper.eq(prevIndex).hide();
		});
	}

	function getTabUrlFragment(path) {
		var tabNames = [];
		$('ul.tabs > li a').each(function(i, o) {
			tabNames.push($(o).attr('rel').substring(1));
		});
		var fragment = path.substring(1); //assume initial '/'
		var _tS = fragment.indexOf('/', 0); //look for fragment variables below l3 and strip them off
		if (_tS > -1) fragment = fragment.substring(0, _tS);
		if ($.inArray(fragment, tabNames) > -1) {
			return fragment;
		}
		else {
			return "";
		}
	}

});

$(window).load(function() {
	$.getJSON('/Prefetch.pxml', function(imgData) {
		if (imgData.prefetch.img)
		{
		$.each(imgData.prefetch.img, function(index, imageNode) {
		var img = new Image();
		img.src = imageNode['@src'];
		});
		}
	});
	
	//leave in doc.ready until scoping can be resolved
	/*$('#blogWidgetL2').everyTime(15000, function() {
		rotateBlogEntries();
	}, 0);*/
});

function encodeForSearchPage(searchString) {
	var searchData = searchString.split(' ');
	var normalized = "";
	for (var i=0; i<searchData.length; i++)
	{
		normalized += searchData[i];
		if (i < searchData.length - 1) normalized += '+';
	}
	return '/search/#/' + normalized;
}

// http://stackoverflow.com/questions/1567327/using-jquery-to-get-elements-position-relative-to-viewport
// getPageScroll() by quirksmode.com
function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll, yScroll);
}
