(function ($) {
  Drupal.behaviors.kvEditLimitCommentViewTimer = {
    attach: function(context, settings) {
      $('body').once(function(){
        var where = Drupal.settings.kv_editlimit.where,
            timeout = Drupal.settings.kv_editlimit.timeout,
            created = Drupal.settings.kv_editlimit.created,
            now = Math.floor(Date.now() / 1000),
            duration = parseInt(created) + parseInt(timeout) - parseInt(now);

        timerdiv = $('<div id="comment-edit-timer" title="осталось времени на редактирование данного комментария"></div>');

        switch(where) {
          case 'icon':
            timerdiv.addClass('comment-edit-icon-timer').appendTo('.comment-edit');
            break;

          case 'form':
            timerdiv.addClass('comment-edit-form-timer').insertAfter('label[for="edit-comment-body-und-0-value"]');
            break;
        }

        display = $('#comment-edit-timer');

        kvEditLimitStartTimer(duration, display, where);
      });
    }
  }

  function kvEditLimitStartTimer(duration, display, where) {
    var timer = duration, minutes, seconds;
    var stopwatch = setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

//        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
          clearInterval(stopwatch);

          switch(where) {
            case 'icon':
              $('li.comment-edit').remove();
              break;

            case 'form':
              $('form#comment-form').replaceWith('<h3 class="comment-edit-timer-timeout">Время, отпущенное на редактирование этого комментария, истекло.</h3>');
            break;
          }
        }
    }, 1000);
  }

})(jQuery);

;
(function ($) {
  Drupal.behaviors.rate = {
    attach: function(context) {
      $('.rate-widget:not(.rate-processed)', context).addClass('rate-processed').each(function () {
        var widget = $(this);
        // as we use drupal_html_id() to generate unique ids
        // we have to truncate the '--<id>'
        var ids = widget.attr('id').split('--');
        ids = ids[0].match(/^rate\-([a-z]+)\-([0-9]+)\-([0-9]+)\-([0-9])$/);
        var data = {
          content_type: ids[1],
          content_id: ids[2],
          widget_id: ids[3],
          widget_mode: ids[4]
        };

        $('a.rate-button', widget).click(function() {
          var token = this.getAttribute('href').match(/rate\=([a-zA-Z0-9\-_]{32,64})/)[1];
          return Drupal.rateVote(widget, data, token);
        });
      });
    }
  };

  Drupal.rateVote = function(widget, data, token) {
    // Invoke JavaScript hook.
    widget.trigger('eventBeforeRate', [data]);

    $(".rate-info", widget).text(Drupal.t('Saving vote...'));

    // Random number to prevent caching, see http://drupal.org/node/1042216#comment-4046618
    var random = Math.floor(Math.random() * 99999);

    var q = (Drupal.settings.rate.basePath.match(/\?/) ? '&' : '?') + 'widget_id=' + data.widget_id + '&content_type=' + data.content_type + '&content_id=' + data.content_id + '&widget_mode=' + data.widget_mode + '&token=' + token + '&destination=' + encodeURIComponent(Drupal.settings.rate.destination) + '&r=' + random;
    if (data.value) {
      q = q + '&value=' + data.value;
    }

    // fetch all widgets with this id as class
    widget = $('.' + widget.attr('id'));

    $.get(Drupal.settings.rate.basePath + q, function(response) {
      if (response.match(/^https?\:\/\/[^\/]+\/(.*)$/)) {
        // We got a redirect.
        document.location = response;
      }
      else {
        // get parent object
        var p = widget.parent();

        // Invoke JavaScript hook.
        widget.trigger('eventAfterRate', [data]);

        widget.before(response);

        // remove widget
        widget.remove();
        widget = undefined;

        Drupal.attachBehaviors(p);
      }
    });

    return false;
  }
})(jQuery);
;
(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);
;
function getCtrlReturn(e) 
{
  if (!e)
	{
		e = window.event;
	}
	if ((e.ctrlKey) && ((e.keyCode == 10) || (e.keyCode == 13))) 
	{
     var path = Drupal.settings.kv_error.basepath;

     var text = "";
     if (window.getSelection)
     {
       text = window.getSelection().toString();
     }
     else if (document.selection && document.selection.type != "Control")
     {
       text = document.selection.createRange().text;
     }

     var url = window.location.href;
     
     if (text)
     {
       jQuery.colorbox({ href:"/"+path+"/kv_error.php?text="+encodeURIComponent(text)+"&url="+encodeURIComponent(url), width:380, height: 610, iframe: true });
     }
	} 
	return true;
}

