
var cmsPreventDefault = function(event) {
    if(window.event)
    {
        window.event.returnValue = false;
    }
    else if(event.preventDefault)
    {
        event.preventDefault();
    }
    else
    {
        event.returnValue = false;
    }
};

/**
 * clone()
 * Properly copy an object
 * @param object object
 * @return object copied_object
 */
function clone(obj) {
    if(obj === null || typeof(obj) !== 'object' || 'isActiveClone' in obj)
        return obj;

    var temp = obj.constructor(); // changed

    for(var key in obj) {
        if(Object.prototype.hasOwnProperty.call(obj, key)) {
            obj['isActiveClone'] = null;
            temp[key] = clone(obj[key]);
            delete obj['isActiveClone'];
        }
    }

    return temp;
}

function toggleSlugField(el) {
    if ( $("#data\\[page\\]\\[slug\\]").hasClass('hide') ) {
        $("#data\\[page\\]\\[slug\\]").removeClass('hide');
        $("#data\\[page\\]\\[slug\\]").show();
        $(".toggle-slug-field-btn").hide();
        $("#page_url_link").hide();
    } else {
        $("#data\\[page\\]\\[slug\\]").addClass('hide');
        $("#data\\[page\\]\\[slug\\]").hide();
        $("#page_url_link").show();
    }
    return false;
}

function selectText(el) {
    var doc = document
        , text = doc.getElementById(el.attr('id'))
        , range, selection
    ;
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

function isLocalStorageQuotaExceeded(e) {
  var quotaExceeded = false;
  if (e) {
    if (e.code) {
      switch (e.code) {
        case 22:
          quotaExceeded = true;
          break;
        case 1014:
          // Firefox
          if (e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
            quotaExceeded = true;
          }
          break;
      }
    } else if (e.number === -2147024882) {
      // Internet Explorer 8
      quotaExceeded = true;
    }
  }
  return quotaExceeded;
}

function isInt(n){
    return Number(n)===n && n%1===0;
}

function anchorClickLoadPage(el, alert_showed) {
    "use strict";
    alert_showed = alert_showed || false;
    if (content_manager.unsaved_changes === true && alert_showed === false) {
        var title = "Confirmation!",
        text = "Are you sure you want to leave? All unsaved changes will be lost.";

        $('#dialog').html(text);

        // dialog box options
        $('#dialog').dialog('option', 'title', title);
        $('#dialog').dialog('option', 'buttons', {
            Leave: function() {
                $(this).dialog("close");
                anchorClickLoadPage(el, true);
            },
            Stay: function() {
                $(this).dialog("close");
                return false;
            }
        });
        if (!checkIfIE()) {
            $('#dialog').dialog('open');
        }
    }
    else {
        if (busyLoading()) {
            return false;
        }
        ldr("loading...");
        var page_id = getAnchorPageId(el),
            tab = getHashValue("tab", $(el).attr("href"));
        if (tab !== null) {
            window.location.hash = "#tab=" + tab;
        }

        // check if we maybe should reload the page
        if (moment().diff(content_manager.init_time) > content_manager.max_time_without_reload) {
            ldr("loading in page...");
            window.location.href = "?page=" + page_id;
            return false;
        }

        pagedataDestroy();
        getPage(page_id, function (page) {
            ldr("fetching page...");
            treatPage(page);
        });
        return false;
    }
}

function checkIfIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
        //the user is using IE
        return true;
    } else {
        return false;
    }
}

function checkAuth() {
    $.ajax({
        timeout: content_manager.timeout_limit,
        cache: false,
        url: 'ajax/auth.php',
        type: 'GET',
    })
    .done(function(result) {
        if ( result === "is mtcadmin" ) {
            content_manager.auth_check_time = moment();
        } else if ( result === "is not mtcadmin" ) {
            content_manager.auth_check_time = moment();
        } else {
            location.reload();
        }

    })
    .fail(function() {
        location.reload();
    })//newPage
    ;
}

function changeSiteTreeActive(page_id) {
    $(".cms-page-active").removeClass('cms-page-active');
    $("ul#site-tree li#item_"+page_id).addClass('cms-page-active');
    $("ul#site-tree li#item_"+page_id).removeClass('hide-submenu');
    $("ul#site-tree li#item_"+page_id+" > a ").addClass('cms-page-active');
    $("ul#site-tree li#item_"+page_id).parentsUntil("ul#site-tree").each(function(index, el) {
        $(el).removeClass('hide-submenu');
    });
    // move site tree listing_container scroll bar to active page
    var cms_active_page_site_tree_element_inside_listing_container = $("ul#site-tree ul.listing_container li.cms-page-active");
    if ( cms_active_page_site_tree_element_inside_listing_container.length > 0 ) {
        cms_active_page_site_tree_element_inside_listing_container
            .parent()
            .scrollTop(0);
        cms_active_page_site_tree_element_inside_listing_container
            .parent()
            .scrollTop(cms_active_page_site_tree_element_inside_listing_container.position().top - 15);
    }
}

/**
 * Reload only the pagedata from the database and in the form
 */
function reloadPagedata(page_id, callback, precall) {

    if ( typeof page_id === "undefined" ) {
        page_id = getPageId("sandbox")
    }
    if ( typeof callback === "undefined" ) {
        callback = function(){
            ldrSuccess();
        };
    }
    if ( typeof precall === "undefined" ) {
        precall = function(){
            ldr("loading pagedata...");
        };
    }

    precall();

    getPage(page_id, function(page){
        content_manager.page_live.page_lists = page.preview_page.page_lists;
        content_manager.page_live.pagedata = page.preview_page.pagedata;
        content_manager.page.page_lists = page.preview_page.page_lists;
        content_manager.page.pagedata = page.preview_page.pagedata;
        content_manager.page_sandbox.page_lists = page.preview_page.page_lists;
        content_manager.page_sandbox.pagedata = page.preview_page.pagedata;
        pagedataDestroy();
        drawPagedataFields(content_manager.page.page_lists);
        callback();
    });
}

/**
 * debugOutput()
 *
 * Display text in debug div
 *
 * @param string text
 * @return void
 */
function debugOutput(text) {
    $(".contentManagerDebugOutput").html(text).show();
}

function rememberChoice(choice_name, choice) {
    if ($("#remember").prop("checked")) {
        try {
            localStorage.setItem(choice_name + "_" + content_manager.init_time.format("x"), choice);
        } catch(e) {
            if (isLocalStorageQuotaExceeded(e)) {
                localStorage.clear();
            }
        }
    }
}

function recallChoice(choice_name) {
    choice = localStorage.getItem(choice_name + "_" + content_manager.init_time.format("x"));
    return choice;
}

function pagedataPasteBtn() {
    var choice = recallChoice("merge_same_name_pagedata_on_paste_choice");
    if (choice !== null) {
        inject_pasted_page_pagedata(choice);
        return;
    }
    var title = "Merge same name pagedata?",
        html = "<p>Merging means writing over pagedata with matching names. If the copy selected to be copied without populated data - it shall keep the values. If you select not to merge pagedata nothing will be overwritten.</p>";
        html += "<div class='row'>";
        html += "<label for='remember'>Remember my choice: </label>";
        html += "<input type='checkbox' name='remember' id='remember' class='text' />";
        html += "<p>(To change choice reload page.)</p>";
        html += "</div>";
    $('#dialog').html(html);
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '427px');
    $('#dialog').dialog('option', 'buttons', {
        Merge: function () {
            rememberChoice("merge_same_name_pagedata_on_paste_choice", 1);
            $('#dialog').dialog('close');
            inject_pasted_page_pagedata(1);
        },
        "Don't Merge": function () {
            rememberChoice("merge_same_name_pagedata_on_paste_choice", 0);
            $('#dialog').dialog('close');
            inject_pasted_page_pagedata(0);
        },
        Cancel: function () {
            $('#dialog').dialog('close');
        }
    });
    $("#dialog").dialog('open');
}

function inject_pasted_page_pagedata(merge_pagedata) {
    ldr("pasting fields...");
    content_manager.xds.getItem('clipboard_pagedata',function(val, response){
        if (val !== "" && val !== null && typeof val !== 'undefined') {
            // Ensure we always send a JSON string for pagedataTree
            var payload = (typeof val === 'string') ? val : JSON.stringify(val);
            var data = {
                page_id:            getPageId("sandbox"),
                pagedataTree:       payload,
                merge_pagedata:     merge_pagedata
            };
            $.ajax({
                type: 'post',
                cache: false,
                url: 'ajax/inject_pasted_page_pagedata.php',
                data: data,
                success: function(result) {
                    if ( result == "true" ) {
                        setUnsavedChanges(true);
                        reloadPagedata(
                            getPageId("sandbox"),
                            function() {
                                ldrSuccess();
                            },
                            function() {}
                        );
                    } else if ( result == "false" ) {
                        reloadPagedata(
                            getPageId("sandbox"),
                            function() {
                                ldrFailure("failed...");
                            },
                            function() {}
                        );
                    } else  {
                        if ( content_manager.debug === 1 ) {
                            debugOutput(result);
                        } else {
                            reloadPagedata(
                                getPageId("sandbox"),
                                function() {
                                    ldrFailure("failed...");
                                },
                                function() {}
                            );
                        }
                    }
                },
                error: function(result) {
                    if ( content_manager.debug === 1 ) {
                        debugOutput(result);
                    } else {
                        reloadPagedata(
                            getPageId("sandbox"),
                            function() {
                                ldrFailure("failed...");
                            },
                            function() {}
                        );
                    }
                }
            });

        } else {
            ldrFailure("clipboard empty!");
        }
    });
}

function pagePasteDialog(context) {
    if (typeof context === "undefined") {
        var context = "default"; // edit page
    }

    var title = "Paste Page(s)",
        dialogue_form_setup = {
            paste_source: {
                label: 'Source:',
                id: 'paste_source',
                type: 'select',
                options: {
                    copyhub: 'copyhub',
                    session: 'session',
                },
                hint: 'Do you wish to paste from the copyhub (supports cross-website copying) or from the website session (supports up to round 500 page pasting)?'
            }
    };

    if (context === "default" && content_manager.page !== null) {
        dialogue_form_setup.paste_target = {
            label: 'Past Page as:',
            id: 'paste_target',
            type: 'select',
            options: {
                sub_page: 'sub page',
                sister_page: 'sister page',
            },
            hint: 'Where you want to paste the page?'
        };
    } else {
        dialogue_form_setup.paste_target = {
            label: false,
            id: 'paste_target',
            value: 'sub_page',
            type: 'hidden'
        };
    }

    $('#dialog').html(dialogueBuilder(dialogue_form_setup));
    $("#dialog .dialogBoxForm .hint").tooltip();
    $('#dialog').dialog('option', 'width', '700px');
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'buttons', {
        Paste: function () {
            if (content_manager.page === null) {
                target_page_id = 0;
            } else {
                if ($("#paste_target").val() === "sub_page") {
                    target_page_id = getPageId("live");
                } else {
                    target_page_id = content_manager.page.sub_id;
                }
            }
            pagePaste(
                ($("#paste_source").val() === "copyhub" ? "copyhub" : "session"),
                target_page_id,
                context
            );
            $('#dialog').dialog('close');
        },
        Cancel: function () {
            $('#dialog').dialog('close');
        }
    });
    $('#dialog').dialog('open');
}

function pagePaste(mode, target_page_id, context) {
    ldr("pasting pages...");
    content_manager.xds.getItem('clipboard_page',function(val,response){
        if ( val !== "" || val !== null ) {
            var data = {
                logic:          val,
                mode:           mode,
                target_page_id: target_page_id
            };
            $.ajax({
                type: 'post',
                cache: false,
                url: 'ajax/page_paste.php',
                data: data,
                success: function(result) {
                    if ( !isNaN(result) ) {
                        if (context === "listing_tab") {
                            getSiteTree(
                                null,
                                function () {
                                    getListingList();
                                }
                            );
                        } else {
                            window.location.href = "./?page="+result;
                        }

                    } else if ( result == "false" || content_manager.debug === 0 ) {
                        ldrFailure("page paste failed...");
                    } else {
                        debugOutput(result);
                    }
                },
                error: function(result) {
                    ldrFailure("failed...");
                    if ( content_manager.debug === 1 ) {
                        debugOutput(result);
                    } else {
                        location.reload();
                    }
                }
            });
        } else {
            ldrFailure("clipboard empty!");
        }

    });
}

function pagedataCopyBtn(el){
    var page_list_id = null;
    if ( el.attr('data-item-list-id') !== null ) {
        page_list_id = el.attr('data-item-list-id');
    }
    var title = "Copy pagedata?";
    var text = "Copy with populated data?";
    $('#dialog').html(text);
    // dialog box options
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'buttons', {
        "Yes": function () {
            pagedataCopy(1, page_list_id, getPageId("sandbox"));
            $('#dialog').dialog('close');
            return;
        },
        "No": function () {
            pagedataCopy(0, page_list_id, getPageId("sandbox"));
            $('#dialog').dialog('close');
            return;
        }
    });
    $('#dialog').dialog('open');
}

function pagedataCopy(with_data, page_list_id, page_id) {
    ldr("copying pagedata...");
    var data = {
        with_data:          with_data,
        page_id:            page_id,
        page_list_id:       page_list_id,
    };
    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/copy_pagedata.php?page_id='+page_id,
        data: data,
        success: function(result) {
            if ( result != "false" ) {
                // Store as JSON via xds helper to avoid [object Object]
                content_manager.xds.setObject('clipboard_pagedata', result, function(response){});
                ldrSuccess();
            } else {
                ldrFailure();
            }
        },
        error: function(result) {
            ldrFailure();
        }
    });
}

/**
 * Returns a JSON value from "data-settings". Used for adding plugins or toolbars in tinymce inits.
 * @param {Element} el
 * @param {string} datasetmember
 * @return {string} value
 */
function getTinymcePluginsOrToolbar(el,datasetmember){
  if(typeof(el.data("settings")) !== 'undefined'){
      if(typeof(el.data("settings")[datasetmember]) !== 'undefined')
      {
        return el.data("settings")[datasetmember];
      } else if(datasetmember == "toolbar") {
        return el.data("settings");
      }
  }
  return "";
}

function customTinymce(el) {
    el.tinymce({
        content_css : "/core/css/tiny_mce.css",
        // General options
        theme : "modern",
        plugins: [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen",
            "insertdatetime media table contextmenu paste",
            getTinymcePluginsOrToolbar($(el),"plugins")
        ],
        menubar : false,
        statusbar : true,
        convert_fonts_to_spans : true,
        paste_as_text: true,
        relative_urls : true,
        remove_script_host : true,
        convert_urls : false,
        body_class: "pageContent",
        width: 500,
        height: 100,
        resize: "both",
        image_advtab: true,
        theme_advanced_resizing_use_cookie : true,
        toolbar: getTinymcePluginsOrToolbar($(el),"toolbar"),
        contextmenu: "code",
        image_dimensions: false,
        image_advtab: false,
        file_picker_callback: openFilePicker,
        // enable browser native spellcheck
        setup: function(ed) {
            ed.on('init', function(evt) {
                ed.getBody().setAttribute('spellcheck', true);
            });
            ed.on('change', function(evt) {
                setUnsavedChanges();
            });
        }
    });
}


function regularTinymce(el) {
    el.tinymce({
        content_css : "/core/css/tiny_mce.css",
        // General options
        theme : "modern",
        plugins: [
                    "advlist autolink lists link image charmap print preview anchor",
                    "searchreplace visualblocks code fullscreen",
                    "insertdatetime media table contextmenu paste",
                    getTinymcePluginsOrToolbar($(el),"plugins")
                ],
        menubar : false,
        statusbar : true,
        convert_fonts_to_spans : true,
        paste_as_text: true,
        relative_urls : true,
        remove_script_host : true,
        convert_urls : false,
        body_class: "pageContent",
        width: 678,
        height: 350,
        resize: "both",
        image_advtab: true,
        theme_advanced_resizing_use_cookie : true,
        selector: 'textarea',
        image_dimensions: false,
        image_advtab: false,
        style_formats: [
            {
                title: "Headers",
                items: [
                    {
                        title: "Header 2",
                        format: "h2"
                    },
                    {
                        title: "Header 3",
                        format: "h3"
                    },
                    {
                        title: "Header 4",
                        format: "h4"
                    },
                    {
                        title: "Header 5",
                        format: "h5"
                    },
                    {
                        title: "Header 6",
                        format: "h6"
                    }
                ]
            },
            {
                title: "Inline",
                items: [
                    {
                        title: "Bold",
                        icon: "bold",
                        format: "bold"
                    },
                    {
                        title: "Italic",
                        icon: "italic",
                        format: "italic"
                    },
                    {
                        title: "Underline",
                        icon: "underline",
                        format: "underline"
                    }
                ]
            },
            {
                title: "Blocks",
                items: [
                    {
                        title: "Paragraph",
                        format: "p"
                    },
                    {
                        title: "Blockquote",
                        format: "blockquote"
                    }
                ]
            }
        ],
        advlist_bullet_styles: 'Default',
        advlist_number_styles: 'Default',
        toolbar: "undo redo | styleselect bold italic | alignleft aligncenter alignright alignjustify | bullist numlist | link insertfile image " + getTinymcePluginsOrToolbar($(el),"toolbar"),
        contextmenu: "link image inserttable subscript superscript | cell row column deletetable code",
        file_picker_callback: openFilePicker,
        // enable browser native spellcheck
        setup: function(ed) {
            ed.on('init', function(evt) {
                ed.getBody().setAttribute('spellcheck', true);
            });
            ed.on('change', function(evt) {
                setUnsavedChanges();
            });
        }
    });
}

function simpleTinymce(el) {
    el.tinymce({
        content_css : "/core/css/tiny_mce.css",
        // General options
        theme : "modern",
        plugins: [
                    "advlist autolink lists link image charmap print preview anchor",
                    "searchreplace visualblocks code fullscreen",
                    "insertdatetime media table contextmenu paste",
                    getTinymcePluginsOrToolbar($(el),"toolbar")
                ],
        menubar : false,
        statusbar : true,
        convert_fonts_to_spans : true,
        paste_as_text: true,
        relative_urls : true,
        remove_script_host : true,
        convert_urls : false,
        body_class: "pageContent",
        width: 500,
        height: 200,
        resize: "both",
        image_advtab: true,
        theme_advanced_resizing_use_cookie : true,
        advlist_bullet_styles: 'Default',
        advlist_number_styles: 'Default',
        toolbar: "styleselect | link | bold italic | bullist numlist outdent indent " + getTinymcePluginsOrToolbar($(el),"toolbar"),
        contextmenu: "code",
        image_dimensions: false,
        image_advtab: false,
        style_formats: [
            {
                title: "Headers",
                items: [
                    {
                        title: "Header 2",
                        format: "h2"
                    },
                    {
                        title: "Header 3",
                        format: "h3"
                    },
                    {
                        title: "Header 4",
                        format: "h4"
                    },
                    {
                        title: "Header 5",
                        format: "h5"
                    },
                    {
                        title: "Header 6",
                        format: "h6"
                    }
                ]
            }
        ],
        file_picker_callback: openFilePicker,
        // enable browser native spellcheck
        setup: function(ed) {
            ed.on('init', function(evt) {
                ed.getBody().setAttribute('spellcheck', true);
            });
            ed.on('change', function(evt) {
                setUnsavedChanges();
            });
        }

    });
}

function newPage(page_type) {

    if (page_type == 'child') {
        createNewPage(getPageId("live"));
        return;
    }

    if (content_manager.page === null) {
        createNewPage(0);
        return;
    }
    var title = "New sister or child page?",
    text = "Should the new page be a sister page (on the same level) or child page (a level under current page)?";
    $('#dialog').html(text);
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'buttons', {
        "Sister": function () {
            createNewPage(content_manager.page_live.sub_id);
            $('#dialog').dialog('close');
            return;
        },
        "Child": function () {
            createNewPage(getPageId("live"));
            $('#dialog').dialog('close');
            return;
        }
    });
    $('#dialog').dialog('open');
    return false;
}

function createNewPage(sub_id) {
    ldrPending("creating new page...");
    $.ajax({
        url: 'ajax/load_new_page.php',
        type: 'GET',
        dataType: 'json',
        data: {'sub_id': sub_id},
        timeout: content_manager.timeout_limit
    })
    .fail(function(result) {
        ldrFailure();
        if(content_manager.debug === 0) {
            location.reload();
        }
    })
    .done(function(result) {
        if ( result === false || result === "false" ) {
            ldrFailure();
            window.location.href = "./";
        } else {
            treatPage(result);
        }
    });
    return false;
}

