if(typeof getSelectedValue == "undefined")
{
  getSelectedValue=function(selectBox)
  {
    if(selectBox.selectedIndex >= 0)
      return selectBox.options[selectBox.selectedIndex].value;
  }
}
if(typeof selectValue == "undefined")
{
  selectValue=function(selectBox,valueToSelect)
  {
    for(i = 0; i < selectBox.options.length; i++)
    {
      if(selectBox.options[i].value == valueToSelect)
      {
          selectBox.selectedIndex = i;
          break;
      }
    }
  }
}
if(typeof getOneChildBySelector == "undefined")
{
  getOneChildBySelector=function(container,selector)
  {
    var l = container.getElementsBySelector(selector);
    if(l && l.size() >= 1)
        return l[0];
    else
        return null;
  }
}

var AVBPlusGuest = Class.create();
AVBPlusGuest.prototype =
{
    initialize: function(ctrl,group,id)
    {
      this.id = id;
      this.group = group;
      this.ctrl = ctrl;
      this.view = false;
      this.ageGroup = false;
    },
    show: function(tableElement)
    {
      tr = document.createElement('tr');
      tr = Element.extend(tr);
      groupId = this.group.getId();

      // Förnamn
      td = document.createElement('td');
      td = Element.extend(td);

      this.inputFirstName = document.createElement('input');
      this.inputFirstName = Element.extend(this.inputFirstName);
      this.inputFirstName.name = 'avbplus[' + groupId +'][guests][' + this.id + '][firstName]';
      td.appendChild(this.inputFirstName);

      // Flagga
      var hidden = document.createElement('input');
      hidden = Element.extend(hidden);
      hidden.name = 'avbplus[' + groupId +'][guests][' + this.id + '][useIt]';
      hidden.type = "hidden";
      hidden.value = "yes";

      td.appendChild(hidden);

      tr.appendChild(td);

      // Efternamn
      td = document.createElement('td');
      td = Element.extend(td);

      this.inputLastName = document.createElement('input');
      this.inputLastName = Element.extend(this.inputLastName);
      this.inputLastName.name = 'avbplus[' + groupId +'][guests][' + this.id + '][lastName]';

      td.appendChild(this.inputLastName);

      tr.appendChild(td);

      // Födelsedatum
      this.selectYear = document.createElement('select');
      this.selectYear = Element.extend(this.selectYear);
      this.selectYear.name = 'avbplus[' + groupId +'][guests][' + this.id + '][yyyy]';
      this.selectYear.onchange = this.onBirthDateChanged.bind(this);

      this.selectMonth = document.createElement('select');
      this.selectMonth = Element.extend(this.selectMonth);
      this.selectMonth.name = 'avbplus[' + groupId +'][guests][' + this.id + '][mm]';
      this.selectMonth.onchange = this.onBirthDateChanged.bind(this);

      this.selectDay = document.createElement('select');
      this.selectDay = Element.extend(this.selectDay);
      this.selectDay.name = 'avbplus[' + groupId +'][guests][' + this.id + '][dd]';
      this.selectDay.onchange = this.onBirthDateChanged.bind(this);

      td = document.createElement('td');
      td = Element.extend(td);

      if(this.ctrl.getLang() == 'sv')
      {
          td.appendChild(this.selectYear);
          td.appendChild(this.selectMonth);
          td.appendChild(this.selectDay);
      }
      else
      {
          td.appendChild(this.selectDay);
          td.appendChild(this.selectMonth);
          td.appendChild(this.selectYear);
      }

      tr.appendChild(td);

      // Pris och åldersgrupp
      this.txtInfo = document.createElement('td');
      this.txtInfo = Element.extend(this.txtInfo);
      tr.appendChild(this.txtInfo);

      // Tabort ..
      td = document.createElement('td');
      td = Element.extend(td);
      a = document.createElement('a');
      a = Element.extend(a);
      a.addClassName("remove");
      a.update('&nbsp;');
      a.onclick = this.onRemove.bind(this);
      td.appendChild(a);

      tr.appendChild(td);
      this.view = tr;

      tableElement.appendChild(tr);
      this._initBirthDate();
    },
    destroy: function()
    {
      if(this.view)
      {
          this.view.remove();
      }
    },
    onRemove: function()
    {
      this.group.onRemoveParticipant(this.id);
    },
    _initBirthDate: function()
    {
        this.selectYear.options.length = 0;
        this.selectYear.options[this.selectYear.options.length] = new Option(this.ctrl.getText('Year'),0);

        for(i = this.ctrl.getMaxYear(); i >= this.ctrl.getMinYear(); i--)
             this.selectYear.options[this.selectYear.options.length] = new Option(i,i);

//        for(i = this.ageCat.maxYear; i >= this.ageCat.minYear; i--)
//             this.selectYear.options[this.selectYear.options.length] = new Option(i,i);

        var months = this.ctrl.getBirthDateMonths();

        var me = this;
        me.selectMonth.options.length = 0;
        me.selectMonth.options[me.selectMonth.options.length] = new Option(me.ctrl.getText('Month'),0);
        months.each( function(pair) { me.selectMonth.options[me.selectMonth.options.length] = new Option(pair.value,pair.key); } );

        this.selectDay.options.length = 0;
        this.selectDay.options[this.selectDay.options.length] = new Option(this.ctrl.getText('Day'),0);
        for(i = 1; i <=31; i++)
        {
            var v = String(i);
            if(v.length == 1)
                v = '0' + v;

            this.selectDay.options[this.selectDay.options.length] = new Option(v,v);
        }
    },
    validate: function()
    {
      var fn = this.getFirstName();
      if(fn == null || fn.length == 0)
      {
          this.inputFirstName.focus();
          alert(this.ctrl.getText("Specify firstname"));
          return false;
      }
      var ln = this.getLastName();
      if(ln == null || ln.length == 0)
      {
          this.inputLastName.focus();
          alert(this.ctrl.getText("Specify lastname"));
          return false;
      }

      var bd = this.getBirthdate();
      if(!isDate(bd))
      {
          this.selectYear.focus();
          alert(this.ctrl.getText("Invalid birthdate"));
          return false;
      }
      return true;
    },
    getFirstName: function()
    {
      return this.inputFirstName.value;
    },
    setFirstName: function(fn)
    {
        this.inputFirstName.value = fn;
    },
    getLastName: function()
    {
      return this.inputLastName.value;
    },
    setLastName: function(ln)
    {
        this.inputLastName.value = ln;
    },
    getBirthdate: function()
    {
      return getSelectedValue(this.selectYear) + '-' + getSelectedValue(this.selectMonth) + '-' + getSelectedValue(this.selectDay);
    },
    setBirthdate: function(birthdate)
    {
      var yyyy = birthdate.substr(0,4);
      var mm = birthdate.substr(5,2);
      var dd = birthdate.substr(8,2);

      selectValue(this.selectYear,yyyy);
      selectValue(this.selectMonth,mm);
      selectValue(this.selectDay,dd);

      this.onBirthDateChanged();
    },
    refresh: function()
    {
      if(this.ageGroup)
      {
        var p = this.getPrice();
        var txt = this.ageGroup.label;

        if(p > 0)
          txt = txt + ' ' + p + ' ' + this.ctrl.getCurrency();

        this.txtInfo.update(txt);
      }
      else
          this.txtInfo.update('');
    },
    onBirthDateChanged: function()
    {
      var birthdate = this.getBirthdate();
      this.ageGroup = false;

      if(isDate(birthdate))
      {
        this.ageGroup = this.ctrl.getAgeGroup(birthdate);
      }
      this.refresh();

      this.ctrl.onPriceChanged();
    },
    getPrice: function()
    {
      if(this.group.isIndividual())
      {
          if(this.ageGroup)
            return this.ageGroup.price;
      }
      return 0;
    }
};

