// Needs the utilities.js file

function PassFinder() { // This guy is for logs
  this.tag = null;
  this.msg = []
  this.msg.pf = 'Passfinder'
  this.msg.pass = 'Pass'
  this.msg.search='search'
  this.msg.result='result'
  this.msg.view='v'
  this.msg.add='a'
}
  
PassFinder.prototype.logResult = function() {
  // Sanity check
  if(this.tag == null) return; 
  
  var countryChoices = reData.countryChoices;
  var nCountries = 0;
  for (var i = 0; i < countryChoices.length; i++) {
    var countryChoice = countryChoices[i];
    var countryCode = countryChoice.code;
    if(countryCode==reData.COUNTRY_DUMMY_CODE) continue;
    else {
      // Add the country to tag
      this.tag.WT.z_pf_nc = (nCountries==0)? 
        countryChoice : this.tag.WT.z_pf_nc + '+' + countryChoice;
    }
    nCountries++;
  }
  
  // Update variables
  this.tag.WT.tx_e='v';
  this.tag.WT.si_x='1';
  this.tag.WT.ti= this.msg.pf+ ' '+ this.msg.result;
  this.tag.WT.z_pf_nc = ""+nCountries;
  this.tag.dcsCollect();
}
  
PassFinder.prototype.logAddToCart = function(formName) {
  // Sanity check
  if(this.tag == null) return; 
  
  var countryChoices = reData.countries;
  var form = document.forms[formName];
  var nCountries = form['nCountries'].value;
  // Update variables
  this.tag.WT.z_pf_nc = ""+nCountries;
  for (var i=0; i<nCountries ; i++) {
    var name = "country"+i;
    var country = countryChoices[form[name].value];
    var countryName = country.name;
    this.tag.WT.z_pf_nc = (i==0)? 
      countryName : this.tag.WT.z_pf_nc + '+' + countryName;
  }
  this.tag.WT.ti= this.msg.pf+ ' '+ this.msg.result;
  this.tag.WT.tx_e= this.msg.add;
  this.tag.WT.si_x='2';
  
  var nSelection = form['nSelections'].value;
  for (var sel=0; sel<nSelection ; sel++) {
    var nXselection = form['nXSelections'+sel].value;
    for (var x=0; x<nXselection; x++) {
      var suffix = sel+"_"+x;
      var product = form['product'+suffix].value;
      var nUnits = form['nUnits'+suffix].value;
      var price  = form['totalPrice'+suffix].value;
      var first = sel==0 && x==0;
      this.tag.WT.pn_sku = first? product: this.tag.WT.pn_sku+ ';'+ product;
      this.tag.WT.z_pf_pc = first? product: this.tag.WT.z_pf_pc+ '+'+ product;
      this.tag.WT.z_pn_cat = first? 
        this.msg.pass : this.tag.WT.z_pn_cat+ ';'+ this.msg.pass;
      this.tag.WT.tx_u = first? nUnits : this.tag.WT.tx_u+ ';'+ nUnits;
    }
  }
  this.tag.dcsCollect();
}
  
function Country(code, name) {
  this.code = code; 
  this.name = name;
}

function CountryChoice(code, travelPeriod, validityPeriod) {
  this.code = code; 
  this.travelPeriod = travelPeriod; 
  this.validityPeriod = validityPeriod;
}

function defaultCountryChoice() {
   return new CountryChoice('', 'P2D', 'P2D')
}
  
function ReData() {
  this.INVALID_INDEX = -1;
  this.MAX_N_COUNTRIES = 6;
  this.COUNTRY_DUMMY_CODE = '';
  this.MAX_N_PAX = 9;
  this.AGE_CUTOFFS = [ 6, 12, 15, 16, 26, 60 ];  //inclusive lower-bounds.
  this.SEARCH_URL = '/biz/$saleCountry/pass_selector/passSelector';
  this.BUY_NOW_URL = '/biz/$saleCountry/shopping/add_pass_selector_product.htm';
  this.xmlHttp1 = makeXmlHttp();
  this.xmlHttp2 = makeXmlHttp();
  this.countryCodes = []; // This is an array of countryCode sorted on the name
  this.paxAges = [];
  this.countryChoices = [ defaultCountryChoice() ];
  this.countries = {
    'AT': new Country('AT', 'Austria'),
    'BE': new Country('BE', 'Belgium'),
    'BG': new Country('BG', 'Bulgaria'),
    'CH': new Country('CH', 'Switzerland'),
    'CZ': new Country('CZ', 'Czech'),
    'DE': new Country('DE', 'Germany'),
    'DK': new Country('DK', 'Denmark'),
    'ES': new Country('ES', 'Spain'),
    'FI': new Country('FI', 'Finland'),
    'FR': new Country('FR', 'France'),
    'ENG': new Country('ENG', 'England'),
    'GR': new Country('GR', 'Greece'),
    'HR': new Country('HR', 'Croatia'),
    'HU': new Country('HU', 'Hungary'),
    'IE': new Country('IE', 'Ireland'),
    'IT': new Country('IT', 'Italy'),
    'LU': new Country('LU', 'Luxembourg'),
    'ME': new Country('ME', 'Montenegro'),
    'MZ': new Country('MZ', 'Macedonia'),
    'NL': new Country('NL', 'Netherlands'),
    'NO': new Country('NO', 'Norway'),
    'PL': new Country('PL', 'Poland'),
    'PT': new Country('PT', 'Portugal'),
    'RO': new Country('RO', 'Romania'),
    'SCO': new Country('SCO', 'Scotland'),
    'SE': new Country('SE', 'Sweden'),
    'RS': new Country('RS', 'Serbia'),
    'SK': new Country('SK', 'Slovakia'),
    'SI': new Country('SI', 'Slovenia'),
    'TR': new Country('TR', 'Turkey'),
    'WAL': new Country('WAL', 'Wales')
  };
}