function getSiteTree(active_page_id, callback) {
    if ( typeof active_page_id === "undefined" || active_page_id === null ) {
        active_page_id = getPageId();
    }
    if (typeof callback === "undefined" || callback === null) {
        callback = function () {};
    }
    $.ajax({
        url: 'ajax/get_sitetree.php',
        type: 'GET',
        data: {active_page_id: active_page_id},
        timeout: content_manager.timeout_limit
    })
    .done(function(result) {
        content_manager.site_tree = result.result.site_tree;
        var parent = $("ul#site-tree").parent();
        $("ul#site-tree").remove();
        parent.append(result.result.html);
        init(".topnav");
        changeSiteTreeActive(active_page_id);
    })
    .fail(function() {
        //
    })
    .always(function () {
        callback();
    })
    ;
    return false;
}

function getListingList() {
    var data = {
        filter_from:$(".listingDateArchive :selected").attr("data-filter-from"),
        filter_to:$(".listingDateArchive :selected").attr("data-filter-to"),
        limit:$(".listingLimit").val(),
        listing_page:$(".listingPage").val(),
        listing_quick_search:$(".listingQuickSearch").val(),
        adv_filter: {}
    };
    $(".listingAdvFilterInput").each(function (index) {
        data.adv_filter[$(this).attr("name")] = {};
        if ($(this).attr("type") === "checkbox") {
            data.adv_filter[$(this).attr("name")]['value'] = ($(this).prop('checked') ? 1 : 0);
        } else {
            data.adv_filter[$(this).attr("name")]['value'] = $(this).val();
        }
    });
    $(".listingAdvFilterInputType").each(function (index) {
        data.adv_filter[$(this).attr("name")]['type'] = $(this).val();
    });
    ldrPending("Getting list...");
    $.ajax({
        url: 'templates/manage_listing_listing.php?page_id='+getPageId("live"),
        type: 'GET',
        data: data,
    })
    .done(function(result) {
        $("#listingContainer").html(result);
        listingInit();
        ldrSuccess();
    })
    .fail(function() {
        ldrFailure();
    })
    ;
}

/**
 * Parse page object recieved from getPage (load_page.php) into page, page_live, page_sandbox
 */
function parsePageAndInsertIntoContentManager(content_manager, page) {
    content_manager.page = clone(page);
    content_manager.page_live = clone(page);
    content_manager.page_sandbox = clone(page.preview_page);

    /**
     * Which variables in content_manager.page are from content_manager.page_live & which from content_manager.page_sandbox
     *
     * allow_delete: "0"               LIVE
     * allow_update: "1"               LIVE
     * created: "2014-03-05 18:49:32"  LIVE
     * data1: ""                       LIVE
     * data2: ""                       LIVE
     * data3: ""                       LIVE
     * history_lock: ""                LIVE
     * frontpage: "1"                  LIVE
     * hide_in_cms: "0"                LIVE
     * id: "1"                         SANDBOX
     * draft_for_page_id: "0"          SANDBOX
     * review_status: "0"              SANDBOX
     * noindex: "0"                    LIVE
     * innav: "1"                      LIVE
     * language: null                  LIVE
     * language_ignored_page: false    LIVE
     * layout: "default.twig"          SANDBOX
     * listing_container: "0"          LIVE
     * lock: "0"                       LIVE
     * logic: ""                       SANBOX
     * order: "0"                      LIVE
     * page_lists: Array[3]            SANDBOX
     * pagedata: Object                SANDBOX
     * path: "/"                       LIVE
     * published: "1"                  SANDBOX
     * redchild: "0"                   LIVE
     * search_content: "Welcom"        LIVE
     * search_title: "Welcom"          LIVE
     * searchable: "1"                 LIVE
     * seo_description: ""             SANDBOX
     * seo_keywords: ""                SANDBOX
     * seo_title: ""                   SANDBOX
     * slug: "welcome"                 LIVE
     * sub_id: "0"                     LIVE
     * subs: Array[0]                  LIVE
     * template: "home.twig"           SANDBOX
     * title: "Welcome"                SANDBOX
     * trail: Array[0]                 LIVE
     * type: "default"                 LIVE
     * updated: "2015-09-17 13:17:06"  SANDBOX
     * url: "/"                        LIVE
     */

    content_manager.page.id                 = content_manager.page_sandbox.id;
    content_manager.page.published          = content_manager.page_sandbox.published;
    content_manager.page.draft_for_page_id  = content_manager.page_sandbox.draft_for_page_id;
    content_manager.page.review_status      = content_manager.page_sandbox.review_status;
    content_manager.page.layout             = content_manager.page_sandbox.layout;
    content_manager.page.logic              = content_manager.page_sandbox.logic;
    content_manager.page.page_lists         = content_manager.page_sandbox.page_lists;
    content_manager.page.pagedata           = content_manager.page_sandbox.pagedata;
    content_manager.page.seo_description    = content_manager.page_sandbox.seo_description;
    content_manager.page.seo_keywords       = content_manager.page_sandbox.seo_keywords;
    content_manager.page.seo_title          = content_manager.page_sandbox.seo_title;
    content_manager.page.template           = content_manager.page_sandbox.template;
    content_manager.page.title              = content_manager.page_sandbox.title;
    content_manager.page.updated            = content_manager.page_sandbox.updated;

    if ( cmPanelDynamicData.HISTORY ) {
        content_manager.page.allow_delete       = content_manager.page_sandbox.allow_delete;
        content_manager.page.allow_update       = content_manager.page_sandbox.allow_update;
        content_manager.page.frontpage          = content_manager.page_sandbox.frontpage;
        content_manager.page.hide_in_cms        = content_manager.page_sandbox.hide_in_cms;
        content_manager.page.innav              = content_manager.page_sandbox.innav;
        content_manager.page.lock               = content_manager.page_sandbox.lock;
        content_manager.page.redchild           = content_manager.page_sandbox.redchild;
        content_manager.page.listing_container  = content_manager.page_sandbox.listing_container;
        content_manager.page.searchable         = content_manager.page_sandbox.searchable;
        content_manager.page.slug               = content_manager.page_sandbox.slug;
        content_manager.page.url                = content_manager.page_sandbox.url;
        if (typeof content_manager.page.history_page !== "undefined") {
            content_manager.page.path               = content_manager.page.history_page.path;
        }
    }

    return content_manager;
}

/**
 * Treat a button page
 */
function treatButtonPage(page) {
    if ( cmPanelDynamicData.IS_ADMIN ) {
        var title = "Trigger or Manage?";
        var text = "Would you like to trigger the button or open it up manage/edit logic?";
        $('#dialog').html(text);
        $('#dialog').dialog('option', 'title', title);
        $('#dialog').dialog('option', 'buttons', {
            "Trigger": function () {
                ldr("creating...");
                treatPageLogic(page);
                $('#dialog').dialog('close');
                return;
            },
            "Manage": function () {
                ldr("loading...");
                loadManagePagePanel();
                $('#dialog').dialog('close');
                return;
            }
        });
        $('#dialog').dialog('open');
    } else {
        treatPageLogic(page);
    }
}

/**
 * Function that treats & actions page logic.
 */
function treatPageLogic(page) {
    ldr("creating...");
    runLogic(
        page.logic,
        page.id,
        function(page_id) {
            ldrSuccess();
            if ( isInt(page_id) ) {
                ldrPending("processing...");
                getPage(page_id, function(page){
                    treatPage(page);
                    if (page.type !== "temp") {
                        getSiteTree(page.id);
                    }
                });
            }
        }
    );
}

/**
 * Clears error messages from screen/panel;
 */
function clearPanelMessages() {
    $(".cmsPanelMessages").html("");
}

/**
 * Function which recieves a recently retrieved page object (from load_page.php)
 *  then reads it, parses it, and does the according actions.
 *  You could call this the router of cm panel pages.
 */
function treatPage(page) {

    content_manager = parsePageAndInsertIntoContentManager(content_manager, page);

    loadPanelMessages();
    changeSiteTreeActive(content_manager.page_live.id);

    var localStorageTab = localStorage.getItem("page_id_"+content_manager.page_live.id+"_tab");
    var hasValueTab = getHashValue("tab");

    if (content_manager.page_live.type != "temp" && hasValueTab !== null) {
        var tab = hasValueTab;
    } else if (content_manager.page_live.type != "temp" && localStorageTab !== null && typeof localStorageTab !== "undefined" && localStorageTab != 3) {
        var tab = localStorageTab;
    } else {
        var tab = 1;
    }

    if (content_manager.page.listing_container != 1 && tab == 2) {
        tab = 1;
    } else if (!cmPanelDynamicData.HISTORY && tab == 3) {
        tab = 1;
    }

    var meta_title = cmPanelDynamicData.PAGE_TITLE+cmPanelDynamicData.TITLE_POSTFIX;
    var meta_page = "?page="+content_manager.page_live.id;

    if (cmPanelDynamicData.HISTORY &&
        typeof content_manager.page.history_page !== "undefined" &&
        content_manager.page.history_page.id != content_manager.page_live.id) {
        meta_page = meta_page + "&history=" + content_manager.page.history_page.id;
    }

    if (tab > 1) {
        meta_page = meta_page+"#tab="+tab;
    }

    history.pushState({}, meta_title, meta_page);
    googleAnalyticsTrack();

    if (page.type == "button") {
        treatButtonPage(page);
    } else if (page.type == "temp") {
        ldr("loading page...");
        loadNewPagePanel();
        googleAnalyticsTrack();
    } else if (page.type == "default") {
        ldr("loading page...");
        if ( tab == 2 ) {
            loadManageListingPanel();
        } else if ( tab == 3 ) {
            loadPageHistoryPanel();
        } else {
            loadManagePagePanel();
        }
    } else {
        window.location.href = "./";
    }
}

function runLogic(logic, page_id, callback) {
    ldrPending("creating ...");
    $.ajax({
        url: 'ajax/run_logic.php',
        type: 'GET',
        dataType: 'json',
        data: {
            'page_id': page_id,
        },
        timeout: (content_manager.timeout_limit * 2) // could potentially be a big process
    })
    .fail(function(result) {
        ldrFailure();
        location.reload();
    })
    .done(function(result) {
        if ( result === false ) {
            ldrFailure();
        } else {
            callback(result);
        }
    });
}

/**
 * loadPageHistoryPanel()
 * Loads page history/version panel
 */
function loadPageHistoryPanel() {
    // destroy
    pagedataDestroy();
    // set in local storage that we like to see tab 2 (listing manger) for this page
    try {
        localStorage.setItem("page_id_"+content_manager.page_live.id+"_tab", 3);
    } catch(e) {
        if ( isLocalStorageQuotaExceeded(e) ) {
            localStorage.clear();
        }
    }
    var result;
    $.ajax({
        url: 'templates/page_history.php?page_id='+content_manager.page_live.id,
        type: 'GET',
        timeout: (content_manager.timeout_limit) // A big load
    })
    .done(function(result) {
        // tabs
        $(".tobBarTab").hide().removeClass('selected');
        $(".historyTab").show().addClass('selected');
        $(".dashboardTab").show();
        $(".updatePageTab").show();

        if ( typeof content_manager.page_live.parent_listing_page != "undefined" && content_manager.page_live.parent_listing_page != false && content_manager.page_live.parent_listing_page != null ) {
            $(".manageParentListingTab a")
                .html("Manage "+stripTags(content_manager.page_live.parent_listing_page.title) + " Container")
                .attr("href", "?page="+content_manager.page_live.parent_listing_page.id+"#tab=2")
                .data("page-id", content_manager.page_live.parent_listing_page.id);
            $(".manageParentListingTab").show();
        }

        if (content_manager.page_live.listing_container == 1) {
            $(".manageListingTab a").html("Manage "+stripTags(content_manager.page_live.title) + " Container");
            $(".manageListingTab").show();
        }

        // header
        $("#workAreaH").html("Update Page");
        $("#workArea").html(result);
        historyInit();
        ldrSuccess();
    })
    .fail(function() {
        ldrFailure();
        location.reload();
    })
    ;
}

function loadIndex() {
    history.pushState({}, cmPanelDynamicData.PAGE_TITLE+cmPanelDynamicData.TITLE_POSTFIX, "./");
    // destroy
    pagedataDestroy();
    // load
    ldr("loading dashboard...");
    $.ajax({
        url: 'templates/dashboard.php',
        type: 'GET',
        timeout: (content_manager.timeout_limit) // A big load
    })
    .done(function(result) {
        // tabs
        $(".tobBarTab").hide();
        $(".dashboardTab").show();
        $(".dashboardTab").addClass('selected');
        // header
        content_manager.page = null;
        $("#workArea").html(result);
        pageActionBtnsFloat();
        dashboardInit();
        googleAnalyticsTrack();
        ldrSuccess();
    })
    .fail(function() {
        ldrFailure();
        location.reload();
    })
    ;
}

/**
 * Checks for google analytics existance and sends (ajax) page change
 */
function googleAnalyticsTrack() {
    if ( typeof ga !== "undefined") {
        var page = window.location.pathname+window.location.search+window.location.hash;
        var title = document.title;
        ga('set', {page: page, title: title});
        ga('send', 'pageview');
    }
}

function loadManageListingPanel() {
    // destroy
    pagedataDestroy();
    // set in local storage that we like to see tab 2 (listing manger) for this page
    try {
        localStorage.setItem("page_id_"+content_manager.page_live.id+"_tab", 2);
    } catch(e) {
        if ( isLocalStorageQuotaExceeded(e) ) {
            localStorage.clear();
        }
    }
    var result;
    $.ajax({
        url: 'templates/manage_listing.php?page_id='+content_manager.page_live.id,
        type: 'GET',
        timeout: (content_manager.timeout_limit) // A big load
    })
    .done(function(result) {
        // tabs
        $(".tobBarTab").hide().removeClass('selected');
        $(".manageListingTab").show().addClass('selected');
        $(".manageListingTab a").html("Manage "+stripTags(content_manager.page_live.title) + " Container");
        $(".updatePageTab").show();
        $(".dashboardTab").show();
        $(".historyTab").show();

        if ( typeof content_manager.page_live.parent_listing_page != "undefined" && content_manager.page_live.parent_listing_page != false && content_manager.page_live.parent_listing_page != null ) {
            $(".manageParentListingTab a")
                .html("Manage "+stripTags(content_manager.page_live.parent_listing_page.title) + " Container")
                .attr("href", "?page="+content_manager.page_live.parent_listing_page.id+"#tab=2")
                .data("page-id", content_manager.page_live.parent_listing_page.id);
            $(".manageParentListingTab").show();
        }

        // header
        $("#workAreaH").html("Update Page");
        $("#workArea").html(result);
        $("#workArea #data\\[page\\]\\[id\\]").val(content_manager.page_live.id);
        googleAnalyticsTrack();
        panelInit();
        getListingList();
    })
    .fail(function() {
        ldrFailure();
        location.reload();
    })
    ;
}

function loadManagePagePanel() {
    // destroy
    pagedataDestroy();
    // set in local storage that we like to see tab 1 (page editor) for this page
    try {
        localStorage.setItem("page_id_"+content_manager.page_live.id+"_tab", 1);
    } catch(e) {
        if ( isLocalStorageQuotaExceeded(e) ) {
            localStorage.clear();
        }
    }
    var result;
    $.ajax({
        url: 'templates/edit_page.php',
        type: 'POST',
        data: {
            'json': JSON.stringify(content_manager.page_live)
        },
        timeout: (content_manager.timeout_limit)
    })
    .done(function(result) {
        // tabs
        $(".tobBarTab").hide().removeClass('selected');
        $(".updatePageTab").show().addClass('selected');
        $(".dashboardTab").show();
        if (content_manager.page.type !== "button") {
            $(".historyTab").show();
        }

        if ( content_manager.page_live.listing_container == 1 ) {
            $(".manageListingTab a").html("Manage "+stripTags(content_manager.page_live.title) + " Container");
            $(".manageListingTab").show();
        }
        if ( typeof content_manager.page_live.parent_listing_page != "undefined" && content_manager.page_live.parent_listing_page != false && content_manager.page_live.parent_listing_page != null ) {
            $(".manageParentListingTab a")
                .html("Manage "+stripTags(content_manager.page_live.parent_listing_page.title) + " Container")
                .attr("href", "?page="+content_manager.page_live.parent_listing_page.id+"#tab=2")
                .data("page-id", content_manager.page_live.parent_listing_page.id);
            $(".manageParentListingTab").show();
        }
        // header
        $("#workAreaH").html("Update Page");
        //
        googleAnalyticsTrack();
        populateWorkArea(result);
    })
    .fail(function() {
        ldrFailure();
        location.reload();
    })
    ;
}

function loadNewPagePanel() {
    // destroy
    pagedataDestroy();
    var result;
    $.ajax({
        url: 'templates/new_page.php',
        type: 'POST',
        data: {
            'json': JSON.stringify(content_manager.page_live)
        },
        timeout: (content_manager.timeout_limit)
    })
    .done(function(result) {
        // tabs
        $(".tobBarTab").hide().removeClass('selected');
        $(".newPageTab").show().addClass('selected');
        $(".dashboardTab").show();
        populateWorkArea(result);
    })
    .fail(function(){
        ldrFailure();
        location.reload();
    })
    ;
}

function drawPagedataFields(page_lists) {
    var result;
    $.ajax({
        data: {
            'pagedata_lists': JSON.stringify(page_lists)
        },
        url: 'templates/edit_page_lists.php',
        type: 'POST',
        timeout: content_manager.timeout_limit
    })
    .done(function(result) {
        var pagedataList = document.querySelector('ul.pagedata-list');

        if (!pagedataList) {
            console.error('Failed locating pagedata list container');
            ldrFailure('Fields container missing');
            return;
        }

        try {
            pagedataList.innerHTML = result;
        } catch (error) {
            console.error('Failed updating pagedata markup', error);
            ldrFailure('Failed rendering fields');
            return;
        }

        $(pagedataList).height("auto");

        try {
            pagedataInit();
            ldrSuccess();
        } catch (error) {
            console.error('Failed initialising pagedata fields', error);
            ldrFailure('Failed initialising fields');
        }
    })
    .fail(function() {
        ldrFailure("timeout fetching fields");
        location.reload();
    })
    ;
}

function populateWorkArea(editPagePanel) {
    var pagedata_list_height = $("ul.pagedata-list").height();
    $("#workArea").html(editPagePanel);
    $("ul.pagedata-list").height(pagedata_list_height);
    panelInit();
    pageActionBtnsFloat();
    fillInDataForPanel(content_manager);
    ldr("fetching fields...");
    drawPagedataFields(content_manager.page.page_lists);
}

function fillInDataForPanel(content_manager) {
    for (var attr in content_manager.page) {
        if ( $("#workArea #data\\[page\\]\\["+attr+"\\]").attr("type") === "checkbox" ) {
            $("#workArea #data\\[page\\]\\["+attr+"\\]").prop('checked', ( content_manager.page[attr] == 1 ? true : false ) );
        } else {
            $("#workArea #data\\[page\\]\\["+attr+"\\]").val(content_manager.page[attr]);
        }
    }

    $("#page_url_link").html(cmPanelDynamicData.SITE_URL+content_manager.page.path);
    $(".goToPageLink").attr("href", content_manager.page_live.url);
}

/**
 * When the content manager treats a temp page it will trigger a ping every content_manager.page_ping.interval_time number of
 *  milliseconds. Once the page becomes not temp it will stop. It's set to every 15 min by default since default temp page
 *  deletion interval is 120 min. The ping (ping_page.php) it self just runs an update query using existing datathus updating
 *  only the `updated` column.
 */
function pingPage() {
    clearInterval(content_manager.page_ping.interval);
    content_manager.page_ping.interval = setInterval(function(){
        $.ajax({
            url: 'ajax/ping_page.php?page_id='+getPageId(),
            type: 'GET',
            timeout: content_manager.timeout_limit
        })
        .fail(function(jq_xhr, text_status, error_thrown) {
            if (content_manager.debug === 1) {
                consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
            } else {
                location.reload();
            }
        });
    }, content_manager.page_ping.interval_time); // content_manager.page_ping.interval_time by default is 15 minutes
}

