﻿(function ($)
{
  $.ibeWidget = function (el, options)
  {
    var base = this;

    // Access to jQuery and DOM versions of element
    base.$el = $(el);
    base.el = el;

    base.today = new Date();

    base.init = function ()
    {
      base.options = $.extend({}, $.ibeWidget.defaultOptions, options);

      //Calculate some of the other options
      base.advancedReservationDate = new Date(base.today.getTime() + (base.options.advancedReservationTime * Date.DAY));
      base.advancedReservationDate.setHours(0);
      base.advancedReservationDate.setMinutes(0);
      base.advancedReservationDate.setSeconds(0);
      base.advancedReservationDate.setMilliseconds(0);
      switch (base.options.formLanguage)
      {
        case 1:
          //English
          base.options.dateFormat = '%m/%d/%Y';
          base.options.requiredDatesMessage = "You must choose dates.";
          base.options.checkinBeforeCheckoutMessage = "Check In must be before Check Out.";
          base.options.invalidChildAges = "The ages for children are required and they must be {maxchildage} years and under.";
          base.options.childAgeLabel = "Child {!Number} Age";
          base.options.editChildAgesLink = "Edit Child Ages";
          break;
        case 2:
          //French
          base.options.dateFormat = '%d/%m/%Y';
          base.options.requiredDatesMessage = "Vous devez choisir des dates.";
          base.options.checkinBeforeCheckoutMessage = "Check In must be before Check Out.";
          base.options.invalidChildAges = "Ages des enfants sont nécessaires et elles doivent être {maxchildage} années ou moins.";
          base.options.childAgeLabel = "Âge de l'enfant {!Number}";
          base.options.editChildAgesLink = "Modifier Age des enfants";
          break;
        case 3:
          //German
          base.options.dateFormat = '%d.%m.%Y';
          base.options.requiredDatesMessage = "Bitte wählen Sie Termine.";
          base.options.checkinBeforeCheckoutMessage = "Check In must be before Check Out.";
          base.options.invalidChildAges = "Alter der Kinder erforderlich sind und sie müssen {maxchildage} Jahre oder jünger sein.";
          base.options.childAgeLabel = "Alter Kind {!Number}";
          base.options.editChildAgesLink = "Bearbeiten Alter der Kinder";
          break;
        case 4:
          //Spanish
          base.options.dateFormat = '%d/%m/%Y';
          base.options.requiredDatesMessage = "Usted debe seleccionar fechas.";
          base.options.checkinBeforeCheckoutMessage = "Check In must be before Check Out.";
          base.options.invalidChildAges = "Edades de los niños son necesarios y deben ser {maxchildage} años o más jóvenes.";
          base.options.childAgeLabel = "Edad del niño {!Number}";
          base.options.editChildAgesLink = "Editar Edades de los Niños";
          break;
        case 5:
          //Japanese
          base.options.dateFormat = '%Y/%m/%d';
          base.options.requiredDatesMessage = "選択してください日付.";
          base.options.checkinBeforeCheckoutMessage = "Check In must be before Check Out.";
          base.options.invalidChildAges = "子供の年齢は必須であり、{maxchildage}年または下でなければなりません。";
          base.options.childAgeLabel = "子供の年齢{!Number}";
          base.options.editChildAgesLink = "小児の年齢を編集";
          break;
      }

      //Setup the input fields and the calendar icons as buttons for the calendars
      Calendar.setup({
        inputField: base.options.checkinFieldId,
        button: base.options.checkinFieldId,
        onUpdate: base.UpdateCheckoutDate,
        ifFormat: base.options.dateFormat,
        align: 'Br',
        singleClick: true,
        weekNumbers: false,
        electric: false,
        cache: true,
        date: new Date(base.advancedReservationDate.getTime()),
        dateStatusFunc: function (date, y, m, d)
        {
          return base.DateStatusHandler(date, y, m, d);
        }
      });

      Calendar.setup({
        inputField: base.options.checkinFieldId,
        button: 'checkinCalendarIcon',
        onUpdate: base.UpdateCheckoutDate,
        ifFormat: base.options.dateFormat,
        align: 'Br',
        singleClick: true,
        weekNumbers: false,
        electric: false,
        cache: true,
        date: new Date(base.advancedReservationDate.getTime()),
        dateStatusFunc: function (date, y, m, d)
        {
          return base.DateStatusHandler(date, y, m, d);
        }
      });

      Calendar.setup({
        inputField: base.options.checkoutFieldId,
        button: base.options.checkoutFieldId,
        onUpdate: null,
        ifFormat: base.options.dateFormat,
        align: 'Br',
        singleClick: true,
        weekNumbers: false,
        electric: false,
        cache: true,
        date: new Date(base.advancedReservationDate.getTime()),
        dateStatusFunc: function (date, y, m, d)
        {
          return base.DateStatusHandler(date, y, m, d);
        }
      });

      Calendar.setup({
        inputField: base.options.checkoutFieldId,
        button: 'checkoutCalendarIcon',
        onUpdate: null,
        ifFormat: base.options.dateFormat,
        align: 'Br',
        singleClick: true,
        weekNumbers: false,
        electric: false,
        cache: true,
        date: new Date(base.advancedReservationDate.getTime()),
        dateStatusFunc: function (date, y, m, d)
        {
          return base.DateStatusHandler(date, y, m, d);
        }
      });

      //Process the general form fields and then pass off the settings and values to the
      //engines custom submit handler
      $("form", base.el).submit(function ()
      {
        if ($("#" + base.options.languagesFieldId).length == 1)
          base.options.languagesFieldValue = $("#" + base.options.languagesFieldId).val();
        else
          base.options.languagesFieldValue = "";
        base.options.checkinFieldValue = $("#" + base.options.checkinFieldId).val();
        base.options.checkinDate = Date.parseDate(base.options.checkinFieldValue, base.options.dateFormat);
        base.options.checkoutFieldValue = $("#" + base.options.checkoutFieldId).val();
        base.options.checkoutDate = Date.parseDate(base.options.checkoutFieldValue, base.options.dateFormat);
        base.options.nights = (base.options.checkoutDate.getTime() - base.options.checkinDate.getTime()) / Date.DAY;
        base.options.roomsFieldValue = $("#" + base.options.roomsFieldId).val();
        base.options.adultsFieldValue = $("#" + base.options.adultsFieldId).val();
        base.options.childrenFieldValue = $("#" + base.options.childrenFieldId).val();
        base.options.form = this;

        for (var i = 0; i < base.options.customFieldIds.length; i++)
        {
          var sValue = $("#" + base.options.customFieldIds[i]).val();
          base.options.customFieldValues.push(sValue);
        }

        if ($.trim(base.options.checkinFieldValue) == "" && $.trim(base.options.checkoutFieldValue) == "")
        {
          alert(base.options.requiredDatesMessage);
          return false;
        }
        else if (base.options.checkoutDate <= base.options.checkinDate)
        {
          alert(base.options.checkinBeforeCheckoutMessage);
          return false;
        }
        else if (base.options.requireChildAges == true && base.ValidChildAges() == false)
        {
          alert(base.options.invalidChildAges.replace("{maxchildage}", base.options.childrenMaxAge));
          return false;
        }
        else
        {
          if (typeof window.ibeWidgetSubmitFunction == 'function')
          {
            return window.ibeWidgetSubmitFunction(base.options);
          }
        }
      });

      //if the form requires child ages then enable the child age entry popup
      if (base.options.requireChildAges == true)
      {
        $("#" + base.options.childrenFieldId).change(function ()
        {
          base.CreateChildrenAgeDropdowns();
        });

        //LOAD DROPDOWNS ONLOAD
        base.CreateChildrenAgeDropdowns();
      }

    }

    base.UpdateCheckoutDate = function (cal)
    {
      var date = cal.date;
      var time = date.getTime()
      var field = document.getElementById(base.options.checkoutFieldId);
      if (field.value == "")
      {
        time += Date.DAY;
        var date2 = new Date(time);
        field.value = date2.print(base.options.dateFormat);
      }
    }

    base.DateStatusHandler = function (date, y, m, d)
    {
      var calDate = date.getTime();
      var limitDate = base.advancedReservationDate.getTime();

      if (calDate < limitDate)
        return true;  //disable date
      else
        return false;
    }

    base.ValidChildAges = function ()
    {
      var bValid = true;
      $(".widgetIBE .childrenAgeShell select").each(function ()
      {
        if ($(this).val() == "")
        {
          bValid = false;
        }
      });
      return bValid;
    }

    base.CreateChildrenAgeDropdowns = function ()
    {
      var formShell = $(".widgetIBE");
      //get/create children age shell
      var $childrenShell = $("#childrenShell", formShell);
      var $childrenSelect = $("select", $childrenShell);

      var $childrenAgesShell = $("#childrenAgesShell", formShell);
      if ($childrenAgesShell.length == 0)
      {
        $childrenAgesShell = $("<div id='childrenAgesShell' class='childrenAgesShell'><a href='#' class='childrenAgesShellClose'>Close</a><div class='childrenAgesPlaceholder'></div></div>");
        $childrenShell.after($childrenAgesShell);
      }
      $childrenAgesPlaceholder = $(".childrenAgesPlaceholder", $childrenAgesShell);
      $(".childrenAgesShellClose", $childrenAgesShell).click(function ()
      {
        $childrenAgesShell.hide();
        return false;
      });

      //edit ages link
      var $childrenAgesEditShell = $("#childrenAgesEditShell", formShell);
      if ($childrenAgesEditShell.length == 0)
      {
        $childrenAgesEditShell = $("<div id='childrenAgesEditShell' class='childrenAgesEditShell'><a href='#' class='childrenAgesEdit'>" + base.options.editChildAgesLink + "</a></div>");
        $childrenAgesShell.after($childrenAgesEditShell);
      }
      $(".childrenAgesEdit", $childrenAgesEditShell).click(function ()
      {
        $childrenAgesShell.show();
        return false;
      });

      //build age dropdown options for each child
      var iChildren = parseInt($("#" + base.options.childrenFieldId).val(), 10);
      if (iChildren == 0)
      {
        $childrenAgesShell.remove();
        $childrenAgesEditShell.remove();
      }
      else
      {
        var sChildrenAgeOptions = "";
        for (var i = 1; i <= iChildren; i++)
        {
          if ($("#childrenAge" + i + "Shell", formShell).length == 0)
          {
            var sChildrenAgeDropdown = "";
            sChildrenAgeDropdown += "<div id='childrenAge" + i + "Shell' class='childrenAgeShell'>";
            sChildrenAgeDropdown += "<label id='childrenAge" + i + "Label' class='childrenAgeLabel' for='childrenAge" + i + "Field'>" + base.options.childAgeLabel.replace("{!Number}", i) + "</label>";
            if (sChildrenAgeOptions == "")
            {
              sChildrenAgeOptions += "<option value=''></option>"
              for (var a = 0; a <= base.options.childrenMaxAge; a++)
              {
                sChildrenAgeOptions += "<option value= '" + a + "' >" + a + "</option>";
              }
            }
            sChildrenAgeDropdown += "<select id='childrenAge" + i + "Field' name='childrenAge" + i + "Field' class='childrenAgeField'>" + sChildrenAgeOptions + "</select>";
            sChildrenAgeDropdown += "</div>";
            $childrenAgesPlaceholder.append(sChildrenAgeDropdown);
          }
        }
        //remove any dropdowns left if they were greater than the newly selected child count
        $(".childrenAgeShell:gt(" + (iChildren - 1) + ")", formShell).remove();

        //show popup and edit link (before positioning so their presence can affect positioning)
        $childrenAgesShell.show();
        $childrenAgesEditShell.show();

        //position popup
        var windowSize = {
          scrollLeft: $(window).scrollLeft(),
          scrollTop: $(window).scrollTop(),
          width: $(window).width(),
          height: $(window).height()
        };
        var popupSize = {
          width: $childrenAgesShell.innerWidth(),
          height: $childrenAgesShell.innerHeight()
        };
        var dropdownSize = {
          width: $childrenShell.width(),
          height: $childrenShell.height()
        };
        var dropdownOffset = $childrenSelect.position();

        if (windowSize.width + windowSize.scrollLeft < dropdownOffset.left + dropdownSize.width + popupSize.width)
        {
          $childrenAgesShell.css("left", dropdownOffset.left - popupSize.width);
        }
        else
        {
          $childrenAgesShell.css("left", dropdownOffset.left + dropdownSize.width);
        }
        $childrenAgesShell.css("top", dropdownOffset.top);

      }
    }

    base.init();
  };

  $.ibeWidget.defaultOptions = {
    dateFormat: "%m/%d/%Y",
    requiredDatesMessage: "You must choose dates.",
    checkinBeforeCheckoutMessage: "Check In must be before Check Out.",
    languagesFieldValue: "",
    checkinFieldValue: "",
    checkinDate: null,
    checkoutFieldValue: "",
    checkoutDate: null,
    nights: 0,
    roomsFieldValue: "",
    adultsFieldValue: "",
    childrenFieldValue: "",
    customFieldValues: []
  };

  $.fn.ibeWidget = function (options)
  {
    return this.each(function ()
    {
      (new $.ibeWidget(this, options));
    });
  }

})(jQuery);