var reFlashMap = null;
var reData = null;
  
function periodDays(period) {
  //alert("Inside periodDays with period="+period);
  if (!period.match(/^P\d+[DM]$/)) {
    return -1;
  }
  var magnitude = period.replace(/\D/g, '');
  var unit = period.replace(/P\d+/, '');
  var ret = (unit == 'M') ? magnitude * 30 : magnitude;
  return ret*1;
}
  
function periodDescription(period) {
  //alert("In periodDescrioption with period="+period)
  var result = '';
  if (period.match(/^P\d+[DM]$/)) {
    var num = period.replace(/\D/g, '');
    var unit = period.replace(/P\d+/, '');
    var unitDesc = ( unit=='M' )? ' month' : ' day';
    if( num > 1 ) unitDesc += 's';
    result = num + unitDesc;
  }
  return result;
}  

/* Generate <options> from lo .. hi inclusive.  The minimum enabled
 * value is minEnabled and the selected option has value selectedValue.
 */
function periodOptions(minEnabled, selectedValue) {
  var options = '';
  var disableStr = ' disabled="disabled" style="color:#999;" ';
  for (var i = 1; i <= 20; i++) {
    var value = 'P' + i + 'D';
    var selected = (value == selectedValue) ? ' selected="selected"' : '';
    var disabled = '';
    if (minEnabled) {
      if (minEnabled == value) {
        minEnabled = '';
      }
      else {
        disabled = disableStr;
      }
    }
    options += '<option value="' + value + '"' + selected + disabled + '>' + 
               i + ' day' + ((i == 1) ? '' : 's') + '</option>';
  }
  for (var i = 1; i <= 3; i++) {
    var value = 'P' + i + 'M';
    var selected = (value == selectedValue) ? ' selected="selected"' : '';
    var disabled = '';
    if (minEnabled) {
      if (minEnabled == value) {
        minEnabled = '';
      }
      else {
        disabled = disableStr;
      }
    }
    options += '<option value="' + value + '"' + selected + disabled + '>' + 
               i + ' month' + ((i == 1) ? '' : 's') + '</option>';
  }
  return options;
}
 
function getPaxAge(age) {
  var newAge = age;
  var ageCutoffs = reData.AGE_CUTOFFS;
  var nChoices = ageCutoffs.length;
  for (var i = 0; i < nChoices; i++) {
    var lo = ageCutoffs[i];
    var hi = (i == nChoices - 1)? 9999 : ageCutoffs[i + 1];
    if( age>=lo && age<hi) {
      newAge = lo;
      break;
    }
  }
  return newAge;
}

function countryOptions(selectedCountryCode) {
  var countryChoices = reData.countryChoices;
  var countryCodes = reData.countryCodes;
  var disabledStr = ' disabled="disabled" style="color:#999;" ';
  var dummySelected = (selectedCountryCode == reData.COUNTRY_DUMMY_CODE)? 
    ' selected="selected" ' : '';
  var dummyOption = '<option value="'+ reData.COUNTRY_DUMMY_CODE+'"' +
    dummySelected + '>Select</option>';
  var options = dummyOption;
  for (var i = 0; i < countryCodes.length; i++) {
    var code = countryCodes[i];
    var name = getCountryName(code);
    var selected = (code == selectedCountryCode) ? ' selected ' : '';
    var disabled = ''; 
    for( var j=0; j < countryChoices.length; j++ ) {
      var usedCode = countryChoices[j].code;
      if( usedCode==code && usedCode!= selectedCountryCode) 
        disabled = disabledStr;
    }
    options += '<option value="' + code + '"' + selected + disabled +'>' +
      name + '</option>';
  }
  return options;
}

function addCountry(name) {
  var countryCode = getCountryCode(name);
  if( countryCode != null) {
    addCountryAct("", countryCode); 
  }
}
  
function getCountryCode(countryName) {
  var code = null;
  for( var countryCode in reData.countries) {
    if( countryName == getCountryName(countryCode)) {
      code = countryCode;
      break;
    }
  }
  //alert(countryName + " has country code="+code);
  return code;
}

