var pathRailengine = "";
var pathImages = "";

var body = "";

function doFinalize(paramPathRailengine, paramPathImages, jsessionid) {
	pathRailengine = paramPathRailengine;
	pathImages = paramPathImages;
	if (jsessionid != null) { document.cookie = 'ue_session=' + escape(jsessionid) +'; path=/'; }
}

function doPost() {
	if (pathRailengine != null && pathRailengine != "") {
		window.status = 'One moment please...';
		self.parent.tb_remove();
		setTimeout("window.scrollTo(0,0);$D('select').hide();$D('#waiting-page').show();",100); // only show the waiting page if the server isn't answering directly.
		return true;
	} else {
		alert('You are not authorized to connect to the railengine.');
		return false;
	}
}

function doSubmit(frm) {
	frm.submit(function() { return doPost(); });
	frm.submit();
	return false;
}

function doBilling() {
	return doPost($D('#billingform'));
}

// USER ACCOUNT


var nbrOfNewPassengers = 0;
function addPassenger() {
	var clone = $D('#addpassengerdummy').clone();
	clone.removeAttr('id');
	clone.removeAttr('style');
	clone.children().children("input[name='re_passengers_new[]']").val(nbrOfNewPassengers);
	clone.children().children("select[name='re_gender_new']").attr("name","re_gender_new"+nbrOfNewPassengers);
	clone.children().children("input[name='re_firstname_new']").attr("name","re_firstname_new"+nbrOfNewPassengers);
	clone.children().children("input[name='re_lastname_new']").attr("name","re_lastname_new"+nbrOfNewPassengers);
	clone.insertBefore('#addpassengerdummy');
	nbrOfNewPassengers++;
	return false; 
}

var nbrOfNewCustomers = 0;
function addCustomer() {
	var clone = $D('#addcustomerdummy').clone();
	clone.removeAttr('id');
	clone.removeAttr('style');
	clone.children().children("input[name='re_customers_new[]']").val(nbrOfNewCustomers);
	clone.children().children().children("select[name='re_gender_new']").attr("name","re_gender_new"+nbrOfNewCustomers);
	clone.children().children().children("input[name='re_firstname_new']").attr("name","re_firstname_new"+nbrOfNewCustomers);
	clone.children().children().children("input[name='re_lastname_new']").attr("name","re_lastname_new"+nbrOfNewCustomers);
	clone.insertBefore('#addcustomerdummy');
	nbrOfNewCustomers++;
	return false; 
}

var nbrOfNewAddresses = 0;
function addAddress() {
	var clone = $D('#addaddressdummy').clone();
	clone.removeAttr('id');
	clone.removeAttr('style');
	clone.children().children("input[name='re_addresses_new[]']").val(nbrOfNewAddresses);
	clone.children().children("input[name='re_address1_new']").attr("name","re_address1_new"+nbrOfNewAddresses);
	clone.children().children("input[name='re_address2_new']").attr("name","re_address2_new"+nbrOfNewAddresses);
	clone.children().children("input[name='re_address3_new']").attr("name","re_address3_new"+nbrOfNewAddresses);
	clone.children().children().children("input[name='re_zip_new']").attr("name","re_zip_new"+nbrOfNewAddresses);
	clone.children().children().children("input[name='re_city_new']").attr("name","re_city_new"+nbrOfNewAddresses);
	clone.children().children().children("input[name='re_state_new']").attr("name","re_state_new"+nbrOfNewAddresses);
	clone.children().children().children("select[name='re_country_new']").attr("name","re_country_new"+nbrOfNewAddresses);
	clone.insertBefore('#addaddressdummy');
	nbrOfNewAddresses++;
	return false; 
}


// SHIPPING PAGE

function updateShippingFee(productId) {
	var plan = $D('input[name=re_protectionplan]:checked');
	var rpp_param = "";
	if (plan.length && plan.val() == "yes") {
		rpp_param = "-with-rpp";
	}
	var newTotalPrice = $D('#shipping-option-'+productId+'-amount-total' + rpp_param).val();
	var newPrice = $D('#shipping-option-'+productId+'-price').text();
	$D('#cart-shippingfee-amount').text(newPrice);
	$D('.cart-checkout-overview-total').html(newTotalPrice);
	$D('#shippingbillingform-total-amount-value').html(newTotalPrice);
	$D('.shipping-option-text div').hide();
	
	$D('.shipping-option-row').removeClass('on');
	$D('div', '.shipping-option-text').removeClass('on');
	
	if ($D('#shipping-option-' + productId + '-text').html().replace(' ', '') != '') {
		$D('#shipping-option-' + productId + '-text').addClass('on');
		$D('#shipping-option-' + productId + '-text').show();
	}
	$D('#shipping-option-row-' + productId).addClass('on');
}

function updateRPP(status) {
	var rpp_param = "";
	if (status == "yes") {
		rpp_param = "-with-rpp";
	}
	var new_total_price;
	var selected_option = $D('input[name=re_shippingoption]:checked');
	if (selected_option.length > 0) {
		new_total_price = $D('#shipping-option-' + selected_option.val() + '-amount-total' + rpp_param).val();
	} else {
		new_total_price = $D('#cart-total' + rpp_param).val();
	}
	$D('.cart-checkout-overview-total').html(new_total_price);
	$D('#shippingbillingform-total-amount-value').html(new_total_price);
	if (status != "yes") {
		$D('#cart-checkout-protectionplan-price', '#cart-checkout-overview-details').html($D('#cart-no-rpp').val());
	} else {
		$D('#cart-checkout-protectionplan-price', '#cart-checkout-overview-details').html($D('#cart-rpp').val());
	}
}


