var imageSwitchTargetImage      = false;		//The image we are switching at the moment
var imageSwitchTargetMethod     = false;    	//The method we are using to switch the image (scale/crop)
var imageSwitchSourceImage      = new Object;   //Information about the source image, not a real dom node
var imageSwitchEditImage        = false;    	//The  image we are using to show the editing process
var imageSwitchCurrentScale     = 0;			//The scale of the image we are editng at the moment 0 - 100
var imageSwitchCurrentMoveDirection = false;    //If a user clicked a button, which way to move the image
var imageSwitchCurrentMovePixels = 1;			//How many pixels we move the image when the user holds don a direction button
var imageSwitchCancelCustomFunction = null;     //Add a custom function when the cancel button is pressed
var imageSwitchAfterCropCustomFunction = null;  //Add a custom function when after the image is cropped

//Steps 

/* Preview the image about to be switched */
function mediaManagerStep_imageSwitchPreview()
{
	dojo.byId('imageSwitchPreviewScreen').style.visibility = 'visible';
	dojo.byId('imageSwitchPreviewImageHolder').innerHTML = '<img src="' + imageSwitchTargetImage.editSrc + '?refresh=' + Math.random() + '" " style="height:' + imageSwitchTargetImage.editHeight + 'px;width=' + imageSwitchTargetImage.editWidth + '" />';
}


/* Crop an image */
function mediaManagerStep_imageCrop()
{
	dojo.byId('imageCropScreen').style.visibility		   = 'visible';
}

//Methods

/* Image Switch Set Up */
function imageSwitch(imageObj, imageSwitchMethod)
{
	imageSwitchTargetMethod    = imageSwitchMethod;
	imageSwitchTargetImage     = imageObj;

	if(imageSwitchTargetImage.src.indexOf('_thumb') != -1)
	{
		imageSwitchTargetImage.editWidth  = parseInt(imageSwitchTargetImage.getAttribute('parentWidth'));
		imageSwitchTargetImage.editHeight = parseInt(imageSwitchTargetImage.getAttribute('parentHeight'));
		imageSwitchTargetImage.editSrc    = imageSwitchTargetImage.getAttribute('parentSrc');
	}
	else
	{
		imageSwitchTargetImage.editWidth  = parseInt(imageSwitchTargetImage.width);
		imageSwitchTargetImage.editHeight = parseInt(imageSwitchTargetImage.height);
		imageSwitchTargetImage.editSrc    = imageSwitchTargetImage.src;
	}
	
	disableBody();
	showMediaManager();	
	mediaManagerStep('imageSwitchPreview');
	
	dojo.event.connect(mediaManagerBox, "minimizeWindow", function(){
		imageSwitchCancel();
	});
	
	dojo.widget.byId('imageSwitchSlider').setValue(0);
	
	var mouseHandler = new dojo.dnd.HtmlDragMoveSource(dojo.byId("imageCropImageMouseHandler"));

	var controls = new dojo.dnd.HtmlDragMoveSource(dojo.byId("imageCropControlBox"));
	//controls.setDragHandle(dojo.byId('imageSwitchContolBoxHeader'));

	dojo.event.connect(mouseHandler, 'onDragStart', function(e){
		var imageMouseHandler 		  		= dojo.byId('imageCropImageMouseHandler');
		imageMouseHandler.className  		= 'showImageCropImageMouseHandler';
		dojo.byId('imageCropBlockTop').className    = "imageSwitchBlockImageMoving";
		dojo.byId('imageCropBlockLeft').className   = "imageSwitchBlockImageMoving";
		dojo.byId('imageCropBlockRight').className  = "imageSwitchBlockImageMoving";
		dojo.byId('imageCropBlockBottom').className = "imageSwitchBlockImageMoving";
	});
	
	dojo.event.connect(mouseHandler, 'onDragEnd', function(e){
		var imageMouseHandler 		  				= dojo.byId('imageCropImageMouseHandler');
		imageMouseHandler.className  				= 'hideImageCropImageMouseHandler';
		
		imageSwitchSetImageToMouseHandler();
		imageSwitchKeepInBox();
		
		dojo.byId('imageCropBlockTop').className    = "imageSwitchBlockImageStatic";
		dojo.byId('imageCropBlockLeft').className   = "imageSwitchBlockImageStatic";
		dojo.byId('imageCropBlockRight').className  = "imageSwitchBlockImageStatic";
		dojo.byId('imageCropBlockBottom').className = "imageSwitchBlockImageStatic";
	});
	
	mediaManagerOnLoadFiles = function(previews)
	{
		//Filter out all of the previews that are too small
		for (var i = 0; i < previews.length; i ++)
		{
			preview = previews[i];
			imageSwitchCheckPreview(preview);
		}
	}
	
	mediaManagerOnAddPreview = function(preview)
	{
		imageSwitchCheckPreview(preview);
	}
	
	mediaManagerOnSelectPreview = function(preview)
	{
		var itemType = preview.getAttribute('itemType');
		
		if (itemType == 'image')
		{
			mediaManagerAddOption('Select Image', condorBaseHREF + '/modules/mediaManager/images/button.goNext.jpg', 'imageSwitchBeginCrop()');
		}
	}
	
	if(mediaManagerSelectedPreview)
	{
		mediaManagerSelectPreview(mediaManagerSelectedPreview);
	}
}	

