if (typeof console == "undefined" || typeof console.log == "undefined") { var console = { log: function() {} }; }

$(function() {
    $('a[rel~=external]').attr('target', '_blank');

    /* for use with tt_mv.js to prevent element shifting when using multivariate tests */
    $('.c1 .sidebarWidget').show();
	
	svlv.initMoreTag();
	
	$(".weatherOpen").click(function() {
		$(".header .weather .contracted").hide();
		$(".header .weather .expanded").show();
		$(".header .weather").css({ width: 389 });
		$(".header .weather").animate({ width: 516 });
	});
	$(".weatherClose").click(function() {
		$(".header .weather").animate({ width: 389 }, function() {
			$(".header .weather .expanded").hide();
			$(".header .weather").css({ width: 189 });
			$(".header .weather .contracted").show();
		});
	});
	
	svlv.initHistory();
	svlv.buildLvDropDowns(".lvDropDown");
	svlv.buildDateInputs($(".dateInput"));
	svlv.buildAjaxOverlays();
	svlv.buildDateInputsTopNav();

	svlv.setRandomBackground(svlv.settings.backgroundThemeId);
	$(".secondaryBackground").show();
	svlv.moveHeaderImage();
	svlv.pairDateInputs();
	svlv.breadcrumb.init();
	$(window).load(function() {
		svlv.asSlider.init();
	});
	svlv.initGhosts();
	
	/* start - omniture tracking for google translate */
	$('a.google-lang-link-alt').live('click',function() {
		try {
			var t = $(this);
			var href = t.attr('href');
			var linkName = 'translate | ' + t.text().toLowerCase();
			
			var bodyclass = $('body').attr('class');
			if (bodyclass && bodyclass !== '') {
				linkName = bodyclass + ' | ' + linkName;
			}
			
			linkName = jQuery.trim(linkName);
			svOm.trackClick(href, linkName, 'o', t.eq(0), 'event45', 'eVar65', linkName);
			/* give time for tracking http request to be sent */
			setTimeout(function(){window.location=href;},700);
			return false;
		} catch(e) {
			return true; 
		}
		
		return false;
		/* end - omniture tracking */
	});
	
});

