/* =============== Steg 2 ========================*/
/**
 * Add a sorting property to the Array object
 */
Array.prototype.propertySort = function(index)
{
  var objectToString = Object.prototype.toString,
      arrayToString = Array.prototype.toString;

  if(typeof index != "function")
  {
    var property = index;
    index = function(){return this[property]};
  }
  Object.prototype.toString = index;
  Array.prototype.toString = index;

  this.sort();

  Object.prototype.toString = objectToString;
  Array.prototype.toString = arrayToString;
}

/**
 * General success function, decodes JSON
 * resonse and calls options.onSuccess(origrequest,evaluated JSON-object)
 */
_onSuccess = function(transport)
{
    if(this.options.onSuccess)
    {
        res = eval('(' + transport.responseText + ')');
        this.options.onSuccess(this,res);
    }
},
/**
 * General failure function, decodes JSON
 * resonse and calls options.onFailure(origrequest)
 */
_onFailure = function(transport)
{
    if(this.options.onFailure)
    {
        this.options.onFailure(this);
    }
}

SkiSchoolDestinationFilter = Class.create();
SkiSchoolDestinationFilter.prototype =
{
  initialize: function(inpuElements)
  {
      this.subAreas = $A();
      this.mainElement = null;

      me = this;
      inpuElements.each(function(cb)
      {
         // assignEventListeners
         cb.onclick = me.onClick.bind(me,cb);

         if(me._isDestination(cb))
             me.mainElement = cb;
         else
             me.subAreas[me.subAreas.length] = cb;
      });
  },
  onClick: function(ib)
  {
    if(this._isDestination(ib))
    {
      // Destination
      if(ib.checked)
        this.subAreas.each(function(x) { x.checked = true; });
      else
        this.subAreas.each(function(x) { x.checked = false; });
    }
    else
    {
        var allchecked = false;
        this.subAreas.each(function(x)
                           {
                               allchecked = allchecked || x.checked;
                           });
        this.mainElement.checked = allchecked;
    }

    this.onChanged();
  },
  onChanged: function()
  {

  },
  _isDestination: function(cb)
  {
      return ((0x00ffffff & cb.value) == 0);
  },
  getMask:function()
  {
      var mask = 0;

      if(this.mainElement.checked)
          mask = this.mainElement.value;

      this.subAreas.each(function(x)
                           {
                               if(x.checked)
                                   mask = mask | x.value;
                           });

      return mask;
   },
   setMask: function(m)
   {
       var allchecked = false;
       me = this;
       this.subAreas.each(function(x)
                          {
                             v = (m & me.mainElement.value) && (m & x.value);
                             x.checked = v;

                             allchecked = allchecked || x.checked;
                          });
        this.mainElement.checked = allchecked;
   }
};
MultipleSelectView  = Class.create();
MultipleSelectView.prototype =
{
  initialize: function(inpuElements)
  {
      this.boxes = $A();

      me = this;
      inpuElements.each(function(cb)
      {
         // assignEventListeners
         cb.onclick = me.onClick.bind(me,cb);
         me.boxes[me.boxes.length] = cb;
      });
  },
  onClick: function(ib)
  {
    this.onChanged();
  },
  onChanged: function()
  {

  },
  getMask:function()
  {
      var mask = 0;

      this.boxes.each(function(x)
                           {
                               if(x.checked)
                                   mask = mask | x.value;
                           });
      return mask;
   },
   setMask: function(m)
   {
      this.boxes.each(function(x) { x.checked = m & x.value; });
   }
};

SkiSchoolFilterView = Class.create();
SkiSchoolFilterView.prototype =
{
  initialize: function(formId)
  {
    this.formId = formId;
    this.enabled = true;

    this.destinationFilters = $A();

    // OK, lets initialize and find our controls ..

    // The destination filter
    var stuff = $$('div.destination_option');
    var me = this;

    stuff.each(function(x)
    {
      var df = new SkiSchoolDestinationFilter(x.getElementsBySelector('input.checkbox'));
      df.onChanged = me._onDestinationChanged.bind(me);

      me.destinationFilters[me.destinationFilters.length] = df;
    });

    // The agegroupFilter
    this.ageGroupFilter = new MultipleSelectView($$('input.age_checkbox'));
    this.ageGroupFilter.onChanged = this._onAgeGroupChanged.bind(this);

    this.equipTypeFilter = new MultipleSelectView($$('input.eqtype_checkbox'));
    this.equipTypeFilter.onChanged = this._onEquipTypeChanged.bind(this);

    this.levelFilter = new MultipleSelectView($$('input.level_checkbox'));
    this.levelFilter.onChanged = this._onLevelChanged.bind(this);
    
    this.saveFilter();
  },
  _onDestinationChanged: function()
  {
    this.onChanged();
  },
  _onAgeGroupChanged: function()
  {
    this.onChanged();
  },
  _onEquipTypeChanged: function()
  {
    this.onChanged();
  },
  _onLevelChanged: function()
  {
    this.onChanged();
  },
  onChanged: function()
  {
      this.saveFilter();

      this._filterChanged();
  },
  _filterChanged: function()
  {
      this._setEnabled(false);
      // OK, disable ourselves, and dispatch notofication
      setTimeout(this._dispatchFilterChanged.bind(this),100);
  },
  _dispatchFilterChanged: function()
  {
      this.controller.onFilterChanged();
  },
  getFilter: function()
  {
     var destinationMask = 0;
     this.destinationFilters.each(function(x) { destinationMask = destinationMask | x.getMask(); });

     return {destinationMask: destinationMask, ageGroupMask: this.ageGroupFilter.getMask(), equipTypeMask: this.equipTypeFilter.getMask(),levelMask: this.levelFilter.getMask()};
  },
  setFilter: function(f)
  {
      this.destinationFilters.each(function(x) { x.setMask(f.destinationMask) });
      this.ageGroupFilter.setMask(f.ageGroupMask);
      this.levelFilter.setMask(f.levelMask);
      this.equipTypeFilter.setMask(f.equipTypeMask);

      this.saveFilter();
  },
  saveFilter: function()
  {
      var f = this.getFilter();
      var myForm = $(this.formId);
      if(myForm)
      {
        myForm.destinationMask.value = f.destinationMask;
        myForm.ageGroupMask.value = f.ageGroupMask;
        myForm.levelMask.value = f.levelMask;
        myForm.equipTypeMask.value = f.equipTypeMask;
      }
  },
  setController: function(c)
  {
      this.controller = c;
  },
  refresh: function()
  {
      // Check controller state
      myS = this.controller.getState();
      switch(myS)
      {
          case 0 :
          this._setEnabled(true);
          break;

          case 1 :
          this._setEnabled(false);
          break;

          case 2 :
          this._setEnabled(false);
          break;

          default:
      }
  },
  _setEnabled: function(e)
  {
      if(e == this.enabled)
          return;
      if(e)
          Form.enable($(this.formId));
      else
          Form.disable($(this.formId));

      this.enabled = e;
  }
};

SkiSchoolFilter=function(destinationMask,ageGroupMask,equipTypeMask,levelMask)
{
  this.destinationMask = destinationMask;
  this.ageGroupMask = ageGroupMask;
  this.equipTypeMask = equipTypeMask;
  this.levelMask = levelMask;
}
MessageView = Class.create();
MessageView.prototype =
{
  initialize: function(view)
  {
    this.view = view;
    this.message = "";
  },
  setMessage: function(m)
  {
    this.message = m;
    this.view.update(this.message);
    if(this.message)
        this.view.show();
    else
        this.view.hide();
  }
};

