$(document).ready(function () {
    editor.init();
});

var editor = new Object({
    /**
     * Standard-Variablen für den Editor
     */
    type: '',
    title: '',
    name: '',
    contentHtml: '',
    contentData: null,

    /**
     * jQuery-Elemente für den Editor
     */
    titleElement: null,
    layerElement: null,
    closeElement: null,
    contentElement: null,
    waitingElement: null,
    editableElement: null,
    formElement: null,
    element: null,

    init: function () {
        editor.initElements();
        editor.hoverEvents();
        editor.clickEvents();
    },

    initElements: function () {
        editor.titleElement = $('#editor_title');
        editor.layerElement = $('#editor_layer');
        editor.closeElement = $('#editor_layer_close');
        editor.contentElement = $('#editor_content');
        editor.editableElement = $('[data-editable]');
        editor.waitingElement = $('#wait');
        editor.title = editor.titleElement.html();
    },

    hoverEvents: function () {
        editor.editableElement.on('mouseenter', function (event) {
            $(event.currentTarget).addClass('editable_hover');
        });
        editor.editableElement.on('mouseleave', function (event) {
            $(event.currentTarget).removeClass('editable_hover');
        });
    },

    clickEvents: function () {
        editor.editableElement.on('click', function (event) {
            if (event.target.tagName === 'A') {
                return true;
            }
            editor.type = event.currentTarget.dataset.editable;
            if (editor.type === 'textimage') {
                return true;
            }
            editor.waitingElement.show();
            editor.name = editor.type.toUpperCase();
            editor.element = $(event.currentTarget).attr('id');
            editor.callEditor();
        });

        editor.closeElement.click(function () {
            editor.close();
            navigation.close();
        });

        editor.contentElement.on('click', '.formSubmit', function () {
            editor.submitData();
        });

        editor.contentElement.on('click', '.formCancel', function () {
            editor.close();
        });

        editor.contentElement.on('click', '.formNext', function () {
            var actualInnerSlider = $(this).parents('.inner');
            actualInnerSlider.hide();
            actualInnerSlider.next('.inner').show();
        });

        editor.contentElement.on('click', '.formPrev', function () {
            var actualInnerSlider = $(this).parents('.inner');
            actualInnerSlider.hide();
            actualInnerSlider.prev('.inner').show();
        });

        editor.contentElement.on('change', '#spieltyp', function () {
            var durationElement = $('#spieldauer');
            var delayedElement = $('#verschoben');
            var duration = $(this).find(':selected').data('duration');
            var delayed = $(this).find(':selected').data('delayed');

            if (duration == 'hide') {
                durationElement.val('regular');
                durationElement[0].disabled = true;
            }
            else if (duration == 'show') {
                durationElement[0].disabled = false;
            }

            if (delayed == 'hide') {
                delayedElement[0].disabled = true;
            }
            else if (delayed == 'show') {
                delayedElement[0].disabled = false;
            }
        });
    },

    close: function () {
        editor.type = '';
        editor.name = '';
        editor.contentHtml = '';
        editor.contentData = null;
        editor.formElement = null;
        editor.titleElement.html(editor.title);
        editor.layerElement.hide();
        editor.contentElement.html('');
        editor.waitingElement.hide();
    },

    callEditor: function () {
        editor.titleElement.html(editor.titleElement.html().replace('%%type%%', editor.name));
        editor.getEditorHtml();
        editor.getEditorData();
        editor.layerElement.show();
    },

    getEditorHtml: function () {
        var editorFile = editorUrl + editorVersion + '/templates/' + editor.type + '.php';
        $.ajax({
            type: 'POST',
            url: editorFile,
            data: {lang: sessLang},
            dataType: 'html',
            error: function () {
                console.log(editorFile);
                console.log(editor.type);
                alert('Fehler beim Holen des Editor-HTMLs!');
            },
            success: function (html) {
                editor.contentHtml = html;
                editor.contentElement.html(html);
                editor.formElement = $('#editor_form');
            }
        });
    },

    getEditorData: function () {
        $.ajax({
            type: 'POST',
            url: webserviceUrl,
            data: {request: 'getData', userId: userId, dataSet: editor.element, prefix: prefix, navId: navigationId},
            dataType: 'json',
            error: function () {
                console.log(webserviceUrl);
                alert('Fehler beim Holen der Editor-Daten!');
            },
            success: function (data) {
                editor.contentData = data;
                console.log(data);
                editor.fillHtml();
            }
        });
    },

    fillHtml: function () {
        if (editor.contentHtml === '' || editor.contentData === null) {
            window.setTimeout(editor.fillHtml, 100);
            return;
        }

        if (editor.type === 'spielbericht') {
            editor.fillSpielBericht();
        }

        if (editor.type === 'struktur') {
            navigation.setData(editor.contentData);
            navigation.fillData();
        }
        else {
            editor.fillStandard();
        }

        editor.fillSpecial();
        editor.checkDuration();
        editor.checkDelayed();
        editor.changeSpielBericht();

        editor.waitingElement.hide();
    },

    fillSpecial: function () {
        $('#userId', editor.contentElement).val(userId);
        $('#prefix', editor.contentElement).val(prefix);
        $('#dataSet', editor.contentElement).val(editor.element);
        $('#siteId', editor.contentElement).val(navId);
    },

    fillStandard: function () {

        $.each(editor.contentData, function (key, value) {
            var input = $('#' + key, editor.contentElement);
            if (input.length == 0) {
                input = $('#' + key + '_' + value, editor.contentElement);
                if (input.length != 0) {
                    input[0].checked = true;
                }
            }
            else {
                input.val(value);
            }
        });

    },

    fillSpielBericht: function () {

        var teamOptions = '';
        $.each(editorParams.spielbericht.teamname, function (key, value) {
            teamOptions += '<option value="' + value + '">' + value + '</option>';
        });
        $('#teamname', editor.contentElement).html(teamOptions);

        var spielTypOptions = '';
        $.each(editorParams.spielbericht.spieltyp, function (key, value) {
            var duration = (value === 'pokal') ? 'show' : 'hide';
            var delayed = (value === 'abgesagt') ? 'show' : 'hide';
            spielTypOptions += '<option data-duration="' + duration + '" data-delayed="' + delayed + '" value="' + value + '">' + value + '</option>';
        });
        $('#spieltyp', editor.contentElement).html(spielTypOptions);

        var spielDauerOptions = '';
        $.each(editorParams.spielbericht.spieldauer, function (key, value) {
            spielDauerOptions += '<option value="' + key + '">' + value + '</option>';
        });
        $('#spieldauer', editor.contentElement).html(spielDauerOptions);
    },

    changeSpielBericht: function () {
        if (editor.type != 'spielbericht') {
            return true;
        }
        $('#siteId').val(navigationId);
    },

    checkDuration: function () {
        var durationElement = $('#spieldauer');
        var duration = $('#spieltyp').find(':selected').data('duration');
        if (duration == 'hide') {
            durationElement.val('regular');
            durationElement[0].disabled = true;
        }
        else if (duration == 'show') {
            durationElement[0].disabled = false;
        }
    },

    checkDelayed: function () {
        var delayedElement = $('#verschoben');
        var delayed = $('#spieltyp').find(':selected').data('delayed');
        if (delayed == 'hide') {
            delayedElement[0].disabled = true;
        }
        else if (delayed == 'show') {
            delayedElement[0].disabled = false;
        }
    },

    submitData: function () {
        /**
         * Update der Textareas mit Daten aus der CKEditor Instanz
         */
        editor.waitingElement.show();
        $('textarea.ckeditor').each(function () {
            var textArea = $(this);
            textArea.val(CKEDITOR.instances[textArea.attr('name')].getData());
        });

        var formData = new FormData(editor.formElement[0]);

        $.ajax({
            //url: webserviceUrl.replace('remote_data', 'test_data'),
            url: webserviceUrl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            error: function (jqXHR, textStatus, errorThrow) {
                console.log(jqXHR);
                console.log(textStatus);
                console.log(errorThrow);
                alert('Bei der Verarbeitung der Daten ist ein Fehler aufgetreten!')
            },
            success: function (data) {
                if (data === 'SUCCESS') {
                    location.reload();
                }
                else {
                    alert('Bei der Verarbeitung der Daten ist ein Fehler aufgetreten!')
                }
            }
        });
    }
});

