/*------------------------------------------------------------------------------
* SoftIdiom
* scripts for Gascony Experience
*
* version history
*
* 1.02 01/02/2008
* new section to do accommodation pricing.
* 1.01 31/01/2008
* new functions to link categories and sub categories.
* 1.00 28/09/2007
* first version
*/

// global objects.
var ge_currentTab;
var ge_BOOKING_FORM = "form_bookingrequest_";

/*
* the site object.
*/
var ge_site = {
  /*
  * initialise the tabs and the carousel.
  */
  start: function(){
    if ($('tabs')) ge_site.startTabs();
    if ($('SI_Carousel')) ge_site.startCarousel();
    $$('input.DatePicker').each( function(el){
      new DatePicker(el);
    });
  },
  /*
  * initialise the tabs.
  */
  startTabs: function(){
    for (var j = 1; j <= 6; j++) {
      var tablink = document.getElementById("tab"+j+"link");
      if (tablink != null && tablink.className.indexOf("Selected") > -1) {
        ge_currentTab = document.getElementById("tab"+j);
        break;
      }
    }
    if ($('tab1link')) $('tab1link').addEvent('click',function(event) {ge_selectTab(event,$('tab1'))});
    if ($('tab2link')) $('tab2link').addEvent('click',function(event) {ge_selectTab(event,$('tab2'))});
    if ($('tab3link')) $('tab3link').addEvent('click',function(event) {ge_selectTab(event,$('tab3'))});
    if ($('tab4link')) $('tab4link').addEvent('click',function(event) {ge_selectTab(event,$('tab4'))});
    if ($('tab5link')) $('tab5link').addEvent('click',function(event) {ge_selectTab(event,$('tab5'))});
    if ($('tab6link')) $('tab6link').addEvent('click',function(event) {ge_selectTab(event,$('tab6'))});
  },
  /*
  * initialise the carousel.
  */
  startCarousel: function(){
    new iCarousel("SI_Carousel_content", {
      idPrevious: "SI_Carousel_previous",
      idNext: "SI_Carousel_next",
      idToggle: "undefined",
      item: {
        klass: "SI_Carousel_item",
        size: 102
      },
      animation: {
        type: 'fadeNscroll',
        transition: Fx.Transitions.Quad.easeOut,
        duration: 500,
        amount: 7
      }
    });
    $$('.thumbnail').addEvent('click', function(){
      var imageSrc = this.src.replace(/_thumb/,"");
      imageSrc = imageSrc.replace(/\/thumbnails/,"");
      imageSrc = imageSrc.replace(/102x68/,"309x206");
      $('bannerMid').src = imageSrc;
      });
  }
};

// setup the onload event to initialise things.
if (window.addEvent != null) { window.addEvent('load', ge_site.start); }

//--------------------------- banner functions  --------------------------------

/*
* remove the last element in the array
* Parameters:
*   imgArray - the image array.
* Returns:
*   none.
*/
function bannerImages(imgArray) {
  return imgArray.remove("");
}

//------------------------------ Tab functions  --------------------------------

/*
* change the displayed tab to the one specified.
* Parameters:
*   event - the event object.
*   tab - the tab node.
* Returns:
*   none.
*/
function ge_selectTab(event,tab) {
  (new Event(event)).stop();
  if(tab == ge_currentTab) return;
  ge_currentTab.style.display = 'none';
  tab.style.display = 'block';
  var link = $(tab.id+'link');
  link.className = link.className+'Selected';
  var currentLink = $(ge_currentTab.id+'link');
  currentLink.className = currentLink.className.replace(/Selected/,'');
  ge_currentTab = tab;
}

//--------------------------- filter functions  --------------------------------

/*
* change the sub categories available in the select field.
* Parameters:
*   category - the current category.
* Returns:
*   none.
*/
function ge_selectSubCategory(category) {
  var subcategoryField = document.getElementById("custom_form_whatson_what2");
  if (subcategoryField == null || category == null || ge__subcat_options == null) { return; }
  var options = ge__subcat_options[category];
  if (options != null) {
    subcategoryField.options.length = 0;
    for (var j = 0; j < options.length; j++) {
      subcategoryField.options[j] = options[j];
    }
    subcategoryField.selectedIndex = 0;
  }
}

//------------------------------- Popup functions ------------------------------