// BILLING PAGE

function copyShippingDetails(criteria) {
	$D('#re_billing_gender').val(cp_gender);
	$D('#re_billing_firstname').val(cp_firstName);
	$D('#re_billing_lastname').val(cp_lastName);
	$D('#billing-phone').val(cp_phone);
	$D('#billing-email').val(cp_email);
	$D('#billing-address1').val(cp_address1);
	$D('#billing-address2').val(cp_address2);
	$D('#billing-address3').val(cp_address3);
	$D('#billing-zip').val(cp_zip);
	$D('#billing-city').val(cp_city);
	$D('#billing-state').val(cp_state);
	$D('#billing-country').val(cp_country);
	if (criteria) {
		$D('#re_billing_gender').attr('disabled','disabled');
		$D('#re_billing_firstname').attr('disabled','disabled');
		$D('#re_billing_lastname').attr('disabled','disabled');
		$D('#billing-phone').attr('disabled','disabled');
		$D('#billing-email').attr('disabled','disabled');
		$D('#billing-address1').attr('disabled','disabled');
		$D('#billing-address2').attr('disabled','disabled');
		$D('#billing-address3').attr('disabled','disabled');
		$D('#billing-zip').attr('disabled','disabled');
		$D('#billing-city').attr('disabled','disabled');
		$D('#billing-state').attr('disabled','disabled');
		$D('#billing-country').attr('disabled','disabled');
		$D('.saved_passenger').attr('disabled','disabled');
		$D('.saved_address').attr('disabled','disabled');
	} else {
		$D('#re_billing_gender').removeAttr('disabled');
		$D('#re_billing_firstname').removeAttr('disabled');
		$D('#re_billing_lastname').removeAttr('disabled');
		$D('#billing-phone').removeAttr('disabled');
		$D('#billing-email').removeAttr('disabled');
		$D('#billing-address1').removeAttr('disabled');
		$D('#billing-address2').removeAttr('disabled');
		$D('#billing-address3').removeAttr('disabled');
		$D('#billing-zip').removeAttr('disabled');
		$D('#billing-city').removeAttr('disabled');
		$D('#billing-state').removeAttr('disabled');
		$D('#billing-country').removeAttr('disabled');
		$D('.saved_passenger').removeAttr('disabled');
		$D('.saved_address').removeAttr('disabled');
	}
}

function checkBillingModes() {
	if ($D('#billingform-options-modes .online input:checked').size() > 0) {
		$D('#billingform-options-cardholder').show();
	} else if ($D('#billingform-options-modes .offline input:checked').size() > 0 || $D('#billingform-options-modes .allowance input:checked').size() > 0) {
		$D('#billingform-options-cardholder').hide();
	}
}

// SHIPPING + BILLING PAGE

var cp_gender = '';
var cp_firstName = '';
var cp_lastName = '';
var cp_address1 = '';
var cp_address2 = '';
var cp_address3 = '';
var cp_zip = '';
var cp_city = '';
var cp_state = '';
var cp_country = '';
var cp_phone = '';
var cp_email = '';
var cp_criteria = false;

