 <!--
	/************************************************************************
	 *                       ******  GLOBAL WARS(tm) *******
	 ************************************************************************
	 */
	var jid;
	var pass;
	var changeway=0;
	var conAmount=1;
	var nick;
	var status = "";
	var onlstat = "";
	var onlmsg = "";
	var onlprio = "8";
	var autoPopup = true;
	var autoPopupAway = false;
	var playSounds = true;
	var focusWindows = false;
	var timestamps = false;
	var usersHidden = false;
	var enableLog = false;
	var loghost;
	var isNoFlash=false;
	/* some globals */
	var roster;
	var fmd; // frames.main.document
	var disco; // holds information from service discovery
	var statusLed;
	var statusMsg;
	var title=document.title;
	var onlstatus = new Object();
	onlstatus["available"] = "\u5728\u7ebf";
	onlstatus["chat"] = "\u6b22\u8fce\u804a\u5929";
	onlstatus["away"] = "\u79bb\u5f00";
	onlstatus["xa"] = "\u4e0d\u53ef\u7528";
	onlstatus["dnd"] = "\u8bf7\u52ff\u6253\u6270";
	onlstatus["invisible"] = "\u9690\u8eab";
	onlstatus["unavailable"] = "\u79bb\u7ebf";
	var fileDownload = new Object();
	var uploading=false;
	var downloading=false;
	var isCancel=false;
	var currentMind="";
	var DEFAULTRESOURCE = "wum";
	var DEFAULTPRIORITY = "10";
	var param = "";
    var t_editName = "";
   	var t_editTel = "";
   	var t_editLinkMan = "";
   	var t_editAddr = "";

	/* debugging options */
	var DEBUG = false; // turn debugging on
	var DEBUG_LVL = 4; // debug-level 0..4 (4 = very noisy)

	var USE_DEBUGJID = false; // if true only DEBUGJID gets the debugger
	var DEBUGJID = "admin@localhost"; // which user get's debug messages


	// most probably you don't want to change anything below

	var timerval = 2000; // poll frequency in msec

	var stylesheet = basePath + THEMESDIR + "/" + stylePath + "/jwchat.css";
	var BACKEND_TYPE = "binding";
	var HTTPBASE = "http://127.0.0.1/chat/JHB";
	var SOUNDS = new Object();
	SOUNDS['message_recv'] = basePath + "sounds/message_recv.swf";
	SOUNDS['message_queue'] = basePath + "sounds/message_queue.swf";
	SOUNDS['chat_recv'] = basePath + "sounds/chat_recv.swf";
	SOUNDS['chat_queue'] = basePath + "sounds/chat_queue.swf";
	/************************************************************************
	 *                         ****** Pop-Up's *******
	 ************************************************************************
	 */
	function openGroupchat(aJid, nick, pass) {
		pass = pass || "";
		nick = nick || "";
		var user = roster.getUserByJID(aJid);
		if (!user) {
			user = roster.addUser(new RosterUser(aJid, "", ["\u804a\u5929\u5ba4"], aJid.substring(0, aJid.indexOf("@"))));
			user.type = "groupchat";
			roster.print();
		}
		if (!user.chatW || user.chatW.closed) {
			user.chatW = open("groupchat.html?jid=" + escape(aJid) + "&nick=" + escape(nick) + "&pass=" + escape(pass), "gchatW" + makeWindowName(aJid + "/" + nick), "width=520,height=390,resizable=yes");
		}
		user.chatW.focus();
	}
	var subw;
	 function openSubscription(aJid) {
        var container="";
        var prefix="openSubscription";
        var displayText =[ aJid ? "发送邀请 至 " + aJid : "发送邀请","<img style=\"margin-top:3px;\" src=\"" + basePath + "images\/adduser.gif\"\/>"];
        var extend="";
        param = (aJid) ? "jid=" + escape(aJid) : "";
        if(arguments[1] && arguments[1] != ""){
            param+=param ? "&isSub=" + arguments[1] : "isSub=" + arguments[1];
        }
        if(arguments[2] && arguments[2] != ""){
            param+=param ? "&nick=" + arguments[2] : "nick=" + arguments[2];
        }
        var parentContainer = document.getElementById("subscriptionWindow");
        if(aJid && arguments[1] && arguments[1]!=""){
            var subPrefix=makeWindowName(aJid);
            var temp="subscriptionWindow" + subPrefix;
            if(document.getElementById(temp)==null){
                container=document.createElement("div");
                container.setAttribute("id",temp); 
                parentContainer.appendChild(container);
            }else{
                return false;
            }
            extend=temp;
            prefix+=subPrefix;
        }else{
            if(document.getElementById("subRequestWindow").hasChildNodes()){
                return false;
            }
            if(document.getElementById("defaultSubscriptionWindow")==null){
                if(parentContainer.hasChildNodes()){
                    return;
                }
                container=document.createElement("div");
                container.setAttribute("id","defaultSubscriptionWindow"); 
                parentContainer.appendChild(container);
            }else{
                if(parentContainer.hasChildNodes() && parentContainer.childNodes.length>1){
                    return false;
                }
                container=document.getElementById("defaultSubscriptionWindow");
            }
        }
        buildWindow(container, prefix, 330, 200, displayText, (flag == 0 ? 90 : 63), "javascript:\"<script src='" + basePath + "um_subscription.js' charset='utf-8'><\/script>\"",extend,130,1,1);
        return false;
    }
    function openSubRequest(aJid,msg) {
        if(document.getElementById("openSubscription")){
            windowMinimize("openSubscription");
        }
        var container="";
        var prefix="openSubRequest";
        var displayText = "来自 " + aJid + "的邀请";
        var extend="";
        var param = "jid=" + escape(aJid);
        if(msg){
            param+="&msg=" + msg;
        }
        var parentContainer = document.getElementById("subRequestWindow");
        var subPrefix=makeWindowName(aJid);
        var temp="subRequestWindow" + subPrefix;
        if(document.getElementById(temp)==null){
            container=document.createElement("div");
            container.setAttribute("id",temp); 
            parentContainer.appendChild(container);
        }else{
            return;
        }
        extend=temp;
        prefix+=subPrefix;
        buildWindow(container, prefix, 330, 100, displayText, (flag == 0 ? 90 : 63), "javascript:\"<script>var param='"+ param +"';<\/script><script src='" + basePath + "subscriptionRequest.js' charset='utf-8'><\/script>\"",extend,130,1);
        
        return false;
    }
	function openUserProps(aJid) {
		var container = document.getElementById("propsWindow");
		var displayText = "\u7f16\u8f91 " + aJid + " \u7684\u5c5e\u6027";
		buildWindow(container, "openProps", 480, 340, displayText, (flag == 0 ? 90 : 63), "javascript:\"<script>var jid='"+ escape(aJid) +"';<\/script><script src='" + basePath + "userprops.js' charset='utf-8'><\/script>\"","",130,1);
		return false;
	}
	function removeUser(aJid) {
	  // get fulljid
	    if(window.confirm("确认要删除吗？")){
			var fulljid = roster.getUserByJID(aJid).fulljid;
			var iq = new JSJaCIQ();
			iq.setType("set");
			var query = iq.setQuery("jabber:iq:roster");
			var item = query.appendChild(iq.getDoc().createElement("item"));
			item.setAttribute("jid", fulljid);
			item.setAttribute("subscription", "remove");
			con.send(iq);
		}
	}
	//var vcardW; // my vcardW;
	function openUserInfo(aJid) {
		var container = document.getElementById("infoWindow");
		var displayText = "个人信息 - " + aJid;
		buildWindow(container, "openInfo", 410, 420, displayText, (flag == 0 ? 90 : 63), "javascript:\"<script>var jid='"+ escape(aJid) +"';<\/script><script src='" + basePath + "um_vcard.js' charset='utf-8'><\/script>\"","",130,1);
		
		return false;
	}
	function openUserHistory(aJid) {
		if (typeof (loghost) == "undefined" || loghost == "") {
			return;
		}
		var user = roster.getUserByJID(aJid);
		if (user == null) {
			return;
		}
		if (!user.histW || user.histW.closed) {
			user.histW = open(basePath + "userhist.html?jid=" + escape(aJid), "histW" + makeWindowName(aJid), "width=600,height=400,resizable=yes,scrollbars=no");
		}
		user.histW.focus();
	}
	function openSearch() {
        var container = document.getElementById("searchWindow");
        var displayText = "查找好友";
        buildWindow(container, "openSearch", 480, 405, displayText, (flag == 0 ? 90 : 63), "javascript:\"<script src='" + basePath + "um_search.js' charset='utf-8'><\/script>\"","",130,1);
        return false;
    }
	/************************************************************************
	 * nifty helpers - always there if you need 'em
	 ************************************************************************
	 */
	/* command line history */
	var messageHistory = new Array();
	var historyIndex = 0;
	function getHistory(key, message) {
		if ((key == "up") && (historyIndex > 0)) {
			historyIndex--;
		}
		if ((key == "down") && (historyIndex < messageHistory.length)) {
			historyIndex++;
		}
		if (historyIndex >= messageHistory.length) {
			if (historyIndex == messageHistory.length) {
				return "";
			}
			return message;
		} else {
			return messageHistory[historyIndex];
		}
	}
	function addtoHistory(message) {
		if (is.ie5) {
			messageHistory = messageHistory.concat(message);
		} else {
			messageHistory.push(message);
		}
		historyIndex = messageHistory.length;
	}
	/* system sounds */
	var soundPlaying = false;
	function soundLoaded() {
		soundPlaying = false;
	}
	function playSound(action) {
		if (!playSounds) {
			return;
		}
		if (!SOUNDS[action]) {
			Debug.log("no sound for '" + action + "'", 1);
			return;
		}
		if (onlstat != "" && onlstat != "available" && onlstat != "chat") {
			return;
		}
		if (soundPlaying) {
			return;
		}
		soundPlaying = true;
		try{
			var frameD = window.frames["jwc_sound"].document;
		}catch(e){
			alert(e);
		}
		var html = "<embed src=\"" + SOUNDS[action] + "\" width=\"1\" height=\"1\" quality=\"high\" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\" type=\"application/x-shockwave-flash\">";
		frameD.open();
		frameD.write(html);
		frameD.close();
	}
	function sendPresence2Groupchats(gc, val, away) {
		var aPresence;
		for (var i = 0; i < gc.length; i++) {
			aPresence = new JSJaCPresence();
	    //aPresence.setXMLNS();
			aPresence.setTo(gc[i]);
			if (away && away != "") {
				aPresence.setStatus(away);
			}
			if (val != "available") {
				aPresence.setShow(val);
			}
			con.send(aPresence);
		}
	}
	function changeStatus(val, away, prio) {
		Debug.log("changeStatus: " + val + "," + away + "," + prio, 2);
		onlstat = val;
		if (away) {
			onlmsg = away;
		}
		if (prio && !isNaN(prio)) {
			onlprio = prio;
		}
		if (!con.connected() && val != "offline") {
			um_connect();
			return;
		}
		var aPresence = new JSJaCPresence();
		switch (val) {
		  case "unavailable":
			val = "invisible";
			aPresence.setType("invisible");
			break;
		  case "offline":
			val = "unavailable";
			aPresence.setType("unavailable");
			con.send(aPresence);
			con.disconnect();
			var img = eval(val + "Led");
			statusLed.src = img.src;
			if (away) {
				statusMsg.innerHTML = away;
			} else {
				statusMsg.innerHTML = onlstatus[val];
			}
			cleanUp();
			return;
			break;
		  case "available":
			val = "available"; // needed for led in status bar
			if (away) {
				aPresence.setStatus(away);
			}
			if (prio && !isNaN(prio)) {
				aPresence.setPriority(prio);
			} else {
				aPresence.setPriority(onlprio);
			}
			break;
		  case "chat":
			if (prio && !isNaN(prio)) {
				aPresence.setPriority(prio);
			} else {
				aPresence.setPriority(onlprio);
			}
		  default:
			if (away) {
				aPresence.setStatus(away);
			}
			if (prio && !isNaN(prio)) {
				aPresence.setPriority(prio);
			} else {
				aPresence.setPriority("0");
			}
			aPresence.setShow(val);
		}
		con.send(aPresence);
		/* send presence to chatrooms
	   */
		if (typeof (roster) != "undefined" && onlstat != "invisible") {
			sendPresence2Groupchats(roster.getGroupchats(), onlstat, onlmsg);
		}
		var img = eval(val + "Led");
		statusLed.src = img.src;
		if (away) {
			statusMsg.innerHTML = away;
		} else {
			statusMsg.innerHTML = onlstatus[val];
		}
	}
	function changeMind(mind){
		var iq = new JSJaCIQ();
		iq.setIQ(jid, "set", "jcl_" + con._rid);
		var query = iq.setQuery('jabber:iq:uminformation');
		var xmldoc = XmlDocument.create('body','jabber:iq:uminformation');
		xmldoc.loadXML('<body xmlns=\"jabber:iq:uminformation\"><mind>' + mind + '</mind></body>');
		for (var i=0; i<xmldoc.documentElement.childNodes.length; i++){
			query.appendChild(xmldoc.firstChild.childNodes.item(i).cloneNode(true));
		}
		con.send(iq);
		var aPresence = new JSJaCPresence();
		aPresence.setStatus(onlstatus[onlstat]);
		if(mind){
			aPresence.setMind(mind);
		}
		aPresence.setPriority("0");
		con.send(aPresence);
	}
	function Len(str)
	{
	     var i,sum;
	     sum=0;
	     for(i=0;i<str.length;i++)
	     {
	         if ((str.charCodeAt(i)>=0) && (str.charCodeAt(i)<=255))
	             sum=sum+1;
	         else
	             sum=sum+2;
	     }
	     return sum;
	}
	/************************************************************************
	 *                   ***** EVENT - HANDLER *****
	 ************************************************************************
	 */
	/************************************************************************
	 * handleMessage
	 ************************************************************************
	 */
	function handleMessage(aMessage) {
		Debug.log(aMessage.getDoc().xml, 2);
		if (aMessage.getType() == "error") {
			return;
		}
		/* check if this is a groupchat invite */
		var x;
		for (var i = 0; i < aMessage.getNode().getElementsByTagName("x").length; i++) {
			if (aMessage.getNode().getElementsByTagName("x").item(i).getAttribute("xmlns") == "http://jabber.org/protocol/muc#user") {
				x = aMessage.getNode().getElementsByTagName("x").item(i);
				break;
			}
		}
		if (x) {
			var from, to, reason, pass;
			to = aMessage.getFrom();
			var aInvite = x.getElementsByTagName("invite").item(0);
			from = aInvite.getAttribute("from");
			if (aInvite.firstChild && aInvite.firstChild.nodeName == "reason" && aInvite.firstChild.firstChild) {
				reason = aInvite.firstChild.firstChild.nodeValue;
			}
			if (x.getElementsByTagName("password").item(0)) {
				pass = x.getElementsByTagName("password").item(0).firstChild.nodeValue;
			}
			Debug.log("You have been invited to " + jid + " pass " + pass + " by " + from + "\nreason:" + reason, 2);
			var user = roster.getUserByJID(cutResource(from));
			if (!user) {// users not in roster (yet)
				Debug.log("creating new user " + from, 3);
				user = roster.addUser(new RosterUser(from));
				user.lastsrc = eval(user.status + "Led").src;
				roster.print();
			}
			if (typeof (user.iwArr) == "undefined") {
				user.iwArr = new Array();
			}
			user.iwArr[to] = open(basePath + "groupchat_invite.html?to=" + escape(to) + "&from=" + escape(from) + "&pass=" + escape(pass) + "&reason=" + escape(reason), "iw" + makeWindowName(to), "width=320,height=320,resizable=yes");
			return;
		}
		var from = cutResource(aMessage.getFrom());
		var type = aMessage.getType();
		Debug.log("from: " + from + "\naMessage.getFrom(): " + aMessage.getFrom(), 3);
		var user = roster.getUserByJID(from);
		if (user == null) {// users not in roster (yet)
			Debug.log("creating new user " + from, 3);
			user = roster.addUser(new RosterUser(from));
			user.lastsrc = eval(user.status + "Led").src;
			roster.print();
		}
		Debug.log("got user jid: " + user.jid, 3);
		var aRoster = roster;
		if (type != "groupchat" && user.roster && from != aMessage.getFrom()) { // private groupchat message
			aRoster = user.roster;
			from = aMessage.getFrom(); // use from with resource (had been cut off first)
			user = user.roster.getUserByJID(from);
		}
		/* change icon in roster - but not if it's a groupchat item */
		if (type != "groupchat") {
			if (!user.lastsrc) {
				user.lastsrc = eval(user.status + "Led").src;
			}
			var images = aRoster.getUserIcons(from);
			for (var i = 0; i < images.length; i++) {
				images[i].src = messageImg.src;
			}
			/* user is not visible right now - make him pop up (lastsrc changed!) */
			if (aRoster.usersHidden && user.status == "unavailable") {
				aRoster.print();
			}
		}
	  
	  // set current timestamp
		var x;
		for (var i = 0; i < aMessage.getNode().getElementsByTagName("x").length; i++) {
			if (aMessage.getNode().getElementsByTagName("x").item(i).getAttribute("xmlns") == "jabber:x:delay") {
				x = aMessage.getNode().getElementsByTagName("x").item(i);
				break;
			}
		}
		if (x) {
			Debug.log("found offline message: " + x.getAttribute("stamp"), 3);
			var stamp = x.getAttribute("stamp");
			aMessage.jwcTimestamp = new Date(Date.UTC(stamp.substring(0, 4), stamp.substring(4, 6) - 1, stamp.substring(6, 8), stamp.substring(9, 11), stamp.substring(12, 14), stamp.substring(15, 17)));
		} else {
			aMessage.jwcTimestamp = new Date();
		}
		if (type == "chat") {
			user.chatmsgs = user.chatmsgs.concat(aMessage);
			/*if (user.chatW && !user.chatW.closed && user.chatW.popMsgs) {
				user.chatW.popMsgs();
				playSound("chat_recv");
			} else {*/
				newMessageNotification("[" + user.name + "]来消息啦...");
				if (autoPopup && (autoPopupAway || onlstat == "available" || onlstat == "chat")) {
					if(user.cFrame){
						aRoster.openChat(from);
						popMsgs(user);
					}else{
						aRoster.openChat(from);
					}
					playSound("chat_recv");
				} else {
					if (focusWindows) {
						window.focus();
					}
					playSound("chat_queue");
	
	      // let arrow blink for toggled groups
					for (var i = 0; i < user.groups.length; i++) {
						if (user.groups[i].name != "临时好友") {
							if (roster.hiddenGroups[user.groups[i].name]) {
								fmd.images[user.groups[i].name + "Img"].src = arrow_right_blinking.src;
							}
						}
					}
				}
		  //}
		} else {
			if (type == "groupchat") {
				/* handle groupchat message 
	     */
				user.chatmsgs = user.chatmsgs.concat(aMessage);
				if (user.chatW && !user.chatW.closed && user.chatW.srcW && typeof (user.chatW.srcW.roster) != "undefined" && user.chatW.popMsgs) {
					user.chatW.popMsgs();
				}
				playSound("chat_recv");
			} else {
				user.chatmsgs = user.chatmsgs.concat(aMessage);
				newMessageNotification("[" + user.name + "]来消息啦...");
				if (autoPopup && (autoPopupAway || onlstat == "available" || onlstat == "chat")) {
					if(user.cFrame){
						aRoster.openChat(from);
						popMsgs(user);
					}else{
						aRoster.openChat(from);
					}
	
	      			// let arrow blink for toggled groups
					for (var i = 0; i < user.groups.length; i++) {
						if (user.groups[i].name != "临时好友") {
							if (roster.hiddenGroups[user.groups[i].name]) {
								fmd.images[user.groups[i].name + "Img"].src = arrow_right_blinking.src;
							}
						}
					}
				}
	
	    // [TODO] zeank 2005-10-26
	    // archiving of single/plain messages
			}
		}
	}
	/************************************************************************
	 * handleMessageError
	 ************************************************************************
	 */
	var error_messages = new Array();
	var errorW;
	function handleMessageError(aJSJaCPacket) {
		if (aJSJaCPacket.getType() != "error") {
			return;
		}
		Debug.log(aJSJaCPacket.getDoc().xml, 2);
		var user = roster.getUserByJID(cutResource(aJSJaCPacket.getFrom()));
		if (user.cFrame) {
			var error = aJSJaCPacket.getNode().getElementsByTagName("error").item(0);
			if (error) {
				if (error.getElementsByTagName("text").item(0)) {
					roster.openChat(cutResource(aJSJaCPacket.getFrom()));
					putMsgHTML(aJSJaCPacket,user);
					//playSound("error");
					return;
				}
			}
		}
		error_messages = error_messages.concat(aJSJaCPacket);
		if (!errorW || errorW.closed) {
			errorW = open(basePath + "error_message.html", "errorW" + makeWindowName(jid), "width=360,height=270,dependent=yes,resizable=yes");
		} else {
			if (error_messages.length > 0 && errorW.document.forms[0]) {
				errorW.document.forms[0].nextButton.disabled = false;
			}
		}
		//playSound("error");
		errorW.focus();
	}
	/************************************************************************
	 * handlePresence
	 ************************************************************************
	 */
	function handlePresence(presence) {
		Debug.log(presence.getDoc().xml, 2);
		var from = cutResource(presence.getFrom());
		var type = presence.getType();
		var show = presence.getShow();
		var status = presence.getStatus();
		var aRoster = roster;
	  // roster subscriptions synchronisation
		var x;
		switch (type) {
		  case null:
		  case "":
			break;
		  case "subscribe":
		  	 if(typeof orgid == dd_u && (typeof uin == "undefined" || uin =="")){
			  	 if (status) {
	                 openSubRequest(escape(from),escape(status));
	             } else {
	                 openSubRequest(escape(from));
	             }
             }
			return;
		  case "unsubscribe":
			alert("\u60a8\u5df2\u7ecf\u53d6\u6d88\u4e86\u6765\u81ea " + presence.getFrom() + " \u7684\u9080\u8bf7");
			break;
		  case "subscribed":
				  var aPresence=new JSJaCPresence();
				  aPresence.setType("subscribe");
				  aPresence.setTo(from);
				  var priority=aPresence.getDoc().createElement("priority");
				  priority.appendChild(aPresence.getDoc().createTextNode("0"));
				  aPresence.getNode().appendChild(priority);
				  con.send(aPresence);
			break;
		  case "error":
			var user = roster.getUserByJID(from);
			if (user && user.cFrame) {
				if (presence.getNode().getElementsByTagName("error").item(0)) {
					var error = presence.getNode().getElementsByTagName("error").item(0);
					roster.openChat(from);
					if (error.getElementsByTagName("text").item(0)) {
						putMsgHTML(presence,user);
					} else {
						if (error.firstChild && error.firstChild.nodeValue) {
							putMsgHTML(error.firstChild.nodeValue,user, new Date(), from, null, true);
						}
					}
				}
			}
		}
		var user = roster.getUserByJID(from);
		if (!user) { // presence from unsubscribed user
			Debug.log("presence from " + from + " not found on roster", 2);
			return;
		}
		/* handle presence for MUC */
		x = null; // reset
		for (var i = 0; i < presence.getNode().getElementsByTagName("x").length; i++) {
			if (presence.getNode().getElementsByTagName("x").item(i).getAttribute("xmlns") == "http://jabber.org/protocol/muc#user") {
				x = presence.getNode().getElementsByTagName("x").item(i);
				break;
			}
		}
		if (user.roster && x) {
			Debug.log("muc presence detected", 2);
			var ofrom = presence.getFrom().substring(presence.getFrom().indexOf("/") + 1);
			Debug.log("jabber.from:" + presence.getFrom() + ", ofrom:" + ofrom, 3);
			var ouser = user.roster.getUserByJID(presence.getFrom());
			if (!ouser) { // no user? create one!
			}
			ouser = new GroupchatRosterUser(presence.getFrom(), ofrom);
			var item = x.getElementsByTagName("item").item(0);
			ouser.affiliation = item.getAttribute("affiliation");
			ouser.role = item.getAttribute("role");
			ouser.nick = item.getAttribute("nick");
			ouser.realjid = item.getAttribute("jid");
			if (item.getElementsByTagName("reason").item(0)) {
				ouser.reason = item.getElementsByTagName("reason").item(0).firstChild.nodeValue;
			}
			if (actor = item.getElementsByTagName("actor").item(0)) {
				if (actor.getAttribute("jid") != null) {
					ouser.actor = actor.getAttribute("jid");
				} else {
					if (item.getElementsByTagName("actor").item(0).firstChild != null) {
						ouser.actor = item.getElementsByTagName("actor").item(0).firstChild.nodeValue;
					}
				}
			}
			if (ouser.role != "") {
				ouser.add2Group(ouser.role + "s");
				/* check if it is our own presence
	       * must be done here cause we want to be sure that role != ''
	       */
				if (ouser.name == htmlEnc(user.roster.nick)) { // seems to be me
					user.roster.me = ouser; // store this reference
					if (user.chatW.updateMe) {
						user.chatW.updateMe();
					}
				}
			}
			Debug.log("ouser.jid: " + ouser.jid + ", ouser.fulljid:" + ouser.fulljid + ", ouser.name:" + ouser.name + ", user.roster.nick:" + user.roster.nick, 3);
			var nickChanged = false;
			if (x.getElementsByTagName("status").item(0)) {
				var code = x.getElementsByTagName("status").item(0).getAttribute("code");
				switch (code) {
				  case "201": // room created
					/* popup dialog to ask for whether to accept default
		 * configuration or make a custom room 
		 */
					if (confirm("\u65b0\u623f\u95f4\u5df2\u7ecf\u521b\u5efa\uff0c\u4f46\u6ca1\u6709\u88ab\u914d\u7f6e\u3002\u60a8\u73b0\u5728\u60f3\u8fdb\u884c\u914d\u7f6e\u5417\uff1f\n\u5355\u51fb'\u53d6\u6d88'\u6309\u94ae\u5c06\u4f7f\u7528\u9ed8\u8ba4\u914d\u7f6e\u3002")) {
						user.chatW.openConfig();
					} else {
						var iq = new JSJaCIQ();
						iq.setType("set");
						iq.setTo(user.jid);
						var query = iq.setQuery("http://jabber.org/protocol/muc#owner");
						var x = query.appendChild(iq.getDoc().createElement("x"));
						x.setAttribute("xmlns", "jabber:x:data");
						x.setAttribute("type", "submit");
						con.send(iq);
					}
					break;
				  case "303": // nick change
		// display message
					if (!ouser.nick) {
						return;
					}
					var aMessage = new JSJaCMessage();
					aMessage.setFrom(user.jid);
					aMessage.setBody("" + ouser.name + " \u73b0\u5728\u5c31\u662f " + htmlEnc(ouser.nick));
					user.chatmsgs = user.chatmsgs.concat(aMessage);
					if (user.cFrame) {
						roster.openChat(user.jid);
						popMsgs(user);
					}
		
		// update nick if it's me
					if (ouser.name == htmlEnc(user.roster.nick)) {
						user.roster.nick = ouser.nick;
					}
		
		// remove old user
					var aChatW = ouser.chatW;
					user.roster.removeUser(ouser);
		
		// add new user
					ouser = new GroupchatRosterUser(presence.getFrom().substring(0, presence.getFrom().lastIndexOf("/") + 1).concat(ouser.nick), ouser.nick);
					if (aChatW && !aChatW.closed) {
						ouser.chatW = aChatW;
						ouser.chatW.user = ouser;
					}
					user.roster.addUser(ouser);
					nickChanged = true;
					break;
				  case "301": // user has been kicked
					var aMessage = new JSJaCMessage();
					aMessage.setFrom(user.jid);
					var body;
					if (ouser.actor) {
						body = "" + ouser.name + " \u88ab " + ouser.actor + " \u5c4f\u853d\u4e86";
					} else {
						body = "" + ouser.name + " \u88ab\u5c4f\u853d\u4e86";
					}
					if (ouser.reason) {
						body += ": " + ouser.reason;
					}
					aMessage.setBody(body);
					user.chatmsgs = user.chatmsgs.concat(aMessage);
					if (user.cFrame) {
						roster.openChat(user.jid);
						popMsgs(user);
					}
					playSound("chat_recv");
					break;
				  case "307": // user has been kicked
					var aMessage = new JSJaCMessage();
					aMessage.setFrom(user.jid);
					var body;
					if (ouser.actor) {
						body = "" + ouser.name + " \u88ab " + ouser.actor + " \u8e22\u51fa\u4e86";
					} else {
						body = "" + ouser.name + " \u88ab\u8e22\u51fa\u4e86";
					}
					if (ouser.reason) {
						body += ": " + ouser.reason;
					}
					aMessage.setBody(body);
					user.chatmsgs = user.chatmsgs.concat(aMessage);
					if (user.cFrame) {
						roster.openChat(user.jid);
						popMsgs(user);
					}
					playSound("chat_recv");
					break;
				}
			}
			Debug.log("<" + ouser.name + "> affiliation:" + ouser.affiliation + ", role:" + ouser.role, 3);
			if (!user.roster.getUserByJID(presence.getFrom()) && !nickChanged) {
	      // add user
				user.roster.addUser(ouser);
	      
	      // show join message
				var aMessage = new JSJaCMessage();
				aMessage.setFrom(user.jid);
				aMessage.setBody("" + ouser.name + " \u53d8\u4e3a\u7a7a\u95f2\u72b6\u6001");
				user.chatmsgs = user.chatmsgs.concat(aMessage);
				if (user.cFrame) {
					roster.openChat(user.jid);
					popMsgs(user);
				}
				//playSound("online");
			} else {
				if (presence.getType() == "unavailable" && !nickChanged) {
	      // show part message
					var aMessage = new JSJaCMessage();
					aMessage.setFrom(user.jid);
					var body = "" + ouser.name + " \u79bb\u5f00\u4e86";
					if (presence.getStatus()) {
						body += ": " + presence.getStatus();
					}
					aMessage.setBody(body);
					user.chatmsgs = user.chatmsgs.concat(aMessage);
					if (user.cFrame) {
						roster.openChat(user.jid);
						popMsgs(user);
					}
					//playSound("offline");
				} else {
					user.roster.updateGroups();
				}
			}
	    
	    // relink roster and user
			aRoster = user.roster;
			user = ouser;
		}
		if (show) {
			if (user.status == "unavailable") {
				//playSound("online");
			}
	    // fix broken pressenc status
			if (show != "chat" && show != "away" && show != "xa" && show != "dnd") {
				show = "available";
			}
			user.status = show;
		} else {
			if (type) {
				if (type == "unsubscribe") {
					user.subscription = "from";
					user.status = "stalker";
				} else {
					if (user.status != "stalker") {
						user.status = "unavailable";
					}
				}
				if (aRoster.name == "GroupchatRoster" && !nickChanged) { // it's a groupchat roster
	      // remove user
					if (!user.cFrame) {
						aRoster.removeUser(user);
					} // we don't need offline users in there
				}
				//playSound("offline");
			} else {
				if (user.status == "unavailable") { // user was offline before
					//playSound("online");
				}
				user.status = "available";
			}
		}
		var img = eval(user.status + "Led");
		if (user.lastsrc) { // message is pending
			user.lastsrc = img.src;
		}
	  
	  // show away message
		if (status) {
			user.statusMsg = status;
		} else {
			user.statusMsg = "[留言]";
		}
	  
	  // update presence indicator of chat window
		if (user.cFrame) {
			updateUserPresence(user);
		}
		aRoster.print(); // update roster
		for(var i=0; i<apperceive_users.length;i++){
			if(apperceive_users[i][1] + "@" +UMWEBSERVER == user.jid){
				if(apperceive_users[i].autoOpen == "on" || (apperceive_users[i].autoOpen == "online" && user.status == "available")){
					apperceive_users[i].autoOpen = "";
					if(typeof uin != "undefined" && uin != "" && flag == 1){
						aRoster.userClicked(document.getElementById(apperceive_users[i][1] + "@" +UMWEBSERVER + "apperceive"),user.jid,1);
					}else{
						aRoster.userClicked(document.getElementById(apperceive_users[i][1] + "@" +UMWEBSERVER + "apperceive"),user.jid);
					}
				}
			}
		}
	}
	 /************************************************************************
	 * handleIQSet
	 ************************************************************************
	 */
	function handleIQSet(iq) {
		 if (iq && iq.getType() == "error") {
            con._handleEvent("onerror", iq.getChild("error"));
            con.disconnect();
			document.getElementById("login_div_1").style.display="";
			document.getElementById("login_div_2").style.display="none";
            return;
        }
		
		if (iq.getQueryXMLNS() == "jabber:iq:umerror") { // only handle roster items so far
			for (var i = 0; i < iq.getQuery().childNodes.length; i++) {
				var item = iq.getQuery().childNodes.item(i);
				if(item.nodeName=="reason"){
					if(item.firstChild && item.firstChild.nodeValue=="is login"){
						if(isBlog == 0){
							alert("您的帐号已在别处登录，您已被迫下线！");
							logout();
						}else{
							logout(1);
						}
					}
				}
			}
		}
		if (iq.getQueryXMLNS() == "jabber:iq:umofflinefiles") {
			var item=iq.getQuery().childNodes.item(0);
			if(item.nodeName=="type"){
				if(item.firstChild && item.firstChild.nodeValue=="101"){
					for (var i = 1; i < iq.getQuery().childNodes.length; i++) {
						item = iq.getQuery().childNodes.item(i);
						if(item.nodeName=="files"){
							var realfilename=item.childNodes.item(2).firstChild.nodeValue;
							if(!fileDownload[realfilename]){
								var from = cutResource(item.childNodes.item(0).firstChild.nodeValue);
								var filename=item.childNodes.item(1).firstChild.nodeValue;
								
								fileDownload[realfilename]=[from,filename,realfilename,item.childNodes.item(3).firstChild.nodeValue,item.childNodes.item(5).firstChild.nodeValue];
								var user = roster.getUserByJID(from);
								if (user == null) {// users not in roster (yet)
									user = roster.addUser(new RosterUser(from));
									user.lastsrc = eval(user.status + "Led").src;
									roster.print();
								}
								user.fileMsg += "<div>&nbsp;<span style=\"color:red;font-size:12px;font-family:Tahoma;font-style: normal;font-weight: normal; \" class=msgnick>&lt;" + user.name + "&gt;</span>&nbsp;新文件[" + filename + "]发送时间[" + fileDownload[realfilename][4] + "]<span><a onclick=\"return parent.downloadFile(this,'" + realfilename + "');\" href=\"##\">[同意]</a>&nbsp;<a onclick=\"return parent.noDownloadFile(this,'" + realfilename + "');\" href=\"##\">[拒绝]</a></span></div>";
							}
						}
					}
					for(var j=0;j<roster.users.length;j++){
						var user=roster.users[j];
						if(user.fileMsg!=""){
							if (autoPopup && (autoPopupAway || onlstat == "available" || onlstat == "chat")) {
								if(user.cFrame){
									roster.openChat(user.jid);
									popMsgs(user);
								}else{
									roster.openChat(user.jid);
								}
								playSound("chat_recv");
							} else {
								if (focusWindows) {
									window.focus();
								}
								playSound("chat_queue");
								for (var i = 0; i < user.groups.length; i++) {
									if (user.groups[i].name != "临时好友") {
										if (roster.hiddenGroups[user.groups[i].name]) {
											fmd.images[user.groups[i].name + "Img"].src = arrow_right_blinking.src;
										}
									}
								}
							}
						}
					}
				}else if(item.firstChild && item.firstChild.nodeValue=="102"){
					if(downloading){
						alert("已有文件在下载，请稍后再试！");
					}else{
						downloading=true;
						var realfilename=iq.getQuery().childNodes.item(3).firstChild.nodeValue;
						fileDownload[realfilename].push(iq.getQuery().childNodes.item(1).firstChild.nodeValue);
						fileDownload[realfilename].push(iq.getQuery().childNodes.item(2).firstChild.nodeValue);
						var fs = FlashHelper.getFlash();
						if(typeof orgid != "undefined"){
							fs.download(fileDownload[realfilename][5],fileDownload[realfilename][6],"$_"+orgid,orgid,realfilename,fileDownload[realfilename][1],fileDownload[realfilename][3]);
						}else if(typeof uin != "undefined" && uin != ""){
							fs.download(fileDownload[realfilename][5],fileDownload[realfilename][6],"$_"+uin,uin,realfilename,fileDownload[realfilename][1],fileDownload[realfilename][3]);
						}else{
							fs.download(fileDownload[realfilename][5],fileDownload[realfilename][6],jid.substring(0,jid.indexOf("@")),pass,realfilename,fileDownload[realfilename][1],fileDownload[realfilename][3]);
						}
					}
				}
			}
		}
		if (iq.getQueryXMLNS() == "jabber:iq:kefuchange") {
			var item=iq.getQuery().childNodes.item(1);
			if(item.nodeName=="tojid"){
				if(item.firstChild){
					var aMessage = new JSJaCMessage();
					aMessage.setType("chat");
					aMessage.setFrom(item.firstChild.nodeValue);
					aMessage.setTo(roster.jid);
					aMessage.setBody("您好！原客服暂时不能为您服务，下面由我为您继续服务。谢谢！");
					handleMessage(aMessage);
				}
			}
		}
		if (iq.getType() != "set") {
			Debug.log("not handling iq:\n" + iq.getDoc().xml, 3);
			return;
		}
		Debug.log("got iq type 'set':\n" + iq.getDoc().xml, 2);
		if (iq.getQueryXMLNS() != "jabber:iq:roster") { // only handle roster items so far
			Debug.log("not handling iq:\n" + iq.getDoc().xml, 1);
			return;
		}
		for (var i = 0; i < iq.getQuery().childNodes.length; i++) {
			var item = iq.getQuery().childNodes.item(i);
			var user = roster.getUserByJID(cutResource(item.getAttribute("jid")));
			if (user) {
				user.subscription = item.getAttribute("subscription");
				if (item.getAttribute("subscription") == "remove") {
					Debug.log("removing user " + user.jid, 2);
					roster.removeUser(user);
					closeAndRemove("contact" + cutResource(item.getAttribute("jid")),"contact" + cutResource(item.getAttribute("jid")) + "_chatWindow");
					for(var i=0;i<windowContacts.length;i++){
						if(windowContacts[i]=="contact" + cutResource(item.getAttribute("jid"))){
							windowContacts.splice(i,1);
							break;
						}
					}
				} else { // update user
					user.name = item.getAttribute("name") ? htmlEnc(item.getAttribute("name")) : item.getAttribute("jid");
					user.groups = new Array(new RosterGroup('临时好友','',''));
					for (var j = 0; j < item.childNodes.length; j++) {
						if (item.childNodes.item(j).nodeName == "group") {
							if(item.childNodes.item(j).hasChildNodes()==true){
								var r_orgid = "";
								var parno = "";
								var groupName = item.childNodes.item(j).firstChild.nodeValue;
								if(item.childNodes.item(j).getAttribute('orgid'))
									r_orgid = item.childNodes.item(j).getAttribute('orgid');
								if(item.childNodes.item(j).getAttribute('parno'))
									parno = item.childNodes.item(j).getAttribute('parno');
								user.groups = user.groups.concat(new RosterGroup(groupName,r_orgid,parno));
							}
						}
					}
					roster.updateGroups();
				}
			} else {// got a new user
				if(item.getAttribute("subscription")!="remove"){
					if(roster.getUserByJID(cutResource(item.getAttribute("jid")))){
						var user = roster.getUserByJID(cutResource(item.getAttribute("jid")));
					    for (var j=0;j<item.childNodes.length;j++)
							if (item.childNodes.item(j).nodeName == 'group' && item.childNodes.item(j).firstChild){
								var r_orgid = "";
								var parno = "";
								var groupName = item.childNodes.item(j).firstChild.nodeValue;
								var group = this.getGroupByName(groupName);
								if(group == null){
									if(item.childNodes.item(j).getAttribute('orgid'))
										r_orgid = item.childNodes.item(j).getAttribute('orgid');
									if(item.childNodes.item(j).getAttribute('parno'))
										parno = item.childNodes.item(j).getAttribute('parno');
									group=new RosterGroup(groupName,r_orgid,parno);
									this.groups = this.groups.concat(group);
								}
								group.users = group.users.concat(user);
								user.add2Group(group);
							}
					}else{
					    var name = item.getAttribute('name') || cutResource(item.getAttribute('jid'));
					    var groups = new Array(new RosterGroup('临时好友','',''));
					    for (var j=0;j<item.childNodes.length;j++)
							if (item.childNodes.item(j).nodeName == 'group' && item.childNodes.item(j).firstChild){
								var r_orgid = "";
								var parno = "";
								var groupName = item.childNodes.item(j).firstChild.nodeValue;
								if(item.childNodes.item(j).getAttribute('orgid'))
									r_orgid = item.childNodes.item(j).getAttribute('orgid');
								if(item.childNodes.item(j).getAttribute('parno'))
									parno = item.childNodes.item(j).getAttribute('parno');
								groups = groups.concat(new RosterGroup(groupName,r_orgid,parno));
							}
					    roster.addUser(new RosterUser(item.getAttribute('jid'),item.getAttribute('subscription'),groups,name));
				    }
					
					var aPresence=new JSJaCPresence();
					aPresence.setType("subscribe");
					aPresence.setTo(item.getAttribute("jid"));
					var priority=aPresence.getDoc().createElement("priority");
					priority.appendChild(aPresence.getDoc().createTextNode("0"));
					aPresence.getNode().appendChild(priority);
					con.send(aPresence);
				}
			}
		}
		roster.print();
	}
	function handleConError(e) {
		switch (e.getAttribute("code")) {
		  case "401":
			alert("用户名或密码错误，验证失败");
			if (!con.connected()) {
				window.close();
			}
			break;
		  case "409":
			alert("\u6ce8\u518c\u5931\u8d25\uff01\n\n\u8bf7\u6362\u4e00\u4e2a\u7528\u6237\u540d\uff01");
			break;
		  case "503":
		  	if(conAmount<4){
		  		con._connected=false;
		  		conAmount++;
		  		if(isCancel){
		  			isCancel = false;
				}else{
					changeStatus(onlstat, onlmsg);
				}
		  	}
			break;
		  case "500":
			if (!con.connected() && !logoutCalled && onlstat != "offline") {
				if (confirm("\u670d\u52a1\u5668\u5185\u90e8\u9519\u8bef\uff01\n\n\u8fde\u63a5\u65ad\u5f00\uff01\n\u91cd\u65b0\u8fde\u63a5\u5417\uff1f")) {
					changeStatus(onlstat, onlmsg);
				}
			}
			break;
		  default:
			alert("An Error Occured:\nCode: " + e.getAttribute("code") + "\nType: " + e.getAttribute("type") + "\nCondition: " + e.firstChild.nodeName); // this shouldn't happen :)
			break;
		}
	}
	function handleDisconnect() {
		if (logoutCalled || onlstat == "offline") {
			return;
		}
	  
	  // disconnecting not with onunload handler triggered
		statusLed.src = unavailableLed.src; // offline icon
		statusMsg.innerHTML = "";
		fmd.getElementById("roster").innerHTML = "";
	  
	// 	if (confirm("连接断开！n重新连接吗？"))
	// 		changeStatus(onlstat,onlmsg);
	}
	function handleConnected(iq) {
		Debug.log("Connected", 0);
		if(typeof orgid != dd_u){
			frames["main_iframe1"].document.getElementById("orgLogoImg").src="http://" + UMWEBSERVER + ":5273/" + orgid + "/" + orgid + "_logo.gif";
		}
		var listStr = "";
		var version = (typeof iq == "undefined") ? -1 : (iq.getNode().getAttribute("version") ? parseInt(iq.getNode().getAttribute("version")) : -1);
		if(version >=0){
			listStr = $um_obj("storage").getRosterCache(version,cutResource(jid) + "localUserList");
		}
		if(listStr == ""){
			/* get/setup roster */
			iq = new JSJaCIQ();
			iq.setIQ(null, "get", "roster_1");
			if(typeof orgid != "undefined"){
				iq.appendNode("query", {xmlns:"jabber:iq:roster"}, [["orgid", oCon.orgid]]);
			}else if(typeof uin != "undefined" && uin != ""){
				iq.appendNode("query", {xmlns:"jabber:iq:webroster"}, [["uins", apperceive_users]]);
			}else{
				iq.setQuery("jabber:iq:roster");
			}
			con.send(iq, getRosters); // cascading information retrieval
		}else{
			var xmldoc = XmlDocument.create('body','http://jabber.org/protocol/httpbind');
			xmldoc.loadXML('<body xmlns=\"http://jabber.org/protocol/httpbind\">' + listStr + '</body>');
			var iq = JSJaCPacket.wrapNode(xmldoc.firstChild.childNodes.item(0).cloneNode(true));
			getRoster(iq);
			iq = new JSJaCIQ();
			iq.setIQ(null, "get", "status_1");
			iq.setFrom(jid);
			iq.setQuery("jabber:iq:status");
			con.send(iq);
		}
	}
	function getRosters(iq){
		getRoster(iq);
		$um_obj("storage").setRosterCache(cutResource(jid) + "localUserList",iq.getDoc().xml);
	}
	/* *** cascading onconnect handlers *** */
	function getRoster(iq) {
		if (!iq || iq.getType() != "result") {
			if (iq) {
				Debug.log("Error fetching roster:\n" + iq.getDoc().xml, 1);
			} else {
				Debug.log("Error fetching roster", 1);
			}
			return;
		}
		Debug.log("got roster:\n" + iq.getDoc().xml, 2);
		roster = new Roster(iq.getQuery().childNodes, fmd);
		roster.usersHidden = usersHidden;
		roster.nick = jid.substring(0, jid.indexOf("@")); // remember nick for 1:1 Chats
	  // print roster
	  	fmd.getElementById("roster").innerHTML="";
		roster.print();
		onlprio = DEFAULTPRIORITY;
	
	  // send presence
		if (onlstat == "") {
			onlstat = "available";
		}
		changeStatus(onlstat, onlmsg, onlprio);
		if(typeof uin == "undefined" || uin == ""){
			objName = "main"; 
			showWindowItem("main");
		    windowMaximizeZ("main");
	    }
    	try{
			t_editName = unescape(JSJaCCookie.read("editname").getValue());
		}catch(e){}
		try{
			t_editTel = unescape(JSJaCCookie.read("edittel").getValue());
		}catch(e){}
		if(typeof linkMan != "undefined" && linkMan != ""){
			t_editLinkMan = linkMan;
		}
		if(t_editName.length>0 || t_editTel.length>0 || t_editLinkMan.length>0 ){
			var iq = new JSJaCIQ();
			iq.setIQ(null, "set", "owninfo_1");
			iq.appendNode("query", {xmlns:"jabber:iq:owninfo"}, [["linkman", t_editLinkMan],["username", t_editName],["usertel", t_editTel]]);
			con.send(iq);
		}
		if(typeof uin != "undefined" && uin != "" && flag == 1){
			var iq = new JSJaCIQ();
			iq.setType('get');
			iq.setTo(uin + "@" + UMWEBSERVER);
			try{
				var vCard = iq.getNode().appendChild(iq.getDoc().createElementNS('vcard-temp','vCard'));
			}catch(e){
				var vCard = iq.getNode().appendChild(iq.getDoc().createElement('vCard'));
				vCard.setAttribute('xmlns','vcard-temp');
			}
			con.send(iq,_handleVCard);
		}
	}
	
	function _handleVCard(iq) {
		if (!iq) {
			return;
		}
		if (iq.getNode().getElementsByTagName('vCard').item(0)) {
			for (var i=0; i<iq.getNode().getElementsByTagName('vCard').item(0).childNodes.length; i++) {
				var token = iq.getNode().getElementsByTagName('vCard').item(0).childNodes.item(i);
				tokenname = token.nodeName;
				if (token.firstChild && token.firstChild.nodeType != 3) { // found a container
					for (var j=0; j<token.childNodes.length; j++) {
						if (document.getElementById(tokenname+"."+token.childNodes.item(j).nodeName) && token.childNodes.item(j).firstChild){
							document.getElementById(tokenname+"."+token.childNodes.item(j).nodeName).innerHTML = token.childNodes.item(j).firstChild.nodeValue;
						}
					}
		
	      		} else{
					if (document.getElementById(tokenname) && token.firstChild){
						document.getElementById(tokenname).innerHTML = token.firstChild.nodeValue;
					}
				}
			}
		}
	}
	/************************************************************************
	*                       ******  END HANDLERS  ******* 
	************************************************************************
	*/
	/************************************************************************
	*                           ******  INIT  *******
	************************************************************************
	*/
	var con, Debug, srcW;
	function init() {
		/* initialise debugger */
		if (!Debug || typeof (Debug) == "undefined" || !Debug.start) {
			if (typeof (Debugger) != "undefined") {
				Debug = new Debugger(DEBUG_LVL, "JWChat " + cutResource(jid));
			} else {
				Debug = new Object();
				Debug.log = function () {
				};
				Debug.start = function () {
				};
			}
		}
		if (DEBUG && (!USE_DEBUGJID || DEBUGJID == cutResource(jid))) {
			Debug.start();
		}
		Debug.log("jid: " + jid + "\npass: " + pass, 2);
		/* get some refs to static elements */
		statusLed = frames["main_iframe1"].document.getElementById("statusLed");
		statusMsg = frames["main_iframe1"].document.getElementById("statusMsg");
		//fmd = frames["main_iframe1"].iRoster.document;
		/* set nick */
		frames["main_iframe1"].document.getElementById("myNickname").innerHTML = nick;
		/* ***
	   * create new connection
	   */
		var oArg = {oDbg:Debug, httpbase:HTTPBASE, timerval:timerval};
		con = new JSJaCHttpBindingConnection(oArg);
		/* register handlers */
		con.registerHandler("iq", handleIQSet);
		con.registerHandler("presence", handlePresence);
		con.registerHandler("message", handleMessage);
		con.registerHandler("message", handleMessageError);
		con.registerHandler("ondisconnect", handleDisconnect);
		con.registerHandler("onconnect", handleConnected);
		con.registerHandler("onerror", handleConError);
		/* connect to remote */
		if(typeof orgid != dd_u){
			oArg = {domain:UMWEBSERVER, username:jid.substring(0, jid.indexOf("@")), resource:jid.substring(jid.indexOf("/") + 1), orgid:orgid};
		}else if(typeof uin != "undefined" && uin != ""){
			oArg = {domain:UMWEBSERVER, username:jid.substring(0, jid.indexOf("@")), resource:jid.substring(jid.indexOf("/") + 1), uin:uin};
		}else{
			oArg = {domain:UMWEBSERVER, username:jid.substring(0, jid.indexOf("@")), resource:jid.substring(jid.indexOf("/") + 1), pass:pass}; 
		}
		con.connect(oArg);
	}
	
	/************************************************************************
	 *                       ******  LOGOUT  *******
	 ************************************************************************
	 */
	
	function cleanUp() {
		
		/* close dependent windows */
		if (roster) {
			roster.cleanUp();
		}
		if (subw && !subw.closed) {
			subw.close();
		}
		if (typeof (ow) != "undefined" && ow && !ow.closed) {
			ow.close();
		}
		
		if(flag == 0 || isBlog == 1){
	        for(var objName in windowItems){
	            if(typeof windowItems[objName] == "function") continue;
	            if(objName.indexOf("openSubscription")>=0 && objName!="openSubscription"){
	                closeAndRemove(objName,"subscriptionWindow"+objName.substring("openSubscription".length));
	             }else if(objName.indexOf("openSubRequest")>=0){
	                closeAndRemove(objName,"subRequestWindow"+objName.substring("openSubRequest".length));
	             }else if(objName.indexOf("contact")>=0){
	                closeAndRemove(objName,objName+"_chatWindow");
	             }else if(objName!="main"){
	                if(taskbarItems[objName + "_taskbarItem"]!=null){
	                      if(objName=="openStatus" || objName=="openSubscription"){
	                          windowMinimize(objName);
	                      }else{
	                          windowClose(objName);
	                      }
	                }else{
	                	windowClose(objName);
	                }
	                delete windowItems[objName];
	                dd.elements[objName + "_frameFantom"].del();
	                dd.elements[objName + "_frame"].del();
	                dd.elements[objName + "_windowButtons"].del();
	                dd.elements[objName + "_textDiv"].del();
	                dd.elements[objName + "_resizehandle"].del();
	                dd.elements[objName + "_headerMovable"].del();
	                if(objName!="openStatus" && objName!="openSubscription" && isBlog == 0)
	                dd.elements[objName + "_taskbarItem"].del();
	            }else if(objName=="main"){
	                windowMinimize(objName);
	            }
	        }
        }
		fmd.getElementById("roster").innerHTML = "";
	
	  // clear frames
		frames["jwc_sound"].document.open();
		frames["jwc_sound"].document.write();
		frames["jwc_sound"].document.close();
	}
	
	var logoutCalled = false;
	function logout() {
        logoutCalled = true;
        cleanUp();
        if (!con.connected()) {
            return;
        }
        var aPresence = new JSJaCPresence();
        aPresence.setType("unavailable");
        con.send(aPresence);
        con.disconnect();
        if(arguments.length==0){
	        if(flag==0){
	        	document.getElementById("login_inner_div").style.background="url(" + basePath + "images/login.png) no-repeat scroll center center transparent";
	        }
	        showWindowItem('login');
	        windowMaximizeZ('login');
        }
    }
    
   	function logout1() {
       logout(1);
    }
	
	function um_connect(){
		dd.elements.shared_downDiv.moveTo((dd.getWndW()-dd.elements.shared_downDiv.w)/2, (dd.getWndH()+dd.getScrollY()-dd.elements.shared_downDiv.h)/2);
		if(FlashHelper.flashLoaded){
			var tempjid;
		  	try{
				tempjid=JSJaCCookie.read("tempjid").getValue();
			}catch(e){
				var now = new Date();
				tempjid= ("0" + (now.getMonth() + 1)).slice(-2) + ("0" + now.getDate()).slice(-2)
					+ ("0" + now.getHours()).slice(-2) + ("0" + now.getMinutes()).slice(-2)
					+ ("0" + now.getSeconds()).slice(-2) + ("00" + now.getMilliseconds()).slice(-3);
				new JSJaCCookie("tempjid",tempjid,10*24*3600).write();
			}
			jid = "um-" + tempjid + "@" + UMWEBSERVER + "/"  + DEFAULTRESOURCE; //"guoqing@" + UMWEBSERVER + "/"  + DEFAULTRESOURCE;
			/*if (!isValidJID(jid)) {
				return false;
			}*/
			nick = jid.substring(0, jid.indexOf("@"));
			//pass="lenovo";
			init();
			return false;
		}else{
			setTimeout(um_connect,100);
		}
	}
	function member_connect(){
		uin="";
		dd.elements.shared_downDiv.moveTo((dd.getWndW()-dd.elements.shared_downDiv.w)/2, (dd.getWndH()+dd.getScrollY()-dd.elements.shared_downDiv.h)/2);
		if(FlashHelper.flashLoaded){
			for(var i=0;i<tempargs.length;i++){
				if(tempargs[i].indexOf("v_username=")>=0){
					jid=tempargs[i].substring(tempargs[i].indexOf("=")+1) + "@" + UMWEBSERVER + "/"  + DEFAULTRESOURCE;
				}
				if(tempargs[i].indexOf("v_pass=")>=0){
					pass=tempargs[i].substring(tempargs[i].indexOf("=")+1);
				}
			}
			if(typeof pass != "undefined" && pass != ""){
				nick = jid.substring(0, jid.indexOf("@"));
				if(document.getElementById("login_textDiv")){
					document.getElementById("login_div_1").style.display="none";
					document.getElementById("login_div_2").style.display="";
					isCancel=false;
				}
				init();
			}
			return false;
		}else{
			setTimeout(member_connect,100);
		}
    }
    function login_init(){
		if (arguments[0] == '') {
			alert("您需要提供一个用户名");
			return false;
		}
		if (arguments[1] == '') {
			alert("您需要提供一个密码");
	    	return false;
	  	}
	  	if(arguments[0].indexOf('@')>0){
	  		UMWEBSERVER = arguments[0].substring(arguments[0].indexOf('@')+1);
	  		arguments[0] = arguments[0].substring(0,arguments[0].indexOf('@'));
	  	}
		if (!isValidJID(arguments[0])) {
			return false;
		}
    	for(var i=0;i<tempargs.length;i++){
			if(tempargs[i].indexOf("v_username=")>=0){
				tempargs.splice(i,1);
			}
			if(tempargs[i].indexOf("v_pass=")>=0){
				tempargs.splice(i,1);
			}
		}
    	tempargs.push("v_username=" + arguments[0]);
    	tempargs.push("v_pass=" + arguments[1]);
    	member_connect();
    }

	/************************************************************************
	*                     ******  INITIALISE VARS  *******
	************************************************************************
	*/
	
	/* get style */
	function updateStyleIE() {
		if (roster) {
			roster.updateStyleIE();
		}
	}
	function openChangeStatus(isShow) {
        var container = document.getElementById("statusWindow");
        var display=["修改状态","<img style=\"margin-top:3px;\" src=\"" + basePath + "images\/status.gif\"\/>"];
        buildWindow(container, "openStatus", 300, 150, display, (flag == 0 ? 90 : 63), "javascript:\"<script src='" + basePath + "changestatus.js' charset='utf-8'><\/script>\"","",60,isShow,1);
        return false;
    }
	
	function buildWindow(container, windowId, windowX, windowY, display, buttonsX, srcPath, extend, taskbarW, isShow) {
		var caption = new Array();
		if(typeof(display)=="object"){
			caption=display;
			display=caption[0];
		}
		var obj = dd.elements[windowId + "_frame"];
		if (obj == null) {
			var rangeX = dd.getWndW() - 325 - 480;
			var rangeY = dd.getWndH() - 40 - 400;
			var ran_unroundedX = Math.random() * rangeX;
			posX = Math.floor(ran_unroundedX);
			var ran_unroundedY = Math.random() * rangeY;
			posY = Math.floor(ran_unroundedY);
			posX = posX + 320;
			if (posY - dd.getScrollY()< topPadding) {
				posY = topPadding + dd.getScrollY();
			}
			var text = "";
			text = text + "<div id=\"" + windowId + "_frameFantom\" class=\"im-windowfantom-des\" style=\"top:" + posY + "px;left:" + posX + "px;width:" + windowX + "px;height:" + windowY + "px\"></div>";
			text = text + "<div id=\"" + windowId + "_resizehandle\" class=\"im-window-resizehandle\" title=\"Resize\"></div>";
			text = text + "<div id=\"" + windowId + "_frame\" class=\"im-window common_border_color\" style=\"top:" + posY + "px;left:" + posX + "px;width:" + windowX + "px;height:" + windowY + "px\">";
			text = text + "	<DIV id=" + windowId + "_frameHeader class=im-windowhead onfocus=focusEvent(this.id)>";
			text = text + "  	<div class=\"im-windowhead-radius-a\"></div>";
			text = text + "		<div class=\"im-windowhead-radius-b common_background_color common_border_color\">";
			text = text + "			<table border=0 cellspacing=0 cellpadding=0 style=\"width:100%;height:1px;\">";
			text = text + "				<tr><td class=\"im-windowhead-radius-b-l\"></td><td class=\"im-windowhead-radius-b-inner\">&nbsp;</td><td class=\"im-windowhead-radius-b-l\"></td></tr>";
			text = text + "			</table>";
			text = text + "		</div>";
			text = text + "		<div class=\"common_background_color\"><div class=\"im-windowhead-radius-m common_border_color\"><div class=\"im-windowhead-radius-f\">&nbsp;";
			text = text + "			<DIV style=\"width:" + buttonsX + "px\" id=" + windowId + "_windowButtons class=im-windowbutton-container onfocus=focusEvent(this.id) align=right>";
			if(flag == 0){
				text = text + "<span class=\"im-window-button im-window-transition\"></span><span class=\"im-window-button im-window-minimizebutton\" title=\"最小化\" onclick=\"windowMinimize('" + windowId + "')\"></span>";
			}
			text = text + "<span class=\"im-window-button im-window-transition\"></span><span class=\"im-window-button im-window-maximizerestorebutton\" title=\"最大化/还原\" onclick=\"windowMaximizeRestore('" + windowId + "')\"></span>";
			text = text + "<span class=\"im-window-button im-window-transition\"></span><span class=\"im-window-button im-window-closebutton\" title=\"关闭\" ";
			if(extend){
				text = text + "onclick=\"closeAndRemove('" + windowId + "','" + extend + "');\"></span>";
			}else if(arguments[10]){
				text = text + "onclick=\"windowMinimize('" + windowId + "');\"></span>";
			}else{
				text = text + "onclick=\"windowClose('" + windowId + "')\"></span>";
			}
			text = text + "			<\/DIV>";
			text = text + "		</div></div></div>";
			text = text + "	<\/DIV>";
			text = text + "<div id=\"" + windowId + "_frame_body\" class=\"im-windowbody common_background_color common_border_color\" onfocus=\"focusEvent(this.id)\">";
			text = text + "<div id=\"" + windowId + "_textDiv\" class=\"im-windowbody-inner common_background_color\">";
			text = text + "<iframe name=\"" + windowId + "_iframe1\" id=\"" + windowId + "_iframe1\" style=\"overflow:hidden;width:100%;height:100%;overflow:auto;border-width:0px\" scrolling=\"no\" frameborder=\"0\" onfocus=\"focusEvent(this.id)\" onblur=\"windowBlur()\" src=\"\" allowTransparency= \"true\"></iframe>";
			text = text + "</div><div id=\"" + windowId + "_statusText\" style=\"font-size:11px;padding:1px 2px;color:555555\">&nbsp;</div></div></div>";
			text = text + "<div id=\"" + windowId + "_headerMovable\" class=\"im-windowfantom-des\" style=\"top:" + posY + "px;left:" + posX + "px;width:220px;height:26px;padding-top:5px;text-indent:6px;line-heigth:26px;\" onfocus=\"focusEvent(this.id)\"><span id=\"" + windowId + "_title\" style=\"font-weight: bold;font-size:12px;vertical-align: top;\">" + display + "</span></div>";
			if(windowId!="openStatus" && windowId!="openSubscription" && flag == 0){
				text = text + "<div id=\"" + windowId + "_taskbarItem\" class=\"im-taskbaritem\" onclick=\"taskbarItemClick(this.id)\" style=\"top:-100px;left:-100px; WIDTH:" + (taskbarW) + "px;\"></div>";
			}
			container.innerHTML = text;
			ADD_DHTML(windowId + "_frameFantom" + TRANSPARENT + NO_DRAG);
			ADD_DHTML(windowId + "_frame" + NO_DRAG);
			ADD_DHTML(windowId + "_windowButtons" + NO_DRAG);
			ADD_DHTML(windowId + "_textDiv" + NO_DRAG);
			ADD_DHTML(windowId + "_resizehandle" + CURSOR_NW_RESIZE);
			ADD_DHTML(windowId + "_headerMovable" + CURSOR_MOVE);
		}
		document.getElementById(windowId + "_iframe1").src = srcPath;
		document.getElementById(windowId + "_title").innerHTML = display;
		dd.elements[windowId + "_windowButtons"].moveTo(dd.elements[windowId + "_frame"].x + dd.elements[windowId + "_frame"].w - dd.elements[windowId + "_windowButtons"].w - 6, dd.elements[windowId + "_frame"].y);
		dd.elements[windowId + "_resizehandle"].moveTo(dd.elements[windowId + "_frame"].x + dd.elements[windowId + "_frame"].w - dd.elements[windowId + "_resizehandle"].w - 2, dd.elements[windowId + "_frame"].y + dd.elements[windowId + "_frame"].h - dd.elements[windowId + "_resizehandle"].h - 2);
		dd.elements[windowId + "_headerMovable"].moveTo(dd.elements[windowId + "_frame"].x, dd.elements[windowId + "_frame"].y);
		dd.elements[windowId + "_headerMovable"].resizeTo(dd.elements[windowId + "_frame"].w - buttonsX - 3, 26);
		//dd.elements[windowId + "_headerMovable"].setOpacity(0);
		var windowItem = windowItems[windowId];
		if (windowItem == null) {
			windowItem = new Object();
			windowItem.x = dd.elements[windowId + "_frame"].x;
			windowItem.y = dd.elements[windowId + "_frame"].y;
			windowItem.w = dd.elements[windowId + "_frame"].w;
			windowItem.h = dd.elements[windowId + "_frame"].h;
			windowItem.state = WINDOW_STATE_REGULAR;
			windowItems[windowId] = windowItem;
		}
		if(isShow){
			showWindowItem(windowId);
			windowMaximizeZ(windowId); 
		}else{
			hideWindowItem(windowId);
		}
		if(typeof(caption.lenght)!=dd_u){
			display=caption[1];
		}
		if(flag == 0){
			var text = "";
			text = text + "<div class=\"im-taskbaritem-des-border\"><div class=\"im-common-shadow\" style=\"float:left;width:95px;\">" + display + "</div>";
			text = text + "<div class=\"im-common-shadow\" style=\"float:left;font-weight:bold;color:red;text-align:center;width:16px;\" title=\"关闭窗口\"";
			if(extend){
				text = text + " onclick=\"closeAndRemove('" + windowId + "','" + extend + "');\">X</div></div>"
			}else if(arguments[10]){
				text = text + " onclick=\"windowMinimize('" + windowId + "');\">X</div></div>"
			}else{
				text = text + " onclick=\"windowClose('" + windowId + "');\">X</div></div>";
			}
			
			addTaskBarItem(windowId + "_taskbarItem", text);
		}
		return false;
	}
	function closeAndRemove(windowId,containerId){
		if(dd.elements[windowId + "_frame"]!=null && dd.elements[windowId + "_frame"].visible){
			windowClose(windowId);
		}
		if(document.getElementById(containerId)!=null){
			delete windowItems[windowId];
			dd.elements[windowId + "_frameFantom"].del();
			dd.elements[windowId + "_frame"].del();
			dd.elements[windowId + "_windowButtons"].del();
			dd.elements[windowId + "_textDiv"].del();
			dd.elements[windowId + "_resizehandle"].del();
			dd.elements[windowId + "_headerMovable"].del();
			if(isBlog == 0){
				dd.elements[windowId + "_taskbarItem"].del();
			}
			document.getElementById(containerId).parentNode.removeChild(document.getElementById(containerId));
		}
	}
	function c(){
		hideAllChatSelecitons();
		windowFocus();
	}
	
	onunload = logout1;
	onresize = updateStyleIE;
	var temp=0;
	window.onscroll=function(){
		if(document.getElementById("main_iframe1").contentWindow.document.getElementById("statusMenuDiv"))
		hideAllChatSelecitons();
		var offsetX=0;
		var offsetY=dd.getScrollY()-temp;
		for(var objName in windowItems){
			if(typeof windowItems[objName] == "function") continue;
			dd.elements[objName + "_frameFantom"].moveBy(offsetX,offsetY);
			dd.elements[objName + "_frame"].moveBy(offsetX,offsetY);
			dd.elements[objName + "_headerMovable"].moveBy(offsetX,offsetY);
			dd.elements[objName + "_resizehandle"].moveBy(offsetX,offsetY);
			var windowItem = windowItems[objName];
			windowItem.y += offsetY;
		}
        for(var i in taskbarItems){
            if(typeof taskbarItems[i] == "function") continue;
            objName = i;
            dd.elements[objName].moveBy(offsetX,offsetY);
        }
        if(flag == 0){
        	dd.elements["taskbar"].moveBy(offsetX,offsetY);
        }else{
			dd.elements["service_logo"].moveBy(offsetX,offsetY);
		}
		dd.elements["login_frameFantom"].moveBy(offsetX,offsetY);
		dd.elements["login_frame"].moveBy(offsetX,offsetY);
		dd.elements["login_headerMovable"].moveBy(offsetX,offsetY);
		temp=dd.getScrollY();
	}
	
	function hideTaskbarItemClick(){
		var hide_div=document.getElementById("hide_div");
		if(flag == 0){
	        var hide_taskbarItem=document.getElementById("hide_taskbarItem");
	        if(hide_div.style.display=="block"){
	            hide_div.style.display="none";
	            document.getElementById("hide_inner_div").style.background="url(" + basePath + "images/design2009/main/max_taskbaritem.png) no-repeat scroll center center transparent";
			    dd.elements.taskbar.moveTo(dd.getWndW()- dd.elements.hide_taskbarItem.w-4, dd.getWndH()+dd.getScrollY()-28);
			    dd.elements.taskbar.resizeTo(dd.elements.hide_taskbarItem.w+4, 28);
	        }else{
	            hide_div.style.display="block";
	            document.getElementById("hide_inner_div").style.background="url(" + basePath + "images/design2009/main/min_taskbaritem.png) no-repeat scroll center center transparent";
				dd.elements.taskbar.moveTo(0, dd.getWndH()+dd.getScrollY()-28);
				dd.elements.taskbar.resizeTo(dd.getWndW(), 28);
	        }
		}else{
			if(hide_div.style.display=="block"){
				hide_div.style.display="none";
				dd.elements.service_logo.show();
			}else{
				hide_div.style.display="block";
				dd.elements.service_logo.hide();
			}
		}
	}
	
	function um_cancelLog(){
			document.getElementById("login_div_1").style.display="";
			document.getElementById("login_div_2").style.display="none";
			isCancel=true;
			cancelLog();
	}
	function cancelLog(){
		if(con._sid && isCancel){
			$um_obj("storage").cancelLog(con._sid);
		}else if(isCancel){
			setTimeout("cancelLog()",10);
		}
	}
	function handleLog(e){
		document.getElementById("login_prompt").innerHTML="";
		document.getElementById("login_prompt").parentNode.style.display="none";
		if(arguments.length>2){
			if(arguments[1] != ""){
				document.getElementById("login_prompt").parentNode.style.display="";
				document.getElementById("login_prompt").innerHTML=arguments[1];
			}
			dd.elements["login_frameFantom"].moveTo(arguments[2],arguments[3]);
			dd.elements["login_frame"].moveTo(arguments[2],arguments[3]);
			dd.elements["login_headerMovable"].moveTo(arguments[2],arguments[3]);
		}
		showWindowItem('login');
		windowMaximizeZ('login');
		if(typeof e != "undefined" && e != ""){(is.ie) ? e.cancelBubble=true : e.stopPropagation()};
	}
	function loginComplete(){
		if(typeof pass != "undefined" && pass != ""){ 
			hideWindowItem('login');
			if(flag == 0){
				document.getElementById("login_inner_div").style.background="url(" + basePath + "images/logout.png) no-repeat scroll center center transparent";
			}
			document.getElementById("login_div_1").style.display="";
			document.getElementById("login_div_2").style.display="none";
			if(typeof roster != "undefined" && flag != 0){
				for(var i=0;i<roster.users.length;i++){
					if(roster.users[i].cFrame){
						document.getElementById(roster.users[i].windowId + "_login_div").style.display = "none";
					}
				}
			}
	        //避免该div的width或height可能超过之前的值，会吧窗口撑出滚动条，计算的窗口宽度或高度出现误差
	        /*dd.elements.service_logo.moveTo(dd.getWndW()-88, (dd.getWndH()-88)+dd.getScrollY());
	        dd.elements.service_logo.resizeTo(24,24);
	        dd.elements.service_logo.moveTo(dd.getWndW()-dd.elements.service_logo.w-2, (dd.getWndH()-dd.elements.service_logo.h-2)+dd.getScrollY());*/
        }
	}
	function getTop(e){
		var offset=e.offsetTop;
		if(e.offsetParent!=null) offset+=getTop(e.offsetParent);
			return offset;
	}
  	function getLeft(e){
		var offset=e.offsetLeft;
		if(e.offsetParent!=null) offset+=getLeft(e.offsetParent);
			return offset;
	}
	
  	function picker(v_color){
  		try{
	  		var v_border_color = "#" + ("00000" + ((parseInt(v_color,16)- 0x503f34)>=0 ? (parseInt(v_color,16)- 0x503f34):0).toString(16)).slice(-6);
	  		if(document.getElementById("picker").styleSheet){
	  			document.getElementById("picker").styleSheet.rules[1].style.borderColor = v_border_color;
	  			document.getElementById("picker").styleSheet.rules[2].style.backgroundColor = "#" + v_color;
	  			document.getElementById("picker").styleSheet.rules[3].style.backgroundColor = "#" + v_color;
	  			document.getElementById("picker").styleSheet.rules[4].style.backgroundColor = "#" + v_color;
	  			document.getElementById("picker").styleSheet.rules[5].style.backgroundColor = v_border_color;
	  			//alert(document.getElementById("picker").styleSheet.rules[0].style.cssText);
	  		}else{
	  			document.getElementById("picker").sheet.cssRules[1].style.borderColor = v_border_color;
	  			document.getElementById("picker").sheet.cssRules[2].style.backgroundColor = "#" + v_color;
	  			document.getElementById("picker").sheet.cssRules[3].style.backgroundColor = "#" + v_color;
	  			document.getElementById("picker").sheet.cssRules[4].style.backgroundColor = "#" + v_color;
	  			document.getElementById("picker").sheet.cssRules[5].style.backgroundColor = v_border_color;
	  			//alert(document.getElementById("picker").sheet.cssRules[0].style.cssText); 
	  		}
	  		if(arguments.length==1){
    			new JSJaCCookie("vcolor",v_color,10*24*3600).write();
    		}
  		}catch(e){alert(e.message);}
	}
	
	function openFlashDiv(){
		FlashHelper.getFlash().height = 160;
		FlashHelper.getFlash().width = 240;
	}
	
	function closeFlashDiv(){
		FlashHelper.getFlash().height = 1;
		FlashHelper.getFlash().width = 1;
	}