var SearchForm = new Class({
	Implements: [Options,Events],
	options: {
		lat: 39.614152,
		lng: 2.888031
	},
	paginating: false,
	initialize: function(zones, options){
		this.setOptions(options);
		this.home = document.body.hasClass("home");
		this.searchForm = $("search-form");		
		if ( $("search-map"))
			this.map = new HomeMap(this.options.lat, this.options.lng);
		this.zones = zones;
		this.calendar = new Calendar(
			{ day_start: 'd/m/Y', day_end: 'd/m/Y'},
			{ direction: 1, days: days, months: months, offset: 1, pad: 0 }
		);	
		InfoBox.init();
		this.addEvents();
		this.updateMap();
		if (this.home) { 
			if ($("dummy").value!="0") this.backButton();
			$("dummy").value = "1";
		}
		
		// Fix for White Label in IE6
		if (ie6 && this.searchForm.target=="_blank") this.searchForm.method = "GET";
	},
	addEvents: function(){
		if (this.searchForm.ajax.value=="True")
			this.searchForm.addEvent('submit', this.search.bind(this));
		//this.addPaginationEvents();
		//this.addResultEvents();
	},
	addResultEvents: function(){		
		$("results-wrapper").getElements("a.info").addEvent("click", this.showInfo.bindWithEvent(this));
	},
	addPaginationEvents: function() {
		var pageInput, page, bw, fw;
		pageInput = this.searchForm.getElement("[name=page]");
		page = pageInput.value.toInt();
		bw = this.results.getElements("[name=paginate_bw]");
		fw = this.results.getElements("[name=paginate_fw]");
		
		fw.addEvent("click", function(ev){ ev.target.form["page"].value = page+1; this.setPage(page+1)}.bind(this));
		bw.addEvent("click", function(ev){ ev.target.form["page"].value = page-1; this.setPage(page-1)}.bind(this));
		this.results.getElements("form").addEvent('submit', this.search.bind(this));
	},
	backButton: function() {
		this.search();
	},
	setPage: function(page) {
		$("page").value = page;
	},
	search: function(event){
		var target;
		this.showSpinner();
		if ($defined(event)) {
			if (event.target.id == "search-form") {
				$("destination_map").value = "";
				$("page").value = "0";
			}
			target = event.target;
			event.stop();
		} else {
			target = this.searchForm;
		}
		
		if ($defined(this.req))
			this.req.cancel();
		this.req = new Request({
			'method': 'post',
			'data': target,
			'url': this.searchForm.action || "/availability_search/search",
			'evalScripts': true,
			'onSuccess': this.processResponse.bind(this)
			// ,'onFailure': function(){this.continuePost(target)}.bind(this)
		});
		$$("#results").set("opacity", 1).fade(0);
		this.req.send();		
	},
	continuePost: function(target) {
		target.removeEvents();
		target.submit();
	},
	processResponse: function(responseText, responseXML) {
		this.fireEvent("results");
		var results = $("results-wrapper");
		results.innerHTML = responseText;
		results.set("opacity", 0).fade(1);
		
		if ($("suggestions")) {		
			$$("#suggestions .submit").addEvent("click", this.selectSuggestion.bind(this))			
		}
		else if ($("results")) {
			this.zones = av_zones; // This variable is global and is defined in step1-results.mako
			this.results = results;
			this.addPaginationEvents();
			this.addResultEvents();
			this.updateMap();
		}
		this.hideSpinner();
        if (this.showAvLnk!=undefined){
          this.showAvLnk();
          this.showAvLnk = undefined;
        }
		var boatTypes = results.getElement("div.boat_types");
		if (boatTypes) {
			boatTypes.getElements("a").addEvent("click", this.filterType.bind(this));
		}
	},
	filterType: function(ev) {
		ev.stop();
		this.searchForm['type'].value = (ev.target.rel)? ev.target.rel:$(ev.target).getParent().rel;
		this.search();
	},
	selectSuggestion: function(ev) {
		ev.stop();
		var sugform = ev.target.form;
		this.searchForm["type"].value = sugform["type"].value;
		this.searchForm["day_start"].value = sugform["day_start"].value;				
		this.searchForm["day_end"].value = sugform["day_end"].value;
		this.calendar.calendars.each(function(i) { this.calendar.changed(i)}.bind(this));
		this.search();
	},
	showSpinner: function() {
		$("spinner").setStyle("display","inline");
	},
	hideSpinner: function() {
		$("spinner").setStyle("display","none");
	},
	updateMap: function(){
		if (!this.map) return;
		this.map.markers.each(function(m){ m.setMap(null); });
		this.map.markers = [];
		if (this.zones.length==0) return;
		this.zones.each(function(z){
			this.map.addDestination(z);
		}.bind(this));
		this.map.zoomMarkers();
		this.showMapBack();
	},
	showMapBack: function() {		
		if ($("destination_map").value && !$("map_back")) {
			var back = new Element("a", {"id":"map_back","href":"#"}).
				addEvent("click", this.mapBack.bindWithEvent(this));
			back.innerHTML = map_back_tx;
			this.map.map.getDiv().adopt(back);
		} else if (!$("destination_map").value && $("map_back"))
			$("map_back").destroy();
	},
	mapBack: function(ev) {
		ev.stop();
		$("destination_map").value = "";
		$("page").value = "0";
		this.search();
	},
	showInfo: function(event){
		event.stop();		
		var target = (event.target.tagName=="IMG")? $(event.target).getParent() : event.target;
		InfoBox.load(target.href, target.rel, event.page.y - 330);
	},
	hideInfo: function(){
		$("more-info-container").empty();
	},
	calculateInfoPosition: function(result, info){
		var top=result.getOffsets().y - 120, left=result.getOffsets().x + 80, width=info.getStyle("width").toInt(),
		body=$(document.body), body_right=body.getCoordinates().right;
			
		if (left + width > body_right) {
			left = body_right - 20 - width;
		}
		
		info.setStyles({'top': top + "px", 'left': left + "px"});
	},
	formToJSON: function(form) {
		if (Browser.Engine.trident) {
			return $H(form).map(function(e){try {return e.value;}catch(error){return e;}});
		} else {
			var data = new Hash;
			$A(form.elements).each(function(e){data[e.name]=e.value});
			return data;
		}
	}
});

