var SearchUpdate = {
	queue: [],
	
	run: function(){
		if(SearchUpdateProgressBar && !SearchUpdateProgressBar.visible()){
			SearchUpdateProgressBar.show();
		}
		var token = (new Date).getTime() + "#" + (Math.random()*1000).floor();
		job = {
			token: token,
			started_at: new Date,
			request: new Ajax.Request($('filter_form').action, {asynchronous:true, evalScripts:false, evalJSON:false, parameters: Form.serialize('filter_form')+'&json=true', onComplete: function(transport){
				SearchUpdate.complete(token);
			}})
		}
		this.queue.push(job);
	},
	
	complete: function(token){
		for(i=0; i < SearchUpdate.queue.length; i++){
			if(SearchUpdate.queue[i] && SearchUpdate.queue[i].token == token){
				job = SearchUpdate.queue[i];
				if(i+1 == SearchUpdate.queue.length){
					if(job.request.transport.statusText == "OK"){
						result = job.request.transport.responseText.evalJSON();
						$('search_results').innerHTML = result.search_results;
						if(result.show_map){
							tickets = result.tickets;
							update_map(tickets);
						}
						if(SearchUpdateProgressBar) SearchUpdateProgressBar.fade();
						// console.log("completed search in "+(new Date - job.started_at)/1000+" seconds: ");
					}
				}else{
					// console.log("ignored: " + i, job.body);
				}
				job.request = null;
				// console.log("going to nullify request in job:", job.request)
				// SearchUpdate.queue[i].request = null;
				// console.log("deleted job from queue");
				
			}
		}
	}
}

SetupDateSlider = function(direction) {
	var from = $F('search_' + direction + '_on_min').split(/\-/);
	var to   = $F('search_' + direction + '_on_max').split(/\-/);
	
	var min_date  = new Date( from[0], new Number(from[1])-1, new Number(from[2]) - 14 );
	var from_date = new Date( from[0], new Number(from[1])-1, new Number(from[2]) );
	
	if(min_date < new Date()){
		min_date = new Date();
	}
	
	var max_date  = new Date( to[0],   new Number(to[1])-1,   new Number(to[2]) + 14  );
	var to_date   = new Date( to[0],   new Number(to[1])-1,   new Number(to[2])  );
	
	// console.log("min_date", min_date);
	// console.log("max_date", max_date);
	
	var days = Math.round((max_date - min_date)/86400000);
	var min_day = 0;
	var max_day = 0 + days;
	
	var from_day = (min_day + (from_date - min_date)/86400000).round() + 1;
	var to_day   = (max_day + (to_date - max_date)/86400000).round() + 1;
	
	return new Control.Slider([direction + '_date_min', direction + '_date_max'], direction + '_date_slider', {
	    range: $R(min_day, max_day),
	    values: $R(min_day, max_day),
	    sliderValue: [from_day, to_day],
//		spans: [direction + '_date_selection'],
		onSlide: function(values) {
			var from = new Date(min_date.getFullYear(), min_date.getMonth(), min_date.getDate() + new Number(values[0]));
			var to   = new Date(min_date.getFullYear(), min_date.getMonth(), min_date.getDate() + new Number(values[1]));
			// console.log("to", to);
			$$('#' + direction + '_date_min span')[0].innerHTML = from.toString('ddd') + "<br/>" + from.toString('dd MMM');
			$$('#' + direction + '_date_max span')[0].innerHTML = to.toString('ddd') + "<br/>" + to.toString('dd MMM');
		},
		onChange: function(values) {
			var from = new Date(min_date.getFullYear(), min_date.getMonth(), min_date.getDate() + new Number(values[0]));
			var to   = new Date(min_date.getFullYear(), min_date.getMonth(), min_date.getDate() + new Number(values[1]));
			$('search_' + direction + '_on_min').value = from.toString('yyyy-MM-dd');
			$('search_' + direction + '_on_max').value = to.toString('yyyy-MM-dd');
			update_results();
		},
	    restricted: true
	});
}

SetupTimeSlider = function(direction) {
	var from = $F('search_' + direction + '_at_min').split(/:/);
	var to   = $F('search_' + direction + '_at_max').split(/:/);
	// console.log("from", from);
	// console.log("to", to);
	
	var from_quarters = new Number(from[0])*4 + Math.round(new Number(from[1])/60*4)/4;
	var from_hours    = from_quarters/4;
	// console.log("misc", Math.round(new Number(to[1])/60*4)/4);
	// console.log("misc", (new Number(to[1])/60*4));
	// console.log(Math.round(new Number(to[1])/60*4));
	var to_quarters   = new Number(to[0])*4 + Math.round(new Number(to[1])/60*4)/4;
	var to_hours      = to_quarters/4;
	if(Math.round(new Number(to[1])/60*4) == 4) to_quarters += 4;
	
	// console.log("to_quarters", to_quarters);
	// console.log("to_hours", to_hours);
	return new Control.Slider([direction + '_time_min', direction + '_time_max'], direction + '_time_slider', {
	    range: $R(0, 24*4),
	    values: $R(0, 24*4),
	    sliderValue: [from_quarters, to_quarters],
//		spans: [direction + '_time_selection'],
		onSlide: function(values) {
			var min_hour = (values[0]/4).round();
			var max_hour = (values[1]/4).round();
			var min = new Date(2008, 1, 1, min_hour, ((values[0]/4-min_hour)*60).round(2), 0);
			var max = new Date(2008, 1, 1, max_hour, ((values[1]/4-max_hour)*60).round(2), 0);
			
			$$('#' + direction + '_time_min span')[0].innerHTML = min.toString('H:mm');
			$('show_' + direction + '_at_min').innerHTML = min.toString('H:mm');
			var max_time = max.toString('H:mm');
			if(max_time == "0:00") max_time = "24:00";
			$$('#' + direction + '_time_max span')[0].innerHTML = max_time;
			$('show_' + direction + '_at_max').innerHTML = max_time.toString('H:mm');
		},
		onChange: function(values) {
			var min_hour = (values[0]/4).round();
			var max_hour = (values[1]/4).round();
			var min = new Date(2008, 1, 1, min_hour, ((values[0]/4-min_hour)*60).round(2), 0);
			
			// 24:00:00 should become 23:59:59
			if(max_hour == 24){
				var max = new Date(2008, 1, 1, max_hour, ((values[1]/4-max_hour)*60).round(2), -1);
			}
			else{
				var max = new Date(2008, 1, 1, max_hour, ((values[1]/4-max_hour)*60).round(2), 0);
			}
			$('search_' + direction + '_at_min').value = min.toString('H:mm:ss');
			$('search_' + direction + '_at_max').value = max.toString('H:mm:ss');
			update_results();
		},
	    restricted: true
	});
}

