function preview(img, selection)
{

    //preview--
    var scaleX = 100 / selection.width;
    var scaleY = 100 / selection.height;

    $('#preview > img').css({
        width: Math.round(scaleX * 400) + 'px',
        height: Math.round(scaleY * 300) + 'px',
        marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
        marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
    });
    //--preview

    $('#outWidth').val(selection.width);
    $('#outHeight').val(selection.height);
    $('#x1').val(selection.x1);
    $('#y1').val(selection.y1);
    $('#x2').val(selection.x2);
    $('#y2').val(selection.y2);

}

$(document).ready(function () {

    var ajaxImg = $('#result').html();

    $('form').submit(function () {

        $('#result')
            .html(ajaxImg)
            .css({display: "block"});
            
        $.post(
            './backend/index.php',
            {
                w: $('#outWidth').val(),
                h: $('#outHeight').val(),
                x: $('#x1').val(),
                y: $('#y1').val(),
                i: $('#workspace > img').attr('src')
            },
            function(txt){
                $('#result').html(txt);
            },
            'text'
        );

        return false;
    });

     $('form').change(function () {

     });


    //preview--
    var wSpaceWidth = $('#workspace > img').width();
    var wSpaceHeight = $('#workspace > img').height();

    var previewWidth = 180;
    var previewHeight = (wSpaceHeight * previewWidth) / wSpaceWidth;

    $('#preview')
    .css({
        position: 'relative',
        overflow: 'hidden',
        width: previewWidth +'px',
        height: previewHeight + 'px'
    })
    .html('<img src="' + $('#workspace > img').attr('src') + '" style="position: relative;" />');
    //--preview

});

$(window).load(function () {
    $('#image').imgAreaSelect({
        movable: true,
        resizable: true,
        onSelectChange: preview
    });
});