var photo_sess_id = Math.floor(Math.random( ) * 999999999);
var supported_image_types = {'jpg':1, 'jpeg':1, 'png':1, 'gif':1};
var cropperSettings = {previewWrap: "cropImagePreview", ratioDim: {x: 1, y: 1}, minWidth: 120, minHeight: 120, displayOnInit: true, onEndCrop: onEndCrop};
var cropperInstance = false;

function initCrop(filename)
{
	var extension = filename.substring(filename.lastIndexOf('.')+1,filename.length).toLowerCase();
	if(supported_image_types[extension] != 1)
	{
		$("crop").hide();
		if($("crop_error"))$("crop_error").show();
		$("sImage").value = "";
		reroundCorners();
		return;
	}
	if($("crop_error"))$("crop_error").hide();

	if ($('avatar-holder')) {
		$('avatar-holder').hide();
	}
	
	if($("cropImage"))
	{
		$("cropImage").src = $("sURL").value + photo_sess_id + filename;
	}
	else
	{
		var img = new Image();
		img.id = "cropImage";
		img.src = $("sURL").value + photo_sess_id + filename;
		$("cropWrap").update(img);
	}
	$("sImage").value = photo_sess_id + filename;

	$("crop").show();
	if(typeof(cropperSettings.previewWrap) != "undefined")
	{
		$(cropperSettings.previewWrap).show();
		if($("imgCrop_cropImage"))
		{
			$("imgCrop_cropImage").src = $("sURL").value + photo_sess_id + filename;
		}
	}

	if (cropperInstance != false)
	{
		cropperInstance.remove();
	}
	else
	{
		cropperInstance = new Cropper.ImgWithPreview( "cropImage", cropperSettings );
	}
	if(typeof(cropperSettings.after_init) == "function")
	{
		cropperSettings.after_init(filename);
	}
	if(typeof(reroundCorners) == "function")
	{
		reroundCorners();
	}
}

function clearCrop()
{
	$("crop").hide();
	if(typeof(cropperSettings.previewWrap) != "undefined")
	{
		$(cropperSettings.previewWrap).hide();
	}
	$("sImage").value = "";
	$('image-x').value = "0";
	$('image-y').value = "0";
	$('image-width').value = "0";
	$('image-height').value = "0";
	
	if(typeof(cropperSettings.after_clear) == "function")
	{
		cropperSettings.after_clear();
	}
	
	if ($('avatar-holder')) {
		$('avatar-holder').show();
	}
}

function onEndCrop( coords, dimensions )
{
	$('image-x').value = coords.x1;
	$('image-y').value = coords.y1;
	$('image-width').value = dimensions.width;
	$('image-height').value = dimensions.height;

	if(typeof(cropperSettings.after_end) == "function")
	{
		cropperSettings.after_end(coords, dimensions);
	}
}

Event.observe(window, "load", function(){	
	
	var uploaderParams = {effectType: "slide",
			flashPath: rooturl + "public/flash/uploader.swf",
			buttonPath: rooturl + "public/images/site_images/forms/elements/upload.png",
			phpPath: rooturl + locale + "/ajax/uploadImage?photo_sess_id=" + photo_sess_id,
			jsCallback: "initCrop"};
	
	swfobject.embedSWF(uploaderParams.flashPath, "uploader", "99", "40", "9.0.0", "", uploaderParams);
});