if (!window.external) {
    window.external = {};
}
if (!window.isChrome) {
    window.isChrome = {};
}
var messageIds = "";
var curMsgId = "";

var funType = 1;            //1联系人 2群组 3短信 4系统 5工具
var contactMessage = "";    //联系人聊天记录
var groupMessage = "";      //群组聊天记录
var smsMessage = "";        //短信聊天记录
var tagMessage = "";		//消息标记记录

var contactList = "";       //联系人列表
var groupList = "";         //群列表
var contactGroupList = "";  //好友分组
var tagList = "";		//联系人列表
var ownerInfo = "";         //本人基本信息
var contactID = "";         //联系人的UID
var contactGroupID = "";      //联系人所在的组
var groupID = "";           //群组ID
var groupType = "";         //GroupMsg和DisGroupMsg及SMSGroupMsg拇指群
var privateMsg = "PrivateMsg";
var groupMsg = "GroupMsg";
var disGroupMsg = "DisGroupMsg";
var smsGroupMsg = "SmsGroupMsg";
var myArray = "";           //消息内容json数组
var pageIndex = 0;          //第几页
var totalPage = 0;          //总页数
var smsType = 0;    //0:发给自己的短信 1：发给别人的短信
var curTagType = "tag_id_all";    //当前标记类型
var isSearch = false; //是否是查询
var searchFunType = 1;
var timeCalendarList = null;    //当前聊天记录的所有时间
var searchKey = "";
var selfSmsCount = 0; //发给自己的短信条数
var otherSmsCount = 0; //发给别人的短信条数
var freeSmsCount = 0; //免费短信条数
var calendarClickFlag = false;
var isDirectShowContact = false; //是否直接显示某人的信息
var showSetDate = false; //日历与当前显示记录的最大时间关联
var isfocusOnRoam = false; //焦点是否在云记录上
var isSearchGoTo = false;
var isCM = 1;           // 是否CM用户 判断是否显示拇指群
window.queryTime = ""; //按日期查询的日期

var killWords = "`1234567890-=~!#$^&*()_+qertyuiop[]\\ERTYUIOP{}|asdfghjkl;'ASDFGHJKL:\"zxcvbn,./ZXCVBN?";
function KillWords(str, count) {
    return GetStr(str, 8, count);
}
function htmlencode(s){  
    var div = document.createElement('div');  
    div.appendChild(document.createTextNode(s));  
    return div.innerHTML;  
}
function GetStr(str, maxLen, count) {
    if (str.length <= maxLen) {
        return str.replace(/</g, "&lt");
    }
    var start = 0;
    var len = maxLen * 2;
    var index = 0;
    var small = 0;
    var frontCount = 0;
    for (var i = 0; i < str.length; i++) {
        if (killWords.indexOf(str[i]) >= 0) {
            start++;
            small++;
            if (i < maxLen) {
                frontCount++;
            }
        } else {
            start += 2;
        }
        if (start == len || start == len - 1) {
            index = i + 1;
        }
    }

    if (start < len - 4) {
        return str.replace(/</g, "&lt");
    }

    index = index - parseInt(frontCount * 2 / 3);
    str = str.substring(0, index < maxLen ? maxLen : index);
    return str.replace(/</g, "&lt") + "...";
}


//json对象
function JsonObj() { }
JsonObj.prototype.X = 0;
JsonObj.prototype.Y = 0;
JsonObj.prototype.Content = "";
JsonObj.prototype.ContentValue = "";
JsonObj.prototype.btType = 0;
JsonObj.prototype.pageIndex = 0;
JsonObj.prototype.showMsg = 0;
JsonObj.prototype.ID = "";
JsonObj.prototype.msgId = [];
JsonObj.prototype.imgType = "";
JsonObj.prototype.isRoam = 0; //0不是漫游，1漫游
JsonObj.prototype.userId = ""; //联系人或是群组ID
JsonObj.prototype.isShowCopy = 1; //是否显示复制选项
JsonObj.prototype.isShowDelete = 1;
JsonObj.prototype.ToJson = function() {
    return {
        ID: this.ID,
        X: this.X,
        Y: this.Y,
        Content: this.Content,
        ContentValue: this.ContentValue,
        btType: this.btType,
        pageIndex: this.pageIndex,
        showMsg: this.showMsg,
        imgType: this.imgType,
        isRoam: this.isRoam,
        isShowCopy: this.isShowCopy,
        isShowDelete: this.isShowDelete,
        userId: this.userId
    }
}


//后退对象
function BackObj() { }
BackObj.prototype.step = 0; //0不可以后退 1后退到搜索前 2后退到搜索
BackObj.prototype.funType = 0;
BackObj.prototype.pageIndex1 = 0;
BackObj.prototype.pageIndex2 = 0;
BackObj.prototype.curId = "";
BackObj.prototype.contactGroupId = "";

BackObj.prototype.key = "";
BackObj.prototype.searchRange = "";
BackObj.prototype.timeType = "";
BackObj.prototype.searchType = "";

BackObj.prototype.Reset = function() {
    this.step = 0;
    this.funType = 0;
}

//前进一步
BackObj.prototype.AddStep = function() {
    this.step++;
    this.pageIndex2 = pageIndex;
}

//保存数据
BackObj.prototype.SaveCurrentInfo = function() {
    this.step = 1;
    this.funType = funType;
    this.pageIndex1 = pageIndex;
    if (funType == 1) {
        this.curId = contactID;
        this.contactGroupId = contactGroupID;
    } else if (funType == 2) {
        this.curId = groupID;
    } else if (funType == 3) {
        this.curId = smsType;
    }
    this.key = $("#txtKey").val();
    var range = $("#txtSearchRange");
    this.searchRange = range.attr("realVal") + "|" + range.attr("btType") + "|" + range.val();
    var tType = $("#txtSearchTime");
    this.timeType = tType.attr("realVal") + "|" + tType.val();
    var sType = $("#txtSearchType");
    this.searchType = sType.attr("realVal") + "|" + sType.val();
}

//后退一步
BackObj.prototype.BackStep = function() {
    this.step--;
    if (this.step == 0) {//返回到搜索前的状态
        funType = this.funType;
        $("#ulTopMenu li").removeClass("on");
        $("#ulTopMenu li").eq(funType - 1).addClass("on");
        pageIndex = this.pageIndex1;
        if (funType == 1) {
            ShowContactMenu();
            ShowContactMessage($("#div" + this.curId + this.contactGroupId), pageIndex);
        } else if (funType == 2) {
            ShowGroupMenu();
            var gId = GetgId(this.curId);
            ShowGroupMessage($("#div" + gId), pageIndex);
        } else if (funType == 3) {
            ShowSmsMenu();
            ShowSmsMessage(parseInt(this.curId), pageIndex);
        }	else if(funType == 6){
			ShowTagMenu(ShowTagMessage,$("#"+curTagType),pageIndex);
			//ShowTagMessage($("#"+curTagType), pageIndex);
		}
    } else if (this.step == 1) {//返回到搜索的状态
        $("#txtKey").val(this.key);
        $("#selSearchRange li").removeClass("p_on");
        var range = this.searchRange.split('|');
        $("#txtSearchRange").attr("realVal", range[0]);
        $("#txtSearchRange").attr("btType", range[1]);
        $("#txtSearchRange").val(range[2]);
        $("#selSearchRange li").each(function() {
            if ($(this).attr("realVal") == range[0]) {
                $(this).addClass("p_on");
            }
        })

        var tType = this.timeType.split('|');
        $("#txtSearchTime").attr("realVal", tType[0]);
        $("#txtSearchTime").val(tType[1]);
        $("#selSearchTime li").removeClass("p_on");
        $("#selSearchTime li").each(function() {
            if ($(this).attr("realVal") == tType[0]) {
                $(this).addClass("p_on");
            }
        })

        var sType = this.searchType.split('|');
        $("#txtSearchType").attr("realVal", sType[0]);
        $("#txtSearchType").val(sType[1]);
        $("#selSearchType li").removeClass("p_on");
        $("#selSearchType li").each(function() {
            if ($(this).attr("realVal") == sType[0]) {
                $(this).addClass("p_on");
            }
        })
        SearchMsg(this.pageIndex2);
    }
    if (this.step <= 0) {
        $("#divCalendar").show();
        $("#divBack").hide();
    }
}
var backObj = new BackObj();

//查询联系人漫游记录参数
function GetConatctRoamingMsg() { }
GetConatctRoamingMsg.prototype.peerId = "";
GetConatctRoamingMsg.prototype.peerUri = "";
GetConatctRoamingMsg.prototype.msgType = "0";
GetConatctRoamingMsg.prototype.contentType = "0";
GetConatctRoamingMsg.prototype.searchType = "";
GetConatctRoamingMsg.prototype.pageIndex = 0;
GetConatctRoamingMsg.prototype.pageSize = 30;
GetConatctRoamingMsg.prototype.smsCode = "";
GetConatctRoamingMsg.prototype.startTime = "";
GetConatctRoamingMsg.prototype.endTime = "";
GetConatctRoamingMsg.prototype.ToJson = function() {
    return {
        peerId: this.peerId,
        peerUri: this.peerUri,
        msgType: this.msgType,
        contentType: this.contentType,
        searchType: this.searchType,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        smsCode: this.smsCode,
        startTime: this.startTime,
        endTime: this.endTime
    };
}
////高红飞 20141114 start

liMore.onclick = function(e) {
    if (window.event.button != 0)	//只处理左键
        return;

    var p = mousePosition(window.event, null);
    var jsonObj = new JsonObj();
	jsonObj.X = 400;
    jsonObj.Y = 33;
    jsonObj.Content = "系统更多";
    //jsonObj.btType = 4;
    SMAjax(4, "ShowMenu", "", jsonObj.ToJson());
    window.event.returnValue = false;
    //AjaxRequest(4, "import", "", {}, function(status, outTxt, outJson) {
    //});
}
////高红飞 20141114 end
liTag.onclick=function(e){
	curTagType = "tag_id_all";
	TagClick();
}
//searchType 0：分页查询，1日期控件查询聊天记录
function CreateGetConatctRoamingMsg(searchType, pageIndex) {
    var roamMsg = new GetConatctRoamingMsg();
    roamMsg.pageIndex = pageIndex;
    roamMsg.searchType = searchType;
    roamMsg.peerId = contactID;
    for (var j = 0; j < contactList.length; j++) {
        if (contactList[j].uid == contactID) {
            roamMsg.peerUri = contactList[j].uri;
            break;
        }
    }
    if (searchType == "1") {
        var time1 = $("#txtTime").val();
        if (time1 != null && time1 != "") {
            roamMsg.startTime = time1 + " 00:00:00";
            roamMsg.endTime = time1 + " 23:59:59";
        }
    }
    return roamMsg;
}

//查询联系人漫游记录参数
function GetGroupRoamingMsg() { }
GetGroupRoamingMsg.prototype.groupUri = "";
GetGroupRoamingMsg.prototype.searchType = "";
GetGroupRoamingMsg.prototype.pageIndex = 0;
GetGroupRoamingMsg.prototype.pageSize = 30;
GetGroupRoamingMsg.prototype.smsCode = "";
GetGroupRoamingMsg.prototype.startTime = "";
GetGroupRoamingMsg.prototype.endTime = "";
GetGroupRoamingMsg.prototype.ToJson = function() {
    return {
        groupUri: this.groupUri,
        searchType: this.searchType,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        smsCode: this.smsCode,
        startTime: this.startTime,
        endTime: this.endTime
    };
}

//searchType 0：分页查询，1日期控件查询聊天记录
function CreateGetGroupRoamingMsg(searchType, pageIndex) {
    var roamMsg = new GetGroupRoamingMsg();
    roamMsg.pageIndex = pageIndex;
    roamMsg.searchType = searchType;
    roamMsg.groupUri = groupID;
    if (searchType == "1") {
        var time1 = $("#txtTime").val();
        if (time1 != null && time1 != "") {
            roamMsg.startTime = time1 + " 00:00:00";
            roamMsg.endTime = time1 + " 23:59:59";
        }
    }
    return roamMsg;
}


String.prototype.replaceAll = function(s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
};
String.prototype.Trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}


//显示联系人聊天记录
function ShowContactMessage(me, pageIndex) {
    if (contactList.length == 0) {//没有联系人
        return;
    }

    isSearch = false;
    var btType = $(me).attr("btType");
    $("#divMenu dl").find("dd").removeClass("show");
    if (btType == "32") {
        $(me).next().addClass("show");
    } else {
        $(me).addClass("show");
    }
    contactID = $(me).attr("userId");
    ShowCurItem(me);
    ShowUpTip();
    ShowTip(contactID, 1);
    ShowLoading();
    var isShowRoam = ("9999980" != $(me).attr("groupId")&&"9999999"!=$(me).attr("groupId")) ? true : false; //公众好友或者已删除联系人不显示漫游
    FocusOnLocalOrRoam(true, isShowRoam);
    window.searchMsgID = null;
    if (contactID != null && contactID != "") {
        contactGroupID = $(me).attr("groupId");
        var jsonObj = new JsonObj();
        jsonObj.pageIndex = pageIndex;

        jsonObj.Content = "type:" + privateMsg + ";userId:" + contactID + ";groupId:" + $(me).attr("groupId");

        AjaxRequest(funType, "QueryHistoryMessage", contactID, jsonObj.ToJson(), function(Status, txt, outJson) {
            ShowMessage(outJson);
        })
        ChangeSearchRange(contactID + contactGroupID);
    } else {
        ShowMessage(null);
    }
}

//显示联系人左侧菜单
function ShowContactMenu() {
    if (!isDirectShowContact) {
        contactID = "";
    }

    $("#divMenu").empty();
    for (var i = 0; i < contactGroupList.length; i++) {
        var menuStr = "";
        contactGroupList[i].count = 0; //统计每个组下面的人数
        for (var j = 0; j < contactList.length; j++) {
            if ((";" + contactList[j].gs + ";").indexOf(";" + contactGroupList[i].id + ";") >= 0) {
                contactGroupList[i].count++;
            }
        }
        var firstUid = "";
        for (var j = 0; j < contactList.length; j++) {
            if ((";" + contactList[j].gs + ";").indexOf(";" + contactGroupList[i].id + ";") >= 0) {
                firstUid = contactList[j].uid;
                break;
            }
        }
        if (contactID == "") {
            contactID = firstUid;
            contactGroupID = contactGroupList[i].id;
        }
        var menuTitle = KillWords(contactGroupList[i].n, contactGroupList[i].count);
        menuStr += "<dl id='div" + contactGroupList[i].id + i + "'><dt type='" + privateMsg + "' t='GroupMsg' btType='32' onclick=\"ClickMenuShowMessage(this,0);\" userId='" + firstUid + "' onMouseup='ShowLeftMenuRightMenu(this)' groupId='" + contactGroupList[i].id + "'><a><span class='arrow_2'></span><span title='" + contactGroupList[i].n + "'>" + menuTitle + "</span><span class='num'>[" + contactGroupList[i].count + "]</span></a></dt>";
        for (var j = 0; j < contactList.length; j++) {
            if ((";" + contactList[j].gs + ";").indexOf(";" + contactGroupList[i].id + ";") >= 0) {
                menuStr += "<dd id='div" + contactList[j].uid + contactGroupList[i].id + "' type='" + privateMsg + "' btType='64' onclick=\"ClickMenuShowMessage(this,0);\" ondblclick='ShowChatDialog(this)' onMouseup='ShowLeftMenuRightMenu(this)' userId='" + contactList[j].uid + "' groupId='" + contactGroupList[i].id + "'><a><img src='" + contactList[j].img + "' alt='' class='per_icon'/><span title='" + contactList[j].n + "'>" + KillWords(contactList[j].n, 100) + "</span></a></dd>";
            }
        }
        menuStr += "</dl>";
        $("#divMenu").append(menuStr);
    }
    $("#divMenu").find("dd").hide();
    $("#divMenu").find("dt").removeClass("over");
}

