/**
 * Universal Engine
 * Rail
 * Version: 3.0 r1
 * Duo NV
 */

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;
	}
	maxCount = 200;
	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();
	
	if(lastCountry == 'BG' || lastCountry == 'ME' || lastCountry == 'RB') {
		lastCountry = 'BGCS';
	}
	if(lastCountry == 'BE' || lastCountry == 'NL' || lastCountry == 'LU') {
		lastCountry = 'BX';
	}
	if(lastCountry == 'HR' || lastCountry == 'SI') {
		lastCountry = 'SIHR';
	}
	
	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(country == 'BG' || country == 'ME' || country == 'RB') {
			country = 'BGCS';
		}
		if(country == 'BE' || country == 'NL' || country == 'LU') {
			country = 'BX';
		}
		if(country == 'HR' || country == 'SI') {
			country = 'SIHR';
		}
		
		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 == 'BG' || country == 'ME' || country == 'RB') {
			country = 'BGCS';
		}
		if(country == 'BE' || country == 'NL' || country == 'LU') {
			country = 'BX';
		}
		if(country == 'HR' || country == 'SI') {
			country = 'SIHR';
		}
		
		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);
	}
}

function doPtpFind(fromRrCode,toRrCode,date) {
	pathRailengine = "duoHack";
	doPost();
	document.location = "/spip.php?page=sales&re_domain=ptp&re_oper=search&re_geography=" +
	"&re_origincityname=&re_origincitycode=" + fromRrCode + 
	"&re_destinationcityname=&re_destinationcitycode=" + toRrCode +
	"&re_departuredate=" + date + "&re_departuredate-alt=" + date +"&re_departuredate_hour=00%3A01&re_returndate=&re_returndate-alt=&re_returndate_hour=" +
	"&re_adults=1&re_children=0&re_youth=0&re_seniors=0";
}

// Abonnements
function getStations(request, response) {
	var script = pathRailengine + "re_domain=ajax&re_oper=stations";
	var params = { 're_value':request.term , 're_geography':stationGeography };
	$D.get(script, params, function(obj) {
		obj = obj.replace(/[\n\r\t]/g,'');
		if(obj.toString().indexOf("NullPointerException") == -1 && obj.toString().indexOf("error") == -1 && obj.toString() != '') {
			var cities = "";
			if(obj.indexOf('|') == -1) {
				cities = obj.split(',');
			} else {
				cities = obj.split('|');
			}
			var res = [];
			var tempHolder = [];
			var hasPopular = false;
			var hasOthers = false;
			
			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];
				var stationscore = citydata[5];
				
				if (stationscore != '0') {
					hasPopular = true;
				} else {
					hasOther = true;
				}
				if (cityname != '' && typeof cityname != 'undefined') {
					tempHolder.push({citycode:citycode, cityname:cityname, citycountry:citycountry, stationcode:stationcode, stationname:stationname, stationscore:stationscore});
				}
			}
			
			for (var i = 0; i < cities.length; i++) {
				var citycode = tempHolder[i].citycode;
				var cityname = tempHolder[i].cityname
				var citycountry = tempHolder[i].citycountry
				var stationcode = tempHolder[i].stationcode;
				var stationname = tempHolder[i].stationname
				var stationscore = tempHolder[i].stationscore
				var category = "";
				if(stationscore != '0') {
					category = labelAutocompleteSuggestedStations;
					otherCities = true;
				}
				if(stationscore == '0' && otherCities) {
					category = labelAutocompleteOtherStations;
				}
				
				// Highlight the user input
				if (cityname != '' && typeof cityname != 'undefined') {
					var stationname_highlight = stationname;
					var x = new RegExp('\\b'+request.term, 'ig'); // notice the escape \ here... 
					stationname_highlight = stationname_highlight.replace(x, function(FullMatch,n){
						return '<span class="autocomplete-abo-stationname-highlight">'+FullMatch+'</span>'
					});
					
					res.push({label:'<span class="autocomplete-abo-stationname">'+stationname_highlight+'</span><span class="autocomplete-abo-citycountry">'+citycountry+'</span>', value:stationname, stationname:stationname, stationcode:stationcode, cityname:cityname, citycode:citycode, citycountry:citycountry, category:category});
				}
			}
			response(res);
		} else {
			response();
		}
	});
}