function getCountryName(countryCode) {
  //alert("Inside getCountryName with code="+countryCode);
  var result = reData.COUNTRY_DUMMY_CODE;
  if( countryCode!=null && countryCode!=result) {
    result = reData.countries[countryCode].name;
  }
  return result;
}  
  
function removeCountry(countryName) {
  // find and remove the countryChoice with the given country name
  // alert("Inside removeCountry with countryName="+countryName);
  var index = reData.INVALID_INDEX;
  var countryCode = getCountryCode( countryName );
  var countryChoices = reData.countryChoices;
  for (var i = 0; i < countryChoices.length; i++) {
    if (countryChoices[i].code == countryCode) {
      index = i;
      break;
    }
  }
  if( index != reData.INVALID_INDEX ) {
    deleteCountryAct(index, true);
  }
}
  
function addCountryAct() {
  var countryCode = (addCountryAct.arguments.length > 1) ? 
    addCountryAct.arguments[1] : reData.COUNTRY_DUMMY_CODE;
  removeEmptyCountryChoices();
  // Only add the country when there is less countries then max allowed
  if( reData.countryChoices.length < reData.MAX_N_COUNTRIES) {
    // Use the first entry when it is not set
    if( reData.countryChoices.length==1 && reData.countryChoices[0].code=='') {
      reData.countryChoices[0].code = countryCode;
    }
    // Otherwise create a new entry
    else {
      var countryChoice = defaultCountryChoice();
      countryChoice.code = countryCode;
      reData.countryChoices[reData.countryChoices.length] = countryChoice;
    }
    displayCountryChoices();
    //processSelection(); 
  }
}  

function removeEmptyCountryChoices() {
  for( var i=0; i < reData.countryChoices.length; i++) { 
    if( reData.countryChoices[i].code == '') {
      deleteCountry(i);
    }
  }
}
  
function deleteCountry(index) {
  // alert("Inside deleteCountry with index="+index);
  var deletedCountryChoice=null;
  if( reData.countryChoices.length == 1) {
    deletedCountryChoice = reData.countryChoices.pop();
    reData.countryChoices.push( defaultCountryChoice() );
  }
  else {
    var wastArray =reData.countryChoices.splice(index, 1);
     deletedCountryChoice = wastArray[0];
  }
  return deletedCountryChoice;
}

function deleteCountryAct(index) {
  // fromMap indicates if the action request is comming from the map
  var fromMap = ( deleteCountryAct.arguments.length > 1) ? 
    deleteCountryAct.arguments[1] : false;
  //alert("Inside deleteCountryAct with index="+index+", and fromMap="+fromMap);
  var countryCode = deleteCountry(index).code;
  // alert("Deleted countryCode="+countryCode)
  if(!fromMap && reFlashMap!=null) {
    reFlashMap.changeCountryStatus( getCountryName(countryCode), false);
  }
  displayCountryChoices();
  //processSelection(); 
}

function isOkCountryCode(countryCode, rowIndex) {
  var isOk = false;
  if( reData.COUNTRY_DUMMY_CODE != countryCode ) {
    var countryChoices = reData.countryChoices;
    for (var i = 0; i < countryChoices.length; i++) {
      if (i != rowIndex && countryChoices[i].code == countryCode) {
        alert('You have selected the same country twice.' +  
              'This error would have not been possible if you were using \n' +
              'a standards-compliant browser like the Firefox.');
        isOk= false;
        break;
      }
    }
    isOk = true;
  }
  return isOk;
}

function countryChangeAct(select, rowIndex) {
  // Checks if the new country code is OK
  var countryChoice = reData.countryChoices[rowIndex];
  var oldCountryCode = countryChoice.code;
  var countryCode = getValue(select);
  // alert("Inside countryChangeAct with countryCode="+countryCode);
  if( isOkCountryCode(countryCode, rowIndex) ) {
    if(reFlashMap!=null) {
      // Remove the old country from the map and add a new one
      reFlashMap.changeCountryStatus( getCountryName(oldCountryCode), false);
      reFlashMap.changeCountryStatus( getCountryName(countryCode), false);
    }
    // Update for the new country value
    countryChoice.code = countryCode;
    displayCountryChoices();
    //processSelection();
  }
  else {
    // Put the old value back to the select
    setValue(select, oldCountryCode);
  }
  return false;
}

function travelPeriodChangeAct(select, rowIndex) {
  //alert("Inside travelPeriodChangeAct with rowInded="+rowIndex );
  var travelPeriod = getValue(select);
  var countryChoice = reData.countryChoices[rowIndex];
  var validityPeriod = countryChoice.validityPeriod;
  var validityPeriodDefault = 
    ( periodDays(travelPeriod) > periodDays(validityPeriod) )?
      travelPeriod : validityPeriod;
  countryChoice.validityPeriod = validityPeriodDefault;
  countryChoice.travelPeriod = travelPeriod;
  displayCountryChoices();
  //processSelection();
  return false;
}

