function CalculateTourPrice() {
  var total_pax = 0;
  var total_price = 0.00;
  var rate_options=$A();
  var lastRO=0;
  var exceeded=false;
  
  $('adult','child','infant','pension','family').each(function(el) { if($(el).value > 0) total_price = total_price + ($(el).value * $(el).readAttribute('price')); });
  $('adult','child','infant','pension').pluck('value').each(function(k) { if(k > 0) total_pax = parseInt(total_pax) + parseInt(k); });
  if($('family').value > 0) total_pax = parseInt(total_pax) + parseInt(($('family').value*4));
    
  $$('.rate_option_quantity').each(function (k) { 
  	if($(k).value > 0) 
  	{
  	  total_price = total_price + ($(k).value * $(k).readAttribute('price'));
  	  var ro_key = $(k).readAttribute('id').split('_');
  	  var ro = $H({IDProduct:$(k).readAttribute('idproduct'),IDRateOption:ro_key[1]});
  	  var total_ro_pax=0;
  	  $('adult_'+ro_key[1],'child_'+ro_key[1]).each(function(a) { 
  	   if(a && a.value>0) total_ro_pax = parseInt(total_ro_pax) + parseInt(a.value);
  	  });
       if(total_ro_pax > total_pax) {
          exceeded=true;
        }
  	  ro[ro_key[0]]=$(k).value;
  	  ro[ro_key[0]+'_price']=$(k).readAttribute('price');
  	  rate_options.push(ro);
  	}
  });
  
  $('RATE_OPTIONS_STRING').value=rate_options.toJSON();
  
  // If agent discount exists, minus discount off price, then add booking fee
  if($('discount_percent')) {
	var discount_amount = total_price*(parseFloat($('discount_percent').value)/100);
	total_price = total_price-discount_amount+parseFloat($('booking_fee').value); 
  } else {
  	total_price = total_price+parseFloat($('booking_fee').value); 
  }
  
  if(total_pax > available || $('status').value==0) {
    $('payment-div').hide();
    $('noavailability-div').show();
    $('bookbutton').hide();
    $('pax_exceeded').hide();
    $('enquirebutton').show();
    $('total_price').update('$'+$('booking_fee').value);
    $('booking_price').value=0.00;
  } else {
    $('payment-div').show();
    $('bookbutton').show();
    $('pax_exceeded').hide();
    $('enquirebutton').hide();
    $('noavailability-div').hide();
    $('total_price').update('<b>$'+total_price.toFixed(2)+'</b>');
    $('booking_price').value=total_price.toFixed(2);
  }
  if(exceeded) {
    $('pax_exceeded').show();
    $('bookbutton').hide();
  }
}

function ShowPickupDetails(idpickup_location) {
  if(pickup_details[idpickup_location]) {
  var details ='<b>'+pickup_details[idpickup_location].time+'</b>';
  if(pickup_details[idpickup_location].notes.length > 1)
    details += '<b> [ '+pickup_details[idpickup_location].notes+' ]</b>';
  
  $('pickup_details').update(details);
  }
}

function DateDifference(x, y) {
  var one_day=1000*60*60*24;  //- 1 day in milliseconds
  var k = Math.ceil((x.getTime()-y.getTime())/(one_day));
  
  return k;
}


function isContinuous(Collection, Caller) {
  var passed=true;
  
  if(Collection.length<=1)
    passed = true;
  else {
    Collection.each(function(c, index) { 
      if(Collection[index+1]) {
        var dateOne = new Date(Collection[index+1].split("-")[0], (Collection[index+1].split("-")[1]-1), Collection[index+1].split("-")[2]);
        var dateTwo = new Date(c.split("-")[0], (c.split("-")[1]-1), c.split("-")[2]);
        if(DateDifference(dateOne, dateTwo) == 1) {
          passed = (passed==true) ? true : false;
        }else {
          var pos = ($(Caller).readAttribute('pos')>15) ? 20: $(Caller).readAttribute('pos');
          var spacing = pos*30;
          $('ErrorLayer').setStyle({left:spacing+'px'});
          $('MinNightsLayer').hide();
          $('ErrorLayer').show(); 
          Caller.checked=(Caller.checked) ? false : true;
          passed = false;
        }
      }
    });
  }
  if(passed==true) {
    $('ErrorLayer').hide();
    return true;
  }
}

