com.bezurk.namespace('com.bezurk.calendar');

/** Event handlers. **/
YAHOO.util.Event.addListener(window, 'load', function() {
  // Initialize AutoComplete widget.
  com.bezurk.hotels.LocationsAutoComplete.onItemSelect = function(type, args) {
    var result = args[2];

    var textbox = args[0]._oTextbox;
    var query = textbox.value;

    textbox.value = com.bezurk.hotels.LocationsAutoComplete.constructLocationDisplay(result, query, false);
    document.getElementById('locationCode').value = result.locationCode;
  };
  com.bezurk.hotels.LocationsAutoComplete.init('location', 'location-results');

  // Clear the location textfield.
  document.getElementById('location').value = '';

  // Initialize calendars.
  var today = new Date();

  var defaultCheckInDate = new Date();
  defaultCheckInDate.setDate(today.getDate()+7);
  var defaultCheckInDay = defaultCheckInDate.getDate(), defaultCheckInMonth = defaultCheckInDate.getMonth()+1, defaultCheckInYear = defaultCheckInDate.getFullYear();
  var defaultCheckOutDate = new Date();
  defaultCheckOutDate.setDate(today.getDate()+9);
  var defaultCheckOutDay = defaultCheckOutDate.getDate(), defaultCheckOutMonth = defaultCheckOutDate.getMonth()+1, defaultCheckOutYear = defaultCheckOutDate.getFullYear();

  // Set the textbox date values.
  document.getElementById('checkInDate').value = defaultCheckInDay+'/'+defaultCheckInMonth+'/'+defaultCheckInYear;
  document.getElementById('checkOutDate').value = defaultCheckOutDay+'/'+defaultCheckOutMonth+'/'+defaultCheckOutYear;
  // And the actual hidden date values in the correct format. (TODO: Hopefully we can get rid of this once the backend is changed to accept alternative date formats.)
  document.getElementById('fromDate').value = defaultCheckInYear+'-'+defaultCheckInMonth+'-'+defaultCheckInDay;
  document.getElementById('toDate').value = defaultCheckOutYear+'-'+defaultCheckOutMonth+'-'+defaultCheckOutDay;

  com.bezurk.calendar.calCheckIn = new YAHOO.widget.Calendar('calCheckIn', 'calCheckInContainer', {
    pagedate : defaultCheckInMonth+'/'+defaultCheckInYear,
    selected : defaultCheckInMonth+'/'+defaultCheckInDay+'/'+defaultCheckInYear,
    mindate : today,
    title : 'Check in:',
    close: true,
    iframe : true,
    LOCALE_WEEKDAYS : '1char',
    HIDE_BLANK_WEEKS : true
  });
  com.bezurk.calendar.calCheckIn.selectEvent.subscribe(com.bezurk.calendar.handleCheckInSelect, com.bezurk.calendar.calCheckIn, true);
  com.bezurk.calendar.calCheckIn.render();

  com.bezurk.calendar.calCheckOut = new YAHOO.widget.Calendar('calCheckOut', 'calCheckOutContainer', {
    pagedate : defaultCheckOutMonth+'/'+defaultCheckOutYear,
    selected : defaultCheckOutMonth+'/'+defaultCheckOutDay+'/'+defaultCheckOutYear,
    mindate : today,
    title : 'Check out:',
    close: true,
    iframe : true,
    LOCALE_WEEKDAYS : '1char',
    HIDE_BLANK_WEEKS : true
  });
    com.bezurk.calendar.calCheckOut.selectEvent.subscribe(com.bezurk.calendar.handleCheckOutSelect, com.bezurk.calendar.calCheckOut, true);
  com.bezurk.calendar.calCheckOut.render();
});

// selectEvent handlers for calendars (TODO: really needs DRYing up).
com.bezurk.calendar.handleCheckInSelect = function(type, args, obj) {
  var selectedDate = args[0][0]; // First (and only) selected date.
  var year = selectedDate[0], month = selectedDate[1], day = selectedDate[2];
  document.getElementById('checkInDate').value = day+'/'+month+'/'+year;
  document.getElementById('fromDate').value = year+'-'+month+'-'+day;
  obj.hide();
}
com.bezurk.calendar.handleCheckOutSelect = function(type, args, obj) {
  var selectedDate = args[0][0]; // First (and only) selected date.
  var year = selectedDate[0], month = selectedDate[1], day = selectedDate[2];
  document.getElementById('checkOutDate').value = day+'/'+month+'/'+year;
  document.getElementById('toDate').value = year+'-'+month+'-'+day;
  obj.hide();
}

// For showing calendars when text fields are clicked.
YAHOO.util.Event.addListener('checkInDate', 'click', function() {
  com.bezurk.calendar.calCheckIn.show();
});
YAHOO.util.Event.addListener('checkOutDate', 'click', function() {
  com.bezurk.calendar.calCheckOut.show();
});

