$(function() {
	//Global variables
	
	URCHIN = typeof(pageTracker)=='undefined'?true:false;

	$('.track').each(function() {
		var tag = '/'+this.name.replace(/:/g,'/');
		if($(this).is('form')) {
			var a = $(this).attr('action');
			$(this).submit(function() {
				URCHIN?urchinTracker(tag):pageTracker._trackEvent('form', 'submit', tag);
				if(tag.indexOf("reservations")>0) {
					//$(this).attr({action:a+'?'+$(this).serialize(), method:'post'});
					URCHIN?__utmLinkPost(this):pageTracker._linkByPost(this);
				}
			});
		} else {
			$(this).click(function(e) {
				URCHIN?urchinTracker(tag):pageTracker._trackPageview(tag);
				if(tag.indexOf("reservations")>0) {
					e.preventDefault();
					var l = URCHIN?__utmLinkerUrl(this.href):pageTracker._getLinkerUrl(this.href);
					$(this).attr('target')=='_blank'?window.open(l,''):window.location=l;
				}
			});
		}
	});
	
	$.id = function(id){  return document.getElementById(id);	 }
	var newheight = 0;

	// Table Stripe
	$("tr:nth-child(odd) td").addClass("odd-row");
	$("tr td:nth-child(odd)").addClass("first-td");
	$("tr:nth-child(odd) td:nth-child(even)").addClass("odd-row-td");
	$("tr:nth-child(even) td:nth-child(even)").addClass("even-row-td");


	$("div#flash-masthead").flash({src:"flash/home.swf", width:583, height:480, wmode:"transparent", quality:"high"}, {version:"7"});
	$("div#photo-gallery").flash({src:"flash/photogallery/photo_gallery.swf", width:490, height:430, wmode:"transparent", quality:"high"}, {version:"7"});

	// Sifr Font
	jQuery('div.meeting-content h3.meeting-rooms-header').sifr( { strSWF: './flash/minion-pro.swf', strColor: '#5e5036', strCase: 'upper', strWmode:'transparent' } );
	jQuery('div#header h3').sifr( { strSWF: './flash/minion-pro.swf', strColor: '#b2996e', strCase: 'upper', strWmode:'transparent' } );
	jQuery('div#content h3').sifr( { strSWF: './flash/minion-pro.swf', strColor: '#b2996e', strCase: 'upper', strWmode:'transparent' } );


	// Rotating Tabs
	// Finds Heights of All Push Marketing elements
	$(this).find(".push-item").each(function() { 
		var currentheight = this.offsetHeight;
		if (currentheight > newheight) {
			newheight = currentheight;
		}
	});
	// Adds room for tabs
	newheight = (newheight + 41)+ "px";

	// Initialize tabs in celebrate container and change Height of Celebrate for the longest push marketing element
	$('#celebrate').css("height", newheight).tabs({ fx: { opacity: 'toggle' } }).tabs( 'rotate' , 5000 );

	// Finds a form on the page and instantiates a Calendar Popup
	// if it is present
	$(this).find("form").each(function() { 
		if ( window.CalendarPopup ) {
			// instantiate CalendarPopup and set some params
			
			// Sets starting date by yesterdays date
			var yesterday = new Date();
			yesterday.setDate( yesterday.getDate() - 1 );
			
			// new instance of Calendar popuu
			cal = new CalendarPopup( "cp" );
			cal.addDisabledDates( null, formatDate( yesterday, "MM/dd/yyyy" ) );
			
			// create the <div> for calendar popup
			var d = document.createElement( "div" );
			d.id = "cp";
			document.body.appendChild( d );
		}
	});

	// For Input Elements that need a calendar, but no calendar Icon
	// Simply put a class on each input and put that class name in the
	// function below
	$(".makeitpopup").click(function() {
	    $(this).next().click();
	    return false;
	});



	// For Input Elements w/a calendar icon
	// Put the class name of the span where the Icon will leave
	// preferrably behind the input

	$(this).find(".form-cal").each(function(i) {
		var format = ( $(this).parents('form').is('#booking') ) ? 'yyyy-MM-dd' : 'MM/dd/yyyy',
		    sep = (format == 'yyyy-MM-dd' ? '-' : '/'),
		    icon = '<a href="#" class="icon-cal" id="form-cal-' + i + '" name="form-cal-' + i + '" title="Click to select a date"><img src="images/icon-cal.gif" /></a>';
		$(icon).appendTo($(this).parent()).click(function(){
			//hide all dropdowns for IE6 and lower
			if (document.all && window.ActiveXObject && !window.opera) { /*$(this).parents("form").find("select").css("visibility","hidden");*/ }

			var o = this.previousSibling;
			while (o.nodeType != 1) { o = o.previousSibling; }
			var clickinput;
			// check to see if it is an arrival/departure pair
			if($(o).is(".date-end")) {
				clickinput = 'depart';
				var arrive_string = $(o).parent().prev(".field").children(".date-begin").attr("value");
				var arrive_label = $(o).parent().prev(".field").children("label").html().replace(":","");
				//check to see if begin date has been set already and adjust disabled/current dates
				if (arrive_string != format.toLowerCase() && arrive_string != format.toLowerCase() && arrive_string) {
					var arrive_array = arrive_string.split(sep);
					var arrive_date = new Date(
					    sep == '-' 
					    ? arrive_array[1]+'/'+arrive_array[2]+'/'+arrive_array[0]
					    : arrive_array[0]+'/'+arrive_array[1]+'/'+arrive_array[2]
					);
					var arrive_date = formatDate(arrive_date, format );
					cal.clearDisabledDates();
					cal.addDisabledDates( null, arrive_date );
					
					cal.select(o,$(this).attr("id"),format, arrive_date);
					return false;
				}
				// begin date not set first, so pull label text and alert
				else {
					alert("Please select \"" + arrive_label + "\" first");
					if (document.all && window.ActiveXObject && !window.opera) { $(this).parents("form").find("select").css("visibility","visible"); }
					return false;
				}
			}
			// it's just a plain calendar popup
			else {
				clickinput = 'arrive';
				cal.clearDisabledDates();
				var yesterday = new Date();
				yesterday.setDate( yesterday.getDate() - 1 );
				cal.addDisabledDates( null, formatDate( yesterday, format ) );
				cal.select( o,$(this).attr("id"), format, yesterday );
				
				return false;
			}
		});
		$(this).remove();
	});


	// Validates the Forms and lets the user know which
	// form fields they have problems with
	$(".validate").submit(function() {
		var counter = 0;
		var first_error = "";
		
		// find all elements w/field class name
		$(this).find(".field").each(function() { 
			// find all elements w/required class name
			$(this).find(".required").each(function() { 
				// if the element is not a label do it
				$.removeWarning($(this));
				if ( ($(this).is("input")) || ($(this).is("select")) ) {
					// This part is for input, select, and textareas

					var valid = true;
					var o = $(this).val();
	
					if ($(this).attr("id") == "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(".date-picker")) && (o.replace( /(^\s+)|(\s+$)/g, '' ).length < 1 || o == "yyyy-mm-dd") ) {
						// 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 it is checked do this
							if(testdis.attr("checked") == true){
								valid = true;
							}
						});
						if(!valid) { 
							$.addWarning($(this));
							counter++;
							if ( first_error == "" ) {
								first_error = $(this).attr("id");
							}		
						}
					});					
				}
			});
		});
		if ( counter > 0 ) {
			var el = $('#' + first_error);
			if ( el.is('#arrive') || el.is('#depart') ) {
			    var label = $('#' + first_error).prev();
			    alert( label[0].title );
			} else {
			    alert( "One or more required fields were not correctly supplied. Please double-check the noted fields." );
			}
			$.id(first_error).focus();
			return false;
		}		
	});


	// Removes the Warning Icon
	jQuery.removeWarning = function(io) {
		// find img elements, if it's present, remove it
		var testwar = $(io).parents(".field").find("img.validation-error").remove();
	};
	
	// Adds the Warning Icon
	jQuery.addWarning = function(inputObject) {
		var img = "<img />";
		// adds the source attribute
		img = $(img).attr("src","images/icon-warning.gif");
		// adds the validation error class
		img = $(img).attr("class","validation-error");	
		// Add the image after the input field
		//if inputObject is part of checkbox group put it after the first list item
		if( $(inputObject).is("ul") ) {
			$(inputObject).find("li:first").append(img);
		}
		// if not throw it at the end
		else {
		    if ( !$(inputObject).is('.date-picker') ) {
			$(inputObject).parent().append(img);
		    }
		}
		// if the focus hasn't been set, set focus to first problem area
		/*if ( first_error == "" ) {
			first_error = $(inputObject).attr("id");
		}*/		
	};


	// For Each Package Wrapper add A Toggle Function if Neccessary
	$("div.package-wrapper").each(function() {
	// Div for the Toggler to be Held
	$(this).append("<div class=\"package-toggle\" style=\"clear:both;\">");

		// If this is a package that is going to be expanded
		// add a control for it
		if( $(this).is(".package-expandable") ) {
			// Since this is expandable hide the details
			$(this).find("div.package-long").hide();
			// Add the Control
			$(this).find(".package-toggle").append("<a class=\"view_details\" href=\"#\">View Details</a>");
		}
	});


	// Once the Package Toggler Control is clicked
	// Toggle the details and chance the text
	$("div.package-toggle a").toggle(function() {
		$(this).ancestors("div.package-wrapper").find("div.package-long").animate({
			height: 'show',
			opacity: 'show'
		}, 'slow');
		// Changes the Text of the Control
		$(this).html("Hide Details");
	}, function() {
		$(this).ancestors("div.package-wrapper").find("div.package-long").animate({
			height: 'hide',
			opacity: 'hide'
		}, 'slow');
		// Changes the Text of the Control
		$(this).html("View Details");
	});


	//Dropdowm menu
    $("ul#nav-primary li").hover(
        function(){ $("ul", this).show("fast"); }, 
        function(){ } 
    );


	if (document.all) {
		$("ul#nav-primary li").hoverClass("sfHover");
	}
});


$.fn.hoverClass = function(c) {
    return this.each(function(){
        $(this).hover( 
            function() { $(this).addClass(c); },
            function() { $(this).removeClass(c); }
        );
    });
};   