function validityPeriodChangeAct(select, rowIndex) {
  var validityPeriod = getValue(select);
  var countryChoice = reData.countryChoices[rowIndex];
  var travelPeriod = countryChoice.travelPeriod;
  if (periodDays(validityPeriod) < periodDays(travelPeriod)) {
    countryChoice.validityPeriod = travelPeriod;
    alert('The validity period cannot be less than the travel period\n' +
          'This error would have not been possible if you were using \n' +
           'a standards-compliant browser like the Firefox.');
  }
  else {
    countryChoice.validityPeriod = validityPeriod;
  }
  displayCountryChoices();
  //processSelection();
  return false;
}

function countryCodeCompare(countryCode1, countryCode2) {
  var countryName1 = getCountryName(countryCode1);
  var countryName2 = getCountryName(countryCode2);
  return (countryName1 < countryName2) ? -1 
       : (countryName1 > countryName2) ? +1 : 0;  
}

function makeSelectionBox(id, klass, options, onChange) {
  return '' +
    '<select id="' + id + '" name="' + id + '" class="' + klass +
      '" onChange="' + onChange + '">' + options + '</select>';
}

function makeButton(id, text, act, isDisabled) {
  var disabled = (isDisabled) ? ' disabled="disabled"' : '';
  return '' +
    '<button id="' + id + '" onClick="' + act + '"' + disabled + '>' + 
    text + 
    '</button>';
}

function displayCountryChoices() {
  var countryChoices = reData.countryChoices;
  var contents = new StringBuffer();
  
  var travelLink = '<a href="." onclick="$(\'#pf-travel-block\').find(\'a:first\').click(); return false;">How many days</a>';
  var countryLink = '<a href="." onclick="$(\'#pf-country-block\').find(\'a:first\').click(); return false;">How long</a>';
  
  for (var i = 0; i < countryChoices.length; i++) {
    var countryChoice = countryChoices[i];
    var countryCode = countryChoice.code;
    var countryName = getCountryName(countryCode);
    var travelPeriod = countryChoice.travelPeriod;
    var validityPeriod = countryChoice.validityPeriod;
    
    var countryId = 'country' + i;
    var countryOpts = countryOptions(countryCode);
    var countryChange = 'countryChangeAct(this, ' + i + ')';
    var countrySelect = makeSelectionBox(countryId, 'country-select-box',
      countryOpts, countryChange);
    
    var travelPeriodId = 'travelPeriod' + i;
    var travelPeriodOpts = periodOptions('', travelPeriod);
    var travelPeriodChange = 'travelPeriodChangeAct(this, ' + i + ')';
    var travelPeriodSelect = makeSelectionBox(travelPeriodId, 'time-field2',
      travelPeriodOpts, travelPeriodChange);
    
    var validityPeriodId = 'validityPeriod' + i;
    var validityPeriodOpts = periodOptions(travelPeriod, validityPeriod);
    var validityPeriodChange = 'validityPeriodChangeAct(this, ' + i + ')';
    var validityPeriodSelect = makeSelectionBox(validityPeriodId, 'time-field2',
      validityPeriodOpts, validityPeriodChange);

    var deleteAct = 'deleteCountryAct(' + i + ')';    
  
    contents.append('<div class="country-entry">\n');
    contents.append('<label>Country '+ (i+1) + ':</label>\n');
    contents.append(countrySelect + '\n');
    contents.append( '</div>\n');
    
    if( countryCode!=reData.COUNTRY_DUMMY_CODE ) {
      contents.append( '<div class="country-entry-right">\n');
      contents.append( '<a href="javascript:'+deleteAct+'">Delete</a>\n');
      contents.append( '<a href="javascript:'+deleteAct+'"><img src="/redesign/images/btn-delete.jpg" alt="Delete" /></a>\n');
      contents.append( '</div>\n');
      contents.append( '<div class="clear"></div>\n');
      contents.append( '<div id="countryTime'+(i+1)+'" class="country-entry-text">\n');
      contents.append( travelLink+' do you plan to be traveling by train while in '+ countryName +'?</div>\n');
      contents.append( '<div class="country-entry-right-input">\n');
      contents.append( travelPeriodSelect+ '\n');
      contents.append( '</div>\n');
      contents.append( '<div class="clear"></div>\n');
      contents.append( '<div class="country-entry-text">'+countryLink+' will you stay in '+ countryName +'?</div>\n');
      contents.append( '<div class="country-entry-right-input">\n');
      contents.append( validityPeriodSelect+ '\n');
      contents.append( '</div>\n');
    }
    contents.append( '<div class="clear"></div>\n');
    contents.append( '<div class="country-entry-line-dotts"/></div>\n');
  }
  getElement('countryChoices').innerHTML = contents.toString();
  adjustAddCountryButton();
}