var AVBPlusGuestHidden = Class.create();
AVBPlusGuestHidden.prototype =
{
    initialize: function(ctrl,group,id)
    {
      this.id = id;
      this.ctrl = ctrl;
      this.group = group;
    },
    show: function(container)
    {
      groupId = this.group.getId();

      this.inputFirstName = document.createElement('input');
      this.inputFirstName = Element.extend(this.inputFirstName);
      this.inputFirstName.name = 'avbplus[' + groupId +'][guests][' + this.id + '][firstName]';
      this.inputFirstName.type = "hidden";
      container.appendChild(this.inputFirstName);

      // Flagga
      var hidden = document.createElement('input');
      hidden = Element.extend(hidden);
      hidden.name = 'avbplus[' + groupId +'][guests][' + this.id + '][useIt]';
      hidden.type = "hidden";
      hidden.value = "yes";
      container.appendChild(hidden);

      this.inputLastName = document.createElement('input');
      this.inputLastName = Element.extend(this.inputLastName);
      this.inputLastName.name = 'avbplus[' + groupId +'][guests][' + this.id + '][lastName]';
      this.inputLastName.type = "hidden";
      container.appendChild(this.inputLastName);

      this.inputYear = document.createElement('input');
      this.inputYear = Element.extend(this.inputYear);
      this.inputYear.name = 'avbplus[' + groupId +'][guests][' + this.id + '][yyyy]';
      this.inputYear.type = "hidden";
      container.appendChild(this.inputYear);

      this.inputMM = document.createElement('input');
      this.inputMM = Element.extend(this.inputMM);
      this.inputMM.name = 'avbplus[' + groupId +'][guests][' + this.id + '][mm]';
      this.inputMM.type = "hidden";
      container.appendChild(this.inputMM);

      this.inputDD = document.createElement('input');
      this.inputDD = Element.extend(this.inputDD);
      this.inputDD.name = 'avbplus[' + groupId +'][guests][' + this.id + '][dd]';
      this.inputDD.type = "hidden";
      container.appendChild(this.inputDD);
    },
    getFirstName: function()
    {
      return this.inputFirstName.value;
    },
    setFirstName: function(fn)
    {
        this.inputFirstName.value = fn;
    },
    getLastName: function()
    {
      return this.inputLastName.value;
    },
    setLastName: function(ln)
    {
        this.inputLastName.value = ln;
    },
    getBirthdate: function()
    {
      return this.inputYear.value + '-' + this.inputMM.value + '-' + this.inputDD.value;
    },
    setBirthdate: function(birthdate)
    {
      var yyyy = birthdate.substr(0,4);
      var mm = birthdate.substr(5,2);
      var dd = birthdate.substr(8,2);

      this.inputYear.value = yyyy;
      this.inputMM.value = mm;
      this.inputDD.value = dd;
    }
};

