/**
 * @fileOverview
 * @author z, faps
 * @vision $Id: g.js 1287 2008-5-7 由house/trunk/j/g.js创建分支
 */
/**
 @author z
 @description 通过id获得DOM元素的快捷方式
 @param {String} id
 @returns {element object}
 */
function _g(id){
    return document.getElementById(id);
}
/**
 @author z
 @description 创建一个DOM元素的快捷方式
 @param {String} ele 要创建的元素名
 @returns {element object}
 */
function _ce(ele){
    ele = ele || "div";
    return document.createElement(ele);
}
/**
 @author z
 @description 创建一个文本DOM元素的快捷方式
 @param {String} txt 要创建的文本内容
 @returns {element object}
 */
function _ct(txt){
    return document.createTextNode(txt);
}
/**
 @author z
 @description 创建一个DIV的快捷方式
 @returns {'div' object}
 */
function div(){return _ce('div')}

/**
 @author z
 @param {String} s
 @returns {Int}
 */
function _pi(s){return (isNaN(s))?0:parseInt(s);}
/**
 *@param {String} s
 *@description w.t() 的别名
 *@see w#t
 */
function _t(s){w.t(s);}
/**
  扩展字符串功能
 */
/**
 * @author Flickr.com
 * @returns {String}
 * @description 字符串去空
 */
