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;
      }
    }
  }
}


RentalController = Class.create();
RentalController.prototype =
{
    initialize: function(form,productIdElement,daysElement,ageGroupElement,data,ageGroups,RentalFilterView,RentalResultView)
    {
      this.form = form;
      this.productIdElement = productIdElement;
      this.daysElement = daysElement;
      this.ageGroupElement = ageGroupElement;

      this.resultSet = data;
      this.ageGroups = ageGroups;
      this.RentalFilterView = RentalFilterView;
      this.RentalFilterView.setRentalController(this);

      this.RentalResultView = RentalResultView;
      this.RentalResultView.setRentalController(this);
      
      this.defaultDays = 0;
    },
    getAgeGroups: function()
    {
      var ag = $H();

      for(var i = 0; i < this.ageGroups.length;i++)
      {
        var code = this.ageGroups[i];
        ag[code] = this.resultSet[code]["desc"];
      }
      return ag;
    },
    getCategories: function(ag)
    {
        var res = $H();
        var a = new Array();

        var group = this.resultSet[ag];
        if(group)
        {
          var products = group["products"];
          for(var i = 0; i < products.length;i++)
          {
            res[products[i]["categoryid"]] = products[i]["category"];
          }
          // Konstruera array och sortera ..

          var i = 0;
          res.each(function(pair) { a[i++] = new RentalCategory(pair.key,pair.value); });
          a.sort(categoriesSorter);
        }
        return a;
    },
    getLevels: function(ag,cat)
    {
        var res = $H();
        var group = this.resultSet[ag];
        var a = new Array();

        if(group)
        {
          var products = group["products"];
          for(var i = 0; i < products.length;i++)
          {
            if(products[i]["categoryid"] == cat)
                res[products[i]["levelid"]] = products[i]["level"];
          }

          var i = 0;
          res.each(function(pair) { a[i++] = new RentalLabel(pair.key,pair.value); });
//          a.sort(labelSorter);
        }
        return a;
    },
    onFilterChanged: function()
    {
        this.RentalResultView.refresh();
    },
    getCurrentSelection: function()
    {
      var ag = this.RentalFilterView.getAgeGroup();
      var category = this.RentalFilterView.getCategory();
      var level = this.RentalFilterView.getLevel();

      var group = this.resultSet[ag];
      var res = $H();

      if(group)
      {
        // For now, return all ..
        var products = group["products"];

        for(var i = 0; i < products.length;i++)
        {
          if(this._matches(category,level,products[i]))
              res[products[i]["id"]] = products[i];
        }
      }

      return res;
    },
    onSelect: function(productId,days,ageGroup)
    {
//      alert('Submit:' + productId + ', dagar:' + days + ' age: ' + ageGroup);

      this.productIdElement.value = productId;
      this.daysElement.value = days;
      this.ageGroupElement.value = ageGroup;

      this.form.submit();
    },
    _matches: function(category,level,p)
    {
      return category == p["categoryid"] && level == p["levelid"];
    },
    init: function()
    {
      this.RentalFilterView.init();
//      this.RentalFilterView.setAgeGroup('VX');
    },
    setFilter: function(ageGroup,categoryId,levelId)
    {
      this.RentalFilterView.setAgeGroup(ageGroup);
      this.RentalFilterView.setCategory(categoryId);
      this.RentalFilterView.setLevel(levelId);
    },
    setDefaultDays: function(days)
    {
      this.defaultDays = days;
      this.RentalResultView.refresh();
    },
    getDefaultDays: function()
    {
      return this.defaultDays;
    }
};
RentalFilterView = Class.create();
RentalFilterView.prototype =
{
    initialize: function(ageGroup,ageGroupContainer,category,categoryContainer,level,levelContainer)
    {
      this.ageGroupElement = ageGroup;
      this.categoryElement = category;
      this.levelElement = level;
      this.ageGroupContainerElement = ageGroupContainer;
      this.categoryContainerElement = categoryContainer;
      this.levelContainerElement = levelContainer;

      Event.observe(this.ageGroupElement,'change',this.onAgeGroupChanged.bindAsEventListener(this));
      Event.observe(this.categoryElement,'change',this.onCategoryChanged.bindAsEventListener(this));
      Event.observe(this.levelElement,'change',this.onLevelChanged.bindAsEventListener(this));
    },
    setRentalController: function(c)
    {
      this.RentalController = c;
    },
    init: function()
    {
        this.ageGroupElement.options.length = 0;
        var ag = this.RentalController.getAgeGroups();
        var me = this;

        this.levelElement.options.length = 0;
        this.levelElement.hide();
        this.levelContainerElement.hide();

        this.categoryElement.options.length = 0;
        this.categoryElement.hide();
        this.categoryContainerElement.hide();

        me.ageGroupElement.options[me.ageGroupElement.options.length] = new Option(this.RentalController.getText('Select agegroup'),"");
        ag.each(function(pair)
        {
            me.ageGroupElement.options[me.ageGroupElement.options.length] = new Option(pair.value,pair.key);
        });
        this.setAgeGroup(me.ageGroupElement.options[0]);
    },
    setAgeGroup: function(ag)
    {
       // OK, försök selecta ..
       selectValue(this.ageGroupElement,ag);
       this.onAgeGroupChanged(null);
    },
    setCategory: function(cat)
    {
       selectValue(this.categoryElement,cat);
       this.onCategoryChanged(null);
    },
    setLevel: function(level)
    {
       selectValue(this.levelElement,level);
       this.onLevelChanged(null);
    },
    getAgeGroup: function()
    {
      return getSelectedValue(this.ageGroupElement);
    },
    getCategory: function()
    {
      return getSelectedValue(this.categoryElement);
    },
    getLevel: function()
    {
      return getSelectedValue(this.levelElement);
    },
    refresh: function()
    {
    },
    onAgeGroupChanged: function(e)
    {
        var ag = this.getAgeGroup();
        if(!ag)
        {
            this.categoryElement.options.length = 0;
            this.categoryElement.hide();
            this.categoryContainerElement.hide();

            this.ageGroupContainerElement.addClassName("smallOrangeArrow");
            return;
        }

        this.ageGroupContainerElement.removeClassName("smallOrangeArrow");

        var cats = this.RentalController.getCategories(ag);
        var me = this;
        var cat = this.getCategory();

        this.categoryElement.show();
        this.categoryContainerElement.show();

        this.categoryElement.options.length = 0;
        me.categoryElement.options[me.categoryElement.options.length] = new Option(this.RentalController.getText("Select ridertype"),"");

        cats.each(function(pair)
        { 
           me.categoryElement.options[me.categoryElement.options.length] = new Option(pair.label,pair.id);
        });
        this.setCategory(cat);

        this.RentalController.onFilterChanged();
    },
    onCategoryChanged: function(e)
    {
        var ag = this.getAgeGroup();

        var cat = this.getCategory();
        if(cat)
            this.categoryContainerElement.removeClassName("smallOrangeArrow");
        else
            this.categoryContainerElement.addClassName("smallOrangeArrow");

        var level = this.getLevel();

        var levels = this.RentalController.getLevels(ag,cat);
        var me = this;
        me.levelElement.options.length = 0;
        if(levels.size() > 1)
            me.levelElement.options[me.levelElement.options.length] = new Option(this.RentalController.getText("Select level"),"");

        levels.each(function(pair)
        {
          me.levelElement.options[me.levelElement.options.length] = new Option(pair.label,pair.id);
        });
        this.setLevel(level);

        if(levels.size() > 1)
        {
            me.levelElement.show();
            me.levelContainerElement.show();
        }
        else
        {
            me.levelElement.hide();
            me.levelContainerElement.hide();
        }

        this.RentalController.onFilterChanged();
    },
    onLevelChanged: function(e)
    {
        var level = this.getLevel();

        if(level)
            this.levelContainerElement.removeClassName("smallOrangeArrow");
        else
            this.levelContainerElement.addClassName("smallOrangeArrow");

        this.RentalController.onFilterChanged();
    }
};