var svlv = {
	settings : {
		controllerURL : "/includes/cfcs/controller/controller.cfm",
		loading : $("<div class='loading'><img src='/includes/images/shell/ajax-loader.gif'/><span>Loading...</span></div>"),
		backgrounds : [],
		backgroundThemeId : 1,
		breadcrumb : [],
		useBread : true
	},
	getHistory : function() {
		var cookie = svlv.misc.getCookie("history");
		if (cookie != "") {
			var history = JSON.parse(cookie);	
		} else {
			var history = {};	
		}
		
		return history;
	},
	initHistory : function() {
		svlv.settings.history = this.getHistory();
		
		if (typeof(svlv.settings.current) != "undefined") {
			svlv.misc.setCookie("history", JSON.stringify(svlv.settings.current));
		}
	},
	setRandomBackground : function(themeid) {
		var theme = [];
		for (var i = 0; i < svlv.settings.backgrounds.length; i++) {
			if (svlv.settings.backgrounds[i].BACKGROUNDTHEMEID == themeid) {
				theme.push(svlv.settings.backgrounds[i]);	
			}
		}
		
		if (theme.length == 0) {
			return false;	
		}
		
		var rand = Math.floor(Math.random()*theme.length);
		$(".primaryBackground").empty();
		
		if (svlv.settings.backgroundThemeId == "9") {
			$(".primaryBackground").css({ 'background-image' : 'url('+theme[rand].url+')' });
		} else {
			$(".primaryBackground").append("<img src='" + theme[rand].url + "'/>");
		}
		
		if (theme[rand].TOPHEX != "") {
			$(".primaryBackground").css("background-color", theme[rand].TOPHEX);
		}
		if (theme[rand].LEFTHEX != "") {
			$(".secondaryBackground .leftStripe").css("background", theme[rand].LEFTHEX);
		}
		if (theme[rand].RIGHTHEX != "") {
			$(".secondaryBackground .rightStripe").css("background", theme[rand].RIGHTHEX)
		}
		if (theme[rand].REPEAT != 'no-repeat') {
			$(".primaryBackground").empty();
			$(".primaryBackground").css({ 'background-image' : 'url('+theme[rand].url+')', 'background-repeat': theme[rand].REPEAT, 'padding-left' : '0', 'width' : '100%' });
		}
	},
	backgroundCutter : function() {
		if ($(".backgroundCutter").length > 0) {
			$(".backgroundCutter").show();
			var height = $(".backgroundCutter").offset().top;
			$(".primaryBackground").height(height);
			$(".secondaryBackground .dotsBgFadeDown").css({ top : height });
			/*$(".backgroundCutter").hide();*/
		}
	},
	toggleLanguageDropdown : function() {
		$(".languageSelect .languages").toggle();
		$(".languageSelect > a").toggleClass("active");
		$(".languageSelect").toggleClass("shadow10");
	},
	buildLvDropDowns : function(nodeclass) {
		var self = this;
		
		$(nodeclass).each(function() {
			self.buildLvDropDown($(this));
		});
		
	},
	buildLvDropDown : function(node, change_callback) {
		var self = this;
		
		if (typeof change_callback == 'undefined' || !change_callback) {
			change_callback = function() {};
		}
	
		if (node.attr("multiple") == true) {
			var myclass = "lvDropDownMultiple";	
		} else {
			var myclass = "lvDropDownSingle";	
		}
		
		var final = $("<div class='lvDropDownFinal " + myclass + "'></div>");
		
		/* begin: in case we are already bound to it, but need to rebind handlers, like with a multivariate test */
		if ( $(node).hasClass('lvDropDownFinal') === true ) {
			final = $(node);
			
			if ( $(this).hasClass('lvDropDownMultiple') ) {
				final.find(".lvOption input[type=checkbox]").click(function() {
					self.updateMultipleCount($(this));
				});
			} else {
				final.find(".lvOption").click(function() {
					var parent = $(this).closest(".lvDropDownFinal");
					parent.find("input").val($(this).attr("data-value"));
					parent.find("input").attr("data-label", $(this).attr("data-label"));
					parent.find(".lvDropDownCurrent").html($(this).html());
					parent.find(".lvOptions").hide();
					change_callback();
				});
			}
			
			final.find(".lvDropDownCurrent").click(function() {
				if ($(this).next().is(":visible")) {
					$(this).next().focus();
				} else {
					$("body").bind("click", svlv.closeDropDowns);
				}
				$(this).next().toggle();
			});
			
			return;
		}
		/* end: in case we are already bound to it, but need to rebind handlers, like with a multivariate test */
		
		if (node.attr("multiple") == true) {
			final.append("<div class='lvDropDownCurrent'><span class='lvCount'></span>" + node.find("option").eq(0).text() + "</div>");
			var lvOptions = $("<div class='lvOptions'></div>");
			node.find("option").not(":first-child").each(function() {
				if ($(this).is(":selected")) {
					var checked = "checked";	
				} else {
					var checked = "";	
				}
				
				lvOptions.append("<div class='lvOption'><label><input type='checkbox' name='" + node.attr('name') + "' data-label='" + $(this).text() + "' value='" + $(this).val() + "' " + checked + ">" + $(this).text() + "</label></div>");
			});
			
			final.append(lvOptions);
			final.append("<input type='hidden' name='" + node.attr('name') + "' value='0'>");
			
			self.updateMultipleCount(lvOptions.find(".lvOption:first-child"));
			
			final.find(".lvOption input[type=checkbox]").click(function() {
				self.updateMultipleCount($(this));
			});
		} else {
			final.append("<input type='hidden' name='" + node.attr('name') + "' value='" + node.val() + "' data-label='" + node.find("option:selected").text() + "'>");
			final.append("<div class='lvDropDownCurrent'>" + node.find("option:selected").text() + "</div>");
			var lvOptions = $("<div class='lvOptions'></div>");
			node.find("option").each(function() {
				lvOptions.append("<div class='lvOption' data-value='" + $(this).val() + "' data-label='" + $(this).text() + "'>" + $(this).text() + "</div>");
			});
			final.append(lvOptions);
			
			final.find(".lvOption").click(function() {
				var parent = $(this).closest(".lvDropDownFinal");
				parent.find("input").val($(this).attr("data-value"));
				parent.find("input").attr("data-label", $(this).attr("data-label"));
				parent.find(".lvDropDownCurrent").html($(this).html());
				parent.find(".lvOptions").hide();
				change_callback();
			});
		}
		
		final.find(".lvDropDownCurrent").click(function() {
			if ($(this).next().is(":visible")) {
				$(this).next().focus();
			} else {
				$("body").bind("click", svlv.closeDropDowns);
			}
			$(this).next().toggle();
		});
		
		if (node.attr("multiple") == true) {
			var padding = 35;	
		} else {
			var padding = 17;	
		}
		
		node.after(final); 
		node.appendTo("body"); /*** This is a hack to properly get width from selects hidden at the time this function is called (used in topNav) ***/
		final.width(node.width() + padding);
		final.find(".lvOptions").width(node.width() + padding - 2); /** 2px difference for borders **/
		node.remove();
	},
	closeDropDowns : function(e) {	
		if ($(e.target).closest(".lvDropDownFinal").length == 0) {
			$(".lvOptions").hide();
			$("body").unbind("click", svlv.closeDropDowns);
		} else {
			$(".lvOptions").not($(e.target).closest(".lvDropDownFinal").find(".lvOptions").get(0)).hide();
		}
	},
	updateMultipleCount : function(node) {
		var count = node.closest(".lvOptions").find("input[type=checkbox]:checked").length;

		if (count == 0) {
			var countHTML = "";	
		} else {
			var countHTML = "(" + count + ")";	
		}
		
		node.closest(".lvDropDownFinal").find(".lvCount").html(countHTML);
	},
	buildDateInputs : function(nodes, format) {
		var min = new Date();
		min.setDate(min.getDate() - 1);
		if (typeof format === 'undefined') {
			format = 'mm/dd/yyyy';
		}
		nodes.dateinput({
			format: format,
			trigger : true,
			min : min,
			max : 365
		});
		$("#calroot").each(function(index, element) {
			$(element).append('<a href="#" class="xCal" onClick="javascript:$(this).parent().hide();$(this).focus();return false;">close <img src="/includes/images/shell/calClose.jpg"></a>');
		});
	},
	buildDateInputsTopNav : function() {
		$(".topNavDateInput").dateinput({
			format : 'mm/dd/yyyy',
			trigger : true,
			min: -1,
			max: 365,
			onShow : function(event, date) {
				var node = this.getInput();
				var calendar = this.getCalendar();
				node.next().after(calendar);
				calendar.css({ left: 0, top: 20});
			},
			onHide : function(event, date) {
				this.getCalendar().appendTo("body");
			}
		});
	},
	buildAjaxOverlays : function() {
		$("body").append("<div id='svlvOverlay'></div>");
		this.buildAjaxOverlay($(".svlvOverlayLink"));
	},
	buildAjaxOverlay : function(nodes, extraClass) {
		nodes.overlay({
			mask : "#444",
			onBeforeLoad : function() {
				var overlay = $("#svlvOverlay");
				
				if (typeof sv != 'undefined' && typeof sv.siteID != 'undefined') {
					overlay.addClass('site'+sv.siteID);
				}
				
				if (typeof extraClass != 'undefined') {
					overlay.addClass(extraClass);
				}
				
				if(overlay.children(".content").length > 0) {
					overlay.children(".content").remove();	
				}
				
				if (this.getTrigger().attr("data-width")) {
					overlay.css("width", this.getTrigger().attr('data-width') + "px");
				} else {
					overlay.css("width", "auto");	
				}
				
				var content = $("<div class='content'></div>");
				
				content.load(this.getTrigger().attr("href"));
				overlay.append(content);
			},
			closeOnClick : false,
			fixed : false
		});
	},
	centerOverlay : function(node) {
		node.css("left", ($(window).width() - node.width()) / 2);
		node.css("top", ($(window).height() - node.height()) / 2);
	},
	bookingFormSubmit : function(form) {
		if (this.validateBooking(form)) {
			form.submit();	
		}
	},
	validateBooking : function(form) {
		var start = form.find("input[name=start-date]").val();
		var end = form.find("input[name=end-date]").val();
		
		if (Date.parse(start) > Date.parse(end)) {
			alert('Invalid date range selected');
			return false;	
		}
		
		return true;
	},
	moveHeaderImage : function() {
		var node = $(".contentHeaderImage, .contentHeaderImage2");
		if (node.length == 0) {
			return true;	
		}
		
		$(".newBreadcrumb").before(node);
		$(".contentHeaderImage, .contentHeaderImage2").show();
	},
	pairDateInputs : function() {
		$(".pairedStart").each(function() {
			var guid = $(this).attr("class").match(/start_\w+/)[0].replace("start_", "");
			
			if ( $(this).data("dateinput") !== undefined && $(this).data("dateinput").unbind !== undefined ) {
				$(this).data("dateinput").unbind('change');
			}
			
			$(this).data("dateinput").change(function() {
				var newDate = new Date(this.getValue().getFullYear(), this.getValue().getMonth(), this.getValue().getDate() + 3);
				$(".end_" + guid).data("dateinput").setMin(this.getValue());
				$(".end_" + guid).data("dateinput").setValue(newDate);
			});
		});		
	},
	adjustTopNav : function() {
		$(".lvTopSecond").each(function() {
			$(this).css({ left: -$(this).parent().position().left });
		});
	},
	addRightBar : function() {
		$(".contentInterior .leftContent").css({ width : "538px", float : "left" });
		$(".contentInterior .rightContent").show();
	},
	createBreadcrumb : function(data) {
		var temp = data.split("|")
	},
	fixNavWidths : function() {
		/*** This is an ugly function which ensures that the top nav items snugly fit with each other ***/
		var nodes = $(".lvTopNavTop > li:not(.lastItem) > a");
		var width = 0;
		
		/*** IE9 allows fractional widths, and width() returns an integer, so we add 1, otherwise text wraps. ***/
		$(".lvTopNavTop > li > a").each(function() {
			$(this).width($(this).width() + 1);
		});
		
		nodes.each(function() {
			width += $(this).width();
		});
		
		var available = $(".lvTopNav").width() - $(".lvTopNav .lastItem").width() - (nodes.length * 2) - 1;
		var paddingLeft = Math.floor((available - width) / (2 * nodes.length));
		
		nodes.each(function() {
			$(this).css({ "paddingLeft" : paddingLeft, "paddingRight" : paddingLeft });
		});
		var available = $(".lvTopNav").width() - width - $(".lvTopNav .lastItem").width() - (nodes.length * paddingLeft * 2) - (nodes.length * 2) + 1;
		var current = parseInt($(".lvTopNav .lastItem > a").css("paddingLeft").replace("px",""));
		var left = current;
		var right = current;
		
		var half = available / 2;
		if (Math.floor(half) == half) {
			left += half;
			right += half;
		} else {
			left += Math.floor(half) + 1;
			right += Math.floor(half);
		}
		
		$(".lvTopNav .lastItem > a").css({ paddingLeft : left, paddingRight : right });
	},
	fixNavWidthsAlt : function() {
		/*** This is an ugly function which ensures that the top nav items snugly fit with each other ***/
		var width = 0, available = 0, x = 0, paddingLeft = 0, current = 0, left = 0, right = 0, half = 0, firstOffset = 0, lastOffset = 0;
		var lvTopNavWidth = $(".lvTopNav").width();
		var nodes = $(".lvTopNavTop > li");
		nodes.each(function() {
			x = $(this).width() + ( $(this).outerWidth(true) - $(this).outerWidth(false) );
			width += x;
		});
		width = Math.floor(width);
		
		available = lvTopNavWidth - width;		
		paddingLeft = Math.floor(available / (2 * nodes.length));
		
		nodes.each(function() {
			$(this).css({ "paddingLeft" : paddingLeft, "paddingRight" : paddingLeft });
		});
		
		width = 0;
		nodes.each(function() {
			width += $(this).outerWidth(true);
		});		
		width = Math.floor(width);
		
		available = lvTopNavWidth - width;
		current = parseInt(nodes.last().css("paddingLeft").replace("px",""));
		left = current;
		right = current;
		
		half = available / 2;
		if (Math.floor(half) == half) {
			left += half;
			right += half;
		} else {
			left += Math.floor(half) + 1;
			right += Math.floor(half);
		}
			
		nodes.last().css({ paddingLeft : left, paddingRight : right });
		
		firstOffset = nodes.first().offset();
		lastOffset = nodes.last().offset();
		x = 0;
		
		while (firstOffset.top < lastOffset.top && left > 0) {
			if (x == 0) { left -= 1; x = 1; } else { right -= 1; x = 0; }
			nodes.last().css({ paddingLeft : left, paddingRight : right });
			firstOffset = nodes.first().offset();
			lastOffset = nodes.last().offset();
		}
		
		/* makes sure the event fires again, combined with the jQuery.onWinZoom.trigger, to ensure proper sizing of items */
		if ($('#ifOnWinZoom').length == 0) {
			$(document).ready(function () {
				var $rframe = $("<iframe />")
					.attr("id", "ifOnWinZoom")
					.css({width: "10em", height: "10px", position: "absolute", borderWidth: 0, top: "-5000px", left: "-5000px"})
					.appendTo("body");
					
					var doc = $rframe[0].contentWindow || $rframe[0].contentDocument || $rframe[0].document;
					doc = doc.document || doc;
					doc.open();
					doc.write('<div style="width:10em;height:10px;"></div>');
					doc.write('<scri' + 'pt>window.onload = function(){window.onresize = function(){if(parent.jQuery.onWinZoom){parent.jQuery.onWinZoom.trigger();}}};</scri' + 'pt>');
					doc.close();
			});
		}
	},
	initGhosts : function() {
		/* when an input is focused and has default value, clear it.. when blurred and has no value, put default value back in */
		/* if you add the data value "ghost_always_clear" equals 1 on an input, it will always clear any value when focused */
		$(".inputGhost").each(function(){
			$(this).data("default", $.trim($(this).val()));
		});
	
		$(".inputGhost").bind("focus.ghost", function(e) {
			var node = $(this);
			if ( ($.trim(node.val()) === $.trim(node.data("default")) ) || node.data("ghost_always_clear") == 1) {
				node.val("");
			}
		});
		
		$(".inputGhost").bind("blur.ghost", function(e) {
			var node = $(this);
			if ($.trim(node.val()).length === 0) {
				node.val($.trim(node.data("default")));
			}
		});
	},
	initMoreTag : function() {
		$(".moreTagLink").click(function(){
			var t = $(this);
			var t2 = t.clone(true);
			var mid = t.attr('data-mid');
			var span = $('.moreTagSpan[data-mid="'+mid+'"]:first');
			span.toggle();
			t.remove();
			if (span.is(":visible")) {
				t2.html('...less');
				t2.insertAfter(span);
			} else {
				t2.html('more...');
				t2.insertBefore(span);
			}
			return false;
		});
	},
	initDetailMapLink : function() {
		var mciw_a = $('.mapColumn .infoWindowContainer:first a.website_redirect:first');
		var vw = false;
		if (mciw_a && mciw_a.length) {
			vw = $('.overviewTop a.view_website:first');
			if (!vw || !vw.length) {
				vw = $('.overviewTop .webaddress a:first');
			}
			if (vw && vw.length) {
				var vw2 = vw.clone();
				vw2.empty().html( mciw_a.html() );
				mciw_a.replaceWith(vw2);
			}
		}
	}
};

