/*
 *************************************
 JMUERY SCRIPT FOR MARLEV TEMPLATE MANAGER - LAYOUT ADMIN PANEL JOOMLA TEMPLATE
 *************************************
 Copyright http://marlev.it
 *************************************
 GPL License
 *************************************
 */

jQuery.loadlayout = function loadlayout(element) {


    jQuery.ajax({
        url: jQuery(location).attr('href'),
        dataType: "html",
        type: 'POST',
        cache: false,
        data: {loadlayout: 1},
        success: function (data) {
            //  var response = data;

            var responseval = jQuery(data).filter('#loadlayout');

            jQuery("#tm-layout").html(responseval).promise().done(function () {
                jQuery("#tm-layout").find("#avvaiable_positions_multi").chosen({"search": true});
                jQuery("#tm-layout").find(".edit-options").on("hover", function () {
                    jQuery.assign_functions_on_edit_click(jQuery(this));
                });

                jQuery.coldelete();
                jQuery.addposition();
                jQuery.suspend_positions();
                jQuery.width_large();
                //    
                jQuery.config_layout_slider(".edit-options", ".close-slider");
                jQuery.lift_scroll();



                jQuery.submit_form();

                //salva la configurazione esistente subito dopo installazione dle template
                if (jQuery(".install-layout").length) {
                    setTimeout(function () {
                        jQuery(".ml-apply").addClass("working").promise().done(function () {
                            jQuery(".ml-apply").click();
                            jQuery(".ml-apply").removeClass("working");
                            jQuery("#ultimateinstall").val(0);
                        });
                    }, 2000);


                }

                jQuery.show_alert_message();
                jQuery("#waitbox").remove();
                jQuery.append_tabscript(data);

            });

        }
    });
};


jQuery.assign_functions_on_edit_click = function assign_functions_on_edit_click(element) {

    if (!jQuery(element).hasClass("func-assigned")) {
        jQuery(element).addClass("func-assigned");
        var id = jQuery(element).data("configid");

        //assegnazione al cambio col
        jQuery(jQuery(id).find(".colchange")).on("change", function () {
            jQuery.colchange(jQuery(this));
        });
        //assegnazione di colmove
        jQuery(jQuery(id).find(".colmove")).on("change", function () {
            jQuery.colmove(jQuery(this));
        });

        //assegnazione di addclear after position
        jQuery(jQuery(id).find(".addclear")).on("click", function () {
            jQuery.addclear_after_position(jQuery(this));
        });
        //seleziona background

        jQuery.choise_background(jQuery(id).find(".background-type"));
        jQuery(jQuery(id).find(".background-type")).on("change", function () {
            jQuery.choise_background(jQuery(this));
        });
        jQuery(jQuery(id).find(".change-config-view")).on("change", function () {
            jQuery.changeDeviceConfig_checkbox(jQuery(this));
        });


        jQuery(id).find(".minicolors").each(function () {
            if (jQuery(this).hasClass("rgb-color")) {
                jQuery(this).minicolors({theme: "bootstrap", opacity: true, control: 'hue', format: 'rgb'});
            } else {
                jQuery(this).minicolors({theme: "bootstrap"});
            }
        });

        ///funzioni per copia di configurazioni
        jQuery(id).find('.copy-actions .btn').on("click", function (e) {
            e.preventDefault();
            jQuery.show_actions_copy_tool(jQuery(this));

        });
        jQuery(id).find(".transfer-config").on("change", function () {
            jQuery.select_device_tocopy_checkbox(jQuery(this));
        });

        jQuery(id).find('.copy-config-now').on("click", function (e) {
            e.preventDefault();
            jQuery.copy_config_now(jQuery(this));
        });

        jQuery(jQuery(id).find(".copy-params-device")).on("click", function () {
            jQuery.copydevicesconfig_checkbox(jQuery(this));
        });
        //fine per la copia di configurazioni

//        jQuery(id).find(".hasTooltip").each(function(){
//            jQuery(this).tooltip({"html": true, "container": "body"});
//        });
        jQuery(id).find(".hasPopover").each(function () {
            jQuery(this).popover({"html": true, "trigger": "hover focus", "container": "#layout-slider-block", "position": "top"});
        });

        //run media
        jQuery(id).find('.field-media-marlev').fieldMedia();

        jQuery(jQuery(id).find('.field-media-marlev .button-select')).on("click", function () {
            jQuery.fix_ovverflow_image_select(jQuery(this));
        });



    }
};
jQuery.fix_ovverflow_image_select = function fix_ovverflow_image_select(element) {
    jQuery(element).parents("#layout-slider-block").css({"overflow": "visible"});
    setTimeout(function () {
        var call_modal = setInterval(function () {
            if (!jQuery(element).parents(".field-media-marlev").find(".modal").hasClass("in")) {
                jQuery(element).parents("#layout-slider-block").css({"overflow": "auto"});
                clearInterval(call_modal);
            }
        }, 500);

    }, 800);

};

jQuery.append_tabscript = function append_tabscript(data) {
    var get_script = /<script>([\s\S]*?)<\/script>/gm;
    var match;
    while (match = get_script.exec(data)) {
        jQuery('head').append('<script>' + match[1] + '</script>');
    }
    // alert(match[1])
};



