// Default JS Content - Do Not Delete
$(document).ready(function() {
	$('#newsletterapp').load('/i/SITE_090210_09180337_N8I1W/newsletter.cfm', function() {
		$('.ajax').css({'display':'none'});
	});
});


$(function(){
	$('form.signup-small').submit(function(){
		document.location.href = 'http://www.canyonranch.com/email_signups/new_email_signup_information/?email='+$(this).find('input').val();
		return false;
	});
$('[placeholder]').focus(function() {
  var input = $(this);
  if (input.val() == input.attr('placeholder')) {
    input.val('');
    input.removeClass('placeholder');
  }
}).blur(function() {
  var input = $(this);
  if (input.val() == '' || input.val() == input.attr('placeholder')) {
    input.addClass('placeholder');
    input.val(input.attr('placeholder'));
  }
}).blur().parents('form').submit(function() {
  $(this).find('[placeholder]').each(function() {
    var input = $(this);
    if (input.val() == input.attr('placeholder')) {
      input.val('');
    }
  })
});
});


var currentPromo = 1;
var pause = false;
function switchToPromo(promo,clicked){
	if(promo != currentPromo)
		{	
			if(clicked)
				pause = true;
			$('#hpromo'+currentPromo).css('z-index','2');
			$('#hpromo'+promo).css('z-index','1').show();
			$('#buttonhpromo'+promo).attr('src',$('#buttonhpromo'+promo).attr('src').replace(/home_promo_selector.gif/,'home_promo_selector_on.gif'));
			$('#hpromo'+currentPromo).fadeOut(1500);
			$('#buttonhpromo'+currentPromo).attr('src',$('#buttonhpromo'+currentPromo).attr('src').replace(/home_promo_selector_on.gif/,'home_promo_selector.gif'));
			currentPromo = promo;
		}
}

window.onload = function(){
$(document).ready(function(){
	var startAutoScroll = function(){
		if(!pause){
			var nextPromo = currentPromo+1;
			if ($('#hpromo'+nextPromo).length==0) nextPromo=1;
			switchToPromo(nextPromo);
			setTimeout(startAutoScroll,9000);
		}
	}
	if($('#hpromo1').length)
	setTimeout(startAutoScroll,4000);
	
	$('#checkInDate').datepicker({
		minDate:0,
		showAnim: 'slideDown'
	});
	$('#checkInButton').click(function(){$('#checkInDate').datepicker("show");});
	var addZero = function(to){
		return to<10?'0'+to:to;
	};
	$('#checkInDate').datepicker("setDate",new Date(new Date())).change();
});
}


if(typeof roivista_init=="function")roivista_init("ROIV-000030-1");
/*
 * jQuery replaceText - v1.1 - 11/21/2009
 * http://benalman.com/projects/jquery-replacetext-plugin/
 * 
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($){$.fn.replaceText=function(b,a,c){return this.each(function(){var f=this.firstChild,g,e,d=[];if(f){do{if(f.nodeType===3){g=f.nodeValue;e=g.replace(b,a);if(e!==g){if(!c&&/</.test(e)){$(f).before(e);d.push(f)}else{f.nodeValue=e}}}}while(f=f.nextSibling)}d.length&&$(d).remove()})}})(jQuery);

/*This code takes any matching example of the 1-800 number and replaces it IF the user has come from an email campaign link
 $(document).ready(function(){
   $('*').replaceText( /\b800-742-9000\b/gi, myPhoneNumber = typeof roivista_number=="string"?roivista_number:"800-742-9000" );
   var myImage = typeof roivista_number=="string"?roivista_image:"http://www.canyonranchtucson.com/i/SITE_090324_09592775_U1PW4/templates/phone.gif";
   $('#tollFreeNumber').attr('src',myImage);
   var myAlt = typeof roivista_number=="string"?roivista_number:"800-742-9000";
   $('#tollFreeNumber').attr('alt',myAlt);
   $('#tollFreeNumber').attr('title',myAlt);

});
*/
$.expr[':'].icontains = function(obj, index, meta, stack){
	return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
};

