var UIRegistry = {}
UIRegistry.conversation = new Conversation();

var movieClipMap = {
	":@" : 'angry_mc',
	":'(" : 'cry_mc'
}

var displayTas = {
   regExpPattern:  new RegExp("「(.*?)」","gmi"),	
   image:'<img src="image/tag/wellcome.jpg">'   
}
function SendIM(cmd) {
	var msgr = null;
	try {
		var msgr = new ActiveXObject("MSNMessengerLib.MSNMessenger");
		if (msgr.MyStatus > 1) {
			var contacts = msgr.MyContacts;
			for (var i = 0; i < contacts.Count; i++) {
				var contact = contacts.Item(i);
				if (contact.SigninName == "i@xiaoi.com") {
					var conv = msgr.InstantMessage(contact);
					conv.SendIM(cmd);
					return false;
				}
			}
		}
	} catch (e) {

	}
	if (msgr != null) {
		msgr = null;
	}
	return true;

}

function showFloatEntrance(cmd) {
	try {
		window.top
				.flashbot_showEntrance('http://www.xiaoi.com/newentrance/2/?SCMD='
						+ cmd);
		return;
	} catch (e) {
	}
	UIRegistry.conversation.SendMessage(cmd);
}

var dataUtils = {
	SEPARATOR : "\1",
	KEY_VALUE_SEPARATOR : "\2",
	parse : function(data) {
		if (!data || data.length == 0)
			return;
		var attrs = data.split(this.SEPARATOR);
		var retMap = {};
		for (var i = 0; i < attrs.length; i++) {
			var idx = attrs[i].indexOf(this.KEY_VALUE_SEPARATOR);
			if (idx > 0) {
				var key = attrs[i].substring(0, idx);
				var value = attrs[i].substring(idx + 1);
				retMap[key] = value;
			}
		}
		return retMap;
	}
}

var isShowNextReply = false;
var realProcessMessageReceived0 = processMessageReceived0;
processMessageReceived0 = function(message) {
	if (message[KEY_COMMAND] == COMMAND_CHAT) {
		var msgText = message[KEY_MESSAGE];
		// var msgText = ':@';
		for (var key in movieClipMap) {
			if (msgText.indexOf(key) != -1)
				UIRegistry.xiaoiFlash.playMc(movieClipMap[key]);
		}
		if (isShowNextReply) {
			realProcessMessageReceived0(message);
		}else{
			globalConversation.ShowMessage("", "「image」"); 
		}
		isShowNextReply = true;
	} else if (message[KEY_COMMAND] == COMMAND_P4) {
		var data = message[KEY_DATA];
		var svc = dataUtils.parse(data)['SCMD'];
		var scmd = "";
		if (svc != null)
			scmd = "?SCMD=" + svc;
		var displayText = "使用更丰富功能请点击这里";
		if (svcMap[svc] != null) {
			displayText = "使用“" + svcMap[svc].name + "”完整功能，请点这里"
			// implement bubble feature
			addSvcBubble(svcMap[svc])
		}
		if (newWindow) {
			var linkText = "<a onclick=\"return window.parent.SendIM('"
					+ (svc ? svc : "?")
					+ "');\" href='http://www.xiaoi.com/newentrance/2" + scmd
					+ "' target='_blank'>" + displayText + "</a>";
		} else {
			var linkText = "<a onclick=\"window.top.flashbot_showEntrance('http://www.xiaoi.com/newentrance/2/index.html"
					+ scmd
					+ "');\" href='javascript:void(0)'>"
					+ displayText
					+ "</a>";
		}
		var linkHtml = "<span id=\"__dn\" class=\"messageText\" >"
				+ FormatString(L_IDS_FORMAT_ACTION, linkText) + "</span>";
		if (scmd != "" && scmd != "?SCMD=?") {
			var history = UIRegistry.conversation.GetTranscriptDiv().innerHTML;
			history = history.substring(0, history.lastIndexOf("__dn"));
			var i = history.lastIndexOf("<");
			if (i > 0) {
				history = history.substring(0, history.lastIndexOf("<"));
				UIRegistry.conversation.GetTranscriptDiv().innerHTML = history;
			}
		}
		UIRegistry.conversation.InsertMessageHtml(linkHtml);

		if (scmd != "" && scmd != "?SCMD=?") {
//			isShowNextReply = false;
//			sendMessageImpl(UIRegistry.conversation.GetDisplayName(), "q",
//					UIRegistry.conversation.GetFormat());
		}

	} else {
		realProcessMessageReceived0(message);
	}

}

function showFlash(ur, w, h) {
	str = ('<object id="xiaoiFlash" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="'
			+ w + '" height="' + h + '"> ');
	str += ('<param name="movie" value="' + ur + '">');
	str += ('<param name="quality" value="high"> ');
	str += ('<param name="wmode" value="transparent"> ');
	str += ('<param name="menu" value="false"> ');
	str += ('<embed name="xiaoiFlash" src="'
			+ ur
			+ '" wmode="transparent" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="'
			+ w + '" height="' + h + '"></embed> ');
	str += ('</object> ');
	document.write(str);
}
var newWindow = true;

function injactParent() {
	try {
		var mainDoc = window.top.document;
		var mainWnd = window.top;
		if (mainWnd == window)
			return;
		var floaterTop = mainDoc.getElementById('floaterTop');
		if (!floaterTop) {
			var el = mainDoc.createElement("span");
			el.innerHTML = '<table id="floaterTop" style="position:absolute;left:0px; top:0px; width:100%; height:100%; display: none;" border=0><tr id="frameEntranceTr"><td align="center" style="color:#0d33bb;">'
					+ '</td></tr><tr><td></td></tr></table>';
			mainDoc.body.appendChild(el.firstChild);
			var el = mainDoc.createElement("span");
			el.innerHTML = '<iframe id="entranceFrame"  border="0" frameborder="no" framespacing="0" style="frame-border:no;border-width:0;position:absolute;left:0px; top:0px;z-index=1000;display: none;" src="about:blank" width="825px"	height="522px" scrolling="hidden"	allowTransparency="true"></iframe>';
			mainDoc.body.appendChild(el.firstChild);
			if (!mainWnd.$) {
				mainWnd
						.eval("window.$ = function(id){	return document.getElementById(id);}");
			}
			if (!mainWnd.IsIE) {
				mainWnd
						.eval("window.IsIE = function(version){var rc = false;if (navigator.userAgent.indexOf('MSIE') >- 1){if (navigator.userAgent.indexOf('Opera') == ( - 1)){if (null != version){if (navigator.userAgent.indexOf(version) >- 1){rc = true;}}else{rc = true;}}}return rc;}");
			}
			if (!mainWnd.flashbot_showEntrance) {
				mainWnd
						.eval("window.flashbot_showEntrance = function(url){"
								+ "$('floaterTop').style.height=document.body.scrollHeight+'px';"
								+ "$('floaterTop').style.width=document.body.scrollWidth+'px';"
								+ "$('frameEntranceTr').style.height=document.body.clientHeight+'px';"
								+ "$('floaterTop').style.display = 'block';"
								+ "if (IsIE()) {"
								+ "$('floaterTop').style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\"http://www.xiaoi.com/newflashbot/images/alpha.png\", sizingMethod=\"scale\")';}"
								+ "else {$('floaterTop').style.background = 'url(http://www.xiaoi.com/newflashbot/images/alpha.png)';}"
								+ "$('entranceFrame').style.top=Math.floor((document.body.clientHeight-$('entranceFrame').height)/2)+document.body.scrollTop+'px';"
								+ "$('entranceFrame').style.left=Math.floor((document.body.clientWidth-$('entranceFrame').width)/2)+'px';"
								+ "$('entranceFrame').style.display='block';"
								+ "window.oldoverflowstyle = document.body.style.overflow;"
								+ "document.body.style.overflow = 'hidden';"
								+ "$('entranceFrame').src = url;}");
			}
			if (!mainWnd.flashBotWnd) {
				mainWnd.flashBotWnd = window;
			}
			if (!mainWnd.HideEntranceFrame) {
				mainWnd
						.eval("window.HideEntranceFrame = function(){"
								+ "document.body.style.overflow = oldoverflowstyle;"
								+ "$('floaterTop').style.display='none';"
								+ "$('entranceFrame').style.display='none';"
								+ "$('entranceFrame').src='about:blank';"
								+ "setTimeout('try{flashBotWnd.resumeConversation();}catch(e){alert(e)}', 100);}")
			};
		}
		newWindow = false;
	} catch (e) {
		alert(e + e.description);
	}
}

