// JavaScript Document
$(document).ready(function() {
	//$('body').addClass('winter'); Add the season specific class to the body tag.
	//Keyword Search Form. Not sure why Tom's original elegant version was failing on levels, but this more verbose version if working.
	//$("#keywords").search();
	$("#keywords").focus(function() {
		if ($(this).val() == 'FIND IT') {
			$(this).val('');
		}
		return false;
	});
	$("#keywords").blur(function() {
		if ($(this).val() == '') {
			$(this).val('FIND IT');
		}
		return false;
	});	
	$("#searchForm").validsearch();
	//Dropdowns show/hide
	supaNavLoader("/places-to-stay/drop-down/index.aspx","ptsDd",1);
	//Trip Planner Expander
	$("#tripPlannerBtn").live("click", function() {
		if($("#tripPlannerBtn").hasClass('opened')){
		  $(this).removeClass('opened');
		  $(this).css('background-position','bottom');
		  $('#tripPlannerDetails').removeClass('opened').slideUp();
		} else {
		  $(this).addClass('opened');
		  $(this).css('background-position','top');
		  $('#tripPlannerDetails').addClass('opened').slideDown();
		}
		return false;
	});
	$("#searchForm").submit(function() {
		//delete_cookie("prevSearch");
		//var deadCookieTest = get_cookie("prevSearch");
		keywordSearchFixes();
		return true;
	});
	$("#siteSearchSubmit").click(function() {
		//delete_cookie("prevSearch");
		//var deadCookieTest = get_cookie("prevSearch");
		keywordSearchFixes();
		return true;
	});
	//left nav display script - moved from external
	$('#secondaryNav ul li.firstGrade:last').addClass('last');	
	var secondNavTest = $('#secondaryNav').html()+' ';
	if(secondNavTest.indexOf('UL') == -1 && secondNavTest.indexOf('ul') == -1){
		$('#secondaryNav').remove();
	}
	//left side nav email scripts - moved from external
	$("#emailSignUp").validemail();
	$("#email").focus(function() {
		if ($(this).val() == 'Email Address') {
			$(this).val('');
		}
		return false;
	});
	$("#email").blur(function() {
		if ($(this).val() == '') {
			$(this).val('Email Address');
		}
		return false;
	});
	//right column empty div test script - moved from external.
	var itemCount = $('.rightColItem').length;
	items=new Array();
	for (i=1;i<=itemCount;i++) {
		if(i==1){
			items[i]=$('.rightColItem:first').html();
			$('.rightColItem:first').attr('id','rightColItem'+i);
		} else {
			var iterationFixer = i-1;
			items[i]=$('.rightColItem:eq('+iterationFixer+')').html();
			$('.rightColItem:eq('+iterationFixer+')').attr('id','rightColItem'+i);
		}
	}
	for (i=1;i<=itemCount;i++) {
		if(items[i].indexOf('H2') == -1 && items[i].indexOf('h2') == -1){
			$('#rightColItem'+i).remove();
		}
	}
});
function keywordSearchFixes(){
	delete_cookie("prevSearch");
	var deadCookieTest = get_cookie("prevSearch");
	var submittedKeywords = $("#keywords").val();
	var ampLoop = submittedKeywords.indexOf('&');
	while (ampLoop != -1){
		submittedKeywords = submittedKeywords.replace('&','%26');
		ampLoop = submittedKeywords.indexOf('&');
	}	
}
//Clear input box plugin.
$.fn.search=function(){return this.focus(function(){if(this.value==this.defaultValue){this.value=""}}).blur(function(){if(!this.value.length){this.value=this.defaultValue}})};

//validate search on submit
$.fn.validsearch=function(){return this.submit(function(){
if(this.elements['keywords'].value==''||this.elements['keywords'].value==this.elements['keywords'].defaultValue){$("p.tryagain").html("Please enter a keyword before submitting").fadeIn(300);setTimeout('$("p.tryagain").fadeOut()', 5000);return false}})};
//validate email on submit
$.fn.validemail=function(){return this.submit(function(){
if(this.elements['email'].value==''||this.elements['email'].value==this.elements['email'].defaultValue||this.elements['email'].value.indexOf('@')==-1||this.elements['email'].value.indexOf('.',this.elements['email'].value.indexOf('@'))==-1){$("p.tryagain2").html("Please enter a valid email address").fadeIn(300);setTimeout('$("p.tryagain2").fadeOut()', 5000);return false}})};

