define(['jquery', 'fmodal', 'handlebars', 'fselect', 'fscroll', 'ajaxRequest', 'validate', 'common', 'webUploader', 'laydate', 'myPlayer', 'audio'], function($, fmodal, handlebars, fselect, fscroll, ajaxRequest, validate, common, webUploader, laydate, myPlayer, audio) {
(function($){
// 备份jquery的ajax方法
var _ajax = $.ajax;
// 重写ajax方法,先判断登录在执行success函数
$.ajax = function (url, opt) {
if ( typeof url === "object" ) {
opt = url;
url = undefined;
} else {
opt = opt || {};
opt.url = url;
}
var _success = opt && opt.success || function (data, textStatus) { };
var _opt = $.extend(opt, {
success: function (result, textStatus) {
if (!result.status && result.data == 201) {
var host = window.location.host,
firstWord = host.split('.')[0].substring(0, 1),
pageJump;
switch ( firstWord ) {
case 't':
pageJump = '/customer/action/login/index';
break;
case 's':
pageJump = '/system/action/login/index';
break;
default:
pageJump = '/merchant/action/login';
break;
}
window.location.href = pageJump;
throw 'You are not recorded';
} else {
_success(result, textStatus);
}
}
});
return _ajax(_opt);
};
})(jQuery);
$(document).on('change', 'input[regular]', function() {
var $this = $(this),
reg = new RegExp($this.attr('regular')),
tips = $this.data('tips') || '输入不合法,请重新输入!';
if ( !reg.test($(this).val().trim()) ) {
alert(tips)
$this.focus().val('');
}
}).on('mousemove', function(e) {
var $el = $(e.target).closest('.js-my-tooltip')
if ($el.length) {
var text = $el.data('tooltip-content') || ''
if ($('.js-my-tooltip-popup').length && $('.js-my-tooltip-popup').text() == text) {
return
} else {
$('.js-my-tooltip-popup').remove()
}
var rectObj = $el[0].getBoundingClientRect()
var placement = $el.data('tooltip-placement') || 'top'
if ($(window).width() - rectObj.left - rectObj.width < 200) {
placement = 'left'
}
var placementStr = ''
var borderStr = ''
if (placement === 'top') {
placementStr = `top: calc(${rectObj.top}px - 6px); left: calc(${rectObj.left}px + ${rectObj.width/2}px); transform: translate(-50%, -100%);`
borderStr = `border-top: 5px solid #303133; border-right: 5px solid transparent; border-left: 5px solid transparent; top: 100%; left: calc(50% - 5px);`
} else if (placement === 'left') {
placementStr = `top: calc(${rectObj.top}px + ${rectObj.height/2}px); left: calc(${rectObj.left}px - 6px); transform: translate(-100%, -50%);`
borderStr = `border-left: 5px solid #303133; border-top: 5px solid transparent; border-bottom: 5px solid transparent; top: calc(50% - 5px); left: 100%;`
} else if (placement === 'bottom') {
placementStr = `top: calc(${rectObj.bottom}px + 6px); left: calc(${rectObj.left}px + ${rectObj.width/2}px); transform: translate(-50%, 0);`
borderStr = `border-bottom: 5px solid #303133; border-right: 5px solid transparent; border-left: 5px solid transparent; bottom: 100%; left: calc(50% - 5px);`
}
$("body").append(`
`);
} else {
$('.js-my-tooltip-popup').remove()
}
})
return {
header: function(){
var self = this;
$('select').fselect();
if($(document).scrollTop()>=300) {
$('.i-tohead').removeClass('hide');
}else {
$('.i-tohead').addClass('hide');
}
$(window).on('scroll', function() {
if($(document).scrollTop()>=300) {
$('.i-tohead').removeClass('hide');
}else {
$('.i-tohead').addClass('hide');
}
});
if ($('#merchantId').length && $('#merchantId').val() == 14498) {
$('.M_header').find('.logo a').remove();
}
$(document).on('click', 'img.js-captcha', function(){
var $this = $(this),
src = $this.data('src');
$this.attr('src', src+"?v="+Math.random());
}).on('click', '.js-agreement-modal', function() {
var $this = $(this);
self.renderAgreementModal($this);
}).on('blur', '.verify-used-phone', function() {
var $this = $(this);
self.verifyUsedPhone($this);
}).on('click', '.js-nav-extend', function() {
var $this = $(this);
self.navExtend($this);
}).on('click', '.js-nav-extend-merchant', function() {
var $this = $(this);
self.navExtendMerchant($this);
}).on('click', '.js-complaint', function() {
var $this = $(this);
self.complaintModal($this);
}).on('click', '.js-customer-complaint', function() {
var $this = $(this);
self.customerComplaintModal($this);
}).on('click', '.js-handle-aside', function() {
var $this = $(this);
self.handleAside($this);
}).on('click', '.js-customer-nav-has-subnav', function() {
var $this = $(this);
self.customerSubNav($this);
}).on('click', '.js-header-switch-account-btn', function() {
self.switchAccount();
});
$('.js-nonzero-int-input').intInput('+');
$('.shortcut-link').on('click', '.contact', function() {
//self.showContactModal($(this));
});
$('.js-account-overview').on('click', '.guide > .close', function() {
var $this = $(this),
$guide = $this.closest('.guide'),
$notice = $guide.siblings('.notice');
$guide.fadeOut();
$notice.removeClass('none');
}).on('click', '.notice', function() {
var $this = $(this);
$this.siblings('.guide').fadeIn();
});
// 商家系统显示隐藏二级菜单
if ($('.js-switch-menu-btn').length) {
$('.js-switch-menu-btn').on('click', function() {
$('.M_main').toggleClass('mini-menu');
});
}
// 如果是后台系统跳转过来的,禁用退出登录按钮
if ($.getUrlParam('loginToken') && $.getUrlParam('encrypt')) {
$('.M_header .logout a').css({'pointer-events': 'none', 'color': '#999'});
}
},
switchAccount: function() {
const popupNode = document.querySelector('.js-switch-account-popup')
if (popupNode) {
popupNode.remove()
}
const _style = `
.dialog-component { display: flex; align-items: center; justify-content: center; position: fixed; top: 0; left: 0; z-index: 2000; width: 100%; height: 100%; }
.dialog-component .dialog-component_bg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.6); animation: .3s dialogBgFadeIn; }
.dialog-component .dialog-component_container { position: relative; z-index: 1; background: #fff; border-radius: 2px; box-shadow: 0 1px 3px rgba(0,0,0,.3); box-sizing: border-box; overflow: hidden; animation: .3s dialogContentFadeIn; width: 1200px; min-width:400px; padding: 24px; }
.dialog-component .dialog-component_close-btn { position: absolute; cursor: pointer; top: 5px; right: 15px; z-index: 9; font-size: 32px; line-height: 1; }
.dialog-component .popup-title { font-size: 16px; color: #000; line-height: 16px; font-weight: 500; text-align: left; padding-bottom: 24px;}
.dialog-component .popup-content { max-height: 80vh; overflow: auto; color: #333; line-height: 1.5; text-align: left; font-size: 14px;}
@keyframes dialogBgFadeIn { 0% { opacity: 0; } 100% { opacity: 1; } }
@keyframes dialogContentFadeIn { 0% { opacity: 0; transform: translateY(-40px); } 100% { opacity: 1; transform: translateY(0px); } }
.dialog-component .search-input-box { position: relative; top: -5px; width: 330px; height: 40px; margin-bottom: 10px; border: 1px solid #dcdfe6; border-radius: 4px; }
.dialog-component .search-input-box input { border: none; width: 100%; height: 100%; background: none; padding: 0 15px; }
.dialog-component .search-input-box svg { position: absolute; right: 10px; top: 9px; }
.dialog-component .radio-cell { display: block; width: 360px; margin: 0 15px 10px 0; height: 65pxpx; float:left; border: 1px solid #e5e5e5; border-radius: 6px; padding: 6px 15px; line-height: 26px; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer;}
.dialog-component .radio-cell.active { background-color: #296dec; color: #fff; }`;
const cookieArr = document.cookie.match(new RegExp("(^| )" + 'merchant_token' + "=([^;]*)(;|$)"));
const _token = cookieArr ? unescape(cookieArr[2]) : null;
fetch(`/merchant/merchant/queryMutipleMerAccount?merchant_token=${_token}`, {
method: 'get',
headers: {'Content-Type': 'application/json'},
// body: JSON.stringify({})
}).then(response => {
if (response.ok) {
return response.json()
} else {
throw new Error(`Request failed. Status: ${response.status}`)
}
}).then(res => {
if (!res.status) {
alert(res.message)
return
}
if (!res.data) {
return
}
let listHtml = ''
for (let i = 0; i < res.data.length; i++) {
const item = res.data[i]
listHtml += `
${item.companyName}
账号:${item.loginName}
`
}
//#88BD65这颜色好看,领导不让用
const _html = `
`
document.querySelector('body').insertAdjacentHTML('beforeEnd', ``);
document.querySelector('.js-switch-account-popup .dialog-component_close-btn').addEventListener('click', () => document.querySelector('.js-switch-account-popup').remove())
const searchInputNode = document.querySelector('.js-switch-account-popup .search-input')
searchInputNode.addEventListener('input', e => {
if (searchInputNode.getAttribute('data-compositionstart')) return
let text = e.target.value || ''
let nodes = document.querySelectorAll('.js-switch-account-popup .radio-cell')
for (let i = 0; i < nodes.length; i++) {
let currTxt = nodes[i].innerText
if (currTxt.includes(text)) {
nodes[i].style.display = 'block'
} else {
nodes[i].style.display = 'none'
}
}
})
searchInputNode.addEventListener('compositionstart', event => {
searchInputNode.setAttribute('data-compositionstart', 1)
})
searchInputNode.addEventListener('compositionend', e => {
searchInputNode.setAttribute('data-compositionstart', '')
let text = e.target.value || ''
let nodes = document.querySelectorAll('.js-switch-account-popup .radio-cell')
for (let i = 0; i < nodes.length; i++) {
let currTxt = nodes[i].innerText
if (currTxt.includes(text)) {
nodes[i].style.display = 'block'
} else {
nodes[i].style.display = 'none'
}
}
})
}).catch(error => {
alert('网络繁忙,请稍后再试')
})
},
handleAside: function($this) {
var $aside = $this.closest('aside'),
$header = $aside.closest('section').siblings('header'),
$footer = $aside.closest('section').siblings('footer');
$aside.toggleClass('pack-up');
$header.toggleClass('pack-up');
$footer.toggleClass('pack-up');
$this.find('.iconfont').toggleClass('icon-gongjulan-shouqi').toggleClass('icon-gongjulan-zhankai');
},
animatePromotionNav: function() {
var $target = $('header.header ul.nav > li.double a') && $('header.header .h-activity a'),
animation = function() {
$target.addClass('tada animated');
setTimeout(function() {
$target.removeClass('tada animated');
}, 1000);
};
setTimeout(animation, 1000);
setInterval(animation, 30000);
},
animateInvite: function() {
var $target = $('.sf-bottom .invite span'),
animation = function() {
$target.addClass('shake animated');
setTimeout(function() {
$target.removeClass('shake animated');
}, 1000);
};
setTimeout(animation, 1000);
setInterval(animation, 5000);
},
animateSym: function() {
var $target = $('.shortcut .new-year > a'),
animation = function() {
$target.addClass('wobble animated');
setTimeout(function() {
$target.removeClass('wobble animated');
}, 1000);
};
setTimeout(animation, 1000);
setInterval(animation, 5000);
},
renderNewTask: function($this) {
var $guide = $this.closest('.guide'),
$notice = $guide.siblings('.notice');
$guide.fadeOut();
$notice.removeClass('none');
},
setNavActived: function($obj, e) {
e.preventDefault();
if ($obj.find('a').length) {
window.location.href = $obj.find('a').attr('href');
} else {
window.localStorage.setItem('current_nav', $obj.data('index') + 1);
window.location.href = '/';
}
},
resetNavActived: function() {
window.localStorage.setItem('current_nav', 1)
},
scrollTop: function(value, func) {
$('body, html').animate({
scrollTop : value
}, 600, function(){
if( typeof func != 'undefined' && typeof func == 'function' ) {
func();
}
});
return false;
},
showContactModal: function($this) {
var url = $this.data('url');
if($this.data('pending')) return false;
$this.data('pending', false);
$.get(url).done(function(modal) {
var $modal = $(modal);
$modal.appendTo($('body'));
$modal.fmodal({
show: true,
afterShow: function() {
$this.data('pending', false);
},
afterClose: function() {
$this.data('pending', false);
}
})
})
},
verifyUsedPhone: function($this) {
if($this[0].offsetParent === null) return;
var $form = $this.closest('form'),
url = $this.data('url'),
data = {
"phone": $this.val()
};
$this.data('ajax', false).ajaxRequest({
"url": url,
"data": data,
"callBack": function(result) {
if (!result.status) {
$form.data('validate', false).validate(result, 'overall');
$this.data('used', true);
} else {
$this.data('used', false);
}
}
})
},
complaintModal: function($this) {
var self = this,
$tpl = $('#' + $this.data('modal')),
$modal = $(handlebars.compile($tpl.html())());
$modal.appendTo($('body'));
$modal.fmodal({
show: true,
afterShow: function() {
$modal.on('click', '.submit', function() {
var $this = $(this);
self.complaintModalSubmit($this, $modal);
})
}
})
},
complaintModalSubmit: function($this, $modal) {
var $form = $this.closest('form'),
url = $form.data('action'),
data = $form.serializeArray();
if ($this.data('pending')) return false;
$this.data('pending', true);
$.post(url, data).done(function(result) {
if(result.status){
$.alert('提交成功!', function() { $modal.fmodal('hide'); });
} else {
$.alert(result.message);
}
$this.data('pending', false);
}).fail(function() {
$.alert();
$this.data('pending', false);
})
},
customerComplaintModal: function($this) {
var self = this,
url = $this.data('url'),
$tpl = $('#complaintModal'),
$modal;
$.post(url).done(function(result) {
if (result.status) {
$modal = $(handlebars.compile($tpl.html())(result.data));
$modal.appendTo($('body'));
$modal.fmodal({
show: true,
afterShow: function() {
self.fcheck();
self.customerComplaintModalUploadInit($modal);
$modal.on('click', '.submenu > ul > li', function() {
var $this = $(this),
$type = $this.data('type');
$('select').fselect();
$this.addClass('active').siblings().removeClass('active');
$('.complaint-modal').find('form.' + $type).removeClass('none').siblings().addClass('none');
}).on('click', '.submit', function() {
self.customerComplaintModalSubmit($(this), $modal);
}).on('mouseenter', '.upload-img-list li', function() {
self.customerComplaintModalInitEnter($(this), $modal);
}).on('mouseleave', '.upload-img-list li', function() {
self.customerComplaintModalInitLeave($(this), $modal);
}).on('click', '.file-panel .cancel', function() {
self.customerComplaintModalInitDelete($(this), $modal);
}).on('click', '.file-panel .view', function() {
self.customerComplaintModalInitView($(this), $modal);
})
}
})
} else {
alert(result.message);
}
}).fail(function() {
alert('服务器内部错误,请稍候重试!');
})
},
customerSubNav: function($this) {
var self = this,
$li = $this.closest('li'),
$subNav = $li.find('.sub-nav'),
subNavH = $subNav.find('a').length * 50;
if($li.hasClass('show-nav')) {
$li.removeClass('show-nav');
$subNav.animate({height: 0});
}else{
$li.addClass('show-nav');
$subNav.animate({height: subNavH});
}
},
customerComplaintModalInitDelete: function($this, $modal){
var $panel = $this.parent();
$panel.siblings('.img').prop('src', '').addClass('none');
$panel.siblings('[type="hidden"]').val('');
$panel.siblings('.imgWrap').removeClass('none').html('点击上传');
$panel.siblings('.info').addClass('none').html('');
$panel.siblings('.exception').addClass('none').html('');
$panel.siblings('.progress').addClass('none').find('> span').css('width', '0%');
$panel.addClass('none');
$panel.parent().removeClass('no-bg');
$panel.siblings('.init').data('ok', false);
},
customerComplaintModalInitView: function($this, $modal){
$('body').append('');
$('.img-box-modal').on('click', '.icon', function(){
$(this).parent().remove();
});
},
customerComplaintModalInitEnter: function($this, $modal){
var ok = $this.find('.init').data('ok');
if(ok){
$this.find('.file-panel').removeClass('none');
}
},
customerComplaintModalInitLeave: function($this, $modal){
$this.find('.file-panel').addClass('none');
},
customerComplaintModalUploadInit: function($modal){
var self = this,
url="http://upload.qiniu.com",
$list = $modal.find('.upload-img-list');
$modal.find('.upload-img-list > li > .init').each(function(i, obj){
var $obj = $(obj),
uploader = null,
progress = 0;
uploader = webUploader.create({
auto: false,
swf: '/static/scripts/vendor/webUploader/Uploader.swf',
server: url,
pick: $obj,
duplicate: true,
accept: {
title: 'Images',
extensions: 'jpg,jpeg,bmp,png,gif',
mimeTypes: 'image/jpg,image/jpeg,image/bmp,image/png'
},
fileSingleSizeLimit: 8000*1024
});
uploader.on( 'fileQueued', function( file ) {
$obj.data('ext', file.ext);
$obj.siblings('.imgWrap').html('正在上传中');
self.uploadFile($obj, this, $list);
}).on('uploadProgress',function(file,percentage){
progress = parseInt(percentage * 100) + '%';
$obj.siblings('.imgWrap').html('已上传:' + progress);
$obj.siblings('.progress').removeClass('none').find('> span').css('width', progress);
}).on( 'uploadSuccess', function( file ,response ) {
var qiniuUrl = $obj.data('qiniudomain') + '/' + response.key;
$obj.data('ok', true);
$obj.siblings('.imgWrap').addClass('none');
$obj.siblings('.info').removeClass('none').html('上传成功');
$obj.siblings('[type="hidden"]').removeClass('none').val(qiniuUrl);
$obj.siblings('.img').removeClass('none').prop('src', qiniuUrl);
$obj.siblings('.exception').addClass('none');
$obj.siblings('.progress').addClass('none').find('> span').css('width', '0%');
$obj.parent().addClass('no-bg');
//uploader.option("formData", null);
}).on("error", function(type) {
//uploader.option("formData", null);
$obj.siblings('.info').addClass('none');
$obj.parent().removeClass('no-bg');
$obj.data('ok', false);
if (type=="Q_TYPE_DENIED") {
$obj.siblings('.exception').removeClass('none').html('只能上传图片');
} else if(type=="F_EXCEED_SIZE") {
$obj.siblings('.exception').removeClass('none').html('文件不能超过800kb');
} else if(type=="F_DUPLICATE") {
$obj.siblings('.exception').removeClass('none').html('请不要重复上传');
} else {
$obj.siblings('.exception').removeClass('none').html('上传失败,请重试');
}
});
});
},
uploadFile: function($obj, $uploader, $list) {
var fileExt = $obj.data('ext'),
tokenUrl = $list.data('tokenurl'),
data = {
ext: fileExt
};
if(fileExt == "") {
$.alert('选择上传文件');
return false;
}
$.post(tokenUrl, data).done(function(result) {
if(result.data.status){
var qiniukey=result.data.data.key,
qiniuToken=result.data.data.token,
qiniuDomain=result.data.data.domain;
$obj.data('qiniudomain', qiniuDomain);
$uploader.option("formData", {key: qiniukey, token: qiniuToken});
$uploader.upload();
}
}).fail(function() {
$.alert('服务器响应失败,请稍后再试!');
})
},
customerComplaintModalSubmit: function($this, $modal) {
var $form = $this.closest('form'),
url = $form.data('action'),
classify = $('.complaint-modal').find('.submenu > ul > li.active').data('classify'),
data = $form.serializeArray();
data.push({name: 'classify', value: classify});
/*if($form.find('[name="complain_supervisor"]').val() == '') {
alert('您还没有选择主管哦!');
return false;
}*/
if($form.find('[name="merchant_id"]').val() == '') {
alert('您还没有选择商家哦!');
return false;
}
if($form.find('[name="content"]').val() == '') {
alert('您还没有填写建议哦!');
return false;
}
if ($this.data('pending')) return false;
$this.data('pending', true);
$.post(url, data).done(function(result) {
if(result.status){
$.alert('提交成功!', function() { $modal.fmodal('hide'); });
} else {
$.alert(result.message);
}
$this.data('pending', false);
}).fail(function() {
$.alert();
$this.data('pending', false);
})
},
renderAgreementModal: function($obj, func) {
var url = $obj.data('url');
$.get(url).done(function(modal) {
var $modal = $(modal);
$modal.appendTo($('body'));
$modal.fmodal({
show: true,
afterShow: function() {
if (func && typeof func == "function") {
func($modal);
}
},
afterClose: function() {
$obj.data('pending', false);
}
})
})
},
replaceNotification: function() {
var $target = $('.account-overview .msg-count');
$target.each(function() {
var currLen = $(this).text();
currLen--;
$(this).text(currLen);
if (currLen == 0) {
$(this).hasClass('notification') && $(this).remove();
}
})
},
fcheck: function(func){
$('label.fcheck').each(function(){
if(!$(this).data('simed')) {
$(this).data('simed', true);
if($(this).find('input[type="checkbox"]').prop('checked')) {
$(this).addClass('checked');
}else {
$(this).removeClass('checked');
}
if($(this).find('input[type="checkbox"]').prop('disabled')) {
$(this).addClass('disabled');
}else {
$(this).removeClass('disabled');
}
$(this).find('input[type="checkbox"]').on('change', function(){
if($(this).prop('checked')) {
$(this).closest('label').addClass('checked');
} else {
$(this).closest('label').removeClass('checked');
}
if ( $(this).closest('label').hasClass('good-radio') || $(this).closest('label').hasClass('bad-radio') ) {
if ($(this).is(':checked')) {
$('input[name="'+ $(this).prop('name') +'"]').prop('checked', false).closest('label').removeClass('checked');
$(this).prop('checked', 'checked').closest('label').addClass('checked');
}
}
if(func && typeof func == "function") func($(this));
});
}
});
},
fradio: function(func){
$('label.fradio').each(function(){
if(!$(this).data('simed')) {
$(this).data('simed', true);
if($(this).find('input[type="radio"]').prop('checked')) {
$(this).addClass('checked');
}else {
$(this).removeClass('checked');
}
if($(this).find('input[type="radio"]').prop('disabled')) {
$(this).addClass('disabled');
}else {
$(this).removeClass('disabled');
}
$(this).find('input[type="radio"]').on('change', function(){
$('input[name="'+ $(this).prop('name') +'"]').closest('label').removeClass('checked');
$(this).closest('label').addClass('checked');
if(func && typeof func == "function") func($(this));
});
}
});
},
pageScroll: function(func) {
var $scrollToHead = $('.shortcut > .top').length ? $('.shortcut > .top') : $('.shortcut-customer > .last'),
scrollTop = $(document).scrollTop();
// this.scrollToHead($scrollToHead, scrollTop);
if($('header.m-header').length) {
(scrollTop > 100) ? $('header.m-header').addClass('fixed') : $('header.m-header').removeClass('fixed');
}else{
(scrollTop > 200) ? $('header.c-header').addClass('fixed') : $('header.c-header').removeClass('fixed');
}
if (func && typeof func =="function") func();
},
scrollToHead: function($obj, top) {
if (top > 730) {
$obj.stop(true).animate({
'opacity': 1,
'bottom': 0
}, 100)
} else {
$obj.stop(true).animate({
'opacity': 0,
'bottom': -60
}, 100)
}
},
scrollnewYearSym: function($obj, top) {
if (top > 850) {
$obj.stop(true).animate({
'right': 0
}, 100)
} else {
$obj.stop(true).animate({
'right': -140
}, 100)
}
},
addEvent: function(obj, evType, fn, useCapture) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, useCapture);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent('on' + evType, fn);
return r;
} else {
obj['on' + evType] = fn;
}
},
poptip: function(){
$(document).on('click', '.js-poptip', function() {
var $this = $(this);
$('.poptip').hide();
$this.next('.poptip').show();
}).on('click', function(e) {
var $target = $(e.target);
if (!$target.closest('.action-list').length) {
$('.poptip').hide();
}
})
},
renderMessageModal: function(data) {
},
scrollStatus: false,
windowScroll: function(position, func) {
var self = this,
interval = 0,
timerScroll = null;
if(self.status) return false;
self.status = true;
position = Math.ceil(position);
clearInterval(timerScroll);
timerScroll = setInterval(function() {
var scTop = $(window).scrollTop();
interval = (position - scTop) / 10;
interval = interval > 0 ? Math.ceil(interval) : Math.floor(interval);
if (scTop == position) {
clearInterval(timerScroll);
func && func();
self.status = false;
}else {
$(window).scrollTop(scTop + interval);
}
}, 10);
},
navExtend: function($obj) {
var $target = $obj.closest('aside'),
$ul = $target.find('ul'),
$li = $ul.find('li > a'),
$img = $ul.find('.logo > img');
if ($obj.data('extend')) {
$ul.animate({
"width": 250
}, 300, function() {
$obj.data('extend', false);
});
$obj.animate({
"left": 227
}, 300);
$img.animate({
"width": 140,
"top": 0,
"left": 0
}, 300);
$li.animate({
"padding-left": 65
});
} else {
$ul.animate({
"width": 65
}, 300, function() {
$obj.data('extend', true);
});
$obj.animate({
"left": 75
}, 300);
$img.animate({
"width": 110,
"top": 8,
"left": 15
}, 300);
$li.animate({
"padding-left": 23
});
}
},
navExtendMerchant: function($obj) {
var $target = $obj.closest('aside'),
$ul = $target.find('ul'),
$li = $ul.find('li > a'),
$leftcon = $('.M_header').find('.left-con'),
$img = $ul.find('.logo > img');
if ($obj.data('extend')) {
$obj.removeClass('icon-hidemenu-copy');
$ul.animate({
"width": 250
}, 300, function() {
$obj.data('extend', false);
});
$obj.animate({
"left": 260
}, 300);
$img.animate({
"width": 140,
"top": 0,
"left": 0
}, 300);
$li.animate({
"padding-left": 65
});
$leftcon.animate({
"left": 120
});
} else {
$obj.addClass('icon-hidemenu-copy');
$ul.animate({
"width": 60
}, 300, function() {
$obj.data('extend', true);
});
$obj.animate({
"left": 75
}, 300);
$img.animate({
"width": 110,
"top": 8,
"left": 15
}, 300);
$li.animate({
"padding-left": 20
});
$leftcon.animate({
"left": -60
});
}
},
phoneVerification: function($obj){
var self = this,
$this = $obj,
$form = $this.closest('form'),
$phoneGroup = $this.closest('dl'),
$tips = $phoneGroup.find('.i-note'),
$message = $phoneGroup.find('.error-msg'),
defaultCount = $tips.find('i').data('count'),
$phone = $this.closest('form').find('input[name="phone"]'),
url = $obj.data('url'),
vcode = $.trim($form.find('input[name="verifyCode"]').val()),
data = {
"phone" : $this.closest('form').find('input[name="phone"]').val(),
"type" : $this.data('type'),
"verifyCode": vcode
};
if($this.data('pending')) return false;
$this.data('pending', true);
if (!$phone.data('phonearr')) {
$phone.data('phonearr', []);
}
for(i in $phone.data('phonearr')) {
if($phone.data('phonearr')[i] == $phone.val()) {
$phone.data('acquired', true);
}
}
if (!$phone.data('acquired')) {
$phone.data('phonearr').push($phone.val());
}
if ($obj.data('invisible')) {
data = {
"type" : $this.data('type'),
"verifyCode": vcode
}
} else {
if($this.data('phone') != data.phone) {
$this.data('pending', false);
}
$this.data('phone', data.phone);
}
$form.data('cansubmit', true);
$form.find('[name="phone"]').validate({'type': 'phone'}, 'local');
$form.find('[name="verifyCode"]').validate({'type': 'none'}, 'local');
if(!$form.data('cansubmit')) {
$this.data('pending', false);
return false;
}
var countdown = function() {
setTimeout(function(){
var count = $tips.find('i').text() - 1;
$tips.find('i').html(count);
if($tips.find('i').html() <= "0") {
self.countdownStatus = false;
clearTimeout(countdown);
$obj.val('重新获取');
$tips.addClass('tj-none').addClass('none').find('i').html(defaultCount);
$this.data('pending', false);
return false;
} else {
countdown();
}
},1000);
};
$obj.data('ajax', false).ajaxRequest({
"url": url,
"data": data,
"callBack": function(result) {
if(result.status) {
$message.addClass('tj-none').addClass('none');
$tips.removeClass('tj-none').removeClass('none');
$tips.find('i').text(defaultCount);
if (!self.countdownStatus) {
self.countdownStatus = true;
countdown();
}
} else {
$form.data('validate', false).validate(result, 'overall');
$this.data('pending', false);
}
}
})
},
getUrlParm:function(parm){
var reg = new RegExp("(^|&)"+ parm +"=([^&]*)(&|$)"),
r = window.location.search.substr(1).match(reg);
if(r!=null)return unescape(r[2]); return null;
},
emailVerification: function($obj){
var $this = $obj,
$form = $this.closest('form'),
$phoneGroup = $this.closest('dl'),
$tips = $phoneGroup.find('.i-note'),
$message = $phoneGroup.find('.error-msg'),
url = $obj.data('url'),
data = {
"email" : $this.closest('form').find('input[name="email"]').val(),
"type" : $this.data('type')
};
if($this.data('pending')) return false;
$this.data('pending', true);
$form.data('cansubmit', true);
$form.find('[name="email"]').validate({'type': 'email'}, 'local');
if(!$form.data('cansubmit')) {
$tips.addClass('tj-none').addClass('none');
$this.data('pending', false);
return false;
}
$obj.data('ajax', false).ajaxRequest({
"url": url,
"data": data,
"callBack": function(result) {
if(result.status) {
$message.addClass('tj-none').addClass('none');
$tips.removeClass('tj-none').removeClass('none').html(result.message);
} else {
$tips.addClass('tj-none').addClass('none');
$message.removeClass('tj-none').removeClass('none').html(result.message);
}
$this.data('pending', false);
}
})
},
getCities: function($obj) {
var $modal = $obj.closest('.js-regionTree'),
url = '/ajax/getCities.json',
data = {
"province" : $obj.val()
};
$obj.data('ajax', false).ajaxRequest({
"url": url,
"data": data,
"callBack": function(result) {
$modal.find('select[name="city"]').find('option').each(function(index){
if(index != 0) {
$(this).remove();
}
});
if(result) {
for(var i=0; i' +
result[i].name + '');
$modal.find('select[name="city"]').append(option);
};
};
$modal.find('select[name="city"]').fselect('update').trigger('change');
}
})
},
getCounties: function($obj) {
var $modal = $obj.closest('.js-regionTree'),
url = '/ajax/getCounties.json',
data = {
"city" : $obj.val()
};
if($modal.find('select[name="county"]').length == 0) return false;
$obj.data('ajax', false).ajaxRequest({
"url": url,
"data": data,
"callBack": function(result) {
$modal.find('select[name="county"]').find('option').each(function(index){
if(index != 0) {
$(this).remove();
}
});
if(result) {
for(var i=0; i' +
result[i].name + '');
$modal.find('select[name="county"]').append(option);
};
};
$modal.find('select[name="county"]').fselect('update');
}
})
},
renderQQNumber: function() {
var $mainConsult = $('.sio-right a.qq'),
$asideConsult = $('.shortcut li.qq > a'),
$footConsult = $('.sfb-desc a.icon-qq'),
$modalConsult = $('.knowmore-right a.icon-qq'),
nightNumber = '2881359809';
this.getHourofServerDate(function(curHour) {
if (curHour < 9 || curHour > 17) {
$mainConsult.prop('href', 'http://wpa.qq.com/msgrd?v=3&uin=2881359809&site=qq&menu=yes');
$asideConsult.prop('href', 'http://wpa.qq.com/msgrd?v=3&uin=2881359809&site=qq&menu=yes');
$footConsult.html(nightNumber).prop('href', 'http://wpa.qq.com/msgrd?v=3&uin=2881359809&site=qq&menu=yes');
$modalConsult.html(nightNumber).prop('href', 'http://wpa.qq.com/msgrd?v=3&uin=2881359809&site=qq&menu=yes');
}
});
},
getDateString: function(current, switchType, count) {
var currentDate = new Date(current),
count = count ? count : 0;
if (switchType == 'month') {
currentDate.setMonth(currentDate.getMonth() + count);
} else if (switchType == 'week'){
currentDate.setDate(currentDate.getDate() + count * 7);
} else {
currentDate.setDate(currentDate.getDate() + count);
}
var y = currentDate.getFullYear(),
m = (currentDate.getMonth() < 9) ? ('0' + (currentDate.getMonth() + 1)) : (currentDate.getMonth() + 1),
d = (currentDate.getDate() < 10) ? ('0' + currentDate.getDate()) : currentDate.getDate();
if (switchType == 'month') {
var str = y + "-" + m;
} else {
var str = y + "-" + m + "-" + d;
}
return str;
},
getDateStringIE: function(current, switchType, count) {
var current = current.split('-'),
now = null,
currentDate = null,
count = count ? count : 0;
if(current.length <= 2){
currentDate = new Date(current[0],current[1] - 1);
} else{
currentDate = new Date(current[0],current[1] - 1,current[2]);
}
if (switchType == 'month') {
currentDate.setMonth(currentDate.getMonth() + count);
} else if (switchType == 'week'){
currentDate.setDate(currentDate.getDate() + count * 7);
} else {
currentDate.setDate(currentDate.getDate() + count);
}
var y = currentDate.getFullYear(),
m = (currentDate.getMonth() < 9) ? ('0' + (currentDate.getMonth() + 1)) : (currentDate.getMonth() + 1),
d = (currentDate.getDate() < 10) ? ('0' + currentDate.getDate()) : currentDate.getDate();
if (switchType == 'month') {
var str = y + "-" + m;
} else {
var str = y + "-" + m + "-" + d;
}
return str;
},
getDateofWeekStart: function(date) {
var now = new Date(date),
nowDayOfWeek = now.getDay() == 0 ? 7 : now.getDay(),
nowYear = now.getFullYear(),
nowMonth = now.getMonth(),
nowDay = now.getDate(),
weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1);
return this.formatDate(weekStartDate);
},
getDateofWeekEnd: function(date) {
var now = new Date(date),
nowDayOfWeek = now.getDay() == 0 ? 7 : now.getDay(),
nowYear = now.getFullYear(),
nowMonth = now.getMonth(),
nowDay = now.getDate(),
weekEndDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 7);
return this.formatDate(weekEndDate);
},
getDatesInWeek: function(date) {
var now = new Date(date),
nowDayOfWeek = now.getDay() == 0 ? 7 : now.getDay(),
nowYear = now.getFullYear(),
nowMonth = now.getMonth(),
nowDay = now.getDate(),
dateArr = [];
for(var i=0; i<7; i++) {
var str = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1 + i);
dateArr.push(this.formatDate(str));
}
return dateArr;
},
getDateofLastWeek: function(date) {
var now = new Date(date),
nowYear = now.getFullYear(),
nowMonth = now.getMonth(),
nowDay = now.getDate(),
newDay = new Date(nowYear, nowMonth, nowDay - 7);
return newDay;
},
getDateofNextWeek: function(date) {
var now = new Date(date),
nowYear = now.getFullYear(),
nowMonth = now.getMonth(),
nowDay = now.getDate(),
newDay = new Date(nowYear, nowMonth, nowDay + 7);
return newDay;
},
getDateofNextWeekIE: function(date) {
var date = date.split('-'),
now = new Date(date[0],date[1] - 1,date[2]),
nowYear = now.getFullYear(),
nowMonth = now.getMonth(),
nowDay = now.getDate(),
newDay = new Date(nowYear, nowMonth, nowDay + 7);
return newDay;
},
getDateofLastWeek: function(date) {
var date = date.split('-'),
now = new Date(date[0],date[1] - 1,date[2]),
nowYear = now.getFullYear(),
nowMonth = now.getMonth(),
nowDay = now.getDate(),
newDay = new Date(nowYear, nowMonth, nowDay - 7);
return newDay;
},
formatDate: function(date) {
var y = date.getFullYear(),
m = (date.getMonth() < 9) ? ('0' + (date.getMonth() + 1)) : (date.getMonth() + 1),
d = (date.getDate() < 10) ? ('0' + date.getDate()) : date.getDate(),
str = y + "-" + m + "-" + d;
return str;
},
getHourofServerDate: function(func) {
$.post('/merchant/action/user/getNowDate').done(function(str) {
if (func && typeof func == "function") func(str);
})
},
scrollMerchantList: function() {
$('.js-switch-merchant').fscroll({
minHeight: 100
})
},
setCookie: function(name, value, day) {
if(day){
var exp = new Date();
exp.setTime(exp.getTime() + day*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}else{
document.cookie = name + "="+ escape (value);
}
},
getCookie: function(name) {
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arr != null) return unescape(arr[2]); return null;
},
delCookie:function(name) {
var cval= this.getCookie(name),
exp = new Date();
exp.setTime(exp.getTime() - 1);
if(cval != null) {
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
},
sortAble: function($table, $li, type) {
var self = this,
$ul = $table.find('ul').not('.head'),
aTrs = new Array,
index = $li.closest('li').index(),
method = type=='asc' ? 1 : -1;
$ul.each(function(i) {
aTrs[i] = $(this);
})
aTrs.sort(self.compareEle(index, method));
var $newTable = $('');
for (var i=0; i < aTrs.length; i++) {
$newTable.append(aTrs[i]);
}
$table.append($newTable.html())
},
compareEle: function(index, method) {
return function (row1, row2) {
var v1 = row1.find('li').eq(index).data('val') * method,
v2 = row2.find('li').eq(index).data('val') * method;
if (v1 < v2) {
return -1;
} else if (v1 > v2) {
return 1;
} else {
return 0;
}
}
},
jsonToString: function(json) {
var arr = [];
var fmt = function(s) {
if (typeof s == 'object' && s != null) return JsonToStr(s);
return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s;
}
for (var i in json) {
arr.push("'" + i + "':" + fmt(json[i]));
}
return '{' + arr.join(',') + '}';
},
flashChecker: function(warnEl) {
var hasFlash = 0; /* 是否安装了flash */
var flashVersion = 0; /* flash版本 */
var isIE =/*@cc_on!@*/0; /* 是否IE浏览器 */
if (isIE) {
var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (swf) {
hasFlash = 1;
flashVersion = swf.GetVariable("$version");
}
} else {
if (navigator.plugins && navigator.plugins.length > 0) {
var swf = navigator.plugins["Shockwave Flash"];
if (swf) {
hasFlash = 1;
flashVersion = swf.description.split(" ");
}
}
}
if (! hasFlash) {
$.alert('flash加载失败');
}
return {
f: hasFlash,
v: flashVersion
};
},
/**
* 常用按钮的ajax操作
*/
normalAjaxButton: function(options){
var $this = options.obj,
msg = options.msg?options.msg:'确认要执行该操作吗?',
url = $this.data('url'),
after = options.after,
data = options.data? options.data: {},
hint = options.hint? options.hint: '请稍后',
text = $.trim($this.html());
if(confirm(msg)){
if ($this.data('pending')) return false;
$this.data('pending', true);
$this.html(hint);
$.post(url, data).done(function(result) {
$this.data('pending', false);
$this.html(text);
if(result.status){
if($.isFunction(after)){
after(options, result);
}
} else {
alert(result.message);
}
}).fail(function(result){
alert('服务器响应失败,请重试!');
$this.html(text);
$this.data('pending', false);
})
}
},
normalAjaxButtonForT: function(options){
var $this = options.obj,
msg = options.msg?options.msg:'确认要执行该操作吗?',
url = $this.data('url'),
after = options.after,
data = options.data? options.data: {},
hint = options.hint? options.hint: '操作中..',
text = $.trim($this.html());
if(confirm(msg)){
if ($this.data('pending')) return false;
$this.data('pending', true);
$this.html(hint);
$.post(url, data).done(function(result) {
$this.data('pending', false);
if(!$.isPlainObject(result)){
result = JSON.parse(result);
}
$this.html(text);
if(result.data.status){
if($.isFunction(after)){
after(options, result);
}
} else {
alert(result.data.message);
}
}).fail(function(result){
alert('服务器响应失败,请重试!');
$this.html(text);
$this.data('pending', false);
})
}
},
/**
* 后台页面[当某个一个操作完成以后执行,会自动根据#js-search-form是否存在从而执行页面刷新还是执行搜索]
*/
refreshOrAjax: function(){
if($('#js-search-form').length == 1){
$('#js-search-form').find('[type="submit"]').trigger('click');
} else {
location.reload();
}
},
/**
* 全选
*/
checkAll: function($this, $target, after) {
var choose = $this.prop('checked');
$target.find('[type="checkbox"]').prop('checked', choose).parent();
if(choose){
$target.find('[type="checkbox"]').parent().addClass('checked');
} else {
$target.find('[type="checkbox"]').parent().removeClass('checked');
}
if($.isFunction(after)){
after($this, $target);
}
},
/**
* [后台]导出文件 ps:需要带表单参数
*/
fileOut: function($this){
var $form = $('#js-search-form'),
$form = $form.length > 0 ? $form : $this.closest('form'),
url = $this.data('url');
if($form.length == 1){
var data = $form.serialize();
window.open(url + '?' + '&' + data);
} else {
window.open(url);
}
},
/**
* 通用表单搜索
*/
filterList: function($this, $form, keepCurrPage) {
if(!keepCurrPage) {
$form.find('[name="currPage"]').val('1');
} else {
$form.find('[name="currPage"]').val(keepCurrPage);
}
var self = this,
$list = $('.js-filter-list'),
url = $form.data('action'),
data = $form.serializeArray();
if ($this.data('pending')) return false;
$this.data('pending', true);
$.post(url, data).done(function(result) {
$list.html($(result));
self.fcheck();
$this.data('pending', false);
}).fail(function() {
alert('服务器响应失败,请稍后再试!');
$this.data('pending', false);
})
},
/**
* 表格录音播放
*/
voicePlay: function($target){
$target.find('audio').on('play',function(){
var $other = $(this).closest('ul').siblings().find('audio');
$other.each(function(i,obj){
var $obj = obj;
$obj.pause();
});
});
},
/**
* 自定义播放
* @param {Object} $this
*/
voiceFileListAudio: function($this){
var $myAudio = $this.parent(),
play = $myAudio.hasClass('play'),
$audio = $myAudio.find('audio'),
$other = $myAudio.closest('ul').siblings().find('audio');
if (play) {
$myAudio.removeClass('play');
$audio[0].pause();
$this.prop('title', '点击播放');
}else{
$myAudio.addClass('play');
$audio[0].play();
$this.prop('title', '点击暂停');
$other.each(function(i, obj){
obj.pause();
$(obj).parent().removeClass('play');
});
}
},
/**
* audio事件绑定
*/
audioEventBind: function($target){
var self = this;
$target.find('.js-audio audio').on('loadedmetadata', function(){
self.audioBeginLoad($(this)[0]);
}).on('timeupdate', function(){
self.audioOnprogress($(this)[0]);
}).on('ended', function(){
self.audioEnded($(this)[0]);
}).on('error', function(){
self.audioError($(this)[0]);
});
},
/**
* 播放结束
* @param {Object} audio
*/
audioEnded: function(audio){
$(audio).parent().removeClass('play');
$(audio).siblings('.audio-progress').find('> div').css('width', '0%');
$(audio).siblings('.audio-result').html('已播放').addClass('c-blue').removeClass('c-red');
},
/**
* 获取音频长度并显示
* @param {Object} audio
*/
audioBeginLoad: function(audio){
var self = this,
$show = $(audio).siblings('.audio-time');
$show.html('00:00/' + self.formatTime(audio.duration));
},
/**
* 音频进度监控
* @param {Object} audio
*/
audioOnprogress: function(audio){
var self = this,
currentTime = audio.currentTime,
$myAudio = $(audio).parent(),
progress = currentTime / audio.duration,
$show = $myAudio.find('.audio-time'),
$progress = $myAudio.find('.audio-progress > div');
$progress.css('width', parseInt(progress * 100) + '%');
$show.html(self.formatTime(currentTime) + '/' + self.formatTime(audio.duration));
},
audioError: function(audio){
var $show = $(audio).siblings('.audio-result');
$show.html('播放失败');
$show.addClass('c-red').removeClass('c-blue');
$show.parent().removeClass('play');
},
/**
* 格式化为分秒
* @param {Object} seconds
*/
formatTime: function(seconds) {
return [
//parseInt(seconds / 60 / 60),
parseInt(seconds / 60 % 60),
parseInt(seconds % 60)
]
.join(":")
.replace(/\b(\d)\b/g, "0$1");
},
/**
* 显示本地modal
*/
showLocalModal: function(options){
var $this = options.obj,
$tpl = $('#' + $this.data('modal'));
data = options.data? options.data: {},
after = options.after,
$modal = $(handlebars.compile($tpl.html())(data));
$modal.appendTo($('body'));
$modal.fmodal({
show: true,
afterShow: function() {
if($.isFunction(after)){
after($modal, options);
}
}
})
},
chooseAll: function($this){
var $list = $('.js-filter-list .tj-table [type=checkbox][name]'),
result = $this.prop('checked');
$list.prop('checked', result);
if(result){
$list.parent().addClass('checked');
} else {
$list.parent().removeClass('checked');
}
},
/**
* ajax显示modal
*/
showAjaxModal: function(options){
var $this = options.obj,
$tpl = $('#' + $this.data('modal'));
ajaxData = options.ajaxData? options.ajaxData: {},
localData = options.localData? options.localData: {},
url = $this.data('url'),
after = options.after;
if ($this.data('pending')) return false;
$this.data('pending', true);
$.post(url, ajaxData).done(function(result) {
var $modal = null;
if($tpl.length == 0){
$modal = $(handlebars.compile(result)(localData));
} else {
$modal = $(handlebars.compile($tpl.html())(localData));
}
$modal.appendTo($('body'));
$modal.fmodal({
show: true,
afterShow: function() {
$this.data('pending', false);
if($.isFunction(after)){
after($modal, options, result);
}
}
});
}).fail(function() {
alert('服务器内部错误,请稍后再试!');
$this.data('pending', false);
})
},
layDateInit: function($panel){
var $objs = null;
if($panel) {
$objs = $panel.find('.form_datetime');
} else {
$objs = $('.form_datetime');
}
$objs.each(function(i, obj){
var input = $(obj).find('[type="text"]')[0],
$input = $(input);
laydate.render({
calendar: true,
elem: input,
type: $input.data('type')?$input.data('type'):'date',
range: $input.data('range')?false:'至',
format: $input.data('format')?$input.data('format'):'yyyy-MM-dd',
min: $input.data('min')?$input.data('min'):'1900-1-1',
max: $input.data('max')?$input.data('max'):'2099-12-31',
done: function(value, date, endDate){
var $this = $(this.elem[0]),
value = value.split(' ' + this.range + ' ');
$this.siblings('.start').val(value[0]);
$this.siblings('.end').val(value[1]);
}
});
$input.next('.add-on').on('click', '.icon-remove', function(){
$input.val('');
$input.siblings('.start').val('');
$input.siblings('.end').val('');
});
});
},
/**
* animated css
*/
animatedCss: function(options){
var $objs = options.objs,
css = options.css + ' animated';
$objs.each(function(i, obj){
var $obj = $(obj),
ran = Math.random() * $obj.index() * 100;
setTimeout(function(){
$obj.addClass(css);
}, ran);
});
},
initPlayer: function (){
if ($('audio').length) {
audiojs.events.ready(function() {
audiojs.createAll();
});
}
if ($('#myplayer').length) {
MyPlayer.init({
useLocal : true,
localUrl : "/static/scripts/vendor/myPlayer/",
baseId : "myplayer",
audioUrl : $('#myplayer').data('url'),
playUrl : "",
pauseUrl : "",
stopUrl : "",
progressColor : "#5ea9ed"
})
}
}
};
});