﻿var imglist = '';
var lastpos = null;
var editor = function(instanceName,width,height)
{
	this.id	= instanceName;
	this.mode = "text";
	this.width			= width			|| '100%';
	this.height			= height		|| '400';	
	this.isIE = (window.showModalDialog) ? true:false;
	this.isIE6 = (navigator.appVersion.indexOf("MSIE 6.0")>0?true:false);
	//this.border = "solid 1px #cccccc";
	this.doc = null;
	this.selectedtext = null;
	this.range	  = null;
	this.maxImgSize = null;

	this.objlayer = document.getElementById('objWindow');
	editorutil.init(this);
}

editor.prototype.init = function(id, maxImgSize){
    if(typeof(document.execCommand)=="undefined") return;    
    try{ 
        this.textarea = document.getElementById(id);
        this.outer = document.createElement("div");
   	    this.texteditor	= document.createElement("textarea");
        this.htmleditor = document.createElement("iframe");
        this.mode = "html";
        
        this.outer.style.border	= "";
	    this.outer.style.width	= this.width;
    	this.outer.style.height = this.height;
    	
        this.textarea.style.display = "none";
	    this.texteditor.style.width = this.width - 20 + "px";
	    //this.texteditor.style.border= "solid 1px blue";
	    this.texteditor.style.display = "none";
	    this.texteditor.style.font = "9pt 굴림";
	    this.texteditor.style.lineHeight = 1.1;
	    this.texteditor.style.margin = "0px";
	    this.texteditor.style.padding = "10px";
    	
	    this.htmleditor.id = "htmlEditor";
	    this.htmleditor.setAttribute("border", "0");
	    this.htmleditor.setAttribute("frameBorder", "0");
	    this.htmleditor.setAttribute("marginWidth", "0");
	    this.htmleditor.setAttribute("marginHeight", "0");
	    this.htmleditor.setAttribute("leftMargin", "0");
	    this.htmleditor.setAttribute("topMargin", "0");
	    this.htmleditor.setAttribute("allowtransparency", "true");
	    this.htmleditor.style.margin = "0px";
	    this.htmleditor.style.padding = "10px";
	    this.htmleditor.style.width = this.width - (isIE6? 22:20) + "px";
	    //this.htmleditor.style.border= "solid 1px #cccccc";
	    
	    this.texteditor.style.height= this.height - (isIE7? 42:20) + "px";
	    this.htmleditor.style.height= this.height - (isIE7? 42:20) + "px";
    	
	    this.textarea.parentNode.insertBefore(this.outer, this.textarea);	    
	    this.outer.appendChild(this.htmleditor);
	    this.outer.appendChild(this.texteditor);
    	
	    this.doc = this.htmleditor.contentWindow.document;
    	this.doc.designMode = "on";
	    var css  = "body{background-color:#ffffff;font-size:9pt;font-family:굴림;line-height:1.2;margin:0px;padding:0px;}";
	    css += "P,div{margin:3px 0px;padding:0px;}";
	    css += "object{background-color: #eeeeee;}";
	    css += "embed{background-color: #eeeeee;}";
	    
	    this.htmleditor.css = css;
	    this.doc.open();
	    this.doc.write('<html><head><style type="text/css">'+css+'</style></head><body>'+this.textarea.value+'</body></html>');
	    this.doc.close();
	    editorutil.addEvent(this.doc, "mousedown", editorutil.hidelayer);
//	    this.htmleditor.contentWindow.onblur = editor.prototype.saveCurrentPos2;
	    //if(this.textarea.style.display != "none")
    	//    this.doc.body.focus();

		//이미지 사이즈 조절로 추가
		this.maxImgSize = maxImgSize;
    }catch(e){
        alert(e.message);
    }
}