document.onkeypress = getCtrlReturn;
;
(function ($) {

Drupal.behaviors.textarea = {
  attach: function (context, settings) {
    $('.form-textarea-wrapper.resizable', context).once('textarea', function () {
      var staticOffset = null;
      var textarea = $(this).addClass('resizable-textarea').find('textarea');
      var grippie = $('<div class="grippie"></div>').mousedown(startDrag);

      grippie.insertAfter(textarea);

      function startDrag(e) {
        staticOffset = textarea.height() - e.pageY;
        textarea.css('opacity', 0.25);
        $(document).mousemove(performDrag).mouseup(endDrag);
        return false;
      }

      function performDrag(e) {
        textarea.height(Math.max(32, staticOffset + e.pageY) + 'px');
        return false;
      }

      function endDrag(e) {
        $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag);
        textarea.css('opacity', 1);
      }
    });
  }
};

})(jQuery);
;
(function ($) {

/**
 * Automatically display the guidelines of the selected text format.
 */
Drupal.behaviors.filterGuidelines = {
  attach: function (context) {
    $('.filter-guidelines', context).once('filter-guidelines')
      .find(':header').hide()
      .closest('.filter-wrapper').find('select.filter-list')
      .bind('change', function () {
        $(this).closest('.filter-wrapper')
          .find('.filter-guidelines-item').hide()
          .siblings('.filter-guidelines-' + this.value).show();
      })
      .change();
  }
};

})(jQuery);
;
(function ($) {

Drupal.behaviors.ulogin_async = {};
Drupal.behaviors.ulogin_async.attach = function(context, settings) {
  
  function uloginInitWidgets() {
    $.each(Drupal.settings.ulogin, function(index, value) {
      $('#' + value + ':not(.ulogin-processed)', context).addClass('ulogin-processed').each(function() {
        uLogin.initWidget(value);
      });
    });
  }
  
  if (typeof uLogin != 'undefined') {
    uloginInitWidgets();
  }
  else {
    /*$.getScript('//ulogin.ru/js/ulogin.js', function(data, textStatus, jqXHR) {
      uloginInitWidgets();
    });*/
    $.ajax({
      url: '//ulogin.ru/js/ulogin.js',
      dataType: 'script',
      cache: true, //otherwise will get fresh copy every page load, this is why not $.getScript().
      success: function(data, textStatus, jqXHR) {
        uloginInitWidgets();
      }
    });
  }
};

})(jQuery);
;
(function ($) {

/**
 * A progressbar object. Initialized with the given id. Must be inserted into
 * the DOM afterwards through progressBar.element.
 *
 * method is the function which will perform the HTTP request to get the
 * progress bar state. Either "GET" or "POST".
 *
 * e.g. pb = new progressBar('myProgressBar');
 *      some_element.appendChild(pb.element);
 */
Drupal.progressBar = function (id, updateCallback, method, errorCallback) {
  var pb = this;
  this.id = id;
  this.method = method || 'GET';
  this.updateCallback = updateCallback;
  this.errorCallback = errorCallback;

  // The WAI-ARIA setting aria-live="polite" will announce changes after users
  // have completed their current activity and not interrupt the screen reader.
  this.element = $('<div class="progress" aria-live="polite"></div>').attr('id', id);
  this.element.html('<div class="bar"><div class="filled"></div></div>' +
                    '<div class="percentage"></div>' +
                    '<div class="message">&nbsp;</div>');
};

/**
 * Set the percentage and status message for the progressbar.
 */
Drupal.progressBar.prototype.setProgress = function (percentage, message) {
  if (percentage >= 0 && percentage <= 100) {
    $('div.filled', this.element).css('width', percentage + '%');
    $('div.percentage', this.element).html(percentage + '%');
  }
  $('div.message', this.element).html(message);
  if (this.updateCallback) {
    this.updateCallback(percentage, message, this);
  }
};

/**
 * Start monitoring progress via Ajax.
 */
Drupal.progressBar.prototype.startMonitoring = function (uri, delay) {
  this.delay = delay;
  this.uri = uri;
  this.sendPing();
};

/**
 * Stop monitoring progress via Ajax.
 */
Drupal.progressBar.prototype.stopMonitoring = function () {
  clearTimeout(this.timer);
  // This allows monitoring to be stopped from within the callback.
  this.uri = null;
};

/**
 * Request progress data from server.
 */
Drupal.progressBar.prototype.sendPing = function () {
  if (this.timer) {
    clearTimeout(this.timer);
  }
  if (this.uri) {
    var pb = this;
    // When doing a post request, you need non-null data. Otherwise a
    // HTTP 411 or HTTP 406 (with Apache mod_security) error may result.
    $.ajax({
      type: this.method,
      url: this.uri,
      data: '',
      dataType: 'json',
      success: function (progress) {
        // Display errors.
        if (progress.status == 0) {
          pb.displayError(progress.data);
          return;
        }
        // Update display.
        pb.setProgress(progress.percentage, progress.message);
        // Schedule next timer.
        pb.timer = setTimeout(function () { pb.sendPing(); }, pb.delay);
      },
      error: function (xmlhttp) {
        pb.displayError(Drupal.ajaxError(xmlhttp, pb.uri));
      }
    });
  }
};

/**
 * Display errors on the page.
 */
Drupal.progressBar.prototype.displayError = function (string) {
  var error = $('<div class="messages error"></div>').html(string);
  $(this.element).before(error).hide();

  if (this.errorCallback) {
    this.errorCallback(this);
  }
};

})(jQuery);
;
(function ($) {
  Drupal.behaviors.KVSubscriptionBlockRollup = {
    attach: function (context, settings) {
      $('body').once(function(){
        var $block = $('#block-kv-maillist-kv-maillist-subscription-block');
        var offset = $block.offset();

        if (($(window).width() > 768) && (!$.cookie('kv_subscription_block'))) {
          $block.css({'position' : 'fixed', 'top' : -1000, 'left' : -1000, 'z-index' : 9999999, 'width' : 250, 'border': '3px solid #8b8b8b'});

          $block.append('<div id="kv-maillist-subscription-block-close" title="Закрыть"></div>');
          $('#kv-maillist-subscription-block-close').css({'position' : 'absolute', 'top' : 3, 'right' : 3, 'cursor' : 'pointer', 'background' : 'url("/sites/all/themes/kvat/images/cross-mark1.svg") no-repeat center', 'width': '8px', 'height': '8px'}).click(function(){
            $block.slideUp(1000);
            $.cookie('kv_subscription_block', 1, {path: '/', expires: 7});
          });

          $block.append('<div id="kv-maillist-subscription-block-minimize" title="Свернуть"></div>');
          $('#kv-maillist-subscription-block-minimize').css({'position' : 'absolute', 'top' : 3, 'right' : 17, 'cursor' : 'pointer', 'background' : 'url("/sites/all/themes/kvat/images/minimize-mark1.svg") no-repeat center', 'width': '8px', 'height': '8px'}).click(function(){
            $block.slideUp(1000);
          });

          setTimeout(function() {
            $block.hide();
            $block.css({'top' : '', 'left' : offset.left, 'bottom' : 0}).slideDown(1000);
          }, 30000);
        }
      });
    }
  }

}(jQuery));  
;
/**
 * @file
 * Loads content of blocks via AJAX just after page loading, updates Drupal.settings, reattaches behaviors.
 */