SkiSchoolResultView = Class.create();
SkiSchoolResultView.prototype =
{
  initialize: function(view)
  {
    this.view = view;
    this.sortingColumns = $H();
  },
  setController: function(c)
  {
      this.controller = c;
  },
  refresh: function()
  {
      // Check controller state
      myS = this.controller.getState();
      switch(myS)
      {
          case 0 :
          var docFragment = document.createDocumentFragment();
          var table = document.createElement("table");
          table.className = "courseTable";
          table.cellSpacing = "0";
          table.cellPadding = "0";

          var head = document.createElement("thead");
          var trElem, thElem, tdElem, txtNode, aNode, tmpNode,div,tbodyElem;

          // The head
          trElem = document.createElement("tr");

          this._createColumnHead(trElem,"Destination",1);
          this._createColumnHead(trElem,"CourseName",2);
          this._createColumnHead(trElem,"Level",3);
          this._createColumnHead(trElem,"Days",4, 90);
          this._createColumnHead(trElem,"Meetingpoint",5);
          this._createColumnHead(trElem,"Participants",6);
          this._createColumnHead(trElem,"Price/person",7);

          // Välj
          thElem = document.createElement("th");
          thElem.scope = "col";
          thElem.nowrap = "nowrap";
          thElem.className = "nopadding";
          thElem.align = "center";
          txtNode = document.createTextNode(this.controller.getText('Select'));
          thElem.appendChild(txtNode);
          trElem.appendChild(thElem);


          head.appendChild(trElem);

          table.appendChild(head);

          // OK, now our data
          var data = this.controller.getDisplayRows();
          num = data.length;

          tbodyElem = document.createElement("tbody");
          table.appendChild(tbodyElem);

          var extraCls = "";

          for(var i = 0; i < num; i++)
          {
              if(i % 2)
                  extraCls = "odd";
              else
                  extraCls = "";
              this._createRow(tbodyElem,data[i],extraCls);
          }

          this.view.update('');
          this.view.appendChild(table);
          // OK, now lets show how we sort
          var currentSort = this.controller.getCurrentSort();
          var currentSortAsc = this.controller.getCurrentSortAsc();

          if(currentSort > 0)
          {
              v = this.sortingColumns[currentSort];

              if(v)
              {
                  v = $(v);
                  v.addClassName("selected");

                  if(currentSortAsc)
                      v.addClassName("asc");
                  else
                      v.addClassName("desc");
              }
          }
          break;

          case 1 :
          break;

          case 2 :
          this.view.update('');
          break;

          default:
      }
  },
  _createColumnHead: function(trElem,nameKey,sortIndex,width)
  {
      var thElem, txtNode, aNode;

      thElem = document.createElement("th");
      thElem.scope = "col";
      thElem.noWrap = "nowrap";
      if(typeof(width) != "undefined")
          thElem.width = width + "px";

      aNode = document.createElement("a");
      aNode.className = "sortable";

      aNode.onclick = this.selectSort.bind(this,sortIndex);
      
      // OK, fixa Hoover
      aNode.title = this.controller.getText("TXTXBOKSS" + (11 + sortIndex),"R2");
      txtNode = document.createTextNode(this.controller.getText(nameKey));
      aNode.appendChild(txtNode);
      thElem.appendChild(aNode);
      trElem.appendChild(thElem);
      this.sortingColumns[sortIndex] = thElem;
  },
  _createRow: function(bodyElement,record,extraCls)
  {
      var trElem, thElem, tdElem, txtNode, aNode, imgNode,spanNode,div,tbodyElem;

      trElem = document.createElement("tr");

      if(typeof(extraCls) != 'undefined')
          trElem.className = extraCls;

      // Resmål
      tdElem = document.createElement("td");
      txtNode = document.createTextNode(record[1]);
      tdElem.appendChild(txtNode);
      trElem.appendChild(tdElem);


      // Kursnamn
      tdElem = document.createElement("td");
      tdElem.nowrap = "nowrap";

/*      aNode = document.createElement("a");
      imgNode = document.createElement("img");
      imgNode.src = "/app/projects/common/images/system/skidskola/icon_tableinfo.gif";
      aNode.appendChild(imgNode);
      tdElem.appendChild(aNode); */
      txtNode = document.createTextNode(record[2]);
      tdElem.appendChild(txtNode);
      trElem.appendChild(tdElem);

      // Nivå
      tdElem = document.createElement("td");
      tdElem.align = "center";
      div = document.createElement("div");
      div.className = record[3];
      tdElem.appendChild(div);
      trElem.appendChild(tdElem);

      // Dagar
      tdElem = document.createElement("td");
      tdElem.className = "coursedates";

      for(var day = 6; day >= 0;day--)
      {
        div = document.createElement("div");
        dayName = this.controller.getText('day' + day);

        if( (0x01 << day) & record[4] )
           cls = "s" + dayName;
        else
           cls = "n" + dayName;

        div.className = "calendarDay " + cls;
        tdElem.appendChild(div);
      }
      trElem.appendChild(tdElem);

      // Mötesplats
      tdElem = document.createElement("td");
      txtNode = document.createTextNode(record[5]);
      tdElem.appendChild(txtNode);
      trElem.appendChild(tdElem);

      // Deltagare
      tdElem = document.createElement("td");
      tdElem.align = "center";
      txtNode = document.createTextNode(record[6]);
      tdElem.appendChild(txtNode);
      trElem.appendChild(tdElem);

      // Pris
      tdElem = document.createElement("td");
      tdElem.title = this.controller.getText("TXTXBOKSS30","R2");
      txtNode = document.createTextNode(record[7]);
      tdElem.appendChild(txtNode);
      trElem.appendChild(tdElem);

      // Välj
      tdElem = document.createElement("td");
      aNode = document.createElement("a");
      aNode.onclick = this.onSelect.bind(this,record[0]);
      imgNode = document.createElement("img");
      imgNode.src = "/app/projects/common/images/system/skidskola/icon_rowselect.gif";
      aNode.appendChild(imgNode);
      tdElem.appendChild(aNode);
      trElem.appendChild(tdElem);

      bodyElement.appendChild(trElem);
  },
  selectSort: function(column)
  {
      var currentSort = this.controller.getCurrentSort();
      var currentSortAsc = this.controller.getCurrentSortAsc();

      if(column == currentSort)
      {
          // OK, toggle order
          this.controller.setSort(currentSort,!currentSortAsc);
      }
      else
      {
          // New sort
          this.controller.setSort(column,false);
      }
  },
  onSelect: function(courseId)
  {
      var res = courseId.split(':');

      this.controller.selectCourse(res[0],res[1]);
  }
};
SkiSchoolNavigationView = Class.create();
SkiSchoolNavigationView.prototype =
{
  initialize: function(view)
  {
    this.view = view;
  },
  setController: function(c)
  {
      this.controller = c;
  },
  refresh: function()
  {
      // Check controller state
      myS = this.controller.getState();
      switch(myS)
      {
            case 0 :
            numPages = this.controller.getNumPages();
            currentIdx = this.controller.getCurrentPage();
            
            this.view.update('');
            var docFragment = document.createDocumentFragment();
            var ulElem,liElem,aElem,txtNode;

            ulElem = document.createElement("ul");
            ulElem.className = "pagination";

            // Simple ..
            for(i = 0; i < numPages; i++)
            {
              liElem = document.createElement("li");

              if( (i + 1) >= 10)
              {

                  if(currentIdx == i)
                      liElem.className = "wideSelected";
                  else
                  {
                      liElem.onmouseover = this.onMouseOver.bind(this,Element.extend(liElem),'wide');
                      liElem.onmouseout = this.onMouseOut.bind(this,Element.extend(liElem),'wide');
                      liElem.className = "wide";
                  }
              }
              else
              {

                  if(currentIdx == i)
                      liElem.className = "smallSelected";
                  else
                  {
                      liElem.className = "small";
                      liElem.onmouseover = this.onMouseOver.bind(this,Element.extend(liElem),'small');
                      liElem.onmouseout = this.onMouseOut.bind(this,Element.extend(liElem),'small');
                  }
              }

              aElem = document.createElement("a");
              aElem.onclick = this.onNavigate.bind(this,i);

              txtNode = document.createTextNode("" + (i + 1));

              aElem.appendChild(txtNode);
              liElem.appendChild(aElem);

              ulElem.appendChild(liElem);
            }
            docFragment.appendChild(ulElem);
            this.view.appendChild(docFragment);
            break;

            case 1 :
            var d = this.view.descendants();
            d.each(function(e)
            {
                e.style.opacity = "0.5";
                e.style.filter = "alpha(opacity=50)";
            });

            break;

            case 2 :
            this.view.hide();
            break;

            default:
      }
  },
  onMouseOver: function(element,type)
  {
    if(type == 'small')
        element.addClassName('smallSelected');
    else
        element.addClassName('wideSelected');
  },
  onMouseOut: function(element,type)
  {
    if(type == 'small')
    {
        element.removeClassName('smallSelected');
        element.addClassName('small');
    }
    else
    {
        element.removeClassName('wideSelected');
        element.addClassName('wide');
    }

  },
  onNavigate: function(pageIdx)
  {
    this.controller.setCurrentPage(pageIdx);
  }
};
SkiSchoolController = Class.create();
SkiSchoolController.prototype =
{
  initialize: function(mainForm,filterView,resultView,navigationView,errorMessageView)
  {
    this.mainForm = mainForm;
    this.state = -1;
    this.filterView = filterView;
    this.filterView.setController(this);

    this.resultView = resultView;
    this.resultView.setController(this);

    this.navigationView = navigationView;
    this.navigationView.setController(this);

    this.errorMessageView = errorMessageView;

    // Model elements
    this.perPage = 20;
    this.state = 0;
    this.selectedItems = $H();
    this.expandedItems = $H();
    this.rawList = null;
    this.selectedList = null;
    this.lookupMap = null;
    this.filteredList = null;
    this.sortedList = null;
    this.displayedList = null;

    this.currentPage = 0;
    this.currentSort = 0;
    this.currentSortAsc = false;

    this.sortFunctions = $A();

    this.sortFunctions[1] = function() { return this[1]};
    this.sortFunctions[2] = function() { return this[2]};
    this.sortFunctions[3] = function() { return this[3]};
    this.sortFunctions[4] = function() { return this[8]};
    this.sortFunctions[5] = function() { return this[5]};
    this.sortFunctions[6] = function() { return this[9]};
    this.sortFunctions[7] = function() { return this[10]};

    this.setState(1);
    this.dataSource = null;
  },
  setSortFunctions: function(sf)
  {
    this.sortFunctions = sf;
  },
  setDefaultSort: function(sortColumn,sortAsc)
  {
    this.currentSort = sortColumn;
    this.currentSortAsc = sortAsc;
  },
  setState: function(newState)
  {
    if(newState != this.state)
    {
      this.state = newState;
      this.refresh();
    }
  },
  getState: function()
  {
    return this.state;
  },
  refresh: function()
  {
    this.filterView.refresh();
    this.resultView.refresh();
    this.navigationView.refresh();
  },
  setDataSource: function(dataSource)
  {
      this.dataSource = dataSource;
  },
  load: function()
  {
     this.setState(1);
     this.dataSource.load(this.onSearchComplete.bind(this));
  },
  onSearchComplete: function(res)
  {
    if(res.num > 0)
    {
      this.rawList = res.rows;
      this.lookupMap = $H();

      // We create an ID, index/lookup
      num = this.rawList.length;

      for(i = 0; i < num; i++)
      {
          r = this.rawList[i];
          this.lookupMap[r[0]] = i;
      }

      this._requestUpdate(this.doFilter.bind(this));
    }
    else
    {
      this.errorMessageView.setMessage(this.getText('TXTXBOKSS08','R2'));
      this.setState(2);
    }
  },
  _requestUpdate: function(operation)
  {
      this.setState(1);
      setTimeout(this._performSlowOperation.bind(this,operation),200);
  },
  _performSlowOperation: function(operation)
  {
      operation();
      this.setState(0);
  },
  onFilterChanged: function()
  {
      this._requestUpdate(this.doFilter.bind(this));
  },
  isMatch: function(filter,row)
  {
    return ((row[11] & filter.destinationMask) == row[11]) && row[12] & filter.ageGroupMask && row[13] & filter.equipTypeMask && row[14] & filter.levelMask;
  },
  doFilter: function()
  {
      if(this.isMatch)
      {
        f = this.filterView.getFilter();
        this.filteredList = $A();
        this.selectedList = $A();

        idx = 0;
        var selectedIdx = 0;
        num = this.rawList.length;

        for(i = 0; i < num; i++)
        {
            r = this.rawList[i];

            var selected = this.selectedItems[r[0]];
            if(selected)
            {
                this.selectedList[selectedIdx++] = r;
                continue;
            }

            if(this.isMatch(f,r))
                this.filteredList[idx++] = r;
        }
      }
      else
      {
          // No matching function, everything but selected matches
        this.filteredList = $A();
        this.selectedList = $A();

        idx = 0;
        var selectedIdx = 0;

        num = this.rawList.length;

        for(i = 0; i < num; i++)
        {
            r = this.rawList[i];

            var selected = this.selectedItems[r[0]];
            if(selected)
            {
                this.selectedList[selectedIdx++] = r;
                continue;
            }

            this.filteredList[idx++] = r;
        }

//        this.filteredList = this.rawList;
      }
      // We must also reSort
      this.doSort();
  },
  doSort: function()
  {
      this.sortedList = this.filteredList;

      this.sortedList.propertySort(this.sortFunctions[this.currentSort]);
      if(this.currentSortAsc)
          this.sortedList.reverse();

      // We must also reset navigation
      this.currentPage = 0;
//        theLog.flush('sort');

      this.doNavigate();
  },
  initSort: function(sortColumn,sortAsc)
  {
      this.currentSort = sortColumn;
      this.currentSortAsc = sortAsc;
  },
  setSort: function(sortColumn,sortAsc)
  {
      this.currentSort = sortColumn;
      this.currentSortAsc = sortAsc;
      this._requestUpdate(this.doSort.bind(this));
  },
  setCurrentPage: function(idx)
  {
      numPages = this.getNumPages();
      if(idx < 0 || idx >= numPages)
          return;
      this.currentPage = idx;
      this._requestUpdate(this.doNavigate.bind(this));
  },
  doNavigate: function()
  {
      // ..
      this.displayedList = $A();

      startIdx = this.getCurrentPage()*this.getPerPage();
      stopIdx = Math.min(startIdx+this.getPerPage(),this.sortedList.length);
      var idx = 0;
      for(i = startIdx; i < stopIdx;i++)
          this.displayedList[idx++] = this.sortedList[i];
  },
  getPerPage: function()
  {
    return this.perPage;
  },
  getNumPages: function()
  {
      return Math.ceil(this.getNumHits()/this.getPerPage());
  },
  getNumHits: function()
  {
      return this.sortedList.length;
  },
  getCurrentPage: function()
  {
      return this.currentPage;
  },
  getCurrentSort: function()
  {
      return this.currentSort;
  },
  getCurrentSortAsc: function()
  {
      return this.currentSortAsc;
  },
  getDisplayRows: function()
  {
    return this.displayedList;
  },
  getSelectedRows: function()
  {
    return this.selectedList;

/*      var selectedRows = $A();

      var me = this;
      var idx = 0;
      this.selectedItems.each(function(pair)
                              {
                                selectedRows[idx++] = me.rawList[me.lookupMap[pair.key]];
                              });

      return selectedRows;
*/
  },
  saveFilter: function()
  {
    var filter = this.filterView.getFilter();

    this.mainForm.destinationMask.value = filter.destinationMask;
    this.mainForm.ageGroupMask.value = filter.ageGroupMask;
    this.mainForm.levelMask.value = filter.levelMask;
    this.mainForm.equipTypeMask.value = filter.equipTypeMask;

    this.mainForm.sortColumn.value = this.currentSort;
    if(this.currentSortAsc)
        this.mainForm.sortAsc.value = "1";
    else
        this.mainForm.sortAsc.value = "";

  },
  selectCourse: function(courseTypeLID,meetingPlaceLID)
  {
    this.mainForm.courseTypeLID.value = courseTypeLID;
    this.mainForm.meetingPlaceLID.value = meetingPlaceLID;
    this.mainForm.bpid.value = 70213;

    this.saveFilter();
    this.mainForm.submit();
  },
  submitGroupSelection: function()
  {
      this.mainForm.bpid.value = 70203;

      this.saveFilter();

      // Validera minst en kurs vald ..
      var me = this;
      var numParticipants = 0;
      this.selectedItems.each(function(pair)
                              {
                                numParticipants = numParticipants + pair.value;
                              });
       if(numParticipants == 0)
       {
           alert(this.getText("Please choose number of students on at least one course"));
           return false;
       }
       this.mainForm.submit();
  },
  onCourseParticipantsChanged: function(courseId,numParticipans)
  {
      if(numParticipans > 0)
          this.selectedItems[courseId] = numParticipans;
      else
          this.selectedItems.remove(courseId);
          
      this.doFilter();
  },
  onMoreInfo: function(courseId,expanded)
  {
    if(expanded)
        this.expandedItems[courseId] = true;
    else
        this.expandedItems.remove(courseId);
  },
  isExpanded: function(courseId)
  {
    return this.expandedItems[courseId];
  },
  getNumSelectedParticipants: function(courseId)
  {
      var v = this.selectedItems[courseId];

      if(v)
          return v;
      else
          return 0;
  }
};
SkiSchoolCourseDayScheduleRequest = Class.create();
SkiSchoolCourseDayScheduleRequest.prototype =
{
    /**
     *
     * Parameters:
     * site           The site to search on [salen/are ..]
     * lang           The isolanguage code
     * isoWeek        Period, season, week
     */
    initialize: function(site,lang,isoWeek,options)
    {
       this.options = options;
       this.site = site;

       var p = $H({ site: site, lang: lang, isoWeek: isoWeek});
       try
       {
           var r = new Ajax.Request('/app/projects/common/templates/skidskola/private/searchapi.php',{method: 'get',parameters: p, onSuccess: _onSuccess.bind(this), onFailure: _onFailure.bind(this) });
       }
       catch(e)
       {
           alert('Exception');
       }
    }
};
/* ===================== End Step 2 ====================================*/