var HomeMap = new Class({
	Implements: Options,
	markers: [],
	options: {
		maxZoom: 9,
		mapApiUrl: "/js/maps-api.js"
	},
	initialize: function(lat, lng, options){
		// Updated to API v3
		if (!$("map_canvas")) return;
		try {
			this.setOptions(options);
			this.map = new google.maps.Map($("map_canvas"), {
				zoom: 9,
				center: new google.maps.LatLng(lat, lng),
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				disableDoubleClickZoom: true,
				scrollwheel: false
			});
			this.addMapCorners();
		} catch(e) {
			this.map = null;
		}
	},
	addDestination: function(zone) {
		if (!this.map) return;
		var mk_name = (zone.count<100)? zone.count: "more";
		var mk = new google.maps.Marker({
			'position': new google.maps.LatLng(zone.location[0], zone.location[1]),
			"title": "{name} ({count})".substitute(zone),
			'map': this.map,
			'clickable': true,
			'dragable': false,
			icon: '/img/markers/'+mk_name+'.png'
		});
		google.maps.event.addListener(mk, 'click', function(){
			form.searchForm.destination_map.value = zone.leftright;
			form.searchForm.page.value = 0;
			form.search();
		});
		this.markers.push(mk);
	},
	zoomMarkers: function() {
		if (!this.map) return;
		var bounds = new google.maps.LatLngBounds();
		[av_center.se, av_center.nw].each(function(i) {
			var pos = new google.maps.LatLng(i[0], i[1]);
			bounds.extend(pos);
		});
		var bounds = new google.maps.LatLngBounds(
			new google.maps.LatLng(av_center.nw[0], av_center.nw[1]),
			new google.maps.LatLng(av_center.se[0], av_center.se[1])
		);
		this.map.fitBounds(bounds);
		if (this.map.getZoom() > 14) this.map.setZoom(14);
		this.map.panToBounds(bounds);
	},
	addMapCorners: function() {
		['map_tl','map_tr','map_bl','map_br'].each(function(e){
			$("map_canvas").grab(new Element('div', {'id': e}));
		});
	},
	loadApi: function(){
		var script = new Element("script", {"type":"text/javascript", "src": this.options.mapApiUrl});
		$(document.body).adopt(script);
	}
});