/*
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.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 getInboundSolutions(solutionId, packageId) {
	$D('.ptpresult-inbound-link').removeClass('selected');
	$D('#inbound-for-'+solutionId+'-'+packageId).addClass('selected');
	$D('#waiting-page').show();
	$D('#ptpresult-inbound-summary').empty();
	$D('#ptpresult-inbound-solutions').empty();
	
	$D.ajax({
		type: "GET",
		url: pathRailengine,
		cache: false,
		data: "re_ajax=true&re_domain=ptp&re_oper=selectreturn&re_solution="+solutionId+"&re_package="+packageId+"&"+$D('input', $D('#ptpresult-outbound-package-'+solutionId+'-'+packageId+'-seating')).serialize(),
		success: function(data) {
			$D('#ptpresult-inbound-summary').replaceWith($D('#ptpresult-inbound-summary', data));
			$D('#ptpresult-inbound-solutions').replaceWith($D('#ptpresult-inbound-solutions', data));
			adaptPtpResultBoundSummary('inbound');
			adaptPtpResultBoundSolutions('inbound');
			tb_init('a.thickbox, area.thickbox, input.thickbox');
			$D('#waiting-page').hide();
			$D.scrollTo($D('#ptpresult-inbound-summary'), {duration:500});
		}
	});
}

function adaptPtpResultBoundSolutions(bound) {
	var topLinks = $D('.ptpresult-'+bound+'-top');
    for (var i=0 ; i<topLinks.size() ; i++) {
    	$D(topLinks[i]).click(function(ev) { $D.scrollTo($D('#ptpresult-' + bound + '-summary'), {duration:500}); return false; });
    }
   
	var moreinfoLinks = $D('#ptpresult .ptpresult-solutions .ptpresult-packages a.moreinfo');
	for (var i = 0 ; i < moreinfoLinks.size(); i++) {
		$D(moreinfoLinks[i]).click(function(ev){ $D(this).toggleClass('on'); $D('#ptpresult-' + bound + '-package-'+ this.name + '-farerules').toggle($D('#ptpresult-' + bound + '-package-'+ this.name + '-farerules').css('display') == 'none'); return false; });
	}
	
	var seatingLinks = $D('#ptpresult .ptpresult-solutions .ptpresult-packages a.seatingPref');
	for (var i = 0; i < seatingLinks.size(); i++) {
		$D(seatingLinks[i]).click(function(ev){ $D(this).toggleClass('on'); $D('#ptpresult-' + bound + '-package-' + this.name + '-seating').toggle($D('#ptpresult-' + bound + '-package-'+ this.name + '-seating').css('display') == 'none'); return false; });
	}
	
	var seatingSelectors = $D('#ptpresult .ptpresult-solutions .ptpresult-packages input.seating-'+bound+'-selector');			
	for (var i = 0; i < seatingSelectors.size(); i++) {
		$D(seatingSelectors[i]).click(function(ev){
			var selected = $D(this).val();
			var id = $D(this).attr('id').replace('re-seating-'+bound+'-selector-', '').replace('-' + selected, '');
			var fieldset = $D('#ptpresult-' +bound + '-seatpref-' + id);
			$D('.extraData', fieldset).hide();
			$D('.' + selected, fieldset).toggle($D('.' + selected, fieldset).css('display') == 'none');
		});
		$D(seatingSelectors[i]).change(function(ev){
			var selected = $D(this).val();
			var id = $D(this).attr('id').replace('re-seating-'+bound+'-selector-', '').replace('-' + selected, '');
			var fieldset = $D('#ptpresult-' + bound + '-seatpref-' + id);
			$D('.extraData', fieldset).hide();
			$D('.' + selected, fieldset).toggle($D('.' + selected, fieldset).css('display') == 'none');
		});
	}
}

function adaptPtpResultBoundSummary(bound) {
	var tableCells = $D('table.ptpresult-solutionsset-' + bound + ' tr td');
	if(bound ==  'inbound') { var inboundSolutionSelected = 'table.ptpresult-solutionsset-' + bound + ' tr td.ptpresult-' + bound + '-solution-1'; }
	if(bound == 'outbound') {
		var outboundSolutionSelected = 'table.ptpresult-solutionsset-' + bound + ' tr td.ptpresult-' + bound + '-solution-1';
		$D.scrollTo($D('#ptpresult'), {duration:500});
	}
	for (var i=0 ; i<tableCells.size() ; i++) {
		$D(tableCells[i]).click(
			function() {
				if(this.className != "") {
					solutionSelected = '';
					if(bound ==  'inbound') { solutionSelected =  inboundSolutionSelected; }
					if(bound == 'outbound') { solutionSelected = outboundSolutionSelected; }
					if(solutionSelected.replace('table.ptpresult-solutionsset-' + bound + ' tr td.', '') != this.className.replace(' on','').replace(' ptpresult-package-fromprice','')) {
						if(bound ==  'outbound') {
							$D('#ptpresult-inbound-summary').empty();
							$D('#ptpresult-inbound-solutions').empty();
						}
					}
					
					var previousId = '#' + solutionSelected.replace('table.ptpresult-solutionsset-' + bound + ' tr td.', '');
					if(previousId != '#') { $D(previousId).hide();}
					
					var className = 'table.ptpresult-solutionsset-' + bound + ' tr td';
					var t = $D(className);
					t.removeClass('on');
					
					solutionSelected = 'table.ptpresult-solutionsset-' + bound + ' tr td.' + this.className.replace(' ptpresult-package-fromprice','');
					var t2 = $D(solutionSelected);
					t2.addClass('on');

					if(bound ==  'inbound') { inboundSolutionSelected  = solutionSelected; }
					if(bound == 'outbound') { outboundSolutionSelected = solutionSelected; }

					var elementId = '#' + this.className.replace(' on','').replace(' ptpresult-package-fromprice','');
					$D(elementId).show();
					$D.scrollTo($D(elementId), {duration:500});
				}
			}
		);
		$D(tableCells[i]).hover(
			function() {
				if(this.className != "") {
					var className = 'table.ptpresult-solutionsset-' + bound + ' tr td.' + this.className.replace(' ptpresult-package-fromprice','');
					var t = $D(className);
					t.addClass('on');
				}
			}, 
			function() {
				if(this.className != "") {
					var className = 'table.ptpresult-solutionsset-' + bound + ' tr td.' + this.className.replace(' on','').replace(' ptpresult-package-fromprice','');
					solutionSelected = '';
					if(bound ==  'inbound') { solutionSelected =  inboundSolutionSelected; }
					if(bound == 'outbound') { solutionSelected = outboundSolutionSelected; }
					if(className != solutionSelected) {
						var t = $D(className);
						t.removeClass('on');
					}
				}
			}
		);
	}
}
*/
function getCities(request, response) {
	var script = pathRailengine + "re_domain=ajax&re_oper=cities";
	var params = { 're_value':request.term , 're_geography':stationGeography };
	$D.get(script, params, function(obj) {
		obj = obj.replace(/[\n\r\t]/g,'');
		if(obj.toString().indexOf("NullPointerException") == -1 && obj.toString().indexOf("error") == -1 && obj.toString() != '') {
			var res = [];
			var tempHolder = [];
			var cities = "";
			if(obj.indexOf('|') == -1) {
				cities = obj.split(',');
			} else {
				cities = obj.split('|');
			}
			var hasPopular = false;
			var hasOther = false;
			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 cityscore = citydata[3];
				if (cityscore != '0') {
					hasPopular = true;
				} else {
					hasOther = true;
				}
				if (cityname != '' && typeof cityname != 'undefined') {
					tempHolder.push({citycode:citycode, cityname:cityname, citycountry:citycountry, cityscore:cityscore});
				}
			}
			for (var i = 0; i < tempHolder.length; i++) {
				var category = "";
				var citycode = tempHolder[i].citycode;
				var cityname = tempHolder[i].cityname;
				var citycountry = tempHolder[i].citycountry
				var cityscore = tempHolder[i].cityscore;
				if (hasPopular && hasOther) {
					if (cityscore != '0') {
						category = labelAutocompleteSuggestedCities;
					} else {
						category = labelAutocompleteOtherCities;
					}
				}
				
				// Highlight the user input
				if (cityname != '' && typeof cityname != 'undefined') {
					var cityname_highlight = cityname;
					var x = new RegExp('\\b'+request.term, 'ig'); // notice the escape \ here... 
					cityname_highlight = cityname_highlight.replace(x, function(FullMatch,n){
						return '<span class="autocomplete-cityname-highlight">'+FullMatch+'</span>'
					});
					
					res.push({label:'<span class="autocomplete-cityname">'+cityname_highlight+'</span><span class="autocomplete-citycountry">'+citycountry+'</span>', value:cityname, cityname:cityname, citycode:citycode, citycountry:citycountry, category:category});
				}
			}
			response(res);
		} else {
			response();
		}
	});
}
/*
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 setNbrPassengers(newPaxNbr) {
	if (nbrPax < newPaxNbr) {
		var diff = newPaxNbr - nbrPax;
		for (var i = 0; i < diff; i++) {
			addPTPPassenger();
		}
	} else {
		for (var i = parseInt(newPaxNbr) + 1; i <= nbrPax; i++) {
			$D('#ptpsearchform-define-traveller-' + i).remove();
		}
	}
	nbrPax = newPaxNbr;
}

function renamePaxFields(element, old, newId) {
	element.attr('id', 'ptpsearchform-define-traveller-' + newId);
	$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).unbind('click');
	$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) {
			calculateDays();
			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();
					}
					calculateDays();
					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;
			if ($D('#passsearchform-country-days-' + (i+1)).size() > 0) {
				$D('#passsearchform-country-days-' + (i+1)).val('');
			}
			calculateDays();
			return false;
		}
	}
	return false;
}

function calculateDays() {
	var map_pass_search_countries = $D('select.passsearchform-country');
	var total = 0;
	total = parseInt(total);
	for (var i = 0; i < map_pass_search_countries.size(); i++) {
		if ($D(map_pass_search_countries[i]).val() && $D('#passsearchform-country-days-' + (i+1)).val() != "") {
			total = total + parseInt($D('#passsearchform-country-days-' + (i+1)).val()) + 1;
		}
	}
	if (total > 0) {
		$D('#passsearchform-europe-days').val(total);
	} else {
		$D('#passsearchform-europe-days').val('');
	}
}

function passShowEmailBox(id) {
	var form = $D('#' + id);
	form.validate({ignore: ":hidden"});
	if (form.valid()) {
		var firstBox = $D('.pass-pax-main-content', form);
		firstBox.hide();
		var secondBox = $D('.pass-pax-additional-content', form);
		if (isdefined('pass_passengerIds')) {
			for (var i = 0; i < pass_passengerIds.length; i++) {
				var gender = $D('#re_' + pass_passengerIds[i] + '_gender').val();
				var title = title_male;
				if (gender == 'F') {
					title = title_female;
				}
				var firstName = $D('#re_' + pass_passengerIds[i] + '_firstname').val();
				var lastName = $D('#re_' + pass_passengerIds[i] + '_lastname').val();
				$D('#re_' + pass_passengerIds[i] + '_name_frp', secondBox).text(title + ' ' + firstName + ' ' + lastName);
			}
		}
		secondBox.show();
	}
	return false;
}

function closeFrpBox(id) {
	var form = $D('#' + id);
	$D('.pass-pax-additional-content', form).hide();
	$D('.pass-pax-main-content', form).show();
	return false;
}

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

//Pass list

function passListShow() {
	$D("#passfamily-holder").hide();
	var selectedCountries = new Array();
	requestedCountries = new Array();
	$D('#passlist-countryBox input[type=checkbox]:checked').each(function() {
		selectedCountries.push($D(this).val());
	});
	
	var selectedTypes = new Array();
	$D('#passlist-typeBox input[type=checkbox]:checked').each(function() {
		selectedTypes.push($D(this).val());
		var code = $D(this).val();
		if (code == "BE" || code == "NL" || code == "LU") code = "BX";
		requestedCountries[code] = [true, false];
	});
	
	$D('.passlist-passes').show();
	$D('.passlist-passes li').hide();
	var found = 0;
	$D('.passlist-passes li').each(function() {
		var showCountry = true;
		var showType = true;
		var classname = $D(this).attr('class');
		if (selectedTypes.length > 0) {
			for ( var i = 0; i < selectedTypes.length; i++) {
				if (classname.indexOf(selectedTypes[i]) == -1) {
					showType = false;
				}
			}
		} else {
			showType = true;
		}
		if (selectedCountries.length > 0) {
			for (var j = 0; j < selectedCountries.length; j++) {
				if (classname.indexOf(selectedCountries[j]) == -1) {
					showCountry = false;
				}
			}
		} else {
			showCountry = true;
		}
		if (showType && showCountry) {
			$D(this).show();
			if ($D('input', this).attr('checked')) {
				$D("#passfamily-holder").show();
			}
			found++;
		} else {
			if ($D('input', this).attr('checked')) {
				$D('input', this).attr('checked', false);
			}
		}
	});
	for (var i = 1; i < 4; i++) {
		if ($D('#passlist-' + i + ' li:visible').size() == 0) {
			$D('#passlist-' + i + '-no-found').show();
		} else {
			$D('#passlist-' + i + '-no-found').hide();
		}
	}
}

function loadPassFamily() {
	$D("#passfamily-holder").hide();
	$D("#passfamily-waiting").show();
	$D("input[name='passfamily-familyId']").attr("disabled", "disabled");
	$D.scrollTo($D("#passfamily-waiting"), {duration:500});
	var passTitle = "<h3>" + $(this).attr('title') + "</h3>";
	$D.ajax({
		type: "GET",
		url: pathRailengine,
		cache: false,
		data: "re_ajax=true&re_domain=snippet&re_oper=passfamily&re_family=" + $(this).val(),
		success: function(html) {
			$D('#passfamily-holder').html(passTitle + html);
			$D('#passfamily-holder').show();
			$D('#passfamily-waiting').hide();
			$D("input[name='passfamily-familyId']").removeAttr('disabled');
			$D.scrollTo($D("#passfamily-holder"), {duration:500});
			tb_init('a.thickbox, area.thickbox, input.thickbox');
			$D('.passengerform-countries').change(function() { checkCountries(this); });
		}
	});
}

// Global

var origincityname_value='';
var destinationcityname_value='';
var viacityname_value='';
if (!isdefined('minLengthAutocomplete')) {
	var minLengthAutocomplete = 3;
}
function initPtp() {
	if ($D('#ptpsearchform-origincityname').size() > 0) {
		if($D('#ptpsearchform-origincityname').autocomplete) {
			$D('#ptpsearchform-origincityname').autocomplete({ source:getCities, minLength:minLengthAutocomplete, delay:100, html:true, select:function(event, ui){$D('#ptpsearchform-origincitycode').val(ui.item.citycode);} });
			$D('#ptpsearchform-origincityname').blur(function(){ $D('#ptpsearchform-origincityname').autocomplete('disable'); });
			$D('#ptpsearchform-origincityname').focus(function(){ $D('#ptpsearchform-origincityname').autocomplete('enable'); });
			$D('#ptpsearchform-origincityname').keyup(function(){ if(this.value!=origincityname_value){$D('#ptpsearchform-origincitycode').val('');}; origincityname_value=this.value; });
		}
	}
	
	if ($D('#ptpsearchform-destinationcityname').size() > 0) {
		if($D('#ptpsearchform-destinationcityname').autocomplete) {
			$D('#ptpsearchform-destinationcityname').autocomplete({ source:getCities, minLength:minLengthAutocomplete, delay:100, html:true, select:function(event, ui){$D('#ptpsearchform-destinationcitycode').val(ui.item.citycode);} });
			$D('#ptpsearchform-destinationcityname').blur(function(){ $D('#ptpsearchform-destinationcityname').autocomplete('disable'); });
			$D('#ptpsearchform-destinationcityname').focus(function(){ $D('#ptpsearchform-destinationcityname').autocomplete('enable'); });
			$D('#ptpsearchform-destinationcityname').keyup(function(){ if(this.value!=destinationcityname_value){$D('#ptpsearchform-destinationcitycode').val('');}; destinationcityname_value=this.value; });
		}
	}
	
	if ($D('#ptpsearchform-viacityname').size() > 0) {
		if($D('#ptpsearchform-viacityname').autocomplete) {
			$D('#ptpsearchform-viacityname').autocomplete({ source:getCities, minLength:minLengthAutocomplete, delay:100, html:true, select:function(event, ui){$D('#ptpsearchform-viacitycode').val(ui.item.citycode);} });
			$D('#ptpsearchform-viacityname').blur(function(){ $D('#ptpsearchform-viacityname').autocomplete('disable'); });
			$D('#ptpsearchform-viacityname').focus(function(){ $D('#ptpsearchform-viacityname').autocomplete('enable'); });
			$D('#ptpsearchform-viacityname').keyup(function(){ if(this.value!=viacityname_value){$D('#ptpsearchform-viacitycode').val('');}; viacityname_value=this.value; });
		}
		
		$D('#ptpsearchform-via').change(function() { if($D(this).attr('checked')) { $D('#ptpsearchform-viacityname').removeAttr('disabled').parent().removeClass('ptpsearchform-disabled'); $D('#ptpsearchform-directOnly').removeAttr('checked'); $D('.ptpsearchform-advanced-direct').addClass('ptpsearchform-disabled'); } else { $D('#ptpsearchform-viacityname').attr('disabled', 'disabled').parent().addClass('ptpsearchform-disabled'); } });
		$D('#ptpsearchform-via').click(function() { if($D(this).attr('checked')) { $D('#ptpsearchform-viacityname').removeAttr('disabled').parent().removeClass('ptpsearchform-disabled'); $D('#ptpsearchform-directOnly').removeAttr('checked'); $D('.ptpsearchform-advanced-direct').addClass('ptpsearchform-disabled'); } else { $D('#ptpsearchform-viacityname').attr('disabled', 'disabled').parent().addClass('ptpsearchform-disabled'); } });
		$D('#ptpsearchform-via').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-returndate-clear').click(function() { $D('#ptpsearchform-returndate-cal').val(''); $D('#ptpsearchform-returndate-cal-alt').val(''); $D('#ptpsearchform-roundtripmode').val('FORWARD_ONLY'); $D('#ptpsearchform-roundtripmode').removeAttr('checked'); disablePtpReturnInputs(); });
	$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('#ptpsearchform-nbrPax').change(function() { return setNbrPassengers($D(this).val()); });
	
	if ($D('#ptpsearchform-directOnly').size() > 0) {
		$D('#ptpsearchform-directOnly').change(function() { if($D(this).attr('checked')) { $D('.ptpsearchform-advanced-direct').removeClass('ptpsearchform-disabled'); $D('#ptpsearchform-via').removeAttr('checked'); $D('#ptpsearchform-viacityname').attr('disabled', 'disabled').parent().addClass('ptpsearchform-disabled'); $D('#ptpsearchform-viacityname').val(''); $D('#ptpsearchform-viacitycode').val(''); } else { $D('.ptpsearchform-advanced-direct').addClass('ptpsearchform-disabled'); } });
		$D('#ptpsearchform-directOnly').click(function() { if($D(this).attr('checked')) { $D('.ptpsearchform-advanced-direct').removeClass('ptpsearchform-disabled'); $D('#ptpsearchform-via').removeAttr('checked'); $D('#ptpsearchform-viacityname').attr('disabled', 'disabled').parent().addClass('ptpsearchform-disabled'); $D('#ptpsearchform-viacityname').val(''); $D('#ptpsearchform-viacitycode').val(''); } else { $D('.ptpsearchform-advanced-direct').addClass('ptpsearchform-disabled'); } });
		$D('#ptpsearchform-directOnly').change();
	}
	
	if ($D('#ptpsearchform-anyStationCriteria').size() > 0) {
		$D('#ptpsearchform-anyStationCriteria').change(function() { if($D(this).attr('checked')) { $D('.ptpsearchform-advanced-abs').removeClass('ptpsearchform-disabled');} else { $D('.ptpsearchform-advanced-abs').addClass('ptpsearchform-disabled'); } });
		$D('#ptpsearchform-anyStationCriteria').click(function() { if($D(this).attr('checked')) { $D('.ptpsearchform-advanced-abs').removeClass('ptpsearchform-disabled');} else { $D('.ptpsearchform-advanced-abs').addClass('ptpsearchform-disabled'); } });
		$D('#ptpsearchform-anyStationCriteria').change();
	}
	
	$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; });
		}
	}
	
	// start of new js for V2
	if ($D('.fare-solution-radio').size() > 0) {
		$D('.fare-solution-radio').live("click", function() { 
			$D('.fare-solution').removeClass('active');
			$D(this).parent().addClass('active');
			var height = $D(this).parent().parent().height();
			$D(this).next().css("height", height - 20);
			$D('.ptpresult-pax-button').removeClass('disabled');
			$D('.ptpresult-submit-button').removeClass('disabled');
			$D('.passresult-pax-button').removeClass('disabled');
		});
		$D('.fare-solution-radio').live("change", function() { $D('.fare-solution').removeClass('active'); $D(this).parent().addClass('active'); $D('.ptpresult-pax-button').removeClass('disabled'); $D('.ptpresult-submit-button').removeClass('disabled'); $D('.passresult-pax-button').removeClass('disabled'); });
		//$D('.fare-solution-radio').change();
	}
	
	if ($D('.ptpresult-pax-button').size() > 0) {
		$D('.ptpresult-pax-button').live("click", function() {
			var selected = $D('.fare-solution-radio:checked');
			if (selected.size() > 0 && $D(selected).val() != null && $D(selected).val() != "") {
				var selectedPackage = $D(selected).val();
				selectedPackage = selectedPackage.split('|');
				$.ajax({
					type: "GET",
					url: pathRailengine,
					cache: false,
					data: "re_solution=" + selectedPackage[0] + "&re_package=" + selectedPackage[1] + "&re_engine=railengine&re_domain=ptp&re_oper=pax",
					success: function(html) {
						$D('.railengine-message-error').hide();
						$D('#ptpresult-pax-holder').html(html);
						$D('#ptpresult-journey').hide();
						$D('#ptpresult-searchcriteria-wrapper').hide();
						$D('#ptpresult-pax-holder').show();
						window.scrollTo(0,0);
					}
				});
			}
			return false;
		});
	}
	
	if ($D('.ptpresult-neropax-button').size() > 0) {
		$D('.ptpresult-neropax-button').live("click", function() {
			var solutionId = $D(this).attr('id');
			if (solutionId != null && solutionId != "") {
				var segments = "";
				var classes = $D('.viasegment_class', $D('#solution_' + solutionId));
				for (var i = 0; i < classes.size(); i++) {
					var id = '#re_class_chosen_' + (i+1) + '_' + solutionId;
					segments += "&re_class[]=" + $D(id).val();
				}
				doPost();
				$.ajax({
					type: "GET",
					url: pathRailengine,
					cache: false,
					data: "re_solution=" + solutionId + "&re_package=" + solutionId + "&re_engine=railengine&re_domain=ptp&re_oper=neropax" + segments,
					success: function(html) {
						var test = html.replace(/(^\s+|\s+$)/g,'');
						var test = test.toLowerCase();
						var error = '<p class="railengine-message-error">';
						if (test.match("^" + error) == error) {
							if ($D('.railengine-message-error').size() > 0) {
								$D('.railengine-message-error').replaceWith(html);
							} else {
								$D('.railenginecontent').prepend(html);
							}
						} else {
							$D('#ptpresult-pax-holder').html(html);
							$D('#ptpresult-journey').hide();
							$D('#ptpresult-searchcriteria-wrapper').hide();
							$D('#ptpresult-pax-holder').show();
							tb_init('a.thickbox, area.thickbox, input.thickbox');
						}
						undoPost();
						window.scrollTo(0,0);
					}
				});
			}
			return false;
		});
	}
	
	$D('a.ptpresult-submit-button').live("click", function() {
		var selected = $D('.fare-solution-radio:checked');
		if (selected.size() > 0 && $D(selected).val() != null && $D(selected).val() != "") {
			var selectedPackage = $D(selected).val();
			selectedPackage = selectedPackage.split('|');
			$D('#ptpresult-submit-form-re-solution').val(selectedPackage[0]);
			$D('#ptpresult-submit-form-re-package').val(selectedPackage[1]);
			return doSubmit($D('#ptpresult-submit-form'));
		}
	});
	
	$D('.ptpresult-earlier-trains-link').live("click", function() { getNextPrevTrains('re_ajax=true&re_domain=ptp&re_oper=prevtrains', 'preprend'); return false; });
	$D('.ptpresult-next-trains-link').live("click", function() { getNextPrevTrains('re_ajax=true&re_domain=ptp&re_oper=nexttrains', 'append'); return false; });
	
	/*
	$D('.ptpresult-inbound-link').live("click", function() {
		var arr_ids = $D(this).attr('id').match('inbound-for-(.+)-(.+)');
		var solutionId = arr_ids[1];
		var packageId = arr_ids[2];		
		getInboundSolutions(solutionId, packageId);
		return false; 
	});
	*/
	
	$D('.cart-ptp-product-info').live("click", function() {
		$D('.' + $D(this).attr('id')).toggle();
		$D('span', this).toggleClass('on');
	});
	
	$D('.order-ptp-product-info').live("click", function() {
		$D('.' + $D(this).attr('id')).toggle();
		$D('span', this).toggleClass('on');
	});
	
	$D('.fare-info-image').each(function(index) {
		if((typeof this.naturalWidth != "undefined" && this.naturalWidth == 0 ) || this.readyState == 'uninitialized' ) {
			$D(this).hide();
		}
	});
}

