/**
 * @param sorce String src of js file
 * @param autoRemove Bool
 * @param id String Element's id when autoRemove:false
 * @author zhys9
 * @date 10-12-2007 dd-mm-yyyy
 * @todo Load javascript file async
 */
function jLoader(source, autoRemove, id, charset) {
	id = id || "";
	charset = charset || "gb2312";
	autoRemove = autoRemove || false;
	var b = document.getElementsByTagName("head")[0];
	var c = document.createElement("script");
	c.type = "text/javascript";
	c.charset = charset;
	if (id) {
		c.id = id;
	}
	c.src = source;
	var remove = function() {
		c.onload = null;
		var h = c.parentNode;
		h.removeChild(c);
		delete c;
	};
	var e = function(h) {
		var j = (h ? h : window.event).target
				? (h ? h : window.event).target
				: (h ? h : window.event).srcElement;
		if (j.readyState == "loaded" || j.readyState == "complete") {
			j.onreadystatechange = null;
			if (autoRemove) {
				remove();
			}
		}
	};
	if (navigator.product == "Gecko" && autoRemove) {
		c.onload = remove;
	} else {
		c.onreadystatechange = e;
	}
	b.appendChild(c);
}

var oJson = {};
var fJson = 
{
	"varName":{},//设定变量名
	"data":{},	 //[0,y,yes,空值]:默认,[-1,n,no]:不运行flush(),
	"file":{},	 //附加js代码文件
	"str":{},	 //附加JS代码
	//------------------//
	"jsonId":{},
	"set":function(element,vars)
	{
		for(key in vars)
		{
			this[key][element] = vars[key];
		}
	},
	"get":function(url,element)
	{
	    element = element || 'element';
	    this.set(element,{"data":"n"});
	    this.main(url,element);
	},
	"main":function(url,element,un)
	{
		this.__url__ = url;
		this.__element__ = element;
		this.__un__ = un;
		eval("oJson['"+element+"'] = this.include()" );
	},
	"getSrc":function(element)
	{
		var rs = '';
		if(this.varName[element])
		{
			rs +='&gJsonVarName='+encodeURI(this.varName[element]);
		}
		if(this.data[element])
		{
			if(this['data'][element] == 'n' || this['data'][element] == '-1' || this['data'][element] == 'no')
			{
				rs +='&gJsonData=n';
			}
		}
		if(this['str'][element])
		{
			rs +='&gJsonDoStr='+encodeURI(this['str'][element]);
		}
		if(this['file'][element])
		{
			rs +='&gJsonDoFile='+encodeURI(this['file'][element]);
		}
		return rs;
	},
	"include":function(url,element,un,charset)
	{
		charset   = charset || this.charset || 'gb2312';
		url       = url || this.__url__;
		element   = element || this.__element__ || 'script';
		un        = un || this.__un__ || false;
		
		var jsonId = this.__getJsonId(element),a;
		if(navigator.appVersion.indexOf("MSIE") == -1 || element == 'script')
		{
			a			= document.createElement('script');
		}else
		{
			a			= document.getElementById("script_"+element+((jsonId >1)?'_'+jsonId:''));
			if(!a)
			{
				a		= document.createElement('script');
				a.setAttribute("id","script_"+element+((jsonId >1)?'_'+jsonId:''));
			}
		}
		var b			= document.getElementsByTagName('HEAD').item(0);
		a.un			= un;
		a.data 			= '';
		a.charset       = charset;
		a.type 			= "text/javascript"; 
		a.src			= url+((url.indexOf('?') == -1 )?'?':'&')+'gJsonId='+jsonId+'&gJson='+element+fJson.getSrc(element);
		b.appendChild(a,null);
		return a;
	},
	"css":function(url)
	{
		if(!url) return;
		var a			= document.createElement('link');
		var b			= document.getElementsByTagName('HEAD').item(0);
		a.rel			= "stylesheet";
		a.type			= "text/css";
		a.href			= url;
		b.appendChild(a,null);
	},
	"__getJsonId":function(element)
    {
        if(this.jsonId[element])
        {
           var i=0;
           do
           {
               i++;
               if(!this.jsonId[element][i])
               {
                   
                   this.jsonId[element][i] = 1;
                   return i;
               }
           }while(1);
        }
        this.jsonId[element]    ={};
        this.jsonId[element][1] = 1;
        return 1;
    },
	"flush":function(element)
	{
		document.getElementById(element).innerHTML =  (oJson[element].un)?unescape(oJson[element].data):oJson[element].data;
		oJson[element] = {};
	}	
};
// JavaScript Document
var oTpl =
{
	"html":false,
	"main":function(element,jsonUrl,html)
	{
		if(html)this.html =html;
		var obj = document.getElementById(element);
		if (!obj) 
		{
			alert("指定的模版容器不"+element+"存在");
			return;
		}
		var oJsonSet =
		{
			"data":"n",
			"str":"oTpl.tpl('"+element+"',oJson."+element+".data)"
		};
		fJson.set(element,oJsonSet);
		fJson.main(jsonUrl,element);		
	},
	"tpl":function(element,jsonUrl,html)
	{
		if(html) this.html =html;
		var obj = document.getElementById(element);
		var templetHTML;
		if (!obj) 
		{
			alert("指定的模版容器不"+element+"存在");
			return;
		}
		if(!obj.oldHTML)
		{
			obj.oldHTML = this.html || obj.innerHTML;
			obj.oldHTML = obj.oldHTML.replace(/\[%/g,"<%").replace(/%\]/g,"%>")
								 .replace(/\{%/g,"<%").replace(/%\}/g,"%>")
								 .replace(/<!--%/g,"<%").replace(/%-->/g,"%>")
								 .replace(/\/\*%/g,"<%").replace(/%\*\//g,"%>");
		}
		obj.innerHTML 		= this.doTpl(obj.oldHTML,jsonUrl,0).replace(/http:\/\/56com\.56\.com/g,"http://dvspace.v.56.com");
		obj.style.display 	= "";
		$(obj).find('#'+element+'_loading').hide('slow');
	},
	"doTpl":function(tpl,data,xLev)
	{
		var sRepeat			= "<%begin_"+xLev+"[^>]*%>((.|\\n)+?)<%end_"+xLev+"%>";
		var rKey_g			= new RegExp("<%begin_"+xLev+"\\s*key=\"([^\"]+)\"[^%]*%>","g");
		var rRepeat			= new RegExp(sRepeat);
		var rRepeat_g		= new RegExp(sRepeat,"g");
		var rVars			= new RegExp("<%=(.+?)%>","g");
		var tDate;
		// 是否有重复
		var aKey = tpl.match(rKey_g);
		if(aKey)
		{
			var aRepeat = tpl.match(rRepeat_g);
			for (var key=0;key<aKey.length;key++)
			{
				aKey[key] 		= aKey[key].replace(rKey_g,"$1");
				aRepeat[key] 	= aRepeat[key].replace(rRepeat,"$1");
				tDate			= data[aKey[key]];
				var html		= '';
				for(var key2 in tDate)
				{
					if(typeof tDate[key2] != "function" && typeof tDate[key2] != "undefined")html 		+=this.doTpl(aRepeat[key],tDate[key2],xLev+1);
				}
				tpl				= tpl.replace(rRepeat,html);
			}
		}
		var aVars = tpl.match(rVars);
		if(aVars)
		{
			for (key=0;key<aVars.length;key++)
			{
				aVars[key]		= aVars[key].replace(rVars,"$1");
				tDate 			= data[aVars[key]]?data[aVars[key]]:'';
				var rVars_		= new RegExp("<%="+aVars[key]+"%>");				
				tpl				= tpl.replace(rVars_,tDate);
			}
		}
		return tpl;
	}
};
//数组扩展
Array.prototype.indexOf = function(o){var l = this.length;for (var i = 0; i < l; i++){if (this[i] == o){return i;}}return -1;};
Array.prototype.remove  = function(n){this.splice(n,1);};
Array.prototype.replace	= function(n,vars){this.splice(n,1,vars);};
jQuery.cookie = function(name, value, options) 
{
	if (typeof value != 'undefined') 
	{ // name and value given, set cookie
		options = options || {expires:1,path:"\/"};
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toGMTString)) 
		{
			var date;
			if (typeof options.expires == 'number') 
			{
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 60 * 60 * 1000));
			} else 
			{
				date = options.expires;
			}
			expires = '; expires=' + date.toGMTString(); // use expires attribute, max-age is not supported by IE
		}
		var path = options.path ? '; path=' + options.path : '';
		var domain = options.domain ? '; domain=' + options.domain : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else 
	{ // only name given, get cookie
		var cookieValue = '';
		if (document.cookie && document.cookie != '') 
		{
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) 
			{
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) 
				{
					try {
						cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					} catch (e) {
						cookieValue = unescape(cookie.substring(name.length + 1));
					}
					break;
				}
			}
		}
		return cookieValue;
	}
};
//几个公用函数
var userAgent = navigator.userAgent.toLowerCase();
var _ =
{
	"map":function(vars,func){func(vars);},
	"rand":function(begin,end){if(typeof begin !='undefined'){end = end?end:2147483648;return Math.floor(Math.random()*(end-begin)+begin);}else{a = new Date();return a.getTime();}},
	"r":function(vars){document.write(vars)},
	"e":function(){var elements = [];for (var i = 0; i < arguments.length; i++){var element = arguments[i];if (typeof element == 'string')element = document.getElementById(element);if (arguments.length == 1)return element;elements.push(element);}return elements;},
	"get":function(name){var get  =location.search||location.hash;var start	=get.indexOf(name + '=');if (start == -1) return '';var len = start + name.length + 1;var end = get.indexOf('&',len);if (end == -1) end = get.length;return unescape(get.substring(len,end));},
	"getCookie":function(name){return jQuery.cookie(name);},
	"setCookie":function(name, value, hours,domain){var options = {};if(hours)options.expires=hours;if(domain)options.domain=domain;options.path="\/";jQuery.cookie(name,value,options);},
	"copy":function(vars,note){note=note||'网址复制成功!';window.clipboardData.setData('text',vars);if(note)alert(note);},
	"rehide":function(obj1, obj2){try{obj1	= this.e(obj1);obj2	= this.e(obj2);if(obj1.style.display==''){$(obj1).hide("slow");$(obj2).show();}else{$(obj2).hide("slow");$(obj1).show();}}catch (e){}},
	"gowin":function(url,t,note){if(note)if(!window.confirm(note))return;if(t){top.document.location.href =url;}document.location.href = url;},
	"checkboxAll":function(a,b){b = b ? b['checked'] : true;a['checked'] = b;	for(var i=0;i<a.length;i++)a[i]['checked'] = b;},
	"checkboxChkFrom":function(a,note)	{note  = note || "提示:\n\t删除将无法恢复!您确定要删除所选吗？\t\n";var b = false;	if(a['checked'])b = true;for(var i=0;i<a.length;i++){	if(a[i]['checked']){ b = true;	break;	}};if(b) if(confirm(note)) return true;return false;},
	"time":function(a,b){var s,d;	if(b==1){d = new Date(a*1000);	s = d.getYear() + "-";  s += (d.getMonth() + 1) + "-";s += d.getDate();}else{d = new Date(a*1000);s = d.getYear() + "-"; s += (d.getMonth() + 1) + "-";	s += d.getDate()+ " ";s += d.getHours() + ":";s += d.getMinutes() + ":";s += d.getSeconds();};	return s;},
	"substr":function(s,n)	{s = s.toString();if(s){n = n||20;if(s.length > n){return s.substr(0,n)+'..';	}}return s;	},
	"size":function(a){var b;if(a<1024){b = 'Bit';}else if(a<1024*1024 && a>1024){a = a/1024;b = 'K';}else if(a<1024*1024*1024 && a>1024*1024){a = a/1024/1024;b = 'M';}else{a = a/1024/1024/1024;b = 'G';};return (Math.round(a*100)/100)+b;},
	"player":function(v,p,w,h,id){p = p || 'http://www.56.com/flashApp/v_player_site_fp7_5_20061219.swf';w = w || '100%';h = h || '100%';var wl = this.get('wl') || 0;return '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="'+(id||'object_flash_player')+'" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'+w+'" height="'+h+'"><param name="movie" value="'+(wl?p+'?'+v:p)+'"><param name="quality" value="high"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" />'+(wl?'':'<param name="FlashVars" value="'+v+'" />')+'<embed src="'+(wl?p+'?'+v:p)+'"  '+(wl?'':'flashvars="'+v+'"')+' quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" allowfullscreen="true" width="'+w+'" height="'+h+'"></embed></object>';},
	"do":function(e,fn){var a= this.e(e+'_loading');if(a){$(a).show('slow');}else{$('#'+e).prepend('<div id="'+e+'_loading" style="text-align:center"><img src="http://www.56.com/space/imgs/all/loading.gif" alt="数据加载中..."  align="absmiddle" /> 数据加载中... '+(fn?'[<a href="javascript:'+fn+'">刷新</a>]':'')+'</div>');}},
	"err":function(a,data,user,woman){data = (typeof data =='object')?data:data||{"flv":"http://www.56.com/v/img/flv_no_photo.gif","user":"http://www.56.com/v/img/user_no_photo.gif","women":"http://www.56.com/space/imgs/all/thu_woman.gif"};if(user){if(woman){a.src=data.woman;}else{a.src=data.user;}}else{a.src=data.flv;}},
    "phost":function(a,b)
    {
        if(b)
        {        
            var c = {0:'u',1:'u',2:'l',3:'p'};
            if(b==1 || b==2 || b ==3)b = c[b];
            return "http://www.56.com/"+b+(a%88+11);
        }else
        {
            var rs = 0,l=a.length,i;for(i=0;i<l;i++)rs+=a.charCodeAt(i);
            return "http://www.56.com/w"+(rs%88+11);
        }
    },
	browser: {
        version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
        safari: /webkit/.test(userAgent),
        opera: /opera/.test(userAgent),
        msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
        mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)

    },
	"getEnId":function(url)
	{
		url=url||location.href;
		return url.indexOf('/v_')==-1
			?(url.indexOf('id=')==-1
				?''
				:url.split('id=')[1].split('&')[0])
			:url.split('/v_')[1].split('.')[0];
	}
};
var _c = 
{
    "sendSms":function(user_id,Subject,Content)
	{
		window.open("http://www.56.com/admin/?http://msg.56.com/fasong.php?to="+user_id);
	},
	"userUrl":function(user_id,s)
	{
	    s = s || 'site';
	    return  s == 'site'
					? _.phost(user_id)+'/show_user.php?user_id='+a
					: _.phost(user_id)+'/spaceListUser.php?user_id='+a;	
	},
	"flvUrl":function(EnId,pct,id,s)
	{
		if(pct == 7){//56看看 Melon`` @ 090805
			return "http://kankan.56.com/v/"+EnId+".html";
		}else if(pct == 8){
			return "http://kankan.56.com/live/" + EnId + ".html";
		}
		s = s || 'site';
		return s == 'site'
		            ? _.phost(id,pct)+'/v_'+EnId+'.html'
					: _.phost(id,pct)+'/spaceDisplay.php?user_id='+EnId;
	}	
}
//用户信息
var usr =
{
	"gLoginId":_.getCookie("member_id"),											//登录用户ID
	"gLoginHost":_.getCookie("host"),												//登录主机名
	"gLoginPass":_.getCookie("pass_hex"),											//pass
	"gLoginMember":_.getCookie("member_login"),										//member_login
	"gNewMail":_.getCookie("newmail") || 0,											//新邮件
	"gNewMsg":_.getCookie("newmsg") || 0,
	"gKeepMail":_.getCookie("keepmail"),											//是否检查邮件的标示
	"gLoginUser":function(){return (this.gLoginId.indexOf("@")==-1 ? this.gLoginId : this.gLoginId.substring(0,this.gLoginId.indexOf("@")));},				//登录用户名
	"user_id":function(){return this.gLoginUser();},
	"photo":function(u,b){var a1 = 0,a2 =0,i,rs;u=u||this.gLoginUser();for (i= 0; i< u.length; i++){a1 += u.charCodeAt(i) * i; a2 += u.charCodeAt(i) * (i * 2 + 1);}a1 %= 100;a2 %= 100;rs  = 'http://uface.56.com/photo/' + a1 + "/" + a2 + "/";if (b){return rs + u + "_b_56.com_.jpg";} else{return rs + u + "_56.com_.jpg";}},
	"gIsLogin":function(){return (_.getCookie("member_id") != "" && _.getCookie("pass_hex") !="" )?true:false;},
	"gIsHomepage":function(){var gh =window.location.host;if(gh=='www.56.com'||gh=='56.com'){return true;} else {return false;	}},
	"nickname":function(){return _.getCookie("user_nickname");}
};
//导航菜单
var isOverMainMenu = false;
var isOverSortMenu = false;
function showMenu(id)
{
	var a = document.getElementById("MainMenu").getElementsByTagName("a");
	for(var i=0;i<a.length;i++)
	{
//		a[i].onmouseover = function()
//		{
//			if(this.className!="active") this.className = "hover";
//			showSortMenu(this.id);
//			isOverMainMenu=true;
//		}
//		a[i].onmouseout = function() 
//		{
//			if(this.className!="active") this.className = "";
//			setTimeout("showSortMenu('"+id+"')", 400);
//			isOverMainMenu=false;
//		}
		if(a[i].id == id)
		{
			a[i].parentNode.className = "active";
			showSortMenu(id);
		} else 
		{
			a[i].parentNode.className = "";
		}
	}
}
function showSortMenu(id)
{
	var a = document.getElementById("SortMenu");
	a.onmouseover = function()
	{
		isOverSortMenu=true;
	}
	a.onmouseout = function()
	{
		isOverSortMenu=false;
	}
	if(!isOverSortMenu && !isOverMainMenu)
	{
		var b = document.getElementById("SortMenu").getElementsByTagName("ul"); 
		for(var i=0;i<b.length;i++)
		{
			if(b[i].id == "SortMenu_"+id)
			{
				b[i].className = "active";
			} else
			{
				b[i].className = "";
			}
		}
	}
}
// header 上的js
var _h =
{
	HeaderNav:function()
	{
		var a = [(usr.gIsLogin()?'您好, <b><font color=@c60a00>'+usr.gLoginUser()+'</font></b></a> | <img src="http://www.56.com/admin/images/maintb1.gif" alt="" />(<a href="http://www.56.com/admin/?http://msg.56.com/" title="最新短消息">'+usr.gNewMsg+'</a>) | <a href="http://www.56.com/admin/">管理中心</a> | ':'<a href="http://w.56.com/userLogin.php">登录</a> | <a href="http://urs.56.com/Reg1.php">注册</a> | '),
				  '<a href="http://www.56.com/help/" target="_blank">帮助</a>',
				  (usr.gIsLogin()?' | <a href="http://space.56.com/php/logout.php">退出</a>':'')
				];
		return a.join('');
	},
	HeaderNavAdmin:function()
	{
		var a = [(usr.gIsLogin()?'您好,<a href="http://www.56.com/admin/" target="_blank"><b>'+usr.gLoginUser()+'</b></a> | <img src="http://www.56.com/admin/images/maintb1.gif" alt="" />(<a href="http://www.56.com/admin/?http://msg.56.com/" title="最新短消息">'+usr.gNewMsg+'</a>) | ':'<a href="http://www.56.com/w/userLogin.php" target="_blank">登录</a> | '),
				  '<img src="http://www.56.com/admin/img/icon_space.gif" align="absmiddle" /><a href="http://space.56.com/'+usr.gLoginUser()+'" target="_blank">地盘</a> | ',
				  '<a href="http://space.56.com/invite/invite.html?'+usr.gLoginUser()+'" target="_blank">邀请朋友</a> | ',
				  '<a href="http://www.56.com/help/" target="_blank">帮助</a>',
				  (usr.gIsLogin()?' | <a href="http://space.56.com/php/logout.php">退出</a>':'')
				];
		return a.join('');
	},
	HeaderMyNav:function()
	{
		var a = 1//usr.gIsLogin()
					?[	'<li><a href="http://www.56.com/admin/">管理中心</a></li>',
						'<li><a href="http://www.56.com/admin/?pg=w.56.com/admin/?mode=list&pct=u&muser='+usr.gLoginUser()+'">我的视频</a></li>',
						'<li><a href="http://www.56.com/admin/?pg=w.56.com/admin/?mode=fav&fuser='+usr.gLoginUser()+'">我的收藏</a></li>',
						'<li><a href="http://www.56.com/admin/?pg=v.56.com/admin_rss.php?user_id='+usr.gLoginUser()+'">我的订阅</a></li>']
					:[];
		return a.join('');
	}
};


//统计add by Melon 09-08-21
function setStat(s) {
	setTimeout(function() {
		jLoader("http://stat3.corp.56.com/player.htm?s=" + s, true);
	}, 1000);
}
