/**
 * 接收XML聊天数据,以HTML形式显示
 * 
 * @author 胡国亮 guoliang1@staff.sina.com.cn
 * @data 2009/08/24
 */
//全局的查询信息,count 记录总数,keyword 关键词
var gloInfo={count:0,keyword:false};

var _DEBUG = true;

//字符串替换
String.prototype.replaceAll = function(regText, replaceText, ignoreCase) {
    //转义
    /*
    regText=regText.replace(/([.\\\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/ig,"\\$1");
    var raRegExp=new RegExp(regText,"g");
    return this.replace(raRegExp,replaceText);
    */

    ignoreCase = ignoreCase | true;

    if (!RegExp.prototype.isPrototypeOf(regText)) {
        return this.replace(new RegExp(regText, (ignoreCase ? "gi" : "g")), replaceText);
    } else {
        return this.replace(regText, replaceText);
    }
};  

function clearDom(root, delSelf) {
	
	var delSelf = delSelf == undefined?true:delSelf;
	if (root.nodeType==1 && root.childNodes.length > 0)
	{
		for (var i=root.childNodes.length -1; i>=0 ;i-- )
		{
			clearDom(root.childNodes[i], true);
		}
	}
	if (root.nodeType==1)
	{
		if (root.onclick) {
			root.onclick = null;
		}
		if (root.ondblclick) {
			root.ondblclick = null;
		}
		if (root.onmousedown) {
			root.onmousedown = null;
		}
		if (root.className == 'img_has_event') {
			root.detachEvent('onmousedown', img_mousedown_event);
			root.detachEvent('ondblclick', img_dblclick_event);
			root.onload = null;
			root.onerror = null;
		}
	}
	if (delSelf)
	{
		root.parentNode.removeChild(root);
	}
	root = null;
	return;
}


function img_mousedown_event() {
	
					if (event.button==2) {
						cHistory.selected_img = event.srcElement;
					}
				}

function img_dblclick_event() {
	                    var src = decodeURI(event.srcElement.src);
	                    if (src.indexOf('file:///') == 0) {
	                        src = src.replace('file:///', '');
	                    }

	                    try {
	                        window.external.onCallStr('openPic', src, "");
	                    } catch (e) { }
	                }

//消息对象,每一行纪录为一个对象
function msg(id, sender, nick, time, d, title, type) {
	this.msgid		= id;	
	this.sender		= sender;
	this.nickname	= nick;
	this.time		= time;
	this.date		= d;
	this.title		= title;
	this.msg		= new Array();
	this.type		= type;
	
	this.font_size = '';
	this.font_bold = '';
	this.font_italic = '';
	this.font_family = '';
	this.font_underline = '';
	this.font_color = '';

	//高亮显示的样式
	this.highLightStyle='color:red;';

	this.addMsg = function(type,msg,other) {
		if (msg == undefined || msg == '') 
			return;
		
		var m = {type: type};

		if (type == 'text') {
			msg = this.highLightMsg(msg);
		} else if (type == 'EMTTYPE_FRIEND' || type == 'EMTTYPE_GROUP')	{
			m.context = other;

		} else if (type == 'file') {
			m.result = other;
		}

		m.content = msg;

		this.msg[this.msg.length] = m;
	}
	
	this.highLightMsg = function(msg) {
		msg = msg.replace(/</g, "&lt;").replace(/>/g, "&gt;");
		
		gloInfo.keyword=new String(gloInfo.keyword);

		//高亮显示关键词
		if (gloInfo.keyword && gloInfo.keyword.length>0)
		{
			gloInfo.keyword=gloInfo.keyword.replace(/</g, "&lt;").replace(/>/g, "&gt;");
//			msg = msg.replaceAll(gloInfo.keyword,'<font style="'+this.highLightStyle+'">'+gloInfo.keyword+'</font>');
try{
			var kw = gloInfo.keyword.replace(/([\[\(\)\]\*\\\+\?\$\^])/g, "\\$1");
			msg = msg.replace(new RegExp("(" + kw + ")", 'gi'), '<font style="'+this.highLightStyle+'">$1</font>');
}catch(e){}
		}

		if (this.font_size != '') {
			msg = '<span style="font-size=' + this.font_size + 'px">' + msg + '</span>';
		}
		
		if (this.font_italic == '1') {
			msg = '<em>' + msg + '</em>';
		}
		
		if (this.font_bold == '1') {
			msg = '<strong>' + msg + '</strong>';
		}
		
		if (this.font_underline == '1') {
			msg = '<U>' + msg + '</U>';
		}
		
		if (this.font_color != '' || this.font_family != '') {
			font_style = '<font';
			
			if (this.font_color != '') {
				font_style = font_style + ' color="' + this.font_color + '"';
			}
			
			if (this.font_family != '') {
				font_style = font_style + ' face="' + this.font_family + '"';
			}
			
			font_style = font_style + '>';
			msg = font_style + msg + '</font>';
		}

		return msg;
	}

	this.getMsg = function() {
		return this.msg;
	}
}

