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;
  }
}

EventController2 = Class.create();
EventController2.prototype =
{
  initialize: function(mainForm,participantContainer,totalElement)
  {
    this.mainForm = mainForm;
    this.container = participantContainer;
    this.totalElement = totalElement;

    // Lets find our stuff
    this.inputCBGroupDiscount = $('familyCheckbox');
    if(this.inputCBGroupDiscount)
        this.inputCBGroupDiscount.onclick = this.onGroupDiscountClick.bind(this);

    this.selectContainer = getOneChildBySelector(this.container,'div.participantControl');

    this.selectEventClassContainer = getOneChildBySelector(this.selectContainer,'div.type');
    this.selectEventClass = getOneChildBySelector(this.selectContainer,'div.type select');
    this.selectEventClass.onchange = this.onSelectedClassChanged.bind(this);

    this.selectNumContainer = getOneChildBySelector(this.selectContainer,'div.number');
    this.selectNum = getOneChildBySelector(this.selectContainer,'div.number select');
    this.selectNum.onchange = this.onSelectedNumChanged.bind(this);

    this.teamContainer = getOneChildBySelector(this.container,'div.team');
    this.inputTxtTeam = getOneChildBySelector(this.container,'div.team input');

    this.addBtn = getOneChildBySelector(this.container,'a.submitBtn');
    this.addBtn.onclick = this.onAddClass.bind(this);

    this.classGroupsContainer = getOneChildBySelector(this.container,'div.classGroups');

    this.eventClasses = false;
    this.eventClassesList = false; // Endast ordning

    this.groupClasses = $H();
    this.participants = $H();
    this.participantID = 1;
    this.groupClassID = 1;
  },
  init: function()
  {
    this._refreshClasses();
    this.refresh();
  },
  getNextParticipantID: function()
  {
    return this.participantID++;
  },
  setGroupTemplate: function(groupTemplate)
  {
    this.groupTemplate = groupTemplate;
  },
  setParticipantTemplate: function(pTemplate)
  {
    this.participantTemplate = pTemplate;
  },
  getParticipantTemplate: function()
  {
    return this.participantTemplate;
  },
  refresh: function()
  {
    // OK, klart ?
    var n = this.getSelectedNum();
    var c = this.getSelectedClass();

    var isSelectedClasses = this.groupClasses.size() > 0;

    // OK, all done ?
    if(c != null && n > 0 || isSelectedClasses)
    {
        this.selectEventClassContainer.removeClassName("active");
        this.selectNumContainer.removeClassName("active");
    }
    else
    {
       if(c == null)
       {
           this.selectEventClassContainer.addClassName("active");
           this.selectNumContainer.removeClassName("active");
       }
       else
       {
           this.selectEventClassContainer.removeClassName("active");
           this.selectNumContainer.addClassName("active");
       }
    }

    var total = 0;
    if(this.isGroupDiscount() && this.groupClasses.size() > 0)
    {
        total = this.getGroupDiscountPrice();
        this.groupClasses.each(function(pair) { pair.value.refresh();});
    }
    else
        this.groupClasses.each(function(pair) { pair.value.refresh(); total += pair.value.getTotal();});

    this.totalElement.update(total);
  },
  _refreshNum: function()
  {
    // Save selection ..
    var selectedNum = this.getSelectedNum();

    // OK, any selected class ?
    var c = this.getSelectedClass();

    // Clear
    var selectNumOption = this.selectNum.options[0];
    this.selectNum.options.length = 0;
    this.selectNum.options[0] = selectNumOption;

    if(c != null)
    {
        if(c.capac == 1)
        {
          // Individual, OK, add options ..
          for(var num = 1; num <= 5; num ++)
              this.selectNum.options[num] = new Option(num + ' ' + this.getText("pcs") + ' - ' + num*c.price + ' ' + this.currency,num);
        }
        else
        {
          // Group
          this.selectNum.options[1] = new Option('1 ' + this.getText("pcs") + ' - ' + c.price + ' ' + this.currency,1);
        }
        this.selectNum.disabled = false;

        this.setSelectedNum(selectedNum);
    }
    else
        this.selectNum.disabled = true;
  },
  _refreshClasses: function()
  {
    // Save any selections ..
    var selectedClass = this.getSelectedPoollid();

    if(this.eventClasses)
    {
       // We save the "first" values
       var selectClassOption = this.selectEventClass.options[0];
       this.selectEventClass.options.length = 0;
       this.selectEventClass.options[0] = selectClassOption;

       var idx = 1;
       for(var i = 0;i < this.eventClassesList.length;i++)
       {
          var v = this.eventClasses[this.eventClassesList[i]];
          if(this.isGroupDiscount())
          {
            // Only add individual courses
            if(v.capac > 1)
                continue;
          }
          this.selectEventClass.options[idx++] = new Option(v.name,v.poollid);
          this.selectEventClass.disabled = false;
       }
    }
    this.setSelectedPoollid(selectedClass);
    this._refreshNum();
  },
  setSelectedPoollid: function(poollid)
  {
    return selectValue(this.selectEventClass,poollid);
  },
  getSelectedPoollid: function()
  {
    return getSelectedValue(this.selectEventClass);
  },
  getSelectedClass: function()
  {
      var poollid = this.getSelectedPoollid();

      if(poollid > 0)
          return this.eventClasses[poollid];
      else
          return null;
  },
  getSelectedNum: function()
  {
    return getSelectedValue(this.selectNum);
  },
  setSelectedNum: function(num)
  {
    return selectValue(this.selectNum,num);
  },
  setGroupDiscount: function(b)
  {
      if(this.inputCBGroupDiscount)
      {
        if(b)
            this.inputCBGroupDiscount.checked = true;
        else
            this.inputCBGroupDiscount.checked = false;
      }
  },
  isGroupDiscount: function()
  {
      if(this.inputCBGroupDiscount)
          return this.inputCBGroupDiscount.checked;
      else
          return false;
  },
  setCurrency: function(currency)
  {
    this.currency = currency;
  },
  setGroupDiscountPrice: function(gdprice)
  {
    this.groupDiscountPrice = gdprice;
  },
  getGroupDiscountPrice: function()
  {
    return this.groupDiscountPrice;
  },
  setClasses: function(eventClasses)
  {
    this.eventClasses = $H();
    this.eventClassesList = $A();
    for(var i = 0;i < eventClasses.length;i++)
    {
        this.eventClassesList[i] = eventClasses[i].poollid;
        this.eventClasses[eventClasses[i].poollid] = eventClasses[i];
    }
  },
  onSelectedClassChanged: function()
  {
    this._refreshNum();
    this.refresh();
  },
  onSelectedNumChanged: function()
  {
    this.refresh();
  },
  addClassParticipant: function(poollid,teamName)
  {
      var c = this.eventClasses[poollid];
      if(c == null)
          return null;

      // OK, class Group ?
      var cg = this._findGroupClassByPoollid(poollid);
      if(!cg)
      {
          cg = this._createClassGroup(c);

          if(typeof(teamName) != 'undefined')
             cg.setTeamName(teamName);

          // .. och spara
          this.groupClasses[cg.getId()] = cg;
      }
      return cg.addClassParticipant();
  },
  addClassGroup: function(c,num)
  {
     if(c.capac > 1)
     {
        // Ok, grupp kan ednast väljas om inte familje rabatt
        if(this.isGroupDiscount())
        {
           this.showMessage(this.getText("TXTXBOKEV006","R2"));
           return;
        }
         // Nehep, då skapar vi en då
         cg = this._createClassGroup(c);

         // .. och spara
         this.groupClasses[cg.getId()] = cg;

         //OK, vi skapar upp participants ..
         for(var i = 0; i < c.capac;i++)
         {
             // och lägger till ..
             cg.addClassParticipant();
         }
         cg.refresh();
     }
     else
     {
         // OK, individuell kurs ..
         var cg = this._findGroupClassByPoollid(c.poollid);
         if(!cg)
         {
             cg = this._createClassGroup(c);
             // .. och spara
             this.groupClasses[cg.getId()] = cg;
         }

         //OK, vi skapar upp participants ..
         for(var i = 0; i < num;i++)
         {
             // och lägger till ..
             cg.addClassParticipant();
         }
         cg.refresh();
     }

     return cg;
  },
  _findGroupClassByPoollid: function(poollid)
  {
     var cg = null;

     this.groupClasses.each( function(pair)
                             {
                                 if(poollid == pair.value.getPoollid())
                                 {
                                     cg = pair.value;
                                     throw $break;
                                 }
                             });
     return cg;
  },
  onAddClass: function()
  {
     // OK, we have all we need ?
     var c = this.getSelectedClass();
     var num = this.getSelectedNum();

     if(c == null)
     {
       this.showMessage(this.getText("TXTXBOKEV004","R2"));
       return;
     }
     if(num == 0)
     {
       this.showMessage(this.getText("TXTXBOKEV005","R2"));
       return;
     }

     this.addClassGroup(c,num);
     this.refresh();
  },
  removeClass: function(id)
  {
      var cg = this.groupClasses.remove(id);
      cg.remove();
      this.refresh();
  },
  _createClassGroup: function(c)
  {
     var myid = this.groupClassID++;

     var ecg = new EventClassGroup(myid,this.groupTemplate,this,c,this.currency);

     this.classGroupsContainer.appendChild(ecg.createHtml());
     ecg.bind();

     return ecg;
  },
  onGroupDiscountClick: function()
  {
     if(this.isGroupDiscount())
     {
       // OK, make sure there are no groups ..
       var isGroup = false;
       this.groupClasses.each(function(pair) { isGroup = isGroup | pair.value.isGroup(); });

       if(isGroup)
       {
           this.showMessage(this.getText("TXTXBOKEV006","R2"));
           return false;
       }
     }

     this._refreshClasses();
     this.refresh();
  },
  _getOne: function(container,selector)
  {
    var l = container.getElementsBySelector(selector);
    if(l && l.size() >= 1)
        return l[0];
    else
        return null;
  },
  getText: function(key,domain)
  {
    return key;
  },
  showMessage: function(txt)
  {
    alert(txt);
  },
  validate: function()
  {
    // Ok, validate classGroups ..
    var isValid = true;
    var numParticipants = 0;

    this.groupClasses.each(function(pair)
                           {
                             isValid = pair.value.validate();
                             if(!isValid)
                                 throw $break;

                             numParticipants += pair.value.getNumParticipants();
                           });
    // OK, sista koll
    if(isValid)
    {
      if(numParticipants == 0)
      {
        this.showMessage(this.getText("TXTXBOKEV008","R2"));
        return false;
      }

      // OK, great
      return true;
    }
    else
        return false;
  },
  submit: function()
  {
    if(this.validate())
        this.mainForm.submit();
  }
};