function deleteListingItem(el) {
    $('#dialog').html('Are you sure you want to delete '+el.attr("data-page-title")+'?');
    $('#dialog').dialog('option', 'title', "Are you sure?");
    $('#dialog').dialog('option', 'buttons', {
        "Yes": function () {
            $('#dialog').dialog('close');
            if ( busyLoading() ) { return false; }
            ldr("deleting ...");
            $.ajax({
                type: 'post',
                data : { page_id : el.attr("data-page-id") },
                timeout: content_manager.timeout_limit,
                cache: false,
                url: 'ajax/delete_page.php'
            })
            .done(function(result) {
                if ( result !== false || result !== "false" ) {
                    // do getSiteTree then getListingList via a callback to minimize stress on server
                    getSiteTree(
                        null,
                        function () {
                            getListingList();
                        }
                    );
                    ldrSuccess();
                } else {
                    ldrFailure();
                    getListingList();
                }
            })
            .fail(function() {
                ldrFailure();
                location.reload();
            })
            ;
        },
        "Cancel": function () {
            $('#dialog').dialog('close');
        }
    });
    $('#dialog').dialog('open');
    return false;
}

/**
 * deleteHistoryItem()
 * Delete a type history page
 */
function deleteHistoryItem(el) {
    var text = 'Are you sure you want to delete '+el.attr("data-page-title")+'?';

    if ($(".lockVersion[data-page-id="+el.attr("data-page-id")+"] i").attr("class") == "fa fa-lock") {
        text += " This version is locked from being auto-deleted.";
    }

    $('#dialog').html(text);
    $('#dialog').dialog('option', 'title', "Are you sure?");
    $('#dialog').dialog('option', 'buttons', {
        "Yes": function () {
            $('#dialog').dialog('close');
            if ( busyLoading() ) { return false; }
            ldr("deleting ...");
            $.ajax({
                type: 'post',
                data : { page_id : el.attr("data-page-id") },
                timeout: content_manager.timeout_limit,
                cache: false,
                url: 'ajax/delete_page.php',
            })
            .done(function(result) {
                if ( result !== false || result !== "false" ) {
                    /*
                     * we could do just loadPageHistoryPanel() here but changes here could affect the page and page
                     * version active. Like if suddenly there wasn't a "newer page version"
                     */
                    getPage(
                        getPageId("live"),
                        function (page) {
                            treatPage(page);
                        },
                        getPageId("history")
                    );
                } else {
                    ldrFailure();
                    loadPageHistoryPanel();
                }
            })
            .fail(function() {
                ldrFailure();
                location.reload();
            })
            ;
        },
        "Cancel": function () {
            $('#dialog').dialog('close');
        }
    });
    $('#dialog').dialog('open');
    return false;
}

function deletePageDialog() {
    if ( content_manager.page.title == "" ) {
        $('#dialog').html("Deleting a page shall delete all it's sub pages.");
    } else {
        $('#dialog').html("Deleting <strong>\""+stripTags(content_manager.page.title)+"\"</strong> page shall delete all it's sub pages.");
    }
    $('#dialog').dialog('option', 'title', 'Are you sure you want to delete this page?');
    $('#dialog').dialog('option', 'buttons', {
        "Delete": function () {
            $('#dialog').dialog('close');
            if ( busyLoading() ) { return false; }
            ldr("deleting ...");
            var page_to_be_deleted = content_manager.page_live;
            $.ajax({
                type: 'post',
                data: { page_id : page_to_be_deleted.id },
                timeout: content_manager.timeout_limit,
                cache: false,
                url: 'ajax/delete_page.php',
            })
            .done(function(result) {
                if ( result === false || result === "false" ) {
                    ldrFailure();
                    window.location.href = "./";
                } else {
                    ldrSuccess();
                    if ( result === 0 || result === "0" ) {
                        // do getSiteTree then loadIndex via a callback to minimize stress on server
                        getSiteTree(
                            null,
                            function () {
                                loadIndex();
                            }
                        );
                    } else {
                        ldr("loading...");
                        // do getSiteTree then getPage via a callback to minimize stress on server
                        getSiteTree(
                            page_to_be_deleted.sub_id,
                            function () {
                                getPage(page_to_be_deleted.sub_id, function(page) {
                                    treatPage(page);
                                });
                            }
                        );
                    }
                }
            })
            .fail(function() {
                ldrFailure();
                location.reload();
            })
            ;
        },
        "Cancel": function () {
            $('#dialog').dialog('close');
        }
    });
    $('#dialog').dialog('open');
    return false;
}

function changeLanguage(language) {
    if ( busyLoading() ) { return false; }
    ldr("switching languages ...");
    $.ajax({
        url: 'ajax/change_language.php',
        type: 'GET',
        data: {language: language},
        timeout: content_manager.timeout_limit
    })
    .done(function(result) {
        getPage(
            getPageId("live"),
            function(page){
                treatPage(page);
            },
            getPageId("history")
        );
    })
    .fail(function() {
        location.reload();
        ldrFailure();
    })
    ;
}

/**
 * commitPageBtn()
 * Action for when commit button is pressed page
 */
function commitPageBtn(el) {
    if (busyLoading() || el.hasClass("disabledBtn")) {
        return false;
    }
    if ($("#workArea #data\\[page\\]\\[published\\]").last().val() == 0) {
        var title = "Page status is 'Not Public'!",
        html = "<p>The page's status you are currently committing is set to <strong>Not Public</strong>. This means this page will not be viewable to the public.</p>";
        html += "<p>Would you like to proceed?</p>";
        $('#dialog').html(html);
        $('#dialog').dialog('option', 'title', title);
        $('#dialog').dialog('option', 'width', '427px');
        $('#dialog').dialog('option', 'buttons', {
            "Yes": function () {
                $('#dialog').dialog("close");
                var title = "Commit message",
                html = "<p>You may enter a page commit message</p>";
                html += "<form class='dialogBoxForm' onkeypress='return event.keyCode != 13;'>";
                html += "<fieldset>";
                html += "<div class='row'>";
                html += "<input type='text' name='save_for_commit_comment' id='save_for_commit_comment' class='text ui-widget-content ui-corner-all' />";
                html += "</div>";
                html += "</fieldset>";
                html += "</form>";
                $('#dialog').html(html);
                $('#dialog').dialog('option', 'title', title);
                $('#dialog').dialog('option', 'width', '427px');
                $('#dialog').dialog('option', 'buttons', {
                    "Continue": function () {
                        $('#dialog').dialog("close");
                        var comment = $("#save_for_commit_comment").val()
                        commitPage(comment);
                    }
                });
                $('#dialog').dialog('open');
            },
            "No": function () {
                $('#dialog').dialog("close");
            }
        })
        $('#dialog').dialog('open');
    } else {
        var title = "Commit message",
        html = "<p>You may enter a page commit message</p>";
        html += "<form class='dialogBoxForm' onkeypress='return event.keyCode != 13;'>";
        html += "<fieldset>";
        html += "<div class='row'>";
        html += "<input type='text' name='save_for_commit_comment' id='save_for_commit_comment' class='text ui-widget-content ui-corner-all' />";
        html += "</div>";
        html += "</fieldset>";
        html += "</form>";
        $('#dialog').html(html);
        $('#dialog').dialog('option', 'title', title);
        $('#dialog').dialog('option', 'width', '427px');
        $('#dialog').dialog('option', 'buttons', {
            "Continue": function () {
                $('#dialog').dialog("close");
                var comment = $("#save_for_commit_comment").val()
                commitPage(comment);
            }
        });
        $('#dialog').dialog('open');
    }
}

/**
 * requestPageReview()
 * Action for when rquest review button is pressed page
 */
function requestPageReview(el) {
    if (busyLoading() || el.hasClass("disabledBtn")) {
        return false;
    }
    ldr("loading ...");

    var title = "Review Comment",
    text = "<p>You may add a review comment to your page</p>";
    text += "<form class='dialogBoxForm' onkeypress='return event.keyCode != 13;'>";
    text += "<fieldset>";
    text += "<div class='row'>";
    text += "<input type='text' name='review_comment' id='review_comment' class='text ui-widget-content ui-corner-all' />";
    text += "</div>";
    text += "</fieldset>";
    text += "</form>";
    $('#dialog').html(text);
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '427px');
    $('#dialog').dialog('option', 'buttons', {
        "Continue": function() {
            $('#dialog').dialog("close");
            ldr("loading ...");
            var data = {
                comment: $("#review_comment").val(),
                page_id: getPageId("history"),
            }
            $.ajax({
                type: 'post',
                cache: false,
                url: 'ajax/set_ready_for_review.php',
                data: data
            })
            .done(function(){
                content_manager.page.history_page.review_status = 1;
                processUnsavedChangesStatus();
            })
            .fail(function() {
                ldrFailure("failed requesting review ...");
            });
        },
        "Cancel": function() {
            $('#dialog').dialog("close");
            ldrDone();
        },
    });
    $('#dialog').dialog('open');
}



/**
 * commitPage()
 * Function for commiting pages to become 'current'.
 * @param string comment - live page comment
 */
function commitPage(comment) {
    if (busyLoading()) {
        return false;
    }
    ldr("approving ...");
    var data = {
        page_id: content_manager.page.id,
        comment: comment
    }
    $.ajax({
        type: 'post',
        dataType: 'json',
        cache: false,
        url: 'ajax/commit_page.php',
        data: data
    })
    .done(function(result) {
        if (result.response == 2) {
            ldr("commiting ...");
            $.ajax({
                type: 'post',
                timeout: content_manager.timeout_limit,
                data:{
                    page_id: content_manager.page.history_page.id
                },
                cache: false,
                url: 'ajax/unmark_ready_for_review.php',
            })
            .fail(function(jq_xhr, text_status, error_thrown) {
                if (content_manager.debug === 1) {
                    consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
                }
            })
            .always(function() {
                getPage(
                    content_manager.page_live.id,
                    function(page){
                        ldr('loading page...');
                        // do getSiteTree then treatPage via a callback to minimize stress on server
                        getSiteTree(
                            content_manager.page_live.id,
                            function () {
                                treatPage(page);
                            }
                        );
                    }
                );
            });
        } else {
            ldrFailure();
        }
    })
    .fail(function(jq_xhr, text_status, error_thrown) {
        if (content_manager.debug === 1) {
            consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
            loadPanelMessages();
        } else {
            window.location.href = "./";
        }
    });
    return false;
}

/**
 * log in console ajax failure params
 * this should only be run if content_manager.debug === 1
 */
function consoleLogAjaxFailure(jq_xhr, text_status, error_thrown) {
    console.log('jq_xhr:');
    console.log(jq_xhr);
    console.log('text_status:');
    console.log(text_status);
    console.log('error_thrown:');
    console.log(error_thrown);
}

// alert user about WYSIWYGs not laoded in yet
function tooQuickAlert() {
    ldrFailure();
    var text = "Please try again! Some of the textareas didn't manage to load up yet!",
        title = "Oops too quick!";
    $('#dialog').html(text);
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'buttons', {
        Ok: function () {
            $('#dialog').dialog("close");
        }
    })
    $('#dialog').dialog('open');
    return false;
}

/**
 * savePage()
 * Main function for saving pages.
 * @param bool retreat_page_after_save - weather or not to run treatPage after save
 * @param bool reload_page_after_save - weather or not to reload the page after save
 */
function savePage(retreat_page_after_save, reload_page_after_save, page_to_save) {
    if (busyLoading()) {
        return false;
    }
    ldr("saving ...");
    var page = {};
    if (typeof page_to_save !== "undefined") {
        page = page_to_save;
    }
    page = gatherPageValuesFromPanel(page);

    // if live page is temp then save it as default
    if (content_manager.page_live.type == "temp") {
        page['type'] = "default";
    } else {
        page['type'] = content_manager.page_live.type;
    }

    page.pagedata = {};
    page.pagedata = gatherPagedataValuesFromPanel(page.pagedata);

    if (page.pagedata === false) {
        return tooQuickAlert();
    }

    $("div.error").removeClass("error");
    $("div.alert").hide();

    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/save.php?page_id='+content_manager.page.id,
        data: {
            serialized_post: JSON.stringify(page)
        },
        error: function(jq_xhr, text_status, error_thrown) {
            if (content_manager.debug === 1) {
                consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
            } else {
                window.location.href = "./";
            }
        },
        success: function(result) {
            result = JSON.parse(result);
            if (result.response == 2) {
                setUnsavedChanges(false);
                setLastSaved();
                processUnsavedChangesStatus();

                getPage(
                    content_manager.page_live.id,
                    function(page){
                        ldr('loading page...');
                        // do getSiteTree then treatPage via a callback to minimize stress on server
                        getSiteTree(
                            content_manager.page_live.id,
                            function () {
                                treatPage(page);
                            }
                        );
                    },
                    result.history_page_id
                );

            } else {

                // this is also checked in the following php script
                if (cmPanelDynamicData.IS_ADMIN) {

                    var text = "There are validation issues on this page. As <strong>mtcadmin</strong>, do you want to try and force save / publish?",
                        title = "Force save / publish?";
                    $('#dialog').html(text);
                    $('#dialog').dialog('option', 'title', title);
                    $('#dialog').dialog('option', 'buttons', {
                        "Yes": function () {
                            $('#dialog').dialog("close");
                            $.ajax({
                                type: 'post',
                                cache: false,
                                url: 'ajax/save.php?page_id='+content_manager.page.id+'&force=true',
                                data: {
                                    serialized_post: JSON.stringify(page)
                                },
                                success: function(result) {
                                    result = JSON.parse(result);
                                    if (result.response == 2) {
                                        setUnsavedChanges(false);
                                        setLastSaved();
                                        processUnsavedChangesStatus();
                                        getPage(
                                            content_manager.page_live.id,
                                            function(page){
                                                ldr('loading page...');
                                                // do getSiteTree then treatPage via a callback to minimize stress on server
                                                getSiteTree(
                                                    content_manager.page_live.id,
                                                    function () {
                                                        treatPage(page);
                                                    }
                                                );
                                            },
                                            result.history_page_id
                                        );
                                    } else {
                                        displayValidationErrors(result);
                                        ldrFailure();
                                    }
                                }
                            });
                        },
                        "No": function () {
                            $('#dialog').dialog("close");
                            displayValidationErrors(result);
                            ldrFailure();
                        }
                    })
                    $('#dialog').dialog('open');

                } else {
                    displayValidationErrors(result);
                    ldrFailure();
                }
            }
        }
    });
    return false;
}

/**
 * gatherPageValuesFromPanel()
 * @param page object
 * @retun page object
 * Gathers the values of page object from the current page panel
 */
function gatherPageValuesFromPanel(page) {
    var t;
    for (var attr in content_manager.page) {
        if ( $("#workArea #data\\[page\\]\\["+attr+"\\]").attr("type") === "checkbox" ) {
            page[attr] = ($("#workArea #data\\[page\\]\\["+attr+"\\]").last().prop('checked') ? 1 : 0);
        } else if ( $("#workArea #data\\[page\\]\\["+attr+"\\]").prop("tagName") == "TEXTAREA" && ( t = tinyMCE.get("data[page]["+attr+"]") !== null ) ) {
            page[attr] = t.getContent({format : 'text'});
            t = null;
        } else if ($("#workArea #data\\[page\\]\\["+attr+"\\]").length > 0){
            page[attr] = $("#workArea #data\\[page\\]\\["+attr+"\\]").last().val();
        }
    }
    return page;
}

/**
 * gatherPagedataValuesFromPanel()
 * @param pagedata object
 * @retun pagedata object
 * Gathers the values of pagedata object from the current page panel
 */
function gatherPagedataValuesFromPanel(pagedata) {
    var tinymce_load_failure = false;

    $("ul.pagedata-list .list-item-data-holder").each(function() {
        var holder = $(this);
        var list_item_data_id = holder.attr('data-list-item-data-id');

        if (!list_item_data_id) {
            var childWithId = holder.find('[data-list-item-data-id]').first();
            if (childWithId.length) {
                list_item_data_id = childWithId.attr('data-list-item-data-id');
            }
        }

        if (!list_item_data_id) {
            var namedField = holder.find('[name^="pagedata["]').first();
            if (namedField.length) {
                var nameAttr = namedField.attr('name');
                var match = nameAttr && nameAttr.match(/^pagedata\[([^\]]+)\]/);
                if (match && match[1]) {
                    list_item_data_id = match[1];
                }
            }
        }

        if (!list_item_data_id) {
            return;
        }

        var checkbox = holder.find('input[type="checkbox"][name="pagedata[' + list_item_data_id + '][value]"]').last();
        if (checkbox.length) {
            pagedata[list_item_data_id] = {
                'value': (checkbox.prop('checked') ? 1 : 0)
            };
            return;
        }

        var select = holder.find('select[name="pagedata[' + list_item_data_id + '][value]"]').last();
        if (select.length) {
            if (select.prop('multiple')) {
                var obj = {};
                select.find('optgroup').each(function(_, optgroup) {
                    var groupName = $(optgroup).attr('data-group-value');
                    var selected = $(optgroup).find('option:selected');

                    if (selected.length > 0) {
                        obj[groupName] = [];

                        selected.each(function() {
                            obj[groupName].push($(this).val());
                        });
                    }
                });

                pagedata[list_item_data_id] = {
                    'value': JSON.stringify(obj),
                    'type': 'text'
                };
            } else {
                pagedata[list_item_data_id] = {
                    'value': select.val()
                };
            }

            return;
        }

        var textarea = holder.find('textarea[name="pagedata[' + list_item_data_id + '][value]"]').last();
        if (textarea.length) {
            var editor = null;
            try {
                editor = tinyMCE.get('pagedata[' + list_item_data_id + '][value]');
            } catch (error) {
                editor = null;
            }

            if (editor !== null) {
                try {
                    pagedata[list_item_data_id] = {
                        'value': editor.getContent(),
                        'type': 'textarea'
                    };
                } catch (error) {
                    tinymce_load_failure = true;
                    return false;
                }
            } else {
                pagedata[list_item_data_id] = {
                    'value': textarea.val()
                };
            }

            return;
        }

        var hiddenFileInput = holder.find('input.real_file_value[data-list-item-data-id="' + list_item_data_id + '"]').last();
        if (hiddenFileInput.length) {
            pagedata[list_item_data_id] = {
                'value': hiddenFileInput.val()
            };

            return;
        }

        var valueInput = holder.find('input[name="pagedata[' + list_item_data_id + '][value]"]').last();
        if (!valueInput.length) {
            valueInput = holder.find('[data-list-item-data-id="' + list_item_data_id + '"][name^="pagedata[' + list_item_data_id + '"]').last();
        }

        if (valueInput.length) {
            pagedata[list_item_data_id] = {
                'value': valueInput.val()
            };
        }

        var typeInput = holder.find('input[name="pagedata[' + list_item_data_id + '][type]"]').last();
        if (typeInput.length && pagedata[list_item_data_id]) {
            pagedata[list_item_data_id].type = typeInput.val();
        }
    });

    if (tinymce_load_failure) {
        return false;
    }

    return pagedata;
}

/**
 * savePageVersion()
 * Main function for saving pages.
 * @param bool retreat_page_after_save - weather or not to run treatPage after save
 * @param bool reload_page_after_save - weather or not to reload the page after save
 */