/* ===================== Start Step 3 ==================================*/
Object.extend(Array.prototype, {
  intersect: function(array){
    return this.findAll( function(token){ return array.include(token) } );
  }
});

SkiSchoolScheduleController = Class.create();
SkiSchoolScheduleController.prototype =
{
  initialize: function(mainForm,sameTeacherElement,numElement,totalElement,firstPriceElement,othersPriceContainerElement,otherPriceElement)
  {
    this.mainForm = mainForm;

    this.lessons =$A();
    this.sameTeacherElement = sameTeacherElement;
    this.numElement = numElement;
    this.numElement.onclick = this.onNumChanged.bind(this);

    this.totalElement = totalElement;
    this.firstPriceElement = firstPriceElement;
    this.othersPriceContainerElement = othersPriceContainerElement;
    this.otherPriceElement = otherPriceElement;

    this.selectedTeachers = null;
  },
  addLesson: function(lesson)
  {
    lesson.setController(this);
    this.lessons[this.lessons.length] = lesson;
  },
  init: function()
  {
      this.sameTeacherElement.onclick = this.onSameTeacherClicked.bind(this);

      this.lessons.each(function(x) { x.init(); });
      this.refresh();
  },
  onSameTeacherClicked: function()
  {
    // OK, kolla att det går ..?
    if(this.selectedTeachers != null)
    {
      var s = this._getSelectedTeachers();

      if(s.size() == 0)
      {
        alert(this.getText('TXTXBOKSS04','R2'));
        return false;
      }
    }
    this.refresh();
  },
  onNumChanged: function()
  {
    this.refreshPrices();
  },
  refresh: function()
  {
      this.selectedTeachers = this._getSelectedTeachers();
      this.lessons.each(function(x) { x.refresh(); });

      this.refreshPrices();
  },
  refreshPrices: function()
  {
    // OK, we calculate ..
    var me = this;
    var selectedLessons = $A();

    var firstPersonStPrice = 0;
    var otherPersonStPrice = 0;

    this.lessons.each(function(x)
                        {
                          if(x.isSelected())
                          {
                            firstPersonStPrice = firstPersonStPrice + x.firstPrice;
                            otherPersonStPrice = otherPersonStPrice + x.normalPrice;
                          }
                        });
    // OK, handle price logic
    var numPersons = this.numElement.value;
    var firstPersonTotal = 0;
    var otherPersonTotal = 0;

    if(numPersons > 0)
    {
      firstPersonTotal = firstPersonStPrice;

      if(numPersons > 1)
          otherPersonTotal = otherPersonStPrice*(numPersons - 1);
    }

    // OK, update elements ..
    this.firstPriceElement.update('' + firstPersonTotal);

    if(otherPersonTotal > 0)
    {
        this.othersPriceContainerElement.show();
        this.otherPriceElement.update('' + otherPersonTotal);
    }
    else
        this.othersPriceContainerElement.hide();

    this.totalElement.update('' + (firstPersonTotal + otherPersonTotal));
  },
  onLessonClicked: function(lesson)
  {
    this.refresh();
  },
  _getSelectedTeachers: function()
  {
      var me = this;
      var selectedTeachers = null;

      this.lessons.each(function(x)
                        {
                          if(x.isSelected())
                          {
                            if(selectedTeachers == null)
                                selectedTeachers = x.teachers;
                            else
                                selectedTeachers = selectedTeachers.intersect(x.teachers);
                          }
                        });
      return selectedTeachers;
  },
  _getSelectedLessons: function()
  {
      var lessons = $A();

      this.lessons.each(function(x)
                        {
                          if(x.isSelected())
                          {
                            lessons[lessons.length] = x;
                          }
                        });
      return lessons;
  },
  getTeachersAllowed: function()
  {
    if(this.sameTeacherElement.checked)
        return this.selectedTeachers;
    else
        return null;
  },
  submit: function()
  {
    var l = this._getSelectedLessons();

    if(l.length > 0)
    {
      this.mainForm.submit();
    }
    else
    {
        alert(this.getText('TXTXBOKSS05','R2'));
        return false;
    }
  }
};
SkiSchoolScheduleLesson = Class.create();
SkiSchoolScheduleLesson.prototype =
{
  initialize: function(view,teachers,firstPrice,normalPrice)
  {
    this.view = view;
    this.teachers = teachers;
    this.firstPrice = firstPrice;
    this.normalPrice = normalPrice;
    this.ctrl = null;
  },
  setController: function(ctrl)
  {
    this.ctrl = ctrl;
  },
  init: function()
  {
      // lets bind and init events
      var ip = this.view.getElementsBySelector('input');
      if(ip.size() > 0)
      {
          this.inputElement = ip[0];

          this.inputElement.onclick = this.onClick.bind(this);
          this.inputElement.disabled = false;
      }
  },
  onClick: function()
  {
      if(this.ctrl)
          return this.ctrl.onLessonClicked(this);
      else
          return false;
  },
  refresh: function()
  {
    if(this.inputElement.checked)
      this.view.addClassName("checked");
    else
    {
      this.view.removeClassName("checked");
      var allowedTeachers = this.ctrl.getTeachersAllowed();

      if(allowedTeachers == null)
      {
        // Meaning everyone allowed
        this._enable();
      }
      else
      {
          var a = this.teachers.intersect(allowedTeachers);

          if(a.size() > 0)
              this._enable();
          else
              this._disable();
      }
    }
  },
  _enable: function()
  {
    this.inputElement.disabled = false;
  },
  _disable: function()
  {
    this.inputElement.disabled = true;
  },
  isSelected: function()
  {
    return this.inputElement.checked;
  }
};

