邓华

BlogJava 联系 聚合 管理
  48 Posts :: 0 Stories :: 149 Comments :: 0 Trackbacks
07年写的,太久了,应该有更好的了吧, 怀念一下.  这么多年没写JS了,都不太记得了.

主要是实现的页面内容的碎片可视化编辑. 
比如在内容碎片,选择某个链接,弹出一个层,直接修改链接的名称和地址
比如动态碎片,弹出一个层,直接修改该碎片引用的某频道列表。

 需要的同学们来摘下哈.  当然,直接运行是运行不起来地。

哼哼哼,当年呐,实现这功能多NB~



var CMSTemplate = Class.create();
CMSTemplate.prototype 
= {
    initialize: 
function() {
        
this.coverDiv = $("sohu_frag_block");
        
this.coverDivIframe = $("sohu_frag_block_iframe");
        
this.currentCoveredId = -1;
        
this.fragBuffer = new Array();
        
this.FRAG_TAGNAME = "span";
        
this.FRAG_ID = "cms4_template_frag";
        
this.tempFragObserveObjectArray = new Array();
        
this.fragEditorArray = new Array();
        
this.coverDiv.onclick = this.clickCover.bind(this);
        
this.coverDiv.onmouseout = this.hideCover.bind(this);
    },
    processFrag: 
function() {
        
var frags = document.getElementsByName(this.FRAG_ID);
        
if (frags.length == 0) {
            alert(
"没有找到碎片");
            
return;
        };
        
this.killBaseTarget();
        
for (var i = 0; i < frags.length; i++) {
            
var frag = frags[i];
            
this.tempFragObserveObjectArray[i] = this.showCover.bind(this);
            $(frag).observe(
"mouseover"this.tempFragObserveObjectArray[i]);
            frag.idx 
= i;
            
this.fragBuffer.push(frag);
        }
    },
    killBaseTarget: 
function() {
        
var bases = $A(document.getElementsByTagName("base"));
        bases.each(
function(b) {
            
if (b.getAttribute("target"!= null && b.getAttribute("target"!= "") {
                b.removeAttribute(
"target");
            }
        });
    },
    showCover: 
function(_event) {
        
var element = this.findElementById(_event, this.FRAG_TAGNAME);
        
while (element != null && element.tagName != "element.tagName" && this.FRAG_ID != element.id) {
            element 
= element.parentElement;
        };
        
this.currentCoveredId = element.idx;
        
this.adjustCoverPosition(element);
        
this.changeCoverContent(element);
        Element.show(
this.coverDivIframe);
        Element.show(
this.coverDiv);
    },
    adjustCoverPosition: 
function(_targetElement) {
        
var ibody = document.documentElement;
        
if (ibody.scrollTop == 0) {
            ibody 
= document.body;
        };
        
var obj = _targetElement.getBoundingClientRect();
        
this.coverDiv.style.left = obj.left + ibody.scrollLeft - 2 + "px";
        
this.coverDiv.style.top = obj.top + ibody.scrollTop - 4 + "px";
        
this.coverDiv.style.width = obj.right - obj.left + 2 + "px";
        
this.coverDiv.style.height = obj.bottom - obj.top + 2 + "px";
        
this.coverDivIframe.style.left = this.coverDiv.style.left;
        
this.coverDivIframe.style.top = this.coverDiv.style.top;
        
this.coverDivIframe.style.width = this.coverDiv.style.width;
        
this.coverDivIframe.style.height = this.coverDiv.style.height;
    },
    changeCoverContent: 
function(_element) {
        
var frag_type = _element.getAttribute("frag_type");
        
var coverContent = "";
        
var converBackgroupColor = "#ffffcc";
        
switch (frag_type) {
        
case "1":
            coverContent 
= "【碎片类型】静态碎片<br>【碎片名称】" + _element.getAttribute("frag_name"+ '<br>【碎片描述】' + _element.getAttribute("frag_desc"+ '<br>【引用类型】' + _element.getAttribute("frag_quotetype"+ (_element.getAttribute("frag_quotefrag"== null ? "": '<br>【引用碎片】' + _element.getAttribute("frag_quotefrag")) + '<br>【碎片权限】' + this.getSplitedPermision(_element);
            
break;
        
default:
            coverContent 
= "碎片类型不正确, fragtype:" + frag_type;
            
break;
        };
        
this.coverDiv.innerHTML = coverContent;
        
this.coverDiv.style.backgroundColor = converBackgroupColor;
    },
    _genStaticFragContent: 
function(_element) {
        
return;
    },
    getSplitedPermision: 
function(_e) {
        
return _e.getAttribute("frag_permission").replace(/\|/g, '<br>');
    },
    clickCover: 
function(_event) {
        
var currentFrag = this.fragBuffer[this.currentCoveredId];
        
var frag_type = currentFrag.getAttribute("frag_type");
        
var frag_quotetype = currentFrag.getAttribute("frag_quotetype");
        
switch (frag_type) {
        
case "1":
            
if ("4" == frag_quotetype) {
                
this._observeQuoteFrag(currentFrag);
            } 
else {
                
this._observeStaticFrag(currentFrag);
            };
            
break;

        
default:
            
break;
        }
    },
    _observeStaticFrag: 
function(currentFrag) {
        currentFrag.stopObserving(
"mouseover"this.tempFragObserveObjectArray[this.currentCoveredId]);
        
this.hideCover();
        
var editor = this.fragEditorArray[this.currentCoveredId];
        
if (editor == null) {
            editor 
= new CMSFragEditor(currentFrag, this);
            
this.fragEditorArray[this.currentCoveredId] = editor;
        };
        editor.show();
    },
    _observeQuoteFrag: 
function(currentFrag) {
        
var cms_url = window.location.protocol + "//" + window.location.hostname + '/fragedit.do?method=view&fragtype=2&channelid=+ currentFrag.getAttribute("frag_channel_id"+ '&fragname=+ currentFrag.getAttribute("frag_quotefrag"+ '&entityid=+ currentFrag.getAttribute("frag_entity_id"+ '&templateid=+ currentFrag.getAttribute("frag_template_id");
        
this.openWindow(cms_url);
    },
    openWindow: 
function(url, width, height) {
        
var window_width = width ? width: "620";
        
var window_height = height ? height: "620";
        window.open(url, '', 'width
=+ window_width + ',height=+ window_height + ',resizable=yes,scrollbars=yes');
    },
    hideCover: 
function(_event) {
        Element.hide(
this.coverDivIframe);
        Element.hide(
this.coverDiv);
    },
    findElementById: 
function(event, tagName) {
        
var element = Event.element(event);
        
while (element.parentNode && (!element.tagName || (element.tagName.toUpperCase() != tagName.toUpperCase())) && element.id != this.FRAG_ID) element = element.parentNode;
        
return element;
    }
};
var CMSInfo = {
    messages: {
        'select.link': '
<h2 style="font-size: large">行修改状态</h2><div>请选择行</div>',
        'select.processLink': '请稍候, 正在计算中',
        'change.first': '
<h2 style=\"color: red; font-size: large \">碎片交换状态</h2><div>请选择要交换链接</div>',
        'change.second': '
<h2 style=\"color: red; font-size: large\">碎片交换状态</h2><div>请选择被交换链接</div>'
    },
    getInfo: 
function(key) {
        
var tmp = CMSInfo.messages[key];
        
if (tmp) return tmp;
        
return key;
    },
    formatMsg: 
function(key, params) {
        
var msgDef = CMSInfo.getInfo(key);
        
if (msgDef && params) {
            
for (var i = 0; i < params.length; ++i) {
                msgDef 
= msgDef.replace('{' + i + '};', CMSInfo.getInfo(params[i]));
            }
        };
        
return msgDef;
    },
    formatMsgs: 
function(msgs, type, sep) {
        
var str = "";
        
for (var msg in msgs) {
            
if (type == 0) {
                
if (msg.indexOf('messages') != 0continue;
            } 
else if (type == 1) {
                
if (msg.indexOf('errors') != 0continue;
            };
            
var param = msgs[msg];
            
if (param.constructor == Array) {
                
var fmsg = CMSInfo.formatMsg(msg, msgs[msg]);
                
if (fmsg) {
                    str 
+= fmsg;
                    
if (typeof sep == 'undefined' || sep == '') {
                        str 
+= '<br />';
                    } 
else {
                        str 
+= sep;
                    }
                }
            }
        };
        
return str;
    },
    readInfo: 
function(type, sep) {
        
var cookieMsg = CMSInfo.getCookie('msg');
        
if (cookieMsg == '' || cookieMsg == 'none') return '';
        
var fmsgs = CMSInfo.htmlInfo(cookieMsg, type, sep);
        
if (fmsgs && fmsgs.length > 0) {
            CMSInfo.setCookie('msg', 'none', '', '
/', 'blog.sohu.com');
        };
        
return fmsgs;
    },
    htmlInfo: 
function(str, type, sep) {
        
var msgs = JSON.parse(str);
        
if (msgs) {
            
return CMSInfo.formatMsgs(msgs, type, sep);
        };
        
return str;
    },
    displayMsg: 
function() {
        document.write(CMSInfo.readInfo(
0));
    },
    displayErr: 
function() {
        document.write(CMSInfo.readInfo(
1));
    },
    blackWord: [
"cms4.sohu.com""sina.com""163.com""news4.sohu.com""mop.com"]
};
var CMSFragEditor = Class.create();
CMSFragEditor.prototype 
= {
    initialize: 
function(_targetFrag, _fragTemplateHandle) {
        
this.idx = _targetFrag.idx;
        
this.fragHandle = _fragTemplateHandle;
        
this.targetFrag = _targetFrag;
        
this.tagPrefix = 'fragEditor_' + this.idx + "_";
        
this.fragEditorId = "frag_editor_" + this.idx;
        
this.link_need_backup_attr = ["href""onclick""target""rel"];
        
this.img_need_backup_attr = ["onclick"];
        
this.targetFrag_backup_html = this.targetFrag.innerHTML;
        
this.rich_tag = ["<script""<object""<iframe""onmouseover""<input""<embed""<select""<option""<style""\#include"];
        
this.alreadyShowed = false;
        
this.editorShowLayer = this.initEditorShowLayer();
        
this.switchTabDesc = [["switchTitle1""switchContent1"], ["switchTitle2""switchContent2"], ["switchTitle3""switchContent3"]];
        
this.currentTabId = null;
        
this.focusObject = $(this.tagPrefix + "focus");
        
this.bufferDiv = document.createElement("div");
        
this.exchangeModeFlag = false;
        
this.fragType = this.targetFrag.getAttribute("frag_type");
        
this.entityId = this.targetFrag.getAttribute("frag_entity_id");
        
this.templateId = this.targetFrag.getAttribute("frag_template_id");
        
this.tfmapId = this.targetFrag.getAttribute("frag_id");
        
this.isRich = null;
        
this.firstClickEl = null;
        
this.firstClickElId = "badfrweabva34213";
        $(
"rich_resource").onclick = function() {
            window.open('http:
//10.1.56.20/');
            return false;
        };
        logger.debug(
"start new TextareaSearch");
        
var area_search = new TextareaSearch(this.tagPrefix + "search"this.tagPrefix + "rich_edit"this.tagPrefix + "go");
    },
    initEditorShowLayer: 
function() {
        
if ($(this.fragEditorId)) {
            
return $(this.fragEditorId);
        };
        
var layer = document.createElement("div");
        layer.id 
= this.fragEditorId;
        layer.style.zIndex 
= 20 + this.idx;
        $(layer).setStyle({
            position: 
"absolute",
            left: 
"0px",
            top: 
"0px"
        });
        layer.innerHTML 
= $("sohu_t_frageditor").value;
        document.body.appendChild(layer);
        
this.changeIdsAndNames(layer);
        
return layer;
    },
    changeIdsAndNames: 
function(_layer) {
        
var es = _layer.getElementsByTagName('*');
        
for (var i = 0; i < es.length; i++) {
            
if (es[i].id.indexOf("fragEditor_"== 0) {
                es[i].id 
= "fragEditor_" + this.idx + "_" + es[i].id.slice(11);
                es[i].idx 
= this.idx;
            }
        }
    },
    show: 
function() {
        
this.adjustPosition();
        
this.targetFrag_backup_html = null;
        
var url = window.location.protocol + "//" + window.location.hostname + "/fragedit.do";
        url 
+= "?date3214=" + Math.round(Math.random() * 10000);
        
var pars = "method=fragContent&eid=" + this.targetFrag.getAttribute("frag_entity_id"+ "&tfmapid=" + this.targetFrag.getAttribute("frag_id"+ "&templateid=" + this.templateId;
        
new Ajax.Request(url, {
            method: 'get',
            asynchronous: 
false,
            parameters: pars,
            onSuccess: 
function(transport) {
                logger.debug(
"fragContent success!");
                
var text = transport.responseText;
                
if (transport.responseText.indexOf("您没有权限"!= -1) {
                    alert(
"您没有权限这么做.请重新登陆。");
                    
return;
                };
                
var json = null;
                
try {
                    json 
= eval(transport.responseText);
                } 
catch(e) {};
                
if (json == null) {
                    json 
= [""];
                };
                logger.debug(json[
0].escapeHTML());
                
if (json[0== "error") {
                    alert(json[
1]);
                    
return;
                };
                
this.targetFrag_backup_html = json[0];
                
this.lastModifyTimestamp = json[1];
                
try {
                    
if (!this.isRichText()) this.targetFrag.innerHTML = json[0];
                } 
catch(e) {
                    alert(e);
                }
            }.bind(
this),
            onFailure: 
function() {
                alert('连接失败');
            }
        });
        
if (this.targetFrag_backup_html == null) {
            
return;
        };
        
if (this.isRichText()) {
            
this.switch2Tab(nullthis.switchTabDesc[1][0], this.switchTabDesc[0][0]);
            $(
this.tagPrefix + "exchange").hide();
            
this.loadContentByAjax();
        } 
else {
            
this.exchangeModeFlag = false;
            
this.switch2Tab(nullthis.switchTabDesc[0][0]);
            
this.changeObjectStatus();
            
if (!this.alreadyShowed) {
                Event.observe(
this.tagPrefix + this.switchTabDesc[1][0], "click"this._clickSimpleFragCode.bind(this));
            };
            $(
this.tagPrefix + "exchange").show();
            
this.status2SimpleContainer(CMSInfo.getInfo("select.link"));
        };
        
if (!this.alreadyShowed) {
            
this.bindAction();
            
var a = new Draggable(this.fragEditorId, {
                reverteffect: 
function(element, top_offset, left_offset) {
                    element.style.cursor 
= "move";
                },
                endeffect: 
function(element) {
                    element.style.cursor 
= ""
                },
                starteffect: 
function(element) {
                    element.style.cursor 
= "move";
                }
            });
        };
        Element.show(
this.editorShowLayer);
        
this.alreadyShowed = true;
        
this.focusObject.focus();
    },
    _clickSimpleFragCode: 
function() {
        logger.debug(
"click  simple fragcode");
        $(
this.tagPrefix + "rich_edit").value = this.getTrueCurrentlyFrag();
    },
    getTrueCurrentlyFrag: 
function() {
        
return CMSUtils.prettyHtmlSource(CMSUtils.format2xhtml(this.restoreObjectStatus(this.targetFrag.innerHTML)));
    },
    status2SimpleContainer: 
function(_text) {
        $(
this.tagPrefix + "simple_container").innerHTML = _text;
    },
    changeObjectStatus: 
function(targetFrag) {
        
var links = this.targetFrag.getElementsByTagName("a");
        
for (var i = 0; i < links.length; i++) {
            
var a = links[i];
            
for (j = 0; j < this.link_need_backup_attr.length; j++) {
                
this.changeLinksAttribute(a, this.link_need_backup_attr[j], "");
            };
            
if (this.exchangeModeFlag) {
                Event.observe(a, 'click', 
this.exchangeLinksAttribute.bindAsEventListener(this));
            } 
else {
                Event.observe(a, 'click', 
this.transferLinksAttribute.bindAsEventListener(this));
            }
        }
    },
    exchangeLinksAttribute: 
function(_event) {
        logger.info(
"exchange action fire!");
        
var _el = Event.findElement(_event, "A");
        
if (this.firstClickEl == null) {
            _el.addClassName(
"fragedit_exchange_click");
            
this.firstClickEl = _el;
            
this.firstClickEl.id = this.firstClickElId;
            
this.status2SimpleContainer(CMSInfo.getInfo("change.second"));
        } 
else {
            
var tmp_href = this.firstClickEl.getAttribute("back_href");
            
var tmp_innerHTML = this.firstClickEl.innerHTML;
            
this.firstClickEl.setAttribute("back_href", _el.getAttribute("back_href"));
            
this.firstClickEl.innerHTML = _el.innerHTML;
            _el.setAttribute(
"back_href", tmp_href);
            _el.innerHTML 
= tmp_innerHTML;
            
this.restoreFirstExchangeLink();
            
this.status2SimpleContainer(CMSInfo.getInfo("change.first"));
        }
    },
    restoreFirstExchangeLink: 
function() {
        
var _el = $(this.firstClickElId);
        
if (_el) {
            _el.removeClassName(
"fragedit_exchange_click");
            _el.removeAttribute(
"id");
            
this.firstClickEl = null;
        }
    },
    restoreObjectStatus: 
function(_text) {
        
if (_text.indexOf("【碎片名称】"!= -1return "";
        
this.bufferDiv.innerHTML = _text;
        
var links = this.bufferDiv.getElementsByTagName("a");
        logger.debug(
"restore links size:" + links.length);
        
for (var i = 0; i < links.length; i++) {
            
var link = links[i];
            
for (var j = 0; j < this.link_need_backup_attr.length; j++) {
                
var attr = this.link_need_backup_attr[j];
                
var bak_attr_value = link.getAttribute("back_" + attr);
                
if (bak_attr_value && bak_attr_value != null && bak_attr_value != "null" && bak_attr_value != "") {
                    link.setAttribute(attr, bak_attr_value);
                };
                link.removeAttribute(
"back_" + attr);
            };
            link.removeAttribute(
"_extended");
        };
        
return this.bufferDiv.innerHTML;
    },
    transferLinksAttribute: 
function(_e) {
        
this.status2SimpleContainer(CMSInfo.getInfo("select.processLink"));
        
var element = Event.findElement(_e, "a");
        
var l = new LineEditor(element, this);
        l.processToElement();
        
this.switch2Tab(nullthis.switchTabDesc[0][0]);
    },
    isRichText: 
function() {
        
if (this.isRich != null) {
            
return this.isRich;
        };
        
var lowercase_html = this.targetFrag_backup_html.toLowerCase();
        
var isrich = false;
        
if (lowercase_html.strip() == "") isrich = true;
        
if (!isrich) {
            
if (lowercase_html.indexOf("【碎片名称】"!= -1) {
                isrich 
= true;
            }
        };
        
if (!isrich) if (this.targetFrag.getElementsByTagName("A").length == 0) isrich = true;
        
if (!isrich) this.rich_tag.each(function(value, index) {
            
if (lowercase_html.indexOf(value) != -1) {
                isrich 
= true;
            }
        });
        
if (!isrich) {
            
if (/%\w{2};/i.test(lowercase_html)) isrich = true;
        };
        
this.isRich = isrich;
        
return isrich;
    },
    loadContentByAjax: 
function() {
        logger.debug(
"load content by ajax");
        
var url = window.location.protocol + "//" + window.location.hostname + "/fragedit.do";
        
var pars = "method=fragget" + "&fragtype=" + this.fragType + "&entityid=" + this.entityId + "&templateid=" + this.templateId + "&tfmapid=" + this.tfmapId;
        url 
+= "?date3214=" + Math.round(Math.random() * 10000);
        logger.debug(
"pars: " + pars);
        
var myAjax = new Ajax.Request(url, {
            method: 'get',
            parameters: pars,
            onSuccess: 
this.loadfrag_Success.bind(this),
            onFailure: 
function() {
                alert('连接失败');
            }
        });
    },
    loadfrag_Success: 
function(transport) {
        logger.debug(
"loadfrag_Success fired!!!");
        
var text = transport.responseText;
        logger.debug(
"response text:" + text);
        
if (text.indexOf("您没有权限"!= -1) {
            alert(
"您没有权限这么做,请重新登陆。");
        } 
else {
            
var json = eval(text);
            
if (json[0== "error") {
                alert(json[
1]);
            } 
else {
                
this.targetFrag_backup_html = json[1];
                $(
this.tagPrefix + "rich_edit").value = json[1];
                
if (this.isFocusFrag(json[1])) {
                    
var focus_status = $(this.tagPrefix + "focus_status");
                    focus_status.show();
                    focus_status.onclick 
= function() {
                        
var url = "/focusfragedit.do?method=view&fragtype=1&entityid=" + this.entityId + "&templateid=" + this.templateId + "&tfmapid=" + this.tfmapId;
                        window.open(url);
                    }.bind(
this);
                }
            }
        }
    },
    isFocusFrag: 
function(content) {
        
if (content.indexOf("pics"!= -1 && content.indexOf("mylinks"!= -1 && content.indexOf("texts"!= -1return true;
    },
    changeLinksAttribute: 
function(node, attr, newValue) {
        node.setAttribute(
"back_" + attr, node.getAttribute(attr));
        
if (attr == "href") {
            node.setAttribute(attr, 
"javascript:void(0)");
        } 
else {
            node.removeAttribute(attr);
        }
    },
    adjustPosition: 
function() {
        
var ibody = document.documentElement;
        
if (ibody.scrollTop == 0) {
            ibody 
= document.body;
        };
        
var obj = this.targetFrag.getBoundingClientRect();
        
var a_l = obj.left + ibody.scrollLeft + this.editorShowLayer.getWidth();
        
var l = a_l > viewport.width ? viewport.width - this.editorShowLayer.getWidth() : obj.left + ibody.scrollLeft;
        
this.editorShowLayer.style.left = l - 2 + "px";
        
this.editorShowLayer.style.top = obj.bottom + ibody.scrollTop + 11 + "px";
    },
    bindAction: 
function() {
        logger.info(
"bind action!!!!");
        
this.bindSwitchTab();
        $(
this.tagPrefix + "close").onclick = this.cancle.bind(this);
        $(
this.tagPrefix + "simple_cancel").observe("click"this.cancle.bind(this));
        $(
this.tagPrefix + "rich_cancel").observe("click"this.cancle.bind(this));
        $(
this.tagPrefix + "exchange").observe("click"this.exchangeMode.bind(this));
        $(
this.tagPrefix + this.switchTabDesc[2][0]).observe("click"this.clickModifyRecord.bind(this));
        $(
this.tagPrefix + "simple_save").observe("click"this.save.bind(this));
        $(
this.tagPrefix + "rich_save").observe("click"this.save.bind(this));
        $(
this.tagPrefix + "rich_testall").observe("click"this.testAll.bind(this));
        $(
this.tagPrefix + "rich_hire").observe("click",
        
function() {
            window.open('http:
//cms4.sohu.com/external/publish/fragHire.jsp?entityid=' + this.entityId + '&tfmapid=' + this.tfmapId, '', 'width=600, height=400');
            return false;
        }.bind(
this));
        $(
this.tagPrefix + "addIMLink").observe("click"this.addIMLink.bind(this));
        $(
this.tagPrefix + "clearIMLink").observe("click"this.clearIMLink.bind(this));
    },
    testAll: 
function() {
        logger.debug(
"testAll fired!");
        
var oForm = document.createElement("FORM");
        oForm.method 
= "POST";
        oForm.action 
= window.location.protocol + "//" + window.location.hostname + window.location.pathname;
        oForm.target 
= "_blank";
        oForm.id 
= "testall_form";
        oForm.appendChild(CMSUtils.createInput(
"ENTITYID"this.entityId));
        oForm.appendChild(CMSUtils.createInput(
"test""yes"));
        oForm.appendChild(CMSUtils.createInput(
"testtfid"this.tfmapId));
        oForm.appendChild(CMSUtils.createInput(
"testcont", $F(this.tagPrefix + 'rich_edit')));
        oForm.appendChild(CMSUtils.createInput(
"view""2"));
        document.body.appendChild(oForm);
        oForm.submit();
        Element.remove(oForm);
    },
    save: 
function() {
        
if (!this.isRichText() && this.currentTabId != this.tagPrefix + this.switchTabDesc[1][0]) {
            $(
this.tagPrefix + "rich_edit").value = this.getTrueCurrentlyFrag();
        } 
else {
            
this.isRich = null;
        };
        
var ck = this.checkContent();
        
if (ck && !confirm("内容中的链接包含:" + ck + "是否继续?")) {
            
return;
        };
        
if (!this.checkContentTag()) {
            
return;
        };
        
this.restoreFirstExchangeLink();
        
this.saveAjax();
    },
    count: 
function(content, value) {
        
var count = 0;
        
var begin = 0;
        
while (content.indexOf(value, begin) >= 0) {
            count 
= count + 1;
            begin 
= content.indexOf(value, begin) + value.length;
        };
        
return count;
    },
    checkContentTag: 
function() {
        
var content = $(this.tagPrefix + "rich_edit").value.toLowerCase();
        
var tag = ["table""tr""td""div""ul""span"];
        
for (var i = 0; i < tag.length; i++) {
            
var t = tag[i];
            
if (this.count(content, "<" + t) != this.count(content, "</" + t + ">")) {
                alert(
"标签 " + t + " 数量不配对,请检查");
                
return false;
            }
        };
        
return true;
    },
    checkContent: 
function() {
        
var value = $(this.tagPrefix + "rich_edit").value;
        
var result = value.match(/\s+href\s*=\s*[('|")]?([^(\s+|'|")]*)[^>]*>/ig);
        
if (result != null && result.length > 0) {
            
var words = CMSInfo.blackWord;
            
for (var i = 0; i < result.length; i++) {
                
for (var k = 0; k < words.length; k++) {
                    
var word = words[k];
                    
if (result[i].indexOf(word) != -1) {
                        
return word;
                    }
                }
            }
        }
    },
    saveAjax: 
function() {
        logger.debug(
"save ajax begin");
        
var url = window.location.protocol + "//" + window.location.hostname + "/fragedit.do";
        
var pars = "method=saveNew" + "&fragtype=" + this.fragType + "&entityid=" + this.entityId + "&templateid=" + this.templateId + "&tfmapid=" + this.tfmapId + "&lastmodifytime=" + this.lastModifyTimestamp;
        
var content = $F(this.tagPrefix + "rich_edit");
        
var cont = escape(encodeURIComponent(content));
        pars 
+= "&content=" + cont;
        logger.debug(
"save ajax pars:" + pars);
        
var myAjax = new Ajax.Request(url, {
            method: 'post',
            parameters: pars,
            onSuccess: 
this._saveAjax_onSuccess.bind(this),
            onFailure: 
function() {
                alert('连接失败');
            }
        });
    },
    _saveAjax_onSuccess: 
function(transport) {
        logger.debug(
"save onsuccess responsetext:" + transport.responseText);
        
var text = transport.responseText;
        
if (text.indexOf("您没有权限"!= -1) {
            alert(
"您没有权限这么做.请重新登陆。");
        } 
else {
            
var json = eval(text);
            
if (json[0== "error") {
                alert(json[
1]);
            } 
else if (json[0== "succ") {
                
var needReload = false;
                
try {
                    
this.targetFrag.innerHTML = $F(this.tagPrefix + "rich_edit");
                } 
catch(e) {
                    needReload 
= true;
                };
                alert(json[
1]);
                
this.closeEditor();
                
if (needReload) location.reload();
            }
        }
    },
    clickModifyRecord: 
function() {
        logger.debug(
"clickModifyRecord fired!");
        logger.debug(
"this.currentTabId" + this.currentTabId);
        logger.debug(
"this.tagPrefix+this.switchTabDesc[2][0]:" + this.tagPrefix + this.switchTabDesc[2][0]);
        
if (this.currentTabId == this.tagPrefix + this.switchTabDesc[2][0]) {
            
return;
        };
        
var url = window.location.protocol + "//" + window.location.hostname + "/fragedit.do";
        
var pars = "method=fragundolist" + "&fragtype=1&entityid=" + this.entityId + "&templateid=" + this.templateId + "&tfmapid=" + this.tfmapId + "&date32123=" + Math.round(Math.random() * 10000);
        logger.debug(
"clickModifyRecord url:" + url);
        logger.debug(
"clickModifyRecord pars:" + pars);
        
var myAjax = new Ajax.Request(url, {
            method: 'get',
            parameters: pars,
            onSuccess: 
this._clickModifyRecord_onSuccess.bind(this),
            onFailure: 
function() {
                alert('连接失败');
            }
        });
    },
    _clickModifyRecord_onSuccess: 
function(transport) {
        logger.debug(
"_clickModifyRecord_onSuccess fire!");
        
var text = transport.responseText;
        
if (text.indexOf("您没有权限"!= -1) {
            alert(
"您没有权限这么做.请重新登陆。");
        } 
else {
            
var json = eval(text);
            
if (json[0== "error") {
                alert(json[
1]);
            } 
else {
                $(
this.tagPrefix + 'fragPath').value = "<!--#" + "include virtual=\"" + json[0] + "\"-->";
                json[
1].tagPrefix = this.tagPrefix;
                
var result = TrimPath.processDOMTemplate("modify_record_template", json[1]);
                
this.bufferDiv.innerHTML = result;
                logger.debug(
"this.bufferDiv.innerHTML" + this.bufferDiv.innerHTML.escapeHTML());
                
var links = this.bufferDiv.getElementsByTagName("a");
                logger.debug(
"links length:" + links.length);
                
for (var i = 0; i < links.length; i++) {
                    
var link = links[i];
                    
if (link.path) Event.observe(link, "click"this._recordClick.bindAsEventListener(this));
                };
                $(
this.tagPrefix + 'record_content').innerHTML = "";
                $(
this.tagPrefix + 'record_content').appendChild(this.bufferDiv.firstChild);
            }
        }
    },
    _recordClick: 
function(_event) {
        logger.debug(
" record click fired!");
        
var element = Event.findElement(_event, "a");
        
if (element.path) {
            
this.fragRollback(element.path, $(this.tagPrefix + "rich_edit"));
        }
    },
    fragRollback: 
function(_path, _target) {
        logger.debug(
"frag rollback fired");
        
var url = window.location.protocol + "//" + window.location.hostname + "/fragedit.do";
        
var pars = "method=fragundo" + "&path=" + _path;
        
var myAjax = new Ajax.Request(url, {
            method: 'get',
            parameters: pars,
            onSuccess: 
function(transport) {
                
if (transport.responseText.indexOf("您没有权限"!= -1) {
                    alert(
"您没有权限这么做.请重新登陆。");
                    
return;
                };
                
var json = eval(transport.responseText);
                logger.debug(json[
0].escapeHTML());
                _target.value 
= json[0];
                
this.switch2Tab(nullthis.switchTabDesc[1][0]);
            }.bind(
this),
            onFailure: 
function() {
                alert('连接失败');
            }
        });
    },
    exchangeMode: 
function() {
        logger.debug(
" exchangeModeFlag done, flag:" + this.exchangeModeFlag);
        
this.targetFrag.innerHTML = this.getTrueCurrentlyFrag();
        
if (this.exchangeModeFlag == false) {
            
this.exchangeModeFlag = true;
            $(
this.tagPrefix + "exchange").addClassName("fragedit_backgroundcolor");
            $(
this.tagPrefix + "exchange").innerText = "取消交换";
            
this.status2SimpleContainer(CMSInfo.getInfo("change.first"));
        } 
else {
            
this.exchangeModeFlag = false;
            $(
this.tagPrefix + "exchange").removeClassName("fragedit_backgroundcolor");
            $(
this.tagPrefix + "exchange").innerText = "交换状态";
            
this.restoreFirstExchangeLink();
            
this.status2SimpleContainer(CMSInfo.getInfo("select.link"));
        };
        
this.changeObjectStatus(this.targetFrag);
    },
    bindSwitchTab: 
function() {
        
for (var i = 0; i < this.switchTabDesc.length; i++) {
            
var currentTab = $(this.tagPrefix + this.switchTabDesc[i][0]);
            currentTab.observe(
"click"this.switch2Tab.bindAsEventListener(this));
        }
    },
    switch2Tab: 
function(_e, _en, _hns) {
        
var element = null;
        
if (_e != null) element = Event.findElement(_e, "li");
        
else element = $(this.tagPrefix + _en);
        
if (this.currentTabId == element.id) return;
        
for (var i = 0; i < this.switchTabDesc.length; i++) {
            
if (element.id == (this.tagPrefix + this.switchTabDesc[i][0])) {
                element.className 
= "fragedit_tab_show";
                $(
this.tagPrefix + this.switchTabDesc[i][1]).show();
                
this.currentTabId = element.id;
            } 
else {
                $(
this.tagPrefix + this.switchTabDesc[i][0]).className = "fragedit_tab_hidden";
                $(
this.tagPrefix + this.switchTabDesc[i][1]).hide();
                
if (_hns) $(this.tagPrefix + _hns).hide();
            }
        };
        logger.debug(
" editorShowLayer can visited : " + this.editorShowLayer.visible());
        
if (_e != null) Event.stop(_e);
    },
    closeEditor: 
function() {
        logger.debug(
"close editor fired!  this.alreadyShowed" + this.alreadyShowed);
        
try {
            
if (!this.isRichText()) {
                
if (this.currentTabId != this.tagPrefix + this.switchTabDesc[1][0]) {
                    
this.targetFrag.innerHTML = this.getTrueCurrentlyFrag();
                } 
else {
                    
this.targetFrag.innerHTML = $(this.tagPrefix + "rich_edit").value;
                }
            }
        } 
catch(e) {};
        
this.restoreFirstExchangeLink();
        
this.editorShowLayer.hide();
        
this.targetFrag.observe("mouseover"this.fragHandle.tempFragObserveObjectArray[this.idx]);
        logger.debug(
"close editor done , this.alreadyShowed:" + this.alreadyShowed);
    },
    cancle: 
function() {
        
try {
            
if (!this.isRichText()) this.targetFrag.innerHTML = this.targetFrag_backup_html;
        } 
catch(e) {};
        
this.closeEditor();
    },
    frageditor_undo: 
function(_target) {},
    addIMLink: 
function() {
        
var scont = $F(this.tagPrefix + "rich_edit");
        
var imlinkRequest = new IMRequest();
        
var newscont = imlinkRequest.addIMLink(scont);
        
if (newscont != null) {
            $(
this.tagPrefix + "rich_edit").value = newscont;
        }
    },
    clearIMLink: 
function() {
        
var scont = $F(this.tagPrefix + "rich_edit");
        
var imlinkRequest = new IMRequest();
        
var newscont = imlinkRequest.removeIMLink(scont);
        
if (newscont != null) {
            $(
this.tagPrefix + "rich_edit").value = newscont;
        }
    }
};
var TextareaSearch = Class.create();
TextareaSearch.prototype 
= {
    initialize: 
function(_input, _textarea, _button) {
        logger.debug(
"TextareaSearch init");
        
this.input = $(_input);
        
this.input.onkeyup = this.inputKeyup.bindAsEventListener(this);
        
this.input.onfocus = this.inputFocus.bindAsEventListener(this);
        
this.textarea = $(_textarea);
        
this.rng = this.textarea.createTextRange();
        
this.button = $(_button);
        
if (this.button) {
            logger.debug(
"go button bind action");
            
this.button.onclick = function() {
                
this.searchKey(this.input.value);
            }.bind(
this);
        }
    },
    inputFocus: 
function(_event) {
        Event.element(_event).select();
    },
    inputKeyup: 
function(_event) {
        
if (_event.keyCode == Event.KEY_RETURN) {
            
this.searchKey(this.input.value);
        }
    },
    searchKey: 
function(_keyword) {
        
if (_keyword == "")  
        
return;
        
var num = 0;
        
if (document.selection)  num = document.selection.createRange().text.length;
        
this.rng.moveStart("character", num);
        
this.rng.moveEnd("character"this.input.value.length);
        
if (this.rng.findText(_keyword)) this.rng.select();
        
if (this.rng.text != _keyword) {  this.rng = this.textarea.createTextRange();
        }
    }
};
var LineEditor = Class.create();
LineEditor.prototype 
= {
    initialize: 
function(_element, _handle) {
        
this.focusElement = $(_element);
        
this.editorHandle = _handle;
        
this.fragIdx = _handle.idx;
        
this.bufferDiv = document.createElement("div");
        
this.container = $(_handle.tagPrefix + "simple_container");
        
this.parentElement = this.focusElement.parentNode;
        
this._initLineElements();
    },
    _initLineElements: 
function() {
        
this.lineElements = new Array();
        
var parent_El_tagName = this.parentElement.tagName;
        
if ((/(H\d|LI|P|TD|DIV)/.test(parent_El_tagName))) {
            logger.debug(
"find line, p_tagname=" + parent_El_tagName);
            
this._processMultiChildNode();
        } 
else {
            
this.lineElements.push(this.focusElement);
        }
    },
    _processMultiChildNode: 
function() {
        
var el_cursor = this.focusElement;
        
this.lineElements.push(el_cursor);
        
while (el_cursor.nextSibling) {
            el_cursor 
= el_cursor.nextSibling;
            
if (el_cursor.nodeName != "BR") {
                
this.lineElements.push(el_cursor);
            } 
else {
                
break;
            }
        };
        el_cursor 
= this.focusElement;
        
while (el_cursor.previousSibling) {
            el_cursor 
= el_cursor.previousSibling;
            
if (el_cursor.nodeName != "BR") {
                
this.lineElements.splice(00, el_cursor);
            } 
else {
                
break;
            }
        };
    },
    processToElement: 
function() {
        
var bDiv = document.createElement("DIV");
        logger.debug(
" processToElement lineElement.length:" + this.lineElements.length);
        
for (var i = 0; i < this.lineElements.length; i++) {
            
var _el = this.lineElements[i];
            
var _idx = i;
            
var c_node = this._createNode(_el, _idx);
            
if (c_node) {
                bDiv.appendChild(c_node);
                bDiv.appendChild(
this._createClearDiv());
            }
        };
        
this.container.innerHTML = "";
        
this.container.appendChild(bDiv);
    },
    _createNode: 
function(_el, _idx) {
        
var tmpContainer = document.createElement("div");
        
if ((_idx + 1% 2 == 0) {
            tmpContainer.className 
= "fragedit_simplecontainer_0";
        } 
else {
            tmpContainer.className 
= "fragedit_simplecontainer_1";
        };
        
if (_el.nodeType == 3) {
            tmpContainer.appendChild(
this._createColumn("文字:"));
            
var d = document.createElement("div");
            d.className 
= "fragediterinput";
            
var t = this._createInput();
            t.lineIdx 
= _idx;
            t.value 
= _el.nodeValue;
            d.appendChild(t);
            tmpContainer.appendChild(d);
            logger.debug(
"tmpcontainer appendchild:" + d.tagName);
            Event.observe(t, 
"keyup"this.changeTextNode.bindAsEventListener(this));
        } 
else if (_el.nodeType == 1) {
            
if (_el.tagName == "A") {
                
if (_el.firstChild && _el.firstChild.tagName == "IMG") {
                    tmpContainer.appendChild(
this._createColumn("图片:"));
                    
var _1d = document.createElement("div");
                    _1d.className 
= "fragediterinput";
                    
var d1 = this._createInput();
                    d1.id 
= this.editorHandle.tagPrefix + "simple_img_src_" + Math.round(Math.random() * 10000);
                    d1.lineIdx 
= _idx;
                    d1.value 
= _el.firstChild.src;
                    _1d.appendChild(d1);
                    tmpContainer.appendChild(_1d);
                    Event.observe(d1, 
"keyup"this.changeImgSrc.bindAsEventListener(this));
                    tmpContainer.appendChild(
this._createClearDiv());
                    tmpContainer.appendChild(
this._createColumn("ALT:"));
                    
var _2d = document.createElement("div");
                    _2d.className 
= "fragediterinput";
                    
var d2 = this._createInput();
                    d2.id 
= this.editorHandle.tagPrefix + "simple_img_alt";
                    d2.lineIdx 
= _idx;
                    d2.value 
= _el.firstChild.alt;
                    _2d.appendChild(d2);
                    tmpContainer.appendChild(_2d);
                    Event.observe(d2, 
"keyup"this.changeImgAlt.bindAsEventListener(this));
                    tmpContainer.appendChild(
this._createClearDiv());
                } 
else {
                    tmpContainer.appendChild(
this._createColumn("标题:"));
                    
var _1d = document.createElement("div");
                    _1d.className 
= "fragediterinput";
                    
var d1 = this._createInput();
                    d1.id 
= this.editorHandle.tagPrefix + "simple_title";
                    d1.lineIdx 
= _idx;
                    d1.value 
= _el.innerHTML;
                    
var r1 = document.createElement("a");
                    r1.innerText 
= "";
                    r1.style.color 
= "red";
                    r1.style.textDecoration 
= "none";
                    r1.href 
= "javascript:void(0)";
                    r1.title 
= "加红";
                    r1.onclick 
= function() {
                        d1.value 
= "<font color='red'>" + d1.value + "</font>";
                        
var _targetEl = this.lineElements[_idx];
                        _targetEl.innerHTML 
= d1.value;
                    }.bind(
this);
                    
var b1 = document.createElement("a");
                    b1.innerText 
= "B";
                    b1.style.fontWeight 
= "bold";
                    b1.style.textDecoration 
= "none";
                    b1.href 
= "javascript:void(0)";
                    b1.title 
= "加粗";
                    b1.onclick 
= function() {
                        d1.value 
= "<strong>" + d1.value + "</strong>";
                        
var _targetEl = this.lineElements[_idx];
                        _targetEl.innerHTML 
= d1.value;
                    }.bind(
this);
                    _1d.appendChild(d1);
                    _1d.appendChild(document.createTextNode(
" "));
                    _1d.appendChild(r1);
                    _1d.appendChild(document.createTextNode(
" "));
                    _1d.appendChild(b1);
                    tmpContainer.appendChild(_1d);
                    Event.observe(d1, 
"keyup"this.changeTitle.bindAsEventListener(this));
                };
                tmpContainer.appendChild(
this._createClearDiv());
                tmpContainer.appendChild(
this._createColumn("链接:"));
                
var _2d = document.createElement("div");
                _2d.className 
= "fragediterinput";
                
var d2 = this._createInput();
                d2.id 
= this.tagPrefix + "simple_links";
                d2.lineIdx 
= _idx;
                d2.value 
= _el.getAttribute("back_href");
                
var c1 = document.createElement("img");
                c1.src 
= "http://cms4.sohu.com/images/ico_newwin.gif";
                c1.title 
= "检查链接";
                c1.style.cursor 
= "pointer";
                c1.onclick 
= function() {
                    window.open(d2.value);
                }.bind(
this);
                _2d.appendChild(d2);
                _2d.appendChild(document.createTextNode(
" "));
                _2d.appendChild(c1);
                tmpContainer.appendChild(_2d);
                Event.observe(d2, 
"keyup"this.changeLinks.bindAsEventListener(this));
            } 
else if (/^(B|STRONG)/gi.test(_el.tagName)) {
                tmpContainer.appendChild(
this._createColumn("标题:"));
                
var _1d = document.createElement("div");
                _1d.className 
= "fragediterinput";
                
var d1 = this._createInput();
                d1.lineIdx 
= _idx;
                d1.value 
= _el.innerHTML;
                _1d.appendChild(d1);
                tmpContainer.appendChild(_1d);
                Event.observe(d1, 
"keyup"this.changeOther.bindAsEventListener(this));
            } 
else {
                
return;
            };
            
var _add = document.createElement("span");
            _add.className 
= "fragedit_simplecontainer_add";
            
var _add_img = document.createElement("img");
            _add_img.src 
= window.location.protocol + "//" + window.location.hostname + "/images/icn_large.gif";
            _add_img.title 
= "增加";
            _add.appendChild(_add_img);
            tmpContainer.appendChild(_add);
            Event.observe(_add, 
"click"this.addNode.bind(this, _idx, tmpContainer));
        };
        
var _del = document.createElement("span");
        _del.className 
= "fragedit_simplecontainer_add";
        
var _del_img = document.createElement("img");
        _del_img.src 
= window.location.protocol + "//" + window.location.hostname + "/images/icn_small.gif";
        _del_img.title 
= "删除";
        _del.appendChild(_del_img);
        tmpContainer.appendChild(_del);
        Event.observe(_del, 
"click"this.deleteNode.bind(this, _idx, tmpContainer));
        tmpContainer.appendChild(
this._createClearDiv());
        
return tmpContainer;
    },
    uploadPic: 
function(_form, _file, _target, _targetImg) {
        logger.debug(
"uploadpic fired!");
        
if (_file.value == "") alert("请选择文件");
        _form.action 
= window.location.protocol + "//" + window.location.hostname + "/uploadPicture.do?method=save&isfrageditor=true&targetid=" + _target.id;
        logger.debug(
"form action :" + _form.action);
        _form.target 
= "fragEditor_uploadpic";
        window.uploadpic_targetElement 
= _targetImg;
        _form.submit();
    },
    changeOther: 
function(_event) {
        
var _el = Event.element(_event);
        
var _targetEl = this.lineElements[_el.lineIdx];
        _targetEl.innerHTML 
= _el.value;
    },
    changeImgSrc: 
function(_event) {
        
var _el = Event.element(_event);
        
var _targetEl = this.lineElements[_el.lineIdx];
        _targetEl.firstChild.src 
= _el.value;
    },
    changeImgAlt: 
function(_event) {
        
var _el = Event.element(_event);
        
var _targetEl = this.lineElements[_el.lineIdx];
        _targetEl.firstChild.alt 
= _el.value;
    },
    deleteNode: 
function(_idx, _line_container) {
        logger.debug(
"deleteNode fired!");
        Element.remove(
this.lineElements[_idx]);
        
this.lineElements[_idx] = null;
        Element.remove(_line_container);
    },
    addNode: 
function(_under_idx, _under_element) {
        logger.debug(
"add node under :" + _under_idx);
        
var _textNode = document.createTextNode(" ");
        
var f_ref = this.lineElements[_under_idx];
        logger.debug(
"f_ref.parentNode outerhtml:" + f_ref.parentNode.outerHTML);
        CMSUtils.insertAfter(f_ref.parentNode, _textNode, f_ref);
        
var _ea = document.createElement("A");
        _ea.innerHTML 
= "sohu";
        _ea.setAttribute(
"back_href""http://www.sohu.com");
        _ea.setAttribute(
"href""javascript:void(0)");
        _ea.setAttribute(
"back_target""_blank");
        CMSUtils.insertAfter(_textNode.parentNode, _ea, _textNode);
        
this._initLineElements();
        
this.processToElement();
    },
    changeTextNode: 
function(_event) {
        
var _el = Event.element(_event);
        
var _targetEl = this.lineElements[_el.lineIdx];
        _targetEl.nodeValue 
= _el.value;
    },
    changeLinks: 
function(_event) {
        
var _el = Event.element(_event);
        
var _targetEl = this.lineElements[_el.lineIdx];
        _targetEl.setAttribute(
"back_href", _el.value);
    },
    changeTitle: 
function(_event) {
        
var _el = Event.element(_event);
        
var _targetEl = this.lineElements[_el.lineIdx];
        _targetEl.innerHTML 
= _el.value;
    },
    _createClearDiv: 
function() {
        
var d1 = document.createElement("div");
        d1.style.clear 
= "both";
        
return d1;
    },
    _createInput: 
function() {
        
var t = document.createElement("input");
        t.setAttribute(
"type""text");
        t.setAttribute(
"size""40");
        Event.observe(t, 
"focus",
        
function() {
            
this.select();
        }.bind(t));
        
return t;
    },
    _createColumn: 
function(_text) {
        
var d1 = document.createElement("div");
        d1.innerText 
= _text;
        d1.className 
= "frageditercolumn";
        
return d1;
    }
}


posted on 2012-01-09 19:18 邓华的碎碎念 阅读(1891) 评论(3)  编辑  收藏

Feedback

# re: 放个07年在搜狐CMS当初写的可视化编辑页面JS代码. 2012-01-10 07:19 牛蛙
晕死啊,这么长的JS,还没个注释 你怎么写得  回复  更多评论
  

# re: 放个07年在搜狐CMS当初写的可视化编辑页面JS代码. 2012-01-10 16:39 aisdf
太长了,实在看不下去。。
其实这种代码写个思路就OK了,懂的人自然懂, 不懂的人只会复制代码进去,反正也用不了!  回复  更多评论
  

# re: 放个07年在搜狐CMS当初写的可视化编辑页面JS代码.[未登录] 2012-01-11 09:09 tbw
看得有点晕 呵呵   回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: