var basepath = window["p_basepath"] || "";
var loadinghtml = '
加载中...
';
base = {
local:function(){
return base.cookie("local") || 'zh';
},
//控制台日志记录
logger : {
log:function(msg){
if(!!window.console){
window.console.log(msg);
}
},
info:function(msg){
if(!!window.console){
window.console.info(msg);
}
},
warn:function(msg){
if(!!window.console){
window.console.warn(msg);
}
},
error:function(msg){
if(!!window.console){
window.console.error(msg);
}
//base.logger.log2server(" [error] " + msg);
} ,
log2server:function(content){
//base.ajax.post(window["p_basepath"] + "/service/behaviorlog/record",true,{
// info:"[web] "+ content
//},"json", function(){},function(){});
}
},
handleuri : function(uri){
return uri;
}
};
base.dialog = {
_mask_classid:"_mask_classid",
_zindex:100,
_getzindex:function(){
return base.dialog._zindex++;
},
//显示遮罩
// .blank{ position:fixed; background:#000000; width:100%; height:100%; z-index:1; display:none;
// filter:alpha(opacity=30); /*ie滤镜,透明度50%*/
// -moz-opacity:0.3; /*firefox私有,透明度50%*/
// opacity:0.3;/*其他,透明度50%*/}
showmask:function(zindex){
// if($("."+base.dialog._mask_classid,document.body).length == 0){
var mask = $("", {
"class":base.dialog._mask_classid,
css: {
"position": "fixed",
"background": "#000000",
"width": "100%",
"height": "100%",
"z-index": zindex || 999,
"filter": "alpha(opacity=30)", /*ie滤镜,透明度50%*/
"-moz-opacity": 0.3, /*firefox私有,透明度50%*/
"opacity": 0.3/*其他,透明度50%*/
}
});
$(document.body).prepend(mask);
// }else{
// $("."+base.dialog._mask_classid,document.body).show();
// }
},
hidemask:function(){
var $masks = $("."+base.dialog._mask_classid, document.body);
var $currentmask = null;
for(var i= 0,len=$masks.length; i < len; i++){
if($currentmask == null){
$currentmask = $($masks[i]);
}else if(parseint($currentmask.css("z-index")) < parseint($($masks[i]).css("z-index"))){
$currentmask = $($masks[i]);
}
}
if($currentmask != null){
$currentmask.remove();
}
},
/**
* 加载内容
* @param uri 请求uri
* @param params {}
* @param callback 回调函数
*/
openhtml:function(uri, params, callback, choicecls){
uri = base.handleuri(uri);
var $loadcontainer = $(".loadhtml_classid",document.body);
if($loadcontainer.length == 0){
$(document.body).append($("", {
"class": "loadhtml_classid",
css: { clear: "both", height: "0px", "overflow": "hidden"}
}));
$loadcontainer = $(".loadhtml_classid",document.body);
}
if($("."+choicecls, $loadcontainer).length > 0){
$("."+choicecls, $loadcontainer).remove();
}
var uricontainer = $("", {"class":"_container " + choicecls, css:{display:"none"}});
uricontainer.data("uri", uri);
uricontainer.data("params", params);
$loadcontainer.append(uricontainer);
base.dialog.showmask(base.dialog._getzindex());
base.tip.showloading($(document.body), true);
base.ajax.load(uri, params, function(){
base.tip.showloading($(document.body), false);
uricontainer.css("z-index", base.dialog._getzindex());
uricontainer.show();
if (callback) {
callback.call(this);
}
}, uricontainer);
},
closehtml:function(choicecls){
base.dialog.hidemask();
var $loadcontainer = $(".loadhtml_classid",document.body);
if($("."+choicecls, $loadcontainer).length > 0){
$("."+choicecls, $loadcontainer).remove();
}
},
/**
* 打开iframe
* @param url
* @param choicecls
* @param config {width, height}
*/
openiframe: function (url, choicecls, config) {
url = base.handleuri(url);
config = config || {width:400, height:260};
var $loadcontainer = $(".loadiframe_classid",document.body);
if($loadcontainer.length == 0){
$(document.body).append($("", {
"class": "loadiframe_classid",
css: { clear: "both", height: "0px", "overflow": "hidden"}
}));
$loadcontainer = $(".loadiframe_classid",document.body);
}
if($("iframe."+choicecls, $loadcontainer).length > 0){
$("iframe."+choicecls, $loadcontainer).remove();
}
base.tip.showloading($(document.body), true);
var height = parseint(config.height);
var width = parseint(config.width);
var top = "-" + parseint(height/2) + "px";
var left = "-" + parseint(width/2) + "px";
var iframecontainer = $("",
{src:url, "class":"_container " + choicecls,frameborder:0,
scroling:"auto",
height:height,
width:width,
css:{
display:"none",
position:"fixed",
width:"400px",height:"260px",
background:"#f2f2f2",
top:"50%", left:"50%",
"margin-top":top,
"margin-left":left,
height:height + "px",
width:width + "px",
"border-radius":"10px",
"box-shadow":"0px 0px 10px #333333",
border:"1px solid #ccc"
}
});
iframecontainer.data("url", url);
$loadcontainer.append(iframecontainer);
base.dialog.showmask(base.dialog._getzindex());
iframecontainer.css("z-index", base.dialog._getzindex());
iframecontainer.show();
base.tip.showloading($(document.body), false);
},
closeiframe:function(choicecls){
parent.window.base.dialog.hidemask();
var $loadcontainer = $(".loadiframe_classid",parent.window.document.body);
if($("iframe."+choicecls, $loadcontainer).length > 0){
$("iframe."+choicecls, $loadcontainer).remove();
}
},
/**
* 打开iframe窗口
* @param title
* @param width
* @param height
* @param url
*/
openiframelayer:function(title, width, height, url, config){
url = base.handleuri(url);
var settings = {
type: 2,
shadeclose: false,
title: title,
shade: [0.8, '#000'],
border: [0],
area: [(width != undefined ? width:1000) + 'px', (height != undefined ? height: ($(window).height() - 50)) +'px'],
content: url
};
settings = $.extend({}, settings, config);
layui.use('layer', function(){
var layer = layui.layer;
layer.open(settings);
});
},
/**
* 打开iframe窗口
* @param title
* @param width
* @param height
* @param selector #id
*/
openlayer:function(title, width, height, selector, config){
var settings = {
type: 1,
shadeclose: false,
title: title,
closebtn: [0, true],
shade: [0.8, '#000'],
border: [0],
offset: ['',''],
area: [(width != undefined ? width:1000) + 'px', (height != undefined ? height: ($(window).height() - 50)) +'px'],
page: {dom: selector}
};
settings = $.extend({}, settings, config);
var index = $.layer(settings);
return index;
},
closeiframelayer:function(index){
layer.close(index);
},
closealllayer:function(){
layer.closeall();
}
};
//need jquery
base.ajax = {
_init:function(){
if(!!!$.ajaxsetup){
return ;
}
$.ajaxsetup({
timeout:60000,
//发送请求前触发
beforesend: function (xmlhttprequest) {
if(window["token"] != undefined){
//可以设置自定义标头
xmlhttprequest.setrequestheader('token', window["token"]);
}
},
error:function (xmlhttprequest, textstatus, errorthrown) {
// 通常 textstatus 和 errorthrown 之中
// 只有一个会包含信息
//this; // 调用本次ajax请求时传递的options参数
base.logger.error(xmlhttprequest.responsetext);
if(xmlhttprequest.responsetext != "" && xmlhttprequest.responsetext.indexof("reloginalert") != -1){
alert(xmlhttprequest.responsetext);
}
}
});
},
/**
* 加载内容
* @param uri 请求uri
* @param params {}
* @param callback 回调函数
* @param containerid 指定加载的容器id,如:"#maincontainerid"(可选)
*/
load : function(uri, params, callback, containerid) {
base.ajax._init();
uri = base.handleuri(uri);
params = params || {};
containerid = containerid || "";
if(containerid == ""){
alert("containerid参数未传入");
return false;
}
//$(containerid).empty();
//$(containerid).html(loadinghtml);
var showloading = $(containerid).data("showloading");
if(!!showloading){
base.tip.showloading($(containerid), true);
}
return $(containerid).load(uri, params, function(text, status, res) {
if(text.indexof('loginpage="true"') != -1){
$(containerid).html("登录超时,请重新登录!");
alert("登录超时,请重新登录!");
location.href = window["p_basepath"] + "/page/login";
}
if (callback) {
if(!!showloading){
base.tip.showloading($(containerid), false);
}
callback.call(this);
}
});
},
/**
* ajax同步请求处理
* @param url 请求的url
* @param async 是否异步
* @param params 请求的参数 {param1:value1,param2:value2}
* @param datatype html、json、jsonp、script、text ,默认json
* @param callback(json, status)
* @param errorcallback(xmlhttprequest, textstatus, errorthrown)
*/
post : function(url, async ,params,datatype, callback, errorcallback){
base.ajax._init();
url = base.handleuri(url);
return $.ajax({
type: "post",
url: url,
data: params,
datatype : datatype ? datatype : "json",
async: async,//是否异步
success: function(json,statu){
try{
if(callback){
callback(json, statu).call(this);
}
}catch(e){
}
},
error:function (xmlhttprequest, textstatus, errorthrown) {
// 通常 textstatus 和 errorthrown 之中
// 只有一个会包含信息
//this; // 调用本次ajax请求时传递的options参数
base.logger.error(xmlhttprequest.responsetext);
if(errorcallback){
errorcallback(xmlhttprequest, textstatus, errorthrown);
}else{
//&& xmlhttprequest.responsetext.indexof("reloginalert") != -1
if(xmlhttprequest.responsetext != "" ){
if(xmlhttprequest.responsetext.indexof('loginpage="true"') != -1){
alert("登录超时,请重新登录!");
location.href = window["p_basepath"] + "/page/login";
}
base.logger.error(xmlhttprequest.responsetext);
}
}
}
});
},
//记录请求时间
_recordrequesttime:function(target){
$(target).data("_ajax_latestrequesttime",new date().gettime());//设置最近一次的请求完成时间 毫秒
},
_recordrequestcount:function(target){
$(target).data("_ajax_latestrequestcount",new date().gettime());
},
/**
* 记录请求信息
* @param target 目标信息记录载体
* @param intervalseconds 允许的间隔时间 秒
*/
recordrequestinfo:function(target, intervalseconds){
var currenttime = new date().gettime();
var beforerequesttime = $(target).data("_ajax_latestrequesttime")||currenttime;
$(target).data("_ajax_intervalseconds", intervalseconds);
var count = 1;
if(parseint((currenttime - beforerequesttime)/1000) <= intervalseconds){
count = parseint($(target).data("_ajax_latestrequestcount") || 0);
count++;
}
$(target).data("_ajax_latestrequestcount", count);
$(target).data("_ajax_latestrequesttime",currenttime);//设置最近一次的请求完成时间 毫秒
},
/**
* 检查是否可以请求
* @param target 目标信息记录载体
* @param allowcounts 在记录的时间段内允许连续请求的次数
* @returns {boolean}
*/
checkenablerequest:function(target, allowcount){
var currenttime = new date().gettime();
var beforerequesttime = $(target).data("_ajax_latestrequesttime")||currenttime;
var intervalseconds = parseint($(target).data("_ajax_intervalseconds") || 60);
if(parseint((currenttime - beforerequesttime)/1000) > intervalseconds){
$(target).data("_ajax_latestrequestcount", 0);
}
var count = parseint($(target).data("_ajax_latestrequestcount") || 0);
return count <= allowcount;
}
}
//use noty tip
base.tip = {
_init: function() {
if(!!!$.jbox){
return false;
}
/* jbox 全局设置 */
var _jboxconfig = {};
_jboxconfig.defaults = {
id: null, /* 在页面中的唯一id,如果为null则自动为随机id,一个id只会显示一个jbox */
zindex:5000,
top: '30%', /* 窗口离顶部的距离,可以是百分比或像素(如 '100px') */
border: 5, /* 窗口的外边框像素大小,必须是0以上的整数 */
opacity: 0.2, /* 窗口隔离层的透明度,如果设置为0,则不显示隔离层 */
timeout: 0, /* 窗口显示多少毫秒后自动关闭,如果设置为0,则不自动关闭 */
showtype: 'fade', /* 窗口显示的类型,可选值有:show、fade、slide */
showspeed: 'fast', /* 窗口显示的速度,可选值有:'slow'、'fast'、表示毫秒的整数 */
showicon: true, /* 是否显示窗口标题的图标,true显示,false不显示,或自定义的css样式类名(以为图标为背景) */
showclose: true, /* 是否显示窗口右上角的关闭按钮 */
draggable: true, /* 是否可以拖动窗口 */
draglimit: true, /* 在可以拖动窗口的情况下,是否限制在可视范围 */
dragclone: false, /* 在可以拖动窗口的情况下,鼠标按下时窗口是否克隆窗口 */
persistent: true, /* 在显示隔离层的情况下,点击隔离层时,是否坚持窗口不关闭 */
showscrolling: true, /* 是否显示浏览的滚动条 */
ajaxdata: {}, /* 在窗口内容使用post:前缀标识的情况下,ajax post的数据,例如:{ id: 1 } 或 "id=1" */
iframescrolling: 'auto', /* 在窗口内容使用iframe:前缀标识的情况下,iframe的scrolling属性值,可选值有:'auto'、'yes'、'no' */
title: 'jbox', /* 窗口的标题 */
width: 350, /* 窗口的宽度,值为'auto'或表示像素的整数 */
height: 'auto', /* 窗口的高度,值为'auto'或表示像素的整数 */
bottomtext: '', /* 窗口的按钮左边的内容,当没有按钮时此设置无效 */
buttons: { '确定': 'ok' }, /* 窗口的按钮 */
buttonsfocus: 0, /* 表示第几个按钮为默认按钮,索引从0开始 */
loaded: function (h) { }, /* 窗口加载完成后执行的函数,需要注意的是,如果是ajax或iframe也是要等加载完http请求才算窗口加载完成,参数h表示窗口内容的jquery对象 */
submit: function (v, h, f) { return true; }, /* 点击窗口按钮后的回调函数,返回true时表示关闭窗口,参数有三个,v表示所点的按钮的返回值,h表示窗口内容的jquery对象,f表示窗口内容里的form表单键值 */
closed: function () { } /* 窗口关闭后执行的函数 */
};
_jboxconfig.statedefaults = {
content: '', /* 状态的内容,不支持前缀标识 */
buttons: { '确定': 'ok' }, /* 状态的按钮 */
buttonsfocus: 0, /* 表示第几个按钮为默认按钮,索引从0开始 */
submit: function (v, h, f) { return true; } /* 点击状态按钮后的回调函数,返回true时表示关闭窗口,参数有三个,v表示所点的按钮的返回值,h表示窗口内容的jquery对象,f表示窗口内容里的form表单键值 */
};
_jboxconfig.tipdefaults = {
content: '', /* 提示的内容,不支持前缀标识 */
icon: 'info', /* 提示的图标,可选值有'info'、'success'、'warning'、'error' */
top: '40%', /* 提示离顶部的距离,可以是百分比或像素(如 '100px') */
width: 'auto', /* 提示的高度,值为'auto'或表示像素的整数 */
height: 'auto', /* 提示的高度,值为'auto'或表示像素的整数 */
opacity: 0, /* 窗口隔离层的透明度,如果设置为0,则不显示隔离层 */
timeout: 2000, /* 提示显示多少毫秒后自动关闭,必须是大于0的整数 */
closed: function () { } /* 提示关闭后执行的函数 */
};
_jboxconfig.messagerdefaults = {
content: '', /* 信息的内容,不支持前缀标识 */
title: '温馨提示', /* 信息的标题 */
icon: 'none', /* 信息图标,值为'none'时为不显示图标,可选值有'none'、'info'、'question'、'success'、'warning'、'error' */
width: 350, /* 信息的高度,值为'auto'或表示像素的整数 */
height: 'auto', /* 信息的高度,值为'auto'或表示像素的整数 */
timeout: 3000, /* 信息显示多少毫秒后自动关闭,如果设置为0,则不自动关闭 */
showtype: 'slide', /* 信息显示的类型,可选值有:show、fade、slide */
showspeed: 600, /* 信息显示的速度,可选值有:'slow'、'fast'、表示毫秒的整数 */
border: 0, /* 信息的外边框像素大小,必须是0以上的整数 */
buttons: {}, /* 信息的按钮 */
buttonsfocus: 0, /* 表示第几个按钮为默认按钮,索引从0开始 */
loaded: function (h) { }, /* 窗口加载完成后执行的函数,参数h表示窗口内容的jquery对象 */
submit: function (v, h, f) { return true; }, /* 点击信息按钮后的回调函数,返回true时表示关闭窗口,参数有三个,v表示所点的按钮的返回值,h表示窗口内容的jquery对象,f表示窗口内容里的form表单键值 */
closed: function () { } /* 信息关闭后执行的函数 */
};
_jboxconfig.languagedefaults = {
close: '关闭', /* 窗口右上角关闭按钮提示 */
ok: '确定', /* $.jbox.prompt() 系列方法的“确定”按钮文字 */
yes: '是', /* $.jbox.warning() 方法的“是”按钮文字 */
no: '否', /* $.jbox.warning() 方法的“否”按钮文字 */
cancel: '取消' /* $.jbox.confirm() 和 $.jbox.warning() 方法的“取消”按钮文字 */
};
layui.use('layer', function(){
var layer = layui.layer;
});
$.jbox.setdefaults(_jboxconfig);
},
_autoclose:function(noty, waitseconds){
},
closeall:function(){
},
alert : function(msg, callback){
layui.use('layer', function(){
var layer = layui.layer;
layer.open({
title: '温馨提示',
icon: 0,
content: msg,
yes: function(index){
if (typeof callback === 'function'){
callback.call(this);
}
layer.close(index)
}
});
});
},
information : function(msg){
jbox.alert(msg, '温馨提示', {width: 400, height: 120, icon:'info' });
},
error : function(msg, callback){
layui.use('layer', function(){
var layer = layui.layer;
layer.open({
title: '温馨提示',
icon: 2,
content: msg,
yes: function(index){
if (typeof callback === 'function'){
callback.call(this);
}
layer.close(index)
}
});
});
},
warning : function(msg){
jbox.alert(msg, '温馨提示', {width: 400, height: 120, icon:'warning' });
},
notification : function(msg){
jbox.tip(msg, 'info');
},
success : function(msg){
jbox.tip(msg, 'success');
},
alertconfirm : function(title, msg, yescallbackfun){
jbox.confirm(msg, title, yescallbackfun, { id:'alertconfirm', showscrolling: false, buttons: { "确定": true} });
},
confirm : function(title, msg, yescallbackfun, nocallbackfun){
jbox.confirm(msg, title, function(v,h,f){
if(v == true){
yescallbackfun();
}else{
nocallbackfun();
}
}, { id:'confirm', showscrolling: false, buttons: { '确定': true, '取消': false } });
},
/**
* 显示loading状态
* @param $container 要显示的jquery dom
* @param isloading boolean 显示or隐藏
* @param showmsg 显示的内容
*
* style class 定义:
.showloading{
background: url("images/waiting.gif") no-repeat scroll 8px 6px #ffffff;
background-image: url("images/waiting.gif");
border: 1px solid #d6d6d6;
position: fixed;
top: 50%;
left: 50%;
margin-left: -60px;
padding: 10px 10px 10px 38px !important;
z-index: 91000;
}
*/
showloading:function($container, isloading, showmsg){
if($(".showloading",$container).length > 0){
$(".showloading",$container).remove();
}
if($(".showloading",$container).length == 0){
var adddiv=$("",{'class':'showloading'});
showmsg = showmsg || "加载中...";
adddiv.append(showmsg);
$container.append(adddiv);
}
var $loading = $(".showloading", $container);
if(isloading){
//$loading.css("left",$(document.body).width()/2); //$container.width()
//$loading.css("top",$(document.body).height()/2);
$loading.css("display","block");
}else{
settimeout(function(){$loading.css("display","none")},50);
}
},
showprogessbar:function($container, isloading, showmsg){
if($(".showprogessbar",$container).length > 1){
$(".showprogessbar",$container).remove();
}
if($(".showprogessbar",$container).length == 0){
var adddiv=$("",{'class':'showprogessbar'});
showmsg = showmsg || "努力加载中~";
adddiv.append('' + showmsg + '
');
$container.append(adddiv);
}
//动画处理
function progressbar(){
$(".progressbar span", $container).animate({
width: "0%"
}, 0).animate({
width: "100%"
}, 3000,"linear", function(){
progressbar();
});
}
var $loading = $(".showprogessbar", $container);
if(isloading){
//$loading.css("left",$(document.body).width()/2); //$container.width()
//$loading.css("top",$(document.body).height()/2);
$loading.css("display","block");
progressbar();
}else{
$(".progressbar span", $container).stop();
settimeout(function(){$loading.css("display","none")},50);
}
}
};
base.tip._init();
/**
* cookie 操作
* @param name
* @param value
* @param options
* @returns {*}
*/
base.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toutcstring)) {
var date;
if (typeof options.expires == 'number') {
date = new date();
date.settime(date.gettime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toutcstring(); // use expires attribute, max-age is not supported by ie
}
// caution: needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason...
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 = null;
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 + '=')) {
cookievalue = decodeuricomponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookievalue;
}
};
/**
* des 加密工具
* @type {{key: *, encrypt: encrypt, decrypt: decrypt}}
*/
base.desutil = {
key:window["deskey"]||"apexsoft",
/**
* 加密
* @param value
* @param key
* @returns {*}
*/
encrypt:function(value, key){
key = key || base.desutil.key;
return encrypt(value, key);
},
/**
* 解密
* @param value
* @param key
* @returns {*}
*/
decrypt:function(value, key){
key = key || base.desutil.key;
return decrypt(value, key);
}
}
/**
* 事件处理:略
*
* utils.htmldecode(str):特殊符号反转义
* utils.htmlencode(sr):特殊符号转义
* utils.findposition(obj):获得元素的坐标
* utils.getbrowsertype():获得当前浏览器类型
* utils.utils.newguid() : 随机生成guid
* utils.object2paramstr(obj) : 将js对象object转化为参数类型的字符串格式:a=1&b=2&c=3
* utils.paramstr2obj(str) : 将参数形式的字符串转化成js对象
* utils.tobin(dec) : 十进制-》二进制
* utils.timer({interval:定时执行时间 秒, run : 定时执行的function函数}) : 定时循环执行
*
* rmbutil.* 人民币大小写转换工具类
*
* numberutil.* 数字操作工具类
*
* validatorutil.* 验证工具类
*
* string扩展
* string.format2(str,arr):格式化字符串,支持array和object两种数据源
* string.prototype.format:格式化字符串
* string.prototype.trim():去除头尾空格
* string.prototype.encode():特殊符号转义
* string.prototype.decode():特殊符号反转义
*
* newguid():生成一个guid
*/
//===utils begin
utils = {
//特殊符号反转义
htmldecode : function(str) {
str = str.replace(/&/g, "&");
str = str.replace(/</g, "<");
str = str.replace(/>/g, ">");
str = str.replace(/"/g, "\"");
str = str.replace(/ /g, " ");
return str;
},
//特殊符号转义
htmlencode : function htmlencode(str) {
str = str.replace(/&/g, "&");
str = str.replace(//g, ">");
str = str.replace(/\"/g, """);
str = str.replace(/ /g, " ");
return str;
},
/**
* 计算字符长度,汉字算两个字符
* @param str
*/
getchineselength:function(str){
var strlength = 0;
var strarr = str.split("");
for(var i= 0,len =strarr.length; i< len; i++){
if(/[\u0391-\uffe5]/.test(strarr[i])){
strlength +=2;
}else{
strlength +=1;
}
}
return strlength;
},
/**
* 截取字符串,中文算两个字符
* @param str
* @param limitlength
* @return {string}
*/
getchineselimitlengthstr:function(str, limitlength){
var strlength = 0;
var resultstr = "";
var strarr = str.split("");
for(var i= 0,len =strarr.length; i< len; i++){
if(/[\u0391-\uffe5]/.test(strarr[i])){
strlength +=2;
}else{
strlength +=1;
}
if(strlength > limitlength){
break;
}
resultstr += strarr[i];
}
return resultstr;
},
/**
* 获取计算机dpi信息
* @returns {array}
*/
getxydpi: function () {
var arrdpi = [];
if (window.screen.devicexdpi) {
arrdpi[0] = window.screen.devicexdpi;
arrdpi[1] = window.screen.deviceydpi;
}
else {
var tmpnode = document.createelement("div");
tmpnode.style.csstext = "width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden";
document.body.appendchild(tmpnode);
arrdpi[0] = parseint(tmpnode.offsetwidth);
arrdpi[1] = parseint(tmpnode.offsetheight);
tmpnode.parentnode.removechild(tmpnode);
}
return arrdpi;
},
/**
* 根据dpi计算出毫米对应的像素
* @param width
* @param height
* @returns {{width: number, height: number}}
*/
convertmm2px:function(width, height){
var dpi = utils.getxydpi();
var w = parseint(width) * parseint(dpi[0]) / 25.4;
var h = parseint(height) * parseint(dpi[1]) / 25.4;
return {
width:parseint(w),
height:parseint(h)
}
},
/**
* 获取页面请求参数
* @param name
* @returns {*}
*/
getrequestparam : function (name) {
var querystring = window.location.search;
var param = querystring.substr(1, querystring.length - 1).split("&");
for (var i = 0; i < param.length; i++) {
var keyvalue = param[i].split("=");
if (keyvalue[0] == name) return keyvalue[1];
}
return null;
},
/*获取时间倒计时, 参数:单位秒*/
gettimecountdownresult : function (secound) {
var s = math.floor(secound%60);
var m = math.floor(secound/60%60);
var h = math.floor(secound/60/60%24);
var d = math.floor(secound/60/60/24);
var time = d + "天" + h + "时" + m + "分" + s + "秒"; // 剩余时间(格式调整)
return time;
},
gettimecountdownobj : function (secound) {
var s = math.floor(secound%60);
var m = math.floor(secound/60%60);
var h = math.floor(secound/60/60%24);
var d = math.floor(secound/60/60/24);
/* d + "天" + h + "时" + m + "分" + s + "秒"; // 剩余时间(格式调整)*/
var time={d:d, h:h, m:m, s:s};
return time;
}
};
//===事件相关处理 begin
//获取event对象,主要用于兼容firefox
utils.getevent = function(a) {
var evt = a || window.event;
if (!evt) {
var arr = [], c = this.getevent.caller;
while (c) {
evt = c.arguments[0];
if (evt && (evt.constructor.target || evt.srcelement)) {
//if(evt && evt.constructor==event){
break;
}
var b = false;
for (var d = 0; d < arr.length; d++) {
if (c == arr[d]) {
b = true;
break;
}
}
if (b) {
break;
} else {
arr.push(c);
}
c = c.caller;
}
}
return evt;
};
//停止事件冒泡
utils.stopevent = function(e) {
if (!e) {
e = this.getevent();
}
if (e.stoppropagation) {
e.stoppropagation();
e.preventdefault();
} else {
e.cancelbubble = true;
e.returnvalue = false;
}
};
//添加事件
utils.addevent = function(obj, eventname, func) {
if (obj.attachevent) {
obj.attachevent(eventname, func)
} else {
obj.addeventlistener(eventname.substring(2), func, false);
}
};
//删除事件
utils.removeevent = function(obj, eventname, func) {
if (obj.detachevent) {
obj.detachevent(eventname, func)
} else {
obj.removeeventlistener(eventname.substring(2), func, false);
}
};
//===事件相关处理 end
//得到元素的绝对坐标
utils.findposition = function(obj) {
var curleft = 0;
var curtop = 0;
if (obj.offsetparent) {
do {
curleft += obj.offsetleft;
curtop += obj.offsettop;
} while (obj = obj.offsetparent);
}
/*while(obj.offsetparent){
obj=obj.offsetparent;
curleft += obj.offsetleft;
curtop += obj.offsettop;
}*/
return [curleft, curtop];
};
//获得浏览器类型
utils.getbrowsertype = function() {
var sys = {};
var ua = navigator.useragent.tolowercase();
var s;
(s = ua.match(/msie ([\d.]+)/)) ? sys.ie = s[1] :
(s = ua.match(/firefox\/([\d.]+)/)) ? sys.firefox = s[1] :
(s = ua.match(/chrome\/([\d.]+)/)) ? sys.chrome = s[1] :
(s = ua.match(/opera.([\d.]+)/)) ? sys.opera = s[1] :
(s = ua.match(/version\/([\d.]+).*safari/)) ? sys.safari = s[1] : 0;
//以下进行测试
if (sys.ie)
return 'ie: ' + sys.ie;
if (sys.firefox)
return 'firefox: ' + sys.firefox;
if (sys.chrome)
return 'chrome: ' + sys.chrome;
if (sys.opera)
return 'opera: ' + sys.opera;
if (sys.safari)
return 'safari: ' + sys.safari;
}
utils.newguid = function() {
var $ = "";
for (var a = 1; a <= 32; a++) {
var _ = math.floor(math.random() * 16).tostring(16);
$ += _;
if ((a == 8) || (a == 12) || (a == 16) || (a == 20))
$ += "-"
}
return $.touppercase()
} ;
/**
* 将js对象object转化为参数类型的字符串格式:a=1&b=2&c=3
* @param obj
*/
utils.object2paramstr = function(obj){
var result = [];
if(obj){
for(var p in obj){
result.push(p + "=" + obj[p]);
}
}
return result.join("&");
};
/**
* 将参数形式的字符串转化成js对象
* @param str
*/
utils.paramstr2obj = function(str){
var obj = {};
var arr1 = str.split("&");
var arr2;
for(var i=0, len=arr1.length; i < len; i++){
arr2 = arr1[i].split("=");
obj[arr2[0]] = arr2[1];
}
return obj;
};
//十进制-》二进制
utils.tobin = function(dec) {
var bits = [];
var dividend = dec;
var remainder = 0;
while (dividend >= 2) {
remainder = dividend % 2;
bits.push(remainder);
dividend = (dividend - remainder) / 2;
}
bits.push(dividend);
bits.reverse();
return bits.join("");
};
//获取位与选择项
utils.getbitselection = function(decimalnum){
var result = [];
if(decimalnum != ""){
var binarynum = utils.tobin(decimalnum); //转成二进制解析
var v = "";
var value;
for(var j=0, jlen=binarynum.length; j < jlen; j++){
v = binarynum.substring(jlen-j-1,jlen-j);
if(v == 1){
value=math.pow(2,j);
result.push(value);
}
}
}
return result;
}
/**
* 定时循环执行
* @param settings {interval:定时执行时间 秒, run : 定时执行的function函数}
* @return {*}
*/
utils.timer = function(settings){
this.settings = settings;
this.timer = null;
this.running = false;
this.interval = (settings.interval || 30) * 1000;
this.timeinit = null;
return this;
}
utils.timer.prototype = {
run: function(){
if(this.running) {
if(this.timer ==null){
this.timeinit += this.interval;
}
this.timer = settimeout(function () {$this.run()}, this.timeinit - (new date).gettime());
var $this = this;
this.settings.run.apply($this, []);
this.timeinit += this.interval;
}
},
start: function(){
if(this.timer == null)
{
this.timeinit = (new date).gettime();
this.running = true;
this.run();
}
},
stop: function(){
if(this.timer != null){
this.running = false;
cleartimeout(this.timer);
this.timer = null;
}
}
}
//客户端ip处理工具类
utils.ip = {
_inner:[],
_public:[],
_ipv6:[],
//get the ip addresses associated with an account
getips:function (callback){
var ip_dups = {};
//compatibility for firefox and chrome
var rtcpeerconnection = window.rtcpeerconnection
|| window.mozrtcpeerconnection
|| window.webkitrtcpeerconnection;
var usewebkit = !!window.webkitrtcpeerconnection;
//bypass naive webrtc blocking using an iframe
if(!rtcpeerconnection){
//note: you need to have an iframe in the page right above the script tag
var iframe = document.createelement('iframe');
//invalidate content script
iframe.sandbox = 'allow-same-origin';
iframe.style.display = 'none';
document.body.appendchild(iframe);
var win = iframe.contentwindow;
rtcpeerconnection = win.rtcpeerconnection
|| win.mozrtcpeerconnection
|| win.webkitrtcpeerconnection;
usewebkit = !!win.webkitrtcpeerconnection;
}
if(!rtcpeerconnection){
return;
}
//minimal requirements for data connection
var mediaconstraints = {
optional: [{rtpdatachannels: true}]
};
var servers = {iceservers: [{urls: "stun:stun.services.mozilla.com"}]};
//construct a new rtcpeerconnection
var pc = new rtcpeerconnection(servers, mediaconstraints);
function handlecandidate(candidate){
//match just the ip address
try{
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
var ip_addr = ip_regex.exec(candidate)[1];
//remove duplicates
if(ip_dups[ip_addr] === undefined)
callback(ip_addr);
ip_dups[ip_addr] = true;
}catch(e){}
}
//listen for candidate events
pc.onicecandidate = function(ice){
//skip non-candidate events
if(ice.candidate)
handlecandidate(ice.candidate.candidate);
};
//create a bogus data channel
pc.createdatachannel("");
//create an offer sdp
pc.createoffer(function(result){
//trigger the stun server request
pc.setlocaldescription(result, function(){}, function(){});
}, function(){});
////wait for a while to let everything done
settimeout(function(){
//read candidate info from local description
var lines = pc.localdescription.sdp.split('\n');
lines.foreach(function(line){
if(line.indexof('a=candidate:') === 0)
handlecandidate(line);
});
}, 1000);
},
initip:function(){
try{
//insert ip addresses into the page
utils.ip.getips(function(ip){
//local ips
if (ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/)){
if(utils.ip._inner.join(",").indexof(ip) ==-1){
utils.ip._inner[utils.ip._inner.length] = ip;
}
}
//ipv6 addresses
else if (ip.match(/^[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7}$/)){
if(utils.ip._ipv6.join(",").indexof(ip) ==-1){
utils.ip._ipv6[utils.ip._ipv6.length] = ip;
}
}
//assume the rest are public ips
else{
if(utils.ip._public.join(",").indexof(ip) ==-1){
utils.ip._public[utils.ip._public.length] = ip;
}
}
});
}catch (e){}
try{
//获取公网ip
jquery.getscript("http://pv.sohu.com/cityjson?ie=utf-8",function(){
if(!!returncitysn){
utils.ip._public[utils.ip._public.length] = returncitysn["cip"];
}
});
}catch(e){}
},
getinnerip1:function(){
if(utils.ip._inner.length > 0){
return utils.ip._inner[0];
}
return "";
},
getipv61:function(){
if(utils.ip._ipv6.length > 0){
return utils.ip._ipv6[0];
}
return "";
},
getpublicip1:function(){
if(utils.ip._public.length > 0){
return utils.ip._public[0];
}
return "";
}
}
//===utils end
//人民币 大写转换 操作工具类
rmbutil = {
/**
* 转千分符
*/
convert2thousand : function(oinput) {
var re = /(-?\d+)(\d{3})/
var num = oinput +'';
while (re.test(num)) {
num = num.replace(re, "$1,$2");
}
return num;
},
/**
* 转中文的大写
* @param n
* @returns
*/
number2chineseupper : function (n) {
//n = parseint(n);
if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) return "";
if (typeof(n) == "number") {
if ( - 1 == n.tostring().indexof(".")) {
if(n == 0){
return "零";
}
var result = rmbutil._seti2c(n);
if(result.substring(result.length-1) == "零"){
result = result.substring(0,result.length-1);
}
return result;
} else {
var i, istr, f, fstr, a, rstr;
a = n.tostring().split(".");
i = a[0];
f = a[1];
istr = rmbutil._seti2c(i);
fstr = rmbutil._setf2c(f);
rstr = istr + "点" + fstr;
rstr = rstr.replace(/零+/g, "零");
return rstr;
}
} else {
return "---";
}
},
/**
* 转中文的大写
* @param n
* @returns
*/
number2chineseuppermoney : function (n) {
//n = parseint(n);
if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) return "";
if (typeof(n) == "number") {
if ( - 1 == n.tostring().indexof(".")) {
if(n == 0){
return "零元整";
}
return rmbutil._seti2cmoney(n) + "整";
} else {
var i, istr, f, fstr, a, rstr;
a = n.tostring().split(".");
i = a[0];
f = a[1];
istr = rmbutil._seti2cmoney(i);
fstr = rmbutil._setf2cmoney(f);
if(istr.length == 0){
rstr = fstr;
}else{
rstr = istr + "零" + fstr;
}
rstr = rstr.replace(/零+/g, "零");
return rstr;
}
} else {
return "---";
}
},
_seti2cmoney:function(n) {
var ns = n.tostring();
var tempstr = "";
for (var i = 1; i < ns.length + 1; i++) {
switch (i) {
case 1:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "元" + tempstr;
} else {
if(ns.length != 1) {
tempstr = "元" + tempstr;
}else{
tempstr = tempstr;
}
}
break;
case 2:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "拾" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 3:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "佰" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 4:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "仟" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 5:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "万" + tempstr;
} else {
tempstr = "万" + tempstr;
}
break;
case 6:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "拾" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 7:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "佰" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 8:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "仟" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 9:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "亿" + tempstr;
} else {
tempstr = "亿" + tempstr;
}
break;
case 10:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "拾" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 11:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "佰" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 12:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "仟" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
default:
break;
}
}
return rmbutil._g2b(tempstr);
},
_setf2cmoney:function (n) {
var ns = n.tostring();
var tempstr = "";
for (var i = 0; i < ns.length; i++) {
switch (i) {
case 0:
var t = ns.substr(i, 1);
if (t != "0") {
tempstr += t + "角";
}
break;
case 1:
var t = ns.substr(i, 1);
if (t != "0") {
tempstr += t + "分";
}
break;
default:
break;
}
}
return rmbutil._g2b(tempstr);
},
_seti2c:function(n) {
var ns = n.tostring();
var tempstr = "";
for (var i = 1; i < ns.length + 1; i++) {
switch (i) {
case 1:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + tempstr;
} else {
tempstr = tempstr;
}
break;
case 2:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "拾" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 3:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "佰" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 4:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "仟" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 5:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "万" + tempstr;
} else {
tempstr = "万" + tempstr;
}
break;
case 6:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "拾" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 7:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "佰" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 8:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "仟" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 9:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "亿" + tempstr;
} else {
tempstr = "亿" + tempstr;
}
break;
case 10:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "拾" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 11:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "佰" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
case 12:
var t = ns.substr(ns.length - i, 1);
if (t != "0") {
tempstr = t + "仟" + tempstr;
} else {
tempstr = "0" + tempstr;
}
break;
default:
break;
}
}
return rmbutil._g2b(tempstr);
},
_setf2c:function (n) {
var ns = n.tostring();
var tempstr = "";
for (var i = 0; i < ns.length; i++) {
switch (i) {
case 0:
var t = ns.substr(i, 1);
if (t != "0") {
tempstr += t;
} else {
tempstr += "0";
}
break;
case 1:
var t = ns.substr(i, 1);
if (t != "0") {
tempstr += t;
}
break;
case 2:
var t = ns.substr(i, 1);
if (t != "0") {
tempstr += t;
}
break;
case 3:
var t = ns.substr(i, 1);
if (t != "0") {
tempstr += t;
}
break;
default:
break;
}
}
return rmbutil._g2b(tempstr);
},
_g2b:function(s) {
var rs = s.replace(/0+/g, "0");
rs = rs.replace("0元", "元");
rs = rs.replace("0亿", "亿");
rs = rs.replace("0万", "万");
rs = rs.replace("亿万", "亿");
rs = rs.replace(/0/g, "零");
rs = rs.replace(/1/g, "壹");
rs = rs.replace(/2/g, "贰");
rs = rs.replace(/3/g, "叁");
rs = rs.replace(/4/g, "肆");
rs = rs.replace(/5/g, "伍");
rs = rs.replace(/6/g, "陆");
rs = rs.replace(/7/g, "柒");
rs = rs.replace(/8/g, "捌");
rs = rs.replace(/9/g, "玖");
return rs;
}
};
//数字 工具类
numberutil = {
//保留两位小数
/**
* 将浮点数四舍五入
* @param x
* @param pos 保留小数位
* @returns {number}
*/
todecimal : function (x, pos) {
var f = parsefloat(x);
if (isnan(f)) {
return 0;
}
var round = math.pow(10, pos);
f = math.round(x*round)/round;
return f;
},
/**
* 制保留pos位小数,如:2,会在2后面补上00.即2.00
* @param x
* @param pos 强制保留的小数位
* @returns {string}
*/
todecimalforce:function (x, pos) {
var f = parsefloat(x);
if (isnan(f)) {
return 0;
}
var round = math.pow(10, pos);
var f = math.round(x*round)/round;
var s = f.tostring();
var rs = s.indexof('.');
if (rs < 0) {
rs = s.length;
s += '.';
}
while (s.length <= rs + pos) {
s += '0';
}
return s;
},
/**
* 将字符串转换为number
* @param v string
* @returns {number}
*/
convert2number:function(v){
return number(v.replace(/[^0-9.]/g,'')).valueof();
},
/**
* 格式化number
* 如:
* formatnumber(0,'');
* formatnumber(12432.21,'#,###');
* formatnumber(12432.21,'#,###.000#');
* formatnumber(12432,'#,###.00');
* formatnumber('12432.415','#,###.0#');
* @param number
* @param pattern
* @return {string}
*/
formatnumber:function (number, pattern) {
try{
var str = number.tostring();
var strint;
var strfloat;
var formatint;
var formatfloat;
if (/\./g.test(pattern)) {
formatint = pattern.split('.')[0];
formatfloat = pattern.split('.')[1];
} else {
formatint = pattern;
formatfloat = null;
}
if (/\./g.test(str)) {
if (formatfloat != null) {
var tempfloat = math.round(parsefloat('0.' + str.split('.')[1]) * math.pow(10, formatfloat.length)) / math.pow(10, formatfloat.length);
strint = (math.floor(number) + math.floor(tempfloat)).tostring();
strfloat = /\./g.test(tempfloat.tostring()) ? tempfloat.tostring().split('.')[1] : '0';
} else {
strint = math.round(number).tostring();
strfloat = '0';
}
} else {
strint = str;
strfloat = '0';
}
if (formatint != null) {
var outputint = '';
var zero = formatint.match(/0*$/)[0].length;
var comma = null;
if (/,/g.test(formatint)) {
comma = formatint.match(/,[^,]*/)[0].length - 1;
}
var newreg = new regexp('(\\d{' + comma + '})', 'g');
if (strint.length < zero) {
outputint = new array(zero + 1).join('0') + strint;
outputint = outputint.substr(outputint.length - zero, zero)
} else {
outputint = strint;
}
var outputint = outputint.substr(0, outputint.length % comma) + outputint.substring(outputint.length % comma).replace(newreg, (comma != null ? ',' : '') + '$1')
outputint = outputint.replace(/^,/, '');
strint = outputint;
}
if (formatfloat != null) {
var outputfloat = '';
var zero = formatfloat.match(/^0*/)[0].length;
if (strfloat.length < zero) {
outputfloat = strfloat + new array(zero + 1).join('0');
//outputfloat = outputfloat.substring(0,formatfloat.length);
var outputfloat1 = outputfloat.substring(0, zero);
var outputfloat2 = outputfloat.substring(zero, formatfloat.length);
outputfloat = outputfloat1 + outputfloat2.replace(/0*$/, '');
} else {
outputfloat = strfloat.substring(0, formatfloat.length);
}
strfloat = outputfloat;
} else {
if (pattern != '' || (pattern == '' && strfloat == '0')) {
strfloat = '';
}
}
return strint + (strfloat == '' ? '' : '.' + strfloat);
}catch (e){
return "error";
}
},
/**
* 时间秒转为 文字显示: x天x时x分x秒
*/
secondtodate : function (lsms) {
if (!lsms) {
return "0秒";
}
// 解决数据异常的问题
//if( lsms>=1*24*60*60 ){
// return "0秒";
//}
var ss = 1;
var mi = ss * 60;
var hh = mi * 60;
var dd = hh * 24;
var day = parseint(lsms / dd);
var hour = parseint((lsms - day * dd) / hh);
var minute = parseint((lsms - day * dd - hour * hh) / mi);
var second = parseint((lsms - day * dd - hour * hh - minute * mi) / ss);
var millisecond = parseint(lsms - day * dd - hour * hh - minute * mi - second * ss);
var strday = "";
if (day == 0) strday = '';
else strday = day < 10 ? "0" + day + "天": day + "天";
var strhour = '';
if (hour == 0) strhour = '';
else strhour = hour < 10 ? "0" + hour + "时": hour + "时";
var strminute = '';
if (minute == 0) strminute = '';
else strminute = minute < 10 ? "0" + minute + "分": minute + "分";
var strsecond = ''
if (second == 0) strsecond = '0秒';
else strsecond = second + "秒";
var dtimestr = strday + strhour + strminute + strsecond ;
// 解决数据异常的问题 超长数据的解决
if( dtimestr.length>12 ) dtimestr = '0秒';
return dtimestr;
},
//浮点数加法运算
floatadd : function (arg1, arg2) {
var r1, r2, m;
try {
r1 = arg1.tostring().split(".")[1].length;
} catch(e) {
r1 = 0
}
try {
r2 = arg2.tostring().split(".")[1].length;
} catch(e) {
r2 = 0
}
m = math.pow(10, math.max(r1, r2)) ;
//动态控制精度长度
var n = (r1 >= r2) ? r1: r2;
var a = (arg1 * m + arg2 * m) / m ;
return parsefloat(a.tofixed(n));
},
//浮点数减法运算
floatsub :function(arg1, arg2) {
var r1, r2, m, n;
try {
r1 = arg1.tostring().split(".")[1].length
} catch(e) {
r1 = 0
}
try {
r2 = arg2.tostring().split(".")[1].length
} catch(e) {
r2 = 0
}
m = math.pow(10, math.max(r1, r2));
//动态控制精度长度
n = (r1 >= r2) ? r1: r2;
return parsefloat( ((arg1 * m - arg2 * m) / m).tofixed(n) );
},
//浮点数乘法运算
floatmul : function (arg1, arg2, dw) {
var m = 0,
s1 = arg1.tostring(),
s2 = arg2.tostring();
try {
m += s1.split(".")[1].length
} catch(e) {}
try {
m += s2.split(".")[1].length
} catch(e) {}
var val = number(s1.replace(".", "")) * number(s2.replace(".", "")) / math.pow(10, m);
if (dw !== undefined){
return parsefloat( val.tofixed(dw) );
} else{
return parsefloat( val.tofixed(2) );
}
},
//浮点数除法运算
floatdiv : function (arg1, arg2) {
var t1 = 0,
t2 = 0,
r1, r2;
try {
t1 = arg1.tostring().split(".")[1].length
} catch(e) {}
try {
t2 = arg2.tostring().split(".")[1].length
} catch(e) {}
with(math) {
r1 = number(arg1.tostring().replace(".", "")) ;
r2 = number(arg2.tostring().replace(".", "")) ;
return (r1 / r2) * pow(10, t2 - t1);
}
}
};
//验证工具类
validatorutil = {
chinesechar : function (s) {
//由数字和26个英文字母组成的字符串
return /^[\u4e00-\u9fa5]+$/gi.test(s);
},
commonchar : function (s) {
//由数字和26个英文字母组成的字符串
return /^[a-za-z0-9]+$/gi.test(s);
},
commoncharinclude_ : function (s) {
//数字、26个英文字母或者下划线组成的字符串
return /^\w+$/gi.test(s);
},
commoncharincludechinese : function (s) {
//数字、字符、汉字
return /^[\da-z\u4e00-\u9fa5\uf900-\ufa2d]+$/gi.test(s);
},
email:function(value){
var email_reg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
return email_reg.test(value);
},
mobile:function(value){
var mobile_reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
return mobile_reg.test(value);
},
phone:function(value){
var reg = /^(0[0-9]{2,3}\-?)?([2-9][0-9]{6,7}){1}(\-[0-9]{1,4})?$/;
return reg.test(value);
},
number:function(value){
var number_reg = /^\d{0,}$/;
return number_reg.test(value);
},
floatnumber: function (value) {
var float_reg = /^([+-]?)\d+\.\d+$/;
return float_reg.test(value);
},
zipcode:function(value){
var reg = /^[1-9]\d{5}$/;
return reg.test(value);
},
//luhm校验银行卡号
luhmcheck: function (bankno) {
if(isnan(parseint(bankno,10))){
return false;
}
if(bankno.length == 20) {
return true;
}
var lastnum = bankno.substr(bankno.length - 1, 1);//取出最后一位(与luhm进行比较)
var first15num = bankno.substr(0, bankno.length - 1);//前15或18位
var newarr = [];
for (var i = first15num.length - 1; i > -1; i--) { //前15或18位倒序存进数组
newarr.push(first15num.substr(i, 1));
}
var arrjishu = []; //奇数位*2的积 <9
var arrjishu2 = []; //奇数位*2的积 >9
var arroushu = []; //偶数位数组
for (var j = 0; j < newarr.length; j++) {
if ((j + 1) % 2 == 1) {//奇数位
if (parseint(newarr[j]) * 2 < 9) {
arrjishu.push(parseint(newarr[j]) * 2);
} else {
arrjishu2.push(parseint(newarr[j]) * 2);
}
} else { //偶数位
arroushu.push(newarr[j]);
}
}
var jishu_child1 = [];//奇数位*2 >9 的分割之后的数组个位数
var jishu_child2 = [];//奇数位*2 >9 的分割之后的数组十位数
for (var h = 0; h < arrjishu2.length; h++) {
jishu_child1.push(parseint(arrjishu2[h]) % 10);
jishu_child2.push(parseint(arrjishu2[h]) / 10);
}
var sumjishu = 0; //奇数位*2 < 9 的数组之和
var sumoushu = 0; //偶数位数组之和
var sumjishuchild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
var sumjishuchild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
var sumtotal = 0;
for (var m = 0; m < arrjishu.length; m++) {
sumjishu = sumjishu + parseint(arrjishu[m]);
}
for (var n = 0; n < arroushu.length; n++) {
sumoushu = sumoushu + parseint(arroushu[n]);
}
for (var p = 0; p < jishu_child1.length; p++) {
sumjishuchild1 = sumjishuchild1 + parseint(jishu_child1[p]);
sumjishuchild2 = sumjishuchild2 + parseint(jishu_child2[p]);
}
//计算总和
sumtotal = parseint(sumjishu) + parseint(sumoushu) + parseint(sumjishuchild1) + parseint(sumjishuchild2);
//计算luhm值
var k = parseint(sumtotal) % 10 == 0 ? 10 : parseint(sumtotal) % 10;
var luhm = 10 - k;
if (lastnum == luhm && bankno != null && bankno != "") {
return true;
} else {
return false;
}
},
//检验组织机构代码值
checkorgcode: function (code) {
//机构代码
var ws = [3, 7, 9, 10, 5, 8, 4, 2];
var str = '0123456789abcdefghijklmnopqrstuvwxyz';
var reg = /^([0-9a-z]){8}-[0-9|x]$/;// /^[a-za-z0-9]{8}-[a-za-z0-9]{1}$/
var sum = 0;
for (var i = 0; i < 8; i++){
sum += str.indexof(code.charat(i)) * ws[i];
}
var c9 = 11 - (sum % 11);
c9 = c9 == 10 ? 'x' : c9;
c9 = c9 == 11 ? 0 : c9;
if (!reg.test(code) || c9 != code.charat(9)) {
return {success: false, msg: "数据验证位不正确!"};
}
return {success:true, msg:"验证正确!"};
},
//校验价格万元格式
price4p6: function (value) {
if (value == undefined || value == null || value.length == 0){
return false;
} else {
var regx = new regexp(/((^[1-9]\d{0,8})|^0)(\.\d{0,6}){0,1}$/);
return regx.test(value);
}
},
//校验价格元格式
price4p2: function (value) {
if (value == undefined || value == null || value.length == 0){
return false;
} else {
var regx = new regexp(/((^[1-9]\d{0,13})|^0)(\.\d{0,2}){0,1}$/);
return regx.test(value);
}
}
}
//=================扩展string begin==================================================
//格式化字符串,支持array和object两种数据源
string.format2 = function(str, arr) {
if (arr.constructor == array) {
for (var i = 0; i < arr.length; i++) {
var re = new regexp('\\{' + (i) + '\\}', 'gm');
str = str.replace(re, arr[i]);
}
} else {
for (elem in arr) {
var re = new regexp('\\{' + elem + '\\}', 'gm');
str = str.replace(re, arr[elem]);
}
}
return str;
};
string.prototype.format = function() {
var str = this;
for (var i = 0; i < arguments.length; i++) {
str = str.replace(eval("/\\{" + i + "\\}/g"), arguments[i]);
}
return str;
};
string.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
string.prototype.encode = function() {
return utils.htmlencode(this);
};
string.prototype.decode = function() {
return utils.htmldecode(this);
};
//=================扩展string end==================================================
//用于临时保存表单内容工具类
utils.tempform={
xmlhead : '',
//获取字段xml格式内容
getfieldxml: function (name, value){
if(name == ""){
return "";
}
var buff = [];
buff.push('');
buff.push('');
buff.push(name);
buff.push('');
buff.push('');
buff.push('');
buff.push('');
buff.push('');
return buff.join("");
},
getxmlvalues:function(jqselector){
var buff = [];
buff.push(utils.tempform.xmlhead);
buff.push('');
$(jqselector).each(function(i, n){
var name = $(n).attr("name");
if(name == undefined){
alert(n.outerhtml + " 未定义name属性" );
}
var value = "";
if($(n).attr("fngetvalue") != undefined && typeof window[ $(n).attr("fngetvalue")] == "function"){
value = window[$(n).attr("fngetvalue")].call($(n));
if(typeof value == "object"){
value = json.stringify(value);
}
}else{
value = $(n).val();
}
buff.push(utils.tempform.getfieldxml(name, value));
});
buff.push('');
return buff.join("");
},
parsexmlvalues:function(xmlvalues){
var fields = $("field",$.parsexml(xmlvalues));
for(var i= 0, len = fields.length; i < len; i++){
var $field = $(fields[i]);
var name = $("name",$field).text();
var value = $("value",$field).text();
if(name == ""){
continue;
}
var $target = $("[name='" + name + "']");
if($target.length == 0){
continue;
}
if($target.attr("fnsetvalue") != undefined &&typeof window[$target.attr("fnsetvalue")] == "function"){
window[$target.attr("fnsetvalue")].call($target, value);
}else{
$target.val(value);
}
}
}
}
//用于控制表单的单次提交,入参为表单id
utils.singlesubmit= function(formid){
var $form = $("#"+formid);
if(!$form[0]){
return false;
}
//如果有提交过,就返回
if($form.hasclass("hadcommit")){
return false;
}
base.tip.showloading($("body"),true,"正在提交");
$form.addclass("hadcommit");
$form.submit();
return true;
}
// 对date的扩展,将 date 转化为指定格式的string
// 月(m)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(s)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new date()).format("yyyy-mm-dd hh:mm:ss.s") ==> 2006-07-02 08:09:04.423
// (new date()).format("yyyy-m-d h:m:s.s") ==> 2006-7-2 8:9:4.18
date.prototype.format = function (fmt) { //author: meizz
var o = {
"m+": this.getmonth() + 1, //月份
"d+": this.getdate(), //日
"h+": this.gethours(), //小时
"m+": this.getminutes(), //分
"s+": this.getseconds(), //秒
"q+": math.floor((this.getmonth() + 3) / 3), //季度
"s": this.getmilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(regexp.$1, (this.getfullyear() + "").substr(4 - regexp.$1.length));
for (var k in o)
if (new regexp("(" + k + ")").test(fmt)) fmt = fmt.replace(regexp.$1, (regexp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}