function copyShippingBillingDetails(criteria) {
	if (criteria == cp_criteria) {
		cp_gender = $D('#re_billing_gender').val();
		cp_firstName = $D('#re_billing_firstname').val();
		cp_lastName = $D('#re_billing_lastname').val();
		cp_address1 = $D('#billing-address1').val();
		cp_address2 = $D('#billing-address2').val();
		cp_address3 = $D('#billing-address3').val();
		cp_zip = $D('#billing-zip').val();
		cp_city = $D('#billing-city').val();
		cp_state = $D('#billing-state').val();
		cp_country = $D('#billing-country').val();
		cp_phone = $D('#billing-phone').val();
		cp_email = $D('#billing-email').val();
		//cp_criteria = criteria;
	}
	if (criteria) {
		$D('#re_billing_gender').val($D('#re_shipping_gender').val());
		$D('#re_billing_firstname').val($D('#re_shipping_firstname').val());
		$D('#re_billing_lastname').val($D('#re_shipping_lastname').val());
		$D('#billing-phone').val($D('#shipping-phone').val());
		$D('#billing-email').val($D('#shipping-email').val());
		if($D('#shipping-address1').is(':visible')) { $D('#billing-address1').val($D('#shipping-address1').val()); }
		if($D('#shipping-address2').is(':visible')) { $D('#billing-address2').val($D('#shipping-address2').val()); }
		if($D('#shipping-address3').is(':visible')) { $D('#billing-address3').val($D('#shipping-address3').val()); }
		if($D('#shipping-zip').is(':visible')) { $D('#billing-zip').val($D('#shipping-zip').val()); }
		if($D('#shipping-city').is(':visible')) { $D('#billing-city').val($D('#shipping-city').val()); }
		if($D('#shipping-state').is(':visible')) { $D('#billing-state').val($D('#shipping-state').val()); }
		if($D('#shipping-country').is(':visible')) { $D('#billing-country').val($D('#shipping-country').val()); }
		$D('#shippingbillingform-address-billing .saved_passenger').val("");
		$D('#shippingbillingform-address-billing .saved_address').val("");
		$D('#re_billing_gender').attr('disabled','disabled');
		$D('#re_billing_firstname').attr('disabled','disabled');
		$D('#re_billing_lastname').attr('disabled','disabled');
		$D('#billing-phone').attr('disabled','disabled');
		$D('#billing-email').attr('disabled','disabled');
		if($D('#shipping-address1').is(':visible')) { $D('#billing-address1').attr('disabled','disabled'); } else { $D('#billing-address1').removeAttr('disabled'); }
		if($D('#shipping-address2').is(':visible')) { $D('#billing-address2').attr('disabled','disabled'); } else { $D('#billing-address2').removeAttr('disabled'); }
		if($D('#shipping-address3').is(':visible')) { $D('#billing-address3').attr('disabled','disabled'); } else { $D('#billing-address3').removeAttr('disabled'); }
		if($D('#shipping-zip').is(':visible')) { $D('#billing-zip').attr('disabled','disabled'); } else { $D('#billing-zip').removeAttr('disabled'); }
		if($D('#shipping-city').is(':visible')) { $D('#billing-city').attr('disabled','disabled'); } else { $D('#billing-city').removeAttr('disabled'); }
		if($D('#shipping-state').is(':visible')) { $D('#billing-state').attr('disabled','disabled'); } else { $D('#billing-state').removeAttr('disabled'); }
		if($D('#shipping-country').is(':visible')) { $D('#billing-country').attr('disabled','disabled'); } else { $D('#billing-country').removeAttr('disabled'); }
		$D('#shippingbillingform-address-billing .saved_passenger').attr('disabled','disabled');
		if($D('#shippingbillingform-address-shipping .saved_address').is(':visible')) { $D('#shippingbillingform-address-billing .saved_address').attr('disabled','disabled'); } else { $D('#shippingbillingform-address-billing .saved_address').removeAttr('disabled'); }
	} else {
		$D('#re_billing_gender').val(cp_gender);
		$D('#re_billing_firstname').val(cp_firstName);
		$D('#re_billing_lastname').val(cp_lastName);
		$D('#billing-phone').val(cp_phone);
		$D('#billing-email').val(cp_email);
		$D('#billing-address1').val(cp_address1);
		$D('#billing-address2').val(cp_address2);
		$D('#billing-address3').val(cp_address3);
		$D('#billing-zip').val(cp_zip);
		$D('#billing-city').val(cp_city);
		$D('#billing-state').val(cp_state);
		$D('#billing-country').val(cp_country);
		$D('#re_billing_gender').removeAttr('disabled');
		$D('#re_billing_firstname').removeAttr('disabled');
		$D('#re_billing_lastname').removeAttr('disabled');
		$D('#billing-phone').removeAttr('disabled');
		$D('#billing-email').removeAttr('disabled');
		$D('#billing-address1').removeAttr('disabled');
		$D('#billing-address2').removeAttr('disabled');
		$D('#billing-address3').removeAttr('disabled');
		$D('#billing-zip').removeAttr('disabled');
		$D('#billing-city').removeAttr('disabled');
		$D('#billing-state').removeAttr('disabled');
		$D('#billing-country').removeAttr('disabled');
		$D('#shippingbillingform-address-billing .saved_passenger').removeAttr('disabled');
		$D('#shippingbillingform-address-billing .saved_address').removeAttr('disabled');
	}
}

// SHARED ONES

function validateAndSubmitForm(theForm) {
	$D('#' + theForm).validate({ignore: ":hidden"});
	if ($D('#' + theForm).valid()) {
		self.parent.tb_remove();
		doPost();
		$D('#' + theForm).submit();
	} else {
		$D('p.railengine-message-error').remove();
		if ($D('#TB_overlay').size() == 0) {
			$D('.railenginecontent').before("<p class=\"railengine-message-error\">"+labelErrorMessage+"</p>");
		}
		window.scrollTo(0,0);
	}
}

function doShowHideCart(theCart) {
	if($D('#' + theCart).is(':hidden')) {
		$D('#' + theCart).slideDown('fast');
		$D('#' + theCart + '-show-hide').html('Hide details');
	}else {
		$D('#' + theCart).slideUp('fast');
		$D('#' + theCart + '-show-hide').html('Show details');
	}
}

