var
  SLIDESHOW_IMAGE_WIDTH = 74,
  SLIDESHOW_IMAGE_PADDING = 10,
  LABEL_LEFT = '&laquo; Inapoi',
  LABEL_RIGHT = 'Inainte &raquo;',
  LABEL_CLOSE = 'Inchide';

$(function()
{
  $('li.servicii').hover(function()
  {
    if (menu.menuItem != null) menu.cancelCloseTimer();
    menu.open($('ul.servicii').hover(
      function() { menu.cancelCloseTimer() },
      function() { menu.startCloseTimer() }));
  }, function()
  {
    menu.startCloseTimer();
  });

  $('.submenu-background').css('opacity', .4);

  $('.slideshow ul').each(function()
  {
    var
      images = $(this).find('img'),
      length = images.length,
      ul = $(this);

    if (length > 0)
    {
      ul.width(length * SLIDESHOW_IMAGE_WIDTH + length * SLIDESHOW_IMAGE_PADDING);
    }

    images.click(function()
    {
      var
        size = $(this).parent().attr('class').replace(/^target-([\dx]+)$/, '$1'),
        width = parseInt(size.replace(/^(\d+)x.*$/, '$1')),
        height = parseInt(size.replace(/^.*x(\d+)$/, '$1')),
        full = this.src.replace(/thumb/, 'full'),
        box =
          $('<div class="image"/>').
            click(function()
            {
              darkbox.close(box);
            }).
            css({
              margin: '-' + (height / 2) + 'px 0 0 -' + (width / 2) + 'px',
              height: height + 'px'
            }).
            append($('<img src="' + full + '" width="' + width + '" height="' + height + '"/>')).
            append($('<div class="close">' + LABEL_CLOSE + '</div>').click(function()
            {
              darkbox.close(box);
            }));
      
      darkbox.open(box);
    });

    var
      moving = false,
      getMarginLeft = function(element)
      {
        var margin = element.css('margin-left');
        if (margin == undefined || margin == '') return 0;
        else return parseInt(margin.replace(/^([-0-9]+)px$/, '$1'));
      },
      move = function(offset)
      {
        if (moving || offset > 0 || offset < -1 * ul.width() / 2) return;
        moving = true;
        ul.animate({marginLeft: offset + 'px'}, 'normal', 'swing', function()
        {
          moving = false;
        });
      },
      totalImageWidth = SLIDESHOW_IMAGE_WIDTH + SLIDESHOW_IMAGE_PADDING,
      moveLeft = function()
      {
        move(getMarginLeft(ul) + totalImageWidth);
      },
      moveRight = function()
      {
        move(getMarginLeft(ul) - totalImageWidth);
      };

    ul.parent().
      append($('<div class="arrows"/>').
        append($('<div class="arrow-left">' + LABEL_LEFT + '</div>').click(moveLeft)).
        append($('<div class="arrow-right">' + LABEL_RIGHT + '</div>').click(moveRight)));
  });
});
