<commit_before>;
(function($) {
  $(function(){

    path = "";

    var fancyBoxOptions = {
      "overlayOpacity": 0,
      "hideOnOverlayClick": false,
      "showCloseButton": false,
      "width": 300,
      "speedIn": 100,
      "speedOut": 100,
      "onComplete": function(){
        $(document).trigger("fancybox_ready")
      }
    };

    $.recountHeight();

    $(window).bind("resize", function(){
      $.recountHeight();
    });

    $("div.directories").folderTree()
    .contextMenu({  // bind context menu to delegate for all elements in folders column
      //title : "Folder menu",
      closeType : {
        zone : 'any',
        events : 'closeFolderClick,openFolderClick'
      },
      list : [
      {
        text : __("Add subfolder"),
        itemClass : "add",
        event : "onAddFolderClick",
        href : "http://www.google.com"
      },
      {
        text : __("Rename"),
        itemClass : "rename",
        event : "filebrowser_folder_rename"
      },
      "break",
      {
        text : __("Delete"),
        itemClass : "delete",
        event : "onDelFolderClick",
        handler : function(){
          alert("сработала функция-обработчик клика по пункту меню ");
          return false;
        },
        href : "/delfolder"
      }
      ]
    });

    $("#filesRow").contextMenu({ // bind context menu to delegate for all elements in files area
      targetSelector : "div.file",
      list: [
      {
        text: __("Select"),
        itemClass: "select"
      },
      {
        text: __("Download"),
        itemClass: "download",
        event: "filebrowser_file_download"
      },
      "break",
      {
        text: __("Resize"),
        itemClass: "resize",
        event: "filebrowser_image_resize"
      },
      {
        text: __("Crop"),
        itemClass: "crop",
        event: "filebrowser_image_crop"
      },
      {
        text: __("Rotate right"),
        itemClass: "rotate-right",
        event: "filebrowser_image_rotate_right"
      },
      {
        text: __("Rotate left"),
        itemClass: "rotate-left",
        event: "filebrowser_image_rotate_left"
      },
      "break",
      {
        text: __("Rename"),
        itemClass: "rename",
        event: "filebrowser_file_rename"
      },
      {
        text: __("Delete"),
        itemClass: "delete",
        event: "filebrowser_file_delete"
      }
      ]
    });

    $(document).bind("filebrowser_load_files", function(e, path) {
      $("#filesRow").empty();

      $.getJSON(global_config.files_url+path, function(data){
        $("#tpl-files").tmpl(data).appendTo("#filesRow");
      });
    }).bind(
    {
      "filebrowser_file_download" : function(e){
        alert($(e.target).children("p:first").text());
      },
      "filebrowser_image_resize" : function(e){
        alert($(e.target).children("p:first").text());
      // Need to open URI wysiwyg/filebrowser/resize/<path> in fancybox
      },
      "filebrowser_image_crop" : function(e){
        if(window.cropresizerWin)cropresizerWin.close();
        var imgSize = Function("var c = new Object(); c="+$(e.target).attr("rel")+"; return c")();
        var openSize = {
          w: (screen.availWidth >= imgSize.width + 20 && imgSize.width + 20 > 900)? imgSize.width + 20 : 900,
          h: (screen.availHeight >= imgSize.height + 50 && imgSize.width + 50 > 500)? imgSize.height + 50 : 500
        };
        window.open("/wysiwyg/filebrowser/crop/"+path+$(e.target).find("p.fileName span").text(), "cropresizerWin",
          "width="+openSize.w+", height="+openSize.h+", left="+(screen.availWidth-openSize.w)/2+", top="+(screen.availHeight-openSize.h)/2+", location=yes, resizable=yes");
      },
      "filebrowser_image_rotate_left" : function(e){
        $.get('wysiwyg/filebrowser/rotate_left/'+path+$(e.target).find("p.fileName span").text(), function(data){
          $(document).trigger('filebrowser_load_files', path)
        });
      },
      "filebrowser_image_rotate_right" : function(e){
        $.get('wysiwyg/filebrowser/rotate_right/'+path+$(e.target).find("p.fileName span").text(), function(data){
          $(document).trigger('filebrowser_load_files', path)
        });
      },
      "filebrowser_file_rename" : function(e){
        $.get('wysiwyg/filebrowser/rename/'+path+$(e.target).find("p.fileName span").text(), function(data){
          $.fancybox(data, fancyBoxOptions);
        });
      },
      "filebrowser_file_download" : function(e){
        location.replace('wysiwyg/filebrowser/download/'+path+$(e.target).find("p.fileName span").text());
      },
      "filebrowser_file_delete" : function(e){
        $.get('wysiwyg/filebrowser/delete/'+path+$(e.target).find("p.fileName span").text(), function(data){
          $.fancybox(data, fancyBoxOptions);
        });
      },
      "filebrowser_startFileMove" : function(){
        $("div.directories div").each(function(){
          $(this).getD().folderRect = $(this).children("p")[0].getBoundingClientRect();
        });
      },

      // Folder menu events
      "filebrowser_folder_rename" : function(e){
        $.get("wysiwyg/filebrowser/rename/"+path+$(e.target).text(), function(data){
          $.fancybox(data, fancyBoxOptions);
        });
      },

      // begin "fancybox_ready" handler
      "fancybox_ready" : function(){
        $("#fancybox-content form").ajaxForm({
          "success": function(responseText, statusText, xhr, $form) {
            if(responseText === "") {
              $(document).trigger("filebrowser_load_files", path);
              $.fancybox.close()
            } else {
              $form.parent().html(responseText);
              $(document).trigger("fancybox_ready")
            }
          }
        });

        $("#fancybox-content .close").click(function(){
          $.fancybox.close();
          return false;
        });

        $("#fancybox-content .ajaxed").each(function(){
          $(this).click(function(){
            $.get(this.href);
            $(document).trigger("filebrowser_load_files", path);
            $.fancybox.close();
            return false;
          })
        });

        window.addEvent('domready', function() {
          /**
           * Uploader instance
           */
          var up = new FancyUpload3.Attach('upload', '#fancybox-content .attach, #fancybox-content .attach-another', {
            path: '/media/filebrowser/fancyupload/Swiff.Uploader.swf',
            url: '/wysiwyg/filebrowser/upload'+path,
            fileSizeMax: 20 * 1024 * 1024,

            verbose: true,

            onSelectFail: function(files) {
              files.each(function(file) {
                new Element('li', {
                  'class': 'file-invalid',
                  events: {
                    click: function() {
                      this.destroy();
                    }
                  }
                }).adopt(
                  new Element('span', {
                    html: file.validationErrorMessage || file.validationError
                  })
                  ).inject(this.list, 'top');
              }, this);
            },

            onFileSuccess: function(file) {
              file.ui.element.highlight('#e6efc2');
            },

            onFileError: function(file) {
              file.ui.cancel.set('html', __("Retry")).removeEvents().addEvent('click', function() {
                file.requeue();
                return false;
              });

              new Element('span', {
                html: file.errorMessage,
                'class': 'file-error'
              }).inject(file.ui.cancel, 'before');
            },

            onFileRequeue: function(file) {
              file.ui.element.getElement('.file-error').destroy();

              file.ui.cancel.set('html', __("Cancel")).removeEvents().addEvent('click', function() {
                file.remove();
                return false;
              });

              this.start();
            }

          });

        });
      },
      // end "fancybox_ready" handler

      onOpenContextMenu : function(e){
        if($(e.target).parent().parent().attr("id") == "root") $(e.menu).pointToggleActive(3);
      }

    }) // end of bind events to document
    .trigger("filebrowser_load_dirs", "")
    .trigger("filebrowser_load_files", "");

    $("#refresh").click(function(){
      $(document).trigger("filebrowser_load_files", path);
      return false
    });

    $("a[rel=boxed]").fancybox(fancyBoxOptions);

    // drag files to folders
    $("#filesRow").delegate("div.file", "mousedown", function(event){
      if(event.which == 1) { // left button down only
        var draggedFile = $(this).addClass("replacing");

        var clone = $("
", {
          "class" : "file clone",
          "css"   : {
            "left" :draggedFile.offset().left+"px",
            "top"  : draggedFile.offset().top+"px"
          },
          "html" : draggedFile.html(),
          "selectstart" : function(){
            return false;
          }
        }).appendTo("body").append("

");

        var shift = {
          X : event.clientX-clone.position().left,
          Y : event.clientY-clone.position().top
        };

        var overFolder = false;
        var prevMove = false;

        $(document).bind({
          mousemove : function(e){
            if(!prevMove) {
              $(document).trigger("filebrowser_startFileMove");
              prevMove = true;
            }
            clone.css({
              left: e.clientX-shift.X+"px",
              top : e.clientY-shift.Y+"px"
            });
            overFolder = false;
            $("div.directories div").each(function(){ // on each move check panels for find panel under during mouse position
              if($(this).draggingOver(e) && !$(this).getD().filesLoaded) {
                overFolder = $(this);
                $(this).children("p").addClass("overDrop");
              }
              else $(this).children("p").removeClass("overDrop");
            });
          },

          mouseup   : function(e){
            $(document).unbind("mousemove");
            if(overFolder) {
              clone.empty().animate({
                width: "5px",
                height: "5px",
                left:   overFolder.getD().folderRect.left*1+10+"px",
                top:   overFolder.getD().folderRect.top+"px"
              },{
                complete: function(){
                  $(this).remove();
                  draggedFile.removeClass("replacing");
                  $(document).unbind("mouseup");
                },
                duration: 200
              });

              var fileName = clone.children("p.fileName").children("span").text();

              var post = {
                "to": overFolder.getD().path
              };

              $.post(global_config.move_url+path+"/"+fileName, post, function(data){
                if (data.result == "ok") {
                  $(document).trigger("filebrowser_load_files", path);
                }
              }, "json");
              overFolder.children("p").removeClass("overDrop");
            }
            else {
              clone.fadeOut(function(){
                $(this).remove();
                draggedFile.removeClass("replacing");
                $(document).unbind("mouseup");
              });
            }
          }
        }); // end of mouse events handlers
      }
    });
  });
  // end document ready

  $.extend({
    "recountHeight": function(){
      $("#dirs>div.directories").height($("body").height()-85+"px");
      $("#files").height($("body").height()-$("#info_wrap").height() - 45+"px");
    }
  });

  $.fn.draggingOver = function(ev){
    var area = this.getD().folderRect;
    return (area.left < ev.clientX && area.right > ev.clientX &&
      area.top < ev.clientY && area.bottom > ev.clientY) ? true : false;
  }

})(jQuery);<commit_msg>Passing the URL of the selected file to the editor opened dialog<commit_after>;
(function($) {
  $(function(){

    path = ""; // this global variable get value on each selecting of folders by execute code in directories.js

    var fancyBoxOptions = {
      "overlayOpacity": 0,
      "hideOnOverlayClick": false,
      "showCloseButton": false,
      "width": 300,
      "speedIn": 100,
      "speedOut": 100,
      "onComplete": function(){
        $(document).trigger("fancybox_ready")
      }
    };

    $.recountHeight();
    $(window).bind("resize", function(){
      $.recountHeight();
    });

    $("div.directories").folderTree()
    .contextMenu({  // bind context menu to delegate for all elements in folders column
      //title : "Folder menu",
      closeType : {
        zone : 'any',
        events : 'closeFolderClick,openFolderClick'
      },
      list : [
      {
        text : __("Add subfolder"),
        itemClass : "add",
        event : "onAddFolderClick",
        href : "http://www.google.com"
      },
      {
        text : __("Rename"),
        itemClass : "rename",
        event : "filebrowser_folder_rename"
      },
      "break",
      {
        text : __("Delete"),
        itemClass : "delete",
        event : "onDelFolderClick",
        handler : function(){
          alert("сработала функция-обработчик клика по пункту меню ");
          return false;
        },
        href : "/delfolder"
      }
      ]
    });

    $("#filesRow").contextMenu({ // bind context menu to delegate for all elements in files area
      targetSelector : "div.file",
      list: [
      {
        text: __("Select"),
        itemClass: "select",
        event: "filebrowser_file_select"
      },
      {
        text: __("Download"),
        itemClass: "download",
        event: "filebrowser_file_download"
      },
      "break",
      {
        text: __("Resize"),
        itemClass: "resize",
        event: "filebrowser_image_resize"
      },
      {
        text: __("Crop"),
        itemClass: "crop",
        event: "filebrowser_image_crop"
      },
      {
        text: __("Rotate right"),
        itemClass: "rotate-right",
        event: "filebrowser_image_rotate_right"
      },
      {
        text: __("Rotate left"),
        itemClass: "rotate-left",
        event: "filebrowser_image_rotate_left"
      },
      "break",
      {
        text: __("Rename"),
        itemClass: "rename",
        event: "filebrowser_file_rename"
      },
      {
        text: __("Delete"),
        itemClass: "delete",
        event: "filebrowser_file_delete"
      }
      ]
    });

    $(document).bind("filebrowser_load_files", function(e, path) {
      $("#filesRow").empty();

      $.getJSON(global_config.files_url+path, function(data){
        $("#tpl-files").tmpl(data).appendTo("#filesRow");
      });
    }).bind(
    {
      "filebrowser_file_select" : function(e) {
        window.opener.CKEDITOR.tools.callFunction($.getUrlParam('CKEditorFuncNum'), 'wysiwyg/filebrowser/download/'+path+$(e.target).find("p.fileName span").text());
        window.close();
      },

      "filebrowser_image_resize" : function(e){
        alert($(e.target).children("p:first").text());
      // Need to open URI wysiwyg/filebrowser/resize/<path> in fancybox
      },

      "filebrowser_image_crop" : function(e){
        if(window.cropresizerWin)cropresizerWin.close();
        var imgSize = Function("var c = new Object(); c="+$(e.target).attr("rel")+"; return c")();
        var openSize = {
          w: (screen.availWidth >= imgSize.width + 20 && imgSize.width + 20 > 900)? imgSize.width + 20 : 900,
          h: (screen.availHeight >= imgSize.height + 50 && imgSize.width + 50 > 500)? imgSize.height + 50 : 500
        };
        window.open("/wysiwyg/filebrowser/crop/"+$.getSelectedFilePath(e), "cropresizerWin",
          "width="+openSize.w+", height="+openSize.h+", left="+(screen.availWidth-openSize.w)/2+", top="+(screen.availHeight-openSize.h)/2+", location=yes, resizable=yes");
      },

      "filebrowser_image_rotate_left" : function(e){
        $.get('wysiwyg/filebrowser/rotate_left/'+$.getSelectedFilePath(e), function(data){
          $(document).trigger('filebrowser_load_files', path)
        });
      },

      "filebrowser_image_rotate_right" : function(e){
        $.get('wysiwyg/filebrowser/rotate_right/'+$.getSelectedFilePath(e), function(data){
          $(document).trigger('filebrowser_load_files', path)
        });
      },

      "filebrowser_file_rename" : function(e){
        $.get('wysiwyg/filebrowser/rename/'+$.getSelectedFilePath(e), function(data){
          $.fancybox(data, fancyBoxOptions);
        });
      },

      "filebrowser_file_download" : function(e){
        location.replace('wysiwyg/filebrowser/download/'+$.getSelectedFilePath(e));
      },

      "filebrowser_file_delete" : function(e){
        $.get('wysiwyg/filebrowser/delete/'+$.getSelectedFilePath(e), function(data){
          $.fancybox(data, fancyBoxOptions);
        });
      },

      "filebrowser_startFileMove" : function(){
        $("div.directories div").each(function(){
          $(this).getD().folderRect = $(this).children("p")[0].getBoundingClientRect();
        });
      },

      // Folder menu events
      "filebrowser_folder_rename" : function(e){
        $.get("wysiwyg/filebrowser/rename/"+path+$(e.target).text(), function(data){
          $.fancybox(data, fancyBoxOptions);
        });
      },

      // begin "fancybox_ready" handler
      "fancybox_ready" : function(){
        $("#fancybox-content form").ajaxForm({
          "success": function(responseText, statusText, xhr, $form) {
            if(responseText === "") {
              $(document).trigger("filebrowser_load_files", path);
              $.fancybox.close()
            } else {
              $form.parent().html(responseText);
              $(document).trigger("fancybox_ready")
            }
          }
        });

        $("#fancybox-content .close").click(function(){
          $.fancybox.close();
          return false;
        });

        $("#fancybox-content .ajaxed").each(function(){
          $(this).click(function(){
            $.get(this.href);
            $(document).trigger("filebrowser_load_files", path);
            $.fancybox.close();
            return false;
          })
        });

        window.addEvent('domready', function() {
          /**
           * Uploader instance
           */
          var up = new FancyUpload3.Attach('upload', '#fancybox-content .attach, #fancybox-content .attach-another', {
            path: '/media/filebrowser/fancyupload/Swiff.Uploader.swf',
            url: '/wysiwyg/filebrowser/upload'+path,
            fileSizeMax: 20 * 1024 * 1024,

            verbose: true,

            onSelectFail: function(files) {
              files.each(function(file) {
                new Element('li', {
                  'class': 'file-invalid',
                  events: {
                    click: function() {
                      this.destroy();
                    }
                  }
                }).adopt(
                  new Element('span', {
                    html: file.validationErrorMessage || file.validationError
                  })
                  ).inject(this.list, 'top');
              }, this);
            },

            onFileSuccess: function(file) {
              file.ui.element.highlight('#e6efc2');
            },

            onFileError: function(file) {
              file.ui.cancel.set('html', __("Retry")).removeEvents().addEvent('click', function() {
                file.requeue();
                return false;
              });

              new Element('span', {
                html: file.errorMessage,
                'class': 'file-error'
              }).inject(file.ui.cancel, 'before');
            },

            onFileRequeue: function(file) {
              file.ui.element.getElement('.file-error').destroy();

              file.ui.cancel.set('html', __("Cancel")).removeEvents().addEvent('click', function() {
                file.remove();
                return false;
              });

              this.start();
            }

          });

        });
      },
      // end "fancybox_ready" handler

      onOpenContextMenu : function(e){
        if($(e.target).parent().parent().attr("id") == "root") $(e.menu).pointToggleActive(3);
      }

    }) // end of bind events to document
    .trigger("filebrowser_load_dirs", "")
    .trigger("filebrowser_load_files", "");

    $("#refresh").click(function(){
      $(document).trigger("filebrowser_load_files", path);
      return false
    });

    $("a[rel=boxed]").fancybox(fancyBoxOptions);

    // drag files to folders
    $("#filesRow").delegate("div.file", "mousedown", function(event){
      if(event.which == 1) { // left button down only to drag file
        var draggedFile = $(this).addClass("replacing");

        var clone = $("
", {
          "class" : "file clone",
          "css"   : {
            "left" :draggedFile.offset().left+"px",
            "top"  : draggedFile.offset().top+"px"
          },
          "html" : draggedFile.html(),
          "selectstart" : function(){
            return false;
          }
        }).appendTo("body").append("

");

        var shift = {
          X : event.clientX-clone.position().left,
          Y : event.clientY-clone.position().top
        };

        var overFolder = false;
        var prevMove = false;

        $(document).bind({
          mousemove : function(e){
            if(!prevMove) {
              $(document).trigger("filebrowser_startFileMove");
              prevMove = true;
            }
            clone.css({
              left: e.clientX-shift.X+"px",
              top : e.clientY-shift.Y+"px"
            });
            overFolder = false;
            $("div.directories div").each(function(){ // on each move check panels for find panel under during mouse position
              if($(this).draggingOver(e) && !$(this).getD().filesLoaded) {
                overFolder = $(this);
                $(this).children("p").addClass("overDrop");
              }
              else $(this).children("p").removeClass("overDrop");
            });
          },

          mouseup   : function(e){
            $(document).unbind("mousemove");
            if(overFolder) {
              clone.empty().animate({
                width: "5px",
                height: "5px",
                left:   overFolder.getD().folderRect.left*1+10+"px",
                top:   overFolder.getD().folderRect.top+"px"
              },{
                complete: function(){
                  $(this).remove();
                  draggedFile.removeClass("replacing");
                  $(document).unbind("mouseup");
                },
                duration: 200
              });

              var fileName = clone.children("p.fileName").children("span").text();

              var post = {
                "to": overFolder.getD().path
              };

              $.post(global_config.move_url+path+"/"+fileName, post, function(data){
                if (data.result == "ok") {
                  $(document).trigger("filebrowser_load_files", path);
                }
              }, "json");
              overFolder.children("p").removeClass("overDrop");
            }
            else {
              clone.fadeOut(function(){
                $(this).remove();
                draggedFile.removeClass("replacing");
                $(document).unbind("mouseup");
              });
            }
          }
        }); // end of mouse events handlers
      } // end of if
    }); // end of delegate
  });
  // end document ready

  $.extend({
    "recountHeight": function(){
      $("#dirs>div.directories").height($("body").height()-85+"px");
      $("#files").height($("body").height()-$("#info_wrap").height() - 45+"px");
    }
  });

  $.fn.draggingOver = function(ev){
    var area = this.getD().folderRect;
    return (area.left < ev.clientX && area.right > ev.clientX &&
      area.top < ev.clientY && area.bottom > ev.clientY) ? true : false;
  }

  $.getUrlParam = function(paramName){
    var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i') ;
    var match = window.location.search.match(reParam) ;
    return (match && match.length > 1) ? match[1] : '' ;
  }

  $.getSelectedFilePath = function(contextMenuEvent) {
   return path+$(contextMenuEvent.target).find("p.fileName span").text()
  }

})(jQuery);<|endoftext|>


