/**
 * 大众版飞信最近联系人
 * 
 * @version 1.0.1 
 * @date 2015-03-20
 * @author gaohongfeipc@feinno.com
*/
if (!window.Fetion)
    window.Fetion = { "ui": { "CacheContact": {},"API":{} } };
function $(id){
		return document.getElementById(id);
}	
function htmlencode(s){  
    var div = document.createElement('div');  
    div.appendChild(document.createTextNode(s));  
    return div.innerHTML;  
} 
function byteLength(str){
	return str.replace(/[^x00-xFF]/g,'**').length;
}
function getStrByBtLength(str,length){
	var bytesCount = 0;
	var i = 0;
	if (str != null){
		for (i = 0; i < str.length&&bytesCount<=length-1; i++){
			var c = str.charAt(i);
			if (/^[\u0000-\u00ff]$/.test(c)){
				bytesCount += 1;
			}else{
				bytesCount += 2;
			}
		}
		return str.substring(0,i);
	}
	return ""; 
}
Fetion.ui.CacheContact = {
    mainPanel: $("list"),
	addCacheContact:function(data){
		this.delCacheContact(data.id);
		var title = data.title;
		var content = "";
		while(byteLength(title)>50){
			var tempStr = getStrByBtLength(title,50);
			content =content+tempStr+"\n";

			title = title.replace(tempStr,"");
		}
		content =content+title;
		var html = "<a title='"+htmlencode(content)+"'>"+htmlencode(data.content)+"</a>";
		if(this.mainPanel.childNodes.length>0){
			var line = document.createElement("li");
			line.className="line-bg";
			this.mainPanel.insertAdjacentElement("afterBegin", line);
		}
        var li = document.createElement("li");
		li.innerHTML= html;
		li.id = data.id;
		this.mainPanel.insertAdjacentElement("afterBegin", li);
		//this.mainPanel.appendChild(li);
		li.onclick=function(e){
			Fetion.ui.API.selectContact({id:this.id});
		}
		li.onselectstart=function(e){
			return false;
		}
	},
	delCacheContact:function(id){
		var o=$(id);
		if(o){
			o.parentElement.removeChild(o);
		}
	}

}

Fetion.ui.API = {
    /**
    /* 注册c++通知接口
    /**/
    register: function() {
        /**
        /* 最近联系人初始加载
        /**/
        SM.ajax('CacheContact', "load", "", "", function(status, outTxt, outJson) {
            if ((status == 200 || status == 188) && outJson != null) {//alert(JSON.stringify(outJson));
				Fetion.ui.CacheContact.mainPanel.innerHTML="";
                for (var i = 0; i < outJson.length; i++) {
                    Fetion.ui.CacheContact.addCacheContact(outJson[i]);
                }
            }
        });
        /**
        /* 添加最近联系人
        /**/
        SM.ajax('CacheContact', "addCacheContact", "", "", function(status, outTxt, outJson) {
            if ((status == 200 || status == 188) && outJson != null) {
                //alert("out="+JSON.stringify(outJson));
                Fetion.ui.CacheContact.addCacheContact(outJson);
            }
        });
    },
	/**
    /* 选中一组联系人
    /**/
    selectContact: function(params) {
        SM.exec('CacheContact', "selectContact", "", params);
    }
}
var loaded = false;
function AfterSMCompleted() {
if( !loaded )
    Fetion.ui.API.register(); //注册接口
loaded = true;
}