function imageSwitchSetImageToMouseHandler()
{
	var imageMouseHandler 		  			= dojo.byId('imageCropImageMouseHandler');

	imageSwitchEditImage.style.left  		= imageMouseHandler.offsetLeft 	+ 'px';
	imageSwitchEditImage.style.top   		= imageMouseHandler.offsetTop  	+ 'px';
}


function imageSwitchBeginCrop()
{
	//Go to the crop screen
	mediaManagerStep('imageCrop');
	
	//Set the current preview as our source image
	imageSwitchSourceImage.src    = mediaManagerSelectedPreview.getAttribute('imageSrc');
	imageSwitchSourceImage.height = mediaManagerSelectedPreview.getAttribute('imageHeight');
	imageSwitchSourceImage.width  = mediaManagerSelectedPreview.getAttribute('imageWidth');
	
	/* Add the image */
	var height = imageSwitchTargetImage.editHeight;
	var width  = imageSwitchTargetImage.editWidth;
	
	var src    = imageSwitchSourceImage.src;
	
	dojo.byId('imageCropImageHolder').innerHTML = '<img id="imageSwitchEditImage" src="' + src + '" />';
	
	imageSwitchEditImage = dojo.byId('imageSwitchEditImage');
	
	imageSwitchDrawCropBox();
	imageSwitchScaleImage(0);
   
	/* Center the image */
	var cropBox 				  = dojo.byId('imageCropBox');
	imageSwitchEditImage.style.top  = imageSwitchEditImage.offsetTop  + ((cropBox.offsetTop - imageSwitchEditImage.offsetTop) / 2) + 'px';
	imageSwitchEditImage.style.left = imageSwitchEditImage.offsetLeft + ((cropBox.offsetLeft - imageSwitchEditImage.offsetLeft) / 2) + 'px';
	imageSwitchSetMouseHandler();

}


/* scale is 0 to 100, 0 being the smallest possible image size, 100 being the full size of the source image */
function imageSwitchScaleImage(scale)
{
	if(imageSwitchEditImage == false)
	{
		return;
	}
	
	imageSwitchCurrentScale = scale;
	
	//Note the prvious height and width of the image we are editing
	var origHeight       = imageSwitchEditImage.height;
	var origWidth        = imageSwitchEditImage.width;
	
	var widthRatio       = imageSwitchSourceImage.width  / imageSwitchTargetImage.editWidth;
	var heightRatio      = imageSwitchSourceImage.height / imageSwitchTargetImage.editHeight;
	
	var minRatio         = (widthRatio < heightRatio) ? widthRatio : heightRatio;
	
	imageSwitchEditImage.style.width  = Math.round(imageSwitchSourceImage.width  - ((imageSwitchSourceImage.width - (imageSwitchSourceImage.width   / minRatio))  * (100 - scale) / 100)) + 'px';   
	imageSwitchEditImage.style.height = Math.round(imageSwitchSourceImage.height - ((imageSwitchSourceImage.height - (imageSwitchSourceImage.height  / minRatio))  * (100 - scale) / 100)) + 'px'; 
	imageSwitchEditImage.width  	  = Math.round(imageSwitchSourceImage.width  - ((imageSwitchSourceImage.width - (imageSwitchSourceImage.width   / minRatio))  * (100 - scale) / 100));   
	imageSwitchEditImage.height       = Math.round(imageSwitchSourceImage.height - ((imageSwitchSourceImage.height - (imageSwitchSourceImage.height  / minRatio))  * (100 - scale) / 100)); 
	imageSwitchEditImage.style.top    = imageSwitchEditImage.offsetTop   + (origHeight - imageSwitchEditImage.height) / 2 + 'px';
	imageSwitchEditImage.style.left   = imageSwitchEditImage.offsetLeft  + (origWidth  - imageSwitchEditImage.width)  / 2 + 'px';
	
	imageSwitchKeepInBox();
}	

