YAHOO.namespace("ibe.util");
YAHOO.namespace("search.calendar");


YAHOO.search.calendar.initVisible = function(params) {
  var IBE_CALENDAR = YAHOO.search.calendar;

  var addHolidays = function(calendar, holidays) {
    for (var i = 0; i < holidays.length; i++) {
      calendar.addRenderer(holidays[i], calendar.renderCellStyleHighlight3);
    }
  };

  var mindate = YAHOO.ibe.util.convertToDate(params.firstDate);
  var lastdate = YAHOO.ibe.util.convertToDate(params.lastDate);
  var holidays = new Array("1/1", "12/25", "12/26");

  var name = params.id;
  var selectedDateElement = $(name);
  var selectedDayElement = $(name + "_day");
  var selectedMonth = $(name + "_month");

  var containerId = name + "_container";
  var buttonId = name + "_button";
  var calendarContainerDivId = 'visibleCalendar_' + name; // The div where the calendar is rendered.

  var calendar = new YAHOO.widget.CalendarGroup(name, calendarContainerDivId, {
    PAGES: 1,
    START_WEEKDAY: 1,
    SHOW_WEEK_HEADER: true,
    mindate: YAHOO.ibe.util.formatDateYahoo(mindate),
    maxdate: YAHOO.ibe.util.formatDateYahoo(lastdate),
    pagedate: YAHOO.ibe.util.formatYearMonthYahoo(mindate)
  });
  addHolidays(calendar, holidays);

  var date = YAHOO.ibe.util.convertToDate(selectedDateElement.value);
  if (date != null) {
    calendar.select(date);
    calendar.cfg.setProperty("pagedate", YAHOO.ibe.util.formatYearMonthYahoo(date), false);
    YAHOO.ibe.util.selectValue(selectedDayElement, date.getDate());
    YAHOO.ibe.util.selectValue(selectedMonth, YAHOO.ibe.util.formatYearMonth(date));
  }

  if (IBE && IBE.CalendarNames) {
    calendar.cfg.setProperty("MONTHS_SHORT", IBE.CalendarNames.MONTHS_SHORT);
    calendar.cfg.setProperty("MONTHS_LONG", IBE.CalendarNames.MONTHS_LONG);
    calendar.cfg.setProperty("WEEKDAYS_1CHAR", IBE.CalendarNames.WEEKDAYS_1CHAR);
    calendar.cfg.setProperty("WEEKDAYS_SHORT", IBE.CalendarNames.WEEKDAYS_SHORT);
    calendar.cfg.setProperty("WEEKDAYS_MEDIUM", IBE.CalendarNames.WEEKDAYS_MEDIUM);
    calendar.cfg.setProperty("WEEKDAYS_LONG", IBE.CalendarNames.WEEKDAYS_LONG);
  }
  calendar.render();
  calendar.show();

  var hide = function() {
    calendar.hide();
  };

  var show = function(e) {
    calendar.show();
  };

  var select = function(type, arguments, object) {
    var selected = YAHOO.ibe.util.convertArrayToDate(arguments[0][0]);
    selectedDateElement.value = YAHOO.ibe.util.formatDate(selected);
    YAHOO.ibe.util.selectValue(selectedDayElement, selected.getDate());
    YAHOO.ibe.util.selectValue(selectedMonth, YAHOO.ibe.util.formatYearMonth(selected));
  };

  calendar.selectEvent.subscribe(select);
  calendar.hideEvent.subscribe(hide);
  calendar.showEvent.subscribe(calendar.show, calendar, true);

  /**
   *This funtion sets the selected date on the calendar when the date is changed via the HTML select element (drop-down).
   */
  var selectChange = function() {
    var day = selectedDayElement.value;
    var yearMonth = selectedMonth.value;
    if (YAHOO.ibe.util.isEmpty(day) || YAHOO.ibe.util.isEmpty(yearMonth)) {
      selectedDateElement.value = "";
      calendar.deselectAll();
    } else {
      var selectedDate = YAHOO.ibe.util.convertToDate(yearMonth + "-" + day);
      selectedDateElement.value = YAHOO.ibe.util.formatDate(selectedDate);
      calendar.select(selectedDate);
      calendar.cfg.setProperty("pagedate", YAHOO.ibe.util.formatYearMonthYahoo(selectedDate), false);
    }
    calendar.render();
  };

  YAHOO.util.Event.addListener(selectedDayElement.id, "change", selectChange);
  YAHOO.util.Event.addListener(selectedMonth.id, "change", selectChange);

  IBE_CALENDAR[name] = calendar;
};

YAHOO.search.calendar.hiddenChanged = function(hidden) {
  var IBE_CALENDAR = YAHOO.search.calendar;
  if (IBE_CALENDAR.hiddenChanged.active) {
    var l = YAHOO.util.Event.getListeners(hidden)[0];
    l.fn.call(YAHOO.util.Dom.get(hidden), l.type, null, l.obj);
  }
};