<commit_before>'use strict';

;(function(root) {

/** Highest positive signed 32-bit float value */
const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1

/** Bootstring parameters */
const base = 36;
const tMin = 1;
const tMax = 26;
const skew = 38;
const damp = 700;
const initialBias = 72;
const initialN = 128; // 0x80
const delimiter = '-'; // '\x2D'

/** Regular expressions */
const regexPunycode = /^xn--/;
const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators

/** Error messages */
const errors = {
	'overflow': 'Overflow: input needs wider integers to process',
	'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
	'invalid-input': 'Invalid input'
};

/** Convenience shortcuts */
const baseMinusTMin = base - tMin;
const floor = Math.floor;
const stringFromCharCode = String.fromCharCode;

/*--------------------------------------------------------------------------*/

/**
 * A generic error utility function.
 * @private
 * @param {String} type The error type.
 * @returns {Error} Throws a `RangeError` with the applicable error message.
 */
function error(type) {
	throw new RangeError(errors[type]);
}

/**
 * A generic `Array#map` utility function.
 * @private
 * @param {Array} array The array to iterate over.
 * @param {Function} callback The function that gets called for every array
 * item.
 * @returns {Array} A new array of values returned by the callback function.
 */
function map(array, fn) {
	const result = [];
	let length = array.length;
	while (length--) {
		result[length] = fn(array[length]);
	}
	return result;
}

/**
 * A simple `Array#map`-like wrapper to work with domain name strings or email
 * addresses.
 * @private
 * @param {String} domain The domain name or email address.
 * @param {Function} callback The function that gets called for every
 * character.
 * @returns {Array} A new string of characters returned by the callback
 * function.
 */
function mapDomain(string, fn) {
	const parts = string.split('@');
	let result = '';
	if (parts.length > 1) {
		// In email addresses, only the domain name should be punycoded. Leave
		// the local part (i.e. everything up to `@`) intact.
		result = parts[0] + '@';
		string = parts[1];
	}
	// Avoid `split(regex)` for IE8 compatibility. See #17.
	string = string.replace(regexSeparators, '\x2E');
	const labels = string.split('.');
	const encoded = map(labels, fn).join('.');
	return result + encoded;
}

/**
 * Creates an array containing the numeric code points of each Unicode
 * character in the string. While JavaScript uses UCS-2 internally,
 * this function will convert a pair of surrogate halves (each of which
 * UCS-2 exposes as separate characters) into a single code point,
 * matching UTF-16.
 * @see `punycode.ucs2.encode`
 * @see <https://mathiasbynens.be/notes/javascript-encoding>
 * @memberOf punycode.ucs2
 * @name decode
 * @param {String} string The Unicode input string (UCS-2).
 * @returns {Array} The new array of code points.
 */
function ucs2decode(string) {
	const output = [];
	let counter = 0;
	const length = string.length;
	while (counter < length) {
		const value = string.charCodeAt(counter++);
		if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
			// It's a high surrogate, and there is a next character.
			const extra = string.charCodeAt(counter++);
			if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
				output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
			} else {
				// It's an unmatched surrogate; only append this code unit, in case the
				// next code unit is the high surrogate of a surrogate pair.
				output.push(value);
				counter--;
			}
		} else {
			output.push(value);
		}
	}
	return output;
}