EventClassGroup = Class.create();
EventClassGroup.prototype =
{
  initialize: function(id,template,ctrl,classDetails,currency)
  {
    this.id = id;
    this.template = template;
    this.details = classDetails;
    this.currency = currency;
    this.ctrl = ctrl;

    this.participants = $H();
  },
  createHtml: function()
  {
     myVars = {gIndex: this.id, poollid:  this.details.poollid, t0: this.id*100 };
     var div = document.createElement('div');

     div = Element.extend(div);
     div.update(this.template.evaluate(myVars));

     this.view = div;

     return this.view;
  },
  bind: function()
  {
    // find stuff
    this.participantsContainer = getOneChildBySelector(this.view,'div.classParcitipants');
    this.teamElement = getOneChildBySelector(this.view,'div.team');
    this.teamInput = getOneChildBySelector(this.view,'div.team input');
    this.removeLink = getOneChildBySelector(this.view,'div.team a.remove');
    this.removeLink.onclick = this.onRemoveMe.bind(this);

    this.summaryContainer = getOneChildBySelector(this.view,'div.summary');
    this.sumContainer = getOneChildBySelector(this.view,'div.summary span.num');
    this.labelsContainer = getOneChildBySelector(this.view,'div.summary span.labels');
    this.priceElement = getOneChildBySelector(this.view,'span.num span.person');
    this.totalElement = getOneChildBySelector(this.view,'span.num em.total');
    this.addLink = getOneChildBySelector(this.view,'a.addParticipant');
    this.addLink.onclick = this.onAddParticipant.bind(this);

    if(this.isGroup())
    {
      this.addLink.style.visibility = "hidden";
      this.teamElement.style.display = "block";

      this.removeLink.style.visibility = "visible";
    }
  },
  remove: function()
  {
    this.view.remove();
  },
  getId: function()
  {
    return this.id;
  },
  getView: function()
  {
    return this.view;
  },
  addClassParticipant: function()
  {
     var index = this.ctrl.getNextParticipantID();

     var ecp = new EventClassParticipant(index,this.ctrl.getParticipantTemplate(),this.ctrl,this,this.details);
     ecp.createHtml();

     this.participantsContainer.appendChild(ecp.getView());
     ecp.bind();
     ecp.setGroupIndex(this.id);

     this.participants[ecp.getId()] = ecp;

     this.ctrl.refresh();

     return ecp;
  },
  removeClassParticipant: function(id)
  {
    var p = this.participants.remove(id);
    p.remove();

    // OK, any more ?
    if(this.participants.size() == 0)
        this.ctrl.removeClass(this.id);

     this.ctrl.refresh();
  },
  onAddParticipant: function()
  {
    this.addClassParticipant();
  },
  onRemoveMe: function()
  {
    this.ctrl.removeClass(this.id);
  },
  isGroup: function()
  {
    return this.details.capac > 1;
  },
  getNumParticipants: function()
  {
    return this.participants.size();
  },
  getPoollid: function()
  {
    return this.details.poollid;
  },
  setTeamName: function(tn)
  {
    this.teamInput.value = tn;
  },
  getTeamName: function()
  {
    return this.teamInput.value;
  },
  getTotal: function()
  {
    if(this.isGroup())
    {
      return this.details.price;
    }
    else
    {
      // Group discount?
      if(this.ctrl.isGroupDiscount())
      {
        return this.ctrl.getGroupDiscountPrice();
      }
      else
      {
          return this.details.price*this.participants.size();
      }
    }
  },
  getEach: function()
  {
    if(this.isGroup())
    {
      if(this.participants.size() == 0)
          return 0;
      else
         return this.details.price/this.participants.size();
    }
    else
    {
      // Group discount?
      if(this.ctrl.isGroupDiscount())
      {
          if(this.participants.size() == 0)
              return 0;
          else
              return this.ctrl.getGroupDiscountPrice()/this.participants.size();
      }
      else
      {
          return this.details.price;
      }
    }

  },
  validate: function()
  {
    if(this.isGroup())
    {
      // Lagnamn
      if(this.teamInput.value == null || this.teamInput.value.length == 0)
      {
        this.ctrl.showMessage(this.ctrl.getText("TXTXBOKEV007","R2"));
        return false;
      }
    }

    // OK, validate all participants ..
    var isValid = true;
    this.participants.each(function(pair)
                           {
                             isValid = pair.value.validate();
                             if(!isValid)
                                 throw $break;
                           });
    return isValid;
  },
  refresh: function()
  {
    if(this.ctrl.isGroupDiscount())
    {
       this.summaryContainer.style.display = "none";
    }
    else
    {
       this.summaryContainer.style.display = "block";
      this.priceElement.update(this.getEach() + ' ' + this.currency);
      this.totalElement.update(this.getTotal() + ' ' + this.currency);

    }
    this.participants.each(function(pair)
                           {
                             pair.value.refresh();
                           });

  }
};