$(document).ready(function(){

	$('.expandHeader').click(function(){
		var t = $(this);
		var down = t.find('img[src$="arrow.png"]');
		if(down.length){
			down.attr('src',down.attr('src').replace(/arrow.png/,'arrow_up.png'));
		}else{
			var up = t.find('img[src$="arrow_up.png"]');
			if(up.length)
				up.attr('src',up.attr('src').replace(/arrow_up.png/,'arrow.png'));
		}
		t.nextAll().each(function(){
			var t2 = $(this);
			if(t2.hasClass('expandSubHeader')){
				t2.slideToggle({complete:function(){moveBox();}});
			}else if(t2.hasClass('expandSubHeaderText')){
				t2.has(':visible').slideUp();
			}else if(t2.hasClass('expandHeaderText')){
				t2.slideToggle({complete:function(){moveBox();}});
				/* Peekaboo Bug Fix */
				if($.browser.msie)
					t2.find('i,em,b').css({'min-width':0});
			}else{
				return false;
			}
		});
	});
	$('.expandSubHeader').click(function(){
		var t = $(this);
		var down = t.find('td[background$="subheader.gif"]');
		if(down.length){
			down.attr('background',down.attr('background').replace(/subheader.gif/,'subheader_up.gif'));
		}else{
			var up = t.find('td[background$="subheader_up.gif"]');
			if(up.length)
				up.attr('background',up.attr('background').replace(/subheader_up.gif/,'subheader.gif'));
		}
		t.nextAll().each(function(){
			var t2 = $(this);
			if(t2.hasClass('expandSubHeaderText')){
				t2.slideToggle({complete:function(){moveBox();}});
				/* Peekaboo Bug Fix */
				if($.browser.msie)
					t2.find('i,em,b').css({'min-width':0});
			}else{
				return false;
			}
		});
	});
});
/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

$(document).ready(function(){
	var minLength=3;
	var maxResults=100;
	var currentResult=0;
	var clearSearch = function(){
		/* Remove previous higlights */
		$('.highlighted').each(function(){
			var $t = $(this);
			$t.replaceWith($t.text());
		});
		/* Collapse all sections */
		$('.expandHeaderText,.expandSubHeaderText,.expandSubHeader').hide();
		/* Change all arrows */
		$('.expandSubHeader td[background$="subheader_up.gif"]').each(function(){
			var $t = $(this);
			$t.attr('background',$t.attr('background').replace(/subheader_up.gif/,'subheader.gif'));
		});
		$('.expandHeader img[src$="arrow_up.png"]').each(function(){
			var $t = $(this);
			$t.attr('src',$t.attr('src').replace(/arrow_up.png/,'arrow.png'));
		});
		rC.html('');
		moveBox();
	};
	$('.expandHeaderText,.expandSubHeaderText').addClass('searchWithin');
	var rC = $('#resultCount');
	$('#findonpage').keyup(function(){
		currentResult=-1;
		if(this.value.length >= minLength){
			clearSearch();
			var searchText = this.value;
			var regx = new RegExp("(" + searchText + ")", 'gi');
			var selector = '.searchWithin p:icontains("' + searchText + '")';
			var c = 0;
			$(selector).each(function(i) {
				c++;
				if(i>maxResults)
					return false;
				var $t = $(this);
				var text = $t.html();
				text = text.replace(regx, '<span class="highlighted">$1</span>');
				$t.html(text);
				
				/* Find the Parent */
				var $p = $t.closest('.searchWithin');
				$p.show();
				/* Find the Header */
				var $h = $p.prevAll('.expandHeader:first');
				$h.nextUntil('.expandHeader').filter('.expandSubHeader,.expandHeaderText').show();
				var down = $h.find('img[src$="arrow.png"]');
				if(down.length)down.attr('src',down.attr('src').replace(/arrow.png/,'arrow_up.png'));
				/* If we're in a subheader, find show the relevant arrow */
				if($p.hasClass('expandSubHeaderText')){
					var down = $p.prev().find('td[background$="subheader.gif"]');
					if(down.length)down.attr('background',down.attr('background').replace(/subheader.gif/,'subheader_up.gif'));
				}
			});
			if(c>0)
				rC.html(c+' results. <a href="#" id="clearSearch">Clear search.</a>');
			else
				rC.html('No results found.');
			$('#clearSearch').click(function(){$('#findonpage').val('');clearSearch();return false;});
		}else{
			clearSearch();
		}
	});
	
	/* Next and Previous Buttons */
	var goToResult = function(){
		$('.active').removeClass('active');
		var $n = $('.highlighted:eq('+currentResult+')');
		$n.addClass('active');
		$.scrollTo($n.offset().top-60,{duration:500});
	};
	$('.nextbtn').click(function(){
		currentResult++;
		if(currentResult>$('.highlighted').length)
			currentResult = 0;
		goToResult();
	});
	$('.prevbtn').click(function(){
		currentResult--;
		if(currentResult<0)
			currentResult = $('.highlighted').length-1;
		goToResult();
	});
	
	/* Scroll The search bar */
	
	var d = $(document);
	var el = $('#findonpageBox');
	moveBox = function(){
		el.css({'marginTop':0});
		var nM = d.scrollTop()-diff;
		if(nM<0)nM=0;
		el.css({'marginTop':nM});
	};
	if(el.length){
		var diff = el.offset().top;
		$(window).scroll(moveBox);
	}
	
	$('.expandSubHeaderText,.expandHeaderText').each(function(){
		var $t = $(this);
		$t.append('<p align="center" class="copy"><a href="#" class="closeButton">- close -</a></p>');
	});
	
	$('.closeButton').click(function(){
		var $t = $(this);
		$t.closest('.expandSubHeaderText,.expandHeaderText').prev().click();
		return false;
	});
	
});