function imageSwitchSetMouseHandler()
{
	/* Position the mouse handler */
	var imageMouseHandler 		  	= dojo.byId('imageCropImageMouseHandler');
	imageMouseHandler.style.left  	= imageSwitchEditImage.offsetLeft 	+ 'px';
	imageMouseHandler.style.top   	= imageSwitchEditImage.offsetTop  	+ 'px';
	imageMouseHandler.style.width 	= imageSwitchEditImage.offsetWidth  + 'px';
	imageMouseHandler.style.height  = imageSwitchEditImage.offsetHeight + 'px';
}

/* Move the edit image */

function imageSwitchMove()
{
	if(imageSwitchCurrentMoveDirection)
	{
		switch(imageSwitchCurrentMoveDirection)
		{
			case 'up':	imageSwitchEditImage.style.top = imageSwitchEditImage.offsetTop + imageSwitchCurrentMovePixels + 'px';  break;
			case 'down': imageSwitchEditImage.style.top = imageSwitchEditImage.offsetTop - imageSwitchCurrentMovePixels + 'px';  break;
			case 'left': imageSwitchEditImage.style.left = imageSwitchEditImage.offsetLeft + imageSwitchCurrentMovePixels + 'px'; break;
			case 'right': imageSwitchEditImage.style.left = imageSwitchEditImage.offsetLeft - imageSwitchCurrentMovePixels + 'px'; break;
			
		}
		
		imageSwitchKeepInBox();
		setTimeout('imageSwitchMove()', 40);
		
		/* Make it move faster if someone holds the button down */
		imageSwitchCurrentMovePixels += 3;
	}
}

/* Begin the image moving */
function imageSwitchStartMove(dir)
{
	imageSwitchCurrentMoveDirection = dir;
	setTimeout('imageSwitchMove()', 40);
	imageSwitchCurrentMovePixels = 1;
}

/* End the image moving */
function imageSwitchEndMove(dir)
{
	imageSwitchCurrentMoveDirection = false;
}

/* Keep the edit image in the box */
function imageSwitchKeepInBox()
{
	var cropBox 				  = dojo.byId('imageCropBox');

	if(imageSwitchEditImage.offsetLeft > cropBox.offsetLeft)
	{
		imageSwitchEditImage.style.left =  cropBox.offsetLeft + 'px';
	} 
	
	if(imageSwitchEditImage.offsetTop > cropBox.offsetTop)
	{
		imageSwitchEditImage.style.top = cropBox.offsetTop + 'px';
	} 
	
	var rightSide  = imageSwitchEditImage.offsetLeft + imageSwitchEditImage.offsetWidth;
	var rightLimit = cropBox.offsetWidth + cropBox.offsetLeft;
	
	if(rightSide < rightLimit)
	{
		imageSwitchEditImage.style.left =  imageSwitchEditImage.offsetLeft + rightLimit - rightSide + 'px';
	} 
	
	var bottomSide  = imageSwitchEditImage.offsetTop + imageSwitchEditImage.offsetHeight;
	var bottomLimit = cropBox.offsetHeight + cropBox.offsetTop;
	
	if(bottomSide < bottomLimit)
	{
		imageSwitchEditImage.style.top =  imageSwitchEditImage.offsetTop + bottomLimit - bottomSide + 'px';
	}
	
	/* Move the mouse handler div to be in the same place as the image */
	imageSwitchSetMouseHandler();

}