function adjustAddCountryButton() {
  setDisplay(getElement('addCountry'),
    reData.MAX_N_COUNTRIES!=reData.countryChoices.length );
}  

function displayPaxAges() {
  var paxAges = reData.paxAges;
  var nChild = 0; var nYouth = 0; var nAdult = 0; var nSenior = 0;
  var youthAges = new Array();
  for( var i=0; i< paxAges.length ; i++) {
    var age = paxAges[i];
    if(age==1) nChild++;
    else if (age==26) nAdult++;
    else if (age==60) nSenior++
    else {
      nYouth++; youthAges.push(age);
    }
  }
  setWidgetValue('nChildren', nChild);
  setWidgetValue('nYouth', nYouth);
  populateYouthFields(getElement('nYouth'));
  setWidgetValue('nAdults', nAdult);  
  setWidgetValue('nSeniors', nSenior);
  // Assign the youth ages
  for( var i=0; i<youthAges.length; i++) 
    setWidgetValue('youthAge'+i, youthAges[i]);
}

function setDynamicData() {
  var xmlHttp = reData.xmlHttp2;
  if (xmlHttp.readyState == 4) {
    var text = xmlHttp.responseText;
    updateDynamicData(text);
    displayCountryChoices();
    //displayPaxAges();
  }
}

function updateDynamicData(text) {
  var results = eval('(' + text + ')');
  var countries = results.countries;
  var nCountries = countries.length;
  reData.countries = new Object();
  for (var i = 0; i < nCountries; i++) {
    reData.countries[countries[i].value] = 
      new Country(countries[i].value,  countries[i].text);
  }
  // Make the below sort to be run only once
  reData.countryCodes = [];
  for (var countryCode in reData.countries) {
    reData.countryCodes[reData.countryCodes.length] = countryCode;
  }
  reData.countryCodes.sort(countryCodeCompare);
  
  var compounds = results.compoundCountries;
  var nCompounds = compounds.length;
  reData.compoundCountries = new Object();
  for (var i = 0; i < nCompounds; i++) {
    reData.compoundCountries[compounds[i].value] = 
      new Country(compounds[i].value,  compounds[i].text);
  }
  var ageCutoffs = results.ageCutoffs;
  var nCutoffs = ageCutoffs.length;
  reData.AGE_CUTOFFS = new Array();
  for (var i = 0; i < nCutoffs; i++) {
    reData.AGE_CUTOFFS[i] = ageCutoffs[i].value;
  }
}

function isSubmit() {
  var fn = getElement('fn');
  return fn && fn.value == 'submit0';
}

function initPassSelector() {
  reData = new ReData();
  reFlashMap = (navigator.appName.indexOf("Microsoft")!=-1)? 
    getElement('map') : window.document['map'];
  //alert("reFlashMap="+reFlashMap);
  doServerRequest(reData.xmlHttp2, "op=script", setDynamicData);   
  var queryString = getQueryString();
  if (queryString && queryString.indexOf('fn=edit') >= 0) {
    doEdit(queryString);
  }
  
  $('#processButton').click(function(){
    if( processSelection() )
      $.scrollTo( $('#results'), 1000 );
    else
      $.scrollTo( $('#content'), 1000 );  
  });
}

function cleanUserEntry() {
  var nCountry = reData.countryChoices.length;
  if( nCountry > 0) reData.countryChoices.slice(0, nCountry);
}

addOnloadEvent(initPassSelector);
addOnunloadEvent(cleanUserEntry);

/*  XmlHttp stuff */

/* Create a new XMLHttpRequest object to talk to the Web server */
function makeXmlHttp() {
  var xmlHttp = false;
  /*@cc_on @*/
  /*@if (@_jscript_version >= 5)
  try {
    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
  } 
  catch (e) {
    try {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    catch (e2) {
      xmlHttp = false;
    }
  }
  @end @*/
  if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
    xmlHttp = new XMLHttpRequest();
  }
  return xmlHttp;
}

function appendParams(params, name, value) {
  var param = name + '=' + escape(value);
  return (params) ? params + '&' + param : param;
}

