var countryNames = new Array();
var borderingCountries = new Array();
var possibleCountries = new Array();
var europeanCountries;

borderingCountries["AT"] = new Array("DE", "HU", "IT", "SIHR", "CH", "CZ");
borderingCountries["BX"] = new Array("FR", "DE", "IE");
borderingCountries["CZ"] = new Array("AT", "DE");
borderingCountries["DK"] = new Array("DE", "NO", "SE");
borderingCountries["FI"] = new Array("DE", "SE");
borderingCountries["FR"] = new Array("BX", "DE", "IE", "IT", "ES", "CH");
borderingCountries["DE"] = new Array("AT", "BX", "DK", "FI", "FR", "SE", "CH", "CZ");
borderingCountries["GR"] = new Array("IT", "BGCS");
borderingCountries["HU"] = new Array("AT", "RO", "SIHR", "BGCS");
borderingCountries["IE"] = new Array("BX", "FR");
borderingCountries["IT"] = new Array("AT", "FR", "GR", "SIHR", "ES", "CH");
borderingCountries["NO"] = new Array("DK", "SE");
borderingCountries["PT"] = new Array("ES");
borderingCountries["ES"] = new Array("FR", "IT", "PT");
borderingCountries["SE"] = new Array("DK", "FI", "DE", "NO");
borderingCountries["CH"] = new Array("AT", "FR", "DE", "IT");
borderingCountries["RO"] = new Array("HU", "BGCS");
borderingCountries["SIHR"] = new Array("AT", "HU", "IT", "BGCS");
borderingCountries["BGCS"] = new Array("GR", "HU", "RO", "SIHR");

europeanCountries = new Array(
	"AT", "BE", "BG", "CH", 
	"CZ", "DE", "DK", "ENG",
	"ES", "FI", "FR", "GR", 
	"HR", "HU", "IE", "IT", 
	"LU", "ME", "MZ", "NL", 
	"NO", "PL", "PT", "RO", 
	"RS", "SCO", "SE", "SI", 
	"SK", "TR", "WAL", "AD", 
	"GI", "LI", "MC", "SM", 
	"VA"
);

function preSelectCountries(productId, index) {
	var count = 1;
	function selectCountry(country) {
		var select = $D('select#re_countries_' + index + '_' + productId + count);
		var options = $D('option', select);
		var found = false;
		options.each(function() {
			if ($D(this).val() == country) {
				found = true;
				return false;
			}
		});
		if (found) {
			if (typeof(requestedCountries[country]) != "undefined") {
				requestedCountries[country][1] = true;
			}
			select.val(country);
			checkCountries(select);
			count++
			return true;
		} else {
			return false;
		}
	}
	
	function findMutualBordering() {
		var match = "";
		for (var nextRequested in requestedCountries) {
			if (requestedCountries[nextRequested][0]) {
				var bordering = borderingCountries[nextRequested];
				for (var x = 0; x < borderingCountries[nextRequested].length; x++) {
					var possibleMatch = borderingCountries[nextRequested][x];
					if (possibleCountries.indexOf(possibleMatch) > -1) {
						if (!isdefined('requestedCountries[countryCode]') || (isdefined('requestedCountries[countryCode]') && requestedCountries[possibleMatch][0])) {
							match = possibleMatch;
							break;
						}
					}
				}
			}
		}
		return match;
	}
	
	for (var i in requestedCountries) {
		if (requestedCountries[i][0] && !requestedCountries[i][1]) {
			solved = selectCountry(i);
			var tries = 1;
			while (!solved && tries < maxCount) {
				tries++;
				var match = findMutualBordering();
				if (match != '') {
					selectCountry(match);
					solved = selectCountry(i);
				}
			}
		}
	}
}