function OnLoad() {
	if (window.Event) {
		window.captureEvents(Event.KEYPRESS);
	}

	UIRegistry.inputBox = document.getElementById("inputBox");
	UIRegistry.sendButton = document.getElementById("sendButton");
	UIRegistry.xiaoiFlash = document['xiaoiFlash']
			? document['xiaoiFlash']
			: document.getElementById("xiaoiFlash");

	var p = window;
	var p1 = null;
	while (p != p1) {
		try {
			p.document.onkeydown = OnDocumentKeyDown;
		} catch (e) {
		}
		p1 = p;
		p = p.parent;
	}

	UIRegistry.conversation.AddEventListener(handleConversationEvent);

//	UIRegistry.inputBox.focus();
	UIRegistry.sendButton.focus();
	
	window.setTimeout("LazyLoad()", 100);
//	injactParent();
	showShortCut();
	EnableSendButton(true)
}

function showShortCut() {
	var els = document.getElementsByName('shortcut');
	for (var index = 0; index < els.length; index++) {
		els[index].style.visibility = "visible";
	}
}

function LazyLoad() {

	var lazyimgs = document.getElementsByName("lazyimg");
	for (var i = 0; i < lazyimgs.length; i++)
		lazyimgs[i].src = lazyimgs[i].getAttribute("source");

}

function handleConversationEvent(type, params) {

	if (type == EVENT_CONVERSATION_OPENED) {
		$('floaterTop').style.display = "none";
	} else if (type == EVENT_ERROR_SESSION_POLYGAMY) {
		ShowError("已在另一个窗口登录,点击重新开始！", true);
	} else if (type == EVENT_ERROR_INTERNAL
			|| type == EVENT_ERROR_SP_UNAVAILABLE) {
		ShowError("服务暂不可用，请稍后刷新重试！");
	} else if (type == EVENT_ERROR_SESSION_TIMEOUT) {
		ShowError("会话已过期，点击重新开始！", true);
	} else if (type == EVENT_ERROR_CONNECTION_ERROR) {
		ShowError("网络连接错误，请稍后刷新重试！");
	}

}

function resumeConversation() {
	$('floaterTop').style.display = "none";
	$('floaterTop').haserror = false;
	UIRegistry.conversation.Enable();
	UIRegistry.sendButton.focus();
}

function ShowError(err, clickable) {
	try {
		UIRegistry.conversation.CloseActivityWindow();
	} catch (e) {
	}
	$('floaterTop').haserror = true;
	$('floaterTop').style.display = "";
	if (clickable) {
		$('floaterTop').onclick = resumeConversation;
	}
	if (IsIE()) {
		$('floaterTop').style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=./image/alpha.png,sizingmethod=scale)";
	} else {
		$('floaterTop').style.background = "url(./image/alpha.png)";
	}
	$('errorBox').innerHTML = err;
}

function IsIE(version) {
	var rc = false;
	if (navigator.userAgent.indexOf('MSIE') > -1) {
		if (navigator.userAgent.indexOf("Opera") == (-1)) {
			if (null != version) {
				if (navigator.userAgent.indexOf(version) > -1) {
					rc = true;
				}
			} else {
				rc = true;
			}
		}
	}
	return rc;
}

function IsVisible(obj) {
	;
	var result = false;
	if (obj != null && obj.style != null) {
		var d = obj.style.display;
		result = (d != null && d != "none");
	}
	return result;
}
function SubmitMessage(message) {
	if (message)
		UIRegistry.inputBox.value = message;
	else{
		message = UIRegistry.inputBox.value;
	}
	if (message.length > 0) {
		if (message.substring(message.length - 1) == "\n") {
			message = message.substring(0, message.length - 1);
		}
		if (message.substring(message.length - 1) == "\r") {
			message = message.substring(0, message.length - 1);
		}
		if (message.length > 0)
			UIRegistry.conversation.SendMessage(message);
	}
	UIRegistry.inputBox.value = "";
	if (!__sendButtonDisabled) {
		EnableSendButton(false);
	}
}

var __sendButtonDisabled = true;
var enabledSendImage = new Image;
enabledSendImage.src = "./images/btn_send_enabled.gif";
var disabledSendImage = new Image;
disabledSendImage.src = "./images/btn_send_disabled.gif";

function EnableSendButton(b) {
	try {
		__sendButtonDisabled = !b;
		var sendButton = $('sendButton');
		if (b) {
			sendButton.obgp = sendButton.style.backgroundPosition;
//			sendButton.style.backgroundPosition = "right bottom ";
			sendButton.style.backgroundPosition = "79px bottom";
			sendButton.style.cursor = "pointer";
			sendButton.onclick = OnSendButtonClicked;

		} else {
			sendButton.style.backgroundPosition = sendButton.obgp;
			sendButton.style.cursor = "default";
			sendButton.onclick = function() {
			}
		}
	} catch (e) {
	}

}