RentalResultView = Class.create();
RentalResultView.prototype =
{
    initialize: function(view,elementTemplate)
    {
      this.view = view;
      this.elementTemplate = elementTemplate;
      this.products = $H();
      this.selections = $H();

    },
    setRentalController: function(c)
    {
      this.RentalController = c;
    },
    refresh: function()
    {
      var resultSet = this.RentalController.getCurrentSelection();

      // Clear ..
      this.view.update('');

      if(resultSet.size() > 0)
      {
        var me = this;
        this.products = $H();
        resultSet.each(
            function(pair)
            {
              var selection = me.selections[pair.value.desc1];
              
              if(!selection)
                selection = me.RentalController.getDefaultDays();

              var rpv = new RentalProductView(me.RentalController,me,pair.value,me.elementTemplate,selection);
              rpv.show(me.view);
              me.products[pair.key] = rpv;
            });
      }
    },
    onPeriodPricesChanged: function(desc1,days)
    {
      this.selections[desc1] = days;
    }
};
RentalProductView = Class.create();
RentalProductView.prototype =
{
  initialize: function(ctrl,RentalResultView,myData,myTemplate,defaultSelection)
  {
    this.data = myData;
    this.template = myTemplate;
    this.RentalController = ctrl;
    this.RentalResultView = RentalResultView;
    this.defaultSelection = defaultSelection;
  },
  show: function(parent)
  {
      var vars = {id: this.data.id};

      // Ok, lets create templates for each result
      var html = this.template.evaluate(vars);
      new Insertion.Bottom(parent,html);

      this.view = $("sh" + this.data.id);
      this.image = $("shImage" + this.data.id);
      this.title = $("shTitle" + this.data.id);
      this.desc = $("shDesc" + this.data.id);
      this.periodPrices = $("shPeriodPrices" + this.data.id);
      this.button = $("shButton" + this.data.id);
      this.buttonLink = $("shButtonLink" + this.data.id);

      this.title.update(this.data.title);

      if(this.data.image)
      {
          this.image.src = this.data.image;
          this.image.show();
          this.image.style.display = "block";
      }

      this.desc.update(this.data.desc);

      // OK, init combo
      var periods = this.data.periods;

      this.periodPrices.options.length = 0;

      this.periodPrices.options[0] = new Option(appLang.getText("Days/price"),"0");

      for(var i = 0; i < periods.length; i++)
      {
         var p = periods[i];
         this.periodPrices.options[this.periodPrices.options.length] = new Option(p.label,p.start + ":" + p.end);
      }

      this._selectValue(this.defaultSelection);
      this.onPeriodPricesChanged();

      Event.observe(this.buttonLink,'click',this.onSelect.bind(this));
      Event.observe(this.periodPrices,'change',this.onPeriodPricesChanged.bind(this));
  },
  onSelect: function()
  {
    var days = this._getSelectedDays();

    if(this.RentalController.onSelect && days > 0)
      this.RentalController.onSelect(this.data.id,days,this.data.ageGroup);
//    else
//        alert('Hårdkodat!: Välj antal dagar');
  },
  onPeriodPricesChanged: function()
  {
      var days = this._getSelectedDays();
/*
      if(days > 0)
      {
          this.button.removeClassName("grey");
          this.button.addClassName("red");
      }
      else
      {
          this.button.removeClassName("red");
          this.button.addClassName("grey");
      }
                                       */
      if(this.RentalResultView.onPeriodPricesChanged)
          this.RentalResultView.onPeriodPricesChanged(this.data.desc1,days);
  },
  _selectValue: function(days)
  {
      for(i = 0; i < this.periodPrices.options.length; i++)
      {
        var startEnd = this.periodPrices.options[i].value;
        var tmp = startEnd.split(":");

        var start = tmp[0];
        var end = tmp[1];

        if(start <= days && days <= end)
        {
            this.periodPrices.selectedIndex = i;
            return;
        }
      }
  },
  _getSelectedDays: function()
  {
    if(this.periodPrices.selectedIndex >= 0)
    {
        var startEnd = this.periodPrices.options[this.periodPrices.selectedIndex].value;
        var tmp = startEnd.split(":");
        if(tmp.size() == 2)
            return tmp[1];
    }
  }
};
function RentalCategory(id,label)
{
  this.id = id;
  this.label = label;
}
function categoriesSorter(a,b)
{
  return a.label > b.label;
}
function RentalLabel(id,label)
{
  this.id = id;
  this.label = label;
}
function labelSorter(a,b)
{
  return a.id > b.id;
}