function checkCountries(select) {
	var lastCountry = $D(select).val();
	var myParent = $D(select).parent().parent();
	possibleCountries = new Array();
	var selectedCountries = new Array();
	var selectsNextNbr;
	var selectsNotEmpty = myParent.children().children("select.passengerform-countries[value!='']");
	var initialOptions = '<option value="">--</option>';
	var possibleOptions = '';
	
	// gets called for each select with a selected value
	// and creates a list of all selected countries
	// note:
	//		only for selects smaller or equal to the one that triggered the function
	//		e.g. re_countries_x3 was changed. Only selecteds re_countries_x1, x2 and x3 are taken into account
	function setSelectedCountries(i) {
		var country = this.value;
		if (i <= name) {
			selectedCountries[country] = true;
		}
	}
	
	// gets called for each select with a selected value
	// lastCountry is the country of the selected that triggered the function
	function findPossibleCountries(i) {
		var country = this.value;
		if (country == lastCountry && isNaN(selectsNextNbr)) {
			selectsNextNbr = i+1;
		}
		if (i <= name) {
			// get all bordering countries of the selected one
			// if not already in the list of possibles and not in the list of selected countries, add to possibles
			for(var j=0 ; j<borderingCountries[country].length ; j++) {
				var countryCode = borderingCountries[country][j];
				if (possibleCountries.indexOf(countryCode) == -1 && typeof(selectedCountries[countryCode]) == 'undefined') {
					possibleCountries.push(countryCode);
				}
			}
		}
	}
	var name = $D(select).attr('name');
	name = name.substring(name.length-1, name.length);
	name = parseInt(name) - 1;
	if(selectsNotEmpty.size() == 0) {
		for(var countryCode in countryNames) {
			possibleCountries.push(countryCode);
		}
	} else {
		selectsNotEmpty.each(setSelectedCountries);
		selectsNotEmpty.each(findPossibleCountries);
	}
	// create the select options
	for(var j=0 ; j<possibleCountries.length ; j++) {
		if (countryNames[possibleCountries[j]] != null && countryNames[possibleCountries[j]] != '') {
			possibleOptions += '<option value="'+possibleCountries[j]+'">'+countryNames[possibleCountries[j]]+'<\/option>';
		}
	}
	
	// if there is a next select, update it with the possible options
	if (!isdefined('selectsNextNbr')) {
		myParent.children().children("select.passengerform-countries:eq("+selectsNextNbr+")").html(initialOptions + possibleOptions);
		myParent.children().children("select.passengerform-countries:gt("+selectsNextNbr+")").html(initialOptions);
	}
}

// Abonnements
function getStations(key, cont) {
	var script = pathRailengine + "re_domain=ajax&re_oper=stations";
	var params = { 're_value':key , 're_geography':stationGeography };
	$D.get(script, params, function(obj) {
		if(obj.toString().indexOf("NullPointerException") == -1 && obj.toString().indexOf("error") == -1) {
			var cities = obj.split(',');
			var res = [];
			for (var i=0 ; i<cities.length ; i++) {
				var city = cities[i];
				var citydata = city.split(':');
				var citycode = citydata[0].replace(/\n/g,'').replace(/\r/g,'');
				var cityname = citydata[1];
				var citycountry = citydata[2];
				var stationcode = citydata[3].replace(/\n/g,'').replace(/\r/g,'');;
				var stationname = citydata[4];
				res.push({id:stationcode, value:stationname, info:citycountry, extra:citycode, city:cityname});
			}
			cont(res);
		}
	});
}

function setOriginStation(station) {
	if (station == null) {
		$D('#abonnement-origincityname').val('');
		$D('#abonnement-origincitycode').val('');
		$D('#abonnement-originstationcode').val('');
	} else {
		$D('#abonnement-origincityname').val(station.city);
		$D('#abonnement-origincitycode').val(station.extra);
		$D('#abonnement-originstationcode').val(station.id);
	}
}

function setDestinationStation(station) {
	if (station == null) {
		$D('#abonnement-destinationcityname').val('');
		$D('#abonnement-destinationcitycode').val('');
		$D('#abonnement-destinationstationcode').val('');
	} else {
		$D('#abonnement-destinationcityname').val(station.city);
		$D('#abonnement-destinationcitycode').val(station.extra);
		$D('#abonnement-destinationstationcode').val(station.id);
	}
}

//PTPS

function getNextPrevTrains(url, direction) {
	/*$D.get(pathRailengine + url, function(data) {
		$D('#ptpresult').replaceWith(data);
		$D('.slide-element').show("slide", { direction: direction }, 350);
	});*/
	
	$D.ajax({
		type: "GET",
		url: pathRailengine,
		cache: false,
		data: url,
		success: function(html) {
			$D('#ptpresult').replaceWith(html);
			$D('.slide-element').show("slide", { direction: direction }, 350);
			tb_init('a.thickbox, area.thickbox, input.thickbox');
		}
	});
}