function initPass() {
	//Don't remove, needed for pass snippets!
	$D('.passengerform-countries').change(function() { checkCountries(this); });
	
	var map_pass_search = $D('#passsearchform-map');
	var map_pass_search_countries = $D('select.passsearchform-country');
	var oldCountryCode = '';
	var newCountryCode = '';
		
	$D('input.passsearchform-country-days').keyup(function(){ calculateDays(); return false;});
	
	var re_youth_prev = $D('.re_youth_age_holder').size();
	$D('#re_youth').change(function() {
		var val = $D(this).val();
		if (val != re_youth_prev) {
			if (val > re_youth_prev) {
				for (var i = parseInt(re_youth_prev)+1; i <= val; i++) {
					var clone = $D('#re_youth_age_dummy').clone();
					clone.removeAttr('style');
					clone.attr('id','re_youth_age_holder_' + i);
					clone.children('span').children('input[name="re_age"]').attr('id','re_youth_age_' + i);
					clone.children('span').children('input[name="re_age"]').attr('name','re_age' + i);
					clone.children('label').attr('for','re_youth_age_' + i);
					$D('#form-sb-other-youthage').append(clone);
				}
				re_youth_prev = val;
			} else {
				val = parseInt(val);
				for (var i = val+1; i <= re_youth_prev; i++) {
					$D('#re_youth_age_holder_' + i).remove();
				}
				re_youth_prev = val;
			}
		}
	});
	
	if (map_pass_search.size() > 0) {
		var nbrMaxCountries = map_pass_search_countries.size() + 1;
		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);
				}
			} 
			calculateDays();
			return false;
		});
	}
	$D('#passsearchform-search').click(function() { validateAndSubmitForm('passsearchform'); return false;});

	if ($D('.passresult-pax-button').size() > 0) {
		$D('.passresult-pax-button').live("click", function() {
			var selected = $D('.fare-solution-radio:checked');
			if (selected.size() > 0 && $D(selected).val() != null && $D(selected).val() != "") {
				var selectedSolution = $D(selected).val();
				$.ajax({
					type: "GET",
					url: pathRailengine,
					cache: false,
					data: "re_solutionId=" + selectedSolution + "&re_engine=railengine&re_domain=pass&re_oper=pax",
					success: function(html) {
						$D('#passresult-pax-holder').html(html);
						$D('#passresult-solutions').hide();
						$D('#passresult-searchcriteria-wrapper').hide();
						$D('#passresult-pax-holder').show();
						window.scrollTo(0,0);
						//curvyCorners.redraw();
					}
				});
			}
			return false;
		});
	}
	
	$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('.paxDepartureDate').size() > 0) {
		$D('.paxDepartureDate').each(function() {
			id = $D(this).attr('id');
			doCal(id, null);
		});
	}
	
	// Pass shopping cart
	$D('.cart-pass-product-info').live("click", function() {
		$D('.' + $D(this).attr('id')).toggle();
		$D('span', this).toggleClass('on');
	});
	
	$D('.order-pass-product-info').live("click", function() {
		$D('.' + $D(this).attr('id')).toggle();
		$D('span', this).toggleClass('on');
	});
	
	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_input').formatInput();
		$D('#passlocalsearchformsearch').click(function() { if ($D('#localpasssearchform').valid()) {return doSubmit($D('#localpasssearchform'));} else { return false} });
		$D('#passType').change(function() {
			var ages = $D('option:selected', this).attr('title');
			var showTitle = false;
			if (ages.indexOf('A') != -1) { $D('#passlocalsearchform-adult-holder').show(); showTitle = true; } else { $D('#passlocalsearchform-adult-holder').hide(); $D('#passlocalsearchform-adult').val(0); }
			if (ages.indexOf('S') != -1) { $D('#passlocalsearchform-senior-holder').show(); showTitle = true; } else { $D('#passlocalsearchform-senior-holder').hide(); $D('#passlocalsearchform-senior').val(0); }
			if (ages.indexOf('Y') != -1) { $D('#passlocalsearchform-youth-holder').show(); showTitle = true; } else { $D('#passlocalsearchform-youth-holder').hide(); $D('#passlocalsearchform-youth').val(0); }
			if (ages.indexOf('C') != -1) { $D('#passlocalsearchform-children-holder').show(); showTitle = true; } else { $D('#passlocalsearchform-children-holder').hide(); $D('#passlocalsearchform-children').val(0); }
			if (ages.indexOf('F') != -1) { $D('#passlocalsearchform-freechildren-holder').show(); showTitle = true; } else { $D('#passlocalsearchform-freechildren-holder').hide(); $D('#passlocalsearchform-freechildren').val(0); }
			if (showTitle) { $D('#passlocalsearchform-passengers-title').show(); } else { $D('#passlocalsearchform-passengers-title').hide(); }
			$D('.passlocalsearchform_input').formatInput();
		});
		$D('#passType').change();
	}
}