function savePageVersion(retreat_page_after_save, reload_page_after_save, page_to_save) {
    if (busyLoading()) {
        return false;
    }
    ldr("saving ...");
    var page = {};
    if (typeof page_to_save !== "undefined") {
        page = page_to_save;
    }
    page = gatherPageValuesFromPanel(page);

    // if live page is temp then save it as default
    if (content_manager.page_live.type == "temp") {
        page['type'] = "default";
    } else {
        page['type'] = content_manager.page_live.type;
    }

    page.pagedata = {};
    page.pagedata = gatherPagedataValuesFromPanel(page.pagedata);

    if (page.pagedata === false) {
        return tooQuickAlert();
    }

    $("div.error").removeClass("error");
    $("div.alert").hide();

    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/save_page_version.php?page_id='+content_manager.page.id,
        data: {
            serialized_page: JSON.stringify(page)
        },
        success: function(result) {
            result = JSON.parse(result);
            if (result.response == 2) {
                setUnsavedChanges(false);
                setLastSaved();
                processUnsavedChangesStatus();

                getPage(
                    content_manager.page_live.id,
                    function(page){
                        ldr('loading page...');
                        // do getSiteTree then treatPage via a callback to minimize stress on server
                        getSiteTree(
                            content_manager.page_live.id,
                            function () {
                                treatPage(page);
                            }
                        );
                    },
                    result.history_page_id
                );
            } else {
                // this is also checked in the following php script
                if (cmPanelDynamicData.IS_ADMIN) {
                    var text = "There are validation issues on this page. As <strong>mtcadmin</strong>, do you want to try and force save / publish?",
                        title = "Force save / publish?";
                    $('#dialog').html(text);
                    $('#dialog').dialog('option', 'title', title);
                    $('#dialog').dialog('option', 'buttons', {
                        "Yes": function () {
                            $('#dialog').dialog("close");
                            $.ajax({
                                type: 'post',
                                cache: false,
                                url: 'ajax/save_page_version.php?page_id='+content_manager.page.id+'&force=true',
                                data: {
                                    serialized_page: JSON.stringify(page)
                                },
                                success: function(result) {
                                    result = JSON.parse(result);
                                    if (result.response == 2) {
                                        setUnsavedChanges(false);
                                        setLastSaved();
                                        processUnsavedChangesStatus();

                                        getPage(
                                            content_manager.page_live.id,
                                            function(page){
                                                ldr('loading page...');
                                                // do getSiteTree then treatPage via a callback to minimize stress on server
                                                getSiteTree(
                                                    content_manager.page_live.id,
                                                    function () {
                                                        treatPage(page);
                                                    }
                                                );
                                            },
                                            result.history_page_id
                                        );

                                    } else {
                                        displayValidationErrors(result);
                                        ldrFailure();
                                    }
                                }
                            });
                        },
                        "No": function () {
                            $('#dialog').dialog("close");
                            displayValidationErrors(result);
                            ldrFailure();
                        }
                    })
                    $('#dialog').dialog('open');
                } else {
                    displayValidationErrors(result);
                    ldrFailure();
                }
            }
        }
    });
    return false;
}

/**
 * displayValidationErrors()
 * @param result - result of save that didn't succeed
 * @return void
 */
function displayValidationErrors(result) {
    for (var field_id in result.all_errors_sorted_by_field_id) {
        var errors = result.all_errors_sorted_by_field_id[field_id];
        for (var error in errors) {
            if(errors.hasOwnProperty(error)){
                var row = $("#div_row_for_"+field_id);
                row.addClass("error");
                row.find("div.alert div.text").html(errors[error].message);
                row.find("div.alert").show();
                // scroll down to error
                $('html, body').animate({
                    scrollTop: $("#div_row_for_"+field_id).offset().top - 200
                }, 100);
            }
        }
    }
}

/**
 * Attach events to make the cm panel action buttons stick to the top when scrolling down or resizing.
 */
function pageActionBtnsFloat() {
    $(window).scroll(function() {
        pageActionBtnsFloatAdjust();
    }).resize(function(event) {
        if ($(".mainForm").length == 0) {
            return false;
        }
        $('.pageActionBtns').css("width", $(".mainForm").width());
        $('.pageActionBtns').css("left", $(".mainForm").offset().left); // ff fix
        pageActionBtnsFloatAdjust();
    }).trigger("resize");
}
/**
 * Make the cm panel action buttons stick to the top when scrolling down.
 */
function pageActionBtnsFloatAdjust() {
    if ($(".mainForm").length == 0 ) {
        return false;
    }
    var page_action_btns_el = $('.pageActionBtns');
    if (page_action_btns_el.hasClass('pageActionBtnsHovering')){
        var is_fixed = true;
    } else {
        var is_fixed = false;
    }
    var scroll_top = $(window).scrollTop();
    if (scroll_top > ($(".mainForm").offset().top * 0.9)) {
        var should_be_fixed = true;
    } else {
        var should_be_fixed = false;
    }
    if (should_be_fixed && !is_fixed) {
        page_action_btns_el.css({
            position: 'fixed',
            top: 0
        });
        page_action_btns_el.addClass('pageActionBtnsHovering');
    } else if (!should_be_fixed && is_fixed) {
        page_action_btns_el.removeClass('pageActionBtnsHovering');
        page_action_btns_el.css({
            position: 'static'
        });
    }
}

/*
 * Get the value of a param in a hash param string
 * either from the current location.hash string or
 * passed location_hash string
 */
function getHashValue(key, location_hash) {
    if (typeof location_hash === "undefined") {
        location_hash = location.hash;
    }
    var value = location_hash.match(new RegExp(key+'=([^&]*)'));
    if ( value === null || typeof value === "undefined" ) {
        return null;
    }
    return value[1];
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function getAnchorPageId(el) {
    var href = $(el).attr("href");
    return getHrefPageId(href);
}

function getHrefPageId(href) {
    var regex = new RegExp("[\\?&]page=([^&#]*)"),
        results = regex.exec(href);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function saveListSettings(el) {
    var settings = el.parent();
    var list_to_top;

    if (settings.children('input[name="item_list_top"]').prop('checked') == 1) {
        list_to_top = 1;
    } else {
        list_to_top = 0;
    }

    data = {

        item_list_id:       el.attr('data-item-list-id'),
        page_id:            getPageId("sandbox"),

        settings: {
            list_lock:              (settings.children('input[name="lock"]').prop('checked') ? 1 : 0),
            list_allow_more:        (settings.children('input[name="allow_more"]').prop('checked') ? 1 : 0),
            list_to_top:            list_to_top,
            list_type:              settings.children('input[name="item_list_type"]').val(),
            list_name:              settings.children('input[name="item_list_name"]').val(),
            list_info:              settings.children('input[name="item_list_info"]').val(),
            list_allow_more_max:    settings.children('input[name="item_list_allow_more_max"]').val(),
            list_allow_more_min:    settings.children('input[name="item_list_allow_more_min"]').val()
        }

    };

    settings.children('.ajax-loader').show();
    el.hide();

    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/update-item-list-settings.php?page_id='+getPageId("sandbox"),
        data: data,
        success: function(){

            settings.children('.ajax-loader').hide();
            el.show();
            setUnsavedChanges(true);
            ldrPending("loading....");
            reloadPagedata(
                getPageId("sandbox"),
                function() {
                    ldrSuccess();
                },
                function() {}
            );
        },
        error: function(jq_xhr, text_status, error_thrown) {
            if (content_manager.debug === 1) {
                consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
            } else {
                reloadPagedata(
                    getPageId("sandbox"),
                    function() {
                        ldrFailure();
                    },
                    function() {}
                );
            }
        },
    });
    return false;
}

/*
 * Get cm panel error messages that have been stored in a session to display in .cmsPanelMessages
 */
function loadPanelMessages() {
    $.ajax({
        url: 'templates/panel_messages.php',
        type: 'GET',
        dataType: 'html',
        timeout: content_manager.timeout_limit
    })
    .fail(function(result) {
        $(".cmsPanelMessages").html("error loading error messages");
    })
    .done(function(result) {
        $(".cmsPanelMessages").html(result);
        if (result === "") {
            $(".alertFieldset").hide();
        } else {
            $(".alertFieldset").show();
        }
    });
}

function saveListItemDataSettings(el) {
    ldrPending("updating pagedata settings...");
    var settings = el.parent();
    data = {
        page_list_id:                el.attr('data-list-id'),
        page_list_item_data_name:    settings.parent().parent().children('label').children('span').html(),
        page_id:                     getPageId("sandbox"),
        settings: {
            required:                   (settings.children('input[name="required"]').prop('checked') ? 1 : 0),
            setup:                      (settings.children('input[name="setup"]').prop('checked') ? 0 : 1),
            regex:                      settings.children('input[name="regex"]').val(),
            mime:                       settings.children('input[name="mime"]').val(),
            info:                       settings.children('input[name="info"]').val(),
            data1:                      settings.children('input[name="data1"]').val(),
            settings:                   settings.children('input[name="settings"]').val()
        }
    };
    if ( settings.children('input[name="allow_more"]').length > 0 ) {
        data.settings.allow_more = (settings.children('input[name="allow_more"]').prop('checked') ? 1 : 0);
    }
    if ( settings.children('input[name="data2"]').length > 0 ) {
        data.settings.data2 = settings.children('input[name="data2"]').val();
    }
    if ( settings.children('input[name="data3"]').length > 0 ) {
        data.settings.data3 = settings.children('input[name="data3"]').val();
    }
    if (settings.children('input[name="css_class"]').length > 0) {
        data.settings.css_class = settings.children('input[name="css_class"]').val();
    }
    if (settings.children('input[name="options"]').length > 0) {
        data.settings.options = settings.children('input[name="options"]').val();
    }
    settings.children('.ajax-loader').show();
    el.hide();
    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/update-list-item-data-settings.php?page_id='+getPageId("sandbox"),
        data: data,
        success: function(result){
            settings.children('.ajax-loader').hide();
            el.show();
            if ( result === "false" || result === false ) {
                settings.children('input[name="regex"]').addClass("error");
                ldrFailure();
            } else {
                settings.children('input[name="regex"]').removeClass("error");
                ldrPending("loading....");
                setUnsavedChanges(true);
                reloadPagedata(
                    getPageId("sandbox"),
                    function() {
                        ldrSuccess();
                    },
                    function() {}
                );
            }
        }
    });
    return false;
}

function getPage(page_id, callback, history_page_id) {
    var result;
    $.ajax({
        url: 'ajax/load_page.php',
        type: 'GET',
        dataType: 'json',
        data: {
            'page_id': page_id,
            'history_page_id': history_page_id
        },
        timeout: content_manager.timeout_limit
    })
    .fail(function(jq_xhr, text_status, error_thrown) {
        consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
        window.location.href = "./";
    })
    .done(function(result) {
        if (result === false) {
            window.location.href = "./";
        } else {
            callback(result);
        }
    });
}

function fieldsetToggles(dom_scope) {
    if ( typeof dom_scope === 'undefined' || dom_scope === false || dom_scope === "" || dom_scope === 0 ) {
        dom_scope = '#workArea';
    }

    $(dom_scope).find("fieldset a.show").on("click", function(event){
        cmsPreventDefault(event);
        el = $(this);
        var h_one = el.parent();
        var filedset = h_one.parent();
        var filedset_parent_li = filedset.parent();
        if ( filedset_parent_li.prop("tagName") != "LI" || typeof filedset_parent_li.attr("data-name") === "undefined"  ) {
            filedset_parent_li = null;
        }
        var display = 'block';
        h_one.siblings().stop(true, true).slideToggle(100, function(){
            txt = el.find("i.fa-caret-down,i.fa-caret-up");
            if(el.parent().siblings().is(':visible')) {
                display = 'block';
                txt.removeClass("fa-caret-down");
                txt.addClass("fa-caret-up");
            } else {
                display = 'none';
                txt.removeClass("fa-caret-up");
                txt.addClass("fa-caret-down");
            }
            try {
                if ( filedset_parent_li !== null ) {
                    localStorage.setItem("li_data_name_"+filedset_parent_li.attr("data-name")+"_fieldset", display);
                } else {
                    localStorage.setItem("fieldset#"+filedset.attr("id"), display);
                }
            } catch(e) {
                if ( isLocalStorageQuotaExceeded(e) ) {
                    localStorage.clear();
                }
            }
        });
    });

    $(dom_scope).find("fieldset").not(".simple_items").each(function(index, el) {
        el = $(el);
        var display = 1;

        var filedset_parent_li = el.parent();
        if ( filedset_parent_li.prop("tagName") != "LI" || typeof filedset_parent_li.attr("data-name") === "undefined" ) {
            filedset_parent_li = null;
        }

        if ( typeof el.attr("id") !== "undefined" && el.attr("id") !== null ) {

            if ( filedset_parent_li === null ) {
                display = localStorage.getItem("fieldset#"+el.attr("id"));
            } else {
                display = localStorage.getItem("li_data_name_"+filedset_parent_li.attr("data-name")+"_fieldset");
            }

            if ( typeof display !== "undefined" && display !== null) {
                el.children('div').css("display", display);

                if (display === "none") {
                    txt = el.find("i.fa-caret-up");
                    txt.removeClass("fa-caret-up");
                    txt.addClass("fa-caret-down");
                } else {
                    txt = el.find("i.fa-caret-down");
                    txt.removeClass("fa-caret-down");
                    txt.addClass("fa-caret-up");
                }

            } else if ( el.attr("id") == "edit_page_seo" || el.attr("id") == "edit_page_settings" ) {
                // by default close seo and settings tab
                el.children('div').css("display", "none");

                txt = el.find("i.fa-caret-up");
                txt.removeClass("fa-caret-up");
                txt.addClass("fa-caret-down");
            }
        }
    });

    // somewhere here i should fix the blue arrows on the side
}

function pagedataListItemDragAndDrop(el) {
    el.nestedSortable({
        handle: ".handle",
        listType: 'ul',
        items: 'li',
        isTree: true,
        maxLevels: 1,
        axis: "y",
        update: function(event,ui) {
            var newOrder = $(this).nestedSortable('toHierarchy');
            data = {
                'page_id': getPageId("sandbox"),
                'new_order': newOrder,
                'list_id': $(this).attr("data-list-id")
            };
            ldrPending("sorting fields...");
            $.ajax({
                type: 'post',
                cache: false,
                url: 'ajax/sort-list-items-pagedata.php',
                data: data,
                success: function() {
                    reloadPagedata(
                        getPageId("sandbox"),
                        function() {
                            ldrSuccess();
                        },
                        function() {}
                    );
                    setUnsavedChanges(true);
                    $('#dialog').dialog( "close" );
                },
            })
            .fail(function(){
                $('#dialog').dialog( "close" );
                reloadPagedata(
                    getPageId("sandbox"),
                    function() {
                        ldrFailure("error occured while sorting...");
                    },
                    function() {}
                );
            });
        }
    });
}

function ldrSuccess(message) {
    content_manager.loading = false;
    content_manager.loading_started = null;
    if ( typeof message !== "undefined" && message !== "" ) {
        $(".loaderMessage").html(message);
    }
    $(".controlPanelLoader").removeClass("error");
    $(".controlPanelLoader").addClass('success');
    $(".controlPanelLoader").fadeOut();
}
function ldrFailure(message) {
    content_manager.loading = false;
    content_manager.loading_started = null;
    if ( typeof message !== "undefined" && message !== "" ) {
        $(".loaderMessage").html(message);
    }
    loadPanelMessages();
    $(".controlPanelLoader").removeClass("success");
    $(".controlPanelLoader").addClass('error');
    $(".controlPanelLoader").fadeOut(2400);
}
function ldr(message) {
    ldrPending(message);
}
function ldrPending(message) {
    content_manager.loading = true;
    content_manager.loading_started = moment();
    if ( typeof message !== "undefined" && message !== "" ) {
        $(".loaderMessage").html(message);
    }
    $(".controlPanelLoader").removeClass("success");
    $(".controlPanelLoader").removeClass("error");
    $(".controlPanelLoader").fadeIn("fast");

    // check if we maybe should reload the page
    // check if theres content that need to be saved prior to this
    // maybe we don't need to do this
    /*
    if (moment().diff(content_manager.init_time) > content_manager.max_time_without_reload ) {
        location.reload();
    }*/
}
function ldrDone(message) {
    content_manager.loading = false;
    content_manager.loading_started = null;
    if ( typeof message !== "undefined" && message !== "" ) {
        $(".loaderMessage").html(message);
    }
    $(".controlPanelLoader").fadeOut(function(){
        $(".controlPanelLoader").removeClass("success");
        $(".controlPanelLoader").removeClass("error");
    });
}

function pagedataListDragAndDrop(el) {
    el.nestedSortable({
        forcePlaceholderSize: true,
        maxLevels: 1,
        distance: 0,
        delay:0,
        opacity: 0.6,
        listType: 'ul',
        dropOnEmpty: false,
        placeholder: 'ui-state-highlight',
        tabSize: 20,
        expandOnHover: 700,
        isTree: true,
        items: 'li',
        tolerance: "intersect",
        handle: ".handle",
        start: function( event, ui ) {
            $("ul.pagedata-list").addClass("dragAndDrop");
        },
        stop: function( event, ui ) {
            $("ul.pagedata-list").removeClass("dragAndDrop");
        },
        update: function(event,ui) {
            // just sort
            if ( ui.item.parent(".pagedata-list").length ) {
                ldrPending("sorting pagedata...");
                var newOrder = $(this).nestedSortable('serialize');
                // AJAX call to sort pages
                $.ajax({
                    type: 'get',
                    cache: false,
                    url: 'ajax/sort_pagedata.php',
                    data: newOrder,
                    success: function(result) {
                        if (result === "true") {
                            setUnsavedChanges(true);
                            ldrSuccess();
                        }
                    }
                })
                .fail(function(){
                    $('#dialog').dialog( "close" );
                    reloadPagedata(
                        getPageId("sandbox"),
                        function() {
                            ldrFailure("error occured while sorting...");
                        },
                        function() {}
                    );
                });

            } else {

                var parent_leaf = null;
                var leaf = ui.item;
                $("ul.pagedata-list > li").each(function(index, el) {
                    if ($(el).find("#"+ui.item.attr("id")).length) {
                        parent_leaf = $(el);
                    }
                });

                if( parent_leaf === null ) {
                    return false;
                }

                if ( leaf.attr("data-complexity") === "item_list" ) {
                    return false;
                }

                if ( parent_leaf.attr("data-complexity") === "item_list" ) {

                    var text = "Do you want to insert field '"+leaf.attr("data-name")+"' into list '"+parent_leaf.attr("data-name")+"' items?";
                    var title = "Field merge";
                    $('#dialog').html(text);
                    $('#dialog').dialog('option', 'title', title);
                    $('#dialog').dialog('option', 'buttons', {
                        "Confirm": function () {
                            data = {
                                'page_id': getPageId("sandbox"),
                                'first_list_id': leaf.attr("id").replace("list_",""),
                                'second_list_id': parent_leaf.attr("id").replace("list_",""),
                                'list_name': parent_leaf.attr("data-name")
                            };
                            $('#dialog').html("Merging...");
                            ldrPending("merging fields...");
                            $.ajax({
                                type: 'post',
                                cache: false,
                                url: 'ajax/merge-pagedata.php',
                                data: data,
                                success: function(data) {
                                    setUnsavedChanges(true);
                                    reloadPagedata(
                                        getPageId("sandbox"),
                                        function() {
                                            ldrSuccess();
                                        },
                                        function() {}
                                    );
                                    $('#dialog').dialog( "close" );
                                }
                            })
                            .fail(function(){
                                $('#dialog').dialog( "close" );
                                reloadPagedata(
                                    getPageId("sandbox"),
                                    function() {
                                        ldrFailure("error occured while sorting...");
                                    },
                                    function() {}
                                );
                            });
                        },
                        "Cancel": function () {
                            $('#dialog').dialog("close");
                            return false;
                        },
                    });
                    $('#dialog').dialog('open');

                } else if ( parent_leaf.attr("data-complexity") === "single_item" ) {

                    var text = "Do you want to group field '"+leaf.attr("data-name")+"' with field '"+parent_leaf.attr("data-name")+"' making a list?";
                    var title = "Please name new list!";
                    $('#dialog').html(text);
                    $('#dialog').dialog('option', 'title', title);
                    $('#dialog').dialog('option', 'buttons', {
                        "Confirm": function () {
                            text =  "Please name the complex item (Players, Employees, Quotes, etc.)";
                            text +=     "<div><br/>";
                            text +=         "<input type='text' name='item_list_name' id='dialog_item_list_name' class='text ui-widget-content ui-corner-all' />";
                            text +=     "</div>";
                            $('#dialog').html(text);
                            $('#dialog').dialog('option', 'title', title);
                            $('#dialog').dialog('option', 'buttons', {
                                "Submit": function () {
                                    var bValid = true;
                                    $('#dialog_item_list_name').removeClass( "ui-state-error" );
                                    if ( $('#dialog_item_list_name').val() === ""  ) {
                                        bValid = false;
                                        $('#dialog_item_list_name').addClass( "ui-state-error" );
                                    }
                                    if ( bValid ) {
                                        data = {
                                            'page_id': getPageId("sandbox"),
                                            'first_list_id': leaf.attr("id").replace("list_",""),
                                            'second_list_id': parent_leaf.attr("id").replace("list_",""),
                                            'list_name': $('#dialog_item_list_name').val()
                                        };
                                        $('#dialog').html("Merging...");
                                        ldrPending("merging fields...");
                                        $.ajax({
                                            type: 'post',
                                            cache: false,
                                            url: 'ajax/merge-pagedata.php',
                                            data: data,
                                            success: function(data) {
                                                setUnsavedChanges(true);
                                                $('#dialog').dialog("close");
                                                reloadPagedata(
                                                    getPageId("sandbox"),
                                                    function() {
                                                        ldrSuccess();
                                                    },
                                                    function() {}
                                                );
                                                $('#dialog').dialog( "close" );
                                            }
                                        })
                                        .fail(function(){
                                            $('#dialog').dialog( "close" );
                                            reloadPagedata(
                                                getPageId("sandbox"),
                                                function() {
                                                    ldrFailure("error occured while sorting...");
                                                },
                                                function() {}
                                            );
                                        });
                                    }
                                },
                                "Cancel": function () {
                                    $('#dialog').dialog("close");
                                    return false;
                                }
                            });
                            // display dialog box
                            $('#dialog').dialog('open');
                        },
                         "Cancel": function () {
                            $('#dialog').dialog("close");
                            return false;
                        }
                    });
                    // display dialog box
                    $('#dialog').dialog('open');
                }
            }
        }
    });
}

