(function ($) {
/*
  Drupal.behaviors.KVExternalLinksNewWindow = {
    attach: function (context, settings) {
      $('body').once(function(){
        $.expr[':'].external = function(obj) {
          return !obj.href.match(/^(https?\:\/\/(www\.){0,1}(m\.|news?\.){0,1}kv\.(minsk\.){0,1}by|mailto|javascript)/)
            && (obj.hostname != location.hostname)
        };
//        $('.node-content .field-name-body a:external, .comment-content .field-name-comment-body a:external').attr('target', '_blank');
        $('.node-content').find('.field-name-body').find('a:external').attr('target', '_blank');
        $('.comment-content').find('.field-name-comment-body').find('a:external').attr('target', '_blank');
      });
    }
  }
*/

  Drupal.behaviors.KVCommentsPagerLinks = {
    attach: function (context, settings) {
      $('body').once(function(){
        var CommentsPagerLinks = $('#comments .pager a');
        CommentsPagerLinks.each(function(){
          this.href = this.href + '#comments';
        });
      });
    }
  }

  Drupal.behaviors.KVFadeBadComments = {
    attach: function (context, settings) {
      $('body').once(function(){
        $('.rate-number-up-down-rating.negative').each(function() {
          var result = Math.abs(parseInt($(this).text()));
          if (result) {
            var maxBad = 4;
            var minOpacity = 0.2
            var maxOpacity = 0.8;
            $(this).parents('.comment').find('.field-name-comment-body').hover(function() {
              $(this).css('opacity', '1');
            }, function() {
              $(this).css('opacity', result >= maxBad ? minOpacity : maxOpacity - (result - 1) / (maxBad - 1) * (maxOpacity - minOpacity));
            }).trigger('mouseleave');
          }
        });
      });
    }
  }

  Drupal.behaviors.KVShareRate = {   
    attach: function(context, settings) {
      $('body').once(function(){
        $("a.rate-fivestar-4, a.rate-fivestar-5").click(function() {
          text = '<h3 align="center">Вы высоко оценили эту публикацию. Поделитесь ею с друзьями прямо сейчас!</h3>';
          jQuery.colorbox({ html: text + '<script type="text/javascript" src="//yastatic.net/es5-shims/0.0.2/es5-shims.min.js" charset="utf-8"></script><script type="text/javascript" src="//yastatic.net/share2/share.js" charset="utf-8"></script><div align="center" class="ya-share2" data-counter="" data-services="vkontakte,facebook,odnoklassniki,gplus,twitter,viber,whatsapp"></div></div>', width: 320, height: 230 });
        });
      });
    } 
  };


}(jQuery));  
;
(function ($) {
  Drupal.behaviors.KVSubscribeOnExit = {
    attach: function (context, settings) {
      $('body').once(function(){
        $.expr[':'].external = function(obj) {
          return !obj.href.match(/^(https?\:\/\/(www\.){0,1}(m\.|news?\.){0,1}kv\.(minsk\.){0,1}by|mailto|javascript)/)
            && (obj.hostname != location.hostname)
        };
        $('#content').find('a:external').click(function() {
          showExitWindow($(this).attr('href'));
          return false;
        });
/*
        $('.node-content').find('.field-name-body').find('a:external').click(function() {
          showExitWindow($(this).attr('href'));
          return false;
        });
        $('.comment-content').find('.field-name-comment-body').find('a:external').click(function() {
          showExitWindow($(this).attr('href'));
          return false;
        });
*/
      });
    }
  }

  function showExitWindow(href) {
    $('<div id="subscribe-on-exit-form"> \
         <form> \
           <p id="subscribe-on-exit-text">Сейчас вы покинете наш сайт, но прежде чем уйти, предлагаем вам подписаться на нашу еженедельную рассылку с подборкой лучших статей и новостей.</p> \
           <input placeholder="Ваш e-mail" type="text" name="subscribe-on-exit-mail" id="subscribe-on-exit-mail" value="" class="text ui-widget-content ui-corner-all"> \
           \
           <input type="submit" id="subscribe-on-exit-submit" name="subscribe-on-exit-submit" value="ОК" class="form-submit"> \
         </form> \
         <p id="subscribe-on-exit-error"></p> \
         <p class="subscribe-on-exit-link">Это не обязательно, вы можете сразу перейти по <a href="'+href+'"><strong>ссылке</strong></a>.</p> \
      </div>').dialog({
      dialogClass: 'subscribe-on-exit-window',
      title: 'До новых встреч!',
      closeOnEscape: true,
//      open: function(event, ui) { $('.ui-dialog-titlebar-close', ui.dialog | ui).hide(); },
      resizable: false,
      height: 'auto',
      width: Math.min(500, $(window).width()),
      modal: true,
      close: function(event, ui) { this.remove(); }
    });

    $('#subscribe-on-exit-form').submit(function(event) {
      event.preventDefault();
      if (addMail()) {
        $('#subscribe-on-exit-form').html('<p class="subscribe-on-exit-goodbye">Спасибо! Еще увидимся!</p>');

        setTimeout(function() { window.location.href = href; }, 1000);
      }
    });
  }

  function addMail() {
    var emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
        mailobj = $('#subscribe-on-exit-mail'),
        mail = mailobj.val();

    if (emailRegex.test(mail))
    {
      var url = Drupal.settings.kv_subscribe_on_exit.url;

      $.ajax({
        url: '/' + url,
        type: 'POST',
        data: { mail: mail },
      });

      return true;
    }
    else
    {
      var $error = $('#subscribe-on-exit-error');
      $error.text('Неверный адрес e-mail').addClass('ui-state-highlight');
      setTimeout(function() {
        $error.removeClass('ui-state-highlight', 3500);
      }, 1500);

      mailobj.addClass('ui-state-error');
      return false;
    }
  }

}(jQuery));  
;
(function ($) {
  Drupal.behaviors.kvQuoteClicks = {
    attach: function(context, settings) {
      $('body').once(function(){
        $('.kv-quote').click(function() {
          var $parents = $(this).parents('.comment');

          var name = $parents.find('.author-datetime .username').text();
//          var text = $parents.find('.field-name-comment-body .field-item').html();
          var text = $parents.find('.field-name-comment-body .field-item').clone().find('blockquote blockquote').remove().end().html();

          for (var instanceName in CKEDITOR.instances) {
            if (instanceName.substr(0, 17)=='edit-comment-body') {
              CKEDITOR.instances[instanceName].insertHtml('<blockquote><p><strong>' + name + ' пишет:</strong></p>' + text + '</blockquote><p></p>');
            }
          }
          return false;
        });
      });
    }
  }
})(jQuery);
;