function validNumber (myNumber){
	if (myNumber == ''){
		myNumber = 0;
	}
	if(parseInt(myNumber)!=myNumber-0){
		return false;
	} else {
		return true;
	}
}

//dropdown for absurdly impractical ultra mega primary navigation dropdowns
$.fn.supaNav=function(){
	return this
	.hoverIntent(
		function () {if ($(this).children('div')) {$(this).children('div').slideDown(300);}},
		function () {$(this).children('div').slideUp(300)});
};
function supaNavLoader(sourcePage,targetDiv,sequence){
	if (sequence == 1 || sequence == 2 || sequence == 3){
		$.ajax({
		  url: sourcePage,
		  cache: true,
		  success: function(html){
			$("#"+targetDiv).html(html);
			if (sequence == 1){
				supaNavLoader("/things-to-do/drop-down/index.aspx","ttdDd",2);
			} else if (sequence == 2) {
				supaNavLoader("/where-to-go/drop-down/index.aspx","wtgDd",3);
			} else if (sequence == 3){
				$('#primaryNav ul li:has(div)').supaNav();
			} else {
				//nothing
			}
		  }
		});
	} else {
		//nothing
	}
};

//Star rater
$.fn.stars=function(r_field){
	return this
	.hover(
		function () {$(this).prevAll().andSelf().addClass('hover')},
		function () {$(this).prevAll().andSelf().removeClass('hover')}
	)
	.click(
		function () {
			var rating = $(this).text();
			$(r_field).attr('value',rating);	
			$(this).siblings().removeClass('active');
			$(this).prevAll().andSelf().addClass('active');
		}
	)
};

// hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+ <http://cherne.net/brian/resources/jquery.hoverIntent.html | author Brian Cherne <brian@cherne.net>
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:6000,interval:150,timeout:500};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

// Cookie retrieval and deletion
function get_cookie(cookie_name) {
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
	if (results)
		return ( unescape ( results[2] ) );
	else
		return null;
};
function delete_cookie(cookie_name) {
	var cookie_date = new Date ( );  
	cookie_date.setTime ( cookie_date.getTime() - 1 );
	document.cookie = cookie_name += "=; path=/; expires=" + cookie_date.toGMTString();
};

//automatic jQuery cookies if you don't feel like parsing them yourself - credit: Klaus Hartl (stilbuero.de)...Klaus is representin' DEUTSCHLAND!!!
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};

//BarkleyREI AJAX Click function 1.0
$.fn.rei_ajax_click=function(templateId, targetId, loadingId){
	return this.click(function(){
		$(loadingId).fadeIn(100);
		var datasource = "/TemplateMarkupCallbackHandler.ashx?templateId=" + templateId + "&amp;",
			datasource = datasource.replace("amp;", ""),
			href = $(this).attr("href").split("?");
			//set cookie, expires in 4:30min
			$.cookie('results_url', datasource + href[1], {expires:.003});
		$.ajax({
			type: "GET",
			url: datasource + href[1],
			dataType: "html",
			success: function(html){
				$(targetId).html(html);
				$(loadingId).hide();
			}
		});
		return false;
	});
};

// Add to planner button
$.fn.plan_btn_add=function(planner_name, status){
	$(this).click(function() {
		//messages						
		var success_msg = "This item has been added to your " + planner_name + ".";
		var fail_msg = "Submission of this item to your " + planner_name + " failed. Please try again.";
		var error_msg = "Error. Submission of this item to your " + planner_name + " may have timed out. Please try again or check your " + planner_name + " to make sure it has been added.";
		//send
		
		jQuery.ajax({
			url: this.href,
			timeout: 10000,
			error: function() {$(status).html(error_msg).fadeIn(300);status_timeout();},
			success: function(r) { 
				if (r == "success=true") {
					$(status).html(success_msg).fadeIn(300);
					
					//update tp dropdown
					$("#tripPlanner").load("/gettransform.ashx?templateId=23");
					
					status_timeout();}
				else if (r == "success=false") {$(status).html(fail_msg).fadeIn(300);status_timeout();}
			}
		});
		return false;
	})
	function status_timeout() {setTimeout('$("' + status + '").fadeOut()', 3000);};
};