function processSelection() {
  var params = '';
  var countryChoices = reData.countryChoices;
  var nCountries = 0;
  for (var i = 0; i < countryChoices.length; i++) {
    var countryChoice = countryChoices[i];
    var countryCode = countryChoice.code;
    if(countryCode==reData.COUNTRY_DUMMY_CODE) continue;
    var travelPeriod = countryChoice.travelPeriod;
    var validityPeriod = countryChoice.validityPeriod;
    var n = i;
    params = appendParams(params, 'country' + n, countryCode);
    params = appendParams(params, 'travelPeriod' + n, travelPeriod);
    params = appendParams(params, 'validityPeriod' + n, validityPeriod);
    nCountries++;
  }
  if( nCountries==0 ) {
    alert("Please select at least one country.");
    return false;
  }
  params = appendParams(params, 'nCountries', nCountries);
  
  // Get Pax info
  if( validatePaxes() ) {
    var nChild  = getWidgetValue('nChildren');
    var nYouth  = getWidgetValue('nYouth');
    var nAdult  = getWidgetValue('nAdults');  
    var nSenior = getWidgetValue('nSeniors');
    var nPax = 0;

    for(var i=0; i< nChild; i++) { // loop children
      params = appendParams(params, 'paxAge' + nPax, 1);
      nPax++;
    }
    for (var i = 0; i < nYouth; i++) { //loop youth
      params = appendParams(params, 'paxAge' + nPax, getPaxAge(getWidgetValue('youthAge'+i)));
      nPax++;
    }
    for(var i=0; i< nAdult; i++) { // loop adults
      params = appendParams(params, 'paxAge' + nPax, 26);
      nPax++;
    }
    for(var i=0; i< nSenior; i++) { // loop seniors
      params = appendParams(params, 'paxAge' + nPax, 60);
      nPax++;
    }
    params = appendParams(params, 'nPax', nPax);
    // var doDebug = (getElement("doDebug").checked) ? 1 : 0;
    params = appendParams(params, 'doDebug', 0);
    doServerRequest(reData.xmlHttp1, params, updatePage);
  }
  return true;
}

function doServerRequest(xmlHttp, params, callbackFn) {
  var cobrand = document.forms["passSearchForm"].cobrand.value;
  var saleCountry = document.forms["passSearchForm"].saleCountry.value;
  //alert("Inside doServerRequest with cobrand="+cobrand+ ", and saleCountry="+saleCountry);
  params = appendParams(params, 'cobrand', cobrand);
  params = appendParams(params, 'saleCountry', saleCountry);
  var baseUrl = reData.SEARCH_URL.replace(/\$saleCountry/, saleCountry);
  var url = baseUrl + '?' + params;
  xmlHttp.open('GET', url, true);
  xmlHttp.onreadystatechange = callbackFn;
  xmlHttp.send(null);
}

function updatePage() {
  var xmlHttp = reData.xmlHttp1;
  if (xmlHttp.readyState == 4) {
    var text = xmlHttp.responseText;
    formatResults(text);
  }
}

function makeParams(results) {
  var params = new Object();
  params.resultsId = results.resultsId;
  params.nextIndex = results.nextIndex;
  params.lastIndex = results.lastIndex;
  return params;   
}