var AVBPlusGuestGroup = Class.create();
AVBPlusGuestGroup.prototype =
{
    initialize: function(ctrl,id,individual)
    {
      this.id = id;
      this.ctrl = ctrl;
      this.individual = individual;
      this.participants = $H();
      this.guestIndex = 0;
    },
    getId: function()
    {
      return this.id;
    },
    createView: function(groupContainerElement)
    {
       this.view = Element.extend(document.createElement("div"));
       this.view.style.display = "none";
       groupContainerElement.appendChild(this.view);

       var separator = Element.extend(document.createElement("div"));
       separator.className = "separator";
       this.view.appendChild(separator);
       this.maxGuestIdx = Element.extend(document.createElement("input"));
       this.maxGuestIdx.type = "hidden";
       this.maxGuestIdx.name = 'avbplus[' + this.id +'][maxid]';
       this.view.appendChild(this.maxGuestIdx);

       this.replaceId = Element.extend(document.createElement("input"));
       this.replaceId.type = "hidden";
       this.replaceId.name = 'avbplus[' + this.id +'][replaceId]';
       this.view.appendChild(this.replaceId);

       var i = Element.extend(document.createElement("input"));
       i.type = "hidden";
       i.name = 'avbplus[' + this.id +'][individual]';

       if(this.isIndividual())
           i.value = "yes";
       else
           i.value = "no";

       this.view.appendChild(i);


       if(!this.isIndividual())
       {
         var header = Element.extend(document.createElement("div"));
         header.className = "head";
         this.view.appendChild(header);

         var e = Element.extend(document.createElement("strong"));
         e.appendChild(document.createTextNode(this.ctrl.getText('Family')));
         header.appendChild(e);
/*
         e = Element.extend(document.createElement("a"));
         e.className = "remove";
         e.update('&nbsp;');
         e.onclick = this.onRemove.bind(this);
         header.appendChild(e);
*/
         this.sumContainer = Element.extend(document.createElement("span"));
         this.sumContainer.className = "sum";
         this.sumContainer.update(this.ctrl.getFamilyPrice() + ' ' + this.ctrl.getCurrency());
         header.appendChild(this.sumContainer);

       }

      var table = Element.extend(document.createElement("table"));
      table.className = 'guestList';
      this.view.appendChild(table);

      var thead = Element.extend(document.createElement("thead"));
      table.appendChild(thead);

      var tr = Element.extend(document.createElement("tr"));
      thead.appendChild(tr);

      var td = Element.extend(document.createElement("td"));
      td.appendChild(document.createTextNode(this.ctrl.getText('Firstname')));
      tr.appendChild(td);

      td = Element.extend(document.createElement("td"));
      td.appendChild(document.createTextNode(this.ctrl.getText('Lastname')));
      tr.appendChild(td);

      td = Element.extend(document.createElement("td"));
      td.appendChild(document.createTextNode(this.ctrl.getText('Birthdate')));
      tr.appendChild(td);

      td = Element.extend(document.createElement("td"));

      tr.appendChild(td);
      this.participantTable = Element.extend(document.createElement("tbody"));
      table.appendChild(this.participantTable);

      e = Element.extend(document.createElement("a"));
      e.className = "bookingControl-add";
      e.update(this.ctrl.getText("Add") + ' ' + this.ctrl.getText("person"));
      e.onclick = this.onAddParticipant.bind(this);
      this.view.appendChild(e);
    },
    getTotal: function()
    {
      if(this.isIndividual())
      {
        var tt = 0;
        this.participants.each(function(pair) { tt += pair.value.getPrice(); });

        return tt;
      }
      else
      {
        if(this.participants.size() > 0)
          return this.ctrl.getFamilyPrice();
        else
            return 0;
      }
    },
    show: function()
    {
        this.view.style.display = "block";
    },
    hide: function()
    {
        this.view.style.display = "none";
    },
    isIndividual: function()
    {
      return this.individual;
    },
    destroy: function()
    {
      if(this.view)
      {
          this.view.remove();
      }
    },
    setReplaceId: function(rid)
    {
        this.replaceId.value = rid;
    },
    addParticipant: function(firstName,lastName,birthdate,hidden)
    {
        if(typeof(hidden) == 'undefined')
            hidden = false;

        var p = this.newParticipant(hidden);

        p.setFirstName(firstName);
        p.setLastName(lastName);
        p.setBirthdate(birthdate);

        return p;
    },
    newParticipant: function(hidden)
    {
      if(typeof(hidden) == 'undefined')
          hidden = false;

      index = this.guestIndex++;
      this.maxGuestIdx.value = this.guestIndex;

      if(!hidden)
      {
        var a = new AVBPlusGuest(this.ctrl,this,index);
        a.show(this.participantTable);
        this.participants[index] = a;
        this.refresh();
        this.ctrl.onPriceChanged();
        return a;
      }
      else
      {
          var a = new AVBPlusGuestHidden(this.ctrl,this,index);
          a.show(this.view);
          return a;
      }
    },
    onAddParticipant: function()
    {
      this.newParticipant();
    },
    onRemoveParticipant: function(index)
    {
      a = this.participants[index];

      if(a)
      {
        a.destroy();
        this.participants.remove(index);
        this.refresh();
        this.ctrl.onPriceChanged();
      }
    },
    onRemove: function()
    {
      this.ctrl.onRemoveGroup(this.id);
    },
    validate: function()
    {
        var valid = true;

        this.participants.each(function(pair) { if(!pair.value.validate()) { valid = false; throw $break; } });

        return valid;
    },
    refresh: function()
    {
        if(this.participants.size() == 0)
            this.hide();
        else
            this.show();

        this.participants.each(function(pair) { pair.value.refresh(); });
    }
};

