window.addEvent("domready", function() {
	i18n.lang = $("lang").value;
	Booking.init();
	Dests.init();
	BDates.init();	
	Defaults.init();
	writeSocial();
	addFbBox();
});

var Booking = {
	init: function() {
		$("booking").addEvent("submit", Booking.send);
		$("dest_1").focus();
	},
	validate: function() {
		var errors = [];
		/*
		if (!Dests.wk.valid)
			errors.push(i18n.get("pickupDestError"));
		if ($("oneway").value=="1" && !Dests.wk2.valid)
			errors.push(i18n.get("returnDestError"));
		*/
		if ($("pickupDate").value == "")
			errors.push(i18n.get("pickupDateError"));
		if ($("returnDate").value == "")
			errors.push(i18n.get("returnDateError"));
		if (errors.length > 0) {
			Booking.showErrors(errors);
			return false;
		}
		return true;
	},
	showErrors: function(errors) {
		alert(i18n.get("correctErrors") + ":\n - " + errors.join("\n - "));
	},
	send: function(ev) {
		// log(ev);
		if (!Booking.validate()) return false;
		BDates.setTime("pickup_time", "from_hour", "from_minute");
		BDates.setTime("return_time", "to_hour", "to_minute");
		if ($("oneway").value == "0") {
			// $("dest_2").value = $("dest_1").value;
			$("dest_2").value = $("dest_1").value;
			$("place_2").value = $("place_1").value;
		}
		$$(".date").each(function(i) { i.value = i.value.replace(/^0/, "").replace("/0", "/");});
		return true;
	}
}

_l = function(msg) { try { console.log(msg); } catch(ex) {}}

var Dests = {
	init: function() {
		// this.initWicks()
		// try { Maps.create($("map")); }
		// catch(err) {}
		// Dests.fillDests();
		this.initSelects();
		$("showReturnLink").addEvent("click", Dests.showReturn);
	},
	initSelects: function() {
		$("country").addEvent("change", this.loadDests.bind(this));
		$("dest_1").addEvent("change", function() { this.loadPlaces(1); }.bind(this));
		$("dest_2").addEvent("change", function() { this.loadPlaces(2); }.bind(this));
		$("place_1").addEvent("change", this.onewayPlace.bind(this));
		this.loadDests();
	},
	loadDests: function() {
		if (this.request) this.request.cancel();
		this.request = new Request({
			url: "/front/DestinationsJson.action",
			data: {lang: i18n.lang, country: $("country").value},
			onSuccess: this.showDests.bind(this)
		}).send();
	},
	showDests: function(res) {
		var dlist = JSON.decode(res);
		var opts = $A(dlist).map(function(i) {
			return "<option value='{id}'>{displayName}</option>".substitute(i);
		}).join(" ");
		$("dest_1").innerHTML = $("dest_2").innerHTML = opts;
		if (Dests.first) {
			$("dest_1").set("value", 4234);
			Dests.first = false;
		}
		$("dest_1").fireEvent("change");
		$("dest_2").fireEvent("change");
	},
	loadPlaces: function(dest_id) {
		if (dest_id==1 && $("oneway").value==0)
			$("dest_2").value = $("dest_1").value;
		if (dest_id==2 && $("oneway").value==0)	return;
		// if (this.request2) this.request2.cancel();
		new Request({
			url: "/front/ValidPlacesJson.action",
			data: { destination: $("dest_"+dest_id).value },
			onSuccess: function(res) { this.showPlaces(res, dest_id); }.bind(this)
		}).send();
	},
	showPlaces: function(res, dest_id) {
		var plist = JSON.decode(res);
		var opts = $A(plist).map(function(i) {
			return "<option value={id}>{name}</option>".substitute({id: i, name: i18n.get("places")[i]});
		}).join(" ");
		this.setPlaceOptions(dest_id, opts);
		if (dest_id==1 && $("oneway").value==0)
			this.setPlaceOptions(2, opts);
	},
	setPlaceOptions: function(d_id, opts) {
		$("place_"+d_id).innerHTML = opts;
		
	},
	onewayPlace: function() {
		if ($("oneway").value==0) $("place_2").value = $("place_1").value;
	},
	first: true,
	setDest: function(dest, index) {
		var entry = this.list[index];
		$("dest_"+dest).value = entry.O;
		$("place_"+dest).value = entry.P[0];
		$("dest_"+dest).value = entry.O;
	},
	showReturn: function() {
		$("showReturnDest").setStyles({"height": 0, "padding": 0});
		$("returnDest").removeClass("hid");
		$("dest_2").focus();
		$("oneway").value = 1;
	},
	filterByCountry: function(i) {
		if ($("country").value < " ") return true;
		return (i.C == $("country").value);
	},
	fillPlaces: function(control, list) {
		var res = list.map(function(i) { return Dests.cnf.placeTpl.substitute({'v':i, 't':i18n.get("places")[i]})});
		$(control).set("html", res.join(""));
	},
	cnf: {
		placeTpl: "<option value='{v}'>{t}</option>",
		// ajx: "js/dest_a.json"		
		ajx: "DestinationsByLetterJson.action?lang=2&letter=[l]"
	},
	// Home Lite
	fillDests: function() {
		var op_tpl = "<option value='{v}'>{t}</option>";
		var group_tpl = "<optgroup label='{t}'>";
		var groupend_tpl = "</optgroup>"
		
		this.list = this.rawlist.filter(function(i) { return i.O!="group" && i.O!="group_end"; });
		this.counter = 0;
		var tx_list = this.rawlist.map(function(i, idx) {			
			if (i.O=='group')
				return group_tpl.substitute({'t':i['N-'+i18n.lang]});
			else if (i.O=='group_end')
				return groupend_tpl;
			else {
				try {
					var mk = Maps.newMarker(i);
					var c = Dests.counter;
					GEvent.addListener(mk, "click", function() { Dests.setDest(1, c); });
					Dests.counter++;
				} catch(err) {}
				return op_tpl.substitute({'v': i.O, 't': i['N-'+i18n.lang]});
			}
		}).join("");
		$("dest_1").set("html", tx_list);
		$("dest_2").set("html", tx_list);
		$("dest_1").addEvent("change", function(ev) { Dests.setDest(1, ev.target.selectedIndex)});
		$("dest_2").addEvent("change", function(ev) { Dests.setDest(2, ev.target.selectedIndex)});
		Maps.zoomMarkers();
		Dests.setDest(1, $("dest_1").selectedIndex)
		Dests.setDest(2, $("dest_2").selectedIndex)
	}
}

