var InputSlider = Class.create(Control.Slider, {
    initialize: function($super, container_id, options) {
	this.slider_container = $(container_id + "-slider-container");
	this.slider = $(container_id + "-slider");
	if(!this.slider) return;
	this.slider_out = $(container_id + "-out");
	this.inputs = $(container_id + "-slider-container").select('input');

	this.slider.observe('click', this.showHandles.bind(this));

	if(options.values)
	    this.orig_values = options.values.map(String);

	if(!options.sliderValue) {
	    if(this.orig_values) {
		options.sliderValue = this.inputs.pluck('value').map(options.fromInputValue || Prototype.K).map(this.orig_values.indexOf.bind(this.orig_values));
	    } else {
		options.sliderValue = this.inputs.pluck('value').map(options.fromInputValue || Prototype.K);
	    }
	}

	options.onChange = this.onChange.bind(this);
	options.onSlide = this.onSlide.bind(this);
	if(options.values) {
	    options.values = $A($R(0, this.orig_values.length-1));
	    options.range = $R(0, options.values.length-1);
	}
	$super(this.slider.select(".handle"), this.slider, options);
	if(options.sliderValue.indexOf(-1) == -1)
	    this.onSlide(this.values);
	else {
	    this.hideHandles();
	    this.updateOutput(this.inputs.pluck('value').map(options.fromInputValue || Prototype.K).map(options.formatOutput || Prototype.K));
	}
	
    },

    hideHandles: function() { this.slider.select('.handle').invoke('hide'); },
    showHandles: function() { this.slider.select('.handle').invoke('show'); },

    setHandleActive: function(values) {
	if(!values.all()) {
	    this.slider_container.addClassName('disabled');
	    this.updateOutput([$('egal').innerHTML]);
	} else {
	    this.slider_container.removeClassName('disabled');

	}
    },

    onChange: function(values) {
	if (!values.length) values = [values];
	if(this.orig_values)
	    values = values.map(function(v) { return this.orig_values[v]; }.bind(this));

	this.updateOutput(values.map(this.options.formatOutput || Prototype.K));

	this.inputs.each(function(input, i) { input.value = (this.options.toInputValue || Prototype.K)(values[i]); }.bind(this));
	this.setHandleActive(values);
	updateSearchResults();
    },
    
    onSlide: function(values) {
	if (!values.length) values = [values];
	if(this.orig_values) 
	    values = values.map(function(v) { return this.orig_values[v]; }.bind(this));

	this.updateOutput(values.map(this.options.formatOutput || Prototype.K));
	this.setHandleActive(values);
    },
    convertValues: function(values) {
	if(this.orig_values)
	    return values.map(this.options.fromInputValue || Prototype.K).map(this.orig_values.indexOf.bind(this.orig_values));

	return values.map(this.options.fromInputValue || Prototype.K);
    },
    setValues: function(values) {
	this.convertValues(values).each(this.setValue, this);
    },
    updateOutput: function(outputs) {
	if(this.slider_out) this.slider_out.select('div').each(function(output, i) { output.update(outputs[i]); });
    }
});