/*
* display a popup page.
* Parameters:
*   name - the name of the site content.
* Returns:
*   false.
*/
function ge_popup(name) {
  return ge_popupPage("/cgi-bin/ge/popup.html", name);
}
/*
* display a popup page.
* Parameters:
*   page - the popup page.
*   name - the name of the site content.
*   domain - the domain of the site content (optional).
*   format - the site content format (optional).
*   other - other parameters (optional).
*   options - the window popup options (optional).
* Returns:
*   false.
*/
function ge_popupPage(page, name, domain, format, other, options) {
  if (name == null) { domain = ""; }
  if (domain == null) { domain = "info"; }
  if (format == null) { format = "popup"; }
  if (other == null) { other = ""; }
  if (other.indexOf("&") != -1) { other = "&"+other; }
  if (options == null) { options = "resizable=1,scrollbars=1,width=500,height=500"; }
  window.open (page+"?domain="+domain+"&name="+name+"&format="+format+other+"","ge_popup", options);
  return false;
}

//-------------------------- availability selection------------------------------

/*
* select an availability calendar.
* Parameters:
*   the select node.
* Returns:
*   none.
*/
function ge_selectCalendar(selectNode) {
  if (selectNode == null) { return; }
  if (selectNode.options == null || selectNode.selectedIndex == null) { return; }
  
  var newType = selectNode.options[selectNode.selectedIndex].value;
  var oldType = selectNode.ge_selectedType;
  if (oldType == null) {
    // use default for old type.
    for (var j = 0; j < selectNode.options.length; j++) {
      if (selectNode.options[j].defaultSelected) {
        oldType = selectNode.options[j].value;
        break;
      }
    }
  }
  if (oldType == null) { oldType = "type1"; }

  var fieldNode = document.getElementById("ge_available_"+oldType);
  if (fieldNode != null) { fieldNode.style.display = "none"; }
  var fieldNode = document.getElementById("ge_available_"+newType);
  if (fieldNode != null) { fieldNode.style.display = "block"; }
  
  selectNode.ge_selectedType = newType;;
}

//------------------------------ pricing ---------------------------------------

/*
* initialise the pricing.
* Parameters:
*   none.
* Returns:
*   none.
*/
function ge_initialisePriceing() {
  // setup the field events.
  var fields = ["from_day","from_month","from_year","from_date","nights","group1","group2"];
  for (var j = 0; j < fields.length; j++) {
    for (var k = 0; k < 7; k++) {
      var fieldNode = document.getElementById(ge_BOOKING_FORM+fields[j]+"_"+k);
      if (fieldNode != null) { 
        fieldNode.onchange = ge_checkSharedUpdate; 
        fieldNode.ge_index = k;
        fieldNode.ge_name = ge_BOOKING_FORM+fields[j]+"_";
      }
    }
  }
  var fieldNode = document.getElementById(ge_BOOKING_FORM+"form");
  if (fieldNode != null) { 
    fieldNode.onsubmit = ge_checkFormSubmit; 
  }
  
  // calculate cost
  ge_getCost();
}

/*
* check the data when the form is submitted.
* Parameters:
*   none.
* Returns:
*   true if all ok and false if the submit is cancelled.
*/
function ge_checkFormSubmit() {
  // validate the fields that the user has filled in in the form
  var geFormFields = {
    'form_bookingrequest_lead_guest': {l:'Name',r: 1,t:'form_bookingrequest_lead_guest',mn:0,mx: 99},
    'form_bookingrequest_lead_guest_email': {l:'Email',f:'email',r: 0,t:'form_bookingrequest_lead_guest_email',mn:0,mx: 99},
    'form_bookingrequest_lead_guest_phone': {l:'Phone',fv:'xor',a:'form_bookingrequest_lead_guest_email',b:'form_bookingrequest_lead_guest_phone',r: 0,t:'form_bookingrequest_lead_guest_phone',mn:0,mx: 99}
  };
  
  // setup the soap call properties to check for availability.
  var fieldNode = document.getElementById(ge_BOOKING_FORM+"record_id");
  var id = (fieldNode != null) ? fieldNode.value: ""; 
  fieldNode = document.getElementById(ge_BOOKING_FORM+"record_table");
  var table = (fieldNode != null) ? fieldNode.value: ""; 
  var inProperties = {
    RecordID:{type:"string",value:id},
    Table:{type:"string",value:table}
  };
  
  var outProperties = {Output:1};
  
  var requestProperties = {};
  var fields = [
    "type","description","from_date","cost","price","nights","group1","group2",
    "bedrooms_double","bedrooms_twin",
    "type_of_price","nights_for_price","units_for_price","unit_type","units_other","units_minimum",
    "date_selection","date_selection_day","date_selection_date",
    "nights_selection","nights_selection_number",
    "units_for_place","double_twin","late_deal","end_date"
  ];
  var hasSelection = false;
  for (var k = 0; k < 7; k++) {
    var fieldNode = document.getElementById(ge_BOOKING_FORM+"enabled_"+k);
    var enabled = (fieldNode != null) ? fieldNode.value: 0;
    if (enabled != 1) { continue; }
    hasSelection = true;
    requestProperties["enabled_"+k] = 1;
    for (var j = 0; j < fields.length; j++) {
      var fieldNode = document.getElementById(ge_BOOKING_FORM+fields[j]+"_"+k);
      if (fieldNode != null) { 
        requestProperties[fields[j]+"_"+k] = fieldNode.value;
      }
    }
  }
  
  if (!hasSelection) {
    alert("You must select at least one booking option.");
    return false;
  }
  
  si4d_soap.setServerURL(si4d_serviceURL);
  var id = si4d_soap.callComponentService("Components/Bookings/GetAvailabilityStatus", inProperties, outProperties, requestProperties);
  var output = si4d_soap.collectComponentOutput(id, "Output");
  if (output.length > 0) {
    alert(output);
    return false;
  }
  return true;
}