svlv.breadcrumb = {
	init : function() {
		if (!svlv.settings.useBread) {
			return false;	
		}
		
		var data = svlv.settings.breadcrumb;
		if (data.length > 0 && $(".newBreadcrumb").length > 0) {
			var elem = $(".newBreadcrumb");
			elem.empty();
			var items = [];
			for(var i = 0; i < data.length; i++) {
				if (i == data.length - 1) {
					var menu = "<span>" + data[i].label + "</span>";	
				} else {
					if ( typeof data[i].onclick == 'undefined' ) { data[i].onclick = ''; }
					var menu = "<a href='" + data[i].url + "' onclick='" + data[i].onclick + "'>" + data[i].label + "</a>";
					if (i == data.length - 2) {
						/* add <div class="breadcrumblast"></div> to show this anywhere needed */
						$(".breadcrumblast").html('<a href="'+data[i].url+'">Back to '+data[i].label+'</a>');
					}
				}
				items.push(menu);
			}
			elem.html(items.join("&nbsp;&nbsp; // &nbsp;&nbsp;"));
		}
	},
	detailHack : function() {
		svlv.settings.breadcrumb = [{ label : "", onclick : "window.history.go(-1); return false" }, { label : svlv.settings.current.pagename }];
		
		var temphistory = svlv.getHistory();
		if (temphistory.pagetype == "layout") {
			svlv.settings.breadcrumb[0].label = temphistory.menuname;	
			svlv.settings.breadcrumb[0].url = temphistory.url;
		} else {
			svlv.settings.breadcrumb.splice(0,1);	
		}
	},
	vmbpressHack : function() {
		var mypname = svlv.settings.current.pagename.replace('&amp;#','&#');
		svlv.settings.breadcrumb.push({ label : mypname });
		this.init();
	},
	mapExplorerHack : function() {
		var temphistory = svlv.getHistory();
		svlv.settings.breadcrumb = [];
		if (temphistory.menuname && temphistory.url) {
			svlv.settings.breadcrumb.push({ label: temphistory.menuname, url: temphistory.url });
		}
		svlv.settings.breadcrumb.push({ label: svlv.settings.current.pagename });
	}
};

