//一次只 run 一次
var tagUserList = false;
var smileStr = $.map(smile_arr, function(val, key) {
return key;
}).join('|');
var searchText = "\\[(" + smileStr + ")\\]";
var smileRegExp = new RegExp(searchText, 'g');
$(document).ready(function() {
// 此寫法使得後來以 AJAX 方式載入的 DOM 也能夠觸發事件
$(document).on('click', '.showMsgBox', function (e) {
e.preventDefault();
let pid = $(this).data('pid');
$.ajax({
url: '/ajax/account/check_login_status.php',
type:'POST',
success:function(data){
var obj = JSON.parse(data);
if (obj.link) {
login_confirm(obj.link);
return;
}
if (obj['error-popup']) {
var link = '';
if (obj['error']['link'] && obj['error']['link'] != '') {
link = obj['error']['link'];
}
$.fancyAlert({
titlesize : 't4',
title : obj.error.msg.title,
msgsize : 'o-fSubMini',
message : obj.error.msg.desc,
model : true,
link : link,
close : '',
});
return;
}
// 關閉其它編輯框
$(".cancelBtn").trigger("click");
$(".emotion").addClass('hidden');
$(".msg-textarea-input").val("");
$('.MsgBox-' + pid).find('.msg-word-count').html('0/100');
$(".MsgBox-" + pid).toggleClass('hidden');
if (!$(".MsgBox-" + pid).hasClass('hidden')) {
$("#msg_" + pid).trigger('focus');
};
// tag dom
dealTagUserDOM();
}
});
})
// 此寫法使得後來以 AJAX 方式載入的 DOM 也能夠觸發事件
$(document).on('click', '.send_msg', function () {
$('.emotion').addClass('hidden');
$(".MsgBox").addClass('hidden');
let that = $(this);
if (that.attr('disabled') == 'disabled') {
return false;
}
that.attr('disabled', true);
var pid = $(this).data('pid');
var tid = $(this).data('tid');
var page = $(this).data('p');
var msg_pid = '#msg_'+pid;
var msg = stripHtml($(msg_pid).val());
// tag user
const rawTags = $(this).data('tags') || [];
var validTags = [];
var totalTagLength = 0;
rawTags.forEach(function (tag) {
var escapedUname = tag.uname.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
var tagRegex = new RegExp(`@${escapedUname}(?:\\s|$)`);
if (tagRegex.test(msg)) {
validTags.push(tag);
var replaceRegex = new RegExp(`@${escapedUname}(?=\\s|$)`, 'g');
msg = msg.replace(replaceRegex, "@" + tag.uid);
totalTagLength += (tag.uname.length + 1);
}
});
const msg_obj = check_msg(msg, totalTagLength);
if ( ! msg_obj['status']) {
var msg_area = get_msg_area($(this));
msg_area.removeClass('hidden');
msg_area.addClass('is-error');
msg_area.find('.o-formError span').html(msg_obj['err_msg']);
$(msg_pid).focus();
that.removeAttr('disabled');
return false;
}
localStorageEmotion();
const tag_uids = validTags.map(function(t) { return t.uid; });
const tag_unames = validTags.map(function(t) { return t.uname; });
var post_obj = {
'mode' : 'add',
'pid' : pid,
'tid' : tid,
'msg' : msg,
'page' : page,
'tag_uid' : tag_uids,
'tag_uname' : tag_unames
}
$.post('/ajax/forum/message.php', post_obj, function(result) {
that.removeAttr('disabled');
if (result['status'] == 'success') {
if ($(".msg-"+pid).length == 0) {
build_msg_area(msg_pid, pid);
}
$(msg_pid).val('');
var cnt = build_content(pid, tid, result['data'], 1, 0, 1, page);
if ($(".msg-"+pid).html().indexOf('floor-show') == -1) {
cnt = cnt.replace('floor-show', '');
}
cnt = styleSmileFormat(cnt);
$(".msg-"+pid).append(cnt);
} else if (result['status'] == 'fail') {
if (result['link']) {
login_confirm(result['link']);
} else if (result['error-popup']) {
var link = '';
if (result['error']['link'] && result['error']['link'] != '') {
link = result['error']['link'];
}
form_popup(result['error']['msg'], link);
} else if (result['popForceAd']) {
$('.addForceAd').remove();
$('body').append($('
').html(result['popForceAd']));
} else {
$.fancyAlert({
titlesize : 't4',
title : result['error'],
msgsize : 'o-fSubMini',
smallBtn : true,
model : true,
close : ''
});
}
}
}, "json");
})
// 此寫法使得後來以 AJAX 方式載入的 DOM 也能夠觸發事件
$(document).on('click', '.showMsg', function (e) {
e.preventDefault();
//關閉其它編輯框
$(".cancelBtn").trigger("click");
var listtotal = $(this).data('magtotal');
var pid = $(this).data('pid');
var tid = $(this).data('tid');
var page = $(this).data('page');
var Msg = ".msg-" + pid;
$(this).toggleClass('is-open');
if ($(Msg + " > .floor-show").length == 0 && $(Msg + " > .floor-hide").length == 0) {
var post_obj = {
'pid' : pid
}
$.post('/ajax/forum/message_list.php', post_obj, function(result) {
if (result["status"] == "success") {
listtotal = result["data_total"];
msg_item_total = $(Msg).find('.msgItem').length;
var flag = listtotal - msg_item_total;
if (result["data"] != null || listtotal > 0) {
var cnt = "";
$.each(result["data"], function(index, value) {
cnt += build_content(pid, tid, value, index, listtotal, flag, page);
});
cnt = styleSmileFormat(cnt);
$(Msg).html(cnt);
if (listtotal > result["data"].length) {
$(Msg).attr('data-blackmsg-total', (listtotal - result["data"].length));
}
}
}
}, "json");
$(this).find('span').text('收合留言');
$(this).data( "magtotal", listtotal);
} else {
if ($(Msg + ' > .floor-hide').css("display") != "none"){
$(Msg + ' > .floor-hide').hide();
black_total = ($(Msg).data('blackmsg-total')) ? $(Msg).data('blackmsg-total') : 0;
listtotal = (listtotal+black_total);
if (listtotal > 2) {
var total = listtotal - 2;
if (isMobile) {
$(this).find('span').text('更多(' + total + ')');
} else {
$(this).find('span').text('還有 ' + total + ' 則留言');
}
}
} else {
$(Msg + ' > .floor-hide').show();
$(this).find('span').text('收合留言');
}
}
})
//smile
var dark = '';
if ($('link[href^="https:\/\/attach2\.mobile01\.com\/css\/main-set-dark.css"]').length || $('link[href^="https:\/\/attach2\.mobile01\.com\/css\/mobile-main-set-dark.css"]').length) {
dark = 'dark/';
$(".emotionList .l-tab__container img").each(function() {
var that = $(this);
var srccontent = that.attr("src");
if (typeof(srccontent) != 'undefined') {
srccontent.replace(/\/\/attach2\.mobile01\.com\/images\/emotions\/(?!.*dark\/)(.*?).gif/ig, function(matched, p1) {
that.attr("src", '//attach2.mobile01.com/images/emotions/dark/'+p1+'.gif');
});
}
});
}
$('.msgContent').each(function () {
var html = $(this).html();
var newhtml = styleSmileFormat(html);
$(this).html(newhtml);
});
function styleSmileFormat(propertyName) {
function replaceSmile(match, offset) {
var index = offset.replace(/(\.|\+|\$|\^)/g, "\\$1");
var img = '
'
return img;
}
return propertyName.replace(smileRegExp, replaceSmile);
}
$(document).on("click", '.emotionBtn', function(e) {
e.preventDefault();
var html = $('.emotionList').html();
if (isMobile) {
$(this).closest('.l-replyItem__main').find('.emotion').html(html).toggleClass('hidden');
new Swiper('[data-tab-slider="fixWidth"]', {
slideClass: 'c-tabNav__item',
wrapperClass: 'c-tabNav__wrap',
slidesPerView: $('[data-tab-slider="fixWidth"] .c-tabNav__item').length >= 4 ? 4 : $('[data-tab-slider="fixWidth"] .c-tabNav__item').length,
watchOverflow: true,
spaceBetween: 0,
navigation: {
nextEl: '.o-tabSwiperNav--next',
prevEl: '.o-tabSwiperNav--prev',
disabledClass: 'is-disabled'
},
breakpointsInverse: true,
breakpoints: {
1024: {
slidesPerView: $('[data-tab-slider="fixWidth"] .c-tabNav__item').length >= 4 ? 4 : $('[data-tab-slider="fixWidth"] .c-tabNav__item').length
}
}
});
} else {
$(this).closest('.l-leaveMsg__msg').find('.emotion').html(html).toggleClass('hidden');
}
});
$(document).on('click', '.emotion > .l-tab__container > a, .emotion > a', function(e) {
if (isMobile) {
var input_area = $(this).closest('.l-replyItem__main').find('.msg-textarea-input');
} else {
var input_area = $(this).closest('.l-leaveMsg__msg').find('.msg-textarea-input');
}
var add_text = '[' + $(this).find('img').attr('title') + ']';
input_area.insertAtCaret(add_text);
});
$.fn.extend({
insertAtCaret: function(myValue) {
return this.each(function() {
if (document.selection) { //For browsers like Internet Explorer
this.focus();
var sel = document.selection.createRange();
sel.text = myValue;
this.focus();
} else if (this.selectionStart || this.selectionStart == '0') { //For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos) +
myValue + this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
});
}
});
$(document).on("click touchstart", '.msgreport', function(e) {
e.preventDefault();
let post_data = {
'mid' : $(this).data('mid'),
'pid' : $(this).data('pid'),
'page' : $(this).data('page'),
};
$.ajax({
url:'ajax/forum/message_report_content.php',
method:'GET',
data: post_data,
dataType: 'json',
success:(result) => {
if (result['status'] == 'success') {
if (result['msg']['title'] != '') {
form_popup(result['msg']);
} else {
$.fancybox.open({
type : 'inline',
src : result.content,
})
if (!isMobile) {
build_fance_select("#msg_violation_type");
}
}
} else {
if (result['link'].length > 0 && result['link'] != '') {
location.href = result['link'];
}
let link = '';
if (result['error']['link'] && result['error']['link'] != '') {
link = result['error']['link'];
}
form_popup(result['error']['msg'], link);
}
}
});
});
$(document).on("click", '#popup_msend', function() {
var post_obj = {
'pid': $("#popup_pid").val(),
'mid' : $("#popup_mid").val(),
'page' : $("#popup_page").val(),
'report_type' : $("#msg_violation_type").val()
};
form_post($(this), "ajax/forum/message_report.php", post_obj);
});
// 留言連結
$(document).on("click touchstart", '.msgshare', function(e) {
e.preventDefault();
var mid = $(this).data('mid');
share_url(mid);
});
//編輯
$(document).on("click touchstart", '.msgedit', function(e) {
e.preventDefault();
//關閉其它編輯框
$(".cancelBtn").trigger("click");
$(".MsgBox").addClass('hidden');
dealTagUserDOM();
var pid = $(this).data('pid');
var tid = $(this).data('tid');
var mid = $(this).data('mid');
var page = $(this).data('page');
var thisDom = $(this).closest('.msgItem')
//處理 smile
var msg_temp = thisDom.find('.msgContent').html().trim();
var re_smile = /
/g;
var msg = msg_temp.replace(re_smile, '[$1]');
//處理 tag user
const re_tagUser = /]*>([^<]*)<\/a>/gi;
var storageMsg = stripHtml(msg.replace(re_tagUser, '[@$1]-[@$2]'));
var tagsArray = [];
var match;
while ((match = re_tagUser.exec(msg)) !== null) {
tagsArray.push({ uid: match[1], uname: match[2] });
}
if (tagsArray.length > 0) {
tagUserList = true;
}
msg = stripHtml(msg.replace(re_tagUser, '@$2'));
const msgLength = msg.length;
//暫存 localStorage
window.localStorage.setItem('usermsg', storageMsg);
if (isMobile) {
var EditHtml = ''+
''+
'
'+
'
'+
'' +
'';
thisDom.find('.msgContent').html(EditHtml);
} else {
$('.messageList .msgContent').css({"max-height":"none"});
var EditHtml = '';
thisDom.find('.msgContent').html(EditHtml).after('
');
}
thisDom.find('.send_edit_msg').data('tags', tagsArray);
thisDom.find('.msgTool').hide();
});
$(document).on("click touchstart", '.send_edit_msg', function(e) {
e.preventDefault();
$('.emotion').addClass('hidden');
var page = $(this).data('page');
var pid = $(this).data('pid');
var tid = $(this).data('tid');
var mid = $(this).data('mid');
var msg_mid = '#msgEdit_'+mid;
var msg = stripHtml($(msg_mid).val());
// tag user
const rawTags = $(this).data('tags') || [];
var validTags = [];
var totalTagLength = 0;
rawTags.forEach(function (tag) {
var escapedUname = tag.uname.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
var tagRegex = new RegExp(`@${escapedUname}(?:\\s|$)`);
if (tagRegex.test(msg)) {
validTags.push(tag);
var replaceRegex = new RegExp(`@${escapedUname}(?=\\s|$)`, 'g');
msg = msg.replace(replaceRegex, "@" + tag.uid);
totalTagLength += (tag.uname.length + 1);
}
});
$('.msgItem').removeClass('is-error');
var msg_area = $(this).closest('.msgItem');
const msg_obj = check_msg(msg, totalTagLength);
if ( ! msg_obj['status']) {
msg_area.addClass('is-error');
msg_area.find('.o-formError span').html(msg_obj['err_msg']);
$(msg_mid).focus();
return false;
}
localStorageEmotion();
const tag_uids = validTags.map(function(t) { return t.uid; });
const tag_unames = validTags.map(function(t) { return t.uname; });
var post_obj = {
'mode' : 'edit',
'page' : page,
'tid' : tid,
'pid' : pid,
'mid' : mid,
'msg' : msg,
'tag_uid' : tag_uids,
'tag_uname' : tag_unames
}
$.post('/ajax/forum/message.php', post_obj, function(result) {
if (result['status'] == 'success') {
var msg = styleSmileFormat(result['data']['msg']);
//留言 DOM 處理
editDom(msg_area, msg);
} else if (result['status'] == 'fail') {
if (result['link']) {
login_confirm(result['link']);
} else {
$.fancyAlert({
popUpsize : 'c-popUp--sm',
icon : 'c-icon--lightboxMsg c-icon--clapGn',
titlesize : 't4',
title : result['error'],
msgsize : 'o-fSubMini',
message : '',
smallBtn : true,
model : true,
close : ''
});
}
}
}, "json");
})
//取消編輯
$(document).on("click touchstart", '.cancelBtn', function(e) {
e.preventDefault();
$(".c-list-group").removeClass('is-active');
//取出 msg 資料
var msg = stripHtml(window.localStorage.getItem('usermsg'));
//移除 localStorage
window.localStorage.removeItem('usermsg');
var thisDom = $(this).closest('.msgItem');
//留言 DOM 處理
//處理 tag user
var tagUser = /\[@([0-9]*)\]-\[@([^\]]*)\]/g;
msg = msg.replace(tagUser, '$2');
msg = styleSmileFormat(msg);
editDom(thisDom, msg);
});
});
//處理 tag user dom
function dealTagUserDOM() {
tagUserList = false;
$(".c-list-group").removeClass('is-active');
$('.send_msg, .send_edit_msg').removeData('tags');
}
//編輯和取消留言 DOM 處理
function editDom(thisDom, msg) {
thisDom.find('.msgContent').html(msg);
thisDom.find('.o-formError').remove();
thisDom.find('.emotion').remove();
thisDom.removeClass('is-error');
//tool
thisDom.find('.msgTool').show();
if (!isMobile) {
//恢復原本css
$('.messageList .msgContent').css({"max-height":"4.2em"});
}
}
function get_msg_area(that) {
$('.MsgBox').removeClass('is-error');
return that.closest('.MsgBox');
}
function date (time) {
var date_time = new Date();
time = time*1000;
date_time.setTime(time);
var year = date_time.getFullYear();
var month = ('0'+ (date_time.getMonth() + 1)).substr(-2);
var date = ('0'+ date_time.getDate()).substr(-2);
var hour = ('0'+ date_time.getHours()).substr(-2);
var minute = ('0'+ date_time.getMinutes()).substr(-2);
return year + "-" + month + "-" + date+" "+hour+":"+minute;
};
function check_msg(msg, tag_uname_length) {
if ($.trim(msg) == '') {
return {'status': false, 'err_msg': '請輸入留言'};
}
// var chk_wording = check_wording(msg);
// if (chk_wording != '') {
// return {'status': false, 'err_msg': '禁用注音符號:' + chk_wording};
// }
let maxChars = getMsgLengthLimit(msg);
var msgLength = msg.length;
if (tag_uname_length > 0) {
msgLength = msgLength - tag_uname_length;
}
if (msgLength > maxChars) {
return {'status': false, 'err_msg': '留言不得超過' + maxChars +'個字'};
}
return {'status': true, 'content': msg};
}
function check_wording(text) {
var regex = /[\u3105-\u3129\u02CA\u02C7\u02CB\u02D9]/;
var match = regex.exec(text);
if (match != null) {
return match[0];
}
return '';
}
function stripHtml(html) {
let doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || "";
}
//自動縮放
function msgBoxHeight(msg, mode) {
var msgboxH = 44;
if (msg.scrollHeight >= msgboxH) {
$(msg).css({"height": msg.scrollHeight + 'px'});
}
if (!isMobile) {
var thisDom = $(msg).closest('.l-leaveMsg__msg');
if (msg.scrollHeight < msgboxH) {
thisDom.find('.msg-word-count').css({"top" : "25%"});
thisDom.find('.emotionBtn').css({"top" : "25%"});
}
var adjustedHeight = msg.clientHeight;
adjustedHeight = Math.max(msg.scrollHeight,adjustedHeight);
if (adjustedHeight > msg.clientHeight){
thisDom.find('.l-searchBar__item').css({"vertical-align" : "top"});
thisDom.find('.msg-word-count').css({"top" : "8px"});
thisDom.find('.emotionBtn').css({"top" : "8px"});
if (mode == 'edit') {
thisDom.find('.msg-textarea-input').css({"padding-right" : "110px"});
thisDom.find('.cancelBtn').css({"top" : "8px"});
}
}
}
}
//顯示我要留言框字數
function checkLength(msg) {
//自動縮放
msgBoxHeight(msg);
let maxChars = getMsgLengthLimit(msg.value);
var msg_area = get_msg_area($(msg));
var wordLength = msg.value.length;
if (isMobile) {
$(msg).closest('.l-replyItem__main').find('.msg-word-count').html(wordLength + '/' + maxChars);
} else {
$(msg).closest('.msg-textarea-area').find('.msg-word-count').html(wordLength + '/' + maxChars);
}
if (msg.value.length > maxChars) {
msg_area.addClass('is-error');
msg_area.find('.o-formError span').html('留言不得超過' + maxChars + '個字');
} else {
msg_area.removeClass('is-error');
}
return true;
}
//顯示編輯框字數
function checkEditLength(msg) {
//自動縮放
msgBoxHeight(msg, 'edit');
let maxChars = getMsgLengthLimit(msg.value);
$('.msgItem').removeClass('is-error');
var msg_area = $(msg).closest('.msgItem');
var wordLength = msg.value.length;
$(msg).closest('.msgContent').find('.msg-word-count').html(wordLength + '/' + maxChars);
if (msg.value.length > maxChars) {
msg_area.addClass('is-error');
msg_area.find('.o-formError span').html('留言不得超過' + maxChars + '個字');
} else {
msg_area.removeClass('is-error');
}
return true;
}
// 取得留言長度限制
function getMsgLengthLimit(msgValue)
{
// 移除表情符號字串
let maxChars = 100;
let chkMsg = msgValue;
chkMsg = chkMsg.replace(smileRegExp, '');
if ( ! chkMsg.match(/\p{sc=Han}/gu)) {
// 英文留言限制
maxChars = 500;
}
return maxChars;
}