EventClassParticipant = Class.create();
EventClassParticipant.prototype =
{
  initialize: function(id,template,ctrl,classGroup,ClassDetails)
  {
    this.id = id;
    this.details = ClassDetails;
    this.template = template;
    this.ctrl = ctrl;
    this.classGroup = classGroup;
  },
  onChanged: function()
  {
    this.refresh();
  },
  isDone: function()
  {
    var fn = this.getFirstName();
    var ln = this.getLastName();
    var bd = this.getBirthDate();

    return fn != null && fn.length > 0 && ln != null && ln.length > 0 && isDate(bd);
  },
  refresh: function()
  {
      if(this.isDone())
          this.participantsContainer.removeClassName("active");
      else
          this.participantsContainer.addClassName("active");
  },
  validate: function()
  {
    // OK, basic validatetion
    var fn = this.getFirstName();
    var ln = this.getLastName();
    var bd = this.getBirthDate();

    if(fn == null || fn.length == 0)
    {
       this.ctrl.showMessage(this.getCaption() + ', ' + this.ctrl.getText('Specify firstname'));
       this.inputFirstname.focus();
       return false;
    }

    if(ln == null || ln.length == 0)
    {
       this.ctrl.showMessage(this.getCaption() + ', ' + this.ctrl.getText('Specify lastname'));
       this.inputLastname.focus();
       return false;
    }
    // Onöly mandatory if exists
    if(this.inputCity)
    {
        var c = this.getCity();
        if(c == null || c.length == 0)
        {
            this.ctrl.showMessage(this.getCaption() + ', ' + this.ctrl.getText('TXTXBOKEV010','R2'));
            return false;
        }
    }
    // Only mandatory if exists
    if(this.inputClub)
    {
        var c = this.getClub();
        if(c == null || c.length == 0)
        {
            this.ctrl.showMessage(this.getCaption() + ', ' + this.ctrl.getText('TXTXBOKEV011','R2'));
            return false;
        }
    }

    if(!isDate(bd))
    {
       this.ctrl.showMessage(this.getCaption() + ', ' + this.ctrl.getText('Invalid birthdate'));
       this.selectYear.focus();
       return false;
    }
    return true;
  },
  createHtml: function()
  {
     var gIdx = this.classGroup.getId()*100;

     gIdx = gIdx + this.id*10;

     myVars = {pIndex: this.id, t0: gIdx + 1, t1: gIdx + 2,t2: gIdx + 3,t3: gIdx + 4,t4: gIdx + 5,t5: gIdx + 6,t6: gIdx + 7,t7: gIdx + 8,t8: gIdx + 9};
     var div = document.createElement('div');

     div = Element.extend(div);
     div.update(this.template.evaluate(myVars));

     this.view = div;
     return this.view;
  },
  bind: function()
  {
    this.participantsContainer = getOneChildBySelector(this.view,'div.participantDetails');

    this.groupIndex = getOneChildBySelector(this.view,'input.groupIdx');

    // Label
    this.headerText = getOneChildBySelector(this.view,'div.header span');

    // Radera
    this.removeLink = getOneChildBySelector(this.view,'div.header a');
    this.removeLink.onclick = this.onRemoveMe.bind(this);

    this.inputFirstname = getOneChildBySelector(this.view,'input.firstName');
    this.inputFirstname.onkeyup = this.onChanged.bind(this);

    this.inputLastname = getOneChildBySelector(this.view,'input.lastName');
    this.inputLastname.onkeyup = this.onChanged.bind(this);

    this.selectDay = getOneChildBySelector(this.view,'select.day');
    this.selectDay.onchange = this.onChanged.bind(this);

    this.selectMonth = getOneChildBySelector(this.view,'select.month');
    this.selectMonth.onchange = this.onChanged.bind(this);

    this.selectYear = getOneChildBySelector(this.view,'select.year');
    this.selectYear.onchange = this.onChanged.bind(this);

    this.inputEmail = getOneChildBySelector(this.view,'input.email');
    this.inputPhone = getOneChildBySelector(this.view,'input.phone');

    this.inputCity = getOneChildBySelector(this.view,'input.city');
    this.inputClub = getOneChildBySelector(this.view,'input.club');

    this.setHeaderText(this.getCaption());

    if(this.classGroup.isGroup())
    {
        this.removeLink.style.visibility = "hidden";
    }

    this.refresh();

  },
  getCaption: function()
  {
    return this.ctrl.getText('Participants') + ' ' + this.id + ' - ' + this.details.name;
  },
  setGroupIndex: function(idx)
  {
    this.groupIndex.value = idx;
  },
  getGroupIndex: function()
  {
    return this.groupIndex.value;
  },
  setHeaderText: function(t)
  {
    this.headerText.update(t);
  },
  setFirstName: function(fn)
  {
    this.inputFirstname.value = fn;
  },
  getFirstName: function()
  {
    return this.inputFirstname.value;
  },
  setLastName: function(ln)
  {
    this.inputLastname.value = ln;
  },
  getLastName: function()
  {
    return this.inputLastname.value;
  },
  getBirthDate: function()
  {
      return getSelectedValue(this.selectYear) + '-' + getSelectedValue(this.selectMonth) + '-' + getSelectedValue(this.selectDay);
  },
  setBirthDate: function(bd)
  {
    selectValue(this.selectYear,bd.substring(0,4));
    selectValue(this.selectMonth,bd.substring(5,7));
    selectValue(this.selectDay,bd.substring(8,10));
  },
  setEmail: function(e)
  {
    this.inputEmail.value = e;
  },
  getEmail: function()
  {
    return this.inputEmail.value;
  },
  setPhone: function(ln)
  {
    this.inputPhone.value = ln;
  },
  getPhone: function()
  {
    return this.inputPhone.value;
  },
  setCity: function(c)
  {
    if(this.inputCity)
        this.inputCity.value = c;
  },
  getCity: function()
  {
    if(this.inputCity)
        return this.inputCity.value;
    else
        return "";
  },
  setClub: function(c)
  {
    if(this.inputClub)
        this.inputClub.value = c;
  },
  getClub: function()
  {
    if(this.inputClub)
        return this.inputClub.value;
    else
        return "";
  },
  onRemoveMe: function()
  {
      this.classGroup.removeClassParticipant(this.id);
  },
  remove: function()
  {
    this.view.remove();
  },
  getView: function()
  {
    return this.view;
  },
  getId: function()
  {
    return this.id;
  }
};