svlv.listings = {
	settings : {
		scrollTimer : 0,
		callback_on_init : function(){}
	},
	init : function() {
		this.addCompares();
		this.initStickyCompare();
		this.compareCallback();
		$(window).load(function() {
			svlv.listings.initAjaxState();
		});
	},
	initAjaxState : function() {
		var params = svlv.misc.getHashParams();
		
		if ($.isEmptyObject(params)) {
			return false;	
		}
		
		this.initFilterState(params);
		window.listings.paginate(window.listings.createAjaxURL(params));
		this.settings.callback_on_init();
	},
	initFilterState : function(params) {
		svlv.listings.clearFilters();
		$("#listingsFiltersForm .lvDropDownMultiple").each(function() {
			for(var i in params) {
				var values = params[i].split(",");
				
				for(var k = 0; k < values.length; k++) {
					var node = $(this).find("input[type=checkbox][name=" + i + "][value=" + values[k] + "]");

					if (node.length > 0) {
						node.attr("checked", true);
						svlv.updateMultipleCount(node);
					}
				}
			}
		});
		$("#listingsFiltersForm .lvDropDownSingle").each(function() {
			for(var i in params) {
				var node = $(this).find("input[name=" + i + "]");
				if (node.length > 0) {
					$(this).find(".lvOption[data-value=" + params[i] + "]").click();	
				}
			}
		});
	},
	addCompares : function() {
		var params = svlv.misc.getUrlParams(window.location.href);
		
		if (typeof(params['compareids']) == "undefined") {
			return false;	
		}
		
		var data = params['compareids'].split(",");
		for(var i = 0; i < data.length; i++) {
			this.compareAdd(data[i]);	
		}
	},
	validateCompare : function() {
		if ($(".compareBar .compareItem").length <= 1) {
			alert('Oops! You must select more than one hotel to compare');
			return false;
		}
		
		window.location.href = $(".compareBar .redArrow").attr("href");
	},
	compareScroll : function() {
		clearTimeout(svlv.listings.settings.scrollTimer);
		svlv.listings.settings.scrollTimer = setTimeout("svlv.listings.updateCompareVisibility()", 200);
	},
	pageScroll : function() {
		clearTimeout(svlv.listings.settings.scrollTimer);
		svlv.listings.settings.scrollTimer = setTimeout("svlv.listings.updatePageVisibility()", 200);
	},
	initComparePage : function() {
		this.settings.pageStartTop = $(".compareListings .topContent").offset().top;
		$(window).bind("scroll", svlv.listings.pageScroll);
		
		/* start - hide amenity row if all compared listings amenity are N/A */
		var cl = $(".compareListings");
		var cls = cl.find("div.amenitySmall");
		var clsd = cl.find("div.amenitySmall.disabled");
		var dfieldid = 0;
		cls.each(function(){
			dfieldid = $(this).attr('data-fieldid');
			var clsrows = cls.filter('[data-fieldid="'+dfieldid+'"]');
			var clsdrows = clsd.filter('[data-fieldid="'+dfieldid+'"]');
			if (clsrows.length == clsdrows.length) { clsrows.hide(); }
		});
		/* end - hide amenity row if all compared listings amenity are N/A */
		
	},
	updatePageVisibility : function() {
		if ($(document).scrollTop() > this.settings.pageStartTop) {
			$(".topContent").each(function() {
				if ($(this).css("position") != "fixed") {
					$(this).css({ left : $(this).offset().left });
					$(this).addClass("fixed");	
				}
			});
		} else if ($(document).scrollTop() <= this.settings.pageStartTop) {
			$(".topContent").each(function() {
				if ($(this).css("position") != "static") {
					$(this).removeClass("fixed");
					$(this).css({ left : "auto" });
				}
			});
		}
	},
	initStickyCompare : function() {
		$(".compareBar").show();
		this.settings.compareStartTop = $(".compareBar").offset().top;
		$(".compareBar").hide();
	},
	compareCallback : function() {
		this.updateCompareCounts();
		this.updateCompareLink();
		this.updateCompareLinks();
		this.updateCompareVisibility();
		this.updateCompareEvent();
	},
	compareAdd : function(listingid) {
		var node = $(".listingLayout .listingItem[data-listingid=" + listingid + "]");
		
		if (node.length == 0) {
			return false;	
		}
		
		var compareItem = $("<div class='compareItem' data-listingid='" + node.attr('data-listingid') + "'></div>");
		compareItem.append("<p class='compareCount'></p>");
		compareItem.append("<p class='compareTitle'>" + node.attr('data-comparetitle') + "</p>");
		compareItem.append("<img src='/includes/images/shell/compareRemove.png' class='compareRemove' onClick='svlv.listings.compareRemove(" + node.attr("data-listingid") + ")'>");
		$(".listingLayout .compareItems").append(compareItem);
		
		this.compareCallback();
	},
	comparePageRemove : function(listingid) {
		$(".compareListing[data-listingid=" + listingid + "]").remove();
		
		var compListings = $(".compareListing");
		if (compListings.length == 0) {
			javascript: history.go(-1);
		}
	},
	compareRemove : function(listingid) {
		var node = $(".listingLayout .compareItem[data-listingid=" + listingid + "]").remove();
		this.compareCallback();
	},
	compareToggle : function(listingid) {
		if (this.compareExists(listingid)) {
			this.compareRemove(listingid);	
		} else if ($(".compareItems .compareItem").length < 4) {
			this.compareAdd(listingid);	
		} else {
			alert('You may only compare 4 properties at a time.');	
		}
	},
	compareExists : function(listingid) {
		if ($(".listingLayout .compareItem[data-listingid=" + listingid + "]").length > 0) {
			return true;	
		} else {
			return false;	
		}
	},
	updateCompareEvent : function() {
		if ($(".compareItems .compareItem").length > 0) {
			$(window).bind("scroll", svlv.listings.compareScroll);
		} else {
			$(window).unbind("scroll", svlv.listings.compareScroll);	
		}
	},
	updateCompareLink : function() {
		var data = [];
		$(".listingLayout .compareItem").each(function() {
			data.push($(this).attr("data-listingid"));
		});
		
		$(".compareBar .redArrow").attr("href", this.compareURL + "?listingids=" + data.join(','));
	},
	updateCompareCounts : function() {
		var i = 1;
		$(".listingLayout .compareItem").each(function() {
			$(this).find(".compareCount").html("Property #" + i);
			i++;
		});
	},
	updateCompareLinks : function() {
		$(".listingLayout .listingItem .lvCompareLink span").html("Compare Property");
		
		$(".listingLayout .compareItem").each(function() {
			$(".listingLayout .listingItem[data-listingid=" + $(this).attr("data-listingid") + "] .lvCompareLink span").html("Remove Compare");
		});
	},
	updateCompareVisibility : function() {
		if ($(document).scrollTop() > this.settings.compareStartTop) {
			if ($(".compareBar").css("position") != "fixed") {
				$(".compareBar").css({ position : "fixed", top : 0, zIndex : 10, left : $(".listingTop").offset().left });
			}
		} else if ($(document).scrollTop() <= this.settings.compareStartTop) {
			if ($(".compareBar").css("position") != "static") {
				$(".compareBar").css({ position : "static", top : "auto", zIndex : "auto", left : "auto" });
			}
		}
		
		if ($(".compareBar .compareItem").length > 0 && $(".compareBar:visible").length == 0) {
			$(".compareBar").show();	
		} else if ($(".compareBar .compareItem").length == 0 && $(".compareBar:visible").length > 0) {
			$(".compareBar").hide();	
		}
	},
	addJackRabbits : function(listingids, callback) {
		var mydate = new Date();
		var day = mydate.getDate();
		var month = mydate.getMonth() + 1;
		var year = mydate.getFullYear();
		var endDay = mydate.getDate();
		var endMonth = mydate.getMonth() + 2;
		var endYear = mydate.getFullYear();
		$.get("/includes/cfcs/controller/controller.cfm?object=jackObj&action=getData&returnType=json", { listingids : listingids, startDate : year + "-" + month + "-" + day, endDate : endYear + "-" + endMonth + "-" + endDay }, function(controllerData) {
			var data = controllerData.data;
			for (var i in data) {
				var listing = $(".jackrabbitItem[data-listingid=" + i + "]");
				var lowest = 0;
				for (var k in data[i]) {
					if (data[i][k] > 0 && (data[i][k] < lowest || lowest == 0)) {
						lowest = data[i][k];	
					}
				}
					
				if (lowest > 0) {
					var bigPrice = Math.floor(lowest);
					var smallPrice = lowest - Math.floor(lowest);
					smallPrice = smallPrice.toFixed(2);
					smallPrice = smallPrice.replace("0.", "");
					listing.find(".bigPrice").html("$" + bigPrice + ".");
					listing.find(".smallPrice").html(smallPrice);
				} else {
					var jrs_phone = listing.find(".listingBook").attr('data-phone');
					if (jrs_phone != '' && typeof(jrs_phone) != 'undefined')
					{
						listing.find(".listingBook").html('<div class="noJRID">For room rates and availability at this location, please contact the property directly at: '+jrs_phone+'</div>');
					}
					else
					{
						listing.find(".bigPrice").html("Sold");
						listing.find(".smallPrice").hide();
						listing.find(".price").append('<div class="jrSoldText">Click "Book Direct" to find rates for other nights</div>');
					}
				}
				
				listing.find(".listingBook").show();
				svlv.buildAjaxOverlay(listing.find(".viewrates"));
			}
			
			if (typeof(callback) == "function") {
				callback();
			}
		}, "json");
	},
	getDetailYouTube : function(userid) {
		$.get(svlv.settings.controllerURL, { object : "listingDetailObj", action : "youtubeAjax", userid : userid, returntype : "json" }, function(data) {
			if (data.status == "success") {
				$(".youtubeAjaxContainer").html(data.data);	
			}
		}, "json");
	},
	compareToLayout : function(elem) {
		var node = $(elem);
		
		var compares = $(".compareListing");
		
		var data = [];
		for(var i = 0; i < compares.length; i++) {
			data.push(compares.eq(i).attr("data-listingid"));
		}
		
		if (data.length > 0) {
			var url = svlv.misc.setUrlVar("compareids", data.join(","), node.attr("href"));
		} else {
			var url = node.attr("href");
		}
		window.location.href = url;	
	},
	clearFilters : function() {
		var nodes = $(".generalFilterBar input[type=checkbox]:checked");
		
		nodes.attr("checked", false);
		$(".lvDropDownMultiple").each(function() {
			svlv.updateMultipleCount($(this).find(".lvOption:first-child"));
		});
	}
}

