var
  animateDuration = 250,

  reveal = function(element, callback)
  {
    var height = $(element).height();

    $(element).css({height: 0, opacity: 0}).animate({
      height: height + 'px',
      opacity: 1
    }, animateDuration, 'swing', function()
    {
        if (callback != undefined) callback();
    });
  },

  dropdown = {
    all: [],

    close: function(i)
    {
      var container = this.all[i];
      if (!container.isOpen) return;

      container.options.fadeOut(animateDuration, function()
      {
        container.removeClass('open');
        container.isOpen = false;
      });
    },

    closeAll: function()
    {
      for (var i in this.all)
        if (this.all[i].isOpen)
          this.close(i);
    },

    open: function(i)
    {
      var container = this.all[i];
      if (container.isOpen) return;

      container.addClass('open');

      reveal(container.options, function() { container.isOpen = true; });
    },

    toggle: function(i)
    {
      if (this.all[i].isOpen) this.close(i);
      else this.open(i);
    },

    append: function(element)
    {
      var
        container = $(element),
        value = container.find('.value'),
        options = container.find('ul'),
        position = this.all.length,
        width =
          container.width() +
          parseInt(container.css('padding-left')) +
          parseInt(container.css('padding-right'));

      if ($.browser.msie && $.browser.version < 7)
      {
        width -= 10;
      }

      options.
        find('a').
        css('width', width + 'px');

      options.
        css('width', width + 'px').
        find('li').click(function()
        {
          var li = $(this);

          value.find('span').text(li.text());
          options.find('li').removeClass('selected');
          li.addClass('selected');
        });

      container.isOpen = false;
      container.value = value.click(function() { dropdown.toggle(position); });
      container.options = options;

      container.click(function(event)
      {
        if ($(event.target).hasClass('dropdown'))
        {
          value.click();
        }
      });

      dropdown.all.push(container);
    },

    fromSelect: function(element, caption)
    {
      var e = $(element), selected = e.val(), html, items = '';

      e.find('option').each(function()
      {
        var itemSelected, value = $(this).val(), onclick;

        if (selected == value) itemSelected = ' class="selected"';
        else itemSelected = '';

        onclick = "$('#" + e.attr('id') + "').val('" + value + "')";

        items +=
          '<li' + itemSelected + '>' +
            '<a href="javascript:void(0)" onclick="' + onclick + '">' +
              value +
            '</a>' +
          '</li>';
      });

      html =
        '<div class="dropdown">' +
          '<div class="value">' +
            '<em>' + caption + ':</em> ' +
            '<span>' + selected + '</span>' +
          '</div>' +
          '<ul>' + items + '</ul>' +
        '</div>';

      $(element).
        css({position: 'absolute', top: '-9999px'}).
        before(html);
    },

    init: function()
    {
      $('.dropdown').each(function() { dropdown.append(this); });

      var close = function() { dropdown.closeAll(); };
      $('body').click(close);
      $(window).blur(close).scroll(close);
    }
  },

  lightLabel = {
    className: 'clear',

    elementEmpty: function(element)
    {
      var e = $(element), value = e.val(), initialText = e.data('initialText');
      return value.replace(/^\s+|\s+$/, '').length == 0 || value == initialText;
    },

    elementsEmpty: function(elements)
    {
      for (var i in elements)
      {
        if (this.elementEmpty(elements[i])) return true;
      }
      return false;
    },

    set: function(element, initialText)
    {
      $(element).
        data('initialText', initialText).
        blur(function()
        {
          var e = $(this);
          if (lightLabel.elementEmpty(e))
            e.addClass(lightLabel.className).val(e.data('initialText'));
        }).
        focus(function()
        {
          var e = $(this);
          if (e.val() == e.data('initialText')) e.val('');
          e.removeClass(lightLabel.className);
        }).
        blur();
    },

    onElementsChanged: function(elements, callbackFilled, callbackEmpty)
    {
      var changeFunction = function()
      {
        var empty = lightLabel.elementsEmpty(elements);

        if (callbackEmpty != undefined && empty)
          callbackEmpty();
        else if (callbackFilled != undefined && !empty)
          callbackFilled();
      }

      for (var i in elements)
      {
        $(elements[i]).keyup(changeFunction).change(changeFunction);
      }
    }
  },

  smoothScroll = {
    init: function()
    {
      var base = window.location.href.replace(/#.*$/, '');

      $('a').each(function()
      {
        if (this.href.indexOf(base + '#') > -1)
        {
          var anchor = this.href.replace(base + '#', '');
          if (anchor.length > 0)
          {
            $(this).click(function(event)
            {
              $.scrollTo(
                'a[name=' + anchor + ']',
                animateDuration * 1.5, {
                  onAfter: function()
                  {
                    window.location.href = base + '#' + anchor;
                  }
                });
              event.preventDefault();
              event.stopPropagation();
            });
          }
        }
      });
    }
  },

  go = function(url)
  {
    window.location.href = url;
  },

  unique = 0,

  map = function (lat, lon, zoom)
  {
    var id = 'map' + (unique++);
    document.write('<div id="' + id + '" class="map"></div>');
    var map = new YMap(id), point = new YGeoPoint(lat, lon);
    map.addZoomLong();
    map.setMapType(YAHOO_MAP_REG);
    map.disableKeyControls();
    map.removeZoomScale();
    map.drawZoomAndCenter(point, zoom);
    map.addOverlay(new YMarker(point));
  },

  dateRange = function(startElement, endElement, options)
  {
    var
      dateInputID = null,
      start = startElement.attr('id'),
      end = endElement.attr('id'),
      dates = {};

    dates[start] = null;
    dates[end] = null;

    // numberOfMonths: [2, 3],
    // showOtherMonths: true,
    // showCurrentAtPos: 1,
    $.datepick.setDefaults({
      mandatory: true,
      showWeeks: true,
      highlightWeek: true,
      changeYear: true,
      showAnim: 'fadeIn',
      duration: 'normal',
      constrainInput: true,
      minDate: new Date,
      onClose: function()
      {
        $('#' + dateInputID).removeClass('clear');
      },
      onSelect: function(value, date)
      {
        dates[dateInputID] = date;
      }});

    var mousedown = function()
    {
      dateInputID = this.id;

      var minDate, maxDate;

      if (dateInputID == start)
      {
        minDate = new Date;
        if (dates[end] != null)
        {
          maxDate = new Date(dates[end]);
          maxDate.setDate(maxDate.getDate() - 1);
        }
        else
        {
          maxDate = null;
        }
      }
      else if (dateInputID == end)
      {
        if (dates[start] != null) minDate = dates[start];
        else minDate = new Date;

        minDate.setDate(minDate.getDate() + 1);
        maxDate = null;
      }

      $.datepick.setDefaults({minDate: minDate, maxDate: maxDate});
    };

    var keydown = function(event)
    {
      event.preventDefault();
    };

    startElement.mousedown(mousedown).keydown(keydown).datepick();
    endElement.mousedown(mousedown).keydown(keydown).datepick();
  },

  hideRooms = function()
  {
    $('div.rooms td.selected').removeClass('selected');
    $('div.availability').fadeOut(animateDuration, function()
    {
      $(this).remove();
    });
  },

  showRooms = r = function(amounts, sender, interval, e)
  {
    hideRooms();
    
    var
      ul = $('<ul/>'),
      pos = $(sender).position(),
      left =
        pos.left +
        $(sender).width() +
        parseInt($(sender).css('padding-left')) +
        parseInt($(sender).css('padding-right')),
      top = pos.top,
      url = window.location.href.replace(/\?.*$/, '?' + interval);

    for (var id in amounts)
    {
      ul.append(
        $('<li>').
          append($('<span class="type"/>').text(roomTypes[id])).
          append($('<span class="available"/>').html('<b>' + amounts[id] + '</b>').
            append($('<a/>').attr('href', url + id).text(textBooking))));
    }

    var
      div = $('<div class="availability"/>').
        css({left: left + 'px', top: top + 'px'}).
        append(ul);

    $('body').append(div).click(function()
    {
      hideRooms();
    });

    $(sender).addClass('selected');
    
    reveal(div);
    if (e.stopPropagation)
      e.stopPropagation();
    else
      e.cancelBubble = true;
  };

$(function()
{
  dropdown.init();
  smoothScroll.init();

  $('.person li input:checked').each(function()
  {
    $(this).parent().addClass('checked');
  });

  $('.person li').click(function()
  {
    var input = $(this).find('input')[0];
    input.checked = !input.checked;

    if (input.checked)
      $(this).addClass('checked');
    else
      $(this).removeClass('checked');
  });

  if (language == 'RO')
  {
    $.datepick.setDefaults({
  		clearText: 'Curata', clearStatus: 'Sterge data curenta',
  		closeText: 'Inchide', closeStatus: 'Inchide fara schimbare',
  		prevText: '&laquo; Inapoi', prevStatus: 'Arata luna precedenta',
  		prevBigText: '&laquo;&laquo;', prevBigStatus: '',
  		nextText: 'Inainte &raquo;', nextStatus: 'Arata luna urmatoare',
  		nextBigText: '&raquo;&raquo;', nextBigStatus: '',
  		currentText: 'Astazi', currentStatus: 'Arata luna curenta',
  		monthNames: [
        'Ianuarie', 'Februarie', 'Martie', 'Aprilie', 'Mai', 'Iunie', 'Iulie',
        'August', 'Septembrie', 'Octombrie', 'Noiembrie', 'Decembrie'
      ],
  		monthNamesShort: [
        'Ian', 'Feb', 'Mar', 'Apr', 'Mai', 'Iun', 'Iul', 'Aug', 'Sep', 'Oct',
        'Noi', 'Dec'
      ],
  		monthStatus: 'Arata o luna diferita', yearStatus: 'Arat un an diferit',
  		weekHeader: '', weekStatus: 'Saptamana anului',
  		dayNames: ['Duminica', 'Luni', 'Marti', 'Miercuri', 'Joi', 'Vineri', 'Sambata'],
  		dayNamesShort: ['Dum', 'Lun', 'Mar', 'Mie', 'Joi', 'Vin', 'Sam'],
  		dayNamesMin: ['Du', 'Lu', 'Ma', 'Mi', 'Jo', 'Vi', 'Sa'],
  		dayStatus: 'Seteaza DD ca prima saptamana zi', dateStatus: 'Selecteaza D, M d',
  		dateFormat: 'd MM yy', firstDay: 1,
  		initStatus: 'Selecteaza o data', isRTL: false,
  		showMonthAfterYear: false, yearSuffix: ''});
  }
  else
  {
    $.datepick.setDefaults({dateFormat: 'MM d yy'});
  }

  $('.cardinfo').click(function(e) {
    dropdown.closeAll();
    $(this).fadeOut(animateDuration);
    if (e.stopPropagation) e.stopPropagation();
    else e.cancelBubble = true;
    return false;
  });

  $('body').click(function(e) {
    $('.cardinfo').fadeOut(animateDuration);
  });
  
  $('div.cards').click(function(e)
  {
    dropdown.closeAll();
    $('.cardinfo').fadeIn(animateDuration);
    if (e.stopPropagation) e.stopPropagation();
    else e.cancelBubble = true;
    return false;
  });
});