/************** Globals Variables **************/
// Define
var GVERSION="120119v10";
var WEBSITE="http://www.lifeplat.com";
//var WEBSITE="http://www.lpv3.com";
var FILESITE="http://fs.lifeplat.com";
var UPLOADFRIENDSIMGS="/upload_friends_imgs/";
var UPLOADFRIENDSIMGST2="/upload_friends_imgs_t2/";
var UPLOADFRIENDSIMGSTHUMB="/upload_friends_imgs_thumb/";

// General
var isIE=(navigator.userAgent.indexOf("MSIE")!=-1)?true:false;
var isFF=(navigator.userAgent.indexOf("Firefox")!=-1)?true:false;
var isChrome=(navigator.userAgent.indexOf("Chrome")!=-1)?true:false;
var isSafari=(navigator.userAgent.indexOf("Safari")!=-1 && navigator.userAgent.indexOf("Chrome")==-1)?true:false;
if (window.location.href.indexOf("\#_")==-1) { // fb return work around 
	var urlComponents=window.location.href.split("\#");
	if (urlComponents[1]) top.window.location.href=WEBSITE+urlComponents[1];
} else {
	top.window.location.href=window.location.href.substr(0,window.location.href.indexOf("\#_"));
}
if (isIE) {
	var IEVersion=navigator.appVersion.substr(navigator.appVersion.indexOf("MSIE")+5,3);
	if (IEVersion<8) var jsClassExt="className";
	else var jsClassExt="class";
} else {
	var IEVersion=null;
	var jsClassExt="class";
}
var timeoutArray=[];
var highZ=300000;
var jsMsg=[];
var hashChangeLock=false;
var onHashChangeTO;
var usrid=null;

// specific
var porchARI=null; //porch auto-refresh interval
var calendarEI=null //calendar event interval
var chatCls=null;
var imgViewer=null;
var noteTab="M";

// Core
var coreID=window.location.href.replace(WEBSITE,"");
if (coreID.length<4) coreID="/index.php";
else coreID=coreID.substring(0,coreID.indexOf(".php")+4);
var core=null; //core object

// Ajax
var dynamicFileLoadTracker="";
var ajaxLock=false;

// RegExp
var emailValidationPattern=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

// Addthis
var addthis_config = {
     ui_cobrand:"Lifeplat",
	 data_track_clickback:false
}

// Analytics
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-16748782-2']);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

/************** Global Event Listeners **************/
window.onhashchange=function() {
	clearTimeout(onHashChangeTO);
	if (hashChangeLock) {
		hashChangeLock=false;
	} else {
		onHashChangeTO=setTimeout(onHashChange,300);
	}
}
function onHashChange() {
	var oldHash=urlComponents[1];
	urlComponents=window.location.href.split("\#");
	if (oldHash) {
		if (oldHash.indexOf("?tab=")!=-1) var oldHashComponents=oldHash.split("?tab=");
		else var oldHashComponents=oldHash.split("&tab=");
	} else {
		var oldHashComponents=[null,null];
	}
	if (urlComponents[1]) {
		if (urlComponents[1].indexOf("?tab=")!=-1)	var currentHashComponents=urlComponents[1].split("?tab=");
		else var currentHashComponents=urlComponents[1].split("&tab=");
	} else {
		var currentHashComponents=[null,null];
	}
	if (oldHashComponents[0]!=currentHashComponents[0]) {
		if (urlComponents[1]) {
			var newCore=urlComponents[1].substring(0,urlComponents[1].indexOf(".php")+4);
			var url=urlComponents[1];
		} else {
			var newCore=urlComponents[0].replace(WEBSITE,"");
			if (newCore.length<4) {
				var url="/index.php";
				newCore="/index.php";
			} else {
				var url=newCore;
				newCore=newCore.substring(0,newCore.indexOf(".php")+4);
			}
		}
		loadPage(newCore,url,1);
	} else {
		var tab=(currentHashComponents[1]?currentHashComponents[1].substr(0,(currentHashComponents[1].indexOf("&")!=-1?currentHashComponents[1].indexOf("&"):currentHashComponents[1].length)):"");
		core.loadTab(tab,urlComponents[1],1);
	}
	if (document.getElementsByTagName("html")[0].style.overflow=="hidden") document.getElementsByTagName("html")[0].style.overflow="";
}