//点击联系人
function ContactClick(me, pIndex) {
    //    SelectTopMenuItem(me);
    //    funType = 1;
    //    pageIndex = pIndex;
    //    ShowContactMenu();
    //    ClickMenuShowMessage($("#div" + contactID + contactGroupID), pageIndex);
	$(".search_pane").show();
    SelectTopMenuItem(me);
    funType = 1;
    pageIndex = pIndex;
    ShowContactMenu();
    ClickMenuShowMessage($("#div" + contactID + contactGroupID), pageIndex);    //定位到此联系人
    if (isDirectShowContact) {
        var top = $("#div" + contactID + contactGroupID).offset().top;
        $("#divMenu").scrollTop(top - 45);
    }
}

//顶部菜单显示当前项
function SelectTopMenuItem(me) {
    $("#ulTopMenu li").removeClass("on");
    $(me).addClass("on");
}

function ShowCurItem(me) {
    if ($(me).attr("btType") == "32") {
        if ($(me).parent().find("dd").is(":hidden")) {
            $(me).parent().find("dt").addClass("over");
            $(me).parent().find("dd").show();
            $(me).addClass("show");
        } else {
            $(me).parent().find("dt").removeClass("over");
            $(me).parent().find("dd").hide();
        }
    } else {
        $("#divMenu").find("dt").removeClass("over");
        $("#divMenu").find("dd").removeClass("show");
        $(me).parent().find("dt").addClass("over");
        $(me).parent().find("dd").show();
        $(me).addClass("show");
    }
}

function ShowGroupMessageById() {
    var gId = GetgId(groupID);
	var me = $("#div" + gId);
	if($(me).html()==null){
		me = document.getElementById("div"+gId);
	}
    ClickMenuShowMessage(me, pageIndex);
}

//显示群组聊天记录
function ShowGroupMessage(me, pageIndex) {
    isSearch = false;
	ShowUpTip();
    var btType = $(me).attr("btType");
    $("#divMenu dl").find("dd").removeClass("show");
    if (btType == "32") {
        $(me).next().addClass("show");
    } else {
        $(me).addClass("show");
    }
    ShowCurItem(me);
    ShowLoading();
    //FocusOnLocalOrRoam(true, true);
    window.searchMsgID = null;
    groupID = $(me).attr("groupId");
	var type = $(me).attr("type");
    // groupType = groupID.indexOf("sip:PG") >= 0 ? groupMsg : disGroupMsg;
    if (groupID.indexOf("sip:PG") >= 0) {
		if(type=="exitGroupMsg"){
			groupType = "exitGroupMsg";
		}else{
			groupType = groupMsg;
		}
    }
    else if (groupID.indexOf("sip:DG") >= 0) {
        if(type=="exitDisGroupMsg"){
			groupType = "exitDisGroupMsg";
		}else{
			groupType = disGroupMsg;
		}
    }
    else if (groupID.indexOf("sip:SG") >= 0) {
        groupType = smsGroupMsg;
    }
    ShowTip(groupID, 2);
    groupType = $(me).attr("type");
    ChangeSearchRange($(me).attr("groupId"));
    if (smsGroupMsg == groupType||"exitGroupMsg"==groupType||"exitDisGroupMsg"==groupType) {
        ;
        FocusOnLocalOrRoam(true, false);
    } else {
        FocusOnLocalOrRoam(true, true);
    }
    var responseCount = 0;
    var jsonObj = new JsonObj();
    jsonObj.pageIndex = pageIndex;


    jsonObj.Content = "type:" + groupType + ";userId:'';groupId:" + groupID;
    AjaxRequest(funType, "QueryHistoryMessage", "", jsonObj.ToJson(), function(Status, txt, outJson) {
        ShowMessage(outJson);
    })
}

//显示群组左侧菜单
function ShowGroupMenu() {
    if (groupList == null || groupList == "" || groupList.length == 0) {
        var menuStr = "<dl><dt><a><span class='arrow_2'></span>我的飞信群<span class='num'>[0]</span></a></dt></dl>";
        menuStr += "<dl><dt><a><span class='arrow_2'></span>我的讨论组<span class='num'>[0]</span></a></dt></dl>";
		menuStr += "<dl><dt><a><span class='arrow_2'></span>已退出的群<span class='num'>[0]</span></a></dt></dl>";
		menuStr += "<dl><dt><a><span class='arrow_2'></span>已退出的讨论组<span class='num'>[0]</span></a></dt></dl>";
        if (isCM == 1) {
            menuStr += "<dl><dt><a><span class='arrow_2'></span>我的拇指群<span class='num'>[0]</span></a></dt></dl>";
        }
        $("#divMenu").empty();
        $("#divMenu").append(menuStr);
        ShowMessage(null);
        ShowTip(null, 0);
        return;
    }
    var pgStr = "";
    var dgStr = "";
	var exitPgStr = "";
    var exitDgStr = "";
    var sgStr = "";
    var pgCount = 0;
    var dgCount = 0;
	var exitPgCount = 0;
    var exitDgCount = 0;
    var sgCount = 0;
    var firstGroup = "";
    var firstDisGroup = "";
	var exitFirstGroup = "";
    var exitFirstDisGroup = "";
    var firstSmsGroup = "";
    if (isDirectShowContact) {
        isDirectShowContact = false;
    } else {
        groupID = "";
    }
    for (var i = 0; i < groupList.length; i++) {
        if (firstGroup == "" && groupList[i].uri.indexOf("sip:PG") >= 0&&groupList[i].valid==1) {
            firstGroup = groupList[i].uri;
        } else if (exitFirstGroup == "" && groupList[i].uri.indexOf("sip:PG") >= 0&&groupList[i].valid==0) {
            exitFirstGroup = groupList[i].uri;
        }else if (firstDisGroup == "" && groupList[i].uri.indexOf("sip:DG") >= 0&&groupList[i].valid==1) {
            firstDisGroup = groupList[i].uri;
        }else if (exitFirstDisGroup == "" && groupList[i].uri.indexOf("sip:DG") >= 0&&groupList[i].valid==0) {
            exitFirstDisGroup = groupList[i].uri;
        } else if (firstSmsGroup == "" && groupList[i].uri.indexOf("sip:SG") >= 0) {
            firstSmsGroup = groupList[i].uri;
        }
    }
    if (groupID != "") {
        if (groupID.indexOf("sip:PG") >= 0) {
            groupType = groupMsg;
        } else if (groupID.indexOf("sip:DG") >= 0) {
            groupType = disGroupMsg;
        } else if (groupID.indexOf("sip:SG") >= 0) {
            groupType = smsGroupMsg;
        }
    } else {
        if (firstGroup == "") {             // ?
            groupType = disGroupMsg;
            groupID = firstDisGroup;
        } else {
            groupType = groupMsg;
            groupID = firstGroup;
        }
    }

    for (var i = 0; i < groupList.length; i++) {
        var groupId = groupList[i].uri;
        var groupName = groupList[i].n;
        if (groupList[i].uri.indexOf("sip:PG") >= 0) {
			if(groupList[i].valid&&groupList[i].valid==0){
				exitPgStr += "<dd type='exitGroupMsg' btType='64' ondblclick='ShowChatDialog(this)' onMouseup='ShowLeftMenuRightMenu(this)' onclick=\"ClickMenuShowMessage(this,0);\" id='div" + groupList[i].id + "' groupId='" + groupId + "' groupName='" + groupName + "'><a><img src='" + groupList[i].img + "' alt='' class='per_icon'/><span title='" + groupName + "'>" + KillWords(groupName, 100) + "</span></a></dd>";
				exitPgCount++;
			}else{
				pgStr += "<dd type='" + groupMsg + "' btType='64' ondblclick='ShowChatDialog(this)' onMouseup='ShowLeftMenuRightMenu(this)' onclick=\"ClickMenuShowMessage(this,0);\" id='div" + groupList[i].id + "' groupId='" + groupId + "' groupName='" + groupName + "'><a><img src='" + groupList[i].img + "' alt='' class='per_icon'/><span title='" + groupName + "'>" + KillWords(groupName, 100) + "</span></a></dd>";
				pgCount++;
			}
        } else if (groupList[i].uri.indexOf("sip:DG") >= 0) {
			if(groupList[i].valid&&groupList[i].valid==0){
				exitDgStr += "<dd type='exitDisGroupMsg'  btType='64' ondblclick='ShowChatDialog(this)' onMouseup='ShowLeftMenuRightMenu(this)'  onclick=\"ClickMenuShowMessage(this,0);\" id='div" + groupList[i].id + "' groupId='" + groupId + "' groupName='" + groupName + "'><a><img src='" + groupList[i].img + "' alt='' class='per_icon'/><span title='" + groupName + "'>" + KillWords(groupName, 100) + "</span></a></dd>";
				exitDgCount++;
			}else{
				dgStr += "<dd type='" + disGroupMsg + "'  btType='64' ondblclick='ShowChatDialog(this)' onMouseup='ShowLeftMenuRightMenu(this)'  onclick=\"ClickMenuShowMessage(this,0);\" id='div" + groupList[i].id + "' groupId='" + groupId + "' groupName='" + groupName + "'><a><img src='" + groupList[i].img + "' alt='' class='per_icon'/><span title='" + groupName + "'>" + KillWords(groupName, 100) + "</span></a></dd>";
				dgCount++;
			}
            
        } else if (groupList[i].uri.indexOf("sip:SG") >= 0) {
            if (isCM == 1) {
                sgStr += "<dd type='" + smsGroupMsg + "'  btType='64' ondblclick='ShowChatDialog(this)' onMouseup='ShowLeftMenuRightMenu(this)'  onclick=\"ClickMenuShowMessage(this,0);\" id='div" + groupList[i].id + "' groupId='" + groupId + "' groupName='" + groupName + "'><a><img src='" + groupList[i].img + "' alt='' class='per_icon'/><span title='" + groupName + "'>" + KillWords(groupName, 100) + "</span></a></dd>";
                sgCount++;
            }
        }

    }
    var menuStr = "<dl id='div" + groupMsg + "'><dt type='" + groupMsg + "' onclick=\"ClickMenuShowMessage(this,0);\"  btType='32' groupId='" + firstGroup + "'><a><span class='arrow_2'></span>我的飞信群<span class='num'>[" + pgCount + "]</span></a></dt>";
    menuStr += pgStr + "</dl>";
    menuStr += "<dl id='div" + disGroupMsg + "'><dt type='" + disGroupMsg + "' onclick=\"ClickMenuShowMessage(this,0)\"  btType='32' groupId='" + firstDisGroup + "'><a><span class='arrow_2'></span>我的讨论组<span class='num'>[" + dgCount + "]</span></a></dt>";
    menuStr += dgStr + "</dl>";
    if (isCM == 1) {
        menuStr += "<dl id='div'" + smsGroupMsg + "'><dt type='" + smsGroupMsg + "' onclick=\"ClickMenuShowMessage(this,0)\"  btType='32' groupId='" + firstSmsGroup + "'><a><span class='arrow_2'></span>我的拇指群<span class='num'>[" + sgCount + "]</span></a></dt>";
        menuStr += sgStr + "</dl>";
    }
	menuStr += "<dl id='divexitGroupMsg'><dt type='exitGroupMsg' onclick=\"ClickMenuShowMessage(this,0)\"  btType='32' groupId='" + exitFirstGroup + "'><a><span class='arrow_2'></span>已退出的群<span class='num'>[" + exitPgCount + "]</span></a></dt>";
    menuStr += exitPgStr + "</dl>";
	menuStr += "<dl id='divexitDisGroupMsg'><dt type='exitDisGroupMsg' onclick=\"ClickMenuShowMessage(this,0)\"  btType='32' groupId='" + exitFirstDisGroup + "'><a><span class='arrow_2'></span>已退出的讨论组<span class='num'>[" + exitDgCount + "]</span></a></dt>";
    menuStr += exitDgStr + "</dl>";

    $("#divMenu").empty();
    $("#divMenu").append(menuStr);
    $("#divMenu").find("dd").hide();
    $("#divMenu").find("dt").removeClass("over");
}
//点击标记
function TagClick(){
	$(".search_pane").hide();
	SelectTopMenuItem($("#liTag"));
    funType = 6;
    //pageIndex = pIndex;
    ShowTagMenu();
    /*ShowGroupMessageById();
    if (isDirectShowContact) {
        var gId = GetgId(groupID);
        var top = $("#div" + gId).offset().top;
        $("#divMenu").scrollTop(top - 45);
    }*/
}
//点击群组
function GroupClick(me, pIndex) {
	$(".search_pane").show();
    SelectTopMenuItem(me);
    funType = 2;
    pageIndex = pIndex;
    ShowGroupMenu();
    ShowGroupMessageById();
    if (isDirectShowContact) {
        var gId = GetgId(groupID);
        var top = $("#div" + gId).offset().top;
        $("#divMenu").scrollTop(top - 45);
    }
}


//显示短信聊天记录
function ShowSmsMessage(sms, pageIndex) {
    if (contactList.length == 0) {//没有联系人
        return;
    }
    FocusOnLocalOrRoam(true, false);
    window.searchMsgID = null;
    isSearch = false;
    smsType = sms;
    if (smsType == 0) {//高红飞 2014年6月18日短信聊天记录修改 开始
        $("#divMySelfSms").addClass("show");
        $("#divOtherSms").removeClass("show");
        $("#divTimeSms").removeClass("show");
		$("#divNoFreeSms").removeClass("show");
} else if (smsType == 1) {
        $("#divMySelfSms").removeClass("show");
        $("#divOtherSms").addClass("show");
		$("#divTimeSms").removeClass("show");
		$("#divNoFreeSms").removeClass("show");
} else if(smsType == 2){
		$("#divMySelfSms").removeClass("show");
		$("#divOtherSms").removeClass("show");
		$("#divTimeSms").addClass("show");
		$("#divNoFreeSms").removeClass("show");
	}else{
		$("#divMySelfSms").removeClass("show");
		$("#divOtherSms").removeClass("show");
		$("#divTimeSms").removeClass("show");
		$("#divNoFreeSms").addClass("show");
	}    //高红飞 2014年6月18日短信聊天记录修改 结束

    ShowLoading();
    //$('#manegeWrap').html("<p class='tips_1'><img src='img/2_tips.png'></p>");
    //$("#ulPaging").parent().hide();
    //$("#divCalendar").hide();
    var jsonObj = new JsonObj();
    jsonObj.pageIndex = pageIndex;
    AjaxRequest(funType, "QuerySmsHistoryMessage", smsType, jsonObj.ToJson(), function(status, txt, outJson) {
        ShowTip(outJson.tc, 3);
        ShowMessage(outJson, smsType);
        ChangeSearchRange(smsType);
    });

}

//显示短信聊天记录
function ShowTagMessage(me, pageIndex) {
    if (contactList.length == 0) {//没有联系人
        return;
    }
    FocusOnLocalOrRoam(false, false,true);
    window.searchMsgID = null;
    isSearch = false;
	for(var i=0; i<tagList.length;i++){
		$("#"+tagList[i].id).removeClass("show");
	}
	$(me).addClass("show");
    ShowLoading();
    //$('#manegeWrap').html("<p class='tips_1'><img src='img/2_tips.png'></p>");
    //$("#ulPaging").parent().hide();
    //$("#divCalendar").hide();
	curTagType = $(me).attr("id");
    var jsonObj = new JsonObj();
    jsonObj.pageIndex = pageIndex;
	ShowTip(curTagType, 6);
    AjaxRequest(funType, "QueryTagHistoryMessage", curTagType, jsonObj.ToJson(), function(status, txt, outJson) {
        ShowTip(outJson.tc, 6);
        ShowMessage(outJson);
        //ChangeSearchRange(smsType);
    });

}

//查询短信信息
function QuerySmsInfo() {
    var jsonObj = new JsonObj();
    AjaxRequest(funType, "SearchSmsInfoHistoryMessage", "", jsonObj.ToJson(), function(status, outTxt, outJson) {
        selfSmsCount = outJson.self;
        otherSmsCount = outJson.other;
        freeSmsCount = outJson.free;
    });
}