//是否按下 SHIFT CTRL 键
var keyShift = false;
var keyCtrl = false;

document.onkeydown = function(evt) {
    var e = evt || window.event;

    var pos = cHistory.getPosition();

    switch (e.keyCode) {
        case 16:
            keyShift = true;
            break;

        case 17:
            keyCtrl = true;
            break;

        case 38: //上
            if (keyShift && cHistory.isRowSelected(pos - 1)) {
                cHistory.clearSelect(pos);
                cHistory.setPosition(pos - 1);
            } else {
                cHistory.selectPre();
            }

            return false;

        case 40: //下
            if (keyShift && cHistory.isRowSelected(pos + 1)) {
                cHistory.clearSelect(pos);
                cHistory.setPosition(pos + 1);
            } else {
                cHistory.selectNext();
            }

            return false;

		case 65:
			if (keyCtrl)
			{
				SelectAll();
				window.focus();
				return false;
			}
			break;
    }

    delete pos, e;
}

document.onkeyup = function(evt) {
    var e = evt || window.event;

    switch (e.keyCode) {
        case 16:
            keyShift = false;

            break;

        case 17:
            keyCtrl = false;

            break;
    }
}

document.onselectstart = function() {
	if (keyShift || (keyCtrl && window.event.keyCode != 65)) {
		event.returnValue = false;
	}

}

function update(json) {
	cHistory.update(json);
}