function doCal(cal, cal2, update, func, maxDate) {
	var startDate = new Date().addDays(minDaysBeforeDeparture); 
	var endDate = (maxDate == null) ? new Date().addMonths(nbrOfNextMonths) : maxDate;
	if (maxDate != null) {
		endDate.zeroTime();
		startDate.zeroTime();
		if (endDate < startDate) {
			startDate = new Date();
		}
	}
	$D("#" + cal).datepicker(
		{
			numberOfMonths: 2,
			minDate: startDate,
			maxDate: endDate,
			constrainInput: true,
			dateFormat: calendarPattern,
			altField: '#' + cal + '-alt',
			altFormat: 'dd/mm/yy',
			closeText: 'X',
			duration: '',
			showButtonPanel: true,
			onClose: function(date) {
				if (cal2 != null && $D('#' + cal2).size() > 0 && update == "forward") {
					Date.format = oriDateFormat;
					var cal2Date = Date.fromString($D("#" + cal2).val());	
					var cal1Date = Date.fromString(date);
					var offset = 1;
					if (func == 'rail') offset = 0;
					if (cal2Date == null || cal2Date == "") {
						cal1Date.addDays(offset);
						$D("#" + cal2).val(cal1Date);
						Date.format = "dd/mm/yyyy";
						$D("#" + cal2 + '-alt').val(cal1Date.asString());
						Date.format = oriDateFormat;
					} else {	
						if (cal1Date != false && cal1Date >= cal2Date) {
							Date.format = oriDateFormat;
							cal1Date.addDays(offset);
							$D("#" + cal2).val(cal1Date.asString());
							Date.format = "dd/mm/yyyy";
							$D("#" + cal2 + '-alt').val(cal1Date.asString());
							Date.format = oriDateFormat;
						}
					}
					$D("#" + cal2).datepicker('option' , 'minDate' , cal1Date);
				}
			}
		}
	);

	if($D("#" + cal).val() == null || $D("#" + cal).val() == "") {
		Date.format = oriDateFormat;
		$D("#" + cal).val(startDate.asString());
		Date.format = "dd/mm/yyyy";
		$D("#" + cal + '-alt').val(startDate.asString());
		Date.format = oriDateFormat;
	}
}

function capitalizeString(s) {
	return s.charAt(0).toUpperCase() + s.substring(1).toLowerCase();
}

function fillPassenger(passenger) {
	var pax = passenger.split('|');
	var number = pax[0] == 'n/a' ? '' : pax[0];
	var gender = (pax[1] == 'MALE' || pax[1] == 'male') ? 'M' : ((pax[1] == 'FEMALE' || pax[1] == 'female') ? 'F' : '');
	var firstname = pax[2];
	var lastname = pax[3];
	$D('select[name="re_'+ number +'_gender"]').val(gender);
	$D('select[name="re_'+ number +'_gender"]').change();
	$D('input[name="re_'+ number +'_firstname"]').val(firstname);
	$D('input[name="re_'+ number +'_firstname"]').keyup();
	$D('input[name="re_'+ number +'_lastname"]').val(lastname);
	$D('input[name="re_'+ number +'_lastname"]').keyup();
	$D('select[name="re_gender_'+number+'"]').val(gender);
	$D('select[name="re_gender_'+number+'"]').change();
	$D('input[name="re_firstname_'+number+'"]').val(firstname);
	$D('input[name="re_firstname_'+number+'"]').keyup();
	$D('input[name="re_lastname_'+number+'"]').val(lastname);
	$D('input[name="re_lastname_'+number+'"]').keyup();	
}

function fillAddress(address) {
	var adr = address.split('|');
	var number = adr[0] == 'n/a' ? '' : adr[0] + '_';
	var address1 = adr[1];
	var address2 = adr[2];
	var address3 = adr[3];
	var buildingName = adr[4];
	var buildingNumber = adr[5];
	var locality = adr[6];
	var zip = adr[7];
	var city = adr[8];
	var county = adr[9];
	var state = adr[10];
	var country = adr[11];
	$D('input[name="re_'+ number +'address1"]').val(address1);
	$D('input[name="re_'+ number +'address1"]').keyup();
	$D('input[name="re_'+ number +'address2"]').val(address2);
	$D('input[name="re_'+ number +'address2"]').keyup();
	$D('input[name="re_'+ number +'address3"]').val(address3);
	$D('input[name="re_'+ number +'address3"]').keyup();
	$D('input[name="re_'+ number +'buildingname"]').val(buildingName);
	$D('input[name="re_'+ number +'buildingname"]').keyup();
	$D('input[name="re_'+ number +'buildingnumber"]').val(buildingNumber);
	$D('input[name="re_'+ number +'buildingnumber"]').keyup();
	$D('input[name="re_'+ number +'locality"]').val(locality);
	$D('input[name="re_'+ number +'locality"]').keyup();
	$D('input[name="re_'+ number +'zip"]').val(zip);
	$D('input[name="re_'+ number +'zip"]').keyup();
	$D('input[name="re_'+ number +'city"]').val(city);
	$D('input[name="re_'+ number +'city"]').keyup();
	$D('input[name="re_'+ number +'county"]').val(county);
	$D('input[name="re_'+ number +'county"]').keyup();
	$D('input[name="re_'+ number +'state"]').val(state);
	$D('input[name="re_'+ number +'state"]').keyup();
	$D('select[name="re_'+ number +'country"]').val(country);
	$D('select[name="re_'+ number +'country"]').change();
}


// HELPERS

function isdefined(variable) {
	return (typeof(window[variable]) == "undefined") ? false : true;
}

if(!Array.indexOf){
	Array.prototype.indexOf = function(obj) {
		for(var i=0; i<this.length; i++) {
			if(this[i]==obj) {
				return i;
			}
		}
		return -1;
	}
}