function ShowSmsMenu() {
    $("#divMenu").empty();
    var menuStr = "<dl><dt class='over'></dt><dd id='divMySelfSms' onclick='ClickMenuShowMessage(0,0);' type='SelfSmsMsg' onMouseup='ShowLeftMenuRightMenu(this)'><a>给自己发的短信</a></dd>";
    menuStr += "<dd id='divOtherSms' onclick='ClickMenuShowMessage(1,0);' type='OtherSmsMsg' onMouseup='ShowLeftMenuRightMenu(this)'><a>给别人发的短信</a></dd>"; //高红飞 2014年6月18日定时短信菜单添加 开始
    menuStr += "<dd id='divTimeSms' onclick='ClickMenuShowMessage(2,0);' type='TimerSmsMsg' onMouseup='ShowLeftMenuRightMenu(this)'><a>定时待发送短信</a></dd>"; //高红飞 2014年6月18日定时短信菜单添加 结束
	menuStr += "<dd id='divNoFreeSms' onclick='ClickMenuShowMessage(3,0);' type='NoFreeSmsMsg' onMouseup='ShowLeftMenuRightMenu(this)'><a>付费短信</a></dd></dl>";
    $("#divMenu").append(menuStr);
}

function ShowTagMenu(callBackFun,panel,index) {
	//加载标记菜单
	AjaxRequest(funType, "TagLeftMenu", "", null, function(status, outTxt, outJson) {
	//var outJson = [{id:"1",type:"all",name:"全部",index:1},{id:"2",type:"img",name:"图片",index:2},{id:"3",type:"audio",name:"语音",index:3},{id:"4",type:"video",name:"视频",index:4}];
		tagList = outJson;
	$("#divMenu").empty();
	var menuStr = "<dl><dt class='over'></dt>";
	for(var i=0;i<tagList.length;i++){
		menuStr += "<dd id='"+tagList[i].id+"' onclick='ClickMenuShowMessage(this,0);' type='"+tagList[i].id+"' onMouseup='ShowLeftMenuRightMenu(this)'><a>"+tagList[i].name+"</a></dd>"
	}
	menuStr += "</dl>";
	$("#divMenu").append(menuStr);
	if(callBackFun){
		callBackFun(panel,index);
	}else{
		ClickMenuShowMessage($("#"+curTagType), 0);
	}
	
    });
	

}

//点击短信
function SmsClick(me, sms, pIndex, isTimeSms) {
	$(".search_pane").show();
    SelectTopMenuItem(me);
    funType = 3;
    isSearch = false;
    pageIndex = pIndex;
    var jsonObj = new JsonObj();
    jsonObj.pageIndex = pageIndex;
    smsType = sms;
    ShowSmsMenu();
    FocusOnLocalOrRoam(true, false);
    $("#divCalendar").show();
    $("#divBack").hide();
    $("#divMySelfSms").addClass("show");
    $("#divOtherSms").removeClass("show");

    if (isTimeSms) {
        ClickMenuShowMessage(2, 0);
    } else {
        AjaxRequest(funType, "QuerySmsHistoryMessage", "0", jsonObj.ToJson(), function(status, outTxt, outJson) {
            ShowTip(outJson.tc, 3);
            ShowMessage(outJson);
            ChangeSearchRange(smsType);
        });
    }
}

function ClickMenuShowMessage(me, pIndex) {
    pageIndex = pIndex;
    $("#divCalendar").show();
    $("#divBack").hide();
    if (funType == 1) {
        ShowContactMessage(me, pageIndex);
    } else if (funType == 2) {
        ShowGroupMessage(me, pageIndex);
    } else if (funType == 3) {
        ShowSmsMessage(me, pageIndex);
    }else if(funType == 6){
		ShowTagMessage(me, pageIndex);
	}
}

//type说明
//PrivateMsg:二人会话  GroupMsg:群组会话 DisGroupMsg:讨论组会话 SmsGroupMsg:拇指群

//显示左边菜单的右键菜单
function ShowLeftMenuRightMenu(me) {
    if (me == null || window.event.button != 2)	//只处理右键
        return;
    isSearch = false;
    //ShowCurItem(me);
    var type = $(me).attr("type");
    var userId = $(me).attr("userId");
    var groupId = $(me).attr("groupId");

    var jsonObj = new JsonObj();
    var p = mousePosition(window.event, me);
    jsonObj.X = p.x;
    jsonObj.Y = p.y;
    jsonObj.btType = parseInt($(me).attr("btType"));
    jsonObj.funType = funType;

    jsonObj.Content = "type:" + type + ";userId:" + userId + ";groupId:" + groupId;
    if (type == privateMsg) {
        if (userId != contactID) {
            jsonObj.showMsg = 1;
        }
    } else {
        if (groupId != groupID) {
            jsonObj.showMsg = 1;
        }
    }
    contactID = userId;
    contactGroupID = groupID = groupId;
    if (funType == 1) {
        ShowTip(contactID, 1);
    } else if (funType == 2) {
        ShowTip(groupID, 2);
    }

    AjaxRequest(funType, "ShowLeftMenu", "", jsonObj.ToJson(), function(status, outTxt, outJson) {
        if (outTxt == "QueryHistoryMessage") {
            FocusOnLocalOrRoam(true, true);
            if (outJson == null || outJson == "") {
                if (funType == 1) {
                    ClickMenuShowMessage($("#div" + contactID + contactGroupID), 0);
                } else if (funType == 2) {
                    ShowGroupMessageById();
                }
            } else {
                ShowMessage(outJson);
            }
        }
        if (outTxt == "Refrush") {//刷新 
            if (outJson.funType == 1) {
                if (outJson.btType == 32) {
                    AjaxRequest(funType, "QueryContactList", "", "", function(status2, outTxt2, outJson2) {
                        contactList = outJson2;
                        contactID = "";
                        var menuStr = "";
                        var contactCount = 0;
                        for (var j = 0; j < contactList.length; j++) {
                            if ((";" + contactList[j].gs + ";").indexOf(";" + outJson.groupId + ";")) {
                                contactCount++;
                                if (contactID == "") {
                                    contactID = contactList[j].uid;
                                    contactGroupID = outJson.groupId;
                                }
                                menuStr += "<dd id='div" + contactList[j].uid + outJson.groupId + "' type='" + privateMsg + "' btType='64' onclick=\"ClickMenuShowMessage(this,0);\" ondblclick='ShowChatDialog(this)' onMouseup='ShowLeftMenuRightMenu(this)' userId='" + contactList[j].uid + "' groupId='" + outJson.groupId + "' onmouseover='addClass(this,\"show\")' onmouseout='removeClass(this,\"show\")'><img src='" + contactList[j].img + "' alt='' class='per_icon'/>" + contactList[j].n + "</dd>";
                            }
                        }

                        $("#div" + outJson.groupId).find("dd").remove();
                        $("#div" + outJson.groupId).append(menuStr);
                        $("#div" + outJson.groupId).find("dt").find(".num").text("[" + contactCount + "]");
                        ClickMenuShowMessage($("#div" + contactID + contactGroupID), 0);
                    });
                } else if (outJson.btType == 64) {
                    contactID = outJson.userId;
                    ClickMenuShowMessage($("#div" + outJson.userId + contactGroupID), 0);
                }
            } else if (outJson.funType == 2) {
                if (outJson.btType == 32) {
                    AjaxRequest(funType, "QueryGroupList", "", "", function(status2, outTxt2, outJson2) {
                        groupList = outJson2;
                        groupID = "";
                        var menuStr = "";

                        var gType = "";
                        if (groupType == groupMsg) {
                            gType = "sip:PG";
                        } else if (groupType == disGroupMsg) {
                            gType = "sip:DG";
                        } else if (groupType == smsGroupMsg) {
                            gType = "sip:SG";
                        }
                        //var gType = outJson.type == groupType ? "sip:PG" : "sip:DG";
                        groupType = outJson.type;
                        var groupCount = 0;
                        for (var i = 0; i < groupList.length; i++) {
                            if (groupList[i].uri.indexOf(gType) >= 0) {
                                groupCount++;
                                if (groupID == "") {
                                    groupID = groupList[i].uri;
                                }
                                var groupId = groupList[i].uri;
                                var groupName = groupList[i].n;
                                if (groupType == groupMsg) {
                                    menuStr += "<dd type='" + groupMsg + "' btType='64' ondblclick='ShowChatDialog(this)' onMouseup='ShowLeftMenuRightMenu(this)' onclick='ClickMenuShowMessage(this,0)' id='div" + groupList[i].id + "' groupId='" + groupId + "' groupName='" + groupName + "' onmouseover='addClass(this,\"show\")' onmouseout='removeClass(this,\"show\")'><img src='" + groupList[i].img + "' alt='' class='per_icon'/>" + groupName + "</dd>";
                                } else if (groupType == disGroupMsg) {
                                    menuStr += "<dd type='" + disGroupMsg + "'  btType='64' ondblclick='ShowChatDialog(this)' onMouseup='ShowLeftMenuRightMenu(this)'  onclick='ClickMenuShowMessage(this,0)' id='div" + groupList[i].id + "' groupId='" + groupId + "' groupName='" + groupName + "' onmouseover='addClass(this,\"show\")' onmouseout='removeClass(this,\"show\")'><img src='" + groupList[i].img + "' alt='' class='per_icon'/>" + groupName + "</dd>";
                                } else if (groupType == smsGroupMsg) {
                                    menuStr += "<dd type='" + smsGroupMsg + "'  btType='64' ondblclick='ShowChatDialog(this)' onMouseup='ShowLeftMenuRightMenu(this)'  onclick='ClickMenuShowMessage(this,0)' id='div" + groupList[i].id + "' groupId='" + groupId + "' groupName='" + groupName + "' onmouseover='addClass(this,\"show\")' onmouseout='removeClass(this,\"show\")'><img src='" + groupList[i].img + "' alt='' class='per_icon'/>" + groupName + "</dd>";
                                }
                            }
                        }
                        $("#div" + outJson.type).find("dd").remove();
                        $("#div" + outJson.type).append(menuStr);
                        $("#div" + outJson.type).find("dt").find(".num").text("[" + groupCount + "]");
                        ShowGroupMessageById();
                    });
                } else if (outJson.btType == 64) {
                    ShowGroupMessageById();
                }
            }
        }
    });
}

//显示聊天窗口
function ShowChatDialog(me) {
    var type = $(me).attr("type");
    var userId = $(me).attr("userId");
    var groupId = $(me).attr("groupId");
    var jsonObj = new JsonObj();
    var p = mousePosition(window.event, me);
    jsonObj.X = p.x;
    jsonObj.Y = p.y;
    jsonObj.btType = 64; //子菜单
    jsonObj.Content = "type:" + type + ";userId:" + userId + ";groupId:" + groupId;
    AjaxRequest(funType, "SendMessage", "", jsonObj.ToJson(), function(status, txt, json) {
        $("#divCalendar").show();
        $("#divBack").hide();
        if (funType == 1) {
            ShowContactMessage(me, pageIndex);
        } else if (funType == 2) {
            ShowGroupMessage(me, pageIndex);
        } else if (funType == 3) {
            ShowSmsMessage(me, pageIndex);
        }
    });
}

function GetMsgLastDate() {
    if (showSetDate && $(".time_tit").length > 0) {
        showSetDate = false;
        return $(".time_tit").eq($(".time_tit").length - 1).html();
    }
    return "";
}

//获取联系人漫游记录
function GetContactRoamMsg(searchType, pIndex) {
    var roamMsg = CreateGetConatctRoamingMsg(searchType, pIndex);
    if (roamMsg.peerId == null || roamMsg.peerId == "" || roamMsg.peerUri == null || roamMsg.peerUri == "") {
        ShowRoamTip(7);
        return;
    }
    var jsonObj = new JsonObj();
    jsonObj.Content = roamMsg.ToJson();
    ShowLoading();
    AjaxRequest(funType, "QueryContactRoamingMsg", "", jsonObj.ToJson(), function(Status, txt, outJson) {
        if (txt == "QueryContactRoamingMsg") {
            ShowMessage(outJson);
        } else {
            SetRoamTime(outJson.roamTime);
        }
    })
}

//获取群组漫游聊天记录
function GetGroupRoamMsg(searchType, pIndex) {
    var roamMsg = CreateGetGroupRoamingMsg(searchType, pIndex);
    if (roamMsg.groupUri == null || roamMsg.groupUri == "") {
        ShowRoamTip(7);
        return;
    }
    var jsonObj = new JsonObj();
    jsonObj.Content = roamMsg.ToJson();
    ShowLoading();
    AjaxRequest(funType, "QueryGroupRoamingMsg", "", jsonObj.ToJson(), function(Status, txt, outJson) {
        if (txt == "QueryGroupRoamingMsg") {
            ShowMessage(outJson);
        } else {
            SetRoamTime(outJson.roamTime);
        }
    })
}

function PageClick(type) {
    if ((type == 1 || type == 2) && pageIndex == totalPage) {
        return;
    }
    if ((type == 3 || type == 4) && pageIndex == 1) {
        return;
    }
    if ($("#apaging" + type).attr("canuse") != "false") {
        //calendarClickFlag = true;
        $("#apaging" + type).attr("canuse", "false");
        showSetDate = true;
        PageClick2(type);
    }
}


function PageClick2(type) {
    switch (type) {
        case 1:
            pageIndex = totalPage;
            break;
        case 2:
            if (pageIndex < totalPage) {
                pageIndex++;
            }
            break;
        case 3:
            if (pageIndex > 1) {
                pageIndex--;
            }
            break;
        case 4:
            pageIndex = 1;
            break;
        default:

            break;
    }
    window.searchMsgID = null;
    if (isSearch) {
        SearchMsg(pageIndex);
    } else {
        switch (funType) {
            case 1:
                if (isfocusOnRoam) {//查询联系人漫游记录
                    GetContactRoamMsg("0", pageIndex);
                } else {//查询本地记录
                    ClickMenuShowMessage($("#div" + contactID + contactGroupID), pageIndex);
                }
                break;
            case 2:
                if (isfocusOnRoam) {//查询群组漫游记录
                    GetGroupRoamMsg("0", pageIndex);
                } else {//查询本地记录
                    ShowGroupMessageById();
                }
                break;
            case 3:
                ClickMenuShowMessage(smsType, pageIndex);
                break;
			case 6:
				ClickMenuShowMessage($("#"+curTagType),pageIndex);
            default:
                break;
        }
    }
}

//设置分页信息
function SetPageInfo() {
    $("#divCalendar").show();
    $("#divPaging").show();
    $("#txtPageIndex").val(pageIndex);
    $("#spanTotalPage").text(totalPage);
    if (totalPage == 0) {
        $("#ulPaging").parent().hide();
        return;
    }
    if (totalPage == 1) {
        for (var i = 1; i <= 4; i++) {
            $("#liPaging" + i).find("a").removeClass("p_arrow_" + i + "_1").addClass("p_arrow_" + i + "_2");
            $("#liPaging" + i).find("a").attr("disabled", "disabled");
            $("#liPaging" + i).find("a").attr("canuse", "false");
        }
        return;
    }
    for (var i = 1; i <= 4; i++) {
        $("#liPaging" + i).find("a").removeClass("p_arrow_" + i + "_2").addClass("p_arrow_" + i + "_1");
        $("#liPaging" + i).find("a").attr("canuse", "true");
    }
    if (pageIndex >= totalPage) {
        $("#liPaging1").find("a").removeClass("p_arrow_1_1").addClass("p_arrow_1_2");
        $("#liPaging1").find("a").attr("disabled", "disabled");
        $("#liPaging1").find("a").attr("canuse", "false");
        $("#liPaging2").find("a").removeClass("p_arrow_2_1").addClass("p_arrow_2_2");
        $("#liPaging2").find("a").attr("disabled", "disabled");
        $("#liPaging2").find("a").attr("canuse", "false");
    } else if (pageIndex <= 1) {
        $("#liPaging3").find("a").removeClass("p_arrow_3_1").addClass("p_arrow_3_2");
        $("#liPaging3").find("a").attr("disabled", "disabled");
        $("#liPaging3").find("a").attr("canuse", "false");
        $("#liPaging4").find("a").removeClass("p_arrow_4_1").addClass("p_arrow_4_2");
        $("#liPaging4").find("a").attr("disabled", "disabled");
        $("#liPaging4").find("a").attr("canuse", "false");
    }
}