/*
* check if the node has a shared update.
* Parameters:
*   none.
* Returns:
*   none.
*/
function ge_checkSharedUpdate() {
  // check if this node has a shared update.
  var sharedUpdate = false;
  var fieldNode = document.getElementById(ge_BOOKING_FORM+"shared_update_"+this.ge_index);
  if (fieldNode != null) { sharedUpdate = fieldNode.checked; }
  if (sharedUpdate) {
    // this node is shared so hunt for other shared nodes.
    for (var k = 0; k < 7; k++) {
      if (k == this.ge_index) { continue; }
      var fieldNode = document.getElementById(ge_BOOKING_FORM+"shared_update_"+k);
      if (fieldNode != null && fieldNode.checked) {
        // this is another shared node so set its value.
        var fieldNode = document.getElementById(this.ge_name+k);
        if (fieldNode != null) {
          if (this.selectedIndex != null && fieldNode.selectedIndex != null) {
            fieldNode.selectedIndex = this.selectedIndex;
          }
          else {
            fieldNode.value = this.value;
          }
        }
      }
    }
  }
  
  // calculate cost
  ge_getCost();
}

/*
* add or delete a rate band.
* Parameters:
*   index - the rate band index.
*   addFlag - if true than always include.
* Returns:
*   none.
*/
function ge_addOrDeleteRateBand(index, addFlag) {
  var fieldNode = document.getElementById(ge_BOOKING_FORM+"enabled_"+index);
  if (fieldNode == null) { return; }
  var buttonText = "+";
  var buttonKlass = "bookingRequestdataButtonPlus";
  var klass = "bookingRequestdataDisabled";
  var display = "none";
  var title="click to include in your booking";
  if (fieldNode.value == "0" || addFlag) {
    // add the rate band.
    fieldNode.value = "1";
    buttonText = "-";
    buttonKlass = "bookingRequestdataButtonMinus";
    klass = "bookingRequestdata";
    display = "block";
    title="click to exclude from your booking";
  
    fieldNode = document.getElementById(ge_BOOKING_FORM+"type_of_price_"+index);
    if (fieldNode != null && fieldNode.value == "exclusive") { 
      for (var j = 0; j < 6; j++) {
        if (j == index) { continue; }
        fieldNode = document.getElementById(ge_BOOKING_FORM+"enabled_"+j);
        if (fieldNode != null && fieldNode.value == "1") {
          ge_addOrDeleteRateBand(j);
        } 
      }
    }
  }
  else {
    // remove the rate band.
    fieldNode.value = "0";
  }
  fieldNode = document.getElementById(ge_BOOKING_FORM+"rate_button_"+index);
  if (fieldNode != null) { 
    fieldNode.className = buttonKlass;
    fieldNode.value = buttonText;
    fieldNode.title = title; 
  }
  fieldNode = document.getElementById(ge_BOOKING_FORM+"rate_"+index+"_text");
  if (fieldNode != null) { fieldNode.className = klass; }
  fieldNode = document.getElementById(ge_BOOKING_FORM+"cost_"+index+"_text");
  if (fieldNode != null) { fieldNode.className = klass; }
  fieldNode = document.getElementById(ge_BOOKING_FORM+"fields_"+index);
  if (fieldNode != null) { fieldNode.style.display = display; }
  
  // calculate cost
  ge_getCost();
}