function addPagedata(el) {
    var title = "Add new pagedata.",
        options = $.parseJSON($('#pagedataTypes').attr('data-types')),
        text = "<p>Please enter a human readable name that would be unique for this kind of a field on this website. For example: <strong>Header Image</strong>, <strong>Frontpage Slideshow Text</strong>, <strong>Member Name</strong>.</p>";
        text += "<form class='dialogBoxForm' onkeypress='return event.keyCode != 13;'>";
        text += "<fieldset>";
        text += "<div class='row'>";
        text += "<label>Name: &nbsp;</label>";
        text += "<input type='text' name='new_pagedata_name' list='new_pagedata_names' id='new_pagedata_name' class='text ui-widget-content ui-corner-all' />";
        text += "</div>";
        text += "<div class='row'>";
        text += "<label>Type: &nbsp;</label>";
        text += "<select id='new_pagedata_type' name='new_pagedata_type'>";
        $.each(options, function(value, name) {
            text += "<option value='" + value + "'>" + name + "</option>";
        });
        text += "</select>";
        text += "</div>";
        text += "</fieldset>";
        text += "</form>";

    $('#dialog').html(text);

    $("#new_pagedata_name")
        .autocomplete({
            source: "ajax/get_existing_pagedata_names.php",
            minLength:0
    })
        .click(function(event) {
            cmsPreventDefault(event);
            $("#new_pagedata_name").autocomplete("search", "");
    });

    // dialog box options
    $('#dialog').dialog('option', 'width', '600px');
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'buttons', {
        Create: function () {
            ldrPending("adding pagedata ...");

            var data = {
                'new_pagedata_name': $("#new_pagedata_name").val().trim(),
                'new_pagedata_type': $("#new_pagedata_type").val(),
                'new_pagedata_value': $("#new_pagedata_value").val()
            };

            $.ajax({
                type: 'post',
                cache: false,
                url: 'ajax/add_pagedata.php?page_id='+getPageId("sandbox"),
                data: data,
                success: function(result) {
                    var pagedata = $(result);
                    if ( $("ul.pagedata-list").html() === "<p>No Content</p>" ) {
                        $("ul.pagedata-list").html("");
                    }
                    $("ul.pagedata-list").first().append(result);
                    setUnsavedChanges(true);
                    pagedataInit("#"+pagedata.attr("id"));
                    ldrSuccess();
                }

            })
            .fail(function(jq_xhr, text_status, error_thrown) {
                if (content_manager.debug === 1) {
                    consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
                }
                reloadPagedata(
                    getPageId("sandbox"),
                    function() {
                        ldrFailure();
                    },
                    function() {}
                );
            });
            $('#dialog').dialog('close');
        },
        Cancel: function () {
            $('#dialog').dialog('close');
        }
    });
    $('#dialog').dialog('open');
    return false;
}

function moveListItem(el) {
    // dont do it if something else is loading
    if (busyLoading()) {
        return false;
    }

    var list_id = el.attr("data-list-id");
    var list_item_id = el.attr("data-list-item-id");
    var direction = el.attr("data-direction");
    var data = {
        action_move_item:list_item_id,
        list_id:list_id,
        direction:direction
    };
    ldr("moving item...");
    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/move_item.php?page_id='+getPageId("sandbox"),
        data: data,
        timeout: content_manager.timeout_limit,
    })
    .done(function(result) {
        if ( direction == "down" ) {
            $("#list-item-"+list_item_id).insertAfter( $("#list-item-"+list_item_id).next(".list-item") );
        }else if ( direction == "up" ) {
            $("#list-item-"+list_item_id).insertBefore( $("#list-item-"+list_item_id).prev(".list-item") );
        }
        setUnsavedChanges(true);
        pagedataDestroy("#list_"+list_id);
        pagedataInit("#list_"+list_id);
        ldrSuccess();
    })
    .fail(function(result) {
        ldrFailure();
    })
    ;
    return false;
}

function listDelete(el) {
    var data = {

        item_list_id:       el.attr('data-item-list-id'),
        item_list_name:     el.attr('data-item-list-name'),
        page_id:            getPageId("sandbox"),

    };

    var title = "Confirmation!";
    var text = "Do you realy want to delete '"+data.item_list_name+"' list?";

    $('#dialog').html(text);

    // dialog box options
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'buttons', {
        "Confirm": function () {

            $('#dialog').html("Deleting...");

            $.ajax({
                type: 'post',
                cache: false,
                url: 'ajax/delete-list.php',
                data: data,
                success: function(result) {

                    $('#dialog').dialog( "close" );
                    setUnsavedChanges(true);
                    $('#list_'+data.item_list_id).fadeOut(170,function(){
                        $(this).remove();
                    });

                }
            });

        },
        "Cancel": function () {
            $('#dialog').dialog("close");
            return false;
        }
    });

    $('#dialog').dialog('open');

    return false;
}

function deleteListItem(el) {

    var list_id = el.attr("data-list-id"),
        list_item_id = el.attr("data-list-item-id"),
        number_of_items_in_list = parseInt($("#list-" + list_id + "-item-holder .list-item").length, 10),
        min_items_in_list = parseInt($("#list_" + list_id + " input[name=item_list_allow_more_min]").val(), 10),
        data = {
            action_delete_item: list_item_id,
            list_id: list_id
        };

    if (min_items_in_list !== 0 && number_of_items_in_list <= min_items_in_list) {
        // dialog box optionstitle = "";
        $('#dialog').html("The minimum number of items in this list is " + min_items_in_list + ".");
        $('#dialog').dialog('option', 'title', "Can't remove anymore!");
        $('#dialog').dialog('option', 'buttons', {
            OK: function () {
                $('#dialog').dialog('close');
            }
        });
        $('#dialog').dialog('open');
        return false;
    }

    ldrPending("deleting item...");

    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/delete_item.php?page_id='+getPageId("sandbox"),
        data: data,
        success: function(result) {
            if ( result == 'true' ) {
                $("#list-item-"+list_item_id).remove();
                setUnsavedChanges(true);
            }
            if ( $("#list-" + list_id + "-item-holder .list-item").length == 1 ) {
                $("#list-" + list_id + "-item-holder .list-item .remove-item-btn").hide();
                $("#list-" + list_id + "-item-holder .list-item .move-up-item-btn").hide();
                $("#list-" + list_id + "-item-holder .list-item .move-down-item-btn").hide();
            }
            ldrSuccess();
        }
    });
    return false;
}

function addNewListItem(el) {
    var list_id = el.attr("data-list-id"),
        number_of_items_in_list = parseInt($("#list-" + list_id + "-item-holder .list-item").length, 10),
        max_items_in_list = parseInt($("#list_" + list_id + " input[name=item_list_allow_more_max]").val(), 10),
        add_list_item_to_top = false,
        item_order_selector = "last",
        add_another_one_copy_content_choice,
        dialog;


    if (max_items_in_list !== 0 && number_of_items_in_list >= max_items_in_list) {
        // dialog box options
        $('#dialog').html("The maximum number of items in this list is " + max_items_in_list + ".");
        $('#dialog').dialog('option', 'title', "Can't add anymore!");
        $('#dialog').dialog('option', 'buttons', {
            "Ok": function () {
                $('#dialog').dialog('close');
            }
        });
        $('#dialog').dialog('open');
        return false;
    }

    // check to add item to top or bottom of the list
    if ($('input[name="add_list_item_to_top"]').length > 0) {
        add_list_item_to_top = true;
        item_order_selector = "first";
    }

    var addItemCallback = function(result) {
        if (add_list_item_to_top) {
            $("#list-" + list_id + "-item-holder").prepend(result);
        } else {
            $("#list-" + list_id + "-item-holder").append(result);
        }
        setUnsavedChanges(true);
        // move the clearfix
        $("#list-" + list_id + "-item-holder").append($("#list-" + list_id + "-item-holder > div[style]"));
        $("#list-" + list_id + "-item-holder div.list-item:" + item_order_selector).ready(function(){
            if ( $("#list-" + list_id + "-item-holder .list-item").length > 1 ) {
                $("#list-" + list_id + "-item-holder .list-item .remove-item-btn").show();
                $("#list-" + list_id + "-item-holder .list-item .move-up-item-btn").show();
                $("#list-" + list_id + "-item-holder .list-item .move-down-item-btn").show();
            }
            pagedataInit("#list-" + list_id + "-item-holder div.list-item:" + item_order_selector);
            ldrSuccess();
        });

    };

    var addMultipleFields = function (number_of_fields, params) {
        var num_additional_items = number_of_fields;
        while (num_additional_items >= 1) {
            addItem(params, addItemCallback);
            num_additional_items--;
            if ((number_of_items_in_list + num_additional_items + 1) > max_items_in_list) {
                break;
            }
        }
    };

    var add_item_params = {
        action_more: list_id,
        language: $(".languageSelect").val()
    };

    // 'remember' action
    add_another_one_copy_content_choice = JSON.parse(recallChoice("add_another_one_copy_content_choice_for_list_" + list_id));

    if (add_another_one_copy_content_choice !== null && add_another_one_copy_content_choice !== undefined) {
        ldr("adding item...");
        add_item_params.copy_content = add_another_one_copy_content_choice.remember;
        addMultipleFields(add_another_one_copy_content_choice.number_of_fields, add_item_params);
        return false;
    }

    var disable_field = "";
    if ((max_items_in_list - number_of_items_in_list) <= 0) {
        disable_field = " disabled='disabled'";
    }

    var title = "Add another one";
    var text = "<div class='row'>";
    text += "   <div class='inputWrap'>";
    text += "       <label for='numFields'>How many fields would you like to add?</label><br/>";
    text += "       <input" + disable_field + " type='number' value='1' min='1' max='" + (max_items_in_list - number_of_items_in_list);
    text += "'      name='numberOfAdditionalFields' id='numFields'> <small>(Remaining: <span class='remainingFields'>" + (max_items_in_list - number_of_items_in_list) + "</span>)</small>";
    text += "   </div>";
    text += "</div><br/><br/>";
    text += "<div class='row'>";
    text += "   Duplicate latest item?<br/>";
    text += "   <label><small>Remember my choice for this page(Always duplicate last item): &nbsp;</small></label>";
    text += "   <input type='checkbox' name='remember' id='remember' class='text' />";
    text += "</div>";

    var num_additional_items;

    dialog = $('#dialog');
    dialog.html(text);
    dialog.dialog({
        open : function ( event, ui ) {
            dialog.find('[name="numberOfAdditionalFields"]').on('change', function () {
                var input_value = parseInt($(this).val(),10);
                var max_value = (max_items_in_list - number_of_items_in_list);
                dialog.find('.remainingFields').html(max_value - input_value);
            });
        }
    });
    dialog.dialog('option', 'title', title);
    dialog.dialog('option', 'width', '400px');
    dialog.dialog('option', 'buttons', {

        "Duplicate": function () {
            num_additional_items = parseInt(dialog.find('input[name="numberOfAdditionalFields"]').val(),10);
            if (isNaN(num_additional_items)) {
                num_additional_items = 0;
            }
            ldr("adding item...");

            if ( $("#remember").prop("checked") ) {
                rememberChoice("add_another_one_copy_content_choice_for_list_" + list_id, JSON.stringify({
                    remember : 1,
                    number_of_fields : num_additional_items
                }));
            }
            add_item_params.copy_content = 1;
            addMultipleFields(num_additional_items,add_item_params);
            $('#dialog').dialog('close');
        },
        "Don't Duplicate": function () {
            num_additional_items = parseInt($('#dialog').find('input[name="numberOfAdditionalFields"]').val(),10);
            if (isNaN(num_additional_items)) {
                num_additional_items = 0;
            }
            ldr("adding item...");

            if ( $("#remember").prop("checked") ) {
                rememberChoice("add_another_one_copy_content_choice_for_list_" + list_id, JSON.stringify({
                    remember : 0,
                    number_of_fields : num_additional_items,
                }));
            }
            add_item_params.copy_content = 0;
            addMultipleFields(num_additional_items, add_item_params);
            dialog.dialog('close');
        },
        "Cancel" : function () {
            dialog.dialog('close');
        }
    });
    if ( cmPanelDynamicData.IS_ADMIN ) {
        dialog.dialog('open');
    } else {
        ldr("adding item...");
        add_item_params.copy_content = 0;
        addItem(
            add_item_params,
            function(result) {
                if (add_list_item_to_top) {
                    $("#list-" + list_id + "-item-holder").prepend(result);
                } else {
                    $("#list-" + list_id + "-item-holder").append(result);
                }
                setUnsavedChanges(true);
                // move the clearfix
                $("#list-" + list_id + "-item-holder").append($("#list-" + list_id + "-item-holder > div[style]"));
                pagedataInit("#list-" + list_id + "-item-holder div.list-item:" + item_order_selector);
                ldrSuccess();
            }
        );
    }

    return false;
}

function addItem(data, callback) {
    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/add_item.php?page_id='+getPageId("sandbox"),
        data: data,
        success: function(result) {
            callback(result);
        }
    })
    .fail(function(jq_xhr, text_status, error_thrown) {
        if (content_manager.debug === 1) {
            consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
        }
        reloadPagedata(
            getPageId("sandbox"),
            function() {
                ldrFailure();
            },
            function() {}
        );
    });
}

function listCopy(el) {
    var page_list_id = el.attr('data-item-list-id');
    var title = "Copy";
    var text = "Copy with populated data?";
    $('#dialog').html(text);
    // dialog box options
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'buttons', {
        "Yes": function () {
            copyPagedata(1, page_list_id);
            return;
        },
        "No, Empty": function () {
            copyPagedata(0, page_list_id);
            return;
        }
    });
    $('#dialog').dialog('open');
}

function copyPagedata(with_data,page_list_id) {

    var data = {
        with_data:          with_data,
        page_id:            getPageId("sandbox"),
        page_list_id:       page_list_id,
    };

    $('#dialog').html("Copying...");
    $('#dialog').dialog('option', 'buttons', {});

    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/copy_pagedata.php',
        data: data,
        success: function(result) {
            if ( result != "false" ) {
                // Store as JSON via xds helper to avoid [object Object]
                content_manager.xds.setObject('clipboard_pagedata', result, function(response){});

                $('#dialog').dialog("close");
            } else {
                $('#dialog').html("<span style='color:red'>Failed!</span>");
                $('.ui-dialog').fadeOut(250, function(){$('#dialog').dialog("close");});
            }
        },
        error: function(result) {
            $('#dialog').html("<span style='color:red'>Failed!</span>");
            $('.ui-dialog').fadeOut(250, function(){$('#dialog').dialog("close");});
        }
    });
}

function listLockBtn(el) {

    var list_id = el.attr('data-list-id');

    var data = {
        page_id:            getPageId("sandbox"),
        page_list_id:       list_id,
        page_list_lock:     (el.hasClass('fa-lock') ? 0 : 1)
    };

    el.hide();
    $('#list-' + list_id + '-lock-btn-loader').show();

    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/update-list-lock.php',
        data: data,
        success: function(result) {
            if ( result === "true" || result === true ) {
                setUnsavedChanges(true);
                $('#list-'+data.page_list_id+'-lock-btn-loader').hide();

                $('#list-'+data.page_list_id+'-lock-btn').removeClass('fa-lock');
                $('#list-'+data.page_list_id+'-lock-btn').removeClass('fa-unlock');

                if ( data.page_list_lock == 0 ) {
                    $('#list-'+data.page_list_id+'-lock-btn').addClass('fa-unlock');
                } else {
                    $('#list-'+data.page_list_id+'-lock-btn').addClass('fa-lock');
                }

                $('#list-'+data.page_list_id+'-lock-btn').show();

            } else {

                $('#list-'+data.page_list_id+'-lock-btn-loader').hide();
                $('#list-'+data.page_list_id+'-lock-btn').show();

            }
        },
        error: function(result) {
            $('#list-'+data.page_list_id+'-lock-btn-loader').hide();
            $('#list-'+data.page_list_id+'-lock-btn').show();
        }
    });
}

function listChangeMoreTextBtn(el) {
    var list_id = el.attr('data-list-id');

    if ( el.attr('data-open') == "false" ) {

        el.css('color', 'green');

        $('#list-' + list_id + '-more_text').show();
        $('#list-' + list_id + '-more-btn').hide();

        el.attr('data-open', "true");

    } else {

        el.hide();

        var data = {
            page_id:            getPageId("sandbox"),
            page_list_id:       list_id,
            page_list_more_text:$('#list-' + list_id + '-more_text').val()
        };

        $.ajax({
            type: 'post',
            cache: false,
            url: 'ajax/update-list-more_text.php',
            data: data,
            success: function(result) {
                if ( result === true || result === "true" ) {
                    setUnsavedChanges(true);
                    $('#list-'+data.page_list_id+'-more_text').hide();

                    $('#list-'+data.page_list_id+'-more-btn > button').html($('#list-'+data.page_list_id+'-more_text').val());
                    $('#list-'+data.page_list_id+'-more-btn').show();

                    $("#list-"+data.page_list_id+"-more_text-btn").attr('data-open', "false");
                    $("#list-"+data.page_list_id+"-more_text-btn").css('color', '');
                    $("#list-"+data.page_list_id+"-more_text-btn").show();

                } else {

                    $('#list-'+data.page_list_id+'-more_text').css('border-color', 'red');

                }
            },
            error: function(result) {
                $('#list-'+data.page_list_id+'-more_text').css('border-color', 'red');
            }
        });

    }
}

function deleteImage(el) {

    var row = el.parent().parent();
    var list_item_data_id = el.attr('data-list-item-data-id');
    var imgSrc = el.closest('.image_container').find('img').attr('src');


    // Optimistic UI clear
    row.children('.image_container').hide();
    $("#pagedata\\[" + list_item_data_id + "\\]\\[value\\]").val("");
    setUnsavedChanges(true);

    $.ajax({
        url: 'ajax/delete-image.php', // adjust if needed
        type: 'POST',
        dataType: 'json',
        data: { id: list_item_data_id, src: imgSrc },
        timeout: 5000
    }).done(function (resp) {
        if (!resp || resp.ok !== true) {
            alert((resp && resp.message) ? resp.message : 'Could not delete image on server.');
        }
    }).fail(function (xhr, status) {
        alert('Network error while deleting the image on the server.');
    });

    return false;
}

function deleteFile(el) {
    var row = el.parent().parent();
    row.children('input.real_file_value').val("");
    row.children('.file_container').hide();
    var list_item_data_id = el.attr('data-list-item-data-id');
    $("#pagedata\\[" + list_item_data_id + "\\]\\[value\\]").val("");
    setUnsavedChanges(true);
    return false;
}

/**
 * Get current relevant page id
 * @param string type ("live"/"sandbox"/null)
 * @return int id / null
 */
function getPageId(type) {
    if (content_manager.page == null) {
        return null
    }
    if (typeof type === "undefined" ) {
        type = "sandbox";
    }

    if (type == "sandbox") {
        if (typeof content_manager.page_sandbox === "undefined") {
            return content_manager.page.id;
        } else {
            return content_manager.page_sandbox.id;
        }
    } else if (type == "live") {
        if (typeof content_manager.page_live === "undefined") {
            return content_manager.page.id;
        } else {
            return content_manager.page_live.id;
        }
    } else if (type == "history") {
        if (typeof content_manager.page.history_page === "undefined") {
            return content_manager.page.id;
        } else {
            return content_manager.page.history_page.id;
        }
    } else {
        return content_manager.page.id;
    }
}

