/**
 *
 * HTML5 Image uploader with Jcrop
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Copyright 2012, Script Tutorials
 * http://www.script-tutorials.com/
 */

$(document).ready(function() {

    var jcrop_api,
            boundx,
            boundy,
            aspect_ratio = 0.75,
            $preview = $('#preview-pane'),
            $pcnt = $('#preview-pane .preview-container'),
            $pimg = $('#preview-pane .preview-container img'),
            xsize = $pcnt.width(),
            ysize = $pcnt.height();

    // convert bytes into friendly format
    function bytesToSize(bytes) {
        var sizes = ['Bytes', 'KB', 'MB'];
        if (bytes == 0)
            return 'n/a';
        var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
    }

    // check for selected crop region
    function checkForm() {
        if (parseInt($('#w').val()))
            return true;
        $('.error').html('Silahkan crop / pilih terlebih dahulu').show();
        return false;
    }

    // update info by cropping (onChange and onSelect events handler)
    function updateInfo(e) {
        $('#x1').val(e.x);
        $('#y1').val(e.y);
        $('#x2').val(e.x2);
        $('#y2').val(e.y2);
        $('#w').val(e.w);
        $('#h').val(e.h);
    }

    // clear info by cropping (onRelease event handler)
    function clearInfo() {
        $('.info #w').val('');
        $('.info #h').val('');
    }

    function updatePreview(c)
    {

        $('#x1').val(c.x);
        $('#y1').val(c.y);
        $('#x2').val(c.x2);
        $('#y2').val(c.y2);
        $('#w').val(c.w);
        $('#h').val(c.h);

        if (parseInt(c.w) > 0)
        {
            var rx = xsize / c.w;
            var ry = ysize / c.h;

            $pimg.css({
                width: Math.round(rx * boundx) + 'px',
                height: Math.round(ry * boundy) + 'px',
                marginLeft: '-' + Math.round(rx * c.x) + 'px',
                marginTop: '-' + Math.round(ry * c.y) + 'px'
            });
        }
    }

    function initJcrop()
    {
        // initialize Jcrop
        $('.step2').fadeIn(500);
        $('#selesai').show();
        $('#preview-pane').fadeIn(500);

        var previewWidth = 360;
        var previewHeight = Math.floor(previewWidth / this.width * this.height);

        $('#preview').Jcrop({
            aspectRatio: aspect_ratio,
            bgFade: true,
            bgOpacity: .3,
            onChange: updatePreview,
            onSelect: updatePreview,
            boxWidth: previewWidth,
            boxHeight: previewHeight
        }, function() {

            // Use the Jcrop API to get the real image size
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];

            // Store the Jcrop API in the jcrop_api variable
            jcrop_api = this;

            // Set initial crop selection
            var initx, inity;
            if (boundx / aspect_ratio > boundy) {
                inity = boundy;
                initx = boundy * aspect_ratio;
            } else {
                initx = boundx;
                inity = boundx / aspect_ratio;
            }
            jcrop_api.animateTo([0, 0, initx, inity]);

            // Move the preview into the jcrop container for css positioning
            $preview.appendTo(jcrop_api.ui.holder);
        });
    }

    $("#foto").on('change', function() {

        if (typeof aspect_ratio == 'undefined') {
            aspect_ratio = 0.75;
        }

        // get selected file
        var oFile = $('#foto')[0].files[0];

        // hide all errors
        $('.error').hide();

        // check for image type (jpg and png are allowed)
        var rFilter = /^(image\/jpeg)$/i;
        if (!rFilter.test(oFile.type)) {
            $('.error').html('Hanya file JPG dan JPEG yang dijinkan').show();
            return;
        }

        // check for file size
        if (oFile.size > 1024 * 1024) {
            $('.error').html('Ukuran file / resolusi terlalu besar, mohon diperkecil').show();
            return;
        }

        // preview element
        var oImage = document.getElementById('preview');
        var oPreview = document.getElementById('cropped');

        // prepare HTML5 FileReader
        var oReader = new FileReader();
        oReader.onload = function(e) {
            oImage.src = e.target.result;
            oPreview.src = e.target.result;
            oImage.onload = function() {
                var sResultFileSize = bytesToSize(oFile.size);
                $('#filesize').val(sResultFileSize);
                $('#filetype').val(oFile.type);
                $('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);
                if (typeof jcrop_api !== 'undefined') {
                    jcrop_api.destroy();
                    jcrop_api = null;
                    $('#preview').width(oImage.naturalWidth);
                    $('#preview').height(oImage.naturalHeight);
                    console.log("destroy and create new jcrop");
                }
                initJcrop();
            };
        };

        // read selected file as DataURL
        oReader.readAsDataURL(oFile);
    });

    $("#selesai").on("click", function() {

        $('.center-cropped').hide();
        $(this).hide();
        jcrop_api.disable();

    });

    if ($("#preview").attr("src")) {
        console.log("ada src");

        var oImage = document.getElementById('preview');
        var oPreview = document.getElementById('cropped');
        oPreview.src = oImage.src;
        initJcrop();
    } else {
        console.log("tidak ada src");
    }

});