var BDates = {
	init: function() {
		BDates.fillTime();
		BDates.setDefault();
		BDates.cal = new Calendar({
			pickupDate: i18n.get("dateFormat"),
			returnDate: i18n.get("dateFormat")
		}, {classes: ['dashboard'], direction: 2, navigation: 1, offset:1, tweak: {x:-100, y:20},
			months: BDates.getMonths(), days: BDates.getWeekDays()});
	},
	fillTime: function() {
		var timeOps = BDates.getTimeOptions();
		$$(".time").set("html", timeOps);
	},
	setTime: function(value, hour, minute) {
		var time = $(value).value.split(":");
		// $(hour).value = (time[0].length==1)? "0"+time[0]:time[0];
		$(hour).value = time[0];
		$(minute).value = time[1];
	},
	getMonths: function() { return i18n.get("months"); },
	getWeekDays: function() { return i18n.get("weekDays"); },
	getTimeOptions: function() {
		var res = [];
		for(var h=0; h<24; h++) {
			["00","15","30","45"].each(function(i) {
				res.push( BDates.cnf.timeTpl.substitute({'class': (i=="00")?'oclock':'', h: h, m: i,
					'extra': (h==12 && i=="00")?'selected="selected"':''}))
			});			
		}
		return res.join("");
	},
	setDefault: function() {
		if ($("pickupDate").value=="") {
			var now = new Date();
			var def_pick = new Date(); def_pick.setDate(now.getDate()+7);
			var def_return = new Date(); def_return.setDate(now.getDate()+10);
			$("pickupDate").value = this.dateStr(def_pick);
			$("returnDate").value = this.dateStr(def_return);
		}
	},
	dateStr: function(d) {
		var td = function(v) { return (v>9)?v:"0"+v; }
		return td(d.getDate()) + "/" + td(d.getMonth()+1) + "/" + td(d.getFullYear());
	},
	cnf: {
		timeTpl: "<option class='{class}' value='{h}:{m}' {extra}>{h}:{m}</option>"
	}
}