/*
* display the cost using the request form data.
* Parameters:
*   none.
* Returns:
*   none.
*/
function ge_getCost() {
  // collect the basic properties.
  var fields = [
    "child_multiplier","deposit","currency_char",
    "towels_extra","bed_linen_extra","heating_extra","cleaning_at_end_extra",
    "local_tax_extra","payment_type"
  ];
  var properties = {
    alert: null,
    rateProperties: []
  };
  ge_getFields(properties, ge_BOOKING_FORM, fields, "");
 
  var fields = [
    "from_day","from_month","from_year","from_date",
    "nights",
    "group1","group2",
    "nights_for_price","units_for_price","type_of_price","enabled"
  ];
  var depositAllowed = true;
  var now = new Date()/1000;
  var eightWeeksFromNow = now + 60*60*24*7*8;
  var cost = 0;
  for (var j = 0; j < 7; j++) {
    var rateProperties = {enabled:0};
    ge_getFields(rateProperties, ge_BOOKING_FORM, fields, "_"+j);
    properties.rateProperties.push(rateProperties);
    var bandCost = 0;
    if (rateProperties.enabled == 1) {
      // calculate the cost for this rate band.
      if (rateProperties.nights == null) { rateProperties.nights = 0; }
      if (rateProperties.group2 == null) { rateProperties.group2 = 0; }
      // first get the date.
      rateProperties.startDate = ge_getStartDate(rateProperties);
      rateProperties.columns = ge_getNightsInRateColumns(properties, rateProperties, j);
      for (var k = 0; k < rateProperties.columns.length; k++) {
        if (rateProperties.columns[k] == 0 && rateProperties.nights_for_price > 0) { continue; }
        var rate = ge_getField("rate_"+j+"_"+k);
        if (rate == null || rate == "") {
          // as there is no rate move the nights in to the next column.
          if (k+1 < rateProperties.columns.length) {
            rateProperties.columns[k+1] += rateProperties.columns[k];
          }
          else {
            // we have run out of date ranges and we have nights not paid for.
            properties.alert = "The date and nights you have selected are not available\nfor this price band.";
            ge_setField(ge_BOOKING_FORM+"from_date_"+j);
          }
          continue; 
        }
        // add the cost for this columnm.
        var columnCost = rate;
        if (rateProperties.nights_for_price > 0) {
          var nightsMultiplier = Math.ceil(rateProperties.columns[k]/rateProperties.nights_for_price);
          columnCost *= nightsMultiplier;
        }
        if (rateProperties.units_for_price > 0) {
          if (rateProperties.group2 != null && rateProperties.group2 > 0) {
            // we have group1 and group2.
            var group1UnitsMultiplier = Math.ceil(rateProperties.group1/rateProperties.units_for_price);
            var group2UnitsMultiplier = Math.ceil(rateProperties.group2/rateProperties.units_for_price);
            group2UnitsMultiplier *= properties.child_multiplier;
            columnCost = columnCost * group1UnitsMultiplier + columnCost * group2UnitsMultiplier;
          }
          else {
            // we have only group1.
            var unitsMultiplier = Math.ceil(rateProperties.group1/rateProperties.units_for_price);
            columnCost *= unitsMultiplier;
          }
        }
        bandCost += columnCost;
        if (rateProperties.startDate > 0 && rateProperties.startDate < eightWeeksFromNow) { 
          depositAllowed = false; 
        }
      }
    }
    ge_setField(ge_BOOKING_FORM+"cost_"+j, bandCost);
    cost += bandCost;
  }
  if (isNaN(cost)) { cost = 0; }
    
  // collect any additions.
  var fields = ["towels_extra","bed_linen_extra","heating_extra","cleaning_at_end_extra","local_tax_extra"];
  for (var j = 0; j < fields.length; j++) {
    if (properties[fields[j]] != null) { cost += properties[fields[j]] * 1; }
  }
  
  // set the cost.
  ge_setField(ge_BOOKING_FORM+"total", properties.currency_char+cost);
  
  // check for deposit.
  if (properties.deposit != null && properties.deposit > 0) {
    if (depositAllowed || properties.payment_type == "allow_deposit") {
      var depositCost = cost * properties.deposit / 100;
      ge_setField(ge_BOOKING_FORM+"deposit_cost", properties.currency_char+depositCost);
    }
    else {
      ge_setField(ge_BOOKING_FORM+"deposit_cost", "N/A");
    }
  }
  
  if (properties.alert != null) {
    alert(properties.alert);
  }
}

