function pagedataInit(dom_scope) {
    if ( typeof dom_scope === 'undefined' || dom_scope === false || dom_scope === "" || dom_scope === 0) {
        dom_scope = 'ul.pagedata-list';
    }

    $(dom_scope).find('.pagedata-copy-btn').on("click", function(event) {
        cmsPreventDefault(event);
        pagedataCopyBtn($(this));
        return false;
    });

    $(dom_scope).find('textarea.cmstinymce, textarea.tinymce, textarea.regularTinymce').each(function(index, el) {
        regularTinymce($(el));
    });

    $(dom_scope).find('textarea.tinymce_simple, textarea.simpleTinymce, textarea.simpletinymce').each(function(index, el) {
        simpleTinymce($(el));
    });

    $(dom_scope).find('textarea.customTinymce').each(function(index, el) {
        customTinymce($(el));
    });

    $(dom_scope).find('a.pagedataAltAnchor').on("click", function (event) {
        updatePagedataAlt($(this), event);
    });

    $(dom_scope).find('.tooltip').tooltip({
        show : false
    });

    $(dom_scope).find('.data-copy').tooltip({
        show : false
    });

    $(dom_scope).find('.data-copy').click(function(event) {
        selectText($(".ui-tooltip"));
    });

    $(dom_scope).find('input.fileUploadifive').each(function(index, el) {
        var pagedata_id = $(el).attr('id').replace(/\[/g, '\\[').replace(/\]/g, '\\]'),
            queue_id = false,
            file_container_id = pagedata_id + '\\[file_container\\]',
            list_item_data_id = $(el).attr('data-list-item-data-id'),
            list_item_data_value = $(el).attr('data-list-item-data-value'),
            data = {
            list_item_data_id : list_item_data_id,
            list_item_data_value : list_item_data_value,
            pagedata : {}
        };
        data.pagedata[list_item_data_id] = {
            'value' : list_item_data_value,
            'type' : 'file'
        };

        if ($("#" + pagedata_id + '\\[queue\\]').length > 0) {
            queue_id = pagedata_id + '\\[queue\\]';
        }

        $(el).uploadifive({
            'dnd' : true,
            'fileObjName' : 'pagedata',
            'buttonClass' : 'btn',
            'buttonText' : 'Choose File',
            'auto' : false,
            onUpload : function() {
                $("#uploadifive-pagedata\\[" + list_item_data_id + "\\]\\[new_file_value\\]").hide();
            },
            onCancel : function() {
                $("#uploadifive-pagedata\\[" + list_item_data_id + "\\]\\[new_file_value\\]").show();
                $("#" + queue_id).html("");
            },
            'formData' : data,
            'queueID' : queue_id,
            'multi' : false,
            'simUploadLimit' : 1,
            'uploadScript' : 'ajax/uploadifive.php?type=file&page_id=' + getPageId("sandbox"),
            'onUploadComplete' : function(file, data) {
                setUnsavedChanges(true);
                $("#" + file_container_id).find(".file_link").attr("href", "/uploads/files/" + data);
                $("#uploadifive-pagedata\\[" + list_item_data_id + "\\]\\[new_file_value\\]").show();
                $("#" + queue_id).html("");
                $("#pagedata\\[" + list_item_data_id + "\\]\\[value\\]").val(data);
                $("#" + file_container_id).fadeIn();
                content_manager.unsaved_changes = true;
            },
            onAddQueueItem : function(file) {
                var pattern = new RegExp($(el).closest('.list-item-data-holder').find("input[name='mime']").val());
                //with some types uploadifive gets mime as empty string - we must not disqualify such files
                if (file.type == '' || pattern.test(file.type)) {
                    $(el).uploadifive('upload', file);
                } else {
                    $("#" + queue_id).html("");
                    $('#dialog').html('<p>If you want to add this file type to allowed types, please get in touch with mtc.</p>');
                    $('#dialog').dialog('option', 'width', '600px');
                    $('#dialog').dialog('option', 'title', 'File type "' + file.type + '" not alowed.');
                    $('#dialog').dialog('option', 'buttons', {
                        OK: function () {
                            $('#dialog').dialog('close');
                        }
                    });
                    $('#dialog').dialog('open');
                }
            },
            onError : function(error_type, response) {
                if (response.xhr.status == 415) {
                    response.queueItem.find('.fileinfo').html(' - File type "' + response.xhr.response + '" not alowed.');
                }
            },
            onProgress : uploadifiveProgressPercents
        });
    });

    $(dom_scope).find('input.imageUploadifive').each(function(index, el) {
        var pagedata_id = $(el).attr('id').replace(/\[/g, '\\[').replace(/\]/g, '\\]'),
            queue_id = false,
            image_container_id = pagedata_id + '\\[image_container\\]',
            list_item_data_id = $(el).attr('data-list-item-data-id'),
            list_item_data_value = $(el).attr('data-list-item-data-value'),
            data = {
                list_item_data_id : list_item_data_id,
                list_item_data_value : list_item_data_value,
                pagedata : {}
            };

        if ($("#" + pagedata_id + '\\[queue\\]').length > 0) {
            queue_id = pagedata_id + '\\[queue\\]';
        }

        data.pagedata[list_item_data_id] = {
            'value' : list_item_data_value,
            'type' : 'image'
        };

        $(el).uploadifive({
            'dnd' : true,
            'fileObjName' : 'pagedata',
            'buttonClass' : 'btn',
            'buttonText' : 'Choose File',
            'auto' : false,
            onUpload : function() {
                $("#uploadifive-pagedata\\[" + list_item_data_id + "\\]\\[new_file_value\\]").hide();
            },
            onCancel : function() {
                $("#uploadifive-pagedata\\[" + list_item_data_id + "\\]\\[new_file_value\\]").show();
                $("#" + queue_id).html("");
            },
            'formData' : data,
            'queueID' : queue_id,
            'multi' : false,
            'simUploadLimit' : 1,
            'uploadScript' : 'ajax/uploadifive.php?type=image&page_id=' + getPageId("sandbox"),
            onUploadComplete: function(file, data) {
                setUnsavedChanges(true);
                $("#pagedata-crop-anchor-id-" + list_item_data_id).show();
                $("#" + queue_id).html("");
                $("#" + image_container_id).find("img").attr("src", "/uploads/images/cms/small/" + data);
                $("#pagedata\\[" + list_item_data_id + "\\]\\[value\\]").val(data);
                $("#" + image_container_id).fadeIn();
                content_manager.unsaved_changes = true;
                loadPanelMessages();
            },
            onAddQueueItem : function(file) {
                var pattern = new RegExp($(el).closest('.list-item-data-holder').find("input[name='mime']").val());
                //with some types uploadifive gets mime as empty string - we must not disqualify such files
                if (file.type == '' || pattern.test(file.type)) {
                    $(el).uploadifive('upload', file);
                } else {
                    $("#" + queue_id).html("");
                    $('#dialog').html('<p>If you want to add this file type to allowed types, please get in touch with mtc.</p>');
                    $('#dialog').dialog('option', 'width', '600px');
                    $('#dialog').dialog('option', 'title', 'File type "' + file.type + '" not alowed.');
                    $('#dialog').dialog('option', 'buttons', {
                        OK: function () {
                            $('#dialog').dialog('close');
                        }
                    });
                    $('#dialog').dialog('open');
                }
            },
            onError : function(error_type, response) {
                if (response.xhr.status == 415) {
                    response.queueItem.find('.fileinfo').html(' - File type "' + response.xhr.response + '" not alowed.');
                }
            },
            onProgress : uploadifiveProgressPercents
        });
    });

    $(dom_scope).find('input.imageMUploadifive').each(function(index, el) {
        multiUploadifive(el, "image");
    });

    $(dom_scope).find('input.fileMUploadifive').each(function(index, el) {
        multiUploadifive(el, "file");
    });

    var crop_result_image_filename;
    $(dom_scope).find('.pagedata-crop-anchor').fancybox({
        type : 'iframe',
        fitToView : false,
        autoSize : false,
        height : 650,
        width : 900,
        beforeLoad: function() {
            var anchorEl = $(this.element),
                hiddenEl = anchorEl.siblings('.input_container').children('.real_file_value'),
                filename = hiddenEl.val(),
                plid_id = hiddenEl.attr('data-list-item-data-id');

            this.href = 'crop_adjust.php?page_list_item_data_id=' + plid_id + '&filename=' + filename;
        },
        beforeClose : function() {
            crop_result_image_filename = $('.fancybox-iframe').contents().find('#result-image').attr("data-filename");
            $(this.element).siblings('.input_container').children('.real_file_value').attr("value", crop_result_image_filename);
            $(this.element).siblings('.input_container').children('.image_container').find('img').attr("src", "/uploads/images/cms/small/" + crop_result_image_filename);
            setUnsavedChanges(true);
        }
    });

    $(dom_scope).find('.pagedata-settings label, .list-settings label, .pagedata-settings input, .list-settings input').on('click', function() {

        var input = $(this),
        children;

        if (input.prop("tagName") === "LABEL") {
            input = $(this).next();
        }

        if (input.attr('type') === "text" || input.prop("tagName") === "SELECT") {
            if (input.css('width') !== "135px") {

                children = $(this).parent().children('input[type="text"],select');

                $.each(children, function(index, val) {
                    $(this).css('width', '10px');
                });

                input.animate({
                    'width' : '135px'
                }, 80);
            }
        }
    });

    $(dom_scope).find('input.datetime').each(function(index, el) {
        datetimeInput($(el));
    });

    $(dom_scope).find('input.coordinates').each(function(index, el) {

        var clear_button = $('<span class="clearCoordinates fa fa-close"></span>'),
            toggle_clear_button = function () {
                if ( $(el).val() === '' ) {
                    clear_button.hide();
                } else {
                    clear_button.show();
                }
            };
        $(el).parent().append(clear_button);
        clear_button.on('click', function () {
            $(el).val('');
            clear_button.hide();
        });

        toggle_clear_button();
        $(el).on('change', toggle_clear_button);

        $(el).addClass('coordinates-' + index);

        $.coordinate_picker[($(el).attr('id'))] = {
            settings : {}
        };

        var coordinates_settings = {
            input : $(el),
            // Form input element selector for latitude
            lat_selector : 'input.coordinates-' + index,

            // Form input element selector for latitude
            long_selector : 'input.coordinates-' + index,

            starting_query : '78247' // address or zip code

        };

        $.fn.coordinate_picker = function(options) {

            var settings = {
                input : el,
                lat_selector : '#lat',
                long_selector : '#long',
                onComplete : function(){
                    setUnsavedChanges(true);
                    clear_button.show();
                },
                starting_query : null,
                path_to_map_php : '/admin/js/libs/coordinate_picker/'
            };

            if (options) {
                $.extend(settings, options);
            }

            $.coordinate_picker[($(el).attr('id'))].settings = settings;

            return $(el).each(function() {
                var $el = $(el);
                $el.click(function(e) {
                    e.preventDefault();
                    $.smodal({
                        src : settings.path_to_map_php + 'map.php?input=' + settings.input.attr('id'),
                        width : 700,
                        height : 500,
                        input : el
                    }).open();
                });
            });

        };

        $('input.coordinates-' + index).coordinate_picker(coordinates_settings);

    });

    $(dom_scope).find('input.colorpicker').each(function(index, el) {

        $(el).addClass('colorpicker-' + index);
        $(el).prop('readonly', true);
        $(el).ColorPicker({
            onChange: function (hsb, hex, rgb, el) {
                $(el).val("#" + hex);
                setUnsavedChanges(true);
            },
            onSubmit: function(hsb, hex, rgb, el) {
                $(el).val("#" + hex);
                $(el).ColorPickerHide();
                setUnsavedChanges(true);
            },
            onBeforeShow: function () {
                var temp = this.value.replace('#','');
                $(this).ColorPickerSetColor(temp);
            },
        });

    });

    $(dom_scope).find('.hint').hover(function() {
        $(this).find(".text").delay(400).fadeIn(200);
    }, function() {
        $(this).find(".text").stop(true, true).delay(200).fadeOut(100);
    });

    pagedataListItemDragAndDrop($(dom_scope).find('.sortable-item-list'));
    pagedataListDragAndDrop($('ul.pagedata-list'));

    $(dom_scope).find('.add-new-list-item-btn-anchor').on("click", function(event) {
        cmsPreventDefault(event);
        addNewListItem($(this));
        return false;
    });

    $(dom_scope).find('.save-list-item-data-settings').on("click", function(event) {
        cmsPreventDefault(event);
        saveListItemDataSettings($(this));
        return false;
    });

    $(dom_scope).find('.save-list-settings').on("click", function(event) {
        cmsPreventDefault(event);
        saveListSettings($(this));
        return false;
    });

    $(dom_scope).find('.remove-item-btn').on("click", function(event) {
        cmsPreventDefault(event);
        deleteListItem($(this));
        return false;
    });

    $(dom_scope).find('.move-item-btn').on("click", function(event) {
        cmsPreventDefault(event);
        moveListItem($(this));
        return false;
    });

    $(dom_scope).find(".list-lock-btn").on('click', function(event) {
        cmsPreventDefault(event);
        listLockBtn($(this));
        return false;
    });

    $(dom_scope).find('.list-change-more-text-btn').on('click', function(event) {
        cmsPreventDefault(event);
        listChangeMoreTextBtn($(this));
        return false;
    });

    $(dom_scope).find(".list-item-data-lock-btn").on('click', function(event) {
        cmsPreventDefault(event);
        listItemDataLock($(this));
        return false;
    });

    $(".list-item-data-delete-btn").on('click', function(event) {
        cmsPreventDefault(event);
        listItemDataDelete($(this));
        return false;
    });

    $(".list-delete-btn").on('click', function(event) {
        cmsPreventDefault(event);
        listDelete($(this));
        return false;
    });

    $(dom_scope).find('.pagedata-settings-btn').on("click", function(event) {
        cmsPreventDefault(event);
        togglePagedataSettings($(this));
        return false;
    });

    $(dom_scope).find('.list-settings-btn').on("click", function(event) {
        cmsPreventDefault(event);
        toggleListSettings($(this));
        return false;
    });

    $(dom_scope).find('.delete-image-btn').on("click", function(event) {
        cmsPreventDefault(event);
        deleteImage($(this));
        return false;
    });

    $(dom_scope).find('.delete-file-btn').on("click", function(event) {
        cmsPreventDefault(event);
        deleteFile($(this));
        return false;
    });

    $(dom_scope).find(".cmsPanelTagsInput").each(function () {
        var params = "?tag_pagedata_name=" + $(this).siblings("label").children("span").html();
        params += "&page_id=" + getPageId("sandbox");
        $(this).autocomplete({
            source: "ajax/tags_json.php" + params,
            minLength: 0
        });

        $(this).on("blur", function () {
            var value = $(this).val(),
                blurred_input = $(this);
            if (value === "") {
                return;
            }
            $(dom_scope).find(".cmsPanelTagsInput").each(function () {
                if ($(this).val() === value && $(this).attr("data-list-item-data-id") !== $(blurred_input).attr("data-list-item-data-id")) {
                    var list_item_remove_btn = $(this).closest("div.list-item").find(".remove-item-btn");
                    deleteListItem($(list_item_remove_btn));
                }
            });

        });
        $(this).attr("title", $(this).val());
        $(this).on("change", function () {
            $(this).attr("title", $(this).val());
        });
        $(this).tooltip({
            show: false
        });

    });

    pagedataInitCustom(dom_scope);

    fieldsetToggles(dom_scope);
    setUnsavedChangesOnPagedataFieldChanges(dom_scope);

    //alert if unsaved content present
    $(window).on('beforeunload', function () {
        "use strict";
        if (content_manager.unsaved_changes === true) {
            return 'Are you sure you want to leave?';
        }
    });
}
