var addToExclusiveInGroup = function($popup, groupId) {
  var $doc = $(document);
  if(!$doc.data("exclusiveGroup")) $doc.data("exclusiveGroup", new Array());
  $popup.data("exclusiveGroupId", groupId);
  if(!$doc.data("exclusiveGroup")[groupId]) $doc.data("exclusiveGroup")[groupId] = new Array();
  $doc.data("exclusiveGroup")[groupId][$doc.data("exclusiveGroup")[groupId].length] = $popup;
};

var addToMayBeInGroup = function($popup, groupId) {
  var $doc = $(document);
  if(!$doc.data("mayBeGroup")) $doc.data("mayBeGroup", new Array());
  $popup.data("mayBeGroupId", groupId);
  if(!$doc.data("mayBeGroup")[groupId]) $doc.data("mayBeGroup")[groupId] = new Array();
  $doc.data("mayBeGroup")[groupId][$doc.data("mayBeGroup")[groupId].length] = $popup;
};

var hideExclusivePopups = function($popup) {
  var $doc = $(document);
  if($popup.data("exclusiveGroupId")) {
    for(var i=0;i<$doc.data("exclusiveGroup")[$popup.data("exclusiveGroupId")].length;i++) {
      $doc.data("exclusiveGroup")[$popup.data("exclusiveGroupId")][i].hide();
    }
  }
};

var prepareCatalogueSwitcher = function($link, $list) {
  var $doc = $(document);
  if(!$doc.data("cataloguePopup")) {
    $doc.data("cataloguePopup", $('<div class="catalogue-popup"><table><tr><td class="r00-"></td><td class="t-"></td><td class="r01-"></td></tr><tr><td class="l-"></td><td class="body-"><div class="pad-"><div class="corn-"></div><a class="close-" href="#">закрыть</a></div></td><td class="r-"></td></tr><tr><td class="r10-"></td><td class="b-"></td><td class="r11-"></td></tr></table></div>'));
    addToExclusiveInGroup($doc.data("cataloguePopup"), 1);
    $("body").append($doc.data("cataloguePopup"));
    $doc.data("cataloguePopup").find(".body- > .pad-").append($list);
    $doc.data("cataloguePopup").find(".body- .close-").click(function() { $doc.data("cataloguePopup").hide(); return false; });
  }
  $link.click(function() {
    this.blur();
    var $doc = $(document),
      $this = $(this);
    hideExclusivePopups($doc.data("cataloguePopup"));
    $doc.data("cataloguePopup").toggle().css({left: $this.offset().left + $this.width() + 22, top: $this.offset().top - ($doc.data("cataloguePopup").height() - $this.height()) / 2});
    $doc.data("cataloguePopup").find(".body- .corn-").css({top: ($doc.data("cataloguePopup").find(".body-").height() - 29) / 2 + 2 });
    return false;
  });
};

var prepareTipPopup = function($link) {
  $link.data("tip", $('<div class="catalogue-popup w300"><table><tr><td class="r00-"></td><td class="t-"></td><td class="r01-"></td></tr><tr><td class="l-"></td><td class="body-"><div class="pad-"><div class="corn-"></div><a class="close-" href="#">закрыть</a></div></td><td class="r-"></td></tr><tr><td class="r10-"></td><td class="b-"></td><td class="r11-"></td></tr></table></div>'));
  addToExclusiveInGroup($link.data("tip"), 1);
  $("body").append($link.data("tip"));
  $link.data("tip").find(".body- > .pad-").append(("<p><b>" + $link.html() + ":</b></p><p>" + $link.attr("title") + "</p>"));
  $link.attr({title: null}).data("tip").find(".body- .close-").click(function() { $(this).data("parentPopup").hide(); return false; }).data("parentPopup", $link.data("tip"));
  $link.click(function(){
    this.blur();
    var $this = $(this);
    hideExclusivePopups($this.data("tip"));
    $this.data("tip").show().css({left: $this.offset().left + $this.width() + 20, top: $this.offset().top - ($this.data("tip").height() - $this.height()) / 2});
    $this.data("tip").find(".body- .corn-").css({top: ($this.data("tip").find(".body-").height() - 29) / 2 + 2 });
    return false;
  });
};

