get_authenticity_token = function(){
	tokens = document.getElementsByName("authenticity_token");
	if(tokens && tokens[0]){
		return $F(tokens[0]);
	}
}

load_alternative_airports = function(for_airports){
	if(for_airports == "origin"){
		new Ajax.Request('/search/nearby_airports?for=origin', {asynchronous:true, evalScripts:true, parameters: {airport_name: $F('search_origin'), within: $F('include_origins_within_km'), authenticity_token: get_authenticity_token(), locale: $F('locale')}});
	}
	else if(for_airports == "destination"){
		new Ajax.Request('/search/nearby_airports?for=destination', {asynchronous:true, evalScripts:true, parameters: {airport_name: $F('search_destination'), within: $F('include_destinations_within_km'), authenticity_token: get_authenticity_token(), locale: $F('locale')}});
	}
}

toggle_alternative_airports = function(for_airports){
	if(for_airports == "origin"){
		select_nearby_airports("origin");
		if($('search_nearby_origin').checked){
			if(!$('search_origins').visible()){
				Effect.BlindDown('search_origins', {duration: 0.2});
			}
		}
		else{
			if($('search_origins').visible()){
				Effect.BlindUp('search_origins', {duration: 0.2});
			}
		}
	}
	else if(for_airports == "destination"){
		select_nearby_airports("destination");
		if($('search_nearby_destination').checked){
			if(!$('search_destinations').visible()){
				Effect.BlindDown('search_destinations', {
					duration: 0.2,
					afterFinish: function(){
						var price_slider = SetupPriceSlider(true);
					}
				});
			}
		}
		else{
			if($('search_destinations').visible()){
				Effect.BlindUp('search_destinations', {
					duration: 0.2,
					afterFinish: function(){
						var price_slider = SetupPriceSlider(true);
					}
				});
			}
		}
	}
}

select_nearby_airports = function(for_airports, checked){
	// if(console && console.log) console.log("checked?", checked);
	if(for_airports == "origin"){
		if(checked === undefined) checked = $('search_nearby_origin').checked;
		$$('#search_origins input[type="checkbox"]').each(function(checkbox){
			checkbox.checked = checked;
		});
	}
	if(for_airports == "destination"){
		if(checked === undefined) checked = $('search_nearby_destination').checked;
		$$('#search_destinations input[type="checkbox"]').each(function(checkbox){
			checkbox.checked = checked;
		});
	}
	// if(console && console.log) console.log(for_airports, checked);
}

// blockEnter = function(evt) {
	// evt = (evt) ? evt : event;
	// var charCode = (evt.charCode) ? evt.charCode :((evt.which) ? evt.which : evt.keyCode);
	// if (charCode == 13) {
	// 	return false;
	// } else {
	// 	return true;
	// }
// }

blockEnter = function(e) {
	var key;      
	if(window.event){
		key = window.event.keyCode; //IE
	}
	else{
		key = e.which; //firefox
	}
	return (key != 13);
}

Element.observe(document, "dom:loaded", function(){
	var price_slider    = SetupPriceSlider(true);
	var duration_slider = SetupDurationSlider(true);
	
	$('price_slider').observe('click', function(){
		if($('search_with_destination_false')){
			$('search_with_destination_false').click();
		}
	});
});

expand_details = function(open, close){
	open  = $(open);
	close = $(close);
	
	if(!open.visible()){
		Effect.BlindDown(open, {
			duration: 0.2,
			afterFinish: function(){
				var price_slider = SetupPriceSlider(true);
			}
		});
	}
	
	if(close.visible()){
		Effect.BlindUp(close, {duration: 0.2});
	}
}

toggle_ticket_type_details = function(){
	one_way    = $('search_ticket_type_one_way').checked;
	return_box = $('return');
	
	if(return_box.visible()){
		if(one_way){
			Effect.BlindUp(return_box, {duration: 0.2});
		}
	}
	else{
		if(!one_way){
			Effect.BlindDown(return_box, {duration: 0.2});
		}
	}
}