function daysInMonth(month, year) {
	return 32 - new Date(year, month, 32).getDate();
}

function getFlashMovie(movieName) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}

function stringToFloat(text) {
	var filteredValues = "1234567890.,";
	var returnString = "";
	for (var i = 0; i < text.length; i++) {
		var c = text.charAt(i);
		if (filteredValues.indexOf(c) != -1) {
			returnString += (c == ',') ? '' : c;
		}
	}
	return parseFloat(returnString);
}


// STARTUP

function initCartOverview() {
	if ($D('#cart-agencyreference-bookingreference').length) {
		if (taRefPattern != '') {
			$D('#cart-agencyreference-bookingreference').addClass("taRef");
		}
		if (maskTaRefPattern != '') {
			$D('#cart-agencyreference-bookingreference').mask(maskTaRefPattern);
		}
	}
	$D('#cart-agencyreference').click(function() { validateAndSubmitForm("agencyreferenceform"); return false; });
	$D('p.cart-passproducts-total a').click(function() { tb_remove(); return doPost(); });
	$D('p.cart-ptpproducts-total a').click(function() { tb_remove(); return doPost(); });
	
	$D('.cart-checkout').click(function() { return doPost(); });
}

function initCartRecap() {
	$D('#cart-recap-commission').click(function(){ $D('#recap-commission').toggle(); $D('#recap-total-net').toggle(); return false; });
	$D('#cart-recap-next').click(function(){ $D('#recapform').submit(); return false; });	
}

function initCartShipping() {
	var btn_delivery_options = $D('input[name=re_shippingoption]');
	if (isdefined('productIdPickupAtShop') && productIdPickupAtShop != '') {
		var btn_delivery_pickup = $D('#shipping-option-'+productIdPickupAtShop);
	}
	if (isdefined('productIdTicketOnDeparture') && productIdTicketOnDeparture != '') {
		var btn_delivery_tod = $D('#shipping-option-'+productIdTicketOnDeparture);
	}
	var sel_delivery_agency = $D('#shippingform-deliveryagency');
	if (sel_delivery_agency.size() > 0) {
		sel_delivery_agency.hide();
		sel_delivery_agency.attr('disabled', 'disabled');
		$D('.shippingform-deliveryagency-details').hide();
		sel_delivery_agency.change(function(){ $D('.shippingform-deliveryagency-details').hide(); $D('#shippingform-deliveryagency-details-'+$D(this).val()).show(); });
	}
	btn_delivery_options.change(function(){	if(this.checked) { updateShippingFee(this.value); }
											if(btn_delivery_pickup != null && btn_delivery_pickup.attr('checked')) {
												sel_delivery_agency.removeAttr('disabled'); sel_delivery_agency.show(); sel_delivery_agency.change(); $D('#shippingform-address-street').hide(); $D('div.shippingform-shipto').hide(); $D('#shippingform-address-city').hide(); $D('#shippingbillingform-address-copy-wrapper').hide(); $D('#shippingbillingform-address-copy').removeAttr('checked'); $D('#shippingbillingform-address-copy').change(); } else { 
												sel_delivery_agency.attr('disabled', 'disabled'); sel_delivery_agency.hide(); $D('.shippingform-deliveryagency-details').hide(); $D('#shippingform-shipto').show(); $D('div.shippingform-address-street').show(); $D('#shippingform-address-city').show(); $D('#shippingbillingform-address-copy-wrapper').show(); }
											if(btn_delivery_tod != null && btn_delivery_tod.attr('checked')) { 
												$D('div.shippingform-shipto').hide(); $D('#shippingform-address-street').hide(); $D('#shippingform-address-city').hide(); /*$D('#shippingbillingform-address-copy-wrapper').hide(); $D('#shippingbillingform-address-copy').removeAttr('checked');*/ $D('#shippingbillingform-address-copy').change(); } else if (btn_delivery_pickup == null || !btn_delivery_pickup.attr('checked')) { 
												$D('div.shippingform-shipto').show(); $D('#shippingform-address-street').show(); $D('#shippingform-address-city').show(); /*$D('#shippingbillingform-address-copy-wrapper').show();*/ $D('#shippingbillingform-address-copy').change(); } });
	btn_delivery_options.click(function(){	if(this.checked) { updateShippingFee(this.value); }
											if(btn_delivery_pickup != null && btn_delivery_pickup.attr('checked')) {
												sel_delivery_agency.removeAttr('disabled'); sel_delivery_agency.show(); sel_delivery_agency.change(); $D('#shippingform-address-street').hide(); $D('div.shippingform-shipto').hide(); $D('#shippingform-address-city').hide(); $D('#shippingbillingform-address-copy-wrapper').hide(); $D('#shippingbillingform-address-copy').removeAttr('checked'); $D('#shippingbillingform-address-copy').change(); } else { 
												sel_delivery_agency.attr('disabled', 'disabled'); sel_delivery_agency.hide(); $D('.shippingform-deliveryagency-details').hide(); $D('div.shippingform-shipto').show(); $D('#shippingform-address-street').show(); $D('#shippingform-address-city').show(); $D('#shippingbillingform-address-copy-wrapper').show(); }
											if(btn_delivery_tod != null && btn_delivery_tod.attr('checked')) { 
												$D('div.shippingform-shipto').hide(); $D('#shippingform-address-street').hide(); $D('#shippingform-address-city').hide(); /*$D('#shippingbillingform-address-copy-wrapper').hide(); $D('#shippingbillingform-address-copy').removeAttr('checked');*/ $D('#shippingbillingform-address-copy').change(); } else if (btn_delivery_pickup == null || !btn_delivery_pickup.attr('checked')) { 
												$D('div.shippingform-shipto').show(); $D('#shippingform-address-street').show(); $D('#shippingform-address-city').show(); /*$D('#shippingbillingform-address-copy-wrapper').show();*/ $D('#shippingbillingform-address-copy').change(); } });
	btn_delivery_options.change();
	var btn_rpp_options = $D('input[name=re_protectionplan]');
	if (btn_rpp_options.length) {
		btn_rpp_options.change(function() {if (this.checked) { updateRPP(this.value); }});
		btn_rpp_options.click(function() {if (this.checked) { updateRPP(this.value); }});
	}
	btn_rpp_options.change();
	$D('#shippingform-shipto').change(function() { if($D(this).attr('checked')) { setDefaultShippingDetails(false); $D('input[name="re_shipto"]').val('yes'); } else { setDefaultShippingDetails(true); $D('input[name="re_shipto"]').val(''); } });
	$D('#shippingform-shipto').click(function() { if($D(this).attr('checked')) { setDefaultShippingDetails(false); $D('input[name="re_shipto"]').val('yes'); } else { setDefaultShippingDetails(true); $D('input[name="re_shipto"]').val(''); } });
	$D('#shippingform-shipto').change();
	$D('#cart-shipping-next').click(function(){ validateAndSubmitForm("shippingform"); return false; });
}