jQuery.recount_exist_positions = function recount_exist_pos(parent, element) {

    var parentid = jQuery(parent).attr("id");

    var find_defcollayout_input = "#" + parentid + '-defcollayout';
    var find_tabcollayout_input = "#" + parentid + '-tabcollayout';
    var find_mobcollayout_input = "#" + parentid + '-mobcollayout';
    var find_positions_input = "#" + parentid + '-positions';
    jQuery(find_defcollayout_input).val("");
    jQuery(find_tabcollayout_input).val("");
    jQuery(find_mobcollayout_input).val("");
    jQuery(find_positions_input).val("");

    jQuery(parent).find(element).each(function () {
        var defcollayout = jQuery(find_defcollayout_input).val();
        var tabcollayout = jQuery(find_tabcollayout_input).val();
        var mobcollayout = jQuery(find_mobcollayout_input).val();
        var getpos = jQuery(find_positions_input).val();
        var pc = jQuery(this).data("pc");
        var mobile = jQuery(this).data("mobile");
        var tablet = jQuery(this).data("tablet");
        var position = jQuery(this).data("position");

        if (defcollayout == '') {
            jQuery(find_defcollayout_input).val(pc);
            jQuery(find_tabcollayout_input).val(tablet);
            jQuery(find_mobcollayout_input).val(mobile);
            jQuery(find_positions_input).val(position);
        } else {
            jQuery(find_defcollayout_input).val(defcollayout + "," + pc);
            jQuery(find_tabcollayout_input).val(tabcollayout + "," + tablet);
            jQuery(find_mobcollayout_input).val(mobcollayout + "," + mobile);
            jQuery(find_positions_input).val(getpos + "," + position);
        }
    });
};
//jQuery.colscount = function colscount(parentid, position_class) {
//    var count = 0;
//    jQuery(parentid).find(position_class).each(function () {
//        count = parseInt(jQuery(this).data("pc")) + count;
//
//    });
//
//    if (count > 12) {
//        jQuery(parentid).addClass("cols-warning");
//        var message = jQuery('#cols-warning').data('message');
//        if (!jQuery(parentid).find(".warning-message").length) {
//            jQuery(parentid).append('<div class="warning-message col-md-12 col-lg-12">' + message + '</div><div class="clearfix remove-clear"></div>');
//        }
//    } else {
//        jQuery(parentid).removeClass("cols-warning");
//        jQuery(parentid).find('.warning-message, .remove-clear').remove();
//    }
//    return count;
//};
jQuery.colchange = function colchange(element) {

    function remove_classes(element, type, parent_class) {
        //  var parent = jQuery(element).parents(position_class);
        for (var i = 1; i <= 12; i++) {
            if (type == "pc") {
                jQuery(parent_class).removeClass('col-md-' + i + ' col-lg-' + i);
            } else if (type == "tablet") {

                jQuery(parent_class).removeClass('col-sm-' + i);
            } else if (type == "mobile") {
                jQuery(parent_class).removeClass('col-xs-' + i);
            }
        }
    }

    function run_colsfunction(element, position_class, parent_class) {
        var thisval = jQuery(element).val();
        var type = jQuery(element).data("type");
        var parentid = '#' + jQuery(element).data("id");

        if (type == "pc") {
            jQuery(parent_class).data("pc", thisval);
            remove_classes(element, type, parent_class);
            jQuery(parent_class).addClass('col-md-' + thisval + ' col-lg-' + thisval);
            jQuery.recount_exist_positions(parentid, position_class);
            //var count = jQuery.colscount(parentid, position_class);
        } else if (type == "tablet") {
            jQuery(parent_class).data("tablet", thisval);
            remove_classes(element, type, parent_class);
            jQuery(parent_class).addClass('col-sm-' + thisval);
            jQuery.recount_exist_positions(parentid, position_class);


        } else if (type == "mobile") {
            jQuery(parent_class).data("mobile", thisval);
            remove_classes(element, type, parent_class);
            jQuery(parent_class).addClass('col-xs-' + thisval);
            jQuery.recount_exist_positions(parentid, position_class);
        }

    }


    function switch_col(element) {
        var parent_class = '.pos_' + jQuery(element).data('position');

        if (jQuery(parent_class).hasClass('subposition')) {

            var position_class = ".subposition";
            run_colsfunction(element, position_class, parent_class);
        } else {

            var position_class = ".innerposition";
            run_colsfunction(element, position_class, parent_class);

        }
    }



//    function change_col() {
//        jQuery(".colchange").change(function () {
//            switch_col(this);
//        });
//    }

    switch_col(element);
};

jQuery.coldelete = function coldelete() {
    function remove_option_from_select_avvaiable_positions(position_class) {
        var position = jQuery(position_class).data("position");
        var remove = '#editconfig-' + position;
        jQuery("#avvaiable_positions_multi").find("option").each(function () {
            if (this.value == remove) {
                jQuery(this).remove();
            }
        });
        jQuery("#params_socialpositions").find("option").each(function () {
            if (this.value == position) {
                jQuery(this).remove();
            }
        });
        jQuery("#avvaiable_positions_multi").trigger("liszt:updated");
        jQuery("#params_socialpositions").trigger("liszt:updated");

    }
    function close_slider_if_deleted_option_in(position_class) {
        var deletedit = '#configid-' + jQuery(position_class).data("position");
        if (jQuery("#layout-slider-block").find(deletedit).length) {
            jQuery(deletedit).find(".close-slider").click();

        }
    }

    function run_delete(element, position_class) {
        jQuery(element).tooltip('hide');
        var position = jQuery(element).parents(position_class).data("position");
        jQuery("#edit-" + position).find(".addclear").each(function () {
            jQuery(this).attr('checked', false);
            jQuery.addclear_after_position(jQuery(this));
        });
        jQuery(element).parents(position_class).remove();
        jQuery.colchange(element);
    }
    function delete_col(position_class) {
        jQuery(position_class).find(".icon-cancel").click(function () {
            close_slider_if_deleted_option_in(jQuery(this).parents(position_class));
            var parentid = '#' + jQuery(this).parents(".position").attr("id");
            run_delete(this, position_class);
            remove_option_from_select_avvaiable_positions(jQuery(this).parents(position_class));
            jQuery.recount_exist_positions(parentid, position_class);
        });
    }
    function delete_col_subposition(position_class) {
        jQuery(position_class).find(".icon-cancel").click(function () {
            if (!jQuery(this).closest(".innerposition").length) {
                close_slider_if_deleted_option_in(jQuery(this).parents(position_class));
                var parentid = '#' + jQuery(this).parents(".position").attr("id");
                run_delete(this, position_class);
                remove_option_from_select_avvaiable_positions(jQuery(this).parents(position_class));
                jQuery.recount_exist_positions(parentid, position_class);
            }
        });
    }
    delete_col_subposition('.subposition');
    delete_col('.innerposition');
};