function getCities(key, cont) {
	var script = pathRailengine + "re_domain=ajax&re_oper=cities";
	var params = { 're_value':key , 're_geography':stationGeography };
	$D.get(script, params, function(obj) {
		if(obj.toString().indexOf("NullPointerException") == -1 && obj.toString().indexOf("error") == -1) {
			var cities = obj.split(',');
			var res = [];
			for (var i=0 ; i<cities.length ; i++) {
				var city = cities[i];
				var citydata = city.split(':');
				var citycode = citydata[0].replace(/\n/g,'').replace(/\r/g,'');
				var cityname = citydata[1];
				var citycountry = citydata[2];
				res.push({id:citycode, value:cityname, info:citycountry, extra:''});
			}
			cont(res);
		}
	});
}

function setOriginCity(city) {
	if(city == null) {
		$D('#ptpsearchform-origincitycode').val('');
	} else { 
		$D('#ptpsearchform-origincitycode').val(city.id);
	}
}

function setDestinationCity(city) {
	if(city == null) {
		$D('#ptpsearchform-destinationcitycode').val('');
	} else { 
		$D('#ptpsearchform-destinationcitycode').val(city.id);
	}
}

function setViaCity(city) {
	if(city == null) {
		$D('#ptpsearchform-viacitycode').val('');
	} else { 
		$D('#ptpsearchform-viacitycode').val(city.id);
	}
}

function disablePtpReturnInputs() {
	$D('.ptpsearchform-to').addClass('ptpsearchform-disabled');
}

function enablePtpReturnInputs() {
	$D('.ptpsearchform-to').removeClass('ptpsearchform-disabled');
}

function renamePaxFields(element, old, newId) {
	element.attr('id', 'ptpsearchform-define-traveller-' + newId);
	
	/*element.children('span[id="re_' + old + '_pax_number"]').html(newId);
	element.children('span[id="re_' + old + '_pax_number"]').attr('id', 're_' + newId + '_pax_number');
	element.children('select[name="re_' + old + '_pax_type"]').attr('name', 're_' + newId + '_pax_type');
	element.children('label[for="re_' + old + '_commercial_card"]').attr('for', 're_' + newId + '_commercial_card');
	element.children('select[name="re_' + old + '_commercial_card"]').attr('id', 're_' + newId + '_commercial_card');
	element.children('select[name="re_' + old + '_commercial_card"]').attr('name', 're_' + newId + '_commercial_card');
	element.children('label[for="re_' + old + '_tcv_card"]').attr('for', 're_' + newId + '_tcv_card');
	element.children('select[name="re_' + old + '_tcv_card"]').attr('id', 're_' + newId + '_tcv_card');
	element.children('select[name="re_' + old + '_tcv_card"]').attr('name', 're_' + newId + '_tcv_card');
	element.children('a[name="re_remove_' + old + '"]').attr('name', 're_remove_' + newId);
	element.children('a[name="re_remove_' + newId + '"]').click(function() { return removePTPPassenger($D(this));});*/
	
	$D('span[id="re_' + old + '_pax_number"]', element).html(newId);
	$D('span[id="re_' + old + '_pax_number"]', element).attr('id', 're_' + newId + '_pax_number');
	$D('select[name="re_' + old + '_pax_type"]', element).attr('name', 're_' + newId + '_pax_type');
	$D('label[for="re_' + old + '_commercial_card"]', element).attr('for', 're_' + newId + '_commercial_card');
	$D('select[name="re_' + old + '_commercial_card"]', element).attr('id', 're_' + newId + '_commercial_card');
	$D('select[name="re_' + old + '_commercial_card"]', element).attr('name', 're_' + newId + '_commercial_card');
	$D('label[for="re_' + old + '_tcv_card"]', element).attr('for', 're_' + newId + '_tcv_card');
	$D('select[name="re_' + old + '_tcv_card"]', element).attr('id', 're_' + newId + '_tcv_card');
	$D('select[name="re_' + old + '_tcv_card"]', element).attr('name', 're_' + newId + '_tcv_card');
	$D('a[name="re_remove_' + old + '"]', element).attr('name', 're_remove_' + newId);
	$D('a[name="re_remove_' + newId + '"]', element).click(function() { return removePTPPassenger($D(this));});
	return element;
}

function addPTPPassenger() {
	if (nbrPax < 9) {
		var clone = $D('#ptpsearchform-define-traveller-dummy').clone();
		clone.removeAttr('id');
		clone.removeAttr('style');
		clone.addClass('ptpsearchform-define-traveller');
		nbrPax++;
		clone = renamePaxFields(clone, 0, nbrPax);
		$D('#ptpsearchform-travellers').append(clone);
		if (nbrPax >= 9) {
			$D('#ptpsearchform-addpax').hide();
		}
	}
	return false;
}