/*
* return the start date number from the properties.
* Parameters:
*   properties - the properties object.
* Returns:
*   the normalized start date.
*/
function ge_getStartDate(properties) {
  var date = 0;
  if (properties.from_date != null && properties.from_date.length > 0) {
    var pattern = new RegExp("(\\d\\d)/(\\d\\d)/(\\d\\d\\d\\d)");
    var elements = pattern.exec(properties.from_date);
    if (elements != null && elements[1] != null && elements[2] != null && elements[3] != null) {
      var dateObj = new Date(elements[3], elements[2]-1, elements[1],12,0,0,0);
      date = dateObj.getTime() / 1000;
    }
  }
  return date;
}

/*
* return the rate columns for the date and nights.
* Parameters:
*   properties - the properties.
*   rateProperties - the rate properties.
*   band the rate band.
* Returns:
*   an array holding the number of nights in each rate column.
*/
function ge_getNightsInRateColumns(properties, rateProperties, band) {
  var date = rateProperties.startDate; // note already normalized.
  if (date == 0) {
    // this means date not relevant so put all the nights in the first column.
    return [rateProperties.nights];
  }
  rateProperties.hasColumn = false;
  var columns = [0,0,0,0,0,0,0];
  var nights = rateProperties.nights*1;
  for (var j = 0; j < 7; j++) {
    var fromDate = 0;
    var fieldNode = document.getElementById("heading_from_date_"+j);
    if (fieldNode != null) { fromDate = ge_nromalizeDate(fieldNode.value*1); }
    var toDate = 0;
    var fieldNode = document.getElementById("heading_to_date_"+j);
    if (fieldNode != null) { toDate = ge_nromalizeDate(fieldNode.value*1) - (60*60*24); }
    if (date >= fromDate && date <= toDate) {
      rateProperties.hasColumn = true;
      while (date <= toDate && nights > 0) {
        columns[j]++;
        nights--;
        date += 60*60*24;
      }
    }
  }
  if (nights > 0) {
    // we have nights left over so set error message.
    properties.alert = "The number of nights you have specified goes\noutside the current booking dates.";
    ge_setField(ge_BOOKING_FORM+"from_date_"+band);
  }
  return columns;
}

/*
* return the date normalized to midday.
* Parameters:
*   date - the date as a number (in seconds).
* Returns:
*   the date number (in seconds) that is midday for the supplied date.
*/
function ge_nromalizeDate(date) {
  var dateObj = new Date(date * 1000);
  newDate = new Date(dateObj.getFullYear(),dateObj.getMonth(),dateObj.getDate(),12,0,0,0);
  return newDate.getTime() / 1000;
}

//-------------------------- support functions ---------------------------------

/*
* set a value in a field.
* Parameters:
*   name - the field name.
*   value - the field value.
* Returns:
*   none.
*/
function ge_setField(name, value) {
  var fieldNode = document.getElementById(name);
  if (fieldNode != null) { fieldNode.value = (value != null) ? value: ""; }
  var fieldNode = document.getElementById(name+"_text");
  if (fieldNode != null) { fieldNode.innerHTML = (value != null) ? value: "&nbsp;"; }
}

/*
* get a value from a field.
* Parameters:
*   name - the field name.
* Returns:
*   the field value.
*/
function ge_getField(name) {
  var fieldNode = document.getElementById(name);
  if (fieldNode != null) { 
    if (fieldNode.options != null && fieldNode.selectedIndex != null) {
      if (fieldNode.selectedIndex > -1) {
        return fieldNode.options[fieldNode.selectedIndex].value;
      }
    }
    else {
      return fieldNode.value;
    }
  }
  return null;
}
/*
* get a value from a collection of fields.
* Parameters:
*   properties - an object to hold the properties.
*   prefix - optional field name prefix.
*   fields - the array of field names.
*   suffix - optional field name suffix.
* Returns:
*   none.
*/
function ge_getFields(properties, prefix, fields, suffix) {
  for (var j = 0; j < fields.length; j++) {
    properties[fields[j]] = ge_getField(prefix+fields[j]+suffix);
  }
}

