var CrEmote = Class.create();
CrEmote.prototype = {
    initialize: function(options){
        this.setOptions(options);
        this.build();
        this.initElements();
        this.initEvents();
        this.active();
    },
    setOptions: function(options){
        this.options = Object.extend({
            parent: document.body,
            matrix: {
                "20": [20, 3],
                "42": [12, 2]
            },
            output: 'ubb',
            callback: Prototype.emptyFunction,
            active: /*getCookie('emote') || */'base'
        }, options ||
        {});
        this.options.parent = $(this.options.parent);
    },
    build: function(){
        var data = CrEmote.Data;
        var arr = [];
        arr.push('<div class="emotionBox"><div class="emotionBar">');
        var tabK;
        for (tabK in data) {
            var tab = data[tabK];
            if (typeof(tab) != "object" || !tab.ubb) 
                continue;
            var img = CrEmote._getImg(tab.ubb, tabK);
            arr.push('<span eType="' + tab.type + '" data_key="' + tabK + '"><img align="absmiddle" src="' + img.url + '" alt="' + tab.alt + '" width="20" height="20" />&nbsp;' + tab.title + '</span>');
        }
        arr.push('</div><div style="clear:both;"></div><div class="basicEm"><div class="emotionBody"></div><div class="emotionNav"></div></div></div>');
        this.options.parent.innerHTML = arr.join('');
    },
    initElements: function(){
        this.tabCtr = $(this.options.parent.firstChild.firstChild);
        var tmpEl = this.tabCtr.nextSibling.nextSibling;
        this.bodyCtr = $(tmpEl.firstChild);
        this.pageCtr = $(tmpEl.lastChild);
    },
    initEvents: function(){
        Event.observe(this.tabCtr, 'mouseup', this.onTabCtr.bindAsEventListener(this));
        Event.observe(this.bodyCtr, 'mouseup', this.onBodyCtr.bindAsEventListener(this));
        Event.observe(this.bodyCtr, 'mouseover', this.showPreview.bindAsEventListener(this));
        Event.observe(this.bodyCtr, 'mouseout', this.hidePreview.bindAsEventListener(this));
        Event.observe(this.pageCtr, 'mouseup', this.onPageCtr.bindAsEventListener(this));
    },
    onTabCtr: function(e){
        var el = Event.element(e);
        if (el == this.tabCtr) 
            return false;
        do {
            if (el.parentNode && el.parentNode == this.tabCtr) 
                break;
        }
        while (el = el.parentNode)
        if (!el.className || el.className != "active") {
            this.options.active = el.getAttribute('data_key');
            this.bodyCtr.innerHTML = '加载中';
            this.pageCtr.innerHTML = '';
            this.active();
            /*setCookie('emote', this.options.active, 'never', '/', document.location.href.indexOf("blog.sohu.com") != -1 ? 'blog.sohu.com' : document.domain);
            if (this.options.stat) 
                CA.a('emotion_' + this.options.stat + '_' + this.options.active);
            */
        }
        Event.stop(e);
        return false;
    },
    showPreview: function(e){
        if (this.activeTab.getAttribute('eType') == 3) {
            if (!this.pLayer || !$('ePreLayer')) {
                $(this.bodyCtr).setStyle({
                    'position': 'relative'
                });
                this.pPos = Dom.getRect(this.bodyCtr);
                this.pLayer = $(document.createElement('div'));
                this.pLayer.setAttribute('id', 'ePreLayer');
                this.pLayer.setStyle({
                    'position': 'absolute',
                    'border': 'solid 1px #f00',
                    'width': '70px',
                    'height': '70px'
                });
                this.bodyCtr.appendChild(this.pLayer);
            }
            this.pLayer.setStyle({
                'left': '-85px',
                'top': '0px'
            });
            this.showPreIcon(e);
        }
    },
    showPreIcon: function(e){
        var el = Event.element(e);
        if (el == this.bodyCtr) 
            return false;
        do {
            if (el.parentNode && el.parentNode == this.bodyCtr) 
                break;
        }
        while (el = el.parentNode)
        var ubb = el.getAttribute("data_ubb");
        var path = this.options.active;
        if (ubb && path) {
            this.pLayer.innerHTML = '<img src="' + CrEmote._getImg(ubb, path).url + '" />';
            this.pLayer.show();
        }
    },
    hidePreview: function(e){
        if (this.pLayer) 
            this.pLayer.hide();
    },
    onBodyCtr: function(e){
        var el = Event.element(e);
        if (el == this.bodyCtr) 
            return false;
        do {
            if (el.parentNode && el.parentNode == this.bodyCtr) 
                break;
        }while (el = el.parentNode);
        var ubb = el.getAttribute("data_ubb"), ubbS = ubb;
        var path = el.getAttribute("data_path");
        if (ubb && path) {
            var more = '';
            if (this.options.output == 'url') {
                var obj = CrEmote._getImg(ubb, path);
                ubb = obj.url;
                more = obj.title;
            }
            else {
                if (path != "base") 
                    ubb = "{" + path + '}' + ubb;
                ubb = '[' + ubb + ']';
            }
            this.options.callback(ubb, more);
            /*
            if (this.options.stat) {
                CA.a('emotion_' + this.options.stat + '_' + path + '_' + (CrEmote.Ubbs[ubbS] && CrEmote.Ubbs[ubbS][0]));
            }*/
        }
        Event.stop(e);
        return false;
    },
    onPageCtr: function(e){
        var el = Event.element(e);
        if (el == this.pageCtr) 
            return false;
        do {
            if (el.parentNode && el.parentNode == this.pageCtr) 
                break;
        }
        while (el = el.parentNode)
        var page = el.getAttribute("data_page");
        if (page) {
            this.page(parseInt(page));
        }
        Event.stop(e);
        return false;
    },
    active: function(){
        var childs = this.tabCtr.childNodes;
        for (var i = 0; i < childs.length; i++) {
            if (childs[i].getAttribute('data_key') == this.options.active) {
                childs[i].className = 'active';
                this.activeTab = childs[i];
            }
            else {
                childs[i].className = '';
            }
        }
        this.page();
    },
    page: function(index){
        if (typeof(index) != 'number') 
            index = 1;
        var active = this.options.active, emoteObj = CrEmote.Data[active], ubbs = emoteObj.data;
        var matrix = this.options.matrix[emoteObj.size], cols = matrix[0], rows = matrix[1];
        if (this.options.output != 'url') 
            rows = Math.ceil(emoteObj.data.length / cols);
        var size = cols * rows, start = (index - 1) * size, count = ubbs.length, end = Math.min(count, index * size), pageCount = Math.ceil(count / size);
        var arr = [];
        
        var path = CrEmote.Config.subPath[1];
        if (emoteObj.thumb) 
            path = emoteObj.thumb;
		/*
        if(active == 's'){
        	this.bodyCtr.removeClassName('big_emotions');
	        for (var i = start; i < end; i++) {
	            if (i != 0 && i % cols == 0) 
	                arr.push('<div style="clear:both;"></div>');
	            if (emoteObj) 
	                var imgObj = CrEmote._getImg(ubbs[i], path);
	            arr.push('<a onclick="return false;" href="javascript:void(0);" data_ubb="' + ubbs[i].replace('"', '\\"') + '" data_path="' + path + '"><img src="' + imgObj.url + '" alt="' + imgObj.title + '" title="' + imgObj.title + '" height="'+ emoteObj.size + '" width="'+ emoteObj.size + '"/></a>');
	        }
	      } else {
	      	this.bodyCtr.addClassName(emoteObj.className);
	      	//arr.push('<div class="big_emotions">')
	      	for (var i = start; i < end; i++) {
	            if (i != 0 && i % cols == 0) 
	                arr.push('<div style="clear:both;"></div>');
	            if (emoteObj) 
	                var imgObj = CrEmote._getImg(ubbs[i], path);
	            arr.push('<a onclick="return false;" href="javascript:void(0);" data_ubb="' + ubbs[i].replace('"', '\\"') + '" data_path="' + path + '"><div src="' + imgObj.url + '" alt="' + imgObj.title + '" title="' + imgObj.title + '" class="emotion_size_'+emoteObj.size+'" ></div></a>');
	        }
	      	//arr.push('</div>');
	      }*/
		this.bodyCtr.className = 'emotionBody';
		this.bodyCtr.addClassName(emoteObj.className);
        //arr.push('<div class="big_emotions">')
        for (var i = start; i < end; i++) {
             if (i != 0 && i % cols == 0) 
                arr.push('<div style="clear:both;"></div>');
             if (emoteObj) 
                var imgObj = CrEmote._getImg(ubbs[i], path);
                arr.push('<a onclick="return false;" href="javascript:void(0);" data_ubb="' + ubbs[i].replace('"', '\\"') + '" data_path="' + path + '"><div src="' + imgObj.url + '" alt="' + imgObj.title + '" title="' + imgObj.title + '" class="emotion_size_'+emoteObj.size+'" ></div></a>');
        }
        this.bodyCtr.innerHTML = arr.join('');
        arr = [];
        if (pageCount > 1) {
            arr.push(index + '/' + pageCount + '&nbsp;&nbsp;&nbsp;&nbsp;');
            if (index > 1) {
                arr.push('<a href="javascript:void(0);" data_page="' + (index - 1) + '">');
            }
            arr.push('上一页');
            if (index > 1) {
                arr.push('</a>');
            }
            arr.push('&nbsp;&nbsp;&nbsp;&nbsp;');
            if (index < pageCount) {
                arr.push('<a href="javascript:void(0);" data_page="' + (index + 1) + '">');
            }
            arr.push('下一页');
            if (index < pageCount) {
                arr.push('</a>');
            }
        }
        this.pageCtr.innerHTML = arr.join('');
    }
}
CrEmote.Config = {
    //imgPath: 'http://js3.pp.sohu.com.cn/ppp/images/emotion/'
    imgPath: 'http://images.chinaren.com/',
    subPath: ['','cs/sms/crm/em/','product/aluclub/images/em/']
}
CrEmote.Data = {
    base: {
        title: '大表情',
        ubb: 'R01',
        alt: '大表情',
        size: '20',
		className: 'big_emotions',
        type: 1,
        data: ["R01", "R02","R03","R04","R05","R06","R07","R08","R09","R10","R11","R12","R13","R14","R15","R16","R17","R18","R19","R20","R21","R22","R23","R24","R25","R26","R27","R28","R29","R30","R31","R32","R33","R34","R35","R36","R37","R38","R39","R40","R41","R42","R43","R44","R45","R46","R47","R48","R49","blank","em65","em66","em67","em68","em69","em70","em71","em72","em73","em74"]    
    },
	
    s: {
        title: '小表情',
        ubb: ':)',
        alt: '小表情',
        size: '20',
		className: 'tiny_emotions',
        type: 2,
		//thumb: 'b/t',
        data: [":)", "#_#", ":D", ":-)", ":P", "B_)", "^_*", ":$", ":|", ":.(", ":_(", "):(", ":V", "*_*", ":^", ":?", ":!", "=:|", ":%", ":O", ":X", "|-)", ":Z", ":9", ":T", ":-*", "*_/", ":#|", ":69", "//shuang", "//qiang", "//ku", "//zan", "//heart", "//break", "//F", "//W", "//mail", "//strong", "//weak", "//share", "//phone", "//kiss", "//V", "//sun", "//moon", "//star", "(!)", "//TV", "//clock", "//gift", "//cash", "//coffee", "//rice", "//watermelon", "//tomato", "//pill", "//pig", "//football", "//shit"]
    }
    /* XXX,
    b: {
        title: '柏夫',
        ubb: 'T[:.(]',
        alt: '柏夫表情',
        size: '42',
        type: 3,
        thumb: 'b/t',
        data: ["hi", "ok", "fco", ":T", ":D", "):(", ":!", "bet", "ft", "gdn", "#_#", "=:|", "sof", ":.(", "nob", "glw", "thd", "pas", ":?", "mop", "b4", "^_*", ":(", "up", "agi", "soy", "stg", "bj", "cmp", "bdn", "fbi", "skt", "wuy", "olc"]
    }
    */
}
CrEmote.Ubbs = {
    ":)": ["em01", "微笑" ,1],
    "#_#": ["em02", "谄媚",1],
    "8*)": ["em03", "偷笑",1],
    ":D": ["em04", "大笑" ,1],
    ":-)": ["em05", "害羞",1],
    ":P": ["em06", "调皮" ,1],
    "B_)": ["em07", "得意",1],
    "B_I": ["em08", "耍酷",1],
    "^_*": ["em09", "讽刺",1],
    ":$": ["em10", "委屈" ,1],
    ":|": ["em11", "郁闷" ,1],
    ":(": ["em12", "难过" ,1],
    ":.(": ["em13", "泪奔",1],
    ":_(": ["em14", "大哭",1],
    "):(": ["em15", "发火",1],
    ":V": ["em16", "咒骂" ,1],
    "*_*": ["em17", "发呆",1],
    ":^": ["em18", "不懂" ,1],
    ":?": ["em19", "疑惑" ,1],
    ":!": ["em20", "吃惊" ,1],
    "=:|": ["em21", "流汗",1],
    ":%": ["em22", "尴尬" ,1],
    ":O": ["em23", "惊恐" ,1],
    ":X": ["em24", "闭嘴" ,1],
    "|-)": ["em25", "犯困",1],
    ":Z": ["em26", "睡觉" ,1],
    ":9": ["em27", "馋"   ,1],
    ":T": ["em28", "吐"   ,1],
    ":-*": ["em29", "耳语",1],
    "*_/": ["em30", "海盗",1],
    ":#|": ["em31", "重伤",1],
    ":69": ["em32", "拥抱" ,1],
    "//shuang": ["em33", "爽",1],
    "//qiang": ["em34", "强" ,1],
    "//ku": ["em35", "酷"    ,1],
    "//zan": ["em36", "赞"   ,1],
    "//heart": ["em37", "红心",1],
    "//break": ["em38", "心碎",1],
    "//F": ["em39", "花开"   ,1],
    "//W": ["em40", "花谢"   ,1],
    "//mail": ["em41", "邮件",1],
    "//strong": ["em42", "手势-棒",1],
    "//weak": ["em43", "手势-逊",1],
    "//share": ["em44", "握手",1],
    "//phone": ["em45", "电话",1],
    "//mobile": ["em46", "手机",1],
    "//kiss": ["em47", "嘴唇" ,1],
    "//V": ["em48", "V"       ,1],
    "//sun": ["em49", "太阳"  ,1],
    "//moon": ["em50", "月亮" ,1],
    "//star": ["em51", "星星" ,1],
    "(!)": ["em52", "灯泡"    ,1],
    "//TV": ["em53", "电视"   ,1],
    "//clock": ["em54", "闹钟",1],
    "//gift": ["em55", "礼物" ,1],
    "//cash": ["em56", "现金" ,1],
    "//coffee": ["em57", "咖啡",1],
    "//rice": ["em58", "饭"   ,1],
    "//watermelon": ["em59", "西瓜",1],
    "//tomato": ["em60", "番茄",1],
    "//pill": ["em61", "药丸" ,1],
    "//pig": ["em62", "猪头"  ,1],	
    "//football": ["em63", "足球",1],
   	"//shit": ["em64", "便便" ,1],
   	
    "em65": ["em65", ""		,1],
    "em66": ["em66", ""		,1],
    "em67": ["em67", ""		,1],
    "em68": ["em68", ""		,1],
    "em69": ["em69", ""		,1],
    "em70": ["em70", ""		,1],
    "em71": ["em71", ""		,1],
    "em72": ["em72", ""		,1],
    "em73": ["em73", ""   		,1],
    "em74": ["em74", ""		,1],
    "R01": ["R01", ""     ,2],
    "R02": ["R02", ""     ,2],
    "R03": ["R03", ""     ,2],
    "R04": ["R04", ""     ,2],
    "R05": ["R05", ""     ,2],
    "R06": ["R06", ""     ,2],
    "R07": ["R07", ""     ,2],
    "R08": ["R08", ""     ,2],
    "R09": ["R09", ""     ,2],
    "R10": ["R10", ""     ,2],
    "R11": ["R11", ""     ,2],
    "R12": ["R12", ""     ,2],
    "R13": ["R13", ""        ,2],
    "R14": ["R14", "" ,2],
    "R15": ["R15", ""      ,2],
    "R16": ["R16", ""     ,2],
    "R17": ["R17", ""     ,2],
    "R18": ["R18", "" ,2],
    "R19": ["R19", ""     ,2],
    "R20": ["R20", ""        ,2],
    "R21": ["R21", ""     ,2],
    "R22": ["R22", ""        ,2],
    "R23": ["R23", ""     ,2],
    "R24": ["R24", "" ,2],
    "R25": ["R25", ""     ,2],
    "R26": ["R26", ""   ,2],
    "R27": ["R27", ""     ,2],
    "R28": ["R28", "" ,2],
    "R29": ["R29", "",2],
    "R30": ["R30", ""     ,2],
    "R31": ["R31", ""     ,2],
    "R32": ["R32", ""   ,2],
    "R33": ["R33", ""     ,2],
    "R34": ["R34", ""   ,2],
    "R35": ["R35", "" ,2],
    R36:   ["R36", ""      ,2],     
    R37:   ["R37", ""      ,2], 
    R38:   ["R38", ""      ,2],
    R39:   ["R39", ""      ,2], 
		R40:   ["R40", ""      ,2],
		R41:   ["R41", ""      ,2], 
		R42:   ["R42", ""      ,2], 
		R43:   ["R43", ""      ,2],  
		R44:   ["R44", ""      ,2], 
		R45:   ["R45", ""      ,2], 
		R46:   ["R46", ""      ,2], 
		R47:   ["R47", ""      ,2], 
		R48:   ["R48", ""      ,2],
		R49:   ["R49", ""      ,2],
		blank:   ["blank", ""      ,2]	
    /* XXX,
    */
}
CrEmote.getImg = function(ubb){
    if (!ubb || ubb.length < 3 || ubb.charAt(0) != '[' || ubb.charAt(ubb.length - 1) != ']') 
        return null;
    var start = 1, end = ubb.length - 1;//, path = 'base';
    var path = CrEmote.Config.subPath1;
    /*
    if (ubb.charAt(1) == '{') {
        var index = ubb.indexOf('}', 1);
        if (index < 3) 
            return null;
        start = index + 1;
        path = ubb.substring(2, index);
    }
    */
    ubb = ubb.substring(start, end); 
    return this._getImg(ubb, path);
}
CrEmote.getUbb = function(url){
    if (url.indexOf(this.Config.imgPath) != 0) 
        return null;
    var start = this.Config.imgPath.length;
    var end = url.indexOf('/', start);
    if (end < 0) 
        return null;
    var path = url.substring(start, end);
    start = end + 1, end = url.indexOf('.', start);
    if (end < 0) 
        return null;
    var ubb = url.substring(start, end);
    if (path != 'base') {
        ubb = '{' + path + '}' + ubb;
    }
    return '[' + ubb + ']';
}
CrEmote._getImg = function(ubb,path){
    var item = this.Ubbs[ubb];
	if(!item) console.log('ubb:' +ubb + ' path:'+ path)
		var subPath = item[2] ? CrEmote.Config.subPath[item[2]] : path;
    return {
        url: ubb=='blank' ? '' : this.Config.imgPath + subPath + item[0] + '.gif',
        title: item[1]
    }
}
CrEmote.init = function(options){
    return new CrEmote(options);
}
