// travel calculator namespace
carrentalCalc = Object.beget(isafoldCalculatorPrototype, window.carrentalCalc||{});

// IF we're going to RUN ??
Event.add(document, 'ready', function(e){

  var theForm =   DOM.$('carrentalcalc_form'),
      _calc =     carrentalCalc,
      _dataset =  _calc.dataset,
      lang =      DOM.getLang(theForm);
  
  lang =  _dataset.texts[lang] ? lang : en;
  var _txt =      _dataset.texts[lang];  // not used yet...


  if (theForm)
  {

    // extend the carrentalCalc object
    Object.merge(_calc, {

      _theForm:  theForm,

      // get price
      calculate:  function () {

        var ds         = this.dataset,
            extras     = this._extraFields,

            numCars    = DOM.getValue('number_of_vehicles'),
            numDrivers = DOM.getValue('extra_drivers'),

            fromDate   = (datePicker.fields['start_date']||{}).dateActive,
            toDate     = (datePicker.fields['end_date']||{}).dateActive,

            fromTime   = DOM.getValue('start_time'),
            toTime     = DOM.getValue('end_time'),
            // just the hours
            fromHours  = fromTime.replace(/\D/g,'').substr(0,2).toInt(),
            toHours    = toTime.replace(/\D/g,'').substr(0,2).toInt(),

            pickupVal  = DOM.getValue('delivery_location'),
            dropoffVal = DOM.getValue('return_location'),

            msInADay   = 24*60*60*1000,
            numDays    = 0;

        if (fromDate && toDate)
        {
          // calculate the number of days selected.
          numDays += Math.ceil( (toDate.getTime() - fromDate.getTime()) / msInADay );
          // add one day if the customer wants to return later in the day than he picked up
          numDays += (toHours > fromHours) ? 1 : 0;

          if (numDays < 1)
          {
            ;;;window.console&&console.log('user selected negative date range');
            return;
          }

          // now let's calculate the costs
          var isCost = 0;
          var extraCost = 0;
          var bbseat = 0;

          // Start with the price of the car rental
          var carDiscount = (numDays > ds.car_discount_mindays) ? ds.car_discount_factor : 0;
          
          ;;;window.console&&console.log( numCars );
          
          if (numDays == 1) {
            isCost += numCars * (ds.prices.oneday * numDays * (1-(carDiscount/100)));
          } else if (numDays > 7) {
            isCost += numCars * (ds.prices.mt8days * numDays * (1-(carDiscount/100)));
          } else {
            isCost += numCars * (ds.prices.car * numDays * (1-(carDiscount/100)));
          }

          // add costs of pickup and dropoff
          extraCost += puCost = ds.prices.pickup_dropoff[pickupVal||'office'];
          extraCost += ds.prices.pickup_dropoff[dropoffVal||'office'];

          // add costs of extra options
          var i = extras.length;
          while (i--)
          {
            if (extras[i].checked)
            {
              
              if (extras[i].name === 'babyseat') {
                //bbseat = ds.prices.extras[extras[i].name] * numDays < (50*ds.currency.eur) ? ds.prices.extras[extras[i].name] * numDays : 50*ds.currency.eur;
                bbseat = ds.prices.extras[extras[i].name] < (50*ds.currency.eur) ? ds.prices.extras[extras[i].name] : 50*ds.currency.eur;
                extraCost += bbseat;
              } else {
                extraCost += ds.prices.extras[extras[i].name] * numDays;
              }

            }
          }
          // add cost of extra drivers...
          extraCost += numDrivers * ds.prices.extradriver;

          this._displayTotalPrice( isCost, extraCost );
        }
      },



      init:  function () {

        this._defaultPreInit();

        autoValidate.validateEachField = 'change';

        var def = this.dataset.defaults;
        DOM.$('start_date').value = datePicker.printDateValue( def.start_date, '%d.%m.%yyyy', lang );
        DOM.$('end_date').value   = datePicker.printDateValue( def.end_date, '%d.%m.%yyyy', lang );

        //jQuery('#start_time').val(def.start_time);
        //jQuery('#end_time').val(def.end_time);

        datePicker.idDefaults['start_date'] = {
            // dateMaxSrc: ['end_date', '-1d'],
            dateMinSrc: def.start_date
          };
        datePicker.idDefaults['end_date'] = {
            dateMinSrc: ['start_date', '1d']
          };

        // hook event for activity display/removal depending on season
        // hook event for activity selector
        // hook events that call for recalculation
        Event.add(DOM.$('start_date'), 'focus', this.calculate, this);
        Event.add(DOM.$('end_date'), 'focus', this.calculate, this);
        Event.add( theForm, (msie?'click':'click'), this.calculate, this);
          /*
        jQuery('#carrentalcalc_form')
              .find('input:text, select')
                  .bind('change', jQuery.proxy(this,'calculate') )
              .end()
              .find('input:checkbox')
                  .bind('click', jQuery.proxy(this,'calculate') );
*/
        this._extraFields = DOM.get('#extraoptions input[type="checkbox"]');

        this._defaultPostInit();

      }



    });

    carrentalCalc.init();


  }

});

