var openSelectBox = {
    filterId: '',
    refresh: function (jqueryVersion) {
        if (this.filterId) {
            jqueryVersion(this.filterId).trigger('chosen:open');
            this.filterId = '';
        }
    }
};

function updateSelects_(jqueryVersion, chosenOptions) {
    jqueryVersion('.gzl-select-text').chosen(chosenOptions);
    openSelectBox.refresh(jqueryVersion);
}

function updateUrl(urlParametersId) {
    if (history.replaceState) {
        var newParameters = document.getElementById(urlParametersId).value;
        var oldParameters = "";
        var lastIndex = location.href.lastIndexOf("?");
        if (lastIndex != -1) {
            oldParameters = location.href.substring(lastIndex + 1);
            if (oldParameters != newHref) {
                var newHref = location.href.substring(0, lastIndex + 1)
                    + newParameters;
                history.replaceState({}, document.title, newHref);
            }
        } else {
            history.replaceState({}, document.title, location.href + "?"
                + newParameters);
        }
    }
}

var longLoadingTimer = null;
var onAjaxStopFunctions = new Array();
var changedRichEditors = new Array();
var submittedFormForEditorCheck = null;

/*
 * Add a function called each time ajax query is complete
 */
function addAjaxStopFunction(ajaxStopFunction) {
    onAjaxStopFunctions.push(ajaxStopFunction);
}

/*
 * Manage HTML status
 */

// show loading div
function makeLongLoadingVisible() {
    resetStatusTimer();
    document.getElementById('longLoadingImage').className = 'loading-visible';
    document.getElementById('longLoadingBackground').className = 'loading-background';
}

// hide loading div
function makeLongLoadingInvisible() {
    resetStatusTimer();
    document.getElementById("longLoadingImage").className = "loading-invisible";
    document.getElementById("longLoadingBackground").className = "loading-invisible";
}

// called by a4j:status on query start
function gazelleStatusStart() {
    resetStatusTimer();
    document.body.style.cursor = 'progress';
    longLoadingTimer = setTimeout("makeLongLoadingVisible();", 500);
}

// reset timer
function resetStatusTimer() {
    if (longLoadingTimer != null) {
        clearTimeout(longLoadingTimer);
        longLoadingTimer = null;
    }
}

// calls all registered functions on ajax query complete
function callAjaxStopFunctions() {
    for (i = 0; i < onAjaxStopFunctions.length; i++) {
        var ajaxStopFunction = onAjaxStopFunctions[i];
        if (typeof (ajaxStopFunction) == 'function') {
            ajaxStopFunction();
        }
    }
}

function gazelleStatusStopFuture(duration) {
    longLoadingTimer = setTimeout("gazelleStatusStop();", duration);
}

// called by a4j:status on query complete
function gazelleStatusStop() {
    resetStatusTimer();
    document.body.style.cursor = 'default';
    makeLongLoadingInvisible();
    callAjaxStopFunctions();
}

// called when body is loaded
function gazelleBodyOnLoad(event) {
    gazelleStatusStop();
    A4J.AJAX.AddListener({
        onbeforeajax: function (formId, domEvt, options) {
            submittedFormForEditorCheck = formId + ":";
        }
    });
}

// called when body is unloaded
function gazelleOnBeforeUnload(event) {
    var aRichEditorModified = false;
    for (i = 0; i < changedRichEditors.length; i++) {
        var editor = changedRichEditors[i];
        if (editor && editor.getDoc() && editor.isDirty()) {
            aRichEditorModified = true;
        }
    }
    if (aRichEditorModified) {
        gazelleStatusStop();
        return 'The form has changed. Your changes will '
            + 'be lost if you press leave this page.';
    }
}

// called when a rich editor is "saved"
// we check that it matches submitted form
// then the editor is removed from modified editors
function richEditorSaved(editorId, html, body) {
    var idx = -1;
    if (submittedFormForEditorCheck != null) {
        if (editorId.startsWith(submittedFormForEditorCheck)) {
            for (i = 0; i < changedRichEditors.length; i++) {
                var editor = changedRichEditors[i];
                if (editor && editor.editorId == editorId) {
                    idx = i;
                }
            }
        }
    }
    if (idx != -1)
        changedRichEditors.splice(idx, 1);
    return html;
}

// called when a rich editor is changed
// keeps track of all changed editors
function richEditorChanged(editor) {
    if (changedRichEditors.indexOf(editor) == -1) {
        changedRichEditors.push(editor);
    }
}

/*
 * Tool functions
 */

// Add a function to be called when body is loaded
function gazelleAddToBodyOnLoad(newOnLoadFunction) {
    var existingOnload = window.onload;
    window.onload = function (oEvent) {
        if (!oEvent) {
            oEvent = event;
        }
        try {
            newOnLoadFunction(oEvent);
        } catch (ex) {
            // Fail silently.
        }
        if (existingOnload) {
            return existingOnload(oEvent);
        }
    }
}

// Add a function to be called before body is unloaded
function gazelleAddToBodyOnBeforeUnload(newOnBeforeUnloadFunction) {
    var existingOnBeforeUnload = window.onbeforeunload;
    window.onbeforeunload = function (oEvent) {
        if (!oEvent) {
            oEvent = event;
        }
        var result = null;
        try {
            result = newOnBeforeUnloadFunction(oEvent);
            if (result != null) {
                return result;
            }
        } catch (ex) {
            // Fail silently.
        }
        if (existingOnBeforeUnload) {
            return existingOnBeforeUnload(oEvent);
        }
    }
}

gazelleAddToBodyOnLoad(gazelleBodyOnLoad);
gazelleAddToBodyOnBeforeUnload(gazelleOnBeforeUnload);