var SearchForm = Class.create({
    initialize: function() {
	jQuery(document).ready(this.domLoaded.bind(this));
    },

    onSuccess: function(transport, json) {
	this.adaptVisibility(json.limited_search_level);
    },

    adaptVisibility: function(limited_search_level) {
	var hide = function(id) { 
	    var el = $(id);
	    if(el.hasClassName('open')) {
		Effect.BlindUp(el, { 
		    'queue': { 
			position: 'end',
			scope: id
		    }, 
		    duration: 0.5,
		    beforeSetup: el.removeClassName.bind(el).curry('open')
		});
	    }
	}.bind(this);

	var show = function(id) { 
	    var el = $(id);
	    if(!el.hasClassName('open')) {
		Effect.BlindDown(el, { 
		    'queue': { 
			position: 'end',
			scope: id
		    }, 
		    duration: 0.5,
		    beforeSetup: el.addClassName.bind(el).curry('open')
		});
	    }
	}.bind(this);

	if(limited_search_level == 'limited_pks') {
	    hide('region-criteria');
	    hide('search-criteria');
	    hide('additional-search-criteria');
	}
	if(limited_search_level == 'limited_regions') {
	    show('region-criteria');
	    hide('search-criteria');
	    hide('additional-search-criteria');
	}
	if(limited_search_level == 'not_limited') {
	    show('region-criteria');
	    show('search-criteria');
	    show('additional-search-criteria');
	}
    },

    destinationAddressChange: function(){
	var maximum_distance_container = $('maximum-distance-container');
	$('id_destination_latlng').value = "";
	if($F($('id_destination_address'))) {
	    // deactivate all regions on destination_address change
	    this.regions.deactivateAll();
	    
	    // make destination maximum distance appear
	    if(maximum_distance_container) Effect.Appear(maximum_distance_container);
	} else {
	    if(maximum_distance_container) $('maximum-distance-container').hide();
	}
    },
   
    domLoaded: function() {
	var form = $('search-form');
	if(form) {
	    form.reset();

	    this.regions = new RegionPicker();

	    // == destination address ==
	    var destination_address_change = this.destinationAddressChange.bind(this);

	    if($('id_destination_address')) $('id_destination_address').observe("change", destination_address_change);
	    // geo autocomplete
	    if(typeof google!="undefined"){
		(function($) {
		
		    $('#id_destination_address').geo_autocomplete(new google.maps.Geocoder, {
			mapkey: 'ABQIAAAAbnvDoAoYOSW2iqoXiGTpYBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQNumU68AwGqjbSNF9YO8NokKst8w', 
			selectFirst: false,
			minChars: 3,
			cacheLength: 50,
			width: 300,
			scroll: true,
			scrollHeight: 330
		    }).result(function(_event, _data) {
			document.getElementById('id_destination_address').blur();
			if(Prototype.Browser.IE) { 
			    destination_address_change();
			    updateSearchResults();
			}
			$('#id_destination_latlng').val(_data.geometry.location.toUrlValue());
		    });
		    
		})(jQuery);
	    }

	    form.getElements().invoke("observe", "change", updateSearchResults);
	    form.getInputs("text").invoke("observe", "keypress", function(ev) {
		if(ev.keyCode == 13) { // enter
		    if(Prototype.Browser.IE && ev.element().id == 'id_destination_address') destination_address_change();
		    ev.element().blur();
		    if(Prototype.Browser.IE) updateSearchResults(); 
		    ev.stop();
		}
	    }.bindAsEventListener());

	    form.observe("submit", function(ev) {
		updateSearchResults();
		ev.stop();
	    });
	    new InputSlider('search_form-number_of_rooms', {
		values: ["", $A($R(1, 5))].flatten(),
		alignX: 18,
		formatOutput: function(v) { return v ? v + '+' : ''; }
	    }); 

	    new InputSlider('search_form-destination_maximum_distance', {
		values: [5, 10, 25, 50],
		alignX: Prototype.Browser.IE ? 6 : 21,
		toInputValue: function(v) { return parseInt(v); },
		formatOutput: function(v) { return parseInt(v) + 'km'; }
	    }); 
	    if(!$F($('id_destination_address')) && $('maximum-distance-container'))
		$('maximum-distance-container').hide();


	    new InputSlider('search_form-price', {
		values: ["", $R(0, 8).map(function(i) { return 1000+250*i; })].flatten(),
		alignX: 18,
		formatOutput: function(v) { return v ? v + '.-' : ''; }
	    });

	    var current_date = Date.today();
	    var date_values = [current_date.toString('yyyy-MM-dd')];

	    for(var i = 0; i < 8; ++i) {
		if(i % 2 == 0) {
		    current_date  = current_date.add({days: parseInt((current_date.getDaysInMonth()-current_date.getDate())/2) });
		} else {
		    current_date.moveToLastDayOfMonth().add({ days: 1});
		}
		date_values.push(current_date.toString('yyyy-MM-dd'));
	    }

	    var rental_from_date_slider = new InputSlider('search_form-rental_from_date', {
		values: ["", date_values].flatten(),
		alignX: 18,
		formatOutput: function(v) { 
		    if(v) return Date.parseExact(v, 'yyyy-MM-dd').toString(Date.CultureInfo.formatPatterns.shortDate); 
		}
	    });
	    var months_natural_language = {
		'de': ['Monat', 'Monate'],
		'en': ['month', 'months'],
		'fr': ['mois', 'mois']
		}

	    var rental_from_date = $('id_rental_from_date');
	    if(rental_from_date) {
		var calendar_button = $('search_form-rental_from_date-slider-container').down('.calendar');
		new DatePicker(calendar_button, rental_from_date, {
		    onBeforeShow: function() {
			//$j(calendar_button).DatePickerSetDate(Date.parse($F(rental_from_date)) || Date.today(), false);
			$j(calendar_button).DatePickerSetDate(Date.parseExact($F(rental_from_date), "yyyy-MM-dd") || Date.today(), false);
		    },
		    onRender: function(date) {
			return {'disabled': date.valueOf() < Date.today().valueOf()};
		    },
		    onChange: function(formatted, date) {
			$('search_form-rental_from_date-out').down('div').update(date.toString(Date.CultureInfo.formatPatterns.shortDate));

			rental_from_date_slider.hideHandles();
			rental_from_date_slider.slider_container.removeClassName('disabled');
			rental_from_date.value = date.toString("yyyy-MM-dd");
			updateSearchResults();
		    }
		});
	    }

	    $$('.flag').each(function(flag_button) {
		var id = flag_button.readAttribute('id');
		var input_id = id.replace(/_flag$/, "");
		flag_button.up('.criterion').observe("click", function() {
		    // rotate choices
		    var choices = [
			'whatever',
			//'preferred',
			'required'];
		    var current_value = $F(input_id);
		    var next_value = choices[(choices.indexOf(current_value) + 1) % choices.length];
		    $(input_id).value = next_value;
		    flag_button.update($("flag_" + next_value).innerHTML);
		    updateSearchResults();
		});
	    });

	    var show_placed_hide = $('show_placed_hide');
	    var show_placed_show = $('show_placed_show');
	    var show_placed_input = $('id_show_placed');
	    show_placed_hide.observe('click', function() {
		show_placed_hide.hide();
		show_placed_show.show();
		show_placed_input.value = 'False';
		updateSearchResults();
	    });
	    show_placed_show.observe('click', function() {
		show_placed_show.hide();
		show_placed_hide.show();
		show_placed_input.value = 'True';
		updateSearchResults();
	    });

	    this.adaptVisibility(limited_search_level);
	}
    },
    
    getDate: function(offset) {
	var d = new Date();
	d.setMonth(d.getMonth() + offset)
	    day = String(d.getDate());
	if(day.length == 1) day = '0' + day;
	month = String(d.getMonth()+1);
	if(month.length == 1) month = '0' + month;
	year = d.getFullYear();
	return "#{year}-#{month}-#{day}".interpolate({day: offset == 0 ? day : "01", month: month, year: year});
    },


    searchMapMouseOver: function(region, repr) {
	this.regions.onMouseOver(region, repr);
    },

    searchMapMouseOut: function(region) {
	this.regions.onMouseOut(region);
    },
    searchMapClick: function(region, pk) {
	this.regions.onClick(region, pk);
	$('id_destination_address').value = '';
	$('id_destination_latlng').value = "";
	var maximum_distance_container = $('maximum-distance-container');
	if(maximum_distance_container) maximum_distance_container.hide.bind(maximum_distance_container).delay(.1);
	updateSearchResults();
    }
});

searchForm = new SearchForm();

var searchMapMouseOver = searchForm.searchMapMouseOver.bind(searchForm);
var searchMapMouseOut = searchForm.searchMapMouseOut.bind(searchForm);
var searchMapClick = searchForm.searchMapClick.bind(searchForm);