function busyLoading() {
    if ( $(".controlPanelLoader").css("display") == "block" && !$(".controlPanelLoader").hasClass("success")) {
        return true;
    }
    return false;
}

function listItemDataDelete(el){

    var data = {
        list_id:            el.attr('data-item-list-id'),
        list_name:          el.attr('data-item-list-name'),
        list_item_data_name:el.attr('data-name'),
        page_id:            getPageId("sandbox")
    };

    var title = "Deleting data field!";
    var text = "Do you realy want to delete <strong>"+data.list_item_data_name+"</strong> data field?<br/><br/>If this field in part of an item it shall be deleted from all items on this page.";
    $('#dialog').html(text);

    // dialog box options
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'buttons', {
        "Confirm": function () {
            $('#dialog').html("Deleting...");
            $.ajax({
                type: 'post',
                cache: false,
                url: 'ajax/delete-item-list-data.php',
                data: data,
                success: function(result) {
                    $('#dialog').dialog("close");
                    setUnsavedChanges(true);
                    $('#list_'+data.list_id+' li[data-name="'+data.list_item_data_name+'"]').fadeOut(170,function(){
                        $(this).remove();
                        if ( $('ul[data-list-id="'+data.list_id+'"] > li').length === 0 ) {
                            $('#list_'+data.list_id).fadeOut(170,function(){
                                $(this).remove();
                            });
                        }
                    });
                }
            });
        },
        "Cancel": function () {
            $('#dialog').dialog("close");
            return false;
        }
    });

    $('#dialog').dialog('open');
}

function listItemDataLock(el){

    var list_item_data_id = el.attr('data-list-item-data-id');
    var list_id = el.attr('data-list-id');
    var page_list_item_data_name = el.attr('data-list-item-data-name');

    var data = {
        page_id:                    getPageId("sandbox"),
        page_list_item_data_id:     list_item_data_id,
        page_list_item_data_name:   page_list_item_data_name,
        page_list_item_data_lock:   (el.hasClass('fa-lock') ? 0 : 1)
    };

    $('#list_' + list_id + ' li[data-name="' + data.page_list_item_data_name + '"] .list-item-data-lock-btn').hide();
    $('#list_' + list_id + ' li[data-name="' + data.page_list_item_data_name + '"] .ajax-loader').show();

    ldr("locking fields...");

    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/update-list-item-data-lock.php',
        data: data,
        success: function(result) {
            if ( result === true || result === "true" ) {
                ldrSuccess();
                setUnsavedChanges(true);
                $('#list_' + list_id + ' li[data-name="' + data.page_list_item_data_name + '"] .ajax-loader').hide();
                $('#list_' + list_id + ' li[data-name="' + data.page_list_item_data_name + '"] .list-item-data-lock-btn').removeClass('fa-lock');
                $('#list_' + list_id + ' li[data-name="' + data.page_list_item_data_name + '"] .list-item-data-lock-btn').removeClass('fa-unlock');
                if ( data.page_list_item_data_lock == 0 ) {
                    $('#list_' + list_id + ' li[data-name="' + data.page_list_item_data_name + '"] .list-item-data-lock-btn').addClass('fa-unlock');
                } else {
                    $('#list_' + list_id + ' li[data-name="' + data.page_list_item_data_name + '"] .list-item-data-lock-btn').addClass('fa-lock');
                }
                $('#list_' + list_id + ' li[data-name="' + data.page_list_item_data_name + '"] .list-item-data-lock-btn').show();
            } else {
                ldrFailure("error locking");
                $('#list_' + list_id + ' li[data-name="' + data.page_list_item_data_name + '"] .list-item-data-lock-btn').hide();
                $('#list_' + list_id + ' li[data-name="' + data.page_list_item_data_name + '"] .list-item-data-lock-btn').show();
            }
        },
        error: function(result) {
            ldrFailure("error locking");
            $('#list_' + list_id + ' li[data-name="' + data.page_list_item_data_name + '"] .list-item-data-lock-btn').hide();
            $('#list_' + list_id + ' li[data-name="' + data.page_list_item_data_name + '"] .list-item-data-lock-btn').show();
        }
    });
}

function togglePagedataSettings(el){
    el.parent().find('.pagedata-settings').stop(true, true).slideToggle(100);
}

function toggleListSettings(el){
    el.parent().find('.list-settings').stop(true, true).slideToggle(100);
}

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

function datetimeInput(el) {

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

    if ( el.val() === "" && format === "d/m/Y H:i" ) {
        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])
    });
}

function generateTrigger(request, callback) {
    ldrPending("generating trigger...");
    $.ajax({
        timeout: content_manager.timeout_limit * 10, // long load
        cache: false,
        url: 'ajax/create_trigger.php',
        type: 'POST',
        data: request
    })
    .done(function(result) {
        if ( result === true || result === "true" ) {
            ldrSuccess();
            callback();
        } else {
            ldrFailure();
        }
    })
    .fail(function() {
        ldrFailure();
    })
    ;
}

function createTrigger(el){
    var title = "Trigger Creation",
        dialogue_form_setup = {
            lapsg_button_text: {
                label: 'Trigger Label:',
                id: 'lapsg_button_text',
                type: 'text',
                value: "Add New",
                hint: "The label for the trigger button. For UX append with relevant name ('Article','Event',..)"
            },
            structure_from_template: {
                label: 'Pagedata structure from template (Don\'t forget to save your structure <i class="fa fa-suitcase"></i>) :',
                id: 'structure_from_template',
                type: 'checkbox',
                checked: 'checked',
                hint: "If checked - when you run this trigger the pagedata structure will come from the template structure rather than within the logic.\nThis is a more dynamic solution - allowing you not to regenerate the trigger if you do changes to the page template."
            },
            lapsg_for_client: {
                label: 'Client Friendly:',
                id: 'lapsg_for_client',
                type: 'checkbox',
                checked: 'checked',
                hint: "Should pages this trigger generates have a placeholder title 'Enter title here' and also be deletable by client also client-friendly in other ways."
            },
            generate_only_temp_pages: {
                label: 'Only Temporary Pages:',
                id: 'generate_only_temp_pages',
                type: 'checkbox',
                checked: 'checked',
                hint: "This will make all pages generated by this trigger temporary - thus automatically deleted if not saved &amp; abandoned.\nDoesn't work when also transfering Child-Pages."
            },
            format_and_simplify_logic: {
                label: 'Format &amp; Simplify Logic:',
                id: 'format_and_simplify_logic',
                type: 'checkbox',
                checked: 'checked',
                hint: "If checked - the generated logic shall be more readable &amp; managable (JSON prettified and default values removed)."
            },
            lapsg_recursive: {
                label: 'Transfer Child-Pages:',
                id: 'lapsg_recursive',
                type: 'checkbox',
                hint: "When this trigger is pressed - should also subpages (this page might have) be generated?\nLeave unchecked, unless you are creating a listing within a listing."
            },
            lapsg_with_content: {
                label: 'Transfer Content:',
                id: 'lapsg_with_content',
                type: 'checkbox',
                hint: "Requires 'Pagedata structure from template' to be unchecked otherwise the structure is responsible if content shall transfer.\nShould this pages content be transferred together with the structure?\nIf this is meant to generate an empty entry like an empty news article - press No."
            },
    };

    $('#dialog').html(dialogueBuilder(dialogue_form_setup));
    $("#dialog .dialogBoxForm .hint").tooltip();

    $("#lapsg_with_content")
        .attr("readonly", "readonly")
        .attr("disabled", "disabled");

    $("#structure_from_template").on("change", function () {
        if ($(this).prop("checked")) {
            $("#lapsg_with_content")
                .prop("checked", false)
                .attr("readonly", "readonly")
                .attr("disabled", "disabled");
        } else {
            $("#lapsg_with_content")
                .attr("readonly", false)
                .attr("disabled", false);
        }
    });

    $("#lapsg_recursive").on("change", function () {
        if ($(this).prop("checked")) {
            $("#generate_only_temp_pages")
                .prop("checked", false)
                .attr("readonly", "readonly")
                .attr("disabled", "disabled");
        } else {
            $("#generate_only_temp_pages")
                .attr("readonly", false)
                .attr("disabled", false);
        }
    });

    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '700px');
    $('#dialog').dialog('option', 'buttons', {
        "Submit": function () {
            var valid = true;
            $('#lapsg_button_text').removeClass( "ui-state-error" );
            if ( $('#lapsg_button_text').val() === "" ) {
                valid = false;
                $('#lapsg_button_text').addClass( "ui-state-error" );
            } else {
                generateTrigger(
                    {
                        'page_id': getPageId("live"),
                        'create_lapsg': true,
                        'lapsg_button_text':  $("#lapsg_button_text").val(),
                        'lapsg_recursive': ( $("#lapsg_recursive").prop("checked" ) ? 1 : 0 ),
                        'lapsg_for_client': ( $("#lapsg_for_client").prop("checked" ) ? 1 : 0 ),
                        'lapsg_with_content': ( $("#lapsg_with_content").prop("checked" ) ? 1 : 0 ),
                        'generate_only_temp_pages': ( $("#generate_only_temp_pages").prop("checked" ) ? 1 : 0 ),
                        structure_from_template: ($("#structure_from_template").prop("checked") ? 1 : 0),
                        format_and_simplify_logic: ($("#format_and_simplify_logic").prop("checked") ? 1 : 0),
                    },
                    function() {
                        getSiteTree(getPageId("live"));
                    }
                );
                $('#dialog').dialog("close");
                return false;
            }
        },
        "Cancel": function () {
            $('#dialog').dialog("close");
            return false;
        }
    });
    $("#dialog").dialog('open'); return false;
}

/**
 * Show (draft) page preview
 */
function pagePreviewBtn(page_id, page_url) {
    if (typeof page_id === "undefined") {
        page_id = content_manager.page.id;
    }
    if (typeof page_url === "undefined") {
        page_url = content_manager.page.url;
    }
    $(".hidden-preview-page-btn").attr("href",page_url+'?_cms_preview_page_id='+page_id,'_blank');
    $(".hidden-preview-page-btn")
    .fancybox({
        type: 'iframe',
        fitToView : false,
        autoSize : false,
        height : "100%",
        width : "100%",
    }).trigger('click');
    return false;
}

/**
 * Show adv page preview.
 * (Save page as temp and show preview of that)
 */
function pageAdvPreviewBtn() {
    ldr("making preview...");
    savePage();
    var page = {};
    var t;
    for (var attr in content_manager.page) {
        if ( $("#workArea #data\\[page\\]\\["+attr+"\\]").attr("type") === "checkbox" ) {
            page[attr] = ($("#workArea #data\\[page\\]\\["+attr+"\\]").last().prop('checked') ? 1 : 0);
        } else if ( $("#workArea #data\\[page\\]\\["+attr+"\\]").prop("tagName") == "TEXTAREA" && ( t = tinyMCE.get("data[page]["+attr+"]") !== null ) ) {
            page[attr] = t.getContent({format : 'text'});
            t = null;
        } else {
            page[attr] = $("#workArea #data\\[page\\]\\["+attr+"\\]").last().val();
        }
    }
    page.pagedata = {};
    page.pagedata = gatherPagedataValuesFromPanel(page.pagedata);

    if (page.pagedata === false) {
        return tooQuickAlert();
    }

    $("div.error").removeClass("error");
    $("div.alert").hide();

    page['type'] = 'temp';
    page['save_for_preview'] = true;

    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/save.php?page_id='+content_manager.page.id,
        data: {
            serialized_post: JSON.stringify(page)
        },
        success: function(result) {
            result = JSON.parse(result);
            if ( result.response == 2 ) {
                $(".hidden-preview-page-btn").attr("href",content_manager.page.url+'?_cms_preview_page_id='+content_manager.page.id,'_blank');
                $(".hidden-preview-page-btn")
                .fancybox({
                    type: 'iframe',
                    fitToView : false,
                    autoSize : false,
                    height : "100%",
                    width : "100%",
                })
                .trigger('click');
                ldrSuccess();
            } else {

                displayValidationErrors(result);
                ldrFailure();
            }
        }
    });

    return false;
}

/**
 * function toggleSettingsLock(object)
 * Function required for alowing administrators hide page settings from regular
 * users. It's sending current key and value to admin options AJAX, destination
 * script will update database. On success action it will receive JSON response
 * with success = true. In all cases ldr, ldrSuccess and ldrFailure highlight
 * state.
 *
 * @return null
 */
var toggleSettingsLock = function(el) {
    var key = el.data('key'),
        val = el.is(':checked');

    $.ajax({
        type: 'post',
        timeout: content_manager.timeout_limit,
        data:{
            options: {
                'key': key,
                'value': val
            }
        },
        cache: false,
        dataType: 'json',
        url: 'ajax/settings-lock-toggle.php',
        beforeSend: function() {
            ldr("Updating option...");
        }
    })
    .done(function(xhr) {
        if ( xhr.success !== false || xhr.success !== "false" ) {
            ldrSuccess('Option updated');
        } else {
            ldrFailure();
        }
    })
    .fail(function(xhr) {
        ldrFailure('Error: cannot apply options');
    });
}

/**
 * function showHelpDialogue(object)
 * Show help dialogue.
 * @return null
 */
function showHelpDialogue(el) {
    var title = "Information for you";
    var text = $(el).find(".text").html();
    $('#dialog').html(text);
    $('#dialog').dialog('option', 'width', 600);
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'buttons', {
        "Thanks" : function () {
            $('#dialog').dialog('close');
        },
    });
    $('#dialog').dialog('open');
}

/*
 * function stripTags(input, allowed)
 * PHP Function strip_tags() replicated for JS
 * @author Gustav Lindqvist
 * @link http://phpjs.org/functions/strip_tags/
 * @return string
 */
function stripTags(input, allowed) {
  allowed = (((allowed || '') + '')
    .toLowerCase()
    .match(/<[a-z][a-z0-9]*>/g) || [])
    .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
  var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
    commentsAndPhpTags = /<!--|<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
  return input.replace(commentsAndPhpTags, '')
    .replace(tags, function($0, $1) {
      return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}

/**
 * function lockVersion(el)
 * Lock a page version from being auto deleted
 * return success
 */
function lockVersion(el) {
    var page_id = el.attr("data-page-id");

    ldr("locking version...");

    $.ajax({
        type: 'post',
        timeout: content_manager.timeout_limit,
        data:{
            page_id: page_id
        },
        cache: false,
        url: 'ajax/lock_page_history_version.php',
    })
    .done(function(result) {
        if (result == "1") {
            el.children("i").attr("class","fa fa-lock");
        } else {
            el.children("i").attr("class","fa fa-unlock-alt");
        }
        ldrSuccess();
    })
    .fail(function(xhr) {
         ldrFailure();
    });
}

/**
 * toggle unsaved changes on page field changes
 */
function setUnsavedChangesOnPageFieldChanges(dom_scope) {
    for (var attr in content_manager.page) {
        $(dom_scope).find("#data\\[page\\]\\["+attr+"\\]")
            .off("keyup", function(){setUnsavedChanges()})
            .on("keyup", function(){setUnsavedChanges()})
            .off("change", function(){setUnsavedChanges()})
            .on("change", function(){setUnsavedChanges()})
        ;
    }
}

/**
 * toggle unsaved changes on pagedata field changes
 */
function setUnsavedChangesOnPagedataFieldChanges(dom_scope) {
    $(dom_scope).find(".list-item-data-holder select, .list-item-data-holder input, .list-item-data-holder textarea")
        .filter(function() {
            return this.id.match(/^pagedata\[[0-9]+\]/);
        })
    .each(function(index, el) {
        $(el)
            .off("keyup", function(){setUnsavedChanges()})
            .on("keyup", function(){setUnsavedChanges()})
            .off("change", function(){setUnsavedChanges()})
            .on("change", function(){setUnsavedChanges()})
        ;
    });
}

/**
 * Store when last save was triggered
 */
function setLastSaved(last_saved_moment) {
    if (typeof last_saved_moment === "undefined") {
        var last_saved_moment = moment();
    }
    content_manager.last_saved = last_saved_moment;
}

/**
 * Process unsaved changes status
 */
function processUnsavedChangesStatus(){
    if (content_manager.page === null) {
        return;
    }
    if (cmPanelDynamicData.HISTORY) {
        if (content_manager.page.type == "default" && content_manager.unsaved_changes == false && content_manager.page_live.type != "temp") {
            $(".saveTriggerBtn").hide();
            $(".savePageBtn").hide();
            $(".savedBtn").show();
            $(".saveForReviewPageBtn").removeClass("disabledBtn");
            $(".commitPageBtn").removeClass("disabledBtn");
            $(".cancelUnsavedChangesBtn").hide();
        } else if(content_manager.page.type == "default" && content_manager.unsaved_changes == true) {
            $(".savePageBtn").show();
            $(".saveTriggerBtn").hide();
            $(".savedBtn").hide();
            $(".commitPageBtn").addClass("disabledBtn");
            $(".saveForReviewPageBtn").addClass("disabledBtn");
            $(".cancelUnsavedChangesBtn").show();
        }
        if (content_manager.page.same_as_current_version) {
            $(".commitPageBtn").addClass("disabledBtn");
            $(".saveForReviewPageBtn").hide();
        } else {
            $(".saveForReviewPageBtn").show();
        }
        if (content_manager.page.same_as_current_version) {
            $(".saveForReviewPageBtn").hide();
            $(".commitPageBtn").hide();
            $(".currentBtn").show();
            $(".goToCurrentPageBtn").hide();
        } else {
            $(".saveForReviewPageBtn").show();
            $(".commitPageBtn").show();
            $(".currentBtn").hide();
            $(".goToCurrentPageBtn").show();
        }
        if (typeof content_manager.page.history_page != "undefined" &&
            content_manager.page.history_page.review_status == 1 ) {
            $(".pendingReviewBtn").show();
            $(".saveForReviewPageBtn").hide();
            $(".declinePageBtn").show();
            $(".goToCurrentPageBtn").hide();
        } else {
            $(".pendingReviewBtn").hide();
            $(".declinePageBtn").hide();
            if (!content_manager.page.same_as_current_version) {
                $(".goToCurrentPageBtn").show();
            }
        }
        if (content_manager.page.type == "button") {
            $(".saveTriggerBtn").show();
            $(".savePageBtn").hide();
            $(".savedBtn").hide();
            $(".commitPageBtn").hide();
            $(".saveForReviewPageBtn").hide();
            $(".goToCurrentPageBtn").hide();
            $(".cancelUnsavedChangesBtn").hide();
        }
    } else {
        if(content_manager.page.type === "default" && content_manager.unsaved_changes === true) {
            $(".cancelUnsavedChangesBtn").show();
        } else {
            $(".cancelUnsavedChangesBtn").hide();
        }
    }
}

/**
 * goToCurrentPageBtn()
 * Basically a "cancel" button for when you are on a version or temp and you want to go to the "current" page
 */
function goToCurrentPageBtn() {
    ldr("loading...");
    getPage(getPageId("live"), function(page){
        ldrDone();
        if (content_manager.unsaved_changes === false) {
            ldr("fetching page...");
            treatPage(page);
        } else {
            var title = "Go to current",
                text  = "Are you sure? Leaving will erase all unsaved changes.";
            $('#dialog').html(text);
            $('#dialog').dialog('option', 'title', title);
            $('#dialog').dialog('option', 'width', '427px');
            $('#dialog').dialog('option', 'buttons', {
                "Yes": function () {
                    $('#dialog').dialog("close");
                    treatPage(page);
                },
                "Cancel": function () {
                    $('#dialog').dialog("close");
                },
            })
            $('#dialog').dialog('open');
        }
    });
}

/**
 * cancelUnsavedChangesBtn()
 * For when your want to cancel all unsaved changes
 */
function cancelUnsavedChangesBtn() {
    ldr("loading...");
    getPage(
        getPageId("live"),
        function(page){
            ldrDone();
            if (content_manager.unsaved_changes === false) {
                ldr("fetching page...");
                treatPage(page);
            } else {
                var title = "Cancel unsaved changes",
                    text  = "Are you sure? This will erase all unsaved changes.";
                $('#dialog').html(text);
                $('#dialog').dialog('option', 'title', title);
                $('#dialog').dialog('option', 'width', '427px');
                $('#dialog').dialog('option', 'buttons', {
                    "Yes": function () {
                        $('#dialog').dialog("close");
                        treatPage(page);
                    },
                    "Cancel": function () {
                        $('#dialog').dialog("close");
                    },
                })
                $('#dialog').dialog('open');
            }
        },
        getPageId("history")
    );
}

/**
 * Set content_manager.unsaved_changes flag
 * @param string status
 */
function setUnsavedChanges(status) {
    if (typeof status === "undefined") {
        status = true;
    }
    content_manager.unsaved_changes = status;
    if (cmPanelDynamicData.HISTORY && content_manager.unsaved_changes == true && content_manager.page_live.type != "temp") {
        content_manager.page.same_as_current_version = false;
        if (typeof content_manager.page.history_page !== "undefined") {
            content_manager.page.history_page.review_status = 0;
        }
    }
    processUnsavedChangesStatus();
}

/**
 * displayVersionInformationBtn()
 */
function displayVersionInformationBtn(el) {
    var title = "Version "+el.data("version")+" Information",
        text  = "<p>This version "+el.data("creation")+".</p>"+
                "<p>Version history: "+el.data("history")+".</p>"+
                "<p>Comment by the editor: <strong>"+el.data("comment")+"</strong></p>";
    $('#dialog').html(text);
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '427px');
    $('#dialog').dialog('option', 'buttons', {
        "OK": function () {
            $('#dialog').dialog("close");
        }
    })
    $('#dialog').dialog('open');
}

/**
 * function markReviewedBtn(el)
 * Action for mark reviewed button
 */
function markReviewedBtn(el) {
    var title = "Mark Version As Reviewed?",
        text  = "<p>You will not be able to send a decline message to the editor or make the version current. You can only do that by first <strong>viewing</strong> it.</p>"+
                "<p>Do you want to mark this version as reviewed?</p>";
    $('#dialog').html(text);
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '427px');
    $('#dialog').dialog('option', 'buttons', {
        "Yes": function () {
            ldr("marking version as reviewed ...");
            $.ajax({
                type: 'post',
                timeout: content_manager.timeout_limit,
                data:{
                    page_id: el.data("page-id")
                },
                cache: false,
                url: 'ajax/unmark_ready_for_review.php',
            })
            .done(function(xhr) {
                ldrSuccess();
                el.closest(".readyForReview").removeClass("readyForReview");
                el.remove();
            })
            $('#dialog').dialog("close");
        },
        "No": function () {
            $('#dialog').dialog("close");
        }
    })
    $('#dialog').dialog('open');
}

