// MaxImage, a wonderful plugin that produced these functions.
//
// Full plugin page: http://www.aaronvanderzwan.com/maximage/
//
// Copyright ©2009 Aaron Vanderzwan, by Aaron Vanderzwan
//
// Stripped down and simplified by Tyler Smith


function _maxify(image){
	_size_image(image);
	_center_image(image);
}


function _get_orig_data(image){
  $this = $(image);
 	
  $this.attr('origWidth', $this.width());
  $this.attr('origHeight', $this.height());
  $this.attr('ratio', find_ratio($this.width(),$this.height()));
}

function _size_image(image){
   $this = image;
   
   var originalWidth = to_i($this.attr('origWidth'));
   var originalHeight = to_i($this.attr('origHeight'));
   var ratio = $this.attr('ratio');
	
 	if(originalWidth == 0 || originalHeight == 0){
 		setTimeout(function(){
				_get_orig_data(image);
				_size_image(image);
			}, 100);
 		return;
 	}
   
   var width_and_height = [];
   width_and_height = find_width_and_height(originalWidth,originalHeight,ratio);
   
   $this.width( width_and_height[0] );
   $this.height( width_and_height[1] );
}

function _center_image(image){
	$this = image;
	
	var newWidth = -1 * ($this.width() - $(window).width())/2;
    var newHeight = -1 * ($this.height() - $(window).height())/2;
	
	$(image).css({'left':newWidth});
    $(image).css({'top':newHeight});
}

function find_width_and_height(originalWidth,originalHeight,ratio) {
	var pageWidth = $(window).width();
	var pageHeight = $(window).height();
   
	width = pageWidth + 40;
	height = width/ratio;
	
	if( height < pageHeight ){
  		height = pageHeight;
  		width = height * ratio;
	}

	if (width > originalWidth){
    	arrayImageSize = new Array(originalWidth,originalHeight);
	} else {
		arrayImageSize = new Array(width,height);
	}
	
  return arrayImageSize;
}


function find_ratio(width,height) {
  width = to_i(width);
  height = to_i(height);
  var ratio = width/height;
  ratio = ratio.toFixed(2);
  return ratio;
}

function to_i(i){
  last = parseInt(i);
  return last;
}