jQuery.addposition = function addposition() {
    function find_prev_numeric_position(parent, get_positions, get_cols) {
        for (var i = 1; i <= get_cols; i++) {

            if (!jQuery(parent).find('.pos_' + get_positions + '-' + i).length) {
                var make_prev = i - 1;
                if (make_prev == 0) {
                    return  ['prima', get_positions + '-' + i];

                } else {
                    return ['.pos_' + get_positions + '-' + make_prev, get_positions + '-' + i];
                }
            }
        }
        return false;
    }
    function find_prev_text_position(parent, positions) {
        var prev_position = false;
        jQuery.each(positions, function (index, value) {

            if (!jQuery(parent).find('.pos_' + value).length) {

                if (index == 0) {

                    prev_position = ['prima', value];
                } else {
                    var make_prev = index - 1;
                    prev_position = ['.pos_' + positions[make_prev], value];
                }
                return prev_position;
            }
        });
        return prev_position;
    }
    function check_if_clear_enabled_for_insert_position(responseval, prev_position) {
        if (jQuery(prev_position).next().hasClass("end-position")) {
            responseval.insertAfter(prev_position);
        } else {
            var nn = jQuery(prev_position).nextAll();
            jQuery(nn).each(function () {
                if (jQuery(this).hasClass("clearfix") && jQuery(this).hasClass("end-position")) {
                    responseval.insertBefore(jQuery(this));
                    return false;
                } else if (!jQuery(this).hasClass("clearfix")) {
                    responseval.insertBefore(jQuery(this));
                    return false;
                }

            });

        }


    }
    function add_as_option_to_select_avvaiable_positions(position) {
        jQuery("#avvaiable_positions_multi").prepend(jQuery('<option>', {
            value: '#editconfig-' + position,
            text: position
        })).trigger("liszt:updated");

        jQuery("#params_socialpositions").prepend(jQuery('<option>', {
            value: position,
            text: position
        })).trigger("liszt:updated");

    }

    function load_position(element, sendposition, sendclass, sendparentid, divclass, prev_this_class, parentid) {

        jQuery.ajax({
            url: jQuery(location).attr('href'),
            dataType: "html",
            type: 'GET',
            cache: false,
            data: {loadposition: 1, position: sendposition, loadclass: sendclass, parentid: sendparentid, blockclass: divclass},
            success: function (data) {
                //  var response = data;

                var responseval = jQuery(data).filter('#load_' + sendposition);

                //  jQuery(parentid).html(responseval);
                var inafter = jQuery(parentid).children(".add-position-block");
                if (prev_this_class[0] == "prima") {

                    responseval.insertAfter(inafter);
                } else {
                    if (jQuery(prev_this_class[0]).length) {
                        check_if_clear_enabled_for_insert_position(responseval, prev_this_class[0])

                    } else {
                        responseval.insertAfter(inafter);
                    }
                }
                jQuery('#load_' + sendposition).find(".show-position").addClass("pos-just-added");
                setTimeout(function () {
                    jQuery('#load_' + sendposition).find(".show-position").addClass("pos-just-added-remove");
                }, 700);
                setTimeout(function () {
                    jQuery('#load_' + sendposition).find(".show-position").removeClass("pos-just-added-remove pos-just-added");
                }, 1700);

                jQuery('#load_' + sendposition).find(".edit-options").on("hover", function () {
                    jQuery.assign_functions_on_edit_click(jQuery(this));
                });

                add_as_option_to_select_avvaiable_positions(sendposition);

                jQuery.coldelete();

                jQuery.config_layout_slider(jQuery('#load_' + sendposition).find(".edit-options"), jQuery('#load_' + sendposition).find(".close-slider"));
                //end new












                jQuery.append_tabscript(data);
//                var ul = jQuery("#myTab" + sendposition + "Tabs");
//                jQuery('#load_' + sendposition).find(".tab-pane").each(function () {
//                    var params = jQuery(this).find(".params-block");
//                    var type = params.data("type");
//                    var active = params.data("active");
//                    var id = jQuery(this).attr("id");
//                    jQuery(ul).append(jQuery("<li class=\"" + active + "\"><a href=\"#" + id + "\" data-toggle=\"tab\">" + type + "<\/a><\/li>"));
//                });

                //     jQuery('#load_' + sendposition).on('click', jQuery.coldelete());
                //     jQuery('#load_' + sendposition).on('click', jQuery.colchange());
                //    jQuery('#load_' + sendposition).on('click', jQuery.colmove());
                //     jQuery('#load_' + sendposition).on('click', jQuery.run_colors_images_script());

                //  jQuery("body").delegate( jQuery('#load_' + sendposition).find(".edit-options"),"click", jQuery.config_layout_slider());
                //close-slider
                //jQuery.config_layout_slider();
                //      jQuery('#load_' + sendposition).find(".edit-options").on('click', jQuery.jQuery.config_layout_slider());
                //       jQuery('#load_' + sendposition).on('click', jQuery.addclear_after_position());
                //jQuery.addclear_after_position
                // jQuery.run_colors_images_script();
                jQuery.recount_exist_positions(parentid, '.' + divclass);
                //    jQuery.config_layout_slider(jQuery('#load_' + sendposition));
                // jQuery('#load_' + sendposition).find(".edit-options").on('click', jQuery.config_layout_slider());
                jQuery(element).removeClass("workinng");
            }
        });
    }
    jQuery(".add-position").click(function () {
        if (jQuery(this).hasClass("workinng")) {
            return;
        } else {
            jQuery(this).addClass("workinng");
        }
        var get_positions = jQuery(this).data('positions');
        var parent = jQuery(this).data('id')
        var parentid = "#" + parent;
        var get_maxcols = jQuery(this).data('maxcols');


        var get_class = jQuery(this).data('class');
//        var response = false;
        var prev_this_class = false
        if (get_maxcols > 1) {
            var prev_this_class = find_prev_numeric_position(parentid, get_positions, get_maxcols);

        } else {
            var positions = get_positions.toString().split(',');
            var maxcols = get_maxcols.toString().split(',');
            var prev_this_class = find_prev_text_position(parentid, positions);
        }

        if (prev_this_class == false) {
            var message = jQuery("#all-positions_added").data("message");

            alert(message);
            jQuery(this).removeClass("workinng");
            return;
        }
        var fix_parent = parent.replace("pos_", "");
        var loadposition = load_position(this, prev_this_class[1], 'pos_' + prev_this_class[1], fix_parent, get_class, prev_this_class, parentid);

    });
};
jQuery.suspend_positions = function suspend_positions() {
    jQuery(".suspend-position").click(function () {
        var parent = '#' + jQuery(this).data('id');
        if (jQuery(this).prop('checked')) {
            jQuery(parent).addClass("pos_suspended");

        } else {
            jQuery(parent).removeClass("pos_suspended");
        }
    });
};
jQuery.width_large = function width_large() {
    jQuery(".inlarge-click").click(function () {
        var parentid = '#' + jQuery(this).data('id');
        var parentinput = '#' + jQuery(this).data('inputid');
        var actual = jQuery(this).data('actual');
        if (actual == "container") {
            var value = "container-fluid";
        } else {
            var value = "container";
        }
        jQuery(parentid).removeClass(actual).addClass(value);
        jQuery(this).data('actual', value);
        jQuery(parentinput).val(value);

    });
};
jQuery.colmove = function colmove(element) {
    function remove_classes(movemode, type, thisclass) {
        //  var parent = jQuery(element).parents(position_class);
        for (var i = 0; i <= 12; i++) {
            if (type == "pc") {
                jQuery(thisclass).removeClass('col-md-' + movemode + '-' + i + ' col-lg-' + movemode + '-' + i);
            } else if (type == "tablet") {

                jQuery(thisclass).removeClass('col-sm-' + movemode + '-' + i);
            } else if (type == "mobile") {
                jQuery(thisclass).removeClass('col-xs-' + movemode + '-' + i);
            }
        }
    }

    function run_move(element) {
        var type = jQuery(element).data("type");
        var position = ".pos_" + jQuery(element).data("position");
        var movemode = jQuery(element).data("move");
        var value = jQuery(element).val();
        remove_classes(movemode, type, position);
        if (value != "") {
            jQuery(position).addClass(value);
        }

    }

//    function change_col() {
//        jQuery(".colmove").change(function () {
//            run_move(this);
//        });
//    }
//
//
//    function onload_col() {
//        jQuery(".colmove").each(function () {
//            run_move(this);
//        });
//    }
    run_move(element);
    // change_col();
    //  onload_col();
};
jQuery.choise_background = function choise_backgrounds(element) {

    var value = jQuery(element).val();

    var parent = jQuery(element).parents(".params-block");

    if (value == "") {
        jQuery(parent).find(".colors-box, .image-box").hide();
    } else if (value == "color") {
        jQuery(parent).find(".colors-box").show();
        jQuery(parent).find(".image-box").hide();
    } else if (value == "image") {
        jQuery(parent).find(".colors-box").hide();
        jQuery(parent).find(".image-box").show();
    }
};