function OnComposeKeyUp(e) {
	;;
	var textControl = UIRegistry.inputBox;
	var sendButton = UIRegistry.sendButton;
	try {
		if (textControl != null && sendButton != null) {

			var msg = textControl.value;
			if (msg.length > 0 && msg != textControl.title) {
				if (__sendButtonDisabled) {
					EnableSendButton(true);
				}
				if (msg.length > 400) {
					textControl.value = msg.substring(0, 400);
				}
			} else {
				if (!__sendButtonDisabled) {
					EnableSendButton(false);
				}
			}
		}
	} catch (exception) {
		alert(exception.description);
	}
}

function OnComposePaste(e) {
	var textControl = UIRegistry.inputBox;
	var sendButton = UIRegistry.sendButton;
	try {
		if (textControl != null && sendButton != null) {
			if (__sendButtonDisabled) {
				EnableSendButton(true);
			}
		}
	} catch (exception) {
		;
	}
}

function OnComposeKeyPressed(e) {
	try {
		if (IsIE()) {
			if (13 == event.keyCode) {
				if (event.shiftKey) {
				} else {
					SubmitMessage();
					// window.setTimeout('SubmitMessage();',10);
					return false;
				}
			}
		} else if ((null != e) && (null != e.which)) {
			if (13 == e.which) {
				if (e.shiftKey) {
				} else {
					SubmitMessage();
					// window.setTimeout('SubmitMessage();',10);
					return false;
				}
			}
		}
	} catch (e) {
		alert(e.description);
	}

	return true;
}

function OnDocumentKeyDown(e) {

	if (IsIE()) {
		var p = window;
		var p1 = null;
		while (p != p1) {
			try {
				if (p.event.altKey) {
					if (67 == p.event.keyCode) {
						globalConversation.AcceptActivity();
					} else if (68 == p.event.keyCode) {
						globalConversation.RejectActivity();
					}
				} else {
					if (27 == p.event.keyCode) {
						return false;
					}
				}
			} catch (e) {
			}
			p1 = p;
			p = p.parent;
		}
	} else {
		if (e.altKey) {
			if (67 == e.which) {
				globalConversation.AcceptActivity();
			} else if (68 == e.which) {
				globalConversation.RejectActivity();
			}
		} else {
			if (27 == e.which) {
				return false;
			}
		}
	}
}

function OnSendButtonClicked() {
	SubmitMessage();
	UIRegistry.inputBox.focus();
	return false;
}

// === flashbot extension ===

/**
 * fly object util method just to simplify common operations
 */
var fly = function(el) {
	return new flyobject(el);
}
var flyobject = function(el) {
	this.el = $(el);
}
String.prototype.trim = function() {
	var re = /^\s+|\s+$/g;
	return function() {
		return this.replace(re, "");
	};
}();
flyobject.prototype = {
	el : null,
	getStyle : function(st) {
		return this.el.style[st];
	},
	setStyle : function(st, val) {
		if (val != null) {
			this.el.style[st] = val;
		} else {
			var styles = st.split(';');
			if (styles && styles.length > 0) {
				for (var i = 0; i < styles.length; i++) {
					if (!styles[i].trim()) continue;
					var s = styles[i].split(":");
					try{
						this.setStyle(s[0].trim(), s[1].trim());
					}catch(e){
						alert('set style fail:'+styles[i]);
					}
				}
			}
		}
	},
	show : function(dvalue) {
		this.setStyle('display', dvalue==null?'block':dvalue);
	},
	hide : function() {
		this.setStyle('display', 'none');
	},
	isHide : function() {
		return this.getStyle('display') == 'none';
	},
	click : function(fn) {
		return this.el.onclick = wrapOnclick(fn);
	},
	html : function(html) {
		if (html != null)
			this.el.innerHTML = html;
		else
			return this.el.innerHTML;
	}
};
function showElm(elToShow, elToHide) {
	if (elToHide)
		fly(elToHide).hide();
	fly(elToShow).show();
}

function insertMyChat(html) {
	$('myChat').innerHTML = html;
}
function limitMyChat(html) {
	var str = '';
	var count = 0;
	var maxLen = 42;
	for (var i = 0; i < html.length && count < maxLen; i++) {
		str += html.charAt(i);
		count++;
		if (html.charCodeAt(i) > 127)
			count++;
	}
	return str + (count >= maxLen ? '...' : '')
}
function insertRobotChat(html, append) {
	if (append === false)
		$('robotChat').innerHTML = html;
	else
		$('robotChat').innerHTML += html;
}

function interceptFn(scopeObj, realFn, interceptFn, aopType) {
	var f = scopeObj[realFn];
	aopType = (aopType ? aopType : 'before');
	scopeObj[realFn] = function() {
		var self = this;
		var args = arguments;
		if (aopType == 'before') {
			var r = interceptFn.apply(self, arguments);

			if (r === false || r != null) {
				return (r === false ? r : r.retValue);
			}
			if (f)
				return f.apply(self, arguments);
		} else {
			var _args = new Array(arguments.length);
			for (var i = 0; i < arguments.length; i++) {
				_args[i] = arguments[i];
			}
			var wrap = function() {
				return f.apply(self, args);
			}
			_args.push(wrap);
			return interceptFn.apply(this, _args);// around invocation
		}

	}
}
var whoareyou = false;
interceptFn(globalConversation, 'ShowMessage', function(displayname, msgText,
		format, emoticons) {
	//alert(msgText);
	if (msgText != null && msgText.length > 0) {
		if (this.GetDisplayName() == displayname) {//user's chat message
			msgText = limitMyChat(msgText);
		}else{
			msgText = msgText.replace(/[\r\n]*[^\r\n]*弹出页面[^\r\n]*$/im,'').replace(/[\r\n]*[^\r\n]*历史进行时[^\r\n]*$/im,'');
		}
		var msgHtml = EntityReplace(msgText);
		if (whoareyou){
			msgHtml = "「image」";
			whoareyou = false;
		}
		while((r=displayTas.regExpPattern.exec(msgHtml))!=null){
			tag = r[0];
			str = r[1];
			if (displayTas[str]){
				msgHtml = msgHtml.replace(tag,displayTas[str]);
			}
		}
	   if (typeof(UBBReplace) == "function")
		  msgHtml = UBBReplace(msgHtml);

		msgHtml = EmoticonReplace(LinkReplace(msgHtml));

		if (emoticons != null && emoticons.Size() > 0)
			msgHtml = emoticons.Replace(msgHtml);

		msgHtml = NewlineReplace(msgHtml);

		if (format != null) {
			msgHtml = format.ApplyFormat(msgHtml);
		}
		msgHtml = "<div style=\"padding-left:15px\">" + msgHtml + "</div>";

		if (this.GetDisplayName() == displayname) {
			insertMyChat(msgHtml);
		} else {
			insertRobotChat(msgHtml);
			setTimeout(function() {
				$('robotChat').scrollTop += 10000;
			}, 20);
		}

		var nameHtml = "<span id=\"__dn\" class=\"messageText\" >"
				+ EmoticonReplace(EntityReplace(FormatString(L_IDS_TEXT_IM,
						displayname))) + "</span>";

		this
				.InsertMessageHtml(FormatString(L_IDS_FORMAT_IM, nameHtml,
						msgHtml));
						
		if (this.GetDisplayName() == displayname) {//user's chat message
			if (msgText=='你是谁'){
				whoareyou = true;
			}
		}
		return false;
	}

})