/* ========================= End step 3 ======================== */

/* ========================= Start step 4 ====================== */
ageGroup=function(lower,upper)
{
  this.lower = lower;
  this.upper = upper;
}
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;
      }
    }
  }
}

SkiSchoolParticipantsController = Class.create();
SkiSchoolParticipantsController.prototype =
{
  initialize: function(containerElement,site,lang,minParticipant,maxParticipant,mainForm,addLink,formTemplateString,firstStudentPriceElement,secondStudentPriceElement,secondStudentPriceContainerElement,partSumElement,totalSumElement,firstPrice,secondPrice,firstDate)
  {
    this.view = containerElement;
    this.site = site;
    this.lang = lang;
    this.minimum = minParticipant;
    this.maximum = maxParticipant;
    this.form = mainForm;
    this.formTemplate = new Template(formTemplateString);
    this.firstStudentPriceElement = firstStudentPriceElement;
    this.secondStudentPriceElement = secondStudentPriceElement;
    this.secondStudentPriceContainerElement = secondStudentPriceContainerElement;
    this.partSumElement = partSumElement;
    this.totalSumElement = totalSumElement;

    this.nextParticipantId = 1;
    this.participants = $H();

    this.addLink = addLink;
    this.firstStudentPrice = firstPrice;
    this.secondStudentPrice = secondPrice;

    this.firstDate = firstDate;

    this.calendar = new CalendarAPI(this.site,this.lang,'skidskola');
    this.validAgeGroups = null;
  },
  init: function(toStart)
  {
    // OK, we create our forms
    for(var i = 0; i < toStart;i++)
      this.addParticipant();

    this.addLink.onclick = this.addParticipant.bind(this);

    this.participants.each(function(x) { x.value.focusFirstName(); throw $break; });

  },
  setPrices: function(first,second)
  {
    this.firstStudentPrice = first;
    this.secondStudentPrice = second;
  },
  addParticipant: function()
  {
      if(this.participants.size() > this.maximium)
          return;

    // Create html ..
      var index = this.nextParticipantId++;
      myVars = {pIndex:  index };
      var div = document.createElement('div');
      div = Element.extend(div);
      div.update(this.formTemplate.evaluate(myVars));
      this.view.appendChild(div);

      var pc = new SkiSchoolParticipantController(index,this,div,this.site,this.lang);
      pc.init();

      this.participants[index] = pc;

      // OK, shall we show the add butt ..
      if(this.participants.size() >= this.maximum)
          this.addLink.hide();

      this.refreshPrices();

      return pc;
  },
  removeParticipant: function(id)
  {
     if(this.participants.size() > 1)
     {
        var p = this.participants[id];

        if(p)
        {
          p.destroy();
  //        this.participants.unset(id);
          this.participants.remove(id);
        }

        if(this.participants.size() < this.maximum)
            this.addLink.show();
     }
     this.refreshPrices();
  },
  setValidAgeGroups: function(validAgeGroups)
  {
    this.validAgeGroups = validAgeGroups;
  },
  refreshPrices: function()
  {
      var secondPrice = 0;
      var total = 0;

      var num = this.participants.size();

      this.firstStudentPriceElement.update('' + this.firstStudentPrice);

      if(num > 1)
      {
        secondPrice = (this.secondStudentPrice*(num -1));
        this.secondStudentPriceElement.update('' + secondPrice);
        this.secondStudentPriceContainerElement.show();
      }
      else
      {
        secondPrice = 0;
        this.secondStudentPriceContainerElement.hide();
      }
      total = this.firstStudentPrice + secondPrice;

      this.partSumElement.update('' + total);
      this.totalSumElement.update('' + total);
  },
  _validate: function(participant)
  {
     // OK, lets validate ..
     var firstName = participant.getFirstName();
     var lastName = participant.getLastName();
     var birthDate = participant.getBirthDate();

     if(firstName == null || firstName.length == 0)
     {
       alert(participant.getCaption() + ', ' + this.getText('Specify firstname'));
       participant.focusFirstName();
       return false;
     }
     if(lastName == null || lastName.length == 0)
     {
       alert(participant.getCaption() + ', ' + this.getText('Specify lastname'));
       participant.focusLastName();
       return false;
     }

     if(!isDate(birthDate))
     {
         alert(participant.getCaption() + ', ' + this.getText('Invalid birthdate'));
         participant.focusBirthDate();
         return false;
     }

     // OK, kolla ålders grupp ..
     var age = this.calendar.getAge(birthDate,this.firstDate)
     if(this.validAgeGroups != null && this.validAgeGroups.length > 0)
     {
       // OK, lets check ..
       var validAge = false;
       for(var i = 0; i < this.validAgeGroups.length;i++)
       {
         if(age >= this.validAgeGroups[i].lower && age <= this.validAgeGroups[i].upper)
         {
           validAge = true;
           break;
         }
       }

       if(!validAge)
       {
         alert(participant.getCaption() + ', ' + this.getText('TXTXBOKSS07','R2'));
         participant.focusBirthDate();
         return false;
       }
     }

     return true;

  },
  submit: function()
  {
    me = this;
    var valid = true;
    this.participants.each(function(pair)
                           {
                             if(!valid)
                                 throw $break;

                             valid = me._validate(pair.value);
                           });

    if(valid)
        this.form.submit();
  }
};
SkiSchoolParticipantController = Class.create();
SkiSchoolParticipantController.prototype =
{
  initialize: function(id,parent,view,site,lang)
  {
    this.id = id;
    this.ctrl = parent;
    this.view = view;
    this.site = site;
    this.lang = lang;

    this.firstName = null;
    this.lastName = null;
    this.removeLink = null;
    
    this.yy = null;
    this.mm = null;
    this.dd = null;

    this.caption = null;
    
    this.genderMale = null;
    this.genderFemale = null;

  },
  init: function()
  {
    // Find our stuff ..
    this.firstName = this._getOne('input.ip_firstname');
    this.lastName = this._getOne('input.ip_lastname');
    this.removeLink = this._getOne('a.deleteicon');
    this.yy = this._getOne('select.ip_year');
    this.mm = this._getOne('select.ip_month');
    this.dd = this._getOne('select.ip_day');
    
    this.genderMale = this._getOne('input.ip_male');
    this.genderFemale = this._getOne('input.ip_female');

    this.caption = this._getOne('h3');
    this.caption = this.caption.firstChild.nodeValue;

    this.removeLink.onclick = this.onRemove.bind(this);

  },
  getCaption: function()
  {
    return this.caption;
  },
  getFirstName: function()
  {
    return this.firstName.value;
  },
  setFirstName: function(fn)
  {
      this.firstName.value = fn;
  },
  getLastName: function()
  {
    return this.lastName.value;
  },
  setLastName: function(fn)
  {
      this.lastName.value = fn;
  },
  getGender: function()
  {
    if(this.genderMale && this.genderFemale)
    {
      if(this.genderMale.checked)
          return "M";

      if(this.genderFemale.checked)
          return "F";
    }
    return "";
  },
  setGender: function(gender)
  {
    if(this.genderMale && this.genderFemale)
    {
      if(gender == "M")
          this.genderMale.checked = true;

      if(gender == "F")
          this.genderFemale.checked = true;
    }
  },
  isGenderMandatory: function()
  {
    return this.genderMale && this.genderFemale;
  },
  getBirthDate: function()
  {
      return getSelectedValue(this.yy) + '-' + getSelectedValue(this.mm) + '-' + getSelectedValue(this.dd);
  },
  setBirthDate: function(bd)
  {
    selectValue(this.yy,bd.substring(0,4));
    selectValue(this.mm,bd.substring(5,7));
    selectValue(this.dd,bd.substring(8,10));
  },
  focusFirstName: function()
  {
    this.firstName.focus();
  },
  focusLastName: function()
  {
    this.lastName.focus();
  },
  focusBirthDate: function()
  {
    this.yy.focus();
  },
  onRemove: function()
  {
    this.ctrl.removeParticipant(this.id);
    return false;
  },
  _getOne: function(selector)
  {
    var l = this.view.getElementsBySelector(selector);
    if(l && l.size() >= 1)
        return l[0];
    else
        return null;
  },
  destroy: function()
  {
    this.view.remove();
  }
};