YAHOO.search.calendar.bindVisible = function(params) {
  var IBE_CALENDAR = YAHOO.search.calendar;

  var returnDateElementId = params.ret;
  var returnDateElement = $(returnDateElementId);
  var selectedDayElement = $(returnDateElementId + "_day");
  var selectedMonthElement = $(returnDateElementId + "_month");
  var departureDateElement = $(params.dep);

  var departureDateCalendar = IBE_CALENDAR[params.dep];
  var returnDateCalendar = IBE_CALENDAR[params.ret];

  var selectDepartureDate = function(type, arguments, object) {
    var inboundDates = returnDateCalendar.getSelectedDates();
    var inboundDate = (inboundDates == null || inboundDates.length == 0) ? null : inboundDates[0];
    var outboundDate = arguments ? YAHOO.ibe.util.convertArrayToDate(arguments[0][0]) : null;
    //var outboundDate = YAHOO.ibe.util.convertArrayToDate(arguments[0][0]);
    if (inboundDate == null || outboundDate > inboundDate) {
      returnDateElement.value = "";
      YAHOO.ibe.util.selectValue(selectedDayElement, "");
      YAHOO.ibe.util.selectValue(selectedMonthElement, "");
      returnDateCalendar.deselectAll();
    }
    returnDateCalendar.cfg.setProperty("mindate", outboundDate, false);
    returnDateCalendar.cfg.setProperty("pagedate", YAHOO.ibe.util.formatYearMonthYahoo(outboundDate), false);
    returnDateCalendar.render();
  };

  departureDateCalendar.selectEvent.subscribe(selectDepartureDate);

  // Set departure date selected on load (if there is a departure date already selected). This is resolves the bug
  // where the return date is set to 3999.
  if (departureDateElement) {
    var date = YAHOO.ibe.util.convertDateToYahooArray(departureDateElement.value);
    selectDepartureDate("select", date, params);
  }

  IBE_CALENDAR.hiddenChanged.active = false;
  if (params.box && params.box.useBox && params.box.startDate && params.box.endDate) {
    IBE_CALENDAR.hiddenChanged.active = true;
    var boxDisplay = function(type, arguments, object) {
      var hiddenDate = YAHOO.ibe.util.convertToDate(params.value);
      if (hiddenDate) {
        if (object.who === 'dep') {
          var startDate = YAHOO.ibe.util.convertToDate(object.cfg.startDate);
          if (hiddenDate.getTime() < startDate.getTime()) {
            object.cfg.dep = true;
          } else {
            object.cfg.dep = false;
          }
        } else {
          var endDate = YAHOO.ibe.util.convertToDate(object.cfg.endDate);
          if (hiddenDate.getTime() > endDate.getTime()) {
            object.cfg.ret = true;
          } else {
            object.cfg.ret = false;
          }
        }
      } else {
        if (object.who === 'dep') {
          object.cfg.dep = undefined;
        } else {
          object.cfg.ret = undefined;
        }
      }

      //ibelog("who: "+object.who+" hidden: " + hiddenDate + "   ret: " +object.cfg.ret + "   dep: "+object.cfg.dep)
      if ((object.cfg.ret || object.cfg.dep) && (object.cfg.dep !== undefined && object.cfg.ret !== undefined)) {
        //ibelog("show it")
        YAHOO.util.Dom.replaceClass(object.cfg.boxId, "removed", "warningbox")
      } else {
        //ibelog("hide it")
        YAHOO.util.Dom.replaceClass(object.cfg.boxId, "warningbox", "removed")
      }
      return "ICompletedMyTask";
    };
    YAHOO.util.Event.addListener(params.dep, "change", boxDisplay, {'cfg':params.box, 'who':'dep'});
    YAHOO.util.Event.addListener(params.ret, "change", boxDisplay, {'cfg':params.box, 'who':'ret'});
  }

};

YUI({
  modules :{
    'ibe-anim' : {}
  }
}).use('node', 'anim', 'ibe-anim', function(Y) {

  /**
   * Shows and hides return date calendar for air search and also shows hotel calendars if oneway-trip is selected.
   *
   * @param returnDateRowId Div id where the return date calendar is located.
   * @param onewayId Checkbox id for the oneway trip.
   * @param partialHotelId Checkbox id for the partial hotel dates calendars.
   * @param hotelDatesId The html element id for the hotel dates. (initially when the page is loaded it's hidden).
   */
  YAHOO.search.calendar.onewaySearch = function(returnDateRowId, onewayId, partialHotelId, hotelDatesId) {
    var onewayCheckbox = Y.one('#' + onewayId);
    var partialHotelCheckbox = Y.one('#' + partialHotelId);
    var returnDateNode = Y.one('#' + returnDateRowId);
    if (onewayCheckbox.get('checked')) {
      var fade = new Y.IBEFade(returnDateRowId, {duration:0.2});
      // when the animation has finished -- set display none.
      fade.anim.on('end', function() {
        fade.node.setStyle('visibility', 'hidden');
      });
      fade.fadeOut();
      if (partialHotelCheckbox != null) {
        partialHotelCheckbox.set('checked', true);
        toggleLayer(hotelDatesId, true); // Display hotel dates, since oneway trip option is selected.
      }
    } else {
      if (returnDateNode.getStyle('visibility') == 'hidden') returnDateNode.setStyle('visibility', 'visible');
      if (returnDateNode.getStyle('display') == 'none') returnDateNode.setStyle('display', 'block');
      new Y.IBEFade(returnDateRowId, {duration:0.2}).fadeIn();
      if (partialHotelCheckbox != null) {
        partialHotelCheckbox.set('checked', false);
        toggleLayer(hotelDatesId, false); // Hide hotel dates, since one way trip option is not selected.
      }
    }
  }
});