interceptFn(window, 'SubmitMessage', function(message) {
	var scroller = fly('example_chat_scroller');
	if (!scroller.isHide()){
		debug(contentScroller.itemPos)
		debug(examples_chat[contentScroller.itemPos])
		UIRegistry.inputBox.value = message = examples_chat[contentScroller.itemPos].c[0].t;
	}
	if (!message
			&& (!UIRegistry.inputBox.value || !UIRegistry.inputBox.value
					.replace(/^\s+|\s+$/, '')))
		return false;
	hideIfVisible('chat_history')
	message = message || UIRegistry.inputBox.value;
	addRecentChat(message);
	insertRobotChat('', false);
	csMgr.addScore(1);
	hideContentScroller();
});
var wrapOnclick = function(fn) {
	return function() {
		fn.apply(this, arguments);
		return false;
	};
};
var hideIfVisible = function(el) {
	if (!fly(el).isHide()) {
		fly(el).hide();
	}
}
var _debugEnabled = false;
function ffDebug() {
	if (_debugEnabled && !IsIE()) {
		debugger
	}
}

//>>> flash call >>>
function levelOver(){
	csMgr.levelOver();
}
//<<< flash call end <<<

function ChatScoreMgr() {
}
ChatScoreMgr.prototype = {
	level : 1,
	score : 0,
	getFlash : function() {
		return UIRegistry.xiaoiFlash;
	},
	getLevelConfig : function() {
		var self = this;
		var cfgs = {
			1 : {
				frame : {
					5 : {
						action : function() {
							self.getFlash().playMc(['pangxie_mc'], 'none',
									null, false);
						}
					},
					40 : {
						action : function() {
							self.getFlash().playMc(['fish2_mc', 'fish1_mc'],
									'none', null, false);
						}
					},
					50 : {
						action : function() {
							self.getFlash().gotoPeriod(2);
						}
					},
					70 : {
						action : function() {
							self.getFlash().swim();
						}
					},
					90 : {
						action : function() {
							self.getFlash().swim();
						}
					},
					100 : {
						action : function(){
							self.getFlash().gotoPeriod(3);
						}
					}
				},
				maxScore : 100
			}
		};
		if (cfgs[this.level]) return cfgs[this.level]; 
		return cfgs[1];
	},
	KEY_SCORE : '_xctsc_sc',
	KEY_LEVEL : '_xctsc_lvl',
	init : function() {
		var level = CookieUtils.getCookie(this.KEY_LEVEL);
		if (level)
			this.level = parseInt(level);
		var score = CookieUtils.getCookie(this.KEY_SCORE);
		if (score)
			this.score = parseInt(score);
	},
	initFlash:function(){
		if (this.score >= 50){
			this.getFlash().gotoPeriod(2);
		}
		this.updateUI();
	},
	updateUI : function() {
		var max = this.getLevelConfig().maxScore;
		var p = parseInt(this.score * 100 / max);
		fly('cs_progress').setStyle('width',p+'%');
		fly('cs_count').html(this.score + '/' + max);
		fly('cs_level').html('Level ' + this.level);
		this.adjustWater();
	},
	save : function(key, value) {
		CookieUtils.setCookie(key, value, 365 * 24 * 3600);
	},
	addScore : function(amount) {
		if (!amount)
			amount = 1;
		this.score += amount;
		var cfg = this.getLevelConfig();
		if (cfg.frame) {
			var frame = cfg.frame[this.score];
			if (frame && frame.action) {
				frame.action();
			}
		}
		if (this.score >= cfg.maxScore) {
			this.level++;
			this.score = 0;
			// this.save(this.KEY_LEVEL, this.level);
		}
		// this.save(this.KEY_SCORE, this.score);
		this.updateUI();
	},
	adjustWater:function(){
		this.getFlash().waterUpDown(-2.1 * this.score);
	},
	levelOver:function(){
		this.getFlash().gotoPeriod(1);
		this.updateUI();
	},
	v : 1
}
function doBlur(el) {
	el.onfocus = function() {
		this.blur()
	};
}
interceptFn(window, '$', function(el, invocFn) {
	if (typeof el != 'string') {
		return {
			retValue : el
		};
	}
		// if (typeof el != 'string') {
		// return el;
		// }
		// return invocFn();
	});