/**
 * Creates a string based on an array of numeric code points.
 * @see `punycode.ucs2.decode`
 * @memberOf punycode.ucs2
 * @name encode
 * @param {Array} codePoints The array of numeric code points.
 * @returns {String} The new Unicode string (UCS-2).
 */
const ucs2encode = array => String.fromCodePoint(...array);

/**
 * Converts a basic code point into a digit/integer.
 * @see `digitToBasic()`
 * @private
 * @param {Number} codePoint The basic numeric code point value.
 * @returns {Number} The numeric value of a basic code point (for use in
 * representing integers) in the range `0` to `base - 1`, or `base` if
 * the code point does not represent a value.
 */
const basicToDigit = function(codePoint) {
	if (codePoint - 0x30 < 0x0A) {
		return codePoint - 0x16;
	}
	if (codePoint - 0x41 < 0x1A) {
		return codePoint - 0x41;
	}
	if (codePoint - 0x61 < 0x1A) {
		return codePoint - 0x61;
	}
	return base;
};

/**
 * Converts a digit/integer into a basic code point.
 * @see `basicToDigit()`
 * @private
 * @param {Number} digit The numeric value of a basic code point.
 * @returns {Number} The basic code point whose value (when used for
 * representing integers) is `digit`, which needs to be in the range
 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
 * used; else, the lowercase form is used. The behavior is undefined
 * if `flag` is non-zero and `digit` has no uppercase form.
 */