var AVBPlusController = Class.create();
AVBPlusController.prototype =
{
    /**
     * @param site Site identifierare
     * @param acitvity Aktivitet
     */
    initialize: function(site,lang,form,boxElement,arrdate,currency)
    {
      this.site = site;
      this.lang = lang;
      this.form = form;
      this.arrdate = arrdate;
      this.currency = currency;
      this.view = boxElement;

      this.familyIndex = 1;
      this.calendar = new CalendarAPI(this.site,this.lang);

      this.individualGroup = false;
      this.familyGroups = $H();
    },
    getLang: function () { return this.lang; },
    getCurrency: function () { return this.currency; },
    setAgeCats: function(ageCats)
    {
      this.ageCats = ageCats;

      me = this;
      me.maxYear = 0;
      me.minYear = 9999;

      this.ageCats.each(function(pair)
                        {
                          if(me.maxYear < pair.value.maxYear)
                              me.maxYear = pair.value.maxYear;

                          if(me.minYear > pair.value.minYear)
                              me.minYear = pair.value.minYear;

                        });
    },
    init: function()
    {
      this.contentContainer = getOneChildBySelector(this.view,'.contentContainer');
      this.groupContainer = getOneChildBySelector(this.contentContainer,'.groupContainer');

      // Add family ?
      var e = getOneChildBySelector(this.view,'a.bookingControl-add.family');
      if(e)
          e.onclick = this.onAddFamily.bind(this);

      // Add individual ?
      e = getOneChildBySelector(this.view,'a.bookingControl-add.individual');
      if(e)
          e.onclick = this.onAddIndividual.bind(this);

      this.individualGroup = new AVBPlusGuestGroup(this,0,true);
      this.individualGroup.createView(this.groupContainer);

    },
    show: function()
    {
      this.view.style.display = 'block';
    },
    showForm: function()
    {
      this.contentContainer.style.display = 'block';
    },
    hideForm: function()
    {
      this.contentContainer.style.display = 'none';
    },
    addFamily: function()
    {
      var index = this.familyIndex++;

      var f = new AVBPlusGuestGroup(this,index,false);
      this.familyGroups[index] = f;
      f.createView(this.groupContainer);

      return f;
    },
    getIndividualGroup: function()
    {
      return this.individualGroup;
    },
    addIndividual: function()
    {
      return this.individualGroup.newParticipant();
    },
    onAddFamily: function()
    {
        f = this.addFamily();
        f.newParticipant();
    },
    onAddIndividual: function()
    {
        this.individualGroup.newParticipant();
    },
    onRemoveGroup: function(id)
    {
      this._notifyChange();
    },
    onPriceChanged: function()
    {
      this._notifyChange();
    },
    _notifyChange: function()
    {
      if(typeof(this.changeListener) != "undefined")
          this.changeListener();
    },
    getAge: function(birthdate)
    {
      return this.calendar.getAge(birthdate,this.arrdate);
    },
    getAgeGroup: function(bd)
    {
      var age = this.getAge(bd);

      me = this;
      var ag = false;
      this.ageCats.each(function(pair)
                        {
                            if(pair.value.maxAge >= age && pair.value.minAge <= age)
                            {
                                ag = pair.value;
                            }
                        });
      return ag;
    },
    getFamilyPrice: function()
    {
      return this.familyPrice;
    },
    setFamilyPrice: function(p)
    {
        this.familyPrice = p;
    },
    getMaxYear: function()
    {
      return this.maxYear;
    },
    getMinYear: function()
    {
      return this.minYear;
    },
    getTotal: function()
    {
        var t = 0;
        
        this.familyGroups.each(function(pair) {t += pair.value.getTotal(); });
        
        return t + this.individualGroup.getTotal();
    },
    getForm: function()
    {
      return this.form;
    },
    getContainer: function()
    {
      return this.view;
    },
    getBirthDateMonths: function()
    {
      return $H({'01': this.getText('January'),
                 '02': this.getText('February'),
                 '03': this.getText('Mars'),
                 '04': this.getText('April'),
                 '05': this.getText('May'),
                 '06': this.getText('June'),
                 '07': this.getText('July'),
                 '08': this.getText('August'),
                 '09': this.getText('September'),
                 '10': this.getText('October'),
                 '11': this.getText('November'),
                 '12': this.getText('December')});
    },
    validate: function()
    {
        if(!this.individualGroup.validate())
            return false;

        var valid = true;

        this.familyGroups.each(function(pair) { if(!pair.value.validate()) { valid = false; throw $break; } });

        return valid;
    },
    prepareSubmit: function()
    {
       // Vi spar lite värden ..
    },
    submit: function()
    {
      if(this.validate())
      {
        this.prepareSubmit();
        this.form.submit();
      }
    }
};