function chatHistory() {
	//xml字串
	this.xml = '';

	//xml格式数据
	this.list = null;

	this.length = 0;

	this.messages = new Array();

	this.msgPanel = 'panel'
	
	this.panel  = null;
	
	this.LI_list = new Array();

	this.selected_img = null;

	//当前焦点所在
	var _position = -1;

	var _self = this;

	/**
	 * 加载json数据
	 */
	this.setJsonList = function(json) {
		if (!json) {
			return false;
		}
		//this.json = json;
		var result = this.loadJson(json);
		return result;
	}

	this.getPosition = function() {
	    return _position;
	}

	this.setPosition = function(i) {
	    _position = i;
	}

	this.isRowSelected = function(i) {
	    return i > -1 && i < _self.length ? _self.LI_list[i].selected: false;
	}

	this.loadJson = function(json) {
		//debugger;
	    var chatJson = eval("(" + json + ")");
	    //---------------2009-8-25 新版修改的数据结构,测试模拟数据,应用时删除
	    //chatJson={count:214,keyword:'http:',data:chatJson};
	    //---------------

	    var json = chatJson.data;
	    if (chatJson.keyword) {
	        gloInfo.keyword = chatJson.keyword;
	    }
	    gloInfo.count = chatJson.count;

	    var date, format, i, j, k, success, item, oMsg, title;
	    for (i in json) {
	        date = json[i].date;
			title = json[i].title;
	        for (j in json[i].items) {
	            item = json[i].items[j];

	            oMsg = new msg(item.id, item.sender, item.nick, item.time, date, title, item.type);
	            date = title = null;
	            if (item.format) {
	                format = item.format;
	                oMsg.font_size = format.size;
	                oMsg.font_bold = format.bolder;
	                oMsg.font_italic = format.italic;
	                oMsg.font_underline = format.underline;
	                oMsg.font_color = format.color;
	                oMsg.font_family = format.family;
	            }



	            for (k in item.content) {
	                success = '';
	                switch (item.content[k].type) {

	                    case 'file':
	                        item.content[k].path = item.content[k].path.replace(/\\/g, "\\\\");
	                        item.content[k].dir = item.content[k].dir.replace(/\\/g, "\\\\");
	                        item.content[k].value += ' <a href="javascript:window.external.onOpenfile(\'' + item.content[k].path + '\', 1)">打开文件</a> <a href="javascript:window.external.onOpenfile(\'' + item.content[k].dir + '\', 0)">打开目录</a>';
	                        success = '1';
	                        oMsg.addMsg(item.content[k].type, item.content[k].value, success);
	                        break;
	                    case 'text':
	                    case 'image':
	                        oMsg.addMsg(item.content[k].type, item.content[k].value, success);
	                        break;

	                    case 'hyperlink':
	                        oMsg.addMsg(item.content[k].type, item.content[k].value);

	                        break;

						case 'EMTTYPE_FRIEND':
							oMsg.addMsg('EMTTYPE_FRIEND', item.content[k].value, item.content[k].context);
							break;
							
						case 'EMTTYPE_GROUP':
							oMsg.addMsg('EMTTYPE_GROUP', item.content[k].value, item.content[k].context);
							break;
	                }
	            }
	            this.messages.push(oMsg);
	            this.length++;
	        }
	    }
	    chatJson = json = date = format = i = j = k = success = item = oMsg = title = null;
		//debugger;
	    return true;
	}
/*
	//接收数据
	this.setXMLList = function(xml) {
		if (!xml) {
			return false;
		}	
			
		this.xml = xml;
		var result = this.loadXML(xml);	
		
		return result;
	}

	this.loadXML = function(xml) {
		var xmldoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
		xmldoc.async = false
		xmldoc.loadXML(xml);
		var list = xmldoc.getElementsByTagName("list");
		
		if (!list || !list[0].childNodes || list[0].childNodes.length <= 0) {
			return false;
		}
		
		this.length = 0;
		
		date = null;
		
		for (r = 0; r < list[0].childNodes.length; r++) {
			row = list[0].childNodes[r]

			if (list[0].childNodes[r].nodeName == 'date') {
				font_size = '';
				font_bold = '';
				font_italic   = '';
				font_family    = '';
				font_underline = '';
				font_color     = '';
				
				date = list[0].childNodes[r].childNodes[0]? list[0].childNodes[r].childNodes[0].nodeValue:'';
			} else if (list[0].childNodes[r].nodeName == 'font') {
				
				font_size = row.getAttribute('size');
				font_bold = row.getAttribute('bolder');
				font_italic   = row.getAttribute('italic');
				font_family    = row.getAttribute('family');
				font_underline = row.getAttribute('underline');
				font_color     = row.getAttribute('color');
				
			} else if (list[0].childNodes[r].nodeName == 'data'){

				var msgid  = row.getElementsByTagName('id')[0]?row.getElementsByTagName('id')[0].childNodes[0].nodeValue:'';
				
				var sender = row.getElementsByTagName('sender')[0]&&row.getElementsByTagName('sender')[0].childNodes[0]?row.getElementsByTagName('sender')[0].childNodes[0].nodeValue:0;
				var nick   = row.getElementsByTagName('nick')[0]&&row.getElementsByTagName('nick')[0].childNodes[0] ? row.getElementsByTagName('nick')[0].childNodes[0].nodeValue: '';
				var time   = row.getElementsByTagName('time')[0]&&row.getElementsByTagName('time')[0].childNodes[0]?row.getElementsByTagName('time')[0].childNodes[0].nodeValue:'';
				
				if (!(msgid || sender || nick || time)) {
					continue;
				}

				var oMsg = new msg(msgid, sender, nick, time, date);
				if (typeof(font_size) != 'undefined' && font_size) {
					oMsg.font_size = font_size;
				}
				if (typeof(font_bold) != 'undefined' && font_bold) {
					oMsg.font_bold = font_bold;
				}
				if (typeof(font_italic) != 'undefined' && font_italic) {
					oMsg.font_italic = font_italic;
				}
				if (typeof(font_underline) != 'undefined' && font_underline) {
					oMsg.font_underline = font_underline;
				}
				if (typeof(font_color) != 'undefined' && font_color) {
					oMsg.font_color = font_color;
				}
				if (typeof(font_family) != 'undefined' && font_family) {
					oMsg.font_family = font_family;
				}
				
				
				date = null;

				for (j = 0 ;j < row.childNodes.length ;j++ ){
					var type = row.childNodes[j].nodeName;
					if (!row.childNodes[j].childNodes[0]) {
						continue;
					}
					success = '';
					switch (type)
					{
						case 'text':
						case 'file':
							success = row.childNodes[j].getAttribute('success');
						case 'image':
							oMsg.addMsg(type, row.childNodes[j].childNodes[0].nodeValue, success);
							break;
					}
				}

				this.messages.push(oMsg);
				this.length++;
			}
		}
		
		return true;
		
		//msg = 'XML加载完毕.总共' + this.length + '条纪录';
		
		//alert(msg);
	}
*/
	this.update = function(json) {
	    
		if (!this.panel) {
	        this.panel = document.getElementById(this.msgPanel);
	    }
		

		var d_history = document.getElementById('history');
		
		d_history.style.display = 'none';
		//debugger;
		// 初始化
		this.length = 0;
	    this.messages = [];
	    this.LI_list = [];
	    this.selected_img = null;
		gloInfo={count:0,keyword:false}

		clearDom(d_history, false);
		d_history.innerHTML = '';

		var d_table = document.createElement('table');
		d_table.id = 'showTable';
		d_table.cellpadding="0";
		d_table.cellspacing="0";
		var d_tbody = document.createElement('tbody');
		d_tbody.id = 'panel';
		
		d_table.appendChild(d_tbody);
		d_history.appendChild(d_table);
		
		d_history.style.display = 'block';
	    // init data
		this.panel = d_tbody;
	    

		d_history = d_table = d_tbody = null;
	    cHistory.setJsonList(json);
		json = null;
		CollectGarbage();
		//debugger;
		cHistory.show();
	},


	this.show = function() {
		
		//debugger;
	    if (!this.panel) {
	        this.panel = document.getElementById(this.msgPanel);
	    }

	    var infoBar = document.getElementById('total');

	    if (gloInfo.keyword && gloInfo.keyword != 'false') {
	        infoBar.innerHTML = '<p>搜索到<em>' + gloInfo.count + '</em>条消息记录</p>';
	    }
	    else {
	        infoBar.style.display = 'none';
	        //infoBar.innerHTML = '<p>共<em>' + gloInfo.count + '</em>条消息记录</p>';
	    }
	    if (!gloInfo.count) { return; }
	    //this.panel.innerHTML = '';
			this.panel.style.display = 'none';
	    //行号
	    var rownum = 0;
	    var row, li, td, h6, text, msgs, p, m, tr;

		var html ,d_images, img_i;
	    for (var k = 0; k < this.length; k++) {
	        row = this.messages[k];

	        if (row.date || row.title) {
	            li = document.createElement('TR');
	            td = document.createElement('TD');
	            td.className = 'date_set';

	            td.innerHTML = row.title ? '<div>' + row.title +'</div>': '<div>日期：' + row.date +'</div>';

	            li.appendChild(td);
	            this.panel.appendChild(li);
	        }

	        tr = document.createElement('TR');

	        td = document.createElement('TD');
	        tr.className = row.sender == 0 ? 'send' : 'recept';
	        

	        h6 = document.createElement('H6');
	        h6.innerHTML = row.nickname.replaceAll(/[<]/g, '&lt;') + '&nbsp;' + row.time;
	        td.appendChild(h6);

	        //text = '';
			html = [];
	        msgs = row.getMsg();

	        p = document.createElement('P');

	        for (var i = 0; i < msgs.length; i++) {
	            m = msgs[i];

	            if (m['type'] == 'file') {
	                if (m['result'] == 1) {
						html = [m['content']];
	                } else {
						html.push(m['content']);
	                }
					html.push('<br />');
	            } else if (m['type'] == 'image') {
					html.push('<img class="img_has_event" src="' + m['content'] + '" />');
	            } else if (m['type'] == 'text') {

					html.push(m['content'].replaceAll(/\n/g, '<br />'));
	            } else if (m['type'] == 'hyperlink') {

					html.push('<a href="' + (m['content'].indexOf('http://') == 0 ? m['content'] : ('http://' + m['content'])) + '" target="_blank">' + m['content'] + '</a>');
	            } else if (m['type'] == 'EMTTYPE_FRIEND')
	            {
					html.push('<a href="#" onclick="showVcard(\'' + m['context'] + '\')">' + m['content'] + '</a>');
	            }
				 else if (m['type'] == 'EMTTYPE_GROUP')
	            {
					html.push('<a href="#" onclick="showGroupVcard(\'' + m['context'] + '\')">' + m['content'] + '</a>');
	            }
	        }

			p.innerHTML = html.join('');

	        //图片双击打开
	        var imgs = p.getElementsByTagName('img');

	        if (imgs.length) {
	            for (var i = 0, l = imgs.length; i < l; i++) {
					imgs[i].attachEvent('onmousedown', img_mousedown_event);
	                imgs[i].attachEvent('ondblclick', img_dblclick_event); 
	                bindImgAdjustWidth(imgs[i]);
	            }
	        }

	        td.appendChild(p);
			tr.appendChild(td);

	        tr.type = row.type;
	        tr.rownum = rownum;
	        tr.msgid = row.msgid;
	        tr.selected = false;

	        tr.onclick = function() {
	            if (keyCtrl) {
	                this.selected ? cHistory.clearSelect(this.rownum) : cHistory.select(this.rownum);
	            } else if (keyShift) {
	                cHistory.select(cHistory.getPosition(), this.rownum);
	            } else {
	                cHistory.clearSelect();
	                cHistory.select(this.rownum);
	            }
	        }

	        tr.ondblclick = function() {

	            if (window.event.srcElement.tagName.toLowerCase() != 'img') {
	                try {
	                    window.external.onCallStr('copyHistoryMsg', this.msgid, "");
	                } catch (e) { };

	            }
	        }

			tr.onmousedown=function(oEvent) {
				if (!oEvent) oEvent=window.event;
				if (oEvent.button==2) {
					if (!this.selected)
					{
						cHistory.clearSelect();
					}
					cHistory.select(this.rownum);
				}
			}

	        this.LI_list.push(tr);

	        this.panel.appendChild(tr);

	        rownum++;
	    }
	    this.panel.style.display = 'block';
	    
	    window.interval = window.setInterval((function(td){
			var ag = 0;
			return function() {
			    ag ++;
			    var loaded = true;
			    for (var i=0; i < document.images.length; i++) {
			    	if (document.images[i].readyState != "complete") {
						loaded = false;
						break;
					}
			    }
//			    
//			    window.clearInterval(window.interval);
			    if (loaded || ag >=20 || document.images.length < 1) {
//			    		alert('clear');
					if (td)
					{
						td.scrollIntoView();
				        td.click();
						td = null;
					}
					window.clearInterval(window.interval);
			    }
			    }})(td),50);
	    /*
	    window.setTimeout(function() {
	        if (typeof tr == 'undefined') {
	            return;
	        }
	        td.scrollIntoView();
	        td.click();
	    }, 500);
	    */
		infoBar = rownum = row = tr = li = td = h6 = text = msgs = p = m = k = i = imgs = l = null;
		CollectGarbage();
		//debugger;
	};

	this.clearSelect = function(rownum) {
	    if (rownum == undefined) {
	        rownum = -1;
	        _position = -1;
	    }

	    for (i = 0; i < this.LI_list.length; i++) {
	        if (this.LI_list[i] && this.LI_list[i].selected) {

	            if (rownum == this.LI_list[i].rownum || rownum == -1) {
	                cName = this.LI_list[i].firstChild.className;
	                //var pos = cName.indexOf(' ');
	                if (cName != '') {
	                    this.LI_list[i].firstChild.className = ''; //cName.substring(0, pos);
	                }

	                this.LI_list[i].selected = false;
	            }
	        }
	    }
	}

	this.select = function(start, end) {
	    end = (end == undefined) ? start: end;
//		end = end || start;
	    
	    if (start <= end) {
	        for (i = start; i <= end; i++) {
	            if (_self.LI_list[i] && !_self.LI_list[i].selected) {
	                _self.LI_list[i].firstChild.className += ' selected';

	                _self.LI_list[i].selected = true;
	            }
	        }
	        _position = end;

	    } else {
	        for (i = start; i >= end; i--) {
	            if (_self.LI_list[i] && !_self.LI_list[i].selected) {
	                _self.LI_list[i].firstChild.className += ' selected';

	                _self.LI_list[i].selected = true;
	            }
	        }
	        _position = start;
	    }
	}

	this.selectPre = function() {
	    var pre = _position - 1;

	    if (pre > -1) {
	        if (!keyShift) {
	            _self.clearSelect();
	        }

	        _self.select(pre);

	        if (!isTopVisible(_self.LI_list[pre])) {
	            document.getElementById('history').scrollTop = _self.LI_list[pre].offsetTop - 4;
	        }

	        return true;
	    }

	    return false;
	}

	this.selectNext = function() {
	    var next = _position + 1;

	    if (next < _self.length) {
	        if (!keyShift) {
	            _self.clearSelect();
	        }

	        _self.select(next);

	        if (!isBottomVisible(_self.LI_list[next])) {
	            document.getElementById('history').scrollTop = _self.LI_list[next].offsetTop - document.body.clientHeight + _self.LI_list[next].clientHeight + 4;
	        }

	        return true;
	    }

	    return false;
	}
	
	this.delSelectedRow = function() {		
		for (i = 0; i < this.LI_list.length; i++) {
			if (this.LI_list[i] && this.LI_list[i].selected) {
				this.panel.removeChild(this.LI_list[i]);
				delete this.LI_list[i];
				this.length--;
			}
		}
		
		return true;
	}
	
	//返回选择了的行的消息ID
	this.getSelectedID = function() {
		var selected = new Array();
		for (i = 0; i < this.LI_list.length; i++) {
			if (this.LI_list[i] && this.LI_list[i].selected) {
				selected.push(this.LI_list[i].msgid);
			}
		}
		
		//alert(selected);
		return selected;
	}
	
	this.getSelectedIDandType = function() {
		var selected = new Array();
		for (i = 0; i < this.LI_list.length; i++) {
			if (this.LI_list[i] && this.LI_list[i].selected) {
				selected.push([this.LI_list[i].msgid, this.LI_list[i].type]);
			}
		}
		
		return selected;
	
	}

	this.copyText = function() {
		return document.execCommand('Copy', 'false',null);
	}
	
	this.copyPic = function() {
		if (this.selected_img && typeof(this.selected_img.contentEditable) != 'undefined'){
		
			if (!document.body.createControlRange) return;
			
			var ctrl = document.body.createControlRange();
			
			this.selected_img.contentEditable = true;
			
			ctrl.addElement(this.selected_img);
			
			ctrl.execCommand('Copy');
			
			this.selected_img.contentEditable = false;
			
			return true;
		} else {
			return document.execCommand('Copy', 'false',null);
		}
	}
}


