/* Created by Valerio Capogna 2011 www.basili.co
 * Open source plugin.
 *
 * Name: jQuery Resizer
 * Version: 0.1 Alpha
 * Requires: jQuery v1.5.1+ (http://jquery.com),
 */

(function($){

  $.fn.resizer = function(params){
    var params = $.extend({

      width: 800,
      height: 600,
      widthOffset: 0,
      heightOffset: 0,
      inflate: false,
      windowSensitive: false,
      relAttributes:false,
      callback: null

    }, params);

    var image = $(this);

    if (params.relAttributes){

      var attributes = image.attr('rel').split(';');

      for (var i = 0; i < attributes.length; i++){
        var pair = attributes[i].split(':');
        params[pair[0]] = pair[1];
      }
    }

    if (params.windowSensitive){
            
      params.width = $(window).width();
      params.height = $(window).height();
            
      $(window).resize(function(){
        params.width = $(window).width();
        params.height = $(window).height();
        resizeImages();
      })
    }

    image.one('load', function() {
      image.data('originalWidth', $(this).attr('width'));
      image.data('originalHeight', $(this).attr('height'));
      resizeImages();
    }).each(function() {
      if(this.complete){
        $(this).load().attr('src', image.attr('src'));
      }
    }).attr('src', image.attr('src'));

    function resizeImages(){

      var originalWidth = parseInt(image.data('originalWidth'));
      var originalHeight = parseInt(image.data('originalHeight'));
      var width = params.width - params.widthOffset;
      var height = params.height - params.heightOffset;

      if (params.inflate){
        if (width > originalWidth && height > originalHeight){

          image.css({
            'height': originalHeight + 'px',
            'width': originalWidth + 'px'
          });

          if (params.callback != null && typeof(params.callback) === 'function'){
            params.callback.call(image);
          }

          return;
        }
      }

      var ratio = originalWidth / originalHeight;

      if (width / height > ratio){
        width = height * ratio;
      }else{
        height = width / ratio;
      }

      image.css({
        'height': height + 'px',
        'width': width + 'px'
      });

      if (params.callback != null && typeof(params.callback) === 'function'){
        params.callback.call({
          image:image
        });
      }
    }
  }
})(jQuery);

