var userId;
var specialSite;
var editorLang;
var grid;
var gridCount;
var prefix;
var navigationId;
var webserviceUrl;
var editorUrl;
var editorVersion;
var sessLang;
var navId;
var editorParams;
var pathMed;
var imageTypes;
var dimOrig;
var stdKeyvisual;
var dimKeyvisual;
var keyvisualThumb;
var stdImage;
var dimImage;
var imageThumb;

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

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

    /**
     * jQuery-Elemente für den Editor
     */
    pageElement: null,
    titleElement: null,
    layerElement: null,
    closeElement: null,
    contentElement: null,
    waitingElement: null,
    editableElement: null,
    formElement: null,
    newObjectElement: null,
    newObjectTitleElement: null,
    newObjectMinElement: null,
    newSublineElement: null,
    newTextElement: null,
    newTextImageTextElement: null,
    newTextImageImageElement: null,
    newElementsClass: null,
    element: null,

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

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

        if (specialSite === true) {
            return true;
        }
        $('> div:not(.headline)', editor.pageElement).each(function () {
            $(this).append('<span class="sort_handle"></span>');
            $(this).append('<span class="del_handle"></span>');
        });

    },

    initNewElements: function () {
        editor.newObjectElement = $('#editor_elements');
        editor.newObjectTitleElement = $('#boxtitle');
        editor.newSublineElement = $('.content', '#content_subline_');
        editor.newTextElement = $('.content', '#content_text_');
        editor.newTextImageTextElement = $('.content', '#content_textimage_');
        editor.newTextImageImageElement = $('img', '#content_textimage_');

        editor.newObjectMinElement = $('.min');
        editor.newElementsClass = $('.elem_button');

        editor.newObjectTitleElement.html(editorLang.newContent.title);
        editor.newSublineElement.html(editorLang.newContent.subline);
        editor.newTextElement.html(editorLang.newContent.text);
        editor.newTextImageTextElement.html(editorLang.newContent.textImage);
        editor.newTextImageImageElement.attr('src', stdImage);
    },

    hoverEvents: function () {
        editor.editableElement.on('mouseenter', function (event) {
            if ($(event.currentTarget).data('editable') === 'textimage') {
                return;
            }
            $(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' || event.target.tagName === 'SPAN') {
                return true;
            }

            var tmpEditorType = event.currentTarget.dataset.editable;
            if (tmpEditorType === 'textimage') {
                return true;
            }

            editor.type = tmpEditorType;
            editor.waitingElement.show();
            editor.name = editor.type.toUpperCase();
            editor.element = $(event.currentTarget).attr('id');
            editor.callEditor();
        });

        editor.closeElement.click(function () {
            editor.close();
            navEditor.close();
            imgEditor.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;
            }
        });

        editor.newObjectElement.on('click', editor.newObjectMinElement, function (event) {
            if (!$(event.target).hasClass('min')) {
                return;
            }
            if (editor.newObjectTitleElement.html() !== '') {
                editor.newObjectTitleElement.html('');
                editor.newObjectMinElement.html('<');
                $(this).css({width: grid, height: grid});
                editor.newObjectMinElement.css({marginRight: -1 * (grid / 2)});
            }
            else {
                editor.newObjectTitleElement.html(editorLang.newContent.title);
                editor.newObjectMinElement.html('>');
                $(this).css({width: '', height: ''});
                editor.newObjectMinElement.css({marginRight: ''});
            }
        });

        editor.newObjectElement.draggable({
            addClasses: false,
            handle: editor.newObjectTitleElement
        });

        editor.pageElement.sortable({
            axis: 'y',
            forcePlaceholderSize: true,
            handle: '.sort_handle',
            items: '> :not(.headline)',
            placeholder: 'editable_hover',
            receive: function (event, ui) {
                editor.preventSortStop = true;

                ui.helper.attr('id', ui.helper.data('temp'));
                ui.helper.removeAttr('style');

                var headline = $('.headline', editor.pageElement);
                var sortOrder = editor.pageElement.sortable('toArray');
                var isTextImage = (ui.helper.attr('id') === 'content_textimage_');
                if (headline.length === 1) {
                    sortOrder.splice(0, 0, headline.attr('id'));
                }

                var formData = {
                    request: 'insertData',
                    userId: userId,
                    prefix: prefix,
                    navId: navigationId,
                    dataSet: ui.helper.data('temp'),
                    content: $('.content', ui.helper).html(),
                    order: sortOrder
                };
                if (isTextImage) {
                    formData.image = $('img', ui.helper).attr('src');
                }

                $.ajax({
                    url: webserviceUrl,
                    data: formData,
                    dataType: 'json',
                    method: 'post',
                    error: function (jqXHR, textStatus, errorThrow) {
                        console.log(jqXHR);
                        console.log(textStatus);
                        console.log(errorThrow);
                        alert('Fehler beim Einfügen des neuen Seitenelements!')
                    },

                    success: function (data) {
                        if (isTextImage) {
                            location.reload();
                        }
                        ui.helper.attr('id', ui.helper.data('temp') + data);
                        editor.preventSortStop = false;
                    }
                });

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

                if (editor.preventSortStop === true) {
                    return;
                }
                var headline = $('.headline', editor.pageElement);
                var sortOrder = editor.pageElement.sortable('toArray');
                if (headline.length === 1) {
                    sortOrder.splice(0, 0, headline.attr('id'));
                }
                var formData = {
                    request: 'updateData',
                    userId: userId,
                    prefix: prefix,
                    dataSet: 'content_' + navigationId,
                    siteContents: sortOrder.join(';').replace(/content_/g, '')
                };

                $.ajax({
                    url: webserviceUrl,
                    data: formData,
                    dataType: 'text',
                    method: 'post',
                    error: function (jqXHR, textStatus, errorThrow) {
                        console.log(jqXHR);
                        console.log(textStatus);
                        console.log(errorThrow);
                        alert('Fehler beim Speichern der Sortierung!')
                    }
                });
            }
        });

        editor.newElementsClass.draggable({
            connectToSortable: editor.pageElement,
            helper: 'clone',
            start: function (event, ui) {
                ui.helper.removeClass('elem_button');
                ui.helper.removeClass('editable_hover');
                $('div', ui.helper).removeClass('editable_hover');
                ui.helper.attr('data-temp', $(ui.helper.context).prop('id'));
            }
        });

        editor.pageElement.on('click', '.del_handle', function () {
            var element = $(this).parent('[data-editable]');
            var formData = {
                request: 'deleteData',
                userId: userId,
                prefix: prefix,
                dataSet: $(this).parent('[data-editable]').attr('id'),
                navId: navigationId
            };

            $.ajax({
                url: webserviceUrl,
                data: formData,
                method: 'post',
                dataType: 'text',
                error: function (x, y, z) {
                    console.log(x);
                    console.log(y);
                    console.log(z);
                    alert('Fehler beim Löschen des Seitenelements!');
                },
                success: function () {
                    element.remove();
                }
            });

        });
    },

    close: function () {
        editor.type = '';
        editor.name = '';
        editor.contentHtml = '';
        editor.contentData = null;
        editor.preventSortStop = false;

        editor.element = 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 (element) {
        var requestElement = (element) ? element : editor.element;
        var elementArray = requestElement.split('_');
        if (elementArray[elementArray.length - 1] === '') {
            editor.contentData = {};
            editor.fillHtml();
            return;
        }

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

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

        if (editor.type === 'spielbericht') {
            editor.fillSpielBericht();
            editor.fillStandard();
        }
        else if (editor.type === 'keyvisual' || editor.type === 'image') {
            imgEditor.setData(editor.contentData);
        }
        else if (editor.type === 'struktur') {
            navEditor.setData(editor.contentData);
            navEditor.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 () {
        editor.waitingElement.show();
        /**
         * Update der Textareas mit Daten aus der CKEditor Instanz
         */
        $('textarea.ckeditor').each(function () {
            var textArea = $(this);
            textArea.val(CKEDITOR.instances[textArea.attr('name')].getData());
        });

        $('.uploadFile').prop('disabled', true);
        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!')
                }
            }
        });
    }
});