var Defaults = {
	query: null,
	init: function() {
		if (this.getQS("refId"))
			$("booking").grab(new Element("input",
				{ "type":"hidden", "name":"refId", "id":"refId", "value":this.getQS("refId")}
			));
		if (this.getQS("promotion_code"))
			$("promotion_code").set("value", this.getQS("promotion_code"));
	},
	getQS: function(key) {
		this.buildQS();
		return this.query[key];
	},
	buildQS: function() {
		if (this.query) return;
		this.query = new Hash();
		if (location.search < " ") return;
		location.search.substring(1).split("&").each(function(i) {
			var kv=i.split("="); Defaults.query[kv[0]]=kv[1]; });
	}
}

var i18n = {
	lang: 1,
	get: function(key) {
		return this[this.lang][key];
	},
	1: {	// Español
		dateFormat: 'd/m/Y',
		weekDays: ["Domingo","Lunes","Martes","Miercoles","Jueves","Viernes","Sábado"],
		months: ["enero","febrero","marzo","abril","mayo","junio","julio","agosto",
				"septiembre","octubre","noviembre","diciembre"],
		pickupDestError: "Destino de recogida",
		retunrDestError: "Destino de devolución",
		pickupDateError: "Fecha de recogida",
		returnDateError: "Fecha de devolución",
		correctErrors: "Por favor, corrige los siguientes errores",
		places: {
				1: "Aeropuerto", 2: "Centro Comercial", 4:"Puerto",
				6:"Hotel", 3:"Oficina", 5:"Estación Marítima",
				8:"Centro Urbano", 7:"Estación de tren"}
	},
	2: {	// English
		dateFormat: 'd/m/Y',
		weekDays: ["Sunday","Monday","Thuesday","Wednesday","Thursday","Friday","Saturday"],
		months: ["January","February","March","April","May","June","July","August",
				"September","October","November","December"],
		pickupDestError: "Pick-Up",
		retunrDestError: "Drop-Off",
		pickupDateError: "Pick-Up date",
		returnDateError: "Drop-Off date",
		correctErrors: "Please be so kind to correct the following error",
		places: {
				1: "Airport", 2: "Comercial Center", 4:"Harbour",
				6:"Hotel", 3:"Office", 5:"Port",
				8:"Down Town", 7:"Train Station"}
	},
	3: {	// Deutch
		dateFormat: 'd/m/Y',
		weekDays: ["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"],
		months: ["Januar","Februar","März","April","Mai","Juni","Juli","August",
				"September","Oktober","November","Dezember"],	
		pickupDestError: "Ort der Anmietung",
		retunrDestError: "Ort der Rückgabe",
		pickupDateError: "Anmietdatum",
		returnDateError: "Rückgabedatum",
		correctErrors: "Bitte korrigieren Sie den folgenden Fehler",
		places: {
				1: "Flughafen", 2: "Comercial Zentrum", 4:"Hafen",
				6:"Hotel", 3:"Lieferstation", 5:"Hafen",
				8:"Stadtzentrum", 7:"Bahnhof"}
	}
}

// Social links
var social = [{
		name: "del.icio.us",
		icon: "img/icons/delicious.png",
		url: "http://del.icio.us/post?url={URL}&title={title}"
	},{
		name: "Google Bookmarks",
		icon: "img/icons/google.png",
		url: "http://www.google.com/bookmarks/mark?op=edit&bkmk=#docurl&title=#doctitle"
	},{
		name: "Mister Wong",
		icon: "img/icons/misterwong.png",
		url: "http://www.mister-wong.com/index.php?action=addurl&bm_url=#docurl&bm_description=#doctitle"
	},{
		name: "LinkARENA",
		icon: "img/icons/linkarena.png",
		url: "http://linkarena.com/bookmarks/addlink/?url=#docurl&title=#doctitle&desc="
}]

function writeSocial() {
	if (!$("bookmark")) return;
	social.each(function(i) {
		var sUrl = i.url.substitute(document);
		$("bookmark").grab(new Element("a", {"href":sUrl})
			.set("html", "<img src='{icon}' alt='{name}' title='{name}' />".substitute(i)));
	});
}

function addFbBox() {
       if (!$("fbLikeBox")) return;
       $("fbLikeBox").set('html', '<iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fcardiddy&amp;width=292&amp;colorscheme=light&amp;connections=5&amp;stream=false&amp;header=false&amp;height=198"'+
         ' scrolling="no" frameborder="0" id="fb_likebox" allowTransparency="true">  </iframe>');
}

function log(msg) { try { console.log(msg) } catch(e) { } }

