/**
 * @author alex michaud
 */

function loadOriginalImage(image_url)
{
	var original_image_url = image_url.replace(/normal/,"original");
	$('#cropbox').attr('src',original_image_url);
	$('#cropbox').load(function(){
		jQueryCropBox.destroy();
		loadCropBox();
	});
	$('#image').attr('value','new_crop');
}

function loadCropBox()
{
	var aRatio = (location.pathname.match("ctrl_post")||location.pathname.match("ctrl_category"))?4/3:'';
	if(location.pathname.match("ctrl_post")||location.pathname.match("ctrl_category"))
	{
		var aRatio = 4/3;
		var oriHeight = $('#cropbox').width()/aRatio;
	}
	else
	{
		var aRatio = '';
		var oriHeight = $('#cropbox').height();
	}
	jQueryCropBox = $.Jcrop('#cropbox',{
						onChange: showPreview,
						onSelect: showPreview,
						aspectRatio: aRatio,
						setSelect: [ 0,0,$('#cropbox').width(),oriHeight ]
					});
	
	$('#preview').attr('src',$('#cropbox').attr('src'));
	return true;
}

// event handler, called from onChange and onSelect
function showPreview(coords)
{
	var ratio = coords.w/coords.h;
	if (parseInt(coords.w) > 0)
	{
		var rx = 120*ratio / coords.w;
		var ry = 120 / coords.h;

		jQuery('#preview').css({
			width: Math.round(rx * $('#cropbox').width()) + 'px',
			height: Math.round(ry * $('#cropbox').height()) + 'px',
			marginLeft: '-' + Math.round(rx * coords.x) + 'px',
			marginTop: '-' + Math.round(ry * coords.y) + 'px'
		});
		
		jQuery('#image_crop').css({
			width:120*ratio+'px',
			height:'120px'
		})
	}
	
	showCoords(coords);
}

function showCoords(c)
{
	jQuery('#x1').val(c.x);
	jQuery('#y1').val(c.y);
	jQuery('#x2').val(c.x2);
	jQuery('#y2').val(c.y2);
	jQuery('#w').val(c.w);
	jQuery('#h').val(c.h);
}

function deleteImage()
{
	try {
		if(jQueryCropBox) 
			jQueryCropBox.destroy();
	}
	catch(e){}
	$('#image').attr('value','delete');
	$('#image_upload').children('img').remove();
	$('#preview').attr('src','');
}

