function toDoubleDigit(num) {
	(String(num).length < 2) ? num = String("0" + num) :  num = String(num);
	return num;		
}
function generateReturnDate(value) {
	return_date = new Date(value);
	return_date.setDate(return_date.getDate() + 7);
	display_date = toDoubleDigit(return_date.getMonth() + 1) + "/" + toDoubleDigit(return_date.getDate()) + "/" + return_date.getFullYear();
	return display_date;
}

var slideshow = null; // IE was breaking without this...

Event.addBehavior.reassignAfterAjax = true;
Event.addBehavior({
	
	/* Form Validations
	-----------------------------------------------------*/
	'form.validate': Validator(),
	
	/* Links to be opened in a new window
	-----------------------------------------------------*/
	'a.new_window': function() {
		this.target = "_blank";
	},
	
	/* Popup Windows
	-----------------------------------------------------*/
	'a.whats_this': Popup({width: '500', height: '760'}),
	'a.send_to_bride': Popup({width: '780', height: '600'}),
	'a.email_to_friend': Popup({width: '800', height: '600'}),
	'a.about_these_tags': Popup({width: '780', height: '600'}),
	'a.no_fees': Popup({width: '500', height: '500'}),
	'a.printable_honeymoon': Popup({width: '800', height: '760'}),
	
	/* Homepage match form
	-----------------------------------------------------*/
	'#start': function() {
		$('honeymoon-type').hide();
	},
	
	'a#slick-show:click': function() {
		$('honeymoon-type').toggle();
		$('destination').down('select').toggle();
		return false;
	},
	
	'a#slick-hide:click': function() {
		$('honeymoon-type').hide();
		$('destination').down('select').show();
		return false;
	},
	
	'input.departure_date:focus': function() {
		this.up('form').down('input.return_date').value = generateReturnDate(this.value);
	},
	'input.departure_date:blur': function() {
		var current_date = new Date();
		if(new Date(this.value) < current_date) {
			this.value = toDoubleDigit(current_date.getMonth() + 1) + "/" + toDoubleDigit(current_date.getDate()) + "/" + current_date.getFullYear();
			this.up('form').down('input.return_date').value = generateReturnDate(this.value);
		}
	},
	
	/* Tabs
	-----------------------------------------------------*/		
	'a.btn_tab:click': function() {
		link = this;
		Element.insert(link, {top: "<img src='/images/small-spinner.gif' width='10' height'10' id='tab_loader' /> "});
		new Ajax.Request(link.href, 
			{
				method:'get',
				onComplete: function() {
					$$('#tabs a').each(
						function(tab) {
							tab.removeClassName("selected");
						}
					);
					link.addClassName("selected");
					$('tab_loader').remove();
				}
			}
		);
		return false;
	},
	
	/* Itineraries
	-----------------------------------------------------*/
	'.itinerary-content': function() {
		this.hide();
		$$('.itinerary-content').first().show();
		$$('#itinerary-tabs a').first().addClassName("selected");
	},
	
	'#itinerary-tabs a:click': function() {
		$$('.itinerary-content').invoke('hide');
		$(this.href.split("#")[1]).show();
		$$('#itinerary-tabs a').each(
			function(tab) {
				tab.removeClassName("selected");
			}
		);
		this.addClassName("selected");
		$('hdr_current_itinerary').innerHTML = this.innerHTML;
		return false;
	},
	
	/* Slideshows
	-----------------------------------------------------*/
	'#slideshow': function() {
		slideshow = new Slideshow(this);
	},
	
	'#slideshow_links a:click': function() {
		if(this.hasClassName("flickr_link")) {
			this.target = "_blank";
		} else {
			slideshow.swapSlideShow(this);
			return false;
		}
	},
	
	'.image_links a:click': function() {
		if(this.hasClassName("flickr_link")) {
			this.target = "_blank";
		} else {
			slideshow.swapImage(this);
			return false;
		}
	},
	
	/* Honeymoon Planner
	-----------------------------------------------------*/	
	/* Add Forms */
	'a.btn_toggle_notneeded_form:click': function() {
		this.up('p').next('div.toggle_add_form').show();
		return false;
	},
	'.toggle_add_form a.btn_cancel:click': function() {
		if(this.up('div.toggle_add_form').previous('a.btn_toggle_add_form')) {
			this.up('div.toggle_add_form').previous('a.btn_toggle_add_form').show();
		}
		this.up('div.toggle_add_form').hide();
		return false;
	},
	'a.btn_toggle_flight_form:click': function() {
		// this.up('div').down('div.booking_form').toggle();
		showBookingForm(this.up('p').next('.add-flight'));
		return false;
	},
	'.booking_form a.btn_cancel:click': function() {
		// this.up('.booking_form').hide();
		hideBookingForm(this.up('.booking_form'));
		return false;
	},
	'.booking_form a.close:click': function() {
		// this.up('.booking_form').hide();
		hideBookingForm(this.up('.booking_form'));
		return false;
	},
	
	
	/* Note Forms */
	'a.btn_toggle_note_form:click': function() {
		this.up('p.mynotes').hide();
		this.up('p.mynotes').next('div.toggle_note_form').show();
		return false;
	},
	'a.btn_toggle_add_note_form:click': function() {
		this.hide();
		this.next('div.toggle_note_form').show();
		return false;
	},
	'.toggle_note_form a.btn_cancel:click': function() {
 		if(this.up('div.toggle_note_form').previous('p.mynotes')) {
 			this.up('div.toggle_note_form').previous('p.mynotes').show();
 		} else {
 			this.up('div.toggle_note_form').previous('a.btn_toggle_add_note_form').show();
 		}
 		this.up('div.toggle_note_form').hide();
 		return false;
	},	
	
	/* Change Password
	-----------------------------------------------------*/
	'a.change_password:click': function() {
		this.next('.password_form').show();
		return false;
	},
	'a.forgot_password:click': function() {
		$('form_forgot_password').show();
		$('form_sign_in').hide();
		return false;
	},
	'#form_forgot_password a.btn_cancel:click': function() {
		$('form_forgot_password').hide();
		$('form_sign_in').show();
		return false;
	},
		
	/* Next Step Drop Down
	-----------------------------------------------------*/
	'a.nextstep:click': function() {
		$('next_step_drop_down').toggle();
		return false;
	},
	'a.close_drop_down:click': function() {
		$('next_step_drop_down').toggle();
		return false;
	},
	
	/* Destination Landing Nav
	-----------------------------------------------------*/
	'ul.region li a:click': function() {
		// Make sure we have subs
	
		$$('.destination_details').each( function(d) {
			d.hide();
		});		
		$(this.readAttribute('id')+'_details').show();
	
		if(this.next('ul')) {
			$(this.readAttribute('id')+'_details').show();
			$$('ul.region li ul').invoke("hide");
			this.next('ul').toggle();

			goto_and_load_destination($(this).readAttribute( 'id'))
		}
		else {
			goto_and_load_sub_destination($(this).readAttribute( 'id'));
		}
		return false;
	},
	
	'a#destinations_by_weather:click': function() {
		new Ajax.Request('/destinations/by_weather?date=' + $('dd').getValue() + '&travel_risk=' + $('travel_risk').getValue(),
		{
			method:'get',
			onSuccess: function(transport){
				var response = transport.responseText;
				var map_data = eval('(' + response + ')');
				load_map_data(map, map_data.properties, false );
			},
			onFailure: function(){ alert("I'm sorry but we were unable to process your request. Please check your date format and try again.") }
		});
		return false;
	},

	/* Newsletter Input
	-----------------------------------------------------*/
	'input.newsletter_email:focus': function() {
		if(this.value == "Enter your email") {
			this.value = "";
		}
	},
	'input.newsletter_email:blur': function() {
		if(this.value == "") {
			this.value = "Enter your email";
		}
	},
	
	/* Send to Bride Form
	-----------------------------------------------------*/
	'input#first_name:blur': function() {
		message = $('message');
		if(message && message.value.include('X')) {
			new_message = message.value.sub('X', this.value);
			message.value = new_message;
		}
	},
		
	/* Careers
	-----------------------------------------------------*/
	'ul.career-list a.main:click': function() {
		this.next('span.career-info').toggle();
		this.toggleClassName("active-career");
		return false;
	},
	'ul.career-list a.close_job:click': function() {
		li_object = this.up('li');
		li_object.down('span.career-info').toggle();
		li_object.down('a').toggleClassName("active-career");
		return false;
	},
	
	/* FAQs
	-----------------------------------------------------*/
	'ul.about-faq a.faq-link:click': function() {
		this.up('div').next('div.answer').toggle();
		this.up('li').toggleClassName("active");
		return false;
	},
	'ul.about-faq a.close:click': function() {
		this.up('div.answer').toggle();
		this.up('li').toggleClassName("active");
		return false;
	},
	
	/* Sub Destination Details
	-----------------------------------------------------*/
	'a.sub-destination_more:click' : function() {
		hideTabs();
		showTab($('tab-details'));
		activateTabLink($('details_link'));
	},
	
	/* Match pagination when not logged in
	-----------------------------------------------------*/
	'a.page_link:click' : function() {
	  $('page_hidden_field').setAttribute('value', this.readAttribute('href') );
    $('match_form').submit();
	  return false;
	},
	
	/* Booking Forms
	-----------------------------------------------------*/
	'a.btn_booking_form:click': function() {
		// this.up('div').down('div.booking_form').toggle();
		showBookingForm(this.up('div').down('div.booking_form'));
		return false;
	},
	'a.btn_booking_form_cancel:click': function() {
		// this.up('div.booking_form').toggle();
		showBookingForm(this.up('div.booking_form'));
		return false;
	},
	'form.hotel_search_form:submit': function() {
	  var property_dom_id = this.identify().slice(0, (this.identify().length-18));

		if($(property_dom_id+'_departure_city').getValue().endsWith(')')) {
			var airport_text = $(property_dom_id+'_departure_city').getValue();
			var code = airport_text.slice(-4, -1);
			$(property_dom_id+'_departure_city').value = code;
		}
		$(property_dom_id+'_profile_origin').value = this.action + "?" + this.serialize();
		$(property_dom_id+'_profile_form').submit();
		return false;
	},
	'form#activity_search_form:submit': function() {
		$('profile_origin').value = $('search_form').action + "?" + $('search_form').serialize();
		$('profile_form').submit();
	},
	'input.toggle_flights:click': function() {
	  var property_dom_id = this.up('form').identify().slice(0, (this.up('form').identify().length-18));

		if($(property_dom_id + '_air_checkbox').value == 'false') {
			 $(property_dom_id + '_air_checkbox').value = 'true';
			 $(property_dom_id + '_roundtrip').value = 'true';
			 $(property_dom_id + '_departure_field').show();
		} else {
			$(property_dom_id + '_air_checkbox').value = 'false';
			if($(property_dom_id + '_car_checkbox').value == 'false') {
				$(property_dom_id + '_roundtrip').value = 'false';
				$(property_dom_id + '_departure_field').hide();
			}
		}
	},
	'input.toggle_rental_cars:click': function() {
	  var property_dom_id = this.up('form').identify().slice(0, (this.up('form').identify().length-18));
		if($(property_dom_id + '_car_checkbox').value == 'false') {
			$(property_dom_id + '_car_checkbox').value = 'true';
			$(property_dom_id + '_roundtrip').value = 'true';
			$(property_dom_id + '_departure_field').show();
		} else {
			$(property_dom_id + '_car_checkbox').value = 'false';
			if($(property_dom_id + '_air_checkbox').value == 'false') {
				$(property_dom_id + '_roundtrip').value = 'false';
				$(property_dom_id + '_departure_field').hide();
			}
		}
	},
	'a.flight_booking_form:click': function() {
		// this.next('div.booking_form').toggle();
		showBookingForm(this.next('div.booking_form'));
		return false;
	},
	'a.flight_booking_form_cancel:click': function() {
		// this.up('div.booking_form').toggle();
		showBookingForm(this.up('div.booking_form'));
		return false;
	},
	'form#flight_search_form:submit': function() {
		if($F('departure_city').endsWith(')')) {
			var airport_text = $F('departure_city');
			var code = airport_text.slice(-4, -1);
			$('departure_city').value = code;
		}
		$('profile_origin').value = $('hotel_search_form').action + "?" + $('hotel_search_form').serialize();
		$('profile_form').submit();
		return false;
	},
	
	
	/* Match tool disabling preferred if required is checked
	-----------------------------------------------------*/
	// '.required_amenities_list input:click': function() {
	//     var self = this;
	//     var selector_string = '.preferred_amenities_list .' + this.classNames();
	//     $$(selector_string).each( function(obj) {
	//       if( self.checked ) {
	//         obj.checked=true;
	//         obj.disable();
	//       }
	//       else {
	//         obj.checked=false;
	//         obj.enable();
	//       }
	//     });
	// },
	// '.required_activities_list input:click': function() {
	//     var self = this;
	//     var selector_string = '.preferred_activities_list .' + this.classNames();
	//     $$(selector_string).each( function(obj) {
	//       if( self.checked ) {
	//         obj.checked=true;
	//         obj.disable();
	//       }
	//       else {
	//         obj.checked=false;
	//         obj.enable();
	//       }
	//     });
	// },
	
	'table.itinerary_day h5:click': function() {
    this.up('td').down('.item_details').toggle();
	  return false;
	},
	
	'.collapse_all_items:click': function() {
	  $$('.item_details').each( function(obj) {
	    obj.hide();
	  });
	  return false;
	},
	
	'.expand_all_items:click': function() {
	  $$('.item_details').each( function(obj) {
	    obj.show();
	  });
	  return false;
	}
	
	
});


