require('jquery-jcrop');
var Crop = {};

Crop.init = function(aspectRatio, realWidth, realHeight){
	jQuery('#cropbox').Jcrop({
		aspectRatio: aspectRatio,
		onChange: updateCoords,
		onSelect: updateCoords,
		trueSize: [realWidth, realHeight]
	});

	jQuery('#CloseCropBtn').on('click', function(){
		window.close();
	});

	jQuery('#CropDoneBtn').on('click', function(){
		return returnThisImage();
	});
};

function updateCoords(c)
{
	jQuery('#CropBtn').removeClass('hide');
	jQuery('#left').val(c.x);
	jQuery('#top').val(c.y);

	var w = Math.round(c.w);
	var h = Math.round(c.h);

	jQuery('#width').val(c.w);
	jQuery('#height').val(c.h);

	jQuery("#cur_width").html(w);
	jQuery("#cur_height").html(h);
}

// send parameters to PHP script to actualy crop image
function returnThisImage()
{
	var info = {
		image_code: jQuery("#image_code").prop('value'),
		left: jQuery('#left').val(),
		top: jQuery('#top').val(),
		width: jQuery('#width').val(),
		height: jQuery('#height').val()
	};
	jQuery.post("image_select_popup.php?action=do_crop", info, passToCaller, "json");
}

// Pass data to calling page. "data" parameter is JSON object returned by PHP
function passToCaller(data)
{
	var dest_name = jQuery("#dest_name").prop('value');
	if (data.error)
	{
		alert(data.error);
		return;
	}
	window.opener.fileUploadImageSelected(dest_name, data.image_code, data.realname);
	window.close();
}

module.exports = Crop;
