// JQuery Zimetrix Audience Popup Plugin

(function($) {

  if( typeof $ != "undefined" ) {
    $.fn.zAudiencePopup = function( options ) {

      // Если селектор пуст - возвращаемся
      if( !this.length ) {
        return this;
      }

      // -- Настройки по-умолчанию --
      var settings =
        {
          mainClass: 'ui-zAudiencePopupR',
          popupTitle: 'Audiences',
          dataAttr: 'z:audience',
          commonUrl: null,
          offsetX: 10,
          offsetY: -10,
          hideSpeed: 'fast',
          hideTimeout: 100
        };
      
      // Выставляем настройки, переданные юзером
      if (options) {
        $.extend( settings, options );
      }

      // -- Приватные свойства --
      var jPopup = $("<div class='" + settings.mainClass + "'>\
                            <div class='content'>\
                              <div>\
                                <h3></h3>\
                                <ul>\
                                </ul>\
                              </div>\
                              <div class='bottom'>\
                                <div class='corn'></div>\
                              </div>\
                            </div>\
                            <div class='corner'></div>\
                          </div>");

      jPopup.css({
        position: 'absolute'
      }).hover(
        function() {
          preventPopupHiding();
          immidiateShowPopup();
        },
        function() {
          hidePopup();
      });

      // Привязывем переход по заданному url при клике на popup-е
      /*if (settings.clickUrl.constructor == String) {
        jPopup.css({
          cursor: 'pointer'
        }).click( function(e) {
          window.location = settings.clickUrl;
          return false;
        })
      }*/

      var jPopupTitle = jPopup.find('h3:first');
      var jPopupList = jPopup.find('ul:first');
      var jLastElem = null;
      var timeoutId = 0;

      // -- Публичные свойства --

      // -- Приватные методы --
      function parseParameters( paramsStr ) {
        var paramsJSON = eval( '(' + paramsStr + ')' ) || [];
        if( !$.isArray(paramsJSON) ) {
          paramsJSON = [paramsJSON];
        }
        // Костыль (удаляем последний элемент, если он false)
        if (paramsJSON[paramsJSON.length-1] === false) {
          paramsJSON.pop();
        }
        return paramsJSON;
      }

      function preventPopupHiding() {
        if( timeoutId != 0 ) {
          clearTimeout( timeoutId );
          timeoutId = 0;
        }
      }

      function hidePopup() {
        timeoutId = setTimeout( function() {
          hideBlock();
          timeoutId = 0;
        }, settings.hideTimeout);
      }

      // Поведение показывания/скрытия попапа в зависимости от браузера
      var hideBlock = new Function();
      var showBlock = new Function();
      var immidiateShowPopup = new Function();

      if ($.browser.msie) {
        hideBlock = function() {
          jPopup.hide();
        };
        showBlock = function() {
          jPopup.show();
        };
      } else {
        hideBlock = function() {
          jPopup.fadeOut(settings.hideSpeed);
        };
        showBlock = function() {
          jPopup.fadeIn(settings.hideSpeed);
        };
        immidiateShowPopup = function() {
          jPopup.stop().show().css("opacity", 1);
        }
      }

      // -- Публичные методы --

      // -- Проходим через все переданные объекты
      var jElems = this.filter('*[' + settings.dataAttr + ']');
      
      if( jElems.length ) {
        jPopup.hide().appendTo( document.body );
      }

      this.each( function() {
        var jElem = $(this);
        var paramsJSON = parseParameters( jElem.attr(settings.dataAttr) );

        // Выставляем переход по ссылке при щелчке на элементе
        var mainHref = null;
        if( settings.commonUrl ) {
          mainHref = settings.commonUrl;
        } else if( paramsJSON.length && paramsJSON[0].href ) {
          mainHref = paramsJSON[0].href;
        }

        if( mainHref != null ) {
          jElem.click( function() {
            window.location.href = mainHref;
          });
        }

        // Вывод попапа при наведении на элементе
        jElem.hover(
          function() {
            if (jLastElem != jElem) {
              jLastElem = jElem;
              jPopupTitle.text( jElem.attr('title') || settings.popupTitle );
              jPopupList.empty();
              for( var i = 0; i < paramsJSON.length; i++ ) {
                /*var jPopupItem = $('<li/>');
                jPopupItem.text( paramsJSON[i].title + ': ' );
                var jPopupItemLink = $('<a/>');*/
                var jPopupItem;
                if( 'count' in paramsJSON[i] ) {
                  jPopupItem = $('<li>' + paramsJSON[i].title + ': <a href="' + (settings.commonUrl || paramsJSON[i].href) + '">' + paramsJSON[i].count + '</a></li>');
                } else {
                  var link = settings.commonUrl || paramsJSON[i].href;
                  var itemHtml = link ? '<a href="' + link + '">' + paramsJSON[i].title + '</a>' : paramsJSON[i].title;
                  jPopupItem = $('<li>' + itemHtml + '</li>' );
                }
                jPopupItem.appendTo( jPopupList );
              }
            }


            if( !jPopup.is(':hidden') ){
              immidiateShowPopup();
            }
            preventPopupHiding();
            showBlock();

            jPopup.css({
              top : jElem.offset().top + jElem.height()/2 + settings.offsetY,
              left: -1000 // Костыль
            });
            if(jElem.offset().left + settings.offsetX + jElem.width() + jPopup.width() > $(window).width()){
              jPopup.css({
                left: jElem.offset().left - jPopup.outerWidth() - settings.offsetX 
              })
              .removeClass('ui-zAudiencePopupR')
              .addClass('ui-zAudiencePopupL');
            } else {
              jPopup.css({
                left: jElem.offset().left + jElem.width() + settings.offsetX
              })
              .removeClass('ui-zAudiencePopupL')
              .addClass('ui-zAudiencePopupR');
            }
          },
          function() {
            hidePopup();
        });
      });

      // Возвращаем исходный jQuery-объект, чтобы не прерывать цепь
      return this;
    }
  } else {
    var errorMsg = "jquery.zAudiencePopup.js:\nThis is jQuery plugin, so jQuery is needed!";
    if( typeof console != "undefined" && console.error != "function" ) {
      console.error( errorMsg );
    } else {
      alert( errorMsg );
    }
  }
})(jQuery);