var editorutil = {
    editor : null,
    init : function(obj){
        this.editor = obj;
    },
    hidelayer : function(){
        try{
            richeditor.objlayer.style.display = 'none';
            richeditor.doc.body.focus(); 
        }catch(e){
            alert(e.message);
        } 
    },
    addEvent : function(object, type, listener)
	{
		if(object.addEventListener) { object.addEventListener(type, listener, false); } 
		else if(object.attachEvent) { object.attachEvent("on"+type, listener); } 
	},
	showcolorpicker : function(func){
        try{ 
            var col= new Array();
		    col[0] = new Array("#ffffff","#e5e4e4","#d9d8d8","#c0bdbd","#a7a4a4","#8e8a8b","#827e7f","#767173","#5c585a","#000000","#fefcdf","#fef4c4","#feed9b","#fee573","#ffed43","#f6cc0b","#e0b800","#c9a601","#ad8e00","#8c7301");		    
		    col[1] = new Array("#ffded3","#ffc4b0","#ff9d7d","#ff7a4e","#ff6600","#e95d00","#d15502","#ba4b01","#a44201","#8d3901","#ffd2d0","#ffbab7","#fe9a95","#ff7a73","#ff483f","#fe2419","#f10b00","#d40a00","#940000","#6d201b");
		    col[2] = new Array("#ffdaed","#ffb7dc","#ffa1d1","#ff84c3","#ff57ac","#fd1289","#ec0078","#d6006d","#bb005f","#9b014f","#fcd6fe","#fbbcff","#f9a1fe","#f784fe","#f564fe","#f546ff","#f328ff","#d801e5","#c001cb","#8f0197");
		    col[3] = new Array("#e2f0fe","#c7e2fe","#add5fe","#92c7fe","#6eb5ff","#48a2ff","#2690fe","#0162f4","#013add","#0021b0","#d3fdff","#acfafd","#7cfaff","#4af7fe","#1de6fe","#01deff","#00cdec","#01b6de","#00a0c2","#0084a0");
		    col[4] = new Array("#edffcf","#dffeaa","#d1fd88","#befa5a","#a8f32a","#8fd80a","#79c101","#3fa701","#307f00","#156200","#d4c89f","#daad88","#c49578","#c2877e","#ac8295","#c0a5c4","#969ac2","#92b7d7","#80adaf","#9ca53b");		    
		    var s="<div style='width:285px'>";
		    for(var i=0; i<5; i++)
		    {
			    for(var j=0; j<20; j++)
			    {
				    color = col[i][j];
				    s += "<a href='javascript:;' onclick=\"" + func + ",'"+color+"');\" style='background-color:"+color+";' class='color'>&nbsp;</a>";
			    }
			    s += "<br />";
		    }
		    s += "</div>";		   
		    this.editor.objlayer.innerHTML = s;
        }catch(e){
            alert(e.message);
        } 
    },
    setColor : function(what, color){   
        if(this.mode == "text") {
            alert("소스보기 상태에서는 실행되지 않습니다.");
            return;
        }       
        try{
            if(what == 'doc'){
                richeditor.doc.body.style.backgroundColor = color;
            }else{                
                richeditor.format(what, color);
            }
        }catch(e){
            alert("setColor=" + e.message);
        }
        this.editor.objlayer.innerHTML = '';
        this.editor.objlayer.style.display = 'none';
       // this.editor.htmleditor.body.focus(); 
        return; 
    }
}