function fillTemplate(ctx, tpl) {
	var ret = tpl
	for (var key in ctx) {
		ret = ret.replace(new RegExp('%' + key, 'ig'), ctx[key])
	}
	return ret;
}
function createEl(html, appendTo) {
	var d = window.__creatediv;
	if (!d) {
		d = window.__creatediv = document.createElement('div');
		d.style.display = 'none'
		document.body.appendChild(d);
	}
	d.innerHTML = html;
	for (var i = 0; i < d.childNodes.length; i++) {
		if (d.childNodes[i].tagName) {
			var n = d.childNodes[i];
			var zi = n.style.zIndex;
			if (appendTo)
				appendTo.appendChild(n);
			if (zi)
				n.style.zIndex = zi;
			return n;
		}
	}
}
// === recent chat ===
var rc_records = [];
function applyChatRecordStyle(el, clicked) {
	if (clicked) {
		el.onclick = function() {
		};
		el.className = 'tabl2';
	} else {
		el.onclick = function() {
			recentChatClick(this);
		}
		el.className = 'tabl';
	}
}
function initChatRecord(el, title, count) {
	el.title = title;
	el.a.innerHTML = count;
	applyChatRecordStyle(el, false)
}
var addRecentChatTimer;
function RCAnim(container) {
	this.container = $(container);
}
RCAnim.getInstance = function() {
	if (!window.__rcAnim) {
		window.__rcAnim = new RCAnim($('recentChatPanel'));
	}
	return window.__rcAnim || new RCAnim();
}
RCAnim.prototype = {
	xOffset : 20,
	yOffset : 10,
	timer : null,
	interval : 10,
	xStep : 2,
	yStep : 1,
	xDirect : 0,// direction from left to right
	startPlaceElm : null,

	reset : function() {
		this.xDirect = 0;
		if (this.timer) {
			this.timer = null;
			clearInterval(this.timer);
		}
		this.el = null;
	},
	startAnim : function(el, startPlaceElm) {
		this.reset();

		this.el = $(el);
		this.startPlaceElm = $(startPlaceElm);

		var self = this;

		fly(this.el).setStyle('position:absolute;top:0;left:0');
		fly(this.startPlaceElm).setStyle('position:relative');

		this.startPlaceElm.appendChild(this.el);

		this.timer = setInterval(function() {
			self.doAnim()
		}, self.interval);
	},
	doAnim : function() {
		if (!this.el)
			return;

		var el = fly(this.el);
		var x = parseInt(el.getStyle('left'));
		var y = parseInt(el.getStyle('top'));
		var xStep = this.xStep;
		var yStep = this.yStep;
		// debug('x=%s;y=%s;x+xStep=%s', x, y, x + xStep);
		if (this.xDirect || x > this.xOffset) {
			xStep = -xStep;
			if (!this.xDirect)
				this.xDirect = 1;
			if (x <= 0) {
				this.finishAnim();
				return;
			}
		}
		el.setStyle('left', x + xStep + 'px')
		el.setStyle('top', y + yStep + 'px')
		var now = new Date();
		while (new Date().getTime() - now.getTime() < 5);
	},
	finishAnim : function() {
		ffDebug()
		if (this.el) {
			var el = fly(this.el);
			el.setStyle('position:static;top:0px;left:0px');
			this.container.appendChild(el.el);
		}
		this.reset();
	}
}
function ShiningAnim() {
}
ShiningAnim.getInstance = function() {
	if (!window.__shiningAnim) {
		return window.__shiningAnim = new ShiningAnim();
	}
	return window.__shiningAnim || new ShiningAnim();
}
ShiningAnim.prototype = {
	adct_count : 0,
	el : null,
	timer : null,
	reset : function() {
		this.adct_count = 0;
		if (this.el) {
			fly(this.el.a).setStyle('backgroundPosition', '0px');
			this.el = null;
		}
		if (this.timer) {
			clearInterval(this.timer);
			this.timer = null;
		}
	},
	startAnim : function(el) {
		var self = this;
		this.reset();
		this.el = el;
		this.timer = setInterval(function() {
			self.doAnim()
		}, 200);
	},
	doAnim : function() {
		if (!this.el)
			return;

		if (++this.adct_count > 10) {
			this.finishAnim();
			return;
		}
		if (this.adct_count % 2 == 1)
			fly(this.el.a).setStyle('backgroundPosition', '-23px');
		else
			fly(this.el.a).setStyle('backgroundPosition', '0px');
	},
	finishAnim : function() {
		this.reset();
	}
}
function addRecentChat(text) {
	if (window.submitFromRecent) {
		window.submitFromRecent = false;
		return;
	}
	var elm;
	var rcAnim = RCAnim.getInstance();
	rcAnim.finishAnim();
	if (rc_records.length < 10) {
		elm = createEl('<div></div>', $('recentChatPanel'));
		elm.a = createEl('<a href="#" onclick="return false;"></a>', elm);
		doBlur(elm.a);
		rc_records.push(elm);
		initChatRecord(elm, text, rc_records.length);
		if (rc_records.length > 1) {
			ffDebug();
			rcAnim.startAnim(elm, rc_records[rc_records.length - 2])
			return;
		}
	} else {
		elm = rc_records.shift();
		rc_records.push(elm);
		initChatRecord(elm, text, 1);
		var pn = elm.parentNode;
		pn.removeChild(elm);
		pn.appendChild(elm);
		for (var i = 0; i < rc_records.length; i++) {
			var cur = rc_records[i];
			cur.a.innerHTML = i + 1;
		}
	}
	ShiningAnim.getInstance().finishAnim();
	ShiningAnim.getInstance().startAnim(elm);
}
function recentChatClick(el) {
	var cur;
	for (var i = 0; i < rc_records.length; i++) {
		cur = rc_records[i];
		if (el != cur && cur.className == 'tabl2')
			applyChatRecordStyle(cur);
	}
	applyChatRecordStyle(el, true);
	window.submitFromRecent = true;
	SubmitMessage(el.title);
}
function showExampleChatPanel(html) {
	fly("exampleChatPanel").html(html);
	fly("exampleChatPanel").show();
}

// === examples ===
var examples_svc = [{
	n : '股票',
	c : [{
		t : '999001'
	}, {
		t : '上证指数涨了吗'
	}]
}, {
	n : '基金',
	c : [{
		t : 'fund:000001'
	}, {
		t : '帮我查一下华夏成长'
	}]
}, {
	n : '天气',
	c : [{
		t : 'tq:北京'
	}, {
		t : '上海明天下雨吗'
	}]
}, {
	n : '翻译',
	c : [{
		t : 'fy:爱'
	}, {
		t : 'love是什么意思'
	}]
}, {
	n : '地图',
	c : [{
		t : '上海地图'
	}, {
		t : '从中山公园到人民广场'
	}]
}, {
	n : '解梦',
	c : [{
		t : 'dream：虎'
	}, {
		t : '梦见猪是什么意思'
	}]
}, {
	n : '姓名预测',
	c : [{
		t : 'xmyc'
	}, {
		t : '姓名预测'
	}]
}, {
	n : '手机预测',
	c : [{
		t : 'sjyc'
	}, {
		t : '手机预测'
	}]
}];