document.observe("dom:loaded", function(){
	
	if($('search_destination')){
		$('search_destination').observe('keyup', function(){
			if($F('search_destination').length > 0){
				$('search_with_destination_true').checked = true;
			}
		});
	}
	
	depart_with_errors = $$('#depart.has_errors');
	if(depart_with_errors.length){
		depart_with_errors[0].observe('click', function(){
			if($('search_depart_on_search_type_period').checked || $('search_depart_on_search_type_date').checked){
				this.removeClassName('has_errors');
			}
		});
	}
	
	return_with_errors = $$('#return.has_errors');
	if(return_with_errors.length){
		return_with_errors[0].observe('click', function(){
			if($('search_return_on_search_type_flexible_duration').checked || $('search_return_on_search_type_date').checked){
				this.removeClassName('has_errors');
			}
		});
	}
	
	$$('#depart_period input[type="text"]').each(function(original_field){
		// text_field = new Element('input', {'id': original_field.id + "_select", 'name': original_field.id + "_select", 'type': 'text', 'class': 'date', 'value': original_field.value});
		// original_field.setStyle("border: 2px solid #c00;");
		// console.log(text_field);
		// original_field.insert({ after: text_field});
		// original_field.type = "hidden";
		// text_field.observe('click', open_calendar);
		// text_field.observe('keypress', function(){ $('search_depart_on_search_type_period').checked = true; });
		// text_field.observe('change', function(){ $('search_depart_on_search_type_period').checked = true; });
		// text_field.observe('change', function(){
		// 	console.log("set", Date.parse(this.value).toString('yyyy-MM-dd'));
		// 	this.previous().value = Date.parse(this.value).toString('yyyy-MM-dd');
		// 	console.log(this);
		// 	});
		// // text_field.observe('click', open_calendar);
		// text_field.observe('blur', close_calendar);
	})
	
	$$('input[name="search[depart_on_search_type]"]').each(function(radio){
		if($('search_depart_on_search_type_period') && !$('search_depart_on_search_type_period').checked){
			$('depart_period').hide();
		}
		if($('search_depart_on_search_type_date') && !$('search_depart_on_search_type_date').checked){
			$('depart_date').hide();
		}
		radio.observe('click', function(){
			if(this.value == "period"){
				expand_details('depart_period', 'depart_date');
			}
			else {
				expand_details('depart_date', 'depart_period');
			}
		})
	});
	
	$$('input[name="search[return_on_search_type]"]').each(function(radio){
		if(!$('search_return_on_search_type_flexible_duration').checked && $('flexible_duration')){
			$('flexible_duration').hide();
		}
		if(!$('search_return_on_search_type_date').checked && $('return_on')){
			$('return_on').hide();
		}
		// console.log(radio);
		radio.observe('click', function(){
			// console.log("show: ", this);
			if(this.value == "flexible_duration"){
				expand_details('flexible_duration', 'return_on');
			}
			else {
				expand_details('return_on', 'flexible_duration');
			}
		})
	});
	
	$$('#depart_on input[type="text"]').each(function(text_field){
		text_field.observe('focus', open_calendar);
		text_field.observe('keypress', function(){ $('search_depart_on_search_type_date').checked = true; });
		text_field.observe('change', function(){ $('search_depart_on_search_type_date').checked = true; });
		// text_field.observe('click', open_calendar);
		text_field.observe('blur', close_calendar);
	});
	
	$$('#return_on input[type="text"]').each(function(text_field){
		text_field.observe('focus', open_calendar);
		text_field.observe('keypress', function(){ $('search_return_on_search_type_date').checked = true; });
		text_field.observe('change', function(){ $('search_return_on_search_type_date').checked = true; });
		// text_field.observe('click', open_calendar);
		text_field.observe('blur', close_calendar);
	});
	
	
	if($('search_ticket_type_one_way') && $('search_ticket_type_one_way').checked){
		$('return').hide();
	}
	
	if($('search_ticket_type_round_trip')){
		$('search_ticket_type_round_trip').observe('click', toggle_ticket_type_details);
		$('search_ticket_type_one_way').observe('click', toggle_ticket_type_details);
	}
});

open_calendar = function()
{
	var year = (new Date).getFullYear();
	// if(console && console.log) console.log("opening", this);
	new CalendarDateSelect( this, { buttons:false, month_year:'label', year_range: [year,year+1], valid_date_check:function(date) { return(date >= (new Date()).stripTime() && date <= (new Date(year+1, 1, 1)).stripTime()) }} );
	this.calendar_date_select.reparse();
	// if(console && console.log) console.log("opened", this.calendar_date_select);
}

close_calendar = function()
{
	if(this.calendar_date_select){
		// this.calendar_date_select.close();
	}
}

document.observe('dom:loaded', function(){
	if($('search_origin_auto_complete') && $('search_origin')){
		var search_origin_auto_completer = new Ajax.Autocompleter(
			'search_origin',
			'search_origin_auto_complete',
			'/search/auto_complete_for_place',
			{
				callback: function(element, value) {
					return 'point=origin&name=' + $F('search_origin') + '&locale=' + $F('locale') + '&authenticity_token=' + encodeURIComponent(get_authenticity_token());
				},
				frequency: 0.1,
				minChars: 3,
				select: 'airport_name'
			}
		);
	}
	if($('search_destination_auto_complete') && $('search_destination')){
		var search_destination_auto_completer = new Ajax.Autocompleter(
			'search_destination',
			'search_destination_auto_complete',
			'/search/auto_complete_for_place',
			{
				callback: function(element, value) {
					return 'point=destination&name='+$F('search_destination')+'&locale='+$F('locale')+'&authenticity_token='+encodeURIComponent(get_authenticity_token())
				},
				frequency: 0.1,
				minChars: 3,
				select:'airport_name'
			}
		);
	}
	
});