function distributeGuestsInRooms(iRooms, iAdults, iChildren)
{
  var iAdultsLeft = iAdults;
  var iChildrenLeft = iChildren;
  var oRoomAdults = new Array();
  var oRoomChildren = new Array();
  var iRoomIndex = 0;
  
  for (var i = 0; i < iRooms; i++)
  {
    oRoomAdults[i] = 0;
    oRoomChildren[i] = 0;
  }
  
  iRoomIndex = 0;
  while (iAdultsLeft > 0)
  {
    oRoomAdults[iRoomIndex]++;
    iAdultsLeft--;
    
    iRoomIndex++;
    if (iRoomIndex == iRooms)
    {
      iRoomIndex = 0;
    }
  }
  
  iRoomIndex = 0;
  while (iChildrenLeft > 0)
  {
    oRoomChildren[iRoomIndex]++;
    iChildrenLeft--;
    
    iRoomIndex++;
    if (iRoomIndex == iRooms)
    {
      iRoomIndex = 0;
    }
  }
  
  var oRoomDistribution = {
    roomAdults: oRoomAdults,
    roomChildren: oRoomChildren
  };
  
  return oRoomDistribution;
}

function IBEWidgetAttachGoogleAnalyticsTrackingCookiesToURL(sURL)
{
  if(typeof pageTracker == 'object')
  {
    if (typeof pageTracker._getLinkerUrl == 'function') {
      sURL = pageTracker._getLinkerUrl(sURL);
    }
  }
  
  return sURL;
}

function IBEWidgetAttachGoogleAnalyticsTrackingCookiesToAction(oForm)
{
  if(typeof pageTracker == 'object')
  {
    if (typeof pageTracker._getLinkerUrl == 'function') {
      oForm.action = pageTracker._getLinkerUrl(oForm.action);
    }
  }
}