editor.prototype.format = function(what, opt, evt){
    if(this.mode == "text") {
        alert("소스보기 상태에서는 실행되지 않습니다.");
        return;
    }
    if(what == 'color'){
        try{ 
            if(opt == 'forecolor'){
                editorutil.showcolorpicker("editorutil.setColor('ForeColor'");
                //this.objlayer.style.left = (this.isIE6) ? -200 : 120 + "px";
                this.objlayer.style.left = "120px";
            }else if(opt == 'backcolor'){            
                editorutil.showcolorpicker("editorutil.setColor('" + (this.isIE?"backcolor":"hilitecolor") + "'");
                //this.objlayer.style.left = (this.isIE6) ? -180 : 170 + "px"; 
                this.objlayer.style.left = "170px"; 
            }else{
                editorutil.showcolorpicker("editorutil.setColor('doc'");
                //this.objlayer.style.left = (this.isIE6) ? -160 : 200 + "px";
                this.objlayer.style.left = "200px";
            }
            this.objlayer.style.top = 53 + "px";
            this.objlayer.style.height = '120px';
            this.objlayer.style.display = 'block';
        }catch(e){
            alert(e.message);
        }
    }else if(what == 'link'){
        try{
            if(opt == ''){
                
				if(this.isIE){                    
                    this.selectedtext	 = this.doc.selection.createRange();
                }else{
                    this.selectedtext	 = this.htmleditor.contentWindow.getSelection().getRangeAt(0);
                }
             this.setSelection();			 
                var strhtml =  "<div class='link'>";
                strhtml +=  "<span>링크연결</span><div class='close'><img src='/images/common/bt_close.gif' onclick='editorutil.hidelayer()'/></div>";
                strhtml += "<input type='text' id='hyperlink' class='hyperlink' value='http://'/>"
                strhtml += " <img src='/images/common/bt_complete.gif' onclick=\"richeditor.format('link', document.getElementById('hyperlink').value);\" align='absmiddle'/></div>";
                this.objlayer.innerHTML = strhtml;
                this.objlayer.style.top = 53 + "px"; 
                //this.objlayer.style.left = (this.isIE6) ? -40 : 200 + "px"; 
                this.objlayer.style.left = "200px"; 
                this.objlayer.style.display = 'block';
                document.getElementById('hyperlink').focus(); 
            }else{
                if(this.isIE){
                    if (this.sel_html == ""){ // 선택된 Text가 없을 경우...
				        this.doc.body.innerHTML += "<a href ="+  opt +" target='_blank'>" +opt +"</a>";
		            }else{
			            this.selectedtext.pasteHTML("<a href ="+  opt +" target='_blank'>" + this.sel_html +"</a>");
		            }
		        }else{
		            if(this.sel_html != ''){
		                try{
		                    this.doc.execCommand("inserthtml", false, "<a href ="+  opt +" target='_blank'>" + this.sel_html +"</a>");
					//		this.doc.execCommand("inserthtml", false, "["+  opt +" " + this.sel_html +"]");
		                }catch(e){
		                    this.doc.body.innerHTML += "<a href ="+  opt +" target='_blank'>" + this.sel_html +"</a>";
					//		this.doc.body.innerHTML += "["+  opt +" " + this.sel_html +"]";
		                }
		            }else{
		                this.doc.body.innerHTML += "<a href ="+  opt +" target='_blank'>" +opt +"</a>";
		            }
		        }
		         
		        this.objlayer.innerHTML = '';
                this.objlayer.style.display = 'none';
		        this.doc.body.focus(); 
		         
            }
        }catch(e){
            alert("link = " + e.message);
        }
    }else if(what == 'mp3'){
        try{
            if(opt == ''){
                
				var strhtml =  "<div class='link'>";
                strhtml +=  "<span>MP3연결</span><div class='close'><img src='/images/common/bt_close.gif' onclick='editorutil.hidelayer()'/></div>";
                strhtml += "<input type='text' id='hyperlink' class='hyperlink' value='http://'/>"
                strhtml += " <img src='/images/common/bt_complete.gif' onclick=\"richeditor.format('mp3', document.getElementById('hyperlink').value);\" align='absmiddle'/></div>";
                this.objlayer.innerHTML = strhtml;
                this.objlayer.style.height = "60px";
                this.objlayer.style.left = (this.isIE6) ? 80 : 200 + "px"; 
                this.objlayer.style.top = 80 + "px"; 
                this.objlayer.style.display = 'block';
                document.getElementById('hyperlink').focus(); 
            }else{
                
				this.doc.body.innerHTML += "<EMBED style='FILTER: gray()' src='"+  opt +"' width=300 height=32 type=audio/x-ms-wma autostart='false' AllowScriptAccess='never' invokeURLS='false' showControls='true' playCount='1' volume='0' LOOP='FALSE' enablecontextmenu='0'>";
		         this.objlayer.innerHTML = '';
                this.objlayer.style.display = 'none';
		        this.doc.body.focus(); 
            }
        }catch(e){
            alert("mp3 = " + e.message);
        }
    }else if(what == 'imgupload'){
        
        var strhtml = "<div id='imguploader'>";
        strhtml += "<span>이미지 업로드</span>";
        strhtml += "<div class='close'><img src='/images/common/bt_close.gif' onclick='editorutil.hidelayer()'/></div>";
        strhtml += "<div id='iframebox'><iframe src='/make/uploader.aspx' style='width:100%;height:200px;' frameborder='no'></iframe></div></div>";
        this.objlayer.innerHTML = strhtml;        
        this.objlayer.style.height = "220px";
        this.objlayer.style.top = 80 + "px";
        this.objlayer.style.left = 80 + "px";
        this.objlayer.style.display = 'block'; 
        
    }else if(what == 'multimedia'){        
        
        var strhtml = "<div id='multimedia'>";
        strhtml += "<iframe src='/Make/UploadMultimedia.aspx' style='width:540px; height:220px;' frameborder='no'></iframe>";
        strhtml += "</div>";
        this.objlayer.innerHTML = strhtml;        
        
        this.objlayer.style.top = 80 + "px";
        this.objlayer.style.left = 80 + "px";
        this.objlayer.style.display = 'block'; 
        
    }else if(what == 'insertorderedlist' || what =='insertunorderedlist'){  
        if(this.isIE){                    
            this.selectedtext	 = this.doc.selection.createRange();
        }else{
            this.selectedtext	 = this.htmleditor.contentWindow.getSelection().getRangeAt(0);
        }
        this.setSelection();                
        if(this.sel_html.length > 0){
             try{
                
                if (opt == null) {
                    this.doc.execCommand(what, false, '');
                }else{                
                    this.doc.execCommand(what, false, opt);
                    
                }
            }catch(e){
                alert("format" + e.message);
            }
            this.doc.body.focus(); 
        }

        
    }else{
        try{
            
            if (opt == null) {
                this.doc.execCommand(what, false, '');
            }else{                
                this.doc.execCommand(what, false, opt);
                
            }
        }catch(e){
            alert("format" + e.message);
        }
        this.doc.body.focus(); 
    }    
}