/* ================================================ */
/*  CALENDER	*/


function newCal(type, calendar_icon){
	var qfly = new qflyCalendar(type);
	qfly.setNav(calendar_icon);
}

qflyCalendar = Class.create();

qflyCalendar.prototype = {
	initialize: function(type){
		if ( type == '' ) return false;
		
		this.type = type;
		qflyCalendar.type = type;
		this.day;
		this.monthYear;
		
		this.startDay        = $('search_depart_on_min_3i');
		this.startMonthYear  = $('search_depart_on_min_year-month');
		this.endDay          = $('search_depart_on_max_3i');
		this.endMonthYear    = $('search_depart_on_max_year-month');
		
		this.departDay       = $('search_depart_on_3i');
		this.departMonthYear = $('search_depart_on_year-month');
		this.returnDay       = $('search_return_on_3i');
		this.returnMonthYear = $('search_return_on_year-month');
		
		
		this.setElement(type);
		
		this.setDates();
	},
	
	setElement: function(type){
		switch ( type ){
			case 'start':
				this.day       = this.startDay;
				this.monthYear = this.startMonthYear;
			break;
			
			case 'end':
				this.day       = this.endDay;
				this.monthYear = this.endMonthYear;
			break;
			
			case 'depart':
				this.day       = this.departDay;
				this.monthYear = this.departMonthYear;
			break;
			
			case 'return':
				this.day       = this.returnDay;
				this.monthYear = this.returnMonthYear;
			break;
		}
	},
	
	setDates: function(){
		this.dayValue           = Date.padded2($F(this.day));
		qflyCalendar.dayValue   = this.dayValue;
		
		var monthYear           = $F(this.monthYear).split('-');
		
		this.monthValue         = Date.padded2(monthYear[1]);
		qflyCalendar.monthValue = this.monthValue;
		
		this.yearValue          = monthYear[0];
		qflyCalendar.yearValue  = this.yearValue;
	},
	
	setStartEndDate: function(){
		var start =	Date.padded2($F(this.startMonthYear).split('-')[1])
					+'-'+
					Date.padded2($F(this.startDay))
					+'-'+
					$F(this.startMonthYear).split('-')[0];
		
		this.startDate = Date.parseExact(start, 'MM-dd-yyyy');
		
		var end =	Date.padded2($F(this.endMonthYear).split('-')[1])
					+'-'+
					Date.padded2($F(this.endDay))
					+'-'+
					$F(this.endMonthYear).split('-')[0];
		
		this.endDate = Date.parseExact(end, 'MM-dd-yyyy');
	},
	
	setNav: function(calendar_icon){
		this.cal = new CalendarDateSelect(
			calendar_icon.previous(),
			{
				hidden: true,
				popup_by: calendar_icon,
				valid_date_check: function(date) { return(date >= (Date.today().add(1).days()).stripTime()) },
				before_show: function(){
					var tmpDate = Date.parseExact(qflyCalendar.monthValue+'-'+qflyCalendar.yearValue, 'MM-yyyy').add(qflyCalendar.dayValue-1).days();
					
					this.calendar_date_select.selection_made = true;
					this.calendar_date_select.selected_date  = tmpDate;
					
				},
				onchangeCustom: function(date){
					var qfly = new qflyCalendar(qflyCalendar.type);
					qfly.update(date);
					qfly.calculateNewDates();
				}
			}
		);
		
		var navDate = Date.parseExact(qflyCalendar.monthValue+'-'+qflyCalendar.yearValue, 'MM-yyyy');
		this.cal.navTo(navDate);
	},
	
	update: function(date){
		this.date = date;
		this.day.setValue(this.date.getDate());
		var monthYear = this.date.getFullYear()+'-'+(this.date.getMonth()+1);
		this.monthYear.setValue(monthYear);
		if(this.monthYear.form){
			this.monthYear.form.fire('calendar:click');
		}
	},
	
	calculateNewDates: function(){
		if ( this.type != 'start' && this.type != 'end' ) return false;
		
		this.setStartEndDate();
		var compare = Date.compare(this.startDate, this.endDate);
		
		if ( compare == 1 ){
			if ( this.type == 'start' ) {
				var newDate = this.startDate.add(7).days();
				this.setCalculation(newDate, this.endDay, this.endMonthYear);
			} else if ( this.type == 'end' ) {
				var newDate = this.endDate.add(-7).days();
				if ( Date.compare(newDate, Date.today()) == -1 ){
					newDate = Date.today();
				}
				this.setCalculation(newDate, this.startDay, this.startMonthYear);
			}
		}
	},
	
	setCalculation: function(newDate, day, monthYear){
		day.setValue(newDate.getDate());
		var tmp = newDate.getFullYear()+'-'+(newDate.getMonth()+1);
		monthYear.setValue(tmp);
	}
};