var prepareRotator = function($ul, auto) {
  var $lis = $ul.find("> li");
  $ul.css({height: $lis.eq(0).height()});
  if($lis.size() == 4) {
    var
      $rotatorControlBlock = $('<li class="rotator-control"></li>'),
      $rotatorControlStatus = $('<div class="rc-status"><div class="rcs-mask"></div></div>'),
      $rotatorControlPrev = $('<a href="#" title="Пред." class="rc-prev"></a>'),
      $rotatorControlNext = $('<a href="#" title="След." class="rc-next"></a>');
    $rotatorControlBlock.autoInterval = 3000;
    $rotatorControlBlock.pauseCount = 0;
    $rotatorControlBlock.pauseCountFinish = 2;

    var showFrame = function($control, pos) {
      if(!$control.data("process")) {
        $control.data("process", true);
        var
          oldPos = $control.data("pos"),
          newPos = oldPos + pos;
        if(newPos < 0) newPos = 3;
        if(newPos > 3) newPos = 0;
        var $lis = $control.data("owner").data("lis");
        var maxHeight = $lis.eq(oldPos).height() > $lis.eq(newPos).height() ? $lis.eq(oldPos).height() : $lis.eq(newPos).height();
        $control.data("owner").animate({height: maxHeight}, "fast", function() {
          $lis.eq(oldPos).fadeOut("normal");
          $lis.eq(newPos).fadeIn("normal", function() { $control.data("owner").animate({height: $lis.eq(newPos).height()}, "fast"); });
        });
        $control.data("status").animate({backgroundPosition: (newPos * 13 + 1) + "px 0px"}, "normal", function() { $(this).data("control").data("process", false); });
        $control.data("pos", newPos);
      }
      return false;
    };

    $rotatorControlBlock.selfRotateIterator = function() {
      if(this.data("selfRotating") || this.pauseCount == this.pauseCountFinish) {
        showFrame(this, +1);
        if(this.pauseCount == this.pauseCountFinish) {
          this.data("selfRotating", true);
          this.pauseCount = 0;
        }
      } else {
        this.pauseCount += 1;
      }
    };

    $rotatorControlBlock
      .append($rotatorControlStatus)
      .append($rotatorControlPrev)
      .append($rotatorControlNext)
      .data("owner", $ul)
      .data("pos", 0)
      .data("process", false)
      .data("selfRotating", true)
      .data("status", $rotatorControlStatus);
    $rotatorControlPrev.data("control", $rotatorControlBlock).click(function() {
      var $control = $(this).data("control");
      $control.data("selfRotating", false).pauseCount = 0;
      return showFrame($control, -1);
    });
    $rotatorControlNext.data("control", $rotatorControlBlock).click(function() {
      var $control = $(this).data("control");
      $control.data("selfRotating", false).pauseCount = 0;
      return showFrame($control, +1);
    });
    $rotatorControlStatus.data("control", $rotatorControlBlock);
    $ul
      .data("control", $rotatorControlBlock)
      .data("lis", $lis)
      .append($rotatorControlBlock);
    if(auto) setInterval(function() { $rotatorControlBlock.selfRotateIterator() }, $rotatorControlBlock.autoInterval);
  }
};

