var IcPowerImage = Class.create();
    
IcPowerImage.prototype = {
  initialize: function(params) {
    this.params = { domId: params.domId,
                    image: params.image,
                    choiceKeyName: params.choiceKeyName,
                    originalImage: params.originalImage,
                    destinationImage: params.destinationImage,
                    cropWidth: params.cropWidth,
                    cropHeight: params.cropHeight,
                    rotation:  params.rotation,
                    extraTransforms: params.extraTransforms,
                    cropX: 0,
                    cropY: 0,
                    transitive: params.transitive }
    if(this.params.transitive == "") this.params.transitive = false;
    this.params.image = $(this.params.image);
    this.params.destinationImage = this._getFileName();
    this.ratio = 1;
    this.scaleModifier = 1;
    if(this.params.extraTransforms != ""){ 
    	this.extraTransforms = eval("([" + this.params.extraTransforms + "])");
    }else{
    	this.extraTransforms = null;
    }
    this.imageHeight = $(this.params.image).getHeight();
    this.imageWidth = $(this.params.image).getWidth();
    this._scaleCallback(this._getScaleForCrop());
},         
  
  crop: function(eventName, win) {
    ImageService.cropImage(this.params.originalImage, {"width":this.imageWidth,"height":this.imageHeight}, this.cropX, this.cropY, this.ratio, {"width":this.cropWidth,"height":this.cropHeight},this.params.rotation, this.params.destinationImage,this.extraTransforms, this._cropOperation.bind(this));  //afterCropReload);  
  },
  
  _getFileName: function(){
    var dotposition = this.params.originalImage.lastIndexOf(".");
    var filebuffer = this.params.originalImage.substring(0,dotposition);
    if (this.params.originalImage != this.params.destinationImage) {
	    filebuffer = this.params.destinationImage;
    	filebuffer = filebuffer + this.params.originalImage.substring(this.params.originalImage.lastIndexOf("/")+1,dotposition);
   	} 
    filebuffer = filebuffer +"_-pi-_"+this.params.cropWidth+"x"+this.params.cropHeight
    if(this.params.rotation > 0){
      filebuffer = filebuffer + "-" + this.params.rotation;
    }
    filebuffer = filebuffer + ".png";
    return filebuffer;
  },
  
  _getScaleForCrop: function(){
    var scaleAmount = 1;
    var fillWidth = this.params.cropWidth;
    var fillHeight = this.params.cropHeight;
    var widthDiff = this.imageWidth - fillWidth;
    var heightDiff = this.imageHeight - fillHeight;
    var scale = "";
    
    if(widthDiff > 0 && heightDiff){
      scale = "down";
    }else if(widthDiff < 0 || heightDiff){
      scale = "up";
    }
    var widthDiffRatio = widthDiff / fillWidth;
    var heightDiffRatio = heightDiff / fillHeight;
    
    if (scale != "" ) {
      if (widthDiffRatio < heightDiffRatio) {
        scaleAmount = fillWidth / this.imageWidth;
      } else {
        scaleAmount = fillHeight / this.imageHeight;
      }
    } 
    this.scaleAmount = scaleAmount;
    return scaleAmount;
  },
  
  _cropOperation: function(loadSuccess) {
    if (!loadSuccess) {
      alert("crop image load failed!");
    }
    if(loadSuccess){
      //If we are successful, we save the new value's to CMS.
      saveUserChunk(this.params.choiceKeyName, this.params.originalImage, this.params.transitive, this.params.choiceKeyName, null, "");
      var imageDomElement = window.parent.$(this.params.domId);
      var newSrc = this.params.destinationImage + "?" + Math.round(100000*Math.random());
      $(imageDomElement).addClassName("currentlyCroppingImage");
      // This is a hack for ie 6 png transparency
      if (imageDomElement.tagName === "VAR") {
        imageDomElement.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+newSrc+"', sizingMethod='scale');";
      } else {
        imageDomElement.src = newSrc;
      }
      imageDomElement.style.width=this.params.cropWidth;
      imageDomElement.style.height=this.params.cropHeight;
      $(imageDomElement).removeClassName("currentlyCroppingImage");
      
      //Close Prototype Window
      /*var ccmName = getCmsChoiceObjectName(this.params.choiceKeyName);
      eval(" ccm = window.parent."+ccmName);
      ccm.prototypeWindow.close();*/
    }
  },
   
  _scaleCallback: function (scaleMultiplier) {
	var parentConstraint = $(this.params.image.parentNode).getWidth()-20;
	var scaledWidth = 10000;
	var scaledHeight = 10000;
	
	while(scaledWidth > parentConstraint || scaledHeight > parentConstraint){
		this.scaleModifier += 0.1;
		var scaledWidth = (this.imageWidth * scaleMultiplier)/this.scaleModifier;
	    var scaledHeight = (this.imageHeight * scaleMultiplier)/this.scaleModifier;
	}

    if (scaledWidth < this.params.cropWidth) scaledWidth++;
    $(this.params.image).width = scaledWidth;
    $(this.params.image).height = scaledHeight;
    var obj = this;
    setTimeout(function(){obj._createCropper();},10);
  },
  
  _createCropper: function(){
    /** Initialize the cropper window and setup the update function for updating the crop operation */
    this.cropper = new Cropper.Img(document.getElementById(this.params.image.id), 
        { ratioDim: { x: this.params.cropWidth-1, y: this.params.cropHeight-1 },
    	  onloadCoords: { x1: 1, y1: $(this.params.image).height, x2: Math.round(this.params.cropWidth/1.6), y2: Math.round(this.params.cropHeight/1.6) },
    	  width: 100,
    	  height: 200,
          minHeight: 50,
          minWidth: 50,
          displayOnInit: true,
          onEndCrop: this._getCrop.bind(this) 
        }
       );
  },
  
  _getCrop: function(coords, dimensions) {
    var x = coords.x1;
    var y = coords.y1;
    //account for rounding negative
    if (x < 0) x = 0;
    if (y < 0) y = 0;
    this.cropX = Math.round( x / (this.scaleAmount/this.scaleModifier) );
    this.cropY = Math.round( y / (this.scaleAmount/this.scaleModifier) );;
    this.cropWidth = Math.round(dimensions.width / (this.scaleAmount/this.scaleModifier));
    this.cropHeight = Math.round(dimensions.height / (this.scaleAmount/this.scaleModifier));
    this.ratio = this.params.cropWidth / this.cropWidth;
  }
      
} 