var AVBPlusBinder = Class.create();
AVBPlusBinder.prototype =
{
    initialize: function(avbplusCtrl,avbplusBox,form)
    {
      this.ctrl = avbplusCtrl;
      this.form = form;

      this.yesBox = getOneChildBySelector(avbplusBox,'.YesNoContainer input.yes');
      if(this.yesBox)
          this.yesBox.onclick = this.onClick.bind(this);

      this.noBox = getOneChildBySelector(avbplusBox,'.YesNoContainer input.no');
      if(this.noBox)
          this.noBox.onclick = this.onClick.bind(this);

      this.sumElement = getOneChildBySelector(avbplusBox,'.YesNoContainer span.amount');
      this.copyNum = true;
    },
    init:function()
    {
      this.ctrl.hideForm();
      this.ctrl.changeListener = this._refreshSum.bind(this);
      this.ctrl.show();
      
      // Any users ..?
      if(this.ctrl.getTotal() > 0)
      {
        this.copyNum = false;
        this.yesBox.checked = true;
        this.noBox.checked = false;
      }
      this._refresh();
    },
    _refresh: function()
    {
      if(this.isSelected())
      {
          if(this.copyNum)
          {
            this.copyNum = false;

            // Copy values from form
/*            var adults = parseInt(this.form.adults.value);
            var youth = parseInt(this.form.youth.value) + parseInt(this.form.childs.value);

            if(adults > 0 || youth > 0)
            {
              for(var i = 0; i < adults;i++)
                   this.ctrl.newParticipant('VX');

              for(var i = 0; i < youth;i++)
                   this.ctrl.newParticipant('UN');
            }
            else
            {
              this.ctrl.newParticipant('VX');
            }
*/        }
          this.ctrl.showForm();
      }
      else
      {
          this.ctrl.hideForm();
      }
      this._refreshSum();
    },
    _refreshSum: function()
    {
        this.sumElement.update(this.getTotal());

        // OK, vi triggar en pris omräkning ..
        if(typeof(updatePrice) != "undefined")
            updatePrice();
    },
    getTotal: function()
    {
      if(this.isSelected())
          return this.ctrl.getTotal();
      else
          return 0;
    },
    validate: function()
    {
      if(this.isSelected())
         return this.ctrl.validate();
      else
         return true;
    },
    prepareSubmit: function()
    {
      this.ctrl.prepareSubmit();
    },
    isSelected: function()
    {
      return this.yesBox.checked;
    },
    onClick: function()
    {
        this._refresh();
    }
};