var navEditor = 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) {
        navEditor.navData = navigationData.navigation;
        navEditor.navPath = navigationData.navPath;
        navEditor.init();
    },

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

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

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

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

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

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

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

        navEditor.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);
        });

        navEditor.showActionElement.on('click', '[data-show]', function () {
            var action = $(this).data('show');
            navEditor.showActionElement.html($('.action' + action, navEditor.templateElement).clone());
            $('.navSort', navEditor.showActionElement).sortable({
                axis: 'y',
                handle: '.sort_handle',
                stop: function () {
                    var newSort = $('.navSort', navEditor.showActionElement).sortable('toArray');
                    $('.newSort', navEditor.showActionElement).val(JSON.stringify(newSort));
                    $('input.hidden', navEditor.showActionElement).removeClass('hidden');
                }
            });
        });

    },

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

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

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

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

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

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

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

        var activeElement = $('span[data-show="Activate"]', navEditor.actionChooserElement);
        var deActiveElement = $('span[data-show="Deactivate"]', navEditor.actionChooserElement);
        if (navEditor.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();
        navEditor.fillSpecialData();

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

        $.each(navEditor.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);
            });

        });

        navEditor.navPointElement.show();
    },

    fillSpecialData: function () {
        navEditor.fillPageTypes();
        navEditor.fillSortData();
    },

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

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

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

    fillSortData: function () {
        var navPoints = navEditor.navData['navStart_' + navEditor.chosenNavStart];
        var button = $('.checkSort');
        var navSort = $('.navSort');

        if (Object.keys(navPoints).length < 2) {
            button.hide();
            button.next('br').hide();
            return true;
        }

        navSort.html('');
        $.each(navPoints, function (navId, navPointData) {
            navSort.append('<li id="sort_' + navPointData[prefix + '_navId'] + '">' + navPointData[prefix + '_navName'] + '<span class="sort_handle"></span></li>');
        });

        button.show();
        button.next('br').show();
    },

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

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

