// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function check_number_of_rooms(select_class, max_rooms_selected) {
  var selects = $$('select.'+select_class);
  var count = 0;
  selects.each(function(e) {			
		count += parseInt(e.value);
	}.bind(this));
	if(count > max_rooms_selected){
	  alert('You can select max ' + max_rooms_selected + ' rooms.');
	  return false;
	}else if(count <= 0){
	  alert('You must choose some room.');
	  return false;
	}
	return true;
}

var TotalPriceHelper = Class.create();

TotalPriceHelper.prototype = {
			
		initialize: function(room_options, room_rate_options, room_select, occupancy_div, total_place, adult_price, child_price, start_number_adults,start_number_children, include_children, number_of_adults, number_of_children) {
		  this.room_options = room_options;
		  this.rate_options = room_rate_options;
		  this.rooms_select = room_select;
		  this.occupancy_div = occupancy_div;
		  this.conversion = {};
		  this.total_place = total_place;
		  this.total = 0;
		  this.start_number_adults = start_number_adults;
		  this.start_number_children = start_number_children;
		  this.room_rate_code = room_options.code + "_" + room_rate_options.code;
		  this.total_hidden_place = $('room_type_form')["room_types[" + this.room_rate_code + "][base_price]"];
		  if (number_of_children == ''){
		  	this.number_of_children = '0';
		  }else{
		  	this.number_of_children = number_of_children;//number_of_children;
		  }
		  this.number_of_adults = parseFloat(number_of_adults);//number_of_adults;
		  this.include_children = include_children;
		  $(this.total_place).update('&euro;'+this.total);
		  
		  //this.roomOccupancyTemplate = new Template('<label class="room-name">#{room_name}&nbsp;#{r_number}:&nbsp;</label>&nbsp;adults:#{select_adults}&nbsp;children:#{select_children}<br />');
		  this.roomOccupancyHeader = new Template('<a class="addroom" href="javascript:void(0);" onclick="helper_' + this.room_rate_code + '.incrementRoomlist()"><span class="alt">Add room</span></a><h4>Occupancy</h4><h5>#{room_name}</h5><p>(Extra adult price '+adult_price+', extra child price '+child_price+')</p><ul>');
		  		  
		  this.roomOccupancyTemplate = new Template('<li>Room #{r_number}: adults #{select_adults}&nbsp;children #{select_children}</li>');
		  
		  this.selectTemplate = new Template('<select name="#{name}" class="#{css}" id="#{id}">#{select_options_tag}</select>');
		  this.optionTemplate = new Template('<option value="#{value}" #{selected}>#{value}</option>');
		  		  
		  $(this.rooms_select).onchange = function() {
				this.changeRooms($(this.rooms_select));
			}.bindAsEventListener(this);
			$(this.rooms_select).selectedIndex = 0;			
		},

		incrementRoomlist: function() {
			
			sel = $(this.rooms_select);

			if(sel.selectedIndex < sel.options.length) {
				sel.options[sel.selectedIndex+1].selected = '1';
			}
			
			this.changeRooms(sel);
		},
		
		changeRooms: function(sel) {
		  var template = '';
		  for(n=0; n < parseInt(sel.value); n++){
		     if(n == 0){
		      template += this.getRoomOccupancyHeader(0) + this.getRoomOccupancyTemplate(n+1);
		    }else{
		      template += this.getRoomOccupancyTemplate(n+1);
		    }	
	      }
	      $(this.occupancy_div).update(template);
      
  		  var selects = $$('div#' + this.occupancy_div + ' select');
		  selects.each(function(s) {
		  	s.onchange = function(e) {					
				this.recalculate(s);
			}.bindAsEventListener(this);
				// end of onchange function for select
		  }.bind(this));
		  this.recalculate();
		},
		
		getRoomOccupancyHeader: function(_number) {
		  this.conversion = {room_name: this.rate_options.name};
		  var template = this.roomOccupancyHeader.evaluate(this.conversion);
		  return template;
		},
		
		getRoomOccupancyTemplate: function(_number) {
		  var room_prefix = 'room_types[' + this.room_rate_code + '][rooms_occupancy][' + _number + ']';
		  var selectChildName = room_prefix + '[children]';
		  var selectAdultsName = room_prefix + '[adults]';
		  var selectChildId = 'select_' + this.room_rate_code + '_child';
		  var selectAdultsId = 'select_' + this.room_rate_code + '_adults';
		  
		  var selectChildren = this.getSelectTemplate(selectChildName, 'select-child', selectChildId, this.room_options.min_children, this.room_options.children, this.number_of_children);
		  var selectAdults = this.getSelectTemplate(selectAdultsName, 'select-adults', selectAdultsId, this.room_options.min_adults, this.room_options.adults, this.number_of_adults);
		  
		  this.conversion = {room_name: this.rate_options.name, r_number: _number, select_adults: selectAdults, select_children: selectChildren};
		  var template = this.roomOccupancyTemplate.evaluate(this.conversion);
		  return template;
		},
		
		getSelectTemplate: function(_name, _class, _id, _from, _to, _selected){
		  var select_options = '';
		  for(j=_from; j <= _to; j++){
		  	if (j == _selected){
				str = "selected";
			}else{
				str = "";
			}
		    this.conversion = {value: j, selected: str};
		    select_options += this.optionTemplate.evaluate(this.conversion);
	      }
	      var select_tag = '';
	      this.conversion = {name: _name, css: _class, id: _id, select_options_tag: select_options};
	      select_tag = this.selectTemplate.evaluate(this.conversion);
	      return select_tag;
		},
		
		recalculate: function(sel) {
		  check_occupancy = this.checkOccupancy(sel);
		  
		  var adults = (this.include_children == 'true') ? (this.getAdultsCount() + this.getChildCount()) : this.getAdultsCount();
		  
		  
		  var child = this.getChildCount();
		  var rooms = this.getRoomsCount();
		  
		  var adults_search = (parseInt(this.number_of_adults) +  ((this.include_children == 'true') ? parseInt(this.number_of_children) : 0) ) * parseInt(rooms);
		  var adult_without_extra = (this.start_number_adults-1) * rooms;
		  
		  if (adults_search == adults) {
		  	diff_adults = 0;
		  }else {			  
		  	if(adults > adults_search){
				if(adults > adult_without_extra){
					if(adults_search > adult_without_extra) diff_adults = adults - adults_search;
					else diff_adults = adults - adult_without_extra;
				} 
				else diff_adults = 0;
			}else{				
				if(adults > adult_without_extra) diff_adults = adult_without_extra - adults;
				else diff_adults = (adult_without_extra - adults_search);//
			}  	
		  }		  
		  //alert('Adults selected:'+adults+' Adults without extra:'+adult_without_extra+' Adults ricercati:'+adults_search+' Diff:'+diff_adults);
		  

                  var children_search = (parseInt(this.number_of_children))  * parseInt(rooms);
		  var children_without_extra = (this.start_number_children-1) * rooms;
		  
		  //alert('Children:'+child+" Children search:"+children_search+" Children without extra:"+children_without_extra);
		  
		  if (children_search == child) {
		  	diff_children = 0;
		  }else {			  
		  	if(child > children_search){
				if(child > children_without_extra){
					if(children_search > children_without_extra) diff_children = child - children_search;
					else diff_children = child - children_without_extra;
				} 
				else diff_children = 0;
			}else{				
				if(child > children_without_extra) diff_children = children_without_extra - child;
				else diff_children = (children_without_extra - children_search);//
			}  	
		  }

		  //alert('Adults:'+adults+' Child:'+child+' Adults search:'+adults_search+' Diff:'+diff_adults);
		  if(this.include_children == 'true')
		  	this.total = (rooms*this.rate_options.base_price) + (diff_adults*this.rate_options.extra_adult_price);
		  else
		  	this.total = (rooms*this.rate_options.base_price) + (diff_adults*this.rate_options.extra_adult_price) + (diff_children*this.rate_options.extra_child_price);
		  
		  $(this.total_place).update('&euro;'+this.total);
	    search_extra_adults = this.number_of_adults - adult_without_extra;
	    if (search_extra_adults < 0) search_extra_adults = 0;
	    original_base_price = this.rate_options.base_price;
	    original_base_price -= search_extra_adults * this.rate_options.extra_adult_price;
	    this.total_hidden_place.value = original_base_price;
		  if(!check_occupancy){
	      alert('Max Occupancy for this room is '+this.room_options.adults);
	    }
		},
		
		getChildCount: function() {
		  var selects_child = $$('div#' + this.occupancy_div + ' select.select-child');
		  var count_child = 0;
		  selects_child.each(function(e) {
					count_child += parseInt(e.value);				 
			});
			return count_child;
		},
		
		getAdultsCount: function() {
		  var selects_adults = $$('div#' + this.occupancy_div + ' select.select-adults');
		  var count_adults = 0;
		  selects_adults.each(function(e) {
					count_adults += parseInt(e.value);				 
			});
			return count_adults;
		},
		
		getRoomsCount: function() {
		  rooms_count = $('room_type_'+this.room_rate_code+'_rooms').value;
		  return parseInt(rooms_count);
		},
		
		checkOccupancy: function(sel){
		  if(sel){
  		  if(sel.name.endsWith('[children]')){
  		    var child_select = sel;
  		    var adults_select = $$('select[name="'+sel.name.gsub('children','adults')+'"]')[0];
  		  }else{
  		    var adults_select = sel;
  		    var child_select = $$('select[name="'+sel.name.gsub('adults','children')+'"]')[0];
  		  }
  		  sum = parseInt(adults_select.value) + parseInt(child_select.value);
  		  result = (this.room_options.adults >= sum)
  		  if(!result){
  		    child_select.selectedIndex = 0;
  		  }
  		  return result;
		  }else{
		    return true;
		  }
		}
}