function genCmdExample(cfg,itemCreateCallback,itemOnClick) {
	var ret = '';
	itemOnClick = itemOnClick ? itemOnClick : 'example_onclick';
	for (var i = 0; i < cfg.length; i++) {
		var row = cfg[i];
		if (row.n)
			ret += '&lt;' + row.n + '&gt';
		var c = row.c;
		var tmp = '';
		for (var j = 0; j < c.length; j++) {
			tmp += '<span class="exampleItem" onclick='+itemOnClick+'(this)>'
					+ c[j].t + '</span>';
			if (j == c.length - 1)
				tmp += '<br>';
			else
				tmp += '，'
		}
		ret += tmp;
		if (itemCreateCallback) itemCreateCallback(row,tmp);
	}
	return ret;
}
function example_onclick(el) {
	SubmitMessage(el.innerHTML)
}
function example_onclick_scroller(el) {
	hideContentScroller();
	UIRegistry.inputBox.focus();
}
function hideContentScroller(){
	if (fly('example_chat_scroller').isHide()) return;
	window.contentScroller.clearActionTimer();
	fly('example_chat_scroller').hide();
}
var left = true;
var bubbledSvc = {};
var lyRegion = new Array(8);// 0:count
var rRegion = new Array(8);// 0:count
function rndInt(baseNum) {
	return parseInt(Math.random() * baseNum);
}
function debug() {
	try{
		if (!IsIE()){
	//		loadFirebugConsole();
//			console.debug.apply(this, arguments);
		}
	}catch(e){}
}
function HideEntranceFrame(){
	fly('xiaoi_inner_table').hide();
	fly('xiaoi_inner_table_mask').hide();
	$('xiaoi_inner_table').src = '';
	fly('mainTable').setStyle('visibility:visible');
	if ($('floaterTop').haserror){
		insertRobotChat('', false);
		resumeConversation();
	}
}
function addSvcBubble(svcConfig) {
	var sc = {};
	for (var key in svcConfig) {
		sc[key] = svcConfig[key];
	}
	svcConfig = sc;
	if (bubbledSvc[svcConfig.id] > 0)
		return;
	if (bubbledSvc[svcConfig.id] == null)
		bubbledSvc[svcConfig.id] = 1;
	else
		bubbledSvc[svcConfig.id]++;

	if (bubbledSvc[svcConfig.id] > 1) {
		return;
	}
	var target = 'rightPanel';
	var yRegion = rRegion;
	var len = yRegion.length;
	if (left) {
		yRegion = lyRegion;
		left = false;
		target = 'leftPanel';
	} else
		left = true;

	var t = rndInt(len * 10);
	var l = rndInt(50) + 20;
	var region = parseInt(t / 10);
	// debug('var region = t/10; %d', region);
	if (yRegion[region]) {
		var pos = rndInt(len);
		// debug('start finding at %d', pos);
		for (var i = 0; i < len; i++, pos = (pos + 1) % len) {
			// debug('::finding at %d=%d', pos, yRegion[pos]);
			if (!yRegion[pos]) {
				yRegion[pos] = 1;
				// debug('::found at %d', pos);
				break;
			}
		}
		// debug('finally we find t=%d', pos);
		yRegion[pos]++;
		t = pos * 10 + rndInt(100 / len);
	} else {
		yRegion[region] = 1;
	}

	svcConfig.top = t + '%';
	svcConfig.left = l + '%';
	var html = fillTemplate(svcConfig, $('tpl_bubble').value);
	var el = createEl(html, $(target));
	el.onclick = function() {
		el.firstChild.innerHTML = '';
		fly(el.firstChild)
				.setStyle('backgroundImage:url(image/paopao-disp.gif)');
		setTimeout(function() {
			fly(el.firstChild)
				.setStyle('backgroundImage:none');
			el.parentNode.removeChild(el);
			bubbledSvc[svcConfig.id] = 0;
//			SubmitMessage(svcConfig.id);
			if (!svcConfig.url){
				if (svcConfig.cmd){
					svcConfig.url = svcConfig.cmd[0];
				}else{
					svcConfig.url = svcConfig.id;
				}
			}
			showInEntrance(svcConfig.url);
		}, 500);
	}

	if (IsIE()) {
		var img = el.firstChild.firstChild;
		var imgID = (img.id) ? "id='" + img.id + "' " : ""
		var imgClass = (img.className) ? "class='" + img.className + "' " : ""
		var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='"
				+ img.alt + "' "
		var imgStyle = "display:inline-block;" + img.style.cssText
		if (img.align == "left")
			imgStyle = "float:left;" + imgStyle
		if (img.align == "right")
			imgStyle = "float:right;" + imgStyle
		if (img.parentElement.href)
			imgStyle = "cursor:hand;" + imgStyle
		var strNewHTML = "<font " + imgID + imgClass + imgTitle + " style=\""
				+ "width:" + img.width + "px; height:" + img.height + "px;"
				+ imgStyle + ";"
				+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
				+ "(src=\'" + img.src + "\', sizingMethod='');\"></font>"
		img.outerHTML = strNewHTML
	}

	new SwingAnim(el.firstChild).startAnim();
}

function copyToClipBoard(content, pmt) {
	// try {
	// window.clipboardData.setData("Text", content);
	// alert(pmt);
	// return;
	// } catch (e) {
	// }
	try {
		var flashcopier = 'flashcopier';
		if (!document.getElementById(flashcopier)) {
			var divholder = document.createElement('div');
			divholder.id = flashcopier;
			document.body.appendChild(divholder);
		}
		document.getElementById(flashcopier).innerHTML = '';
		var divinfo = '<embed src="http://www.xiaoi.com/widget/common/2/flash/_clipboard.swf" FlashVars="clipboard='
				+ encodeURIComponent(content)
				+ '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		document.getElementById(flashcopier).innerHTML = divinfo;
		if (pmt)
			alert(pmt);
	} catch (e) {
	}
}
var svcConfigList = [{
	id : 'stock',
	name : '股票',
	cmd : ['41@m']
}, {
	id : 'wzfw',
	name : '百宝箱',
	cmd : ['baikemenu','baike']
}, {
	id : 'kaiyun',
	name : '开运',
	cmd : ['M@40']
}, {
	id : 'mdb',
	name : '影视库',
	cmd : ['?@33']
}, {
	id : 'game',
	name : '游戏',
	cmd : ['flash']
}, {
	id : 'map',
	name : '地图'
}, {
	id : 'tv',
	name : '收视'
}, {
	id : 'tq',
	name : '天气'
}, {
	id : 'xdf',
	name : '新东方'
},
 {id:'grzx',name: '个人中心',cmd:['usercenter']},
		{
			id : 'chat',
			name : '聊天室',
			cmd : ['聊天室']
		}, {
			id : 'travian',
			name : '部落战争'
		}, {
			id : 'dy',
			name : '订阅中心'
		}, {
			id : 'video',
			name : '视频',
			cmd : ['YoukuPagingService@56']
		}, {
			id : 'dden',
			name : '天天英语'
		}, {
			id : 'house',
			name : '搜房'
		}, {
			id : 'zazhi',
			name : '杂志'
		}, {
			id : 'fy',
			name : '翻译',
			cmd : ['trans']
		}, {
			id : 'music',
			name : '音乐',
			cmd : ['play-a8-song']
		},{
			id : 'ayzb',
			name : '网络影视',
			cmd : ['77@m']
		},{
			id : 'zhaopin',
			name : '招聘',
			cmd : ['zhaopin']
		},{
			id : 'xba',
			name : '篮球经理',
			cmd : ['xba']
		},{
			id : 'sg',
			name : '武林三国',
			cmd : ['sg']
		},{
			id : 'teachi',
			name : '教小i说话'
		}
		,{
			id : 'sex',
			name : '性爱宝典'
		}
		,{
			id : 'girl',
			name : '美女图库'
		},{
			id : 'handsome',
			name : '帅哥型男'
		},{
			id : 'yx',
			name : '武林英雄'
		},{
			id : 'zs',
			name : '战神世界'
		},{
			id : 'farm',
			name : '牧场物语',
			cmd : ['mm']
		},{
			id : 'sgfy',
			name : '三国风云',
			cmd : ['sf']
		},{
			id : '3g',
			name : '战三国'
		},{
			id : 'blcx',
			name : '兵临城下',
			cmd:['bl']
		},{
			id : 'hslj',
			name : '华山论剑',
			cmd:['hs']
		}
		];
var svcMap = {}
function initSvcConfig() {
	for (var i = 0; i < svcConfigList.length; i++) {
		var cfg = svcConfigList[i];
		var cmd = cfg.cmd;
		if (!cfg.cmd){
			cmd = cfg.cmd = [];
			cmd.push(cfg.id);
		}
		for (var j = 0; j < cmd.length; j++) {
			svcMap[cmd[j]] = cfg;
		}
	}
}