svlv.asSlider = { 
	init : function() {
		$(".agnosticSlider").each(function() {
			var myContainer = $(this).find(".asWindowContainer");
			var myWindow = $(this).find(".asWindow");
			var myTrack = $(this).find(".asTrack");
			var myItems = $(this).find(".asItem");
			var myItem = myItems.eq(0);
			
			var count = parseInt(myTrack.attr("data-count"));
			var margin = myItem.outerWidth(true) - myItem.width();
			var windowWidth = (count * myItem.width()) + ((count - 1) * margin);
			myWindow.width(windowWidth);
			myContainer.width(windowWidth);
			svlv.misc.setSameHeight($(this).find(".asItem"));
			myWindow.height(myItem.height());
			$(this).find(".asDivider").each(function() {
				$(this).width(windowWidth + margin);
			});
		});
		
		$(".agnosticSlider .asWindow").scrollable({
			items : ".asDivider",
			prev : ".asLeft",
			next : ".asRight",
			circular : true
		});
	}
}

svlv.overlayCalendar = {
	init : function() {
		svlv.buildDateInputs($(".viewRatesTopRight .dateInput"));
		svlv.buildLvDropDowns(".lvDropDown");
		this.selectDate($(".viewCalendar .viewDay.hasData").eq(0).attr("data-date"));
		$(".viewWindow").scrollable({
			onSeek : function() {
				var self = this;
				if (this.getIndex() == this.getSize() - 1) {
					var items = this.getItems();
					var current = items.eq(this.getIndex());
					
					var data = current.attr('data-date');
					var dateParts = data.split("-");
					
					var newDate = new Date(dateParts[0], dateParts[1], 1);
					var dateString = newDate.getFullYear() + "-" + (newDate.getMonth() + 1) + "-" + newDate.getDate();
					$(".viewCalendars").append(svlv.settings.loading);
					$.get(svlv.settings.controllerURL, { object : "listingDetailObj", action : "calendarBottom", startdate : dateString, listingid : $(".viewRates").attr("data-listingid") }, function(data) {
						var newContent = $(data);
						$(".loading").detach();
						$(".viewCalendars").append(newContent);
						self.seekTo(self.getIndex());
						svlv.overlayCalendar.adjustHeight();
					});
				}
			},
			next : ".viewRight",
			prev : ".viewLeft"
		});
		this.adjustHeight();
	},
	adjustHeight : function() {
		var topHeight = $(".viewCalendarContainer").height();
		$(".viewCalendarContainer").each(function() {
			if ($(this).height() > topHeight) {
				topHeight = $(this).height();	
			}
		});
		$(".viewWindow").height(topHeight);
	},
	selectDate : function(dateString) {
		var start = $(".viewCalendar .viewDay.start");
		var finish = $(".viewCalendar .viewDay.finish");
		var newNode = $(".viewDay.hasData[data-date=" + dateString + "]");
		var allNodes = $(".viewDay").not(".notactive");
		
		if (start.length == 0) {
			$(".viewRatesTopRight .dateInput").eq(0).val(dateString);
			$(".viewRatesTopRight .dateInput").eq(1).val(dateString);
			newNode.addClass("selected").addClass("start");
		} else if (start.length == 1 && finish.length == 0 && newNode.get(0) != start.get(0)) {
			var startPos = $.inArray(start.get(0), allNodes);
			var endPos = $.inArray(newNode.get(0), allNodes);
			
			if (endPos < startPos) {
				start.removeClass("selected").removeClass("start");
				return this.selectDate(dateString);	
			}
			
			for(var i = startPos; i < endPos; i++) {
				if (allNodes.eq(i).hasClass("hasData")) {
					allNodes.eq(i).addClass("selected");	
				} else {
					alert('Invalid date range, day in between does not have available rooms');
					allNodes.removeClass("selected");
					start.addClass("selected");
					return false;
				}
			}
			
			$(".viewRatesTopRight .dateInput").eq(1).val(dateString);
			newNode.addClass("selected").addClass("finish");	
		} else if (newNode.get(0) == start.get(0) && finish.length == 0) {
			allNodes.removeClass("finish").removeClass("selected").removeClass("start");
			this.selectDate("");
		} else {
			allNodes.removeClass("finish").removeClass("selected").removeClass("start");
			this.selectDate(dateString);
		}
	},
	selectNode : function(node) {
		this.selectDate(node.attr("data-date"));
	}
}

svlv.overlayGallery = {
	init : function() {
		$(".overlayGallery .pane").eq(0).fadeIn().addClass("active");
		svlv.misc.readyImages($(".overlayGallery img"), function() {
			$(".overlayGallery .panes").show();
			$(".overlayGallery .overlayBottom").show();
			$(".overlayGallery .loading").hide();
			svlv.centerOverlay($("#svlvOverlay"));
		});
	},
	cycle : function(num) {
		var activeNode = $(".overlayGallery .pane.active");
		var nodes = $(".overlayGallery .pane");
		for (var i = 0; i < nodes.length; i++) {
			if (nodes.get(i) == activeNode.get(0)) {
				index = i;
			}
		}
		
		next = index + num;
		
		if (next >= nodes.length) {
			next = 0;	
		} else if (next < 0) {
			next = nodes.length - 1;
		}
		
		activeNode.removeClass("active").hide();
		nodes.eq(next).addClass("active").fadeIn();
		
		$(".overlayGallery .count").html(next + 1);
		
		svlv.centerOverlay($("#svlvOverlay"));
	}
}

svlv.dragdrop = {
	getDefaultSettings : function() {
		return {
			clone : false,
			callback : "",
			dropSelector : ".lvDroppable",
			dropProxy : $("<div class='lvDropProxy'>Insert Here</div>")
		}
	},
	makeDraggable : function(nodes, settings) {
		var mysettings = this.getDefaultSettings();
		for (var i in settings) {
			mysettings[i] = settings[i];	
		}
		
		nodes.bind('mousedown', { settings : mysettings, library : this }, this.dragFunction);
	},
	dragFunction : function(e) {
		var original = this;
		if (e.which == 1) {
			var drag = $(this).clone().hide().appendTo("body").addClass('lvDragging').css({ opacity : .6 });
			var dropProxy = e.data.settings.dropProxy;
			var startx = $(original).offset().left;
			var starty = $(original).offset().top;
			var diffx = e.pageX - startx;
			var diffy = e.pageY - starty;
			drag.css({ left : startx, top : starty, width : $(original).width() });
			var i = 0;
			$("body").mousemove(function(data) {
				var startx = data.pageX - diffx;
				var starty = data.pageY - diffy;
				$(".lvDragging").css({ left : startx, top : starty }).show();
				var inDrop = false;
				$(e.data.settings.dropSelector).each(function() {
					var dropZone = $(this);
					if (e.data.library.mouseWithin(data.pageX, data.pageY, dropZone)) {
						var draggable = $(this).find(".lvDraggable");
						draggable.each(function() {
							var offset = $(this).offset();
							var height = $(this).outerHeight(true);
							
							if (data.pageY > offset.top + height/2 && data.pageY < offset.top + height) {
								if ($(this).next().hasClass("lvDropProxy") == false) {
									$(this).after(dropProxy);
								}
								
								return false;
							} else if (data.pageY > offset.top && data.pageY < offset.top + height/2) {
								if ($(this).prev().hasClass("lvDropProxy") == false) {
									$(this).before(dropProxy);
								}
								
								return false;
							}
						});
						
						if (draggable.length == 0) {
							$(this).append(dropProxy);	
						}
						
						inDrop = true;
						return false;
					}
				});
				
				if (!inDrop) {
					dropProxy.detach();
				}
				
				return false;
			}); 
			$("body").mouseup(function(data) {
				var drop = dropProxy.closest(".lvDroppable");
				var drag = $(".lvDragging").removeClass("lvDragging");
				
				if (drop.length > 0) {
					if (e.data.settings.clone) {
						drag.removeAttr("style");
						dropProxy.after(drag);
					} else {
						dropProxy.after(original);
						drag.remove();
					}
				} else {
					drag.remove();	
				}
				
				if (e.data.settings.callback != "") {
					e.data.settings.callback($(original), drop, drag); 
				}
				
				$(this).unbind('mousemove').unbind(data);
				dropProxy.remove();
			});
			
			return false;
		}
	},
	mouseWithin : function(x,y,node) {
		var offset = node.offset();
		var height = node.outerHeight(true);
		var width = node.outerWidth(true);
		
		if (x > offset.left && x < offset.left + width && y > offset.top && y < offset.top + height) {
			return true;	
		} else {
			return false;	
		}
	}
}

