
var ImageCropper = Class.create({
	uploadImage_img: null,

	initialize: function(settings)
	{
		var uploadImage;

		this.settings = [];

		// Import passed settings, ITIS
		if (settings) Object.extend(this.settings, settings);
	},
	
	
	extendSettings: function(json)
	{
		if (json) Object.extend(this.settings, json);
	},
	
	submitImageSelection: function(dbfield, cropMinWidth, cropMinHeight, columns)
	{
		// THIS FUNCTION IS UNTESTED, WAS UNUSED ON ORIGINAL IMPLEMENTATION OF THE IMAGECROPPER PLUGIN
		
		
		
		// Data protection - verify existence of values for each required dimension
		cropping = true;
		inputs = [dbfield+'_cropper_filename', dbfield+'_cropper_x1', dbfield+'_cropper_y1', dbfield+'_cropper_width', dbfield+'_cropper_height', dbfield+'_cropper_ratio'];
		for (i = 0; i < inputs.length; i++)
		{
			if (!$(inputs[i])) cropping = false;;
		}
		cropMinWidth = (parseInt(cropMinWidth) > 0 ? parseInt(cropMinWidth) : 0);
		cropMinHeight = (parseInt(cropMinHeight) > 0 ? parseInt(cropMinHeight) : 90);

		if (cropping)
		{
			imagesrc = $F(dbfield+'_cropper_filename')+'&x1='+$F(dbfield+'_cropper_x1')+'&y1='+$F(dbfield+'_cropper_y1')+'&cropwidth='+$F(dbfield+'_cropper_width')+'&cropheight='+$F(dbfield+'_cropper_height')+'&cropimgratio='+$F(dbfield+'_cropper_ratio');
		}else{
			imagesrc = $F(dbfield+'_cropper_filename');
		}

		// Update the input or list, ITIS
		if ($(dbfield+'_files_list'))
		{
			// This is a list of images

			// Setup protection
			if (!(multi_selector && multi_selector != null && multi_selector != undefined))
			{
				alert('This site is not configured correctly: The multi file upload helper is not instantiated, and it is required. This is usually done via core->formhelper->drawMultipleFileUpload(). #mfucf1');
				return false;
			}

			if (imagesrc != '')
			{
				// Update the input(s)
				$(dbfield).value = ($(dbfield).value+','+imagesrc).replace(/^,/, '');

				// Get any other columns from the facebox and store values into #theform
				columns.split(',').each(function(column)
				{
					if ($('imageUtility_'+column))
					{
						// Create DOM element for each column
						column_elem =  new Element(($('imageUtility_'+column).tagName != "" ? $('imageUtility_'+column).tagName : 'input'), {'name': multi_selector.elementnameprefix+'_'+column+'_'+(multi_selector.count - 1), 'style': 'display: none;'});
						if ($('imageUtility_'+column).tagName.toLowerCase() == 'input')
						{
							column_elem.value = $F('imageUtility_'+column);
						}else if ($('imageUtility_'+column).tagName.toLowerCase() == 'textarea')
						{
							column_elem.innerHTML = $F('imageUtility_'+column);
						}

						// Add column to DOM
						$('theform').appendChild(column_elem);
					}
				});

				// Trigger adding this new image to the multifile list
				params = [];
				params.w = cropMinWidth;
				params.h = cropMinHeight;
				multi_selector.addListRow(dbfield, params)
			}

			facebox.close();
		}else if ($(dbfield))
		{
			// This is a single image

			// Update the input
			$(dbfield).value = imagesrc;

			// Update the thumb, ITIS
			if ($(dbfield+'_thumb'))
			{
				$(dbfield+'_thumb').src = '/core/images/image.php?src='+imagesrc+'&w=87&h=65';
				$(dbfield+'_thumb').show();
			}

			facebox.close();
		}
	},
	
	onChange: function(file, elem)
	{
	},
	
	onSubmit: function(file, ext)
	{
		// Show loading indicator, ITIS
		if (this.settings.responsesWrapper) ajax.showLoadingIndicator(this.settings.responsesWrapper);
	},
	
	onComplete: function(response, uploadElemID)
	{
		if (response != null && response != 'error' && response != '')
		{
			file = response;

			this.uploadImage_img = new Image();
			this.uploadImage_img.src = file.evalJSON().path+file.evalJSON().filename;

			imagecropper._onComplete(uploadElemID, file, response);
		}
	},

	_onComplete: function(uploadElemID, file, filename)
	{
		if (this.uploadImage_img.complete)
		{
			if ($('filesystem_dir_root'))
			{
				// THIS LOOKS LIKE IT ONLY APPLIES TO THE FILESYSTEM SELECTOR, ITIS - UNTESTED...
				
				
				// Define filesystem link for newly uploaded image and add to DOM
				if ($$('#filesystem_dir_root .filename')[0])
				{
					newlink = $$('#filesystem_dir_root .filename')[0].cloneNode(true);
					newlink.addClassName('selected');
					newlink.id = 'uploadedimage_'+new Date().getTime();
					$$('#filesystem_dir_root a.filename').each(function(elem) { elem.removeClassName('selected'); } );
					$('filesystem_dir_root').appendChild(newlink);	
					if ($$('#'+newlink.id+' span.filename')[0]) $$('#'+newlink.id+' span.filename')[0].innerHTML = filename;
					$('filesystem_wrapper').scrollTop = $('filesystem_dir_root').getHeight();

					// Set handler for new link
					thefunc = $(newlink.id).onclick.toString();
					thefunc = thefunc.replace(/^[^{]*{/, '');
					thefunc = thefunc.replace(/}$/, '');
					thefunc = thefunc.replace(/return.*;/, '');
					thefunc = thefunc.replace(/updateCropper\("([^"]*)", "[^"]*"/, 'imagecropper.update("$1", "'+file+'"');
					$(newlink.id).setAttribute('onclick', '');

					eval("Event.observe($(newlink.id), 'click', function() {	"+thefunc.replace('"', '\"')+"	});");
				}
			}

			imagecropper.update(uploadElemID.replace(/_upload$/, ''), file);
		}else{
			window.setTimeout("imagecropper._onComplete('"+uploadElemID+"', '"+file+"', '"+filename+"');", 250);
		}
	},
	
	start: function(params)
	{
		// Instantiate the cropper...

		// Wait an arbitrary amount of time, then fire actual instantiator for Cropper...
		// Doing this because IE fails to load cropper within a facebox initially - could not find an attribute to test for in order to detect if the image was "ready for IE", so I am just waiting a short amount of time, which seems to work fine
		// Probably has to be >= the animation time on the facebox...
		
		_params = '';
		for (param in params)
		{
			if (typeof params[param] == 'string')
			{
				_params += param+': \''+params[param]+'\', ';
			}else if (typeof params[param] == 'number')
			{
				_params += param+': '+params[param]+', ';
			}else if (typeof params[param] == 'object')
			{
				subparams = '';
				for (subparam in params[param])
				{
					if (typeof params[param][subparam] == 'string')
					{
						subparams += subparam+': \''+params[param][subparam]+'\', ';
					}else if (typeof params[param][subparam] == 'number')
					{
						subparams += subparam+': '+params[param][subparam]+', ';
					}
				}
				subparams = '{'+subparams.replace(/, $/, '')+'}';
				
				_params += param+': '+subparams+', ';
			}else if (typeof params[param] == 'function')
			{
				_params += param+': '+params[param]+', ';
			}
		}
		_params = '{'+_params.replace(/, $/, '')+'}';

		window.setTimeout('imagecropper._start('+_params+');', 600);
	},
	
	_start: function(params)
	{
		if (params.showPreview)
		{
			cropper = new Cropper.ImgWithPreview(params.ElemID, params);
		}else{
			cropper = new Cropper.Img(params.ElemID, params);
		}
	},

	update: function(ID, imagesrc, params)
	{
		// Data protection
		if (params != null && params != undefined)
		{
			paramsarray = params.split('&');
			params = [];
			for (i = 0; i < paramsarray.length; i++)
			{
				params[paramsarray[i].replace(/=.*$/, '')] = paramsarray[i].replace(/^.*=/, '');
			}
		}else{
			params = [];
		}
		params.width = (parseInt(params.width) > 0 ? parseInt(params.width) : (parseInt(params) > 0 ? params : 0));
		params.minWidth = (parseInt(params.minWidth) > 0 ? parseInt(params.minWidth) : this.settings.cropMinWidth);
		params.minHeight = (parseInt(params.minHeight) > 0 ? parseInt(params.minHeight) : this.settings.cropMinHeight);
		if (params.ratioDim)
		{
			eval('params.ratioDim = '+params.ratioDim);
		}else{
			// default
			params.ratioDim = this.settings.ratioDim;
		}
		if (params.onloadCoords)
		{
			eval('params.onloadCoords = '+params.onloadCoords);
		}else{
			// default
			params.onloadCoords = '{x1: 0, y1: 0, x2: '+params.minWidth+', y2: '+params.minHeight+'}';
		}

		// Define callback
		cb = function(status, resp)
		{
			if ($('imageUtility_cropper'))
			{
				if (status == 200)
				{
					$('imageUtility_cropper').innerHTML = resp;

					//update image fields
					imagecropper.updateImageFields( ID , imagesrc );

					// Hide loading indicator, ITIS
					if (imagecropper.settings.responsesWrapper) ajax.hideLoadingIndicator(imagecropper.settings.responsesWrapper);										
					
					_params = {ElemID: ID+'_image', showPreview: (imagecropper.settings.showPreview ? 1 : 0), previewWrap: ID+'_preview_wrapper', minWidth: params.minWidth, minHeight: params.minHeight, ratioDim: params.ratioDim.evalJSON(), onloadCoords: params.onloadCoords.evalJSON(), displayOnInit: (imagecropper.settings.displayOnInit ? 1 : 0), onEndCrop: getImageCropperCoords };

					imagecropper.start(_params);
				}else{
					alert('Oops! The image cropper was unable to load. Please try again');
				}
			}
		};

		// Data protection
		if (!$(ID)) return false;
		if (imagesrc == "") return false;
		width = (params['width'] != null ? params['width'] : (params != '' ? params : 0));
		if (width <= 0)
		{
			if ($('imageUtility_cropper') && parseInt($('imageUtility_cropper').getStyle('width')) > 0)
			{
				width = parseInt($('imageUtility_cropper').getStyle('width'));
			}else{
				width = 0;
			}
		}

		// Get the cropper HTML content via AJAX
		ajax.get(this.settings.ui+'?ElemID='+ID+'&imagesrc='+imagesrc+'&wrapperWidth='+width+'&cropMinWidth='+params.minWidth+'&cropMinHeight='+params.minHeight+'&ratioDim='+params.ratioDim+'&onloadCoords='+params.onloadCoords+'&debug='+(this.settings.debugMode ? '1' : '0')+'&showPreview='+(this.settings.showPreview ? '1' : '0'), cb);
	},

	updateImageFields: function( ID , imagesrc )
	{
		// Update input element(s) for filename
		if ($(ID+'_cropper_filename')) $(ID+'_cropper_filename').value = imagesrc;
		if ($(ID+'_filename')) $(ID+'_filename').value = imagesrc.evalJSON().filename;
	}		

	

});



	
function getImageCropperCoords(coords, dimensions)
{
	if ($$('.cropper_x1').length == 1) $$('.cropper_x1').first().value = coords.x1;
	if ($$('.cropper_y1').length == 1) $$('.cropper_y1').first().value = coords.y1;
	if ($$('.cropper_x2').length == 1) $$('.cropper_x2').first().value = coords.x2;
	if ($$('.cropper_x2').length == 1) $$('.cropper_y2').first().value = coords.y2;
	if ($$('.cropper_width').length == 1) $$('.cropper_width').first().value = dimensions.width;
	if ($$('.cropper_height').length == 1) $$('.cropper_height').first().value = dimensions.height;
}
	
	
var imagecropper;
// Instantiation occurs in footer