function isTopVisible(li) {
    var history = document.getElementById('history');

    return li.offsetTop >= history.scrollTop && li.offsetTop < history.scrollTop + document.body.clientHeight;
}

function isBottomVisible(li) {
    var history = document.getElementById('history');


    return li.offsetTop + li.clientHeight <= history.scrollTop + document.body.clientHeight && li.offsetTop + li.clientHeight > history.scrollTop;
}

function bindImgAdjustWidth(img) {
    img.onload = function() {
        if (!this.oWidth) {
            this.oWidth = this.width;
        }

        var toWidth = Math.ceil(document.body.clientWidth * .90 - 15);

        if (this.width > toWidth) {
            this.width = toWidth;

            this.title = "双击可查看原图";

        } else if (this.width < toWidth && this.width < this.oWidth) {
            this.width = this.oWidth;

            this.title = '';
        }

        this.loaded = true;

        delete toWidth;
    }

	img.onerror = function(){
		this.onerror = null;
/*
		var s = this.src.split('.');
		s[s.length-1] = 'gif';
		this.src = s.join('.');
		
*/
	}
}

function runSave(){ if (saveImg.location != "about:blank")window.saveImg.document.execCommand("SaveAs"); }
function createIframe() {
	ifm = document.createElement('<iframe src="about:blank" name="saveImg" onload="runSave()" style="display:none;"></iframe>');
	document.body.appendChild(ifm);
} 
function saveImgAs(url){
	if (!window.saveImg) {
		createIframe();
	} 
	if(window.saveImg && url) {
		window.saveImg.location=url; 
	}
}