/* show popup plugin */
(function($){
  $.extend($.fn, {
    showPopup: function(options) {
      return this.each(function() {
        var $this = $(this);
        if($this.data('showPopup')) {
          var showPopup = $this.data('showPopup');
          $.extend(true, showPopup.settings, options);
          showPopup.reset();
        } else $this.data('showPopup', new ShowPopup(this, options));
      });
    }
  });
  ShowPopup = function(elem, options){
    this.elem = $(elem);

    this.settings = $.extend(true, {
      position: "bottom"
    }, options);

    this.reset();
  };
  $.extend(ShowPopup.prototype, {
    reset: function() {
      if(this.settings.popup) {
        if(!this.settings.popup.data("corn-box")) {
          var pBody = this.settings.popup.find(".p-body");
          pBody.prepend("<div></div>");
          this.settings.popup.data("corn-box", pBody.find("div:first-child"));
        }
        this.elem.click(function() {
          this.blur();
          var $this = $(this);
          var settings = $this.data("showPopup").settings;
          settings.popup.data("corn-box").get(0).className = "p-corn-" + settings.position;
          var left = $this.offset().left - ((settings.popup.width() - $this.width()) / 2);
          var cornLeft = (settings.popup.width() - 27) / 2;
          var baseWidth = $this.parents(".base-width");
          var leftShift = 0;
          if(baseWidth) {
            if(left > baseWidth.outerWidth() + baseWidth.offset().left - settings.popup.width())
              leftShift = baseWidth.outerWidth() + baseWidth.offset().left - settings.popup.width() - left - 20;
            if(left < baseWidth.offset().left)
              leftShift = baseWidth.offset().left - left + 20;
          }
          var top = settings.position == "bottom" ?
                  $this.offset().top + $this.height() + 15 :
                  $this.offset().top - settings.popup.height() - 15;
          settings.popup.css({left: left + leftShift, top: top}).show();
          settings.popup.find(".p-body > div:first-child").css({left: cornLeft - leftShift});
          return false;
        });
      }
    }
  });
}(jQuery));

/* tip input plugin */
(function($){
  $.extend($.fn, {
    tipInput: function() {
      return this.each(function() {
        $(this).data('tipInput', new TipInput(this));
      });
    }
  });
  TipInput = function(elem){
    this.elem = $(elem);
    this.reset();
  };
  $.extend(TipInput.prototype, {
    reset: function() {
      this.elem.val(this.elem.attr("title")).focus(function() {
        var $this = $(this);
        if($this.val() == $this.attr("title")) {
          $this.val("").removeClass("tip-input");
        }
      }).blur(function() {
        var $this = $(this);
        if($this.val() == "") {
          $this.val($this.attr("title")).addClass("tip-input");
        }
      });
    }
  });
}(jQuery));

