/**
* 基础库方法
*/
var utils = {
//hostUrl: "http://www.website.com/",
hostUrl: "/",
isNull: function (s) {
if (!s) return true;
s = s.replace(/ /ig, ""); //去掉
var patrn = /^\s*$/;
if (!patrn.exec(s)) return false;
return true;
},
isDigit: function (s) {
var patrn = /^[0-9]{1,20}$/;
if (!patrn.exec(s)) return false;
return true;
},
isDate: function (s) {
var r = s.match(/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
if (r == null) return false;
var d = new Date(r[1], r[3] - 1, r[4]);
return (d.getFullYear() === r[1] && (d.getMonth() + 1) === r[3] && d.getDate() === r[4]);
},
isMail: function (str) {
var myReg = /^[_\-\.a-zA-Z0-9]+@([_\-a-zA-Z0-9]+\.)+[a-zA-Z0-9]{2,3}$/;
if (myReg.test(str))
return true;
return false;
},
isMobile: function (mobile) {
if (this.isNull(mobile))
return false;
var mobileReg = !!mobile.match(/^(0|86|17951)?(13[0-9]|15[012356789]|17[03678]|18[0-9]|14[57])[0-9]{8}$/);
return mobileReg;
},
Trim: function (str) {
if (str === undefined) return "";
return str.replace(/(^\s*)|(\s*$)/g, "");
},
isPwd: function (str) {
if (str.length < 6 || str.length > 16) {
return false;
}
return true;
},
isName: function (str) {
if (str.length < 2 || str.length > 16) {
return false;
}
return true;
},
isChar: function (s) {
var patrn = /^[0-9a-zA-Z]*$/;
if (!patrn.exec(s)) return false;
return true;
},
isDigitFloat: function (s) {
try {
if (parseInt(s) === 0)
return true;
} catch (e) {
}
var patrn = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/;
if (patrn.exec(s)) return true;
patrn = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/;
if (patrn.exec(s)) return true;
return false;
},
isUrl: function (urlString) {
urlString = (urlString || '').toLowerCase();
var regExp =
/^(https?|http):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/;
if (urlString.match(regExp)) return true;
else return false;
},
formatDate: function (date, fmt) {
if (!date) return "";
if (!(date instanceof Date)) {
try {
date = new Date(date);
} catch (ex) {
return date;
} finally {
}
}
var o = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, //小时
"H+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
var week = {
"0": "/u65e5",
"1": "/u4e00",
"2": "/u4e8c",
"3": "/u4e09",
"4": "/u56db",
"5": "/u4e94",
"6": "/u516d"
};
if (!fmt) fmt = "yyyy-MM-dd HH:mm:ss";
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
}
if (/(E+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[date.getDay() + ""]);
}
for (var k in o) {
if (o.hasOwnProperty(k)) {
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;
},
utcToLocal: function (ticks, format) {
if (!ticks) {
return "";
}
var t = new Date(ticks);
var utc = new Date(t.getUTCFullYear(), t.getUTCMonth(), t.getUTCDate(), t.getUTCHours(), t.getUTCMinutes(), t.getUTCSeconds());
if (!format) {
format = "yyyy-MM-dd HH:mm:ss";
}
try {
return this.formatDate(utc, format);
} catch (e) {
return "Invalid Date";
}
},
initEnter: function (d, callBack) {
//记录令牌信息
$.cookie("token", d.Data.Token, { path: "/" });
$.cookie("memberid", d.Data.User.MemberId, { path: "/" });
$.cookie("membername", d.Data.User.MemberName, { path: "/" });
$.cookie("memberfacepic", d.Data.User.FacePic ? d.Data.User.FacePic.replace("/bgimg/", "/xx_bgimg/") : "/img/none.gif", { path: "/" });
$.cookie("issystemmanager", d.Data.User.IsSystemManager, { path: "/" });
$.cookie("isteammanager", d.Data.User.IsTeamManager, { path: "/" });
$.cookie("teamid", d.Data.User.TeamId, { path: "/" });
$.cookie("teamname", d.Data.User.TeamName, { path: "/" });
$.cookie("teamshortname", d.Data.User.TeamShortName, { path: "/" });
$.cookie("teamicon", d.Data.User.TeamIcon, { path: "/" });
$.cookie("globalgroupid", d.Data.User.GlobalGroupId, { path: "/" });
$.cookie("newbg", "w", { path: "/" });
var href = "/app/#staging";
if (callBack) {
callBack();
} else {
if (d.Data.User.IsSystemManager) {
window.location.href = "/a/#staging";
} else {
window.location.href = href;
}
}
},
loginSystem: function (loginName, loginPwd, seltObj, callBack) {
var params = {};
var helper = new buttonHelper(seltObj, "正在登录,请稍后...");
if (helper.isDisabled()) {
return;
}
helper.disable();
params.username = $.trim(loginName);
params.password = CryptoJS.MD5($.trim(loginPwd)).toString();
params.granttype = "password";
params.appkey = 10000;
params.appsecret = "d2s0b1g6y0i3h2u8lu";
utils.postRequest("account/login", params, function (d) {
helper.enable();
if (d.IsError) {
$.msg(d.Msg);
$(seltObj).removeAttr("disabled");
$(seltObj).val("登录");
} else {
//记录令牌信息
utils.initEnter(d, callBack);
}
}, true, true).always(function (d) {
if (d.IsError) {
helper.enable();
}
});
},
loadPage: function () {
var self = this;
var showPages = function (target, curPage, itemCount, navFunc, pagesize, totalPage, pgType, container) { //初始化属性
this.currentPage = curPage; //当前页数
this.totalPage = totalPage; //总页数
this.itemCount = itemCount; //总记录数
this.pageSize = pagesize; //每页显示多少条
this.target = target; //要显示分页的标签
this.navFunc = navFunc; //分页的回调函数
this.pgType = pgType;
this.Container = container;//数据容器
}
showPages.prototype.checkPages = function () { //进行当前页数和总页数的验证
if (isNaN(parseInt(this.currentPage))) this.currentPage = 1;
if (this.currentPage < 1) this.currentPage = 1;
this.currentPage = parseInt(this.currentPage);
if (this.currentPage > this.totalPage) this.currentPage = this.totalPage;
}
showPages.prototype.createHtml = function () { //生成html代码
if (this.itemCount < 1) {
return "";
}
var strHtml = "", prevPage = this.currentPage - 1, nextPage = this.currentPage + 1;
strHtml += "<ul class=\"pagination pull-left\">";
if (prevPage < 1) {
strHtml += "<li title=\"首页\" class=\"disabled\"><a>首页</a></li>";
strHtml += "<li title=\"上一页\" class=\"disabled\"><a>上一页</a></li>";
} else {
strHtml += "<li title=\"首页\"><a href=\"javascript:void(0);\" page=\"1\">首页</a></li>";
strHtml += "<li title=\"上一页\"><a href=\"javascript:void(0);\" page=\"" + prevPage + "\">上一页</a></li>";
}
var startPage;
if (this.currentPage % 6 === 0) {
startPage = this.currentPage - 5;
} else {
startPage = this.currentPage - this.currentPage % 6 + 1;
}
if (startPage > 6) strHtml += "<li title=\"前8页\"><a href=\"javascript:void(0);\" page=\"" + (startPage - 1) + "\">...</a></li>";
for (var i = startPage; i < startPage + 6; i++) {
if (i > this.totalPage) break;
if (i === this.currentPage) {
strHtml += "<li title=\"第" + i + "页\" class=\"disabled\"><a>" + i + "</a></li>";
} else {
strHtml += "<li title=\"第" + i + "页\"><a href=\"javascript:void(0);\" page=\"" + i + "\">" + i + "</a></li>";
}
}
if (this.totalPage >= startPage + 6) strHtml += "<li title=\"后6页\"><a href=\"javascript:void(0);\" page=\"" + (startPage + 6) + "\">...</a></li>";
if (nextPage > this.totalPage) {
strHtml += "<li title=\"下一页\" class=\"disabled\"><a>下一页</a></li>";
strHtml += "<li title=\"尾页\" class=\"disabled\"><a>尾页</a></li>";
} else {
strHtml += "<li title=\"下一页\"><a href=\"javascript:void(0);\" page=\"" + nextPage + "\">下一页</a></li>";
strHtml += "<li title=\"尾页\"><a href=\"javascript:void(0);\" page=\"" + this.totalPage + "\">尾页</a></li>";
}
//strHtml += "</ul>";
strHtml += "<div class=\"changePageSize\" style=\"float: left;\"> 每页显示:" +
" <select style=\"width:auto;height:32px;display: inline;\">";
strHtml += " <option value=\"10\">10</option>";
strHtml += " <option selected=\"\" value=\"20\">20</option>";
strHtml += " <option value=\"30\">30</option>";
strHtml += " <option value=\"50\">50</option>";
strHtml += " <option value=\"100\">100</option>";
strHtml += "</select><span class=\"pg_count\"> 总记录:" + this.itemCount + "</span></div>";
strHtml += "</ul>";
return strHtml;
};
/**
* 滑动底部加载更多
* @returns {}
*/
showPages.prototype.createMobileHtml = function () {
//$(this.target).addClass("row");
if (this.itemCount < 20 || this.itemCount <= (this.pageSize * this.currentPage)) {
return '<a href="javascript:void(0)" class="btn btn-default btn-block no-border loadmore">数据已经加载完啦!</a>';
}
return '<a href="javascript:void(0)" class="btn btn-default btn-block no-border loadmore">查看更多</a>';
};
showPages.prototype.printHtml = function () { //显示html代码
this.checkPages();
var pgtg = this.target;
var navPage = this.navFunc;
var psize = this.pageSize;
var tPage = this.totalPage;
var container = this.Container;
if (this.pgType === 1 || $(window).width() < 768) {
var stop = true;
var indexPage = this.currentPage;
if (utils.isMobileBrowser()) {
$(this.target).addClass("row");
}
function pullDown() {
if ($("#pulldownload").length === 0) {
//$("#pulldownload").empty().remove();
if (utils.isMobileBrowser()) {
$(container).prepend('<div id="pulldownload" style="padding:16px 0;text-align:center;">下拉刷新...</div>');
$(container).attr("style", "transform:translate(0px,-50px)");
self.slide(container, 50, function (e) {
var that = this;
//$(pgtg).hide();
navPage(1, psize, function () {
that.back.call();
$("#pulldownload").html("刷新完成");
//$(pgtg).show();
});
});
}
}
}
//pullDown();
function loadMore() {
indexPage++;
$(pgtg).find("a").html("<span class=\"s-loading\">加载中</span>");
//这里当是动态列表的时候数据结构比较特殊一点没有totalpage 滑动到底部是自动加载的
if (tPage < indexPage) {
$(pgtg).find("a").html("数据已经加载完啦!");
return false;
} else {
navPage(indexPage, psize, function () {
$(pgtg).find("a").html("查看更多");
});
}
return false;
};
$(window).unbind("scroll.loaddata").on("scroll.loaddata", window, function () {
var totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());
/*if($(window).scrollTop()<10){
$(container).attr("style", "transform:translate(0px,-50px)");
}else{
$(container).attr("style", "transform:translate(0px,0px)");
}*/
if ($(document).height() <= totalheight) {
if (stop === true) {
stop = false;
loadMore();
}
}
});
$(this.target).html(this.createMobileHtml());
$(this.target).find("a").unbind("click").click(function () {
loadMore();
});
} else {
$(this.target).html(this.createHtml());
$(this.target).find(".pagination a[page]").click(function () {
ipage = $(this).attr("page");
navPage(ipage, psize);
});
$(this.target).find(".changePageSize").find("select").val(psize);
$(this.target).find(".changePageSize").find("select").change(function () {
if ($("[data-evt='selectAll']").length > 0) {
$("[data-evt='selectAll']").prop(":checked", false);
}
psize = $(this).val();
$.cookie("pageSize", $(this).val());
navPage(1, psize);
});
}
}
return showPages;
},
getRequest: function (requestUrl, params, callBack, noToken, noFilter, async) {
requestUrl = this.hostUrl + requestUrl;
var token;
if (!noToken) {
token = $.cookie("token");
if (!token || this.isNull(token) || token === "null") {
setTimeout(function () {
initLogin();
},
500);
return false;
}
if ($.type(params) === "string") {
params += "&accesstoken=" + token + "&rnd=" + Math.random();
} else {
params.accesstoken = token;
params.rnd = Math.random();
}
}
if (async == undefined) {
async = true;
}
setTimeout(function () {
return $.ajax({
async: async,
url: requestUrl,
type: "GET",
dataType: "JSON",
data: params,
success: function (d) {
if ($.type(params) !== "string") {
if (('revisionPointer' in params) && revisionPointer !== params.revisionPointer) return false;
}
if ("undefined" == typeof noFilter || !noFilter) {
if (d.IsError) {
if (d.ErrorCode === 10000) {
$.msg("登录已失效,请重新登录!");
setTimeout(function () {
//if (wechatHelper.isWeiXin()) {
// loginOut(function () {
// location.reload();
// });
//} else {
//loginOut(function () {
// initLogin();
//});
//}
window.location.href = 'login.html';
}, 500);
} else {
$.msg(d.Msg);
}
return false;
} else {
callBack(d);
}
} else {
callBack(d);
}
},
error: function (e, text, err) {
if (err == 'abort') {
return;
}
if (e.readyState === 0) {
//$.msg("获取数据失败,请检查网络连接");
} else {
$.msg("出错了");
}
},
complete: function (xhr, ts) {
xhr = null;
}
});
}, 15);
},
postRequest: function (requestUrl, params, callBack, noToken, noFilter, async) {
requestUrl = this.hostUrl + requestUrl;
if (!noToken) {
var token = $.cookie("token");
if (!token || this.isNull(token) || token === "null") {
setTimeout(function () {
initLogin();
}, 500);
return false;
}
if ($.type(params) === "string") {
params += "&accesstoken=" + token;
} else {
params.accesstoken = token;
}
}
return $.ajax({
async: async == undefined ? true : async,
url: requestUrl,
type: "POST",
dataType: "JSON",
data: params,
success: function (d) {
if ("undefined" == typeof noFilter || !noFilter) {
if (d.IsError) {
if (d.ErrorCode === 10000) {
$.msg("登录已失效,请重新登录!");
setTimeout(function () {
//if (wechatHelper.isWeiXin()) {
// loginOut(function () {
// location.reload();
// });
//} else {
//loginOut(function () {
// initLogin();
//});
//}
window.location.href = 'login.html';
}, 500);
} else {
$.msg(d.Msg);
}
return false;
} else {
if (callBack) {
callBack(d);
}
}
} else {
if (callBack) {
callBack(d);
}
}
},
error: function (e, text, err) {
if (err === 'abort') {
return;
}
$.msg("出错了");
return false;
},
complete: function (xhr, ts) {
xhr = null;
}
});
},
postHandleFun: function (postUrl, params, callBack, confirmMsg, noToken, noFilter, completeCallBack) {
var self = this;
var handleFun = function () {
self.postRequest(postUrl, params, function (d) {
if (callBack)
callBack(d);
}, noToken, noFilter).complete(function (d) {
if ($.isFunction(completeCallBack))
completeCallBack(d);
});
}
if (!confirmMsg && self.isNull(confirmMsg)) {
handleFun();
} else {
self.confirm({
content: confirmMsg,
ok: handleFun
});
}
},
loadDataList: function (api, params, tmpid, container, pgtag, pageSize, noToken, pgType, callBack, dcb/*绑定数据到html前的回掉*/, decb/*绑定数据到html后的回掉*/) {
if (!container)
container = "#datalist";
var oldcontainer = container;
container = typeof container === 'string' ? utils.getCurrObj().find(container) : container;
if (!pgtag)
pgtag = ".pg";
var oldpgtag = pgtag;
pgtag = typeof pgtag === 'string' ? utils.getCurrObj().find(pgtag) : pgtag;
if (params.PageIndex == undefined || params.PageIndex <= 1) {
$(container).html("");
}
if (pageSize == undefined) {
pageSize = 20;
if ($.cookie("pageSize") != null) {
pageSize = $.cookie("pageSize");
}
}
var tmp = tmpid;
// if (utils.isMobileBrowser()) {
// tmp = "mobile/" + tmpid;
// }
if (!pgType && $(window).width() >= 768) {
$(container).html("<tr><td colspan='30'><div class='loading'>加载中,请稍候...</div></td></tr>");
} else {
$(window).unbind("scroll.loaddata");
$(pgtag).html('<a href="javascript:void(0)" class="btn btn-default btn-block no-border loadmore"><span class=\"s-loading\">加载中</span></a>');
}
if (params && params.revisionPointer == undefined) {
revisionPointer++;
params.revisionPointer = revisionPointer;
}
params.PageSize = pageSize;
var self = this;
this.getRequest(api, params, function (d) {
if (('revisionPointer' in params) && params.revisionPointer != revisionPointer) {
return;
}
if (dcb) dcb(d);
if (d.Data && d.Data.TotalCount > 0) {
var html = template(tmp, {
items: d.Data.Collection,
curUserId: $.cookie("memberid"),
isSystemManager: $.cookie("issystemmanager")
});
if ((pgType && pgType === 1) || $(window).width() < 768) {
$(container).append(html);
} else {
$(container).html(html);
}
$(pgtag).show();
} else {
if (!pgType || pgType === 0) {
$(pgtag).html("");
$(container).find("td").addClass("nodata").html("没有符合条件的数据记录!");
} else {
$(pgtag).html('<a href="javascript:void(0)" class="btn btn-default btn-block no-border loadmore">数据已经加载完啦!</a>');
}
}
var pgFunc = self.loadPage();
var pg = new pgFunc(pgtag, params.PageIndex, d.Data ? d.Data.TotalCount : 0, function (ipage, pSize, pCallBack) {
params.PageIndex = ipage;
params.PageSize = pSize;
self.loadDataList(api, params, tmpid, oldcontainer, oldpgtag, pSize, noToken, pgType, function () {
if (callBack) {
callBack(d);
}
if (pCallBack) {
pCallBack();
}
}, dcb, decb);
}, pageSize, d.Data ? d.Data.TotalPages : 0, pgType, container);
pg.printHtml();
if (callBack) {
callBack(d);
}
if (decb) decb(d);
}, noToken);
},
openDialog: function (opts) {
$.bgdialog.dialog(opts);
},
closeDialog: function (id) {
$.bgdialog._remove($("#_dlg" + id));
},
confirm: function (opts) {
utils.openDialog({
id: "confirm",
title: "提示",
content: $("<div class=\"confirm-msg\" />").html(opts.content),
modelSizeCss: "modal-md",
callBack: function (dlgbox) {
$("#_dlgconfirm").find(".ui-dlg-bottom").attr("style", "padding:0 20px 20px 0;");
dlgbox.find("[data-evt='confirmOk']").unbind("click").click(function () {
if (opts.ok) {
opts.ok();
}
utils.closeDialog("confirm");
return false;
});
},
closeCallBack: opts.cancel
});
},
getUrlId: function () {
var self = this;
var hash = location.hash.split(/\?/)[0];
var len = hash.split("/").length;
var hasharr = hash.split("/");
var id = null;
if (self.isDigit(hasharr[(len - 1)])) {
id = hasharr[(len - 1)];
}
return id;
},
buttonHelper: function (btn, disabledText) {
return new buttonHelper(btn, disabledText);
},
goBack: function () {
history.back();
},
uploader: function (opts) {
var self = this;
if (!opts) {
opts = {};
}
var mimeTypes = [
{ title: "Image files", extensions: "jpg,gif,png,pmb,jpeg,tiff,svg" },
{ title: "files", extensions: "doc,docx,7z,xls,xlsx,ppt,pptx,rar,zip,pdf,txt,rtf,wps,dps,et" }
];
if (opts.mimeType && opts.mimeType === 1) {
mimeTypes = [
{ title: "Image files", extensions: "jpg,gif,png,pmb,jpeg,tiff,svg" }
];
} else if (opts.mimeType && opts.mimeType === 2) {
mimeTypes = [
{ title: "files", extensions: "doc,docx,7z,xls,xlsx,ppt,pptx,rar,zip,pdf,txt,rtf,wps,dps,et" }
];
} else if (opts.mimeType && opts.mimeType === 3) {
mimeTypes = [
{ title: "files", extensions: "apk,zip" }
];
} else if (opts.mimeType && opts.mimeType == 4) {
mimeTypes = [{ title: 'files', extensions: 'mp3,mp4,avi' }];
}
if (!opts.filelist) {
opts.filelist = "filelist";
}
var btnId = opts.browse_button == undefined ? "upload-acc" : opts.browse_button,
//currentPage = opts.container || utils.getCurrObj(),
$btn = $('#' + btnId),
$fileList = $('#' + opts.filelist);
var uploader = $btn.data("uploaderObj");
if (uploader) {
uploader.destroy();
}
uploader = new plupload.Uploader({
runtimes: "html5,flash,silverlight,html4",
browse_button: $btn[0],
//url: utils.hostUrl + (opts.uploadUrl == undefined ? "fileupload/chunkupload" : opts.uploadUrl),
url: utils.hostUrl + 'fileuploader.ashx',
max_file_count: opts.max_file_count == undefined ? 10 : opts.max_file_count,
multi_selection: opts.multi_selection == undefined ? true : opts.multi_selection,
max_file_size: opts.max_file_size == undefined ? "1024mb" : opts.max_file_size,
chunk_size: opts.chunk_size == undefined ? "2mb" : opts.chunk_size,
max_retries: 3,
filters: {
max_file_size: opts.max_file_size == undefined ? "1024mb" : opts.max_file_size,
mime_types: mimeTypes
},
flash_swf_url: "/js/libs/plupload/Moxie.swf",
silverlight_xap_url: "/js/libs/plupload/Moxie.xap",
multipart_params: {
accesstoken: $.cookie('token'),
//groupid: utils.getGroupId(),
//projectid: utils.getProjectId()
},
init: opts.init == undefined ? {
FilesAdded: function (up, files) {
plupload.each(files, function (file) {
//var html = $(template("upload/item", {
// fileId: file.id,
// fileName: file.name,
// fileSize: plupload.formatSize(file.size)
//}));
//html.find(".cancel").find("a").click(function () {
// $(this).closest(".uploadify-queue-item").empty().remove();
//});
//$fileList.append(html);
});
uploader.start();
},
BeforeUpload: function (up, file) {
if (opts.data) {
for (var key in opts.data) {
uploader.settings.multipart_params[key] = opts.data[key];
}
}
uploader.settings.multipart_params.realfilename = file.name;
},
ChunkUploaded: function (up, file, result) {
var json = $.parseJSON(result.response);
if (!json.IsError) {
uploader.settings.multipart_params.StorePath = json.Data[0].DownloadUrl;
} else {
uploader.removeFile(file);
}
},
UploadProgress: function (up, file) {
var cb = null;
if ($.isFunction(opts.progressFun)) {
cb = opts.progressFun;
}
if (cb) {
cb(file.percent);
}
if (file.percent < 100) {
$fileList.find("#" + file.id).find(".data").html(file.percent + "%");
} else {
$fileList.find("#" + file.id).find(".data").html("<span class='red'>还在上传中,请稍等...</span>");
}
},
FileUploaded: function (uploader, file, resp) {
$fileList.find("#" + file.id).find(".data").html("<span class='green'>已完成</span>");
var d = eval("(" + resp.response + ")");
if (!d) {
return;
}
if (d.IsError) {
$.msg('error', d.Msg);
return;
}
$("#" + file.id).attr("data-id", d.Data[0].ID);
//var ext = self.getFileExt(d.Data[0].DownloadUrl);
//var imgext = "jpg,gif,png,pmb,jpeg,tiff,svg".split(",");
//if (imgext.indexOf(ext) >= 0) {
// $("#" + file.id).find(".progressLeft").find("img").attr("src", d.Data[0].DownloadUrl.replace("/bgimg/", "/xx_bgimg/"));
//}
//console.log(d.Data[0].DownloadUrl);
if (opts.completeCallback)
opts.completeCallback(d.Data[0].DownloadUrl.replace("/bgimg/", "/x_bgimg/"));
},
Error: function (up, err) {
//错误回调
$.msg("error", err.code + ": " + err.message);
}
} : opts.init
});
//在实例对象上调用init()方法进行初始化
uploader.init();
$btn.data('uploaderObj', uploader)
return uploader;
},
handleBreadcrumb: function (title, callBack) {
document.title = "家服宝:" + title;
$(".breadcrumb").find("li:gt(0)").empty().remove();
if (utils.getCurrObj().find("[data-evt='query']").length == 0) {
utils.getCurrObj().append('<a href="javascript:void(0);" class="hide" data-evt="query"></a>');
}
if (title != "") {
$(".breadcrumb").append('<li class="active">' + title + '</li>');
utils.getCurrObj().find("[data-evt='query']:first").unbind("b.click").bind("b.click", function () {
$(".breadcrumb").find("li:gt(0)").empty().remove();
document.title = "家服宝:" + title;
$(".breadcrumb").append('<li class="active">' + title + '</li>');
if (callBack) {
callBack();
}
});
} else if (callBack) {
utils.getCurrObj().find("[data-evt='query']:first").unbind("b.click").bind("b.click", callBack);
}
},
initCkEditor: function (opts) {
var editor = UE.getEditor(opts.id, {
wordCount: false,
elementPathEnabled: false,
autosave: false,
zIndex: opts.zIndex === undefined ? 2000 : opts.zIndex,
initialFrameHeight: opts.height === undefined ? (utils.isMobileBrowser() ? 200 : 300) : opts.height,
toolbars: opts.toolbar === undefined ? [[
'source', '|', 'undo', 'redo', '|',
'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
'directionalityltr', 'directionalityrtl', 'indent', '|',
'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
'simpleupload', '|', 'horizontal', '|',
'inserttable', "fullscreen", "insertvideo"
]] : (opts.toolbar === 1 ? [[
'source', '|', 'undo', 'redo', '|',
'fontfamily', 'fontsize',
'bold', 'italic', 'underline', 'fontborder', 'forecolor', 'backcolor'
]] : [[]])
});
return editor;
},
getEditorId: function (id) {
var editorId = mPageManager.getPageUrl() + id;
utils.getCurrObj().find("#" + id).attr("id", editorId);
return editorId;
},
getCurrObj: function (strhash) {
return $('[data-url-id="{0}"]'.format(mPageManager.getPageUrl(strhash)));
},
initSelect: function ($select, url, width, initData) {
if (initData) {
if (!$.isArray(initData)) return;
}
$($select).select2({
data: initData,
placeholder: '请选择',
width: width ? width : '100%',
ajax: {
url: utils.hostUrl + url,
delay: 250,
data: function (params) {
params.accesstoken = $.cookie("token");
return params;
},
processResults: function (d) {
var results = [];
if (d && d.Data && d.Data.Collection) {
for (var i = 0, len = d.Data.Collection.length; i < len; i++) {
var p = {};
p.id = d.Data.Collection[i].Id;
p.text = d.Data.Collection[i].Name;
results.push(p);
}
}
return {
results: results
};
}
},
language: {
noResults: function () {
return "";
}
}
});
$($select).trigger('change');
},
initSelect2: function ($select, url, width, initData) {
// initSelect2 比 initSelect,添加一个“全部”选项
if (initData) {
if (!$.isArray(initData)) return;
}
$($select).select2({
data: initData,
placeholder: '请选择',
width: width ? width : '100%',
ajax: {
url: utils.hostUrl + url,
delay: 250,
data: function (params) {
params.accesstoken = $.cookie("token");
return params;
},
processResults: function (d) {
var results = [];
var p = {};
// 添加一个“全部”选项
p.id = 0;
p.text = "全部";
results.push(p);
if (d && d.Data && d.Data.Collection) {
for (var i = 0, len = d.Data.Collection.length; i < len; i++) {
var p = {};
p.id = d.Data.Collection[i].Id;
p.text = d.Data.Collection[i].Name;
results.push(p);
}
}
return {
results: results
};
}
},
language: {
noResults: function () {
return "";
}
}
});
$($select).trigger('change');
},
isMobileBrowser: function () {
return $(window).width() < 769;
}
};