/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
var tiny_height = 560;
var text_area_class = 'textarea.editable';

if ($('textarea.editable').attr('height')) {
    tiny_height = $('textarea.editable').attr('height');
}

if ($('textarea.send-client-email-textarea').attr('height')) {
    tiny_height = $('textarea.send-client-email-textarea').attr('height');
    text_area_class += ' ,textarea.send-client-email-textarea';
}

if ($(text_area_class).attr('maxlength')) {
    var max_chars = $(text_area_class).attr('maxlength');
    
    tinymce.init({
    selector: text_area_class,
    menubar: true,
    visual: false,
    height: tiny_height,
    inline_styles: true,
    entity_encoding: "numeric",
    plugins: [
        "advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker",
        "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
        "save table directionality emoticons template paste fullpage code legacyoutput"
    ],
    content_css: "css/content.css",
    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image fullpage table | forecolor backcolor emoticons | preview | code | pagebreak ",
    pagebreak_separator: '<pagebreak />',
    fullpage_default_encoding: "UTF-8",
    extended_valid_elements: "svg[*],defs[*],pattern[*],desc[*],metadata[*],g[*],mask[*],path[*],line[*],marker[*],rect[*],circle[*],ellipse[*],polygon[*],polyline[*],linearGradient[*],radialGradient[*],stop[*],image[*],view[*],text[*],textPath[*],title[*],tspan[*],glyph[*],symbol[*],switch[*],use[*]",
    fullpage_default_doctype: "<!DOCTYPE html>",
    init_instance_callback: function (editor)
    {
        //$('#' + this.id).prev().append('<div class="char_count" style="text-align:right"></div>');
        tinymce_updateCharCounter($('.char-count-text'), tinymce_getContentLength());

    },
     file_picker_callback: function(cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.onchange = function() {
                var file = this.files[0];
                
                var reader = new FileReader();
                reader.onload = function () {
                    var id = 'blobid' + (new Date()).getTime();
                    var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
                    var base64 = reader.result.split(',')[1];
                    console.log('tineymce',id,file,base64);
                    var blobInfo = blobCache.create(id, file, base64);
                    blobCache.add(blobInfo);

                    // call the callback and populate the Title field with the file name
                    cb(blobInfo.blobUri(), { title: file.name });
                };
                reader.readAsDataURL(file);
            };

            input.click();
        },
        setup: function (ed) {
        var allowedKeys = [8, 37, 38, 39, 40, 46]; // backspace, delete and cursor keys
        ed.on('keydown keyup', function (e) {
            
            var is_ignore = false;
            if (e.keyCode == 88 && e.ctrlKey){
                return true;
            } 

            if (allowedKeys.indexOf(e.keyCode) != -1){
                return true
            } 

            console.log(tinymce_getContentLength(),max_chars,(tinymce_getContentLength() + 1 > max_chars),e.keyCode);

            if ((tinymce_getContentLength() + 1 > max_chars)) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
            return true;
        });
        
//        ed.on('keypress', function (e) {
//            console.log(tinymce_getContentLength())
//            //if (allowedKeys.indexOf(e.keyCode) != -1) return true;
//            if (tinymce_getContentLength() + 1 > max_chars) {
//                e.preventDefault();
//                e.stopPropagation();
//                return false;
//            }
//            return true;
//        });
        
    },
    paste_preprocess: function (plugin, args) {
        if(args.content){
            var editor = tinymce.get(tinymce.activeEditor.id);
            var editor_content = editor.getContent({format: 'text'});
            args.content = args.content.replace(/'/g, "\\'");
            
            var final_length = parseInt(args.content.length) + parseInt(editor_content.length);
            if (final_length > max_chars) {
                alert('Pasting this exceeds the maximum allowed number of ' + max_chars + ' characters.');
                args.content = '';
            }else{
                tinymce_updateCharCounter(editor, args.content.length)
            } 
        }
    }
});
}else{
    tinymce.init({
    selector: "textarea.editable",
    menubar: true,
    visual: false,
    height: tiny_height,
    inline_styles: true,
    entity_encoding: "numeric",
    plugins: [
        "advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker",
        "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
        "save table directionality emoticons template paste fullpage code legacyoutput"
    ],
    content_css: "css/content.css",
    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image fullpage table | forecolor backcolor emoticons | preview | code | pagebreak ",
    pagebreak_separator: '<pagebreak />',
    fullpage_default_encoding: "UTF-8",
    extended_valid_elements: "svg[*],defs[*],pattern[*],desc[*],metadata[*],g[*],mask[*],path[*],line[*],marker[*],rect[*],circle[*],ellipse[*],polygon[*],polyline[*],linearGradient[*],radialGradient[*],stop[*],image[*],view[*],text[*],textPath[*],title[*],tspan[*],glyph[*],symbol[*],switch[*],use[*]",
    fullpage_default_doctype: "<!DOCTYPE html>",
    init_instance_callback: function (editor)
    {
        editor.on('Change', function (e) {
//            if ($('.save-draft').hasClass('disabled')) {
//                $('.save-draft').removeClass('disabled').text('Save Draft');
//            }
        });

//        if (localStorage.getItem(templateID) !== null) {
//            editor.setContent(localStorage.getItem(templateID));
//        }

//        setTimeout(function () {
//            editor.execCommand("mceRepaint");
//        }, 2000);

    },
     file_picker_callback: function(cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.onchange = function() {
                var file = this.files[0];
                
                var reader = new FileReader();
                reader.onload = function () {
                    var id = 'blobid' + (new Date()).getTime();
                    var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
                    var base64 = reader.result.split(',')[1];
                    console.log('tineymce',id,file,base64);
                    var blobInfo = blobCache.create(id, file, base64);
                    blobCache.add(blobInfo);

                    // call the callback and populate the Title field with the file name
                    cb(blobInfo.blobUri(), { title: file.name });
                };
                reader.readAsDataURL(file);
            };

            input.click();
        }
});
}



function tinymce_updateCharCounter(el, len) {
    $('#' + el.id).prev().find('.char-count-text').text(len + '/' + max_chars);
}

function tinymce_getContentLength() {
    return tinymce.get(tinymce.activeEditor.id).contentDocument.body.innerText.length;
}