/************** Core Operation Functions **************/
function loadPage(newCore, hash, noUrlMod) {
	if (!ajaxLock) {
		showLoading("invisDiv");
		var oldHash=urlComponents[1];
		urlComponents[1]=hash;
		if (typeof(noUrlMod)=="undefined") {
			if (oldHash!=hash) hashChangeLock=true;
			top.window.location.href="\#"+hash;
		}
		if (!newCore) {
			newCore=hash;
			if (newCore.length<4) {
				newCore="/index.php";
			} else {
				newCore=newCore.substring(0,newCore.indexOf(".php")+4);
			}
		}
		switch (newCore) {
			case "/index.php":
				dynamicJsCssLoader("/index/css/index.css?"+GVERSION,"css");
				dynamicJsCssLoader("/index/js/index.js?"+GVERSION,"js");
			break;
			case "/p/p.php":
				dynamicJsCssLoader("/p/css/profile.css?"+GVERSION,"css");
				dynamicJsCssLoader("/p/js/profile.js?"+GVERSION,"js");
			break;
			case "/poh/r.php":
				dynamicJsCssLoader("/poh/css/post.css?"+GVERSION,"css");
				dynamicJsCssLoader("/poh/js/post.js?"+GVERSION,"js");
			break;
			case "/pic/pic.php":
				dynamicJsCssLoader("/pic/css/picture.css?"+GVERSION,"css");
				dynamicJsCssLoader("http://j.maxmind.com/app/geoip.js","js");
				dynamicJsCssLoader("/pic/js/picture.js?"+GVERSION,"js");
			break;
			case "/pic/upload.php":
				dynamicJsCssLoader("/css/swfu.css?"+GVERSION,"css");
				dynamicJsCssLoader("/js/swfu.js?"+GVERSION,"js");
				dynamicJsCssLoader("/pic/css/upload.css?"+GVERSION,"css");
				dynamicJsCssLoader("/pic/js/upload.js?"+GVERSION,"js");
			break;
			case "/pic/sc.php":
				dynamicJsCssLoader("/pic/css/sc.css?"+GVERSION,"css");
				dynamicJsCssLoader("/pic/js/sc.js?"+GVERSION,"js");
			break;
			case "/setting/setting.php":
				dynamicJsCssLoader("/setting/css/setting.css?"+GVERSION,"css");
				dynamicJsCssLoader("/setting/js/setting.js?"+GVERSION,"js");
				dynamicJsCssLoader("/members/validate/jquery.validate.min.js","js");
			break;
			case "/blog/b.php":
				dynamicJsCssLoader("/blog/css/blog.css?"+GVERSION,"css");
				dynamicJsCssLoader("/blog/js/blog.js?"+GVERSION,"js");
			break;
			case "/blog/edit.php":
				dynamicJsCssRemover("/plugin/tiny_mce/tiny_mce_gzip.js","js");
				dynamicJsCssLoader("/blog/css/edit.css?"+GVERSION,"css");
				dynamicJsCssLoader("http://j.maxmind.com/app/geoip.js","js");
				dynamicJsCssLoader("/plugin/tiny_mce/tiny_mce_gzip.js","js");
				dynamicJsCssLoader("/blog/js/edit.js?"+GVERSION,"js");
			break;
			case "/inbox/ib.php":
				dynamicJsCssLoader("/inbox/css/inbox.css?"+GVERSION,"css");
				dynamicJsCssLoader("/inbox/js/inbox.js?"+GVERSION,"js");
			break;
			case "/forum/forum.php":
				dynamicJsCssLoader("/forum/css/forum.css?"+GVERSION,"css");
				dynamicJsCssLoader("/forum/js/forum.js?"+GVERSION,"js");
			break;
			case "/forum/edit.php":
				dynamicJsCssRemover("/plugin/tiny_mce/tiny_mce_gzip.js","js");
				dynamicJsCssLoader("/forum/css/edit.css?"+GVERSION,"css");
				dynamicJsCssLoader("/plugin/tiny_mce/tiny_mce_gzip.js","js");
				dynamicJsCssLoader("/forum/js/edit.js?"+GVERSION,"js");
			break;
			case "/e/e.php":
				dynamicJsCssLoader("/e/css/event.css?"+GVERSION,"css");
				dynamicJsCssLoader("/e/js/event.js?"+GVERSION,"js");
			break;
			case "/e/edit.php":
				dynamicJsCssRemover("/plugin/tiny_mce/tiny_mce_gzip.js","js");
				dynamicJsCssLoader("/css/swfu.css?"+GVERSION,"css");
				dynamicJsCssLoader("/e/css/edit.css?"+GVERSION,"css");
				dynamicJsCssLoader("http://j.maxmind.com/app/geoip.js","js");
				dynamicJsCssLoader("/js/swfu.js?"+GVERSION,"js");
				dynamicJsCssLoader("/plugin/tiny_mce/tiny_mce_gzip.js","js");
				dynamicJsCssLoader("/e/js/edit.js?"+GVERSION,"js");
			break;
			case "/policy/contact_us.php":
				dynamicJsCssLoader("/policy/css/contact.css?"+GVERSION,"css");
				dynamicJsCssLoader("/policy/js/contact.js?"+GVERSION,"js");
			break;
			case "/policy/legal.php":
				dynamicJsCssLoader("/policy/css/legal.css?"+GVERSION,"css");
				dynamicJsCssLoader("/policy/js/legal.js?"+GVERSION,"js");
			break;
			case "/search/s.php":
				dynamicJsCssLoader("/search/css/search.css?"+GVERSION,"css");
				dynamicJsCssLoader("/search/js/search.js?"+GVERSION,"js");
			break;
			case "/map/faces.php":
				dynamicJsCssLoader("/map/css/faces.css?"+GVERSION,"css");
				dynamicJsCssLoader("http://j.maxmind.com/app/geoip.js","js");
				dynamicJsCssLoader("/map/js/faces.js?"+GVERSION,"js");
			break;
			case "/map/web.php":
				dynamicJsCssLoader("/map/css/web.css?"+GVERSION,"css");
				dynamicJsCssLoader("/map/js/web.js?"+GVERSION,"js");
			break;
			case "/map/events.php":
				dynamicJsCssLoader("/map/css/events.css?"+GVERSION,"css");
				dynamicJsCssLoader("http://j.maxmind.com/app/geoip.js","js");
				dynamicJsCssLoader("/map/js/events.js?"+GVERSION,"js");
			break;
			case "/help/index.php":
				dynamicJsCssLoader("/help/css/help.css?"+GVERSION,"css");
				dynamicJsCssLoader("/help/js/help.js?"+GVERSION,"js");
			break;
			case "/music/m.php":
				dynamicJsCssLoader("/music/css/music.css?"+GVERSION,"css");
				dynamicJsCssLoader("/music/js/music.js?"+GVERSION,"js");
			break;
			case "/music/upload.php":
				dynamicJsCssLoader("/css/swfu.css?"+GVERSION,"css");
				dynamicJsCssLoader("/js/swfu.js?"+GVERSION,"js");
				dynamicJsCssLoader("/music/css/upload.css?"+GVERSION,"css");
				dynamicJsCssLoader("/music/js/upload.js?"+GVERSION,"js");
			break;
			case "/music/s.php":
				dynamicJsCssLoader("/music/css/song.css?"+GVERSION,"css");
				dynamicJsCssLoader("/music/js/song.js?"+GVERSION,"js");
			break;
			case "/game/title.php":
				dynamicJsCssLoader("/game/css/game.css?"+GVERSION,"css");
				dynamicJsCssLoader("/game/js/game.js?"+GVERSION,"js");
			break;
			default:
			break;
		}
		if (newCore!=coreID) {
			ajaxRequest(hash,"",0,function(rs) {
				try {
					rs=JSON.parse(rs);
					document.getElementById("contentDiv").innerHTML=rs["out"];
					scrollTo(0,0);
					clearPreviousCore(newCore);
					initCore(newCore,rs["initSeq"]);
					_gaq.push(['_trackPageview', coreID]);
				} catch (ex) {
					loadMask(400,50);
					document.getElementById("maskContentDiv").innerHTML="<table class='fillerTable'><tr><td class='error'>"+rs+"</td></tr></table>";
				}
			});
		} else {
			ajaxRequest(hash,"",0,function(rs) {
				try {
					rs=JSON.parse(rs);
					document.getElementById("contentDiv").innerHTML=rs["out"];
					scrollTo(0,0);
					if (rs["initSeq"]) eval(rs["initSeq"]);
					_gaq.push(['_trackPageview', coreID]);
				} catch (ex) {
					loadMask(400,50);
					document.getElementById("maskContentDiv").innerHTML="<table class='fillerTable'><tr><td class='error'>"+rs+"</td></tr></table>";
				}
			});
		}
		document.getElementById("ftrCurrentUrl").innerHTML=WEBSITE+hash;
	}
}
function clearPreviousCore(newCore) {
	if (newCore!=coreID) {
		switch (coreID) {
			case "/index.php":
				core=null;
				dynamicJsCssRemover("/index/js/index.js?"+GVERSION,"js");
				dynamicJsCssRemover("/index/css/index.css?"+GVERSION,"css");
			break;
			case "/p/p.php":
				clearInterval(porchARI);
				window.onscroll=null;
				document.onmousemove=null;
				document.onclick=null;
				document.onkeydown=null;
				core=null;
				dynamicJsCssRemover("/p/js/profile.js?"+GVERSION,"js");
				dynamicJsCssRemover("/f/js/invite_friends.js?"+GVERSION,"js");
				dynamicJsCssRemover("/members/validate/jquery.validate.min.js","js");
				dynamicJsCssRemover("/p/css/profile.css?"+GVERSION,"css");
			break;
			case "/poh/r.php":
				window.onscroll=null;
				core=null;
				dynamicJsCssRemover("/poh/js/post.js?"+GVERSION,"js");
				dynamicJsCssRemover("/poh/css/post.css?"+GVERSION,"css");
			break;
			case "/pic/pic.php":
				window.onscroll=null;
				core=null;
				dynamicJsCssRemover("/pic/js/picture.js?"+GVERSION,"js");
				dynamicJsCssRemover("http://j.maxmind.com/app/geoip.js","js");
				dynamicJsCssRemover("/pic/css/picture.css?"+GVERSION,"css");
			break;
			case "/pic/upload.php":
				core=null;
				dynamicJsCssRemover("/pic/js/upload.js?"+GVERSION,"js");
				dynamicJsCssRemover("/pic/css/upload.css?"+GVERSION,"css");
			break;
			case "/pic/sc.php":
				window.onscroll=null;
				core=null;
				dynamicJsCssRemover("/pic/js/sc.js?"+GVERSION,"js");
				dynamicJsCssRemover("/pic/css/sc.css?"+GVERSION,"css");
			break;
			case "/setting/setting.php":
				core=null;
				dynamicJsCssRemover("/setting/js/setting.js?"+GVERSION,"js");
				dynamicJsCssRemover("/members/validate/jquery.validate.min.js","js");
				dynamicJsCssRemover("/setting/css/setting.css?"+GVERSION,"css");
			break;
			case "/blog/b.php":
				window.onscroll=null;
				core=null;
				dynamicJsCssRemover("/blog/js/blog.js?"+GVERSION,"js");
				dynamicJsCssRemover("/blog/css/blog.css?"+GVERSION,"css");
				document.documentElement.style.background="#fff";
			break;
			case "/blog/edit.php":
				core=null;
				dynamicJsCssRemover("/blog/js/edit.js?"+GVERSION,"js");
				dynamicJsCssRemover("http://j.maxmind.com/app/geoip.js","js");
				dynamicJsCssRemover("/blog/css/edit.css?"+GVERSION,"css");
				document.documentElement.style.background="#fff";
			break;
			case "/inbox/ib.php":
				core=null;
				dynamicJsCssRemover("/inbox/js/inbox.js?"+GVERSION,"js");
				dynamicJsCssRemover("/inbox/css/inbox.css?"+GVERSION,"css");
			break;
			case "/forum/forum.php":
				core=null;
				dynamicJsCssRemover("/forum/js/forum.js?"+GVERSION,"js");
				dynamicJsCssRemover("/forum/css/forum.css?"+GVERSION,"css");
			break;
			case "/forum/edit.php":
				core=null;
				dynamicJsCssRemover("/forum/js/edit.js?"+GVERSION,"js");
				dynamicJsCssRemover("/forum/css/edit.css?"+GVERSION,"css");
			break;
			case "/e/e.php":
				window.onscroll=null;
				core=null;
				dynamicJsCssRemover("/e/js/event.js?"+GVERSION,"js");
				dynamicJsCssRemover("/e/css/event.css?"+GVERSION,"css");
			break;
			case "/e/edit.php":
				core=null;
				dynamicJsCssRemover("/e/js/edit.js?"+GVERSION,"js");
				dynamicJsCssRemover("http://j.maxmind.com/app/geoip.js","js");
				dynamicJsCssRemover("/e/css/edit.css?"+GVERSION,"css");
			break;
			case "/policy/contact_us.php":
				core=null;
				dynamicJsCssRemover("/policy/js/contact.js?"+GVERSION,"js");
				dynamicJsCssRemover("/policy/css/contact.css?"+GVERSION,"css");
			break;
			case "/policy/legal.php":
				core=null;
				dynamicJsCssRemover("/policy/js/legal.js?"+GVERSION,"js");
				dynamicJsCssRemover("/policy/css/legal.css?"+GVERSION,"css");
			break;
			case "/search/s.php":
				core=null;
				dynamicJsCssRemover("/search/js/search.js?"+GVERSION,"js");
				dynamicJsCssRemover("/search/css/search.css?"+GVERSION,"css");
			break;
			case "/map/faces.php":
				core=null;
				dynamicJsCssRemover("/map/js/faces.js?"+GVERSION,"js");
				dynamicJsCssLoader("http://j.maxmind.com/app/geoip.js","js");
				dynamicJsCssRemover("/map/css/faces.css?"+GVERSION,"css");
				document.getElementById("footerDiv").style.position="static";
			break;
			case "/map/web.php":
				core=null;
				dynamicJsCssRemover("/map/js/web.js?"+GVERSION,"js");
				dynamicJsCssRemover("/map/css/web.css?"+GVERSION,"css");
				document.getElementById("footerDiv").style.position="static";
			break;
			case "/map/events.php":
				core=null;
				dynamicJsCssRemover("/map/js/events.js?"+GVERSION,"js");
				dynamicJsCssLoader("http://j.maxmind.com/app/geoip.js","js");
				dynamicJsCssRemover("/map/css/events.css?"+GVERSION,"css");
				document.getElementById("footerDiv").style.position="static";
			break;
			case "/help/index.php":
				core=null;
				dynamicJsCssRemover("/help/js/help.js?"+GVERSION,"js");
				dynamicJsCssRemover("/help/css/help.css?"+GVERSION,"css");
			break;
			case "/music/m.php":
				core=null;
				dynamicJsCssRemover("/music/js/music.js?"+GVERSION,"js");
				dynamicJsCssRemover("/music/css/music.css?"+GVERSION,"css");
			break;
			case "/music/upload.php":
				core=null;
				dynamicJsCssRemover("/music/js/upload.js?"+GVERSION,"js");
				dynamicJsCssRemover("/music/css/upload.css?"+GVERSION,"css");
			break;
			case "/music/s.php":
				window.onscroll=null;
				core=null;
				dynamicJsCssRemover("/music/js/song.js?"+GVERSION,"js");
				dynamicJsCssRemover("/music/css/song.css?"+GVERSION,"css");
			break;
			case "/music/upload.php":
				core=null;
				dynamicJsCssRemover("/game/js/game.js?"+GVERSION,"js");
				dynamicJsCssRemover("/game/css/game.css?"+GVERSION,"css");
			break;
			default:
				core=null;
			break;
		}
	}
}
function initCore(newCore,initSeq) {
	if (newCore!=coreID) {
		var interval;
		loadClass=function() {
			switch (newCore) {
				case "/index.php":
					if (typeof(indexClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/p/p.php":
					if (typeof(profileClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/poh/r.php":
					if (typeof(porchPostClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/pic/pic.php":
					if (typeof(pictureClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/pic/upload.php":
					if (typeof(photoUploadClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/pic/sc.php":
					if (typeof(scClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/setting/setting.php":
					if (typeof(settingClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/blog/b.php":
					if (typeof(blogClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/blog/edit.php":
					if (typeof(blogEditClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/inbox/ib.php":
					if (typeof(inboxClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/forum/forum.php":
					if (typeof(forumClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/forum/edit.php":
					if (typeof(forumEditClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/e/e.php":
					if (typeof(eventClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/e/edit.php":
					if (typeof(eventEditClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/policy/contact_us.php":
					if (typeof(contactClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/policy/legal.php":
					if (typeof(legalClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/search/s.php":
					if (typeof(searchClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/map/faces.php":
					if (typeof(mapClass_faces)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/map/web.php":
					if (typeof(mapClass_web)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/map/events.php":
					if (typeof(mapClass_events)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/help/index.php":
					if (typeof(helpClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/music/m.php":
					if (typeof(musicClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/music/upload.php":
					if (typeof(musicUploadClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/music/s.php":
					if (typeof(songClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				case "/game/title.php":
					if (typeof(gameClass)==="function") {
						clearInterval(interval);
						coreID=newCore;
						if (initSeq) eval(initSeq);
					}
				break;
				default:
					clearInterval(interval);
					coreID=newCore;
					core=null;
					if (initSeq) eval(initSeq);
				break;
			}
		}
		interval=setInterval(loadClass,100);
	}
}

/************** General Functions **************/
function initGeneral(init) {
	init=JSON.parse(init);
	usrid=init.uid;
	jsMsg=init.msg;	
	if (usrid) {
		chatCls=new chatClass();
		setTimeout(autoEvent_calendar,15000);
	}
}
function jsVersionCheck(version) {
	if (version!=GVERSION) window.location.reload();
}
function showLoading(divID) {
	if (divID=="invisDiv") {
		document.getElementById("invisDiv").style.display="block";
	}
	document.getElementById(divID).innerHTML="<table style='width:100%;height:100%;'><tr><td align='center'><div style='height:11px;width:16px;background-image:url(/img/loading.gif);_font-size:0px;'></div></td></tr></table>";
}
function loadMask(w, h, title) {
	var str;
	str="<table style='height:100%;width:100%;'><tr><td align='center'>";
		str+="<div id='maskOutterDiv' style='width:"+(w+2)+"px;height:"+(h+33)+"px;'>";
				str+="<div id='maskTitleDiv' style='width:"+w+"px;'>";
					if (typeof(title)!='undefined') str+="<div id='maskInfoDiv'>"+title+"</div>";
					str+="<div id='maskCancelBtnDiv' onClick='clearMask();'></div>";
				str+="</div>";
				str+="<div id='maskContentDiv' style='width:"+w+"px;height:"+h+"px;' align='left'></div>";
		str+="</div>";
	str+="</td></tr></table>";
	document.getElementById('invisDiv').innerHTML=str;
	document.getElementById('invisDiv').style.display="block";
	showLoading("maskContentDiv");
}
function setMask(w, h) {
	document.getElementById("maskContentDiv").style.width=w+"px";
	document.getElementById("maskContentDiv").style.height=h+"px";
	document.getElementById("maskTitleDiv").style.width=w+"px";
	document.getElementById("maskOutterDiv").style.width=w+2+"px";
	document.getElementById("maskOutterDiv").style.height=h+33+"px";
}
function clearMask() {
	document.getElementById('invisDiv').innerHTML="";
	document.getElementById('invisDiv').style.display="none";
	document.getElementById('invisDiv').style.backgroundImage="url(about:blank)";
}
function loadInterrupt(msg) {
	hashChangeLock=true;
	if (typeof(msg)=="undefined") msg=jsMsg[3];
	var str;
	str="<table style='height:100%;width:100%;'><tr><td align='center'>";
		str+="<div id='maskInterruptDiv'>"+msg+"</div>";
	str+="</td></tr></table>";
	if (!isIE || (isIE && IEVersion>=7)) document.getElementById('invisDiv').style.backgroundImage="url('/img/transfill.png')";
	document.getElementById('invisDiv').innerHTML=str;
	document.getElementById('invisDiv').style.display="block";
}
function clearInterrupt() {
	document.getElementById('invisDiv').innerHTML="";
	document.getElementById('invisDiv').style.display="none";
	document.getElementById('invisDiv').style.backgroundImage="url(about:blank)";
	hashChangeLock=false;
}
function killDiv(divID, speed) {
	if (document.getElementById(divID)) {
		var killDivInterval;
		var h=document.getElementById(divID).offsetHeight;
		var t=Math.abs(Math.ceil(h/(20*speed)));
		var i=t-1;
		document.getElementById(divID).style.overflow="hidden";
		killDivProcess=function(divID) {
			if (i>0 && document.getElementById(divID)) {
				document.getElementById(divID).style.height=Math.round((h/t)*i)+"px";
				i--;
			} else {
				clearInterval(killDivInterval);
				if (document.getElementById(divID))	document.getElementById(divID).parentNode.removeChild(document.getElementById(divID));
			}
		}
		killDivInterval=setInterval("killDivProcess('"+divID+"')",50);
	}
}
function preventDefaultIE(ele) {
	ele.onselectstart=function() {
		return false;
	}
}
function addListener(eleId, eventName, callback) {
	var element=document.getElementById(eleId);
	if (!element) return false;
	if (element.addEventListener) {
		if (eventName=="mousewheel") {
			element.addEventListener("DOMMouseScroll",callback,false);  
		}
		element.addEventListener(eventName,callback,false);
	} else if (element.attachEvent) {
		element.attachEvent("on"+eventName,callback);
	}
}
function removeListener(eleId, eventName, callback) {
	var element=document.getElementById(eleId);
	if (!element) return false;
	if (element.removeEventListener) {
		if (eventName=="mousewheel") {
			element.removeEventListener("DOMMouseScroll",callback,false);  
		}
		element.removeEventListener(eventName,callback,false);
	} else if (element.detachEvent) {
		element.detachEvent("on"+eventName,callback);
	}
}
function cancelEvent(e) {
	e=e?e:window.event;
	if (e.stopPropagation) e.stopPropagation();
	if (e.preventDefault) e.preventDefault();
	e.cancelBubble=true;
	e.cancel=true;
	e.returnValue=false;
	return false;
}
function objEmpty(obj) {
	for (var i in obj) {
		return false;
	}
	return true;
}
function autoScroll(dy) {
	var interval;
	var i=1;
	var st=(isIE?document.documentElement.scrollTop:window.pageYOffset);
	
	function autoScrollProcess() {
		if (i<6) {
			scrollTo(0,Math.round(st+(dy*Math.sin((Math.PI/5*i)/2))));
			i++;
		} else {
			clearInterval(interval);
		}
	}
	
	interval=setInterval(autoScrollProcess,50);
}
function getGeoInfo() { //require http://j.maxmind.com/app/geoip.js
	var geoInfo=[];
	try {
		geoInfo['lat']=geoip_latitude();
		geoInfo['lng']=geoip_longitude();
	} catch(ex) {
		geoInfo['lat']=25.0392;
		geoInfo['lng']=121.5250;
	}
	return geoInfo;
}
function getElementsByClass(cls, node, tag) {
	var result=new Array();
	if (node==null) node=document;
	if (tag==null) tag='*';
	var els=((tag=="*" && node.all)?node.all:node.getElementsByTagName(tag));
	var pattern=new RegExp("(^|\\s)"+cls+"(\\s|$)");
	for (var i=0; i<els.length; i++) {
		if (pattern.test(els[i].className)) {
			result.push(els[i]);
		}
	}
	return result;
}
function htmlspecialchars(str) {
  return str
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
}

/************** Auto Events **************/
function autoEvent_calendar() {
	var params="uid="+usrid;
	ajaxRequest("/calendar/auto_event.php",params,0,function(rs) {
		try {
			rs=JSON.parse(rs);
			if (rs.flag=="pass") {
				if (document.getElementById('calendarEventDiv')) document.getElementById('eventDiv').removeChild(document.getElementById('calendarEventDiv'));
				var ele=document.createElement("div");
				ele.id="calendarEventDiv";
				ele.className="autoEventMainDiv calendarAEIcon";
				ele.innerHTML=rs.out;
				document.getElementById("eventDiv").appendChild(ele);
				document.getElementById("eventAlertAudio").currentTime=0;
				document.getElementById("eventAlertAudio").play();
				setTimeout("try {document.getElementById('eventDiv').removeChild(document.getElementById('calendarEventDiv'));} catch(ex) {}",30000);
			}
		} catch(ex) {
		}
		clearInterval(calendarEI);
		calendarEI=setInterval(autoEvent_calendar,3600000);
	});
}

function autoEvent_gift(from) {
	noteCounterUpdate();
	var params="uid="+usrid+"&from="+from;
	ajaxRequest("/gift/auto_event.php",params,0,function(rs) {
		try {
			rs=JSON.parse(rs);
			if (rs.flag=="pass") {
				if (document.getElementById('giftEventDiv')) document.getElementById('eventDiv').removeChild(document.getElementById('giftEventDiv'));
				var ele=document.createElement("div");
				ele.id="giftEventDiv";
				ele.className="autoEventMainDiv giftAEIcon";
				ele.innerHTML=rs.out;
				document.getElementById("eventDiv").appendChild(ele);
				document.getElementById("eventAlertAudio").currentTime=0;
				document.getElementById("eventAlertAudio").play();
			}
		} catch(ex) {
		}
	});
}

function autoEvent_AAF(from) {
	noteCounterUpdate();
	var params="uid="+usrid+"&from="+from;
	ajaxRequest("/f/auto_event.php",params,0,function(rs) {
		try {
			rs=JSON.parse(rs);
			if (rs.flag=="pass") {
				if (document.getElementById('AAFEventDiv')) document.getElementById('eventDiv').removeChild(document.getElementById('AAFEventDiv'));
				var ele=document.createElement("div");
				ele.id="AAFEventDiv";
				ele.className="autoEventMainDiv AAFAEIcon";
				ele.innerHTML=rs.out;
				document.getElementById("eventDiv").appendChild(ele);
				document.getElementById("eventAlertAudio").currentTime=0;
				document.getElementById("eventAlertAudio").play();
			}
		} catch(ex) {
		}
	});
}

function autoEvent_inbox(from) {
	noteCounterUpdate();
	document.getElementById("menuNPMIndicator").setAttribute(jsClassExt,"menuNPMIndicator");
	var params="uid="+usrid+"&from="+from;
	ajaxRequest("/inbox/auto_event.php",params,0,function(rs) {
		try {
			rs=JSON.parse(rs);
			if (rs.flag=="pass") {
				if (document.getElementById('inboxEventDiv')) document.getElementById('eventDiv').removeChild(document.getElementById('inboxEventDiv'));
				var ele=document.createElement("div");
				ele.id="inboxEventDiv";
				ele.className="autoEventMainDiv inboxAEIcon";
				ele.innerHTML=rs.out;
				document.getElementById("eventDiv").appendChild(ele);
				document.getElementById("eventAlertAudio").currentTime=0;
				document.getElementById("eventAlertAudio").play();
			}
		} catch(ex) {
		}
	});
}

function autoEvent_event(from) {
	noteCounterUpdate();
	var params="uid="+usrid+"&from="+from;
	ajaxRequest("/e/auto_event.php",params,0,function(rs) {
		try {
			rs=JSON.parse(rs);
			if (rs.flag=="pass") {
				if (document.getElementById('eventEventDiv')) document.getElementById('eventDiv').removeChild(document.getElementById('eventEventDiv'));
				var ele=document.createElement("div");
				ele.id="eventEventDiv";
				ele.className="autoEventMainDiv eventAEIcon";
				ele.innerHTML=rs.out;
				document.getElementById("eventDiv").appendChild(ele);
				document.getElementById("eventAlertAudio").currentTime=0;
				document.getElementById("eventAlertAudio").play();
			}
		} catch(ex) {
		}
	});
}

function autoEvent_eco(from) {
	var params="uid="+usrid+"&from="+from;
	ajaxRequest("/eco/auto_event.php",params,0,function(rs) {
		try {
			rs=JSON.parse(rs);
			if (rs.flag=="pass") {
				if (document.getElementById('ecoEventDiv')) document.getElementById('eventDiv').removeChild(document.getElementById('ecoEventDiv'));
				var ele=document.createElement("div");
				ele.id="ecoEventDiv";
				ele.className="autoEventMainDiv ecoAEIcon";
				ele.innerHTML=rs.out;
				document.getElementById("eventDiv").appendChild(ele);
				document.getElementById("eventAlertAudio").currentTime=0;
				document.getElementById("eventAlertAudio").play();
			}
		} catch(ex) {
		}
	});
}

function autoEvent_event(arg) {
	noteCounterUpdate();
	arg=arg.split(",");
	var params="uid="+usrid+"&from="+arg[0]+"&event="+arg[1];
	ajaxRequest("/e/auto_event.php",params,0,function(rs) {
		try {
			rs=JSON.parse(rs);
			if (rs.flag=="pass") {
				if (document.getElementById('eventEventDiv')) document.getElementById('eventDiv').removeChild(document.getElementById('eventEventDiv'));
				var ele=document.createElement("div");
				ele.id="eventEventDiv";
				ele.className="autoEventMainDiv eventAEIcon";
				ele.innerHTML=rs.out;
				document.getElementById("eventDiv").appendChild(ele);
				document.getElementById("eventAlertAudio").currentTime=0;
				document.getElementById("eventAlertAudio").play();
			}
		} catch(ex) {
		}
	});
}

function autoEvent_request(from) {
	var params="uid="+usrid+"&from="+from;
	ajaxRequest("/notes/auto_event.php",params,0,function(rs) {
		try {
			rs=JSON.parse(rs);
			if (rs.flag=="pass") {
				if (document.getElementById('requestEventDiv')) document.getElementById('eventDiv').removeChild(document.getElementById('requestEventDiv'));
				var ele=document.createElement("div");
				ele.id="requestEventDiv";
				ele.className="autoEventMainDiv requestAEIcon";
				ele.innerHTML=rs.out;
				document.getElementById("eventDiv").appendChild(ele);
				document.getElementById("eventAlertAudio").currentTime=0;
				document.getElementById("eventAlertAudio").play();
			}
		} catch(ex) {
		}
	});
}

function autoEvent_close(divID) {
	document.getElementById('eventDiv').removeChild(document.getElementById(divID));
}

/************** Ajax Core **************/
function ajaxRequest(filePath, params, lockTimer, fn) { // lockTimer=0: bypass ajaxLock; 0<lockTimer<10000 locking ajax for time=lockTimer; lockTimer>=10000: ajax perma lock until unlockAjax is called
	if (lockTimer && ajaxLock) return false;
	if (lockTimer) {
		ajaxLock=true;
		if (lockTimer<10000) setTimeout("ajaxLock=false;",lockTimer);
	}
	params=params+"&ajaxSignature=1";
	var xmlhttp;
	if (window.XMLHttpRequest) {
		xmlhttp=new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("Your Browser Does Not Support XMLHTTP!");
	}
	xmlhttp.open("POST", filePath, true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.send(params);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {	
			if (fn) fn(xmlhttp.responseText);
		}
	}
}
function lockAjax(time) { // time: locking time, if undefined = perma lock
	ajaxLock=true;
	if (typeof (time)!=="undefined") {
		setTimeout("ajaxLock=false;",time);
	}
}
function unlockAjax() {
	ajaxLock=false;
}
function dynamicJsCssLoader(filePath, fileType, callback, debug) {		
	callback=(typeof callback == 'function')?callback:((!isNaN(callback))?callback:0);	
	if (dynamicFileLoadTracker.indexOf("["+filePath+"]")==-1) {	
		debug=debug || ((!isNaN(callback))?callback:0);		
		if (fileType=="js") {			
			var fileref=document.createElement('script');
			fileref.setAttribute("type","text/javascript");
			if (typeof(debug)!="undefined" && debug==1) fileref.setAttribute("src", filePath+"?"+Math.floor(Math.random()*1001));
			else fileref.setAttribute("src", filePath);			
		}
		else if (fileType=="css"){
			var fileref=document.createElement("link");
			fileref.setAttribute("rel", "stylesheet");
			fileref.setAttribute("type", "text/css");
			if (typeof(debug)!="undefined" && debug==1) fileref.setAttribute("href", filePath+"?"+Math.floor(Math.random()*1001));
			else fileref.setAttribute("href", filePath);
		}
		if (typeof callback=="function") {
			if (isIE) {
				fileref.onreadystatechange=function() { // IE
					if (this.readyState === 'loaded' || this.readyState === 'complete') {
						callback.call();
					}
				};
			} else {
				fileref.onload=function() { // Firefox,chrome,safari, Opera...
					callback.call();					
				};
			}
		}
		if (typeof fileref!="undefined")
			document.getElementsByTagName("head")[0].appendChild(fileref);
		dynamicFileLoadTracker+="["+filePath+"]";
	} else {
		if (typeof callback=="function") callback.call();		
	}
}
function dynamicJsCssRemover(filePath, fileType, callback) { //replace to empty, then remove
	if (fileType=="js") {
		var fileref=document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src","/js/empty.js");
	} else if (fileType=="css") {
		var fileref=document.createElement("link");
		fileref.setAttribute("rel","stylesheet");
		fileref.setAttribute("type","text/css");
		fileref.setAttribute("href","/css/empty.css");
	}
	var targetEle=(fileType=="js")?"script":(fileType=="css")?"link":"none";
	var targetAttr=(fileType=="js")?"src":(fileType=="css")?"href":"none";
	var allSuspects=document.getElementsByTagName(targetEle);
	for (var i=allSuspects.length; i>=0; i--) {
		if (allSuspects[i] && allSuspects[i].getAttribute(targetAttr)!=null && allSuspects[i].getAttribute(targetAttr).indexOf(filePath)!=-1) {
			allSuspects[i].parentNode.replaceChild(fileref, allSuspects[i]);
			allSuspects[i].parentNode.removeChild(allSuspects[i]);
			dynamicFileLoadTracker=dynamicFileLoadTracker.replace("["+filePath+"]","");
		}
	}
	if (callback) callback.call();
}

/************** Text **************/
function detectURL(text) {
	var patt=/((http|ftp|https):\/\/|www\.)[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@!;?^=%&:\/~\+#]*[\w\-\@!;?^=%&\/~\+#])/gi;
	urls=text.match(patt);
	if (urls!=null) {
		var i=0;
		var href="";
		var urlShort="";
		var pos=0;
		var prefix="";
		var re;
		while (urls[i]) {
			pos=text.indexOf(urls[i]);
			prefix=text.substring(pos-5,pos);
			if (prefix!="src='" && prefix!="src=\"" && prefix!="ref='" && prefix!="tp://") {
				if (urls[i].indexOf("www.")===0) href="http://"+urls[i];
				else href=urls[i];
				if (urls[i].length>40) urlShort=urls[i].substr(0,40)+"..."; else urlShort=urls[i];
				re=urls[i].replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
				text=text.replace(new RegExp(re,'gi'), "<a href='"+href+"' target='_blank'>"+urlShort+"</a>");
			}
			i++;
		}
	}
	return text;
}
String.prototype.trimmark=function () {
	var htmltag =['!--','--','a','abbr','acronym','address','applet','area','b','basefont','bdo','bgsound','big','blockquote',
		'body','br','button','button-live','caption','center','cite','code','colgroup','dd','del','dfn','div','dl','dt','em',
		'embed','fieldset','font','form','frame','frameset','h1','h2','h3','h4','h5','h6','head','hr','html','i','iframe','img',
		'input','ins','kbd','label','legend','li','link','map','marquee','meta','noframes','noscript','object','ol','optgroup',
		'option','p','param','pre','samp','script','select','small','span','strong','style','sub','sup','table','tbody','td',
		'textarea','tfoot','th','thead','title','tr','tt','ul','var','xml','xmp'];
	if (arguments.length == 1 && arguments[0].constructor.toString().indexOf("Array") != -1 ) {
		var allow_tags=	arguments[0];
		var new_arr=new Array();
		var a=0;
		for (var i in htmltag) {
			a=0;
			for (var j in allow_tags) {
				if (allow_tags[j] == htmltag[i]) {
					a=1;							
					break;									
				}						
			}
			if (a == 0) {new_arr.push(htmltag[i]);}
		}
		var strarray = (new_arr.length == 0)?htmltag.join('|'):new_arr.join('|');
		var regex = '((<|&lt;)\/?(('+strarray+')(([\s ][^>]*(>|&gt;))|\/?>|&gt;|[\s ]))|<\!\-?\-?[^>]*(>|&gt;)?)';
		return this.replace(new RegExp(regex, 'gi'),' ');	
	} else {
		var regex = '((<|&lt;)\/?(('+htmltag.join('|')+')(([\s ][^>]*(>|&gt;))|\/?>|&gt;|[\s ]))|<\!\-?\-?[^>]*(>|&gt;)?)';
		return this.replace(new RegExp(regex, 'gi'),' ');
	}
}
function trim(str) {
	return str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
}

/************** Video Functions **************/
// YouTube
function parseYouTube(vStr) {
	var pos=vStr.indexOf('http://www.youtube.com');
	if (pos<0) pos=vStr.indexOf('http://youtu.be');
	if (pos<0) pos=vStr.indexOf('http://www.youtube-nocookie.com');
	if (pos<0) pos=vStr.indexOf('https://www.youtube.com');
	if (pos<0) pos=vStr.indexOf('https://www.youtube-nocookie.com');
	if (pos<0) pos=vStr.indexOf('https://www.youtube-nocookie.com');
	if (pos<0) {
		return false;
	} else if (pos==0) {
		vStr=vStr.replace('/watch?v=','/v/');
		vStr=vStr.replace('/watch_popup?v=','/v/');
		vStr=vStr.replace('http://youtu.be/','http://youtube.com/v/');
		pos=vStr.indexOf('\&');
		if (pos>0) vStr=vStr.substring(0,pos);
	} else if (pos>0) {
		vStr=vStr.substring(pos);
		pos=vStr.indexOf('?');
		if (pos>0) vStr=vStr.substring(0,pos);
		pos=vStr.indexOf('\"');
		if (pos>0) vStr=vStr.substring(0,pos);
		vStr=vStr.replace('/embed/','/v/');
	}
	return vStr;
}
function embedYouTube(vStr, width, height, autoplay, loop) {
	var str="<object type='application/x-shockwave-flash' data='"+vStr+"&autoplay="+autoplay+"&loop="+loop+"' width='"+width+"' height='"+height+"' style='outline:none;'>";
	str+="<param name='movie' value='"+vStr+"&autoplay="+autoplay+"&loop="+loop+"'></param>";
	str+="<param name='allowFullScreen' value='true'></param>";
	str+="<param name='allowscriptaccess' value='always'></param>";
	str+="<param name='wmode' value='opaque'></param>";
	str+="<embed src='"+vStr+"&autoplay="+autoplay+"&loop="+loop+"' type='application/x-shockwave-flash' allowFullScreen='true' allowscriptaccess='always' wmode='opaque' width='"+width+"' height='"+height+"'></embed>";
	str+="</object>";
	return str;
}
function imgYouTube(vStr) {
	var imgSrc=vStr.substring(vStr.indexOf("/v/")+3);
	var pos=imgSrc.indexOf("?");
	if (pos>0) imgSrc=imgSrc.substring(0,pos);
	pos=imgSrc.indexOf("&");
	if (pos>0) imgSrc=imgSrc.substring(0,pos);
	pos=imgSrc.indexOf("#");
	if (pos>0) imgSrc=imgSrc.substring(0,pos);
	imgSrc="http://img.youtube.com/vi/"+imgSrc+"/0.jpg";
	return imgSrc;
}

/************** Image Viewer Class *****************/
function imgViewerClass(imgList, pos) {
	var obj=this;
	var autoPlayInterval;
	
	this.imgList=JSON.parse(imgList);
	this.pos=pos;
	this.next=(typeof this.imgList[this.pos+1]=="undefined"?0:this.pos+1);
	this.prev=(typeof this.imgList[this.pos-1]=="undefined"?this.imgList.length-1:this.pos-1);
	this.img=new Image();
	this.imgNext=new Image();
	this.imgPrev=new Image();
	this.imgWidth=0;
	this.imgHeight=0;
	imgList=null;
	
	this.callViewer=function() {
		var str;
		str="<table style='height:100%;width:100%;'><tr><td align='center'>";
			str+="<div id='ivOutterDiv' style='width:500px;height:500px;' onMouseover='imgViewer.showControl();' onMouseout='imgViewer.hideControl();'>";
				str+="<div id='ivContentDiv' style='width:500px;height:500px;'></div>";
				str+="<div id='ivControlDiv'>";
					str+="<table style='width:100%;height:100%;'><tr>";
						str+="<td style='width:34px;'><div id='ivPrevBtn' onClick='imgViewer.showPrev();'></div></td>";
						str+="<td>&nbsp;</td>";
						str+="<td style='width:34px;'><div id='ivCloseBtn' class='removeBtn' style='position:absolute;top:0px;right:0px;' onClick='imgViewer.closeViewer();'></div><div id='ivNextBtn' onClick='imgViewer.showNext();'></div></td>";
					str+="</tr></table>";	
				str+="</div>";
			str+="</div>";
		str+="</td></tr></table>";
		if (!isIE || (isIE && IEVersion>=7)) document.getElementById('invisDiv').style.backgroundImage="url('/img/transfill_dark.png')";
		document.getElementById('invisDiv').innerHTML=str;
		document.getElementById('invisDiv').style.display="block";
	}
	
	this.closeViewer=function() {
		imgViewer=null;
		document.getElementById('invisDiv').innerHTML="";
		document.getElementById('invisDiv').style.display="none";
		document.getElementById('invisDiv').style.backgroundImage="url(about:blank)";
	}
	
	this.showControl=function() {
		if (isIE && IEVersion<9) {
			document.getElementById('ivControlDiv').filters.alpha.opacity=100;
		} else {
			document.getElementById('ivControlDiv').style.opacity=1;
		}
		clearInterval(this.autoPlayInterval);
	}
	
	this.hideControl=function() {
		if (isIE && IEVersion<9) {
			document.getElementById('ivControlDiv').filters.alpha.opacity=0;
		} else {
			document.getElementById('ivControlDiv').style.opacity=0;
		}
		this.autoPlayInterval=setInterval(this.autoPlay,6000);
	}
	
	this.morph=function(w, h, speed, fn) {
		if (document.getElementById('ivOutterDiv')) {
			document.getElementById('ivContentDiv').innerHTML="";
			var cw=document.getElementById('ivOutterDiv').clientWidth;
			var ch=document.getElementById('ivOutterDiv').clientHeight;
			var dw=w-cw;
			var dh=h-ch;
			var t=Math.abs(Math.round(dw/(20*speed)));
			var t2=Math.abs(Math.round(dh/(20*speed)));
			if (t<t2) t=t2;
			if (t==0) t=1;
			var interval;
			var i=0;
			
			this.morphProcess=function() {
				if (i<t && document.getElementById('ivOutterDiv')) {
					i++;
					document.getElementById('ivOutterDiv').style.width=cw+Math.round(dw/t*i)+"px";
					document.getElementById('ivOutterDiv').style.height=ch+Math.round(dh/t*i)+"px";
					document.getElementById('ivContentDiv').style.width=cw+Math.round(dw/t*i)+"px";
					document.getElementById('ivContentDiv').style.height=ch+Math.round(dh/t*i)+"px";
				} else {
					clearInterval(interval);
					if (fn) eval(fn);
				}
			}
			
			interval=setInterval(this.morphProcess,75);
		}
	}
	
	this.showNext=function() {
		this.pos=this.next;
		this.next=(typeof this.imgList[this.pos+1]=="undefined"?0:this.pos+1);
		this.prev=(typeof this.imgList[this.pos-1]=="undefined"?this.imgList.length-1:this.pos-1);
		
		this.display();
	}
	
	this.showPrev=function() {
		this.pos=this.prev;
		this.next=(typeof this.imgList[this.pos+1]=="undefined"?0:this.pos+1);
		this.prev=(typeof this.imgList[this.pos-1]=="undefined"?this.imgList.length-1:this.pos-1);
		
		this.display();
	}
	
	this.display=function() {
		var interval;
		var i=0;
		
		this.img.src=this.imgList[this.pos];
		if (this.next!=this.pos) this.imgNext.src=this.imgList[this.next];
		if (this.prev!=this.pos && this.prev!=this.next) this.imgPrev.src=this.imgList[this.prev];
		
		this.displayProcess=function() {
			obj.imgWidth=obj.img.width;
			obj.imgHeight=obj.img.height;
			if ((obj.imgWidth && obj.imgHeight) || !document.getElementById('ivOutterDiv')) {
				clearInterval(interval);
				if (obj.imgWidth>700) {
					var imgRatio=obj.imgWidth/obj.imgHeight;
					obj.imgWidth=700;
					obj.imgHeight=700/imgRatio;
				}
				obj.morph(obj.imgWidth,obj.imgHeight,0.75,"obj.fadeIn()");
			}
		}
		
		interval=setInterval(this.displayProcess,50);
	}
	
	this.fadeIn=function() {
		var interval;
		var i=0;
		
		if (document.getElementById('ivOutterDiv')) document.getElementById('ivContentDiv').innerHTML="<img id='ivImg' src='"+this.img.src+"' />";
		
		this.fadeInProcess=function() {
			if (i<10 && document.getElementById('ivOutterDiv')) {
				i++;
				if (isIE && IEVersion<9) {
					document.getElementById('ivImg').filters.alpha.opacity=(i/10)*100;
				} else {
					document.getElementById('ivImg').style.opacity=(i/10);
				}
			} else {
				clearInterval(interval);
			}
		}
		
		interval=setInterval(this.fadeInProcess,50);
	}
	
	this.autoPlay=function() {
		if (obj.imgList.length>1 && document.getElementById('ivOutterDiv')) {
			obj.showNext();
		} else {
			clearInterval(obj.autoPlayInterval);
		}
	}
	
	this.callViewer();
	this.display();
	this.autoPlayInterval=setInterval(this.autoPlay,6000);
}

/************** Smiley Class **************/
function smileyClass(textAreaID, divID, dalObj) { //textAreaID=>id of the textarea to be modified, dalObj=>don't need unless using with the DAL class.
	var obj=this;
	
	this.TA=textAreaID;
	this.divID=divID;
	this.dalObj=dalObj;
	this.smileySet=["{sml}", "{ohh}", "{hum}", "{heh}", "{hah}", "{err}", "{bla}", "{001}", "{002}", "{004}", "{005}", "{006}", "{007}", "{009}", "{010}", "{011}", "{012}", "{013}", "{014}", "{015}", "{018}", "{019}", "{020}", "{021}", "{022}", "{026}", "{027}", "{028}", "{030}", "{031}", "{034}", "{036}", "{037}", "{039}", "{040}", "{041}", "{042}", "{043}", "{044}", "{045}", "{046}", "{047}", "{048}", "{049}", "{050}", "{051}", "{053}"];
	for (var i=47; i<84; i++) {
		this.smileySet[i]="{0"+(i+7)+"}";
	}
	
	this.list=function() {
		var ele;
		var smiley;
		for (var i=0; i<this.smileySet.length; i++) {
			ele=document.createElement("img");
			ele.className="smileyImg";
			ele.src="/img/i/"+this.smileySet[i].substr(1,3)+".gif";
			ele.name=this.smileySet[i];
			ele.onclick=function() {
				obj.add(this.name);
			};
			document.getElementById(this.divID).appendChild(ele);
		}
	}
	
	this.add=function(smiley) {
		var ele=document.getElementById(this.TA);
		var scrollPos=ele.scrollTop;
		if (typeof ele.selectionStart!="undefined") {
			var ss=ele.selectionStart;
			if (isIE) {
				if (ss==0) ss=ele.value.length;
			}
			ele.value=ele.value.substr(0,ss)+smiley+ele.value.substr(ss);
		} else if (document.selection) {
			ele.focus();
			var selObj=document.selection.createRange();
			selObj.text=smiley;
		} else {
			ele.value=ele.value+smiley;
		}
		ele.scrollTop=scrollPos;
		if (this.dalObj) this.dalObj.inputTracker();
	}
	
	this.replace=function(str) {
		var matches=str.match(/\{[A-Za-z0-9]{1}[A-Za-z0-9]{1}[A-Za-z0-9]{1}\}/gi);
		if (matches!=null) {
			for (var i=0; i<matches.length; i++) {
				for (var j=0; j<this.smileySet.length; j++) {
					if (matches[i]==this.smileySet[j]) {
						str=str.replace(matches[i],'<img src=/img/i/'+matches[i].substr(1,3)+'.gif>');
						break;
					}
				}
			}
		}
		return str;
	}
}

/************** Drop A Line Class **************/
function dalClass(id, limit, type) {
	this.id=id;
	this.limit=limit;
	if (typeof(type)==="undefined") this.type="full";
	else this.type=type;
	this.submitLock=false;
	this.smiley=new smileyClass(this.id+"dalTA", this.id+"dalSmileyOutterDiv", this);
	
	this.smileyDivToggle=function() {
		if (document.getElementById(this.id+"dalSmileyOutterDiv").style.display=="none") {
			highZ++;
			document.getElementById(this.id+"dalSmileyBtn").setAttribute(jsClassExt,"dalSmileyBtnPress");
			document.getElementById(this.id+"dalSmileyBtnHitArea").setAttribute(jsClassExt,"dalSmileyBtnHitAreaPress");
			document.getElementById(this.id+"dalSmileyBtn").style.zIndex=highZ;
			document.getElementById(this.id+"dalSmileyOutterDiv").style.zIndex=highZ;
			document.getElementById(this.id+"dalSmileyOutterDiv").style.display="block";
			this.smiley.list();
		} else {
			if (this.type=="full") document.getElementById(this.id+"dalSmileyBtn").setAttribute(jsClassExt,"dalSmileyBtn");
			else document.getElementById(this.id+"dalSmileyBtn").setAttribute(jsClassExt,"cdalSmileyBtn");
			document.getElementById(this.id+"dalSmileyBtnHitArea").setAttribute(jsClassExt,"dalSmileyBtnHitArea");
			document.getElementById(this.id+"dalSmileyOutterDiv").style.display="none";
			document.getElementById(this.id+"dalSmileyOutterDiv").innerHTML="";
		}
	}
	
	this.smileyDivClose=function() {
		if (this.type=="full") document.getElementById(this.id+"dalSmileyBtn").setAttribute(jsClassExt,"dalSmileyBtn");
		else document.getElementById(this.id+"dalSmileyBtn").setAttribute(jsClassExt,"cdalSmileyBtn");
		document.getElementById(this.id+"dalSmileyBtnHitArea").setAttribute(jsClassExt,"dalSmileyBtnHitArea");
		document.getElementById(this.id+"dalSmileyOutterDiv").style.display="none";
		document.getElementById(this.id+"dalSmileyOutterDiv").innerHTML="";
	}
	
	this.inputTracker=function() {
		var charCnt=document.getElementById(this.id+"dalTA").value.length;
		if (this.limit-charCnt<0) {
			this.submitLock=true;
			document.getElementById(this.id+"dalCntDiv").innerHTML="<span style='color:#ff0000;'>"+(this.limit-charCnt)+"</span>";
		} else {
			document.getElementById(this.id+"dalCntDiv").innerHTML=this.limit-charCnt;	
			this.submitLock=false;
		}
	}
	
	this.show=function() {
		document.getElementById(this.id+"dalMaskDiv").style.display="none";
		document.getElementById(this.id+"dalContentDiv").style.display="block";
	}
	
	this.cancel=function() {
		if (this.type=="full") {
			document.getElementById(this.id+"dalContentDiv").style.display="none";
			document.getElementById(this.id+"dalMaskDiv").style.display="block";
		}
		document.getElementById(this.id+"dalTA").value="";
		document.getElementById(this.id+"dalCntDiv").innerHTML=this.limit;
		document.getElementById(this.id+"dalErrorDiv").innerHTML="";
		this.submitLock=false;
		this.smileyDivClose();
	}
}

/************** Menu Functions **************/
// General
function menuOpenHiddenDiv(id) {
	for (i in timeoutArray) {
		document.getElementById(i+"OptionsDiv").setAttribute(jsClassExt,"menuMultiOptionDiv");
		document.getElementById(i+"ArrowDiv").style.backgroundPosition="0px -50px";
		document.getElementById(i+"HiddenOutterDiv").style.display="none";
	}
	clearTimeout (timeoutArray[id]);
	highZ++;
	document.getElementById(id+"OptionsDiv").setAttribute(jsClassExt,"menuMultiOptionDivHover");
	document.getElementById(id+"OptionsDiv").style.zIndex=highZ;
	document.getElementById(id+"ArrowDiv").style.backgroundPosition="-12px -50px";
	document.getElementById(id+"HiddenOutterDiv").style.display="block";
}
function menuCloseHiddenDiv(id) {
	menuCloseProcess=function(id) {
		document.getElementById(id+"OptionsDiv").setAttribute(jsClassExt,"menuMultiOptionDiv");
		document.getElementById(id+"ArrowDiv").style.backgroundPosition="0px -50px";
		document.getElementById(id+"HiddenOutterDiv").style.display="none";
	}
	timeoutArray[id]=setTimeout("try {menuCloseProcess('"+id+"')} catch(ex) {}",((id=="si" && document.getElementById("siEmailInput").value!=="")?5000:300));
}

// Search
function menuSrhFocus() {
	document.getElementById("srhBarDiv").setAttribute(jsClassExt,"srhBarDivFocus");
}
function menuSrhBlur() {
	document.getElementById("srhBarDiv").setAttribute(jsClassExt,"srhBarDiv");
}
function menuSrhSubmit() {
	var input=trim(document.getElementById('srhBarInput').value.trimmark());
	if (input==="") {
		loadPage("/search/s.php","/search/s.php");
	} else {
		loadPage("/search/s.php","/search/s.php?srh="+encodeURIComponent(input));
	}
}
function menuSrhSubmitE13(e) {
	var key=(isIE?window.event.keyCode:e.which);
	if (key==13) menuSrhSubmit();
}

// Sign in / out
function siSubmit(sourceId) {
	var email=trim(document.getElementById('si'+sourceId+'EmailInput').value);
	var password=trim(document.getElementById('si'+sourceId+'PWInput').value);
	var saveCookie=(document.getElementById('si'+sourceId+'CookieCB').checked?1:0);
	
	document.getElementById('si'+sourceId+'ErrorDiv').innerHTML="";
	if (email=="") document.getElementById('si'+sourceId+'ErrorDiv').innerHTML=jsMsg[0];
	else if (password=="") document.getElementById('si'+sourceId+'ErrorDiv').innerHTML=jsMsg[1];
	else if (!emailValidationPattern.test(email)) document.getElementById('si'+sourceId+'ErrorDiv').innerHTML=jsMsg[2];
	else {
		email=encodeURIComponent(email);
		password=encodeURIComponent(password);
		var params="email="+email+"&password="+password+"&saveCookie="+saveCookie;
		ajaxRequest("/si/process/si_process.php",params,1000,function(rs) {
			try {
				rs=JSON.parse(rs);
				//top.window.location.href=WEBSITE+"/p/p.php?uid="+rs.uid;
				top.window.location.reload();
			} catch(ex) {
				document.getElementById('si'+sourceId+'ErrorDiv').innerHTML=rs;
				document.getElementById('si'+sourceId+'EmailInput').style.backgroundColor="#ffcccc";
				document.getElementById('si'+sourceId+'PWInput').style.backgroundColor="#ffcccc";
			}
		});
	}
}
function siSubmitE13(sourceId, e) {
     var key=(isIE?window.event.keyCode:e.which);
     if (key==13) siSubmit(sourceId);
}
function si_popup() {
	loadMask(260,323,jsMsg[4]);
	ajaxRequest("/si/si.php","",500,function(rText) {
		document.getElementById("maskContentDiv").innerHTML=rText;
	});
}
function signOut() {
	ajaxRequest("/si/so.php","",500,function(rText) {
		if (rText=="pass") {
			if (document.cookie.indexOf('lp_cookie')==-1) {
				top.window.location.href=WEBSITE;
			} else {
				setTimeout("top.window.location.href=WEBSITE",1000);
			}
		} else {
			loadMask(400,50);
			document.getElementById("maskContentDiv").innerHTML="<table class='fillerTable'><tr><td class='error'>"+rText+"</td></tr></table>";
		}
	});
}
function passwordRetrieval () {
	loadMask(500,160);
	ajaxRequest("/si/pwr.php","",500,function(rText) {
		document.getElementById("maskContentDiv").innerHTML=rText;
	});
	
}
function pwrSubmit(errmsg1, errmsg2) {
	var email_validation_pattern=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	var email=document.getElementById('pwrEmailInput').value.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
	if (email==""){
		$("#pwrEmailInput").css("border-color","red");
		document.getElementById('pwrErrorDiv').innerHTML=errmsg1;
	} else if (!email_validation_pattern.test(email)){
		$("#pwrEmailInput").css("border-color","red");
		document.getElementById('pwrErrorDiv').innerHTML=errmsg2;
	} else {
		document.getElementById('pwrSubmitBtn').disabled="disabled";
		email=trim(email);
		var params="email="+email;
		ajaxRequest("/si/pwrp.php",params,10000,function(rText) {
			unlockAjax();
			if (rText=="pass") {
				document.getElementById('pwrPreDiv').style.display="none";
				document.getElementById('pwrPostDiv').style.display="block";
			} else {
				$("#pwrEmailInput").css("border-color","#333");
				document.getElementById('pwrErrorDiv').innerHTML=rText;
				document.getElementById('pwrSubmitBtn').disabled="";
			}
		});
	}
}
/*
 * @description google、yahoo、fb按鈕點擊觸發的函式
 * @param {String} url 連結處理的網址
 */
function extraacc(url){
	if(extraacc.prototype.firstload === false) return false;
	extraacc.prototype.firstload=false;
	var to_url = $('#ftrCurrentUrl').html();
	if(to_url != ''){
		location.href=url+'?to_url='+to_url;
	}else{
		location.href=url;
	}
}
extraacc.prototype.firstload=true;
/*
 * @description 註冊函式
 * @param {String} url 連結處理的網址
 */
function signUp(title) {
	loadMask(550,450,title);
	signUp_fn_ck();
}
/*
 * @description 註冊函式
 * @param {String} url 連結處理的網址
 * @requires signUp
 */
function signUp_fn_ck() {	
	dynamicJsCssLoader("/members/js/select_account.js?"+GVERSION,"js",function() {
		$("#maskContentDiv").load("/members/select_account.php");
	},1);
}

/************** Footer Functions **************/
function ftrToggleHiddenDiv(id) {
	if (document.getElementById(id+"HiddenOutterDiv").style.display=="none") {
		highZ++;
		document.getElementById(id+"OptionsDiv").setAttribute(jsClassExt,"ftrMultiOptionDivHover");
		document.getElementById(id+"OptionsDiv").style.zIndex=highZ;
		document.getElementById(id+"HiddenOutterDiv").style.display="block";
	} else {
		document.getElementById(id+"OptionsDiv").setAttribute(jsClassExt,"ftrMultiOptionDiv");
		document.getElementById(id+"HiddenOutterDiv").style.display="none";
	}
}
function langChange(lang) {
	ajaxRequest("/lang/process/change.php","language="+lang,500,function(rText) {
		window.location.reload();
	});
}
function recommendPage(title) {
	var recPageSubmitLock=false;
	loadMask(500,220,title);
	var tmp=window.location.href.split("\#");
	if (tmp[1]) var url=WEBSITE+tmp[1];
	else var url=tmp[0];
	var params="uid="+usrid+"&url="+encodeURIComponent(url);
	ajaxRequest("/notes/recommend_page.php",params,500,function(rs) {
		try {
			rs=JSON.parse(rs);
			document.getElementById("maskContentDiv").innerHTML=rs.out;
		} catch(ex) {
			document.getElementById("maskContentDiv").innerHTML="<table class='fillerTable'><tr><td class='error'>"+rs+"</td></tr></table>";
		}
	});
	
	recommendPageSubmit=function() {
		if (recPageSubmitLock) return false;
		recPageSubmitLock=true;
		var mid=url.replace(WEBSITE,"");
		var mtype="hash";
		var gid=document.getElementById("recGroupSelect").value;
		var comment=trim(document.getElementById('recCommentInput').value.trimmark());
		var params2="uid="+usrid+"&mid="+encodeURIComponent(mid)+"&mtype="+mtype+"&gid="+gid+"&comment="+encodeURIComponent(comment);
		ajaxRequest("/notes/process/add_request.php",params2,500,function(rs) {
			try {
				rs=JSON.parse(rs);
				loadMask(400,50);
				document.getElementById("maskContentDiv").innerHTML="<table class='fillerTable'><tr><td><span class='aGreen'>"+rs.out+"</span></td></tr></table>";
			} catch(ex) {
				document.getElementById("recErrorDiv").innerHTML=rs;
			}
			recPageSubmitLock=false;
		});
	}
}

/************** Sticky Functions **************/
// Notifications
function toggleNotificationDiv() {
	if (document.getElementById("noteHiddenDiv").style.display=="none") {
		if (usrid) {
			if (document.getElementById("jplayerHiddenDiv").style.display=="block") {
				document.getElementById("jplayerDiv").setAttribute(jsClassExt,"jplayerDiv");
				document.getElementById("jplayerHiddenDiv").style.display="none";
			}
			showLoading("noteHiddenDiv");
			document.getElementById("notificationDiv").setAttribute(jsClassExt,"notificationDivHover");
			document.getElementById("noteHiddenDiv").style.display="block";
			document.getElementById("noteNewCntSpan").innerHTML="";
			loadNotification(noteTab);
		} else {
			si_popup();
		}
	} else {
		document.getElementById("notificationDiv").setAttribute(jsClassExt,"notificationDiv");
		document.getElementById("noteHiddenDiv").style.display="none";
		document.getElementById("noteHiddenDiv").innerHTML="";
	}
}
function loadNotification(tab) {
	if (usrid) {
		noteTab=tab;
		switch (noteTab) {
			case "M":
				var file="/notes/mlist.php";
			break;
			case "T":
				var file="/notes/tlist.php";
			break;
		}
		ajaxRequest(file,"",1000,function(rs) {
			document.getElementById("noteHiddenDiv").innerHTML=rs;
		});
	} else {
		document.getElementById("noteHiddenDiv").innerHTML="<table class='fillerTable'><tr><td class='error'>"+jsMsg[4]+"</td></tr></table>";
	}
}
function noteLoadPage(pc) {
	showLoading("noteHiddenDiv");
	switch (noteTab) {
		case "M":
			var file="/notes/mlist.php";
		break;
		case "T":
			var file="/notes/tlist.php";
		break;
	}
	ajaxRequest(file,"pc="+pc,0,function(rs) {
		document.getElementById("noteHiddenDiv").innerHTML=rs;
	});
}
function noteLoadTab(tab) {
	noteTab=tab;
	loadNotification(noteTab);
}
function noteCounterUpdate() {
	if (document.getElementById("noteNewCntSpan").innerHTML=="") {
		document.getElementById("noteNewCntSpan").innerHTML="(1)";
	} else {
		var str=document.getElementById("noteNewCntSpan").innerHTML;
		document.getElementById("noteNewCntSpan").innerHTML="("+(parseInt(str.substring(1,str.length-1))+1)+")";
	}
}
function showNotificationMenu() {
	document.getElementById("noteMenuDiv").setAttribute(jsClassExt,"noteMenuDivHover");
}
function hideNotificationMenu() {
	document.getElementById("noteMenuDiv").setAttribute(jsClassExt,"noteMenuDiv");
}

/* Chat Class */
function chatClass() {
	this.chatV={};
	this.onbeforeunloadevt=false;
    this.conning=false;
	/*圖片路徑*/
	this.chatV.thumbImgPath="http://fs.lifeplat.com/upload_portrait_thumb/"
	this.chatV.green="/img/chat/bullet_green.png"; //狀況圖示: 線上
	this.chatV.grey="/img/chat/bullet_grey.png";	//狀況圖示: 離開

	/*設定*/
	this.chatV.online=1; //是否上線
	this.chatV.onlineProc=false;  //上、下線是否處理中
	this.chatV.barTxtLimit=10; //show message bar的字串長度限制
	this.chatV.maxtxtlength=200; //文字輸入限制字數
	this.chatV.key13=false;
	this.chatV.title=document.title;
	this.chatV.focusStus=1; //頁面是否被focus
	this.chatV.notmainpage=0; //同帳號開多分頁時，判斷是否為非主要發話分頁
	this.chatV.stophis=false; //停止歷史對話
	this.chatV.ifrec=true;    
	
	this.IMCCurrentID="";
	this.IMCInstanceCnt=0;
	this.IMCDownShiftCnt=0;
	this.IMCShiftOffSet=16;
	this.IMCUpShiftControl=false;
	this.IMCDownShiftControl=false;
	this.IMCWindowState=0; //0 hide, 1 bar, 2 window
	this.IMCAnimationLock=false;
	this.IMCList=[];
	this.IMCListTop=0;
	this.IMCListBot=0;
	this.smilecls=new smileyClass("","");
	$(function(){	
		//if($.browser.safari && !/chrome/.test(navigator.userAgent.toLowerCase()) || $.browser.opera){
		if($.browser.opera){			
			chatCls.chatV.ifrec=false;
		}
		$(window).bind("blur",function(event){		
			chatCls.chatV.focusStus=0;
			return false;
		}).bind("focus",function(event){
			chatCls.chatV.focusStus=1;
			document.title=chatCls.chatV.title;
			try{			
				clearInterval(chatCls.chatV.titleInterval);
			}catch(e){}		
			return false;
		});		
		
		//chrome使用
		if(chatCls.chatV.ifrec){			
			window.onbeforeunload=function(){		
				if(chatCls.onbeforeunloadevt) return;
				chatCls.onbeforeunloadevt=true;
				if(chatCls.IMCCurrentID != ""){
					$("#fcpIMCContent").html($("#IMCHID"+chatCls.IMCCurrentID).val());
				}
				if(chatCls.IMCAnimationLock){//動畫中				
					clearInterval(chatCls.chatV.animinterval);
					chatCls.IMCAnimationLock=false;
					var params=chatCls.chatV.chathispos;				
				}else{
					var params={
							uid:usrid,
							IMCCurrentID:chatCls.IMCCurrentID,
							IMCInstanceCnt:chatCls.IMCInstanceCnt,
							IMCDownShiftCnt:chatCls.IMCDownShiftCnt,
							IMCShiftOffSet:chatCls.IMCShiftOffSet,
							IMCUpShiftControl:chatCls.IMCUpShiftControl,
							IMCDownShiftControl:chatCls.IMCDownShiftControl,
							IMCWindowState:chatCls.IMCWindowState,					
							IMCList:chatCls.IMCList.toString(),
							IMCListTop:chatCls.IMCListTop,
							IMCListBot:chatCls.IMCListBot,
							contrec:$("#chatrecdiv").html()
					};	
				}			
							
				$.ajax({
					type:"POST",
					url:'/chat/chat_rec_set.php',
					data:params,
					cache:false, 
					async:false, //同步請求鎖住瀏覽器
					timeout:5000,
					success: function(data){},
					error: function(xhr){}
				});		
			};
			
		}	
		//設定
		$("#dis_helpdiv").hover(
		  function () {
			  $("#chat_helpdiv").toggle();
		  },
		  function () {
			  $("#chat_helpdiv").toggle();
		  }
		);
		$.fn.extend({
			strips:function(){
				var a=$(this).val().replace(/^[\s\xA0]+|[\s\xA0]+$/g, "").replace(/(&nbsp;)+/g,"");
				$(this).val(a);	
				return a;
			},
			stripSpace:function(){
				var a=$(this).val().replace(/[\s\xA0]+/g, "");
				$(this).val(a);
				return a;
			}
		});
	
		
		function isObject(targetID){ 
			var isFound = false; 
			var el = document.getElementById(targetID); 
			if(el && (el.nodeName === "OBJECT" || el.nodeName === "EMBED")){ 
				isFound = true; 
			} 
			return isFound; 
		}
		if(!isObject("chatswf")){
			//swfobject.removeSWF("chatswf");
			var flashvars = {"uid":usrid,"cache":1}; 
			var params={};
			var attributes = {}; 
			params.allowscriptaccess = "sameDoamin"; //sameDoamin always	
			if ($.browser.msie && $.browser.version.toString()=="7.0"){		
				var bversion=GVERSION;//new Date().getTime();	110629v2
			}else{
				var bversion=GVERSION; //GVERSION "110222v02";
			}
			swfobject.embedSWF("/as/chat_f_v3_new.swf?"+bversion, "chatswf", "0", "0", "9.0.0", "/as/assets/expressInstall.swf",flashvars,params,attributes,callbackFn);
		}
		//崁入swf時回傳成功或失敗的函式
		function callbackFn(e){	
			if(e.success == false){				
				$("#chatDiv").click(function(){
					if($("#frichatdiv").css("display") == 'none'){
						document.getElementById("chatDiv").setAttribute(jsClassExt,"chatDivHover");
						$("#frichatdiv").css("display","block");
						$("#frilist").html("<div onclick='window.open(\"http://www.adobe.com/go/getflashplayer\");' style='color:red;cursor:pointer;margin:0px;height:100%;background-image:url(/img/chat/no_flash.jpg);'><div style='font-size:15px;padding-top:10px;'>"+jsMsg["chat"][4]+"</div></div>");
					}else{		
						document.getElementById("chatDiv").setAttribute(jsClassExt,"chatDiv");
						$("#frichatdiv").css("display","none");
						$("#frilist").html("");						
					}
				});			
			}
		}
	});
	
	this.stripslashes=function(str) {
	    return (str + '').replace(/\\(.?)/g, function (s, n1) {
	        switch (n1) {
	        case '\\':
	            return '\\';
	        case '0':
	            return '\u0000';
	        case '':
	            return '';
	        default:
	            return n1;
	        }
	    });
	};
	//由javascript呼叫AS3的函式用
	this.flashMovie=function(movieName){
		if($.browser.msie){
			return window[movieName];
		}else{
			return document[movieName];
		}
	};
	//當AS3跟red5連線後AS3呼叫的函式
	this.chat_addClickEvent=function(online){		
		//有歷史對話紀錄	
		if(this.chatV.ifrec){
			$.ajax({
				type:"POST",
				url:'/chat/chat_rec_get.php',
				data:{uid:usrid},
				cache:false, 
				timeout:10000,
				dataType:"json",
				success: function(data){
					//data=true或還沒觸發Incomming函式
					if(data && typeof(data.error) == "undefined" && !chatCls.chatV.stophis  && data.contrec != "null"){						
						data.contrec=chatCls.stripslashes(data.contrec);
						$("#chatrecdiv").html(data.contrec);			
						chatCls.IMCCurrentID=data.IMCCurrentID;					
						chatCls.IMCInstanceCnt=(isNaN(parseInt(data.IMCInstanceCnt)))? 0:parseInt(data.IMCInstanceCnt);
						chatCls.IMCDownShiftCnt=(isNaN(parseInt(data.IMCDownShiftCnt)))? 0:parseInt(data.IMCDownShiftCnt);
						chatCls.IMCShiftOffSet=(isNaN(parseInt(data.IMCShiftOffSet)))? 0:parseInt(data.IMCShiftOffSet);
						chatCls.IMCUpShiftControl=(data.IMCUpShiftControl === 'true');
						chatCls.IMCDownShiftControl=(data.IMCDownShiftControl === 'true');
						chatCls.IMCWindowState=(isNaN(parseInt(data.IMCWindowState)))? 0:parseInt(data.IMCWindowState);
						if(chatCls.IMCWindowState == 0 && $.browser.msie){
							$("#chatrecdiv").css("display","none");
						}			
						if(typeof(data.IMCList) != "undefined"){					
							IMCList=data.IMCList.toString().split(",");
							//IMCList=data.IMCList;
						}					
						chatCls.IMCListTop=(isNaN(parseInt(data.IMCListTop)))? 0:parseInt(data.IMCListTop);
						chatCls.IMCListBot=(isNaN(parseInt(data.IMCListBot)))? 0:parseInt(data.IMCListBot);
					}
				},
				error: function(xhr){}
			});
		}
		online =parseInt(online);
		if(online == 0){
			this.chatV.online=0;
			$("#fcpIMStatus").attr({"class":"fcpIMOffline20","title":jsMsg["chat"][10]});
		}else{
			$("#fcpIMStatus").attr({"class":"fcpIMOnline20","title":jsMsg["chat"][9]});
		}
		//當red5連線後，新增click事件
		
		$("#chatDiv").css({"display":"block","color":"#333"}).bind("click",chatCls.chat_Start);		//#999900
		//alert("chat_addClickEvent");
		//建立切換上、下線checkbox觸發事件
		$("#fcpIMStatus").bind("click",function(){		
			if(chatCls.chatV.onlineProc == false){
				chatCls.chatV.onlineProc = true; //處理中			
				if(chatCls.chatV.online == 1){
					//換成離線
					chatCls.chatV.online = 0;
					chatCls.flashMovie("chatswf").connOnOff(0);
				}else{
					//換成上線
					chatCls.chatV.online = 1;
					chatCls.flashMovie("chatswf").connOnOff(1);
				}
			}
		});	
	};
	this.connOnOffResponder=function(str){
		if(str == "ok"){
			if(this.chatV.online == 1){
				$("#fcpIMStatus").attr({"class":"fcpIMOnline20","title":jsMsg["chat"][9]});
			}else{
				$("#fcpIMStatus").attr({"class":"fcpIMOffline20","title":jsMsg["chat"][10]});
			}		
		}else{
			alert("Please try again.");
		}
		this.chatV.onlineProc = false; //解除處理狀態
	};
	
	//由AS3呼叫的函式，當發生錯誤移除聊天室框和swf
	/*this.chat_removeChat=function(){
		//alert(msg);
		//$("#chatswf").remove();
	};*/
	
	//as3呼叫的javascript顯示朋友列表函式
	this.chat_showOnLineFriends=function(map){
		chatCls.reconning=false;
		var len=0;
		var tmptalk="";
		for(var s in map){	
			len++;	
			if(map[s][1] == ""){
				switch(map[s][2]){
					case "M":
						var pic="/img/s_no_portrait.jpg";
						break;
					case "F":
						var pic="/img/s_no_portrait_f.jpg";
						break;
					case "O":
						var pic="/img/s_no_portrait_o.jpg";
						break;
					default:
						var pic="/img/s_no_portrait_n.jpg";
						break;
				}			
			}else{			
				var pic=this.chatV.thumbImgPath+map[s][1];
			}	
			tmptalk+="<div class='chat_list'><a onclick='javascript:chatCls.IMCIncoming(\""+s+"\",\""+map[s][0]+"\",\""+pic+"\",1);'><img class='chat_album' src='"+pic+"' align='absmiddle' onclick='loadPage(\"/p/p.php\",\"/p/p.php?uid="+s+"\");' /><span class='chat_name'>"+map[s][0]+"</span></a></div>";
		}	
		if(len > 0){
			tmptalk="<div id='chat_album'>"+tmptalk+"</div>";		
			$("#frilist").html(tmptalk);
			
		}else{		
			$("#frilist").html("<div style='text-align:center;font-size:13px;color:red;'>"+jsMsg["chat"][5]+"</div>");
		}
		$("#frinum span").text(len);
	};
	
	//as3呼叫的javascript顯示朋友列表錯誤函式
	this.showOnLineFriendsError=function(msg){	
		$("#frilist").html("<div style='text-align:center;font-size:13px;color:red;'>"+msg+"</div>");
	};
	
	//點擊聊天室所呼叫的函示
	this.chat_Start=function(){	
		var div=$("#frichatdiv");		
		if(div.css("display") == 'none'){			
			div.css("display","block");
			document.getElementById("chatDiv").setAttribute(jsClassExt,"chatDivHover");
			if(typeof(chatCls.reconning) == 'undefined' || chatCls.reconning === false){
				$("#frilist").html("<div style='text-align:center;height:340px;line-height:340px;'><img src='/img/chat/ajax-loader.gif' style='margin-top:10px;'/></div>");		//
				//呼叫列出線上朋友列表 -> as3 -> java ->as3 -> javascript
				//呼叫as3的getOnLineFriends函式
				chatCls.flashMovie("chatswf").getOnLineFriends();
			}	
		}else{	
			div.css("display","none");
			document.getElementById("chatDiv").setAttribute(jsClassExt,"chatDiv");
			if(typeof(chatCls.reconning) == 'undefined' || chatCls.reconning === false){
				$("#frilist").html("");
			}
		}
		
	};
	this.chat_reconnClick=function(){
		chatCls.reconning=true;        
		$("#frilist").html("<div style='text-align:center;height:340px;line-height:340px;'>"+jsMsg["chat"][13]+"<img src='/img/chat/ajax-loader.gif' style='margin-top:10px;'/></div>");		//
		//呼叫列出線上朋友列表 -> as3 -> java ->as3 -> javascript
		//呼叫as3的getOnLineFriends函式
		chatCls.flashMovie("chatswf").setReconn(1);
		chatCls.flashMovie("chatswf").chkLogin();	
	};
    this.chat_connsts=function(chat_conn){
        if(chat_conn == '1'){
            chatCls.conning=true;
        }else{
            chatCls.conning=false;
        }       
    };
	//點擊聊天室所呼叫的函示
	this.chat_reconn=function(chat_sts){
		switch(chat_sts){
		case "NetConnection.Connect.Closed":
			var str=jsMsg["chat"][14];
			break;
		case "NetConnection.Connect.Failed":
			var str=jsMsg["chat"][15];
			break;
		case "NetConnection.Connect.Rejected":
			var str=jsMsg["chat"][16];
			break;
		case "ioError":
			var str=jsMsg["chat"][17];
			break;
		default:
			var str=jsMsg["chat"][18];
			break;
		}
		chatCls.reconning=false;
        chatCls.conning=false;
		$("#frilist").html("<div style='text-align:center;font-size:13px;color:red;'>"+str+" <input type='button' style='' onclick='javascript:chatCls.chat_reconnClick();' value='"+jsMsg["chat"][19]+"'/></div>");
	};
	this.IMCSwtich=function(IMC_ID) {	
		if ($("#IMC"+this.IMCCurrentID).length > 0) {
			$("#IMC"+this.IMCCurrentID).attr("class","fcpIMCLeft1");
		}
		$("#IMC"+IMC_ID).attr("class","fcpIMCLeft2");
		this.IMCCurrentID=IMC_ID;
		if(typeof($("#IMC"+IMC_ID).data("msg")) == "undefined"){
			var hidtxt=$("#IMCHID"+IMC_ID).val();
			$("#fcpIMCContent").html(hidtxt);
			$("#IMC"+IMC_ID).data("msg",hidtxt);
		}
		$("#fcpIMCContent").html($("#IMC"+IMC_ID).data("msg")).scrollTop($('#fcpIMCContent')[0].scrollHeight);
	};
	this.IMCClear=function() {
		$("#IMC"+this.IMCCurrentID).data("msg","");
		$("#IMCHID"+this.IMCCurrentID).val("");
		$("#fcpIMCContent").html("");
	};
	this.IMCClose=function(IMC_ID) {
		if ($("#IMC"+IMC_ID).length > 0) {		
			if(IMC_ID == this.IMCCurrentID){
				var num = $(".fcpIMCLeftFront").length;
				var a=0;
				var id="";
				$(".fcpIMCLeftFront").each(function(i){
					id=$(this).parent().attr("id");
					if(id == "IMC"+IMC_ID){
						a=i;
						return false;
					}				
				});
				if(a > 0){
					var id= $("div[class='fcpIMCLeftFront']").eq(a-1).parent().attr("id").replace("IMC","");
					this.IMCSwtich(id);
				}else if(num-1 > a){
					var id= $("div[class='fcpIMCLeftFront']").eq(a+1).parent().attr("id").replace("IMC","");
					this.IMCSwtich(id);
				}else{
					this.IMCClear();
				}
			}		
			
			var pos=0;
			while (this.IMCList[pos]!=IMC_ID && pos<this.IMCInstanceCnt) {
				pos++;
			}
			for (var i=pos; i<=this.IMCInstanceCnt; i++) {
				this.IMCList[i]=this.IMCList[i+1];
			}
			this.IMCList.length--;
			if (this.IMCListBot==1) this.IMCListTop--;
			if (this.IMCListBot==this.IMCInstanceCnt) this.IMCListBot--;		
			$("#IMC"+IMC_ID).remove();
			this.IMCInstanceCnt--;	
			if (this.IMCInstanceCnt<=(10+this.IMCDownShiftCnt)) {
				this.IMCDownShiftControl=false;
				$("#fcpIMCNevBtnDown").attr("class","fcpIMCNevBtnDown1");
				if (this.IMCDownShiftCnt>0) {
					this.IMCUpShiftControl=true;
					this.IMCShiftUp();
				}
			} else {
				this.IMCUnreadCounterUpdate();
			}
		}
		if($(".fcpIMCLeftFront").length == 0){
			this.IMCCurrentID="";
		}
	};
	/*
	type=0: 其他人送訊息過來
	type=1: 點選人物
	*/
	this.IMCIncoming=function(suid,uname,pic,type) {	
		if (type==1 && this.IMCAnimationLock === true) return false;	
		this.chatV.stophis=true;//設為true,不載入get回來的歷史對話
		if($("#chatrecdiv").css("display") == "none"){
			$("#chatrecdiv").css("display","block");		
		}
		
		if($("#fcpIMCList").length > 0){
			if($(".fcpIMCLeftFront").length == 0){			
				this.IMCCurrentID=suid;
				var cls="fcpIMCLeft2";
			}else{
				var cls="fcpIMCLeft3";
			}
			var num=arguments.length;
			//限制在bar上顯示的字數
			if(num >= 6){
				var msg=arguments[4];
				var who=arguments[5];			
				if(msg.length > this.chatV.barTxtLimit){
					msg=msg.substring(0,this.chatV.barTxtLimit);				
				}
			}
			if(num >= 6 && who ==1 && $("#IMC"+suid).length <= 0){			
				this.chatV.notmainpage=1;
				return false;
			}
			var newdiv=0;	
			
			if($("#IMC"+suid).length <= 0){
				//div不存在，建立新div			
				$("<div></div>").attr({"id":"IMC"+suid,"class":cls})
				.html("<div class='fcpIMCLeftFrontImg'><input type='hidden' id='IMCHID"+suid+"' value='' /><img src='"+pic+"' style='width:20px;height:25px;padding-top:1px;' onclick='loadPage(\"/p/p.php\",\"/p/p.php?uid="+suid+"\");'/></div><div class='fcpIMCLeftFront' onClick='chatCls.IMCSwtich(\""+suid+"\")'>"+uname+"</div>"+"<div class='fcpIMCDelBtn' onClick='chatCls.IMCClose(\""+suid+"\")'></div>")
				.appendTo($("#fcpIMCList")).data("msg","");
				
				this.IMCInstanceCnt++;
				this.IMCList[this.IMCInstanceCnt]=suid;
				newdiv=1;
			}	
			
			/*
			 * type=0: chat_showmsg 訊息顯示函式觸發
			 * type=1: 點選朋友列表的名單
			 */
			 var isSwitch=false;	//防止IMCSwtich被呼叫第二次
			if (this.IMCWindowState==0) {
				if (type==0) {
					if(who != 1){
						this.IMCWindowState=1;
						$("#fcpIMCBar").attr("class","fcpIMCBar2");
						$("#fcpIMCBarFront").html(uname+": "+msg);
						$("#fcpIMCBar").css("display","block");
					}
				} else {
					this.IMCWindowState=2;
					isSwitch=true;
					this.IMCSwtich(suid);				
					$("#fcpIMCWindow").css("display","block");
				}			
			} else if (this.IMCWindowState==1) {
				if (type==0) {
					if(who != 1){
						$("#fcpIMCBar").attr("class","fcpIMCBar2");
						$("#fcpIMCBarFront").html(uname+": "+msg);
					}					
				} else {
					this.IMCWindowState=2;
					isSwitch=true;
					this.IMCSwtich(suid);
					$("#fcpIMCBar").css("display","none");
					$("#fcpIMCWindow").css("display","block");
				}
			} else if(this.IMCWindowState==2 && type==1){
				//已打開大window且是由點選人物觸發
				//focus到該使用者，訊息顯示不用focus
				isSwitch=true;
				this.IMCSwtich(suid);
			}
			
			if (type==0) {
				if (newdiv == 1) {
					if (this.IMCInstanceCnt>(10+this.IMCDownShiftCnt)) {
						this.IMCDownShiftControl=true;
						$("#fcpIMCNevBtnDown").attr("class","fcpIMCNevBtnDown3");
					} else {
						if (this.IMCListTop==0) this.IMCListTop++;
						this.IMCListBot++;
					}
				} else {
					this.IMCIncomingMsg(suid);
				}
			} else {
				if (newdiv == 1) {
					if (this.IMCInstanceCnt>(10+this.IMCDownShiftCnt)) {
						this.animhisrecfunc();					
						var shiftMagnitude=this.IMCInstanceCnt-this.IMCListBot;
						this.IMCListBot=this.IMCInstanceCnt;
						this.IMCListTop=this.IMCListTop+shiftMagnitude;
						this.IMCDownShiftCnt=this.IMCDownShiftCnt+shiftMagnitude;
						this.IMCDownShiftControl=false;
						this.IMCUpShiftControl=true;
						$("#fcpIMCNevBtnDown").attr("class","fcpIMCNevBtnDown1");
						$("#fcpIMCNevBtnUp").attr("class","fcpIMCNevBtnUp2");
						this.IMCShiftAnimation(-1,shiftMagnitude,0.5);
					} else {
						if (this.IMCListTop==0) this.IMCListTop++;
						this.IMCListBot++;
					}
				} else {
					this.IMCShiftToTarget(suid);
					//IMCSwtich(IMC_ID);
					if(!isSwitch){this.IMCSwtich(suid)};
				}	
			}
		}
	};
	
	//聊天訊息顯示函式
	this.chat_showmsg=function(suid,name,pic,g,msg,who){		
		if(who != 1){
			if(this.chatV.focusStus == 0){ //頁面沒有被focus				
				try{
					clearInterval(this.chatV.titleInterval);			
					this.changeTitleTxt(name+jsMsg["chat"][7]);					
				}catch(e){
					alert(e.message);
				}			
			}
			//在hide和bar的情況下鈴聲才會響
			if(this.IMCWindowState == 0 || this.IMCWindowState == 1){
				chatCls.flashMovie("chatswf").ringPlay();
			}			
		}	
		
		var pic1="";
		if(pic == ""){
			switch(g){
				case "M":
					pic="/img/s_no_portrait.jpg";
					break;
				case "F":
					pic="/img/s_no_portrait_f.jpg";
					break;
				case "O":
					pic="/img/s_no_portrait_o.jpg";
					break;
				default:
					pic="/img/s_no_portrait_n.jpg";
					break;
			}			
		}else{			
			pic=this.chatV.thumbImgPath+pic;
		}	
		this.IMCIncoming(suid,name,pic,0,msg,who);
		if(this.chatV.notmainpage==1){
			this.chatV.notmainpage=0;
			return false;
		}
		
		msg='<div class="msgcls" style="padding:5px 2px 0; border-bottom:1px #CCCCCC dotted; clear:both;"><div style="float:left;padding-right:5px;"><img src="'+pic+'" title="'+name+'" style="width:20px;height:25px;" /></div><div style="line-height:1.5em; padding-bottom:12px;">'+this.smilecls.replace(msg)+'</div></div>';
		$("#IMC"+suid).data("msg",$("#IMC"+suid).data("msg")+msg);
		$("#IMCHID"+suid).val(msg);
		//who=1是自己發的
		if(this.IMCCurrentID == suid){
			try{			
				$("#fcpIMCContent").append(msg).scrollTop($('#fcpIMCContent')[0].scrollHeight);
			}catch(e){
				alert(e.message);
			}		
		}else{
			if(who != 1){
				$("#IMC"+suid).attr("class","fcpIMCLeft3");
				this.IMCUnreadCounterUpdate();
			}
		}		
	};
	this.chat_showmsgerr=function(suid,msg){
		if ($("#IMC"+suid).length > 0) {	
			if(typeof($("#IMC"+suid).data("msg")) == "undefined"){
				$("#IMC"+suid).data("msg","");
			}	
			msg='<div style="padding:5px 2px 0; border-bottom:1px #CCCCCC dotted; clear:both;"><div style="color:red;">['+jsMsg["chat"][6]+']</div><div style="line-height:1.5em; padding-bottom:12px;">'+msg+'</div></div>';
			$("#IMC"+suid).data("msg",$("#IMC"+suid).data("msg")+msg);
			$("#IMCHID"+suid).val(msg);
			if(this.IMCCurrentID == suid){
				$("#fcpIMCContent").append(msg).scrollTop($('#fcpIMCContent')[0].scrollHeight);
			}
		}
	};
	//動畫前對話紀錄儲存
	this.animhisrecfunc=function(){	
		this.chatV.chatrecdiv=$("#chatrecdiv").html();
		this.chatV.chathispos={
			uid:usrid,
			IMCCurrentID:this.IMCCurrentID,
			IMCInstanceCnt:this.IMCInstanceCnt,
			IMCDownShiftCnt:this.IMCDownShiftCnt,
			IMCShiftOffSet:this.IMCShiftOffSet,
			IMCUpShiftControl:this.IMCUpShiftControl,
			IMCDownShiftControl:this.IMCDownShiftControl,
			IMCWindowState:this.IMCWindowState,					
			IMCList:this.IMCList.toString(),
			IMCListTop:this.IMCListTop,
			IMCListBot:this.IMCListBot,
			contrec:this.chatV.chatrecdiv
		};
	};
	this.IMCShiftUp=function() {
		if (this.IMCUpShiftControl && !this.IMCAnimationLock) {
			this.animhisrecfunc();
			
			this.IMCDownShiftCnt--;
			if ((this.IMCListBot-this.IMCListTop)==9) this.IMCListBot--;
			this.IMCListTop--;
			if (this.IMCInstanceCnt>(10+this.IMCDownShiftCnt)) {
				this.IMCDownShiftControl=true;
				$("#fcpIMCNevBtnDown").attr("class","fcpIMCNevBtnDown2");
			}
			if (this.IMCDownShiftCnt<=0) {
				this.IMCUpShiftControl=false;
				$("#fcpIMCNevBtnUp").attr("class","fcpIMCNevBtnUp1");
			}
			this.IMCShiftAnimation(1,1,0.5);		
		}
	}
	this.IMCShiftDown=function() {
		if (this.IMCDownShiftControl && !this.IMCAnimationLock) {
			this.animhisrecfunc();
			this.IMCDownShiftCnt++;
			this.IMCListTop++;
			this.IMCListBot++;
			if (this.IMCInstanceCnt<=(10+this.IMCDownShiftCnt)) {
				this.IMCDownShiftControl=false;
				$("#fcpIMCNevBtnDown").attr("class","fcpIMCNevBtnDown1");
			}
			this.IMCUpShiftControl=true;
			$("#fcpIMCNevBtnUp").attr("class","fcpIMCNevBtnUp2");
			this.IMCShiftAnimation(-1,1,0.5);		
		}
	};
	
	this.IMCShiftToTarget=function(IMC_ID) {
		if (!this.IMCAnimationLock) {
			
			var pos=0;
			while (this.IMCList[pos]!=IMC_ID && pos<this.IMCInstanceCnt) {
				pos++;
			}
			if (pos<this.IMCListTop) {
				this.animhisrecfunc();
				var shiftMagnitude=this.IMCListTop-pos;
				this.IMCListBot=this.IMCListBot-shiftMagnitude;
				this.IMCListTop=pos;
				this.IMCDownShiftCnt=this.IMCDownShiftCnt-shiftMagnitude;
				if (this.IMCListTop>1) {
					this.IMCUpShiftControl=true;
					$("#fcpIMCNevBtnUp").attr("class","fcpIMCNevBtnUp2");
				} else {
					this.IMCUpShiftControl=false;
					$("#fcpIMCNevBtnUp").attr("class","fcpIMCNevBtnUp1");
				}
				if (this.IMCListBot<this.IMCInstanceCnt) {
					this.IMCDownShiftControl=true;
					$("#fcpIMCNevBtnDown").attr("class","fcpIMCNevBtnDown2");
				} else {
					this.IMCDownShiftControl=false;
					$("#fcpIMCNevBtnDown").attr("class","fcpIMCNevBtnDown1");
				}
				this.IMCShiftAnimation(1,shiftMagnitude,0.5);
			} else if (pos>this.IMCListBot) {
				this.animhisrecfunc();
				var shiftMagnitude=pos-this.IMCListBot;
				this.IMCListBot=pos;
				this.IMCListTop=this.IMCListTop+shiftMagnitude;
				this.IMCDownShiftCnt=this.IMCDownShiftCnt+shiftMagnitude;
				if (this.IMCListTop>1) {
					this.IMCUpShiftControl=true;
					$("#fcpIMCNevBtnUp").attr("class","fcpIMCNevBtnUp2");
				} else {
					this.IMCUpShiftControl=false;
					$("#fcpIMCNevBtnUp").attr("class","fcpIMCNevBtnUp1");
				}
				if (this.IMCListBot<this.IMCInstanceCnt) {
					this.IMCDownShiftControl=true;
					$("#fcpIMCNevBtnDown").attr("class","fcpIMCNevBtnDown2");
				} else {
					this.IMCDownShiftControl=false;
					$("#fcpIMCNevBtnDown").attr("class","fcpIMCNevBtnDown1");
				}
				this.IMCShiftAnimation(-1,shiftMagnitude,0.5);
			}
		}
	};
	this.IMCIncomingMsg=function(IMC_ID) {
		if (IMC_ID==this.IMCCurrentID) return true;
		var pos=0;
		while (this.IMCList[pos]!=IMC_ID && pos<this.IMCInstanceCnt) {
			pos++;
		}
		if (pos<this.IMCListTop) {
			$("#fcpIMCNevBtnUp").attr("class","fcpIMCNevBtnUp3");
		} else if (pos>this.IMCListBot) {
			$("#fcpIMCNevBtnDown").attr("class","fcpIMCNevBtnDown3");
		}
	};
	this.IMCSendE13=function(e) {
		if(!this.chatV.key13){
			var key;
			e = e || event;
			if (window.event) key=window.event.keyCode; //IE
			else key=e.which; //firefox			
			if (key==13 && !e.shiftKey) {
				if($("#fcpIMCInputTA").val().length > this.chatV.maxtxtlength){
					$("#fcpIMCInputTA").val($("#fcpIMCInputTA").val().substring(0, this.chatV.maxtxtlength));
				}		
				var content=$("#fcpIMCInputTA").val().trimmark().replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1").replace(/\n/g,"<br>");
                if (content!="") {
					this.chatV.key13=true;
                    if(chatCls.conning==true){
                        chatCls.flashMovie("chatswf").sendMsg(this.IMCCurrentID,content);
                    }else{
                        msg='網路中斷';
                        msg='<div style="padding:5px 2px 0; border-bottom:1px #CCCCCC dotted; clear:both;"><div style="color:red;">['+msg+','+jsMsg["chat"][6]+']</div><div style="line-height:1.5em; padding-bottom:12px;">'+content+'</div></div>';
                        $("#fcpIMCContent").append(msg).scrollTop($('#fcpIMCContent')[0].scrollHeight);
                    }
				}
			}
		}		
	};
	this.IMCSendE13UP=function(){
		if(this.chatV.key13){
			$("#fcpIMCInputTA").val("");
			this.chatV.key13=false;
		}
		$("#txtLimit").text(this.chatV.maxtxtlength - $("#fcpIMCInputTA").val().length);
	};
	this.IMCWindowOpen=function() {
		if (this.IMCWindowState!=2) {
			this.IMCWindowState=2;
			$("#fcpIMCBar").css("display","none");
			$("#fcpIMCWindow").css("display","block");
			$("#fcpIMCContent").scrollTop($('#fcpIMCContent')[0].scrollHeight);
			$("#chatrecdiv").css("display","block");
		}
	};
	this.IMCBarHide=function() {
		if (this.IMCWindowState!=0) {
			this.IMCWindowState=0;
			$("#fcpIMCBar").attr("class","fcpIMCBar1");
			$("#fcpIMCWindow").css("display","none");
			$("#fcpIMCBar").css("display","none");	
			$("#chatrecdiv").css("display","none");
		}
	};
	this.IMCWindowMin=function() {
		if (this.IMCWindowState!=1) {
			this.IMCWindowState=1;
			$("#fcpIMCBar").attr("class","fcpIMCBar1");
			$("#fcpIMCBarFront").html(jsMsg["chat"][8]+": "+this.IMCInstanceCnt);
			$("#fcpIMCWindow").css("display","none");
			$("#fcpIMCBar").css("display","block");	
			$("#chatrecdiv").css("display","block");
		}
	};
	this.IMCShiftAnimation=function(direction, magnitude, speed) {	
		this.IMCAnimationLock=true;
		var h=29*magnitude;
		var t=Math.abs(Math.round(h/(20*speed)));
		var i=1;		
		process=function () {			
			if (i<=t) {
				$("#fcpIMCList").css("marginTop",chatCls.IMCShiftOffSet+(direction*Math.round((h/t)*i))+"px");
				i++;
			} else {
				clearInterval(chatCls.chatV.animinterval);
				chatCls.IMCShiftOffSet=chatCls.IMCShiftOffSet+(direction*h);
				chatCls.IMCUnreadCounterUpdate();
				chatCls.IMCAnimationLock=false;
			}
		}
		this.chatV.animinterval=setInterval("process();", 50);
	};
	this.IMCUnreadCounterUpdate=function() {
		var unreadCntTop=0;
		var unreadCntBot=0;
		var str="";
		var i;
		
		if (this.IMCListTop>1) {
			for (i=1; i<this.IMCListTop; i++) {
				if (document.getElementById("IMC"+this.IMCList[i]).className=="fcpIMCLeft3") {
					unreadCntTop++;
				}
			}
			if (unreadCntTop>0) {
				str+="<div class='fcpIMCUnreadCounterTop' onClick='chatCls.IMCShiftToFristUnread(1);'>"+unreadCntTop+"</div>";
			}
		}
		if (this.IMCListBot<this.IMCInstanceCnt) {
			for (i=this.IMCInstanceCnt; i>this.IMCListBot; i--) {
				if (document.getElementById("IMC"+this.IMCList[i]).className=="fcpIMCLeft3") {
					unreadCntBot++;
				}
			}
			if (unreadCntBot>0) {
				str+="<div class='fcpIMCUnreadCounterBot' onClick='chatCls.IMCShiftToFristUnread(-1);'>"+unreadCntBot+"</div>";
			}
		}
		document.getElementById("fcpIMCUnreadControl").innerHTML=str;
	};
	this.IMCShiftToFristUnread=function(direction) {
		if (!this.IMCAnimationLock) {
			var target="";
			var i;
			
			if (direction==1) {
				if (this.IMCListTop>1) {
					for (i=(this.IMCListTop-1); i>=1; i--) {
						if (document.getElementById("IMC"+this.IMCList[i]).className=="fcpIMCLeft3") {
							target=this.IMCList[i];
							break;
						}
					}
				}
			} else {
				if (this.IMCListBot<this.IMCInstanceCnt) {
					for (i=(this.IMCListBot+1); i<=this.IMCInstanceCnt; i++) {
						if (document.getElementById("IMC"+this.IMCList[i]).className=="fcpIMCLeft3") {
							target=this.IMCList[i];
							break;
						}
					}
				}
			}
			if (target) {
				this.IMCShiftToTarget(target);
			}
		}
	};
	this.changeTitleTxt=function(str){
		var a=0;
		process=function(){
			if(a==0){
				document.title=str;
				a=1;
			}else{
				document.title=chatCls.chatV.title;
				a=0;
			}
		}
		this.chatV.titleInterval=setInterval("process();", 1000);
	};
}


var songlist=new Array();	//清單陣列
var audioPlaylist=null;			//物件
var jplay_status=false;

var Playlist = function(instance, playlist, options) {
	var self = this;
	this.instance = instance; // String: To associate specific HTML with this playlist
	this.playlist = playlist; // Array of Objects: The playlist
	this.options = options; // Object: The jPlayer constructor options for this playlist
	this.recErr=0;
	this.recNextErr=0;
	this.current = 0;
	this.playStatus={
		repeat:false,	//單曲循環
		random:false	//隨機播放
	}

	this.cssId = {
		jPlayer: "jquery_jplayer_",
		interface: "jp_interface_",
		playlist: "jp_playlist_"
	};
	this.cssSelector = {};

	$.each(this.cssId, function(entity, id) {
		self.cssSelector[entity] = "#" + id + self.instance;
	});

	if(!this.options.cssSelectorAncestor) {
		this.options.cssSelectorAncestor = this.cssSelector.interface;
	}
	$(this.cssSelector.jPlayer).jPlayer(this.options);

	$(this.cssSelector.interface + " .jp-previous").click(function() {
		self.playlistPrev();
		$(this).blur();
		return false;
	});

	$(this.cssSelector.interface + " .jp-next").click(function() {
		self.playlistNext("cast");
		$(this).blur();
		return false;
	});
	//單曲循環觸發函式
	$(this.cssSelector.interface + " .jp-repeat").click(function() {
		if(self.playStatus.repeat){
			$(this).attr("title",jsMsg["music"][6]+"["+jsMsg["music"][5]+"]").css({"background":"url(/music/img/jplayer.music.png) -177px -140px no-repeat"});
			self.playStatus.repeat=false;
		}else{
			$(this).attr("title",jsMsg["music"][6]+"["+jsMsg["music"][4]+"]").css({"background":"url(/music/img/jplayer.music.png) -154px -140px no-repeat"});
			self.playStatus.repeat=true;
			if(self.playStatus.random){
				$(self.cssSelector.interface + " .jp-random").attr("title",jsMsg["music"][7]+"["+jsMsg["music"][5]+"]").css({"background":"url(/music/img/jplayer.music.png) -223px -140px no-repeat"});
				self.playStatus.random=false;
			}
		}
		return false;
	});
	//隨機播放觸發函式
	$(this.cssSelector.interface + " .jp-random").click(function() {
		if(self.playStatus.random){
			$(this).attr("title",jsMsg["music"][7]+"["+jsMsg["music"][5]+"]").css({"background":"url(/music/img/jplayer.music.png) -223px -140px no-repeat"});
			self.playStatus.random=false;
		}else{
			$(this).attr("title",jsMsg["music"][7]+"["+jsMsg["music"][4]+"]").css({"background":"url(/music/img/jplayer.music.png) -200px -140px no-repeat"});
			self.playStatus.random=true;
			if(self.playStatus.repeat){
				$(self.cssSelector.interface + " .jp-repeat").attr("title",jsMsg["music"][6]+"["+jsMsg["music"][5]+"]").css({"background":"url(/music/img/jplayer.music.png) -177px -140px no-repeat"});
				self.playStatus.repeat=false;
			}
		}
		return false;
	});
	//清空清單觸發函式
	$(this.cssSelector.interface + " .jp-m_list").click(function() {		
		if (confirm(jsMsg["music"][9]+"?")) {
			var params="uid="+usrid;
			ajaxRequest("/music/process/clear_playlist.php",params,500,function(rText) {
				if (rText=="pass") {
					if (document.getElementById("mPLNewEntryDiv")) document.getElementById("mPLNewEntryDiv").innerHTML="";
					if (document.getElementById("mPLDiv")) document.getElementById("mPLDiv").innerHTML="<div id='mPLFiller' class='filler'></div>";
					self.listclear();
				} else {
					loadMask(400,50);
					document.getElementById("maskContentDiv").innerHTML="<table class='fillerTable'><tr><td class='error'>"+rText+"</td></tr></table>";
				}
			});
		}
		return false;
	});
	//前往歌曲觸發函式
	$(this.cssSelector.interface + " .jp-m_box").click(function() {
		loadPage("/music/s.php","/music/s.php?sid="+self.playlist[self.current].mp3);
		return false;
	});
};

Playlist.prototype = {
	displayPlaylist: function() {
		var self = this;
		$(this.cssSelector.playlist + " ul").empty();
		if(this.playlist.length == 0){
			var listItem = "<li id='nosongsay'>";
			listItem += "<div class='s_listl'><a href='javascript:;' tabindex='1'>"+jsMsg["music"][3]+"</a></div>";		
			listItem += "</li>";
			$(this.cssSelector.playlist + " ul").append(listItem);
			return;
		}
		for (i=0; i < this.playlist.length; i++) {
			var listItem = (i === this.playlist.length-1) ? "<li class='jp-playlist-last'>" : "<li>";
			if(this.playlist[i].del == '0'){
				listItem += "<div class='s_listl'><a href='javascript:;' id='" + this.cssId.playlist + this.instance + "_item_" + i +"' tabindex='1'>"+ this.playlist[i].name +"</a></div>";
			}else{
				listItem += "<div class='s_listd'><div id='" + this.cssId.playlist + this.instance + "_item_" + i +"' class='jplayer_del_song'>"+ this.playlist[i].name +"</div></div>";
			}
			listItem += "<div class='s_listr'><a href='javascript:;' id='" + this.cssId.playlist + this.instance + "_del_" + i +"' class='jp-del' title='"+jsMsg["music"][2]+"'></a></div>";				
			listItem += "</li>";

			// Associate playlist items with their media
			$(this.cssSelector.playlist + " ul").append(listItem);
			$(this.cssSelector.playlist + "_item_" + i).not(".jplayer_del_song").data("index", i).click(function() {			
				var index = $(this).data("index");	
				var recidx=0;
				$.each(self.playlist,function(i,n){
					if(n.id == index){
						recidx=i;
					}
				});		
				if(self.current !== recidx) {					
					$(self.cssSelector.jPlayer).jPlayer("setNeedDownload",true);
					self.playlistChange(recidx);
				} else {
					$(self.cssSelector.jPlayer).jPlayer("play");
				}
				$(this).blur();
				return false;
			});
			$(this.cssSelector.playlist + "_del_" + i).data("index", i).click(function() {
				var emt=$(this);
				var index = emt.data("index");
				var recidx=0;
				
				$.each(self.playlist,function(i,n){
					if(n.id == index){
						recidx=i;
					}
				});
				var sid=self.playlist[recidx].mp3;
				var params="uid="+usrid+"&sid="+sid+"&ajaxSignature=1";
				$.ajax({
					type: "POST",
					url: "/music/process/remove_from_playlist.php",
					data: params,
					dataType:"text",
					success: function(rText){
						if (rText=="pass") {
							//假如刪除的音樂剛好是現在正在播的音樂		
							var delnowplay=false;
							if(self.current == recidx){	
								delnowplay=true;
								if(self.current == self.playlist.length-1){
									self.current=0;
								}								
							}else if(self.current > recidx){
								self.current--;
							}			
							self.playlist.splice(recidx, 1);					   				
							emt.parents("li").remove();							
							if(self.playlist.length == 0){
								var listItem = "<li id='nosongsay'>";
								listItem += "<div class='s_listl'><a href='javascript:;' tabindex='1'>"+jsMsg["music"][3]+"</a></div>";		
								listItem += "</li>";
								$(self.cssSelector.playlist + " ul").append(listItem);
								self.current=0;
							}else if(delnowplay){
								var ispaused = $(self.cssSelector.jPlayer).jPlayer("getPaused");
								if(ispaused){
									var cssidx=self.playlist[self.current].id;
									$(self.cssSelector.jPlayer).jPlayer("setNeedDownload",true);
									self.playlistConfig(self.current,cssidx);
								}else{
									$(self.cssSelector.jPlayer).jPlayer("setNeedDownload",true);
									self.playlistChange(self.current);
								}						
							}		
							if (document.getElementById("mPLE"+sid)) {
								killDiv("mPLE"+sid,1);
							}
						} else {
							loadMask(400,50);
							document.getElementById("maskContentDiv").innerHTML="<table class='fillerTable'><tr><td class='error'>"+rText+"</td></tr></table>";
						}
					}
				});				
				return false;
			});
			
		}
	},
	playlistInit: function(autoplay) {
		if(autoplay) {
			this.playlistChange(this.current);
		} else {
			this.playlistConfig(this.current,0);
		}
	},
	playlistConfig: function(index,cssidx) {
		try{
			var cssIndex=this.playlist[parseInt(this.current)].id;			
			$(this.cssSelector.playlist + "_item_" + cssIndex).removeClass("jp-playlist-current").parents("li").removeClass("jp-playlist-current");
		}catch(e){}
		$(this.cssSelector.playlist + "_item_" + cssidx).addClass("jp-playlist-current").parents("li").addClass("jp-playlist-current");
		this.current = index;		
		$("#jp-songname").html(this.playlist[this.current].name);
	},
	playlistChange: function(index) {
		try{
			if(arguments[1] == 'error'){
				this.recErr++;
			}else{
				this.recErr=0;
			}
			var cssidx=this.playlist[index].id;		
			this.playlistConfig(index,cssidx);	
			//$(this.cssSelector.jPlayer).jPlayer("setMedia", this.playlist[parseInt(this.current)]);
			if(arguments[1] == undefined){
				$(this.cssSelector.jPlayer).jPlayer("play");
			}else{
				$(this.cssSelector.jPlayer).jPlayer("play",arguments[1]);
			}			
		}catch(e){}		
	},
	playlistNext: function() {	
		try{
			if(arguments[0] == 'error'){
				this.recNextErr++;
			}else{
				this.recNextErr=0;
			}
			var listnums=this.playlist.length;
			if(this.playStatus.random && typeof(arguments[0]) == 'undefined' && listnums > 1){//隨機播放
				//亂數取出 index
				var maxNum = listnums-1;   
				var minNum = 0;
				var index =Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum;				
			}else{
				var index = (this.current + 1 < this.playlist.length) ? this.current + 1 : 0;
				if(this.playStatus.repeat && typeof(arguments[0]) == 'undefined'){ //單曲循環
					var index =this.current;
				}else{
					var index = (this.current + 1 < this.playlist.length) ? this.current + 1 : 0;
				}
			}						
			$(this.cssSelector.jPlayer).jPlayer("setNeedDownload",true);
			this.playlistChange(index,'next');
		}catch(e){}
	},
	playlistPrev: function() {
		try{
			//檢查是否有小數點,不用檢查是否為整數		
			if(this.recNextErr > 0){
				this.recNextErr=0;
			}			
			var index = (this.current - 1 >= 0) ? parseInt(this.current - 1) : this.playlist.length - 1;
			$(this.cssSelector.jPlayer).jPlayer("setNeedDownload",true);
			this.playlistChange(index,'prev');
		}catch(e){}
	},
	playlistAdd:function(js,name,sid,playnow){		
		//檢查是否重複
		name=$.trim(name);
		sid=$.trim(sid);
		if(name != '' && sid != ''){
			var repeat=false;
			var idx=-1;
			$.each(this.playlist,function(i,val){
				if(sid == val.mp3){
					repeat=true;
					idx=i;
					return false;
				}					
			});
			if(repeat && playnow){	
				if(idx > -1){
					if(js == '1'){
						//改名
						this.playlist[idx].name=name;						
						$("#"+this.cssId.playlist + this.instance + "_item_" + this.playlist[idx].id).html(name);
					}
					if(this.current != idx){
						$(this.cssSelector.jPlayer).jPlayer("setNeedDownload",true);
						this.playlistChange(idx);
					}else if($(audioPlaylist.cssSelector.jPlayer).jPlayer("getPaused")){
						$(this.cssSelector.jPlayer).jPlayer("play");
					}
				}		
				return;
			}else if(repeat && !playnow){
				return;
			}
		}else{				
			return;
		}
		if($("#nosongsay").length > 0){
			$("#nosongsay").remove();
		}	
		var lastIndex=this.playlist.length-1;
		try{
			var cssIndex=parseInt(this.playlist[lastIndex].id)+1 ;			
		}catch(e){
			var cssIndex= 0;			
		}			
		var newlist={"name":name,"mp3":sid,"id":cssIndex,"del":"0"};
		this.playlist.push(newlist);
		var self = this;
			
		var listItem = "<li class='jp-playlist-last'>";
		listItem += "<div class='s_listl'><a href='javascript:;' id='" + this.cssId.playlist + this.instance + "_item_" + cssIndex +"' tabindex='1'>"+ name +"</a></div>";
		listItem += "<div class='s_listr'><a href='javascript:;' id='" + this.cssId.playlist + this.instance + "_del_" + cssIndex +"' class='jp-del'></a></div>";
		listItem += "</li>";
		
		$(this.cssSelector.playlist + " ul").append(listItem);			
		$(this.cssSelector.playlist + "_item_" + cssIndex).not(".jplayer_del_song").data("index", cssIndex).click(function() {
			var index = $(this).data("index");
			var recidx=0;				
			$.each(self.playlist,function(i,n){
				if(n.id == index){						
					recidx=i;
				}
			});	
			if(self.current !== recidx) {
				$(self.cssSelector.jPlayer).jPlayer("setNeedDownload",true);
				self.playlistChange(recidx);
			} else {
				$(self.cssSelector.jPlayer).jPlayer("play");
			}
			$(this).blur();
			return false;
		});
		$(this.cssSelector.playlist + "_del_" + cssIndex).data("index", cssIndex).click(function() {
			var emt=$(this);
			var index = emt.data("index");
			var recidx=0;
			
			$.each(self.playlist,function(i,n){
				if(n.id == index){
					recidx=i;
				}
			});
			var sid=self.playlist[recidx].mp3;
			var params="uid="+usrid+"&sid="+sid+"&ajaxSignature=1";
			$.ajax({
				type: "POST",
				url: "/music/process/remove_from_playlist.php",
				data: params,
				dataType:"text",
				success: function(rText){
					if (rText=="pass") {
						//假如刪除的音樂剛好是現在正在播的音樂	
						var delnowplay=false;
						if(self.current == recidx){
							delnowplay=true;
							if(self.current == self.playlist.length-1){
								self.current=0;
							}
						}else if(self.current > recidx){
							self.current--;
						}
						self.playlist.splice(recidx, 1);
						emt.parents("li").remove();	
						if(self.playlist.length == 0){
							var listItem = "<li id='nosongsay'>";
							listItem += "<div class='s_listl'><a href='javascript:;' tabindex='1'>"+jsMsg["music"][3]+"</a></div>";		
							listItem += "</li>";
							$(self.cssSelector.playlist + " ul").append(listItem);
							self.current=0;
						}else if(delnowplay){
							var ispaused = $(self.cssSelector.jPlayer).jPlayer("getPaused");						
							if(ispaused){
								var cssidx=self.playlist[self.current].id;	
								$(self.cssSelector.jPlayer).jPlayer("setNeedDownload",true);
								self.playlistConfig(self.current,cssidx);
							}else{
								$(self.cssSelector.jPlayer).jPlayer("setNeedDownload",true);
								self.playlistChange(self.current);
							}												
						}	
						if (document.getElementById("mPLE"+sid)) {
							killDiv("mPLE"+sid,1);
						}
					} else {
						loadMask(400,50);
						document.getElementById("maskContentDiv").innerHTML="<table class='fillerTable'><tr><td class='error'>"+rText+"</td></tr></table>";
					}
				}
			});			
			return false;
			
		});		
		if(playnow){
			$(this.cssSelector.jPlayer).jPlayer("setNeedDownload",true);
			this.playlistChange(this.playlist.length-1);
		}
	},
	listclear:function(){
		$(".jp-playlist ul li").remove();
		songlist=[];
		audioPlaylist.playlist=[];
		this.recErr=0;
		this.recNextErr=0;
		this.current = 0;
		var listItem = "<li id='nosongsay'>";
		listItem += "<div class='s_listl'><a href='javascript:;' tabindex='1'>"+jsMsg["music"][3]+"</a></div>";		
		listItem += "</li>";
		$(this.cssSelector.playlist + " ul").append(listItem);
	}
};

/* music player */
function toggleJplayerDiv() {	
	if (document.getElementById("jplayerHiddenDiv").style.display=="none") {
		if (usrid) {
			openJplayerDiv();
		} else {
			si_popup();
		}
	} else {
		document.getElementById("jplayerDiv").setAttribute(jsClassExt,"jplayerDiv");
		document.getElementById("jplayerHiddenDiv").style.display="none";
	}
}
function openJplayerDiv() {
	if (document.getElementById("noteHiddenDiv").style.display=="block") {
		document.getElementById("notificationDiv").setAttribute(jsClassExt,"notificationDiv");
		document.getElementById("noteHiddenDiv").style.display="none";
		document.getElementById("noteHiddenDiv").innerHTML="";
	}
	document.getElementById("jplayerDiv").setAttribute(jsClassExt,"jplayerDivHover");
	document.getElementById("jplayerHiddenDiv").style.display="block";	
	getJplayerlist();
}

function getJplayerlist(){	
	if (usrid) {
		if(!audioPlaylist){
			var args=arguments;			
			dynamicJsCssLoader("/music/css/jplayer.music.css?"+GVERSION,"css");//new Date().getTime()
			dynamicJsCssLoader("/music/js/jquery.jplayer.js?"+GVERSION,"js",function(){
				//抓取清單
				$.ajax({
					type:"POST",
					url:'/music/process/getmusiclist.php',
					data:{"uid":usrid},
					dataType:"json",
					cache:false, 
					timeout:10000,
					beforeSend: function(){},
					success: function(data){					
						if(data.length > 0){
							var arr={};				
							$.each(data,function(i,n){
								arr.name=(n.artist == "")?n.title:n.title+" - "+n.artist;
								arr.mp3=n.sid;
								arr.id=i;
								arr.del=n.del;
								songlist.push(arr);					
								arr={};
							});			
						}		
						audioPlaylist = new Playlist("1", 
							songlist
							, {
							ready: function() {								
								audioPlaylist.displayPlaylist();
								audioPlaylist.playlistInit(false); // Parameter is a boolean for autoplay.
								jplay_status=true;									
							},
							ended: function() {
								audioPlaylist.playlistNext();
							},
							play: function() {
								$(this).jPlayer("pauseOthers");
							},
							volume:0.5,
							swfPath: "/music/js",	//swf儲存目錄
							supplied: "mp3"
						});
						try{
							if(args[0] == 'add'){
								var jplayerEI=setInterval(function(){							
									if(audioPlaylist && jplay_status){															
										if(args[4] === true){ //新增即播放
											$(audioPlaylist.cssSelector.playlist + "_item_0").removeClass("jp-playlist-current").parents("li").removeClass("jp-playlist-current");
										}	
										audioPlaylist.playlistAdd(args[1],args[2],args[3],args[4]);
										clearInterval(jplayerEI);
									}				
								},500);
							}
						}catch(e){}												
					},
					error: function(){}
				});
			});
		}
		
	} else {
		document.getElementById("jplayerHiddenDiv").innerHTML="<table class='fillerTable'><tr><td class='error'>"+jsMsg["music"][4]+"</td></tr></table>";
	}
}

function add2Playlist(sid) {
	if (usrid) {
		var params="uid="+usrid+"&sid="+sid;
		var playnow=(typeof(arguments[1]) != 'undefined')?arguments[1]:true;
		try{
			var ispaused = $(audioPlaylist.cssSelector.jPlayer).jPlayer("getPaused");
			if(!ispaused){
				playnow=false;
			}else{
				playnow=true;
			}
		}catch(e){}
		ajaxRequest("/music/process/add_to_playlist.php",params,500,function(rs) {
			try {
				rs=JSON.parse(rs); //rs.sid, rs.title, rs.artist, rs.js
				if(rs.flag == 'pass'){				
					var name=(rs.artist == "")?rs.title:rs.title+" - "+rs.artist;					
					if(usrid && !audioPlaylist){
						getJplayerlist('add',rs.js,name,rs.sid,playnow);
					}else if(usrid && audioPlaylist){
						audioPlaylist.playlistAdd(rs.js,name,rs.sid,playnow);
					}
				}
				if (document.getElementById("mPLNewEntryDiv")) {
					if (document.getElementById("mPLE"+rs.sid)) {
						document.getElementById("mPLE"+rs.sid).innerHTML=rs.out;
					} else {
						var parent=document.getElementById("mPLNewEntryDiv");
						var ele=document.createElement("div");
						ele.id="mPLE"+rs.sid;
						ele.innerHTML=rs.out;
						parent.insertBefore(ele,parent.firstChild);
						if (document.getElementById('mPLFiller')) document.getElementById('mPLDiv').removeChild(document.getElementById('mPLFiller'));
					}
				}
			} catch(ex) {
				loadMask(400,50);
				document.getElementById("maskContentDiv").innerHTML="<table class='fillerTable'><tr><td class='error'>"+rs+"</td></tr></table>";
			}
		});
	} else {
		si_popup();
	}
}

function stickyPlaylistDel(sid){
	var recidx=-1;
	$.each(audioPlaylist.playlist,function(i,val){
		if(sid == val.mp3){					
			recidx=i;
			return false;
		}					
	});
	if(recidx > -1){
		var cssIndex=parseInt(audioPlaylist.playlist[recidx].id);
		//假如刪除的音樂剛好是現在正在播的音樂					
		if(audioPlaylist.current == recidx){
			delnowplay=true;
			if(audioPlaylist.current == audioPlaylist.playlist.length-1){
				audioPlaylist.current=0;
			}
		}else if(audioPlaylist.current > recidx){
			audioPlaylist.current--;
		}	
		var emt=$(audioPlaylist.cssSelector.playlist + "_del_" + cssIndex);
		audioPlaylist.playlist.splice(recidx, 1);
		emt.parents("li").remove();	
		if(audioPlaylist.playlist.length == 0){
			var listItem = "<li id='nosongsay'>";
			listItem += "<div class='s_listl'><a href='javascript:;' tabindex='1'>"+jsMsg[4]+"</a></div>";		
			listItem += "</li>";
			$(audioPlaylist.cssSelector.playlist + " ul").append(listItem);
		}else if(delnowplay){
			var ispaused = $(audioPlaylist.cssSelector.jPlayer).jPlayer("getPaused");						
			if(ispaused){
				var cssidx=audioPlaylist.playlist[audioPlaylist.current].id;	
				$(audioPlaylist.cssSelector.jPlayer).jPlayer("setNeedDownload",true);
				audioPlaylist.playlistConfig(audioPlaylist.current,cssidx);
			}else{
				$(audioPlaylist.cssSelector.jPlayer).jPlayer("setNeedDownload",true);
				audioPlaylist.playlistChange(audioPlaylist.current);
			}												
		}
	}
}

function removeFromPlaylist(sid) {
	var params="uid="+usrid+"&sid="+sid;
	ajaxRequest("/music/process/remove_from_playlist.php",params,500,function(rText) {
		if (rText=="pass") {
			if (usrid && audioPlaylist){					
				stickyPlaylistDel(sid);				
			}
			if (document.getElementById("mPLE"+sid)) {
				killDiv("mPLE"+sid,1);
			}
		} else {
			loadMask(400,50);
			document.getElementById("maskContentDiv").innerHTML="<table class='fillerTable'><tr><td class='error'>"+rText+"</td></tr></table>";
		}
	});
}

function musicRequestInc () {
	ajaxRequest("/music/process/request_inc.php","sid="+audioPlaylist.playlist[audioPlaylist.current].mp3);
}

/***** Fubee *****/
function fubeeReward(update) {
	var str;
	var frInterval;
	var k=1;
	
	str="<div id='maskViewerCloseBtn' onClick='clearMask();'></div>";
	str+="<table style='height:100%;width:100%;' onClick='clearMask();'><tr><td align='center'>";
		str+="<div id='frImgDiv'>";
			str+="<div id='frText1'></div>";
		str+="</div>";
	str+="</td></tr></table>";
			
	function fubeeRewardEaseIn() {
		if (document.getElementById('frImgDiv') && k<21) {
			if (k<11) {
				if (isIE && IEVersion<9) {
					document.getElementById('frImgDiv').filters.alpha.opacity=(k*10);
				} else {
					document.getElementById('frImgDiv').style.opacity=(k/10);
				}
			}
			document.getElementById('frText1').style.top=Math.round(-40*Math.sin((Math.PI/20*k)/2))+"px";
			k++;
		} else {
			clearInterval(frInterval);
		}
	}
	
	document.getElementById('invisDiv').style.backgroundImage="url('/img/transfill.png')";
	document.getElementById('invisDiv').innerHTML=str;
	document.getElementById('invisDiv').style.display="block";
	
	frInterval=setInterval(fubeeRewardEaseIn,100);
	if (update) {
		if (document.getElementById('profileFubeeASpan')) {
			document.getElementById('profileFubeeASpan').innerHTML=parseInt(document.getElementById('profileFubeeASpan').innerHTML)+1;
			document.getElementById('profileFubeeRSpan').innerHTML=parseInt(document.getElementById('profileFubeeRSpan').innerHTML)+1;
		}
	}
}
