$(document).ready(function(){

 	$('#dialog_upload_my_face').dialog({
		bgiframe: true,
		modal: true,
		autoOpen: false,
		width: 800,
		buttons: {
			"Закрыть": function() {
				$(this).dialog("close");
			}
		}
	});

	$(".add_my_face").click(function(){
		$('#dialog_upload_my_face').dialog('open');
		return false;
	});

	 var options = {
		 beforeSubmit:  onlyFileValidator,
		 success:	function (data, statusText){

		 	if(data.response == 'error')
			{
				 $.gritter.add(data.error);
				 return false;
			};

			var w;
			var h;

			function showPreview(coords)
			{
				if (parseInt(coords.w) < 0) return;

				var rx = 100 / coords.w;
				var ry = 100 / coords.h;

				$('#face_form_step2 .input_prev_image_here img').css({
					width: Math.round(rx * w) + 'px',
					height: Math.round(ry * h) + 'px',
					marginLeft: '-' + Math.round(rx * coords.x) + 'px',
					marginTop: '-' + Math.round(ry * coords.y) + 'px'
				});

				$('#face_form_step2 input[name="crop[x1]"]').val(coords.x);
				$('#face_form_step2 input[name="crop[y1]"]').val(coords.y);
				$('#face_form_step2 input[name="crop[x2]"]').val(coords.x2);
				$('#face_form_step2 input[name="crop[y2]"]').val(coords.y2);
				$('#face_form_step2 input[name="crop[w]"]').val(coords.w);
				$('#face_form_step2 input[name="crop[h]"]').val(coords.h);
			};


			if(data.response == 'ok')
			{
				$("#face_form_step2 .input_image_here").html('<img src="'+data.url+'" alt="" />');
				$("#face_form_step2 .input_prev_image_here").html('<div style="width:100px;height:100px;overflow:hidden;margin-left:5px;"><img src="'+data.url+'" width="100" height="100" /></div>');

				w = data.w || 600;
				h = data.h || 600;

				$('#face_form_step2 .input_image_here img').Jcrop({
					onChange: showPreview,
					onSelect: showPreview,
					aspectRatio: 1
				});

				$('#face_form_step2 input[name="crop[filename]"]').val(data.filename);
				$('#face_form_step2 input[name="crop[type]"]').val(data.type);
				$('#face_form_step2 input[name="crop[url]"]').val(data.userUrl);
				$('#face_form_step2 input[name="crop[nomId]"]').val(data.nomId);

				$("#face_form").hide();
				$("#face_form_step2").show();

				return true;
			};

		},
		 url:       "/ajax?file=upload_my_face",
		 resetForm: true,
		 dataType:  'json'
	 };

	$("#face_form").ajaxForm(options);

	 var options = {
		success:	function (data, statusText){
			$("#dialog_upload_my_face").html("Ваш запрос на добавление отправлен. После проверки, Ваше фото появиться на RuGeroi.ru.");
		},
		url:       "/ajax?file=upload_my_face",
		resetForm: true,
		dataType:  'json'
	 };

	 $("#face_form_step2").ajaxForm(options);

	 $('.add_my_face img').mouseover( function(){ changeImage(this,null,"add_face_active"); } );
	 $('.add_my_face img').mouseout( function(){ changeImage(this,null,"add_face"); } );
});

preload('add_face_active', '/images/add_my_face_a.jpg');
preload('add_face', '/images/add_my_face.gif');