//이미지 사이즈 체크
var fileurl = "";

function img_Load()
{
	document.getElementById('imgWidth').value = this.width;
	richeditor.addimg(fileurl, "");
}

editor.prototype.preLoadImg = function(strfile, arraytype){
	var imgInfo = new Image();
	imgInfo.onload = img_Load;
	imgInfo.src ="/FileServer/Temp/bbs/" + strfile;
	fileurl = strfile;
}

editor.prototype.addimg = function(strfile, arraytype){
	var imgWidth = document.getElementById('imgWidth').value;

	if (imgWidth > this.maxImgSize)
	{
		imgWidth = this.maxImgSize;
	}
	if(arraytype != "") 
        var strimg = "<div align ="+arraytype+">";
    else
        var strimg = "<div>";
        
    strimg += "<img src=\"/FileServer/Temp/bbs/" + strfile + "\" border=\"0\" width=\""+imgWidth+"\">";
    strimg += "</div>";
    
    var strimg2 = "/FileServer/Temp/bbs/" + strfile;

    if (document.selection && document.selection.createRange) { 
        this.doc.body.focus();
        var rng = this.doc.selection.createRange();
        rng.pasteHTML(strimg);
    }
    else if (window.getSelection) { 
        this.doc.execCommand('insertImage', false, strimg2);
	    imglist += strfile + "＆";
        return;
    }
}

editor.prototype.addImgList = function(newFileName, orginFileName) {    
    if(orginFileName.length > 11){
        orginFileName = orginFileName.substr(0, 11) + "...";
    }
    var strimg = "<div id='" + newFileName.replace(".jpg","") + "' onmouseover='Editor.ImageOver(this)' onmouseout='Editor.ImageOut(this)'><img class='Image' src='/FileServer/Temp/bbs/Thumbnail_" + newFileName + "' onclick=\"javascript:richeditor.preLoadImg(\'"+newFileName+ "\', '');\"/><img class='Delete' src='/images/editor/ico_imagex.gif' id='del" + newFileName.replace(".jpg","") + "' onclick=\"Editor.DeleteImage('" + newFileName.replace(".jpg","") + "')\"/></div>";
    document.getElementById('ImageList').innerHTML += strimg;
	imglist += newFileName + "＆";
	Editor.Image.push(newFileName.replace(".jpg",""));
	if(Editor.Image.length > 10) 
          $(newFileName.replace(".jpg","")).style.display = 'none';
    return;
}

editor.prototype.swapmode = function(t){
    try{ 
        var strcontent = this.getvalue();
        if(this.mode == 'html'){
            t.src = "/images/editor/ico_editor.gif";
            this.mode = 'text';
            this.texteditor.style.display = 'inline';
            this.htmleditor.style.display = 'none';
            this.texteditor.value = strcontent;
        }else{
            t.src = "/images/editor/ico_html.gif";
            this.mode = 'html';
            this.texteditor.style.display = 'none';
            this.htmleditor.style.display = 'inline';
            this.doc.body.innerHTML = strcontent;
        }
    }catch(e){alert(e.message);}
    return;
}

