$(document).ready(function() {
  makeMenu();
  regionCityHandler();
  preventFormDoubleClick();
  refreshWatchlistCounter();
  addCalendars();
  prepareMaps();
});

function makeMenu() {
  $("#main-menu").supersubs({
    minWidth: 9,
    maxWidth: 30,
    extraWidth: 0.5
  }).superfish();
  $("#main-menu ul ul").each(function(){
    //alert($(this).parent().css("width"));
    $(this).css("left",$(this).parent().parent().css("width"));
  });
}

function addCalendars()
{
  $('#date-from').datepicker({
    dateFormat: 'dd.mm.yy',
    defaultDate: 14,
    minDate: "0",
    maxDate: "+300",
    onSelect: function(dateText, inst) {
      setMinDate($("#date-to"),dateText);
    }
  });

  var dateTo = $("#date-to");
  var dateFrom = $("#date-from");
  /*
    Set date-to to date-from value if it was changed by hand instead
    of selecting date in datepicker
  */
  $('#date-from').change(function(e) {
    if (checkDate($(this),'von'))
    {
      if (!checkMaxSearchPeriod($(this).val(), dateTo.val()))
      {
        alert("Maximal 27 Nächte Nächte in der Suche erlaubt.");
        return false;
      }
      setMinDate(dateTo,$(this).val());
    }
    return false;
  });

  $('#date-to').change(function(e) {
    if (checkDate($(this),'bis'))
    {
      if (!checkMaxSearchPeriod(dateFrom.val(), $(this).val()))
      {
        alert("Maximal 27 Nächte Nächte in der Suche erlaubt.");
        return;
      }
    }
    return false;
  })
  
  dateTo.datepicker({
    dateFormat: 'dd.mm.yy',
    defaultDate: 21,
    minDate: "0",
    maxDate: "+300"
  });
}

/**
 * Initialize colorbox for google map.
 */
function prepareMaps()
{
  $("#maps").colorbox({innerWidth: 980, innerHeight: 620, scrolling: false, iframe:true});
}

/**
 * Registers change handler on "region" and "city" select list.
 * If region/city is selected the selection from the other is removed.
 */
function regionCityHandler()
{
  $("#region").bind("keydown.loadSelectOptions mousedown.loadSelectOptions click.loadSelectOptions", function(event){
    loadSelectOptions(event.target, "hofer_aldi.search_regions", "Error on loading search regions");
  });

  $("#region").change(function() {
    removeSelection($("#city"));
  });

  $("#city").bind("keydown.loadSelectOptions mousedown.loadSelectOptions click.loadSelectOptions", function(event){
    loadSelectOptions(event.target, "hofer_aldi.search_locations", "Error on loading search locations");
  });
  
  $("#city").change(function() {
    removeSelection($("#region"));
  });
}

/**
 * Loads select options by ajax request to procedure with given name
 */
function loadSelectOptions(selectControl, procedureName, errorMessage)
{
  $.ajax({
    type: 'POST',
    url: '/business/' + procedureName,
    async: false,
    data: {},
    success: function(data){
      $(selectControl).html(data);
      $(selectControl).unbind(".loadSelectOptions");
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert(errorMessage);
      return false;
    }
  });
}

/**
 * Removes all selection attribute from the given select object.
 * @param {Object} selectObj The select-list selector object.
 */
function removeSelection(selectObj)
{
  $(selectObj).attr("value", "");
}

/**
 * Sets defaultDate and minDate of datepicker.
 * @param {Object} obj Selector of datepicker textfield on which the new date should be set.
 * @param {string} date The new date value for the datepicker.
 */
function setMinDate(obj,date)
{
  $(obj).datepicker("option", "defaultDate", date);
  $(obj).datepicker("option", "minDate", date);
}

/**
 * Checks if the given date is in the correct date format "[d]d.[m]m.yyyy".
 * @param {Object} inputObj The selector object of the date input field.
 * @param {string} name The name of the date input field used for the error message.
 * @return {boolean} False if date is not in correct format.
 */
function checkDate(inputObj,name)
{
  if (!isValidDate(inputObj.val(),'dmy',4))
  {
    alert("Ungültiges Format. Bitte geben Sie das \"" + name + "\"-Datum im Format \"DD.MM.YYYY\" ein.");
    return false;
  }
}

/**
 * Checks if the serch period is greater than 28 days on new hofer site.
 * @param {string} fromDate The date-from value.
 * @param {string} toDate The date-to value.
 * @return {boolean} True if ok, false if search period too large.
 */
function checkMaxSearchPeriod()
{
  var dur = calcDuration();
  if(dur && dur < 28)
    return true;
  else
    return false;
}

function refreshWatchlistCounter()
{
  countBasket("watchlist_counter");
}

function addToWatchlist(p_offerCode)
{
  addSvnoToBasket(p_offerCode, "watchlist_counter");
}

function removeFromWatchlist(p_offerCode, caller)
{
  delSvnoFromBasket(p_offerCode, "watchlist_counter");
  $(caller).parent().parent().parent().hide("fade", {}, 1000);
  $(caller).empty().remove();
}

function preventFormDoubleClick() {
  $('form').submit(function(){
    $(this).find('input[type="submit"]').attr('disabled', 'disabled');
  });
}