const digitToBasic = function(digit, flag) {
	//  0..25 map to ASCII a..z or A..Z
	// 26..35 map to ASCII 0..9
	return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};

/**
 * Bias adaptation function as per section 3.4 of RFC 3492.
 * https://tools.ietf.org/html/rfc3492#section-3.4
 * @private
 */
const adapt = function(delta, numPoints, firstTime) {
	let k = 0;
	delta = firstTime ? floor(delta / damp) : delta >> 1;
	delta += floor(delta / numPoints);
	for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
		delta = floor(delta / baseMinusTMin);
	}
	return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};

/**
 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
 * symbols.
 * @memberOf punycode
 * @param {String} input The Punycode string of ASCII-only symbols.
 * @returns {String} The resulting string of Unicode symbols.
 */
const decode = function(input) {
	// Don't use UCS-2.
	const output = [];
	const inputLength = input.length;
	let i = 0;
	let n = initialN;
	let bias = initialBias;

	// Handle the basic code points: let `basic` be the number of input code
	// points before the last delimiter, or `0` if there is none, then copy
	// the first basic code points to the output.

	let basic = input.lastIndexOf(delimiter);
	if (basic < 0) {
		basic = 0;
	}

	for (let j = 0; j < basic; ++j) {
		// if it's not a basic code point
		if (input.charCodeAt(j) >= 0x80) {
			error('not-basic');
		}
		output.push(input.charCodeAt(j));
	}

	// Main decoding loop: start just after the last delimiter if any basic code
	// points were copied; start at the beginning otherwise.

	for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {

		// `index` is the index of the next character to be consumed.
		// Decode a generalized variable-length integer into `delta`,
		// which gets added to `i`. The overflow checking is easier
		// if we increase `i` as we go, then subtract off its starting
		// value at the end to obtain `delta`.
		let oldi = i;
		for (let w = 1, k = base; /* no condition */; k += base) {

			if (index >= inputLength) {
				error('invalid-input');
			}

			const digit = basicToDigit(input.charCodeAt(index++));

			if (digit >= base || digit > floor((maxInt - i) / w)) {
				error('overflow');
			}

			i += digit * w;
			const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);

			if (digit < t) {
				break;
			}

			const baseMinusT = base - t;
			if (w > floor(maxInt / baseMinusT)) {
				error('overflow');
			}

			w *= baseMinusT;

		}

		const out = output.length + 1;
		bias = adapt(i - oldi, out, oldi == 0);

		// `i` was supposed to wrap around from `out` to `0`,
		// incrementing `n` each time, so we'll fix that now:
		if (floor(i / out) > maxInt - n) {
			error('overflow');
		}

		n += floor(i / out);
		i %= out;

		// Insert `n` at position `i` of the output.
		output.splice(i++, 0, n);

	}

	return String.fromCodePoint(...output);
};

/**
 * Converts a string of Unicode symbols (e.g. a domain name label) to a
 * Punycode string of ASCII-only symbols.
 * @memberOf punycode
 * @param {String} input The string of Unicode symbols.
 * @returns {String} The resulting Punycode string of ASCII-only symbols.
 */
const encode = function(input) {
	const output = [];

	// Convert the input in UCS-2 to an array of Unicode code points.
	input = ucs2decode(input);

	// Cache the length.
	let inputLength = input.length;

	// Initialize the state.
	let n = initialN;
	let delta = 0;
	let bias = initialBias;

	// Handle the basic code points.
	for (const currentValue of input) {
		if (currentValue < 0x80) {
			output.push(stringFromCharCode(currentValue));
		}
	}

	let basicLength = output.length;
	let handledCPCount = basicLength;

	// `handledCPCount` is the number of code points that have been handled;
	// `basicLength` is the number of basic code points.

	// Finish the basic string with a delimiter unless it's empty.
	if (basicLength) {
		output.push(delimiter);
	}

	// Main encoding loop:
	while (handledCPCount < inputLength) {

		// All non-basic code points < n have been handled already. Find the next
		// larger one:
		let m = maxInt;
		for (const currentValue of input) {
			if (currentValue >= n && currentValue < m) {
				m = currentValue;
			}
		}

		// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
		// but guard against overflow.
		const handledCPCountPlusOne = handledCPCount + 1;
		if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
			error('overflow');
		}

		delta += (m - n) * handledCPCountPlusOne;
		n = m;

		for (const currentValue of input) {
			if (currentValue < n && ++delta > maxInt) {
				error('overflow');
			}
			if (currentValue == n) {
				// Represent delta as a generalized variable-length integer.
				let q = delta;
				for (let k = base; /* no condition */; k += base) {
					const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
					if (q < t) {
						break;
					}
					const qMinusT = q - t;
					const baseMinusT = base - t;
					output.push(
						stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
					);
					q = floor(qMinusT / baseMinusT);
				}

				output.push(stringFromCharCode(digitToBasic(q, 0)));
				bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
				delta = 0;
				++handledCPCount;
			}
		}

		++delta;
		++n;

	}
	return output.join('');
};

/**
 * Converts a Punycode string representing a domain name or an email address
 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
 * it doesn't matter if you call it on a string that has already been
 * converted to Unicode.
 * @memberOf punycode
 * @param {String} input The Punycoded domain name or email address to
 * convert to Unicode.
 * @returns {String} The Unicode representation of the given Punycode
 * string.
 */
const toUnicode = function(input) {
	return mapDomain(input, function(string) {
		return regexPunycode.test(string)
			? decode(string.slice(4).toLowerCase())
			: string;
	});
};

/**
 * Converts a Unicode string representing a domain name or an email address to
 * Punycode. Only the non-ASCII parts of the domain name will be converted,
 * i.e. it doesn't matter if you call it with a domain that's already in
 * ASCII.
 * @memberOf punycode
 * @param {String} input The domain name or email address to convert, as a
 * Unicode string.
 * @returns {String} The Punycode representation of the given domain name or
 * email address.
 */
const toASCII = function(input) {
	return mapDomain(input, function(string) {
		return regexNonASCII.test(string)
			? 'xn--' + encode(string)
			: string;
	});
};

/*--------------------------------------------------------------------------*/

/** Define the public API */
window.punycode = {
	/**
	 * A string representing the current Punycode.js version number.
	 * @memberOf punycode
	 * @type String
	 */
	'version': '2.1.0',
	/**
	 * An object of methods to convert from JavaScript's internal character
	 * representation (UCS-2) to Unicode code points, and back.
	 * @see <https://mathiasbynens.be/notes/javascript-encoding>
	 * @memberOf punycode
	 * @type Object
	 */
	'ucs2': {
		'decode': ucs2decode,
		'encode': ucs2encode
	},
	'decode': decode,
	'encode': encode,
	'toASCII': toASCII,
	'toUnicode': toUnicode
};

})(this);
<commit_msg>Remove punycode library loader modification<commit_after>'use strict';

/** Highest positive signed 32-bit float value */
const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1

/** Bootstring parameters */
const base = 36;
const tMin = 1;
const tMax = 26;
const skew = 38;
const damp = 700;
const initialBias = 72;
const initialN = 128; // 0x80
const delimiter = '-'; // '\x2D'

/** Regular expressions */
const regexPunycode = /^xn--/;
const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators

/** Error messages */
const errors = {
	'overflow': 'Overflow: input needs wider integers to process',
	'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
	'invalid-input': 'Invalid input'
};