//jQuery.change_this = function change_this() {



//    function show_hide_background(element) {
//
//        var value = element.val();
//        var parent = element.parents(".params-block");
//
//        if (value == "") {
//            jQuery(parent).find(".colors-box, .image-box").hide();
//        } else if (value == "color") {
//            jQuery(parent).find(".colors-box").show();
//            jQuery(parent).find(".image-box").hide();
//        } else if (value == "image") {
//            jQuery(parent).find(".colors-box").hide();
//            jQuery(parent).find(".image-box").show();
//        }
//    }
//    ;
//    jQuery(".background-type").change(function () {
//        show_hide_background(jQuery(this));
//    });


//    jQuery(".edit-options").click(function () {
//
//        if (!jQuery(this).hasClass("elaborato")) {
//            jQuery(this).addClass("elaborato");
//            var id = jQuery(this).data("configid");
//            var element = jQuery(id).find(".background-type");
//            show_hide_background(element);
//            jQuery(jQuery(id).find(".colchange")).on("change", function () {
//                jQuery.colchange(jQuery(this));
//            });
//
//        }
//    });


//funzioni servono per popup di selezione immagine e coretta visualizzazione di z-index di loadlayout
//    jQuery(".closeimg").click(function () {
//        jQuery(this).parents(".field-media-marlev").find(".modal").modal('hide');
//        jQuery("#loadlayout").css({"z-index": 9999});
//
//    });
//    jQuery(".button-select").click(function () {//button image select
//        jQuery("#loadlayout").css({"z-index": 9});
//        var element = this;
//        var define_interval = setInterval(function () {
//            var button = jQuery(element).parents(".field-media-marlev").find("iframe").contents();
//            if (jQuery(button).length) {
//                jQuery(button.find(".btn-success")).attr("onclick", "window.parent.jQuery('#loadlayout').css({'z-index':9999});");
//                jQuery(button.find(".button-cancel")).attr("onclick", "window.parent.jQuery('.modal.in').modal('hide'); window.parent.jQuery('#loadlayout').css({'z-index':9999});");
//
//                clearInterval(define_interval);
//            }
//        }, 100);
//
//    });
//};