function formatResults(text) {
  // alert("inside formatResults with text="+text);
  var results = eval('(' + text + ')');
  if (results.errors != null) {
    formatErrors(results); 
    return; 
  }
  var request = results.passSearchRequest;
  var saleCountry = document.forms["passSearchForm"].saleCountry.value;
  var html = new StringBuffer();
  html.append('\n<form name="addToCartForm">\n');
  
  for (var klass = 1; klass <= 2; klass++) {
    var klassSolutions = results['klass' + klass + 'Solutions'];
    var sols = klassSolutions.solutions;
    var nSols = sols.length;
    
    var klassDesc= (klass==1)? '1st class' : '2nd class';
    html.append('<h2>Solutions in '+ klassDesc +'</h2>\n');
    
    // header table
    html.append('<table cellpadding="0" cellspacing="0" class="table-choice-options table-width-635">\n');
    html.append('<tr>\n');
    html.append('<td class="itinerary-info td-61" scope="row"><span class="txt-bold txt-113em">Quantity</span></td>\n');
    html.append('<td class="itinerary-info td-210"><span class="txt-bold txt-113em">Pass Name</span></td>\n');
    html.append('<td class="itinerary-info td-210"><span class="txt-bold txt-113em">Validity</span></td>\n');
    html.append('<td class="class-head"><a href="#" class="thickbox left-padd-5">'+klassDesc+'</a></td>\n');
    html.append('</tr>\n');
    html.append('</table>\n');
    
    if (nSols == 0) {
      html.append( klassSolutions.noSolutionsMessage);
    }
    else {
      for (var i = 0; i < nSols; i++) {
        var formName = 'klass'+klass+'sol'+i;
        var solution = sols[i];
        var selections = solution['selections'];
        var nSelection = selections.length;
        html.append('<table cellpadding="0" cellspacing="0" class="table-choice-options table-width-635">\n');
        
        for(var n=0; n < nSelection; n++) {
          var sel = selections[n];
          var url = ''; //sel.url;
          var passTitle = (url)? 
            '<a href=\'javascript:showPopup("/' + saleCountry + url +
              '", 420, 420)\'>' + sel.titleText + ' </a>' :
            sel.titleText;
          
          var paxDesc = '';
          var qty = '';
          var xSel = sel.xSelections;
          for( var k=0; k< xSel.length; k++) {
            var x = xSel[k];
            paxDesc += '<br/>';
            paxDesc += x.paxTypesText + ' @ ' + x.unitPriceText;
            qty += '<br/>';
            qty += x.nUnits+' pass'+ ((x.nUnits>1)? 'es': '');
          }
          
          var extraTd = (n==0)? ' top-border' :
            (nSelection==1)? ' top-border' :
            ((n+1)==nSelection)? ' btm-border' : ' no-border';
          
          html.append('<tr>\n');
          
          html.append('<td scope="row" class="td-quantity'+extraTd+'">'+qty+'</td>\n');
          html.append('<td class="td-pass-info'+extraTd+'">\n');
          html.append('<span class="time">'+passTitle+'</span>'+paxDesc+'\n');
          html.append('</td>\n');
          var durrationText = sel.durationText;
          var nExtraDays = sel.nExtraDays;
          if( !isNaN(nExtraDays) && nExtraDays>0) {
            var durrations = sel.durationCode.split('/');
            if( durrations.length==2) {
              var days = periodDescription('P'+(durrations[0][1]*1+nExtraDays)+'D');
              var span = periodDescription(durrations[1]);
              durrationText = (days==span)? days:  days + ' in ' + span;
            }
          }
          html.append('<td class="td-pass-info'+extraTd+'">Unlimited train travel for '+durrationText+' period.</td>\n');
          if( n==0 ) {  
          html.append('<td class="td-choice-options" rowspan="'+(nSelection+4)+'">\n');          
          html.append('<input class="no-border" type="radio" name="group" id="group" value="'+formName+'" />\n');
          html.append('<span class="price">'+solution.totalPriceText.strip()+'</span>\n');
          html.append('</td>\n');
          }
          html.append('<tr>\n');
        }
        html.append('</table>\n');
        html.append('<div class="gap"></div>\n');
      }
    }
    html.append('<div class="clear-space-lrg"></div>\n');
    
  }
  html.append('</form>\n');
  html.append('<div id="pass-finder-submit" class="pass-finder-btn-holder">\n');
  html.append('<input type="submit" onClick="addToCart()" class="btn-small center" value="Add To Cart" /> \n');
  html.append('</div>\n');
  html.append('<div id="pass-finder-process" class="pass-finder-btn-holder" style="display:none;">\n');
  html.append('<img src="/redesign/images/fs_waiting.gif" /> \n');
  html.append('</div>\n');

  
  // Place different forms outside the main form
  for (var klass = 1; klass <= 2; klass++) {
    var klassSolutions = results['klass' + klass + 'Solutions'];
    var sols = klassSolutions.solutions;
    var nSols = sols.length;
    
    var klassDesc= (klass==1)? '1st class' : '2nd class';
    if (nSols > 0) {
      for (var i = 0; i < nSols; i++) {
        var formName = 'klass'+klass+'sol'+i;
        var sol = sols[i];
        html.append( makeBuyNowForm(request, sol, formName)+'\n');
      }
    }
  }
  getElement('results').innerHTML = html.toString();
  if(typeof sIFR == "function"){
    sIFR.replaceElement(named({sSelector:"body h2", sFlashSrc:"/redesign/swf/tradegothic.swf", sColor:"#852c71", sBgColor:"#FFFFFF", sWmode:"transparent"}));
  }
  re_paf.logResult();
  //getElement('error').innerHTML = '<pre>' + results.trace + '</pre>';
}
 
function addToCart() {
  //var value = getWidgetValue('group', 'addToCartForm');
  var value = $("input[name=group]:checked").val();
  if( value==null) {
    alert("Please select a solution you like."); 
  }
  else {
    $('#pass-finder-submit').hide();
    $('#pass-finder-process').show();
    re_paf.logAddToCart(value);
    document.forms[value].submit();
  }
}

function formatErrors(results) {
  var errors = results.errors;
  var html = "<ul>";
  var nErrors = errors.length;
  for (var i = 0; i < nErrors; i++) {
    html += "<p><li>" + errors[i] + "</li></p>";
  }    
  html += "</ul>"; 
  getElement('results').innerHTML = html;
}

function makeBuyNowForm(request, sol, formName) {
  var saleCountry = document.forms["passSearchForm"].saleCountry.value;
  var buyNowUrl = reData.BUY_NOW_URL.replace(/\$saleCountry/, saleCountry);
  var form = '';  
  form += '<form name="'+formName+'" method="POST" action="' + buyNowUrl + '">';
  form += makeHidden('referer', location.href);
  if(reData.itemId) form += makeHidden('itemId', reData.itemId);
  for (var k in request) {
    form += makeHidden(k, request[k]);
  }
  var nSelections = sol.selections.length; 
  form += makeHidden('nSelections', nSelections);
  form += makeHidden('fn', 'submit');
  for (var i = 0; i < nSelections; i++) {
    var sel = sol.selections[i];
    form += makeHidden('nExtraDays' + i, sel.nExtraDays);
    form += makeHidden('nAdjacentCountries' + i, sel.nAdjacentCountries);
    form += makeHidden('adjacentCountries' + i, 
                       sel.adjacentCountries.join('|'));
    form += makeHidden('nXSelections' + i, sel.xSelections.length);
    if (sel.freeKids) form += makeHidden('freeKids' + i, sel.freeKids);
    for (var x = 0; x < sel.xSelections.length; x++) {
      var xSel = sel.xSelections[x];
      var suffix = i + '_' + x;
      form += makeHidden('productId'+ suffix, xSel.productId);
      form += makeHidden('product'+ suffix, xSel.titleText);
      form += makeHidden('totalPrice'+ suffix, xSel.totalPrice);
      form += makeHidden('nUnits'+ suffix, xSel.nUnits);
      form += makeHidden('selPaxAges'+ suffix, xSel.selPaxAges.join('|'));
    }
  }
  form += '</form>';
  return form;
}

