﻿/**
 * 处理6个参数
 * 1) 该脚本要放在BODY中实际要显示插件的位置处，代码会自动在 script 标签之前创建
 * 一个 DIV 容器对象。
 * 2) 参数说明
 *   demo = 是否处于 demo 中，demo中的需要导出对象 badge，可以为空，默认为 false
 *   config = 配置信息，可以为空，默认为 "alex,0,20,true,false,user"
 *     [0] = string, 用户名
 *     [1] = string, 风格编号，0=简洁（默认），1=风格1
 *     [2] = number, 消息条数
 *     [3] = boolean, 是否显示用户头像
 *     [4] = boolean, 是否显示好友头像
 *     [5] = string, 显示我的消息或我和好友的消息
 */
(function(){

/**
 * 工具函数库
 */
function $(id){return window.document.getElementById(id);}
function $T(tag){return window.document.getElementsByTagName(tag);}
function $C(tag){return window.document.createElement(tag);}

/**
 * class Badge
 */
function Badge(){this._init.apply(this, arguments);}
(function(){
	this._init = function(){
		//this._serverUrl = "K:\\_setup\\SVN\\Pics\\zuosajs\\";
		this._serverUrl = "http://zuosa.com/badge/zuosajs/";
		this._self = null;
		this._data = null;
		this._type = "user";
		this._url = "http://api.zuosa.com/statuses/" + this._type + "_timeline.json";
		this._username = "";
		this._usericon == null;
		this._title = this._username + "在做啥";
		this._style = "0";  //默认风格
		this._count = 15;
		this._ownerIcon = false;
		this._friendIcon = false;
		this._demo = true;
		this._script = null;
		var ol = $T("script");
		this._htmlNode = ol[ol.length - 1];

		//BODY 中直接执行的代码，所以可以使用 window.document.write，但更好的方式不
		//应该使用这个创建 CSS 样式单
		window.document.write("<style>"
			+ ".Badge {width:204px;background:#F0F0F0;font:12px 宋体;padding:0px;}"
			+ ".Badge A {text-decoration:none;}"
			+ ".Badge A:link{color:#009;}"
			+ ".Badge A:visited{color:#800080;}"
			+ ".Badge A:hover,A:active,A:focus{color:#c00;}"
			+ ".Badge H3 {text-align:center;}"
			+ ".Badge SPAN.owner {display:none;text-align:center;margin-bottom:5px;}"
			+ ".Badge UL {margin:0px;padding:2px;}"
			+ ".Badge TD {font:9pt Arial;line-height:11pt;}"
			+ ".Badge TD DIV {width:100%;margin:2px;word-break:break-all;}"
			+ ".Badge LI {margin-bottom:5px;border-bottom:1px solid #DDDDDD;word-break:break-all;}"
			+ ".Badge LI .cell {float:left:border:1px solid #000000;}"
			+ ".Badge H3 {font:bold 14px;color: #7a9bc5;margin:4px;}"
			+ "</style>");
		this._demo = this._htmlNode.getAttribute("demo") == "true" || false;
		var config = this._htmlNode.getAttribute("config") || "alex,0,20,true,false,user";
		config = config.split(",");

		this.setUsername(config[0]);
		this.setStyle(config[1]);
		this.setCount(parseInt(config[2]));
		this.setOwnerIcon(config[3] == "true");
		this.setFriendIcon(config[4] == "true");
		this.setType(config[5] || "user");
		this.create();
		this.send();
	};
	this.create = function(){
		var obj = $C("div");
		this._htmlNode.parentNode.insertBefore(obj, this._htmlNode);
		this.init(obj);
		return obj;
	};
	this.init = function(obj){
		obj._ptr = this;
		this._self = obj;
		this._self.className = "Badge";
		this._self.innerHTML =
				'<h3></h3>'
			+ '<span class="owner"><a href="" target="_blank"><img src="" border="0" /></a></span>'
			+ '<ul></ul>'
			+ '<a href="http://zuosa.com/' + this._username + '">到做啥关注' + this._username + '</a>';
		this._head = this._self.childNodes[0];
		this._owner = this._self.childNodes[1];
		this._list = this._self.childNodes[2];
	};
	this.dispose = function(){
		this._list = null;
		this._owner = null;
		this._head = null;
		this._htmlNode = null;
		this._script = null;
		this._self._ptr = null;
		this._self = null;
	};
	/*
	this.initConfig = function(username, style, count, ownerIcon, friendIcon){
		this.setUsername(username);
		this.setStyle(style);
		this.setCount(count);
		this.setOwnerIcon(ownerIcon);
		this.setFriendIcon(friendIcon);
		if(this._demo){
		}
	};
	*/
	this.callback = function(obj){
		this._data = obj;
		if(this._ownerIcon) this._owner.style.display = "block";
		var title = this._username + (this._type == "user" ? "" : "和朋友") + "在做啥";
		this.setTitle(title);
		this.setStyle(this._style);
		this.setCount(this._count);
		this.updateOwnerIcon(this._ownerIcon);
		if(this._demo){
			$("zuosa_box_count").value = this._count;
			$("zuosa_box_style").value = this._style;
			$("zuosa_box_title").value = title;
			//$("no_title").
			this.updateCode();
		}
	};
	this.setUsername = function(v){this._username = v;};
	this.setOwnerIcon = function(v){this._ownerIcon = v;};
	this.setFriendIcon = function(v){this._friendIcon = v;};
	/**
	 * @param type {String} 类型(user|friends)
	 */
	this.setType = function(type){
		this._type = type;
		switch(type){
		case "user"   : this._url = "http://api.zuosa.com/statuses/user_timeline.json";break;
		case "friends": this._url = "http://api.zuosa.com/statuses/friends_timeline.json";break;
		}
		if(this._demo)
			this.send();
	};
	this.setStyle = function(style){
		this._style = style;
		if(this._self){
			switch(style){
			case "0":
				this._head.style.fontSize = "";
				this._head.style.fontWeight = "";
				this._head.style.backgroundImage = "";
				this._head.style.margin = "";
				break;
			case "1":
				this._head.style.fontSize = "13px";
				this._head.style.fontWeight = "bold";
				this._head.style.backgroundImage = "url(src/9_01.gif)";
				this._head.style.margin = "0px";
				break;
			}
			this.build();
			this.setCount(this._count);
		}
	};
	this.setCount = function(count){
		this._count = count;
		if(this._self){
			var nodes = this._list.childNodes;
			for(var i = 0; i < nodes.length; i++){
				nodes[i].style.display = (i >= count && i != 20 ? "none" : "block");
			}
			nodes = null;
		}
	};
	this.build = function(){
		var sb = [];
		for(var i = 0; i < this._data.length; i++){
			var o = this._data[i];
			if(o.user.screen_name == this._username && this._usericon == null){
				this._usericon = o.user.profile_image_url;
				this.updateOwnerIcon(this._ownerIcon);
			}
			switch(this._style){
			case "0":
				/*
				sb.push('<li>');
				if(this._friendIcon) sb.push('<img class="cell" width="52" height="52" src="' + o.user.profile_image_url+ '">');
				sb.push('<span class="cell" style="width:100px;">');
				sb.push('<span>');
				if(o.mms_img_pre) sb.push('<a href="' + o.mms_img + '" target="_blank"><img align="left" border="0" src="' + o.mms_img_pre + '" style="margin:2px;" /></a>');
				if(this._type == "friends") sb.push('<a href="http://www.zuosa.com/' + o.user.screen_name + '">' + o.user.screen_name + '</a>：');
				sb.push(o.text);
				sb.push(' <a href="http://zuosa.com/statuses/' + o.id + '" target="_blank">' + this.relative_time2(o.created_at) + '</a>');
				sb.push('</span>');
				sb.push('</span>');
				sb.push('</li>');
				*/
				sb.push('<div style=\'width:100%;overflow:hidden;\'>');
				sb.push('<table width="100%" border="0" cellspacing="0" cellpadding="0" style="border-bottom:1px solid #DDDDDD;">');
				break;
			case "1":
				sb.push('<div style=\'width:100%;overflow:hidden;border:2px solid #869fa1;\'>');
				sb.push('<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#ffffff">');
				break;
			}
			sb.push('<tr valign="top">');
			if(this._friendIcon)
				sb.push('<td width="52"><img width="52" height="52" src="' + o.user.profile_image_url+ '" style="margin:1px;"></td>');
			sb.push('<td width="*" align="left">'
				+ (o.mms_img_pre ? '<div align="center"><a href="' + o.mms_img + '" target="_blank"><img border="0" src="' + o.mms_img_pre + '" style="margin:2px;" /></a></div>' : '')
				+ '<div>'
				+ (this._type == "user" ? "" : '<a href="http://www.zuosa.com/' + o.user.screen_name + '">' + o.user.screen_name + '</a>')
				+ '(' + o.source + ')：' + o.text + '……'
				//+ '<a href="http://zuosa.com/statuses/' + o.id + '" target="_blank">详细</a>'
				+ ' <font color=#888888><a href="http://zuosa.com/statuses/' + o.id + '" target="_blank">于 ' + this.relative_time2(o.created_at) + '</a></font></div></td>');

			sb.push('</tr>');
			sb.push('</table>');
			sb.push('</div>');
			o = null;
		}
		this._list.innerHTML = sb.join("");
		var nodes = this._list.childNodes;
		var w = this._self.offsetWidth - 8;
		for(var i = 0; i < nodes.length; i++){
			nodes[i].style.width = w + "px";
		}
		nodes = null;
	};
	/*
	this.relative_time1 = function(time_value){
		var values = time_value.split(" ");
		time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
		var parsed_date = Date.parse(time_value);
		var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
		var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
		delta = delta + (relative_to.getTimezoneOffset() * 60);
		if(delta < 60){
			return "less than a minute ago";
		}else if(delta < 120){
			return "about a minute ago";
		}else if(delta < (45*60)){
			return (parseInt(delta / 60)).toString() + " minutes ago";
		}else if(delta < (90*60)){
			return "about an hour ago";
		}else if(delta < (24*60*60)){
			return "about " + (parseInt(delta / 3600)).toString() + " hours ago";
		}else if(delta < (48*60*60)){
			return "1 day ago";
		}else{
			return (parseInt(delta / 86400)).toString() + " days ago";
		}
	};
	*/
	this.relative_time2 = function(time_value){
		var values = time_value.split(" ");
		time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
		//var parsed_date = Date.parse(time_value);
		var parsed_date = Date.parse(time_value)-1000*60*60*8; //we use +0800 timezone.
		var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
		var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
		delta = delta + (relative_to.getTimezoneOffset() * 60);
		if(delta < 60){
			return "少于 1 分钟";
		}else if(delta < 120){
			return "约 1 分钟前";
		}else if(delta < (45*60)){
			return (parseInt(delta / 60)).toString() + " 分钟前";
		}else if(delta < (90*60)){
			return "约 1 小时前";
		}else if(delta < (24*60*60)){
			return "约 " + (parseInt(delta / 3600)).toString() + " 小时前";
		}else if(delta < (48*60*60)){
			return "1 天前";
		}else{
			return (parseInt(delta / 86400)).toString() + " 天前";
		}
	};
	this.updateStyle = function(style){
		this.setStyle(style);
		if(this._demo) this.updateCode();
	};
	this.updateNoTitle = function(checkbox){
		this._head.style.display = checkbox.checked ? "none" : "block";
		if(this._demo) this.updateCode();
	};
	this.setTitle = function(title){
		this._head.innerHTML = "<a href=\"http://zuosa.com/" + this._username + "\" target=\"_blank\">" + title + "</a>";
		if(this._demo) this.updateCode();
	};
	this.updateCount = function(count){
		this.setCount(count);
		if(this._demo) this.updateCode();
	};
	this.updateOwnerIcon = function(bShow){
		this._ownerIcon = bShow; 
		this._owner.style.display = this._ownerIcon ? "block" : "none";
		this._owner.childNodes[0].href = "http://zuosa.com/" + this._username;
		this._owner.childNodes[0].childNodes[0].src = this._usericon;
		if(this._demo) this.updateCode();
	};
	this.updateFriendIcon = function(bShow){
		this._friendIcon = bShow;
		this.build();
		this.setCount(this._count);
		if(this._demo) this.updateCode();
	};
	this.getUrl = function(){
		return this._url
			+ "?id=" + this._username
			+ "&callback=badge.callback"
			+ (this._demo ? "" : "&count=" + this._count)  // demo 下不限数量，服务器会最多给 20 条
			+ "&style=" + this._style
			+ "&time=" + new Date().getTime();
	};
	this.send = function(){
		var obj = $C("script");
		obj.type = "text/javascript";
		obj.src = this.getUrl();
		if(!this._script){
			this._htmlNode.parentNode.insertBefore(obj, this._htmlNode);
		}else
			this._script.parentNode.replaceChild(obj, this._script);
		this._script = obj;
		obj = null;
	};
	this.updateCode = function(){
		if($("html_code")){
			var code = "<sc" + "ript type=\"text/javascript\" charset=\"utf-8\""
				+ " src=\"" + this._serverUrl + "js/blogger01.js\""
				+ " config=\"" + this._username + "," + this._style + "," + this._count + "," + this._ownerIcon + "," + this._friendIcon + "," + this._type + "\""
				+ "></sc" + "ript>"
			$("html_code").value = code;
		}
	};
	this.copyData = function(obj){
		obj.select();
		var range = obj.createTextRange();
		range.execCommand("Copy");
		range = null;
	};
}).apply(Badge.prototype);

	var badge = new Badge();
	//if(badge._demo == true)
	window.badge = badge;

})(this);