if (typeof(cHistory) == 'undefined') {
	cHistory = new chatHistory();
}


function GetSelectedTabID() {
	return cHistory.getSelectedID().join(',');
}

// 得到id和type的json字串
function GetSelectedTabIDandType() {
	var data = cHistory.getSelectedIDandType();
	var items = new Array();
	for (var i in data )
	{
		items.push('{"id":"' + data[i][0] + '", "type":"' + data[i][1] + '"}');
	}
	return "[" + items.join(",") + "]";
}

function DeleteSelectedTab() {
	return cHistory.delSelectedRow();
}

function CopyPic() {
	if (document.selection.createRange().text != '') {
		return CopyText();
	}

	return cHistory.copyPic();
}

function CopyText() {
	return cHistory.copyText()
}

function SaveAsPic() {
	try{
			var src = decodeURI(cHistory.selected_img.src);
			if (src.indexOf('file:///') == 0)
			{
				src = src.replace('file:///', '');
			}
			window.external.onCallStr('savePicAs', src, "");
	}catch(e) {}
}

//全选
function SelectAll() {

	var rng = document.body.createTextRange();
	rng.moveToElementText(document.getElementById("panel"));
    rng.select();
	window.focus();
}

function AddToGif() {
	if (cHistory.selected_img){
		external.AddToGif(cHistory.selected_img.src);
	}
}