/** Convenience shortcuts */
const baseMinusTMin = base - tMin;
const floor = Math.floor;
const stringFromCharCode = String.fromCharCode;

/*--------------------------------------------------------------------------*/

/**
 * A generic error utility function.
 * @private
 * @param {String} type The error type.
 * @returns {Error} Throws a `RangeError` with the applicable error message.
 */
function error(type) {
	throw new RangeError(errors[type]);
}

/**
 * A generic `Array#map` utility function.
 * @private
 * @param {Array} array The array to iterate over.
 * @param {Function} callback The function that gets called for every array
 * item.
 * @returns {Array} A new array of values returned by the callback function.
 */
function map(array, fn) {
	const result = [];
	let length = array.length;
	while (length--) {
		result[length] = fn(array[length]);
	}
	return result;
}

/**
 * A simple `Array#map`-like wrapper to work with domain name strings or email
 * addresses.
 * @private
 * @param {String} domain The domain name or email address.
 * @param {Function} callback The function that gets called for every
 * character.
 * @returns {Array} A new string of characters returned by the callback
 * function.
 */
function mapDomain(string, fn) {
	const parts = string.split('@');
	let result = '';
	if (parts.length > 1) {
		// In email addresses, only the domain name should be punycoded. Leave
		// the local part (i.e. everything up to `@`) intact.
		result = parts[0] + '@';
		string = parts[1];
	}
	// Avoid `split(regex)` for IE8 compatibility. See #17.
	string = string.replace(regexSeparators, '\x2E');
	const labels = string.split('.');
	const encoded = map(labels, fn).join('.');
	return result + encoded;
}

/**
 * Creates an array containing the numeric code points of each Unicode
 * character in the string. While JavaScript uses UCS-2 internally,
 * this function will convert a pair of surrogate halves (each of which
 * UCS-2 exposes as separate characters) into a single code point,
 * matching UTF-16.
 * @see `punycode.ucs2.encode`
 * @see <https://mathiasbynens.be/notes/javascript-encoding>
 * @memberOf punycode.ucs2
 * @name decode
 * @param {String} string The Unicode input string (UCS-2).
 * @returns {Array} The new array of code points.
 */
function ucs2decode(string) {
	const output = [];
	let counter = 0;
	const length = string.length;
	while (counter < length) {
		const value = string.charCodeAt(counter++);
		if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
			// It's a high surrogate, and there is a next character.
			const extra = string.charCodeAt(counter++);
			if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
				output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
			} else {
				// It's an unmatched surrogate; only append this code unit, in case the
				// next code unit is the high surrogate of a surrogate pair.
				output.push(value);
				counter--;
			}
		} else {
			output.push(value);
		}
	}
	return output;
}

/**
 * Creates a string based on an array of numeric code points.
 * @see `punycode.ucs2.decode`
 * @memberOf punycode.ucs2
 * @name encode
 * @param {Array} codePoints The array of numeric code points.
 * @returns {String} The new Unicode string (UCS-2).
 */
const ucs2encode = array => String.fromCodePoint(...array);

/**
 * Converts a basic code point into a digit/integer.
 * @see `digitToBasic()`
 * @private
 * @param {Number} codePoint The basic numeric code point value.
 * @returns {Number} The numeric value of a basic code point (for use in
 * representing integers) in the range `0` to `base - 1`, or `base` if
 * the code point does not represent a value.
 */
const basicToDigit = function(codePoint) {
	if (codePoint - 0x30 < 0x0A) {
		return codePoint - 0x16;
	}
	if (codePoint - 0x41 < 0x1A) {
		return codePoint - 0x41;
	}
	if (codePoint - 0x61 < 0x1A) {
		return codePoint - 0x61;
	}
	return base;
};

/**
 * Converts a digit/integer into a basic code point.
 * @see `basicToDigit()`
 * @private
 * @param {Number} digit The numeric value of a basic code point.
 * @returns {Number} The basic code point whose value (when used for
 * representing integers) is `digit`, which needs to be in the range
 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
 * used; else, the lowercase form is used. The behavior is undefined
 * if `flag` is non-zero and `digit` has no uppercase form.
 */
const digitToBasic = function(digit, flag) {
	//  0..25 map to ASCII a..z or A..Z
	// 26..35 map to ASCII 0..9
	return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};

/**
 * Bias adaptation function as per section 3.4 of RFC 3492.
 * https://tools.ietf.org/html/rfc3492#section-3.4
 * @private
 */
const adapt = function(delta, numPoints, firstTime) {
	let k = 0;
	delta = firstTime ? floor(delta / damp) : delta >> 1;
	delta += floor(delta / numPoints);
	for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
		delta = floor(delta / baseMinusTMin);
	}
	return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};

/**
 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
 * symbols.
 * @memberOf punycode
 * @param {String} input The Punycode string of ASCII-only symbols.
 * @returns {String} The resulting string of Unicode symbols.
 */
const decode = function(input) {
	// Don't use UCS-2.
	const output = [];
	const inputLength = input.length;
	let i = 0;
	let n = initialN;
	let bias = initialBias;

	// Handle the basic code points: let `basic` be the number of input code
	// points before the last delimiter, or `0` if there is none, then copy
	// the first basic code points to the output.

	let basic = input.lastIndexOf(delimiter);
	if (basic < 0) {
		basic = 0;
	}

	for (let j = 0; j < basic; ++j) {
		// if it's not a basic code point
		if (input.charCodeAt(j) >= 0x80) {
			error('not-basic');
		}
		output.push(input.charCodeAt(j));
	}

	// Main decoding loop: start just after the last delimiter if any basic code
	// points were copied; start at the beginning otherwise.

	for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {

		// `index` is the index of the next character to be consumed.
		// Decode a generalized variable-length integer into `delta`,
		// which gets added to `i`. The overflow checking is easier
		// if we increase `i` as we go, then subtract off its starting
		// value at the end to obtain `delta`.
		let oldi = i;
		for (let w = 1, k = base; /* no condition */; k += base) {

			if (index >= inputLength) {
				error('invalid-input');
			}

			const digit = basicToDigit(input.charCodeAt(index++));

			if (digit >= base || digit > floor((maxInt - i) / w)) {
				error('overflow');
			}

			i += digit * w;
			const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);

			if (digit < t) {
				break;
			}

			const baseMinusT = base - t;
			if (w > floor(maxInt / baseMinusT)) {
				error('overflow');
			}

			w *= baseMinusT;

		}

		const out = output.length + 1;
		bias = adapt(i - oldi, out, oldi == 0);

		// `i` was supposed to wrap around from `out` to `0`,
		// incrementing `n` each time, so we'll fix that now:
		if (floor(i / out) > maxInt - n) {
			error('overflow');
		}

		n += floor(i / out);
		i %= out;

		// Insert `n` at position `i` of the output.
		output.splice(i++, 0, n);

	}

	return String.fromCodePoint(...output);
};

/**
 * Converts a string of Unicode symbols (e.g. a domain name label) to a
 * Punycode string of ASCII-only symbols.
 * @memberOf punycode
 * @param {String} input The string of Unicode symbols.
 * @returns {String} The resulting Punycode string of ASCII-only symbols.
 */
const encode = function(input) {
	const output = [];

	// Convert the input in UCS-2 to an array of Unicode code points.
	input = ucs2decode(input);

	// Cache the length.
	let inputLength = input.length;

	// Initialize the state.
	let n = initialN;
	let delta = 0;
	let bias = initialBias;

	// Handle the basic code points.
	for (const currentValue of input) {
		if (currentValue < 0x80) {
			output.push(stringFromCharCode(currentValue));
		}
	}

	let basicLength = output.length;
	let handledCPCount = basicLength;

	// `handledCPCount` is the number of code points that have been handled;
	// `basicLength` is the number of basic code points.

	// Finish the basic string with a delimiter unless it's empty.
	if (basicLength) {
		output.push(delimiter);
	}

	// Main encoding loop:
	while (handledCPCount < inputLength) {

		// All non-basic code points < n have been handled already. Find the next
		// larger one:
		let m = maxInt;
		for (const currentValue of input) {
			if (currentValue >= n && currentValue < m) {
				m = currentValue;
			}
		}

		// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
		// but guard against overflow.
		const handledCPCountPlusOne = handledCPCount + 1;
		if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
			error('overflow');
		}

		delta += (m - n) * handledCPCountPlusOne;
		n = m;

		for (const currentValue of input) {
			if (currentValue < n && ++delta > maxInt) {
				error('overflow');
			}
			if (currentValue == n) {
				// Represent delta as a generalized variable-length integer.
				let q = delta;
				for (let k = base; /* no condition */; k += base) {
					const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
					if (q < t) {
						break;
					}
					const qMinusT = q - t;
					const baseMinusT = base - t;
					output.push(
						stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
					);
					q = floor(qMinusT / baseMinusT);
				}

				output.push(stringFromCharCode(digitToBasic(q, 0)));
				bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
				delta = 0;
				++handledCPCount;
			}
		}

		++delta;
		++n;

	}
	return output.join('');
};

