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

var Booking = {
	init: function() {
		$("booking").addEvent("submit", Booking.send);
		$("destination_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;
			$("destination_2").value = $("destination_1").value;
			$("place_2").value = $("place_1").value;
		}
		$$(".date").each(function(i) { i.value = i.value.replace(/^0/, "").replace("/0", "/");});
		return true;
	}
}

var Dests = {
	init: function() {
		// this.initWicks()
		try { Maps.create($("map")); }
		catch(err) {}
		Dests.fillDests();
		$("showReturnLink").addEvent("click", Dests.showReturn);
	},
	initWicks: function() {
		Dests.wk = new Wick( $("destination"), {
			ajaxUrl: Dests.cnf.ajx, listFilter: Dests.filterByCountry,
			valueField: "O", textField: "N-1", searchFields: ["N-2","N-3","F-1","F-2","F-3"], hiddenField: "dest_1"
		}).addEvents({
			"match": function() {
				Dests.fillPlaces("place_1", Dests.wk.entry.P);
				$("lb_place").removeClass("inv");
				$("country").value = Dests.wk.entry.C;
			},
			"dematch": function() {
				$("lb_place").addClass("inv");
				if (!Dests.wk2.valid) $("country").value = "";
			}
		});
		Dests.wk2 = new Wick( $("destination_2"), {
			ajaxUrl: Dests.cnf.ajx, listFilter: Dests.filterByCountry,
			valueField: "O", textField: "N-1", searchFields: ["N-2","N-3","F-1","F-2","F-3"], hiddenField: "dest_2"
		}).addEvents({
			"match": function() {
				Dests.fillPlaces("place_2", Dests.wk2.entry.P);
				$("lb_place_2").removeClass("inv");				
				$("country").value = Dests.wk2.entry.C;
			},
			"dematch": function() {
				$("lb_place_2").addClass("inv");
				if (!Dests.wk.valid) $("country").value = "";
			}
		});
	},
	first: true,
	setDest: function(dest, index) {
		var entry = this.list[index];
		$("dest_"+dest).value = entry.O;
		$("place_"+dest).value = entry.P[0];
		$("destination_"+dest).value = entry.O;
		if (dest==1 && !Dests.first)
			Maps.zoomMap(entry.LT, entry.LN);
		else
			Dests.first = false;
	},
	showReturn: function() {
		$("showReturnDest").setStyles({"height": 0, "padding": 0});
		$("returnDest").removeClass("hid");
		$("destination_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':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() {
		this.list.each(function(i, idx) {
			try {
			var mk = Maps.newMarker(i);
			GEvent.addListener(mk, "click", function() { Dests.setDest(1, idx); });
			} catch(err) {}
			$("destination_1").grab(new Element("option", {value: i.O}).set("html", i["N-"+i18n.lang]));			
			$("destination_2").grab(new Element("option", {value: i.O}).set("html", i["N-"+i18n.lang]));
		});
		$("destination_1").addEvent("change", function(ev) { Dests.setDest(1, ev.target.selectedIndex)});
		$("destination_2").addEvent("change", function(ev) { Dests.setDest(2, ev.target.selectedIndex)});
		Maps.zoomMarkers();
		Dests.setDest(1, $("destination_1").selectedIndex)
		Dests.setDest(2, $("destination_2").selectedIndex)
	},
	list: [
		{'O':1026,'N-3':"Mallorca - Am Flughafen",'F-3':"mallorca---am-flughafen",'N-2':"Majorca - Airport",'F-2':"majorca---airport",'N-1':"Mallorca - Aeropuerto",'F-1':"mallorca---aeropuerto",'A':"PMI",'C':32,'P':[1],
			'LT':39.547603, 'LN':2.730618},
		{'O':1039,'N-3':"Mallorca - El Arenal", 'F-3':"mallorca---el-arenal",
			'N-2':"Majorca - El Arenal",'F-2':"majorca---el-arenal",
			'N-1':"Mallorca - El Arenal",'F-1':"mallorca---el-arenal",
			'A':"",'C':32,'P':[3,6],'LT':39.509087, 'LN':2.751250},
		{'O':1048,'N-3':"Mallorca - Puerto Soller",'F-3':"mallorca---puerto-soller",'N-2':"Majorca - Puerto Soller",'F-2':"majorca---puerto-soller",'N-1':"Mallorca - Puerto Soller",'F-1':"mallorca---puerto-soller",'A':"",'C':32,'P':[3,6],
			'LT': 39.794884, 'LN':2.696867},		
		{'O':1027,'N-3':"Mallorca - Alcudia",'F-3':"mallorca---alcudia",
			'N-2':"Majorca - Alcudia",'F-2':"majorca---alcudia",
			'N-1':"Mallorca - Alcudia",'F-1':"majorca---alcudia",
			'A':"",'C':32,'P':[3], 'LT': 39.85200583899987, 'LN':3.1238937377929688},
		{'O':1033,'N-3':"Mallorca - Cala Ratjada",'F-3':"mallorca---cala-ratjada",
			'N-2':"Majorca - Cala Ratjada",'F-2':"majorca---cala-ratjada",
			'N-1':"Mallorca - Cala Ratjada",'F-1':"majorca---cala-ratjada",
			'A':"",'C':32,'P':[3], 'LT': 39.71131348440835, 'LN':3.462367057800293},
		{'O':1050,'N-3':"Mallorca - Santa Ponsa",'F-3':"mallorca---santa-ponsa",
			'N-2':"Majorca - Santa Ponsa",'F-2':"majorca---santa-ponsa",
			'N-1':"Mallorca - Santa Ponsa",'F-1':"majorca---santa-ponsa",
			'A':"",'C':32,'P':[3], 'LT': 39.50774921888317, 'LN':2.477846145629883},
		{'O':1032,'N-3':"Mallorca - Cala Millor",'F-3':"mallorca---cala-millor",
			'N-2':"Majorca - Cala Millor",'F-2':"majorca---cala-millor",
			'N-1':"Mallorca - Cala Millor",'F-1':"majorca---cala-millor",
			'A':"",'C':32,'P':[3], 'LT': 39.60535753628011, 'LN':3.386406898498535},
		{'O':1923,'N-3':"Malaga - Am Flughafen",'F-3':"malaga-am-flughafen",'N-2':"Malaga - Airport",'F-2':"malaga-airport",
			'N-1':"Malaga - Aeropuerto",'F-1':"malaga-aeropuerto",'A':"",'C':32,'P':[1],
			'LT': 36.674019, 'LN':-4.491800},
		{'O':1913,'N-3':"Ibiza - Am Flughafen",'F-3':"ibiza-am-flughafen",'N-2':"Ibiza - Airport",'F-2':"ibiza-airport",
			'N-1':"Ibiza - Aeropuerto",'F-1':"ibiza-aeropuerto",'A':"",'C':32,'P':[1],
			'LT': 38.874956, 'LN':1.368283},
		{'O':1916,'N-3':"Alicante - Am Flughafen",'F-3':"alicante-am-flughafen",'N-2':"Alicante - Airport",'F-2':"alicante-airport",
			'N-1':"Alicante - Aeropuerto",'F-1':"alicante-aeropuerto",'A':"",'C':32,'P':[1],
			'LT': 38.285739, 'LN':-0.561481},
		{'O':1912,'N-3':"Girona - Am Flughafen",'F-3':"girona-am-flughafen",'N-2':"Girona - Airport",'F-2':"girona-airport",
			'N-1':"Girona - Aeropuerto",'F-1':"girona-aeropuerto",'A':"Gerona",'C':32,'P':[1],
			'LT': 41.900211, 'LN':2.764008},
		{'O':1926,'N-3':"Menorca - Am Flughafen",'F-3':"menorca-am-flughafen",'N-2':"Menorca - Airport",'F-2':"menorca-airport",
			'N-1':"Menorca - Aeropuerto",'F-1':"menorca-aeropuerto",'A':"",'C':32,'P':[1],
			'LT': 39.865167, 'LN':4.223833},
		{'O':1915,'N-3':"Valencia - Am Flughafen",'F-3':"valencia-am-flughafen",'N-2':"Valencia - Airport",'F-2':"valencia-airport",
			'N-1':"Valencia - Aeropuerto",'F-1':"valencia-aeropuerto",'A':"",'C':32,'P':[1],
			'LT': 39.491064, 'LN':-0.477375},	
		{'O':1917,'N-3':"Sevilla - Am Flughafen",'F-3':"sevilla-am-flughafen",'N-2':"Seville - Airport",'F-2':"seville-airport",
			'N-1':"Sevilla - Aeropuerto",'F-1':"sevilla-aeropuerto",'A':"",'C':32,'P':[1],
			'LT': 37.423400, 'LN':-5.899394},
		{'O':1911,'N-3':"Madrid - Am Flughafen",'F-3':"madrid-am-flughafen",'N-2':"Madrid - Airport",'F-2':"madrid-airport",
			'N-1':"Madrid - Aeropuerto",'F-1':"madrid-aeropuerto",'A':"",'C':32,'P':[1],
			'LT': 40.491242, 'LN':-3.592525},
		{'O':1914,'N-3':"Barcelona - Am Flughafen",'F-3':"jerez-de-la-frontera-am-flughafen",'N-2':"Barcelona - Airport",'F-2':"barcelona-airport",
			'N-1':"Barcelona - Aeropuerto",'F-1':"barcelona-aeropuerto",'A':"",'C':32,'P':[1],
			'LT': 41.303231, 'LN':2.078667},
		{'O':1924,'N-3':"Jerez de la Frontera - Am Flughafen",'F-3':"jerez-de-la-frontera-am-flughafen",'N-2':"Jerez de la Frontera - Airport",'F-2':"jerez-de-la-frontera-airport",
			'N-1':"Jerez de la Frontera - Aeropuerto",'F-1':"jerez-de-la-frontera-aeropuerto",'A':"",'C':32,'P':[1],
			'LT': 36.747972, 'LN':-6.061600}
	]
	/*	 
	list: [
		{'O':1026,'N-3':"Mallorca - Am Flughafen",'F-3':"mallorca---am-flughafen",'N-2':"Majorca - Airport",'F-2':"majorca---airport",'N-1':"Mallorca - Aeropuerto",'F-1':"mallorca---aeropuerto",'A':"PMI",'C':32,'P':[1],
			'LT':39.547603, 'LN':2.730618},
		{'O':1039,'N-3':"Mallorca - El Arenal",'F-3':"mallorca---el-arenal",'N-2':"Majorca - El Arenal",'F-2':"majorca---el-arenal",'N-1':"Mallorca - El Arenal",'F-1':"mallorca---el-arenal",'A':"",'C':32,'P':[3,6],
			'LT':39.509087, 'LN':2.751250},
		{'O':1048,'N-3':"Mallorca - Puerto Soller",'F-3':"mallorca---puerto-soller",'N-2':"Majorca - Puerto Soller",'F-2':"majorca---puerto-soller",'N-1':"Mallorca - Puerto Soller",'F-1':"mallorca---puerto-soller",'A':"",'C':32,'P':[3,6],
			'LT': 39.794884, 'LN':2.696867}
	]
	*/
}

var BDates = {
	init: function() {
		BDates.fillTime();
		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("");
	},
	cnf: {
		timeTpl: "<option class='{class}' value='{h}:{m}' {extra}>{h}:{m}</option>"
	}
}

var Maps = {
	request: null,
	markers: new Array(),
	step: 200,
	zoom: 8,
	centerLat: 39.6,
	centerLng: 2.92,
	iconUrl: "http://www.cardiddy.com:11112/",
	create: function(element, filter) {
		if (!$(element)) return;		
		this.element = $(element);
		var latlng = new GLatLng(this.centerLat, this.centerLng);        
        this.map = new GMap2($(element));
		this.map.setCenter(latlng, this.zoom);
		this.map.disableDoubleClickZoom();
		this.map.disableDragging();
		this.map.getContainer().adopt(
			new Element("div", {"id":"map_tl", "class":"map_corner"}),
			new Element("div", {"id":"map_tr", "class":"map_corner"}),
			new Element("div", {"id":"map_bl", "class":"map_corner"}),
			new Element("div", {"id":"map_br", "class":"map_corner"})
		);
	},
	zoomMap: function(lat, lng) {
		if (this.map.getZoom() != this.zoom)
			this.map.setZoom( this.zoom );
		this.map.panTo(new GLatLng(lat, lng));
		// this.map.setCenter( new GLatLng(lat, lng), this.zoom);
	},
	addMarker: function(marker) {
		this.markers.push(marker);
		this.map.addOverlay(marker);
	},
	newMarker: function(point) {
		try {
			var marker = new GMarker(new GLatLng(point.LT, point.LN), {
				title: point["N-" + i18n.lang],
				icon: Maps.cddIcon()
			})
			this.addMarker(marker);
			return marker;
		} catch(e) { log(e); return null; }
	},
	cddIcon: function() {
		var icon = new GIcon();
		icon.image = "img/cdd_home/marker_cdd.png";
        icon.shadow = "img/cdd_home/marker_shadow_cdd.png";
        icon.iconSize = new GSize(31, 33);
        icon.shadowSize = new GSize(51, 33);
        icon.iconAnchor = new GPoint(15, 34);
        icon.infoWindowAnchor = new GPoint(15, 2);
		return icon;
	},
	zoomMarkers: function(max) {
		var bounds = new GLatLngBounds();
		this.markers.each(function(i) { bounds.extend(i.getLatLng())});
		var zoom = Math.max(max||0, this.map.getBoundsZoomLevel(bounds))
		this.map.setCenter( bounds.getCenter(), zoom);
	}
}

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"
	},
	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"		
	},
	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"	
	}
}

// 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 log(msg) { try { console.log(msg) } catch(e) { } }
