// 格式化
String.prototype.format = function() {
    if (arguments.length == 0)
        return this;
    var reg = /{(\d+)?}/g;
    var args = arguments;
    var result = this.replace(reg, function($0, $1) {
        return args[parseInt($1)];
    })
    return result;
}
// 判断是否email
String.prototype.isEmail = function() {
    return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(this);
}
// 去空格
String.prototype.trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

String.prototype.filterHTMLTag = function() {
    var tmp = this;
    tmp = tmp.replace(/ /gi, "&nbsp;");
    tmp = tmp.replace(/</gi, "&lt;");
    tmp = tmp.replace(/>/gi, "&gt;");
    tmp = tmp.replace(/\r\n/gi, "<br/>");
    tmp = tmp.replace(/\n/gi, "<br/>");
    return tmp;
}

String.prototype.isExistChinese = function() {
    return !/^[\x00-\xff]*$/.test(this);
}

function px(px) {
    if (px == undefined) {
        return 0;
    }

    if (px.indexOf('px') < 0)
        return px;

    return parseInt(px.substring(0, px.indexOf('px')));
}


//时间处理
function prettyDate(time){ //console.log(time);
	var date, re, r, ms_time, ms_diff, diff, day_diff, now = new Date();
	re = /(\d{4})[\/-](\d{2})[\/-](\d{2})\s(\d{2})\:(\d{2})\:(\d{2})/;
	r  = time.match(re);	//console.log(r);
	var serverTZ = -480;
	if (r != null) {
		ms_time = Date.parse(r[2]+"/"+r[3]+"/"+r[1]+" "+r[4]+":"+r[5]+":"+r[6]);
		//ms_time = Date.UTC(r[1],r[2],r[3],r[4],r[5],r[6]) + serverTZ * 60 * 1000;
	} else {
		date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," "));
		ms_time = date.getTime();
	}
	var offset = (serverTZ - now.getTimezoneOffset())*60*1000; //console.log(offset);
		ms_diff = (now.getTime() - ms_time);
		diff = (ms_diff + offset) / 1000;
		day_diff = Math.floor(diff / 86400);
	//console.log(ms_time, ms_diff, diff, day_diff);
	
	if ( isNaN(day_diff) || day_diff < 0 )
		return false;
	if ( day_diff >= 31 ) {
		date = new Date(ms_time);
		var year = date.getFullYear();
		if (now.getFullYear() == year) {
			return (date.getMonth() + 1) + "月" + date.getDate() + "日";
		}
		return year + "-" +(date.getMonth() + 1) + "-" + date.getDate();
	}
	
	return day_diff == 0 && (
			diff < 60 && "刚才" ||
			diff < 120 && "1分钟前" ||
			diff < 3600 && Math.floor( diff / 60 ) + " 分钟前" ||
			diff < 7200 && "1 小时前" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " 小时前") ||
		day_diff == 1 && "昨天" ||
		day_diff == 2 && "前天" ||
		day_diff < 7 && day_diff + " 天前" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " 周前";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
};