// Add to planner form 
$.fn.plan_submit=function(planner_name, status){
	$(this).submit(function() {
		var form = "#" + this.id;
		//messages
		var success_msg = "Checked item(s) have been added to your " + planner_name + ".";
		var fail_msg = "Submission failed. Please ensure that you have checked an item and try again.";
		var error_msg = "Error. Submission of these items to your " + planner_name + " timed out. Please try again or check your " + planner_name + " to make sure it has been added.";
		//gather checkbox values
		var inputs = [];		
		$(':input', this).each(function() {
			if($(this).attr("checked") && !($(this).attr("disabled")))  {
				inputs.push(this.name + '=' + escape(this.value));
			}
		});
	  	//send
		jQuery.ajax({
			data: inputs.join(unescape('%26')),
			url: this.action,
			timeout: 10000,
			error: function() {$(status).html(error_msg).fadeIn(300);status_timeout();},
			success: function(r) { 
				if (r == "success=true") {
					$(status).html(success_msg).fadeIn(300);
					$(form + ' :input').each(function() {
						if($(this).attr("checked"))  {
							$(this).attr({disabled: "disabled",value: ""});	
							//$(this).parent("li").hide();
						};
					});
					//update tp dropdown
					$("#tripPlanner").load("/gettransform.ashx?templateId=23");
					status_timeout();
				}
				else if (r == "success=false") {$(status).html(fail_msg).fadeIn(300);status_timeout();}
			}
		});
		return false;
	});
	function status_timeout() {setTimeout('$("' + status + '").fadeOut()', 3000);};
};


// Add to event calendar button
$.fn.event_btn_add=function(planner_name, status){
	$(this).click(function() {
		//messages						
		var success_msg = "This item has been added to your " + planner_name + ".";
		var fail_msg = "Submission of this item to your " + planner_name + " failed. Please try again.";
		var error_msg = "Error. Submission of this item to your " + planner_name + " may have timed out. Please try again or check your " + planner_name + " to make sure it has been added.";
		//send
		jQuery.ajax({
			url: this.href,
			timeout: 10000,
			error: function() {$(status).html(error_msg).fadeIn(300);status_timeout();},
			success: function(r) { 
				if (r == "success=true") {
					$(status).html(success_msg).fadeIn(300);
					
					status_timeout();}
				else if (r == "success=false") {$(status).html(fail_msg).fadeIn(300);status_timeout();}
			}
		});
		return false;
	})
	function status_timeout() {setTimeout('$("' + status + '").fadeOut()', 3000);};
};

//These aren't really necessary, and they can probably just be deleted
//BarkleyREI AJAX Submit function 1.0
$.fn.rei_ajax_submit=function(templateId, targetId, loadingId){
	return this.submit(function(){
		$(loadingId).fadeIn(100);
		var datasource = "/gettransform.ashx?templateId=" + templateId + "&amp;",
			datasource = datasource.replace("amp;", ""),
			formdata = $(this).serialize();
			//set cookie, expires in 4:30min
			$.cookie('results_url', datasource + formdata, {expires:.003});
		$.ajax({
			type: "GET",
			url: datasource + formdata,
			dataType: "html",
			success: function(html){
				$(targetId).html(html);
				$(loadingId).hide();
			}
		});
		return false;
	});
};

//BarkleyREI AJAX State Restore 1.0
function restore_ajax_state(targetId, loadingId) {
	if ($.cookie('results_url') != null) {
		$(loadingId).fadeIn(100);
		$.ajax({
			type: "GET",
			url: $.cookie('results_url'),
			dataType: "html",
			success: function(html){$(targetId).html(html);$(loadingId).hide();}
		});
	};
};

//REI AJAX Seondary Form Set Cookie
$.fn.rei_ajax_second_form=function(templateId, cookiePath){
	return this.submit(function(){
		var datasource = "/gettransform.ashx?templateId=" + templateId + "&amp;",
			datasource = datasource.replace("amp;", ""),
			formdata = $(this).serialize();
		//set cookie, expires in 4:30min
		$.cookie('results_url', datasource + formdata, {path:cookiePath, expires:.003});
		return true;
	});
};

function cookiekiller(deliciousCookies) {
	$.cookie('results_url', '', {path:deliciousCookies, expires: -1}); 
}