$(document).ready(function(){
	$('a[href^="https://booking.ihotelier.com/istay/istay.jsp"]').click(function (event) {
		IHLink($(this).attr('href'));
		event.preventDefault();
	});
});

function IHLink(theUrl){
	_gaq.push(function() {
        var tracker = _gat._getTrackerByName(); 
        window.open(tracker._getLinkerUrl(theUrl));
     });
}

function postBookingForm(oForm){
	var qs = "";
	qs = qs + "?hotelid="	+ oForm.HotelID.value;
	qs = qs + "&datein=" 	+ oForm.DateIn.value;
	qs = qs + "&length=" 	+ oForm.Length.value;
	qs = qs + "&Adults=" 	+ oForm.Adults.value;
	qs = qs + "&Children=" 	+ oForm.Children.value;
	 _gaq.push(function() {
        	var tracker = _gat._getTrackerByName(); 
			window.open(tracker._getLinkerUrl('https://booking.ihotelier.com/istay/istay.jsp' + qs));
     	 });
	}

 	$(document).ready(function() {
		var startDate = new Date();
		$("#calArrivalDateField").attr("value", startDate.format("yyyy-mm-dd"))
		$("#calArrivalDateField").datepicker({
			minDate:0,
			showAnim: "fadeIn",
			dateFormat: 'yy-mm-dd',
			showOn: 'both',
			buttonText: 'Select Date',
			buttonImage: '/miamibeach/i/SITE_090324_10192315_AQO1G/templates/btn_cal.gif',
			buttonImageOnly: true
		});

		
		$('#resform2').submit(function() {
			var nights 			= 	$('#nights').val();
			var checkInDate 	= 	$("#calArrivalDateField").datepicker('getDate');
			
			if(checkInDate == null)
				{
					var tDate = new Date();
					$("#calArrivalDateField").attr("value", tDate.format("yyyy-mm-dd"))
					checkInDate 	= 	$("#calArrivalDateField").datepicker('getDate');
				}

				var eDate			= 	new Date(checkInDate.getTime() + (nights*24*60*60*1000));
				var	checkOutDate 	=	eDate.format("yyyy-mm-dd");
				var qs = "";
				
				//set the departure date into the form field
				$("#calDepartureDateField").val(checkOutDate);
				//assemble the url string for the google ananlytic call			
				qs = qs + "&calArrivalDateField=" + checkInDate.format("yyyy-mm-dd");
				qs = qs + "&calDepartureDateField=" + checkOutDate;
				//call google for the url
				_gaq.push(function() 
					{
						var tracker = _gat._getTrackerByName();
						var myTrackURL = tracker._getLinkerUrl('https://www.yourreservation.net/tb3/relocate.cfm?bf=Canyonranch&language=EN&quick=quick&prsRoomCount=1' + qs + '&rateAccessCode=*S1$|*S2$|*S3$|*S10$|*L60$|*L08$');
						window.open(myTrackURL);
					});
				
			return false;

		});
	
	});
//date formatting functions
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};