svlv.google = {
	isMapVisible : function() {
		return $(".mapHolder .gmapBox").is(":visible");
	},
	toggleMap : function() {
		if (this.isMapVisible()) {
			this.hideMap();	
		} else {
			this.showMap();	
		}
	},
	showMap : function() {
		$(".mapHolder .gmapBox").show();
		initWidgetMap();
	},
	hideMap : function() {
		$(".mapHolder .gmapBox").hide();
	},
	goToPlacemark : function(num) {
		if (!this.isMapVisible()) {
			this.showMap();	
		}
		
		jQuery.scrollTo(".mapHolder", 400, {axis:"y", offset:-50});
		for(var i in placemarks) {
			placemark = placemarks[i][num];
		}
		
		placemark.marker.openInfoWindowHtml(placemark.marker.myInfoHTML);
	}
}

/*** Owen: This section is pretty ugly spaghetti code. If I had known I was going to use the same slider for both videos and photos I would have made it object oriented. Let me know if you encounter problems. ***/
svlv.vpt = {
	settings : {
		imagesLoaded : 0,
		selvideos : "ALL",
		youtubeacct : "lasvegas"
	},
	loadVideos : function(videoid) {
		var self = this;
		
		$.get("/includes/cfcs/controller/controller.cfm?object=vptObj&action=videoPane&selvideos="+self.settings.selvideos+"&youtubeacct="+self.settings.youtubeacct, function(html) {
			$(".vptVideoAjax").empty().html(html);
			if (videoid != "") {
				self.selectVideo(videoid);	
			} else {
				self.selectVideo($(".vptVideoAjax .photoItem").eq(0).attr("data-videoid"));	
			}
			
			$(".vptVideoAjax .photoWindow").scrollable({
				circular : true
			});
			
			$(".vptVideoAjax .photoItem").tooltip({ effect: "slide", opacity : ".9", predelay : 100 });
			
			$(".vptVideoAjax .photoItem").click(function() {
				self.selectVideo($(this).attr("data-videoid"));
			});
			
			var api = $(".vptVideoAjax .photoWindow").data("scrollable");
			var node = $(".vptVideoAjax .photoItem[data-videoid=" + videoid + "]");
			self.positionSlide(api, node);
			svlv.buildAjaxOverlay($(".videoShare"));
		});
	},
	cyclePhoto : function(num) {
		var index = 0;
		
		if ($(".vptPhotoAjax .photoContainer:visible").length) {
			index = parseInt($(".vptPhotoAjax .photoContainer:visible").attr("data-index"))-1;
		}
		
		var next = index + num;
		var totalPhotos = parseInt($(".vptPhotoAjax .photoContainer").length)-1;
		
		if (next > totalPhotos) {
			next = 0;	
		} else if (next < 0) {
			next = totalPhotos;
		}
		
		var photo = svlv.vpt.settings.photos[next];
		var nextId = photo.PHOTOID;
		
		this.selectPhotoById(nextId);
		var api = $(".vptPhotoAjax .photoWindow").data("scrollable");
		var node = $(".vptPhotoAjax .photoItem[data-index=" + next + "]");
		this.positionSlide(api, node);
	},
	selectVideo : function(videoid) {		
		for(var i = 0; i < svlv.vpt.settings.videos.length; i++) {
			if (svlv.vpt.settings.videos[i].videoid == videoid) {
				var video = svlv.vpt.settings.videos[i];
				var container = $(".vptVideoAjax .largeVideo");
				container.find("iframe").attr("src", "http://www.youtube.com/embed/" + video.videoid + "?wmode=transparent&rel=0");
				container.find("h2").html(video.title);
				container.find(".contentString").html(video.content);
				container.find(".dateString").html(video.published);
				$(".vptVideoAjax .photoItem").removeClass("current");
				$(".vptVideoAjax .photoItem[data-videoid=" + video.videoid + "]").addClass("current");
				svlv.misc.setHashVar("videoid", video.videoid);
				
				var siteName = 'Visit Las Vegas';
				if (typeof sv != 'undefined' && typeof sv.siteName != 'undefined') {
					siteName = sv.siteName;
				}
				
				var shareURL = "/includes/cfcs/controller/controller.cfm?object=shareContent&action=mailOverlay&subject=" + encodeURI(siteName+': Video Tour') + "&title=" + encodeURI('Share Video with a Friend') + "&url=" + encodeURIComponent(window.location.href);
				$(".vptVideoAjax .videoShare").attr("href", shareURL);
			}
		}
	},
	loadTour : function(tourid) {
		svlv.misc.setHashVar("tourid", tourid);
		this.settings.imagesLoaded = 0;
		$(".vptPhotoAjax").empty().html("<div class='loading' style='text-align: center;'><img src='/includes/images/shell/ajax-loader.gif'></div>");
		$.get("/includes/cfcs/controller/controller.cfm?object=vptObj&action=photoTour", { tourid : tourid }, function(data) {
			$(".vptPhotoAjax").empty().html(data);
			svlv.buildLvDropDown($(".vptFull select"));
			svlv.buildAjaxOverlay($(".photoShare"));
		});
	},
	selectPhoto : function(index) {
		if (svlv.vpt.settings.photos[i].photoid == photoid) {
			var photo = svlv.vpt.settings.photos[i];
			
			$(".vptPhotoAjax .photoContainer").hide();
			
			var container = $(".vptPhotoAjax .photoPaneTop").find(".photoContainer[data-index=" + index + "]");
			container.find("h2").html(video.title);
			container.fadeIn();
			$(".vptPhotoAjax .photoItem").removeClass("current");
			$(".vptPhotoAjax .photoItem[data-index=" + index + "]").addClass("current");
			
			var siteName = 'Visit Las Vegas';
			if (typeof sv != 'undefined' && typeof sv.siteName != 'undefined') {
				siteName = sv.siteName;
			}
			
			var shareURL = "/includes/cfcs/controller/controller.cfm?object=shareContent&action=mailOverlay&subject=" + encodeURI(siteName+': Photo Tour') + "&title=" + encodeURI('Share Photo with a Friend') + "&url=" + encodeURIComponent(window.location.href);
			$(".vptPhotoAjax .photoShare").attr("href", shareURL);
			
			svlv.misc.setHashVar("photoid", $(".vptPhotoAjax .photoItem.current").attr("data-photoid"));
		}
	},
	selectPhotoById : function(photoid) {
		var newPhoto = $(".vptPhotoAjax .photoPaneTop").find(".photoContainer[data-photoid=" + photoid + "]");
		
		$(".vptPhotoAjax .photoContainer").hide();
		$(newPhoto).show();
		
		for(var i = 0; i < svlv.vpt.settings.photos.length; i++) {
			if (svlv.vpt.settings.photos[i].PHOTOID == photoid) {
				var photo = svlv.vpt.settings.photos[i];
				var container = $(".vptPhotoAjax .photoPaneTop").find(".photoContainer[data-photoid=" + photoid + "]");
				container.find("h2").html(photo.TITLE);
				container.find(".dateString").html(photo.CREATEDATE);
				container.find(".contentString").html(photo.DESCRIPTION);
				
				$(".vptPhotoAjax .photoItem").removeClass("current");
				$(".vptPhotoAjax .photoItem[data-photoid=" + photoid + "]").addClass("current");
				svlv.misc.setHashVar("photoid", $(".vptPhotoAjax .photoItem.current").attr("data-photoid"));
				
				var siteName = 'Visit Las Vegas';
				if (typeof sv != 'undefined' && typeof sv.siteName != 'undefined') {
					siteName = sv.siteName;
				}
				
				var shareURL = "/includes/cfcs/controller/controller.cfm?object=shareContent&action=mailOverlay&subject=" + encodeURI(siteName+': Photo Tour') + "&title=" + encodeURI('Share Photo with a Friend') + "&url=" + encodeURIComponent(window.location.href);
				$(".vptPhotoAjax .photoShare").attr("href", shareURL);
			}
		}
	},
	initPhotos : function() {
		var self = this;
		var photoid = svlv.misc.getHashVar("photoid");
		if (photoid == "") {
			photoid = $(".vptPhotoAjax .photoItem").eq(0).attr("data-photoid");
		}
		
		self.sizeWindows();
		
		if (photoid != "") {
			self.selectPhotoById(photoid);
		} else {
			self.selectPhotoById($(".vptPhotoAjax .photoItem").eq(0).attr("data-photoid"));
		}
		
		$(".vptPhotoAjax .photoWindow").scrollable({
			circular : true
		});
		
		$(".vptPhotoAjax .photoItem").tooltip({ effect: "slide", opacity : ".9", predelay : 100 });
		
		$(".vptPhotoAjax .photoItem").click(function() {
			self.selectPhotoById($(this).attr("data-photoid"));
		});
		
		var api = $(".vptPhotoAjax .photoWindow").data("scrollable");
		var node = $(".vptPhotoAjax .photoItem[data-photoid=" + photoid + "]");
		self.positionSlide(api, node);
		svlv.buildAjaxOverlay($(".photoShare"));
	},
	initAjaxState : function() {
		var tourid = svlv.misc.getHashVar("tourid");
		var videoid = svlv.misc.getHashVar("videoid");
		
		if ($(".vptVideoAjax").length){
			this.loadVideos(videoid);
		}
		
		if ($(".vptPhotoAjax").length){
			if (tourid) {
				this.loadTour(svlv.misc.getHashVar("tourid"));
				this.settings.tourid = tourid;	
			} else {
				this.loadTour(this.settings.tourid);
			}
			$(".vptFull .lvDropDownFinal .lvOption[data-value=" + this.settings.tourid + "]").click();
		}
	},
	getInitialPhotoIndex : function() {
		var photoid = svlv.misc.getHashVar("photoid");
		
		if (photoid) {
			var index = $(".photoContainer[data-photoid=" + photoid + "]").attr("data-index");
			if (!index) {
				return 1;	
			} else {
				return index;
			}
		} else {
			return 1;	
		}
	},
	getInitialIndex : function() {
		if (svlv.misc.getHashVar("tab")) {
			var name = svlv.misc.getHashVar("tab");	
		} else {
			var name = "Video";	
		}
		
		var tabs = $(".vptTab");
		
		for (var i = 0; i < tabs.length; i++) {
			if (tabs.eq(i).attr("data-name") == name) {
				return i;
			}
		}
		
		return 1;
	},
	sizeWindows : function() {
		/*** 
		Owen: Image width cannot be got until window is loaded. In addition, hidden images have no width, thus we have to append them to a div off the screen and handle the modifications. It is certainly an imperfect solution, but I am unaware of a better way. If you find it, let me know.
		***/
		$("body").append("<div class='hiddenExchanger' style='position: absolute; left: -10000'></div>");
		$(".primaryPhoto").each(function() {
			$(this).find(".mainImage").appendTo(".hiddenExchanger");
			var width = $(".hiddenExchanger .mainImage").width();
			$(".hiddenExchanger .mainImage").prependTo($(this));
			$(this).width(width);
		});
		$(".hiddenExchanger").remove();
	},
	imageLoaded : function() {
		this.settings.imagesLoaded++;
		if (this.settings.imagesLoaded == $(".vptFull .mainImage").length) {
			this.initPhotos();	
		}
	},
	positionSlide : function(api, node) {
		/*** Owen: Ensures that the slider is currently displaying the selected node ***/
		var slides = api.getItems();
		
		for (var i = 0; i < slides.length; i++) {
			if (slides.eq(i).has(node).length > 0) {
				if (!slides.eq(i).is(":visible")) {
					slides.eq(i).closest(".vptPane").show();
					api.seekTo(i);
					slides.eq(i).closest(".vptPane").hide();
				} else {
					api.seekTo(i);
				}
			}
		}
	}
};