/* Steg 2 */
RentalController2 = Class.create();
RentalController2.prototype =
{
    initialize: function(site,lang,form,periodLength,periodStart,ageGroupLowerBound,ageGroupUpperBound,basePrice,insurancePrice,helmetPrice,currency)
    {
      this.form = form;
      this.site = site;
      this.lang = lang;
      this.ageGroupLowerBound = ageGroupLowerBound;
      this.ageGroupUpperBound = ageGroupUpperBound;
      this.basePrice = 0 + basePrice;
      this.insurancePrice = 0 + insurancePrice;
      this.helmetPrice = 0 + helmetPrice;
      this.periodLength = periodLength;
      this.periodStart = periodStart;

      this.currency = currency;

      this.calendar = new CalendarAPI(this.site,this.lang,'skiduthyrning');

      this.firstNameElement = $('firstname');
      this.lastNameElement = $('lastname');

      this.lengthElement = $('length');
      this.footlengthElement = $('footlength');

      this.weightElement = $('weight');
      this.sexMaleElement = $('sexMale');
      this.sexFemaleElement = $('sexFemale');

      this.insuranceYesElement = $('insuranceYes');
      this.insuranceNoElement = $('insuranceNo');

      this.helmetYesElement = $('helmetYes');
      this.helmetNoElement = $('helmetNo');

      this.yyyyElement = $('yyyy');
      this.mmElement = $('mm');
      this.ddElement = $('dd');

      this.handingOutDateElement = $('handingOutDate');
      this.handingOutDateLink = $('handingOutDateLink');

      this.skishopElement = $('skishop');

      this.totalElement = $('totalAmount');

      if(this.totalElement)
      {
        // OK, vi skall hålla koll på en summa ..
        if(this.insuranceYesElement)
        {
            Event.observe(this.insuranceYesElement,'click',this.onPriceChanged.bindAsEventListener(this));
            Event.observe(this.insuranceNoElement,'click',this.onPriceChanged.bindAsEventListener(this));
        }

        if(this.helmetYesElement)
        {
            Event.observe(this.helmetYesElement,'click',this.onPriceChanged.bindAsEventListener(this));
            Event.observe(this.helmetNoElement,'click',this.onPriceChanged.bindAsEventListener(this));
        }

        this.onPriceChanged();
      }
      if(this.handingOutDateLink)
          Event.observe(this.handingOutDateLink,'click',this.onChangeDate.bindAsEventListener(this));
    },
    setDate: function(d)
    {
      this.handingOutDateElement.value = d;
    },
    getBirthdate: function()
    {
      return this.yyyyElement.value + '-' + this.mmElement.value + '-' + this.ddElement.value;
    },
    onChangeDate: function(e)
    {
		var obj;

		if(e.currentTarget)
			obj = e.currentTarget;
		else if(window.event.srcElement)
			obj = e.srcElement; // IE

      JT_show('/app/projects/common/templates/calendar/inlineMain.php?KeepThis=true&bLang='+this.lang + '&bSite='+this.site +'&path=/app/projects/common/&activity=skiduthyrning&mode=days&callback=setHandingOutDateFromPopup&name=yep&limitsEndOverride=-' + (this.periodStart -1) + '&TB_iframe=true&height=400&width=300&tooltip=true',obj.id,'');
    },
    onPriceChanged: function(e)
    {
      var sum = this.basePrice;

      // OK, uppdatera pris ..
      if(this.totalElement)
      {
        // OK, vi skall hålla koll på en summa ..
        if(this.insuranceYesElement && this.insuranceYesElement.checked)
            sum = sum + this.insurancePrice;


        if(this.helmetYesElement && this.helmetYesElement.checked)
            sum = sum + this.helmetPrice;

        this.totalElement.update(sum + '&nbsp;' + this.currency);
      }

    },
    submit: function(requestedPid)
    {
      if(this.isValid())
      {
        // OK, allt är giltigt, fixa för postning ..
        if(this.yyyyElement)
        {
          var age = this.calendar.getAge(this.getBirthdate(),this.handingOutDateElement.value);
          this.form.age.value = age;
          this.form.birthdate.value = this.getBirthdate();
        }

        if(requestedPid)
            this.form.redirectPid.value = parseInt(requestedPid);
        else
            this.form.encodedRedirect.value = "";

        // OK, validera
        this.form.submit();
      }
    },
    isValid: function()
    {
      var valid =  this._isNotEmpty(this.firstNameElement,'Please specify your name') &&
                   this._isNotEmpty(this.lastNameElement,'Please specify your name') &&
                   this._isNotEmpty(this.lengthElement,'Please specify your length') &&
                   this._isNotEmpty(this.footlengthElement,'Please specify your footlength') &&
                   this._isNotEmpty(this.weightElement,'Please specify your weight') &&
                   this._isSelected(this.sexMaleElement,this.sexFemaleElement,'Please specify your sex') &&
                   this._isBirthdate('Specify birthdate') &&
                   this._isNotEmpty(this.handingOutDateElement,'Specify handing out date') &&
                   this._isNotEmpty(this.skishopElement,'Please specify place') &&
                   this._isSelected(this.insuranceYesElement,this.insuranceNoElement,'TXTXBOKSK04','R2') &&
                   this._isSelected(this.helmetYesElement,this.helmetNoElement,'TXTXBOKSK05','R2');
                   
      if(!valid)
          return false;
          
      // OK, kolla så att perioden går att lägga i kundkorgen ..
      var opts = $({limitsEndOverride: -1*(this.periodStart-1)});

      var res = this.calendar.validate(this.handingOutDateElement.value,opts);
      if(res == 2)
      {
        alert(appLang.getText('TXTXBOKSK12','R2'));
        return false;
      }

      // OK, funkar åldersgrupp, och har vi den angiven ?
      if(this.yyyyElement)
      {
        var age = this.calendar.getAge(this.getBirthdate(),this.handingOutDateElement.value);
        if(!(age >= this.ageGroupLowerBound && age <= this.ageGroupUpperBound))
        {
          alert(appLang.getText('TXTXBOKSK13','R2'));
          return false;
        }
      }
      
      return true;
    },
    _isNotEmpty: function(e,messageKey)
    {
      if(!e)
          return true;
      
      var val = jQuery.trim(e.value);

      if(val.length == 0)
      {
          alert(appLang.getText(messageKey));
          if(e.focus)
              e.focus();

          return false;
      } 

      if(!e.value)
      {
          alert(appLang.getText(messageKey));
          if(e.focus)
              e.focus();

          return false;
      }

      return true;
    },
    _isSelected: function(e1,e2,messageKey,messageCat)
    {
      if(!e1 || !e2)
          return true;

      if(!e1.checked && !e2.checked)
      {
          alert(appLang.getText(messageKey,messageCat));
          return false;
      }

      return true;
    },
    _isBirthdate: function(message)
    {
        if(!this.yyyyElement)
            return true;

        if(this.yyyyElement.value && this.mmElement.value && this.ddElement.value)
        {
            if(isDate(this.getBirthdate()))
                return true;
            else
            {
               alert(appLang.getText('Invalid birthdate'));
               return false;
            }
        }
        else
        {
          alert(appLang.getText(message));
          return false;
        }
    }
};
PlaceController = Class.create();
PlaceController.prototype =
{
    initialize: function(site,lang,firstDateElement,placeElement,selectItemText,recommendedFetchingPlace)
    {
      this.site = site;
      this.lang = lang;
      this.firstDateElement = firstDateElement;
      this.placeElement = placeElement;
      this.selectItemText = selectItemText;
      this.recommendedFetchingPlace = recommendedFetchingPlace;

      // OK, add listener to firstDate
      Event.observe(this.firstDateElement,'keyup',this.onFirstDateChanged.bindAsEventListener(this));
      
      // And add listener to skishop
      Event.observe($('skishop'),'change',this.onSkishopChange.bindAsEventListener(this));

      this.placesCache = $H();
      this.firstRefresh = true;
      this.defaultPlace = "";
      
    },
    onFirstDateChanged: function(event)
    {
      this.refresh();
    },
    onSkishopChange: function(event)
    {
      this.alertCloseFetchingPlace();      
    },
    refresh: function()
    {           
      if(this.isValidFirstDate())
      {
        // OK, lets refresh utlamningsstalle ..
        places = this.placesCache[this.getDate()];

        if(places && places.length > 0)
           this.refreshPlaces(places);
        else
           this._fetchPlaces();
      }
      else
      {
        this.placeElement.disable();
      }
    },
    refreshPlaces: function(places)
    {  
        // Save selection
        selectedPlace = this.getSelectedPlace();

        this.placeElement.options.length = 0;

        if(places == null)
        {
            alert(this.getText('TXTXBOKSK14','R2'));
        }
        else
        {
          if(places.length > 0)
          {
              if(this.firstRefresh)
              {
                //selectedPlace = this.defaultPlace;
                selectedPlace = this.recommendedFetchingPlace;
                this.firstRefresh = false;                
              }
              if(places.length == 1)
              {
                this.placeElement.options[0] = new Option(places[0][0],places[0][1]);
                this.placeElement.selectedIndex = 0;
              }
              else
              {
                this.placeElement.options[this.placeElement.options.length] = new Option(this.selectItemText,"");

                for(var i = 0; i < places.length;i++)
                  this.placeElement.options[this.placeElement.options.length] = new Option(places[i][0],places[i][1]);

                this.setSelectedPlace(selectedPlace);
              }
              this.alertCloseFetchingPlace();
              this.placeElement.enable();
          }
        }

    },
    alertCloseFetchingPlace: function()
    {
      if(this.getSelectedPlace() == this.recommendedFetchingPlace)
        $('closeFetchingPlaceSelected').style.display = "block";
      else
        $('closeFetchingPlaceSelected').style.display = "none";
    },
    getDate: function()
    {
        return this.firstDateElement.value;
    },
    getSelectedPlace: function()
    {      
      return getSelectedValue(this.placeElement);
    },
    setSelectedPlace: function(place)
    {        
      selectValue(this.placeElement,place);
    },
    setDefaultPlace: function(place)
    {
      this.defaultPlace = place;
    },
    isValidFirstDate: function()
    {
      return isDate(this.getDate());
    },
    _fetchPlaces: function()
    {
        this.placeElement.disable();
        var p = $H({site: this.site,lang: this.lang,firstDate: this.getDate()});
        new Ajax.Request('/app/projects/common/templates/skiduthyrning/api/fetchPlaces.php',{method: 'get',parameters: p,onSuccess: this._onFetchPlacesSuccess.bind(this),onFailure: this._onFetchPlacesFailed.bind(this)});
    },
    _onFetchPlacesSuccess: function(transport)
    {
      try
      {
       res = eval('(' + transport.responseText + ')');
       if(res.result == 0)
       {
         places = res.places;

         if(places && places.length > 0)
         {
           // save in cache
           this.placesCache[res.firstDate] = places;
         }

         // And refresh control
         this.refreshPlaces(places);
       }
       else
       {
         alert(res.errorMessage);
       }
      }
      catch(e)
      {
          alert(e);
      }
    },
    _onFetchPlacesFailed: function()
    {
    }
};


