// http://stackoverflow.com/questions/158070/jquery-how-to-position-one-element-relative-to-another/1128764#1128764
jQuery.fn.getBox = function() {
  return {
    left: $(this).offset().left,
    top: $(this).offset().top,
    width: $(this).outerWidth(),
    height: $(this).outerHeight()
  };
}

jQuery.fn.center = function(target, options) {
  var anchorOffsets = {t: 0, l: 0, c: 0.5, b: 1, r: 1};
  var defaults = {
    anchor: ['tl', 'tl'],
    animate: false,
    offset: [0, 0]
  };
  options = $.extend(defaults, options);

  var targetBox = $(target).getBox();
  var sourceBox = $(this).getBox();

  //origin is at the top-left of the target element
  var top = targetBox.top;
  var left = targetBox.left;

  //alignment with respect to source
  top -= anchorOffsets[options.anchor[0].charAt(0)] * sourceBox.height;
  left -= anchorOffsets[options.anchor[0].charAt(1)] * sourceBox.width;

  //alignment with respect to target
  top += anchorOffsets[options.anchor[1].charAt(0)] * targetBox.height;
  left += anchorOffsets[options.anchor[1].charAt(1)] * targetBox.width;

  // горизонтальный скролл
  if (left + sourceBox.width > $('.page > .container').width()) {
    left = $('.page > .container').width() - sourceBox.width - 62;
    options.offset[1] = 0;
  };
  
  //add offset to final coordinates
  top += options.offset[0];
  left += options.offset[1];
  
  if ($(this).is(':visible')) {
    $(this).css('top', top + 'px').animate({
      left: left + 'px'
    }, 'fast');
  } else {
    $(this).css({
      top: top + 'px',
      left: left + 'px'
    }).fadeIn('fast', function() {
      if ($.browser.msie) {
        this.style.removeAttribute('filter');
      };
    })
  }
}

$(document).ready(function() {
  
  $('.popup .close').click(function() {
    $(this).parents('.popup').fadeOut('fast');
  });
  
  $('a.pseudo-link[rel]').click(function() {
    var popupId = $(this).attr('rel');
    var popup = $(popupId);
    if ($(this).hasClass('help')) {
      $(popupId).center($(this), {
        anchor: ['tl', 'tr'],
        offset: [0, 40]
      });
    } else {
      $(popupId).center($(this), {
        anchor: ['tl', 'tr'],
        offset: [40, -62]
      });
    }
    return false;
  });
  
}).click(function(event) {
  if ($('.popup').is(':visible') &&
      $(event.target).parents('.popup').length == 0 &&
      !$(event.target).is('.popup')) {
    $('.popup').fadeOut('fast');
  };
});

