	var messageInABottle = false;	
	
	jQuery(document).ready(function($){

	
	
			// this prepopulates the dates in calendars if there are dates in the querystring
			if ( getCalendar("depart") || getCalendar("depart2") || getCalendar("depart3") || getCalendar("depart4") ) {
					if ( getCalendar("depart") )
					{
						active_depart = 'depart';
						active_return = 'return';
					}
					else if ( getCalendar("depart2") )
					{
						active_depart = 'depart2';
						active_return = 'return2';
					}
					else if ( getCalendar("depart3") )
					{
						active_depart = 'depart3';
						active_return = 'return3';
					}
					else if ( getCalendar("depart4") )
					{
						active_depart = 'depart4';
						active_return = 'return4';
					}
					
					if ( $_get("day").length > 0 && $_get("yearmonth").length > 0 )
					{					
						_departday = parseInt( $_get("day") , 10) + 1;
						_returnDay = _departday + 14;
						_returnYearMonth =  $_get("yearmonth") ;
						if ( _returnDay > 28 ) {
							_returnYearMonth = mdf_fixMonth( _returnDay, _returnYearMonth );
							_returnDay = mdf_fixDay( _returnDay, _returnYearMonth );
						}
						_departdate = escape($_get("yearmonth") + "/" + ( _departday ));
						_returndate = escape( _returnYearMonth + "/" + ( _returnDay ));
						split_yearmonth = $_get("yearmonth").split("/");
						split_returnYearMonth = _returnYearMonth.split("/");

						if($_get("rtnDate").length > 0)
						{
							_returnDay = parseInt( $_get("day") , 10) + 1;
							_returnYearMonth =  $_get("yearmonth") ;
							
							if($_get("rtnDateAuto").length > 0)
							{
								var _myDate = $_get("rtnDate").split("/");
								_returnDay = parseInt(_myDate[2],  10);
								_returnYearMonth =  _myDate[0] + "/" + _myDate[1];
								_returnYearMonth = mdf_fixMonth( _returnDay, _returnYearMonth );
							}
							else
							{
								_departday = _returnDay - 14;
								var _departYearMonth =  $_get("yearmonth") ;
								if ( _departday < 1 ) {
									_departYearMonth = mdf_fixMonth( _departday, _departYearMonth );
									_departday = mdf_fixDay( _departday, _departYearMonth );
								}
								_departdate = escape( _departYearMonth + "/" + ( _departday ));
								split_yearmonth = _departYearMonth.split("/");
							}
							_returndate = escape( _returnYearMonth + "/" + ( _returnDay ));
							split_returnYearMonth = _returnYearMonth.split("/");
						}

						
						// set the values in the flight search box
						getCalendar( active_depart )._setDate( split_yearmonth[0], split_yearmonth[1] - 1, _departday );
						getCalendar( active_return )._setDate( split_returnYearMonth[0], split_returnYearMonth[1] - 1, _returnDay );
					}
					if ( $_get("TravelClass") )
						$("#TravelClass").val( $_get("TravelClass") );
					if ( !messageInABottle && $_get("showreturnmessage") ) {
							$("#booking_form table.tabledata").prepend("<tr><td colspan=4><p style=\"font-size: 120%; font-weight: bold; color: #000;\">Select your return date and press Search Flights to check availability.</p></td></tr>");
							messageInABottle = true;
					}
			}
            
            // Hide the oneway selector if the query string has suggested so
            if ( $_get("hideoneway") )
            {
                $( 'label[for=TripTypeOneWay], #TripTypeOneWay').remove();
                $( '#TripTypeReturn' ).hide();
                $( 'label[for=TripTypeReturn]' ).append(' Airfare').wrapInner('<span></span>');
            }
            
            if ( $_get("hd_showtips") )
            {
                $( '#priceinfo').remove();
                $('p.df_tip').html('<strong>Tip:</strong> You can add your hotel after flights are selected.');
                $('.df_note').hide();
                $( '#tips' ).show();
            }
            if ( $_get("showtips") )
            {
                $( '#priceinfo').remove();
                $('p.df_tip').html('<strong>Tip:</strong> Enter Your Return Date');
                if($_get("rtnDateAuto").length > 0 && $_get("rtnDateAuto") != "true")
                	$('p.df_tip').html('<strong>Tip:</strong> Price based on return date shown');
                
                $( '#tips' ).show();
            }            
            
        if ( $_get("dftip") )
	{
		//$( '#dftip' ).show();
	}
        if ( $_get("CarCityFrom")){
            $('#CarCityFrom').val($_get("CarCityFrom"));
        }        
            
            // Grey out all fields except return date if the query string has suggested so
           
            if ( $_get("lockallfieldsexceptreturn") || $_get("lockallfieldsexceptreturnandorigin") )
            {
                var elements = 'input[name=CityFrom], input[name=CityTo], select[name=CityTo], select[name=TravelClass]';
                if(!$_get("lockallfieldsexceptreturnandorigin"))
                {
                    elements += ', select[name=CityFrom]';
                }
                $( elements ).each(function(){
                   var input = ('<input type="hidden" name="' + $(this).attr('name') + '" id="' + $(this).attr('id') + '" value="' + $.trim($(this).val()) + '" />');
                   var text = $.trim($(this).val().toUpperCase());
                   if($(this).attr('name') == 'CityFrom' || $(this).attr('name') == 'CityTo')
                   {
                       if( airports[text] )
                           text = airports[text];
                   }
                   var theText = text.toLowerCase();
                   if(theText == "premiumeconomy")
                   	theText = "premium economy";
                   var span = $('<span>' + theText + '</span>').css('text-transform','capitalize');
                   $(this).before(input).before(span).remove();
                });
                
               // put a yellow background on the return date
              
               
               // Tweak some styles to make it look nice after all the abuse above. It's messy but it works
               $('#booking_form td[width=230]').css('width', '190px');
               $('#booking_form td.classrow').css({height: '25px', paddingTop: '9px'});
               
               // set the month to the same as the depart month and blank out the day
               if($_get("rtnDate").length == 0)
               {
    
               		$('#return2_month').prepend('<option value=""></option>').val('');
               		$('#return2_day').prepend('<option value=""></option>').val('');
               		$('#return2_day,#return2_month').css('background','#ffffad');
               	
               }
               else
               {
               	if ( $_get("showtips") && !$_get("dftip") )
            	{
               		$('p.df_tip').html('<strong>Tip:</strong> Enter Your Departure Date');
               	}
			if($_get("rtnDateAuto").length > 0){
				//Do Nothing
			}
			else
               		{
				$('#depart2_month').prepend('<option value=""></option>').val('');
				$('#depart2_day').prepend('<option value=""></option>').val('');
				$('#depart2_day,#depart2_month').css('background','#ffffad');
			}
               }
               	 
                
               // add validation to the return day now that we've added a blank option
               $("form.validate_flight_search").submit( function(){
                    
                    if($("input[name=TripType]:checked").val() == "Return")
                    {
                    
			    if ( $("#return2_day", this).val() == "" ) {
				alert( "Please select a return date");
				$("#return2_day", this).focus();
				return false;
			    }
			    if ( $("#return2_month", this).val() == "" ) {
				alert( "Please select a return month");
				$("#return2_month", this).focus();
				return false;
			    }
		    }
                    
                    
               });
            }
			
	});
	
	function mdf_fixDay( day, monthyear ) {
										
			dateparts = monthyear.split("/");
			month = dateparts[1];
			year = dateparts[0];
			
			if ( (month == 2 && day > 1))
					return parseInt(day, 10) - 28;
			else if ( day > 29 )
					return parseInt(day, 10) - 29;
			else if ( day < 1 )
					return parseInt(day, 10) + 28;
			else
					return day;		
	
	}
	
	function mdf_fixMonth( day, monthyear) {
	
			dateparts = monthyear.split("/");
			month = dateparts[1];
			year = dateparts[0];
			
			if ( (month == 2 && day > 1) || day > 29 ) {
					var returnMonth = parseInt(month * 1, 10) + 1;
					var returnYear = year;
					if ( returnMonth > 12 ) {
							returnMonth = 1;
							returnYear = parseInt(returnYear) + 1;
					}
					return returnYear + "/" + returnMonth;
	
			} else if (day < 1)
			{
				var returnMonth = parseInt(month * 1, 10) - 1;
				var returnYear = year;
				if(returnMonth < 1)
				{
					returnMonth = 12
					returnYear = parseInt(returnYear) - 1;
				}
				
				return returnYear + "/" + returnMonth;
			}
			else {
					
				return monthyear;		
			}
	
	}