function showBookingForm(el) {
	// hide flash chart
	if ( $('climate_chart') ) {
		$('climate_chart').setStyle({
			visibility: 'hidden'
		});
	}
		
	// position and show the form
  if (self.innerHeight) {  // all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }  
	offsets = document.viewport.getScrollOffsets();
  posTop = ((windowHeight / 2) - (el.getHeight() / 2)) + offsets.top;
	posLeft = ($('container').getWidth() / 2) - (el.getWidth() / 2);
	if(posTop < 1) {
		posTop = 0;
	}
	el.setStyle({'position': 'fixed', 'top': posTop + 'px', 'left': posLeft + 'px'})	
	el.show();
	
	// create the white out
	Element.insert(document.body, {bottom: "<div id='whiteout' style='position:fixed;z-index:999;top:0;left:0;width:"+windowWidth+"px;height:"+windowHeight+"px;background:#fff;'>&nbsp;</div>"});
	Element.setOpacity($('whiteout'), 0.8);
}

function hideBookingForm(el) {
	Element.remove('whiteout');
	el.hide();
	if ( $('climate_chart') ) {
		$('climate_chart').setStyle({
			visibility: 'visible'
		});
	}
}

/* Turn off Autofill yellow backgrounds */
if(window.attachEvent) {
	window.attachEvent("onload",setListeners);

  function setListeners(){
    inputList = document.getElementsByTagName("INPUT");
    for(i=0;i<inputList.length;i++){
      inputList[i].attachEvent("onpropertychange",restoreStyles);
      inputList[i].style.backgroundColor = "";
    }
    selectList = document.getElementsByTagName("SELECT");
    for(i=0;i<selectList.length;i++){
      selectList[i].attachEvent("onpropertychange",restoreStyles);
      selectList[i].style.backgroundColor = "";
    }
  }

  function restoreStyles(){
    if(event.srcElement.style.backgroundColor != "")
      event.srcElement.style.backgroundColor = "";
  }
}