//jQuery.find_frame_image_choise = function find_frame_image_choise(element) {
//
//    if (jQuery(element).parents(".field-media-marlev").find("iframe").contents().find(".button-cancel").length) {
//        clearInterval(define_interval);
//    }
//
//};



jQuery.addclear_after_position = function addclear_after_position(element) {

    /// jQuery(".addclear").click(function () {
    var device = jQuery(element).data("device");
    var position = jQuery(element).data("position");
    if (jQuery(element).is(':checked')) {
        var el_class = '.pos_' + position;
        switch (device) {
            case "pc":
                var clear = 'visible-md-block visible-lg-block';
                break;
            case "tablet":
                var clear = 'visible-sm-block';
                break;
            case "mobile":
                var clear = 'visible-xs-block';
                break;

        }
        jQuery(el_class).after('<div id="clear-' + device + '-' + position + '" class="clearfix ' + clear + '"></div>');
    } else {
        var el_id = '#clear-' + device + '-' + position
        jQuery(el_id).remove();
    }
    //   });

};


jQuery.config_layout_slider = function config_layout_slider(openslider, closeslider) {
//    function run_minicolors(element) {
//        if (jQuery(element).find(".minicolors-theme-bootstrap").length) {
//            return;
//        }
//        jQuery(element).find(".minicolors").minicolors({theme: "bootstrap"});
//    }

    function open_slider(slider_width) {
        var w_width = jQuery(window).width();
        var loadlayout_width = w_width - slider_width - 10;
        var spzio_left = w_width - jQuery("#loadlayout").width();
        var offset_left = jQuery("#loadlayout").offset().left;
        var load_width = jQuery("#loadlayout").width();
        //    jQuery("#loadlayout").css({'position': 'absolute', left: offset_left, "width": load_width});
        var run_minimize_loadlayout = setInterval(function () {
            var layoutsilder_offset_left = jQuery("#layout-slider-block").offset().left;
            var rimanenza = spzio_left - slider_width - 30;
            if (rimanenza <= layoutsilder_offset_left) {
                jQuery("#loadlayout").animate({"width": loadlayout_width, "right": 0}, 350).css({'position': 'absolute'});
                //    jQuery("#loadlayout").css({"position": 'absolute', "left": slider_width, "width": loadlayout_width});
                clearInterval(run_minimize_loadlayout);
            }
        }, 1);
        jQuery("#layout-slider-block").show("slide", {direction: "left"}, 700).data("state", "open");
        //      jQuery("#layout-slider-block").animate({"marginLeft": 0}, 500).data("state", "open");

    }

    function close_slider(content_modified, parentid) {
        jQuery("#loadlayout").animate({"width": jQuery(".tm-home").width() - 15, "marginRight": 15}, 400).promise().done(function () {
            //   jQuery("#loadlayout").animate({"marginRight": 15}, 350).promise().done(function(){
            jQuery("#loadlayout").removeAttr("style");
            // });
        });
        setTimeout(function () {
            jQuery.run_fixed_menu();
        }, 700);
        jQuery("#layout-slider-block").toggle("slide", {direction: "left"}, 700).promise().done(function () {
            jQuery(content_modified).hide();
            jQuery(content_modified).appendTo(parentid);
        });

        // jQuery("#loadlayout").css({"position": 'relative', "left": 'auto', "width": "auto"});
        jQuery("#layout-slider-block").data("state", "close");

    }

    function load_content_inslider(configid) {
        var state = jQuery("#layout-slider-block").data("state");
        if (state == "close") {
            //jQuery(configid).fadeIn(1200);
            jQuery(configid).appendTo("#load-slider-content").promise().done(function () {
                jQuery(configid).show();
            });
        } else {
            jQuery(configid).appendTo("#load-slider-content");
            jQuery(configid).fadeIn(1200);
        }
        jQuery("#avvaiable-positions-block").appendTo("#load-slider-content .positions-posto");


        // setTimeout(function () {
        // run_minicolors(configid);
        ///   jQuery(configid).find('.field-media-marlev').fieldMedia();
        jQuery(configid).find(".font").find("select").chosen();

        // },200);

    }
    function return_content_alposto(configid) {

        if (jQuery("#load-slider-content").find(".ml-configs").length) {

            var content_modified = jQuery("#load-slider-content").find(".ml-configs");

            var parentid = content_modified.data("parent");
            var get_parent_from_click = jQuery(configid).data("parent");

            if (get_parent_from_click == parentid) {
                close_slider(content_modified, parentid);

            } else {
                jQuery("#avvaiable_positions").appendTo("#avvaiable-positions-content");
                jQuery("#avvaiable_positions_multi").val("").trigger("liszt:updated");
                jQuery(content_modified).hide();
                jQuery(content_modified).appendTo(parentid).promise().done(function () {
                    load_content_inslider(configid);

                });


            }
        }

    }
    jQuery(closeslider).click(function () {
        var slider_width = jQuery("#layout-slider-block").data("width");
        var configid = "#" + jQuery("#layout-slider-block").find(".ml-configs").attr("id");

        return_content_alposto(configid, slider_width);
    });

    jQuery(openslider).click(function () {
        var configid = jQuery(this).data("configid");
        var state_slider = jQuery("#layout-slider-block").data("state");
        var slider_width = jQuery("#layout-slider-block").data("width");
        if (state_slider == "close") {
            load_content_inslider(configid);
            open_slider(slider_width);

        } else if (state_slider == "open") {

            return_content_alposto(configid, slider_width);

        }
        jQuery(".edit-options").stop();
    });




};

