/**
* @package XenCentral Ad Server
* @author Skydevelop EU
* @copyright Drnoyan & Nalyan LDA, Portugal, EU
* @license http://www.dnf.pt/eula.html
* @link http://www.skydevelop.com
* @revision 97
* @version 2.0.0 beta 3 rev. 3
*/
var initCropControl;
jQuery(function ($) {
    initCropControl = function (imageId) {
        var crop_api;
        var $image = $('#' + imageId);
        var $imageContainer = $image.closest('.jCropContainer');
        var options = {
            onChange: saveCoordinates,
            onSelect: saveCoordinates,
            onRelease: clearCoordinates,
        };

        var aspectRatio = 0;

        if (
            parseInt($imageContainer.data('force'))
        ) {
            aspectRatio = parseInt($imageContainer.data('width')) / parseInt($imageContainer.data('height'));
            options.aspectRatio = aspectRatio;
            var size=[parseInt($imageContainer.data('width')), parseInt($imageContainer.data('height'))]
            // options.minSelect = size;
            options.minSize = size;
        }

        var callback= function () {
            crop_api = this;
            if ($imageContainer.data('width') && $imageContainer.data('height')) {
                crop_api.setSelect([
                    0,
                    0,
                    parseInt($imageContainer.data('width')),
                    parseInt($imageContainer.data('height'))
                ]);
            }
        };

        $image.Jcrop(options, callback);

        $('span.imageSizeLabel input', $imageContainer).blur(function () {
            if ($(this).data('disableHandler')) {
                return true;
            }

            var width = parseInt($('span.imageSizeLabel input.width', $imageContainer).val());
            var height = parseInt($('span.imageSizeLabel input.height', $imageContainer).val());

            if (aspectRatio) {
                if ($(this).hasClass('width')) {
                    height = width * aspectRatio;
                } else {
                    width = height * aspectRatio;
                }
            }

            var x1 = parseInt($('input[name=x1]', $imageContainer).val());
            var y1 = parseInt($('input[name=y1]', $imageContainer).val());

            crop_api.setSelect([
                x1,
                y1,
                x1 + width,
                y1 + height
            ]);
        });

        function saveCoordinates(c) {
            if (
                parseInt($imageContainer.data('force'))
            ) {
                var width = c.x2 - c.x;
                var ratio = parseInt($imageContainer.data('width')) / parseInt($imageContainer.data('height'));
                var calculatedHeight = width * ratio;
                /*if(
                 calculatedHeight!=Math.round(c.h)
                 && calculatedHeight<=Math.round($imageContainer.data('height'))
                 ) {
                 // force constrains
                 crop_api.setSelect([
                 c.x,
                 c.y,
                 c.x2,
                 c.y + calculatedHeight
                 ]);
                 return;
                 }
                 c.h=calculatedHeight;*/
            }

            $('input[name=x1]', $imageContainer).val(c.x);
            $('input[name=y1]', $imageContainer).val(c.y);
            $('input[name=x2]', $imageContainer).val(c.x2);
            $('input[name=y2]', $imageContainer).val(c.y2);
            $('input[name=w]', $imageContainer).val(c.w);
            $('input[name=h]', $imageContainer).val(c.h);

            $('span.imageSizeLabel', $imageContainer).data('disableHandler', 1);
            $('span.imageSizeLabel .width', $imageContainer).val(c.w);
            $('span.imageSizeLabel .height', $imageContainer).val(c.h);
            $('span.imageSizeLabel', $imageContainer).data('disableHandler', 0);

            if (c.w == 0 && c.h == 0) {
                $('input.crop', $imageContainer).hide();
            } else {
                $('input.crop', $imageContainer).show();
            }
        }

        function clearCoordinates() {
            $('input[type=hidden]', $imageContainer).val(0);
            $('span.width', $imageContainer).html($('span.width', $imageContainer).data('width'));
            $('span.height', $imageContainer).html($('span.height', $imageContainer).data('height'));
        }

        $imageContainer.find('input.crop').click(function () {
            XenForo.ajax($imageContainer.data('submit'), {
                'x1': $('input[name=x1]', $imageContainer).val(),
                'y1': $('input[name=y1]', $imageContainer).val(),
                'x2': $('input[name=x2]', $imageContainer).val(),
                'y2': $('input[name=y2]', $imageContainer).val(),
                'w': $('input[name=w]', $imageContainer).val(),
                'h': $('input[name=h]', $imageContainer).val()
            }, function (serverData) {
                if(typeof serverData=='object') {
                    ajaxData=serverData;
                } else {
                    try {
                        var ajaxData = $.parseJSON(serverData);
                    }
                    catch (exception) {
                        console.warn(exception);
                        return;
                    }
                }

                if (ajaxData.error) {
                    var $overlayHtml = XenForo.alert(
                        ajaxData.error,
                        'error',
                        5
                    );
                }
                else {
                    crop_api.setImage(ajaxData.viewUrl);
                    return;
                    crop_api.destroy();
                    var $imageClone=$('<img src="'+ ajaxData.viewUrl+'" id="'+$image.attr('id')+'" />');

                    $imageClone.load(function(){
                        $image = $imageClone;
                        $image.Jcrop(options, callback);
                    });

                    var $parent=$image.parent();
                    $image.remove();
                    $imageClone.appendTo($parent);
                }
            })
        });

        $imageContainer.find('input.cancel').click(function () {
            crop_api.setSelect([0, 0, 0, 0]);
        });
    }
});

// Simple event handler, called from onChange and onSelect
// event handlers, as per the Jcrop invocation above
function showCoords(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);*/
};

function clearCoords() {
    $('#coords input').val('');
};