﻿(function( $ ){
  $.fn.fitImage = function(widthX,heightY) {
    return this.each(function() {
          
        var $this = $(this);
        if (!heightY || heightY == 0) heightY=$this.parent().height(); 
       if (!widthX || widthX == 0) widthX=$this.parent().width();
        if ( heightY == -1) heightY=$(window).height(); 
       if ( widthX == -1) widthX=$(window).width();     
        var imgRatio = widthX/heightY;
    var imgwX = $this.width();
    var imghY = $this.height();
    var strX = widthX+"px";
    var strY = heightY+"px";
    $this.css({"position": "absolute", "left":"50%", "top":"50%", "z-index":555});
    if((imghY*imgRatio)<= imgwX){
     $this.css({
      "height": strY, "width":"auto", "marginTop": (-1*heightY/2)+"px"
     });
     var tx = $this.width();  
     var tx2 = tx/2;
     var xoff = (tx-widthX)/2;
     var strxoff = "-"+tx2+"px"; 
     //var clipping = "rect(0px "+(widthX+xoff)+"px "+strY+" "+xoff+"px)";
     $this.css({
      "marginLeft": strxoff,
      
     });
    }else{
     $this.css({
      "width": strX, "height":"auto", "marginLeft": (-1*widthX/2)+"px"  
     });
     var ty = $this.height(); 
     var ty2 = ty/2;
     var yoff = (ty-heightY)/2;
     var stryoff = "-"+ty2+"px";
     //var clipping = "rect("+yoff+"px "+strX+" "+(heightY+yoff)+"px 0px)";
     $this.css({
      "marginTop": stryoff,
      
     });    
    };
    var $myP = $this.parent();
    var pboX = $myP.width()+"px";
    var pboY = $myP.height()+"px";
    $this.addClass("fitted").wrap("<div class='PN_imgFix' style='width:"+pboX+";height:"+pboY+";display: inline-block'><div class='PN_imgAbs' style='width:"+pboX+";height:"+pboY+";position:absolute;overflow:hidden'></div></div>");
    });
  };
})( jQuery );