jQuery.layout_slider_onload = function open_config() {

    function height_of_slider() {
        var h = jQuery(window).height();
        jQuery("#layout-slider-block").css({"height": h});
        jQuery("#load-slider-content").css({"min-height": "110%"});
    }
    function width_of_slider() {
        var w = jQuery(window).width();
        var state = jQuery("#layout-slider-block").data("state");

//        if (w <= 992) {
//            var new_w = -w;
//            if (state === "open") {
//                new_w = 0;
//            }
//            jQuery("#layout-slider-block").css({"width": '100%', 'marginLeft': new_w}).data("width", w);
//        } else {
        var w = jQuery("#layout-slider-block").width();
        var new_w = -w;
        if (state === "open") {
            new_w = 0;
        }
        //   jQuery("#layout-slider-block").data("width", w);
        //  jQuery("#layout-slider-block").css({"width": w, 'marginLeft': new_w}).data("width", w);
        jQuery("#layout-slider-block").css({"width": w}).data("width", w);
        //  }
    }
    height_of_slider();
    width_of_slider()
    jQuery(window).resize(function () {
        height_of_slider();
        width_of_slider();

    });
};
jQuery.submit_form = function submit_form() {

    function savepresets(data) {
        var responseval = jQuery(data).find('.load-table');
        jQuery(responseval).find("tr").each(function () {
            var thisid = jQuery(this).attr("id");
            if (!jQuery('#presets-block').find("#" + thisid).length) {

                jQuery("#presets-block").find(".load-table").prepend(jQuery(this)).promise().done(function () {
                    var element = jQuery('#presets-block').find("#" + thisid);
                    jQuery.run_fixed_menu();
                    jQuery(jQuery(element).find(".tm-preset-action")).on("click", function () {
                        jQuery.presetsChecked();
                    });
                    jQuery(element).addClass("pos-just-added");
                    setTimeout(function () {
                        jQuery(element).addClass("pos-just-added-remove-presets");
                    }, 700);
                    setTimeout(function () {
                        jQuery(element).removeClass("pos-just-added-remove-presets pos-just-added");
                    }, 1700);
                });

            }
        });
    }
    function loadpresets(data) {

        if (jQuery(data).find('.reload-page').length) {
            /// var id = jQuery("#layout-id").val();
            var url = jQuery(location).attr('href') + '&task=template.reloadpresets';
            window.location.replace(url);
        }

    }
    function cancellpresets(data) {
        var responseval = jQuery(data).find('.load-table');
        jQuery(jQuery('#presets-block .load-table')).find("tr").each(function () {
            var thisid = jQuery(this).attr("id");
            if (!jQuery(responseval).find("#" + thisid).length) {

                jQuery(this).hide("fade", 800).promise().done(function () {
                    jQuery(this).remove().promise().done(function () {
                        jQuery.run_fixed_menu();
                    });
                });
            }
        });
    }

    function get_serialized(get_task) {
        if (get_task === "template.cancellpresets" || get_task === "template.loadpresets") {
            var s = jQuery("#presets-block").find('.load-table :input').serializeArray();
        } else {
            var editors_pages = ['#error-modules-config', '#offline-modules-config'];
            jQuery(editors_pages).each(function (key, value) {
                jQuery(value).find("iframe").each(function () {
                    var lang = jQuery(this).parents(".modules-config").data("lang");
                    if (value === '#error-modules-config') {
                        var ed = 'params_errortext_' + lang + '_';
                    } else {
                        var ed = 'params_offlinetext_' + lang + '_';
                    }
                    var content = tinymce.get(ed).getContent();

                    jQuery(this).parents(".modules-config").find("textarea").val(content);

                });
            });
//            jQuery("#error-modules-config").find("iframe").each(function () {
//                var lang = jQuery(this).parents(".modules-config").data("lang");
//                var ed = 'params_errortext_' + lang + '_';
//                var content = tinymce.get(ed).getContent();
//
//                jQuery(this).parents(".modules-config").find("textarea").val(content);
//
//            });
            var s = jQuery("#adminForm").serializeArray();
        }


        var out = '';
        jQuery.each(s, function (i, a) {
            if (a.value !== '') {
                out = out + '{{-|-}}' + a.name + '=' + a.value + '';
            }

        });


        return out;
    }
    jQuery('.ml-submit').click(function (e) {
        e.preventDefault();
        if (jQuery(this).hasClass("disabled")) {
            return;
        }
        var stored_text = jQuery(this).data("lang");
        var thisbutton = jQuery(this);
        var button_width = jQuery(this).outerWidth();
        //serve per non inserire immagine quando si salva la configurazione dopo installazione del template
        if (!jQuery(this).hasClass("working")) {
            var uri = jQuery("#ml-uri").val() + "components/com_tmarlevv2/images/spinner.gif";
            var load_image = '<img  src="' + uri + '" />';
            jQuery(this).css({"width": button_width}).html(load_image);
        }
        var get_task = jQuery(this).data("task");
        if (get_task === "template.cancel") {
            var redirect = jQuery("#ml-uri").val() + "index.php?option=com_templates";
            window.location.replace(redirect);
        }
        var out = get_serialized(get_task);


        var token = jQuery('#hidden-token').find("input").attr("name");

        jQuery.ajax({
            url: jQuery(location).attr('href') + '&' + token + '=1',
            dataType: "html",
            type: 'POST',
            cache: false,
            data: {task: get_task, postdata: out},
            success: function (data) {

                var responseval = jQuery(data).find('#system-message-container');

                jQuery(responseval).find(".alert").each(function () {
                    jQuery(this).hide();
                    jQuery(this).find(".close").removeAttr("data-dismiss");
                    jQuery(this).find(".alert-heading, .alert-message").removeAttr("class");
                    jQuery(this).appendTo("#alert-box").promise().done(function () {

                        jQuery.show_alert_message();

                    });
                });
                if (get_task === "template.apply" && !jQuery("#ml-save-fixed").hasClass("btns-closed")) {
                    jQuery(thisbutton).html("Saved");
                    setTimeout(function () {
                        jQuery(thisbutton).html(stored_text);
                    }, 1500);
                } else {
                    jQuery(thisbutton).html(stored_text);
                }
                if (get_task === "template.savepresets") {
                    setTimeout(function () {
                        savepresets(data);
                    }, 300);
                }
                if (get_task === "template.cancellpresets") {
                    setTimeout(function () {
                        cancellpresets(data);
                    }, 300);

                }
                if (get_task === "template.loadpresets") {
                    setTimeout(function () {
                        loadpresets(data);
                    }, 2500);

                }
                if (get_task === "template.apply") {
                    var yrminifier = jQuery(data).find('.tm-prestazioni').find(".tm-config");
                    // var yrminifier = jQuery(data).find('.tm-prestazioni');
                    jQuery(".yrminifier-config").html(yrminifier);
                    jQuery.create_tabs_script(yrminifier);
                    jQuery(".yrminifier-config").find("select").chosen();

                    jQuery(jQuery(".yrminifier-config").find(".radio").find("label")).on("click", function () {
                        jQuery.bootstrap_button_after_ajax(jQuery(this));
                    });
                    jQuery(".yrminifier-config").find(".radio").find("label").each(function () {
                        jQuery.bootstrap_button_after_ajax(jQuery(this));
                    });

                }


            }


        });

    });
};