//添加为表情
function AddToEmotion() {
    if (cHistory.selected_img) {

        var src = decodeURI(cHistory.selected_img.src);
        
        if (src.indexOf('file:///') == 0) {
            src = src.replace('file:///', '');
        }

        window.external.onCallStr('AddToEmotion', src, "");
    }
}

//打开文件或者文件夹
function doOpenfile(link, openfile) {
try{
	if (openfile == 1) {
		//alert('打开' + link);
		external.doOpenfile(link,1); 
	} else if (openfile == 0){
		//alert('打开目录');
		external.doOpenfile(link,0); 
	}
}catch(e){};
}

showInterval = null;

function loadXML(str) {
//try{
	xmlloaded = cHistory.setXMLList(str);
	
	if (!xmlloaded) {
		return false;
	}
	
	if (!showInterval){
		showInterval = window.setInterval(
		function() {
			if (isloaded) {
				showMessage();
				window.clearInterval(showInterval);
			}
		}
		,100);
	}
//}catch(e){};
}

function showMessage() {
	cHistory.show();
}

/**
 * 设置表格宽度
 */
function setTableWidth(w) {
	tab = document.getElementById('showTable');
	if (tab) {
		tab.style.width = w + 'px';
	}
}

//查询某用户的资料
function showVcard(id) {
	try{
		window.external.onCallStr('SysMsgHyperLink' ,  'EMTTYPE_FRIEND', new String(id));
	}catch(e){};
}
//查询某群组的资料
function showGroupVcard(id) {
	try{
		window.external.onCallStr('SysMsgHyperLink' ,  'EMTTYPE_GROUP', new String(id));
	}catch(e){};
}


