$(window).load(function(){
	$('#pre-footer').append('<ul id="twitter_update_list"/>');
	$.getScript("http://twitter.com/javascripts/blogger.js", function(){
		$.getScript("http://twitter.com/statuses/user_timeline/woodmarkhotel.json?callback=twitterCallback2&count=1");
	});
});

function lastMinuteTravel(url){
	$.pageTracker._trackPageview('Last_Minute_Travel');
	window.open(url, 'lastminute');
}

function randomInnerPhoto(complete)
{
	$('.featured-photo-container img').hide();
	$.ajax({
		cache: true,
		complete: function(req, status){
			var list = req.responseText.split('\n');
			
			$('.featured-photo-container img').attr('src', $('link').attr('href').substring(0, $('link').attr('href').lastIndexOf('assets/index.php') + 11) + list[ Math.round(Math.random() * list.length + 1) ]).show();
			
			if(complete && $.isFunction(complete))
			{
				complete();
			}
		},
		async: false,
		dataType: "json",
		url: $('link').attr('href').substring(0, $('link').attr('href').lastIndexOf('assets/index.php') + 11) + 'json/inner_photo.txt'
	});
}

$(function(){
	if ( DOMAIN_TRACKING ) {
		var trackDomains = DOMAIN_TRACKING.split(',');
		for (var i=trackDomains.length-1;i>=0;i--) {
			$('a[href*="'+trackDomains[i]+'"], form[action*="'+trackDomains[i]+'"]').addClass('track-crossdomain');
		}
	}

	// Tracking email links / set email as the name
	$('a[href^="mailto:"]').each(function(){
		$(this).attr('name',$(this).attr('href')).addClass('track');
	});
	
	$('.track, .track-crossdomain').each(function() {
		var tag = '';
		if ( this.name ) {
			tag = '/'+this.name.replace(/:/g,'/');
		}
		if($(this).is('form')) {
			var a = $(this).attr('action');
			$(this).submit(function() {
				if (tag) { pageTracker._trackEvent('form', 'submit', tag); }
				if ( $(this).hasClass('track-crossdomain') ) {
					$(this).attr({action:a+'?'+$(this).serialize(), method:'post'});
					pageTracker._linkByPost(this);
				}
			});
		} else {
			$(this).click(function(e) {
				if (tag) { pageTracker._trackEvent('link','click', tag); }
				if ( $(this).hasClass('track-crossdomain') ) {
					e.preventDefault();
					var l = pageTracker._getLinkerUrl(this.href);
					$(this).attr('target')=='_blank'?window.open(l,''):window.location=l;
				}
			});
		}
	});

	//Modal
	$("#fall-promo-modal").each(function() {
		var windowWidth = ($(window).width()-$(this).width())/2;
		$(this).css('left',windowWidth);
		$(this).css('top','120px');
		$(this).jqm({closeClass:'fall-promo-close,overlay:100'}).jqmShow();
	});
		   
	$('.booknow').click(function(){
		$.pageTracker._trackPageview('Book_Now');
	});
	
	/*$('#menu-main a').each(function(i){
		if( this.href == location.href || ((location.href.lastIndexOf('index.php') == location.href.length - 1) && (this.href == location.href + 'index.php' || this.href + 'index.php' == location.href)) || ( location.href.indexOf(this.href.substring(0,this.href.lastIndexOf('index.php'))) > -1 && i > 0 ) )
		{
			$(this).addClass('selected');
		}
	});*/
	
	$('#menu-inner-left li a').each(function(){
		if( this.href == location.href || ((location.href.lastIndexOf('index.php') == location.href.length - 1) && (this.href == location.href + 'index.php' || this.href + 'index.php' == location.href)) )
		{
			$(this).addClass('selected');
		}
	});
	
	$('.toggler').hide();
	$('body').prepend($('#toggle-container'));
	var active = null;
	$('.togglebtn').click(function(){
		var last_active = active;
		if(last_active) {
			last_active.slideUp('normal');
		}
		active = $(this.rel);
		$('.togglebtn').removeClass('toggled');
		
		if( (last_active && last_active[0] != active[0]) || !last_active)
		{
			$(this).addClass('toggled');
			active.slideDown('normal');
		} else {
			active.slideUp('normal');
			active = null;
		}
		return false;
	});
	
	randomInnerPhoto();
	
	$('#banner-slideshow').cycle({
		fx: 'fade',
		speed: 700,
		timeout: 7000
	});
	
	$("#features").easySlider({
		vertical: false,
		continuous: true,
		speed: 600,
		auto: true,
		pause: 7000
	});
	
	var newSelection = "";
	$(".events-calendar-info a").click(function(){
		$(".events-calendar-boxes").fadeTo(200, 0.10);
			$(".events-calendar-info a").removeClass("current");
			$(this).addClass("current");
			newSelection = $(this).attr("rel");
			$(".events-calendar-boxes").not("."+newSelection).slideUp();
			$("."+newSelection).slideDown();
		$(".events-calendar-boxes").fadeTo(600, 1);
	});
	
	// first param is API KEY
	// second param is group ID
	$.flickrGroup('6254be35907c25f700e498d52ee57e55','1401495@N24',{
		per_page: 30
	});
	
	$("#tabs").tabs({ fx: { opacity: 'toggle' } });
	
	swfobject.embedSWF("../assets/flash/propertymap/propertymap.swf", "tour", "100%", "400", "9.0.0", "../assets/flash/expressInstall.swf", { xml: '../assets/flash/propertymap/propertymap.xml' }, {
		menu: 'false',
		wmode: 'opaque'
	});
	
	//gallery
	$('#gallery-menu a').click(function(){
		$('#gallery-menu a').removeClass('selected');
		$(this).addClass('selected');
		
		window.location.hash = $(this).attr('href');
		
		swfobject.embedSWF("../assets/swf/gallery.swf", "galleryPhoto", "100%", "100%", "9.0.0", "assets/flash/expressInstall.html", {
			xml: 'images.php',
			gallery : $(this).attr('href').substring(1)
		}, {
			menu: 'false',
			wmode: 'opaque'
		});	
		
		return false;
	});
	
	swfobject.embedSWF("../assets/swf/gallery.swf", "galleryPhoto", "100%", "100%", "9.0.0", "assets/flash/expressInstall.html", {
		xml: 'images.php',
		gallery : window.location.hash.substring(1) == '' ? 'exterior' : window.location.hash.substring(1)
	}, {
		menu: 'false',
		wmode: 'opaque'
	});	
	
	$("#sub-menu-exterior").addClass("selected");
	
	$('.date-picker').datepicker({ 
		showAnim: "slide", 
		showOptions: { 
			direction: "left" 
		},
		gotoCurrent: true,
		hideIfNoPrevNext: true,
		numberOfMonths: 2,
		showOn: "both",
		highlightWeek: true,
		dateFormat: 'mm/dd/yy',
		buttonImage: "/assets/graphics/icon-cal.gif",
		buttonImageOnly: true
	});
	
	// Booking console - Check availability promo code click button
	$("form#reservations-console").each(function(){
		var x = $(this);
		$("a#promo-click", x).click(function(){
			$("#dropdown-fields",x).show();
			return false;
		});
		$("#extra-fields-close").click(function() {
			$("#dropdown-fields",x).hide();
			return false;
		});
	});
	$("#promo-done-btn").click(function(){
		$("#dropdown-fields").hide();
		if ($('#group-code').val() || $('#promo-code').val() || $('#iata-number').val()) {
			$("#promo-click").addClass("selected-promo-click");
		} else {
			$("#promo-click").removeClass("selected-promo-click");
		}
		return false;
	});
	
	$.fn.expand = function(options) {
		var defaults = {
			openText: 'View Details',
			closeText: 'Hide Details',
			longClass: '.package-long'
		},
		opts = $.extend(defaults, options);
		return this.each(function() {
			var obj = $(this);
			var tog = $('<div />').addClass('toggle');
			var control = $('<a />').attr('href', '#')
							.addClass('toggler')
							.html(opts.openText)
							.appendTo(tog)
							.toggle(function() { $(opts.longClass, obj).slideDown('slow'); $(this).html(opts.closeText).addClass('open'); },
									function() { $(opts.longClass, obj).slideUp('slow'); $(this).html(opts.openText).removeClass('open'); });
			
			$(opts.longClass, obj).after(tog).hide();
		});
	};

	$.fn.packagePreview = function(options) {
		return this.each(function() {
			$('a.package-details', this).toggle(function(event) {
				event.preventDefault();
				$('.share-panel').hide();
				var el = $(this);
				el.html('Hide Details');
				$(this).addClass('active').parent().addClass('active').parent().find('.package-long').slideDown('slow');
				
			},function(event) { 
				event.preventDefault();
				$('.share-panel').hide();
				var el = $(this);
				el.html('View Details');
				$(this).removeClass('active').parent().removeClass('active').parent().find('.package-long').slideUp('slow');
			});
		});
	};
	
	$.fn.eventPreview = function(options) {
		return this.each(function() {
			$('a.view-details', this).toggle(function(event) {
				event.preventDefault();
				$('.share-panel').hide();
				var el = $(this);
				el.html('<em class="alt">Hide Details</em>');
				$(this).addClass('active').parent().parent().find('.event-description').slideDown('slow');
				
			},function(event) { 
				event.preventDefault();
				$('.share-panel').hide();
				var el = $(this);
				el.html('<em class="alt">View Details</em>');
				$(this).removeClass('active').parent().parent().find('.event-description').slideUp('slow');
			});
		});
	};

	$.fn.initializeSharing = function() {
		return this.each(function() {
			$('.share-link').live('click',function(event) {
				event.preventDefault();
				$('.share-panel').hide();
				$(this).parents('.rss-item').find('.share-panel').css('display','inline');
			});
			$('.share-close').live('click',function(event){
				event.preventDefault();
				$(this).parents('.rss-item').find('.share-panel').slideUp('fast');
			});
		});
	};
	
	
// Validates the form, adding warning icons where needed and alerting user upon completion
	$(".validate").submit(function() {
		var counter = 0;
		var first_error = "";
		
		// find all elements with class name of "required" within all divs with a class of field
		$(this).find("div.field .required").each(function() { 
			// remove any previous warnings and validate based on element type
			$.removeWarning($(this));
			if ( ($(this).is("input")) || ($(this).is("select")) || ($(this).is("textarea")) ) {
				var valid = true;
				var o = $(this).val().replace(/^\s+|\s+$/g, '');

				if ($(this).is(".email")) {
					// if it's an email address make sure the email is valid using both regular expressions
					var regExp = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
					var regExp2 = /(\s+)|(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
					if ( ( o.search( regExp ) ) == -1 || o.search( regExp2 ) != -1 ) {
						valid = false;
					}
				} 
				else if ($(this).is(".select-other") && $(this).val() == "--" && $(this).parent().next().find("input").val().replace( /(^\s+)|(\s+$)/g, '' ).length < 1 ) {
					$.addWarning($(this).parent().next().find("input"));
				} 
				else if ( ($(this).next().is(".icon-cal")) && (o.replace( /(^\s+)|(\s+$)/g, '' ).length < 1 || o == "mm/dd/yyyy") ) {
					// if it's a date field
					valid = false;
				} 
				else if (o.replace( /(^\s+)|(\s+$)/g, '' ).length < 1) {
					// if not an email address take out funky characters and see if its still blank
					valid = false;
				}
				// if the data is not valid show warning icon
				if (!valid) {
					$.addWarning($(this));
					counter++;
					if ( first_error == "" ) {
						first_error = $(this).attr("id");
					}		
				}
				
			}
			else if ( $(this).is("ul") ) {
				// This is for checkboxes
				$(this).each(function() { 
					// find all elements w/required class name
					var valid = false;
					$(this).find("li").each(function() {
						// checkboxes in the list
						var testdis = $(this).children("input");
						//if not an "other" pair
						if ( testdis.length == 1 ) {
							if ( $(testdis).attr("checked") == true ) {
								valid = true;
							}
						}
						//it is an "other"
						else {
							if ( $(testdis[0]).attr("checked") && $(testdis[1]).val().replace( /(^\s+)|(\s+$)/g, '' ).length > 0 ) {
								valid = true;
							}
						}
					});
					if(!valid) { 
						$.addWarning($(this));
						counter++;
						if ( first_error == "" ) {
							first_error = $(this).attr("id");
						}
					}
				});			
			}
		});
		if ( counter > 0 ) {
			alert( "A valid " + $('#'+first_error).parent().children('label').html().replace(":","").replace("*","") + " is required." );
			$('#'+first_error).focus();
			return false;
		}
		
	 if($(this).hasClass('signup-destdelivers')){
			var first = $('#first_name').val();
			var last = $('#last_name').val();
			var email = $('#email').val();
			var zip = $('#zip').val();
			var ddpage = 'http://www.destinationdelivers.com/signup/?firstname='+first+'&lastname='+last+'&email='+email+'&zip='+zip;
			window.open(ddpage);
		}	
	});
	
	
// Removes the Warning Icon
	jQuery.removeWarning = function(el) {
		// find img elements, if it's present, remove it
		$(el).parents(".field").find("img.validation-error").remove();
	};
	
// Adds the Warning Icon
	jQuery.addWarning = function(el) {
		//alert($(el).attr("id"));
		var img = "<img />";
		// adds the source and class attributes
		img = $(img).attr("src", "/images/icon-warning.gif").addClass("validation-error");	
		// Add the image after the input field
		// if el is part of checkbox group put it after the first list item
		if( $(el).is("ul") ) {
			$(el).find("li:first").append(img);
		}
		// if not throw it at the end
		else {
			$(el).parent().append(img);
		}
	};
	
	//If the URL has a hash (anchor) bit, scroll to that.
	if ( window.location.hash ) {
		$.scrollTo(window.location.hash);
	}

});