function SwingAnim(el) {
	this.el = $(el);
	this.adjustStep();
}
SwingAnim.prototype = {
	xOffset : 10,
	XOffsetStep : 2,
	timer : null,
	interval : 1,
	xStep : 1,
	xDirect : 0,// direction from left to right

	reset : function() {
		this.xDirect = 0;
		if (this.timer)
			clearInterval(this.timer);
	},
	startAnim : function() {
		this.reset();

		var self = this;

		this.timer = setInterval(function() {
			self.doAnim()
		}, self.interval);
	},
	adjustStep : function() {
		var adjustOffset;
		// adjustOffset = parseInt(this.xOffset / 2);
		adjustOffset = 1;
		if (adjustOffset < this.XOffsetStep)
			adjustOffset = this.XOffsetStep;

		this.xStep = this.xStep > 0 ? adjustOffset : -adjustOffset;

	},
	doAnim : function() {
		if (!this.el)
			return;

		var el = fly(this.el);
		var x = parseInt(el.getStyle('left'));
		var xStep = this.xStep
		// debug('xOffset=%s; xStep=%s', this.xOffset, this.xStep)
		if (this.xOffset > 0 && this.xStep != 0 && Math.abs(x) > this.xOffset
				// && Math.abs(x + xStep
				// + (xStep > 0 ? this.XOffsetStep : -this.XOffsetStep)) >
				// this.xOffset
				&& Math.abs(x + xStep) > this.xOffset) {
			this.xOffset -= this.XOffsetStep;
			xStep = this.xStep = -this.xStep;
			this.adjustStep()
		} else if (this.xOffset <= 0) {
			this.finishAnim();
			return;
		}
		el.setStyle('left', x + xStep + 'px')
	},
	finishAnim : function() {
		if (this.el) {
			var el = fly(this.el);
			el.setStyle('position:static;top:0px;left:0px');
			this.reset();
		}
	}
}

var csMgr = new ChatScoreMgr();
interceptFn(window, 'OnLoad', function(invoc) {
	invoc();// process invocation

	ffDebug()
	var showchat = function() {
		showElm('example_chat', 'example_svc')
		showClickMask()
	};
	var showsvc = function() {
		showElm('example_svc', 'example_chat')
		showClickMask()
	};
	// patch class diaplay:none;
	fly('example_svc').hide();
	fly('example_chat').hide();
	// TODO: check why - if wrapped as inner function,the code assistent not
	// work
	var chatOnClick = function() {
		var fo = fly('example_chat');
		if (fo.isHide()) {
			showchat()
		} else {
			fly('example_chat').hide();
		}
	}
	fly('showExampleChatBtn').click(chatOnClick);
	fly('switchExampleChat').click(showsvc);
	fly('showExampleSvcBtn').click(showsvc);
	fly('switchExampleSvc').click(showchat);

	fly('showChatHistoryBtn').click(function() {
		fly('chat_history').show();
		showClickMask()
	});

	fly('chat_history').hide();
	fly('chat_history_closeBtn').click(function() {
		fly('chat_history').hide();
	});

	fly('copyBtn').click(function() {
		var content = $('chat_history_frame').contentWindow.document.body.innerHTML;
		content = content.replace(/<BR>|<\/DIV>/ig, '\r\n');
		content = content.replace(/<IMG title=([^\s>]+)[^>]+\/?>/ig, '$1');
		content = content.replace(/<[^>]+>/ig, '');
		content = content.replace(/&nbsp;/ig, ' ');
		content = content.replace(/&gt;/ig, '>');
		content = content.replace(/&lt;/ig, '<');
		copyToClipBoard(content + '马上访问 http://www.xiaoi.com 和全球最聪明的机器人聊天',
				'聊天记录复制成功！')
	});

	initSvcConfig();
	var pClick = function() {
		hideIfVisible('chat_history');
		hideIfVisible('example_svc');
		hideIfVisible('example_chat');
	}

	function doBatchBlur(tn) {
		var els = document.getElementsByTagName(tn);
		for (var i = 0; i < els.length; i++) {
			doBlur(els[i]);
		}
	}
	function showClickMask() {
		var mask = window.__clickMask;
		if (!mask) {
			mask = window.__clickMask = createEl(
					'<div style="z-index:200;position:absolute;top:0px;left:0px;width:100%;height:100%"></div>',
					document.body);
			mask.onclick = function() {
				pClick();
				fly(mask).hide()
			};
		}
		fly(mask).show();
	}
	doBatchBlur('A');

	// flash init
	var f = UIRegistry.xiaoiFlash;
	var initFlash = function() {
		try {
			f.SetVariable('rndBaseSecond', 10000);
			f.SetVariable('rndStartSecond', 1);
			f.SetVariable('rndEndSecond', 5);
			csMgr.initFlash();
		} catch (e) {
			if (!f.initCount)
				f.initCount = 0;
			if (f.initCount++ < 20) {
				setTimeout(initFlash, 500);
			}
		}
	}
	// chat score manager init
	csMgr.init();
	initFlash();
	
	/*$('get_user_count_frame').src = 'http://p4c.xiaoi.com/flashbot/visitCount.html';
	$('get_user_count_frame').onload=function(){
		var s = $('get_user_count_frame').contentWindow.document.body.innerHTML;
		var fNumEl = fly('usercount_number'); 
		fNumEl.html(s);
		fly(fNumEl.el.parentNode).show('');
	}*/
	//init top btns
	var top_btns = fly('top_btns').el.childNodes;
	for(var i=0;i<top_btns.length;i++){
		var b = top_btns[i];
		if (b.tagName && !b.getAttribute('target')){
			var cmd = b.getAttribute('cmd');
			var act = b.getAttribute('act');
			if (act == 'sendim'){
				fly(b).click(function(){SubmitMessage(this.getAttribute('cmd'));})
			}else{
				if (cmd == 'more'){
					fly(b).click(function(){showInEntrance()});
				}else if (cmd == 'chat'){
					fly(b).click(showchat);
				}else{
					fly(b).click(function(){showInEntrance(this.getAttribute('cmd'))});
				}
			}
		}
	}
	var contentItems = [];
	genCmdExample(examples_chat,function(item,str){
		contentItems[contentItems.length]='<span>'+item.c[0].t+'</span>';
	});
	window.contentScroller = new ContentScroller('example_chat_scroller',2000,10,16,1,contentItems);
	fly('example_chat_scroller').click(function(){UIRegistry.inputBox.focus()});
	UIRegistry.inputBox.onfocus=function(){hideContentScroller(); OnComposeKeyUp();};
	
	var oScript=document.createElement("script") ;
	oScript.src="http://enterpriseadmin.xiaoi.com/enterpriseAdmin/idleRobotQuery.do?script=true&robottag=xiaoi5&defaultRobot=xiaoi171@hotmail.com&callback=initAddRobotBtn";
	document.getElementsByTagName("head")[0].appendChild(oScript);
	window.initAddRobotBtn = function(robot){
		if (IsIE()){
			$('addRobotBtn').href = 'msnim:add?contact='+robot;
		}else{
			$('addRobotBtn').onclick=function(){
				copyToClipBoard(robot,'帐号已复制到剪贴板，请粘贴后添加MSN帐号:'+robot)
			}
		}
	}
	//right-bottom Ad
	fadeIn('popsan',2);
	
}, 'around');
function showInEntrance(cmd){
	fly('mainTable').setStyle('visibility:hidden');
	cmd = cmd?'?SCMD='+cmd:'';
	var entranceFrame = $('xiaoi_inner_frame');
	entranceFrame.src = ('http://www.xiaoi.com/newentrance/2/'+ cmd);
	
	fadeIn(entranceFrame)
	fly('xiaoi_inner_table').show('');
	fly('xiaoi_inner_table_mask').show('');
}
var fadeInTimerCount = 0;
function fadeIn(target,opacityStep){
	target = fly(target);
	target.show('');
	var curOpacity = 0;
	if (!opacityStep) opacityStep = 8; 
	fadeInTimerCount++;
	if (!window['fadeInTimer'+fadeInTimerCount]){
		setOpacity(target,curOpacity);
		window['fadeInTimer'+fadeInTimerCount] = setInterval(function(){
			curOpacity += opacityStep;
			if (curOpacity > 100) stopOpacityTimer(target)
			else setOpacity(target,curOpacity);
		},50);
	}
}
function stopOpacityTimer(target){
	clearInterval(window['fadeInTimer'+fadeInTimerCount]);
	window['fadeInTimer'+fadeInTimerCount] = null;
	target.setStyle('filter:');
}
function setOpacity(flyObj,curOpacity){
	if (IsIE())
		flyObj.setStyle('filter:alpha(opacity='+curOpacity+')');
	else
		flyObj.setStyle('MozOpacity',curOpacity/100); 
}