//点击工具
function ToolClick(me) {
    var p = mousePosition(window.event, me);
    var jsonObj = new JsonObj();
    jsonObj.X = p.x;
    jsonObj.Y = p.y;
    jsonObj.Content = "Tool";
    AjaxRequest(funType, "ShowTool", "", jsonObj.ToJson(), {});
}

function QueryByTime() {
    window.queryTime = $("#txtTime").val();
    var jsonObj = new JsonObj();
    var fType = funType;
    if (fType == 3 && smsType == 0) {
        fType = 4;
    }
    calendarClickFlag = true;
    //showSetDate = true;
    window.searchMsgID = null;
    if (isfocusOnRoam) {
        if (fType == 1) {//联系人漫游记录
            GetContactRoamMsg("1", 0);
        } else if (fType == 2) {//群讨论组漫游记录
            GetGroupRoamMsg("1", 0);
        }
    } else {
        ShowLoading();
        jsonObj.Content = "{\"time\":\"" + window.queryTime + "\",\"funType\":" + fType + "}";
        AjaxRequest(fType, "QueryHistoryMessageByTime", "", jsonObj.ToJson(), function(status, outTxt, outJson) {
            ShowMessage(outJson);
        });
    }
    window.event.returnValue = false;
}


//显示右侧聊天内容 区分是本地还是远端
function ShowMessage(outJson, smsType) {
	if(groupID=="9999999"){
		FocusOnLocalOrRoam(true, false);
	}
    $(".history_ct").show();
    if (outJson == null || outJson == "" || outJson.info == null || outJson.info == "" || outJson.info.length == 0) {
        if (funType == 6){
			$('#manegeWrap').html("<p class='tips_1'><img src='img/no-tag.png'></p>");
		}else{
			$('#manegeWrap').html("<p class='tips_1'><img src='img/no_tips.png'></p>");
		}
        $("#divPaging").hide();
        $("#divCalendar").hide();
        $("#divBack").hide();
        $("#manegeWrap").removeClass("his_chat pd_t01").addClass("his_chat");
        backObj.step = 0;
        return;
    }

    if (funType == 1) {
        contactMessage = outJson;
    } else if (funType == 2) {
        groupMessage = outJson;
    } else if (funType == 3) {
        smsMessage = outJson;
    } else if(funType == 6){
		tagMessage = outJson;
	}

    myArray = outJson.info;
    totalPage = parseInt(outJson.tp);
    pageIndex = parseInt(outJson.cp);
    for (var i = 0; i < myArray.length; i++) {
        var date1 = myArray[i].dt.split(' ');
        myArray[i].DayString = date1[0]; //日期
        myArray[i].TimeString = date1[1]; //时间点
        myArray[i].n = myArray[i].n.replace("<", "&lt").replace(">", "&gt");
    }
    window.scrollHeightList = [];
    var currentDay, strMsgBody;
    while (manegeWrap.childNodes.length)
        manegeWrap.removeChild(manegeWrap.childNodes[0]);
    for (var i = 0; i < myArray.length; i++) {
        if (isSearchGoTo) {
            break;
        }
        if (!calendarClickFlag) {
            window.searchMsgID = myArray[myArray.length - 1].id;
            break;
        } else {
            if (window.queryTime == myArray[i].DayString) {
                window.searchMsgID = myArray[i].id;
                break;
            }
        }
    }
    for (var i = 0; i < myArray.length; i++) {
        if (i > 0 && myArray[i].DayString == currentDay) {
            strMsgBody = AddMessageSingle(myArray[i], smsType);
            var tmpDIV = document.createElement("DIV");
            tmpDIV.innerHTML = strMsgBody;
            document.getElementById(currentDay).appendChild(tmpDIV);
        }
        else {
            currentDay = myArray[i].DayString;
            strMsgBody = AddMessageBody(myArray, myArray[i], i, smsType);
            var tmpDIV = document.createElement("DIV");
            tmpDIV.innerHTML = strMsgBody;
            manegeWrap.appendChild(tmpDIV);
        }
        var ddMsgId = "dd_" + myArray[i].id;
        Fetion.Web.Chat.newMsg(document.getElementById(ddMsgId), myArray[i].msg);
    }

    SetBackRefreshDelete(funType != 2);
    if ($("#manegeWrap").find("dl").length > 0) {
        var lastDl = $("#manegeWrap").find("dl").eq($("#manegeWrap").find("dl").length - 1);
        lastDl.addClass("mouse_on");
    }

    $(".seac_pop").hide();
    $(".search_type").hide();
    if (!isSearchGoTo) {
        if (!calendarClickFlag) {
            if ($(".time_tit").length > 0) {
                $("#txtTime").val($(".time_tit").eq($(".time_tit").length - 1).html());
            }
        } else {
            $("#txtTime").val(window.queryTime);
        }
    }
    $("#manegeWrap dl").removeClass("mouse_on");
    for (var i = 0; i < $("#manegeWrap dl").length; i++) {
        if ($("#manegeWrap dl").eq(i).attr("id") == window.searchMsgID) {
            $("#manegeWrap dl").eq(i).addClass("mouse_on");
            //$('.his_ct_m').scrollTop($("#manegeWrap dl").eq(i).offset().top - 100);
            break;
        }
    }

    //搜索关键字加背景色
    if (isSearch) {
        searchKey = searchKey.replace("<", "&lt;").replace(">", "&gt;");
        var re = new RegExp(searchKey, "gi");
        var tmpKey = "嗭";
        var tmpRe = new RegExp(tmpKey, "gm");
        $("#manegeWrap dd").each(function() {
            $(this).find("span").each(function() {
                var msgType = $(this).attr("type");
                if (msgType == "text" || msgType == "urllink" || msgType == "location" || msgType == "email" || msgType == "feinno_card" || msgType == "file" || msgType == "phone_card" || msgType == undefined) {
                    var str = $(this).html();
                    str = str.replaceAll("&amp;", "&");
                    str = str.replaceAll("&lt;", "<");
                    str = str.replaceAll("&gt;", ">");
                    var arry = [];
                    str = str.replace(/<\/?[^>]*>/g, function(a) { arry.push(a); return tmpKey; });
                    str = str.replace(re, function(a) { return "<span class='searchKey'>" + a + "</span>"; });
                    var l = 0;
                    str = str.replace(tmpRe, function() { return arry[l++]; });
                    $(this).html(str);
                }
            })
        })
    }
    var selection = window.getSelection();
    selection.setBaseAndExtent("", 0, "", 0);
    if (smsType != 2) {
        SetPageInfo(); // 设置定时短信不分页 Add by 冯旭飞
    }

    //搜索全部
    if (isSearch && $("#txtSearchRange").attr("realVal") == "10") {
        $("#manegeWrap dl").each(function() {
            var fType = $(this).attr("funType");
            if (fType == "2") {//群组
                var groupId = $(this).attr("groupId");
                for (var i = 0; i < groupList.length; i++) {
                    if (groupList[i].uri == groupId) {
                        //var groupName = groupId.indexOf("sip:PG") >= 0 ? "群组-我的飞信群-" : "群组-我的讨论组-";
                        var groupName = "";
                        if (groupId.indexOf("sip:PG") >= 0) {
                            groupName = "群组-我的飞信群-";
                        } else if (groupId.indexOf("sip:DG") >= 0) {
                            groupName = "群组-我的讨论组-";
                        } else if (groupId.indexOf("sip:SG") >= 0) {
                            /*if (isCM == 1) {
                                groupName = "群组-我的拇指群-";
                            }*/
                        }
                        groupName = "<span class='fc_001'>" + groupName + groupList[i].n + "</span>";
                        $(this).find("dt").append(groupName);
                        break;
                    }
                }
            }
        })
    }
    if (smsType == 2|| funType == 6) {
        $("#divCalendar").hide();
    }
    if (!isfocusOnRoam) {
        ShowCalendar();
    }
    Fetion.Web.Chat.scroll();
}

function AddMessageBody(objList, obj, index, smsType) {
    var divItems = "<h1 class='time_tit'>" + obj.DayString + "</h1>";
    divItems += "<div class='his_chat_inf' id='" + obj.DayString + "'>";
    divItems += AddMessageSingle(obj, smsType);
    divItems += "</div>";
    return divItems;
}

var fh_timedsms = 67108864; //定时短信
var fh_directsms = 16777216, fh_fetiontransmitsms = 33554432, fh_directsmslogined = 134217728;fh_groupsms=2; //付费短信 
var fh_forcesms = 4; //发短信
var fh_mms = 8;     //发彩信
var fh_mobilesms = 131072; //手机转存短信

function GetSmsTip(isSelf, msgType, newFunType) {
    var t = parseInt(msgType);
    if (isSelf == 1 && (t == fh_mobilesms || t == fh_forcesms)) {
        return "";
    }

    var fType = parseInt(newFunType);
    if ((!isSearch && funType == 3) || (isSearch && fType == 3)) {
        return "发送给 ";
    } else if (t == fh_timedsms || t == fh_directsms || t == fh_fetiontransmitsms || t == fh_forcesms || t == fh_mms || t == fh_directsmslogined) {
        return "发送短信给 ";
    }
    return "";
}

function GetSmsName(isSelf, name, type, code, newFunType,isMobile) {
    name = name.replaceAll("<", "&lt;");
    name = name.replaceAll(">", "&gt;");
	//name = htmlencode(name);
    var t = parseInt(type);
    var fType = parseInt(newFunType);
    if (isSelf == 1) {//当前联系人是自己
        if (t == fh_mobilesms) {//手机上行给自己的短信
            return "来自手机" + code;
        } else if (t == fh_forcesms) {//发送到自己手机的短信
            return "发到手机 <img class='emotion_icon' src='img/icon1.png' style='max-height:10px;max-width:12px;'>" + code;
        }
    }
    if (t == fh_timedsms) {//定时短信
        return (isMobile==1 ? "<span class='zf_mobileicon' title='真实号码'></span>" : "")+name + code;
    }
    if ((t==(fh_timedsms|fh_directsmslogined)||t==(fh_timedsms|fh_directsms))||t == fh_directsms || t == fh_fetiontransmitsms || t == fh_directsmslogined||(t==(fh_directsmslogined|fh_groupsms))||(t==(fh_directsms|fh_groupsms))) {//付费短信
        //return "<span class='zf_icon' title='付费短信'></span>"+(((t == fh_directsms)||(t == fh_directsmslogined)||(t==(fh_directsmslogined|fh_groupsms))||(t==(fh_directsms|fh_groupsms))) ? "<span class='zf_mobileicon' title='真实号码'></span>" : "")+"<span style='color: #EB6302;'>" + name + "</span>" + code
		return "<span class='zf_icon' title='付费短信'></span>"+(isMobile==1 ? "<span class='zf_mobileicon' title='真实号码'></span>" : "")+"<span style='color: #EB6302;'>" + name + "</span>" + code;
    } else if (t == fh_timedsms || t == fh_forcesms || t == fh_mms) {
        if ((!isSearch && funType == 3) || (isSearch && fType == 3)) {
            return (isMobile==1 ? "<span class='zf_mobileicon' title='真实号码'></span>" : "")+name + code;
        } else if (isSearch) {
            var realVal = $("#txtSearchRange").attr("realVal");
            if (realVal == "0" || realVal == "1" || realVal == "7") {
                return (isMobile==1 ? "<span class='zf_mobileicon' title='真实号码'></span>" : "")+name + code;
            }
        }
        return "<img class='emotion_icon' src='img/icon1.png' style='max-height:10px;max-width:12px;'>" +(isMobile==1 ? "<span class='zf_mobileicon' title='真实号码'></span>" : "")+ name + code;
    }
    return (isMobile==1 ? "<span class='zf_mobileicon' title='真实号码'></span>" : "")+name + code;
}


function GetFileTransTip(msgType, uid, eventType, funType) {
    if (msgType == "16" || msgType == "32" || msgType == "64" || msgType == "128") {
        if (funType == "1") {//二人会话
            var isSelf = (uid == ownerInfo.uid);
            if (msgType == "16" || msgType == "32") {
                return isSelf ? "文件发送成功" : "文件接收完成";
            } else if (msgType == "64") {
                return isSelf ? "文件夹发送成功" : "文件夹接收成功";
            } else {
                return isSelf ? "离线文件发送成功" : "文件接收完成";
            }
        } else if (funType == "2") {//群/讨论组
            if (eventType == "6") {
                return "共享文件下载完成";
            } else {
                return "共享文件上传成功";
            }
        }
    }
    return "";
}
var isSelect = false;
function selectItem() {
    if (isSelect) {
        event.returnValue = false;
        return false;
    } else {
        return true;
    }
}