//functon va richiamata dal metodo onchange in checkbox pc, tablet, mobile //segue devicetab
jQuery.changeDeviceConfig_checkbox = function changeDeviceConfig_checkbox(element) {
    var this_config = jQuery(element).data("configid");
    if (jQuery(element).is(':checked') && !jQuery(element).hasClass('checbox-checked')) {

        jQuery(element).addClass("working checbox-checked");
        jQuery(element).parents(".select-edit-device").find("input").each(function () {
            var get_config = "#" + jQuery(this).data("configid");
            if (!jQuery(this).hasClass("working")) {
                // alert(get_config)
                jQuery(this).attr("checked", false).removeClass("checbox-checked");
                ;
                //jQuery(get_config).hide("fade", 500);
                jQuery(get_config).hide();
            } else {
                // jQuery(get_config).show();
                jQuery(get_config).show("fade", 500);
            }
        });
        jQuery(element).removeClass("working");
    } else {

        jQuery(element).attr("checked", true);

    }
};

jQuery.show_actions_copy_tool = function show_actions_copy_tool(element) {
    function show_element(block, showit) {

        var h = jQuery(block).find(showit).height();

        jQuery(block).css({"height": 0, "display": "block"}).animate({"height": h}, 700);
        jQuery(block).find(showit).addClass("slideInDown animated").show();
        setTimeout(function () {
            jQuery(block).find(showit).removeClass("slideInDown animated");
        }, 700);

    }
    function hide_elements(block) {
        jQuery(block).animate({"height": 0}, 700).promise().done(function () {
            jQuery(block).removeAttr("style").hide();
        });
        jQuery(block).find(".for-positions, .for-all-device").addClass("slideOutDown animated");

        setTimeout(function () {
            jQuery(block).find(".for-positions, .for-all-device").hide().removeClass("slideOutDown animated");
        }, 700);
    }

    var block = jQuery(element).parents("#load-slider-content").find(".copy-actions-block");
    var type = jQuery(element).data("type");
    var block_state = jQuery(block).data("state");
    if (type === "copy") {
        var showit = ".for-all-device";
        var hideit = ".for-positions";
    } else {
        var showit = ".for-positions";
        var hideit = ".for-all-device";
    }

    if (block_state === "close") {
        show_element(block, showit);
        jQuery(block).data("opened", type).data("state", "open");

    } else if (block_state === "open") {
        var opened = jQuery(block).data("opened");
        if (opened === type) {
            hide_elements(block);
            jQuery(block).data("state", "close");

        } else {
            var h = jQuery(block).find(showit).height();
            jQuery(block).find(hideit).hide();
            jQuery(block).animate({"height": h}, 700);
            jQuery(block).find(showit).addClass("slideInDown animated").show();
            setTimeout(function () {
                jQuery(block).find(showit).removeClass("slideInDown animated");
            }, 700);
            jQuery(block).data("opened", type);
        }
    }

    jQuery(element).stop().off().on("click", function (e) {
        e.preventDefault();
        jQuery.show_actions_copy_tool(jQuery(element));
    });
};
//funzione per copia di configurazioni da una posizione ad altra
jQuery.select_device_tocopy_checkbox = function select_device_tocopy_checkbox(element) {
    var elpar = jQuery(element).parents(".select-device-tocopy");
    var type = jQuery(element).data("copy");

    if (type == "all") {
        jQuery(element).addClass("working");
        jQuery(elpar).find(".transfer-config").each(function () {
            if (!jQuery(this).hasClass("working")) {
                jQuery(this).attr("checked", false);
            }
        });
        jQuery(element).removeClass("working");
    } else {
        jQuery(elpar).find(".copy-all").attr("checked", false);
    }
};
jQuery.copy_config_now = function copy_config_now(element) {
    jQuery(element).parent().find(".element-message").remove();
    var elpar = jQuery(element).parents(".copy-actions-block");
    var tocopy = {};
    jQuery(elpar).find(".transfer-config").each(function () {
        if (jQuery(this).is(':checked')) {
            tocopy[jQuery(this).data("copy")] = true;
        }
    });
    if (jQuery.isEmptyObject(tocopy)) {
        var select_device_first = jQuery(element).data("selectdevicefrst");
        jQuery("<div class='element-message'>" + select_device_first + "</div>").insertAfter(element);
        return false;
    }
    var positions = jQuery("#avvaiable_positions_multi").val();
    if (positions === null) {
        var selectdestination_first = jQuery(element).data("selectdestination");
        jQuery("<div class='element-message'>" + selectdestination_first + "</div>").insertAfter(element);
        return false;
    }
    var ifall = 'all' in tocopy;
    if (ifall) {
        var tocopy = {pc: true, tablet: true, mobile: true};
    }
    var copyconfig = jQuery(element).data("copyconfig");
    jQuery.each(tocopy, function (key) {
        jQuery.each(positions, function (thisnull, transfer) {
            console.log("#" + copyconfig + "-" + key, transfer + "-" + key);
            jQuery.copy_configuration("#" + copyconfig + "-" + key, transfer + "-" + key);
        });

    });
    var eseguito = jQuery(element).data("eseguito");
    jQuery(element).parent().find(".element-message").remove();
    jQuery("<div class='element-message'>" + eseguito + "</div>").insertAfter(element);
    setTimeout(function () {
        jQuery(element).parent().find(".element-message").remove();
    }, 2000);

};
//funzione che esegue la copia stessa, usata in due funzioni
jQuery.copy_configuration = function copy_configuration(source, destination) {
    jQuery(source).find("input").each(function () {
        var identifier = "." + jQuery(this).parents(".controls").data("identifier");

        var value = jQuery(this).val();
        var element = jQuery(this);
        jQuery(destination).find(identifier).each(function () {
            var inp = jQuery(this).find("input");//minicolors
            //if checkbox
            if (jQuery(inp).parent().hasClass("checkbox")) {
                var checked = false;
                if (jQuery(element).is(":checked")) {
                    checked = true;
                }
                jQuery(inp).attr("checked", checked);
                if (jQuery(inp).hasClass("addclear")) {
                    jQuery.addclear_after_position(jQuery(inp));
                }
            } else {//altri input di tipo color, input normali
                jQuery(inp).val(value);
                if (jQuery(inp).hasClass("minicolors-input")) {
                    jQuery(inp).parents(".minicolors").find(".minicolors-swatch-color").css({"background-color": value});
                }
            }


        });
    });
    jQuery(source).find("select").each(function () {
        var identifier = "." + jQuery(this).parents(".controls").data("identifier");

        var getvalue = jQuery(this).val();

        jQuery(destination).find(identifier).each(function () {
            var inp = jQuery(this).find("select");//minicolors
            var exists_option = false;
            jQuery(inp).find("option").each(function () {
                if (this.value == getvalue) {
                    exists_option = true;
                }
            });
            if (exists_option === true) {
                jQuery(inp).val(getvalue);
                if (jQuery(inp).hasClass("background-type")) {
                    jQuery.choise_background(inp);
                } else if (jQuery(inp).hasClass("colchange")) {
                    jQuery.colchange(jQuery(inp));
                } else if (jQuery(inp).hasClass("colmove")) {
                    jQuery.colmove(jQuery(inp));
                }

            }

        });
    });
};