function ContentScroller(outerDiv,scrollDelay,animInterval,scrollUnitHeight,scrollUnitCount,items){
	this.outerDiv = document.getElementById(outerDiv);
	this.outerDiv.style.overflow='hidden';
	
	var el=document.createElement('DIV');
  	el.style.verticalAlign='middle';
	this.innerDiv = el;
	this.outerDiv.appendChild(el);
	
	this.scrollDelay = scrollDelay;
	this.animInterval = animInterval;
	
	this.contentItems = items;
	this.scrollUnitHeight = scrollUnitHeight;
	this.scrollUnitCount = scrollUnitCount;
	this.scrollerHeight=this.scrollUnitHeight*this.scrollUnitCount;
	
	this.initContent();
	this.stopOnMouseOver();
	this.scheduleScrollAction();
}
ContentScroller.prototype = {
	animInterval:50,
	itemPos:0,
	scrollDelay:4000,
	scrollUnitHeight:18,
	scrollUnitCount:1,
	scrollAnimTimer:null,
	scrollActionTimer:null,
	startScrollAction : function() {
 		this.itemPos++;
  		if(this.itemPos>=this.contentItems.length) this.itemPos=0;
  		
 		var str=this.contentItems[this.itemPos];
  		var outerDiv = this.outerDiv;
  		
 		if(outerDiv.childNodes.length==1) {
  			var nextLine=document.createElement('DIV');
  			nextLine.innerHTML=str;
  			nextLine.style.verticalAlign='middle';
  			outerDiv.appendChild(nextLine);
  		}
 		else {
 			var pstr = this.getPreviousContent();
  			outerDiv.childNodes[0].innerHTML=str;
			outerDiv.childNodes[1].innerHTML=pstr;
  			outerDiv.style.verticalAlign='middle';
  			outerDiv.appendChild(outerDiv.childNodes[0]);
  			outerDiv.scrollTop=0;
  		}
  		
 		if (this.scrollAnimTimer) clearInterval(this.scrollAnimTimer);
 		var self = this;
 		this.scrollAnimTimer=setInterval(function(){self.doScroll()},self.animInterval);
	},
	getPreviousContent : function (_cid){
		_cid = _cid ? _cid : this.itemPos;
		var items = this.contentItems;
		var offset = _cid+items.length;
		var str = "";
		for(var i=this.scrollUnitCount;i>0;i--){
			str+=items[(offset-i)%items.length];
		}
		return str;
	},
	doScroll : function() {
 		var outerDiv = this.outerDiv;
 		outerDiv.scrollTop++;
 		if(outerDiv.scrollTop%this.scrollUnitHeight==this.scrollUnitHeight-1){
  			clearInterval(this.scrollAnimTimer);
  		}
 	},
 	initContent : function (){
		var str="";
		if (this.scrollUnitCount > 1){
			this.itemPos=this.scrollUnitCount-1;
		}
		this.outerDiv.style.height=this.scrollerHeight;
		this.innerDiv.innerHTML=this.getPreviousContent(this.itemPos+1);
	},
	clearActionTimer:function(){
		if (this.scrollActionTimer) clearInterval(this.scrollActionTimer);
	},
	scheduleScrollAction:function(){
		var self = this;
		this.clearActionTimer();
		this.scrollActionTimer=setInterval(function(){self.startScrollAction()},this.scrollDelay);
	},
 	stopOnMouseOver:function(){
 		var self = this;
 		this.outerDiv.onmouseover = function(e){
 			e = e ? e : window.event;
 			try{
	 			if (!this.contains(e.fromElement)){
			 		contentScroller.clearActionTimer();
			 	}
			 }catch(e){}
			 
 		}
 		this.outerDiv.onmouseout = function(e){
	 		e = e ? e : window.event;
	 		try{
	 			if (!this.contains(e.toElement)){
		 			self.scheduleScrollAction();
	 			}
	 		}catch(e){}
 		}
 	},
	v:1
}
if (!IsIE()){
	
Event.prototype.__defineGetter__("fromElement",function(){
    var node;
    if(this.type=="mouseover")
        node=this.relatedTarget;
    else if(this.type=="mouseout")
        node=this.target;
    if(!node)return;
    while(node.nodeType!=1)node=node.parentNode;
    return node;
});
Event.prototype.__defineGetter__("toElement",function(){
    var node;
    if(this.type=="mouseout")
        node=this.relatedTarget;
    else if(this.type=="mouseover")
        node=this.target;
    if(!node)return;
    while(node.nodeType!=1)node=node.parentNode;
    return node;
});
        
HTMLElement.prototype.contains=function(Node){
	do if(Node==this)return true;
	while(Node=Node.parentNode);
	return false;
}	
	
}

function debugAlert(c){
	debug(c);
}