$(function(){
	
	var $cropImg = $('#cropThis');
	var $previewImg = $('#preview');
	var $sendCoordsBtn = $('._jsSendJcropCoords');
	
	var maxWidth = 300;
	var maxHeight = 300;
	
	var initial = {
		x1 : $cropImg.width()*.5 - maxWidth*.5,
		x2 : $cropImg.width()*.5 - maxWidth*.5 + maxWidth,
		y1 : $cropImg.height()*.5 - maxHeight*.5,
		y2 : $cropImg.height()*.5 - maxHeight*.5 + maxHeight
	};
	
	var initialCoords = [initial.x1, initial.y1, initial.x2, initial.y2];
	
	$cropImg.Jcrop({
		maxSize : [maxWidth, maxHeight],
		aspectRatio : maxWidth/maxHeight,
		setSelect: initialCoords,
		onChange : function( c ){
			$cropImg.data(c);
			
			var perc = {
				x : $cropImg.width() / c.w,
				y : $cropImg.height() / c.h
			};
			
			var correctSize = {
				width : $cropImg.width() / c.w * maxWidth,
				height : $cropImg.height() / c.h * maxHeight,
				marginTop : -maxWidth / c.h * c.y,
				marginLeft : -maxHeight / c.w * c.x
			};
			
			var fittedSize = {
				width : $previewImg.parent().width() * perc.x,
				height : $previewImg.parent().height() * perc.y,
				marginTop : -$previewImg.parent().height() / c.h * c.y,
				marginLeft : -$previewImg.parent().width() / c.w * c.x
			};

			$previewImg.css({
				width: fittedSize.width,
				height: fittedSize.height,
				marginTop: fittedSize.marginTop,
				marginLeft: fittedSize.marginLeft
			})
		},
		onSelect : function(){}
	});
	
	$sendCoordsBtn.click( function ( event ) {
		event.preventDefault();
		
		var c = $cropImg.data();
		var imgPath = $cropImg.attr('src');
		console.log(c.x);
		
		$.ajax({
			url : 'home',
			type : 'post',
			dataType : 'json',
			data : {
				'img_path' : imgPath,
				'coords' : {
					'x' : c.x,
					'y' : c.y,
					'x2' : c.x2,
					'y2' : c.y2,
					'w' : c.w,
					'h' : c.h
				},
				ajax_on : true
			},
			success : function ( data ) {
				if ( data.success ) {
					console.log("SUCCESS : ", data);
				}
			},
			error: function ( ) {
				alert("an error occured");
			}
		});
		
	});
	
});