function initCartBilling() {
	$D('#billingform-address-copy').change(function() { if($D(this).attr('checked')) { copyShippingDetails(true); $D('input[name="re_copy_address"]').val('yes'); } else { copyShippingDetails(false); $D('input[name="re_copy_address"]').val(''); } });
	$D('#billingform-address-copy').click(function() { if($D(this).attr('checked')) { copyShippingDetails(true); $D('input[name="re_copy_address"]').val('yes'); } else { copyShippingDetails(false); $D('input[name="re_copy_address"]').val(''); } });
	$D('#billingform-address-copy').change();
	$D('input[name="dummy_cardtype"]').change(function() { $D('input[name="re_cardtype"]').val(this.value); });
	$D('input[name="dummy_cardtype"]').click(function() { $D('input[name="re_cardtype"]').val(this.value); });
	$D('#billingform-options-modes, radio').change(checkBillingModes);
	$D('#billingform-options-modes, radio').change();
	$D('#cart-billing-next').click(function(){ validateAndSubmitForm('billingform'); return false; });
}

function initCartShippingBilling() {
	$D('#shippingbillingform-address-copy').change(function() { if($D(this).attr('checked')) { copyShippingBillingDetails(true); $D('input[name="re_copy_address"]').val('yes'); } else { copyShippingBillingDetails(false); $D('input[name="re_copy_address"]').val(''); } });
	$D('#shippingbillingform-address-copy').click(function() { if($D(this).attr('checked')) { copyShippingBillingDetails(true); $D('input[name="re_copy_address"]').val('yes'); } else { copyShippingBillingDetails(false); $D('input[name="re_copy_address"]').val(''); } });
	$D('#shippingbillingform-address-copy').change();
	
	$D('#re_shipping_gender').change(function() { if($D('#shippingbillingform-address-copy').attr('checked')) { $D('#re_billing_gender').val($D(this).val()); $D(this).focus(); } });
	$D('#re_shipping_firstname').keyup(function() { if($D('#shippingbillingform-address-copy').attr('checked')) { $D('#re_billing_firstname').val($D(this).val()); $D(this).focus(); } });
	$D('#re_shipping_lastname').keyup(function() { if($D('#shippingbillingform-address-copy').attr('checked')) { $D('#re_billing_lastname').val($D(this).val()); $D(this).focus(); } });
	$D('#shipping-phone').keyup(function() { if($D('#shippingbillingform-address-copy').attr('checked')) { $D('#billing-phone').val($D(this).val()); $D(this).focus(); } });
	$D('#shipping-email').keyup(function() { if($D('#shippingbillingform-address-copy').attr('checked')) { $D('#billing-email').val($D(this).val()); $D(this).focus(); } });
	$D('#shipping-address1').keyup(function() { if($D('#shippingbillingform-address-copy').attr('checked')) { $D('#billing-address1').val($D(this).val()); $D(this).focus(); } });
	$D('#shipping-address2').keyup(function() { if($D('#shippingbillingform-address-copy').attr('checked')) { $D('#billing-address2').val($D(this).val()); $D(this).focus(); } });
	$D('#shipping-address3').keyup(function() { if($D('#shippingbillingform-address-copy').attr('checked')) { $D('#billing-address3').val($D(this).val()); $D(this).focus(); } });
	$D('#shipping-zip').keyup(function() { if($D('#shippingbillingform-address-copy').attr('checked')) { $D('#billing-zip').val($D(this).val()); $D(this).focus(); } });
	$D('#shipping-city').keyup(function() { if($D('#shippingbillingform-address-copy').attr('checked')) { $D('#billing-city').val($D(this).val()); $D(this).focus(); } });
	$D('#shipping-state').keyup(function() { if($D('#shippingbillingform-address-copy').attr('checked')) { $D('#billing-state').val($D(this).val()); $D(this).focus(); } });
	$D('#shipping-country').change(function() { if($D('#shippingbillingform-address-copy').attr('checked')) { $D('#billing-country').val($D(this).val()); $D(this).focus(); } });
	
	$D('#shipping-email').keyup(function() { $D('#shippingbillingform-username').val($D(this).val()); $D(this).focus(); });
	$D('#shipping-email').keyup(function() { $D('#shippingbillingform-username-login').val($D(this).val()); $D(this).focus(); });
	$D('#cart-shippingbilling-next').click(function(){ validateAndSubmitForm('shippingbillingform'); return false; });
}

