$(document).ready(function() {
	$("#foto").change(function() {
		$(this).upload(urlAction, function(resposta) {
			if(resposta.erro != undefined) {
				alert(resposta.erro);
			} else {
				// Desenha a foto upada no temporário na modal
				$("#dialog").html('<img id="imgResize" src="' + urlImg + resposta.filename + '" alt="' + resposta.filename + '" />');
				
				$("#dialog").dialog({
					heigth: resposta.altura,
					width: resposta.largura + 25,
					modal: true,
					draggable: false,
					resizable: false,
					buttons: { "Recortar" : function() {
						$.post(urlResize, 
						{
							x: $("#x").val(),
							y: $("#y").val(),
							w: $("#w").val(),
							h: $("#h").val(),
							id: idResize,
							img: resposta.filename,
							dir: dirImg,
							urlimg: urlImg
						},
						function(retorno) {
							$("#imgResize").imgAreaSelect({ remove: true});
							$("#pfoto").append(retorno); // Desenha aimagem recortada e o botão de excluir
							$("#dialog").dialog( "close", function(){
									$("#imgResize").imgAreaSelect({ remove: true}); // Faz o resize das imagens 
									$("#foto").reset(); 
								
							});
						});
					}},
					close: function() {
						$("#imgResize").imgAreaSelect({ remove: true}); // Faz o resize das imagens 
						$("#foto").reset(); 
					}
				});
				
				$("#imgResize").imgAreaSelect({
					x1: 0,
					x2: 140, // Comprimento inicial
					y1: 0,
					y2: 140, // Altura inicial
					minWidth: 140, // Comprimento mínimo permitido
					minHeight: 140, // Altura mínima permitida
					aspectRatio: '1:1',
					onSelectChange: function(img, selecao) {
						$("#x").val(selecao.x1),
						$("#y").val(selecao.y1),
						$("#w").val(selecao.width),
						$("#h").val(selecao.height)
					}
				});
			}
		}, 'json');
	});
});