/**
 * Converts a Punycode string representing a domain name or an email address
 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
 * it doesn't matter if you call it on a string that has already been
 * converted to Unicode.
 * @memberOf punycode
 * @param {String} input The Punycoded domain name or email address to
 * convert to Unicode.
 * @returns {String} The Unicode representation of the given Punycode
 * string.
 */
const toUnicode = function(input) {
	return mapDomain(input, function(string) {
		return regexPunycode.test(string)
			? decode(string.slice(4).toLowerCase())
			: string;
	});
};

/**
 * Converts a Unicode string representing a domain name or an email address to
 * Punycode. Only the non-ASCII parts of the domain name will be converted,
 * i.e. it doesn't matter if you call it with a domain that's already in
 * ASCII.
 * @memberOf punycode
 * @param {String} input The domain name or email address to convert, as a
 * Unicode string.
 * @returns {String} The Punycode representation of the given domain name or
 * email address.
 */
const toASCII = function(input) {
	return mapDomain(input, function(string) {
		return regexNonASCII.test(string)
			? 'xn--' + encode(string)
			: string;
	});
};

/*--------------------------------------------------------------------------*/

/** Define the public API */
const punycode = {
	/**
	 * A string representing the current Punycode.js version number.
	 * @memberOf punycode
	 * @type String
	 */
	'version': '2.1.0',
	/**
	 * An object of methods to convert from JavaScript's internal character
	 * representation (UCS-2) to Unicode code points, and back.
	 * @see <https://mathiasbynens.be/notes/javascript-encoding>
	 * @memberOf punycode
	 * @type Object
	 */
	'ucs2': {
		'decode': ucs2decode,
		'encode': ucs2encode
	},
	'decode': decode,
	'encode': encode,
	'toASCII': toASCII,
	'toUnicode': toUnicode
};

module.exports = punycode;
<|endoftext|>


<commit_before>if (typeof NEWSBLUR == 'undefined') NEWSBLUR = {};
if (typeof NEWSBLUR.Globals == 'undefined') NEWSBLUR.Globals = {};

/* ============================= */
/* = Core NewsBlur Javascript = */
/* ============================= */

var URL_REGEX = /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi;

NEWSBLUR.log = function(msg) {
    try {
        if (typeof o == "object")
        {
            var new_m = [];
            for (var i=0; i < msg.length; i++) {
                if (i!=0) new_m.push(msg[i]);
            }
            console.debug(msg[0], new_m);
        }
        else
        {
            console.log(msg);
        }
    } catch(e) {
        console =
        {
            log: function() {}
        };
    }
};

(function($) {

    $.fn.extend({

        autolink: function() {
            return this.each(function(){
                var desc = $(this);
                desc.textNodes().each(function(){
                    var text = $(this);
                    if(text && text.parent() && text.parent()[0] && text.parent()[0].nodeName != 'A') {
                        text.replaceWith(this.data.replace(URL_REGEX, function($0, $1) {
                            return '' + $0 + '';
                        }));
                    }
                });
            });
        },

        textNodes: function() {
            var ret = [];

            (function(el){
                if (!el) return;
                if ((el.nodeType == 3)) {
                    ret.push(el);
                } else {
                    for (var i=0; i < el.childNodes.length; ++i) {
                        arguments.callee(el.childNodes[i]);
                    }
                }
            })(this[0]);
            return $(ret);
        },

        isScrollVisible: function($elem) {
            var docViewTop = 0; // $(this).scrollTop();
            var docViewBottom = docViewTop + $(this).height();
            var docOffset = $(this).offset().top;

            var elemTop = $elem.offset().top - docOffset;
            var elemBottom = elemTop + $elem.outerHeight();

            // NEWSBLUR.log(['isScrollVisible', docViewTop, docViewBottom, docOffset, elemTop, elemBottom]);

            return ((elemTop >= docViewTop) && (elemBottom <= docViewBottom));
        },

        // Align an element relative to a target element's coordinates. Forces the
        // element to be absolutely positioned. Element must be visible.
        // Position string format is: "top -right".
        // You can pass an optional offset object with top and left offsets specified.
        align : function(target, pos, offset) {
          var el = this;
          pos = pos || '';
          offset = offset || {};
          var scrollTop = document.documentElement.scrollTop || document.body.scrollTop || 0;
          var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft || 0;
          var clientWidth = document.documentElement.clientWidth;
          var clientHeight = document.documentElement.clientHeight;

          if (target == window) {
            var b = {
              left    : scrollLeft,
              top     : scrollTop,
              width   : $(window).width(),
              height  : $(window).height()
            };
          } else {
            target = $(target);
            var targOff = target.offset();
            var b = {
              left    : targOff.left,
              top     : targOff.top,
              width   : target.innerWidth(),
              height  : target.innerHeight()
            };
          }

          var elb = {
            width : el.innerWidth(),
            height : el.innerHeight()
          };

          var left, top;

          if (pos.indexOf('-left') >= 0) {
            left = b.left;
          } else if (pos.indexOf('left') >= 0) {
            left = b.left - elb.width;
          } else if (pos.indexOf('-right') >= 0) {
            left = b.left + b.width - elb.width;
          } else if (pos.indexOf('right') >= 0) {
            left = b.left + b.width;
          } else { // Centered.
            left = b.left + (b.width - elb.width) / 2;
          }

          if (pos.indexOf('-top') >= 0) {
            top = b.top;
          } else if (pos.indexOf('top') >= 0) {
            top = b.top - elb.height;
          } else if (pos.indexOf('-bottom') >= 0) {
            top = b.top + b.height - elb.height;
          } else if (pos.indexOf('bottom') >= 0) {
            top = b.top + b.height;
          } else { // Centered.
            top = b.top + (b.height - elb.height) / 2;
          }

          var constrain = (pos.indexOf('no-constraint') >= 0) ? false : true;

          left += offset.left || 0;
          top += offset.top || 0;

          if (constrain) {
            left = Math.max(scrollLeft, Math.min(left, scrollLeft + clientWidth - elb.width));
            top = Math.max(scrollTop, Math.min(top, scrollTop + clientHeight - elb.height));
          }

          // var offParent;
          // if (offParent = el.offsetParent()) {
          //   left -= offParent.offset().left;
          //   top -= offParent.offset().top;
          // }

          $(el).css({position : 'absolute', left : left + 'px', top : top + 'px'});
          return el;
        }

    });

    $.extend({

        // Color format: {r: 1, g: .5, b: 0}
        textColor: function(background_color) {
            var contrast = function (color1, color2) {
                var lum1 = luminosity(color1);
                var lum2 = luminosity(color2);
                if(lum1 > lum2)
                return (lum1 + 0.05) / (lum2 + 0.05);
                return (lum2 + 0.05) / (lum1 + 0.05);
            };

            var luminosity = function (color) {
                var r = color.r, g = color.g, b = color.b;
                var red = (r <= 0.03928) ? r/12.92 : Math.pow(((r + 0.055)/1.055), 2.4);
                var green = (g <= 0.03928) ? g/12.92 : Math.pow(((g + 0.055)/1.055), 2.4);
                var blue = (b <= 0.03928) ? b/12.92 : Math.pow(((b + 0.055)/1.055), 2.4);

                return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
            };

            if (contrast(background_color, {r: 1, g: 1, b: 1}) >
                contrast(background_color, {r: .5, g: .5, b: .5})) {
                return 'white';
            } else {
                return 'black';
            }
        },

        favicon: function(feed_favicon, empty_on_missing) {
            if (feed_favicon && feed_favicon.indexOf('data:image/png;base64,') != -1) return feed_favicon;
            else if (feed_favicon) return 'data:image/png;base64,' + feed_favicon;
            else if (empty_on_missing) return 'data:image/png;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
            return NEWSBLUR.Globals.MEDIA_URL + '/img/icons/silk/world.png';
        },

        deepCopy: function(obj) {
            var type = $.typeOf(obj);
            switch (type) {
                case 'object':
                    var o = {};
                    for (key in obj) {
                        o[key] = $.deepCopy(obj[key]);
                    };
                    return o;
                case 'array':
                    var a = [];
                    for (var i = 0; i < obj.length; i++) {
                        a.push($.deepCopy(obj[i]));
                    }
                    return a;
                default:
                    return obj;
            };
        },

        typeOf: function(value) {
            var s = typeof value;
            if (s == 'object') {
                if (value) {
                    if (typeof value.length == 'number' &&
                        !(value.propertyIsEnumerable('length')) &&
                        typeof value.splice == 'function') {
                            s = 'array';
                    }
                } else {
                    s = 'null';
                }
            }
            return s;
        },

        targetIs: function(e, opts, callback){
            if(!e || !opts){ return false; }
            // defaults
            // (want to make this explicit, since it's a little weird)
            opts = {
                childOf: opts.childOf || null,
                tagSelector: opts.tagSelector || null,
                cancelBubbling: opts.cancelBubbling || false
            };
            var target = e.target;
            var $t = $(target);
            var $p = null;
            var fails = false;
            if(opts.childOf){
                $p = $t.closest(opts.childOf);
                if(!$p.length){
                    fails = true;
                }
            }
            if(opts.tagSelector){
                var ts = opts.tagSelector;
                if(!$t.is(ts)){
                    if(opts.cancelBubbling){
                        fails = true;
                    }else{
                        $tp = $t.closest(ts);
                        if(!$tp.length){
                            fails = true;
                        }else{
                            // we are going to assume dev
                            // wants the $elem we bubbled to
                            $t = $tp;
                        }
                    }
                };
            }
            if(fails){
                return false;
            }else{
                if(callback && typeof callback == 'function'){
                    // NEWSBLUR.log(['Target', e, opts.tagSelector, opts]);
                    callback($t, $p);
                }
                return true;
            }
        },

        entity: function(str) {
            var e = document.createElement('div');

            e.innerHTML = String(str);

            return e.innerHTML;
        },

        make: function(){
            var $elem, text, children, type, name, props;
            var args = arguments;
            var tagname = args[0];

            // Second argument can be TextNode or Attributes
            // $.make('div', 'inner text') || $.make('div', { className: 'etc' })
            if (args[1]) {
                if (typeof args[1] == 'string' || typeof args[1] == 'number') {
                    text = args[1];
                } else if (typeof args[1] == 'object' && args[1].push) {
                    children = args[1];
                } else {
                    props = args[1];
                    if (props.className) {
                      props['class'] = props.className;
                      delete props.className;
                    }
                }
            }

            // Third argument can be TextNode or an array of additional $.make
            if (args[2]) {
                if (typeof args[2] == 'string' || typeof args[2] == 'number') {
                    text = args[2];
                } else if (typeof args[1] == 'object' && args[2].push) {
                    children = args[2];
                }
            }

            $elem = $(document.createElement(tagname));
            if (props) {
                for (var propname in props) {
                    if (props.hasOwnProperty(propname)) {
                        if ($elem.is(':input') && propname == 'value') {
                            $elem.val(props[propname]);
                        } else {
                            $elem.attr(propname, props[propname]);
                        }
                    }
                }
            }
            if (children) {
                for (var i = 0; i < children.length; i++) {
                    if (children[i]) {
                        $elem.append(children[i]);
                    }
                }
            }
            if (text) {
                $elem.html(text);
            }
            return $elem;
        },

        rescope: function(func, thisArg){
            return function(a, b, c, d, e, f){
                func.call(thisArg, this, a, b, c, d, e, f);
            };
        },

        closest: function(value, array) {
            var offset = 0;
            var index = 0;
            var closest = Math.abs(array[index] - value);
            for (var i in array) {
                var next_value = array[i] - value;
                if (next_value <= offset && Math.abs(next_value) < closest) {
                    index = parseInt(i, 10);
                    closest = Math.abs(array[index] - value);
                } else if (next_value > offset) {
                    // NEWSBLUR.log(['Not Closest', index, next_value, value, closest]);
                    return index;
                }
            }
            return index;
        },

        getQueryString: function (name) {
            function parseParams() {
                var params = {},
                    e,
                    a = /\+/g,  // Regex for replacing addition symbol with a space
                    r = /([^&=]+)=?([^&]*)/g,
                    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                    q = window.location.search.substring(1);

                while (e = r.exec(q))
                    params[d(e[1])] = d(e[2]);

                return params;
            }

            if (!this.queryStringParams)
                this.queryStringParams = parseParams();

            return this.queryStringParams[name];
        }

    });
})(jQuery);