editor.prototype.getvalue = function(){
    var html = "";	
    try{ 
	    if(this.mode=="text"){
	        html = this.texteditor.value;
	    }else{
	        for(i=0;i<this.doc.links.length;i++)
	            if(!this.doc.links[i].target) this.doc.links[i].target = '_blank';
		    html = this.doc.body.innerHTML;
	    }
    }catch(e){alert(e.message);} 
	return html;
}

editor.prototype.setSelection = function() 
{
	var _iframe=this._iframe;
	var sel=null,range=null,html="";

	if(this.doc.selection)
	{
		sel = this.doc.selection;
		range = sel.createRange();
		html = range.htmlText;
	}
	else if(this.htmleditor.contentWindow.getSelection)
	{
		sel=this.htmleditor.contentWindow.getSelection();
		if (typeof(sel)!="undefined") range=sel.getRangeAt(0);
		else range=this.doc.createRange();
		if(sel.rangeCount > 0 && window.XMLSerializer)
		{	
			html=new XMLSerializer().serializeToString(range.cloneContents());
		}
	}
	this.sel = sel;
	this.range = range;
	this.sel_html = html;
}
editor.prototype.saveCurrentPos = function(objTextArea) {
    if (objTextArea.createTextRange) 
        objTextArea.currentPos = document.selection.createRange().duplicate();
}
editor.prototype.saveCurrentPos2 = function() {
    lastpos = this.doc.body.currentPos;
    alert(lastpos);
}
editor.prototype.insertText = function(objTextArea, text) {
    if (objTextArea.createTextRange && objTextArea.currentPos) {
        var currentPos = objTextArea.currentPos;
        currentPos.pasteHTML(currentPos.text.charAt(currentPos.text.length - 1) == ' ' ? text + ' ' : text);
   }
    else
        objTextArea.value += text;       
}

var Editor = {
    IsEditor : false,
    Image : new Array(),
    ImagePage : 1,
    Close : function(obj) {
        obj.style.display = 'none';
    },
    ShowUploader : function(target) {
        if($('Editor' + target).style.display != 'inline') {
            $('Editor' + target).setStyle({display:'inline'});
            $('btn' + target).setStyle({backgroundColor:'#fee9a8'});
        }
        else {
            $('Editor' + target).setStyle({display:'none'});
            $('btn' + target).setStyle({backgroundColor:'#ffffff'});
        }
    },
    ImageOver : function(obj) {
        obj.style.borderColor = '#f78f0a';
        $('del' + obj.id).style.display = 'inline';
    },
    ImageOut : function(obj) {
        obj.style.borderColor = '#d7d1c5';
        $('del' + obj.id).style.display = 'none';
    },
    DeleteImage : function(id) {
        for(i=0;i<this.Image.length;i++) {
            if(this.Image[i] == id) {
                this.Image.splice(i,1);
                $(id).update('');
                $(id).style.display = 'none';
            }
        }
    },
    ClearImages : function() {
        $('ImageList').update('');
        this.Image = new Array();
    },
    GetImageNext : function() {
        var totalpage = parseInt((this.Image.length - 1) / 10) + 1;
        if(this.ImagePage >= totalpage) { alert('마지막 페이지입니다.'); return; }
  
        this.ImagePage = this.ImagePage + 1;
        
        var first = (this.ImagePage - 1) * 10;
        var last = first + 9;    
        if(last >= this.Image.length) last = this.Image.length - 1;

        for(i=0;i<this.Image.length;i++) {
            if(i >= first && i <= last)
                $(this.Image[i]).style.display = 'inline';
            else
                $(this.Image[i]).style.display = 'none';
        }
        
    },
    GetImagePrev : function() {
        var totalpage = parseInt((this.Image.length - 1) / 10) + 1;
        if(this.ImagePage == 1) { alert('첫 페이지입니다.'); return; }

        this.ImagePage = this.ImagePage - 1;
        
        var first = (this.ImagePage - 1) * 10;
        var last = first + 9;
        if(last >= this.Image.length) last = this.Image.length - 1;
        
        for(i=0;i<this.Image.length;i++) {
            if(i >= first && i <= last)
                $(this.Image[i]).style.display = 'inline';
            else
                $(this.Image[i]).style.display = 'none';
        }
    }
}