var abo_origincityname_value = '';
var abo_destinationcityname_value = '';
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({ source:getStations, minLength:minLengthAutocomplete, delay:500, html:true, select:function(event, ui){
							$D('#abonnement-origincityname').val(ui.item.cityname);
							$D('#abonnement-origincitycode').val(ui.item.citycode);
							$D('#abonnement-originstationcode').val(ui.item.stationname);
					} });
					$D('#abonnement-origincityname-display').blur(function(){ $D('#abonnement-origincityname-display').autocomplete('disable'); });
					$D('#abonnement-origincityname-display').focus(function(){ $D('#abonnement-origincityname-display').autocomplete('enable'); });
					$D('#abonnement-origincityname-display').keyup(function(){
						if(this.value!=abo_origincityname_value){
							$D('#abonnement-origincityname').val('');
							$D('#abonnement-origincitycode').val('');
							$D('#abonnement-originstationcode').val('');
						};
						abo_origincityname_value=this.value;
					});
				}
			}
			if ($D('#abonnement-destinationcityname-display').size() > 0) {
				if($D('#abonnement-destinationcityname-display').autocomplete) {
					$D('#abonnement-destinationcityname-display').autocomplete({ source:getStations, minLength:minLengthAutocomplete, delay:500, html:true, select:function(event, ui){
							$D('#abonnement-destinationcityname').val(ui.item.cityname);
							$D('#abonnement-destinationcitycode').val(ui.item.citycode);
							$D('#abonnement-destinationstationcode').val(ui.item.stationname);
					} });
					$D('#abonnement-destinationcityname-display').blur(function(){ $D('#abonnement-destinationcityname-display').autocomplete('disable'); });
					$D('#abonnement-destinationcityname-display').focus(function(){ $D('#abonnement-destinationcityname-display').autocomplete('enable'); });
					$D('#abonnement-destinationcityname-display').keyup(function(){
						if(this.value!=abo_destinationcityname_value){
							$D('#abonnement-destinationcityname').val('');
							$D('#abonnement-destinationcitycode').val('');
							$D('#abonnement-destinatinostationcode').val('');
						};
						abo_destinationcityname_value=this.value;
					});
				}
			}
			$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 initPassList() {
	if ($D('#passlist-countryBox').size() > 0 && $D('#passlist-typeBox').size() > 0) {
		var content = [];
		content.push('<table><tr>');
		var i = 0;
		var passcountries_simple = new Array();
		for (country in passcountries) {
			passcountries_simple.push(passcountries[country]);
		}
		passcountries_simple.sort();
		for (var j = 0; j < passcountries_simple.length; j++) {
			i++;
			var country_code = "";
			for (country in passcountries) {
				if (passcountries[country] == passcountries_simple[j]) {
					country_code = country
				}
			}
			content.push('<td><input type="checkbox" name="passlist-countryBox" id="passlist-countryBox-' + country_code + '" value="' + country_code + '" />');
			content.push('<label for="passlist-countryBox-' + country_code + '">' + passcountries_simple[j] + '</label></td>');
			if (i == 6) {
				content.push('</tr><tr>');
				i = 0;
			}
		}
		for ( j = i; j < 6; j++) {
			content.push('<td></td>');
		}
		content.push('</tr></table>');
		$D('#passlist-countryBox').append(content.join(''));
		$D('#passlist-countryBox input[type=checkbox]').click(function() {
			passListShow();
		});
		$D('#passlist-typeBox input[type=checkbox]').click(function() {
			passListShow();
		});
	}
	$("input[name='passfamily-familyId']").change(loadPassFamily);
	$("input[name='passfamily-familyId']").click(loadPassFamily);
}

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

$D(document).ready(initRail);
