<? if ( !defined("_INCLUDED_GLOBAL") ) exit;		// [Security]Allow_url_fopen = On ?>

<? if ($G_SYS['WEBEDITOR'] == 'TINYMCE5') { ?>
	<link rel="STYLESHEET" type="text/css" href="<?= nskindirroot('main') ?>/tinymce5.css?v=<?= NM_VER ?>">
	<script language="JavaScript" src="<?= $nmpath2 ?>/addon/tinymce5/tinymce.min.js?v=<?= NM_VER ?>"></script>
	<? if ( ! (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== false || strpos($_SERVER['HTTP_USER_AGENT'],
					'Trident') !== false)) { ?>
		<script language="JavaScript" src="<?= $nmpath2 ?>/addon/juice/build/bundle.min.js?v=<?= NM_VER ?>"></script>
	<? } ?>

	<script>

	// 웹에디터
	function tinymce5_images_upload_handler(blobInfo, success, failure, progress) {
	    var xhr, formData;

	    xhr = new XMLHttpRequest();
	    xhr.withCredentials = false;
	    xhr.open('POST', '<?= $G_SYS['HTTP_URL_ROOT'] ?>/sign_upload_json.php');

	    xhr.upload.onprogress = function (e) {
	        progress(e.loaded / e.total * 100);
	    };

	    xhr.onload = function () {
	        var json;

	        if (xhr.status === 403) {
	            failure('이미지 업로드가 실패하였습니다.\n\nHTTP Error: ' + xhr.status, {remove: true});
	            return;
	        }

	        if (xhr.status < 200 || xhr.status >= 300) {
	            failure('이미지 업로드가 실패하였습니다.\n\nHTTP Error: ' + xhr.status, {remove: true});
	            return;
	        }

	        try {
	            json = JSON.parse(xhr.responseText);
	        } catch (e) {
	            failure('이미지 업로드 결과의 JSON 파싱이 실패하였습니다.\n\nHTTP Error: ' + xhr.status, {remove: true});
	            return;
	        }
	        if (typeof json === 'object' && json.error) {
	            failure(json.error, {remove: true});
	        }

	        if (!json || typeof json.location != 'string') {
	            failure('이미지 업로드 결과의 JSON 파싱이 실패하였습니다.\n\nInvalid JSON: ' + xhr.responseText, {remove: true});
	            return;
	        }

	        success(json.location);

	        // 이미지 업로드 성공 처리
	        var form = document.forms.list;

            if (form.sg_files.value === '') {
                form.sg_files.value = json.sg_name + '|' + json.sg + '|' + json.sg_size;
            } else {
                form.sg_files.value = form.sg_files.value + '||' + json.sg_name + '|' + json.sg + '|' + json.sg_size;
            }
	    };

	    xhr.onerror = function () {
	        // failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
	        failure('이미지 업로드가 실패하였습니다.\n\nCode: ' + xhr.status);
	    };

	    formData = new FormData();
	    formData.append('file', blobInfo.blob(), blobInfo.filename());

	    xhr.send(formData);
	}

    function tinymce5_get_height() {
        if (localStorage) {
            var height = localStorage.getItem('tinymce_sg_content_height');
            if (height !== null) {
                return height + 'px';
            }
        }

        return '350px';
    }

	window.onload = function () {
	    // 웹에디터
	    tinymce.init({
	        // General options
	        language: "ko_KR",
	        mode: "exact",
	        theme: "silver",
	        elements: "sg_content",
	        //images_upload_url: '<?= $G_SYS['HTTP_URL_ROOT'] ?>/mail_write_upload_cid.php',
	        images_upload_handler: tinymce5_images_upload_handler,
	        // [2011-08-08] disable convert url
	        //document_base_url : "<?= $G_SYS['HTTP_URL_ROOT'] ?>",
	        relative_urls: false,
	        remove_script_host: false,
	        // oninit: "mf_body_letter_active",
	        visual: false,		// 가이드라인 비표시
	        branding: false,

	        // plugins: 'print preview paste importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap quickbars emoticons',
	        plugins: 'paste importcss searchreplace autolink code visualblocks visualchars fullscreen image link media table charmap hr nonbreaking insertdatetime advlist lists imagetools noneditable help charmap quickbars',
	        // plugins: "image,autolink,table,preview,media,contextmenu,fullscreen,visualchars,paste",

	        // menubar: 'file edit view insert format tools table help',
	        menubar: '',

	        // toolbar: 'undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist | forecolor backcolor removeformat | pagebreak | charmap emoticons | fullscreen  preview save print | insertfile image media template link anchor codesample | ltr rtl',
		    <? if ($G_SYS[UPLOAD_MAIL_SIGN_FILE_MAX_SIZE] == 0) { ?>
		    toolbar: 'fontselect fontsizeselect | bold italic underline strikethrough forecolor backcolor | alignleft aligncenter alignright alignjustify | outdent indent | lineheight | numlist bullist | removeformat | image media link charmap hr table | undo redo | code fullscreen',
		    <? } else { ?>
		    toolbar: 'quickimage | fontselect fontsizeselect | bold italic underline strikethrough forecolor backcolor | alignleft aligncenter alignright alignjustify | outdent indent | lineheight | numlist bullist | removeformat | image media link charmap hr table | undo redo | code fullscreen',
	        <? }    // if() ?>
		    toolbar_sticky: true,

	        quickbars_selection_toolbar: 'bold italic forecolor backcolor | quicklink blockquote | outdent indent',

	        // 빈 라인마다 이미지, 테이블 삽입 버튼 보여주기 생략
	        quickbars_insert_toolbar: false,

	        font_formats: '맑은 고딕=Malgun Gothic,맑은 고딕,sans-serif; 굴림=Gulim,굴림,sans-serif; 돋움=Dotum,돋움,sans-serif; 바탕=Batang,바탕,serif; 궁서=Gungsuh,궁서,serif; 나눔고딕=NanumGothic,나눔고딕,sans-serif; Andale Mono=andale mono,times; Arial=arial,helvetica,sans-serif; Arial Black=arial black,avant garde; Book Antiqua=book antiqua,palatino; Comic Sans MS=comic sans ms,sans-serif; Courier New=courier new,courier; Georgia=georgia,palatino; Helvetica=helvetica; Impact=impact,chicago; Symbol=symbol; Tahoma=tahoma,arial,helvetica,sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms,geneva; Verdana=verdana,geneva; Webdings=webdings; Wingdings=wingdings,zapf dingbats',
	        fontsize_formats: '8px 10px 12px 14px 16px 18px 24px 36px 48px',
	        lineheight_formats: '1 1.1 1.2 1.3 1.4 1.5 1.6 1.8 2',

	        color_map: [
	            '#BFEDD2', 'Light Green',
	            '#FBEEB8', 'Light Yellow',
	            '#F8CAC6', 'Light Red',
	            '#ECCAFA', 'Light Purple',
	            '#C2E0F4', 'Light Blue',

	            '#2DC26B', 'Green',
	            '#F1C40F', 'Yellow',
	            '#E03E2D', 'Red',
	            '#B96AD9', 'Purple',
	            '#3598DB', 'Blue',

	            '#169179', 'Dark Turquoise',
	            '#E67E23', 'Orange',
	            '#BA372A', 'Dark Red',
	            '#843FA1', 'Dark Purple',
	            '#236FA1', 'Dark Blue',

	            '#ECF0F1', 'Light Gray',
	            '#CED4D9', 'Medium Gray',
	            '#95A5A6', 'Gray',
	            '#7E8C8D', 'Dark Gray',
	            '#34495E', 'Navy Blue',

	            '#000000', 'Black',
	            '#ffffff', 'White',
	            '#ffff00', 'Yellow',
	            '#ff0000', 'Red',
	            '#0000ff', 'Blue',
	        ],

	        // [2010-02-09] Performance tuning
	        // [2012-11-16] 3.5.7 - 크롬/사파리 빈라인 무시 현상 해결
	        //verify_html: false,
	        cleanup: false,

	        // [2013-07-09] style
	        paste_retain_style_properties: 'all',

	        // 테이블 스타일 등 유지
	        paste_remove_styles_if_webkit: false,

	        // 이미지 클립보드에서 붙여넣기시 업로드 처리
	        paste_data_images: true,

	        // 에디터 컨텐츠 영역 스타일
	        content_css: '<?= nskindirroot('main') ?>/tinymce5-content.css',

	        cache_suffix: '?v=<?= NM_VER ?>',

            // 에디터 높이 변경 저장
                height: tinymce5_get_height(),
                setup: function (editor) {
                    editor.on('ResizeEditor', function (e) {
                        if (localStorage) {
                            localStorage.setItem('tinymce_sg_content_height', editor.getContainer().offsetHeight);
                        }
                    });
                },

	        // 클립보드 붙여넣기시 inline 스타일로 변환 (엑셀 붙여넣기시 테이블 스타일 유지 등)
	        paste_preprocess: function (plugin, args) {
	            if (typeof juice === 'function') {
	                try {
	                    args.content = juice(args.content);
	                } catch (e) {
	                    console.log(e);
	                }
	            }
	        },
	    });
    }
	</script>

<? }	// if() ?>