function GetAccomPrice(el) {
  var firstDate;
  var dates = $A();
  
  if($(el).type != 'load') var Caller = $(el);
  
  dates[0] = $A();
  dates.push($('idproduct').value);
  $A(document.getElementsByClassName('NightsCB')).each(function(cb, k) {
    if(k==0) {
      var fd = $(cb).readAttribute("date").split("-");
      firstDate = new Date(fd[0], (fd[1]-1), fd[2]);
    }
    if(cb.checked) {
      dates[0].push($(cb).readAttribute('date'));
      var sd = $(cb).readAttribute("date").split("-");
      var selectedDate = new Date(sd[0], (sd[1]-1), sd[2]);
      if(DateDifference(selectedDate, firstDate) > 20)
        $('Container').scrollLeft=500;
    }
  });

  if(!isContinuous(dates[0], Caller)) return false;

  if(dates[0].length==0) {
    $('RevTable').descendants().each(function(row) { row.remove(); });
    new Insertion.Bottom('RevTable','<tr><td align="center" colspan=3>Please select a date with an available rate above to continue.</td></tr>');
    $('price-subtotal','price-total','total_price').invoke('update','$0.00');
    $('MinNightsLayer').hide();
    $('bookbutton').show();
    return false;
 }
 
 Ajax.Responders.register({
  onCreate: function() {
    if($('Busy') && Ajax.activeRequestCount>0)
      $('Busy').show();
  },
  onComplete: function() {
    if($('Busy') && Ajax.activeRequestCount==0)
      $('Busy').hide();
  }
  });
  var kAjax = new Ajax.Request($('_sbu').value+'service/booking',{
                      method: 'post', 
                      parameters: 'request='+dates.toJSON(),
                      onSuccess: function(response) { 
                        $('RevTable').descendants().each(function(row) { row.remove(); });
                        var kObj = response.responseText.evalJSON();
                        kObj.rates.each(function(rate, index) {
                          var color = (0 == index % 2) ? "#FFF8D1" : "#FFEC9D";
                          new Insertion.Bottom('RevTable','<tr style="background-color:'+color+';"> \
                                                            <td width="10%">'+rate.date+'</td> \
                                                            <td width="10%">$'+rate.sell+'</td> \
                                                            <td width="80%" style="border-right:solid 1px #AAA;">'+rate.inclusions+'&nbsp;</td> \
                                                          </tr>');
                          if(rate.min_nights > kObj.rates.size()) {
                            $('min_nights').update(rate.min_nights+' ');
                              $('MinNightsLayer').show(); 
                              $('bookbutton').hide();
                          }else {
                              $('MinNightsLayer').hide();
                              $('bookbutton').show();

                          }
                        });
                        $('nights').value=kObj.rates.size();
                        $('checkin_date').value=kObj.rates.first().date;
                        $('checkout_date').value=kObj.rates.last().date;
                        $('price-subtotal').update('$'+kObj.total.toFixed(2));
                        $('price-fee').update('$'+$('booking_fee').value);
                        $('price-total').update('$'+(parseFloat(kObj.total.toFixed(2))+parseFloat($('booking_fee').value)));
                        $('total_price').update('$'+(parseFloat(kObj.total.toFixed(2))+parseFloat($('booking_fee').value)));
                        $('booking_price').value=parseFloat(kObj.total.toFixed(2));
                      } 
                    });
}

function FindRates() {
  var datestring = '';
  $('CID_Year','CID_Month','CID_Day').pluck('value').each(function(d) {
    datestring += d+'-';
  });
  var cleanDate = datestring.replace(/-$/g,'');
   document.location='/booking?idproduct='+$('idproduct').value+'&type=Open&date='+cleanDate;
}

function BookAndPay(type) {
    if(ValidateForm(type)) {
      document.BookingForm.submit();
    }
}

function PaymentPay(type) {
    if(ValidateForm(type)) {
      document.BookingForm.submit();
    }
}

function Enquire() 
{

  var type=$('type').value;
  if(ValidateForm('enquiry')) 
  {
	
	
    if(type=='Accommodation') { document.EnquiryForm.submit(); }
    if(type=='Tour') {  
      var Data  = $H();
	  if($('idfeature')) {
		  $('idproduct','idsupplier','adult','child','infant','pension','family','first_name','surname','phone','email','comments','agentcode','type','DOT_Day','DOT_Month','DOT_Year','idfeature').each(function(d) {
		  Data[$(d).id]=$(d).value;
		  });
	  } else {
		  $('idproduct','idsupplier','adult','child','infant','pension','family','first_name','surname','phone','email','comments','agentcode','type','DOT_Day','DOT_Month','DOT_Year').each(function(d) {
		  Data[$(d).id]=$(d).value;
		  });
	  }

      var kAjax = new Ajax.Request($('_sbu').value+'service/enquiry',{
        method: 'post', 
        parameters: 'request='+Data.toJSON(),
        onSuccess: function(response) { 
          //console.log(response);
          document.location='/enquiry-complete';
        }
      });
    }    
  }
}


function Close() {  $('ErrorLayer').hide(); }

function CheckAvailability()
{
var datestring = '';
  $('DOT_Year','DOT_Month','DOT_Day').pluck('value').each(function(d) {
    datestring += d+'-';
  });
  var cleanDate = datestring.replace(/-$/g,'');
  $('date_travel').value=cleanDate;
  var dateOne = new Date(cleanDate.split("-")[0], (cleanDate.split("-")[1]-1), cleanDate.split("-")[2]);
  var dateTwo = new Date();  
  if(DateDifference(dateOne, dateTwo) <1) 
  {
    $('status').value=0;
    CalculateTourPrice();
  }
  else {
    Ajax.Responders.register({
      onCreate: function() { if($('DateBusy') && Ajax.activeRequestCount>0) $('DateBusy').show(); },
      onComplete: function() { if($('DateBusy') && Ajax.activeRequestCount==0) { $('DateBusy').hide();CalculateTourPrice(); }
      }
    });
    var Data = $H();
    $('idproduct','date_travel','adult','child','infant','pension','family').each(function(d) {
      Data[$(d).id]=$(d).value;
    });
    new Ajax.Request($('_sbu').value+'service/availability',{
      method: 'post', 
      parameters: 'request='+Data.toJSON(),
      onSuccess: function(response) { 
        var result = response.responseText.evalJSON();
        available=result.available;
        $('status').value=result.status;
      } 
    });
  }
    
}
function winclose()
{
  alert("close");
  document.window.close();
}
