$(function () {

    $("input[name=stdClass\\[table_name\\]]").on('change', function () {
        var table_name_val = $(this).val();
        $("input[name=stdClass\\[module_folder_name\\]]").val(table_name_val);
    });

    if (typeof phpDateFormatStringToJQueryFormat !== "function") {
        /**
         * Function for transforming php date format string into a jQuery format string
         * @param string dateFormat
         */
        function phpDateFormatStringToJQueryFormat(dateFormat)
        {
            dateFormat = dateFormat.replace("d","dd");
            dateFormat = dateFormat.replace("j","d");
            dateFormat = dateFormat.replace("l","DD");
            dateFormat = dateFormat.replace("z","o");
            dateFormat = dateFormat.replace("F","MM");
            dateFormat = dateFormat.replace("M","M");
            dateFormat = dateFormat.replace("n","m");
            dateFormat = dateFormat.replace("m","mm");
            dateFormat = dateFormat.replace("Y","yy");
            dateFormat = dateFormat.replace("y","y");

            dateFormat = dateFormat.replace("H","HH");
            dateFormat = dateFormat.replace("i","mm");
            return dateFormat;
        }
    }

    /**
     * Event for automatically adding currenty date in empty input.datetime fields
     */
    $.each($('input.datetime'), function (index, el) {

        var format = $(el).attr("data-datetime-frontend-format");
        if ( format === undefined || format === "" ) {
            format = "d/m/Y H:i";
        }

        if ($(el).val() === "" && format === "d/m/Y H:i" && !$(el).hasClass("emptyDefaultDatetime")) {
            var current_date = new Date();
            var string;
            current_date.setDate(current_date.getDate());

            string  = ('0' + current_date.getDate()).slice(-2) + '/';
            string += ('0' + (current_date.getMonth()+1)).slice(-2);
            string += '/' + current_date.getFullYear();
            string += ' ' + ('0' + current_date.getHours()).slice(-2) + ':';
            string += ('0' + current_date.getMinutes()).slice(-2);

            $(el).val(string);
        }

        var format_arr = format.split(" ");
        if ( format_arr[0] === undefined ) {
            format_arr[0] = "d/m/Y";
        }
        if ( format_arr[1] === undefined ) {
            format_arr[1] = "H:i";
        }

        $(el).datetimepicker({
            dateFormat: phpDateFormatStringToJQueryFormat(format_arr[0]),
            timeFormat: phpDateFormatStringToJQueryFormat(format_arr[1])
        });

    });

    /**
     * Event for the module quick search
     */
    $(".modelAutoSearch").autocomplete({
        source: "search_list.php?limit="+($(".modelAutoSearchLimit").val()),
        minLength: 0,
        response: function ( event, ui ) {
            $(".listTBody").html("");
            if ( ui.content.length > 0 ) {
                for (var i = 0; i < ui.content.length; i++) {
                    $(".listTBody").append(ui.content[i].data);
                }
            } else {
                $(".listTBody").append("No Results Found");
            }
            return false;
        },
        open: function ( event, ui ) {
            $(".ui-autocomplete").hide();
        }
    });

    $(".onChangeThisFormSubmit").on("change",function () {
        $(this).parents("form").submit();
    });

    $(".do-add-another-one").on("click", function (event) {
        event.preventDefault();
        addAnotherOne($(this));
        return false;
    });

    /**
     * Add another multiinput (images, combo_selects, ...) input.
     * Getts triggered when the (+) button is pressed
     * @param el - current input
     */
    function addAnotherOne(el)
    {
        $(".combobox").combobox("destroy");
        var one  = el.parent(".rowRow").clone();
        one.find("select").val("");
        one.find("input").val("");
        one.find("img.imageInputPreview").remove("");
        el.parent(".rowRow").after(one);
        $(".combobox").combobox();
        $(".do-add-another-one").off("click");
        $(".do-add-another-one").on("click", function (event) {
            event.preventDefault();
            addAnotherOne($(this));
            return false;
        });
        $(".do-remove-this-one").off("click");
        $(".do-remove-this-one").on("click", function (event) {
            event.preventDefault();
            removeThisOne($(this));
            return false;
        });
        return false;
    };

    $(".do-remove-this-one").on("click", function (event) {
        event.preventDefault();
        removeThisOne($(this));
        return false;
    });

    /**
     * Remove an input from multiinput (images, combo_selects, ...) input.
     * Getts triggered when the (-) button is pressed
     * If this is the last input - it's value simply gets emptied
     * @param el - the input that needs removed
     */
    function removeThisOne(el)
    {
        if ( el.parent().parent().children(".rowRow").length == 1 ) {
            el.siblings("input").val("");
            el.siblings("select").val("");
            el.siblings(".custom-combobox").children("input").val("");
            el.siblings(".imageInputAndPreviewContainer").children("input").val("");
            el.siblings(".imageInputAndPreviewContainer").children("img").remove();
            return false;
        }
        el.closest(".rowRow").remove();
        return false;
    };

    $(".combobox").combobox();

    $('tbody.dragAndDropOrder').sortable({
        opacity: 0.6,
        handle: ".orderHandle",
        cursor: 'move',
        update: function () {
            var new_order = $(this).sortable("serialize"),
                data = {};
            if ($("#parent_key").length) {
                data.parent_key = $("#parent_key").val();
            }
            if ($("#parent_id").length) {
                data.parent_id = $("#parent_id").val();
            }
            if ($("#relation_key").length) {
                data.relation_key = $("#relation_key").val();
            }
            $.ajax({
                type: 'get',
                cache: false,
                url: 'ajax/order.php?' + new_order,
                data: data,
                dataType: 'json'
            })
            .done(function (result) {
                if (result.result !== true) {
                    location.reload();
                }
            });
        }
    });

    $('.cropAdjust').fancybox({
        type: 'iframe',
        fitToView: false,
        autoSize: false,
        height: 650,
        width: 900,
        beforeLoad: function () {
            var this_input = $(this.element).parent().find("input[type=file]"),
                attr_name = this_input.attr("data-attr-name"),
                model = this_input.attr("id");

            this.href = 'crop_adjust.php?attr_name=' + attr_name + '&id=' + getModelId();
            if ($("#relation_key").length > 0) {
                this.href += '&relation_key=' + $("#relation_key").val();
            }
        },
        beforeClose: function () {
            var crop_result_image_filename = $('.fancybox-iframe').contents().find('#result-image').attr("data-filename"),
                preview_image_path = $(this.element)
                .siblings('input[type=file]')
                .attr("data-preview-image-path");

            $(this.element && crop_result_image_filename != undefined && crop_result_image_filename != "")
                .siblings('.imageInputPreview')
                .attr("src", "/" + preview_image_path + "/" + crop_result_image_filename);
        }
    });

    /*
     * Get the model, that's being edited, id
     */
    function getModelId() {
        var model_name = $("form.moduleBuilder").attr("data-model-name").replace(/[\\\\']/g, '\\$&'),
            model_id = $("#" + model_name + "\\[id\\]").val();
        return model_id;
    }

    $('#mbCropAdjust').Jcrop({
        onChange: updatePreview,
        onSelect: updatePreview,
        aspectRatio: $('#aspectratio').val(),
        boxWidth: 395,
        boxHeight: 295,
    });

    function updatePreview(c) {
        $('#jcropW').val(c.w);
        $('#jcropH').val(c.h);
        $('#jcropX').val(c.x);
        $('#jcropY').val(c.y);
    };

    $("input.closeFancybox").on("click", function () {
        parent.$.fancybox.close();
    });

    $("#image_cms_images_size").on("change", function () {
        this.form.submit();
    });

});
