var MitrePeakOrder = Class.create();

MitrePeakOrder.prototype = {
  initialize: function(current_departure_month, departure_time_hash, package_deal){
    
    this.package_deal = package_deal;
    //this.currency_list = currency_list;
      	
    // Prices
    //this.children_default_price = children_default_price;
    //this.adult_default_price = adult_default_price;
    //this.children_under_water_price = children_under_water_price;
    //this.adult_under_water_price = adult_under_water_price;

    // Object Handles
    this.the_form = $('order_form');
    this.adult_number = $('adult_number');
    this.children_number = $('children_number');
    this.infant_number = $('infant_number');
    this.under_water = $('under_water');
    this.departure_time = $('departure_time');
    this.total_price = $('span_total_price');
    this.form_total_price = $('total_price');
    
    this.departing_time = $('departing_time');
    
    this.adult_ticket_price = $('adult_ticket_price');
    this.child_ticket_price = $('child_ticket_price');
    this.uw_adult_ticket_price = $('uw_adult_ticket_price');
    this.uw_child_ticket_price = $('uw_child_ticket_price');
    
    this.departing_from = $('departing_from');
    this.package_type = $('package_type');
    this.current_month = current_departure_month;
    this.departure_year_hash = departure_time_hash;
    this.departure_time_hash = this.departure_year_hash[$('date_year').getValue()];
		
    // Booking Date
    this.day_names = $A(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']);
    this.year = $('date_year');
    this.month = $('date_month');
    this.day = $('date_day');
    this.day_name = $('day_name');

    this.currency_code_loaded = false;
    this.total_price_loaded = false;
    this.current_day_loaded = false;
    this.init();
  },
  
  init: function() {
    if (this.package_deal) {
      this.departure_time_hash = this.departure_year_hash[this.package_type.getValue()][this.departing_from.getValue()][this.getYearValue()];
    }
    this.addEvents();
    this.current_departure_month;
    //this.setCurrencyListSelect();
    this.update_months();
    this.setCurrentDepartureMonth();
    this.setDepartureTimeSelect();
    if (this.package_deal) {
      this.updateDepartingFromValues();
    }
  },
  
  addEvents: function() {
    // Add Events
    Event.observe(this.the_form, 'submit', function() {
      //after click submit button  
    }.bind(this))
        	
    Event.observe(window, 'load', function() {
      this.bookingDateEventUpdates(); 
    }.bind(this));

   $A([this.package_type]).each(function(item) {
      if (item != null) {
        $A(['change', 'keyup']).each(function(action) {
          Event.observe(item, action, function() {
            this.setDepartureTimeSelect();
            this.updateDepartingFromValues();
            this.eventUpdates();                        
          }.bind(this));
        }.bind(this));
      }
    }.bind(this)); 

    $A([this.year, this.departing_from, this.package_type]).each(function(item) {
      if (item != null) {
        $A(['change', 'keyup']).each(function(action) {
          Event.observe(item, action, function() {
            if (this.package_deal) {
              this.departure_time_hash = this.departure_year_hash[this.package_type.getValue()][this.departing_from.getValue()][this.getYearValue()];              
            } else {
              this.departure_time_hash = this.departure_year_hash[$('date_year').getValue()];
            }
            this.update_months();
            this.setDepartureTimeSelect();
            this.eventUpdates();                       
          }.bind(this));
        }.bind(this));
      }
    }.bind(this));
    
    
    $A([this.year, this.month, this.day]).each(function(item) {
      $A(['change', 'keyup']).each(function(action) {
        Event.observe(item, action, function() {
          this.bookingDateEventUpdates();
        }.bind(this));
      }.bind(this));
    }.bind(this));
    
    
    $A([this.adult_number, this.children_number, this.departure_time, this.under_water, this.departing_from]).each(function(item) {
      if (item != null) {
        $A(['change', 'keyup']).each(function(action) {
          Event.observe(item, action, function() {
            this.eventUpdates();
          }.bind(this));
        }.bind(this));
      }
    }.bind(this));
   

   
  },
  
  bookingDateEventUpdates: function() {
    this.adjust_days(); 
    this.change_day();
    this.setDepartureTimeSelect();    
    this.setDepartingTime();
    this.setTotalPrice();
  },
  
  eventUpdates: function() {
    this.setDepartingTime();
    this.setTotalPrice();   
  },
  
  updateDepartingFromValues: function() {
    //Remove existing options
    if(this.departing_from == null) return;
    var length = this.departing_from.options.length;
    for (var index = 0, len = length; index < len; ++index) {
      this.departing_from.remove(0);
    }
    
    if (this.package_type.getValue() == "Coach-Cruise-Coach") {
      this.departing_from.options[0] = new Option("Queenstown");
      this.departing_from.options[1] = new Option("Te Anau");
    } else {
      this.departing_from.options[0] = new Option("Queenstown");
    }
    this.eventUpdates();
  },
  
  days_in_month: function(year, month) {
    return 32 - new Date(year, month, 32).getDate();
  },
  
  update_months: function() {
    // remove all months before this date for the first year
    if(this.month == null) return;
    var length = this.month.options.length;
    for (var index = 0, len = length; index < len; ++index) {
      this.month.remove(0);
    }
    
    var month_names = $A(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]);
    var i;
    var box_id = 0;
    if (this.year.options[0].text == this.getYearValue()) {
      i = this.current_month;
    } else {
      i = 1;
    }
    while (i < 13) {
      if (this.departure_time_hash[i].length > 0) {   
        this.month.options[box_id++] = new Option(month_names[i-1], i);  
        i++;        
      } else {
        break;
      }
    }
  },
  
  adjust_days: function() {  
    if(this.day != undefined) {                          
      var year_index = 0;
      var month_index = 0;
      if(this.year != undefined) { year_index = this.year.options[this.year.selectedIndex].value; }
      if(this.month != undefined) { month_index = this.month.options[this.month.selectedIndex].value; }
      var current_day = this.day.options[this.day.selectedIndex].value;
      var days = this.days_in_month(year_index, month_index-1);                   
      if(current_day > days) { current_day = days; } // Adjust current day to max day if new max days is smaller than current day                
      var length = this.day.options.length // Remove day options                     
      var temp_day = this.day.options[0].text == '1' ? null : this.day.options[0].text // If day has default value other then 1 make sure it is set again
      for (var index = 0, len = length; index < len; ++index) {
      	this.day.remove(0);
      }                          
      var offset = 0;            
      if(temp_day != null) {
        offset = 1;
        this.day.options[0] = new Option(temp_day, '');
      } 
      for(var i = 0, d = days; i < d; i++) {
        var j = i+offset;
        this.day.options[j] = new Option(i+1,i+1);
        if((i+1) == current_day) { this.day.options[j].selected = "selected"; }
      }	
    }
  },

  change_day: function() {
    this.highlight_day();
    var selected_date = new Date(this.getYearValue(), this.getMonthValue()-1, this.getDayValue());
    this.day_name.innerHTML = this.day_names[selected_date.getDay()];
  },
    
  highlight_day: function() { 
    if(this.is_loaded())
      $(this.day_name).innerHTML = new Effect.Highlight(this.day_name, {startcolor:'#e9eaeb', endcolor:'#e9eaeb', restorecolor:'#e9eaeb' }, {queue: {position: 'end', scope: 'change_day', limit: 1}});
    else
      this.current_day_loaded = true;
  },
  
  getYearValue: function() {
    return this.year.getValue();  	
  },
  
  getMonthValue: function() {
    return this.month.getValue();  	
  },
  
  getDayValue: function() {
    return this.day.getValue();  	
  },    

  setCurrentDepartureMonth: function() {
    this.current_departure_month = this.departure_time_hash[1][ this.getMonthValue() ];
  },
  
  /*
   setCurrencyListSelect: function() {    
    // Add options
    var currencies = $A(this.currency_list);
    currencies.each(function(currency, code) {
      this.currency_list.options[index] = new Option(currency['country'], code['code']);
    }.bind(this));
  },  */

  setDepartureTimeSelect: function() {
    // Remove existing options
    if(this.departure_time == null) return;
    var length = this.departure_time.options.length;
    for (var index = 0, len = length; index < len; ++index) {
      this.departure_time.remove(0);
    }
    
    // Add new options
    var month_number = this.getMonthValue();
    var month = $A(this.departure_time_hash[this.getMonthValue()]); 
    month.each(function(departure, index) {
      this.departure_time.options[index] = new Option(departure['time'], departure['id']);
    }.bind(this));
    
    this.setCurrentDepartureMonth();
  },
  
  checkUnderWater: function() {
    return this.under_water.checked;	
  },
  
  getAdultPrice: function() {
    if (!this.package_deal) {
      var price = parseFloat(this.departure_time_hash[this.getMonthValue()][this.departure_time.selectedIndex]['adult_price']);
      this.adult_ticket_price.value = price;
      if (this.checkUnderWater()) {
        price += parseFloat(this.departure_time_hash[this.getMonthValue()][this.departure_time.selectedIndex]['uw_adult_price']);
        this.uw_adult_ticket_price.value = parseFloat(this.departure_time_hash[this.getMonthValue()][this.departure_time.selectedIndex]['uw_adult_price']);
      } 
      return price;
    } else {
      var price = parseFloat(this.departure_time_hash[this.getMonthValue()][this.departure_time.selectedIndex]['adult_price']);
      this.adult_ticket_price.value = price;
      return price;      
    }
  },
  
  getChildrenPrice: function() {
    if (!this.package_deal) {      
      var price = parseFloat(this.departure_time_hash[this.getMonthValue()][this.departure_time.selectedIndex]['child_price']);
      this.child_ticket_price.value = price;
      if (this.checkUnderWater()) {
        price += parseFloat(this.departure_time_hash[this.getMonthValue()][this.departure_time.selectedIndex]['uw_child_price']);
        this.uw_child_ticket_price.value = parseFloat(this.departure_time_hash[this.getMonthValue()][this.departure_time.selectedIndex]['uw_child_price']);
      } 
      return price;
    } else {
      this.child_ticket_price.value = parseFloat(this.departure_time_hash[this.getMonthValue()][0]['child_price']);
      return price = parseFloat(this.departure_time_hash[this.getMonthValue()][0]['child_price']);
    }
  },
  
  getAdultTotalPrice: function() {
    return this.getAdultPrice() * parseInt(this.adult_number.getValue());
  },
  
  getChildrenTotalPrice: function() {
    return this.getChildrenPrice() * parseInt(this.children_number.getValue());
  },  
  
  getTotalPrice: function() {
    return this.getAdultTotalPrice() + this.getChildrenTotalPrice();  	
  },
  
  setDepartingTime: function() {
    this.departing_time.value = this.departure_time.options[this.departure_time.options.selectedIndex].text;
  },
  
  setTotalPrice: function() {
    this.highlight_total_price();
    this.total_price.innerHTML = "$" + this.getTotalPrice();
    this.form_total_price.value = this.getTotalPrice();
  },
  
  highlight_total_price: function() {
  	if(this.is_loaded())
      $(this.total_price).innerHTML = new Effect.Highlight(this.total_price, {startcolor:'#cccccc', endcolor:'#e9eaeb', restorecolor:'#e9eaeb' }, {queue: {position: 'end', scope: 'total_price', limit: 1}});
    else
      this.total_price_loaded = true;
  },
  
  is_loaded: function() {
  	return this.total_price_loaded && this.current_day_loaded;
  }
  
};