// For hiding calendars on click away.
YAHOO.util.Event.addListener(document, 'click', function(e) {
  var target = (e && e.target) || (event && event.srcElement);
  if (target.id != 'checkInDate') {
    if (document.getElementById('calCheckInContainer').style.display == 'block') {
      if (!com.bezurk.calendar.checkParentIsCalendarDiv(target, 'calCheckInContainer')) {
        document.getElementById('calCheckInContainer').style.display = 'none';
      }
    }
  }
  if (target.id != 'checkOutDate') {
    if (document.getElementById('calCheckOutContainer').style.display == 'block') {
      if (!com.bezurk.calendar.checkParentIsCalendarDiv(target, 'calCheckOutContainer')) {
        document.getElementById('calCheckOutContainer').style.display = 'none';
      }
    }
  }
});
// For hiding calendars on ESC key being pressed.
YAHOO.util.Event.addListener(document, 'keypress', function(e) {
  if (e.keyCode == 27) {
    if (document.getElementById('calCheckOutContainer').style.display == 'block') {
      document.getElementById('calCheckOutContainer').style.display = 'none';
    }
    if (document.getElementById('calCheckInContainer').style.display == 'block') {
      document.getElementById('calCheckInContainer').style.display = 'none';
    }
  }
});
com.bezurk.calendar.checkParentIsCalendarDiv = function(t, calendarDivId){
  while (t.parentNode) {
    if (t == document.getElementById(calendarDivId)) {
      return true;
    }
    t = t.parentNode;
  }
  return false;
}

// Handler for popular destination radio boxes being selected.
var popularDestinations = {
  bangkok : { name : 'Bangkok, Thailand', code : 'BKK'},
  beijing : { name : 'Beijing, China', code : 'BJS'},
  hongkong : { name : 'Hong Kong, China', code : 'HKG'},
  sydney : { name : 'Sydney, NSW, Australia', code : 'SYD'},
  bali : { name : 'Bali, Indonesia', code : 'DPS'},
  phuket : { name : 'Phuket, Thailand', code : 'HKT'},
  shanghai : { name : 'Shanghai, China', code : 'SHA'},
  singapore : { name : 'Singapore, Singapore', code : 'SIN'},
  melbourne : { name : 'Melbourne, VIC, Australia', code : 'MEL'},
  london : { name : 'London, United Kingdom', code : 'LON'}
};
for (id in popularDestinations) {
  if (popularDestinations.hasOwnProperty(id)) {
    YAHOO.util.Event.addListener(id, 'click', function(event, location) {
        console.debug(location);
        document.getElementById('location').value = location.name;
        document.getElementById('locationCode').value = location.code;
    }, popularDestinations[id]);
  }
}

// onSubmit handler for search form.
YAHOO.util.Event.addListener('bezurk_hotel_search', 'submit', function(event) {
  if (!com.bezurk.hotels.searchHotels()) {
    YAHOO.util.Event.stopEvent(event);
  }
});

com.bezurk.hotels.searchHotels = function() {
  // Validation
  if (document.getElementById('location').value.length == 0) {
    alert('Please enter where you would like to stay');
    return false;
  }

  if (!document.getElementById('fromDate').value) {
    alert('Please enter a valid check-in date DD/MM/YYYY');
    return false;
  }
  if (!document.getElementById('toDate').value) {
    alert('Please enter a valid check-out date DD/MM/YYYY');
    return false;
  }

  // Dates can't be in the past.
  var checkInDate = com.bezurk.hotels.parseDate(document.getElementById('checkInDate').value);
  var checkOutDate = com.bezurk.hotels.parseDate(document.getElementById('checkOutDate').value);

  if (checkInDate < new Date()) {
    alert('Your check-in date can\'t be in the past');
    return false;
  }
  if (checkOutDate < new Date()) {
    alert('Your check-out date can\'t be in the past');
    return false;
  }

  // Make sure check-in date is before check-out date
  if (checkOutDate != null && checkInDate != null) {
    if (checkOutDate < checkInDate) {
      alert('Your check-in date must be before the check-out date');
      return false;
    }
  }

  // Format dates correctly.
  document.getElementById('fromDate').value = checkInDate.getFullYear() + '-' + (checkInDate.getMonth()+1) + '-' + checkInDate.getDate();
  document.getElementById('toDate').value = checkOutDate.getFullYear() + '-' + (checkOutDate.getMonth()+1) + '-' + checkOutDate.getDate();

  return true;
}

com.bezurk.hotels.parseDate = function(dateString, dateFormat) {
  // TODO dateFormat isn't actually being used at the moment, only dd/mm/yyyy format is accepted

  var pieces = dateString.split('/');
  if (pieces.length != 3) {
    return null;
  }

  var date = new Date();
  date.setFullYear(pieces[2], pieces[1]-1, pieces[0]);

  return date;
}


YAHOO.util.Event.addListener('location', 'focus', function() {
  document.getElementById('location').select();
});

// Check for Firebug and whether to debug.
var debug = window.location.href.indexOf('debug') > -1;
if (!('console' in window) || !('firebug' in console) || !debug) {
  (function() {
      window.console =  {
          log: function(){},
          debug: function(){},
          info: function(){},
          warn: function(){},
          error: function(){}
      };

  })();
}