svlv.blog = {
	init : function() {
		this.prepareCaptions();
	},
	prepareCaptions : function() {
		$(".blogContent img").not(".nocaption").each(function() {
			if ($(this).attr("title") == "") {
				return true;
			}
			
			var caption = $("<div class='blogCaption'></div>");
			$(this).after(caption);
			caption.append($(this));
			caption.append("<p>" + $(this).attr("title") + "</p>");
			caption.width($(this).width());
			if ($(this).attr("align") == "left") {
				caption.addClass("floatleft");	
			} else if ($(this).attr("align") == "right") {
				caption.addClass("floatright");
			}
		});
	}
};
svlv.search = {
	 siteSearch : function(){
	 	var keyWord = $('#keyword').val();
		if(keyWord.length < 2){
			alert('Please Enter a Search Term')
			return true;
		}
		else{
			window.location = '/search/'+keyWord+'/';
		}
	}
};
svlv.forms = {
	convertDate : function(input, form, years) {
	
		if (typeof years === 'undefined') {
			years = 18;
		}
	
		input.hide();
		input.next().hide();
		
		var date = new Date();
		var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
		
		var monthSelect = $("<select name='alias_month'></select>");
		for (var i = 0; i < months.length; i++) {
			monthSelect.append("<option value='" + (i + 1) + "'>" + months[i] + "</option>");	
		}
		
		var daySelect = $("<select name='alias_day'></select>");
		for (var i = 1; i <= 31; i++) {
			daySelect.append("<option value='" + i + "'>" + i + "</option>");
		}
		
		var yearSelect = $("<select name='alias_year'></select>");
		
		var sdate = date.getFullYear() - years;
		
		for ( var i = sdate; i > sdate - 100; i--) {
			yearSelect.append("<option value='" + i + "'>" + i + "</option>");
		}
		
		input.after(yearSelect);
		input.after(daySelect);
		input.after(monthSelect);
		
		$("select[name='alias_month'], select[name='alias_day'], select[name='alias_year']").change(function(){
			var dateString = $("select[name='alias_month']").val() + "/" + $("select[name='alias_day']").val() + "/" + $("select[name='alias_year']").val();
			input.val(dateString);
		});
	}
};
svlv.misc = {
	getUrlParams : function(url) {
		url = typeof(url) == "undefined" ? window.location.href : url;
		url = url.replace(/#.*/, "");
		var paramString = url.match(/\?(.*)/ig);
		if (!paramString) {
			return {}; 	
		}

		var data = paramString[0];
		data = data.replace("?", "").split("&");
		var params = {};
		for(var i = 0; i < data.length; i++) {
			var internal = data[i].split("=");
			if (typeof(params[internal[0]]) != "undefined") {
				params[internal[0]] += "," + internal[1];	
			} else {
				params[internal[0]] = internal[1];
			}
		}
		
		return params;
	},
	getUrlBase : function(url) {
		var final = typeof(url) == "undefined" ? "" : url.replace(/#.*/,'');
		return final.replace(/\?.*/,'');
	},
	setUrlVar : function(name, value, url) {
		url = typeof(url) == "undefined" ? window.location.href : url;
		
		var base = this.getUrlBase(url);
		var params = this.getUrlParams(url);
		var hashparams = this.getHashParams(url);
		params[name] = value;
		
		return this.paramsToUrl(base, params, hashparams);
	},
	paramsToUrl : function(base, params, hashparams) {
		var data = [];
		var hashdata = [];
		var final = base;
		for (var i in params) {
			data.push(i + "=" + params[i]);
		}
		
		for (var i in hashparams) {
			hashdata.push(i + "=" + hashparams[i]);	
		}
		
		if (data.length > 0) {
			final += "?" + data.join("&");
		}
		
		if (hashdata.length > 0) {
			final += "#" + hashdata.join("&");	
		}
		
		return final;
	},
	getHashParams : function(hash) {
		hash = typeof(hash) == "undefined" ? window.location.hash : hash;
		var paramString = hash.match(/#(.*)/ig);
		if (!paramString) {
			return {}; 	
		}

		var data = paramString[0];
		data = data.replace("#", "").split("&");
		var params = {};
		for(var i = 0; i < data.length; i++) {
			var internal = data[i].split("=");
			if (typeof(params[internal[0]]) != "undefined") {
				params[internal[0]] += "," + internal[1];	
			} else {
				params[internal[0]] = internal[1];
			}
		}
		
		return params;
	},
	paramsToHash : function(params) {
		var data = [];
		for (var i in params) {
			if (i != "") {
				data.push(i + "=" + params[i]);
			}
		}
		
		window.location.hash = data.join("&");
	},
	getHashVar : function(name) {
		var hash = this.getHashParams();
		
		if (name in hash) {
			return hash[name];	
		} else {
			return "";	
		}
	},
	setHashVar : function(name, value) {
		var hash = this.getHashParams();
		
		hash[name] = value;
		
		this.paramsToHash(hash);
	},
	setCookie : function(name, value, days) {
		var expires = '';
		var domain = '';
		
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			expires = '; expires=' + date.toGMTString();
		}
		
		document.cookie = name + '=' + escape(value) + expires + '; path=/';
	},
	getCookie : function(name) {
		var nameEQ = name + '=';
		var ca = document.cookie.split(';');
		
		for (var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1, c.length);
			}
			
			if (c.indexOf(nameEQ) == 0) {
				return unescape(c.substring(nameEQ.length, c.length));
			}
		}
		
		return "";
	},
	setSameHeight : function(nodes) {
		var tallest = nodes.eq(1).height();
		for (var i = 0; i < nodes.length; i++) {
			if (nodes.eq(i).height() > tallest) {
				tallest = nodes.eq(i).height();	
			}
		}
		nodes.height(tallest);	
	},
	youtubeAddWmode : function(nodes) {
		nodes.each(function() {
			var src = $(this).attr("src");
			if ($(this).attr("src").match("http://www.youtube.com").length > 0) {
				if ($(this).attr("src").match("\\?") > 0) {
					var add = "&";	
				} else {
					var add = "?"	
				}
					
				$(this).attr("src", $(this).attr("src") + add + "wmode=transparent");
			}
		});
	},
	getKeyArray : function(arr,key) {
		var data = [];
		for(var i = 0; i < arr.length; i++) {
			data.push(arr[i][key]);	
		}
		
		return data;
	},
	readyImages : function(nodes, callback) {
		var total = nodes.length;
		var loaded = 0;
		var call = callback;
		
		if (total == 0) {
			callback();
			return false;
		}
		
		nodes.each(function() {
			var img = new Image();
			img.onload = function() { 
				loaded++;
				if (loaded == total) {
					callback();
					return false;
				}
			}
			
			img.src = $(this).attr("src");
		});
	}
};