function initUserAccount() {
	$D('#userform-login').click(function() { $D('#userform').submit(); return false; });
	$D('#miniuserform-login').click(function() { $D('#miniuserform').submit(); return false; });
	
	$D('#registerform-register').click(function() { $D('#registerform').submit(); return false; });
	$D('#miniregisterform-register').click(function() { $D('#miniregisterform').submit(); return false; });

	$D('#accreditedform-company').click(function() { this.value == 'Other' ? $D('#accreditedform-company-other').show() : $D('#accreditedform-company-other').hide()});
	$D('#accreditedform-company').click();
	$D('#accreditedform-submit').click(function() { $D('#accreditedform').submit(); return false; });
	
	$D('#pwdform-submit').click(function() { $D('#pwdform').submit(); return false; });
	
	$D('#accountform-save').click(function(){ $D('#accountform').submit(); return false; });
	$D('#accountform-reset').click(function(){ $D('#accountform')[0].reset(); return false; });
	$D('#password').formatInput();
	$D('#passwordconfirm').formatInput();
	
	$D('#addressesform-add').click(addAddress);
	$D('#addressesform-save').click(function(){ $D('#addressesform').submit(); return false; });
	$D('#addressesform-reset').click(function(){ $D('#addressesform')[0].reset(); return false; });
	
	$D('#newslettersform-save').click(function(){ $D('#newslettersform').submit(); return false; });
	$D('#newslettersform-reset').click(function(){ $D('#newslettersform')[0].reset(); return false; });
	
	$D('#passengersform-add').click(addPassenger);
	$D('#passengersform-save').click(function(){ $D('#passengersform').submit(); return false; });
	$D('#passengersform-reset').click(function(){ $D('#passengersform')[0].reset(); return false; });
	
	$D('#customersform-add').click(addCustomer);
	$D('#customersform-save').click(function(){ $D('#customersform').submit(); return false; });
	$D('#customersform-reset').click(function(){ $D('#customersform')[0].reset(); return false; });
	
	$D('#customersform-newpassenger-save').click(function(){ $D('#customersform-newpassenger').submit(); return false; });
	$D('#customersform-newaddress-save').click(function(){ $D('#customersform-newaddress').submit(); return false; });
	
	$D('.saved_passenger').change(function(){ fillPassenger(this.value); });
	$D('.saved_address').change(function(){ fillAddress(this.value); });
}

