var IcPowerImage = Class.create();
		
IcPowerImage.prototype = {
	initialize: function(originalImage, destinationImage, cropWidth, cropHeight, rotation, initiatingDomImage, instanceName, cms, extraTransforms) {
	  this.cropImageId = instanceName+"_cropImage";
	  this.cropSetupAlreadyCalled = false;
		var templateHandle = CROP_TEMPLATE.evaluate( { originalImage:   originalImage, 
		                                               cropImageId:     this.cropImageId });
		this._initiatingDomImage = initiatingDomImage;
    this.cms = cms;  
		this.originalImage = originalImage;
		this.destinationImage = destinationImage;
		this.cropWidth = cropWidth;
		this.cropHeight = cropHeight;
		this.rotation   = rotation;
		this.instanceName = instanceName;
		this.extraTransforms = extraTransforms;
		this._powerImageMadeItToScale=false;
		this.window = new UI.Window({width:500, theme:prototypeUiTheme});
		this.window.setContent(templateHandle);
		this.window_onShow = this._onShow.bind(this);
		this.window_onClose = this._onClose.bind(this);
		this.window.observe("showing", this.window_onShow);
		this.window.observe("hiding", this.window_onClose);
    this.window.show().focus();
	},				 
  
	_onClose: function(eventName, win) {
	  this.operation.callback = this._cropOperation.bind(this);
	  this.image.process(this.operation);
	  Event.stopObserving(this.window, "hiding", this.window_onClose);
	},
	
	_cropOperation: function(loadSuccess) {
		if (!loadSuccess) {
      alert("crop image load failed!");
		} else {
      var imageId = document.getElementById(this._initiatingDomImage).parentNode.id;
      
	    var imageDomElement = $(this._initiatingDomImage);
	    var newSrc = this.operation.destinationUrl + "?" + Math.round(100000*Math.random());
      var imageContainer = imageDomElement.parentNode;
      
      $(imageContainer).addClassName("currentlyCroppingImage");
       
      var updateImageCall = "var powerImageImageDomElement = $('"+this._initiatingDomImage+"');";
      // This is a hack for ie 6 png transparency
	    if (imageDomElement.tagName === "VAR") { 
	      updateImageCall += "powerImageImageDomElement.style.filter = \"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+newSrc+"', sizingMethod='scale');\";";
	    } else {
	      updateImageCall += "powerImageImageDomElement.src = '"+newSrc+"';";
	    }
	    updateImageCall += "powerImageImageDomElement.style.width="+this.cropWidth+";\npowerImageImageDomElement.style.height="+this.cropHeight+";";
	    
	    // Update, then Clean up the cropper object
	    setTimeout(updateImageCall+"$('"+imageId+"').removeClassName(\"currentlyCroppingImage\");", 3000);
		}
		
		
	},
	
	_onShow: function() {
	  if (!this.cropSetupAlreadyCalled) {
		  Event.stopObserving(this.window, "showing", this.window_onShow);
		  var domImage = $(this.cropImageId);
		  var continueCropSetupFunctionCall = "if (!(typeof "+this.instanceName+" == 'undefined')) "+this.instanceName+"._onShow()";
	    if (!this.cropSetupAlreadyCalled && !domImage) setTimeout(continueCropSetupFunctionCall, 50);
	    else {
	      var imageWidth = domImage.getWidth();
	      if (!this.cropSetupAlreadyCalled && (!imageWidth || imageWidth == 0)) setTimeout(continueCropSetupFunctionCall, 50);
	      else if (!this.cropSetupAlreadyCalled) {
	        this.cropSetupAlreadyCalled = true;
	        this._continueCropSetup();
	      }
	    }
	  }
	},		
	
	_continueCropSetup: function() {
    var domImage = $(this.cropImageId);
    var imageWidth = domImage.getWidth();    
		var imageHeight = domImage.getHeight();
		this.image = new IcImage(this.originalImage, imageWidth, imageHeight, domImage);
		this.operation = new IcImageOperation(this.destinationImage, 0, 0, this.cropWidth, this.cropHeight, this.rotation, this.extraTransforms);
		ImageUtil.getScaleForCrop(this.image.dimension, this.operation.dimension,	this._scaleCallback.bind(this));
  },
			
			
	_scaleCallback: function (scaleMultiplier) {
		var image = this.image;
		var domImage = image.domReference;
		var scaledWidth = image.dimension.width * scaleMultiplier;
		if (scaledWidth < this.operation.dimension.width) scaledWidth++;
		domImage.width = scaledWidth;
		this.window.setSize(this.window.getSize().width, $$(".cropImageContainer")[0].getHeight(), true);
		this.window.center();
		domImage.addClassName("showImage");
		this._setupCropper();
	},
			
			
	/** Initialize the cropper window and setup the update function for updating the crop operation */
	_setupCropper: function() {
		var cropDim = this.operation.dimension;
		// We removed one pixel from these dimensions to accomadate for floating point rounding on the scale.
    var width = cropDim.width-1;
    var height = cropDim.height-1;
		this.cropper = new Cropper.Img(this.image.domReference.id, 
										{ minWidth: width, 
										  minHeight: height, 
											ratioDim: { x: width, y: height }, 
											displayOnInit: true,
											onEndCrop: this._setupCropper_onEndCrop.bind(this) 
										}
									 );
  },
  
  _setupCropper_onEndCrop: 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.operation.x = x;
    this.operation.y = y;
    /*
      callingForm.x2.value = coords.x2;
      callingForm.y2.value = coords.y2;
      callingForm.width.value = dimensions.width;
      callingForm.height.value = dimensions.height;
    */
  }
			
} 

/** Handle event bubbling from the power image edit button. */
function stopEventBubblingFromPowerImage() {
	var powerImageEditButtons = $$("div.powerImageEditButton");
	powerImageEditButtons.each( function (element, index) {
																Event.observe(element, "click", function(event) { Event.stop(event); } );	
															}
														);
}

