$(function () {
    // Global
    var state = false;

    console.log('RTPE is ready to use');

    // On boot
    $('a[rtpe-element="button"]').removeClass('disabled');

    // Service functions
    function toBool(str) {
        var strToBoolean = (str === 'true') ? true : false;
        return strToBoolean;
    }

    // Click handler
    $('a[rtpe-element="button"]').on('click', function ( event ) {
        event.preventDefault();
        var currentState = toBool($(this).attr('rtpe-toggle'));
        state = !currentState;
        $(this).attr('rtpe-toggle', state);

        if(state) {
            $(this).find('i').removeClass('glyphicon-eye-open').addClass('glyphicon-eye-close');
            $('[rtpe-element="field"]').addClass('rtpe-editor-active').bind('click', function ( event ) {
                event.preventDefault();
                activate_rtpe_editor( $(this).attr('rtpe-type'), $(this).html(), $(this).attr('rtpe-field') );
            });
        }
        else {
            $(this).find('i').removeClass('glyphicon-eye-close').addClass('glyphicon-eye-open');
            $('[rtpe-element="field"]').removeClass('rtpe-editor-active').unbind('click');
        }
    });

    // Active RTPE element click handler
    function activate_rtpe_editor(type, val, field) {
        switch (type) {
            case 'text':
                text_edit_handler(val, field, type);
                break;
            case 'post':
                post_text_edit_handler(val, field, type);
                break;
            default:
                break;
        }
    }

    // Text edit handler
    function text_edit_handler(val, field, type) {
        $('#rtpeModal div.modal-dialog').removeClass('modal-lg');
        $('#rtpeModal div.modal-body').html('<input class="form-control" rtpe-element="edit-field" rtpe-field-type="" rtpe-save-to="" />').find('input').val(val.trim()).attr('rtpe-save-to', field).attr('rtpe-field-type', type);
        $('#rtpeModal').modal('show');
    }

    // Post text edit handler
    function post_text_edit_handler(val, field, type) {
        $('#rtpeModal div.modal-dialog').addClass('modal-lg');
        $('#rtpeModal div.modal-body').html('<textarea class="form-control" id="rtpe-post-text-editor" rtpe-field-type="" rtpe-element="edit-field" rtpe-save-to=""></textarea>').find('textarea').val(val.trim()).attr('rtpe-save-to', field).attr('rtpe-field-type', type);
        tinymce.init({
            selector: "#rtpe-post-text-editor",
            content_css: "/plugins/tinymce/skins/lightgray/tenews.css",
            language:"uk",
            theme: "modern",
            plugins: [
                "advlist autolink lists link image charmap print preview hr anchor pagebreak",
                "searchreplace wordcount visualblocks visualchars code fullscreen",
                "insertdatetime media nonbreaking save table contextmenu directionality",
                "emoticons template paste textcolor colorpicker textpattern"
            ],
            toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
            toolbar2: "print preview media | forecolor backcolor emoticons",
            image_advtab: true,
            toolbar: "image",
            templates: [
                {title: 'Test template 1', content: 'Test 1'},
                {title: 'Test template 2', content: 'Test 2'}
            ],
            height:300,
            convert_urls:false,
            relative_urls:true,
            image_caption: true,
            style_formats: [
                {title: "Headers", items: [
                    {title: "Header 1", format: "h1"},
                    {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: "Strikethrough", icon: "strikethrough", format: "strikethrough"},
                    {title: "Superscript", icon: "superscript", format: "superscript"},
                    {title: "Subscript", icon: "subscript", format: "subscript"},
                    {title: "Code", icon: "code", format: "code"}
                ]},
                {title: "Blocks", items: [
                    {title: "Paragraph", format: "p"},
                    {title: "Blockquote", format: "blockquote"},
                    {title: "Div", format: "div"},
                    {title: "Pre", format: "pre"}
                ]},
                {title: "Alignment", items: [
                    {title: "Left", icon: "alignleft", format: "alignleft"},
                    {title: "Center", icon: "aligncenter", format: "aligncenter"},
                    {title: "Right", icon: "alignright", format: "alignright"},
                    {title: "Justify", icon: "alignjustify", format: "alignjustify"}
                ]},
                {title: 'Фото (лівий край)', selector: 'img', styles: {
                    'float' : 'left',
                    'margin': '0 10px 0 10px'
                }},
                {title: 'Фото (правий край)', selector: 'img', styles: {
                    'float' : 'right',
                    'margin': '0 10px 0 10px'
                }},
                {title: 'Блок (лівий край)', selector: 'div', styles: {
                    'float' : 'left',
                    'margin': '0 10px 0 10px'
                }},
                {title: 'Блок (правий край)', selector: 'div', styles: {
                    'float' : 'right',
                    'margin': '0 10px 0 10px'
                }}

            ]
        });

        $('#rtpeModal').modal('show');
    }

    $('[rtpe-type="save-changes"]').on('click', function ( event ) {
        event.preventDefault();
        var type = $('[rtpe-element="edit-field"]').attr('rtpe-field-type');

        switch (type) {
            case 'text':
                save_text_handler();
                break;
            case 'post':
                save_post_text_handler();
                break;
            default:
                break;
        }
    });

    function save_text_handler() {
        var save_to = $('[rtpe-element="edit-field"]').attr('rtpe-save-to');
        var save_value = $('[rtpe-element="edit-field"]').val();
        send_changes(save_to, save_value);
    }

    function save_post_text_handler() {
        var save_to = $('[rtpe-element="edit-field"]').attr('rtpe-save-to');
        var save_value = tinymce.get('rtpe-post-text-editor').getContent();
        send_changes(save_to, save_value);
    }

    function send_changes(save_to, save_val) {
        var slug = $('[rtpe-type="slug"]').attr('rtpe-href');

        $.ajax({
            url: 'http://www.tenews.org.ua/post/rtpe_save',
            type: 'POST',
            data: {
                save_slug: slug,
                save_field: save_to,
                save_value: save_val
            }
        }).done(function (data) {
            if(data === 'done') {
                $('#rtpeModal').modal('hide');
                var url = window.location.href;
                if(url.match(/\/no-cache/) !== null) {
                    window.location.replace(url);
                }
                else {
                    url = url + '/no-cache';
                    window.location.replace(url);
                }
            }
        }).fail(function () {
            console.log('RTPE request return error');
        });
    }
});