navigation = new Object({
    navData: null,
    navPath: [],
    structureHtml: '',
    moveHtml: '',
    breadCrumb: '',
    chosenNavStart: 0,
    chosenNavId: 0,
    chosenData: null,

    structureElement: null,
    navPointElement: null,
    breadCrumbElement: null,
    showActionElement: null,
    templateElement: null,
    actionChooserElement: null,
    moveChooserElement: null,

    setData: function (navigationData) {
        navigation.navData = navigationData.navigation;
        navigation.navPath = navigationData.navPath;
        navigation.init();
    },

    init: function () {
        navigation.initElements();
        navigation.clickEvents();
    },

    initElements: function () {
        navigation.structureElement = $('#struktur');
        navigation.navPointElement = $('#navPoint');
        navigation.breadCrumbElement = $('#breadCrumb');
        navigation.showActionElement = $('#showAction');
        navigation.templateElement = $('#actionTemplates');
        navigation.moveChooserElement = $('#otherMain_box');
        navigation.actionChooserElement = $('.actionChooser', navigation.templateElement);
    },

    clickEvents: function () {
        navigation.structureElement.on('click', 'li.open > span', function () {
            var parent = $(this).parent('li');
            parent.removeClass('open');
            parent.addClass('navclose');
        });

        navigation.structureElement.on('click', 'li.navclose > span', function () {
            var parent = $(this).parent('li');
            parent.removeClass('navclose');
            parent.addClass('open');
        });

        navigation.navPointElement.on('click', 'li.open > span', function () {
            var parent = $(this).parent('li');
            parent.removeClass('open');
            parent.addClass('navclose');
        });

        navigation.navPointElement.on('click', 'li.navclose > span', function () {
            var parent = $(this).parent('li');
            parent.removeClass('navclose');
            parent.addClass('open');
        });

        navigation.structureElement.on('click', 'li.editable', function (event) {
            if (this != event.target) {
                return true;
            }
            navigation.chosenNavStart = $(this).data('navstart');
            navigation.chosenNavId = $(this).data('navid');
            navigation.makeBreadCrumb(this);
            navigation.fillEditArea();
        });

        navigation.navPointElement.on('click', 'li.editable', function (event) {
            if (this != event.target) {
                return true;
            }
            $('#navStart', editor.formElement).val($(this).data('navid'));
            $('#parentNavName', editor.formElement).val($(this).context.childNodes[1].textContent);
        });

        navigation.showActionElement.on('click', '[data-show]', function () {
            var action = $(this).data('show');
            navigation.showActionElement.html($('.action' + action, navigation.templateElement).clone());
        });

    },

    fillData: function () {
        navigation.makeHtml(0);
        $(navigation.structureElement, editor.contentElement).html(navigation.structureHtml);
        navigation.moveHtml = '<ul><li class="editable open"><span>&nbsp;</span> / ' + navigation.structureHtml + '</li></ul>';
        navigation.moveChooserElement.html(navigation.moveHtml);
        navigation.fillEditArea();
    },

    makeHtml: function (navStart) {
        var actualNavStartElements = navigation.navData['navStart_' + navStart];
        navigation.structureHtml += '<ul>';

        $.each(actualNavStartElements, function (key, actualNavElement) {
            var liClass = (actualNavElement[prefix + '_navEditable'] === 'true') ? 'editable ' : 'not_editable ';
            if ($.inArray(actualNavElement[prefix + '_navId'], navigation.navPath) !== -1) {
                liClass += 'open ';
                navigation.breadCrumb += '> ' + actualNavElement[prefix + '_navName'] + ' ';
            }
            else {
                liClass += 'navclose ';
            }
            liClass += (navigation.navData['navStart_' + actualNavElement[prefix + '_navId']] == undefined) ? 'empty ' : '';
            liClass += (actualNavElement[prefix + '_navActive'] != 'Y') ? 'editorDeactive ' : '';
            if (actualNavElement[prefix + '_navId'] == navigationId) {
                liClass += 'editorChosen';
                navigation.chosenNavStart = navStart;
                navigation.chosenNavId = navigationId;
            }
            navigation.structureHtml += '<li data-navstart="' + navStart + '" data-navid="' + actualNavElement[prefix + '_navId'] + '" class="' + liClass + '"><span>&nbsp;</span>' + actualNavElement[prefix + '_navName'];
            if (navigation.navData['navStart_' + actualNavElement[prefix + '_navId']] != undefined) {
                navigation.makeHtml(actualNavElement[prefix + '_navId']);
            }
            navigation.structureHtml += '</li>';
        });

        navigation.structureHtml += '</ul>';
    },

    makeBreadCrumb: function (element) {
        navigation.breadCrumb = ' > ' + $(element).context.childNodes[1].textContent;

        $.each($(element).parents('li'), function () {
            navigation.breadCrumb = ' > ' + ($(this).context.childNodes[1].textContent) + navigation.breadCrumb;
        });
    },

    fillEditArea: function () {
        navigation.breadCrumbElement.html(navigation.breadCrumb);
        navigation.chosenData = navigation.navData['navStart_' + navigation.chosenNavStart]['navId_' + navigation.chosenNavId];

        var activeElement = $('span[data-show="Activate"]', navigation.actionChooserElement);
        var deActiveElement = $('span[data-show="Deactivate"]', navigation.actionChooserElement);
        if (navigation.chosenData[prefix + '_navActive'] === 'Y') {
            activeElement.next('br').hide();
            activeElement.hide();
            deActiveElement.next('br').show();
            deActiveElement.show();
        }
        else {
            deActiveElement.next('br').hide();
            deActiveElement.hide();
            activeElement.next('br').show();
            activeElement.show();
        }

        editor.fillSpecial();
        navigation.fillSpecialData();

        navigation.showActionElement.html(navigation.actionChooserElement.clone());

        $.each(navigation.chosenData, function (key, value) {
            $('#' + key.replace(prefix + '_', ''), editor.formElement).val(value);
            /**
             * In den einzelnen Aktions-Templates suchen
             */
            $.each($('#' + key.replace(prefix + '_', ''), '#actionTemplates  div'), function () {
                $(this).val(value);
            });

        });

        navigation.navPointElement.show();
    },

    fillSpecialData: function () {
        navigation.fillPageTypes();
    },

    fillPageTypes: function () {
        var optionHtml = '';

        $.each(editorParams.pageTypes, function (key, value) {
            optionHtml += '<option value="' + value + '">' + editorLang.struktur[value] + '</option>';
        });

        $('.navigationType').html(optionHtml);
    },

    close: function () {
        navigation.structureHtml = '';
        navigation.navData = null;
        navigation.navPath = [];
        navigation.structureHtml = '';
        navigation.moveHtml = '';
        navigation.breadCrumb = '';
        navigation.chosenNavStart = 0;
        navigation.chosenNavId = 0;
        navigation.chosenData = null;

        navigation.structureElement = null;
        navigation.navPointElement = null;
        navigation.breadCrumbElement = null;
        navigation.showActionElement = null;
        navigation.templateElement = null;
        navigation.actionChooserElement = null;
        navigation.moveChooserElement = null;
    }


});