Ext.namespace("BookingForm");

BookingForm = {
	
	InitQuickQuote: function() {
		Ext.BLANK_IMAGE_URL = "haute/extjs/resources/images/default/s.gif";
		
		//Event.observe($("AirportRoute"), "change", BookingForm.ToggleRouteType);
		//Event.observe($("InResortRoute"), "change", BookingForm.ToggleRouteType);
		
		//Event.observe($("FromAirport"), "change", BookingForm.RouteChanged);
		//Event.observe($("ToAirport"), "change", BookingForm.RouteChanged);
		//Event.observe($("FromResort"), "change", BookingForm.RouteChanged);
		//Event.observe($("ToResort"), "change", BookingForm.RouteChanged);
		
		//Event.observe($("OneWay"), "click", BookingForm.ReturnChanged);
		//Event.observe($("Return"), "click", BookingForm.ReturnChanged);
		
		//Event.observe($("AirportRouteLink"), "click", BookingForm.ClickAirportRoute);
		//Event.observe($("InResortRouteLink"), "click", BookingForm.ClickInResortRoute);
		//Event.observe($("OneWayLink"), "click", BookingForm.ClickedOneWay);
		//Event.observe($("ReturnLink"), "click", BookingForm.ClickedReturn);
		
		BookingForm.MakeTimePicker(1);
		BookingForm.MakeTimePicker(2);
		BookingForm.DatePickers = {};
		BookingForm.AddDatePicker(1);
		BookingForm.AddDatePicker(2);
		Event.observe($("GetQuote"), "click", BookingForm.GetQuote);

		Event.observe($("Passengers"), "change", BookingForm.OnQuoteInputChanged);
		Event.observe($("Date1"), "change", BookingForm.OnQuoteInputChanged);
		Event.observe($("Date2"), "change", BookingForm.OnQuoteInputChanged);
		Event.observe($("Hour1"), "change", BookingForm.OnQuoteInputChanged);
		Event.observe($("Minute1"), "change", BookingForm.OnQuoteInputChanged);
		Event.observe($("Hour2"), "change", BookingForm.OnQuoteInputChanged);
		Event.observe($("Minute2"), "change", BookingForm.OnQuoteInputChanged);

		Event.observe($("SubmitForm"), "click", BookingForm.SubmitForm);
		
		Event.observe($("MakeSame1"), "click", BookingForm.MakeSame.bind(this, 1));
		Event.observe($("MakeSame2"), "click", BookingForm.MakeSame.bind(this, 2));
		
		document.onclick = BookingForm.OnDocClick;
	},
	
	HaveQuoted: false,
	NeedsReQuote: false,
	
	OnQuoteInputChanged: function() {
		if(BookingForm.HaveQuoted) {
			if(!BookingForm.NeedsRequote) {
				Oasys.showMessage("Please click the 'Get Quote' button again to re-price this journey.");
				$("Step2").style.display = "none";
				BookingForm.HaveQuoted = false;
			}
			BookingForm.NeedsRequote = true;
		}
	},
	
	MakeSame: function(index) {
		if(index == 1) {
			$("FromAddress2").value = $("ToAddress1").value;
		} else {
			$("ToAddress2").value = $("FromAddress1").value;
		}
	},
	
	SubmitForm: function() {
		
		var data = BookingForm.GetQuoteData();
		data.fullName = $("Name").value;
		data.mobile = $("Mobile").value;
		data.email = $("Email").value;
		data.notes = $("CustomerNotes").value;
		data.flight1Number = $("FlightNumber1").value;
		data.flight2Number = $("FlightNumber2").value;
		data.t1From = $("FromAddress1").value;
		data.t1To = $("ToAddress1").value;
		data.t2From = $("FromAddress2").value;
		data.t2To = $("ToAddress2").value;

		data.transferTypeId = null;
		if(BookingForm.QuoteResults.Options.length > 0) {
			var index = 1;
			for(var i=0; i < BookingForm.QuoteResults.Options.length; i++) {
				if($("Option" + index).checked) {	
					 data.transferTypeId = $("Option" + index).value;
					 break;
				}
				index++;
			}
		} else if($("EnqType").value != "") {
			data.transferTypeId = $("EnqType").value;
		}
		
		if(data.transferTypeId == null) {
			Oasys.showErrors(["Please select your desired transfer type."]);
			return;
		}
		
		if(aff != null) {
			if($("PayCc").checked) {
				data.paymentMethod = 2;
				data.isEnquiry = false;
			} else if($("PayCash").checked) {
				data.paymentMethod = 1;
				data.isEnquiry = true; //? assume so, even though "available for isntant"... 
			} else {
				data.paymentMethod = null;
				data.isEnquiry = true;
			} 
			
			data.fromAffiliate = aff.AffiliateId;
		} else {
			data.fromAffiliate = $("Accomm").value == "" ? null : $("Accomm").value;
			
			//client has no choice but to pay by cc, if this option available:
			data.isEnquiry = (BookingForm.CanPayOptions[data.transferTypeId] == null);
		}
		
		data.optionIds = [];
		data.optionValues = [];
		for(var i=0; i < transferOptions.length; i++) {
			data.optionIds.push(transferOptions[i].id);
			data.optionValues.push($("Option_" + transferOptions[i].id).value);
		}
		
		Oasys.callMethod(
			"MakeBooking", 
			data, 
			data.isEnquiry ? "Sending enquiry..." : "Please wait...",
			BookingForm.OnSuccess2, 
			BookingForm.OnFailure2
		);
	},
	
	OnFailure2: function() { },
	
	GetQuoteData: function() {
		var data = {
			language: "en",
			passengers: $("Passengers").value,
			isRoundTrip: $("Return").checked,
			sDate1: $("Date1").value,
			hour1: $("Hour1").value,
			minute1: $("Minute1").value,
			sDate2: $("Date2").value,
			hour2: $("Hour2").value,
			minute2: $("Minute2").value,
			swClientId: 6
		};
		
		if($("AirportRoute").checked) {
			data.fromPlaceId = $("FromAirport").value;
			data.toPlaceId = $("ToAirport").value;
		} else {
			data.fromPlaceId = $("FromResort").value;
			data.toPlaceId = $("ToResort").value;
		}
		
		return data;
	},
	
	GetQuote: function() {

		Oasys.callMethod(
			"GetQuote", 
			BookingForm.GetQuoteData(), 
			"Getting quote...",
			BookingForm.OnSuccess, 
			BookingForm.OnQuoteFailure
		);
	},
	
	ClickedOption: function(optionId) {
		var options = Ext.select(".Option").elements;
		for(var i=0; i < options.length; i++) {
			options[i].className = "Option";
		}
		
		$("OptionDiv" + optionId).className = "Option SelOption";
		$("Option" + optionId).checked = true;
		
		BookingForm.OptionChanged($("Option" + optionId).value);
	},

	OnSuccess2: function(response) { 
		if(response.SuccessMessage != null) {
			// as in, enquiry sent, show a message to confirm:
			Oasys.showMessage(response.SuccessMessage);
			$("pageBody").hide();
		} else if(response.FormRedirectAction != null) {
			// we're supposed to submit a form to redirect them to the bank:
			$("payboxForm").action = response.FormRedirectAction;
			$("payboxForm").innerHTML = response.FormRedirectContents;
			$("payboxForm").submit();
		} else if(response.RedirectUrl != null) {
			document.location.href = response.RedirectUrl;
		}
	},

	OnSuccess: function(results) {
		
		var optionDesc = {
			7: "<ul><li>Lowest Fare available</li>"
+ "<li>Central Meeting Point</li>"
+ "<li>Shared transfer (waiting time up to 45 minutes)</li>"
+ "<li>Available for Round Trip Only</li>"
+ "<li>Transferable for 15€ fee</li>"
+ "<li>Non-refundable</li></ul>",
			8: "<ul><li>8 Seater Renault Traffic</li>"
+ "<li>Driver meets you in arrivals</li>"
+ "<li>Door-to-door service</li>"
+ "<li>Available for Single and Round Trip Fares</li>"
+ "<li>Complimentary refreshments</li>"
+ "<li>Refundable</li>"
+ "<li>Transferable free of charge</li></ul>",

			19: "<ul><li>Driver meets you in arrivals</li>"
+ "<li>Door-to-door service</li>"
+ "<li>Available for Single and Round Trip Fares</li>"
+ "<li>Complimentary refreshments</li>"
+ "<li>Refundable</li>"
+ "<li>Transferable free of charge</li></ul>",

			20: "<ul><li>7 Seater Mercedes Viano</li>"
+ "<li>Driver meets you in arrivals</li>"
+ "<li>Door-to-door service</li>"
+ "<li>Available for Single and Round Trip Fares</li>"
+ "<li>Complimentary refreshments</li>"
+ "<li>Refundable</li>"
+ "<li>Transferable free of charge</li></ul>"
		};
		
		BookingForm.HaveQuoted = true;
		BookingForm.NeedsRequote = false;
		var html = "";
		BookingForm.QuoteResults = results;
		if(results.Options.length == 0) {
			$("OptionPrefix").innerHTML = "We are not able to give you an online price quote for this journey. Please fill out the following enquiry form and we will get back to you within 24 hours.";
			$("EnqTypeTr").style.display = "";
		} else {
			$("EnqTypeTr").style.display = "none";
			$("OptionPrefix").innerHTML = "";
			BookingForm.CanPayOptions = { };
			BookingForm.CanPay = false;
			for(var i=0; i < results.Options.length; i++) {
				var option = results.Options[i];
				//option.AllowInstantBuy = false; ///until paybox ready
				var pricing;
				if($("AirportRoute").checked) {
					//show pricing per person/direction
					var ppp = option.Price / $("Passengers").value;
					
					pricing = "€" + sprintf("%.2f", Math.round(ppp*100)/100) + "/person";
				} else {
					pricing = "€" + sprintf("%.2f", option.Price);
				}
				
				if(option.ListPrice != null && option.ListPrice != option.Price) {
					detailText = " <span style='color:green;'>(with your affiliate discount)</span> List price: ";
					
					if(option.ListPrice == null) {
						detailText += "not available<br/>";
					} else {
						detailText += "€" + sprintf("%.2f", option.ListPrice) + "<br/>";
					}
				} else {
					detailText = "";
				}
				
				if(option.AllowInstantBuy) {
					BookingForm.CanPay = true;
					BookingForm.CanPayOptions[option.OptionId] = true;
				}
				
				html += "<div id='OptionDiv" + (i+1) + "' class='Option' onclick=\"BookingForm.ClickedOption(" + (i+1) + ")\"><div class='OptionDesc'>" + optionDesc[option.OptionId] + "</div><input type='radio' name='OptionId' onclick=\"BookingForm.ClickedOption(" + (i+1) + ")\" id='Option" + (i+1) + "' autocomplete='off' value='" + option.OptionId + "'/> "
					+ pricing + ($("Return").checked ? " (return)" : " (one way)")
					+ "<br/><span style='width:20px;display:inline-block'></span>" + option.MoreInfo + "<br/><div class='OptionDetails'>Total price: €" + sprintf("%.2f", option.Price) + " " + detailText + (option.AllowInstantBuy ? "Available for online booking and instant confirmation." : "Subject to availability. Confirmation within 24 hours") + "</div></div>";
			}
			
		}
		$("Options").innerHTML = html;
		
		if(places[BookingForm.GetFromPlaceId()].IsAirport
			|| places[BookingForm.GetToPlaceId()].IsAirport) {
			$("FlightNumber1Tr").style.display = "";
			$("FlightNumber2Tr").style.display = "";
		} else {
			$("FlightNumber1Tr").style.display = "none";
			$("FlightNumber2Tr").style.display = "none";
		}
		
		$("FromAddress1Tr").style.display = (places[BookingForm.GetFromPlaceId()].IsAirport) ? "none" : "";
		$("ToAddress2Tr").style.display = (places[BookingForm.GetFromPlaceId()].IsAirport) ? "none" : "";
		
		$("ToAddress1Tr").style.display = (places[BookingForm.GetToPlaceId()].IsAirport) ? "none" : "";
		$("FromAddress2Tr").style.display = (places[BookingForm.GetToPlaceId()].IsAirport) ? "none" : "";
		
		$("Transfer2").style.display = $("Return").checked ? "" : "none";
		
		BookingForm.OptionChanged();
		
		$("RouteDesc1").innerHTML = places[BookingForm.GetFromPlaceId()].Name + " to " + places[BookingForm.GetToPlaceId()].Name;
		
		if($("Return").checked) {
			$("RouteDesc2").innerHTML = places[BookingForm.GetToPlaceId()].Name + " to " + places[BookingForm.GetFromPlaceId()].Name;
		}
		
		//affiliates auto select if logged in:
		if(aff != null) {
			$("Accomm").value = aff.affiliateId;
		}
		
		$("PayWrapper").style.display = (aff != null) ? "" : "none";

		
		$("ReferredWrapper").style.display = (aff == null) ? "" : "none";

		$("Step2").style.display = "";
	},
	
	PayMethodChanged: function(newValue) {
		BookingForm.OptionChanged(BookingForm.CurrentOption);
	},
	
	OptionChanged: function(newId) {
		BookingForm.CurrentOption = newId;
		
		//aff has options for payment, so let them select. by default it's invoice me
		var cc;
		if(newId == null) {
			//no option selected yet so guess:
			if(aff != null) {
				//aff default to invoice me
				cc = false;
			} else if(BookingForm.CanPay) {
				//at least one cc option so assume that
				cc = true;
			}
			
			$("PayCcWrapper").style.display = "none";
		} else if(aff != null) {
			//allow aff to choose to pay, if this option allows it:
			$("PayCcWrapper").style.display = (BookingForm.CanPayOptions[newId] != null) ? "" : "none";
			if(BookingForm.CanPayOptions[newId] == null) {
				$("PayCc").checked = false;
			}
			
			cc = ($("PayCc").checked);
		} else {
			//customers must pay, if supported by the option
			cc = (BookingForm.CanPayOptions[newId] != null);
		}
		
		if(cc) {
			$("SubmitForm").value = "Proceed to payment";	
			$("CcLogos").style.display = "";
		} else {
			$("SubmitForm").value = aff == null ? "Send enquiry" : "Complete booking";	
			$("CcLogos").style.display = "none";
		}
	},
	
	GetFromPlaceId: function() {
		if($("AirportRoute").checked) {
			return $("FromAirport").value;
		} else {
			return $("FromResort").value;
		}
	},

	GetToPlaceId: function() {
		if($("AirportRoute").checked) {
			return $("ToAirport").value;
		} else {
			return $("ToResort").value;
		}
	},

	OnQuoteFailure: function(results) {
		
	},
	
	OnDocClick: function(e) {
		
		if(e == null) {
			element = event.srcElement;
		} else {
			element = e.element();
		}

		for( ; element.tagName != "BODY"; element = element.parentNode) {
			if(element.id == "CalPopup1"
			   || element.id == "CalPopup2"
			   || element.id == "CalTrigger1"
			   || element.id == "CalTrigger2"
			) {
				return;
			}
		}
		
		BookingForm.DatePickers[1].hide();
		//IE zindex bug:
		$("CalPopup2").style.visibility = "visible";
		BookingForm.DatePickers[2].hide();
	},
	
	AddDatePicker: function(dateId) {
		
		var datePicker = BookingForm.DatePickers[dateId] = new Ext.DatePicker({
			minDate: new Date(),
			listeners: {
				"select": BookingForm.OnDatePicked.bindAsEventListener(this, dateId)
			}
		});

		datePicker.index = dateId;

		datePicker.render("CalPopup" + dateId);
		datePicker.hide();
		
		BookingForm.DatePickers[dateId] = datePicker;
		
		Event.observe($("CalTrigger" + dateId), "click", BookingForm.DatePickerClicked.bindAsEventListener(this, datePicker));
	},
	
	DatePickerClicked: function(e, picker) {
		
		var textDate = BookingForm.ParseDate($("Date" + picker.index).value);
		
		if(textDate != null) {
			//value already set in text field. use it.
			picker.setValue(textDate);
		} else if(picker.index == 2 && BookingForm.ParseDate($("Date1")) != null) {
			//popping up date2. no date2 set yet, so use default of date1:
			picker.setValue(BookingForm.ParseDate($("Date1")));
		}
		// else, no dates to guess so use whatever ext defaults (today)
		picker.show();
		
		//hide other date picker:
		BookingForm.DatePickers[picker.index == 1 ? 2 : 1].hide();
		/*
		if(/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) && picker.index == 1) {
			//IE zindex bug:
			$("CalTrigger2").style.visibility = "hidden";
		}
		*/
	},
	
	ParseDate: function(value) {
		formats = [
			"d/m/y",
			"d/m/Y",
			"j/m/y",
			"j/m/Y",
			"d/n/y",
			"d/n/Y",
			"j/n/y",
			"j/n/Y" ];

		for(var i=0; i < formats.length; i++) {
			date = Date.parseDate(value, formats[i]);
			if(date) {
				return date;
			}
		}
		
		return null;
	},

	OnDatePicked: function(e, dateId) {
		$("Date" + dateId).value = BookingForm.DatePickers[dateId].getValue().format('d/m/Y');
		BookingForm.OnQuoteInputChanged();
		BookingForm.DatePickers[dateId].hide();
		//IE zindex bug:
		$("CalTrigger2").style.visibility = "visible";
	},
	
	ClickAirportRoute: function() { 
		$('AirportRoute').checked = true;
		BookingForm.OnQuoteInputChanged();
		BookingForm.ToggleRouteType();
	},

	ClickInResortRoute: function() { 
		$('InResortRoute').checked = true;
		BookingForm.OnQuoteInputChanged();
		BookingForm.ToggleRouteType();
	},

	ClickedOneWay: function() { 
		$('OneWay').checked = true;
		BookingForm.ReturnChanged();
	},

	ClickedReturn: function() { 
		$('Return').checked = true;
		BookingForm.ReturnChanged();
	},

	ToggleRouteType: function(newValue) {
		//alert(newValue);
		$("FromAirportTr").style.display = newValue == "Airport" ? "" : "none";
		$("ToAirportTr").style.display = newValue == "Airport" ? "" : "none";
		$("FromResortTr").style.display = newValue != "Airport" ? "" : "none";
		$("ToResortTr").style.display = newValue != "Airport" ? "" : "none";
		
		BookingForm.OnQuoteInputChanged();
		BookingForm.SyncDateText(newValue);
	},
	
	ReturnChanged: function(isReturn) {
		BookingForm.OnQuoteInputChanged();
		$("Date2Tr").style.display = isReturn ? "" : "none";
	},
	
	RouteChanged: function(newValue) {
		BookingForm.OnQuoteInputChanged();
		BookingForm.SyncDateText(newValue);
	},
	
	SyncDateText: function(newValue) {
		if(newValue != "Airport") {
			$("Date1Text").innerHTML = "Pickup:";	
			$("Date2Text").innerHTML = "Returning:";	
		} else if($("FromAirport").value == "" || places[$("FromAirport").value].IsAirport) {
			$("Date1Text").innerHTML = "Flight arrives:";	
			$("Date2Text").innerHTML = "Flight departs:";	
		} else {
			$("Date1Text").innerHTML = "Flight departs:";	
			$("Date2Text").innerHTML = "Flight arrives:";	
		}
	},

	MakeTimePicker: function(id) {
		$("Hour" + id).options[$("Hour" + id).options.length] = new Option("", "");
		for(var i=0; i < 24; i++) {
			if(i < 10) {
				text = "0" + i;
			} else {
				text = i;
			}
			$("Hour" + id).options[$("Hour" + id).options.length] = new Option(text, i);
		}
	
		$("Minute" + id).options[$("Minute" + id).options.length] = new Option("", "");
		for(var i=0; i < 60; i+=5) {
			if(i < 10) {
				text = "0" + i;
			} else {
				text = i;
			}
			$("Minute" + id).options[$("Minute" + id).options.length] = new Option(text, i);
		}		
	}
}