/* ========================= End step 4 ================================= */

SkiSchoolPrivateDataSource = Class.create();
SkiSchoolPrivateDataSource.prototype =
{
  initialize: function(site,lang,isoWeek)
  {
    this.site = site;
    this.lang = lang;
    this.isoWeek = isoWeek;
    
    this.loadCallBack = null;
  },
  load: function(loadedCallback)
  {
      this.loadCallBack = loadedCallback;
      new SkiSchoolCourseDayScheduleRequest(this.site,this.lang,this.isoWeek,{onSuccess: this.onSearchComplete.bind(this)});
  },
  onSearchComplete: function(r,res)
  {
    if(this.loadCallBack)
        this.loadCallBack(res);
  }
};

SkiSchoolGroupResultView = Class.create();
SkiSchoolGroupResultView.prototype =
{
  initialize: function(view)
  {
    this.view = view;
    this.sortingColumns = $H();
    
    this.MAXMEETINGPLACELENGTH = 20;
  },
  setController: function(c)
  {
      this.controller = c;
  },
  refresh: function()
  {
      // Check controller state
      myS = this.controller.getState();
      switch(myS)
      {
          case 0 :
          var docFragment = document.createDocumentFragment();
          var table = document.createElement("table");
          table.className = "courseTable";
          table.cellSpacing = "0";
          table.cellPadding = "0";

          var head = document.createElement("thead");
          var trElem, thElem, tdElem, txtNode, aNode, tmpNode,div,tbodyElem;

          // The head
          trElem = document.createElement("tr");

          this._createColumnHead(trElem,"Destination",1);
          this._createColumnHead(trElem,"CourseName",2);
          this._createColumnHead(trElem,"Level",3);
          this._createColumnHead(trElem,"Days",4, 100);
          this._createColumnHead(trElem,"Coursetime",5);
          this._createColumnHead(trElem,"Location",6);
          this._createColumnHead(trElem,"Free",7);
          this._createColumnHead(trElem,"Price",8);

          thElem = document.createElement("th");
          thElem.scope = "col";
          thElem.noWrap = "nowrap";
          trElem.appendChild(thElem);

          head.appendChild(trElem);

          table.appendChild(head);

          // Create the body
          tbodyElem = document.createElement("tbody");
          table.appendChild(tbodyElem);

          // OK, now our data, first we do the selected (if any)
          var data = this.controller.getSelectedRows();
          num = data.length;
          var extraCls = "";

          if(num > 0)
          {
            for(var i = 0; i < num; i++)
            {
                if(i % 2)
                    extraCls = "odd";
                else
                    extraCls = "";
                this._createRow(tbodyElem,data[i],extraCls);
            }

            // OK, a nice little separator
            trElem = document.createElement("tr");
            trElem.className = "separator";
            tdElem = document.createElement("td");
            tdElem.colSpan = 9;
            trElem.appendChild(tdElem);
            tbodyElem.appendChild(trElem);
          }

          // We create some kind of separator ..

          data = this.controller.getDisplayRows();
          num = data.length;

          var extraCls = "";

          for(var i = 0; i < num; i++)
          {
              if(i % 2)
                  extraCls = "odd";
              else
                  extraCls = "";
              this._createRow(tbodyElem,data[i],extraCls);
          }

          this.view.update('');
          this.view.appendChild(table);
          // OK, now lets show how we sort
          var currentSort = this.controller.getCurrentSort();
          var currentSortAsc = this.controller.getCurrentSortAsc();

          if(currentSort > 0)
          {
              v = this.sortingColumns[currentSort];

              if(v)
              {
                  v = $(v);
                  v.addClassName("selected");

                  if(currentSortAsc)
                      v.addClassName("asc");
                  else
                      v.addClassName("desc");
              }
          }
          break;

          case 1 :
          break;

          case 2 :
          this.view.update('');
          break;

          default:
      }
  },
  _createColumnHead: function(trElem,nameKey,sortIndex,width)
  {
      var thElem, txtNode, aNode;

      thElem = document.createElement("th");
      thElem.scope = "col";
      thElem.noWrap = "nowrap";
      if(typeof(width) != "undefined")
          thElem.width = width + "px";

      aNode = document.createElement("a");
      aNode.className = "sortable";

      aNode.onclick = this.selectSort.bind(this,sortIndex);
      aNode.title = this.controller.getText("TXTXBOKSS" + (21 + sortIndex),"R2");

      txtNode = document.createTextNode(this.controller.getText(nameKey));
      aNode.appendChild(txtNode);
      thElem.appendChild(aNode);
      trElem.appendChild(thElem);
      this.sortingColumns[sortIndex] = thElem;
  },
  _createRow: function(bodyElement,record,extraCls)
  {
      var trElem, thElem, tdElem, txtNode, aNode, imgNode,spanNode,div,tbodyElem;

      trElem = document.createElement("tr");

      if(typeof(extraCls) != 'undefined')
          trElem.className = extraCls;

      // Resmål
      tdElem = document.createElement("td");
      txtNode = document.createTextNode(record[1]);
      tdElem.appendChild(txtNode);
      trElem.appendChild(tdElem);


      // Kursnamn
      tdElem = document.createElement("td");
      tdElem.nowrap = "nowrap";

      aNode = document.createElement("a");
      aNode.id = "a" + record[0];

      if(this.controller.isExpanded(record[0]))
          aNode.className = "itemFold";
      else
          aNode.className = "itemExpand";

      txtNode = document.createTextNode(record[2]);
      aNode.appendChild(txtNode);
      aNode.onclick = this.onMoreInfo.bind(this,record[0]);
      tdElem.appendChild(aNode);
      trElem.appendChild(tdElem);

      // Nivå
      tdElem = document.createElement("td");
      tdElem.align = "center";
      div = document.createElement("div");
      div.className = record[3];
      tdElem.appendChild(div);
      trElem.appendChild(tdElem);

      // Dagar
      tdElem = document.createElement("td");
      tdElem.className = "coursedates";

//6 = måndag; 0 = söndag
      var startDay = 1;

      for(var day = 0; day < 9; day++)
      {
        div = document.createElement("div");

        dayName = this.controller.getText('day' + startDay);

        if( 0x01<<day & record[4] )
           cls = "s" + dayName;
        else
           cls = "n" + dayName;

        div.className = "calendarDay " + cls;
        tdElem.appendChild(div);
        // Add
        startDay--;
        if(startDay < 0)
            startDay = 6;
      }
      trElem.appendChild(tdElem);

      // Tid
      tdElem = document.createElement("td");
      tdElem.style.whiteSpace = "nowrap";
      txtNode = document.createTextNode(record[5]);
      tdElem.appendChild(txtNode);
      trElem.appendChild(tdElem);

      // Mötesplats
      tdElem = document.createElement("td");
/*      tdElem.style.whiteSpace = "nowrap";
      if(record[6].length > this.MAXMEETINGPLACELENGTH)
      {
        mp = record[6].substr(0,this.MAXMEETINGPLACELENGTH) + "...";
        tdElem.title = record[6];
        txtNode = document.createTextNode(mp);

      }
      else
          txtNode = document.createTextNode(record[6]);
*/
      txtNode = document.createTextNode(record[6]);
      tdElem.appendChild(txtNode);
      trElem.appendChild(tdElem);

      // Ledig / inte
      tdElem = document.createElement("td");
      tdElem.align = "center";
      txtNode = document.createTextNode(record[8] + "(" +record[9]+")");
      tdElem.appendChild(txtNode);
      if(record[8] == 0)
          tdElem.style.textDecoration = "line-through";

      trElem.appendChild(tdElem);

      // Pris
      tdElem = document.createElement("td");
      tdElem.style.whiteSpace = "nowrap";
      txtNode = document.createTextNode(record[7]);
      tdElem.appendChild(txtNode);
      trElem.appendChild(tdElem);

      // Välj
      tdElem = document.createElement("td");
      div = document.createElement("div");
      div.id = "d" + record[0];
      if(this.controller.isExpanded(record[0]))
          div.className = "expandItemLink";
      else
          div.className = "foldItemLink";

      div.onclick = this.onMoreInfo.bind(this,record[0]);
      tdElem.style.padding = "0px";
      tdElem.appendChild(div);
      trElem.appendChild(tdElem);

      bodyElement.appendChild(trElem);

      // OK, create hidden table row for details
      trElem = document.createElement("tr");
      trElem.id = record[0];
      if(!this.controller.isExpanded(record[0]))
          trElem.style.display = "none";

      tdElem = Element.extend(document.createElement("td"));
      tdElem.colSpan = 9;
      tdElem.update(record[17]);
      if(record[8] > 0)
      {
        var selectElem = document.createElement("select");
        selectElem.name = "groups[" + record[0] + "]";
        selectElem.onchange = this.onSelectChange.bind(this,selectElem,record[0]);

        var o = document.createElement("option");
        o.value = 0;
        txtNode = document.createTextNode(this.controller.getText('Select number of participants'));
        o.appendChild(txtNode);
        selectElem.appendChild(o);
        var selectedParticipants = this.controller.getNumSelectedParticipants(record[0]);

        for(var i = 0; i < record[8];i++)
        {
            o = document.createElement("option");
            o.value = (i + 1);
            txtNode = document.createTextNode('' + (i + 1));
            o.appendChild(txtNode);
            selectElem.appendChild(o);
        }
        tdElem.appendChild(selectElem);

        div = document.createElement("div");
        div.className = "reserveLink";
        aNode = document.createElement("a");
        aNode.onclick = this.controller.submitGroupSelection.bind(this.controller);
        txtNode = document.createTextNode(this.controller.getText('Reserve selected courses'));
        aNode.appendChild(txtNode);
        txtNode = document.createTextNode(this.controller.getText('TXTXBOKSS31','R2'));
        div.appendChild(aNode);
        div.appendChild(txtNode);

        tdElem.appendChild(div);

        if(selectedParticipants > 0)
        {
            selectElem.selectedIndex = selectedParticipants;

        }
        else
            div.style.display = "none";


      }

      tdElem.className = "detail";
      trElem.appendChild(tdElem);
      trElem.appendChild(tdElem);
      bodyElement.appendChild(trElem);

  },
  selectSort: function(column)
  {
      var currentSort = this.controller.getCurrentSort();
      var currentSortAsc = this.controller.getCurrentSortAsc();

      if(column == currentSort)
      {
          // OK, toggle order
          this.controller.setSort(currentSort,!currentSortAsc);
      }
      else
      {
          // New sort
          this.controller.setSort(column,false);
      }
  },
  onMoreInfo: function(courseId)
  {
    var e = $(courseId);
    var expanded = (e.style.display == "none");
    var aElement = $("a" +courseId);
    var dElement = $("d" +courseId);

    if(expanded)
    {
        e.style.display = "";

        aElement.className = "itemFold";
        dElement.className = "expandItemLink";
    }
    else
    {
        e.style.display = "none";
        aElement.className = "itemExpand";
        dElement.className = "foldItemLink";
    }

    this.controller.onMoreInfo(courseId,expanded);
  },
  onSelectChange: function(selectBox,courseId)
  {
      var numParticipants = parseInt(selectBox.options[selectBox.selectedIndex].value);

      // Hide / show div
      var e = $(courseId);
      var l = e.getElementsBySelector("div.reserveLink");
      var div = null;
      if(l && l.size() >= 1)
          div = l[0];

      if(numParticipants > 0)
          div.style.display = "";
      else
          div.style.display = "none";

      this.controller.onCourseParticipantsChanged(courseId,numParticipants);
  }
};