document.onmousedown = function(e) {
    if (event.shiftKey) {
        isSelect = true;
    } else {
        isSelect = false;
    }
}
function AddMessageSingle(obj, smsType) {
    var fType = funType;
    if (obj.funType != undefined && obj.funType != null && obj.funType != "") {
        fType = obj.funType;
    }
	var datas1 = eval("(" + obj.msg + ")");
	var sourcename="";
	var url = "";
	var isshowsource=0;
    var typelist = datas1.length > 1 ? datas1[1].type : "";
    for (var k = 0; k < datas1.length; k++) {
        typelist += "," + datas1[k].type;
		if(datas1[k].sourcename){
			sourcename=datas1[k].sourcename;
		}
		if(datas1[k].isshowsource){
			isshowsource=datas1[k].isshowsource;
		}
		if(datas1[k].url&&datas1[k].type=="head"){
			url=datas1[k].url;
		}
    }
    var divItem = "<dl id ='" + obj.id + "' uid='"+obj.uid+"' key='" + obj.key + "' funType='" + fType + "' groupId='" + obj.groupId + "'" + " date='" + obj.DayString + "' " +
		"onclick='ClickMessage(this)' onselectstart='selectItem()' ondblclick='MouseDbClickHistoryRecord(this)' \
		oncontextmenu='MouseClickHeightLightMe(this)' \
		>";
    var aLink = " ";
    if (isSearch) {
        aLink = "<a id='a" + obj.id + "' funType='" + fType + "' msgId='" + obj.id + "' key='" + obj.key + "' class='see_mes' onclick='GoToContext(this);'>查看前后消息</a> ";
    }
    if (smsType == 2) {
 		if(typelist.indexOf("sms_annex")>-1){
			divItem = "<dl id ='" + obj.id + "' uid='"+obj.uid+"' key='" + obj.key + "' funType='" + fType + "' groupId='" + obj.groupId + "'" + " date='" + obj.DayString + "' " +
			"onclick='ClickMessage(this," + smsType + ");' onselectstart='selectItem()' ondblclick='MouseDbClickHistoryRecord(this)' \
			oncontextmenu='MouseClickHeightLightMe(this)' \
			onmouseover='addClass(this,\"mouse_on\")' \
			onmouseout='removeClass(this,\"mouse_on\")'>";
			aLink = "<a funType='" + fType + "' msgId='" + obj.id + "' key='" + obj.key + "' class='more_operate' onclick='GoEditOrDelSms(this,0);'>撤回</a>";
		}else{
			divItem = "<dl id ='" + obj.id + "' uid='"+obj.uid+"' key='" + obj.key + "' funType='" + fType + "' groupId='" + obj.groupId + "'" + " date='" + obj.DayString + "' " +
			"onclick='ClickMessage(this," + smsType + ");' onselectstart='selectItem()' ondblclick='MouseDbClickHistoryRecord(this)' \
			oncontextmenu='MouseClickHeightLightMe(this)' \
			onmouseover='addClass(this,\"mouse_on\")' \
			onmouseout='removeClass(this,\"mouse_on\")'>";
			aLink = "<a funType='" + fType + "' msgId='" + obj.id + "' key='" + obj.key + "' class='more_operate' onclick='GoEditOrDelSms(this,1);'>修改</a><a funType='" + fType + "' msgId='" + obj.id + "' key='" + obj.key + "' class='more_operate' onclick='GoEditOrDelSms(this,0);'>撤回</a>";
		}
    }
	if (smsType==3) {
        divItem = "<dl id ='" + obj.id + "' uid='"+obj.uid+"' key='" + obj.key + "' funType='" + fType + "' groupId='" + obj.groupId + "'" + " date='" + obj.DayString + "' " +
		"onclick='ClickMessage(this," + smsType + ");' onselectstart='selectItem()' ondblclick='MouseDbClickHistoryRecord(this)' \
		oncontextmenu='MouseClickHeightLightMe(this)' \
		onmouseover='addClass(this,\"mouse_on\")' \
		onmouseout='removeClass(this,\"mouse_on\")'>";
    }
    if (obj.recvct != undefined && obj.recvct != null && obj.recvct != "" && obj.recvct != "0") {
        var nameList = (parseInt(obj.type) == fh_timedsms) ? "<span class='zf_timeicon' title='定时短信'></span>" : "";
        var count = parseInt(obj.recv.length);
		for (var i = 0; i < count; i++) {
			if(smsType==1&&obj.recv[i].uid==ownerInfo.uid){
				continue;
			}
			var code = i < count - 1 ? " , " : "  ";
			if (i == 1) {
				code = " ";
			}
			nameList += GetSmsName(obj.isSelf, obj.recv[i].n.replace("<", "&lt").replace(">", "&gt"), obj.type, code, fType,obj.trueno);
			if (count > 2) {
				if (i == 1) {
					nameList += "<span class='spanMore'>... </span><span class='divExtend' style='display:none;'> , ";
				}
			}
            
        }

        if (count > 2) {
            nameList += "</span><span class='show_k'><a class='txt_link01' onclick='SmsExtend(this)'>展开</a> " + GetFileTransTip(obj.type, obj.uid, obj.eventType, fType) + " " + (smsType == 2 ? "" : obj.TimeString) + "</span>";
        } else {
            nameList += (smsType == 2 ? "" : obj.TimeString);
        }
        divItem += "<dt>" +((fType==6)?("<img width='20px' height='20px' src='fetionres:///"+url+"' class='tag-pic' />"):"")+ aLink + GetSmsTip(obj.isSelf, obj.type, fType) + nameList + ((fType==6&&isshowsource==1)?("<label class='mgl-20'><span class='from-wh'></span>&nbsp;&nbsp;"+sourcename+"</label>"):"")+" </dt>";
    } else {
        var name = (obj.recv != undefined && obj.recv != null && obj.recv != "") ? obj.recv : obj.n;
        divItem += "<dt>" +((fType==6)?("<img width='20px' height='20px' src='fetionres:///"+url+"' class='tag-pic' />"):"")+ aLink + GetSmsTip(obj.isSelf, obj.type, fType) + ((parseInt(obj.type) == fh_timedsms) ? "<span class='zf_timeicon' title='定时短信'></span>" : "")+ GetSmsName(obj.isSelf, name, obj.type, "  ", fType,obj.trueno) + GetFileTransTip(obj.type, obj.uid, obj.eventType, fType) + " " + (smsType == 2 ? "" : obj.TimeString) + ((fType==6&&isshowsource==1)?("<label class='mgl-20'><span class='from-wh'></span>&nbsp;&nbsp;"+sourcename+"</label>"):"")+ " </dt>";
    }
    var ddMsgId = "dd_" + obj.id;
    /*var datas1 = eval("(" + obj.msg + ")");
    var typelist = datas1.length > 1 ? datas1[1].type : "";
    for (var k = 2; k < datas1.length; k++) {
        typelist += "," + datas1[k].type;
    }*/
    divItem += "<dd id='" + ddMsgId + "' typelist='" + typelist + "'></dd>";
    divItem += "</dl>";
    return divItem;
}

//短信展开/收起
function SmsExtend(me) {
    if ($(me).html() == "展开") {
        $(me).removeClass("txt_link01").addClass("txt_link02");
        $(me).html("收起");
        $(me).parent().prev().show();
        $(me).parent().prev().prev().hide();
    } else {
        $(me).removeClass("txt_link02").addClass("txt_link01");
        $(me).html("展开");
        $(me).parent().prev().hide();
        $(me).parent().prev().prev().show();
    }
}

function ShowCalendar() {
    if (calendarClickFlag) {
        calendarClickFlag = false;
    }
    if (!isfocusOnRoam) {
        var json = new JsonObj();
        json.funType = funType;
        if (funType == 1) {
            json.Content = contactID;
        } else if (funType == 2) {
            json.Content = groupID;
        } else if (funType == 3) {
            json.Content = smsType.toString();
        }
        AjaxRequest(funType, "QueryMessageTimeList", "", json.ToJson(), function(status, outTxt, outJson) {
            if (outTxt != null && outTxt != "") {
                var txt = outTxt.substr(0, outTxt.length - 1);
                timeCalendarList = txt.split(',');
                //$("#txtTime").val(timeCalendarList[timeCalendarList.length - 1]);
            } else {
                timeCalendarList = null;
                $("#txtTime").val("");
            }
            $('.text_2').datePicker({ clickInput: true, enableDates: timeCalendarList });
        });
    }
}


function GoToContextShowMenu(searchType) {
    if (funType != searchType) {
        if (searchType == 1) {
            ShowContactMenu();
        } else if (searchType == 2) {
            ShowGroupMenu();
        } else if (searchType == 3) {
            ShowSmsMenu();
        } else if (searchType >= 6) {
			ShowTagMenu();
		}
    }
}

function ShowTip(id, fType) {
    if (id == undefined || id == null || id == "") {
        $("#divTitleTip").html("");
        return;
    }
    if (fType == 1) {
        if (id == ownerInfo.uid) {
            if (ownerInfo.phone && ownerInfo.phone != "") {
                $("#divTitleTip").html("与  自己手机 ( " + ownerInfo.phone + " )  的历史记录");
            } else {
                $("#divTitleTip").html("与  自己手机的历史记录");
            }
        } else {
            for (var i = 0; i < contactList.length; i++) {
                if (contactList[i].uid == id) {
                    var phone = (contactList[i].phone == null || contactList[i].phone == "") ? contactList[i].no : contactList[i].phone;
                    if (contactList[i].gs == "9999980" && contactList[i].hphone != null) {
                        phone = contactList[i].hphone;
                    }
                    var groupName = GetStr(contactList[i].n, 14, 100);
                    $("#divTitleTip").html("与  " + groupName + " ( " + phone + " )  的历史记录");
                    break;
                }
            }
        }
    } else if (fType == 2) {
        for (var i = 0; i < groupList.length; i++) {
            if (groupList[i].uri == id) {
                var groupName = GetStr(groupList[i].n, 16, 100);
                var num = groupList[i].uri.indexOf("sip:PG") >= 0 ? " ( " + groupList[i].id + " )" : "";
                $("#divTitleTip").html("在 " + groupName + num + " 的历史记录");
                break;
            }
        }
    } else if (fType == 3) {
        var count = parseInt(id);
        var countStr = count > 999 ? "999+" : count;
        if (smsType == 0) {
            $("#divTitleTip").html("给自己发的短信 [" + countStr + "]");
        } else if (smsType == 1) {
            $("#divTitleTip").html("给别人发的短信 [" + countStr + "]");
        } else if (smsType == 2) {
            $("#divTitleTip").html("定时待发送短信 [" + countStr + "]");
        } else {
            $("#divTitleTip").html("付费短信 [" + countStr + "]");
        }
    }else if(fType == 6){
		for(var i=0; i<tagList.length;i++){
			if(curTagType&&tagList[i].id==curTagType){
				$("#divTitleTip").html(tagList[i].name+"标记 ");
				break;
			}
		}
	}
}
//升级提示
function ShowUpTip() {
    AjaxRequest(0, "getUpTip", "", "", ShowUpTipView);
}
function ShowUpTipView(status, outText, data) {
    $("#upTip").html("<a><span id='spanUpTip'>" + data.linkText + "</span></a>" + data.text);
    $("#parentDivUpTip").css("display", "");
    $("#spanUpTip").click(function() {
        SMAjax(0, "ShowUpTipPage", "", "");
    })
}
function closeUpTip() {
    $("#parentDivUpTip").css("display", "none");
}
function GetContactGroupID(contactID) {
    for (var i = 0; i < contactList.length; i++) {
        if (contactID == contactList[i].uid) {
            var gid = contactList[i].gs;
            return gid.indexOf(";") >= 0 ? gid.split(";")[0] : gid;
        }
    }
    return "";
}

//查看前后消息
function GoToContext(me) {
    var fType = $(me).attr("funType");
    if (fType == undefined || fType == null || fType == "") {
        fType = searchFunType;
    }
    searchFunType = fType;
    var json = new JsonObj();
    var msgId = $(me).attr("msgId");
    json.Content = "{\"msgId\":\"" + msgId + "\",\"key\":\"" + $(me).attr("key") + "\",\"funType\":" + fType + "}";
    json.pageIndex = pageIndex;
    window.searchMsgID = msgId;
    ShowLoading();
    AjaxRequest(searchFunType, "QueryMessageContextByID", "", json.ToJson(), function(status, outTxt, outJson) {
        backObj.AddStep();
        isSearch = false;
        GoToContextShowMenu(searchFunType);
        if (fType == 1) {
            contactID = outJson.contactId;
            contactGroupID = GetContactGroupID(contactID);
            funType = 1;
            ShowTip(contactID, 1);
            ShowCurItem($("#div" + contactID + contactGroupID));
        } else if (fType == 2) {
            funType = 2;
            groupID = outJson.groupId;
            var gId = GetgId(groupID);
            ShowCurItem($("#div" + gId));
            ShowTip(groupID, 2);
        } else if (fType >= 3) {
            funType = 3;
            smsType = (fType == 4 ? 0 : 1);
            ShowTip("", 3);
            if (smsType == 0) {
                $("#divMySelfSms").addClass("show");
                $("#divOtherSms").removeClass("show");
            } else {
                $("#divMySelfSms").removeClass("show");
                $("#divOtherSms").addClass("show");
            }
        }
        SelectTopMenuItem($("#ulTopMenu li").eq(funType - 1));
        isSearchGoTo = true;
        ShowMessage(outJson);
        //        $("#manegeWrap dl").removeClass("mouse_on"); 
        //        for (var i = 0; i < $("#manegeWrap dl").length; i++) {
        //            if ($("#manegeWrap dl").eq(i).attr("id") == msgId) {
        //                $("#manegeWrap dl").eq(i).addClass("mouse_on");
        //                $('.his_ct_m').scrollTop($("#manegeWrap dl").eq(i).offset().top-78);
        //                break;
        //            }
        //        }
    });
    window.event.returnValue = false;
}
//修改或者删除指定的定时短信
function GoEditOrDelSms(me, operate) {
    var fType = $(me).attr("funType");
    if (fType == undefined || fType == null || fType == "") {
        fType = searchFunType;
    }
    searchFunType = fType;
    var json = new JsonObj();
    var msgId = $(me).attr("msgId");
    //json.Content = "{\"msgId\":\"" + msgId + "\",\"key\":\"" + $(me).attr("key") + "\",\"funType\":" + fType + "}";
    json.Content = "msgId:" + msgId + ";key:" + $(me).attr("key") + ";funType:" + fType;
    json.pageIndex = pageIndex;
    window.searchMsgID = msgId;
    if (operate == 1) {
        operate = "EditScheduleSms";    // 编辑定时短信
    } else {
        operate = "DelScheduleSms";
    }
    AjaxRequest(searchFunType, operate, "", json.ToJson(), function(status, outTxt, outJson) {
        ShowTip(outJson.tc, 3);
        ShowMessage(outJson, 2);
        if (operate == "EditScheduleSms" && outJson.msgid) {
            if ($("#manegeWrap").find("dl").length > 0) {
                var lastDl = $("#manegeWrap").find("dl").eq($("#manegeWrap").find("dl").length - 1);
                lastDl.removeClass("mouse_on");
            }
            $("#" + outJson.msgid).addClass("mouse_on");
        }
    });
    window.event.returnValue = false;
}

function GetgId(groupId) {
    var gId = "";
    for (var i = 0; i < groupList.length; i++) {
        if (groupId == groupList[i].uri) {
            gId = groupList[i].id;
            break;
        }
    }
    return gId;
}

function ShowLoading() {
    //$(".history_ct").hide();
    $("#divPaging").hide();
    var loading = "<div class=\"his_chat_inf\" id=\"divSearchLoading\"> \
                    <p class=\"tips_2\"><img alt='' src=\"img/hm_loading.gif\">查找中，请稍候...</p>\
                  </div>"
    $("#manegeWrap").html(loading);
}

function SearchMsgClick() {
    backObj.step = 0;
	searchKey="";
    SearchMsg(0);
}

var txtKeyContent = "";
function SearchMsg(pIndex) {
    $(".search_type").hide();
    if ($("#txtSearchType").attr("realVal") == "0") {
        if ($("#txtKey").val() == "查找内容"&&(searchKey==null||searchKey=="")) {
            $("#divSearchTip").show();
            $("#txtKey").focus();
            $("#txtKey").val("");
            return;
        }
        if ($.trim($("#txtKey").val()) == ""&&(searchKey==null||searchKey=="")) {
            $("#divSearchTip").show();
            $("#txtKey").focus();
            return;
        }
        if($.trim($("#txtKey").val().replace("\\", "\\\\"))!=""&&$.trim($("#txtKey").val().replace("\\", "\\\\"))!="查找内容"){
			searchKey = $.trim($("#txtKey").val().replace("\\", "\\\\"));
		}
    } else {
        searchKey = "<object type='IMG'"; //搜索图片就搜索这一串
        $("#txtKey").val("");
    }
    txtKeyContent = "";
    if (backObj.step == 0) {
        backObj.SaveCurrentInfo();
    }
    pageIndex = pIndex;

    ShowLoading();
    var jsonObj = new JsonObj();
    searchFunType = funType;
    var realVal = $("#txtSearchRange").attr("realVal");
    var localSmsType = 0;
    if (realVal == "5") {
        searchFunType = 1;
    } else if (realVal == "6") {
        searchFunType = 2;
    } else if (realVal == "7") {
        searchFunType = 3;
        localSmsType = 2; //短信
    } else if (realVal == "0") {
        localSmsType = 0; //发给自己的短信
    } else if (realVal == "1") {
        localSmsType = 1; //发给别人的短信
    }else if(realVal == "8"){
		searchFunType = 6;
	}
    var isShowRoam = funType != 3;
    if (funType == 1 && "9999980" == contactGroupID||"9999999" == contactGroupID) { //公众好友不显示漫游
        isShowRoam = false;
    }
    if (smsGroupMsg == groupType) {
        FocusOnLocalOrRoam(true, false);
    } else {
        FocusOnLocalOrRoam(true, isShowRoam);
    }
    jsonObj.funType = searchFunType;
    jsonObj.pageIndex = pageIndex;
    jsonObj.btType = parseInt($("#txtSearchRange").attr("btType"));
    jsonObj.Content = "{\"key\":\"" + searchKey + "\",\"searchRange\":\"" + realVal + "\",\"timeType\":" + $("#txtSearchTime").attr("realVal") + ",\"smsType\":" + localSmsType + "}";
    AjaxRequest(searchFunType, "SearchHistoryMessage", "", jsonObj.ToJson(), function(status, outTxt, outJson) {
        isSearch = true;
        $("#divTitleTip").html("已搜索到" + outJson.tc + "条记录");
        $("#divCalendar").hide();
        if (outJson.tc > 0) {
            $("#divBack").show();
            ShowMessage(outJson);
        } else {
            if (funType == 6){
				$('#manegeWrap').html("<p class='tips_1'><img src='img/no-tag.png'></p>");
			}else{
				$('#manegeWrap').html("<p class='tips_1'><img src='img/2_tips.png'></p>");
			}
			//$('#manegeWrap').html("<p class='tips_1'><img src='img/2_tips.png'></p>");
            $("#ulPaging").parent().hide();
            $("#divCalendar").hide();
            SetBackRefreshDelete(false);
        }
    });
}

$(document).ready(function() {
    $("#liGroup").click(function() {
        $('#divMenu').empty();
        isDirectShowContact = false;
        GroupClick(this, 0);
    })
    searchRangeClickBind();
})