function removePTPPassenger(id) {
	var oldNbrPax = nbrPax;
	var oldNbr = parseInt(id.attr('name').replace('re_remove_', ''));
	oldNbr++;
	nbrPax--;
	id.parent().parent().remove();
	for (var i = oldNbr; i <= oldNbrPax; i++) {
		renamePaxFields($D('#ptpsearchform-define-traveller-' + i), i, i - 1);
	}
	if (nbrPax < 9 && $D('#ptpsearchform-addpax').is(':hidden')) {
		$D('#ptpsearchform-addpax').show();
	}
	return false;
}

function calculatePaxTypes() {
	var nbrAdults = 0;
	var nbrChilds = 0;
	var nbrYouth = 0;
	var nbrSeniors = 0;
	$D('.ptpsearchform-define-traveller').each(function() {
		var id = $D(this).attr('id').replace('ptpsearchform-define-traveller-', '');
		var type = $D('select[name="re_' + id + '_pax_type"]').val();
		if (type == 'adult') nbrAdults++;
		if (type == 'child') nbrChilds++;
		if (type == 'youth') nbrYouth++;
		if (type == 'senior') nbrSeniors++;
	});
	
	$D('#ptpsearchform-adults').val(nbrAdults);
	$D('#ptpsearchform-children').val(nbrChilds);
	$D('#ptpsearchform-youth').val(nbrYouth);
	$D('#ptpsearchform-seniors').val(nbrSeniors);
}

// PASSES


var nbrOfNewPassPassengers = 0;
function addPassPassenger() {
	nbrOfNewPassPassengers = $D('div.passsearchform-passenger').size();
	if (nbrOfNewPassPassengers < 9) {
		var clone = $D('#passsearchform-addpassenger-dummy').clone();
		clone.removeAttr('style');
		clone.attr('id','passsearchform-passenger-'+(nbrOfNewPassPassengers+1));
		clone.addClass('passsearchform-passenger');
		clone.children('input[name="re_age"]').attr('name','re_age'+(nbrOfNewPassPassengers+1));
		clone.children('a[id="passsearchform-delpassenger"]').attr('id','passsearchform-delpassenger-'+(nbrOfNewPassPassengers+1));
		clone.children('a[id="passsearchform-delpassenger-'+(nbrOfNewPassPassengers+1)+'"]').click(function(){ return delPassPassenger(this.id.replace('passsearchform-delpassenger-','')); });
		clone.insertBefore('#passsearchform-addpassenger');
		nbrOfNewPassPassengers++;
		if (nbrOfNewPassPassengers == 1) {
			$D('.passsearchform-delpassenger').hide();
		} else {
			$D('.passsearchform-delpassenger').show();
		}
	}
	if (nbrOfNewPassPassengers == 9) {
		$D('#passsearchform-addpassenger').hide();
	}
	$D('#passsearchform-passenger-'+(nbrOfNewPassPassengers)+' input').focus();
	return false; 
}

function delPassPassenger(nbr) {
	$D('#passsearchform-passenger-'+nbr).remove();
	$D('#passsearchform-addpassenger').show();
	nbrOfNewPassPassengers = $D('div.passsearchform-passenger').size();
	if (nbrOfNewPassPassengers == 1) {
		$D('.passsearchform-delpassenger').hide();
	}
	return false;
}

function addCountry(countryCode) {
	var map_pass_search_countries = $D('select.passsearchform-country');
	for(var i=0 ; i<map_pass_search_countries.size() ; i++) {
		if (map_pass_search_countries[i].value == countryCode) {
			return false;
		}
	}
	for(var i=0 ; i<map_pass_search_countries.size() ; i++) {
		if (map_pass_search_countries[i].value == '') {
			for (var j=0; j<map_pass_search_countries[i].length; j++) {
				if (map_pass_search_countries[i][j].value == countryCode) {
					map_pass_search_countries[i][j].selected = true;
					map_pass_search_countries[i].id = countryCode;
					if (i > 1 && $D(map_pass_search_countries[i+1]).parent().parent().css('display') == 'none') {
						$D(map_pass_search_countries[i+1]).parent().parent().show();
						$D('#passsearchform-days tr').eq(i+2).show();
					}
					return false;
				}
			}
		}
	}
	return false;
}