/* Position all of the divs for switching */
function imageSwitchDrawCropBox()
{
	var cropScreen   		      = dojo.byId('imageCropScreen');
	var cropBlockTop 		      = dojo.byId('imageCropBlockTop');
	var cropBlockLeft 		      = dojo.byId('imageCropBlockLeft');
	var cropBlockRight 		      = dojo.byId('imageCropBlockRight');
	var cropBlockBottom 	      = dojo.byId('imageCropBlockBottom');
	var cropBox 				  = dojo.byId('imageCropBox');
	
	/* Size and position the blocking elements */
	cropBlockLeft.style.width 	  = Math.floor((cropScreen.offsetWidth - imageSwitchTargetImage.editWidth) / 2) + 'px';
	cropBlockLeft.style.height    = cropScreen.offsetHeight + 'px';
	cropBlockRight.style.width 	  = (cropScreen.offsetWidth - imageSwitchTargetImage.editWidth - cropBlockLeft.offsetWidth) + 'px';
	cropBlockRight.style.height   = cropScreen.offsetHeight + 'px';
	cropBlockTop.style.height	  = Math.floor((cropScreen.offsetHeight - imageSwitchTargetImage.editHeight) / 2) + 'px';
	cropBlockTop.style.width      = imageSwitchTargetImage.editWidth + 'px';
	cropBlockTop.style.left		  = cropBlockLeft.offsetWidth + 'px';
	cropBlockBottom.style.height  = (cropScreen.offsetHeight - imageSwitchTargetImage.editHeight - cropBlockTop.offsetHeight) + 'px';
	cropBlockBottom.style.width   = imageSwitchTargetImage.editWidth + 'px';
	cropBlockBottom.style.left	  = cropBlockLeft.offsetWidth + 'px';
	cropBox.style.height          = imageSwitchTargetImage.editHeight -2 + 'px';
	cropBox.style.width           = imageSwitchTargetImage.editWidth -2 + 'px';
	cropBox.style.left            = cropBlockLeft.offsetWidth  + 'px';
	cropBox.style.top             = cropBlockTop.offsetHeight  + 'px';
	
}


//See if the item is acceptable
function imageSwitchCheckPreview(preview)
{
	var itemType = preview.getAttribute('itemType');
			
	if(itemType == 'folder')
	{
		//Fine
	}
	else if (itemType == 'image') 
	{
		if(preview.getAttribute('imageHeight') < imageSwitchTargetImage.editHeight)
		{
			
			preview.className = 'mediaManagerPreviewDisabled';
		}
	
		if(preview.getAttribute('imageWidth') < imageSwitchTargetImage.editWidth)
		{
			preview.className = 'mediaManagerPrevimageWidthiewDisabled';
		}
	}
	else
	{
		preview.className = 'mediaManagerPreviewDisabled';
	}
}

//Cancel Switching an image
function imageSwitchCancel()
{

	//Allow for other events to happen on cancel.
	if(typeof(imageSwitchCancelCustomFunction) == 'function')
	{
		imageSwitchCancelCustomFunction();
	}
	else
	{
		with(mediaManagerBox.domNode.style){
	        left = '-1900px';
	    }
	    
	    mediaManagerBox.hide();
	    enableBody();
	}
}


function imageSwitchApplyCrop()
{
   
    var socketVars 			= new Object;
    var socketCallUrl	    = prepSocketCall('mediaManager', 'imageCropAndScale', socketVars);
         
    
	//Send a request for content
	dojo.io.bind({
	    url: socketCallUrl,
	    load: function(type, data, evt)
	    	  {

	    	  	imageSwitchTargetImage.src = imageSwitchTargetImage.src + '?refresh=' + Math.random();
	    	  
	    	  	if(imageSwitchAfterCropCustomFunction)
	    	  	{
	    	  		hideWait();
					imageSwitchAfterCropCustomFunction();
	    	  	}
	    	  	else
	    	  	{
					hideWait();
		    	  	hideMediaManager();
	    	  	}
	    	  	
	    	   },
	    	   
	    error: function(type, error)
	          {
	    	 	   alert('There was an error and the image could not be cropped properly.');
	          },
	    content:{
					method					: 'crop',
					
					newWidth    			: imageSwitchTargetImage.editWidth,
					newHeight   			: imageSwitchTargetImage.editHeight,
					
					oldWidth    			: imageSwitchSourceImage.width,
					oldHeight   			: imageSwitchSourceImage.height,
					
					sourceImage 			: imageSwitchSourceImage.src,
					targetImage 			: imageSwitchTargetImage.editSrc,
					
					offsetTop   			: dojo.byId('imageCropBlockTop').offsetHeight   - imageSwitchEditImage.offsetTop,
					offsetLeft  			: dojo.byId('imageCropBlockLeft').offsetWidth   - imageSwitchEditImage.offsetLeft,
					
					oldWidthChanged     	: imageSwitchEditImage.width,
					oldHeightChanged     	: imageSwitchEditImage.height
	    	  },
	    	  
	    mimetype: "text/javascript",
	    method:   "POST"
	    
	});
}