function ChangeSearchRange(curId) {
    $("#selSearchRange li").each(function() {
        if ($(this).attr("btType") != "0") {
            $(this).remove();
        }
    })

    $("#selSearchRange li").removeClass("p_on");
    if (funType == 1) {
        $("#selSearchRange").append("<li realVal='" + $("#div" + curId).attr("groupId") + "' btType='32'><a>当前分组</a></li>");
        $("#selSearchRange").append("<li realVal='" + $("#div" + curId).attr("userId") + "' btType='64' class='p_on'><a>当前联系人</a></li>");
    } else if (funType == 2) {
        if (groupMsg == groupType) {
            $("#selSearchRange").append("<li realVal='sip:PG' btType='32'><a>当前分组</a></li>");
            $("#selSearchRange").append("<li realVal='" + curId + "' btType='64' class='p_on'><a>当前群</a></li>");
        /*} else if (smsGroupMsg == groupType) {
            $("#selSearchRange").append("<li realVal='sip:SG' btType='32'><a>当前分组</a></li>");
            $("#selSearchRange").append("<li realVal='" + curId + "' btType='64' class='p_on'><a>当前拇指群</a></li>");*/
        } else {
            $("#selSearchRange").append("<li realVal='sip:DG' btType='32'><a>当前分组</a></li>");
            $("#selSearchRange").append("<li realVal='" + curId + "' btType='64' class='p_on'><a>当前讨论组</a></li>");
        }
    } else if (funType == 3 && smsType != 2) {
        $("#selSearchRange").append("<li realVal='" + curId + "' btType='32' class='p_on'><a>当前分组</a></li>");
    }
    searchRangeClickBind();
    var curLi = $("#selSearchRange li").eq($("#selSearchRange li").length - 1);
    $("#txtSearchRange").attr("realVal", curLi.attr("realVal"));
    $("#txtSearchRange").attr("btType", curLi.attr("btType"));
    $("#txtSearchRange").val(curLi.find("a").html());
}

function searchRangeClickBind() {
    $("#selSearchRange li").click(function() {
        $("#txtSearchRange").attr("realVal", $(this).attr("realVal"));
        $("#txtSearchRange").attr("btType", $(this).attr("btType"));
        $("#txtSearchRange").val($(this).find("a").html());
        $('#selSearchRange').parent().hide();
        $("#selSearchRange li").removeClass("p_on");
        $(this).addClass("p_on");
    });

    $("#selSearchTime li").click(function() {
        $("#txtSearchTime").attr("realVal", $(this).attr("realVal"));
        $("#txtSearchTime").val($(this).find("a").html());
        $('#selSearchTime').parent().hide();
        $("#selSearchTime li").removeClass("p_on");
        $(this).addClass("p_on");
    });

    $("#selSearchType li").click(function() {
        $("#txtSearchType").attr("realVal", $(this).attr("realVal"));
        $("#txtSearchType").val($(this).find("a").html());
        $('#selSearchType').parent().hide();
        $("#selSearchType li").removeClass("p_on");
        $(this).addClass("p_on");
        if ($(this).attr("realVal") == "1") {
            if ($("#txtKey").val() != "") {
                txtKeyContent = $("#txtKey").val();
            }
            $("#txtKey").val("");
            $("#txtKey").attr("disabled", "disabled");
        } else {
            if ($("#txtKey").val() == "") {
                $("#txtKey").val(txtKeyContent);
            }
            $("#txtKey").focus();
            $("#txtKey").attr("disabled", "");
        }
    });
}

//刷新当前信息，点击日历右边的执行这个方法
function RefrushCurItem() {
    pageIndex = 0;
    if (isfocusOnRoam) {//刷新漫游记录
        if (funType == 1) {
            GetContactRoamMsg("0", pageIndex);
        } else if (funType == 2) {
            GetGroupRoamMsg("0", pageIndex);
        }
    } else {//刷新本地消息
        if (funType == 1) {
            ShowContactMessage($("#div" + contactID + contactGroupID), pageIndex)
        } else if (funType == 2) {
            ShowGroupMessageById();
        } else {
            ShowSmsMessage(smsType, pageIndex);
        }
    }
}