isloaded = false;

//loadXML(testxml);

window.onload = function(){
	isloaded = true;
};

//获取窗口大小
function findDimensions(){
	if (window.innerWidth)
		 winWidth = window.innerWidth;
	else if ((document.body) && (document.body.clientWidth))
		 winWidth = document.body.clientWidth;
	if (window.innerHeight)
		 winHeight = window.innerHeight;
	else if ((document.body) && (document.body.clientHeight))
		 winHeight = document.body.clientHeight;
	if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth){
		 winHeight = document.documentElement.clientHeight;
		 winWidth = document.documentElement.clientWidth;
		}
}
//窗口改变大小时,修改容器尺寸
function resizeWin() {
	//alert('reach....');//alert(body.clientHeight);
    
    var body = (document.compatMode != "BackCompat") ? document.documentElement : document.body;
    var oList = document.getElementById('history');
    var oTotal = document.getElementById('total');
    var iTotalHeight = (oTotal.style.display == 'none') ? 0 : 25;  //25;
    //var iTotalHeight = 25;

    if (iTotalHeight > 0) {

        oTotal.style.height = oList.style.top = (iTotalHeight) + 'px';
        oList.style.height = (body.clientHeight - iTotalHeight - 5) + 'px';
        oList.style.width = (body.clientWidth - 4) + 'px';
    } else {
        oList.style.top = (iTotalHeight) + 'px';
        oList.style.height = (body.clientHeight - iTotalHeight - 5) + 'px';
        oList.style.width = (body.clientWidth - 4) + 'px';

    }

    //触发img的load事件
    if (document.getElementById('panel')) {
        var imgs = document.getElementById('panel').getElementsByTagName('img');
        for (var i = 0, l = imgs.length; i < l; i++) {
            imgs[i].loaded && imgs[i].onload && imgs[i].onload();
        }
    }

};
window.onload = window.onresize = resizeWin;