/**
 * function viewVersionBtn(el)
 * Load up the page this version is
 */
function viewVersionBtn(el) {
    ldr("loading ...");
    window.location.hash = "";
    getPage(
        el.data("page-id"),
        function(page){
            ldr("fetching page...");
            treatPage(page);
        },
        el.data("history-id")
    );
}

/**
 * Amend uploadifive progress bar so that it does not show 100% when
 * uploaded files are being processed on server side.
 *
 * @author Jindřich Prokop <jindrich.prokop@mtcmedia.co.uk>
 *
 * @param {object} file passed by onProgress uploadifive event
 * @param {object} e passed by onProgress uploadifive event
 */
function uploadifiveProgressPercents(file, e) {
    if (e.lengthComputable) {
        var percent = Math.round((e.loaded / e.total) * 100) - 1;
    }
    var progress_text = ' - ' + percent + '%';
    if (percent == 99) {
        progress_text += ' - processing uploaded file';
    }

    file.queueItem.find('.fileinfo').html(progress_text);
    file.queueItem.find('.progress-bar').css('width', percent + '%');
}

/*
 * Alert about an invalid file type
 */
function alertAboutInvalidFileType(file_type) {
    $('#dialog').html('<p>The file you uploaded has an invalid file type and is not permitted to be uploaded.</p>');
    $('#dialog').dialog('option', 'width', '600px');
    $('#dialog').dialog('option', 'title', 'File type "' + file_type + '" not allowed.');
    $('#dialog').dialog('option', 'buttons', {
        OK: function () {
            $('#dialog').dialog('close');
        }
    });
    $('#dialog').dialog('open');
}

/*
 * Inject image into an items image data
 */
function injectImageIntoItemsImageData(list_item_jquery_object, list_item_data_name, filename, type) {
    var list_item_data_id = list_item_jquery_object
        .find("li[data-name='" + list_item_data_name + "']")
        .data("list-item-data-id");
    list_item_jquery_object.addClass("dataInsertedInThisItemAlready");

    $("#uploadifive-pagedata\\[" + list_item_data_id + "\\]\\[new_file_value\\]").show();
    $("#pagedata-crop-anchor-id-" + list_item_data_id).show();

    if (type == "image") {
        $("#pagedata\\[" + list_item_data_id + "\\]\\[new_file_value\\]\\[image_container\\]")
            .fadeIn()
            .find("img")
            .attr("src", "/uploads/images/cms/small/" + filename);
    } else {
        $("#pagedata\\[" + list_item_data_id + "\\]\\[new_file_value\\]\\[file_container\\]").show();
        $("#pagedata\\[" + list_item_data_id + "\\]\\[new_file_value\\]\\[file_container\\]")
            .find(".file_link")
            .attr("href", "/uploads/files/" + filename);
    }
    $("#pagedata\\[" + list_item_data_id + "\\]\\[value\\]").val(filename);
    $("#pagedata\\[" + list_item_data_id + "\\]\\[new_file_value\\]")
        .attr('data-list-item-data-value', filename);
}

/*
 * Alert regarding maximum number of items in a list reached
 */
function maximumItemsAlert(max_allowed_items_in_list) {
    // dialog box options
    $('#dialog').html("The maximum number of items in this list is " + max_allowed_items_in_list + ".");
    $('#dialog').dialog('option', 'title', "Can't add anymore!");
    $('#dialog').dialog('option', 'buttons', {
        "Ok": function () {
            $('#dialog').dialog('close');
        }
    });
    $('#dialog').dialog('open');
}

/*
 * Attach a uploadifive multi upload functionality to a field
 */
function multiUploadifive(el, upload_type){
    if (upload_type !== "file" && upload_type !== "image") {
        return false;
    }
    // variables initialised here are within the scope of only this input.imageMUploadifive
    var raw_id = $(el).attr('id') || '',
        pagedata_id = raw_id.replace(/\[/g,'\\[').replace(/\]/g,'\\]'),
        list_item = $(el).closest('.list-item'),
        list_id = list_item.data('list-id'),
        list_item_id = list_item.data("list-item-id"),
        list_item_data_id = $(el).attr('data-list-item-data-id'),
        list_item_data_value = $(el).attr('data-list-item-data-value'),
        list_item_data_name = $(el).closest('.list-item-data-holder').data("name"),
        uploadifive_add_list_item_to_top = false,
        max_items_in_list = parseInt($("#list_" + list_id + " input[name=item_list_allow_more_max]").val(), 10),
        number_of_items_in_list = parseInt($("#list-" + list_id + "-item-holder .list-item").length, 10),
        data = {
            list_item_data_id: list_item_data_id,
            list_item_data_value: list_item_data_value,
            new_one : false,
            pagedata : {}
        },
        legacy_queue_el = document.getElementById(raw_id + '[queue]'),
        queue_base = raw_id.replace(/[^A-Za-z0-9_-]+/g, '_'),
        queue_id = 'uploadifive_' + (queue_base || 'queue') + '_multi',
        queue_selector = '#' + queue_id;

    if (legacy_queue_el) {
        legacy_queue_el.parentNode.removeChild(legacy_queue_el);
    }

    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 : upload_type
    };

    // check to add item to top or bottom of the list
    if ($('li#list_' + list_id + ' input[name="item_list_top"]:checked').length > 0) {
        uploadifive_add_list_item_to_top = true;
    }

    $(el).uploadifive({
        dnd             : true,
        fileObjName     : 'pagedata',
        buttonClass     : 'btn',
        buttonText      : 'Choose ' + upload_type + '(s)',
        auto            : true,
        simUploadLimit  : 1,
        removeCompleted : true,
        formData        : data,
        queueID         : queue_id,
        multi           : true,
        uploadScript    : 'ajax/uploadifive.php?type=' + upload_type + '&page_id=' + getPageId("sandbox"),
        onAddQueueItem: function(file) {
            ldr("uploading " + upload_type + "...");
            // reset "data inserted in this item already" css class flag. this is applied when a item has had a data injected into it.
            $("#list-" + list_id + "-item-holder .dataInsertedInThisItemAlready").removeClass("dataInsertedInThisItemAlready");
            // first js regex validation. there will be a php side one when it get's passed to server
            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('clearQueue');
                alertAboutInvalidFileType(file.type);
            }
        },
        onCancel: function() {
            if ($(queue_selector).children().length <= 1) {
                $(queue_selector).html("");
                ldrSuccess();
            }
        },
        onUploadComplete: function(file, data) {
            setUnsavedChanges(true);
            // check if this item has been used
            if (!list_item.hasClass("dataInsertedInThisItemAlready")) {
                injectImageIntoItemsImageData(list_item, list_item_data_name, data, upload_type)
            } else {
                // check if there is an item after this one
                if (uploadifive_add_list_item_to_top) {
                    var items = list_item.prevAll(".list-item:not(.dataInsertedInThisItemAlready)");
                } else {
                    var items = list_item.nextAll(".list-item:not(.dataInsertedInThisItemAlready)");
                }

                if (items.length > 0) {
                    injectImageIntoItemsImageData($(items[0]), list_item_data_name, data, upload_type);
                } else {
                    // if not - add one
                    number_of_items_in_list = parseInt($("#list-" + list_id + "-item-holder .list-item").length, 10);

                    if (max_items_in_list !== 0 && number_of_items_in_list >= max_items_in_list) {
                        $(el).uploadifive('clearQueue');
                        maximumItemsAlert(max_items_in_list);

                    } else {
                        item_data = {
                            copy_content : 0,
                            action_more  : list_id,
                            language     : $(".languageSelect").val()
                        };
                        addItem(item_data, function(result) {
                            var new_list_item;
                            if (uploadifive_add_list_item_to_top) {
                                $("#list-" + list_id + "-item-holder").prepend(result);
                                new_list_item = $("#list-" + list_id + "-item-holder .list-item:first-of-type");
                            } else {
                                $("#list-" + list_id + "-item-holder").append(result);
                                new_list_item = $("#list-" + list_id + "-item-holder .list-item:last-of-type");
                            }
                            // move the clearfix
                            $("#list-" + list_id + "-item-holder").append($("#list-" + list_id + "-item-holder > div[style]"));
                            new_list_item.ready(function(){
                                pagedataInit("#list-item-" + new_list_item.data("list-item-id"));
                                if ($("#list-" + list_id + "-item-holder .list-item").length > 1) {
                                    $("#list-" + list_id + "-item-holder .list-item .remove-item-btn").show();
                                    $("#list-" + list_id + "-item-holder .list-item .move-up-item-btn").show();
                                    $("#list-" + list_id + "-item-holder .list-item .move-down-item-btn").show();
                                }
                                injectImageIntoItemsImageData(new_list_item, list_item_data_name, data, upload_type);
                            });
                        });
                    }
                }
            }
        },
        onQueueComplete: function() {
            loadPanelMessages();
            ldrSuccess();
        },
        onClearQueue: function() {
            ldrSuccess();
        },
        onError: function(error_type, response) {
            if (response.xhr.status == 415) {
                alertAboutInvalidFileType(response.xhr.response);
            }
            pagedataDestroy("#list-item-" + list_item_id);
            pagedataInit("#list-item-" + list_item_id);
        },
        onProgress: uploadifiveProgressPercents
    });
}

/**
 * updatePagedataAlt button next to images to update alt text for pagedata
 */
function updatePagedataAlt(el, event) {
    el.tooltip("close");
    cmsPreventDefault(event);
    if (busyLoading()) {
        return false;
    }
    var title = "Manage Image Alt Text",
        page_list_item_data_id = el.data("page-list-item-data-id"),
        html = "<p>Alt text helps users with screenreaders and your SEO!</p>";
        html += "<form class='dialogBoxForm'>";
        html += "<fieldset>";
        html += "<div class='row'>";
        html += "<input type='text' name='alt_text' id='alt_text' value='" + el.attr("data-alt") + "' class='text ui-widget-content ui-corner-all' />";
        html += "</div>";
        html += "</fieldset>";
        html += "</form>";
    $('#dialog').html(html);
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '427px');
    $('#dialog').dialog('option', 'buttons', {
        Save: function () {
            $('#dialog').dialog('close');
            ldrPending("updating alt text ...");
            $.ajax({
                type: 'post',
                dataType: 'json',
                cache: false,
                url: 'ajax/update_alt_text.php',
                data: {
                    page_list_item_data_id: page_list_item_data_id,
                    alt_text: $("#alt_text").val().trim()
                }
            })
            .done(function (result) {
                $("#pagedata_alt_anchor_" + page_list_item_data_id)
                    .attr("data-alt", result.alt_text);
                $("#page_list_item_data_" + page_list_item_data_id + "_img")
                    .attr("title", result.alt_text)
                    .attr("alt", result.alt_text);
                $("#pagedata_alt_anchor_" + page_list_item_data_id).tooltip("close");
                ldrSuccess();
                setUnsavedChanges(true);
            })
            .fail(function (jq_xhr, text_status, error_thrown) {
                if (content_manager.debug === 1) {
                    consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
                }
                reloadPagedata(
                    getPageId("sandbox"),
                    function () {
                        ldrFailure();
                    },
                    function () {}
                );
            });
        },
        Cancel: function () {
            $('#dialog').dialog('close');
        }
    });
    $("#dialog").dialog('open');
}

/*
 * Script to prompt how to store pagedata structure in the template
 */
function storePagedataStructureInTheTemplateAction() {
    ldrPending("checking template ...");
    $.ajax({
        type: 'get',
        cache: false,
        url: 'ajax/check_if_there_is_an_existing_pagedata_structure_file.php',
        data: {
            template: $("#data\\[page\\]\\[template\\]").val(),
            page_id: getPageId("sandbox")
        }
    })
    .done(function (result) {
        ldrSuccess();
        if (result === "true") {
            var title = "Overwrite existing template structure file?",
                html = "<p>There's already a structure file '" + $("#data\\[page\\]\\[template\\]").val() + ".json' for this template in your sites directory. Would you liike to overwrite it?</p>";
            $('#dialog').html(html);
            $('#dialog').dialog('option', 'title', title);
            $('#dialog').dialog('option', 'width', '427px');
            $('#dialog').dialog('option', 'buttons', {
                Overwrite: function () {
                    $('#dialog').dialog('close');
                    storePagedataStructureInTheTemplatePrompt();
                },
                Cancel: function () {
                    $('#dialog').dialog('close');
                }
            });
            $("#dialog").dialog('open');
        } else {
            storePagedataStructureInTheTemplatePrompt();
        }
    })
    .fail(function (jq_xhr, text_status, error_thrown) {
        if (content_manager.debug === 1) {
            consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
        }
        ldrFailure();
    });

}

/*
 * As is with or without data to store pagedata structure in the template
 */
function storePagedataStructureInTheTemplatePrompt() {
    var title = "Store structure?",
        html = "Store template structure into a structure json file '" + $("#data\\[page\\]\\[template\\]").val() + ".json' inside /sites/ directory?";
    $('#dialog').html(html);
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '427px');
    $('#dialog').dialog('option', 'buttons', {
        Store: function () {
            ldrPending("storing structure ...");
            $('#dialog').dialog('close');
            storePagedataStructureInTheTemplate(0);
        },
        Cancel: function () {
            $('#dialog').dialog('close');
        }
    });
    $("#dialog").dialog('open');
}

/*
 * Script for storing pagedata structure in the template
 */
function storePagedataStructureInTheTemplate(include_content_in_structure) {
    $.ajax({
        type: 'get',
        cache: false,
        url: 'ajax/store_pagedata_structure_in_the_template.php',
        dataType: 'json',
        data: {
            template: $("#data\\[page\\]\\[template\\]").val(),
            page_id: getPageId("sandbox"),
            include_content_in_structure: include_content_in_structure,
        }
    })
    .done(function (list_of_pages_that_have_this_template) {
        ldrSuccess();
        $(".structureIsNotSaved.storePagedataStructureInTheTemplateBtn")
            .addClass("structureIsSaved")
            .removeClass("structureIsNotSaved");
        // no reson to prompt sync if this is the only page with this template
        if (list_of_pages_that_have_this_template.length > 1) {
            syncTemplateStructureCrossPagesDialogue(list_of_pages_that_have_this_template);
        }
    })
    .fail(function (jq_xhr, text_status, error_thrown) {
        if (content_manager.debug === 1) {
            consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
        }
        ldrFailure();
    });
}

function syncTemplateStructureCrossPagesDialogue(list_of_pages_that_have_this_template) {
    var choice = recallChoice("sync_template_structure_cross_pages_choice");
    if (choice !== null) {
        choice = JSON.parse(choice);
        if (choice.sync_template_structure_cross_pages == false) {
            return false;
        } else {
            loadPagedataStructureFromTheTemplate(
                choice.clear_pagedata,
                choice.merge_pagedata,
                choice.delete_unreferenced_pagedata,
                "*"
            );
        }
        return;
    }

    var title = "Sync structure across pages w/ the same template?",
        html = "";

    html += "Pages that have this template: ";

    for (var i = 0; i < list_of_pages_that_have_this_template.length; i++) {
        html += stripTags(list_of_pages_that_have_this_template[i].title) + "(" + list_of_pages_that_have_this_template[i].id + ")";
        if ((i + 1) < list_of_pages_that_have_this_template.length) {
            html += ", ";
        }
    }

    html += "<form class='dialogBoxForm'>";
    html += "<fieldset>";

    html += "<div class='row'>";
    html += "<label for='clear_pagedata' class='longLabel'>Clear Existing Fields:</label>";
    html += "<div class='hint el' title='If ticked, existing fields will be cleared.'>";
    html += "<i class='fa fa-info-circle'></i>";
    html += "</div>";
    html += "<input type='checkbox' name='clear_pagedata' id='clear_pagedata' class='text ui-widget-content ui-corner-all' />";
    html += "</div>";

    html += "<div class='row mergeFieldsRow'>";
    html += "<label for='merge_pagedata' class='longLabel'>Merge Fields:</label>";
    html += "<div class='hint el' title='Whether or not to merge pagedata. Not merging pagedata means two pagedata with the same name might appear.'>"
    html += "<i class='fa fa-info-circle'></i>";
    html += "</div>";
    html += "<input type='checkbox' checked name='merge_pagedata' id='merge_pagedata' class='text ui-widget-content ui-corner-all' />";
    html += "</div>";

    html += "<div class='row deleteUnrefRow'>";
    html += "<label for='delete_unreferenced_pagedata' class='longLabel'>Delete Unreferenced Fields:</label>";
    html += "<div class='hint el' title='If ticked this will delete pagedata from page that is not referenced in the structure.'>";
    html += "<i class='fa fa-info-circle'></i>";
    html += "</div>";
    html += "<input type='checkbox' checked name='delete_unreferenced_pagedata' id='delete_unreferenced_pagedata' class='text ui-widget-content ui-corner-all' />";
    html += "</div>";

    html += "<div class='row'>";
    html += "<label for='remember' class='longLabel'>Remember My Choice:</label>";
    html += "<div class='hint el' title='Will remember if you'd like to or not sync structure and how. To clear choices refresh page.'>";
    html += "<i class='fa fa-info-circle'></i>";
    html += "</div>";
    html += "<input type='checkbox' name='remember' id='remember' class='text ui-widget-content ui-corner-all' />";
    html += "</div>";

    html += "</fieldset>";
    html += "</form>";

    $('#dialog').html(html);
    $("#dialog .dialogBoxForm .hint").tooltip();
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '500px');
    $('#dialog').dialog('option', 'buttons', {
        Sync: function () {
            rememberChoice(
                "sync_template_structure_cross_pages_choice",
                JSON.stringify({
                    sync_template_structure_cross_pages: true,
                    clear_pagedata: ($("#clear_pagedata").prop("checked") ? 1 : 0),
                    merge_pagedata: ($("#merge_pagedata").prop("checked") ? 1 : 0),
                    delete_unreferenced_pagedata: ($("#delete_unreferenced_pagedata").prop("checked") ? 1 : 0)
                })
            );
            $('#dialog').dialog('close');
            loadPagedataStructureFromTheTemplate(
                ($("#clear_pagedata").prop("checked") ? 1 : 0),
                ($("#merge_pagedata").prop("checked") ? 1 : 0),
                ($("#delete_unreferenced_pagedata").prop("checked") ? 1 : 0),
                "*"
            );
        },
        No: function () {
            rememberChoice(
                "sync_template_structure_cross_pages_choice",
                JSON.stringify({
                    sync_template_structure_cross_pages: false
                })
            );
            $('#dialog').dialog('close');
        }
    });
    $("#dialog").dialog('open');
}