function delCountry(countryCode) {
	var map_pass_search_countries = $D('select.passsearchform-country');
	for(var i=0 ; i<map_pass_search_countries.size() ; i++) {
		if (map_pass_search_countries[i].value == countryCode) {
			map_pass_search_countries[i].selectedIndex = -1;
			return false;
		}
	}
	return false;
}

function submitPaxForm(theSolutionId) {
	if ($D('#passresult-paxform-' + theSolutionId).valid()) {
		self.parent.tb_remove();
		doPost();
		$D('#passresult-paxform-' + theSolutionId).submit();
	}
}


// Global

function initPtp() {
	if ($D('#ptpsearchform-origincityname').size() > 0) {
		if($D('#ptpsearchform-origincityname').autocomplete) {
			$D('#ptpsearchform-origincityname').autocomplete({ ajax_get:getCities, minchars:3, callback:setOriginCity, delay:500, cache:false, pre_callback:setOriginCity });
		}
	}
	
	if ($D('#ptpsearchform-destinationcityname').size() > 0) {
		if($D('#ptpsearchform-destinationcityname').autocomplete) {
			$D('#ptpsearchform-destinationcityname').autocomplete({ ajax_get:getCities, minchars:3, callback:setDestinationCity, delay:500, cache:false, pre_callback:setDestinationCity});
		}
	}
	
	if ($D('#ptpsearchform-viacityname').size() > 0) {
		if($D('#ptpsearchform-viacityname').autocomplete) {
			$D('#ptpsearchform-viacityname').autocomplete({ ajax_get:getCities, minchars:3, callback:setViaCity, delay:500, cache:false, pre_callback:setViaCity});
		}
		
		$D('#re_via_ind').change(function() { if($D(this).attr('checked')) {$D('#ptpsearchform-viacityname').removeAttr('disabled').parent().removeClass('ptpsearchform-disabled'); } else { $D('#ptpsearchform-viacityname').attr('disabled', 'disabled').parent().addClass('ptpsearchform-disabled'); } });
		$D('#re_via_ind').click(function() { if($D(this).attr('checked')) {$D('#ptpsearchform-viacityname').removeAttr('disabled').parent().removeAttr('ptpsearchform-disabled'); } else { $D('#ptpsearchform-viacityname').attr('disabled', 'disabled').parent().addClass('ptpsearchform-disabled'); } });
		$D('#re_via_ind').change();
	}
	
	$D('#ptpsearchform-originstationname').change(function(){ checkDestinations(this.value); return false; });
	$D('#ptpsearchform-originstationname').click(function(){ checkDestinations(this.value); return false; });
	
	$D('#ptpsearchform-selectorigin').click(function(){ window.open(pathRailengine+'re_domain=ptp&re_oper=cities&re_target=ptpsearchform-origincityname','selector','height=400,width=480,status=no,toolbar=no,location=no,menu=no,resizable=yes,scrollbars=yes'); return false; });
	$D('#ptpsearchform-selectdestination').click(function(){ window.open(pathRailengine+'re_domain=ptp&re_oper=cities&re_target=ptpsearchform-destinationcityname','selector','height=400,width=480,status=no,toolbar=no,location=no,menu=no,resizable=yes,scrollbars=yes'); return false; });

	if ($D('#ptpsearchform-departuredate-cal').size() > 0) {
		doCal('ptpsearchform-departuredate-cal', 'ptpsearchform-returndate-cal', 'forward', 'rail');
		$D('#ptpsearchform-departuredate-cal').mask(maskPattern);
	}
	
	if ($D('#ptpsearchform-returndate-cal').size() > 0) {
		$D('#ptpsearchform-returndate-cal').focus(function() { $D('#ptpsearchform-roundtrip').attr('checked','checked'); $D('#ptpsearchform-roundtripmode').val('FORWARD_AND_RETURN'); $D('#ptpsearchform-roundtripmode').attr('checked','checked'); enablePtpReturnInputs(); });
		doCal('ptpsearchform-returndate-cal', 'ptpsearchform-departuredate-cal', 'back', 'rail');
		$D('#ptpsearchform-returndate-cal').mask(maskPattern);
	}
	
	$D('input.ptpresult-pax-dateofbirth').mask("99/99/9999");
	
	$D('#ptpsearchform-oneway').change(function() { $D('#ptpsearchform-roundtripmode').val('FORWARD_ONLY'); $D('#ptpsearchform-roundtripmode').removeAttr('checked'); disablePtpReturnInputs(); });
	$D('#ptpsearchform-oneway').click(function() { $D('#ptpsearchform-roundtripmode').val('FORWARD_ONLY'); $D('#ptpsearchform-roundtripmode').removeAttr('checked'); disablePtpReturnInputs(); });
	$D('#ptpsearchform-roundtrip').change(function() { $D('#ptpsearchform-roundtripmode').val('FORWARD_AND_RETURN'); $D('#ptpsearchform-roundtripmode').attr('checked','checked'); enablePtpReturnInputs(); });
	$D('#ptpsearchform-roundtrip').click(function() { $D('#ptpsearchform-roundtripmode').val('FORWARD_AND_RETURN'); $D('#ptpsearchform-roundtripmode').attr('checked','checked'); enablePtpReturnInputs(); });
	$D('#ptpsearchform-roundtripmode').change(function() { if (this.checked) { enablePtpReturnInputs(); $D('#ptpsearchform-roundtripmode').val('FORWARD_AND_RETURN') } else { disablePtpReturnInputs(); $D('#ptpsearchform-roundtripmode').val('FORWARD_ONLY'); }});
	$D('#ptpsearchform-roundtripmode').click(function() { if (this.checked) { enablePtpReturnInputs(); $D('#ptpsearchform-roundtripmode').val('FORWARD_AND_RETURN') } else { disablePtpReturnInputs(); $D('#ptpsearchform-roundtripmode').val('FORWARD_ONLY'); }});
	$D('#ptpsearchform-reservation').change(function() { if (this.checked) { $D('#ptpsearchform-reservation-value').val('yes'); } else { $D('#ptpsearchform-reservation-value').val(''); } });
	$D('#ptpsearchform-reservation').click(function() { if (this.checked) { $D('#ptpsearchform-reservation-value').val('yes'); } else { $D('#ptpsearchform-reservation-value').val(''); } });
	
	if ($D('#ptpsearchform-adults').size() > 0) {
		$D('#ptpsearchform-adults').formatInput();
		$D('#ptpsearchform-seniors').formatInput();
		$D('#ptpsearchform-youth').formatInput();
		$D('#ptpsearchform-children').formatInput();
	}
	
	$D('a#ptpsearchform-search').click(function() { if ($D('#ptpsearchform').valid()) { if ($D('#ptpsearchform-travellers').size() > 0) { calculatePaxTypes(); } return doSubmit($D('#ptpsearchform')); } else { return false} });
	$D('a#bookinghorizonform-submit').click(function() { return doSubmit($D('#bookinghorizonform')); });
	$D('a.ptpresult-select-package').live("click", function() { return doSubmit($D(this).prev()); });
	$D('a#advancedSearchLink').click(function() {
		$D('#re_oper').val('advanced');
		if ($D('#ptpsearchform').valid()) { return doSubmit($D('#ptpsearchform')); } else {  return false; }
	});
	
	$D('#ptpsearchform-addpax').click(function() { return addPTPPassenger(); });
	$D('.ptpsearchform-traveller-remove').click(function() { return removePTPPassenger($D(this));});
	
	$D('.ptp-citySelector').click(function() { return doPost(); });
	
	if ($D('#ptpsearchform').size() > 0) {
		$D('#ptpsearchform').validate({
			rules: {
				"re_departuredate": { required: true, dateBE: true},
				"re_returndate": { 
					required: function(element) { return $D('#ptpsearchform-roundtripmode').val() == "FORWARD_AND_RETURN"},
					dateBE: function(element) { return $D('#ptpsearchform-roundtripmode').val() == "FORWARD_AND_RETURN"}
				},
				"re_origincityname": { required: function(element) { return $D('#re_oper').val() != "advanced" } },
				"re_destinationcityname": { required: function(element) { return $D('#re_oper').val() != "advanced" } },
				"re_1_pax_type": {
					required: function(element) { return $D('#ptpsearchform-travellers').size() > 0}
				}
			}, submitHandler: function(form) { if ($D('#ptpsearchform-travellers').size() > 0) { calculatePaxTypes(); } doPost(); form.submit();}
		});
	}
	
	if ($D('#order-ptpproducts').size() > 0) {
		var moreinfoLinks = $D('#order-ptpproducts .order-ptp-terms a.moreinfo');
		for (var i=0 ; i<moreinfoLinks.size() ; i++) {
			$D(moreinfoLinks[i]).click(function(ev){ $D(this).toggleClass('on'); $D('#order-ptp-fare-'+ this.name).toggle($D('#order-ptp-fare-'+ this.name).css('display') == 'none'); return false; });
		}
	}
}