//funzione per copiare le configurazione di diveces, da quello selezionato ad altri
jQuery.copydevicesconfig_checkbox = function copydevicesconfig_checkbox(element) {
    function close_opration(element) {
        var label = jQuery(element).parent().find("label");
        var defaultlang = jQuery(label).data("default");
        var eseguito = jQuery(label).data("eseguito");
        var wlabel = jQuery(label).width();
        jQuery(label).css({"width": wlabel}).html(eseguito);
        setTimeout(function () {
            jQuery(label).removeAttr("style").html(defaultlang);
            jQuery(element).removeClass("working");
            jQuery(element).attr("checked", false);
        }, 1500);
    }
    function copy_data(element) {
        var content = jQuery(element).parents("#load-slider-content");
        var checkbox_block = jQuery(content).find(".select-edit-device");
        var selected;
        jQuery(checkbox_block).find("input").each(function () {

            if (jQuery(this).is(':checked')) {
                selected = jQuery(this).data("configid");

            }
        });
        jQuery.copy_configuration("#" + selected, "#load-slider-content");

    }


    if (jQuery(element).is(':checked') && !jQuery(element).hasClass('working')) {

        jQuery(element).addClass("working");
        copy_data(element);
        close_opration(element);
    }
};

jQuery.lift_scroll = function layout_lift_change() {

    function run(element) {
        jQuery(element).on("change", function () {
            var getid = "#" + jQuery(this).val();
            var goto = jQuery(getid).offset().top - 35;
            // alert(goto)
            jQuery("html, body").animate({scrollTop: goto}, 500);

        });
    }
    run(".layout-fast-navigate-section");
    run(".layout-fast-navigate-blocks");
};



jQuery(document).ready(function () {


    jQuery.loadlayout("#tm-layout");
    jQuery.layout_slider_onload();




});