
var ChildAges = {
  currentQuery: {
    ptcSelect:null,
    agesInput:null,
    ageRange:{
      min:0,
      max:99
    },
    ptc: null,
    callback: null
  },
  
  rowTemplate: new Template('<div class="paxAgeInput"><span>#{paxType} #{paxIndex} Age</span><select class="paxAge">#{options}</select></div>'),

  init: function(field, minAge, maxAge) {
    if (!$(field)) return;
    var idSplit = $(field).id.split('_');
    var ptcSelect = this._fieldName(idSplit, 'ptc');
    var ageField = this._fieldName(idSplit, 'ages');
    var specField = this._fieldName(idSplit, 'ageSpec');

    this.currentQuery = {
      ptcSelect:$(ptcSelect),
      ageField:$(ageField),
      specField: $(specField),
      ageRange:{
        min:minAge,
        max:maxAge
      },
      callback: null
    };

  },

  doPopup: function (field, minAge, maxAge, typeDesc, cb) {

    if (paxTypes.get(typeDesc)) {
      this.ptc = paxTypes.get(typeDesc);
      if (minAge == null) minAge = this.ptc.minAge;
      if (maxAge == null) maxAge = this.ptc.maxAge;
      typeDesc = this.ptc.singular;
    } else {
      this.ptc = null;
    }

    this.init(field, minAge, maxAge);
    this.currentQuery.callback= cb;
      
    var ptcCount = $F(this.currentQuery.ptcSelect);
    if (ptcCount == 0) {
      this.currentQuery.ageField.value = '';
      this.updateSpec(this.currentQuery.specField, this.currentQuery.ageField);
    } else {
      var curValues = $F(this.currentQuery.ageField).split("|");
      var content = "";
      for (var i = 0; i < ptcCount; i++) {
        content += this.rowTemplate.evaluate({
          paxType: this.ptc.singular,
          paxIndex: (i+1),
          options: this.options(minAge, maxAge, (curValues.length > i ? curValues[i] : null))
        });
      }
        
      $('ageRangeFloatyContent').update(content);
      $('ageRangeFloaty').style.width = '308px';
      $('ageRangeFloaty').style.height = 'auto';
      Event.stopObserving($('ageRangeFloaty').select('.floatyCloseButton')[0], 'click');
      Event.observe($('ageRangeFloaty').select('.floatyCloseButton')[0], 'click', ChildAges.popupCancel);

      // Only popupulate popup warning for rail paxtypes
      if (this.ptc != null && this.ptc.popup != null && (field.form != null && (field.form.id == 'railForm' || field.form.id == 'entryForm')))
        $('ageRangeFloatyWarning').update(this.ptc.popup)
      else
        $('ageRangeFloatyWarning').update('');
      
      showFloaty('ageRangeFloaty', null, {
        element: this.currentQuery.ptcSelect,
        left: (this.currentQuery.ptcSelect.hasClassName('bookTourPax') ? -270 : 30),
        top:  (this.currentQuery.ptcSelect.hasClassName('bookTourPax') ? 30 : 0)
      }, {
        onActivate: function(){
          $('ageRangeFloaty').select('select')[0].focus();
        }
      });
    }
  },
    
  options: function (ageMin, ageMax, dflt) {
    if (dflt == null) dflt = ageMin;
    var result = "";
    for (var i = ageMin; i <= ageMax; i++) {
      result += '<option value="'+i+'"'+(i==dflt?' selected="selected"':'')+'>'+i+'</option>';
    }
    return result;
  },
    
  _fieldName: function(idSplit, name) {
    var offset = idSplit.indexOf('ptc');
    if (offset == -1) offset = idSplit.indexOf("ageSpec");
    if (offset == -1) offset = idSplit.indexOf("ages");
    var copy = idSplit.clone();
    copy[offset] = name;
    return $(copy.flatten().compact().join("_"));
  },
    
  popupCommit: function () { 
    hideFloaty('ageRangeFloaty');
    var ages = $('ageRangeFloatyContent').select('select');
    var values = new Array();
    for (var age = 0; age < ages.length; age++) {
      values[age] = $F(ages[age]);
    }
    this.currentQuery.ageField.value = values.join("|");
    if (this.currentQuery.specField) this.updateSpec(this.currentQuery.specField, this.currentQuery.ageField);
    if (Object.isFunction(this.currentQuery.callback)) this.currentQuery.callback();
    this.currentQuery.ptcSelect.focus();
  },
  
  popupCancel: function () {
    hideFloaty('ageRangeFloaty');
    AniteDDB.setValue(ChildAges.currentQuery.ptcSelect, $F(ChildAges.currentQuery.ageField).split("|").nonBlanks().length);
    this.currentQuery = null;

  },
  
  updateSpec: function (specEl, agesInput) {
    if (!$(specEl)) return;
    if ($F(agesInput) == "") {
      specEl.update('&nbsp;');
    //specEl.hide();
    } else {
      var values = $F(agesInput).split("|").nonBlanks().flatten();
      var specContent = (values.length == 1 ? 'Age: ':'Ages: ') + values.join(", "); 
      specEl.update(specContent); 
    //specEl.show();
    }
  },

  setAges: function(agesInput, value) {
    if (!$(agesInput)) return;
    this.init(agesInput);
    this.currentQuery.ageField.value = value.split("|").nonBlanks().flatten().join("|");
    this.updateSpec(this.currentQuery.specField, this.currentQuery.ageField);
  },

  refresh: function(ptcInput) {
    this.init(ptcInput);
    if (this.currentQuery.specField) this.updateSpec(this.currentQuery.specField, this.currentQuery.ageField);
  }
};

Object.extend(Array.prototype, {
  nonBlanks: function(){
    return this.select(function(value) {
      return value != null && value != '';
    });
  }
});

function searchPanelGetAges() {
  var idSplit = this.id.split("_");
  var ptcCode = idSplit[idSplit.length-1];
  var ptc = paxTypes.get(ptcCode);
  if (!ptc) return;
  if (ptc.ageRestricted) {
    currentAgeRangeQuery = {
      type: ptc,
      id: idSplit.slice(0, idSplit.length-2)
    };
    var fieldIdParts = [currentAgeRangeQuery.id, 'ages', currentAgeRangeQuery.type.code];
    var ptcSelect = $([currentAgeRangeQuery.id, 'ptc', currentAgeRangeQuery.type.code].flatten().compact().join("_"));
    
    var agesField = $(fieldIdParts.flatten().compact().join("_"));
    if ($(ptcSelect) == null){
      alert([currentAgeRangeQuery.id, 'ptc', currentAgeRangeQuery.type.code].flatten().compact().join("_")); return;
    }
    if ($F(ptcSelect) == 0) { 
      var specIdParts = [currentAgeRangeQuery.id, 'ageSpec', currentAgeRangeQuery.type.code];
      var spec = $(specIdParts.flatten().compact().join("_"));
      agesField.value = '';
      ChildAges.updateSpec(spec, agesField);
      if (typeof ciPaxChange == 'function')
        ciPaxChange.call(this);
    }  else {  	
      ChildAges.doPopup(ptcSelect, ptc.minAge, ptc.maxAge, ptc.code, (typeof ciPaxChange == 'function'?ciPaxChange.bindAsEventListener(this):null));
    }  
  }
}