/*
 * Script to prompt load pagedata structure from the template
 */
function loadPagedataStructureFromTheTemplateAction() {
    var choice = recallChoice("load_template_pagedata_structure_choice");
    if (choice !== null) {
        choice = JSON.parse(choice);
        loadPagedataStructureFromTheTemplate(
            choice[0],
            choice[1],
            choice[2],
            getPageId("sandbox")
        );
        return;
    }

    var title = "Load template pagedata structure?",
        html = "";

    html += "<form class='dialogBoxForm'>";
    html += "<fieldset>";

    html += "<div class='row'>";
    html += "<label for='clear_pagedata' class='longLabel'>Clear Existing Fields:</label>";
    html += "<div class='hint el' title='If ticked, existing fields will be cleared.'>";
    html += "<i class='fa fa-info-circle'></i>";
    html += "</div>";
    html += "<input type='checkbox' name='clear_pagedata' id='clear_pagedata' class='text ui-widget-content ui-corner-all' />";
    html += "</div>";

    html += "<div class='row mergeFieldsRow'>";
    html += "<label for='merge_pagedata' class='longLabel'>Merge Fields:</label>";
    html += "<div class='hint el' title='Whether or not to merge pagedata. Not merging pagedata means two pagedata with the same name might appear.'>"
    html += "<i class='fa fa-info-circle'></i>";
    html += "</div>";
    html += "<input type='checkbox' checked name='merge_pagedata' id='merge_pagedata' class='text ui-widget-content ui-corner-all' />";
    html += "</div>";

    html += "<div class='row deleteUnrefRow'>";
    html += "<label for='delete_unreferenced_pagedata' class='longLabel'>Delete Unreferenced Fields:</label>";
    html += "<div class='hint el' title='If ticked this will delete pagedata from page that is not referenced in the structure.'>";
    html += "<i class='fa fa-info-circle'></i>";
    html += "</div>";
    html += "<input type='checkbox' checked name='delete_unreferenced_pagedata' id='delete_unreferenced_pagedata' class='text ui-widget-content ui-corner-all' />";
    html += "</div>";

    html += "<div class='row'>";
    html += "<label for='remember' class='longLabel'>Remember Choices:</label>";
    html += "<div class='hint el' title='Will use the above selected options next time and not provide this dialogue. To clear choices refresh page.'>";
    html += "<i class='fa fa-info-circle'></i>";
    html += "</div>";
    html += "<input type='checkbox' name='remember' id='remember' class='text ui-widget-content ui-corner-all' />";
    html += "</div>";

    html += "</fieldset>";
    html += "</form>";

    $('#dialog').html(html);
    $("#dialog .dialogBoxForm .hint").tooltip();
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '500px');
    $('#dialog').dialog('option', 'buttons', {
        Load: function () {
            rememberChoice(
                "load_template_pagedata_structure_choice",
                JSON.stringify([
                    ($("#clear_pagedata").prop("checked") ? 1 : 0),
                    ($("#merge_pagedata").prop("checked") ? 1 : 0),
                    ($("#delete_unreferenced_pagedata").prop("checked") ? 1 : 0)
                ])
            );
            $('#dialog').dialog('close');
            loadPagedataStructureFromTheTemplate(
                ($("#clear_pagedata").prop("checked") ? 1 : 0),
                ($("#merge_pagedata").prop("checked") ? 1 : 0),
                ($("#delete_unreferenced_pagedata").prop("checked") ? 1 : 0),
                getPageId("sandbox")
            );
        },
        Cancel: function () {
            $('#dialog').dialog('close');
        }
    });
    $("#dialog").dialog('open');
}

// Generate a list form the site_tree tree to be used in form selects
function getPageListFromSiteTree(site_tree, n) {
    if (typeof n === "undefined" || n === null) {
        n = 0;
    }
    var list = {};
    for (page_id in site_tree) {
        // skip loop if the property is from prototype
        if (!site_tree.hasOwnProperty(page_id)) continue;

        list[page_id] = "";

        for (var i = 0; i < n; i++) {
            list[page_id] += "-";
        }

        list[page_id] += site_tree[page_id].title;

        var sub_list =getPageListFromSiteTree(site_tree[page_id].sub, n+1);
        for (sub_list_page_id in sub_list) {
            list[sub_list_page_id] = sub_list[sub_list_page_id];
        }
    }
    return list;
}

/*
 * Dialogue that allows user to set allowed templates for switching between
 */
function setAllowedTemplatesForSwitchingDialogue() {
    var title = "Select what templates client can switch between.",
        dialogue_form_setup = {},
        templates = {};

    $("#data\\[page\\]\\[template\\] option").each(function() {
        templates[$(this).attr("value")] = $.trim($(this).html());
    });

    dialogue_form_setup.what_templates_client_can_switch_between = {
        label: 'Templates:',
        id: 'what_templates_client_can_switch_between',
        type: 'select',
        multiple: true,
        options: templates
    };
    dialogue_form_setup.set_these_templates_for_pages = {
        label: 'Set for:',
        id: 'set_these_templates_for_pages',
        type: 'select',
        options: {
            current: 'Current Page',
            select: 'Select Pages',
        }
    };
    dialogue_form_setup.what_templates_client_can_switch_between_pages_input = {
        label: 'Pages:',
        id: 'what_templates_client_can_switch_between_pages_input',
        type: 'select',
        multiple: true,
        options: getPageListFromSiteTree(content_manager.site_tree)
    };

    $('#dialog').html(dialogueBuilder(dialogue_form_setup));
    $('#what_templates_client_can_switch_between_pages_input').parent(".row").hide();

    $("#set_these_templates_for_pages").on("change", function() {
        if ($("#set_these_templates_for_pages").val() == "select") {
            $('#what_templates_client_can_switch_between_pages_input').parent(".row").show();
        } else {
            $('#what_templates_client_can_switch_between_pages_input').parent(".row").hide();
        }
    });

    $("#dialog .dialogBoxForm .hint").tooltip();
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '700px');
    $('#dialog').dialog('option', 'buttons', {
        Set: function () {
            setAllowedTemplatesForSwitching(
                $("#what_templates_client_can_switch_between").val(),
                $("#set_these_templates_for_pages").val(),
                $("#what_templates_client_can_switch_between_pages_input").val(),
            );
            $('#dialog').dialog('close');
            return;
        },
        Cancel: function () {
            $('#dialog').dialog("close");
            return false;
        }
    });

    $('#dialog').dialog('open');
    return false;
}

// Call to set what templates client is allowed to switch between for page(s)
function setAllowedTemplatesForSwitching(templates, set_form, page_ids) {
    ldrPending("setting allowed templates ...");
    $.ajax({
        type: 'get',
        cache: false,
        dataType: 'json',
        url: 'ajax/set_allowed_templates_for_switching.php',
        data: {
            templates: templates,
            set_form: set_form,
            page_ids: page_ids,
            current_page_id: getPageId()
        }
    })
    .done(function (result) {
        location.reload();
    })
    .fail(function (jq_xhr, text_status, error_thrown) {
        if (content_manager.debug === 1) {
            consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
        }
        ldrFailure();
    });
}

/*
 * Script to load pagedata structure from the template
 */
function loadPagedataStructureFromTheTemplate(clear_pagedata, merge_pagedata, delete_unreferenced_pagedata, page_id) {
    ldrPending("loading structure ...");
    $.ajax({
        type: 'get',
        cache: false,
        dataType: 'json',
        url: 'ajax/load_pagedata_structure_from_the_template.php',
        data: {
            page_id: page_id,
            clear_pagedata: clear_pagedata,
            merge_pagedata: merge_pagedata,
            delete_unreferenced_pagedata: delete_unreferenced_pagedata,
            template: $("#data\\[page\\]\\[template\\]").val()
        }
    })
    .done(function (result) {
        if (result.result === true) {
            setUnsavedChanges(true);
            $(".structureIsNotSaved.storePagedataStructureInTheTemplateBtn")
                .addClass("structureIsSaved")
                .removeClass("structureIsNotSaved");
            reloadPagedata(
                getPageId("sandbox"),
                function () {
                    ldrSuccess();
                },
                function () {}
            );
        } else {
            ldrFailure();
            var title = "Can't load pagedata from template.",
                html = "<p>" + result.message + "</p>";
            $('#dialog').html(html);
            $('#dialog').dialog('option', 'title', title);
            $('#dialog').dialog('option', 'width', '500px');
            $('#dialog').dialog('option', 'buttons', {
                Close: function () {
                    $('#dialog').dialog('close');
                }
            });
            $("#dialog").dialog('open');
        }
    })
    .fail(function (jq_xhr, text_status, error_thrown) {
        if (content_manager.debug === 1) {
            consoleLogAjaxFailure(jq_xhr, text_status, error_thrown);
        }
        ldrFailure();
    });
}

// Get an array of the IDs of the pages listed in the listing tab
function getListingPageListedPageIDs() {
    var listed_page_ids = [];
    $(".listedPage").each(function (index, el) {
        listed_page_ids.push($(el).attr("data-page-id"));
    });
    return listed_page_ids;
}

function copyPagesDialogue(page_ids, context) {
    if (typeof context === "undefined") {
        var context = "default"; // edit page
    }

    var title = "",
        dialogue_form_setup = {};

    if (context === "listing_tab") {
        title = "Copy Listed Page(s)";
    } else {
        title = "Copy Page(s)";
        dialogue_form_setup.copy_sister_pages = {
            label: 'Copy sister page(s):',
            id: 'copy_sister_pages',
            type: 'checkbox',
            hint: 'Copies also sister pages. Clicking yes while being on a top level page - allows you to copy whole site trees.'
        };
    }

    dialogue_form_setup.copy_field_data = {
        label: 'Copy page field data:',
        id: 'copy_field_data',
        type: 'checkbox',
        checked: 'checked',
        hint: 'Do you wish the page data fields to be exact copy of the original? Choose no to copy them wihtout the values.'
    };

    dialogue_form_setup.copy_child_pages = {
        label: 'Copy child pages:',
        id: 'copy_child_pages',
        type: 'checkbox',
        hint: 'Do you wish to copy the child pages? Choose no to copy this level only.'
    };

    dialogue_form_setup.keep_slugs = {
        label: 'Keep Slugs:',
        id: 'keep_slugs',
        type: 'checkbox',
        hint: 'Whether or not to keep slugs for the copied pages.'
    };

    $('#dialog').html(dialogueBuilder(dialogue_form_setup));
    $("#dialog .dialogBoxForm .hint").tooltip();
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '700px');
    $('#dialog').dialog('option', 'buttons', {
        Copy: function () {
            pageCopy(
                page_ids,
                ($("#copy_field_data").prop("checked") ? 1 : 0),
                ($("#copy_child_pages").prop("checked") ? 1 : 0),
                ($("#keep_slugs").prop("checked") ? 1 : 0),
                ($("#copy_sister_pages").prop("checked") ? 1 : 0)
            );
            $('#dialog').dialog('close');
            return;
        },
        Cancel: function () {
            $('#dialog').dialog("close");
            return false;
        }
    });

    $('#dialog').dialog('open');
    return false;
}

function pageCopy(page_ids, copy_field_data, copy_child_pages, keep_slugs, copy_sister_pages) {
    ldr("copying page(s)...");
    var data = {
        page_ids:          page_ids,
        copy_field_data:   copy_field_data,
        copy_child_pages:  copy_child_pages,
        keep_slugs:        keep_slugs,
        copy_sister_pages: copy_sister_pages,
    };
    $.ajax({
        type: 'post',
        cache: false,
        url: 'ajax/page_copy.php',
        data: data,
        success: function (result) {
            if (result != "false") {
                content_manager.xds.setItem('clipboard_page', result, function (response) {});
                ldrSuccess();
            } else {
                ldrFailure();
            }
        },
        error: function () {
            ldrFailure();
        }
    });
}
/*
 * Function that queries db to check for slug conflicts
 */
function checkSlugForConflicts(el) {
    if (el.val() === "") {
        return;
    }
    $.ajax({
        type: 'get',
        timeout: content_manager.timeout_limit,
        data:{
            page_id: getPageId("live"),
            sub_id: content_manager.page.sub_id,
            slug: el.val(),
        },
        cache: false,
        url: 'ajax/check_slug_conflicts.php',
    })
    .done(function (result) {
        if (result === "slug conflict") {
            $("#page_slug_alert").show();
        } else {
            $("#page_slug_alert").hide();
        }
    })
}

var dialogue_builder_form_html = null;
function dialogueBuilderInit() {
    $.ajax({
        type: 'get',
        timeout: content_manager.timeout_limit,
        dataType: 'json',
        url: 'ajax/dialogue_builder.php',
    })
    .done(function (result) {
        dialogue_builder_form_html = result;
    });
}
function dialogueBuilder(form_setup) {
    if (dialogue_builder_form_html === null) {
        return false;
    }
    var form_content = dialogue_builder_form_html.layout,
        form_rows = "",
        options_content = "",
        attribute_name,
        attribute,
        form_row_content,
        option_value,
        additionals = "";

    for (attribute_name in form_setup) {
        // skip loop if the property is from prototype
        if (!form_setup.hasOwnProperty(attribute_name)) continue;

        additionals = "";
        attribute = form_setup[attribute_name];

        form_row_content = "";
        if (typeof attribute.label !== "undefined" && attribute.label !== false) {
            form_row_content = dialogue_builder_form_html.row;
            form_row_content = form_row_content.replace("{{ label }}", attribute.label);
            if (typeof attribute.label_class === "undefined" || attribute.label_class === false) {
                attribute.label_class = "";
            }
            form_row_content = form_row_content.replace("{{ label_class }}", attribute.label_class);
            form_row_content = form_row_content.replace("{{ id }}", attribute.id);
            if (typeof attribute.hint !== "undefined" && attribute.hint !== false) {
                form_row_content = form_row_content.replace("{{ hint_content }}", dialogue_builder_form_html.hint);
                form_row_content = form_row_content.replace("{{ hint }}", attribute.hint );
            } else {
                form_row_content = form_row_content.replace("{{ hint_content }}", "");
            }
        }

        if (attribute.type === "select") {
            form_row_content = form_row_content.replace("{{ content }}", dialogue_builder_form_html.select);
            form_row_content = form_row_content.replace("{{ id }}", attribute.id);
            form_row_content = form_row_content.replace("{{ name }}", attribute_name);

            if (attribute.multiple === true) {
                additionals = "multiple";
            }

            form_row_content = form_row_content.replace("{{ additionals }}", additionals);
            if (typeof attribute.class === "undefined" || attribute.class === false) {
                attribute.class = "";
            }
            form_row_content = form_row_content.replace("{{ class }}", attribute.class);
            options_content = "";
            for (option_value in attribute.options) {
                // skip loop if the property is from prototype
                if (!attribute.options.hasOwnProperty(option_value)) continue;

                options_content += "<option value='" + option_value + "'>" + attribute.options[option_value] + "</option>";
            }
            form_row_content = form_row_content.replace("{{ options_content }}", options_content);
        } else if (attribute.type === "checkbox") {
            form_row_content = form_row_content.replace("{{ content }}", dialogue_builder_form_html.checkbox);
            form_row_content = form_row_content.replace("{{ id }}", attribute.id);
            form_row_content = form_row_content.replace("{{ name }}", attribute_name);
            if (typeof attribute.class === "undefined" || attribute.class === false) {
                attribute.class = "";
            }
            form_row_content = form_row_content.replace("{{ class }}", attribute.class);
            if (typeof attribute.checked === "undefined" || attribute.checked === false) {
                attribute.checked = "";
            }
            form_row_content = form_row_content.replace("{{ checked }}", attribute.checked);
        } else if (attribute.type === "hidden" || attribute.type === "number" || attribute.type === "text") {
            if (form_row_content === "") {
                form_row_content = dialogue_builder_form_html.input;
            } else {
                form_row_content = form_row_content.replace("{{ content }}", dialogue_builder_form_html.input);
            }
            form_row_content = form_row_content.replace("{{ type }}", attribute.type);
            form_row_content = form_row_content.replace("{{ id }}", attribute.id);
            form_row_content = form_row_content.replace("{{ name }}", attribute_name);
            if (typeof attribute.class === "undefined" || attribute.class === false) {
                attribute.class = "";
            }
            form_row_content = form_row_content.replace("{{ class }}", attribute.class);
            form_row_content = form_row_content.replace("{{ value }}", attribute.value);
        }
        form_rows += form_row_content;
    }
    form_content = form_content.replace("{{ content }}", form_rows);

    return form_content;
}

// Deleted pages passed in via param as ids
function deleteAllListedPagesDialog(page_ids) {
    if (typeof context === "undefined") {
        var context = "default"; // edit page
    }

    var title = "Are you sure?",
        dialogue_form_setup = {
            delete_all_currently_listed_pages: {
                type: 'checkbox',
                label_class: 'longLabel',
                label: 'Delete all listed pages:',
                id: 'delete_all_currently_listed_pages',
                hint: false
            }
    };

    $('#dialog').html(dialogueBuilder(dialogue_form_setup));
    $("#dialog .dialogBoxForm .hint").tooltip();
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '400px');
    $('#dialog').dialog('option', 'buttons', {
        Delete: function () {
            if ($("#delete_all_currently_listed_pages").prop("checked")) {
                deletePages(
                    page_ids
                );
            }
            $('#dialog').dialog('close');
            return;
        },
        Cancel: function () {
            $('#dialog').dialog("close");
            return false;
        }
    });

    $('#dialog').dialog('open');
    return false;
}

// function for delete page in bulk
// if using the function in custom sitaution make sure you have dialogues confirming delete
function deletePages(pages) {
    ldr("deleting all listed pages...");
    $.ajax({
        type: 'post',
        data: {
            page_ids: pages
        },
        timeout: content_manager.timeout_limit,
        cache: false,
        url: 'ajax/delete_page.php'
    }).done(function (result) {
        if (result === false || result === "false") {
            ldrFailure();
            location.reload();
        } else {
            ldrSuccess();
            location.reload();
        }
    }).fail(function () {
       ldrFailure();
       location.reload();
    });
}


function movePagesDialog(page_ids) {
    var title = "Under what page would you like to move listed pages?",
        dialogue_form_setup = {
            new_sub_id: {
                label: 'Page ID:',
                id: 'new_sub_id',
                type: 'number',
                value: 0,
                hint: false
            }
    };

    $('#dialog').html(dialogueBuilder(dialogue_form_setup));
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '700px');
    $('#dialog').dialog('option', 'buttons', {
        Submit: function () {
            ldr("moving all listed pages...");
            $.ajax({
                type: 'post',
                data: {
                    page_ids: page_ids,
                    new_sub_id: $("#new_sub_id").val(),
                    current_page_id: getPageId('live')
                },
                timeout: content_manager.timeout_limit,
                cache: false,
                url: 'ajax/move_page.php'
            }).done(function (result) {
                if (result === false || result === "false") {
                    ldrFailure();
                    location.reload();
                } else {
                    ldrSuccess();
                    location.reload();
                }
            }).fail(function () {
                ldrFailure();
            });

            $('#dialog').dialog('close');
            return;
        },
        Cancel: function () {
            $('#dialog').dialog("close");
            return false;
        }
    });

    $('#dialog').dialog('open');
    return false;
}

// Dialogue that displays when client tries to switch templates
function clientSwitchTemplatesDialogue() {
    var title = "Are you sure you want to change templates?",
        html = "Changing templates might result in lost content!";

    $('#dialog').html(html);
    $("#dialog .dialogBoxForm .hint").tooltip();
    $('#dialog').dialog('option', 'title', title);
    $('#dialog').dialog('option', 'width', '500px');
    $('#dialog').dialog('option', 'buttons', {
        Yes: function () {
            $('#dialog').dialog('close');
            loadPagedataStructureFromTheTemplate(
                0,
                1,
                1,
                getPageId("sandbox")
            );
        },
        Cancel: function () {
            // if cancel undo template switch
            $('#data\\[page\\]\\[template\\]').val(content_manager.page.template);
            $('#dialog').dialog('close');
        }
    });
    $("#dialog").dialog('open');
}