var DateSelector = Class.create();

DateSelector.prototype = {
  initialize: function(){
    this.year_start = $('date_year_start');
    this.month_start = $('date_month_start');
    this.day_start = $('date_day_start');
    this.year_end = $('date_year_end');
    this.month_end = $('date_month_end');
    this.day_end = $('date_day_end');
    this.addEvents();
    this.adjust_days('start');
    this.adjust_days('end');
  },
  
  addEvents: function() {
    // Add Events   
    $A([this.year_start, this.month_start]).each(function(item) {
      $A(['change', 'keyup']).each(function(action) {
        Event.observe(item, action, function() {
          this.adjust_days('start');
        }.bind(this));
      }.bind(this));
    }.bind(this));
    
    $A([this.year_end, this.month_end]).each(function(item) {
      $A(['change', 'keyup']).each(function(action) {
        Event.observe(item, action, function() {
          this.adjust_days('end');
        }.bind(this));
      }.bind(this));
    }.bind(this));
  },
  
  days_in_month: function(year, month) {
    return 32 - new Date(year, month, 32).getDate();
  },
  
  adjust_days: function(type) {  
    if (type == 'start') {
      this.month = this.month_start;
      this.year = this.year_start;
      this.day = this.day_start;
    } else {
      this.month = this.month_end;
      this.year = this.year_end;
      this.day = this.day_end;
    }
    
    
    if(this.day != undefined) {                          
      var year_index = 0;
      var month_index = 0;
      if(this.year != undefined) { year_index = this.year.options[this.year.selectedIndex].value; }
      if(this.month != undefined) { month_index = this.month.options[this.month.selectedIndex].value; }
      var current_day = this.day.options[this.day.selectedIndex].value;
      var days = this.days_in_month(year_index, month_index-1);                   
      if(current_day > days) { current_day = days; } // Adjust current day to max day if new max days is smaller than current day                
      var length = this.day.options.length // Remove day options                     
      var temp_day = this.day.options[0].text == '1' ? null : this.day.options[0].text // If day has default value other then 1 make sure it is set again
      for (var index = 0, len = length; index < len; ++index) {
      	this.day.remove(0);
      }                          
      var offset = 0;            
      if(temp_day != null) {
        offset = 1;
        this.day.options[0] = new Option(temp_day, '');
      } 

      
      
      this.day.options[1] = new Option(1,1);
      this.day.options[2] = new Option(days,days);
      if (this.day.selectedIndex == 1) {
        this.day.options[1].selected = "selected";  
      } else {
        this.day.options[2].selected = "selected";  
      }

    }
  }
};