String.prototype.trim=function(){
    if (this.length=0) return ;
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
/**
 * @author z
 * @param {HTML Tag}
 * @returns {String | empty}
 * @description 给字符串添加标记
 */
String.prototype.addTag=function(tag){
    if (isNull(this)) return ;
    return "<"+tag+">"+this+"</"+tag+">";
}
/**
 * @author Flickr.com
 * @returns {String}
 * @description 字符串中的换行换成br
 */
String.prototype.nl2br = function() {
	return this.split('\n').join('<br \/>\n');
}
/**
 * @author Flickr.com
 * @returns {String}
 * @description 转换字符串为合法的xml格式
 */
String.prototype.escapeForXML = function() {
	return this.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
/**
 * @returns {Int}
 * @description 获得字符串长度，中文x2
 */
String.prototype.len = function(){
    return this.replace(/[^\x00-\xff]/g,"aaa").length;
}
/**
 * 提取字符串中的数字，注意：没有数字时返回false
 * @author z
 * @returns {Int|false}
 */
String.prototype.getNum=function(){
	var re=/\D/g;
	var s=this.replace(re,   '');
	return s==''?false:s;
}
/**
 * @param {String} s
 * @returns {String}
 * @description 字符串去空
 * @see String#trim
 * @deprecated 不建议使用
 * @see  {@link String.prototype.trim}
 */
function trim(s){
    return s.trim();
}
/**
 *@author z
 *@param {String} k
 *@returns {boolean}
 *@description 判断客户都是否是k
 *@deprecated 建议使用jQuery $.browser
 *@example
 *_is_bn('firefox')==true
 */
function _is_bn(k){return (isNull(k))?false:(navigator.userAgent.toLowerCase().indexOf(k.toLowerCase())>-1);}
/**
 *@author z
 *@param {Array} a
 *@returns {boolean}
 *@description 判断参数类型是否是数组
 */
function isArray(a){return a.constructor==Array}
/**
 *@author z
 *@param {String} s
 *@returns {boolean}
 *@description 判断s是否为空
 */
function isNull(s){
    if (s==null) return true;
    return (s+'').trim()+"123" == "123";
}
/**
 *@author faps
 *@param {String} str
 *@returns {boolean}
 *@description 判断参数是否整数
 */
function isInt(str){	return /^(-|\+)?\d+$/.test(str);}
/**
 *@author faps
 *@param {String} str
 *@returns {boolean}
 *@description 判断参数是否为合法的邮件格式
 */
function isMail(str){
	//var par = /^\w*[-.]?\w+@\w+\.([a-zA-Z]{2,4}|\w+\.[a-zA-Z]{2,4})$/;
	var par = /^([a-zA-Z0-9]+[-_.])*[a-zA-Z0-9]+@\w+\.([a-zA-Z]{2,4}|\w+\.[a-zA-Z]{2,4})$/;
	return (str.search(par)>=0);
}
/**
 *@author faps
 *@param {String} s
 *@returns {boolean}
 *@description 判断参数是否为合法的手机号
 */
function isMobile(s){return ((""+s).replace(/^1[35]\d{9}$/,"")=="");}
/**
 *@author faps
 *@param {String} s
 *@returns {boolean}
 *@description 判断参数是否为合法的电话
 */
function isTel(s){return ((""+s).replace(/^[56789]\d{7}$/,"")=="");}
/**
 *@author z
 *@param {String} s
 *@returns {boolean}
 *@description 判断参数是否为中文
 */
function isChinese(s){
	if(s=="") return false;
	return (s.search(/^[^\x00-\xff]+$/g)!=-1);
}
/**
 *@param {String} text 要检测的字符串
 *@param {Int} tt 要检测的类型
 *@param {String} valid_str 指定的检测规则
 *@returns {boolean} 是否为检测的类型
 *@description 字符组合检测，如果没有特别指定检测规则则按照提供的检测类型检测
 *@author faps
 */
function ckText(text, tt, valid_str){
	var p="";
	switch(tt){
		case 1:
			p = /[a-z]+/;
			break;
		case 2:
			p = /[A-Z]+/;
			break;
		case 3:
			p = /[0-9]+/;
			break;
		case 4:
			p = /[^\x00-\xff]+/;
			break;
		case 5:
			p = /[a-zA-Z]+/;
			break;
		case 6:
			p = /[a-z0-9]+/;
			break;
		case 7:
			p = /[A-Z0-9]+/;
			break;
		case 8:
			p = /[a-zA-Z0-9]+/;
			break;
		case 9:
			p = /([a-zA-Z0-9]|[^\x00-\xff])+/;
			break;
		case 10:
			p = /([a-zA-Z]|[^\x00-\xff])+/;
			break;
	}
	if(typeof(valid_str)!="undefined"){
		var ppp = new RegExp("["+valid_str+"]+", "g");
		text = text.replace(ppp, "");
	}
	//alert(text.replace(p,""));
	return (text.replace(p,"")=="");
}
/**
 *@author z
 *@param {String} a
 *@param {String} s
 *@returns {boolean}
 *@description 判断a中是否包含s
 */
function in_array(a, s){
	var s = new String(s).toLowerCase();
	var a = new String(a).toLowerCase();
	return ((","+a+",").indexOf(","+s+",")>-1);
}
/**
 *@author z
 *@param {event} e
 *@param {object} o
 *@returns {boolean}
 *@description 判断鼠标是否在一个对象区域内
 *@requires zEvent
 */
function is_in_area(e, o){
	var ze=new zEvent(e);
	var x = ze.x;
	var y = ze.y;
    var _scroll=getScroll();
	return (x>(findPos(o)[0]-_scroll[0]) && x<(findPos(o)[0]+o.offsetWidth-_scroll[0]) && y>(findPos(o)[1]-_scroll[1]) && y<(findPos(o)[1]+o.offsetHeight-_scroll[1]));
}
//================================操作对象
/**
 *@param {object} obj
 *@returns {Array} [left, top]
 *@description 找到对象的位置
 */
function findPos(obj){
    if(obj==null) return [0,0]
	var curleft = curtop = 0;
	if (obj.offsetParent){
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent){
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}
/**
 *@author z
 *@param {object} o
 *@description 删除对象
 */
function rmo(o){
	if (o!=null){
        if (o.rowIndex==undefined){
            o.innerHTML="";
            o.parentNode.removeChild(o);
        }else{
            o.parentNode.deleteRow(o.sectionRowIndex)
        }
	}
}
//显示对象属性
//var _list=function(o){for (a in o){	_t([o.a,o[a]],1)}}
/**
 *@author z
 *@param {object} o
 *@param {Integer} sec
 *@returns {false|0|iTimerID}
 *@description 自动隐藏对象
 */
function auto_hide(o, sec){
    if (o==null) return false;
	if (sec==0){
		o.style.display='none';
		return 0;
	}
	return setTimeout(function(){o.style.display='none'}, sec*1000);
}

/**
 *@class
 *@constructor
 *@name zEvent
 *@param {event} evt
 *@author z
 */
function zEvent(evt){
	var e=evt || window.event;
	this.offsetX=e.layerX||e.offsetX;
	this.offsetY=e.layerY||e.offsetY;
	this.x=e.clientX||e.x;
	this.y=e.clientY||e.y;
	this.srcElement=e.target||e.srcElement;
	this.wheelDelta=e.detail||e.wheelDelta;
	this.keyCode=e.which||e.keyCode;
	this.o=e;
}

/**
 *@param {String} u url
 *@param {String} target 目标框架
 *@description 指定 window.location或者u.location
 *@author z
 */
function _go(u){
	var tg=(arguments.length>1)?arguments[1]:window;
	tg.location.href=u;
}
/**
 *@returns {Array} [left, top]
 *@description 得到当前的滚动条位置
 *@author z
 */
function getScroll(){
	if (arguments.length>0)	return [arguments[0].scrollLeft,arguments[0].scrollTop];
	return (document.documentElement.scrollTop>0)?[document.documentElement.scrollLeft,document.documentElement.scrollTop]:[document.body.scrollLeft,document.body.scrollTop];
}
//地址栏参数
/**
 * 获取url中的变量值
 *@author faps
 *@param {String} k 变量名
 *@returns {String|null}
 */
function gp(k){
	var query=(arguments.length>1)?arguments[1]:window.location.search;
	if (query != null || query != ""){
		query = query.replace(/^\?+/, "");
		var qArray = query.split("&");
		var len = qArray.length;
		if (len > 0){
			for (var i=0; i<len; i++){
				var sArray = qArray[i].split("=", 2);
				if (sArray[0] && sArray[1] && sArray[0] == k)		return unescape(sArray[1]);
			}
		}
	}
	return null;
}
/**
 *@param {filename} s
 *@returns {String}
 *@description 取文件扩展名
 */
function get_extname(s){
	var s = new String(s).toLowerCase();
	return ((s.lastIndexOf(".")>-1) &&((s.length-1)>s.lastIndexOf(".")))?s.substring(s.lastIndexOf(".")+1):false;
}
/**
 *@param {obejct} o
 *@param {String} s
 *@description 设置对象背景色
 *@author z
 */
function set_color(o,s){o.style.background=s}
/**
 *@param {obejct} o
 *@param {String} color
 *@description 对象获得焦点时更改背景色，失去焦点时恢复背景色
 *@author z
 */
function highlight(o,color){
    var o_color='#fff';
    if (isNull(color)){
        if (!isNull(o.getAttribute('highlight')))
            color=o.getAttribute('highlight');
    }
    if (!isNull(o.style.background)){
        o_color=o.style.background;
    }
    o.style.background=color;
    o.onblur=function(){
        this.style.background=o_color
    }
}
/**
 *@author faps
 *@param {String} tid
 *@param {String} bc
 *@param {String} bc2
 *@param {String} vc
 *@param {String} s 开始的行数
 *@param {String} end 结束的行数
 *@description 表格斑线
 */
function setTabBG(tid, bc, bc2, vc, s, end){
    if (_g(tid)==null) return false;
	var o = _g(tid);
	var o_sub = o.getElementsByTagName("tr");
	var n = o_sub.length;
	if(n>0){
		var start = (typeof(s)=="undefined")?0:s-1;
		var end = (typeof(end)=="undefined")?n:end;
		end =(end>n||end==0)?n:(end<0?(n+end):end);
		for(i=start;i<end;i++){
			o_sub[i].style.backgroundColor=(i%2==0)?bc:bc2
			if(typeof(vc)!="undefined" && vc!=null){
				if(i%2==0){
					o_sub[i].onmouseout = function (){ this.style.backgroundColor = bc;}
				}else{
					o_sub[i].onmouseout = function (){ this.style.backgroundColor = bc2;}
				}
				o_sub[i].onmouseover = function(){ this.style.backgroundColor = vc;}
			}
		}
	}
}
/**
 *@author faps
 *@param {Int} y
 *@param {Int} m
 *@param {Int} d_start
 *@param {Int} to
 *@description 按照y,m生成日期
 */
function listDay(y, m, d_start, to){
	var d=0;
	y = parseInt(y);
	switch(parseInt(m)){
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			d = 31;
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			d = 30;
			break;
		case 2:
			d = ((y%4==0 && y%100!=0) || y%400==0)?29:28;
			break;
	}
	if(d_start<1) d_start=1;
	if(d_start>d) d_start=d;
	var o = document.getElementById(to);
	o.innerHTML = "";
	var s = "";
	for(i=d_start;i<=d;i++){
		var op=document.createElement("option");
		op.value=i;
		op.text=i;
		o.options.add(op);
	}
}
/**
 *@author z
 *@param {object} o
 *@param {String} s
 *@param {Int|String} pos
 *@returns {element object}
 *@requires auto_hide
 *@see auto_hide
 *@description 在o上创建提示，内容为s，提示放在pos，如果pos为正负数，则以o的中间位置偏移
 *@example
 * op_tip(o, 'hello', 'center');
 * op_tip(_g('div'), 'hello', -100);
 */
function op_tip(o,s,pos){
	var odiv=$("#op_tip_dialog_box");
	var $o=$(o);
	if (odiv.length==1){
        if (o==null){
			$o.hide();
			//auto_hide(odiv[0], 0);
			return false;
		}
		odiv.show();
	}else{
		if(o==null){
			return false;
		}
		odiv=$("<div id='op_tip_dialog_box'><div class='tip-close'></div><div class='tip-content'></div></div>").appendTo('body');
	}
	var ooffset=$o.offset();
	odiv.css('left', (ooffset.left+$o.width()/2));
    if (pos==undefined) pos="center";
    if (s==undefined) s="";
	if (pos=="center"){
		odiv.css('left', (ooffset.left+$o.width()/2 - odiv.width()/2));
	}else if (isInt(pos)){
		odiv.css('left', (ooffset.left+$o.width()/2 + pos));
	}
	odiv.css('top', (ooffset.top-54)).find('.tip-content').html(s);
    $o.mouseout(function(){
		odiv.fadeOut('slow');
		//auto_hide(odiv[0], 5);
	});
    return odiv[0];
}




 /**
  *@description 将一个网址添加到收藏夹
  *@param {String} url
  *@param {String} title
  *@author z
  */
function addsfav(url, title){
    if ((typeof window.sidebar == 'object') && (typeof window.sidebar.addPanel == 'function')){
        //Gecko
        window.sidebar.addPanel(title,url,"");
    }else{
        //IE
        window.external.AddFavorite(url,title);
    }
}
 /**
  *@description 复制字符串到剪贴板
  *@param {String} str 要复制的字符串
  *@returns {Boolean}
  *@author faps
  */
function copyToCB(str){
	try{
		clipboardData.setData('Text', str);
		if(arguments.length>1) wTools.hint(arguments[1]);
		return true;
	}catch(e){
		return false;
	}
}

/**
 *@namespace
 */
var wTools={};
/**
 *@function
 */
wTools.hint=function(txt, callback, pt, img, classname, mask){
    var txt=txt||'';
    var imgurl=img||"";
    if (callback==undefined) callback="";
    classname=classname||'w_alert2';
    if (typeof mask == 'undefined'){mask=true}
    if (pt==undefined) pt=1;
    var tb=document.createElement("div");
    if (imgurl!=""){
        var ib=document.createElement("img");
        tb.appendChild(ib);
        ib.src=imgurl;
    }else{
        tb.style.cssText="padding:4px 0 18px;";
    }
    tb.innerHTML+=txt;
    if (callback==undefined) callback="";
    var btn=[];
    if (pt==1){//有按钮
        if (callback!=''){//有确定和取消
            btn.push({caption:' 确定 ', callback:function(){w.setCallback(callback, 1);}}, {caption:' 取消 ', callback:function(){w.setCallback(callback, 0);}})
        }else{//只有关闭
            btn.push({caption:' 关闭 '});
        }
    }
    var panel=w.UI.hint.create('', tb, btn, mask, classname);
    return panel;
}
/**
 *@function
 */
wTools.hint.close=function(){w.UI.hint.close();}
/**
 *@author xap
 */
function rmo_time(o,t,c){
	//颜色渐变，删除某对象
	var c_arr = Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
	if (c==16){
		rmo(o);
	}else{
		//o.style.background = "#"+c_arr[c]+c_arr[c]+c_arr[c];	//底色渐变
		o.style.color = "#"+c_arr[c]+c_arr[c]+c_arr[c];		//字体颜色渐变
		setTimeout(function(){rmo_time(o,t,c+1)},t);
	}
}

//填充距离
/**
 *@author faps
 */
function fill_distance(lup, fdp, fdp_id_prv){
	//lup:[uid, x, y]
	//fdp:[lup, lup, lup, ...]
	//fdp_id_prv:[id_prv1, id_prv2, ...]
	if(typeof(lup[1])=='number' && typeof(lup[2])=='number'){
		var d = "";
		var o = null;
		for(i=0;i<fdp.length;i++){
			d = "";
			if(fdp[i][0]!=lup[0]) d = Map2s.getDistance(lup[1], lup[2], fdp[i][1], fdp[i][2]);//getDistance(lup[1], lup[2], fdp[i][1], fdp[i][2]);
			if(d!=false){
				for(j=0;j<fdp_id_prv.length;j++){
					$o = $("#"+fdp_id_prv[j]+fdp[i][0]);
					if($o.length>0){
						$o.text(d).addClass('block');
					}
				}
			}
		}
	}
}
/**
 *@author faps
 */
function newvalid(id) { //更换验证码
	_g(id).src = "/valid_code.php?t="+Math.random();
}

/**
 *@class
 *@constructor
 *@description 颜色渐变
 *@param {Number} x
 *@param {Number} y
 */
function GradualColor(){
    this.idx=0;
    this.colorList=['#ffff00','#ffff33','#ffff66','#ffff99','#ffffcc','#ffffff'];
    this.timeId=0;
    /**
     *@memberOf GradualColor
     *@returns {String} color
     *@private
     */
    this.colors=function(){
        var a='#ffff', color=new Array(), b,c;
        for (var i=0; i<256; i+=51) {
            i=Math.floor(i);
            b=i.toString(16);
            c="00";
            b=c.substr(0, 2-b.length)+""+b;
            color.push(a+b);
        }
        return color;
    };
    /**
     *@memberOf GradualColor
     *@param {element object} o DOM元素
     */
    this.run=function(o){
        o.style.backgroundColor=this.colorList[this.idx];
        this.idx++;
        if (this.idx==6){
            clearTimeout(this.timeId);
        }
        var self=this;
        this.timeId=setTimeout(function(){self.run(o)}, 200)
    }
}

/**
* 时间对象的格式化;
*@param {String} format
*@example
*  new Date().format("YYYY-MM-dd hh:mm:ss")
*/
Date.prototype.format = function(format){
    var o = {
        "M+" :  this.getMonth()+1,  //month
        "d+" :  this.getDate(),     //day
        "h+" :  this.getHours(),    //hour
        "m+" :  this.getMinutes(),  //minute
        "s+" :  this.getSeconds(), //second
        "q+" :  Math.floor((this.getMonth()+3)/3),  //quarter
        "S"  :  this.getMilliseconds() //millisecond
    }

    if(/(y|Y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }

    for(var k in o) {
        if(new RegExp("("+ k +")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
        }
    }
    return format;
}
/**
* 一组格式化方法;
*@namespace
*/
var Format={
    /**
     *格式化距离
     *param {Number} len 要格式化的字符串
     *param {Integer} precision 小数点后的位数
     */
    distance:function(len, precision){
        precision=precision||2;
        var a=Math.pow(10, precision);
        return (len>=1000)?Math.floor(len/10)/a+"公里":Math.floor(len*a)/a+"米";
    },
	/**
	 *把秒转化成可读的时间格式
	 *param {Integer} 秒数
	 */
    sec2time:function(s){
        var me=this;
        return s>=60?
                        s/60>=60?
                            Math.floor(s/3600)+"小时"+(s%3600>0?me.sec2time(s%3600):'')
                            :(Math.floor(s/60)+"分"+(s%60>0?me.sec2time(s%60):''))
                        :(s+"秒");
    }
};


/**
* 处理html
*@param {String} str
*@param {String} a
*@example
*  disableHtml('<p>a</p><b>adf<br/></b>', 'b,br');
*/
function disableHtml(str, a) {
	var ab_arr = [];
	str = str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g, '&gt;');
	if(typeof(a)=="undefined") return str;
	if(a.trim()!='') ab_arr = a.split(',');
	if(ab_arr.length>0) {
		for(i=0;i<ab_arr.length;i++) {
			if(ab_arr[i].trim()!='') {
				re = "";
				re = new RegExp("&lt;(\/?"+ab_arr[i]+"\\b.*?\/?)&gt;","gim");
				str = str.replace(re,'<$1>');
			}
		}
	}
	return str;
}

/*
 * Jquery checkBox 选择容器中的checkbox
 * @param string status //all:全选 rev:反选 clear:清空
 * @param dom/jquery object //指定一个checkBox容器, 默认:$(docuemnt)
*/
function selectCheckBox(status, container) {
	if(typeof(status)=="undefined") status='all';
	if(typeof(container)=="undefined") container=$(document);
	$('input:checkbox', container).each(function(){
		switch(status) {
			case 'all':
				this.checked=true;
				break;
			case 'clear':
				this.checked=false;
				break;
			case 'rev':
				this.checked=!this.checked;
				break;
		}
	});
}

/*
 * Jquery checkBox 返回选中checkbox的值
 * @param object $checkboxes
 * @return string ids
 */
function getSelectedIds($checkboxes) {
	var id_arr = [];
	$checkboxes.each(function(){
		id_arr.push(this.value);
	});
	return id_arr.join(',');
}


/**
 *@author faps
 *@param {String} k 地址栏参数名
 *@param {String} v 参数新值
 *@description 替换地址栏参数
 */
function rp(k, v)
{
	var query=(arguments.length>2)?arguments[2]:window.location.search;
	if (query != "")
	{
		query = query.replace(/^\?+/, "");
		var qArray = query.split("&");
		var len = qArray.length;
		if (len > 0)
		{
			var par = Array();
			var r = false;
			for (var i=0; i<len; i++)
			{
				var sArray = qArray[i].split("=", 2);
				if (sArray[0] && sArray[1] && sArray[0] == k)
				{
					r = true;
					sArray[1] = v;
				}
				par[i]=sArray.join("=");
			}
			if(!r) par[i]=k+"="+v;
			return "?"+par.join("&");
		}
	}
	else	{return "?"+k+"="+v;}
}



function setHomepage(url)
{
 if (document.all)
    {
        document.body.style.behavior='url(#default#homepage)';
  document.body.setHomePage(url);

    }
    else if (window.sidebar)
    {
    if(window.netscape)
    {
         try
   {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
         }
         catch (e)
         {
    alert( "该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true" );
         }
    }
    var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
    prefs.setCharPref('browser.startup.homepage', url);
 }
 return false;
}