function makeHidden(name, value) {
  return '<input type="hidden" name="' + name + '" value="' + value + '"  />';
}  

function getQueryString() {
  var loc = location.href;
  var qIndex = loc.indexOf("?");
  if (qIndex < 0) return null;
  var query = loc.substr(qIndex + 1);
  return (!query || query.length == 0) ? null : query;
}

function getQueryParams(queryString) {
  var queryParams = new Object();
  var nameValues = queryString.split("&");
  for (var i = 0; i < nameValues.length; i++) {
    var pair = nameValues[i].split("=");
    queryParams[pair[0]] = (pair.length > 1) ? pair[1] : '';
  }
  return queryParams;
}

function doEdit(queryString) {
  var query = getQueryParams(queryString);
  reData.itemId = query.itemId;
  for (var i = 0; i < query.nCountries; i++) {
    var countryCode = query['country' + i];
    var travelPeriod = query['travelPeriod' + i];
    var validityPeriod = query['validityPeriod' + i];
    //alert("Country["+i+"]={"+countryCode+","+travelPeriod+","+validityPeriod+"}")
    reData.countryChoices[i] = 
      new CountryChoice(countryCode, travelPeriod, validityPeriod);
    if(reFlashMap!=null) {
      reFlashMap.changeCountryStatus( getCountryName(countryCode), false);
    }
  } 
  displayCountryChoices();
  for (var i = 0; i < query.nPax; i++) {
    reData.paxAges[i] = query['paxAge' + i];
  }
  displayPaxAges();
  doServerRequest(reData.xmlHttp1, queryString, updatePage);
}
  
function validatePaxes() {
  var isOk = true;
  // Checks if the user Pax info is correct
  var nAdult  = getWidgetValue('nAdults');
  var nYouth  = getWidgetValue('nYouth');
  var nChild  = getWidgetValue('nChildren');
  var nSenior = getWidgetValue('nSeniors');

  var nPax = nAdult*1+nYouth*1+nChild*1+nSenior*1+0; //alert("nPax="+nPax);
  if( isNaN(nPax) ) {
    alert("One of the traveler number is invalid.\nPlease correct and continue!");
    isOk = false;
  }
  else if (nPax==0) {
    alert("Please select at least one traveler.");
    isOk = false;
  }
  else if (nPax > 9) {
    alert("Maximum number of travelers should not exceed 9.\nPlease correct and continue!");
    isOk = false;
  }
  else {
    for(var i=0; i<nYouth && isOk; i++ ) {
      var ctr = getElement('youthAge'+i);
      isOk = validateYouth(ctr,i);
      ctr.focus();
    }
  }
  return isOk;
}
  
function populateYouthFields(ctr) {
  var youthSpec = getElement('youthSpec');
  var nYouth = getValue(ctr);
  if( isNaN(nYouth) ) {
    nYouth=0;
    setValue(ctr, nYouth);
    youthSpec.innerHTML = '';
  }
  else if( nYouth == 0) {
    youthSpec.innerHTML = '';
  }
  else {
    // This section is for nYouth > 0
    var headerText = "To ensure we offer you the best prices, please tell us the age of each youth:";
    var content = new StringBuffer();
    content.append('<table><tbody>');
    content.append('<tr><td><br/>' + headerText + '</td></tr><tr><td>&nbsp;</td></tr>');
    for( var i=0; i < nYouth; i++ ) {
      content.append('<tr><td>Age of Youth #'+(i+1)+' <input type="text" id="youthAge'+i+'" class="youth-field" maxlength="2" onblur="validateYouth(this,'+i+')"/>' + '</td></tr>\n');
    }
    content.append("</tbody></table>");
    youthSpec.innerHTML = content.toString();
  }
}
  
function validateYouth(ctr, index) {  
  var nr = getValue(ctr);
  var isOk = isValidNumber(nr, 12, 25);
  if( !isOk ) {
    alert("Youth #"+ (index+1) +" age should be a number between 12 and 25 inclusive.");
  }
  return isOk;
}
  
function isValidNumber( num, min, max) {
  var isOk = false;
  if( !isNaN(num) ) {
    var number = num*1;
    isOk = number>=min && number<=max;
  }
  return isOk;
}