// ------- IE Debug -------- //

(function($) {
    var _$ied;
    $.extend({
        iedebug: function(msg){
            if(!_$ied){
                _$ied = $.make('div', [
                    $.make('ol')
                ]).css({
                    'position': 'absolute',
                    'top': 10,
                    'left': 10,
                    'zIndex': 20000,
                    'border': '1px solid #000',
                    'padding': '10px',
                    'backgroundColor': '#fff',
                    'fontFamily': 'arial,helvetica,sans-serif',
                    'fontSize': '11px'
                });
                $('body').append(_$ied);
                _$ied.draggable();
            }
            _$ied.find('ol').append($.make('li', msg).css({
                'borderBottom': '1px solid #999999'
            }));
        }
    });
})(jQuery);<commit_msg>Fixing autolinking of text links to no longer indiscriminately replace text, causing double encoding of html entities.<commit_after>if (typeof NEWSBLUR == 'undefined') NEWSBLUR = {};
if (typeof NEWSBLUR.Globals == 'undefined') NEWSBLUR.Globals = {};

/* ============================= */
/* = Core NewsBlur Javascript = */
/* ============================= */

var URL_REGEX = /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi;

NEWSBLUR.log = function(msg) {
    try {
        if (typeof o == "object")
        {
            var new_m = [];
            for (var i=0; i < msg.length; i++) {
                if (i!=0) new_m.push(msg[i]);
            }
            console.debug(msg[0], new_m);
        }
        else
        {
            console.log(msg);
        }
    } catch(e) {
        console =
        {
            log: function() {}
        };
    }
};