SkiSchoolGroupDataSource = Class.create();
SkiSchoolGroupDataSource.prototype =
{
  initialize: function(site,lang,isoWeek,areas)
  {
    this.site = site;
    this.lang = lang;
    this.isoWeek = isoWeek;

    this.loadCallBack = null;
    this.areas = areas;
  },
  load: function(loadedCallback)
  {
      this.areasToDo = $A();
      for(i = 0; i < this.areas.length; i++)
          this.areasToDo[i] = $H({ areaCode: this.areas[i], done: false});

      this.loadCallBack = loadedCallback;

      for(i = 0; i < this.areasToDo.length; i++)
          new SkiSchoolGroupCoursesRequest(this.site,this.lang,this.isoWeek,this.areasToDo[i].areaCode,{onSuccess: this.onAreaSearchComplete.bind(this)});

//      new SkiSchoolCourseDayScheduleRequest(this.site,this.lang,this.isoWeek,{onSuccess: this.onSearchComplete.bind(this)});
  },
  onAreaSearchComplete: function(r,res)
  {
    this.areasToDo.each(function(x) { if(x.areaCode == res.areaCode){ x.done = true; x.result = res; }});

    // all done ?
    var done = true;

    this.areasToDo.each(function(x) { done = (done && x.done); });

    if(done)
    {
        r = $A();
        this.areasToDo.each(function(s) { if(s.result.rows != null) { r = r.concat(s.result.rows); } });

        if(this.loadCallBack)
            this.loadCallBack({num: r.length,rows: r});
    }
  }
};

