YAHOO.namespace("ibe.util");

YAHOO.ibe.util.selectValue = function(select, value) {
  var options = select.options;
  for (var i = 0; i < options.length; i++) {
    var option = options[i];
    if (option.value == value) {
      option.selected = true;
    }
  }
};

YAHOO.ibe.util.isEmpty = function(string) {
  return string == null || string.length == 0;
};

YAHOO.ibe.util.convertToDate = function(string) {
  if (YAHOO.ibe.util.isEmpty(string)) {
    return null;
  } else {
    var arr = string.split("-");
    return YAHOO.ibe.util.convertArrayToDate(arr);
  }
};

YAHOO.ibe.util.convertArrayToDate = function(arr) {
  return new Date(arr[0], arr[1] - 1, arr[2]);
};

/**
 * This method is used to fire a select date event, without clicking on a date.
 *
 * @param date is a String on the format YYYY-MM-dd.
 *
 * @return arguments array [[[2010, 1, 23]]].
 */
YAHOO.ibe.util.convertDateToYahooArray = function(date) {
  if (date) {
    var args = date.split('-');
    return [
      [
        [(+args[0]), (+args[1]), (+args[2])]
      ]
    ];
  }
};

YAHOO.ibe.util.formatDateYahoo = function(date) {
  if (date == null) return null;
  return (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
};

YAHOO.ibe.util.formatYearMonthYahoo = function(date) {
  if (date == null) return null;
  return (date.getMonth() + 1) + "/" + date.getFullYear();
};

YAHOO.ibe.util.formatYearMonth = function(date) {
  var month = date.getMonth() + 1;
  if (month < 10) {
    month = "0" + month;
  }
  return date.getFullYear() + "-" + month;
};

YAHOO.ibe.util.formatDate = function(date) {
  var day = date.getDate();
  if (day < 10) {
    day = "0" + day;
  }
  return YAHOO.ibe.util.formatYearMonth(date) + "-" + day;
};


YAHOO.namespace("search.calendar");

YAHOO.search.calendar.init = function() {
  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(this.firstDate);
  var lastdate = YAHOO.ibe.util.convertToDate(this.lastDate);
  var holidays = new Array("1/1", "12/25", "12/26");

  var name = this.id;
  var hiddenValue = getObj(name);
  var daySelect = getObj(name + "_day");
  var monthSelect = getObj(name + "_month");

  var containerId = name + "_container";
  var buttonId = name + "_button";

  var overlay = new YAHOO.widget.Overlay(containerId, {
    context: [ buttonId, "tl", "tr" ] // align top left of calendar to top right of button
  });
  overlay.render(document.body);
  overlay.hide();

  var calendar = new YAHOO.widget.CalendarGroup(name, overlay.id, {
    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),
    title: this.title,
    close: true
  });
  addHolidays(calendar, holidays);
  var date = YAHOO.ibe.util.convertToDate(hiddenValue.value);
  if (date != null) {
    calendar.select(date);
    calendar.cfg.setProperty("pagedate", YAHOO.ibe.util.formatYearMonthYahoo(date), false);
    YAHOO.ibe.util.selectValue(daySelect, date.getDate());
    YAHOO.ibe.util.selectValue(monthSelect, 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.hide();

  var hide = function() {
    overlay.hide();
    // YAHOO.util.Event.removeListener(document.body, "click", calendar.hide);
  };
  var show = function(e) {
    calendar.show();
    overlay.align();
    // YAHOO.util.Event.addListener(document.body, "click", calendar.hide, calendar, true);
    // YAHOO.util.Event.stopEvent(e);
  };
  YAHOO.util.Event.addListener(buttonId, "click", show);

  var select = function(type, arguments, object) {
    var selected = YAHOO.ibe.util.convertArrayToDate(arguments[0][0]);
    hiddenValue.value = YAHOO.ibe.util.formatDate(selected);
    /*YAHOO.search.calendar.hiddenChanged(hiddenValue.id);*/
    YAHOO.ibe.util.selectValue(daySelect, selected.getDate());
    YAHOO.ibe.util.selectValue(monthSelect, YAHOO.ibe.util.formatYearMonth(selected));
    calendar.hide();
  };
  calendar.selectEvent.subscribe(select);
  calendar.hideEvent.subscribe(hide);
  calendar.showEvent.subscribe(overlay.show, overlay, true);

  /**
   * This funtion sets the selected date on the calendar when the date is changed via the HTML select element.
   */
  var selectChange = function() {
    var day = daySelect.value;
    var yearMonth = monthSelect.value;
    if (YAHOO.ibe.util.isEmpty(day) || YAHOO.ibe.util.isEmpty(yearMonth)) {
      hiddenValue.value = "";
      calendar.deselectAll();
    } else {
      var selectedDate = YAHOO.ibe.util.convertToDate(yearMonth + "-" + day);
      hiddenValue.value = YAHOO.ibe.util.formatDate(selectedDate);
      calendar.select(selectedDate);
      calendar.cfg.setProperty("pagedate", YAHOO.ibe.util.formatYearMonthYahoo(selectedDate), false);
    }
    /*YAHOO.search.calendar.hiddenChanged(hiddenValue.id);*/
    calendar.render();
  };
  YAHOO.util.Event.addListener(daySelect.id, "change", selectChange);
  YAHOO.util.Event.addListener(monthSelect.id, "change", selectChange);

  YAHOO.search.calendar[name] = calendar;
};

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

YAHOO.search.calendar.bind = function() {
  var name = this.ret;
  var hiddenValue = getObj(name);
  var daySelect = getObj(name + "_day");
  var monthSelect = getObj(name + "_month");
  var departureDateElement = getObj(this.dep);

  var outboundCal = YAHOO.search.calendar[this.dep];
  var inboundCal = YAHOO.search.calendar[this.ret];

  var selectOutbound = function(type, arguments, object) {
    var inboundDates = inboundCal.getSelectedDates();
    var inboundDate = (inboundDates == null || inboundDates.length == 0) ? null : inboundDates[0];

    var outboundDate = YAHOO.ibe.util.convertArrayToDate(arguments[0][0]);
    if (inboundDate == null || outboundDate > inboundDate) {
      hiddenValue.value = "";
      /*YAHOO.search.calendar.hiddenChanged(hiddenValue.id);*/
      YAHOO.ibe.util.selectValue(daySelect, "");
      YAHOO.ibe.util.selectValue(monthSelect, "");
      inboundCal.deselectAll();
    }
    inboundCal.cfg.setProperty("mindate", outboundDate, false);
    inboundCal.cfg.setProperty("pagedate", YAHOO.ibe.util.formatYearMonthYahoo(outboundDate), false);
    inboundCal.render();
  };
  outboundCal.selectEvent.subscribe(selectOutbound);

  // 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);
    selectOutbound("select", date, this);
  }

  YAHOO.search.calendar.hiddenChanged.active = false;
  if (this.box && this.box.useBox && this.box.startDate && this.box.endDate) {
    YAHOO.search.calendar.hiddenChanged.active = true;
    var boxDisplay = function(type, arguments, object) {
      var hiddenDate = YAHOO.ibe.util.convertToDate(this.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;
        }
      }

      //console.log("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)) {
        //console.log("show it")
        YAHOO.util.Dom.replaceClass(object.cfg.boxId, "removed", "warningbox")
      } else {
        //console.log("hide it")
        YAHOO.util.Dom.replaceClass(object.cfg.boxId, "warningbox", "removed")
      }
      return "ICompletedMyTask";
    };
    YAHOO.util.Event.addListener(this.dep, "change", boxDisplay, {'cfg':this.box, 'who':'dep'});
    YAHOO.util.Event.addListener(this.ret, "change", boxDisplay, {'cfg':this.box, 'who':'ret'});
  }
};

