function pagedataInit(dom_scope) {
    var scopeSelector = dom_scope;

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

    var $scope = $(scopeSelector);

    if ($scope.length === 0) {
        if (scopeSelector !== 'ul.pagedata-list') {
            $scope = $('ul.pagedata-list');
            if ($scope.length) {
                scopeSelector = 'ul.pagedata-list';
            }
        }

        if ($scope.length === 0) {
            console.warn('pagedataInit: scope not found', scopeSelector);
            return;
        }
    }

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

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

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

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

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

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

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

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

    $scope.find('input.fileUploadifive').each(function(index, el) {
        var raw_id = $(el).attr('id') || '',
            pagedata_id = raw_id.replace(/\[/g, '\\[').replace(/\]/g, '\\]'),
            legacy_queue = document.getElementById(raw_id + '[queue]'),
            queue_base = raw_id.replace(/[^A-Za-z0-9_-]+/g, '_'),
            queue_id = 'uploadifive_' + (queue_base || 'queue') + '_file',
            queue_selector = '#' + queue_id,
            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 (legacy_queue) {
            legacy_queue.parentNode.removeChild(legacy_queue);
        }

        if ($(queue_selector).length === 0) {
            $(el).after('<div id="' + queue_id + '" class="uploadifive-queue"></div>');
        }

        var fileUploadOptions = {
            '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_selector).html("");
            },
            'formData' : data,
            '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_selector).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_selector).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,
            queueID: queue_id
        };

        $(el).uploadifive(fileUploadOptions);
    });

    $scope.find('input.imageUploadifive').each(function(index, el) {
        var raw_id = $(el).attr('id') || '',
            pagedata_id = raw_id.replace(/\[/g, '\\[').replace(/\]/g, '\\]'),
            legacy_queue = document.getElementById(raw_id + '[queue]'),
            queue_base = raw_id.replace(/[^A-Za-z0-9_-]+/g, '_'),
            queue_id = 'uploadifive_' + (queue_base || 'queue') + '_image',
            queue_selector = '#' + queue_id,
            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 (legacy_queue) {
            legacy_queue.parentNode.removeChild(legacy_queue);
        }

        if ($(queue_selector).length === 0) {
            $(el).after('<div id="' + queue_id + '" class="uploadifive-queue"></div>');
        }

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

        var imageUploadOptions = {
            '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_selector).html("");
            },
            'formData' : data,
            '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_selector).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_selector).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,
            'overrideEvents' : ['onError'],
            queueID: queue_id
        };

        $(el).uploadifive(imageUploadOptions);
    });

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

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

    var crop_result_image_filename;
    $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);
        }
    });

    $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);
            }
        }
    });

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

    $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);

    });

    $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);
            },
        });

    });

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

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

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

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

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

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

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

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

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

    $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;
    });

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

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

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

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

    $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;
            }
            $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(scopeSelector);

    fieldsetToggles(scopeSelector);
    setUnsavedChangesOnPagedataFieldChanges(scopeSelector);

    //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?';
        }
    });
}
