/***************************************

   @author Natalie Downe
   @enhanced by Karl Swedberg
   @requires jQuery v1.2.6+

   @options
   these are the defaults. you can change them to whatever you want.

   extensions:   'doc,xls,exe,zip,pdf,swf',
   insertionType: 'append'


************************************* */


(function($) {
$.fn.addSizes = function(options) {
  var opts = $.extend({}, $.fn.addSizes.defaults, options);

  return this.each(function(event) {
    var ext = opts.extensions.split(/\s?,\s?/).join('|'),
        extPattern = new RegExp('\.(' + ext + ')$');

    var $container = $(this);

    // link hints...
      var aNum = 0;
      $container.find('a').each(function() {
        var $a = $(this),
            aPath = this.pathname,
            aExt = aPath.slice(aPath.lastIndexOf('.')),
            aType = aExt.slice(1),
            alt = aType.toUpperCase();

        if ( (opts.excludeContainer && $a.parents(opts.excludeContainer).length) || (opts.exclude && $a.is(opts.exclude)) ) { return false; }

        if ( extPattern.test(aExt)) {

          var url= "http://json-head.appspot.com/?url="+encodeURI(this.href)+"&callback=?";
          $.getJSON(url, function(json){
            if (json.ok && json.headers['content-length'] && json.headers['content-length'] > 20) {
              var length = +json.headers['content-length'],
                  lengthUnits = '';

              // divide the length into its largest unit
              var units = [
                [1024 * 1024 * 1024, 'GB'],
                [1024 * 1024, 'MB'],
                [1024, 'KB'],
                [1, 'bytes']
              ];

              for(var i = 0; i < units.length; i++){

                var unitSize = units[i][0];
                var unitText = units[i][1];

                if (length >= unitSize) {
                  length = length / unitSize;
                  // 1 decimal place
                  length = Math.ceil(length * 10) / 10;
                  var lengthUnits = unitText;
                  break;
                }
              }
              var content = {
                length: length + lengthUnits,
                alt: alt
              };
              var output = opts.contentBefore;
              for (var i = 0; i < opts.content.length; i++) {
                output += content[opts.content[i]];
              }
              output += opts.contentAfter;
              if (output) {
                $(document).ready(function() {
                  $a[opts.insertionType](output);
                });
              }
            }
          });
        }
      });
  });
};

$.fn.addSizes.defaults = {
  extensions: 'doc,xls,exe,zip,pdf,ppt,swf,skp,dwg,mp4,m4v,avi',
  exclude: null,
  excludeContainer: null,
  insertionType: 'append', // can be 'before' or 'after' or 'prepend' or 'append'
	contentBefore: ' (',
	contentAfter: ')',
	content: ['length', 'alt']
};

})(jQuery);