function initPass() {
	//Don't remove, needed for pass snippets!
	$D('.passengerform-countries').change(function() { checkCountries(this); });
	
	var btn_pass_addpax = $D('#passsearchform-addpassenger');
	var btn_pass_delpax = $D('.passsearchform-delpassenger');
	var map_pass_search = $D('#passsearchform-map');
	var map_pass_search_countries = $D('select.passsearchform-country');
	var oldCountryCode = '';
	var newCountryCode = '';
	if (btn_pass_addpax.size() > 0) {
		if (btn_pass_delpax.size()-1 == 0) {
			addPassPassenger();
		}
		btn_pass_addpax.click(addPassPassenger);
	}
	for (var i=0 ; i<btn_pass_delpax.size() ; i++) {
		var nbr = btn_pass_delpax[i].id.replace('passsearchform-delpassenger-','');
		if (nbr != 'passsearchform-delpassenger') {
			btn_pass_delpax[i].onclick = function(){ return delPassPassenger(this.id.replace('passsearchform-delpassenger-','')); };
		}
	}
	if (map_pass_search.size() > 0) {
		var nbrMaxCountries = map_pass_search_countries.size();
		var countries = '';
		for (var i=0 ; i<map_pass_search_countries.size() ; i++) {
			if (map_pass_search_countries[i].value != '' && map_pass_search_countries[i].value != null) {
				countries += map_pass_search_countries[i].value + '|';
				$D(map_pass_search_countries[i]).parent().parent().show();
			} else if (i>2 && map_pass_search_countries[i-1].value != '' && map_pass_search_countries[i-1].value != null) {
				$D(map_pass_search_countries[i]).parent().parent().show();
			}
		}
		var flashvars = {
		  clickableCountry: 'Y',
		  activeColor: '0x'+passMapColor,
		  numberMax: nbrMaxCountries,
		  countries: countries
		};
		var params = {
		  allowscriptaccess: 'always',
		  wmode: 'transparent'
		};
		var attributes = {};
		swfobject.embedSWF(pathImages+'map.swf', 'passsearchform-map', passMapSize, passMapSize, '8', "expressInstall.swf", flashvars, params, attributes);
	}
	for (var i=0 ; i<map_pass_search_countries.size() ; i++) {
		$D(map_pass_search_countries[i]).change(function() {
			oldCountryCode = this.id;
			newCountryCode = this.value;
			for (var j=0 ; j<map_pass_search_countries.size() ; j++) {
				if (this.name != map_pass_search_countries[j].name && map_pass_search_countries[j].value == newCountryCode) {
					this.selectedIndex = -1;
					newCountryCode = this.value;
				} else if (this.name == map_pass_search_countries[j].name && j > 1 && this.value != '') {
					$D(map_pass_search_countries[j+1]).parent().parent().show();
					$D('#passsearchform-days tr').eq(j+2).show();
				}
			}
			if (getFlashMovie('passsearchform-map') != null) {
				getFlashMovie('passsearchform-map').uncheckCountry(oldCountryCode);
				if (newCountryCode != '') {
					this.id = newCountryCode;
					getFlashMovie('passsearchform-map').checkCountry(newCountryCode);
				}
			} 
			return false;
		});
	}	
	$D('a#passsearchform-search').click(function() { return doSubmit($D('#passsearchform')); });
	
	$D('#passresult .passresult-solutions a.moreinfo').click(function(ev){ 
		$D(this).toggleClass('on'); 
		$D('#passresult-prices-'+ this.id.replace('moreinfo-','') + 'a').toggle($D('#passresult-prices-'+ this.id.replace('moreinfo-','') + 'a').css('display') == 'none'); 
		$D('#passresult-prices-'+ this.id.replace('moreinfo-','') +'b').toggle($D('#passresult-prices-'+ this.id.replace('moreinfo-','') +'b').css('display') == 'none'); 
		$D('#passresult-passterms-'+ this.id.replace('moreinfo-','')).toggle($D('#passresult-passterms-'+ this.id.replace('moreinfo-','')).css('display') == 'none'); 
		return false; });
	$D('#passresult a.passresult-other-passes').click(function(ev){ 
		var hiddenPasses = $D('#passresult tr.passresult-pass-hidden'); 
		$D(this).hide(); 
		for (var j=0 ; j<hiddenPasses.size() ; j++) { $D(hiddenPasses[j]).toggle($D(hiddenPasses[j]).css('display') == 'none'); } 
		return false;
	});
	
	if ($D('#order-passproducts').size() > 0) {
		var moreinfoLinks = $D('#order-passproducts .order-pass-terms a.moreinfo');
		for (var i=0 ; i<moreinfoLinks.size() ; i++) {
			$D(moreinfoLinks[i]).click(function(ev){ $D(this).toggleClass('on'); $D('#order-pass-fare-'+ this.name).toggle($D('#order-pass-fare-'+ this.name).css('display') == 'none'); return false; });
		}
	}
}