function init() {
	// OVERVIEW
	initCartOverview();
		
	// RECAP
	initCartRecap();
	
	// SHIPPING
	initCartShipping();	
	
	// BILLING
	initCartBilling();
	
	// SHIPPING + BILLING
	initCartShippingBilling();

	// USER
	initUserAccount();
	
	// SHARED
	$D('#printLink').click(function(){ print(); return false; });
	
	// X-sales
	if ($D('#railengine-xsales-wrapper').size() > 0) {
		var xsales_title = $D('#railengine-xsales-wrapper').attr('title');
		xsales_title = xsales_title.replace('&amp;', '&');
		if (xsales_title == "") {
			xsales_title = "&re_image=Y&re_show=DestOnly";
		} else {
			if (xsales_title.charAt(0) != "&") {
				xsales_title = "&" + xsales_title;
			}
		}
		$D('#railengine-xsales-wrapper').load(pathRailengine + "re_domain=cart&re_oper=xsales&re_xsales=all" + xsales_title);
	}
	
	// VALIDATOR
	$D.validator.messages.required = "*";
	$D.validator.messages.email = "*";
	$D.validator.messages.creditcard = "*";
	$D.validator.messages.digits = "*";
	
	$D.validator.addMethod(
		"dateBE",
		// function to check date input
		// only valid dates will get through
		function(value, element) {
			var check = false;
			var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
			if (datePattern == "dd/MM/yyyy" || datePattern == "MM/dd/yyyy") {
				re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
			} else {
				if (datePattern == "yyyy/MM/dd") {
					re = /^\d{4}\/\d{1,2}\/\d{1,2}$/;
				} else if (datePattern == "yyyy-MM-dd") {
					re = /^\d{4}-\d{1,2}-\d{1,2}$/;
				}
			}
			if (re.test(value)){
				var xdata = null;
				var adata = "";
				var dd = "";
				var mm = "";
				var yy = "";
				if (datePattern == "dd/MM/yyyy") {
					adata = value.split('/');
					dd = parseInt(adata[0],10);
					mm = parseInt(adata[1],10);
					yy = parseInt(adata[2],10);
					
				}
				
				if (datePattern == "MM/dd/yyyy") {
					adata = value.split('/');
					mm = parseInt(adata[0],10);
					dd = parseInt(adata[1],10);
					yy = parseInt(adata[2],10);
				}
				
				if (datePattern == "yyyy/MM/dd") {
					adata = value.split('/');
					yy = parseInt(adata[0],10);
					mm = parseInt(adata[1],10);
					dd = parseInt(adata[2],10);
				}
				
				if (datePattern == "yyyy-MM-dd") {
					adata = value.split('-');
					yy = parseInt(adata[0],10);
					mm = parseInt(adata[1],10);
					dd = parseInt(adata[2],10);
				}
				
				xdata = new Date(yy,mm-1,dd);
				var mindate = new Date().addDays(minDaysBeforeDeparture).zeroTime();
				var diff = xdata - mindate;
				if ((( xdata.getFullYear() == yy ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == dd )) && diff >= 0) {
					check = true;
				} else {
					check = false;
				}
			} else {
				check = false;
			}
			return this.optional(element) || check;
		}, 
		"*"
	);
	
	$D.validator.addMethod(
		"dateBeSimple",
		// function to check date input
		// only valid dates will get through
		function(value, element) {
			var check = false;
			var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
			if (re.test(value)){
				var xdata = null;
				var adata = "";
				var dd = "";
				var mm = "";
				var yy = "";
				adata = value.split('/');
				dd = parseInt(adata[0],10);
				mm = parseInt(adata[1],10);
				yy = parseInt(adata[2],10);
				xdata = new Date(yy,mm-1,dd);
				if ((( xdata.getFullYear() == yy ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == dd ))) {
					check = true;
				} else {
					check = false;
				}
			} else {
				check = false;
			}
			return this.optional(element) || check;
		}, 
		"*"
	);
	
	// Add validation for TA ref number check (REC only)
	if (isdefined('taRefPattern') && taRefPattern != "") {
		$D.validator.addMethod(
			"taRef",
			function(value, element) {
				var patterns = taRefPattern.split('|');
				var hasValidBookingId = true;
				if (patterns.length > 0 && patterns[0] != "") {
					hasValidBookingId = false;
					for (var i = 0; i < patterns.length; i++) {
						var pattern = patterns[i].replace(/d/g, "\\d");
						pattern = pattern.replace(/\*/g, "\\w");
						pattern = pattern.replace(/a/g, "[a-zA-Z]");
						pattern = "^" + pattern + "$";
						var match = new RegExp(pattern);
						hasValidBookingId = match.test(value);
						if (hasValidBookingId) {
							break;
						}
					}
				}
				return hasValidBookingId;
			},
			labelErrorMessageTaReference.replace('{0}','')
		);
	}
	
	// Add validation for dropDowns (which isn't provided by default)
	$D.validator.addMethod( "dropDown", function(value, element) { return (value != "")},"*" ); 
	
	// Add validation to allow only Roman characters plus these exceptions (which are taken care off in by the URE)
	$D.validator.addMethod(
		"onlyRoman",
		function(value, element) {
			var reg = "^[\A-Za-z-_ ";
			reg += "\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"; 					// AaEeIiOoUu	grave
			reg += "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"; 		// AaEeIiOoUuYy	acute
			reg += "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"; 		// AaEeIiOoUuYy	circumflex
			reg += "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"; 											// AaOoNn	tilde
			reg += "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"; 		// AaEeIiOoUuYy	umlaut
			reg += "\u00C5\u00E5"; 																	// Aa	ring
			reg += "\u00C7\u00E7"; 																	// Cc	cedilla
			reg += "\u0150\u0151\u0170\u0171";														// OoUu	double acute
			reg += "]*$";
			var matchString = new RegExp(reg);
			return matchString.test(value);
		}, 
		"*"
	);
	
	// Add validation for a max field length of 4 chars
	$D.validator.addMethod(
		"maxLength4",
		function(value, element) {
			return value.length <= 4;
		},
		"*"
	);
	
	// Add validation for a max field length of 15 chars
	$D.validator.addMethod(
		"maxLength15",
		function(value, element) {
			return value.length <= 15;
		},
		"*"
	);
	
	// Add validation for a min field length of 8 chars
	$D.validator.addMethod(
		"minLength8",
		function(value, element) {
			return value.length >= 8;
		},
		"*"
	);
	
	// Add validation for required fields
	$D.validator.addMethod("req", function (value, element){ return jQuery.trim(value).length > 0;}, "*");
	
	// Add validation for pax country non-european
	$D.validator.addMethod(
		"nonEuropean",
		function(value, element) {
			for (var i = 0; i < europeanCountries.length; i++) {
				if (europeanCountries[i] == value) {
					$D('.railengine-message-error-popup').show();
					return false;
				}
			}
			return true;
		},
		"*"
	);
}

if (!isdefined('$D')) { $D = jQuery; }

$D.fn.formatInput = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
};

$D(document).ready(init);