(function ($) {

Drupal.ajaxblocksSendRequest = function (request, delay) {
  if (delay) {
    setTimeout(function () { Drupal.ajaxblocksSendRequest(request, 0); }, delay);
    return;
  }
  $.ajax({
    url: ((typeof Drupal.settings.ajaxblocks_path !== 'undefined') ? Drupal.settings.ajaxblocks_path : (Drupal.settings.basePath + Drupal.settings.pathPrefix + "ajaxblocks")),
    type: "GET",
    dataType: "json",
    data: request + '&nocache=1',
    cache: false,
    success: function (data) {
      // Replaces the placeholder divs by the actual block contents returned by the AJAX call,
      // executes the extra JavaScript code and attach behaviours if the apply to the blocks.
      Drupal.freezeHeight();
      for (var id in data) {
        Drupal.ajaxblocksSetBlockContent(id, data[id]);
      }
      Drupal.unfreezeHeight();
    }
  });
};

Drupal.ajaxblocksSetBlockContent = function (id, data) {
  if (data['delay']) {
    setTimeout(function () {data['delay'] = 0; Drupal.ajaxblocksSetBlockContent(id, data);}, data['delay']);
    return;
  }
  var wrapper = $('#block-' + id + '-ajax-content');
  if (!wrapper) {
    return;
  }
  var context = wrapper.parent();
  Drupal.detachBehaviors(context);
  if (!context) {
    return;
  }
  $('#block-' + id).addClass('ajaxblocks-loaded');
  context.html(data['content']);
  if (data['ajaxblocks_settings']) {
    $.extend(true, Drupal.settings, data['ajaxblocks_settings']);
  }
  Drupal.attachBehaviors(context);
};

$(document).ready(function () {
  if (typeof Drupal.settings.ajaxblocks !== 'undefined') {
    Drupal.ajaxblocksSendRequest(Drupal.settings.ajaxblocks, Drupal.settings.ajaxblocks_delay);
  }
});

$(window).load(function () {
  if (typeof Drupal.settings.ajaxblocks_late !== 'undefined') {
    Drupal.ajaxblocksSendRequest(Drupal.settings.ajaxblocks_late, Drupal.settings.ajaxblocks_late_delay);
  }
});

})(jQuery);
;
(function ($) {
    Drupal.behaviors.colorboxNode = {
        // Lets find our class name and change our URL to
        // our defined menu path to open in a colorbox modal.
        attach: function (context, settings) {
            // Make sure colorbox exists.
            if (!$.isFunction($.colorbox) || typeof settings.colorbox === 'undefined') {
                return;
            }

            // Mobile detection extracted from the colorbox module.
            // If the mobile setting is turned on, it will turn off the colorbox modal for mobile devices.
            if (settings.colorbox.mobiledetect && window.matchMedia) {
                // Disable Colorbox for small screens.
                var mq = window.matchMedia("(max-device-width: " + settings.colorbox.mobiledevicewidth + ")");
                if (mq.matches) {
                    return;
                }
            }

            $('.colorbox-node', context).once('init-colorbox-node-processed', function () {
                $(this).colorboxNode({'launch': false});
            });

            // When using contextual links and clicking from within the colorbox
            // we need to close down colorbox when opening the built in overlay.
            $('ul.contextual-links a', context).once('colorboxNodeContextual').click(function () {
                $.colorbox.close();
            });
        }
    };

    // Bind our colorbox node functionality to an anchor
    $.fn.colorboxNode = function (options) {
        var settings = {
            'launch': true,
            'width': Drupal.settings.colorbox_node.width,
            'height': Drupal.settings.colorbox_node.height
        };

        $.extend(settings, options);

        var href = $(this).attr('data-href');
        if (typeof href == 'undefined' || href == false) {
            href = $(this).attr('href');
        }
        // Create an element so we can parse our a URL no matter if its internal or external.
        var parse = document.createElement('a');
        parse.href = href;

        if(!href) {
            alert(Drupal.t('No url found on element'));
        }

        // Lets add our colorbox link after the base path if necessary.
        var base_path = Drupal.settings.basePath;
        var path_prefix = Drupal.settings.pathPrefix;
        var pathname = parse.pathname;

        // Lets check to see if the pathname has a forward slash.
        // This problem happens in IE7/IE8
        if (pathname.charAt(0) != '/') {
            pathname = '/' + parse.pathname;
        }

        // If clean URL's are not turned on, lets check for that.
        var url = $.getParameterByName('q', href);
        if (base_path != '/') {
            if (url != '') {
                var link = pathname.replace(base_path, base_path + parse.search.replace('?q=', '?q=/' + path_prefix + 'colorbox/'));
            } else {
                var link = pathname.replace(base_path, base_path + path_prefix + 'colorbox/') + parse.search;
            }
        } else {
            if (url != '') {
                var link = base_path + parse.search.replace('?q=', '?q=/' + path_prefix + 'colorbox/');
            } else {
                var link = base_path + path_prefix + 'colorbox' + pathname + parse.search;
            }
        }

        // Bind Ajax behaviors to all items showing the class.
        var element_settings = {};

        // This removes any loading/progress bar on the clicked link
        // and displays the colorbox loading screen instead.
        element_settings.progress = { 'type': 'none' };
        // For anchor tags, these will go to the target of the anchor rather
        // than the usual location.
        if (href) {
            element_settings.url = link;
            element_settings.event = 'click';
        }

        $(this).click(function () {
            var $this = $(this).clone();

            // Clear out the rel to prevent any confusion if not using the gallery class.
            if(!$this.hasClass('colorbox-node-gallery')) {
                $this.attr('rel', '');
            }

            // Lets extract our width and height giving priority to the data attributes.
            var innerWidth = $this.data('inner-width');
            var innerHeight = $this.data('inner-height');
            if (typeof innerWidth != 'undefined' && typeof innerHeight != 'undefined') {
                var params = $.urlDataParams(innerWidth, innerHeight);
            } else {
                var params = $.urlParams(href);
            }

            // If we did not find a width or height, lets use the default.
            if (params.innerHeight == undefined) params.innerHeight = settings.height;
            if (params.innerWidth == undefined) params.innerWidth = settings.width;

            params.html = '<div id="colorboxNodeLoading"></div>';
            params.onComplete = function () {
                $this.colorboxNodeGroup();
            }
            params.open = true;

            // Launch our colorbox with the provided settings
            $this.colorbox($.extend({}, Drupal.settings.colorbox, params));
        });

        // Log our click handler to our ajax object
        var base = $(this).attr('id');
        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);

        // Default to auto click for manual call to this function.
        if (settings.launch) {
            Drupal.ajax[base].eventResponse(this, 'click');
            $(this).click();
        }
    }

    // Allow for grouping on links to showcase a gallery with left/right arrows.
    // This function will find the next index of each link on the page by the rel
    // and manually force a click on the link to call that AJAX and update the
    // modal window.
    $.fn.colorboxNodeGroup = function () {
        // Lets do setup our gallery type of functions.
        var $this = $(this);
        var rel = $this.attr('rel');
        if(rel && $this.hasClass('colorbox-node-gallery')) {
            if ($('a.colorbox-node-gallery[rel="' + rel + '"]:not("#colorbox a[rel="' + rel + '"]")').length > 1) {
                $related = $('a.colorbox-node-gallery[rel="' + rel + '"]:not("#colorbox a[rel="' + rel + '"]")');

                // filter $related array by href, to have mutliple colorbox links to the same target
                // appear as one item in the gallery only
                var $related_unique = [];
                $related.each(function() {
                    $.findHref($related_unique, this.href);
                    if (!$.findHref($related_unique, this.href).length) {
                        $related_unique.push(this);
                    }
                });
                // we have to get the actual used element from the filtered list in order to get it's relative index
                var current = $.findHref($related_unique, $this.get(0).href);
                $related = $($related_unique);
                var idx = $related.index($(current));
                var tot = $related.length;

                // Show our gallery buttons
                $('#cboxPrevious, #cboxNext').show();
                $.colorbox.next = function () {
                    index = getIndex(1);
                    $related[index].click();
                };
                $.colorbox.prev = function () {
                    index = getIndex(-1);
                    $related[index].click();
                };

                // Setup our current HTML
                $('#cboxCurrent').html(Drupal.settings.colorbox.current.replace('{current}', idx + 1).replace('{total}', tot)).show();
                $('#cboxNext').html(Drupal.settings.colorbox.next).show();
                $('#cboxPrevious').html(Drupal.settings.colorbox.previous).show();

                var prefix = 'colorbox';
                // Remove Bindings and re-add
                // @TODO: There must be a better way?  If we don't remove it causes a memory to be exhausted.
                $(document).unbind('keydown.' + prefix);

                // Add Key Bindings
                $(document).bind('keydown.' + prefix, function (e) {
                    var key = e.keyCode;
                    if ($related[1] && !e.altKey) {
                        if (key === 37) {
                            e.preventDefault();
                            $.colorbox.prev();
                        } else if (key === 39) {
                            e.preventDefault();
                            $.colorbox.next();
                        }
                    }
                });
            }

            function getIndex(increment) {
                var max = $related.length;
                var newIndex = (idx + increment) % max;
                return (newIndex < 0) ? max + newIndex : newIndex;
            }

        }
    }

    // Find a colorbox link by href in an array
    $.findHref = function(items, href) {
        return $.grep(items, function(n, i){
            return n.href == href;
        });
    };

    // Utility function to parse out our width/height from our url params
    $.urlParams = function (url) {
        var p = {},
            e,
            a = /\+/g,  // Regex for replacing addition symbol with a space
            r = /([^&=]+)=?([^&]*)/g,
            d = function (s) {
                return decodeURIComponent(s.replace(a, ' '));
            },
            q = url.split('?');
        while (e = r.exec(q[1])) {
            e[1] = d(e[1]);
            e[2] = d(e[2]);
            switch (e[2].toLowerCase()) {
                case 'true':
                case 'yes':
                    e[2] = true;
                    break;
                case 'false':
                case 'no':
                    e[2] = false;
                    break;
            }
            if (e[1] == 'width') {
                e[1] = 'innerWidth';
            }
            if (e[1] == 'height') {
                e[1] = 'innerHeight';
            }
            p[e[1]] = e[2];
        }
        return p;
    };

    // Utility function to return our data attributes for width/height
    $.urlDataParams = function (innerWidth, innerHeight) {
        return {'innerWidth':innerWidth,'innerHeight':innerHeight};
    };

    $.getParameterByName = function(name, href) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexString = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexString);
        var found = regex.exec(href);
        if(found == null)
            return "";
        else
            return decodeURIComponent(found[1].replace(/\+/g, " "));
    }

})(jQuery);
;