var imgEditor = new Object({
    thumbSuffix: '_thumb',
    origSuffix: '_orig',
    editImageID: 'editImage',

    isFirst: true,
    imgCount: 0,
    imgIDs: [],
    imgData: {},
    imgPath: '',
    imgTypes: [],
    maxDimension: {},
    imgDummy: '',
    imgDummyExtension: '',
    imgDimension: {},
    imgOrigDimension: {},
    thumbDimension: {},
    coverDimension: {},
    uploadSource: '',
    chosenThumb: -1,

    editActive: true,
    sortActive: false,
    deleteActive: false,
    uploadActive: false,

    imgThumbElement: null,
    dataSetElement: null,
    imgSliderElement: null,
    sortBoxElement: null,
    sortButtonElement: null,
    sortCancelElement: null,
    deleteCancelElement: null,
    rightBoxElement: null,
    formActionElement: null,
    imagePlaceholder: null,
    imagePreview: null,
    imageCover: null,
    coverTop: null,
    coverRight: null,
    coverBottom: null,
    coverLeft: null,
    previewTop: null,
    previewLeft: null,
    previewHeight: null,
    previewWidth: null,
    editImage: null,

    setData: function (imageData) {
        if ($.isEmptyObject(imageData) === true) {
            imgEditor.imgCount = 0;
            imgEditor.init();
            imgEditor.fillData();
            return;
        }

        imgEditor.imgData[imageData.id] = imageData;

        if (imgEditor.isFirst === true) {
            imgEditor.imgIDs.push(imageData.id);
            imgEditor.isFirst = false;

            if (imageData.sliderContent !== '') {
                var sliderContents = imageData.sliderContent.split(';');
                imgEditor.getSliderContent(sliderContents);
            }

            imgEditor.init();
        }

        imgEditor.imgCount++;
        if (imgEditor.imgCount === 1) {
            imgEditor.fillData();
        }
    },

    initElements: function () {
        imgEditor.imgThumbElement = $('#imgThumbs');
        imgEditor.dataSetElement = $('#dataSet');
        imgEditor.imgSliderElement = $('#imageSlider');
        imgEditor.sortBoxElement = $('#newSort_box');
        imgEditor.sortButtonElement = $('#sortButton');
        imgEditor.sortCancelElement = $('#sortCancel');
        imgEditor.deleteCancelElement = $('#deleteCancel');
        imgEditor.uploadCancelElement = $('#uploadCancel');
        imgEditor.sortBoxElement.css({width: imgEditor.thumbDimension.width + 4 * grid});
        imgEditor.rightBoxElement = $('.rightBox');
        imgEditor.rightBoxElement.css({width: (parseInt(gridCount) * parseInt(grid - 1) - parseInt(imgEditor.sortBoxElement.css('width')) - 8)});
        imgEditor.formActionElement = $('#formAction');
        imgEditor.imagePlaceholder = $('#imagePlaceholder');
        imgEditor.imagePreview = $('#imagePreview');
        imgEditor.imageCover = $('#imageCover');
        imgEditor.coverTop = $('#coverTop');
        imgEditor.coverRight = $('#coverRight');
        imgEditor.coverBottom = $('#coverBottom');
        imgEditor.coverLeft = $('#coverLeft');
        imgEditor.previewTop = $('#previewTop');
        imgEditor.previewLeft = $('#previewLeft');
        imgEditor.previewHeight = $('#previewHeight');
        imgEditor.previewWidth = $('#previewWidth');
        imgEditor.editImage = $('#' + imgEditor.editImageID);
    },

    clickEvents: function () {

        imgEditor.sortButtonElement.click(function () {
            imgEditor.enableSorting();
        });
        imgEditor.sortCancelElement.click(function () {
            imgEditor.enableEdit();
        });
        imgEditor.sortBoxElement.on('click', '.del_handle', function (event) {
            imgEditor.enableDelete(event);
        });
        imgEditor.deleteCancelElement.click(function () {
            imgEditor.enableEdit();
        });
        imgEditor.uploadCancelElement.click(function () {
            imgEditor.enableEdit();
        });

        $('.uploadFile', editor.contentElement).change(imgEditor.handleFileSelect);


    },

    init: function () {
        imgEditor.imgPath = pathMed + prefix + '/' + navigationId + '/';
        imgEditor.imgTypes = imageTypes;
        imgEditor.maxDimension = dimOrig;

        if (editor.type === 'keyvisual') {
            imgEditor.imgDummy = stdKeyvisual;
            imgEditor.imgDimension = dimKeyvisual;
            imgEditor.thumbDimension = keyvisualThumb;
        }
        else if (editor.type === 'image') {
            imgEditor.imgDummy = stdImage;
            imgEditor.imgDimension = dimImage;
            imgEditor.thumbDimension = imageThumb;
        }

        imgEditor.imgDummyExtension = imgEditor.getExtension(imgEditor.imgDummy);

        imgEditor.initElements();
        imgEditor.clickEvents();

        imgEditor.enableEdit();
    },

    fillData: function () {
        if (imgEditor.imgCount < imgEditor.imgIDs.length) {
            window.setTimeout(imgEditor.fillData, 50);
            return;
        }

        $('#navId', editor.contentElement).val(navigationId);

        if (editor.type === 'keyvisual') {
            $.each(imgEditor.imgIDs, function (key, value) {
                if (key === 0) {
                    imgEditor.imgThumbElement.append('<li id="sort_' + value + '"><img src="' + imgEditor.imgPath + imgEditor.imgData[value].imgName + imgEditor.thumbSuffix + '.' + imgEditor.imgData[value].imgExtension + '" onclick="imgEditor.fillForm(' + value + ', ' + key + ');"/></li>');
                    return true;
                }
                imgEditor.imgThumbElement.append('<li id="sort_' + value + '"><img src="' + imgEditor.imgPath + imgEditor.imgData[value].imgName + imgEditor.thumbSuffix + '.' + imgEditor.imgData[value].imgExtension + '" onclick="imgEditor.fillForm(' + value + ', ' + key + ');"/><span class="del_handle">&nbsp;</span></li>');
            });

            if (imgEditor.imgData[imgEditor.imgIDs[0]].hasSlider === 'Y') {
                imgEditor.sortBoxElement.append('<img src="' + imgEditor.imgDummy.replace(imgEditor.imgDummyExtension, imgEditor.thumbSuffix + imgEditor.imgDummyExtension) + '" onclick="imgEditor.enableUpload();"/>');
            }
        }
        else if (editor.type === 'image') {
            imgEditor.imgData[imgEditor.imgIDs[0]].sliderContent = '';
            imgEditor.imgData[imgEditor.imgIDs[0]].hasSlider = 'N';
            imgEditor.fillForm(imgEditor.imgIDs[0], 0);
        }
    },

    getSliderContent: function (sliderContents) {
        $.each(sliderContents, function (key, value) {
            imgEditor.imgIDs.push(value);
            editor.getEditorData(editor.type + '_' + value);
        });
    },

    fillForm: function (imgID, imgKey) {
        imgEditor.chosenThumb = imgKey;
        if (imgEditor.editActive !== true) {
            return;
        }

        editor.contentData = imgEditor.imgData[imgID];
        editor.fillStandard();

        if (imgKey !== 0) {
            imgEditor.imgSliderElement.hide();
        }
        else {
            imgEditor.imgSliderElement.show();
        }

        imgEditor.makeEditingArea(imgID);
        (imgID === -1) ? imgEditor.dataSetElement.val(editor.type + '_' + imgEditor.imgIDs[0]) : imgEditor.dataSetElement.val(editor.type + '_' + imgID);

        var actualInnerSlider = $('.editor_slider').children('.inner');
        actualInnerSlider.hide();
        actualInnerSlider.next('.inner').show();
    },

    getExtension: function (imgPath) {
        var imgPathArray = imgPath.split('.');
        return '.' + imgPathArray[imgPathArray.length - 1];
    },

    makeEditingArea: function (imgID) {
        var origImage = imgEditor.imgPath + imgEditor.imgData[imgID].imgName + imgEditor.origSuffix + '.' + imgEditor.imgData[imgID].imgExtension;
        $('img', imgEditor.imagePlaceholder).remove();

        if (imgID === -1) {
            imgEditor.imagePlaceholder.append('<img id="' + imgEditor.editImageID + '" src="' + imgEditor.uploadSource + '"/>');
            $('#uploadFile').val(imgEditor.uploadSource);
            $('#uploadFile').prop('disabled', false);
            editor.waitingElement.hide();
        }
        else {
            imgEditor.imagePlaceholder.append('<img id="' + imgEditor.editImageID + '" src="' + origImage + '"/>');
            $('#uploadFile').val('');
            $('#uploadFile').prop('disabled', true);
            imgEditor.formActionElement.val('');
            imgEditor.formActionElement.prop('disabled', true);
        }
        imgEditor.editImage = $('#' + imgEditor.editImageID);

        imgEditor.editImage.load(function () {
            imgEditor.imgOrigDimension = {width: $(this).width(), height: $(this).height()};
            imgEditor.editImage.css({width: imgEditor.imgDimension.width});
            imgEditor.imagePlaceholder.css({width: imgEditor.imgDimension.width, height: imgEditor.editImage.innerHeight()});
            imgEditor.imageCover.css({width: imgEditor.imgDimension.width, height: imgEditor.editImage.innerHeight()});
            imgEditor.setCover();

            imgEditor.imagePreview.resizable({
                aspectRatio: true,
                containment: imgEditor.imagePlaceholder,
                handles: 'se',
                minWidth: (imgEditor.imgDimension.width * imgEditor.imgDimension.width / imgEditor.imgOrigDimension.width),
                create: function() {
                    if(imgEditor.imagePreview.innerHeight() > imgEditor.editImage.innerHeight()) {
                        imgEditor.imagePreview.css({width: (imgEditor.imagePreview.innerWidth() * imgEditor.editImage.innerHeight() / imgEditor.imagePreview.innerHeight()), height: imgEditor.editImage.innerHeight() });
                        imgEditor.previewHeight.val(imgEditor.editImage.innerHeight());
                        imgEditor.previewWidth.val(imgEditor.imagePreview.innerWidth() * imgEditor.editImage.innerHeight() / imgEditor.imagePreview.innerHeight());
                        imgEditor.setCover();
                    }
                },
                resize: function (event, ui) {
                    imgEditor.previewHeight.val(ui.size.height);
                    imgEditor.previewWidth.val(ui.size.width);
                    imgEditor.setCover();
                }
            });

            imgEditor.imagePreview.draggable({
                containment: imgEditor.imagePlaceholder,
                cursor: 'crosshair',
                drag: function (event, ui) {
                    imgEditor.previewTop.val(ui.position.top);
                    imgEditor.previewLeft.val(ui.position.left);
                    imgEditor.setCover();
                }
            });
        });

    },

    setCover: function () {
        imgEditor.coverDimension = {
            top: parseFloat(imgEditor.previewTop.val()),
            right: parseFloat(imgEditor.previewLeft.val()) + parseFloat(imgEditor.previewWidth.val()),
            bottom: parseFloat(imgEditor.previewTop.val()) + parseFloat(imgEditor.previewHeight.val()),
            left: parseFloat(imgEditor.previewLeft.val()),
            width: parseFloat(imgEditor.previewWidth.val()),
            height: parseFloat(imgEditor.previewHeight.val())
        };

        imgEditor.imagePreview.css({
            top: imgEditor.coverDimension.top,
            left: imgEditor.coverDimension.left,
            height: imgEditor.coverDimension.height,
            width: imgEditor.coverDimension.width
        });
        imgEditor.coverTop.css({top: 0, left: 0, height: imgEditor.coverDimension.top, width: imgEditor.imgDimension.width});
        imgEditor.coverRight.css({
            top: imgEditor.coverDimension.top,
            left: imgEditor.coverDimension.right,
            height: imgEditor.coverDimension.bottom - imgEditor.coverDimension.top,
            width: imgEditor.imgDimension.width - imgEditor.coverDimension.right
        });
        imgEditor.coverBottom.css({
            top: imgEditor.coverDimension.bottom,
            left: 0,
            height: (imgEditor.editImage.innerHeight() - imgEditor.coverDimension.bottom),
            width: imgEditor.imgDimension.width
        });
        imgEditor.coverLeft.css({
            top: imgEditor.coverDimension.top,
            left: 0,
            height: imgEditor.coverDimension.height,
            width: imgEditor.coverDimension.left
        });
    },

    enableEdit: function () {
        imgEditor.editActive = true;
        imgEditor.disableDelete();
        imgEditor.disableUpload();
        imgEditor.disableSorting();

        imgEditor.formActionElement.val('updateData');

        $('input', '.editFields').prop('disabled', false);
        $('.editFields').show();
    },

    enableDelete: function (event) {
        imgEditor.deleteActive = true;
        imgEditor.disableEdit();
        imgEditor.disableUpload();
        imgEditor.disableSorting();

        $('#dataSet').val($(event.target).parent('li').attr('id').replace('sort', editor.type));
        $('#firstImage').val($('li:first-of-type', imgEditor.imgThumbElement).attr('id').replace('sort_', ''));

        $('#request').val('deleteData');
        $('input', '.deleteFields').prop('disabled', false);
        $('.deleteFields').show();
    },

    enableUpload: function () {
        if (imgEditor.editActive !== true) {
            return;
        }
        imgEditor.chosenThumb = -1;
        imgEditor.uploadActive = true;
        imgEditor.disableEdit();
        imgEditor.disableDelete();
        imgEditor.disableSorting();

        imgEditor.formActionElement.val('updateData');

        $('input', '.uploadFields').prop('disabled', false);
        $('.uploadFields').show();
    },

    handleFileSelect: function (event) {
        var uploadFile = event.target.files[0];
        var fileReader = new FileReader();

        if ($.inArray(uploadFile.type, imageTypes) === -1) {
            alert('Die gewählte Datei kann nicht verarbeitet werden. Wählen Sie ein passendes Bildformat!');
            return false;
        }

        editor.waitingElement.show();
        fileReader.onload = (function (uploadFile) {
            return function (fileEvent) {
                var extension = uploadFile.type.replace('image/', '').replace('jpeg', 'jpg');
                var fileName = uploadFile.name.split('.');
                fileName.pop();
                fileName = fileName.join('.');

                imgEditor.imgData[-1] = {
                    id: -1,
                    imgName: fileName.toLowerCase(),
                    imgExtension: extension,
                    imgTitle: fileName.charAt(0).toUpperCase() + fileName.slice(1).toLowerCase(),
                    imgOrigname: fileName + '.' + extension,
                    previewTop: 0,
                    previewLeft: 0,
                    previewHeight: imgEditor.imgDimension.height,
                    previewWidth: imgEditor.imgDimension.width,
                    hasSlider: 'N',
                    sliderContent: ''
                };
                if (imgEditor.chosenThumb === 0) {
                    imgEditor.imgData[-1].hasSlider = imgEditor.imgData[imgEditor.imgIDs[imgEditor.chosenThumb]].hasSlider;
                    imgEditor.imgData[-1].sliderContent = imgEditor.imgData[imgEditor.imgIDs[imgEditor.chosenThumb]].sliderContent;
                }

                var uploadImg = new Image();
                uploadImg.src = fileEvent.target.result;

                uploadImg.onload = function () {
                    if (this.width < imgEditor.imgDimension.width || this.height < imgEditor.imgDimension.height) {
                        alert('Das gewählte Bild entspricht nicht den minimalen Abmessungen (Breite:' + imgEditor.imgDimension.width + 'px x Höhe: ' + imgEditor.imgDimension.height + 'px)');
                        editor.waitingElement.hide();
                        return false;
                    }
                    imgEditor.uploadSource = fileEvent.target.result;

                    if (imgEditor.imagePreview.is(':ui-resizable')) {
                        imgEditor.imagePreview.resizable('destroy');
                    }

                    imgEditor.enableEdit();
                    imgEditor.fillForm(-1, -1);

                    if ($(event.target).prop('id') === 'newUploadFile') {
                        imgEditor.formActionElement.val('appendImage');
                        imgEditor.formActionElement.prop('disabled', false);
                    }
                    else if ($(event.target).prop('id') === 'changeUploadFile') {
                        imgEditor.formActionElement.val('');
                        imgEditor.formActionElement.prop('disabled', true);
                    }

                };

            };
        })(uploadFile);
        fileReader.readAsDataURL(uploadFile);
    },

    enableSorting: function () {

        if (imgEditor.imgCount < 2) {
            return;
        }

        imgEditor.sortActive = true;
        imgEditor.disableEdit();
        imgEditor.disableDelete();
        imgEditor.disableUpload();

        $.each($('li', imgEditor.imgThumbElement), function () {
            $(this).append('<span class="sort_handle">&nbsp;</span>');
            $('.del_handle', this).remove();
        });

        $('input', '.sortFields').prop('disabled', false);
        $('.sortFields').show();

        imgEditor.imgThumbElement.sortable({
            axis: 'y',
            handle: '.sort_handle',
            stop: function () {
                imgEditor.formActionElement.val('updateSort');
                imgEditor.formActionElement[0].disabled = false;
                var sorting = imgEditor.imgThumbElement.sortable('toArray');
                var newFirstImageID = sorting.shift().replace('sort_', '');
                var sliderContent = sorting.join(';').replace(/sort_/g, '');
                editor.contentData = imgEditor.imgData[newFirstImageID];
                editor.fillStandard();
                imgEditor.dataSetElement.val(editor.type + '_' + newFirstImageID);
                $('#sortSave').show();
                $('#sliderContent').val(sliderContent);
            }
        });
    },

    disableEdit: function () {
        imgEditor.editActive = false;

        $('input', '.editFields').prop('disabled', true);
        $('.editFields').hide();
    },

    disableDelete: function () {
        imgEditor.deleteActive = false;

        $('input', '.deleteFields').prop('disabled', true);
        $('.deleteFields').hide();
    },

    disableUpload: function () {
        imgEditor.uploadActive = false;

        $('input', '.uploadFields').prop('disabled', true);
        $('.uploadFields').hide();
    },

    disableSorting: function () {
        imgEditor.sortActive = false;

        if (imgEditor.imgThumbElement.is(':ui-sortable')) {
            imgEditor.imgThumbElement.sortable('destroy');

            $.each($('li', imgEditor.imgThumbElement), function (key) {
                if (key > 0) {
                    $(this).append('<span class="del_handle">&nbsp;</span>');
                }
                $('.sort_handle', this).remove();
            });
        }

        $('input', '.sortFields').prop('disabled', true);
        $('.sortFields').hide();
        $('#sortSave').hide();
    },

    close: function () {
        imgEditor.isFirst = true;
        imgEditor.imgCount = 0;
        imgEditor.imgIDs = [];
        imgEditor.imgData = {};
        imgEditor.imgPath = '';
        imgEditor.imgTypes = [];
        imgEditor.maxDimension = {};
        imgEditor.imgDummy = '';
        imgEditor.imgDummyExtension = '';
        imgEditor.imgDimension = {};
        imgEditor.imgOrigDimension = {};
        imgEditor.thumbDimension = {};
        imgEditor.coverDimension = {};
        imgEditor.uploadSource = '';
        imgEditor.chosenThumb = -1;

        imgEditor.editActive = true;
        imgEditor.sortActive = false;
        imgEditor.deleteActive = false;
        imgEditor.uploadActive = false;

        imgEditor.imgThumbElement = null;
        imgEditor.dataSetElement = null;
        imgEditor.imgSliderElement = null;
        imgEditor.sortBoxElement = null;
        imgEditor.sortButtonElement = null;
        imgEditor.sortCancelElement = null;
        imgEditor.deleteCancelElement = null;
        imgEditor.rightBoxElement = null;
        imgEditor.formActionElement = null;
        imgEditor.imagePlaceholder = null;
        imgEditor.imagePreview = null;
        imgEditor.imageCover = null;
        imgEditor.coverTop = null;
        imgEditor.coverRight = null;
        imgEditor.coverBottom = null;
        imgEditor.coverLeft = null;
        imgEditor.previewTop = null;
        imgEditor.previewLeft = null;
        imgEditor.previewHeight = null;
        imgEditor.previewWidth = null;
        imgEditor.editImage = null;
    }
});