function initLocalPass() {
	if ($D('#localpasssearchform').size() > 0) {
		doCal('passlocalsearchform-departuredate-cal', null, null, 'rail');
		$D('#passlocalsearchform-departuredate-cal').mask(maskPattern);
		
		$D('#passlocalsearchform-adult').formatInput();
		$D('#passlocalsearchform-children').formatInput();
		$D('#passlocalsearchform-youth').formatInput();
		$D('#passlocalsearchformsearch').click(function() { if ($D('#localpasssearchform').valid()) {return doSubmit($D('#localpasssearchform'));} else { return false} });
	}
}

function initCommercialCards() {
	
	if ($D('#cards-form').length) {
		$D('#cards-form-commercial').click(function() { $D('#commercial-card').show(); $D('#abonnement').hide();});
		$D('#cards-form-abonnement').click(function() { $D('#commercial-card').hide(); $D('#abonnement').show();});
		
		if ($D('#commercial-card-form').size() > 0) {
			doCal('commercial-card-validationDate', null, null, 'rail');
			$D('#commercial-card-validationDate').mask(maskPattern);
			$D('#commercial-card-dateOfBirth').mask("99/99/9999");
			$D('#commercial-card-form-button').click(function() { if ($D('#commercial-card-form').valid()) {return doSubmit($D('#commercial-card-form'));} else { return false} });
		}
		
		if ($D('#abonnement-form').size() > 0) {
			if ($D('#abonnement-origincityname-display').size() > 0) {
				if($D('#abonnement-origincityname-display').autocomplete) {
					$D('#abonnement-origincityname-display').autocomplete({ ajax_get:getStations, minchars:3, callback:setOriginStation, delay:500, cache:false, pre_callback:setOriginStation });
				}
			}
			if ($D('#abonnement-destinationcityname-display').size() > 0) {
				if($D('#abonnement-destinationcityname-display').autocomplete) {
					$D('#abonnement-destinationcityname-display').autocomplete({ ajax_get:getStations, minchars:3, callback:setDestinationStation, delay:500, cache:false, pre_callback:setDestinationStation});
				}
			}
			$D('#re_all_stations').change(function() { if($D(this).attr('checked')) { $D('.abonnement_station_field').attr('disabled', 'disabled'); } else { $D('.abonnement_station_field').removeAttr('disabled'); } });
			$D('#re_all_stations').click(function() { if($D(this).attr('checked')) { $D('.abonnement_station_field').attr('disabled', 'disabled'); } else { $D('.abonnement_station_field').removeAttr('disabled'); } });
			$D('#re_all_stations').change();
			
			$D('#abonnement-form-button').click(function() { if ($D('#abonnement-form').valid()) {return doSubmit($D('#abonnement-form'));} else { return false} });
			$D('#abonnement-form').validate({
				rules: {
					"re_cardtype": { required: true },
					"re_abonnement_classOfService": { required: true },
					"re_origincityname_display": { required: function(element) { return !$D('#re_all_stations').attr('checked') } },
					"re_destinationcityname_display": { required: function(element) { return !$D('#re_all_stations').attr('checked') } }
				}, submitHandler: function(form) { doPost(); form.submit();}
			});
		}
	}
	
	if ($D('#abonnement-results').length) {
		doCal('abonnement-validationDate', null, null, 'rail');
		$D('#abonnement-validationDate').mask(maskPattern);
		$D('#abonnement-dateOfBirth').mask("99/99/9999");
		$D('#abonnement-results-button').click(function() { if ($D('#abonnement-result-summary-form').valid()) {return doSubmit($D('#abonnement-result-summary-form'));} else { return false} });
	}
}

function initRail() {
	
	//PTP
	initPtp();
	
	// PASS
	initPass();
	
	// Local pass (REC only)
	initLocalPass();
	
	// Commercial cards (REC only)
	initCommercialCards();
}

$D(document).ready(initRail);