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

<script language="JavaScript" src="<?= $nmpath ?>/addon/js/prototype.js?v=<?= NM_VER ?>"></script>
<script language="JavaScript" src="<?= $nmpath ?>/addon/actb/actb.js?v=<?= NM_VER ?>"></script>
<script language="JavaScript" src="<?= $nmpath ?>/addon/actb/common.js?v=<?= NM_VER ?>"></script>
<script language="JavaScript">
<!--

	var get_qs = "<?= get_qs() ?>";
	var nm_php_self = "mail_write_ok.php";
	var wform = document.forms.write;
    var addattachs = '';

	// [2007-06-14] 주소 자동완성
	var actb_to = actb(wform.mf_to,new Array());
	if (wform.mf_cc)
		var actb_cc = actb(wform.mf_cc,new Array());
	if (wform.mf_bcc)
		var actb_bcc = actb(wform.mf_bcc,new Array());

	var nm_webeditor = '<?= $G_SYS['WEBEDITOR'] ?>';

	<? if ($G_SYS['WEBEDITOR'] == 'FCK') { ?>
		var sBasePath = '<?= $nmpath ?>/addon/fckeditor/';
		var oFCKeditor = new FCKeditor( 'mf_body_html', '100%', '350', 'Nmail' ) ;
		oFCKeditor.BasePath	= sBasePath ;
		oFCKeditor.Config['SkinPath'] = 'skins/office2003/';

		oFCKeditor.ReplaceTextarea() ;
	<? }	// if() ?>

	<? if ($view['mf_cc']) { ?>
		addCc();
	<? }	// if() ?>

	<? if ($view['mf_bcc']) { ?>
		addBcc();
	<? }	// if() ?>

	// 받는 사람 주소 자동확장.
	rowsUp(wform.mf_to, 40, 10);

	// 입력안내
	//input_guide(true);

	// 임시보관함에 자동 저장.
	function mail_write_draft_save_auto()
	{
		mail_write_draft_save(1);
		window.setTimeout('mail_write_draft_save_auto()', <?= ($G_SYS['DRAFT_SAVE_AUTO_TIME']*1000) ?>);
	}
	var mwdsa = window.setTimeout('mail_write_draft_save_auto()', <?= ($G_SYS['DRAFT_SAVE_AUTO_TIME']*1000) ?>);

	// 메일전달시 첨부파일
	function forward_attach_add()
	{
        <? if (is_multi_upload()) { ?>
        /*addattachs = "<?//= $view['forward_attach_add_js'] ?>";
        document.forms.write.mf_attach_names.value += "<?//= $view['forward_attach_add_js'] ?>";*/
        <?= $view['forward_attach_add_js'] ?>
        <? } else { ?>
        <?= $view['forward_attach_add_js'] ?>
        <? } ?>
	}	// function()


	<? if ($G_SYS['NM_LETTER_USE'] && (strpos($_SERVER['PHP_SELF'], 'mailer/send.php') === false || $G['__MAILER_MAIL_WRITE_JS_UPDATE'])) {		// 편지지 사용시 ?>
		// 편지지
		var _mf_body_html_tbl_width = '';		// 편지지 적용전 에디터 너비
		var _mf_body_html_tbl_height = '';		// 편지지 적용전 에디터 높이
		var _mf_body_html_ifr_height = '';		// 편집창
		var mf_body_letter_view = false;
		function mf_body_letter_click()
		{
			if (mf_body_letter_view == false)
			{
				_mf_body_html_tbl_width = document.getElementById('mf_body_html_tbl').style.width;
				_mf_body_html_tbl_height = document.getElementById('mf_body_html_tbl').style.height;
				_mf_body_html_ifr_height = document.getElementById('mf_body_html_ifr').style.height;
				document.getElementById('mf_body_html_tbl').style.width = '766px';
				document.getElementById('mf_body_html_tbl').style.height = '420px';
				document.getElementById('mf_body_html_ifr').style.height = '350px';
				document.getElementById('mf_body_right').style.width = '160px';
				document.getElementById('mf_body_right').style.height = '100%';
				document.getElementById('mf_body_right').style.display= '';
				document.getElementById('mf_body_right').innerHTML = '<iframe width=160 height=100% frameborder=0 src="<?= $nmpath ?>/mail_write_letter.php" style="width:160px; height:100%; margin:0px"></iframe>';
				mf_body_letter_view = true;
			} else
			{
				if (document.getElementById('mf_body_letter').value != '')
				{
					alert("편지지가 선택된 상태에서는 편지지 목록을 숨길 수 없습니다.\n\n편지지를 사용하지 않으려면 [편지지 빼기]를 눌러주셔야 합니다.");
					return;
				}
				document.getElementById('mf_body_html_tbl').style.width = _mf_body_html_tbl_width;
				document.getElementById('mf_body_html_tbl').style.height = _mf_body_html_tbl_height;
				document.getElementById('mf_body_html_ifr').style.height = _mf_body_html_ifr_height;
				document.getElementById('mf_body_right').style.display= 'none';
				mf_body_letter_view = false;
			}
		}

		function mf_body_letter_active()
		{
			if(typeof window.addEventListener != 'undefined')
			{
				document.getElementById('mf_body_html_nm_letter_box_text').addEventListener("click", function() { mf_body_letter_click(); }, false);
				document.getElementById('mf_body_html_nm_letter_box_open').addEventListener("click", function() { mf_body_letter_click(); }, false);
			} else if(typeof window.attachEvent != 'undefined')
			{
				document.getElementById('mf_body_html_nm_letter_box_text').attachEvent( "onclick", function () { mf_body_letter_click(); } );
				document.getElementById('mf_body_html_nm_letter_box_open').attachEvent( "onclick", function () { mf_body_letter_click(); } );
			}
		}

		tinymce.create('tinymce.plugins.nmLetterPlugin', {
			createControl: function(n, cm) {
				switch (n) {
					case 'nm_letter_box':
						var mlb = cm.createListBox('nm_letter_box', {
							 title : '편지지'
						});
						return mlb;
				}
				return null;
			}
		});
		tinymce.PluginManager.add('nm_letter', tinymce.plugins.nmLetterPlugin);
	<? } else { ?>
		function mf_body_letter_active()
		{
			//
		}
	<? }	// if() ?>


    <? if ($G_SYS['WEBEDITOR'] == 'TINYMCE5' && (strpos($_SERVER['PHP_SELF'], 'mailer/send.php') === false || $G['__MAILER_MAIL_WRITE_JS_UPDATE'])) { ?>
    // 웹에디터
    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'] ?>/mail_write_upload_cid_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);
                return;
            }

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

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

            success(json.location);

            // 이미지 업로드 성공 처리
            var wuform = document.forms.write_upload;
            wform.mf_cid.value = wform.mf_cid.value + '|' + json.cid;
            wform.mf_cid_name.value = wform.mf_cid_name.value + '|' + json.cid_name;
            wform.mf_cid_size.value = parseInt(wform.mf_cid_size.value, 10) + parseInt(json.cid_size, 10);

            if (wuform.mf_attachs_size && typeof(FileAPI)!="object")
            {// 일반첨부
                wuform.mf_attachs_size.value = parseInt(wuform.mf_attachs_size.value, 10) + parseInt(json.cid_size, 10);
                wuform.mf_attachs_size_h.value = SizeCalc(wuform.mf_attachs_size.value);
            } else if (typeof(FileAPI)=="object")
            {// 멀티업로드
                wuform.mf_attachs_size.value = parseInt(wuform.mf_attachs_size.value, 10) + parseInt(json.cid_size, 10);
                //wuform.mf_attachs_size.click();
                document.getElementById("mf_attachs_size").click();
            }	// if()
        };

        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_mf_body_html_height');
            if (height !== null) {
                return height + 'px';
            }
        }

        return '350px';
    }
    <? } ?>

	window.onload = function()
	{
		<? /* [2010-05-27] tinyMCE.init : mail_write.html -> mail_write_js.php */ ?>
		<? if ($G_SYS['WEBEDITOR'] == 'TINYMCE' && (strpos($_SERVER['PHP_SELF'], 'mailer/send.php') === false || $G['__MAILER_MAIL_WRITE_JS_UPDATE'])) { ?>
			// 웹에디터
			tinyMCE.init({
				// General options
				language : "<?= $G_SYS['nm_lang'] ?>",
				mode : "exact",
				theme : "advanced",
				elements : "mf_body_html",
				// [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,		// 가이드라인 비표시

				plugins : "safari,table,advimage,advlink,preview,media,contextmenu,fullscreen,visualchars,inlinepopups,paste<? if ($G_SYS['NM_LETTER_USE']) {		// 편지지 사용시 ?>,-nm_letter<? }	// if() ?>",

				// Theme options
				<? if ($G_SYS['nm_lang'] == 'ko') { ?>
					theme_advanced_fonts : '굴림=굴림,돋움=돋움,바탕=바탕,궁서=궁서,Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace;Georgia=georgia,times new roman,times,serif;Tahoma=tahoma,arial,helvetica,sans-serif;Times New Roman=times new roman,times,serif;Verdana=verdana,arial,helvetica,sans-serif;Impact=impact;WingDings=wingdings',
				<? } else { ?>

				<? }	// if() ?>

				theme_advanced_buttons1 : "fontselect,fontsizeselect,|,bold,italic,underline,strikethrough,forecolor,backcolor,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,|,removeformat",
				theme_advanced_buttons2 : "image,media,charmap,|,hr,|,tablecontrols,|,visualaid,|,code,preview,fullscreen<? if ($G_SYS['NM_LETTER_USE']) {		// 편지지 사용시 ?>,|,nm_letter_box<? }	// if() ?>",
				theme_advanced_buttons3 : "",
				theme_advanced_buttons4 : "",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : true,
				theme_advanced_resize_horizontal : false,

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

				// [2010-05-27] path hidden
				theme_advanced_path : false,

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

				// [2013-08-14] excel border hidden fix
				paste_auto_cleanup_on_paste : false,

				content_css : '<?= $nmpath ?>/addon/tinymce/themes/advanced/skins/default/content.css?v=<?= NM_VER ?>'
			});
		<? }	// if() ?>

		<? if ($G_SYS['WEBEDITOR'] == 'TINYMCE5' && (strpos($_SERVER['PHP_SELF'], 'mailer/send.php') === false || $G['__MAILER_MAIL_WRITE_JS_UPDATE'])) { ?>
        tinymce.init({
            // General options
            language: "ko_KR",
            mode: "exact",
            theme: "silver",
            elements: "mf_body_html",
            //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['__MAILER_MAIL_WRITE_JS_UPDATE']) { ?>
                toolbar: 'customCode | 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 | 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',
            <? } ?>
            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_mf_body_html_height', editor.getContainer().offsetHeight);
                    }
                });

	            <? if ($G['__MAILER_MAIL_WRITE_JS_UPDATE']) { ?>
                editor.ui.registry.addButton('customCode', {
                    text: 'HTML 소스 편집',
                    onAction: function (_) {
                        editor.execCommand('mceCodeEditor');
                    }
                });
	            <? }	// if() ?>
            },

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

		<? if (get_activex_use()) { ?>
			uploadConfigSet();
		<? }	// if() ?>

		<? if ($_GET['me']) {		// [2013-07-09] 좌측메뉴에 내게쓰기 추가?>
		mail_write_me('<?= $AUTH['auth_m_id'].'@'.$G_SYS['MAIL_DOMAIN'] ?>');
		<? }	// if() ?>

		// [2007-06-05] 받는사람/제목에 커서 이동
		if (wform.mf_to.value == '')
		{
			wform.mf_to.focus();
		} else
		{
			wform.mf_subject.focus();
		}	// if()

		// 메일전달시 첨부파일
		forward_attach_add();

		<? if (get_activex_use()) { ?>
		// 용량갱신
		attachSizeUpdate();
		<? }	// if() ?>
	}

//-->
</script>