SkiSchoolGroupCoursesRequest = Class.create();
SkiSchoolGroupCoursesRequest.prototype =
{
    /**
     *
     * Parameters:
     * site           The site to search on [salen/are ..]
     * lang           The isolanguage code
     * isoWeek        Period, season, week
     * options        Ajax options
     * area           areaCode to load
     */
    initialize: function(site,lang,isoWeek,area,options)
    {
       this.options = options;
       this.site = site;

       var p = $H({ site: site, lang: lang, isoWeek: isoWeek, areaCode: area});
       try
       {
           var r = new Ajax.Request('/app/projects/common/templates/skidskola/group/searchapi.php',{method: 'get',parameters: p, onSuccess: _onSuccess.bind(this), onFailure: _onFailure.bind(this) });
       }
       catch(e)
       {
           alert('Exception');
       }
    }
};

SkiSchoolGroupController = Class.create();
SkiSchoolGroupController.prototype =
{
  initialize: function(baseId,containerElement,site,lang,minParticipant,maxParticipant,mainForm,addLink,formTemplateString,partSumElement,studentPrice,firstDate,numToStartWith,courseName)
  {
    this.view = containerElement;
    this.site = site;
    this.lang = lang;
    this.minimum = minParticipant;
    this.maximum = maxParticipant;
    this.form = mainForm;
    this.formTemplate = new Template(formTemplateString);
    this.partSumElement = partSumElement;
    this.numToStartWith = numToStartWith;
    this.courseName = courseName;

    this.baseId = baseId;
    this.nextParticipantId = baseId;
    this.participants = $H();

    this.addLink = addLink;
    this.studentPrice = studentPrice;
    this.firstDate = firstDate;

    this.calendar = new CalendarAPI(this.site,this.lang,'skidskola');
    this.validAgeGroups = null;
    
    this.onPriceChanged = null;
  },
  init: function()
  {
    // OK, we create our forms
    for(var i = 0; i < this.numToStartWith;i++)
      this.addParticipant();

    this.addLink.onclick = this.addParticipant.bind(this);

    this.participants.each(function(x) { x.value.focusFirstName(); throw $break; });
  },
  addParticipant: function()
  {
      if(this.participants.size() > this.maximium)
          return;

    // Create html ..
      var index = this.nextParticipantId++;
      myVars = {pIndex:  index, pNum: (index - this.baseId + 1) };
      var div = document.createElement('div');
      div = Element.extend(div);
      div.update(this.formTemplate.evaluate(myVars));
      this.view.appendChild(div);

      var pc = new SkiSchoolParticipantController(index,this,div,this.site,this.lang);
      pc.init();

      this.participants[index] = pc;

      // OK, shall we show the add butt ..
      if(this.participants.size() >= this.maximum)
          this.addLink.hide();

      this.refreshPrices();

      return pc;
  },
  removeParticipant: function(id)
  {
     if(this.participants.size() > 1)
     {
        var p = this.participants[id];

        if(p)
        {
          p.destroy();
  //        this.participants.unset(id);
          this.participants.remove(id);
        }

        if(this.participants.size() < this.maximum)
            this.addLink.show();
     }
     this.refreshPrices();
  },
  setValidAgeGroups: function(validAgeGroups)
  {
    this.validAgeGroups = validAgeGroups;
  },
  refreshPrices: function()
  {
      this.partSumElement.update('' + this.getTotal());

      if(this.onPriceChanged)
          this.onPriceChanged();
  },
  setOnPriceChanged: function(callback)
  {
      this.onPriceChanged = callback;
  },
  getTotal: function()
  {
      var num = this.participants.size();
      return this.studentPrice*num;
  },
  _validate: function(participant)
  {
     // OK, lets validate ..
     var firstName = participant.getFirstName();
     var lastName = participant.getLastName();
     var birthDate = participant.getBirthDate();

     if(firstName == null || firstName.length == 0)
     {
       alert(this.courseName + ', ' +participant.getCaption() + ', ' + this.getText('Specify firstname'));
       participant.focusFirstName();
       return false;
     }
     if(lastName == null || lastName.length == 0)
     {
       alert(this.courseName + ', ' + participant.getCaption() + ', ' + this.getText('Specify lastname'));
       participant.focusLastName();
       return false;
     }

     if(!isDate(birthDate))
     {
         alert(this.courseName + ', ' +participant.getCaption() + ', ' + this.getText('Invalid birthdate'));
         participant.focusBirthDate();
         return false;
     }

     if(participant.isGenderMandatory() && !participant.getGender())
     {
         alert(this.courseName + ', ' +participant.getCaption() + ', ' + this.getText('Please choose a gender'));
         return false;
     }
     // OK, kolla ålders grupp ..
     var age = this.calendar.getAge(birthDate,this.firstDate)
     if(this.validAgeGroups != null && this.validAgeGroups.length > 0)
     {
       // OK, lets check ..
       var validAge = false;
       for(var i = 0; i < this.validAgeGroups.length;i++)
       {
         if(age >= this.validAgeGroups[i].lower && age <= this.validAgeGroups[i].upper)
         {
           validAge = true;
           break;
         }
       }

       if(!validAge)
       {
         alert(this.courseName + ', ' +participant.getCaption() + ', ' + this.getText('TXTXBOKSS07','R2'));
         participant.focusBirthDate();
         return false;
       }
     }

     return true;

  },
  validate: function()
  {
    me = this;
    var valid = true;
    this.participants.each(function(pair)
                           {
                             if(!valid)
                                 throw $break;

                             valid = me._validate(pair.value);
                           });
                           
    return valid;
  }
};