(function($) {

    $.fn.extend({

        autolink: function() {
            return this.each(function(){
                var $desc = $(this);
                $desc.textNodes().each(function(){
                    var text = $(this);
                    if(text && text.parent() && text.parent()[0] && text.parent()[0].nodeName != 'A') {
                        if (this.data.indexOf('http') != -1) {
                            text.replaceWith(this.data.replace(URL_REGEX, function($0, $1) {
                                console.log(["Replacing text link", $0]);
                                return '' + $0 + '';
                            }));
                        }
                    }
                });
            });
        },

        textNodes: function() {
            var ret = [];

            (function(el){
                if (!el) return;
                if ((el.nodeType == 3)) {
                    ret.push(el);
                } else {
                    for (var i=0; i < el.childNodes.length; ++i) {
                        arguments.callee(el.childNodes[i]);
                    }
                }
            })(this[0]);
            return $(ret);
        },

        isScrollVisible: function($elem) {
            var docViewTop = 0; // $(this).scrollTop();
            var docViewBottom = docViewTop + $(this).height();
            var docOffset = $(this).offset().top;

            var elemTop = $elem.offset().top - docOffset;
            var elemBottom = elemTop + $elem.outerHeight();

            // NEWSBLUR.log(['isScrollVisible', docViewTop, docViewBottom, docOffset, elemTop, elemBottom]);

            return ((elemTop >= docViewTop) && (elemBottom <= docViewBottom));
        },

        // Align an element relative to a target element's coordinates. Forces the
        // element to be absolutely positioned. Element must be visible.
        // Position string format is: "top -right".
        // You can pass an optional offset object with top and left offsets specified.
        align : function(target, pos, offset) {
          var el = this;
          pos = pos || '';
          offset = offset || {};
          var scrollTop = document.documentElement.scrollTop || document.body.scrollTop || 0;
          var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft || 0;
          var clientWidth = document.documentElement.clientWidth;
          var clientHeight = document.documentElement.clientHeight;

          if (target == window) {
            var b = {
              left    : scrollLeft,
              top     : scrollTop,
              width   : $(window).width(),
              height  : $(window).height()
            };
          } else {
            target = $(target);
            var targOff = target.offset();
            var b = {
              left    : targOff.left,
              top     : targOff.top,
              width   : target.innerWidth(),
              height  : target.innerHeight()
            };
          }

          var elb = {
            width : el.innerWidth(),
            height : el.innerHeight()
          };

          var left, top;

          if (pos.indexOf('-left') >= 0) {
            left = b.left;
          } else if (pos.indexOf('left') >= 0) {
            left = b.left - elb.width;
          } else if (pos.indexOf('-right') >= 0) {
            left = b.left + b.width - elb.width;
          } else if (pos.indexOf('right') >= 0) {
            left = b.left + b.width;
          } else { // Centered.
            left = b.left + (b.width - elb.width) / 2;
          }

          if (pos.indexOf('-top') >= 0) {
            top = b.top;
          } else if (pos.indexOf('top') >= 0) {
            top = b.top - elb.height;
          } else if (pos.indexOf('-bottom') >= 0) {
            top = b.top + b.height - elb.height;
          } else if (pos.indexOf('bottom') >= 0) {
            top = b.top + b.height;
          } else { // Centered.
            top = b.top + (b.height - elb.height) / 2;
          }

          var constrain = (pos.indexOf('no-constraint') >= 0) ? false : true;

          left += offset.left || 0;
          top += offset.top || 0;

          if (constrain) {
            left = Math.max(scrollLeft, Math.min(left, scrollLeft + clientWidth - elb.width));
            top = Math.max(scrollTop, Math.min(top, scrollTop + clientHeight - elb.height));
          }

          // var offParent;
          // if (offParent = el.offsetParent()) {
          //   left -= offParent.offset().left;
          //   top -= offParent.offset().top;
          // }

          $(el).css({position : 'absolute', left : left + 'px', top : top + 'px'});
          return el;
        }

    });

    $.extend({

        // Color format: {r: 1, g: .5, b: 0}
        textColor: function(background_color) {
            var contrast = function (color1, color2) {
                var lum1 = luminosity(color1);
                var lum2 = luminosity(color2);
                if(lum1 > lum2)
                return (lum1 + 0.05) / (lum2 + 0.05);
                return (lum2 + 0.05) / (lum1 + 0.05);
            };

            var luminosity = function (color) {
                var r = color.r, g = color.g, b = color.b;
                var red = (r <= 0.03928) ? r/12.92 : Math.pow(((r + 0.055)/1.055), 2.4);
                var green = (g <= 0.03928) ? g/12.92 : Math.pow(((g + 0.055)/1.055), 2.4);
                var blue = (b <= 0.03928) ? b/12.92 : Math.pow(((b + 0.055)/1.055), 2.4);

                return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
            };

            if (contrast(background_color, {r: 1, g: 1, b: 1}) >
                contrast(background_color, {r: .5, g: .5, b: .5})) {
                return 'white';
            } else {
                return 'black';
            }
        },

        favicon: function(feed_favicon, empty_on_missing) {
            if (feed_favicon && feed_favicon.indexOf('data:image/png;base64,') != -1) return feed_favicon;
            else if (feed_favicon) return 'data:image/png;base64,' + feed_favicon;
            else if (empty_on_missing) return 'data:image/png;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
            return NEWSBLUR.Globals.MEDIA_URL + '/img/icons/silk/world.png';
        },

        deepCopy: function(obj) {
            var type = $.typeOf(obj);
            switch (type) {
                case 'object':
                    var o = {};
                    for (key in obj) {
                        o[key] = $.deepCopy(obj[key]);
                    };
                    return o;
                case 'array':
                    var a = [];
                    for (var i = 0; i < obj.length; i++) {
                        a.push($.deepCopy(obj[i]));
                    }
                    return a;
                default:
                    return obj;
            };
        },

        typeOf: function(value) {
            var s = typeof value;
            if (s == 'object') {
                if (value) {
                    if (typeof value.length == 'number' &&
                        !(value.propertyIsEnumerable('length')) &&
                        typeof value.splice == 'function') {
                            s = 'array';
                    }
                } else {
                    s = 'null';
                }
            }
            return s;
        },

        targetIs: function(e, opts, callback){
            if(!e || !opts){ return false; }
            // defaults
            // (want to make this explicit, since it's a little weird)
            opts = {
                childOf: opts.childOf || null,
                tagSelector: opts.tagSelector || null,
                cancelBubbling: opts.cancelBubbling || false
            };
            var target = e.target;
            var $t = $(target);
            var $p = null;
            var fails = false;
            if(opts.childOf){
                $p = $t.closest(opts.childOf);
                if(!$p.length){
                    fails = true;
                }
            }
            if(opts.tagSelector){
                var ts = opts.tagSelector;
                if(!$t.is(ts)){
                    if(opts.cancelBubbling){
                        fails = true;
                    }else{
                        $tp = $t.closest(ts);
                        if(!$tp.length){
                            fails = true;
                        }else{
                            // we are going to assume dev
                            // wants the $elem we bubbled to
                            $t = $tp;
                        }
                    }
                };
            }
            if(fails){
                return false;
            }else{
                if(callback && typeof callback == 'function'){
                    // NEWSBLUR.log(['Target', e, opts.tagSelector, opts]);
                    callback($t, $p);
                }
                return true;
            }
        },

        entity: function(str) {
            var e = document.createElement('div');

            e.innerHTML = String(str);

            return e.innerHTML;
        },

        make: function(){
            var $elem, text, children, type, name, props;
            var args = arguments;
            var tagname = args[0];

            // Second argument can be TextNode or Attributes
            // $.make('div', 'inner text') || $.make('div', { className: 'etc' })
            if (args[1]) {
                if (typeof args[1] == 'string' || typeof args[1] == 'number') {
                    text = args[1];
                } else if (typeof args[1] == 'object' && args[1].push) {
                    children = args[1];
                } else {
                    props = args[1];
                    if (props.className) {
                      props['class'] = props.className;
                      delete props.className;
                    }
                }
            }

            // Third argument can be TextNode or an array of additional $.make
            if (args[2]) {
                if (typeof args[2] == 'string' || typeof args[2] == 'number') {
                    text = args[2];
                } else if (typeof args[1] == 'object' && args[2].push) {
                    children = args[2];
                }
            }

            $elem = $(document.createElement(tagname));
            if (props) {
                for (var propname in props) {
                    if (props.hasOwnProperty(propname)) {
                        if ($elem.is(':input') && propname == 'value') {
                            $elem.val(props[propname]);
                        } else {
                            $elem.attr(propname, props[propname]);
                        }
                    }
                }
            }
            if (children) {
                for (var i = 0; i < children.length; i++) {
                    if (children[i]) {
                        $elem.append(children[i]);
                    }
                }
            }
            if (text) {
                $elem.html(text);
            }
            return $elem;
        },

        rescope: function(func, thisArg){
            return function(a, b, c, d, e, f){
                func.call(thisArg, this, a, b, c, d, e, f);
            };
        },

        closest: function(value, array) {
            var offset = 0;
            var index = 0;
            var closest = Math.abs(array[index] - value);
            for (var i in array) {
                var next_value = array[i] - value;
                if (next_value <= offset && Math.abs(next_value) < closest) {
                    index = parseInt(i, 10);
                    closest = Math.abs(array[index] - value);
                } else if (next_value > offset) {
                    // NEWSBLUR.log(['Not Closest', index, next_value, value, closest]);
                    return index;
                }
            }
            return index;
        },

        getQueryString: function (name) {
            function parseParams() {
                var params = {},
                    e,
                    a = /\+/g,  // Regex for replacing addition symbol with a space
                    r = /([^&=]+)=?([^&]*)/g,
                    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                    q = window.location.search.substring(1);

                while (e = r.exec(q))
                    params[d(e[1])] = d(e[2]);

                return params;
            }

            if (!this.queryStringParams)
                this.queryStringParams = parseParams();

            return this.queryStringParams[name];
        }

    });
})(jQuery);

// ------- IE Debug -------- //

(function($) {
    var _$ied;
    $.extend({
        iedebug: function(msg){
            if(!_$ied){
                _$ied = $.make('div', [
                    $.make('ol')
                ]).css({
                    'position': 'absolute',
                    'top': 10,
                    'left': 10,
                    'zIndex': 20000,
                    'border': '1px solid #000',
                    'padding': '10px',
                    'backgroundColor': '#fff',
                    'fontFamily': 'arial,helvetica,sans-serif',
                    'fontSize': '11px'
                });
                $('body').append(_$ied);
                _$ied.draggable();
            }
            _$ied.find('ol').append($.make('li', msg).css({
                'borderBottom': '1px solid #999999'
            }));
        }
    });
})(jQuery);<|endoftext|>