/* team manager plugin */
(function($){
  $.extend($.fn, {
    teamManager: function() {
      return this.each(function() {
        var $this = $(this);
        $this.data('teamManager', new TeamManager(this));
      });
    }
  });
  TeamManager = function(elem){
    this.elem = $(elem);

    this.gallery = $('<div class="team-gallery"></div>');
    this.shortList = $('<ul class="team-short"></ul>');
    this.pics = this.elem.find("> li > div > img");
    this.maps = this.elem.find("> li > div > map");
    this.names = this.elem.find("h2");
    this.posts = this.elem.find(".t-post");

    this.reset();
  };
  $.extend(TeamManager.prototype, {
    reset: function() {
      if(this.pics.size() == this.maps.size() && this.pics.size() == this.names.size() && this.pics.size() == this.posts.size()) {
        for(var i = 0; i < this.pics.size(); i++) {
          this.maps.eq(i).find("area").data("teamManager", this).data("index", i)
            .click(function() { this.blur(); return $(this).data("teamManager").showData($(this).data("index")); })
            .hover(
              function() { $(this).data("teamManager").showTitle($(this).data("index")); },
              function() { $(this).data("teamManager").hideTitle($(this).data("index")); }
            );
          var $a = $('<a href="#" id="'+this.names.eq(i).attr('id')+'">' + this.names.eq(i).html() + '</a>');
          $a.data("teamManager", this).data("index", i)
            .click(function() { this.blur(); return $(this).data("teamManager").showData($(this).data("index")); })
            .hover(
              function() { $(this).data("teamManager").showTitle($(this).data("index")); },
              function() { $(this).data("teamManager").hideTitle($(this).data("index")); }
            );
          var $li = $('<li></li>');
          $li.append($a).append($('<em>' + this.posts.eq(i).html() + '</em>'));
          this.shortList.append($li);
          var $titleBox = $('<table class="team-title"><tr><td class="tt-w">&nbsp;</td><td class="tt-t">&nbsp;</td><td class="tt-w tt-01">&nbsp;</td></tr><tr><td class="tt-s">&nbsp;</td><td class="tt-c"><b>' + this.names.eq(i).html() + '</b> <em>' + this.posts.eq(i).html() + '</em></td><td class="tt-s tt-r">&nbsp;</td></tr><tr><td class="tt-w tt-10">&nbsp;</td><td class="tt-b">&nbsp;</td><td class="tt-w tt-11">&nbsp;</td></tr></table>');
          var $imageWrap = $('<div class="tg-one active-"></div>');
          $imageWrap.append(this.pics.eq(i));
          this.gallery.append($imageWrap).append($titleBox);
          this.elem.before(this.gallery).before(this.shortList);
        }
        this.galleryOrder();
        this.elem.find("> li").hide();
      }
    },
    galleryOrder: function() {
      var baseLeft = 0;
      var shift;
      var title;
      var titleLeft;
      var titleWidth;
      this.titles = this.gallery.find("> table");
      for(var i = 0; i < this.pics.size(); i++) {
        var coords = this.maps.eq(i).find("area").attr("coords").split(",");
        if(baseLeft != 0) baseLeft -= coords[0] / 2;
        this.pics.eq(i).parent().css({background: "url(" + this.maps.eq(i).find("area").attr("rel") + ")", left: baseLeft});
        title = this.titles.eq(i);
        titleWidth = title.width();
        if(i == 0) { // проверяем, помещается ли тайтл
          shift = (parseInt(coords[0]) + parseInt(coords[2]) - titleWidth) / 2;
          if(shift < 0) {
            titleLeft = 0;
            title.find(".tt-t").css({backgroundPosition: ((titleWidth - 38) / 2 - 185 + shift) + "px 0"});
          }
        } else if(i == this.pics.size() - 1) {
          shift = (parseInt(coords[0]) + parseInt(coords[2]) + titleWidth) / 2 - this.pics.eq(i).width();
          if(shift > 0) {
            titleLeft = baseLeft - (parseInt(coords[0]) + parseInt(coords[2]) - titleWidth) / 2 - 2 * shift;
            title.css({width: titleWidth}).find(".tt-t").css({backgroundPosition: ((titleWidth - 38) / 2 - 185 + shift + shift / 2) + "px 0"});
          }else{
            titleLeft = baseLeft - (parseInt(coords[0]) + parseInt(coords[2]) - titleWidth) / 2;
          }
        } else {
          titleLeft = baseLeft + (parseInt(coords[0]) + parseInt(coords[2]) - titleWidth) / 2;
        }
        title.data("teamManager", this).data("index", i).css({left: titleLeft}).hide()
          .hover(
            function() { $(this).data("teamManager").showTitle($(this).data("index")); },
            function() { $(this).data("teamManager").hideTitle($(this).data("index")); }
          );
        baseLeft += (parseInt(coords[2]) + parseInt(this.pics.eq(i).width())) / 2;
      }
    },
    showData: function(index) {
      this.titles.hide();
      this.shortList.hide();
      this.elem.find("> li").hide().eq(index).show();
      this.pics.parent().removeClass("active-").eq(index).addClass("active-");
      this.scrollGallery(index);
      return false;
    },
    showTitle: function(index) {
      this.titles.eq(index).show();
      return false;
    },
    hideTitle: function(index) {
      this.titles.eq(index).hide();
      return false;
    },
    scrollGallery: function(index) {
      var curTitle = this.titles.eq(index);
      var left = parseInt(curTitle.css("left"));
      var scroll = left - (this.gallery.width() - curTitle.width()) / 2;
      var lastPic = this.pics.eq(this.pics.size() - 1);
      var lastTitle = this.pics.eq(this.titles.size() - 1);
      var maxWidth = parseInt(lastPic.css("left")) + lastPic.width();
      if(maxWidth < parseInt(lastTitle.css("left")) + lastTitle.width())
        maxWidth = parseInt(lastTitle.css("left")) + lastTitle.width();
      if(scroll + this.gallery.width() > maxWidth)
        scroll = maxWidth - this.gallery.width();
      this.gallery.stop().animate({scrollLeft: scroll}, "slow");
    }
  });
}(jQuery));