//查找文本框相关事件
$(document).ready(function() {
    $("#txtKey").bind("click", function() {
        $('.search_type').show();
        $('#divSearchTip').hide();
        if ($(this).val() == '查找内容') {
            $(this).val('');
        } else if ($.trim($(this).val()) != "") {
            $(this).select();
        }
    })

    $("#txtKey").bind("keypress", function() {
        if (event.keyCode == 13) {
            SearchMsg(0);
        }
    })

    $("#txtKey").bind("blur", function() {
        if ($.trim($(this).val()) == '') {
            $(this).val('查找内容');
            $("#divSearchTip").hide();
        }
    })

    $("#txtKey").bind("keyup", function() {
        if ($.trim($(this).val()) != '') {
            $('#divSearchTip').hide();
            if (event.keyCode != 13) {
                $('.search_type').show();
            }
        }
    })

    $("#txtPageIndex").bind("keyup", function() {
        $(this).val($(this).val().replace(window.getSelection(), ''));
        $(this).val($(this).val().replace(/\D/g, ''));
    })

    $("#txtPageIndex").bind("keypress", function() {
        if (event.keyCode == 13) {
            pageIndex = parseInt($(this).val());
            if (pageIndex > totalPage) {
                pageIndex = totalPage;
            }
            if (isfocusOnRoam) {
                if (funType == 1) {
                    GetContactRoamMsg("0", pageIndex);
                } else if (funType == 2) {
                    GetGroupRoamMsg("0", pageIndex);
                }
            } else {
                if (isSearch) {
                    SearchMsg(pageIndex);
                } else {
                    switch (funType) {
                        case 1:
                            ClickMenuShowMessage($("#div" + contactID + contactGroupID), pageIndex);
                            break;
                        case 2:
                            ShowGroupMessageById();
                            break;
                        case 3:
                            ClickMenuShowMessage(smsType, pageIndex);
                            break;
						case 6:
                            ClickMenuShowMessage($("#"+curTagType), pageIndex);
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    })

    $("#txtPageIndex").bind("blur", function() {
        if ($.trim($(this).val()) == '') {
            $(this).val(pageIndex);
        }
    })


    $("#btBack").click(function() {
        backObj.BackStep();
    })
})

function addClass(me, c) {
    if (event.ctrlKey == false) {
        if (messageIds == "") {
            $(".his_chat_inf dl").removeClass(c);
        }
        if (me.className.indexOf(c) == -1) {
            me.className = c;
        }
        curMsgId = $(me).attr("id");
    }
}

function removeClass(me, c) {
    if (me != null && event.ctrlKey == false) {
        if (me.className != null) {
            me.className = "";
        }
        messageIds = "";
        curMsgId = "";
    }
}

function MouseDbClickHistoryRecord(me) {
    e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
    var tname;
    tname = targ.tagName;

    //图片双击
    if (tname.toLocaleLowerCase() == "img") {
        return;
    }
}


function ClickMessage(me, smsType) {
    if (event.ctrlKey == true) {
        $(".history_con").attr("style", "-webkit-user-select: none;");
    } else {
        $(".history_con").attr("style", "");
    }

    if (event.ctrlKey == true && event.shiftKey == true) {
        if (curMsgId != "") {
            var start = 0, end = 0, index = 0;
            $("#manegeWrap dl").each(function() {
                if ($(this).attr("id") == curMsgId) {
                    start = index;
                } else if ($(this).attr("id") == $(me).attr("id")) {
                    end = index;
                }
                index++;
            });
            if (end < start) {
                var tmp = end;
                end = start;
                start = tmp;
            }
            for (var i = start; i <= end; i++) {
                if (messageIds.indexOf($("#manegeWrap dl").eq(i).attr("id")) < 0) {
                    messageIds += "|" + $.trim($("#manegeWrap dl").eq(i).attr("id"));
                }
                $("#manegeWrap dl").eq(i).addClass("mouse_on");
            }
        }
    } else {
        if (event.ctrlKey == true) {
            if (messageIds.indexOf($(me).attr("id")) >= 0) {
                messageIds = messageIds.replace("|" + $(me).attr("id"), "");
                $(me).removeClass("mouse_on");
            } else {
                messageIds += "|" + $.trim($(me).attr("id"));
                $(me).addClass("mouse_on");
            }
        } else {
            if (smsType != 2) {
                $(".mouse_on").removeClass("mouse_on");
                $(me).addClass("mouse_on");
            }
            messageIds = "";
        }
    }
    if (messageIds != "") {
        curMsgId = $(me).attr("id");
    } else {
        curMsgId = "";
    }
}

function MouseClickHeightLightMe(me) {
    if (me == null) {
        return;
    }
    if (window.event.button == 1) {//处理左键   
        return;
    }

    //处理右键
    ShowCurMenu(me);
    window.event.returnValue = false;
}

var noRightMenuNewMsg = ["OUT_CE", "CE_AUDIO", "OP_CARD", "FEINNO_CARD", "AUDIO", "AUDIOLINK", "VIDEO", "FOCUS_PICTEXT", "LOCATION", "EMAIL", "GAMELINK", "MULTI_PICTEXT", "IMGS", "GROUP_CARD", "URLLINK", "OUTCARD", "PHONE_CARD", "FILE"];

function ShowCurMenu(me) {
	if(event.ctrlKey == false){
		$(".mouse_on").removeClass("mouse_on");
		$(me).addClass("mouse_on");
	}
    if (me != "clip" && (me == null || window.event.button != 2 || window.event.returnValue == false)){	//只处理右键
        return;
	}
	if(window.event.button == 2){
		window.selMsgCtrl = null;
	}
    var selRange = getSelectedText();
    var selectText = selRange.text;
    var command = "ShowMenu", txt = "";
    if (me == "clip") {
        command = "SetClipbrd";
    }

    var p = mousePosition(window.event, me);
    var jsonObj = new JsonObj();
    jsonObj.X = p.x;
    jsonObj.Y = p.y;
    jsonObj.isRoam = isfocusOnRoam ? 1 : 0;
    if (selectText != "") 	//框选
    {
        jsonObj.Content = selectText;
        jsonObj.ContentValue = selRange.value;
        jsonObj.btType = 2;
        if (jsonObj.Content == "[图片]" && jsonObj.ContentValue != jsonObj.Content) {
            jsonObj.btType = 8;
        }
    }
    else {
        e = window.event;
        if (window.selMsgCtrl && window.selMsgCtrl != null) {
            targ = window.selMsgCtrl.img;
        }
        else if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;
        window.selMsgCtrl = null;
        if (targ.tagName == undefined || targ.tagName.toLocaleLowerCase() != "img") { //不在图片上右键
            jsonObj.btType = 0;
            jsonObj.userId = funType == 1 ? contactID : groupID;
			if(!jsonObj.userId){
				jsonObj.userId="";
			}
            jsonObj.isRoam = isfocusOnRoam ? 1 : 0;
            var isShowCopy = 1; //是否显示复制菜单项   
            var isShowDelete = 1; //是否显示删除菜单项  
            var msgId = "[";
            var msgContent = "";
            $("#manegeWrap").find(".mouse_on").each(function() {
                msgId += "{\"id\":\"" + $(this).attr("id") + "\",\"uid\":\"" + $(this).attr("uid") + "\",\"key\":\"" + $(this).attr("key") + "\",\"date\":\"" + $(this).attr("date") + "\"},";
                $(this).find(".see_mes").remove();
                if ($(this).find(".more_operate").length > 0) {
                    isShowDelete = 0;
                }
                msgContent += "<dl>" + $(this).html() + "</dl>";
                var types = $(this).find("dd").attr("typelist").split(",");
                for (var j = 0; j < types.length; j++) {
                    for (var i = 0; i < noRightMenuNewMsg.length; i++) {
                        if (types[j] == noRightMenuNewMsg[i]) {
                            isShowCopy = 0;
                            break;
                        }
                    }
                    if (isShowCopy == 0) {
                        break;
                    }
                }
            });
            var str1 = handleSelectedStr(msgContent);
            jsonObj.ID = msgId.substr(0, msgId.length - 1) + "]";
            jsonObj.Content = str1.text;
            jsonObj.ContentValue = str1.value;
            jsonObj.isShowCopy = isShowCopy;
            jsonObj.isShowDelete = isShowDelete;
            if (me != "clip") {
                command = "ShowTool";
            }
        }
        else if (targ.tagName.toLocaleLowerCase() == "img") {	//图片上右键 
            var type = $(targ).attr("type");
            if (type == null || type == "" || "HEAD,TEXT,CE,IMG,CE_AUDIO,OUT_CE".indexOf(type) == -1)
                return false;

            imgFilePath = unescape($(targ).attr("src"));
            imgFilePath = imgFilePath.replaceAll("/", "\\");
            indexRight = imgFilePath.lastIndexOf("\\");
            var fileName = imgFilePath.substring(indexRight + 1);
            if (indexRight <= 0) {
                //alert("error");
                return;
            }
            tmpPath = imgFilePath.substring(0, indexRight);
            indexLeft = tmpPath.lastIndexOf("\\");
            filePathName = imgFilePath.substring(indexLeft + 1, indexRight);

            //temp文件夹是普通图片，customemotion、received文件夹下是表情
            TMEP_PATH = "temp";
            CUSTOM_EMOTION_PATH = "customemotion";
            CUSTOM_SLIENT_EMOTION_PATH = "emotions";
            EMOTION_RECEIVED_PATH = "received";
            tmpFilePathName = filePathName.toLocaleLowerCase();
            if (tmpFilePathName == TMEP_PATH
				|| tmpFilePathName == CUSTOM_EMOTION_PATH
				|| tmpFilePathName == CUSTOM_SLIENT_EMOTION_PATH
				|| tmpFilePathName == EMOTION_RECEIVED_PATH) {
                jsonObj.Content = imgFilePath.replace("file:\\\\\\", "");
                jsonObj.Content = jsonObj.Content.replace("file:///", "");
                jsonObj.btType = 8;
            }
            else {
                jsonObj.btType = 0;
            }

            $(me).find("img").each(function() {
                if ($(this).attr("src").indexOf(fileName) >= 0) {
                    jsonObj.imgType = $(this).attr("type") == undefined ? "" : $(this).attr("type");
                    var id, type1;
                    if ($(this).attr("type") == "CE_AUDIO" || $(this).attr("type") == "OUT_CE") {
                        id = fileName.substr(0, fileName.indexOf('.'));
                    } else {
                        id = $(this).attr("id");
                    }
                    var imgObj = "<OBJECT ID='" + id + "' type='" + $(this).attr("type") + "' name='" + fileName + "'>" + $(this).attr("shortcut") + "</OBJECT>";
                    jsonObj.ContentValue = jsonObj.ID = imgObj;
                }
            });
        }
    }
	var mIds = [];
	$("#manegeWrap").find(".mouse_on").each(function() {
		mIds[mIds.length]=$(this).attr("id");
		jsonObj.msgId=mIds;
	});
    jsonObj.ID = jsonObj.ID.replace(/(src)=("[^"]*")|\s$/g, "").replaceAll('imgid', 'ID')
            .replace(/<img/gi, "<OBJECT").replace(/img>/gi, "OBJECT>").replace(/<\/?(FONT|P|TABLE)[^>]*>/gi, "");
    jsonObj.ID = jsonObj.ID.replace("<[^>]*>", "").replace(/&nbsp;/gi, " ");
    $(".seac_pop").hide();
    $(".search_type").hide();
    SMAjax(funType, command, txt, jsonObj.ToJson());
}

function SMAjax(funType, command, txt, json) {
    AjaxRequest(funType, command, txt, json, function(status, outTxt, outJson) {
        if (outTxt == "SelectAll") {
            SelectAll();
        }
        else if (outTxt == "Refrush") {
            if (isfocusOnRoam) {//刷新漫游记录
                if (funType == 1) {
                    GetContactRoamMsg("0", pageIndex);
                } else if (funType == 2) {
                    GetGroupRoamMsg("0", pageIndex);
                }
            } else {//刷新本地记录
                if (isSearch) {
                    backObj.AddStep();
                    backObj.BackStep();
                } else {
                    if (funType == 1) {
                        ShowContactMessage($("#div" + contactID + contactGroupID), pageIndex)
                    } else if (funType == 2) {
                        ShowGroupMessageById();
                    } else if (funType == 3) {
                        ShowSmsMessage(smsType, pageIndex);
                    }
                }
            }

        }

    });
}

function mousePosition(ev, me) {
    if (ev.screenX || ev.screenY) {
        return { x: ev.screenX, y: ev.screenY };
    }
    return {
        x: ev.clientX - document.body.scrollLeft,
        y: ev.clientY - document.body.scrollTop
    };
}

function handleSelectedStr(str) {
    var replaceKey = "嗭";
    str = str.replaceAll('<br>', replaceKey);
    str = str.replaceAll('><dt> ', '><dt>');
    str = str.replaceAll('</h1><', replaceKey + '</h1><');
    str = str.replaceAll('</dt><dd', replaceKey + '</dt><dd');
    str = str.replaceAll('</dd></dl><', '</dd>' + replaceKey + '</dl><');
    var showDiv = $('<div id="showDiv" style="display:none"></div>');
    $('body').append(showDiv);

    showDiv.html(str);
    showDiv.find('.spanSpace').remove();
    //showDiv.find('table').remove();
    if ($("#showDiv").find(".spanMore").css("display") == "none") {
        $("#showDiv").find(".spanMore").remove();
    }
    if ($("#showDiv").find(".divExtend").css("display") == "none") {
        $("#showDiv").find(".divExtend").remove();
    }

    var imgItems = showDiv.find('img');

    if (imgItems.length > 0) {
        for (var i = 0; i < imgItems.length; i++) {
            var st = imgItems.eq(i).attr('shortcut');
            if (st != undefined) {
                imgItems.eq(i).removeAttr('style').removeAttr('shortcut').removeAttr('title').removeAttr('class').removeAttr('width').removeAttr('height');
                imgItems.eq(i).html(imgItems.eq(i)[0].outerHTML + st + '</img>');
            } else {
                imgItems.eq(i).remove();
            }
        }
    }

    var str2 = $('#showDiv').html();
    var selText = $('#showDiv').text();
    $('#showDiv').remove();
    str2 = str2.replace(/(src|style)=("[^"]*")|\s$/g, "");
    str2 = str2.replace(/<img/gi, "<OBJECT");
    str2 = str2.replace(/<(?!((OBJECT) |(OBJECT)>|(BR)|(BR)>|\/(OBJECT)>))[^>]+>/g, '');
    str2 = str2.Trim();
    str2 = str2.replaceAll('&nbsp;', ' ');
    str2 = str2.replace(/(\n[\s|\t]*\r*\n)/g, '\r\n');    //去除多余空行 
    str2 = str2.replaceAll(replaceKey, '\r\n');
    str2 = str2.replace(/(^\s+)|(\s+$)/g, "");
    str2 = str2.replaceAll('type="OBJECT"', 'type="IMG"');
    var htmlstr = str.replace(/<\/?(FONT|P|TABLE)[^>]*>/gi, "");
    var isImg = htmlstr.Trim().substring(0, 4) == ('<IMG');
    var urlStr = (isImg == true) ? $(htmlstr).attr("src").replace('fetionres:///', '') : '';
    selText = selText.replaceAll(String.fromCharCode(160), String.fromCharCode(32)).replace(/(^\s+)/g, "").replace(/<OBJECT.*?OBJECT>/g, "").replace("<[^>]*>", "").replace(/<br>/g, "\n").replace(/<br\/>/g, "\n").replace(/<BR>/g, "\n").replace(/<BR\/>/g, "\n");
    selText = selText.replaceAll(replaceKey, '\r\n');
    return {
        text: selText, value: str2
    };
}


function getSelectedText() {
    var container = document.createElement('div');
    var range = window.getSelection();
    try {
        container.appendChild(range.getRangeAt(0).cloneContents());
    }
    catch (e) {
    }
    return container.innerHTML ? handleSelectedStr(container.innerHTML) : { text: "", value: "" };
}


//点击左键隐藏菜单和取消选中的内容
function HideMenu() {
    $(".seac_pop").hide();
    $(".search_type").hide();
    var jsonObj = new JsonObj();
    jsonObj.btType = 0;
    SMAjax(funType, "ShowMenu", "", jsonObj.ToJson());
    window.event.returnValue = true;
}


//全选
function SelectAll() {
    var text = document.getElementById("manegeWrap");
    if ($.browser.msie) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if ($.browser.mozilla || $.browser.opera) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    } else if ($.browser.safari) {
        var selection = window.getSelection();
        selection.setBaseAndExtent(text, 0, text, 9999);
    }
}

//左键点击手机号
function phoneLeftClick(me) {
    var p = mousePosition(window.event, me);
    var jsonObj = new JsonObj();
    jsonObj.X = p.x;
    jsonObj.Y = p.y;

    jsonObj.Content = $(me).text();
    jsonObj.btType = 16;
    SMAjax(funType, "ShowMenu", "", jsonObj.ToJson());
    window.event.returnValue = false;
}

//右键点击手机号
function phoneRightClick(me) {
    if (me == null || window.event.button != 2)	//只处理右键
        return;

    var p = mousePosition(window.event, me);
    var jsonObj = new JsonObj();
    jsonObj.X = p.x;
    jsonObj.Y = p.y;
    jsonObj.Content = $(me).text();
    jsonObj.btType = 2;
    SMAjax(funType, "ShowMenu", "", jsonObj.ToJson());
    window.event.returnValue = false;
}

//打开地址
function OpenUrl(url) {
    var jsonObj = new JsonObj();
    jsonObj.Content = url;
    SMAjax(funType, "OpenUrl", "", jsonObj.ToJson());
}

//查看图片
function OpenPicture(src) {
    var jsonObj = new JsonObj();
    jsonObj.Content = src;
    SMAjax(funType, "OpenPicture", "", jsonObj.ToJson());
}

//打开文件
function OpenFile(filePath) {
    AjaxRequest(0, "OpenFile", filePath, "", null);
}

//打开文件夹
function OpenFolder(filePath) {
    AjaxRequest(0, "OpenFolder", filePath, "", null);
}


//开始加载
function InitLoad() {
    var selectType = document.getElementById("divSelectType");
    selectType.onclick = function(ev) {
        ev = ev || event;
        this.style.display = "block";
        ev.cancelBubble = true;
    }
    document.onclick = function() {
        e = window.event;
        if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;
        var targetId = targ.id;
        if (targetId == "txtKey") {
            selectType.style.display = "block";
        } else {
            if (targetId != "aSearch") {
                $(".seac_pop").hide();
            }
            selectType.style.display = "none";
            $(".person_list").hide();
        }
    }
    document.onkeydown = function() {
        if ((event.ctrlKey) && (event.keyCode == 65)) {
            SelectAll();
            return false;
        }
        if ((event.ctrlKey) && (event.keyCode == 67)) {
            try {
                //执行拷贝
                ShowCurMenu("clip");
            }
            catch (e) {
                //alert(e);
            }
            return false;
        }
        return true;
    }

    AjaxRequest(funType, "InitLoad", "", "", InitLoadBack);
}

//点击联系人
function ShowRoamItem(fType) {
    $(".history_ct").show();
    SelectTopMenuItem($("#liOpenRoam"));
    funType = fType;
    var me;
    if (funType == 1) {
        ShowContactMenu();
        me = $("#div" + contactID + contactGroupID);
    } else if (funType == 2) {
        ShowGroupMenu();
        var gId = GetgId(groupID);
        me = $("#div" + gId);
    } else {
        return;
    }

    var btType = $(me).attr("btType");
    $("#divMenu dl").find("dd").removeClass("show");
    if (btType == "32") {
        $(me).next().addClass("show");
    } else {
        $(me).addClass("show");
    }
    contactID = $(me).attr("userId");
    ShowCurItem(me);
    ShowTip(contactID, 1);

    if (isDirectShowContact) {
        var top = me.offset().top;
        $("#divMenu").scrollTop(top - 45);
    }
    $(".msgex").show();
    FocusOnLocalOrRoam(false, true);
    if (ownerInfo.isOpenRoam == 1) {//云服务已开启，显示记录
        if (funType == 1) {
            GetContactRoamMsg("0", 0);
        } else {
            GetGroupRoamMsg("0", 0);
        }
    } else {//没开启，引导开通
        OpenRoamNavigation();
    }
}

var responseCount = 0;
var isTimeSmsMenu = 0;

function InitLoadBack(status, outTxt, outJson) {
    if (outTxt == "QueryContactList") {
        contactList = outJson;
        responseCount++;
    } else if (outTxt == "QueryGroupList") {
        groupList = outJson;
        responseCount++;
    } else if (outTxt == "QueryContactGroupList") {
        contactGroupList = outJson;
        responseCount++;
    } else if (outTxt == "QueryOwnerInfo") {
        ownerInfo = outJson[0];
        funType = ownerInfo.funType;
        isCM = ownerInfo.isCM;

        if (ownerInfo.isTimeSmsMenu != undefined) {
            isTimeSmsMenu = ownerInfo.isTimeSmsMenu;
        }
        if (funType == 1 && ownerInfo.contactID != "") {
            contactID = ownerInfo.contactID;

        } else if (funType == 2 && ownerInfo.contactID != "") {
            groupID = ownerInfo.contactID;
        }
        SetRoamStatus(ownerInfo.isOpenRoam);
        responseCount++;
    }

    if (responseCount == 4) {
        responseCount = 0;
        if (funType <= 0) {
            funType = 1;
        }
        switch (funType) {
            case 1:         //联系人
                isDirectShowContact = contactID != "";
                contactGroupID = GetContactGroupID(contactID);
                if (ownerInfo.isShowRoam == 1) {
                    ShowRoamItem(funType)
                } else {
                    ContactClick($("#liContact"), 0);
                }
                break;
            case 2:         //群组 
                isDirectShowContact = groupID != "";
                if (ownerInfo.isShowRoam == 1) {
                    ShowRoamItem(funType)
                } else {
                    GroupClick($('#divMenu'), 0);
                }
                break;
            case 3:         //短信
                if (isTimeSmsMenu == 0) {
                    $("#liSms").onlick = SmsClick(this, 0, 0);
                } else {
                    $("#liSms").onlick = SmsClick(this, 0, 0, true);
                }
                break;
			case 6:         //标记
                //"标记";
                break;
            case 4:         //系统
                //"系统";
                break;
            default:        //工具
                //"工具";
                break;
        }
    } else {
        ShowLoading();
    }
}

function ListenWidgetBack(status, outTxt, outJson) {
    if (outTxt == "Redirect") {//已经打开的窗口，重定位到某联系人/群组/短信
        funType = outJson.funType;
        if (funType == 1) {
            contactID = outJson.contactID;
        } else if (funType == 2) {
            groupID = outJson.contactID;
        }
        if (outJson.isTimeSmsMenu != undefined) {
            isTimeSmsMenu = outJson.isTimeSmsMenu;
        }
        ownerInfo.isShowRoam = outJson.isShowRoam;
        switch (funType) {
            case 1:         //联系人
                isDirectShowContact = contactID != "";
                contactGroupID = GetContactGroupID(contactID);
                if (ownerInfo.isShowRoam == 1) {
                    ShowRoamItem(funType)
                } else {
                    ContactClick($("#liContact"), 0);
                }
                break;
            case 2:         //群组
                isDirectShowContact = groupID != "";
                if (ownerInfo.isShowRoam == 1) {
                    ShowRoamItem(funType)
                } else {
                    GroupClick($("#liGroup"), 0);
                }
                break;
            case 3:         //短信
                if (isTimeSmsMenu == 0) {
                    $("#liSms").onlick = SmsClick(this, 0, 0);
                } else {
                    $("#liSms").onlick = SmsClick(this, 0, 0, true);
                }
                break;
			case 6:         //短信
                TagClick();
                break;
        }
        if (ownerInfo.isShowRoam == 1) {
            $("#liOpenRoam").click();
        }
    } else if (outTxt == "ChangeTheme") {
        ChangeTheme(outJson);
    } else if (outTxt == "CloseCalendar") {//关闭日历控件
        $("#dp-popup").hide();
    } else if (outTxt == "RoamResponseTip") {//漫游请求返回提示
        ShowRoamTip(outJson.responseCode);
    } else if (outTxt == "UpdateCtrl") {//更新信息  
        Fetion.Web.Chat.updateCtrl(outJson);
    }
}

//换肤
function ChangeTheme(json) {
    $('.wrap')[0].style.background = (json.layout&&json.layout==1)?("url(" + json.themeSrc + ") repeat top left"):("url(" + json.themeSrc + ") no-repeat top left ");//$('.wrap')[0].style.backgroundImage = "url(" + json.themeSrc + ")";
    $('.wrap')[0].style.backgroundColor = json.bgColor;
	if(json.posX){
		$('.wrap')[0].style.backgroundPositionX = json.posX;
	}
	if(json.posY){
		$('.wrap')[0].style.backgroundPositionY = json.posY;
	}
}


function AjaxRequest(path, command, txt, json, funBack) {
    SM.ajax(path, command, txt, json, function(status, outTxt, outJson) {
        if (funBack != undefined && funBack != null && funBack != "") {
            funBack(status, outTxt, outJson);
        }
    });
}



//----------------------------------------云聊天记录相关功能------------------------------start

//显示云聊天记录相关提示
function ShowRoamTip(tipType) {
    $("#divProtocol").hide();
    var content = null;
    if (tipType == 1) {      //1:关闭云聊天服务
        content = "<p class=\"tips_1\"><img src=\"img/close_tips.png\"></p>" +
                "<p class=\"opt_btn01\"><input type=\"button\" class=\"btn03\" value=\"确定\" onclick=\"CloseRoamSuccess();\"></p>";
        SetRoamStatus(0);
    } else if (tipType == 2) {//2:没有云聊天记录
        content = "<p class=\"tips_1\"><img src=\"img/no_tips2.png\"></p>";
    } else if (tipType == 3) {//3:成功开启云聊天服务记录
        SetRoamStatus(1);
        content = "<p class=\"tips_1\"><img src=\"img/suc_tips.png\"></p>" +
                "<p class=\"opt_btn01\"><input type=\"button\" class=\"btn03\" value=\"确定\" onclick=\"ShowRoamRecord();\"></p>";
    } else if (tipType == 4) {//4:验证已经达到当日上限
        content = "<p class=\"tips_1\"><img src=\"img/check_tips.png\"></p>";
    } else if (tipType == 5) {//5:网络连接失败
        content = "<p class=\"tips_1\"><img src=\"img/fale_tips.png\"></p>";
    } else if (tipType == 7) {//7:操作失败
        content = "<p class=\"tips_1\"><img src=\"img/1210_tips2.png\"></p>";
    }
    if (content != null) {
        $("#divCalendar").hide();
        $("#divBack").hide();
        $("#divPaging").hide();
        content = "<div class=\"his_chat_inf\">" + content + "</div>";
        $("#manegeWrap").html(content);
        $("#manegeWrap").removeClass("his_chat pd_t01").addClass("his_chat");
        $(".history_ct").show();
    }
}

function CloseRoamSuccess() {
    if (funType != 1 && funType != 2) {
        funType = 1;
        contactID = ownerInfo.uid;
        contactGroupID = ownerInfo.gs;
        SelectTopMenuItem($("#ulTopMenu li").eq(0));
        ShowContactMenu();
        isSearch = false;
        ShowCurItem($("#div" + contactID + contactGroupID));
    }
    OpenRoamNavigation();
}

//开通云服务引导页
function OpenRoamNavigation() {
    $(".history_ct").show();
    $("#divCalendar").hide();
    $("#divBack").hide();
    $("#manegeWrap").empty();
    if (funType == 1 || funType == 2) {
        FocusOnLocalOrRoam(false, true);
    }
    $("#manegeWrap").html("<div class=\"his_chat_inf\"><p class=\"tips_4\"><a id='aRoamOpen' class=\"free_kt_0\" href=\"javascript:;\"></a></p></div>");
    $("#aRoamOpen").click(function() {//开通云聊天服务
        if ($(this).attr("class") == "free_kt_0") {
            SMAjax(funType, "OpenRoamRecord", "", "");
        }
    });
    $("#manegeWrap").removeClass("his_chat pd_t01").addClass("his_chat");
    $("#divProtocol").html("<div class=\"serv_file\"><a><span class=\"check_hover\" id='checkRoamProtocol'></span><span id='spanRoamProtocol'>我已经阅读并同意以上服务协议</span></a></div>");
    $("#divProtocol").show();
    $("#divProtocol").parent().show();
    $("#checkRoamProtocol").click(function() {
        if ($(this).attr("class") == "check_hover") {
            $(this).removeClass("check_hover").addClass("check_auto");
            $("#aRoamOpen").removeClass("free_kt_0").addClass("free_kt_1");
        } else {
            $(this).removeClass("check_auto").addClass("check_hover");
            $("#aRoamOpen").removeClass("free_kt_1").addClass("free_kt_0");
        }
    })
    $("#spanRoamProtocol").click(function() {//查看云聊天服务协议
        $("#checkRoamProtocol").removeClass("check_auto").addClass("check_hover");
        $("#aRoamOpen").removeClass("free_kt_1").addClass("free_kt_0");
        SMAjax(funType, "ShowRoamProtocol", "", "");
    })
    SMAjax(funType, "CloseHistoryRoamImportTip", "", "");
}

//点击云开通记录
$("#liOpenRoam").click(function() {
    if (ownerInfo.isOpenRoam == 1) {//在开通的情况下弹出关闭菜单
        var p = mousePosition(window.event, this);
        var jsonObj = new JsonObj();
        jsonObj.X = 280;
        jsonObj.Y = 33;
        SMAjax(funType, "CloseRoamRecord", "", jsonObj.ToJson());
    } else {
        OpenRoamNavigation();
    }
})

function FocusOnLocalOrRoam(isLocal, isShowRoam,notShowLocal) {
    if (isLocal) {
        $("#divProtocol").hide();
        isfocusOnRoam = false;
        $("#liLocal").attr("class", "see_t");
        $("#liRoam").attr("class", "");
    } else {
        $("#liLocal").attr("class", "");
        $("#liRoam").attr("class", "see_t");
        if (ownerInfo.isOpenRoam == 1) {
            isfocusOnRoam = true;
        } else {
            isfocusOnRoam = false;
        }
        $("#divPaging").hide();
    }
    if (isShowRoam) {
        $("#liRoam").show();
    } else {
        $("#liRoam").hide();
    }
	if(notShowLocal||funType==6){
		$("#liLocal").hide();
	}else{
		$("#liLocal").show();
	}

}
function hideOfScheduleSmsMsg(smslocal, smsRoam) {
    if (smslocal) {
        $("#divProtocol").hide();
        isfocusOnRoam = false;
        $("#liLocal").attr("class", "see_t");
        $("#lischeduleSms").attr("class", "");
    } else {
        $("#liLocal").attr("class", "");
        $("#lischeduleSms").attr("class", "see_t");
        if (ownerInfo.isOpenRoam == 1) {
            //isfocusOnRoam = true;
        } else {
            //isfocusOnRoam = false;
        }
        $("#divPaging").hide();
    }
    if (isShowRoam) {
        $("#lischeduleSms").show();
    } else {
        $("#lischeduleSms").hide();
    }
}
//本地聊天记录
$("#liLocal").click(function() {
    isfocusOnRoam = false;
    FocusOnLocalOrRoam(true, true);
    if (funType == 1) {
        ShowContactMessage($("#div" + contactID + contactGroupID), 0);
    } else if (funType == 2) {
                var id = GetgId(groupID);
		var me =$("#div" + id);
		if($(me).html()==null){
			me = document.getElementById("div"+id);
		}
        ShowGroupMessage(me, 0);
    } else if (funType == 3) {
        ShowSmsMessage(smsType, 0);
    }
})

//显示云聊天记录
function ShowRoamRecord() {
    isSearch = false;
    FocusOnLocalOrRoam(false, true);
    if (ownerInfo.isOpenRoam == 1) {//云服务已开启，显示记录
        if (funType == 1) {
            GetContactRoamMsg("0", 0);
        } else if (funType == 2) {
            GetGroupRoamMsg("0", 0);
        } else {
            funType = 1;
            contactID = ownerInfo.uid;
            contactGroupID = ownerInfo.gs;
            SelectTopMenuItem($("#ulTopMenu li").eq(0));
            ShowContactMenu();
            isSearch = false;
            ShowCurItem($("#div" + contactID + contactGroupID));
            ShowTip(contactID, 1);
            GetContactRoamMsg("0", 0);
        }
    } else {//没开启，引导开通
        OpenRoamNavigation();
    }
}

//云聊天记录
$("#liRoam").click(function() {
    ShowRoamRecord();
})

$("#liOpenRoam").bind("mouseover", function() {
    if (ownerInfo.isOpenRoam == 1) {//云服务已开启
        $("#divOpenRoamTip").attr("class", "pop_y");
        $("#divOpenRoamTip").html("服务已开启");
    } else {
        $("#divOpenRoamTip").attr("class", "pop_wy");
        $("#divOpenRoamTip").html("完整云记录随时查看，点击去开通");
    }
    $("#divOpenRoamTip").show();
}).bind("mouseout", function() {
    $("#divOpenRoamTip").hide();
})

//设置返回/刷新/删除按钮的显示
function SetBackRefreshDelete(isShowDelete) {
    var content = null;
    if (isSearch || isSearchGoTo) {//搜索时显示返回按钮
        content = "<div class=\"option_y\" id=\"divBack\"><input class=\"btn02\" type=\"button\" value=\"\" id=\"btBack\" /></div>";
        $("#divProtocol").hide();
        $("#manegeWrap").prepend(content);
        $("#btBack").click(function() {
            backObj.BackStep();
        })
        isSearchGoTo = false;
    } else {
        if (isfocusOnRoam && isShowDelete&&funType != 6) {
            content = "<div class=\"option_y\"><a href='javascript:;' title=\"删除\" class=\"delete_auto\" id='aDeleteRoam'></a><a href='javascript:;' class=\"refresh_auto\" onclick=\"RefrushCurItem();\" title=\"刷新\"></a></div>";
        } else if(funType != 6) {
            content = "<div class=\"option_y\"><a href='javascript:;' class=\"refresh_auto\" onclick=\"RefrushCurItem();\" title=\"刷新\"></a></div>";
        }else{
			content="<div class=\"option_y\"></div>";
		}
        $("#manegeWrap").prepend(content);
        if (isShowDelete) {
            $("#aDeleteRoam").click(function() {//删除云聊天记录
                var jsonObj = new JsonObj();
                jsonObj.Content = contactID;
                jsonObj.isRoam = 1;
                SMAjax(funType, "DeleteRoamRecord", "", jsonObj.ToJson());
            })
        }
    }
    $("#manegeWrap").removeClass("his_chat").addClass("his_chat pd_t01");
    FocusOnLocalOrRoam(!isfocusOnRoam, $("#liRoam").css("display") != "none");
}

function SetRoamStatus(isOpenRoam) {
    ownerInfo.isOpenRoam = isOpenRoam;
    if (ownerInfo.isOpenRoam == 1) {//已经开通云聊天记录
        $("#liOpenRoam").attr("class", "on_y");
        $("#liAOpenRoam").html("<span class='icon_5'></span>云记录设置");
    } else {
        $("#liOpenRoam").attr("class", "");
        $("#liAOpenRoam").html("<span class='icon_5'></span>开通云记录");
    }
}

function SetRoamTime(outTxt) {
    if (outTxt != null && outTxt != "") {
        var txt = outTxt.substr(0, outTxt.length);
        var timeArr = txt.split(',');
        timeCalendarList = [];
        for (var i = timeArr.length - 1; i >= 0; i--) {
            timeCalendarList.push(timeArr[i]);
        }
        timeCalendarList.unshift($("#txtTime").val());
        timeCalendarList.push($("#txtTime").val());
    } else {
        timeCalendarList = null;
        $("#txtTime").val("");
    }
    $('.text_2').datePicker({ clickInput: true, enableDates: timeCalendarList });
}

//播放音频 flag：1播放，2停止
window.external.OperateSoundMsg = function(path_, flag_) {
    var jsonObj = new JsonObj();
    jsonObj.Content = { path: path_, flag: flag_ };
    jsonObj.isRoam = isfocusOnRoam ? 1 : 0;
    SMAjax(funType, "OperateSoundMsg", "", jsonObj.ToJson());
}

//转发
window.external.ForwardingMsg = function(msgId_, msgJson_) {
    var jsonObj = new JsonObj();
    if (msgId_.indexOf("dd_") == 0) {
        msgId_ = msgId_.substr(3, msgId_.length - 3);
    }

    jsonObj.Content = { msgId: msgId_, msgJson: msgJson_ };
    jsonObj.isRoam = isfocusOnRoam ? 1 : 0;
    SMAjax(funType, "ForwardMsg", "", jsonObj.ToJson());
}
//转发
window.external.onClickMenu = function(msgId_, msgJson_, x, y) {
    var jsonObj = new JsonObj();
    if (msgId_.indexOf("dd_") == 0) {
        msgId_ = msgId_.substr(3, msgId_.length - 3);
    }

    jsonObj.Content = { msgId: msgId_, msgJson: msgJson_ };
    jsonObj.isRoam = isfocusOnRoam ? 1 : 0;
	jsonObj.X = x;
	jsonObj.Y = y;
    SMAjax(funType, "onClickMenu", "", jsonObj.ToJson());
}

//另存为
window.external.SaveFileAs = function(path) {
    var jsonObj = new JsonObj();
    jsonObj.Content = path;
    jsonObj.isRoam = isfocusOnRoam ? 1 : 0;
    SMAjax(funType, "SaveFileAs", "", jsonObj.ToJson());
}

//双击
window.external.LDblClick = function(id_, type_) {
    var jsonObj = new JsonObj();
    jsonObj.Content = { id: id_, type: type_ };
    jsonObj.isRoam = isfocusOnRoam ? 1 : 0;
    SMAjax(funType, "LDblClick", "", jsonObj.ToJson());
}

//左键单击
window.external.LClick = function(type_, texturl_, desc_) {
    var jsonObj = new JsonObj();
    jsonObj.Content = { type: type_, texturl: texturl_, desc: desc_ };
    jsonObj.isRoam = isfocusOnRoam ? 1 : 0;
    SMAjax(funType, "LClick", "", jsonObj.ToJson());
}
//打开公众好友名片
window.external.AddPubFeinno = function(type_, iduri_, sid_) {
    var jsonObj = new JsonObj();
    jsonObj.Content = { opaccount: type_, iduri: iduri_, sid: sid_ };
    jsonObj.isRoam = isfocusOnRoam ? 1 : 0;
    SMAjax(funType, "AddPubFeinno", "", jsonObj.ToJson());
}

//加好友
window.external.AddBuddy = function(sid_, name_) {
    var jsonObj = new JsonObj();
    jsonObj.Content = { sid: sid_, name: name_ };
    jsonObj.isRoam = isfocusOnRoam ? 1 : 0;
    SMAjax(funType, "AddBuddy", "", jsonObj.ToJson());
}

//加好友
window.external.OpenAddContactDlg = function(sid_, openType_) {
    var jsonObj = new JsonObj();
    jsonObj.Content = { sid: sid_, openType: openType_ };
    jsonObj.isRoam = isfocusOnRoam ? 1 : 0;
    SMAjax(funType, "OpenAddContactDlg", "", jsonObj.ToJson());
}

//下载文件
window.external.DownLoadObj = function(id_) {
    var jsonObj = new JsonObj();
    jsonObj.Content = { id: id_ };
    jsonObj.isRoam = isfocusOnRoam ? 1 : 0;
    SMAjax(funType, "DownLoadObj", "", jsonObj.ToJson());
}
var API={
	register:function(){
		try{
			//监听控件
			AjaxRequest(funType, "ListenWidget", "", "", ListenWidgetBack);
			//监听删除联系人
			AjaxRequest(funType, "DeleteContact", "", "", function(status, outTxt, outJson){
				if((status == 200 || status == 188) && outJson != null){
					var obj=document.getElementById("div"+outJson.uid+outJson.gid);
					var num = parseInt(obj.parentNode.childNodes[0].childNodes[0].childNodes[2].innerHTML.replace(/\[/g,"").replace(/\]/g,""))-1;
						obj.parentNode.childNodes[0].childNodes[0].childNodes[2].innerHTML="[" + num + "]";
						obj.parentNode.removeChild(obj);
				}
			});
			//监听关闭云
			SM.ajax(6, "CloseRoamRecord", "", "", function(status, outTxt, outJson) {
				if (outTxt == "SelectAll") {
					SelectAll();
				}
				else if (outTxt == "Refrush") {
					if (isfocusOnRoam) {//刷新漫游记录
						if (funType == 1) {
							GetContactRoamMsg("0", pageIndex);
						} else if (funType == 2) {
							GetGroupRoamMsg("0", pageIndex);
						}
					} else {//刷新本地记录
						if (isSearch) {
							backObj.AddStep();
							backObj.BackStep();
						} else {
							if (funType == 1) {
								ShowContactMessage($("#div" + contactID + contactGroupID), pageIndex)
							} else if (funType == 2) {
								ShowGroupMessageById();
							} else if (funType == 3) {
								ShowSmsMessage(smsType, pageIndex);
							}
						}
					}

				}
				
			});
			//监听打开云
			SM.ajax(6, "OpenRoamNavigation", "", "", function(status, outTxt, outJson) {
				OpenRoamNavigation();
			});
			SM.ajax(6, "tagMsgShowAction", "", "", function(status, outTxt, outJson) {
				//msgId,status
				var ww = document.body.clientWidth;
				var wh = document.body.clientHeight;
				if(outJson.status==1){
					msgDIV.innerHTML="<div class='sms-pop'><div class='sms-pop-t'></div><div class='sms-pop-c'><span class='tag-suc'></span>标记成功！</div><div class='sms-pop-b'></div></div>";
				}else if(outJson.status==0){
					msgDIV.innerHTML="<div class='sms-pop'><div class='sms-pop-t'></div><div class='sms-pop-c'><span class='tag-fail'></span>标记失败！</div><div class='sms-pop-b'></div></div>";
				}else if(outJson.status==2){
					msgDIV.innerHTML="<div class='sms-pop'><div class='sms-pop-t'></div><div class='sms-pop-c'><span class='tag-fail'></span>发送失败！</div><div class='sms-pop-b'></div></div>";
				}else if(outJson.status==3){
					msgDIV.innerHTML="<div class='sms-pop'><div class='sms-pop-t'></div><div class='sms-pop-c'><span class='tag-suc'></span>发送成功！</div><div class='sms-pop-b'></div></div>";
				}else if(outJson.status==4){
					msgDIV.innerHTML="<div class='sms-pop'><div class='sms-pop-t'></div><div class='sms-pop-c'><span class='tag-fail'></span>删除失败！</div><div class='sms-pop-b'></div></div>";
				}else if(outJson.status==5){
					msgDIV.innerHTML="<div class='sms-pop'><div class='sms-pop-t'></div><div class='sms-pop-c'><span class='tag-fail'></span>下载标记失败，请重试！</div><div class='sms-pop-b'></div></div>";
				}
				msgDIV.style.display="";
				msgDIV.style.top=(wh/2-msgDIV.clientHeight/2)+"px";
				msgDIV.style.left=(ww/2-msgDIV.clientWidth/2)+"px";

				setTimeout(function () { msgDIV.style.display="none"; },2000);
			});
		}catch(e){
			alert(e.message);
		}
		
	}
	
}
var loaded = false;
function AfterSMCompleted() {
    //modified start by chiyubo on 2015-03-13
	/*代码原顺序:
    AjaxRequest(funType, "ListenWidget", "", "", ListenWidgetBack);
    InitLoad();
	*/
	//修改的执行顺序:
	InitLoad();
	
    //modified end
	if( !loaded )
   API.register(); //注册接口
	loaded = true;
}