SetupPriceSlider = function(do_not_update_results_after_change) {
	var maximum_price_value = $F("search_maximum_price");
	$('show_maximum_price').innerHTML = maximum_price_value;
	$$("#maximum_price span")[0].innerHTML = "&euro; " + maximum_price_value;
	
	// console.log("SetupPriceSlider(maximum_price_value)", maximum_price_value);
	return new Control.Slider('maximum_price', 'price_slider', {
	    range: $R(20/10, 500/10),
	    values: $R(20/10, 500/10),
	    sliderValue: maximum_price_value/10,
		onSlide: function(value) {
			var maximum_price = Math.round(value);
			if(maximum_price >= 500/10) maximum_price = 2000/10;
			$$("#maximum_price span")[0].innerHTML = "&euro; "+maximum_price*10;
			$('show_maximum_price').innerHTML = maximum_price*10;
		},
		onChange: function(value) {
			var maximum_price = Math.round(value);
			if(maximum_price >= 500/10) maximum_price = 2000/10;
			$("search_maximum_price").value = maximum_price*10;
			$$("#maximum_price span")[0].innerHTML = "&euro; "+maximum_price*10;
			$('show_maximum_price').innerHTML = maximum_price*10;
			if(!do_not_update_results_after_change) update_results();
			$("search_maximum_price").form.fire("slider:change");
			if($('search_with_destination_false')){
				$('search_with_destination_false').click();
			}
		},
	    restricted: true
	});
	// console.log(price_slider);
}

var select_new_price_maximum = function(new_max_price){
	new Effect.Highlight("price_filter", { keepBackgroundImage:true, restorecolor:'#DBEEF9', startcolor:'#48BF0E' });
	if(price_slider.setValue){
		window.price_slider.setValue(new_max_price/10);
	}
	// the price_slider automatically calls update_results(), so we don't have to do that here..
}

var select_all_origins = function(){
	new Effect.Highlight("origin-filter", { keepBackgroundImage:true, restorecolor:'#DBEEF9', startcolor:'#48BF0E' });
	toggle_origins(true, false);
	update_results();
}

var select_all_destinations = function(){
	new Effect.Highlight("destination-filter", { keepBackgroundImage:true, restorecolor:'#DBEEF9', startcolor:'#48BF0E' });
	toggle_destinations(true, false);
	update_results();
}

var select_all_routes = function(){
	new Effect.Highlight("origin-filter", { keepBackgroundImage:true, restorecolor:'#DBEEF9', startcolor:'#48BF0E' });
	new Effect.Highlight("destination-filter", { keepBackgroundImage:true, restorecolor:'#DBEEF9', startcolor:'#48BF0E' });
	toggle_origins(true, false);
	toggle_destinations(true, false);
	update_results();
}

var select_all_websites = function(){
	new Effect.Highlight("website_filter", { keepBackgroundImage:true, restorecolor:'#DBEEF9', startcolor:'#48BF0E' });
	toggle_websites(true, false);
	update_results();
}

SetupDurationSlider = function(do_not_update_results_after_change) {
	// console.log("SetupDurationSlider(min_duration, max_duration)", min_duration, max_duration);
	return new Control.Slider(['min_duration','max_duration'], 'duration_slider', {
	    range: $R(0, 30),
	    values: $R(0, 30),
		width: 279,
	    sliderValue: [$F('search_min_duration'), $F('search_max_duration')],
//		spans: ['duration_selection'],
		onSlide: function(values) {
			$$("#min_duration span")[0].innerHTML = Math.round(values[0]);
			$$("#max_duration span")[0].innerHTML = Math.round(values[1]);
			$("min_duration_preview").innerHTML   = Math.round(values[0]);
			$("max_duration_preview").innerHTML   = Math.round(values[1]);
		},
		onChange: function(values) { 
			$("search_min_duration").value = Math.round(values[0]);
			$("search_min_duration").form.fire("slider:change");
			$("search_max_duration").value = Math.round(values[1]);
			$("search_max_duration").form.fire("slider:change");
			if(!do_not_update_results_after_change) update_results();
		},
	    restricted: true
	});
}