svlv.ta = {
	settings : {},
	init : function() {
		svlv.ta.settings.root = $(".tripAdvisorTab");
		svlv.ta.contractAll();
		
		svlv.ta.settings.root.find(".expandClick").click(function() {
			svlv.ta.expandClick(this);
			return false;
		});
		
		svlv.ta.settings.root.find(".contractClick").click(function() {
			svlv.ta.contractClick(this);
			return false;
		});
	},
	expandClick : function(elem) {
		var node = $(elem);
		
		node.closest(".reviewsHolder").find(".review").show();
		node.closest(".reviewsHolder").find(".reviewSummary").hide();
	},
	contractClick : function(elem) {
		var node = $(elem);
		
		node.closest(".reviewsHolder").find(".review").hide();
		node.closest(".reviewsHolder").find(".reviewSummary").show();
	},
	expandAll : function() {
		svlv.ta.settings.root.find(".review").show();
		svlv.ta.settings.root.find(".reviewSummary").hide();
	},
	contractAll : function() {
		svlv.ta.settings.root.find(".review").hide();
		svlv.ta.settings.root.find(".reviewSummary").show();
	}
};

svlv.rowImageBoxes = {
	alreadyRun : false,
	init : function() {
		if (svlv.rowImageBoxes.alreadyRun) { return; }
		svlv.rowImageBoxes.alreadyRun = true;
		
		var t = false;
		var lastY = 0;
		
		var myY = 999;
		var numPerRow = 3;
		
		var firstInRow = false;
		var curRow = 0;
		var rowWidth = 0;
		var rowWidth2 = 0;
		var itemPadding = 0;
		
		var aw = $('.activities_wrap');
		
		aw.each(function(index, value)
		{
			t = $(this);
			
			if (myY >= numPerRow) {
				curRow++;
				firstInRow = false;
				myY = 0;
			}
			
			myY++;
			
			t.addClass('imgbox-row-'+curRow);
			if (firstInRow === false) {
				firstInRow = aw.filter('.imgbox-row-'+curRow).first();
				$("<div class='imgboxclear1' style='clear:both;'></div>").insertBefore(firstInRow);
			}
		});
		
		var lastm = false;
		
		for(x=1;x<=curRow;x++)
		{
			rowWidth2 = 0;
			
			var m = aw.filter('.imgbox-row-'+x);
			if ( m.length > 0 )
			{	
					m.css({ 'padding-left' : '0px', 'padding-right' : '0px' });
					m.first().addClass('nopad');
					
					if (m.length != 2) {
						m.last().addClass('nopad');
					}
					
					m.each(function(index, value)
					{
						rowWidth2 += $(this).outerWidth(true);
						
						/* last item in row */
						if (index + 1 == m.length) {
							/* not the last row on the page */
							if ( x < curRow ) {
								$("<div class='imgboxclear2' style='clear:both;height:1px;margin-bottom:20px;width:100%;background:#cdcdcd'></div>").insertAfter( m.last() );
							} else {
								$("<div class='imgboxclear3' style='clear:both;'></div>").insertAfter( m.last() );
							}
						}

					});
					
					var m2 = m.filter(':not(.nopad)');
				
					if (m.length == 2)
					{
						if (x == 1) {
							itemPadding = 31;
						} else {
							var firstRowItem = aw.filter('.imgbox-row-1:not(.nopad):first');
							itemPadding = parseFloat( firstRowItem.css('padding-left') );
						}
					}
					else
					{
						rowWidth = m.first().parent().width();
						itemPadding = parseFloat(rowWidth) - parseFloat(rowWidth2);
						itemPadding = itemPadding / m2.length / 2;
						itemPadding = Math.floor(itemPadding);
					}
					
					m2.css({ 'padding-left' : itemPadding+'px', 'padding-right' : itemPadding+'px' });
					
					lastm = m;
			}
				
		}
		
	}
};

/* for fixNavWidthsAlt to work with window zooming and resizing, should only be used in conjunction with fixNavWidthsAlt function */
jQuery.onWinZoom = (function ($) {

	$(document).bind("winzoom", function (event, data) {
		svlv.fixNavWidthsAlt();
		svlv.adjustTopNav();
	});

	return {
		/* public method -- it can be called in an iframe */
		trigger: function () {
			$(document).trigger("winzoom");
		}
	};
}) (jQuery);

function googleTranslateElementInit() {
	new google.translate.TranslateElement({
		pageLanguage: 'en',
		autoDisplay: true
	});
}

