blob: 06fbd32008c28934f3abde643fbdb7c9ea76109f [file] [log] [blame]
lh9ed821d2023-04-07 01:36:19 -07001define("sim_abnormal","jquery knockout service set main opmode".split(" "),
2 function ($, ko, service, config, home, opmode) {
3
4 function init() {
5 var container = $('#container')[0];
6 ko.cleanNode(container);
7 var vm = new simViewMode();
8 ko.applyBindings(vm, container);
9
10 $('#frmPUK').validate({
11 submitHandler: function () {
12 vm.enterPUK();
13 },
14 rules: {
15 txtNewPIN: "pin_check",
16 txtConfirmPIN: {
17 equalToPin: "#txtNewPIN"
18 },
19 txtPUK: "puk_check"
20 }
21 });
22
23 $('#frmPIN').validate({
24 submitHandler: function () {
25 vm.enterPIN();
26 },
27 rules: {
28 txtPIN: "pin_check"
29 }
30 });
31 }
32
33 function simViewMode() {
34 var target = this;
35 var staInfo = service.getStatusInfo();
36 var curCableMode = "PPPOE" == staInfo.blc_wan_mode || "AUTO_PPPOE" == staInfo.blc_wan_mode;
37 target.hasRj45 = config.RJ45_SUPPORT;
38 target.hasSms = config.HAS_SMS;
39 target.hasPhonebook = config.HAS_PHONEBOOK;
40 target.isSupportSD = config.SD_CARD_SUPPORT;
41 if (config.WIFI_SUPPORT_QR_SWITCH) {
42 var wifiInfo = service.getWifiBasic();
43 target.showQRCode = config.WIFI_SUPPORT_QR_CODE && wifiInfo.show_qrcode_flag;
44 } else {
45 target.showQRCode = config.WIFI_SUPPORT_QR_CODE;
46 }
47 target.qrcodeSrc = './pic/qrcode_ssid_wifikey.png?_=' + $.now();
48 target.hasParentalControl = ko.observable(config.HAS_PARENTAL_CONTROL && curCableMode);
49 target.pageState = {
50 NO_SIM: 0,
51 WAIT_PIN: 1,
52 WAIT_PUK: 2,
53 PUK_LOCKED: 3,
54 LOADING: 4
55 };
56 target.isHomePage = ko.observable(false);
57 if (window.location.hash == "#main") {
58 target.isHomePage(true);
59 }
60
61 var info = service.getLoginData();
62 target.PIN = ko.observable();
63 target.newPIN = ko.observable();
64 target.confirmPIN = ko.observable();
65 target.PUK = ko.observable();
66 target.pinNumber = ko.observable(info.pinnumber);
67 target.pukNumber = ko.observable(info.puknumber);
68
69 var state = computePageState(info);
70 target.page = ko.observable(state);
71 if (state == target.pageState.LOADING) {
72 addTimeout(refreshPage, 500);
73 }
74 target.showOpModeWindow = function () {
75 showSettingWindow("change_mode", "opmode_popup", "opmode_popup", 400, 300, function () {});
76 };
77 target.isLoggedIn = ko.observable(false);
78 target.enableFlag = ko.observable(false);
79 //更新当前工作模式状态信息
80 target.refreshOpmodeInfo = function () {
81 var staInfo = service.getStatusInfo();
82 target.isLoggedIn(staInfo.isLoggedIn);
83
84 if (!curCableMode && checkCableMode(staInfo.blc_wan_mode)) { //如果有线,则重新加载
85 if (target.page() == target.pageState.NO_SIM || target.page() == target.pageState.WAIT_PIN || target.page() == target.pageState.WAIT_PUK || target.page() == target.pageState.PUK_LOCKED) {
86 window.location.reload();
87 }
88 }
89
90 curCableMode = checkCableMode(staInfo.blc_wan_mode);
91 target.hasParentalControl(config.HAS_PARENTAL_CONTROL && curCableMode);
92 if (curCableMode && staInfo.ethWanMode.toUpperCase() == "DHCP") {
93 target.enableFlag(true);
94 } else if ((!curCableMode && staInfo.connectStatus != "ppp_disconnected") || (curCableMode && staInfo.rj45ConnectStatus != "idle" && staInfo.rj45ConnectStatus != "dead")) {
95 target.enableFlag(false);
96 } else {
97 target.enableFlag(true);
98 }
99 var mode = (staInfo.blc_wan_mode == "AUTO_PPP" || staInfo.blc_wan_mode == "AUTO_PPPOE") ? "AUTO" : staInfo.blc_wan_mode;
100 var currentOpMode = "";
101 switch (mode) {
102 case "PPP":
103 currentOpMode = "opmode_gateway";
104 break;
105 case "PPPOE":
106 currentOpMode = "opmode_cable";
107 break;
108 case "AUTO":
109 currentOpMode = "opmode_auto";
110 break;
111 default:
112 break;
113 }
114 $("#opmode").attr("data-trans", currentOpMode).text($.i18n.prop(currentOpMode));
115 }
116 //刷新页面状态
117 function refreshPage() {
118 var data = service.getLoginData();
119 var state = computePageState(data);
120 if (state == target.pageState.LOADING) {
121 addTimeout(refreshPage, 500);
122 } else {
123 target.page(state);
124 target.pinNumber(data.pinnumber);
125 target.pukNumber(data.puknumber);
126 }
127 }
128 //输入PUK设置新PIN事件处理
129 target.enterPUK = function () {
130 showLoading();
131 target.page(target.pageState.LOADING);
132 var newPIN = target.newPIN();
133 var confirmPIN = target.confirmPIN();
134 var params = {};
135 params.PinNumber = newPIN;
136 params.PUKNumber = target.PUK();
137 service.enterPUK(params, function (data) {
138 if (!data.result) {
139 hideLoading();
140 if (target.pukNumber() == 2) {
141 showAlert("last_enter_puk", function () {
142 refreshPage();
143 });
144 } else {
145 showAlert("puk_error", function () {
146 refreshPage();
147 if (target.page() == target.pageState.PUK_LOCKED) {
148 hideLoading();
149 }
150 });
151 }
152 target.PUK('');
153 target.newPIN('');
154 target.confirmPIN('');
155 } else {
156 refreshPage();
157 if (target.page() == target.pageState.PUK_LOCKED) {
158 hideLoading();
159 }
160 }
161 });
162 };
163 //验证输入PIN事件处理
164 target.enterPIN = function () {
165 showLoading();
166 target.page(target.pageState.LOADING);
167 var pin = target.PIN();
168 service.enterPIN({
169 PinNumber: pin
170 }, function (data) {
171 if (!data.result) {
172 hideLoading();
173 if (target.pinNumber() == 2) {
174 showAlert("last_enter_pin", function () {
175 refreshPage();
176 });
177 } else {
178 showAlert("pin_error", function () {
179 refreshPage();
180 });
181 }
182 target.PIN('');
183 }
184 refreshPage();
185 if (target.page() == target.pageState.WAIT_PUK) {
186 hideLoading();
187 }
188 });
189 };
190
191 if (target.hasRj45) {
192 target.refreshOpmodeInfo();
193 addInterval(function () {
194 target.refreshOpmodeInfo();
195 }, 1000);
196 }
197 //根据登录状态和SIM卡状态设置页面状态
198 function computePageState(data) {
199 var state = data.modem_main_state;
200 if (state == "modem_undetected" || state == "modem_sim_undetected" || state == "modem_sim_destroy") {
201 return target.pageState.NO_SIM;
202 } else if (state == "modem_waitpin") {
203 return target.pageState.WAIT_PIN;
204 } else if ((state == "modem_waitpuk" || data.pinnumber == 0) && (data.puknumber != 0)) {
205 return target.pageState.WAIT_PUK;
206 } else if ((data.puknumber == 0 || state == "modem_sim_destroy") && state != "modem_sim_undetected" && state != "modem_undetected") {
207 return target.pageState.PUK_LOCKED;
208 } else if ($.inArray(state, config.TEMPORARY_MODEM_MAIN_STATE) != -1) {
209 return target.pageState.LOADING;
210 } else {
211 location.reload();
212 }
213 }
214
215 }
216
217 return {
218 init: init
219 };
220});
221
222define("ota_update", "jquery jq_fileinput service knockout set statusBar".split(" "),
223
224 function ($, fileinput, service, ko, config, status) {
225
226 function FotaUpdateViewModel() {
227 var target = this;
228 var setting = service.getOTAUpdateSetting();
229
230 target.allowRoamingUpdate = ko.observable(setting.allowRoamingUpdate);
231 target.hasDdns = config.DDNS_SUPPORT;
232 target.hasUpdateCheck = config.HAS_UPDATE_CHECK;
233 target.hasUssd = config.HAS_USSD;
234 target.isDataCard = config.PRODUCT_TYPE == 'DATACARD';
235 target.lastCheckTime = ko.observable('');
236 target.updateIntervalDay = ko.observable(setting.updateIntervalDay);
237 target.updateMode = ko.observable(setting.updateMode);
238 target.updateType = ko.observable(service.getUpdateType().update_type);
239
240
241 // 自动检测设置按钮事件
242 target.apply = function () {
243 var updateSettingInfo = {
244 updateMode: target.updateMode(),
245 updateIntervalDay: target.updateIntervalDay(),
246 allowRoamingUpdate: target.allowRoamingUpdate()
247 };
248 showLoading();
249 service.setOTAUpdateSetting(updateSettingInfo, function (settingInfo) {
250 if (settingInfo && settingInfo.result == "success") {
251 setting.allowRoamingUpdate = target.allowRoamingUpdate();
252 successOverlay();
253 } else {
254 errorOverlay();
255 }
256 });
257 };
258
259
260 // 按钮【检测】点击事件处理接口
261 target.checkNewVersion = function () {
262 var newVersionState = service.getNewVersionState();
263 if(newVersionState.fota_package_already_download == "yes"){
264 showAlert("fota_package_already_download");
265 return;
266 }
267
268 if(config.UPGRADE_TYPE=="FOTA"){
269 var checkingState = ["checking"];
270 if ($.inArray(newVersionState.fota_current_upgrade_state, checkingState) != -1) {
271 showAlert("ota_update_running");
272 return;
273 }
274 }
275
276 // FOTA开始下载前,判断当前是否已经在下载过程中,防止错误清空fota_new_version_state状态
277 var statusInfo = service.getStatusInfo();
278 if (newVersionState.fota_current_upgrade_state == "prepare_install") {
279 showInfo('ota_download_success');
280 return;
281 }
282
283 var upgradingState = ["downloading", "confirm_dowmload"];
284 if ($.inArray(newVersionState.fota_current_upgrade_state, upgradingState) != -1) {
285 status.showOTAAlert();
286 return;
287 }
288
289 if (statusInfo.roamingStatus) {
290 showConfirm("ota_check_roaming_confirm", function () {
291 checkNewVersion();
292 });
293 } else {
294 checkNewVersion();
295 }
296 // 检测是否有新版本
297 function checkNewVersion() {
298 showLoading("ota_new_version_checking");
299 function checkNewVersionResult() {
300 var result = service.getNewVersionState();
301 if (result.hasNewVersion) {
302 if(result.fota_new_version_state == "already_has_pkg"&&result.fota_current_upgrade_state !="prepare_install"&&result.fota_current_upgrade_state !="low_battery")
303 {
304 addTimeout(checkNewVersionResult, 1000);
305 }
306 else
307 {
308 status.showOTAAlert();
309 }
310 } else if (result.fota_new_version_state == "no_new_version") {
311 showAlert("ota_no_new_version");
312 }else if (result.fota_new_version_state == "check_failed" ) {
313 errorOverlay("ota_check_fail");
314 } else if ( result.fota_new_version_state == "bad_network"){
315 errorOverlay("ota_connect_server_failed");
316 }else {
317 addTimeout(checkNewVersionResult, 1000);
318 }
319 }
320
321 service.setUpgradeSelectOp({selectOp: 'check'}, function (result) {
322 if (result.result == "success") {
323 checkNewVersionResult();
324 } else {
325 errorOverlay();
326 }
327 });
328 }
329 };
330
331
332
333 // 确认按钮状态:可用/灰化
334 target.fixPageEnable = function () {
335 var connectStatusInfo = service.getStatusInfo();
336 var opModeData = service.getOpMode();
337 if (checkConnectedStatus(connectStatusInfo.connectStatus, opModeData.rj45_state, connectStatusInfo.connectWifiStatus)) {
338 enableBtn($("#btnCheckNewVersion"));
339 } else {
340 disableBtn($("#btnCheckNewVersion"));
341 }
342 };
343
344 target.clickAllowRoamingUpdate = function () {
345 var checkedbox = $("#chkUpdateRoamPermission:checked");
346 if (checkedbox && checkedbox.length == 0) {
347 target.allowRoamingUpdate("1");
348 } else {
349 target.allowRoamingUpdate("0");
350 }
351 };
352
353 service.getOTAlastCheckTime({}, function(info){
354 target.lastCheckTime(info.dm_last_check_time);
355 });
356
357 }
358 // 获取升级文件大小
359 function getFileSize(object){
360 var fileLenth = 0;
361 var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
362 if (isIE) { //如果是ie
363 var objectValue = object.value;
364 try {
365 var fso = new ActiveXObject("Scripting.FileSystemObject");
366 fileLenth = parseInt(fso.GetFile(objectValue).size);
367 } catch (e) {
368 fileLenth = 1;
369 }
370 }else{ //对于非IE获得要上传文件的大小
371 try{
372 fileLenth = parseInt(object.files[0].size);
373 }catch (e) {
374 fileLenth = 1; //获取不到取-1
375 }
376 }
377 return fileLenth/1024/1024;
378 }
379
380 function init() {
381 var container = $('#container')[0];
382 ko.cleanNode(container);
383 var fwVm = new FotaUpdateViewModel();
384 ko.applyBindings(fwVm, container);
385
386 if(fwVm.updateType() == "mifi_fota"){
387 fwVm.fixPageEnable();
388 addInterval(function () {
389 fwVm.fixPageEnable();
390 }, 1000);
391 }else{
392 if ($(".customfile").length == 0) {
393 $("#fileField").customFileInput();
394 }
395 }
396
397 $('#frmOTAUpdate').validate({
398 submitHandler: function () {
399 fwVm.apply();
400 }
401 });
402 }
403
404 return {
405 init: init
406 };
407});
408
409// SD卡 模块
410
411define("sd", "jquery set service knockout".split(" ") , function($, config, service, ko) {
412
413 // 基目录。感觉此根目录不显示给用户会更友好
414 var basePath = config.SD_BASE_PATH;
415
416 function SDCardViewModel() {
417 var target = this;
418 var SDConfiguration = service.getSDConfiguration();
419
420 target.selectedMode = ko.observable(SDConfiguration.sd_mode);
421 target.orignalMode = ko.observable(SDConfiguration.sd_mode);
422 target.sdStatus = ko.observable(SDConfiguration.sd_status);
423 target.orignalSdStatus = ko.observable(SDConfiguration.sd_status);
424 target.sdStatusInfo = ko.observable("sd_card_status_info_" + SDConfiguration.sd_status);
425 target.selectedShareEnable = ko.observable(SDConfiguration.share_status);
426 target.selectedFileToShare = ko.observable(SDConfiguration.file_to_share);
427 target.selectedAccessType = ko.observable(SDConfiguration.share_auth);
428
429 var path = SDConfiguration.share_file.substring(basePath.length);
430
431 target.pathToShare = ko.observable(path);
432 target.isInvalidPath = ko.observable(false);
433 target.checkEnable = ko.observable(true);
434
435
436 addInterval(function(){
437 target.refreshSimStatus();
438 }, 3000);
439
440 // 检查共享路径是否有效
441 target.checkPathIsValid = ko.computed(function () {
442 if (target.orignalMode() == 0 && target.selectedShareEnable() == '1' && target.selectedFileToShare() == '0'
443 && target.pathToShare() != '' && target.pathToShare() != '/') {
444 service.checkFileExists({
445 "path": basePath + target.pathToShare()
446 }, function (info) {
447 if (info.status != "exist") {
448 target.isInvalidPath(true);
449 } else {
450 target.isInvalidPath(false);
451 }
452 });
453 } else {
454 target.isInvalidPath(false);
455 }
456 });
457
458
459 target.disableApplyBtn = ko.computed(function(){
460 return target.selectedMode() == target.orignalMode() && target.selectedMode() == '1';
461 });
462
463 // 文件共享方式radio点击事件
464 target.fileToShareClickHandle = function(){
465 if(target.selectedFileToShare() == "1"){
466 target.pathToShare("/");
467 }
468 return true;
469 };
470
471 // T卡热插拔时状态监控,拔插卡重刷界面
472 target.refreshSimStatus = function(){
473 if(target.checkEnable()){
474 var SDConfiguration = service.getSDConfiguration();
475 if(SDConfiguration.sd_status && (SDConfiguration.sd_status != target.orignalSdStatus())){
476 if(SDConfiguration.sd_status != '1'){
477 target.sdStatusInfo("sd_card_status_info_" + SDConfiguration.sd_status);
478 target.sdStatus(SDConfiguration.sd_status);
479 target.orignalSdStatus(SDConfiguration.sd_status);
480 $("#sd_card_status_info").translate();
481 }else{
482 clearTimer();
483 clearValidateMsg();
484 init();
485 }
486 }
487 }
488 }
489
490
491
492
493
494 // 表单submit事件处理
495 target.save = function(){
496 showLoading('waiting');
497 target.checkEnable(false);
498 if(target.orignalMode() == target.selectedMode()){
499 showAlert("setting_no_change");
500 } else {
501 service.setSdCardMode({
502 mode : target.selectedMode()
503 }, function(info) {
504 if(info.result){
505 target.orignalMode(target.selectedMode());
506 if(info.result == "processing"){
507 errorOverlay("sd_usb_forbidden");
508 }else{
509 successOverlay();
510 }
511 } else {
512 if (target.selectedMode() == "0") {
513 errorOverlay("sd_not_support");
514 } else {
515 errorOverlay();
516 }
517 }
518 }, function(error) {
519 if (target.selectedMode() == "0") {
520 errorOverlay("sd_not_support");
521 } else {
522 errorOverlay();
523 }
524 });
525 }
526 target.checkEnable(true);
527 return true;
528 };
529
530
531
532 // 保存详细配置信息
533 target.saveShareDetailConfig = function() {
534 showLoading('waiting');
535 target.checkEnable(false);
536 var param = {
537 share_status : target.selectedShareEnable(),
538 share_auth : target.selectedAccessType(),
539 share_file : basePath + target.pathToShare()
540 };
541
542 if (target.selectedShareEnable() == "0") {
543 setSdCardSharing(param);
544 } else {
545 service.checkFileExists({
546 "path" : param.share_file
547 }, function(info) {
548 if (info.status != "exist" && info.status != "processing") {
549 errorOverlay("sd_card_share_setting_" + info.status);
550 } else {
551 setSdCardSharing(param);
552 }
553 }, function(){
554 errorOverlay();
555 });
556 }
557
558 target.checkEnable(true);
559 return true;
560 }
561
562 // 设置SD卡共享信息
563 function setSdCardSharing(param){
564 service.setSdCardSharing(param, function(result) {
565 if (isErrorObject(result)) {
566 if (result.errorType == "no_sdcard") {
567 errorOverlay("sd_card_share_setting_no_sdcard");
568 } else {
569 errorOverlay();
570 }
571 } else {
572 successOverlay();
573 }
574 });
575 }
576 }
577
578 // 将配置的option项转换成Option数组
579 // {Array} configItem [{name: "name1", value: "val1"},{name: "name2", value: "val2"}]
580 function getOptionArray(configItem) {
581 var arr = [];
582 for ( var i = 0; i < configItem.length; i++) {
583 arr.push(new Option(configItem.name, configItem.value));
584 }
585 return arr;
586 }
587
588 function init() {
589 var container = $('#container')[0];
590 ko.cleanNode(container);
591 var fwVm = new SDCardViewModel();
592 ko.applyBindings(fwVm, container);
593 $("#sd_card_status_info").translate();
594 $('#sdmode_form').validate({
595 submitHandler : function() {
596 fwVm.save();
597 }
598 });
599 $('#httpshare_form').validate({
600 submitHandler : function() {
601 fwVm.saveShareDetailConfig();
602 },
603 rules : {
604 path_to_share : "check_file_path"
605 }
606 });
607 }
608
609 return {
610 init : init
611 };
612});
613
614// SD卡 HttpShare模块
615
616define("sd_httpshare","jquery underscore jq_fileinput set service knockout".split(" ") ,
617
618 function($, _, fileinput, config, service, ko) {
619
620 // 每页记录条数
621 // 不能够设置每页数据个数,默认:10
622 // 默认值不可修改
623 var perPage = 10;
624
625 // 当前页
626 var activePage = 1;
627
628 // 当前目录,默认根目录""
629 var currentPath = "";
630
631 // 基目录。是否需要显示给用户?用户友好度
632 var basePath = config.SD_BASE_PATH;
633
634 // 前置路径,发现有的设备会将sd卡数据显示在web目录
635 // prePath = "/usr/conf/web";
636 var prePath = "";
637
638 // 是否隐藏重命名按钮
639 var readwrite = true;
640
641 // 文件列表模板
642 var sdFileItemTmpl = null;
643
644 // 分页模板
645 var pagerTmpl = null;
646 // 配置信息原始状态
647 var originalStatus = null;
648
649 var zoneOffsetSeconds = new Date().getTimezoneOffset() * 60;
650
651 var shareFilePath = '';
652
653 var sdIsUploading = false;//SD卡是否正在上传文件
654
655 // 生成分页数据数组
656 // @method generatePager
657 // @param {Integer} totalSize 总记录数
658 // @param {Integer} perPageNum 每页记录条数
659 // @param {Integer} currentPage 当前页
660 // @return {Array} 分页数据数组
661 function generatePager(totalSize, perPageNum, currentPage) {
662 if (totalSize == 0) {
663 return [];
664 }
665 var pagersArr = [];
666 var totalPages = getTotalPages(totalSize, perPageNum);
667 pagersArr.push({
668 pageNum: currentPage - 1,
669 isActive: false,
670 isPrev: true,
671 isNext: false,
672 isDot: false
673 });
674 if (currentPage == 6) {
675 pagersArr.push({
676 pageNum: 1,
677 isActive: false,
678 isPrev: false,
679 isNext: false,
680 isDot: false
681 });
682 } else if (currentPage > 5) {
683 pagersArr.push({
684 pageNum: 1,
685 isActive: false,
686 isPrev: false,
687 isNext: false,
688 isDot: false
689 });
690 pagersArr.push({
691 pageNum: 0,
692 isPrev: false,
693 isNext: false,
694 isActive: false,
695 isDot: true
696 });
697 }
698 var i;
699 var startPage = currentPage - 4 > 0 ? currentPage - 4 : 1;
700 var endPage = currentPage + 4;
701 for (i = startPage; i <= endPage && i <= totalPages; i++) {
702 pagersArr.push({
703 pageNum: i,
704 isActive: i == currentPage,
705 isPrev: false,
706 isNext: false,
707 isDot: false
708 });
709 }
710 if (currentPage + 5 == totalPages) {
711 pagersArr.push({
712 pageNum: totalPages,
713 isPrev: false,
714 isNext: false,
715 isActive: false,
716 isDot: false
717 });
718 } else if (currentPage + 3 <= totalPages && i - 1 != totalPages) {
719 pagersArr.push({
720 pageNum: 0,
721 isPrev: false,
722 isNext: false,
723 isActive: false,
724 isDot: true
725 });
726 pagersArr.push({
727 pageNum: totalPages,
728 isPrev: false,
729 isNext: false,
730 isActive: false,
731 isDot: false
732 });
733 }
734 pagersArr.push({
735 pageNum: parseInt(currentPage, 10) + 1,
736 isPrev: false,
737 isNext: true,
738 isActive: false,
739 isDot: false
740 });
741 return pagersArr;
742 }
743
744 function getTotalPages(total, perPage){
745 var totalPages = Math.floor(total / perPage);
746 if (total % perPage != 0) {
747 totalPages++;
748 }
749 return totalPages;
750 }
751
752 // 整理文件列表数据,并用模板显示
753 function showFileSet(files) {
754 var i = 0;
755 var shownFiles = $.map(files, function(n) {
756 var obj = {
757 fileName : HTMLEncode(n.fileName),
758 fileType : n.attribute == 'document' ? 'folder' : getFileType(n.fileName),
759 fileSize : getDisplayVolume(n.size, false),
760 filePath : basePath + getCurrentPath() + "/" + n.fileName,
761 lastUpdateTime : transUnixTime((parseInt(n.lastUpdateTime, 10) + zoneOffsetSeconds) * 1000),
762 trClass : i % 2 == 0 ? "even" : "",
763 readwrite : readwrite
764 };
765 i++;
766 return obj;
767 });
768
769 if(sdFileItemTmpl == null){
770 sdFileItemTmpl = $.template("sdFileItemTmpl", $("#sdFileItemTmpl"));
771 }
772 $("#fileList_container").html($.tmpl("sdFileItemTmpl", {data: shownFiles}));
773 }
774
775 // HttpShareViewModel
776 function HttpShareViewModel() {
777 var isGuest = false;
778 if(window.location.hash == "#httpshare_guest"){
779 isGuest = true;
780 }
781 readwrite = true;
782 activePage = 1;
783 setCurrentPath('');
784 basePath = config.SD_BASE_PATH;
785 showLoading('waiting');
786 service.getSDConfiguration({}, function(data){
787 originalStatus = data;
788 shareFilePath = data.share_file;
789 if(shareFilePath.charAt(shareFilePath.length - 1) == '/'){//如果路径中有/,则去掉
790 shareFilePath = shareFilePath.substring(0, shareFilePath.length - 1);
791 }
792
793 if(data.sd_status == '1' && data.sd_mode == '0'){ //共享
794 if(isGuest && data.share_status == '1'){// guest and share
795 basePath = shareFilePath;
796 if(data.share_auth == '0'){ // readonly
797 readwrite = false;
798 $("#uploadSection, #delete_file_button, .sd_guest_hide_th", "#httpshare_form").hide();
799 }else{
800 $("#uploadSection, #delete_file_button, .sd_guest_hide_th", "#httpshare_form").show();
801 }
802 $("#go_to_login_button").removeClass("hide");
803 $('#sd_menu').hide();
804 $('.form-note').hide();
805 if ($(".customfile").length == 0) {
806 $("#fileField").customFileInput();
807 }
808 pagerItemClickHandler(1);
809 } else if(isGuest && data.share_status == '0'){ // guest not share
810 $(".form-body .content", "#httpshare_form").hide().remove();
811 $(".form-title", "#httpshare_form").attr("data-trans", "httpshare").html($.i18n.prop("httpshare"));
812 $(".form-note", "#httpshare_form").attr("data-trans", "note_http_share_cannot_access").html($.i18n.prop("note_http_share_cannot_access"));
813 hideLoading();
814 } else {
815 if ($(".customfile").length == 0) {
816 $("#fileField").customFileInput();
817 }
818 pagerItemClickHandler(1);
819 }
820 } else { // usb
821 $(".form-body .content", "#httpshare_form").hide().remove();
822 $(".form-title", "#httpshare_form").attr("data-trans", "httpshare").html($.i18n.prop("httpshare"));
823 $(".form-note", "#httpshare_form").attr("data-trans", "note_http_share_usb_access").html($.i18n.prop("note_http_share_usb_access"));
824 $(".form-note", "#httpshare_form").addClass("margintop10");
825 hideLoading();
826 }
827 }, function(){
828 errorOverlay();
829 $(".form-body .content", "#httpshare_form").hide().remove();
830 $(".form-title", "#httpshare_form").attr("data-trans", "httpshare").html($.i18n.prop("httpshare"));
831 $(".form-note", "#httpshare_form").attr("data-trans", "note_http_share_cannot_access").html($.i18n.prop("note_http_share_cannot_access"));
832 });
833
834 addInterval(function(){
835 !sdIsUploading && self.checkSdStatus();
836 }, 3000);
837
838 // T卡热插拔时状态监控,拔插卡重刷界面
839 self.checkSdStatus = function(){
840 var data = service.getSDConfiguration();
841 if(data.sd_status && (data.sd_status != originalStatus.sd_status)){
842 if(data.sd_status == '1'){
843 window.location.reload();
844 }else{
845 clearTimer();
846 clearValidateMsg();
847 init();
848 }
849 }
850 }
851 }
852
853 // 页码点击事件处理
854 pagerItemClickHandler = function(num) {
855 activePage = num;
856 refreshFileList(getCurrentPath(), activePage);
857 };
858
859 function checkConfiguration(){
860 var data = service.getSDConfiguration();
861 if(!_.isEqual(originalStatus, data)){
862 showAlert('sd_config_changed_reload', function(){
863 init();
864 });
865 return false;
866 }
867 return true;
868 }
869
870 //检查操作路径是否为共享路径,如果是共享路径,给用户提示
871 function inSharePath(path, wording) {
872 var tmpShareFilePath = shareFilePath + '/';
873 var tmpPath = path + '/';
874 if (originalStatus.share_status == '1' && shareFilePath != '' && shareFilePath != '/' && tmpShareFilePath.indexOf(tmpPath) != -1) {
875 showAlert(wording);
876 return true;
877 }
878 return false;
879 }
880
881 // 进入文件夹
882 enterFolder = function(name) {
883 if(!checkConfiguration()){
884 return false;
885 }
886 var path;
887 if (name == "") {
888 path = "";
889 } else {
890 path = getCurrentPath() + '/' + name;
891 }
892 refreshFileList(path, 1);
893 return true;
894 };
895
896 // 回到上一级目录
897 backFolder = function() {
898 if(!checkConfiguration()){
899 return false;
900 }
901 var path = getCurrentPath().substring(0, getCurrentPath().lastIndexOf("/"));
902 refreshFileList(path, 1);
903 return true;
904 };
905
906 // 更新按钮状态
907 refreshBtnsStatus = function() {
908 if (getCurrentPath() == "") {
909 $("#rootBtnLi, #backBtnLi").hide();
910 } else {
911 $("#rootBtnLi, #backBtnLi").show();
912 }
913 if (readwrite) {
914 $("#createNewFolderLi").hide();
915 $("#createNewFolderLi").find(".error").hide();
916 $("#newFolderBtnLi").show();
917 $("#newFolderName").val('');
918 $("#createNewFolderErrorLabel").removeAttr('data-trans').text('');
919 } else {
920 $("#newFolderBtnLi, #createNewFolderLi").hide().remove();
921 }
922 checkDeleteBtnStatus();
923 };
924
925
926 // 刷新文件列表
927 refreshFileList = function(path, index, alertShown) {
928 if(!alertShown){
929 showLoading('waiting');
930 }
931 service.getFileList({
932 path : prePath + basePath + path,
933 index : index
934 }, function(data) {
935 if (isErrorObject(data)) {
936 showAlert(data.errorType);
937 return;
938 }
939 setCurrentPath(path);
940 $("#sd_path").val(path);
941 activePage = index;
942 totalSize = data.totalRecord;
943 showFileSet(data.details);
944 pagination(totalSize); //测试分页时可以将此处totalSize调大
945 refreshBtnsStatus();
946 updateSdMemorySizes();
947 if(!alertShown){
948 hideLoading();
949 }
950 });
951 };
952
953
954 // 显示新建文件夹按钮点击事件
955 openCreateNewFolderClickHandler = function() {
956 $("#newFolderBtnLi").hide();
957 $("#newFolderName").show();
958 $("#createNewFolderLi").show();
959 };
960
961 // 取消显示新建文件夹按钮点击事件
962 cancelCreateNewFolderClickHandler = function() {
963 $("#createNewFolderLi").hide();
964 $("#newFolderName").val('');
965 $("#newFolderBtnLi").show();
966 $("#createNewFolderLi").find(".error").hide();
967 };
968
969 // 新建文件夹按钮点击事件
970 createNewFolderClickHandler = function() {
971 if(!checkConfiguration()){
972 return false;
973 }
974 var newFolderName = $.trim($("#newFolderName").val());
975 var newPath = prePath + basePath + getCurrentPath() + "/" + newFolderName;
976 showLoading('creating');
977 service.checkFileExists({
978 path : newPath
979 }, function(data1) {
980 if (data1.status == "noexist" || data1.status == "processing") {
981 service.createFolder({
982 path : newPath
983 }, function(data) {
984 if (isErrorObject(data)) {
985 showAlert(data.errorType);
986 return false;
987 } else {
988 successOverlay();
989 refreshFileList(getCurrentPath(), 1);
990 }
991 });
992 } else if (data1.status == "no_sdcard") {
993 showAlert("no_sdcard", function(){
994 window.location.reload();
995 });
996 } else if (data1.status == "exist") {
997 $("#createNewFolderErrorLabel").attr('data-trans', 'sd_card_share_setting_exist').text($.i18n.prop("sd_card_share_setting_exist"));
998 hideLoading();
999 }
1000 }, function(){
1001 errorOverlay();
1002 });
1003 return true;
1004 };
1005
1006 // 重命名按钮点击事件
1007 renameBtnClickHandler = function(oldName) {
1008 var oldPath = prePath + basePath + getCurrentPath() + "/" + oldName;
1009 if(inSharePath(oldPath, 'sd_share_path_cant_rename')){
1010 return false;
1011 }
1012 showPrompt("sd_card_folder_name_is_null", function() {
1013 renamePromptCallback(oldName);
1014 }, 160, oldName, checkPromptInput);
1015 };
1016
1017 function renamePromptCallback(oldName){
1018 if(!checkConfiguration()){
1019 return false;
1020 }
1021 var promptInput = $("div#confirm div.promptDiv input#promptInput");
1022 var newFolderName = $.trim(promptInput.val());
1023 var newPath = prePath + basePath + getCurrentPath() + "/" + newFolderName;
1024 service.checkFileExists({
1025 path : newPath
1026 }, function(data1) {
1027 if (data1.status == "noexist" || data1.status == "processing") {
1028 hideLoadingButtons();
1029 var oldPath = prePath + basePath + getCurrentPath() + "/" + oldName;
1030 service.fileRename({
1031 oldPath : oldPath,
1032 newPath : newPath,
1033 path : prePath + basePath + getCurrentPath()
1034 }, function(data) {
1035 if (isErrorObject(data)) {
1036 showAlert($.i18n.prop(data.errorType));
1037 if(data.errorType == "no_exist"){
1038 var alertShown = true;
1039 refreshFileList(getCurrentPath(), 1, alertShown);
1040 } else if(data.errorType == "processing"){
1041 //
1042 }
1043 } else {
1044 refreshFileList(getCurrentPath(), 1);
1045 successOverlay();
1046 }
1047 showLoadingButtons();
1048 return true;
1049 });
1050 } else if (data1.status == "no_sdcard") {
1051 showAlert("no_sdcard", function(){
1052 window.location.reload();
1053 });
1054 return false;
1055 } else if (data1.status == "exist") {
1056 $(".promptErrorLabel").text($.i18n.prop("sd_card_share_setting_exist"));
1057 return false;
1058 }
1059 return true;
1060 }, function(){
1061 errorOverlay();
1062 });
1063 return false;
1064 }
1065
1066 // Prompt弹出框INPUT校验函数
1067 function checkPromptInput(){
1068 var promptInput = $("div#confirm div.promptDiv input#promptInput");
1069 var newFileName = $.trim(promptInput.val());
1070 var newPath = (prePath + basePath + getCurrentPath() + "/" + newFileName).replace("//", "/");
1071 var checkResult = checkFileNameAndPath(newFileName, newPath);
1072 if (1 == checkResult) {
1073 $(".promptErrorLabel").text($.i18n.prop("sd_upload_rename_null"));//tip filena is null
1074 return false;
1075 }else if (2 == checkResult) {
1076 $(".promptErrorLabel").text($.i18n.prop("sd_card_path_too_long"));
1077 return false;
1078 }else if (3 == checkResult) {
1079 $(".promptErrorLabel").text($.i18n.prop("check_file_path"));
1080 return false;
1081 }else{
1082 $(".promptErrorLabel").text("");
1083 return true;
1084 }
1085 return true;;
1086 }
1087
1088 hideLoadingButtons = function () {
1089 $(".buttons", "#confirm").hide();
1090 };
1091
1092 showLoadingButtons = function () {
1093 $(".buttons", "#confirm").show();
1094 };
1095
1096 // 删除按钮点击事件
1097 deleteBtnClickHandler = function() {
1098 if(!checkConfiguration()){
1099 return false;
1100 }
1101 var files = $("input:checkbox:checked", "#fileList_container");
1102 var fileNames = "";
1103 if (!files || files.length == 0) {
1104 return false;
1105 }
1106 var hasSharePath = false;
1107 $.each(files, function (i, n) {
1108 var theFile = $(n).val();
1109 if (inSharePath(prePath + basePath + getCurrentPath() + "/" + theFile, {msg: 'sd_share_path_cant_delete', params: [theFile]})) {
1110 hasSharePath = true;
1111 return false;
1112 }
1113 return true;
1114 });
1115 if (hasSharePath) {
1116 return false;
1117 }
1118 showConfirm("confirm_data_delete", function(){
1119 $.each(files, function(i, n) {
1120 fileNames += $(n).val() + "*";
1121 });
1122 var thePath = prePath + basePath + getCurrentPath();
1123 service.deleteFilesAndFolders({
1124 path : thePath,
1125 names : fileNames
1126 }, function(data) {
1127 if (data.status == "failure") {
1128 showAlert("delete_folder_failure");
1129 }
1130 else if(data.status == "no_sdcard"){
1131 showAlert("no_sdcard");
1132 }
1133 else if(data.status == "processing"){
1134 showAlert("sd_file_processing_cant_delete");
1135 }
1136 else if(data.status == "success"){
1137 successOverlay();
1138 }
1139 refreshFileList(getCurrentPath(), 1);
1140 }, function(){
1141 errorOverlay();
1142 });
1143 });
1144 return true;
1145 };
1146
1147 // 文件上传按钮点击事件
1148 fileUploadSubmitClickHandler = function(ifReName) {
1149 if(ifReName){
1150 var fileName = $.trim($("div#confirm div.promptDiv input#promptInput").val());
1151 }else{
1152 var fileName = $(".customfile").attr('title');
1153 }
1154 var newPath = (basePath + getCurrentPath() + "/" + fileName).replace("//", "/");
1155 var fileSize = getFileSize($("#fileField")[0]);
1156 if(!checkuploadFileNameAndPath(fileName, newPath, fileSize)){
1157 return false;
1158 }
1159 doCheckAndUpload(fileName, newPath, fileSize);
1160 };
1161
1162 function doCheckAndUpload(fileName, newPath, fileSize){
1163 service.getSdMemorySizes({}, function(data) {
1164 if (isErrorObject(data)) {
1165 showAlert(data.errorType);
1166 return false;
1167 }
1168 if (data.availableMemorySize < fileSize) {
1169 showAlert("sd_upload_space_not_enough");
1170 return false;
1171 }
1172 $.modal.close();
1173 showLoading('uploading', '<span data-trans="note_uploading_not_refresh">' + $.i18n.prop('note_uploading_not_refresh') + '</span>');
1174 service.checkFileExists({
1175 path : newPath
1176 }, function(data1) {
1177 if (data1.status == "noexist") {
1178 $("#fileUploadForm").attr("action", "/cgi-bin/httpshare/" + URLEncodeComponent(fileName));
1179 var currentTime = new Date().getTime();
1180 $("#path_SD_CARD_time").val(transUnixTime(currentTime));
1181 $("#path_SD_CARD_time_unix").val(Math.round((currentTime - zoneOffsetSeconds * 1000) / 1e3));
1182 if(!iframeLoadBinded){
1183 bindIframeLoad();
1184 }
1185 sdIsUploading = true;
1186 $("#fileUploadForm").submit();
1187 } else if (data1.status == "no_sdcard") {
1188 showAlert("no_sdcard", function(){
1189 window.location.reload();
1190 });
1191 } else if (data1.status == "processing") {
1192 showAlert("sd_upload_file_is_downloading");//("system is downloading,try later!");
1193 }else if (data1.status == "exist") {
1194 showPrompt("sd_upload_rename",function(){
1195 fileUploadSubmitClickHandler(true);
1196 },160, fileName, checkPromptInput, clearUploadInput);
1197 }
1198 }, function(){
1199 errorOverlay();
1200 });
1201 return true;
1202 });
1203 }
1204
1205 var iframeLoadBinded = false;
1206 function bindIframeLoad(){
1207 iframeLoadBinded = true;
1208 $('#fileUploadIframe').load(function() {
1209 sdIsUploading = false;
1210 var txt = $('#fileUploadIframe').contents().find("body").html().toLowerCase();
1211 var alertShown = false;
1212 if (txt.indexOf('success') != -1) {
1213 successOverlay();
1214 } else if (txt.indexOf('space_not_enough') != -1) {
1215 alertShown = true;
1216 showAlert('sd_upload_space_not_enough');
1217 } else if (txt.indexOf('data_lost') != -1) {
1218 alertShown = true;
1219 showAlert('sd_upload_data_lost');
1220 } else {
1221 errorOverlay();
1222 }
1223
1224 clearUploadInput();
1225 refreshFileList(getCurrentPath(), 1, alertShown);
1226 });
1227 }
1228
1229 // 更新SD卡容量显示数据
1230 updateSdMemorySizes = function() {
1231 service.getSdMemorySizes({}, function(data) {
1232 if (isErrorObject(data)) {
1233 showAlert(data.errorType);
1234 return false;
1235 }
1236 var total = getDisplayVolume(data.totalMemorySize, false);
1237 var used = getDisplayVolume(data.totalMemorySize - data.availableMemorySize, false);
1238 $("#sd_volumn_used").text(used);
1239 $("#sd_volumn_total").text(total);
1240 return true;
1241 });
1242 };
1243
1244 // 翻页
1245 pagination = function(fileTotalSize) {
1246 var pagers = generatePager(fileTotalSize, perPage, parseInt(activePage, 10));
1247 if(pagerTmpl == null){
1248 pagerTmpl = $.template("pagerTmpl", $("#pagerTmpl"));
1249 }
1250 $(".pager", "#fileListButtonSection").html($.tmpl("pagerTmpl", {data: {pagers : pagers, total : getTotalPages(fileTotalSize, perPage)}}));
1251 renderCheckbox();
1252 $(".content", "#httpshare_form").translate();
1253 };
1254
1255 // 下载文件是检查文件路径是否包含特殊字符
1256 checkFilePathForDownload = function(path){
1257 if(!checkConfiguration()){
1258 return false;
1259 }
1260 var idx = path.lastIndexOf('/');
1261 var prePath = path.substring(0, idx+1);
1262 var name = path.substring(idx+1, path.length);
1263 if(checkFileNameChars(prePath, true) && checkFileNameChars(name, false)){
1264 return true;
1265 }
1266 showAlert('sd_card_invalid_chars_cant_download');
1267 return false;
1268 };
1269
1270 gotoLogin = function(){
1271 window.location.href="#entry";
1272 };
1273
1274 // 事件绑定
1275 function bindEvent(){
1276 $('#createNewFolderForm').validate({
1277 submitHandler : function() {
1278 createNewFolderClickHandler();
1279 },
1280 rules : {
1281 newFolderName : {sd_card_path_too_long:true,check_filefold_name: true}
1282 }
1283 });
1284 $("p.checkbox", "#httpshare_form").die().live('click', function () {
1285 addTimeout(function () {
1286 checkDeleteBtnStatus();
1287 }, 100);
1288 });
1289 $(".icon-download", "#httpshare_form").die().live("click", function () {
1290 return checkFilePathForDownload($(this).attr("filelocal"));
1291 });
1292 $(".folderTd", "#httpshare_form").die().live("click", function () {
1293 return enterFolder($(this).attr("filename"));
1294 });
1295 $(".fileRename", "#httpshare_form").die().live("click", function () {
1296 return renameBtnClickHandler($(this).attr("filename"));
1297 });
1298 iframeLoadBinded = false;
1299 }
1300
1301
1302 // 刷新删除按钮状态
1303 function checkDeleteBtnStatus(){
1304 var checkedItem = $("p.checkbox.checkbox_selected", '#fileListSection');
1305 if(checkedItem.length > 0){
1306 enableBtn($('#delete_file_button'));
1307 } else {
1308 disableBtn($('#delete_file_button'));
1309 }
1310 }
1311
1312
1313 // 文件名和路径检查
1314 function checkFileNameAndPath(filename, path) {
1315 if (filename == "" || filename.length > 25) {
1316 return 1;
1317 }
1318 if (path.length >= 200) {
1319 return 2;
1320 }
1321 if (!checkFileNameChars(filename, false)) {
1322 return 3;
1323 }
1324 }
1325
1326 // 文件名特殊字符检查
1327 function checkFileNameChars(filename, isIncludePath) {
1328 var ASCStringInvalid = '+/:*?<>\"\'\\|#&`~';
1329 if(isIncludePath){
1330 ASCStringInvalid = '+:*?<>\"\'\\|#&`~';
1331 }
1332 var flag = false;
1333 var dotFlag = false;
1334 var reg = /^\.+$/;
1335 for ( var filenamelen = 0; filenamelen < filename.length; filenamelen++) {
1336 for ( var ACSlen = 0; ACSlen < ASCStringInvalid.length; ACSlen++) {
1337 if (filename.charAt(filenamelen) == ASCStringInvalid.charAt(ACSlen)) {
1338 flag = true;
1339 break;
1340 }
1341 }
1342 if (reg.test(filename)) {
1343 dotFlag = true;
1344 }
1345 if (flag || dotFlag) {
1346 return false;
1347 }
1348 }
1349 return true;
1350 }
1351
1352
1353 function checkuploadFileNameAndPath(fileName, newPath, fileSize){
1354 if(!checkConfiguration()){
1355 return false;
1356 }
1357
1358 if (typeof fileName == "undefined" || fileName == '' || fileName == $.i18n.prop("no_file_selected")) {
1359 showAlert("sd_no_file_selected");
1360 return false;
1361 }
1362 if (newPath.length >= 200) {
1363 showAlert("sd_card_path_too_long");
1364 return false;
1365 }
1366
1367 if (fileSize/1024/1024/1024 > 2){ //no more than 2G
1368 showAlert("sd_file_size_too_big");
1369 return false;
1370 }
1371
1372 if (fileName.indexOf('*') >= 0){ //no *
1373 showAlert("sd_file_name_invalid");
1374 return false;
1375 }
1376 return true;
1377 }
1378
1379
1380 //清空上传控件
1381 function clearUploadInput(){
1382 $("#fileField").closest('.customfile').before('<input id="fileField" name="filename" maxlength="200" type="file" dir="ltr"/>').remove();
1383 addTimeout(function(){
1384 $("#fileField").customFileInput();
1385 }, 0);
1386 $("#uploadBtn", "#uploadSection").attr("data-trans", "browse_btn").html($.i18n.prop('browse_btn'));
1387 $(".customfile", "#uploadSection").removeAttr("title");
1388 $(".customfile span.customfile-feedback", "#uploadSection")
1389 .html('<span data-trans="no_file_selected">'+$.i18n.prop('no_file_selected')+'</span>')
1390 .attr('class', 'customfile-feedback');
1391 }
1392
1393
1394 function getCurrentPath(){
1395 return currentPath;
1396 }
1397
1398 function setCurrentPath(path){
1399 if(path.lastIndexOf("/") == path.length - 1){
1400 currentPath = path.substring(0, path.length - 1);
1401 } else {
1402 currentPath = path;
1403 }
1404 }
1405
1406
1407 function getFileSize(object){
1408 var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
1409 if (isIE) { //如果是ie
1410 var objValue = object.value;
1411 try {
1412 var fileSysObj = new ActiveXObject("Scripting.FileSystemObject");
1413 fileLenth = parseInt(fileSysObj.GetFile(objValue).size);
1414 } catch (e) { //('IE内核取不到长度');
1415 fileLenth = 1;
1416 }
1417 }else{ //其他
1418 try{//对于非IE获得要上传文件的大小
1419 fileLenth = parseInt(object.files[0].size);
1420 }catch (e) {
1421 fileLenth=1; //获取不到取-1
1422 }
1423 }
1424 return fileLenth;
1425 }
1426
1427 function init() {
1428 var container = $('#container')[0];
1429 ko.cleanNode(container);
1430 var fwVm = new HttpShareViewModel();
1431 ko.applyBindings(fwVm, container);
1432 bindEvent();
1433 }
1434
1435
1436 jQuery.validator.addMethod("check_filefold_name", function(value, element, param) {
1437 var result = checkFileNameChars(value, false);
1438 return this.optional(element) || result;
1439 });
1440
1441 jQuery.validator.addMethod("sd_card_path_too_long", function(value, element, param) {
1442 var newFolderName = $.trim($("#newFolderName").val());
1443 var newPath = prePath + basePath + getCurrentPath() + "/" + newFolderName;
1444 var result = true;
1445 if (newPath.length >= 200) {
1446 result = false;
1447 }
1448 return this.optional(element) || result;
1449 });
1450
1451 return {
1452 init : init
1453 };
1454});
1455
1456define("ussd","set service knockout jquery".split(" "), function (set, fnc, libko, libjq) {
1457 var time_interval = 0;
1458 var initFlg = true;
1459 var numTimeout = 0;
1460 var replyFlg = false;
1461 var ussd_action = 1;
1462
1463 function init() {
1464 var container = libjq('#container')[0];
1465 libko.cleanNode(container);
1466 var vm = new vmUSSD();
1467 libko.applyBindings(vm, container);
1468
1469 }
1470 var USSDLocation = {
1471 SEND: 0,
1472 REPLY: 1
1473 };
1474 function vmUSSD() {
1475 var target = this;
1476
1477 target.hasUpdateCheck = set.HAS_UPDATE_CHECK;
1478 target.ussd_action = libko.observable(ussd_action);
1479 target.USSDLocation = libko.observable(USSDLocation.SEND);
1480 target.USSDReply = libko.observable("");
1481 target.USSDSend = libko.observable("");
1482 target.hasDdns = set.DDNS_SUPPORT;
1483
1484 function checkTimeout() {
1485 if (replyFlg) {
1486 replyFlg = true;
1487 window.clearInterval(time_interval);
1488 numTimeout = 0;
1489 } else {
1490 if (numTimeout > 28) {
1491 replyFlg = true;
1492 window.clearInterval(time_interval);
1493 showAlert("ussd_operation_timeout");
1494 target.USSDReply("");
1495 target.USSDSend("");
1496 target.USSDLocation(USSDLocation.SEND);
1497 numTimeout = 0;
1498
1499 } else {
1500 numTimeout++;
1501 }
1502
1503 }
1504 };
1505
1506 target.sendToNet = function () {
1507 numTimeout = 0;
1508 window.clearInterval(time_interval);
1509 var command = target.USSDSend();
1510
1511 var idx_t = 0;
1512 var indexChar;
1513 for (idx_t = 0; idx_t < command.length; ) { //corem0418, delte left blanks and right blanks
1514 indexChar = command.charAt(idx_t);
1515 if (indexChar == ' ') {
1516 if (command.length > 1) {
1517 command = command.substr(idx_t + 1);
1518 } else {
1519 command = ''; // string is filled with blank
1520 break;
1521 }
1522 } else {
1523 break;
1524 }
1525 }
1526
1527 for (idx_t = command.length - 1; idx_t >= 0 && command.length > 0; --idx_t) {
1528 indexChar = command.charAt(idx_t);
1529 if (indexChar == ' ') {
1530 if (command.length > 1) {
1531 command = command.substr(0, idx_t);
1532 } else {
1533 command = ''; // string is filled with blank
1534 break;
1535 }
1536 } else {
1537 break;
1538 }
1539 }
1540
1541 if (('string' != typeof(command)) || ('' == command)) {
1542 showAlert("ussd_error_input");
1543 return;
1544 }
1545
1546 showLoading('waiting');
1547
1548 var tmp = {};
1549 tmp.operator = "ussd_send";
1550 tmp.strUSSDCommand = command;
1551 tmp.sendOrReply = "send";
1552
1553 fnc.getUSSDResponse(tmp, function (result, content) {
1554 hideLoading();
1555 if (result) {
1556 USSD_reset();
1557 target.USSDLocation(USSDLocation.REPLY);
1558 target.ussd_action(content.ussd_action);
1559 libjq("#USSD_Content").val(decodeMessage(content.data, true));
1560 replyFlg = false;
1561 numTimeout = 0;
1562 } else {
1563 showAlert(content);
1564 }
1565 });
1566 };
1567
1568 target.replyToNet = function () {
1569 numTimeout = 0;
1570 window.clearInterval(time_interval);
1571 var command = target.USSDReply();
1572
1573 var idx_t = 0;
1574 var indexChar;
1575 for (idx_t = 0; idx_t < command.length; ) { //corem0418, delte left blanks and right blanks
1576 indexChar = command.charAt(idx_t);
1577 if (indexChar == ' ') {
1578 if (command.length > 1) {
1579 command = command.substr(idx_t + 1);
1580 } else {
1581 command = ''; // string is filled with blank
1582 break;
1583 }
1584 } else {
1585 break;
1586 }
1587 }
1588
1589 for (idx_t = command.length - 1; idx_t >= 0 && command.length > 0; --idx_t) {
1590 indexChar = command.charAt(idx_t);
1591 if (indexChar == ' ') {
1592 if (command.length > 1) {
1593 command = command.substr(0, idx_t);
1594 } else {
1595 command = ''; // string is filled with blank
1596 break;
1597 }
1598 } else {
1599 break;
1600 }
1601 }
1602
1603 if (('string' != typeof(command)) || ('' == command)) {
1604 showAlert("ussd_error_input");
1605 return;
1606 }
1607
1608 showLoading('waiting');
1609
1610 var tmp = {};
1611 tmp.operator = "ussd_reply";
1612 tmp.strUSSDCommand = command;
1613 tmp.sendOrReply = "reply";
1614
1615 fnc.getUSSDResponse(tmp, function (result, content) {
1616 hideLoading();
1617 if (result) {
1618 target.ussd_action(content.ussd_action);
1619 libjq("#USSD_Content").val(decodeMessage(content.data, true));
1620 replyFlg = false;
1621 USSD_reset();
1622 numTimeout = 0;
1623 } else {
1624 showAlert(content);
1625 }
1626 });
1627 };
1628
1629 USSD_reset = function () {
1630 target.USSDReply("");
1631 target.USSDSend("");
1632 };
1633 USSD_cancel = function () {
1634 fnc.USSDReplyCancel(function (result) {});
1635 };
1636
1637 target.noReplyCancel = function () {
1638 numTimeout = 0;
1639 replyFlg = true;
1640 window.clearInterval(time_interval);
1641 fnc.USSDReplyCancel(function (result) {
1642 if (result) {
1643 USSD_reset();
1644 target.USSDLocation(USSDLocation.SEND);
1645 } else {
1646 showAlert("ussd_fail");
1647 }
1648 });
1649 };
1650
1651 //如果首次进入USSD菜单,先发送USSD取消命令,进行初始化
1652 if (initFlg) {
1653 USSD_cancel();
1654 initFlg = false;
1655 }
1656 }
1657
1658 return {
1659 init: init
1660 };
1661});
1662
1663
1664define("phonebook","underscore jquery knockout set service jq_chosen".split(" "),
1665
1666 function (_, $, ko, config, service, chosen) {
1667
1668 var locationValue = {
1669 SIM: "0",
1670 DEVICE: "1"
1671 };
1672 var pageState = {
1673 LIST: 0,
1674 NEW: 1,
1675 EDIT: 2,
1676 VIEW: 3,
1677 SEND_MSM: 4
1678 };
1679 //存储位置选项
1680 var saveLocationOpts = function (hasSIMCard) {
1681 var opts = [];
1682 opts.push(new Option($.i18n.prop("device_book"), locationValue.DEVICE));
1683 if (hasSIMCard) {
1684 opts.push(new Option($.i18n.prop("sim_book"), locationValue.SIM));
1685 }
1686 return opts;
1687 };
1688
1689 function getCurrentGroup() {
1690 return $("#selectedFilterGroup").val();
1691 }
1692 //列表模板对应的Columns
1693 var templateColumns = {
1694 cardColumns: [{
1695 rowText: "index",
1696 display: false
1697 }, {
1698 rowText: "name"
1699 }, {
1700 rowText: "mobile_phone_number"
1701 }, {
1702 rowText: "home_phone_number"
1703 }
1704 ],
1705 listColumns: [{
1706 columnType: "checkbox",
1707 headerTextTrans: "number",
1708 rowText: "index",
1709 width: "10%"
1710 }, {
1711 headerTextTrans: "name",
1712 rowText: "name",
1713 width: "25%",
1714 sortable: true
1715 }, {
1716 columnType: "image",
1717 headerTextTrans: "save_location",
1718 rowText: "imgLocation",
1719 width: "20%",
1720 sortable: true
1721 }, {
1722 headerTextTrans: "mobile_phone_number",
1723 rowText: "mobile_phone_number",
1724 width: "30%",
1725 sortable: true
1726 }, {
1727 headerTextTrans: "group",
1728 rowText: "transGroup",
1729 width: "15%",
1730 sortable: true,
1731 needTrans: true
1732 }
1733 ]
1734 };
1735 //分组选项
1736 var groupOpts = function () {
1737 var opts = [];
1738 opts.push(new Option($.i18n.prop("common"), "common"));
1739 opts.push(new Option($.i18n.prop("family"), "family"));
1740 opts.push(new Option($.i18n.prop("friend"), "friend"));
1741 opts.push(new Option($.i18n.prop("colleague"), "colleague"));
1742 return opts;
1743 };
1744
1745 var _phoneBookStopSMSSending = false;
1746
1747 function pbViewMode() {
1748 var target = this;
1749
1750 //property for common
1751 target.pageState = ko.observable(pageState.LIST);
1752 target.initFail = ko.observable(true);
1753 target.hasSms = ko.observable(config.HAS_SMS);
1754
1755 var smsHasCapability = true;
1756 var smsLeftCount = 0;
1757
1758 //property for list
1759 var capacity = {
1760 simMaxNameLen: 0,
1761 simMaxNumberLen: 0,
1762 IsSimCardFull: true,
1763 IsDeviceFull: true,
1764 Used: 0,
1765 Capacity: 0,
1766 Ratio: "(0/0)"
1767 };
1768 target.capacity = ko.observable(capacity);
1769 target.phoneBookCapacity = ko.observable(capacity.Ratio);
1770 target.books = ko.observableArray();
1771 //列表模板创建
1772 target.gridTemplate = new ko.simpleGrid.viewModel({
1773 tableClass: "table-fixed",
1774 data: target.books(),
1775 idName: "index",
1776 columns: templateColumns.listColumns,
1777 defaultSortField: "name",
1778 defaultSortDirection: "ASC",
1779 pageSize: 10,
1780 tmplType: 'list',
1781 searchColumns: ["name", "mobile_phone_number"],
1782 primaryColumn: "mobile_phone_number",
1783 showPager: true,
1784 rowClickHandler: function (dataId) {
1785 target.editBooks(dataId, 'view');
1786 },
1787 deleteHandler: function (dataId) {
1788 target.deleteOneBook(dataId);
1789 },
1790 changeTemplateHandler: function () {
1791 target.changeTemplate();
1792 }
1793 });
1794
1795 //property for edit or new
1796 target.locations = ko.observableArray();
1797 target.originLocation = "";
1798 target.selectedLocation = ko.observable(locationValue.DEVICE);
1799 target.locationTrans = ko.observable();
1800 target.locationTransText = ko.observable();
1801 target.index = ko.observable(-1);
1802 target.name = ko.observable("");
1803 target.nameMaxLength = ko.computed(function () {
1804 var max = getNameMaxLength();
1805 var name = target.name().substring(0, max);
1806 target.name(name);
1807 return getNameMaxLength();
1808 });
1809 function getNameMaxLength() {
1810 var max = 22;
1811 if (target.selectedLocation() == locationValue.DEVICE) {
1812 var encodeType = getEncodeType(target.name());
1813 if ("UNICODE" == encodeType.encodeType || encodeType.extendLen > 0) {
1814 max = 11;
1815 } else {
1816 max = 22;
1817 }
1818 //max = 22;
1819 } else {
1820 //对"^"需要按照2个字符处理
1821 var encodeType = getEncodeType(target.name());
1822 if ("UNICODE" == encodeType.encodeType || encodeType.extendLen > 0) {
1823 max = (target.capacity().simMaxNameLen / 2) - 1;
1824 } else {
1825 max = target.capacity().simMaxNameLen;
1826 }
1827 }
1828 return max;
1829 }
1830
1831 target.mobile_phone_number = ko.observable("");
1832 target.mobileMaxLength = ko.computed(function () {
1833 var max = getMobileMaxLength();
1834 var mobileNumber = target.mobile_phone_number().substring(0, max);
1835 target.mobile_phone_number(mobileNumber);
1836 return getMobileMaxLength();
1837 });
1838 function getMobileMaxLength() {
1839 var max = 40;
1840 if (target.selectedLocation() == locationValue.DEVICE) {
1841 max = 40;
1842 } else {
1843 max = target.capacity().simMaxNumberLen;
1844 }
1845 return max;
1846 }
1847
1848 target.home_phone_number = ko.observable("");
1849 target.office_phone_number = ko.observable("");
1850 target.mail = ko.observable("");
1851 target.transEditAreaTitle = ko.dependentObservable(function () {
1852 var state = target.pageState();
1853 if (state == pageState.EDIT) {
1854 return "edit";
1855 } else if (state == pageState.NEW) {
1856 return "new";
1857 } else if (state == pageState.VIEW) {
1858 return "view";
1859 }
1860 });
1861 var groups = groupOpts();
1862 target.groups = ko.observableArray(groups);
1863 target.selectedGroup = ko.observable();
1864 target.groupTrans = ko.observable();
1865 target.groupTransText = ko.observable();
1866
1867 target.selectedFilterGroup = ko.observable('all');
1868 target.selectedFilterGroupChangeHandler = function () {
1869 target.selectedFilterGroup($("#selectedFilterGroup").val());
1870 getPhoneBookReady();
1871 };
1872
1873 //property for sendMessage
1874 target.showErrorInfo = ko.observable(false);
1875 target.messageContent = ko.observable("");
1876 target.messageCount = ko.computed(function () {
1877 var msgInput = $("#txtSmsContent", "#sendMessage");
1878 var msgInputDom = msgInput[0];
1879 target.messageContent();
1880 var strValue = msgInput.val();
1881 var encodeType = getEncodeType(strValue);
1882 var maxLength = encodeType.encodeType == 'UNICODE' ? 335 : 765;
1883 if (strValue.length + encodeType.extendLen > maxLength) {
1884 var scrollTop = msgInputDom.scrollTop;
1885 var insertPos = getInsertPos(msgInputDom);
1886 var moreLen = strValue.length + encodeType.extendLen - maxLength;
1887 var insertPart = strValue.substr(insertPos - moreLen > 0 ? insertPos - moreLen : 0, moreLen);
1888 var reversed = insertPart.split('').reverse();
1889 var checkMore = 0;
1890 var cutNum = 0;
1891 for (var i = 0; i < reversed.length; i++) {
1892 if (getEncodeType(reversed[i]).extendLen > 0) {
1893 checkMore += 2;
1894 } else {
1895 checkMore++;
1896 }
1897 if (checkMore >= moreLen) {
1898 cutNum = i + 1;
1899 break;
1900 }
1901 }
1902 var iInsertToStartLength = insertPos - cutNum;
1903
1904 target.messageContent(strValue.substr(0, iInsertToStartLength) + strValue.substr(insertPos));
1905 if (target.messageContent().length > maxLength) {
1906 target.messageContent(target.messageContent().substr(0, maxLength));
1907 }
1908 setInsertPos(msgInputDom, iInsertToStartLength);
1909 msgInputDom.scrollTop = scrollTop;
1910 }
1911 pbDraftListener();
1912 var newValue = $(msgInputDom).val();
1913 var newEncodeType = getEncodeType(newValue);
1914 var newMaxLength = newEncodeType.encodeType == 'UNICODE' ? 335 : 765;
1915 if (newValue.length + newEncodeType.extendLen >= newMaxLength) {
1916 $("#msgCount").addClass("colorRed");
1917 } else {
1918 $("#msgCount").removeClass("colorRed");
1919 }
1920 return "(" + (newValue.length + newEncodeType.extendLen) + "/" + newMaxLength + ")" + "(" + getSmsCount(newValue) + "/5)";
1921 });
1922
1923 target.clear = function (isNeedInit) {
1924 if (target.pageState() == pageState.SEND_MSM) {
1925 smsPageCheckDraft(clearPhonebookForm, isNeedInit);
1926 } else {
1927 clearPhonebookForm(isNeedInit);
1928 }
1929 config.resetContentModifyValue();
1930 };
1931
1932 //通过按钮返回列表状态事件处理
1933 target.btnClear = function (isNeedInit) {
1934 if (target.pageState() == pageState.SEND_MSM) {
1935 smsPageCheckDraft(clearPhonebookForm, isNeedInit);
1936 config.resetContentModifyValue();
1937 } else if ((target.pageState() == pageState.NEW || target.pageState() == pageState.EDIT) && (target.preContent.location != target.selectedLocation()
1938 || target.preContent.name != target.name()
1939 || target.preContent.mobile_phone_number != target.mobile_phone_number()
1940 || target.preContent.home_phone_number != target.home_phone_number()
1941 || target.preContent.office_phone_number != target.office_phone_number()
1942 || target.preContent.mail != target.mail()
1943 || target.preContent.group != target.selectedGroup())) {
1944 showConfirm("leave_page_info", {
1945 ok: function () {
1946 clearPhonebookForm(isNeedInit);
1947 config.resetContentModifyValue();
1948 },
1949 no: function () {
1950 return false;
1951 }
1952 });
1953 } else {
1954 clearPhonebookForm(isNeedInit);
1955 config.resetContentModifyValue();
1956 }
1957 };
1958
1959 function clearPhonebookForm(isNeedInit) {
1960 $("#frmPhoneBook").hide();
1961 target.pageState(pageState.LIST);
1962 target.index(-1);
1963 target.name("");
1964 target.mobile_phone_number("");
1965 target.home_phone_number("");
1966 target.office_phone_number("");
1967 target.mail("");
1968 target.messageContent("");
1969 if (true == isNeedInit) {
1970 refreshPage();
1971 }
1972 target.gridTemplate.clearAllChecked();
1973 clearValidateMsg();
1974 $("#books ").translate();
1975 $("#frmPhoneBook").show();
1976 }
1977
1978 //检查SIM卡状态
1979 target.checkHasSIMCard = function (showMsg) {
1980 var status = service.getStatusInfo();
1981 if (status.simStatus != "modem_init_complete") {
1982 if (showMsg) {
1983 showAlert("sim_removed", function () {
1984 target.pageState(pageState.LIST);
1985 target.clear(true);
1986 });
1987 }
1988 return false;
1989 }
1990 return true;
1991 };
1992
1993 //保存电话本事件
1994 target.save = function () {
1995 var saveBook = function (index) {
1996 var isSaveInSIM = (location == locationValue.SIM);
1997 if (isSaveInSIM) {
1998 if (!target.checkHasSIMCard(true)) {
1999 return;
2000 }
2001 }
2002 if (target.pageState() == pageState.NEW || (target.pageState() == pageState.EDIT && location != target.originLocation)) {
2003 if (isSaveInSIM) {
2004 if (target.capacity().IsSimCardFull) {
2005 showAlert("sim_full");
2006 return;
2007 }
2008 } else {
2009 if (target.capacity().IsDeviceFull) {
2010 showAlert("device_full");
2011 return;
2012 }
2013 }
2014 }
2015 var name = target.name();
2016 var mobile_phone_number = target.mobile_phone_number();
2017 if ($.trim(name) == "" || $.trim(mobile_phone_number) == "") {
2018 return;
2019 }
2020 showLoading('saving');
2021 var params = {};
2022 params.location = location;
2023 params.index = index;
2024 params.name = name;
2025 params.mobile_phone_number = mobile_phone_number;
2026 if (!isSaveInSIM) {
2027 params.home_phone_number = target.home_phone_number();
2028 params.office_phone_number = target.office_phone_number();
2029 params.mail = target.mail();
2030 params.group = target.selectedGroup();
2031 }
2032 if (target.selectedLocation() != target.originLocation) {
2033 params.delId = target.index();
2034 }
2035 service.savePhoneBook(params, target.callback);
2036 }
2037 var location = target.selectedLocation();
2038 var editIndex = (location == target.originLocation) ? target.index() : -1;
2039 if (location == locationValue.SIM && target.originLocation == locationValue.DEVICE) {
2040 showConfirm("change_device_to_sim_confirm", function () {
2041 saveBook(editIndex);
2042 });
2043 } else {
2044 saveBook(editIndex);
2045 }
2046 };
2047 //打开添加电话本记录页面事件
2048 target.openNewPage = function () {
2049 if (target.pageState() == pageState.SEND_MSM) {
2050 pbDraftListener();
2051 smsPageCheckDraft(openNewPageAct, false);
2052 } else if (target.pageState() == pageState.EDIT && (target.preContent.location != target.selectedLocation()
2053 || target.preContent.name != target.name()
2054 || target.preContent.mobile_phone_number != target.mobile_phone_number()
2055 || target.preContent.home_phone_number != target.home_phone_number()
2056 || target.preContent.office_phone_number != target.office_phone_number()
2057 || target.preContent.mail != target.mail()
2058 || target.preContent.group != target.selectedGroup())) {
2059 showConfirm("leave_page_info", {
2060 ok: function () {
2061 openNewPageAct(false);
2062 },
2063 no: function () {
2064 return false;
2065 }
2066 });
2067 } else {
2068 openNewPageAct(false);
2069 }
2070 };
2071 function openNewPageAct(isNeedInit) {
2072 target.pageState(pageState.NEW);
2073 target.selectedLocation(locationValue.DEVICE);
2074 target.originLocation = "";
2075 if (target.checkHasSIMCard(false)) {
2076 target.locations(saveLocationOpts(true));
2077 } else {
2078 target.locations(saveLocationOpts(false));
2079 }
2080 var group = getCurrentGroup();
2081 if (group != "all") {
2082 target.selectedGroup(group);
2083 } else {
2084 target.selectedGroup("common");
2085 }
2086 target.name("");
2087 target.mobile_phone_number("");
2088 target.home_phone_number("");
2089 target.office_phone_number("");
2090 target.mail("");
2091 target.index(-1);
2092 target.dynamicTranslate();
2093 preOpenEditPage();
2094 }
2095 //打开添加电话本记录编辑页面事件
2096 target.openPage = function (option) {
2097 var index;
2098 if (target.pageState() == pageState.LIST) {
2099 var result = target.checkSelect(option);
2100 if (!result.isCorrectData)
2101 return;
2102 index = result.selectedIds[0];
2103 } else {
2104 index = target.index();
2105 }
2106 target.editBooks(index, option);
2107 };
2108 //打开添加电话本记录查看页面事件
2109 target.openViewPage = function () {
2110 target.openPage("view");
2111 };
2112 //打开添加电话本记录查看页面事件
2113 target.openEditPage = function () {
2114 target.openPage("edit");
2115 if ($.browser.mozilla) {
2116 $("#txtName, #txtMobile").removeAttr('maxlength');
2117 }
2118 preOpenEditPage();
2119 };
2120 //编辑电话本事件处理
2121 target.editBooks = function (selectedId, option) {
2122 if (!selectedId)
2123 return;
2124
2125 if (target.checkHasSIMCard(false)) {
2126 target.locations(saveLocationOpts(true));
2127 } else {
2128 target.locations(saveLocationOpts(false));
2129 }
2130 var data = target.books();
2131 for (var i = 0; i < data.length; i++) {
2132 var n = data[i];
2133 if (n.index == selectedId) {
2134 target.index(n.index);
2135 target.selectedLocation(n.location);
2136 target.originLocation = n.location;
2137 var trans = (n.location == locationValue.DEVICE) ? "device" : "sim";
2138 target.locationTrans(trans);
2139 var transText = $.i18n.prop("trans");
2140 target.locationTransText(transText);
2141 target.name(n.name);
2142 target.mobile_phone_number(n.mobile_phone_number);
2143 target.home_phone_number(n.home_phone_number);
2144 target.office_phone_number(n.office_phone_number);
2145 target.mail(n.mail);
2146 target.selectedGroup(n.group);
2147 target.groupTrans("group_" + n.group);
2148 target.groupTransText($.i18n.prop(target.groupTrans()));
2149 if (option == "edit") {
2150 target.pageState(pageState.EDIT);
2151 } else {
2152 target.pageState(pageState.VIEW);
2153 }
2154 break;
2155 }
2156 }
2157 target.dynamicTranslate();
2158
2159 if (target.selectedLocation() == locationValue.SIM) {
2160 target.checkHasSIMCard(true)
2161 }
2162 };
2163 //翻译编辑区域
2164 target.dynamicTranslate = function () {
2165 $("#container").translate();
2166 };
2167 //删除一条电话本事件处理(card模式使用)
2168 target.deleteOneBook = function (index) {
2169 showConfirm("confirm_pb_delete", function () {
2170 showLoading('deleting');
2171 var params = {};
2172 params.indexs = [String(index)];
2173 service.deletePhoneBooks(params, target.callback);
2174 });
2175 return false;
2176 };
2177 //删除一条电话本事件处理
2178 target.deleteBook = function () {
2179 target.deleteOneBook(target.index());
2180 };
2181 //删除一条或多条电话本事件处理
2182 target.deleteBooks = function () {
2183 var result = target.checkSelect("delete");
2184 if (!result.isCorrectData)
2185 return;
2186 showConfirm("confirm_pb_delete", function () {
2187 showLoading('deleting');
2188 var params = {};
2189 params.indexs = result.selectedIds;
2190 service.deletePhoneBooks(params, target.callback);
2191 });
2192 };
2193 //判断电话本选中
2194 target.checkSelect = function (pState) {
2195 var ids;
2196 if ("send" == pState) {
2197 ids = target.gridTemplate.selectedPrimaryValue();
2198 } else {
2199 ids = target.gridTemplate.selectedIds();
2200 }
2201
2202 var isCorrectData = true;
2203 if (ids.length == 0) {
2204 showAlert("no_data_selected");
2205 isCorrectData = false;
2206 } else if ("edit" == pState || "view" == pState) {
2207 if (ids.length > 1) {
2208 showAlert("too_many_data_selected");
2209 isCorrectData = false;
2210 }
2211 } else if ("send" == pState) {
2212 if (ids.length > 5) {
2213 showAlert("max_send_number");
2214 isCorrectData = false;
2215 }
2216 }
2217 return {
2218 selectedIds: ids,
2219 isCorrectData: isCorrectData
2220 };
2221 };
2222 //全部删除电话本事件处理
2223 target.deleteAllBooks = function () {
2224 showConfirm("confirm_data_delete", function () {
2225 showLoading('deleting');
2226 var group = getCurrentGroup();
2227 var params = {};
2228 if (group == "all") {
2229 params.location = 2;
2230 service.deleteAllPhoneBooks(params, target.callback);
2231 } else {
2232 params.location = 3;
2233 params.group = group;
2234 service.deleteAllPhoneBooksByGroup(params, target.callback);
2235 }
2236 });
2237 };
2238
2239 target.callback = function (data) {
2240 if (data && data.result == "success") {
2241 target.clear(true);
2242 $("#books ").translate();
2243 renderCheckbox();
2244 successOverlay(null, true);
2245 } else {
2246 errorOverlay();
2247 }
2248 };
2249 //变换显示方式事件处理
2250 target.changeTemplate = function () {
2251 if (target.gridTemplate.tmplType == "card") {
2252 target.gridTemplate.tmplType = "list";
2253 target.gridTemplate.pageSize = 10;
2254 target.gridTemplate.columns = templateColumns.listColumns;
2255 } else {
2256 target.gridTemplate.tmplType = "card";
2257 target.gridTemplate.pageSize = 10;
2258 target.gridTemplate.columns = templateColumns.cardColumns;
2259 }
2260 refreshPage();
2261 $("#books ").translate();
2262 };
2263 //显示发送短信页面
2264 target.openSendMessagePage = function () {
2265 if (pageState.SEND_MSM == target.pageState()) {
2266 return;
2267 }
2268 if ((target.pageState() == pageState.EDIT || pageState.NEW == target.pageState()) && (target.preContent.location != target.selectedLocation()
2269 || target.preContent.name != target.name()
2270 || target.preContent.mobile_phone_number != target.mobile_phone_number()
2271 || target.preContent.home_phone_number != target.home_phone_number()
2272 || target.preContent.office_phone_number != target.office_phone_number()
2273 || target.preContent.mail != target.mail()
2274 || target.preContent.group != target.selectedGroup())) {
2275 showConfirm("leave_page_info", {
2276 ok: function () {
2277 openSendMessagePageAct();
2278 },
2279 no: function () {
2280 return false;
2281 }
2282 });
2283 } else {
2284 openSendMessagePageAct();
2285 }
2286 };
2287
2288 function openSendMessagePageAct() {
2289 if (pageState.NEW == target.pageState()) {
2290 target.pageState(pageState.SEND_MSM);
2291 showAlert("no_data_selected");
2292 target.clear();
2293 return;
2294 }
2295 var selectedNumber = null;
2296 if (pageState.LIST == target.pageState()) {
2297 var result = target.checkSelect("send");
2298 if (!result.isCorrectData)
2299 return;
2300 selectedNumber = result.selectedIds;
2301 } else {
2302 selectedNumber = target.mobile_phone_number();
2303 }
2304
2305 var select = $("#chosenUserList .chosen-select-deselect");
2306 select.empty();
2307 var options = [];
2308 var tmp = [];
2309 for (var j = 0; j < config.phonebook.length; j++) {
2310 var book = config.phonebook[j];
2311 if ($.inArray(book.pbm_number, tmp) == -1) {
2312 options.push(new Option(book.pbm_name + "/" + book.pbm_number, book.pbm_number, false, true));
2313 tmp.push(book.pbm_number);
2314 } else {
2315 for (var i = 0; i < options.length; i++) {
2316 if (options[i].value == book.pbm_number) {
2317 options[i].text = book.pbm_name + "/" + book.pbm_number;
2318 break;
2319 }
2320 }
2321 }
2322 }
2323 var opts = "";
2324 $.each(options, function (i, e) {
2325 opts += "<option value='" + HTMLEncode(e.value) + "'>" + HTMLEncode(e.text) + "</option>";
2326 });
2327 select.append(opts);
2328 select.chosen({
2329 max_selected_options: 5,
2330 search_contains: true,
2331 width: '545px'
2332 });
2333 $("#chosenUserSelect").val(selectedNumber);
2334 $("#chosenUserSelect").trigger("chosen:updated.chosen");
2335 config.resetContentModifyValue();
2336 pbDraftListener();
2337 target.pageState(pageState.SEND_MSM);
2338 }
2339
2340 //发送短信
2341 target.sendMessage = function () {
2342 service.getSmsCapability({}, function (capability) {
2343 var hasCapability = capability.nvUsed < capability.nvTotal;
2344 if (!hasCapability) {
2345 showAlert("sms_capacity_is_full_for_send");
2346 return false;
2347 }
2348 var numbers = syncSelectAndChosen($("select#chosenUserSelect"), $('.search-choice', '#chosenUserSelect_chosen'));
2349 if (numbers.length + capability.nvUsed > capability.nvTotal) {
2350 showAlert({
2351 msg: "sms_capacity_will_full_just",
2352 params: [capability.nvTotal - capability.nvUsed]
2353 });
2354 return false;
2355 }
2356 target.sendMessageAction();
2357 return true;
2358 });
2359 };
2360
2361 target.sendMessageAction = function () {
2362 var numbers = syncSelectAndChosen($("select#chosenUserSelect"), $('.search-choice', '#chosenUserSelect_chosen'));
2363
2364 if (!numbers || numbers.length == 0) {
2365 target.showErrorInfo(true);
2366 var timer = addTimeout(function () {
2367 target.showErrorInfo(false);
2368 window.clearTimeout(timer);
2369 }, 5000);
2370 return;
2371 }
2372 var content = target.messageContent();
2373 var sentCount = 0;
2374 var failCount = 0;
2375 if (numbers.length > 1) {
2376 showLoading("sending", "<button id='btnStopSending' onclick='phoneBookStopSMSSending();' class='btn btn-primary'>"
2377 + $.i18n.prop("sms_stop_sending")
2378 + "</button>");
2379 } else {
2380 showLoading('sending');
2381 }
2382 var callback = function (data) {
2383 sentCount++;
2384 if (sentCount == numbers.length) {
2385 $("#chosenUserSelect").val("");
2386 target.messageContent("");
2387 config.CONTENT_MODIFIED.modified = false;
2388 if (failCount == 0) {
2389 successOverlay();
2390 location.hash = "#msg_list";
2391 } else {
2392 var msg = $.i18n.prop("success_info") + $.i18n.prop("colon") + (sentCount - failCount)
2393 + "<br/>" + $.i18n.prop("error_info") + $.i18n.prop("colon") + (failCount);
2394 showAlert(msg, function () {
2395 location.hash = "#msg_list";
2396 });
2397 }
2398
2399 } else {
2400 sendSMS();
2401 }
2402 }
2403 _phoneBookStopSMSSending = false;
2404 var sendSMS = function () {
2405 if (_phoneBookStopSMSSending) {
2406 hideLoading();
2407 return;
2408 }
2409 if ((sentCount + 1) == numbers.length) {
2410 $("#loading #loading_container").html("");
2411 }
2412 service.sendSMS({
2413 number: numbers[sentCount],
2414 message: content,
2415 id: -1
2416 }, function (data) {
2417 callback(data);
2418 }, function (data) {
2419 failCount++;
2420 callback(data);
2421 });
2422 };
2423 sendSMS();
2424 };
2425 //清除搜索关键字事件
2426 target.clearSearchKey = function () {
2427 target.gridTemplate.searchInitStatus(true);
2428 target.gridTemplate.searchKey($.i18n.prop("search"));
2429 $("#ko_grid_search_txt").addClass("ko-grid-search-txt-default").attr("data-trans", "search");
2430 };
2431 //点击搜索输入框事件
2432 target.searchTextClick = function () {
2433 var searchText = $("#ko_grid_search_txt");
2434 if (searchText.hasClass("ko-grid-search-txt-default")) {
2435 target.gridTemplate.searchKey("");
2436 target.gridTemplate.searchInitStatus(false);
2437 searchText.removeClass("ko-grid-search-txt-default").removeAttr("data-trans");
2438 }
2439 };
2440 //离开搜索输入框事件
2441 target.searchTextBlur = function () {
2442 var txt = $.trim(target.gridTemplate.searchKey()).toLowerCase();
2443 if (txt == "") {
2444 target.clearSearchKey();
2445 }
2446 };
2447 //当前表格是否有数据
2448 target.hasData = ko.computed(function () {
2449 return target.gridTemplate.afterSearchData().length > 0;
2450 });
2451 //当前表格是否有选中的数据
2452 target.hasChecked = ko.computed(function () {
2453 return target.gridTemplate.checkedCount() > 0;
2454 });
2455 //是否可以点击发送按钮
2456 target.canSend = ko.computed(function () {
2457 var checked = target.gridTemplate.checkedCount();
2458 if (!target.checkHasSIMCard(false)) {
2459 return false;
2460 }
2461 return (checked > 0 && checked <= 5);
2462 });
2463
2464 //发送短信时,选择用户变化的监控事件
2465 target.draftListenerEvent = function () {
2466 pbDraftListener();
2467 };
2468 //文档内容监听,判断是否修改过
2469 function pbDraftListener() {
2470 var smsHasCapability = true;
2471 if (smsHasCapability) {
2472 var content = target.messageContent();
2473 var hasContent = false;
2474 var numbers = getSelectValFromChosen($('.search-choice', '#chosenUserSelect_chosen'));
2475 var noContactSelected = !(numbers && numbers.length > 0);
2476 if (typeof content == "undefined" || content == '') {
2477 config.resetContentModifyValue();
2478 return false;
2479 } else {
2480 hasContent = true;
2481 }
2482 if (hasContent && !noContactSelected) {
2483 config.CONTENT_MODIFIED.modified = true;
2484 config.CONTENT_MODIFIED.message = 'sms_to_save_draft';
2485 config.CONTENT_MODIFIED.callback.ok = saveDraftAction;
2486 config.CONTENT_MODIFIED.callback.no = $.noop;
2487 config.CONTENT_MODIFIED.data = {
2488 content: content,
2489 numbers: numbers
2490 };
2491 return false;
2492 }
2493 if (hasContent && noContactSelected) {
2494 config.CONTENT_MODIFIED.modified = true;
2495 config.CONTENT_MODIFIED.message = 'sms_no_recipient';
2496 config.CONTENT_MODIFIED.callback.ok = $.noop;
2497 config.CONTENT_MODIFIED.callback.no = function () {
2498 // 返回true,页面保持原状
2499 return true;
2500 };
2501 return false;
2502 }
2503 }
2504 /*else { cov_2
2505 config.resetContentModifyValue();
2506 }*/
2507 }
2508
2509 function saveDraftAction(data) {
2510 var datetime = new Date();
2511 var params = {
2512 index: -1,
2513 currentTimeString: getCurrentTimeString(datetime),
2514 groupId: data.numbers.length > 1 ? datetime.getTime() : '',
2515 message: data.content,
2516 numbers: data.numbers
2517 };
2518 service.saveSMS(params, function () {
2519 successOverlay('sms_save_draft_success');
2520 }, function () {
2521 errorOverlay("sms_save_draft_failed")
2522 });
2523 }
2524 function smsPageCheckDraft(clearCallback, isNeedInit) {
2525 if (config.CONTENT_MODIFIED.message != 'sms_to_save_draft') {
2526 if (config.CONTENT_MODIFIED.modified) {
2527 showConfirm(config.CONTENT_MODIFIED.message, {
2528 ok: function () {
2529 config.CONTENT_MODIFIED.callback.ok(config.CONTENT_MODIFIED.data);
2530 clearCallback(isNeedInit);
2531 },
2532 no: function () {
2533 if (config.CONTENT_MODIFIED.message == 'sms_to_save_draft') {
2534 clearCallback(isNeedInit);
2535 }
2536 return false;
2537 }
2538 });
2539 return false;
2540 } else {
2541 clearCallback(isNeedInit);
2542 }
2543 } else {
2544 config.CONTENT_MODIFIED.callback.ok(config.CONTENT_MODIFIED.data);
2545 clearCallback(isNeedInit);
2546 }
2547 }
2548
2549 //重新获取页面数据并显示
2550 function getPhoneBookReady() {
2551 service.getPhoneBookReady({}, function (data) {
2552 if (data.pbm_init_flag == "6") {
2553 target.initFail(true);
2554 hideLoading();
2555 showAlert("phonebook_init_fail");
2556 } else if (data.pbm_init_flag != "0") {
2557 addTimeout(getPhoneBookReady, 1000);
2558 } else {
2559 target.initFail(false);
2560 var capacity = getCapacity();
2561 target.capacity(capacity);
2562 target.phoneBookCapacity(capacity.Ratio);
2563 var phoneBooks = getBooks(capacity.Used);
2564 target.books(phoneBooks);
2565 target.gridTemplate.data(phoneBooks);
2566 $('#books').find('tbody').translate();
2567 hideLoading();
2568 }
2569 });
2570 }
2571
2572 showLoading('waiting');
2573 addTimeout(getPhoneBookReady, 200);
2574
2575 //重新获取页面数据并显示
2576 function refreshPage() {
2577 showLoading();
2578 var capacity = getCapacity();
2579 target.phoneBookCapacity(capacity.Ratio);
2580 target.capacity(capacity);
2581 var books = getBooks(capacity.Used);
2582 target.books(books);
2583 target.gridTemplate.data(books);
2584 hideLoading();
2585 }
2586
2587 target.preContent = {};
2588 //保存编辑前的内容
2589 function setPreContent() {
2590 target.preContent.location = target.selectedLocation();
2591 target.preContent.name = target.name();
2592 target.preContent.mobile_phone_number = target.mobile_phone_number();
2593 target.preContent.home_phone_number = target.home_phone_number();
2594 target.preContent.office_phone_number = target.office_phone_number();
2595 target.preContent.mail = target.mail();
2596 target.preContent.group = target.selectedGroup();
2597 }
2598
2599 //检测数据是否改变
2600 function checkContentChang() {
2601 var changed = (target.preContent.location != target.selectedLocation()
2602 || target.preContent.name != target.name()
2603 || target.preContent.mobile_phone_number != target.mobile_phone_number()
2604 || target.preContent.home_phone_number != target.home_phone_number()
2605 || target.preContent.office_phone_number != target.office_phone_number()
2606 || target.preContent.mail != target.mail()
2607 || target.preContent.group != target.selectedGroup());
2608 config.CONTENT_MODIFIED.modified = changed;
2609 }
2610
2611 function preOpenEditPage() {
2612 config.resetContentModifyValue();
2613 setPreContent();
2614 config.CONTENT_MODIFIED.checkChangMethod = checkContentChang;
2615 }
2616 }
2617
2618 //设置停止发送标志为true
2619 phoneBookStopSMSSending = function () {
2620 _phoneBookStopSMSSending = true;
2621 $("#loading #loading_container").html($.i18n.prop("sms_cancel_sending"));
2622 }
2623
2624 //获取电话本
2625 function getBooks(capacity) {
2626 var para = {};
2627 para.page = 0;
2628 para.data_per_page = capacity;
2629 para.orderBy = "name";
2630 para.isAsc = true;
2631 var books = [];
2632 var group = getCurrentGroup();
2633 if (config.HAS_SMS) {
2634 books = service.getPhoneBooks(para);
2635 config.phonebook = books.pbm_data;
2636 if (group != "all") {
2637 books = {
2638 "pbm_data": _.filter(books.pbm_data, function (item) {
2639 return item.pbm_group == group;
2640 })
2641 };
2642 }
2643 } else {
2644 if (group != "all") {
2645 para.group = group;
2646 books = service.getPhoneBooksByGroup(para);
2647 } else {
2648 books = service.getPhoneBooks(para);
2649 }
2650 }
2651 return translateData(books.pbm_data);
2652 }
2653
2654 //获取电话本容量信息
2655 function getCapacity() {
2656 var sim = service.getSIMPhoneBookCapacity();
2657 var device = service.getDevicePhoneBookCapacity();
2658 return {
2659 simUsed: sim.simPbmUsedCapacity,
2660 deviceUsed: device.pcPbmUsedCapacity,
2661 simCapacity: sim.simPbmTotalCapacity,
2662 deviceCapacity: device.pcPbmTotalCapacity,
2663 simMaxNameLen: sim.maxNameLen,
2664 simMaxNumberLen: sim.maxNumberLen,
2665 IsSimCardFull: (sim.simPbmUsedCapacity == sim.simPbmTotalCapacity),
2666 IsDeviceFull: (device.pcPbmUsedCapacity == device.pcPbmTotalCapacity),
2667 Used: sim.simPbmUsedCapacity + device.pcPbmUsedCapacity,
2668 Capacity: sim.simPbmTotalCapacity + device.pcPbmTotalCapacity,
2669 Ratio: "(" + (sim.simPbmUsedCapacity + device.pcPbmUsedCapacity) + "/" + (sim.simPbmTotalCapacity + device.pcPbmTotalCapacity) + ")"
2670 };
2671 }
2672
2673 function translateData(books) {
2674 var ret = [];
2675 var group = getCurrentGroup();
2676 var hasFilter = (group != "all");
2677 if (books) {
2678 for (var i = 0; i < books.length; i++) {
2679 if (hasFilter) {
2680 var currentGroup = books[i].pbm_group;
2681 if (books[i].pbm_location == locationValue.SIM || currentGroup != group) {
2682 continue;
2683 }
2684 }
2685 var temp = {
2686 index: books[i].pbm_id,
2687 location: books[i].pbm_location,
2688 imgLocation: books[i].pbm_location == locationValue.SIM ? "pic/simcard.png" : "pic/res_device.png",
2689 name: books[i].pbm_name,
2690 mobile_phone_number: books[i].pbm_number,
2691 home_phone_number: books[i].pbm_anr,
2692 office_phone_number: books[i].pbm_anr1,
2693 mail: books[i].pbm_email,
2694 group: books[i].pbm_group,
2695 transGroup: (!books[i].pbm_group) ? "group_null" : "group_" + books[i].pbm_group
2696 };
2697 ret.push(temp);
2698 }
2699 }
2700 return ret;
2701 }
2702 //初始化ViewModel并进行绑定
2703 function init() {
2704 var container = $('#container');
2705 ko.cleanNode(container[0]);
2706 var vm = new pbViewMode();
2707 ko.applyBindings(vm, container[0]);
2708 $("#txtSmsContent").die().live("contextmenu", function () {
2709 return false;
2710 });
2711 $('#frmPhoneBook').validate({
2712 submitHandler: function () {
2713 vm.save();
2714 },
2715 rules: {
2716 txtMail: "email_check",
2717 txtName: "name_check",
2718 txtMobile: "phonenumber_check",
2719 txtHomeNumber: "phonenumber_check",
2720 txtOfficeNumber: "phonenumber_check"
2721 }
2722 });
2723
2724 }
2725
2726 return {
2727 init: init
2728 };
2729});
2730
2731define("sms_list","underscore jquery knockout set service jq_chosen".split(" "),
2732 function (_, $, ko, config, service, chosen) {
2733
2734 var currentPage = 1;
2735 //数据是否加载完成
2736 var ready = false,
2737 //聊天室信息正在加载中
2738 chatRoomInLoading = false;
2739 //快速添加联系人模板
2740 var addPhonebookTmpl = null,
2741 //短消息模板
2742 smsTableTmpl = null,
2743 //接收短消息模板
2744 smsOtherTmpl = null,
2745 //发送短消息模板
2746 smsMeTmpl = null,
2747 //群聊草稿
2748 groupDrafts = [],
2749 //短消息列表显示群聊草稿
2750 groupDraftItems = [],
2751 //短消息列表显示群聊草稿及其草稿群聊细节
2752 groupedDraftsObject = {},
2753 //短消息容量信息
2754 smsCapability = {},
2755 //短消息是否还有存储空间
2756 hasCapability = true;
2757 //获取全部短消息,并将短信通过回调函数getPhoneBooks,与电话本进行关联
2758 function getSMSMessages(callback) {
2759 return service.getSMSMessages({
2760 page: 0,
2761 smsCount: 500,
2762 nMessageStoreType: 1,
2763 tags: 10,
2764 orderBy: "order by id desc"
2765 }, function (data) {
2766 tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), data.messages.length);
2767 config.dbMsgs = data.messages;
2768 config.listMsgs = groupSms(config.dbMsgs);
2769 callback();
2770 }, function () {
2771 tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), 0);
2772 config.dbMsgs = [];
2773 config.listMsgs = [];
2774 cleanSmsList();
2775 });
2776 }
2777
2778 //清楚短消息列表内容
2779 cleanSmsList = function () {
2780 $("#smslist-table").empty();
2781 };
2782
2783 //关联后的短消息根据电话号码进行分组
2784 function groupSms(messages) {
2785 var peoples = {},
2786 theSortedPeoples = [];
2787 config.listMsgs = [];
2788 groupDrafts = [];
2789 $.each(messages, function (i, e) {
2790 if (e.tag == '4' && e.groupId != '') { // 群聊草稿
2791 groupDrafts.push(e);
2792 return;
2793 }
2794 e.target = e.number;
2795 if (parseInt(e.id, 10) > config.smsMaxId) {
2796 config.smsMaxId = e.id;
2797 }
2798 var last8 = getLastNumber(e.number, config.SMS_MATCH_LENGTH);
2799 if (last8 in peoples) {
2800 peoples[last8].push(e);
2801 } else {
2802 peoples[last8] = [e];
2803 theSortedPeoples.push(e);
2804 }
2805 });
2806 theSortedPeoples = _.sortBy(theSortedPeoples, function (ele) {
2807 return 0 - parseInt(ele.id + "", 10);
2808 });
2809 $.each(theSortedPeoples, function (s_i, sp) {
2810 var people = getLastNumber(sp.number, config.SMS_MATCH_LENGTH);
2811 var newCount = 0;
2812 var hasDraft = false;
2813 for (var i = 0; i < peoples[people].length; i++) {
2814 if (peoples[people][i].isNew) {
2815 newCount++;
2816 }
2817 if (peoples[people][i].tag == '4' && peoples[people][i].groupId == '') { // 单条草稿
2818 hasDraft = true;
2819 }
2820 }
2821 config.listMsgs.push({
2822 id: peoples[people][0].id,
2823 name: "",
2824 number: peoples[people][0].number,
2825 latestId: peoples[people][0].id,
2826 totalCount: peoples[people].length,
2827 newCount: newCount,
2828 latestSms: peoples[people][0].content,
2829 latestTime: peoples[people][0].time,
2830 checked: false,
2831 itemId: getLastNumber(people, config.SMS_MATCH_LENGTH),
2832 groupId: peoples[people][0].groupId,
2833 hasDraft: hasDraft
2834 });
2835 });
2836 return config.listMsgs;
2837 }
2838
2839 //获取电话本信息,并与短消息关联
2840 function getPhoneBooks() {
2841 var books = service.getPhoneBooks({
2842 page: 0,
2843 data_per_page: 2000,
2844 orderBy: "name",
2845 isAsc: true
2846 });
2847 if ($.isArray(books.pbm_data) && books.pbm_data.length > 0) {
2848 config.phonebook = books.pbm_data;
2849 }
2850 dealPhoneBooks();
2851 }
2852
2853 //双异步获取设备侧和sim卡侧的短信息,并将其合并
2854 function dealPhoneBooks() {
2855 var select = $("#chosenUserList .chosen-select-deselect");
2856 select.empty();
2857 var options = [];
2858 var tmp = [];
2859 var pbTmp = [];
2860 for (var j = 0; j < config.phonebook.length; j++) {
2861 var book = config.phonebook[j];
2862 var last8Num = getLastNumber(book.pbm_number, config.SMS_MATCH_LENGTH);
2863 if (last8Num && $.inArray(last8Num, pbTmp) == -1) {
2864 options.push(new Option(book.pbm_name + "/" + book.pbm_number, last8Num, false, true));
2865 if ($.inArray(last8Num, tmp) == -1) {
2866 tmp.push(last8Num);
2867 }
2868 pbTmp.push(last8Num);
2869 } else {
2870 for (var i = 0; i < options.length; i++) {
2871 if (options[i].value == last8Num) {
2872 options[i].text = book.pbm_name + "/" + book.pbm_number;
2873 break;
2874 }
2875 }
2876 }
2877 }
2878 var groupIds = [];
2879 for (var k = 0; k < groupDrafts.length; k++) { // 将草稿做对象Map封装,供草稿组点击后的草稿分解
2880 if ($.inArray(groupDrafts[k].groupId, groupIds) == -1) {
2881 groupIds.push(groupDrafts[k].groupId);
2882 var draft = groupDrafts[k];
2883 groupedDraftsObject[groupDrafts[k].groupId] = [draft];
2884 } else {
2885 var draft = groupDrafts[k];
2886 groupedDraftsObject[groupDrafts[k].groupId].push(draft);
2887 }
2888 var itemId = getLastNumber(groupDrafts[k].number, config.SMS_MATCH_LENGTH);
2889 if ($.inArray(itemId, tmp) == -1) {
2890 options.push(new Option(groupDrafts[k].number, itemId));
2891 tmp.push(itemId);
2892 }
2893 }
2894 for (var g in groupedDraftsObject) { // 处理列表显示的草稿信息
2895 var drafts = groupedDraftsObject[g];
2896 var draftItem = drafts[drafts.length - 1];
2897 draftItem.draftShowName = '';
2898 draftItem.draftShowNameTitle = '';
2899 $.each(drafts, function (i, n) {
2900 var showName = getShowNameByNumber(n.number);
2901 draftItem.draftShowName += (i == 0 ? '' : ';') + showName;
2902 draftItem.draftShowNameTitle += (i == 0 ? '' : ';') + showName;
2903 });
2904
2905 var len = 10;
2906 if (getEncodeType(draftItem.draftShowName).encodeType == "UNICODE") {
2907 len = 10;
2908 }
2909 draftItem.draftShowName = draftItem.draftShowName.length > len ? draftItem.draftShowName.substring(0, len) + "..." : draftItem.draftShowName;
2910 draftItem.totalCount = drafts.length;
2911 draftItem.hasDraft = true;
2912 draftItem.latestTime = draftItem.time;
2913 groupDraftItems.push(draftItem);
2914 }
2915 for (var i = 0; i < config.listMsgs.length; i++) {
2916 var smsItem = config.listMsgs[i];
2917 for (var j = config.phonebook.length; j > 0; j--) {
2918 var book = config.phonebook[j - 1];
2919 var last8Num = getLastNumber(book.pbm_number, config.SMS_MATCH_LENGTH);
2920 if (smsItem.itemId == last8Num) {
2921 smsItem.name = book.pbm_name;
2922 for (var k = 0; k < options.length; k++) {
2923 if (last8Num == options[k].value) {
2924 options[k].value = getLastNumber(smsItem.number, config.SMS_MATCH_LENGTH);
2925 options[k].text = book.pbm_name + '/' + smsItem.number;
2926 break;
2927 }
2928 }
2929 break;
2930 }
2931 }
2932 if ($.inArray(smsItem.itemId, tmp) == -1) {
2933 options.push(new Option(smsItem.number, getLastNumber(smsItem.number, config.SMS_MATCH_LENGTH)));
2934 tmp.push(smsItem.itemId);
2935 }
2936 }
2937
2938 var opts = "";
2939 $.each(options, function (i, e) {
2940 opts += "<option value='" + HTMLEncode(e.value) + "'>" + HTMLEncode(e.text) + "</option>";
2941 });
2942 select.append(opts);
2943 select.chosen({
2944 max_selected_options: 5,
2945 search_contains: true,
2946 width: '740px'
2947 });
2948 showSmsListData();
2949 showMultiDraftListData();
2950 //changeShownMsgs();
2951 ready = true;
2952 }
2953
2954 function showSmsListData() {
2955 if (smsTableTmpl == null) {
2956 smsTableTmpl = $.template("smsTableTmpl", $("#smsTableTmpl"));
2957 }
2958 cleanSmsList();
2959 $.tmpl("smsTableTmpl", {
2960 data: config.listMsgs
2961 }).translate().appendTo("#smslist-table");
2962
2963 if (config.HAS_PHONEBOOK) {
2964 $(".sms-add-contact-icon").removeClass("hide");
2965 } else {
2966 $(".sms-add-contact-icon").addClass("hide");
2967 }
2968 }
2969 //群组草稿列表显示
2970 function showMultiDraftListData() {
2971 if (groupDraftItems.length == 0) {
2972 return false;
2973 }
2974 if (smsTableTmpl == null) {
2975 smsTableTmpl = $.template("smsTableTmpl", $("#smsTableTmpl"));
2976 }
2977 $.tmpl("smsTableTmpl", {
2978 data: groupDraftItems
2979 }).translate().prependTo("#smslist-table");
2980 }
2981
2982 // 页面发生滚动后,改变页面显示的短消息
2983 function changeShownMsgs() {
2984 var shownMsgsTmp = [];
2985 var range = _.range((currentPage - 1) * 5, currentPage * 5);
2986 $.each(range, function (i, e) {
2987 if (config.listMsgs[e]) {
2988 shownMsgsTmp.push(config.listMsgs[e]);
2989 }
2990 });
2991 //shownMsgsTmp = config.listMsgs;
2992 currentPage++;
2993
2994 if (smsTableTmpl == null) {
2995 smsTableTmpl = $.template("smsTableTmpl", $("#smsTableTmpl"));
2996 }
2997 $.tmpl("smsTableTmpl", {
2998 data: shownMsgsTmp
2999 }).translate().appendTo("#smslist-table");
3000
3001 renderCheckbox();
3002 if (shownMsgsTmp.length == 0) {
3003 disableBtn($("#smslist-delete-all"));
3004 tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), 0);
3005 } else {
3006 enableBtn($("#smslist-delete-all"));
3007 tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), 1);
3008 }
3009 if (currentPage == 2 && window.innerHeight == $("body").height()) {
3010 changeShownMsgs();
3011 }
3012 return shownMsgsTmp;
3013 }
3014
3015 //将被checked的条目添加到self.checkedItem中,用于在滚动还原checkbox
3016 checkboxClickHandler = function (id) {
3017 checkDeleteBtnStatus();
3018 };
3019
3020 //获取已选择的条目
3021 getSelectedItem = function () {
3022 var selected = [];
3023 var checkedItem = $("#smslist-table input:checkbox:checked");
3024 checkedItem.each(function (i, e) {
3025 selected.push($(e).val());
3026 });
3027 return selected;
3028 };
3029
3030 //删除按钮是否禁用
3031 checkDeleteBtnStatus = function () {
3032 var size = getSelectedItem().length;
3033 if (size == 0) {
3034 disableBtn($("#smslist-delete"));
3035 } else {
3036 enableBtn($("#smslist-delete"));
3037 }
3038 };
3039
3040 //刷新短消息列表
3041 refreshClickHandler = function () {
3042 $("#smslist-table").empty();
3043 disableBtn($("#smslist-delete"));
3044 disableCheckbox($("#smslist-checkAll", "#smsListForm"));
3045 init();
3046 renderCheckbox();
3047 };
3048
3049 //删除全部短消息
3050 deleteAllClickHandler = function () {
3051 showConfirm("confirm_data_delete", function () {
3052 showLoading('deleting');
3053 service.deleteAllMessages({
3054 location: "native_inbox"
3055 }, function (data) {
3056 cleanSmsList();
3057 tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), 0);
3058 successOverlay();
3059 }, function (error) {
3060 errorOverlay(error.errorText);
3061 });
3062 });
3063 };
3064
3065 //删除选中的短消息
3066 deleteSelectClickHandler = function () {
3067 showConfirm("confirm_sms_delete", function () {
3068 showLoading('deleting');
3069 var items = getIdsBySelectedIds();
3070 service.deleteMessage({
3071 ids: items.ids
3072 }, function (data) {
3073 renderAfterDelete(items);
3074 disableBtn($("#smslist-delete"));
3075 $("#checkbox-all").removeAttr("checked");
3076 renderCheckbox();
3077 successOverlay();
3078 }, function (error) {
3079 errorOverlay(error.errorText);
3080 });
3081 });
3082
3083 function renderAfterDelete(items) {
3084 var ids = items.ids;
3085 var nums = [];
3086 $.each(config.dbMsgs, function (i, e) {
3087 if ($.inArray(e.id, items.normalIds) != -1) {
3088 nums.push(e.number);
3089 }
3090 });
3091 nums = _.uniq(nums);
3092 $.each(nums, function (i, e) {
3093 $("#smslist-item-" + getLastNumber(e, config.SMS_MATCH_LENGTH)).hide().remove();
3094 });
3095 $.each(items.groups, function (i, e) {
3096 $("#smslist-item-" + e).hide().remove();
3097 });
3098 synchSmsList(nums, ids);
3099 }
3100
3101 function getIdsBySelectedIds() {
3102 var nums = [];
3103 var resultIds = [];
3104 var normalIds = [];
3105 var groups = [];
3106 var selectedItem = getSelectedItem();
3107 $.each(selectedItem, function (i, e) {
3108 var checkbox = $("#checkbox" + e);
3109 if (checkbox.attr("groupid")) {
3110 groups.push(checkbox.attr("groupid"));
3111 } else {
3112 nums.push(getLastNumber(checkbox.attr("number"), config.SMS_MATCH_LENGTH));
3113 }
3114 });
3115
3116 $.each(config.dbMsgs, function (i, e) {
3117 if ($.inArray(getLastNumber(e.number, config.SMS_MATCH_LENGTH), nums) != -1 && (typeof e.groupId == "undefined" || _.isEmpty(e.groupId + ''))) {
3118 resultIds.push(e.id);
3119 normalIds.push(e.id);
3120 } else if ($.inArray(e.groupId + '', groups) != -1) { //删除草稿组
3121 resultIds.push(e.id);
3122 }
3123 });
3124 resultIds = _.uniq(resultIds);
3125 return {
3126 ids: resultIds,
3127 groups: groups,
3128 normalIds: normalIds
3129 };
3130 }
3131 };
3132
3133 //新短信按钮点击
3134 newMessageClickHandler = function () {
3135 $("#chosenUser1", "#smsChatRoom").addClass("hide");
3136 $("#chosenUser", "#smsChatRoom").show();
3137
3138 cleanChatInput();
3139 checkSmsCapacityAndAlert();
3140 $("select.chosen-select-deselect").val("").trigger("chosen:updated.chosen");
3141 switchPage('chat');
3142 gotoBottom();
3143 clearChatList();
3144 };
3145
3146 //返回聊天室列表
3147 chatCancelClickHandler = function () {
3148 if (config.CONTENT_MODIFIED.modified) {
3149 var confirmMessage = 'sms_to_save_draft';
3150 var selectedContact = syncSelectAndChosen($("select#chosenUserSelect"), $('.search-choice', '#chosenUserSelect_chosen'));
3151 var noContactSelected = !selectedContact || selectedContact.length == 0;
3152 if (noContactSelected) {
3153 confirmMessage = 'sms_no_recipient';
3154 }
3155 if (noContactSelected) {
3156 showConfirm(confirmMessage, {
3157 ok: function () {
3158 if (!noContactSelected) {
3159 saveDraftAction({
3160 content: $("#chat-input", "#smsChatRoom").val(),
3161 numbers: selectedContact,
3162 isFromBack: true
3163 });
3164 }
3165 config.resetContentModifyValue();
3166 backToSmsListMainPage();
3167 },
3168 no: function () {
3169 if (noContactSelected) {
3170 return true;
3171 }
3172 config.resetContentModifyValue();
3173 backToSmsListMainPage();
3174 }
3175 });
3176 } else {
3177 saveDraftAction({
3178 content: $("#chat-input", "#smsChatRoom").val(),
3179 numbers: selectedContact,
3180 isFromBack: true
3181 });
3182 config.resetContentModifyValue();
3183 backToSmsListMainPage();
3184 }
3185 return false;
3186 }
3187 backToSmsListMainPage();
3188 };
3189
3190 //跳转页面至SIM卡侧、设置界面
3191 toOtherClickHandler = function (href) {
3192 config.CONTENT_MODIFIED.checkChangMethod();
3193 if (config.CONTENT_MODIFIED.modified) {
3194 draftListener();
3195 if (config.CONTENT_MODIFIED.message == 'sms_to_save_draft') {
3196 config.CONTENT_MODIFIED.callback.ok(config.CONTENT_MODIFIED.data);
3197 config.resetContentModifyValue();
3198 window.location.hash = href;
3199 } else {
3200 showConfirm(config.CONTENT_MODIFIED.message, {
3201 ok: function () {
3202 config.CONTENT_MODIFIED.callback.ok(config.CONTENT_MODIFIED.data);
3203 config.resetContentModifyValue();
3204 window.location.hash = href;
3205 },
3206 no: function () {
3207 var result = config.CONTENT_MODIFIED.callback.no(config.CONTENT_MODIFIED.data);
3208 if (!result) {
3209 window.location.hash = href;
3210 config.resetContentModifyValue();
3211 }
3212 }
3213 });
3214 }
3215 return false;
3216 } else {
3217 window.location.hash = href;
3218 }
3219 };
3220
3221 function backToSmsListMainPage() {
3222 $("select.chosen-select-deselect").val("").trigger("chosen:updated.chosen");
3223 config.currentChatObject = null;
3224 $(".smslist-btns", "#smslist-main").removeClass('smsListFloatButs');
3225 switchPage('list');
3226 }
3227
3228 function switchPage(page) {
3229 if (page == 'chat') {
3230 $("#smslist-main").hide();
3231 $("#smsChatRoom").show();
3232 } else {
3233 $("#smsChatRoom").hide();
3234 $("#smslist-main").show();
3235 }
3236 }
3237
3238 var sendSmsErrorTimer = null;
3239 //添加发送错误消息
3240 addSendSmsError = function (msg) {
3241 if (sendSmsErrorTimer) {
3242 window.clearTimeout(sendSmsErrorTimer);
3243 sendSmsErrorTimer = null;
3244 }
3245 $("#sendSmsErrorLi").text($.i18n.prop(msg));
3246 sendSmsErrorTimer = addTimeout(function () {
3247 $("#sendSmsErrorLi").text("");
3248 }, 5000);
3249 };
3250
3251 //发送短消息
3252 sendSmsClickHandler = function () {
3253 if (!hasCapability) {
3254 showAlert("sms_capacity_is_full_for_send");
3255 return;
3256 }
3257 var inputVal = $("#chat-input", "#smsChatRoom");
3258 var msgContent = inputVal.val();
3259 if (msgContent == $.i18n.prop("chat_input_placehoder")) {
3260 inputVal.val("");
3261 msgContent = "";
3262 }
3263 var nums = syncSelectAndChosen($("select#chosenUserSelect"), $('.search-choice', '#chosenUserSelect_chosen'));
3264 if ($.isArray(nums)) {
3265 nums = $.grep(nums, function (n, i) {
3266 return !_.isEmpty(n);
3267 });
3268 }
3269 if (!nums || nums.length == 0) {
3270 addSendSmsError("sms_contact_required");
3271 return;
3272 }
3273 if (nums.length + smsCapability.nvUsed > smsCapability.nvTotal) {
3274 showAlert({
3275 msg: "sms_capacity_will_full_just",
3276 params: [smsCapability.nvTotal - smsCapability.nvUsed]
3277 });
3278 return;
3279 }
3280 if (nums.length == 1) {
3281 config.currentChatObject = getLastNumber(nums[0], config.SMS_MATCH_LENGTH);
3282 showLoading('sending');
3283 } else if (nums.length > 1) {
3284 showLoading("sending", "<button id='sms_cancel_sending' onclick='cancelSending()' class='btn btn-primary'>"
3285 + $.i18n.prop("sms_stop_sending")
3286 + "</button>");
3287 config.currentChatObject = null;
3288 }
3289 var i = 0;
3290 var leftNum = nums.length;
3291 couldSend = true;
3292 disableBtn($("#btn-send", "#inputpanel"));
3293 sendSms = function () {
3294 if (!couldSend) {
3295 hideLoading();
3296 return;
3297 }
3298 var newMsg = {
3299 id: -1,
3300 number: nums[i],
3301 content: msgContent,
3302 isNew: false
3303 };
3304
3305 if (leftNum == 1) {
3306 $("#loading #loading_container").html("");
3307 }
3308
3309 leftNum--;
3310 service.sendSMS({
3311 number: newMsg.number,
3312 message: newMsg.content,
3313 id: -1
3314 }, function (data) {
3315 var latestMsg = getLatestMessage() || {
3316 id: parseInt(config.smsMaxId, 10) + 1,
3317 time: transUnixTime($.now()),
3318 number: newMsg.number
3319 };
3320 config.smsMaxId = latestMsg.id;
3321 newMsg.id = config.smsMaxId;
3322 newMsg.time = latestMsg.time;
3323 newMsg.tag = 2;
3324 newMsg.hasDraft = false;
3325 if (nums.length > 1) {
3326 newMsg.targetName = getNameOrNumberByNumber(newMsg.number);
3327 }
3328 addSendMessage(newMsg, i + 1 != nums.length);
3329 updateDBMsg(newMsg);
3330 updateMsgList(newMsg);
3331 tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
3332 gotoBottom();
3333 if (i + 1 == nums.length) {
3334 updateChatInputWordLength();
3335 enableBtn($("#btn-send", "#inputpanel"));
3336 hideLoading();
3337 return;
3338 }
3339 i++;
3340 sendSms();
3341 }, function (error) {
3342 var latestMsg = getLatestMessage() || {
3343 id: parseInt(config.smsMaxId, 10) + 1,
3344 time: transUnixTime($.now()),
3345 number: newMsg.number
3346 };
3347 config.smsMaxId = latestMsg.id;
3348 newMsg.id = config.smsMaxId;
3349 newMsg.time = latestMsg.time;
3350 newMsg.errorText = $.i18n.prop(error.errorText);
3351 newMsg.tag = 3;
3352 newMsg.target = newMsg.number;
3353 newMsg.hasDraft = false;
3354 if (nums.length > 1) {
3355 newMsg.targetName = getNameOrNumberByNumber(newMsg.number);
3356 }
3357 addSendMessage(newMsg, i + 1 != nums.length);
3358 updateDBMsg(newMsg);
3359 updateMsgList(newMsg);
3360 tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
3361 gotoBottom();
3362 if (i + 1 == nums.length) {
3363 updateChatInputWordLength();
3364 enableBtn($("#btn-send", "#inputpanel"));
3365 hideLoading();
3366 return;
3367 }
3368 i++;
3369 sendSms();
3370 });
3371 };
3372 sendSms();
3373 };
3374
3375 var couldSend = true;
3376
3377 //取消剩余短信发送操作
3378 cancelSending = function () {
3379 couldSend = false;
3380 $("#loading #loading_container").html($.i18n.prop('sms_cancel_sending'));
3381 };
3382
3383 //获取最新的短消息
3384 getLatestMessage = function () {
3385 var data = service.getSMSMessages({
3386 page: 0,
3387 smsCount: 5,
3388 nMessageStoreType: 1,
3389 tags: 10,
3390 orderBy: "order by id desc"
3391 });
3392 if (data.messages.length > 0) {
3393 for (var i = 0; i < data.messages.length; i++) {
3394 if (data.messages[i].tag == '2' || data.messages[i].tag == '3') {
3395 return data.messages[i];
3396 }
3397 }
3398 return null;
3399 } else {
3400 return null;
3401 }
3402 };
3403
3404 //发送短信后,更新短信数据对象
3405 function updateDBMsg(msg) {
3406 if (config.dbMsgs.length == 0) {
3407 config.dbMsgs = [msg];
3408 } else {
3409 /* cov_2
3410 for(var j = 0; j < config.dbMsgs.length; j++){
3411 if(config.dbMsgs[j].id == msg.id){
3412 config.dbMsgs[j] = msg;
3413 return;
3414 } else {
3415 var newMsg = [msg];
3416 $.merge(newMsg, config.dbMsgs);
3417 config.dbMsgs = newMsg;
3418 return;
3419 }
3420 }
3421 */
3422 if (config.dbMsgs[0].id == msg.id) {
3423 config.dbMsgs[0] = msg;
3424 return;
3425 } else {
3426 var newMsg = [msg];
3427 $.merge(newMsg, config.dbMsgs);
3428 config.dbMsgs = newMsg;
3429 return;
3430 }
3431 }
3432 }
3433
3434 //发送短信后,更新短信列表, number不为空做删除处理,为空做增加处理
3435 function updateMsgList(msg, number, counter) {
3436 if ((!msg || !msg.number) && !number) {
3437 return;
3438 }
3439 var itemId = '';
3440 if (msg && typeof msg.groupId != "undefined" && msg.groupId != '') {
3441 itemId = msg.groupId;
3442 } else {
3443 itemId = getLastNumber((number || msg.number), config.SMS_MATCH_LENGTH);
3444 }
3445 var item = $("#smslist-item-" + itemId);
3446 if (item && item.length > 0) {
3447 var totalCountItem = item.find(".smslist-item-total-count");
3448 var count = totalCountItem.text();
3449 count = Number(count.substring(1, count.length - 1));
3450 if (number) {
3451 if (count == 1 || msg == null) {
3452 item.hide().remove();
3453 return;
3454 } else {
3455 totalCountItem.text("(" + (count - (counter || 1)) + ")");
3456 item.find(".smslist-item-draft-flag").addClass('hide');
3457 }
3458 } else {
3459 totalCountItem.text("(" + (count + 1) + ")");
3460 if (msg.tag == '4') {
3461 item.find(".smslist-item-draft-flag").removeClass('hide');
3462 }
3463 }
3464 item.find(".smslist-item-checkbox p.checkbox").attr("id", msg.id);
3465 item.find(".smslist-item-checkbox input:checkbox").val(msg.id).attr("id", "checkbox" + msg.id);
3466 var contentHtml = msg.content;
3467 var msgContent;
3468 if (msg.tag == '4') {
3469 //contentHtml = '<span class="smslist-item-draft-flag colorRed" data-trans="draft"></span>: ' + contentHtml;
3470 msgContent = item.find(".smslist-item-msg").html('<span class="smslist-item-draft-flag colorRed" data-trans="draft"></span>: ' + HTMLEncode(contentHtml)); //.addClass("font-weight-bold");
3471 } else {
3472 msgContent = item.find(".smslist-item-msg").html(HTMLEncode(contentHtml)); //.addClass("font-weight-bold");
3473 }
3474 //var msgContent = item.find(".smslist-item-msg").html(HTMLEncode(contentHtml)); //.addClass("font-weight-bold");
3475 msgContent.closest('td').prop('title', msg.content);
3476 item.find(".smslist-item-repeat span").die().click(function () {
3477 forwardClickHandler(msg.id);
3478 });
3479 item.find("span.clock-time").text(msg.time);
3480 var tmpItem = item;
3481 item.hide().remove();
3482 $("#smslist-table").prepend(tmpItem.show());
3483 } else {
3484 if (smsTableTmpl == null) {
3485 smsTableTmpl = $.template("smsTableTmpl", $("#smsTableTmpl"));
3486 }
3487 msg.checked = false;
3488 msg.newCount = 0;
3489 msg.latestId = msg.id;
3490 msg.latestSms = msg.content;
3491 msg.latestTime = msg.time;
3492 if (msg.groupId == '' || typeof msg.groupId == "undefined") {
3493 msg.totalCount = 1;
3494 }
3495 if (!msg.hasDraft) {
3496 msg.hasDraft = false;
3497 }
3498 msg.itemId = itemId;
3499 msg.name = getNameByNumber(msg.number);
3500 $.tmpl("smsTableTmpl", {
3501 data: [msg]
3502 }).translate().prependTo("#smslist-table");
3503 }
3504 if (config.HAS_PHONEBOOK) {
3505 $(".sms-add-contact-icon").removeClass("hide");
3506 } else {
3507 $(".sms-add-contact-icon").addClass("hide");
3508 }
3509 $("#smslist-table").translate();
3510 renderCheckbox();
3511 }
3512
3513 //增加发送内容到聊天室, notCleanChatInput 是否清除输入框内容
3514 addSendMessage = function (sms, notCleanChatInput) {
3515 if (smsMeTmpl == null) {
3516 smsMeTmpl = $.template("smsMeTmpl", $("#smsMeTmpl"));
3517 }
3518 $.tmpl("smsMeTmpl", sms).appendTo("#chatlist");
3519 $("#chatlist").translate();
3520 if (!notCleanChatInput) {
3521 cleanChatInput();
3522 }
3523 clearMySmsErrorMessage(sms.id);
3524 };
3525
3526 //清楚错误消息,避免翻译问题
3527 clearMySmsErrorMessage = function (id) {
3528 addTimeout(function () {
3529 $("div.error", "#talk-item-" + id).text("");
3530 }, 3000);
3531 };
3532
3533 //快速添加联系人overlay是否打开
3534 var isPoped = false;
3535
3536 //关闭快速添加联系人overlay
3537 hidePopup = function () {
3538 $(".tagPopup").remove();
3539 isPoped = false;
3540 };
3541
3542 //清空聊天室内容
3543 clearChatList = function () {
3544 $("#chatlist").empty();
3545 updateChatInputWordLength();
3546 };
3547
3548 //过滤短消息内容
3549 dealContent = function (content) {
3550 if (config.HAS_PHONEBOOK) {
3551 return HTMLEncode(content).replace(/(\d{3,})/g, function (word) {
3552 var r = (new Date().getTime() + '').substring(6) + (getRandomInt(1000) + 1000);
3553 return "<a id='aNumber" + r + "' href='javascript:openPhoneBook(\"" + r + "\", \"" + word + "\")'>" + word + "</a>";
3554 });
3555 } else {
3556 return HTMLEncode(content);
3557 }
3558
3559 };
3560
3561 //打开快速添加联系人overlay
3562 openPhoneBook = function (id, num) {
3563 var target = null;
3564 var outContainer = "";
3565 var itemsContainer = null;
3566 var isChatRoom = false;
3567 if (!id) {
3568 target = $("#listNumber" + getLastNumber(num, config.SMS_MATCH_LENGTH));
3569 outContainer = ".smslist-item";
3570 itemsContainer = $("#addPhonebookContainer");
3571 } else {
3572 target = $("#aNumber" + id);
3573 outContainer = ".msg_container";
3574 itemsContainer = $("#chatlist");
3575 isChatRoom = true;
3576 }
3577 if (isPoped) {
3578 hidePopup();
3579 }
3580 isPoped = true;
3581 $("#tagPopup").remove();
3582
3583 if (addPhonebookTmpl == null) {
3584 addPhonebookTmpl = $.template("addPhonebookTmpl", $("#addPhonebookTmpl"));
3585 }
3586 $.tmpl("addPhonebookTmpl", {
3587 number: num
3588 }).appendTo(itemsContainer);
3589 var p = target.position();
3590 var msgContainer = target.closest(outContainer);
3591 var msgP = msgContainer.position();
3592 var _left = 0,
3593 _top = 0;
3594 if (isChatRoom) {
3595 var containerWidth = itemsContainer.width();
3596 var containerHeight = itemsContainer.height();
3597 var pop = $("#innerTagPopup");
3598 _left = msgP.left + p.left;
3599 _top = msgP.top + p.top + 20;
3600 if (pop.width() + _left > containerWidth) {
3601 _left = containerWidth - pop.width() - 20;
3602 }
3603 if (containerHeight > 100 && pop.height() + _top > containerHeight) {
3604 _top = containerHeight - pop.height() - 5;
3605 }
3606 } else {
3607 _left = p.left;
3608 _top = p.top;
3609 }
3610 $("#innerTagPopup").css({
3611 top: _top + "px",
3612 left: _left + "px"
3613 });
3614 $('#quickSaveContactForm').translate().validate({
3615 submitHandler: function () {
3616 quickSaveContact(isChatRoom);
3617 },
3618 rules: {
3619 name: "name_check",
3620 number: "phonenumber_check"
3621 }
3622 });
3623 };
3624
3625 //快速添加联系人
3626 quickSaveContact = function () {
3627 var name = $(".tagPopup #innerTagPopup #name").val();
3628 var number = $(".tagPopup #innerTagPopup #number").val();
3629 var newContact = {
3630 index: -1,
3631 location: 1,
3632 name: name,
3633 mobile_phone_number: number,
3634 home_phone_number: "",
3635 office_phone_number: "",
3636 mail: ""
3637 };
3638 var device = service.getDevicePhoneBookCapacity();
3639 if (device.pcPbmUsedCapacity >= device.pcPbmTotalCapacity) {
3640 showAlert("device_full");
3641 return false;
3642 }
3643 showLoading('waiting');
3644 service.savePhoneBook(newContact, function (data) {
3645 if (data.result == "success") {
3646 config.phonebook.push({
3647 pbm_name: name,
3648 pbm_number: number
3649 });
3650 updateItemShowName(name, number);
3651 hidePopup();
3652 successOverlay();
3653 } else {
3654 errorOverlay();
3655 }
3656 }, function (data) {
3657 errorOverlay();
3658 });
3659 };
3660
3661 function updateItemShowName(name, number) {
3662 var lastNum = getLastNumber(number, config.SMS_MATCH_LENGTH);
3663 $("span.smslist-item-name2", "#smslist-item-" + lastNum).text(name);
3664 $("#listNumber" + lastNum).hide();
3665 }
3666
3667 //聊天室删除单条消息
3668 deleteSingleItemClickHandler = function (id, resendCallback) {
3669 if (resendCallback) {
3670 deleteTheSingleItem(id);
3671 } else {
3672 showConfirm("confirm_sms_delete", function () {
3673 showLoading('deleting');
3674 deleteTheSingleItem(id);
3675 });
3676 }
3677
3678 function deleteTheSingleItem(id) {
3679 service.deleteMessage({
3680 ids: [id]
3681 }, function (data) {
3682 var target = $(".smslist-item-delete", "#talk-item-" + id).attr("target");
3683 $("#talk-item-" + id).hide().remove();
3684
3685 synchSmsList(null, [id]);
3686 updateMsgList(getPeopleLatestMsg(target), target);
3687 if (resendCallback) {
3688 resendCallback();
3689 } else {
3690 hideLoading();
3691 }
3692 tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
3693 }, function (error) {
3694 if (resendCallback) {
3695 resendCallback();
3696 } else {
3697 hideLoading();
3698 }
3699 });
3700 }
3701 };
3702
3703 //删除草稿
3704 function deleteDraftSms(ids, numbers) {
3705 stopNavigation();
3706 service.deleteMessage({
3707 ids: ids
3708 }, function (data) {
3709 updateSmsCapabilityStatus(null, function () {
3710 draftListener();
3711 restoreNavigation();
3712 });
3713 for (var i = 0; i < numbers.length; i++) {
3714 updateMsgList(getPeopleLatestMsg(numbers[i]), numbers[i], ids.length);
3715 }
3716 synchSmsList(null, ids);
3717 tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
3718 }, function (error) {
3719 restoreNavigation();
3720 // Do nothing
3721 });
3722 }
3723
3724 //删除群聊草稿草稿
3725 function deleteMultiDraftSms(ids, groupId) {
3726 service.deleteMessage({
3727 ids: ids
3728 }, function (data) {
3729 synchSmsList(null, ids);
3730 $("#smslist-item-" + groupId).hide().remove();
3731 checkSmsCapacityAndAlert();
3732 tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
3733 }, function (error) {
3734 // Do nothing
3735 });
3736 }
3737
3738 getCurrentChatObject = function () {
3739 var nums = $("select.chosen-select-deselect").val();
3740 if (!nums) {
3741 config.currentChatObject = null;
3742 } else if (nums.length == 1) {
3743 config.currentChatObject = getLastNumber(nums, config.SMS_MATCH_LENGTH);
3744 } else if (nums.length > 1) {
3745 config.currentChatObject = null;
3746 }
3747 return config.currentChatObject;
3748 };
3749
3750 //获取当前聊天对象最新的短消息
3751 getPeopleLatestMsg = function (number) {
3752 for (var j = 0; j < config.dbMsgs.length; j++) {
3753 if (!config.dbMsgs[j].groupId && getLastNumber(config.dbMsgs[j].number, config.SMS_MATCH_LENGTH) == getLastNumber(number, config.SMS_MATCH_LENGTH)) {
3754 return config.dbMsgs[j];
3755 }
3756 }
3757 return null;
3758 };
3759
3760 //重新发送,复制消息到发送框
3761 resendClickHandler = function (id) {
3762 if (!hasCapability) {
3763 showAlert("sms_capacity_is_full_for_send");
3764 return;
3765 }
3766 showLoading('sending');
3767 $("div.error", "#talk-item-" + id).text($.i18n.prop("sms_resending"));
3768 var targetNumber = $("div.smslist-item-resend", "#talk-item-" + id).attr("target");
3769 var content = $("div.J_content", "#talk-item-" + id).text();
3770 for (var j = 0; j < config.dbMsgs.length; j++) {
3771 if (config.dbMsgs[j].id == id) {
3772 content = config.dbMsgs[j].content;
3773 }
3774 }
3775
3776 disableBtn($("#btn-send", "#inputpanel"));
3777 var newMsg = {
3778 id: -1,
3779 number: targetNumber,
3780 content: content,
3781 isNew: false
3782 };
3783 service.sendSMS({
3784 number: newMsg.number,
3785 message: newMsg.content,
3786 id: -1
3787 }, function (data) {
3788 var latestMsg = getLatestMessage() || {
3789 id: parseInt(config.smsMaxId, 10) + 1,
3790 time: transUnixTime($.now()),
3791 number: newMsg.number
3792 };
3793 config.smsMaxId = latestMsg.id;
3794 newMsg.id = config.smsMaxId;
3795 newMsg.time = latestMsg.time;
3796 newMsg.tag = 2;
3797 newMsg.target = latestMsg.number;
3798 newMsg.targetName = getNameOrNumberByNumber(targetNumber);
3799 updateDBMsg(newMsg);
3800 updateMsgList(newMsg);
3801 deleteSingleItemClickHandler(id, function () {
3802 addSendMessage(newMsg, true);
3803 updateChatInputWordLength();
3804 enableBtn($("#btn-send", "#inputpanel"));
3805 hideLoading();
3806 gotoBottom();
3807 });
3808 }, function (error) {
3809 var latestMsg = getLatestMessage() || {
3810 id: parseInt(config.smsMaxId, 10) + 1,
3811 time: transUnixTime($.now()),
3812 number: newMsg.number
3813 };
3814 config.smsMaxId = latestMsg.id;
3815 newMsg.id = config.smsMaxId;
3816 newMsg.time = latestMsg.time;
3817 newMsg.errorText = $.i18n.prop("sms_resend_fail");
3818 newMsg.tag = 3;
3819 newMsg.target = latestMsg.number;
3820 newMsg.targetName = getNameOrNumberByNumber(targetNumber);
3821 updateDBMsg(newMsg);
3822 updateMsgList(newMsg);
3823 deleteSingleItemClickHandler(id, function () {
3824 addSendMessage(newMsg, true);
3825 updateChatInputWordLength();
3826 enableBtn($("#btn-send", "#inputpanel"));
3827 hideLoading();
3828 gotoBottom();
3829 });
3830 });
3831 };
3832
3833 //滚动到底部
3834 gotoBottom = function () {
3835 $("#chatpanel .clear-container").animate({
3836 scrollTop: $("#chatlist").height()
3837 });
3838 };
3839
3840 //最后一条短消息距离顶部的距离
3841 var lastItemOffsetTop = 0;
3842 //页面是否处于滚动中
3843 var scrolling = false;
3844 //初始化页面状态信息
3845 function initStatus() {
3846 currentPage = 1;
3847 ready = false;
3848 shownMsgs = [];
3849 scrolling = false;
3850 lastItemOffsetTop = 0;
3851 groupDrafts = groupDraftItems = [];
3852 groupedDraftsObject = {};
3853 config.dbMsgs = [];
3854 config.listMsgs = null;
3855 config.smsMaxId = 0;
3856 config.phonebook = [];
3857 }
3858
3859 function getReadyStatus() {
3860 showLoading('waiting');
3861 config.currentChatObject = null;
3862 var getSMSReady = function () {
3863 service.getSMSReady({}, function (data) {
3864 if (data.sms_cmd_status_result == "2") {
3865 $("input:button", "#smsListForm .smslist-btns").attr("disabled", "disabled");
3866 hideLoading();
3867 showAlert("sms_init_fail");
3868 } else if (data.sms_cmd_status_result == "1") {
3869 addTimeout(getSMSReady, 1000);
3870 } else {
3871 if (config.HAS_PHONEBOOK) {
3872 getPhoneBookReady();
3873 } else {
3874 initSMSList(false);
3875 }
3876 }
3877 });
3878 };
3879
3880 var getPhoneBookReady = function () {
3881 service.getPhoneBookReady({}, function (data) {
3882 if (data.pbm_init_flag == "6") {
3883 initSMSList(false);
3884 } else if (data.pbm_init_flag != "0") {
3885 addTimeout(getPhoneBookReady, 1000);
3886 } else {
3887 initSMSList(true);
3888 }
3889 });
3890 };
3891
3892 var initSMSList = function (isPbmInitOK) {
3893 initStatus();
3894 if (isPbmInitOK) {
3895 getSMSMessages(function () {
3896 getPhoneBooks();
3897 hideLoading();
3898 });
3899 } else {
3900 getSMSMessages(function () {
3901 config.phonebook = [];
3902 //if(config.HAS_PHONEBOOK){
3903 dealPhoneBooks();
3904 //}
3905 hideLoading();
3906 });
3907 }
3908 bindingEvents();
3909 fixScrollTop();
3910 window.scrollTo(0, 0);
3911 initSmsCapability();
3912 };
3913
3914 getSMSReady();
3915 }
3916
3917 //初始化短信容量状态
3918 function initSmsCapability() {
3919 var capabilityContainer = $("#smsCapability");
3920 updateSmsCapabilityStatus(capabilityContainer);
3921 checkSimStatusForSend();
3922 addInterval(function () {
3923 updateSmsCapabilityStatus(capabilityContainer);
3924 checkSimStatusForSend();
3925 }, 5000);
3926 }
3927
3928 //SIM卡未准备好时,禁用发送按钮
3929 function checkSimStatusForSend() {
3930 var data = service.getStatusInfo();
3931 if (data.simStatus != 'modem_init_complete') {
3932 disableBtn($("#btn-send"));
3933 $("#sendSmsErrorLi").html('<span data-trans="no_sim_card_message">' + $.i18n.prop('no_sim_card_message') + '</span>');
3934 $("#chatpanel .smslist-item-resend:visible").hide();
3935 } else {
3936 enableBtn($("#btn-send"));
3937 $("#chatpanel .smslist-item-resend:hidden").show();
3938 }
3939 }
3940
3941 //更新短信容量状态
3942 function updateSmsCapabilityStatus(capabilityContainer, callback) {
3943 service.getSmsCapability({}, function (capability) {
3944 if (capabilityContainer != null) {
3945 capabilityContainer.text("(" + (capability.nvUsed > capability.nvTotal ? capability.nvTotal : capability.nvUsed) + "/" + capability.nvTotal + ")");
3946 }
3947 hasCapability = capability.nvUsed < capability.nvTotal;
3948 smsCapability = capability;
3949 if ($.isFunction(callback)) {
3950 callback();
3951 }
3952 });
3953 }
3954
3955 //初始化页面及VM
3956 function init() {
3957 getReadyStatus();
3958 }
3959
3960 //事件绑定
3961 bindingEvents = function () {
3962 var $win = $(window);
3963 var $smsListBtns = $("#smslist-main .smslist-btns");
3964 var offsetTop = $("#mainContainer").offset().top;
3965 $win.unbind("scroll").scroll(function () {
3966 if ($win.scrollTop() > offsetTop) {
3967 $smsListBtns.addClass("smsListFloatButs marginnone");
3968 } else {
3969 $smsListBtns.removeClass("smsListFloatButs marginnone");
3970 }
3971 //loadData(); //由于目前数据显示是全显示,不做动态加载,因此暂时注释掉
3972 });
3973
3974 $("#smslist-table p.checkbox").die().live("click", function () {
3975 checkboxClickHandler($(this).attr("id"));
3976 });
3977
3978 $("#smslist-checkAll", "#smsListForm").die().live("click", function () {
3979 checkDeleteBtnStatus();
3980 });
3981
3982 $("#chat-input", "#smsChatRoom").die().live("drop", function () {
3983 $("#inputpanel .chatform").addClass("chatformfocus");
3984 var $this = $(this);
3985 $this.removeAttr("data-trans");
3986 if ($this.val() == $.i18n.prop("chat_input_placehoder")) {
3987 $this.val("");
3988 }
3989 updateChatInputWordLength();
3990 }).live("focusin", function () {
3991 $("#inputpanel .chatform").addClass("chatformfocus");
3992 var $this = $(this);
3993 $this.removeAttr("data-trans");
3994 if ($this.val() == $.i18n.prop("chat_input_placehoder")) {
3995 $this.val("");
3996 }
3997 updateChatInputWordLength();
3998 }).live("focusout", function () {
3999 $("#inputpanel .chatform").removeClass("chatformfocus");
4000 var $this = $(this);
4001 if ($this.val() == "" || $this.val() == $.i18n.prop("chat_input_placehoder")) {
4002 $this.val($.i18n.prop("chat_input_placehoder")).attr("data-trans", "chat_input_placehoder");
4003 }
4004 updateChatInputWordLength();
4005 }).live("keyup", function () {
4006 updateChatInputWordLength();
4007 }).live("paste", function () {
4008 window.setTimeout(function () {
4009 updateChatInputWordLength();
4010 }, 0);
4011 }).live("cut", function () {
4012 window.setTimeout(function () {
4013 updateChatInputWordLength();
4014 }, 0);
4015 }).live("drop", function () {
4016 window.setTimeout(function () {
4017 updateChatInputWordLength();
4018 }, 0);
4019 }).live("contextmenu", function () {
4020 return false;
4021 });
4022
4023 $("#name").die().live("drop", function () {
4024 updateNameInputWordLength();
4025 }).live("focusin", function () {
4026 updateNameInputWordLength();
4027 }).live("focusout", function () {
4028 updateNameInputWordLength();
4029 }).live("keyup", function () {
4030 updateNameInputWordLength();
4031 }).live("paste", function () {
4032 updateNameInputWordLength();
4033 }).live("cut", function () {
4034 updateNameInputWordLength();
4035 }).live("dragend", function () {
4036 updateNameInputWordLength();
4037 }).live("contextmenu", function () {
4038 return false;
4039 });
4040
4041 $("select.chosen-select-deselect", "#smsChatRoom").die().live('change', function () {
4042 draftListener();
4043 });
4044 $("#searchInput").die().live('blur', function () {
4045 searchTextBlur();
4046 }).live('keyup', function () {
4047 updateSearchValue($("#searchInput").val());
4048 });
4049 };
4050
4051 //更新剩余字数
4052 updateNameInputWordLength = function () {
4053
4054 var msgInput = $("#name", "#quickSaveContactForm");
4055 var msgInputDom = msgInput[0];
4056 var strValue = msgInput.val();
4057 var encodeType = getEncodeType(strValue);
4058 var maxLength = encodeType.encodeType == 'UNICODE' ? 11 : 22;
4059 while (strValue.length + encodeType.extendLen > maxLength) {
4060 strValue = strValue.substring(0, strValue.length - 1);
4061 msgInputDom.value = strValue;
4062 encodeType = getEncodeType(strValue);
4063 maxLength = encodeType.encodeType == 'UNICODE' ? 11 : 22;
4064 }
4065 };
4066
4067//获取聊天对象的名字
4068 getNameByNumber = function (num) {
4069 for (var i = config.phonebook.length; i > 0; i--) {
4070 if (getLastNumber(config.phonebook[i - 1].pbm_number, config.SMS_MATCH_LENGTH) == getLastNumber(num, config.SMS_MATCH_LENGTH)) {
4071 return config.phonebook[i - 1].pbm_name;
4072 }
4073 }
4074 return "";
4075 };
4076 //获取聊天对象的名字和号码
4077 getShowNameByNumber = function (num) {
4078 for (var i = config.phonebook.length; i > 0; i--) {
4079 if (getLastNumber(config.phonebook[i - 1].pbm_number, config.SMS_MATCH_LENGTH) == getLastNumber(num, config.SMS_MATCH_LENGTH)) {
4080 return config.phonebook[i - 1].pbm_name /* + "/" + num*/;
4081 }
4082 }
4083 return num;
4084 };
4085
4086 //获取聊天对象的名字,如果没有名字,则显示号码
4087 getNameOrNumberByNumber = function (num) {
4088 for (var i = config.phonebook.length; i > 0; i--) {
4089 if (config.phonebook[i - 1].pbm_number == num) {
4090 return config.phonebook[i - 1].pbm_name;
4091 }
4092 }
4093 for (var i = config.phonebook.length; i > 0; i--) {
4094 if (getLastNumber(config.phonebook[i - 1].pbm_number, config.SMS_MATCH_LENGTH) == getLastNumber(num, config.SMS_MATCH_LENGTH)) {
4095 return config.phonebook[i - 1].pbm_name;
4096 }
4097 }
4098 return num;
4099 };
4100
4101 //点击短信列表条目,进入聊天室页面
4102 smsItemClickHandler = function (num) {
4103 if (chatRoomInLoading) {
4104 return false;
4105 }
4106 chatRoomInLoading = true;
4107 if (smsOtherTmpl == null) {
4108 smsOtherTmpl = $.template("smsOtherTmpl", $("#smsOtherTmpl"));
4109 }
4110 if (smsMeTmpl == null) {
4111 smsMeTmpl = $.template("smsMeTmpl", $("#smsMeTmpl"));
4112 }
4113
4114 var name = getShowNameByNumber(num);
4115 $("#chosenUser", "#smsChatRoom").hide();
4116 $("#chosenUser1", "#smsChatRoom").addClass("hide");
4117
4118 config.currentChatObject = getLastNumber(num, config.SMS_MATCH_LENGTH);
4119 setAsRead(num);
4120 cleanChatInput();
4121 clearChatList();
4122 var userSelect = $("select.chosen-select-deselect", "#smsChatRoom");
4123 var ops = $("option", userSelect);
4124 var numberExist = false;
4125 for (var i = 0; i < ops.length; i++) {
4126 var n = ops[i];
4127 if (getLastNumber(n.value, config.SMS_MATCH_LENGTH) == config.currentChatObject) {
4128 num = n.value;
4129 numberExist = true;
4130 break;
4131 }
4132 }
4133 if (!numberExist) {
4134 userSelect.append("<option value='" + HTMLEncode(num) + "' selected='selected'>" + HTMLEncode(num) + "</option>");
4135 }
4136 $("select.chosen-select-deselect").val(num).trigger("chosen:updated.chosen");
4137 switchPage('chat');
4138 config.dbMsgs = _.sortBy(config.dbMsgs, function (e) {
4139 return 0 - e.id;
4140 });
4141 var draftIds = [];
4142 var dbMsgsTmp = [];
4143 var dbMsgsTmpIds = [];
4144 var chatHasDraft = false;
4145 for (var i = config.dbMsgs.length - 1; i >= 0; i--) {
4146 var e = config.dbMsgs[i];
4147 if (_.indexOf(dbMsgsTmpIds, e.id) != -1) {
4148 continue;
4149 }
4150 if (getLastNumber(e.number, config.SMS_MATCH_LENGTH) == config.currentChatObject && _.isEmpty(e.groupId)) {
4151 e.isNew = false;
4152 e.errorText = '';
4153 e.targetName = '';
4154 if (e.tag == "0" || e.tag == "1") {
4155 $.tmpl("smsOtherTmpl", e).appendTo("#chatlist");
4156 dbMsgsTmpIds.push(e.id);
4157 dbMsgsTmp.push(e);
4158 } else if (e.tag == "2" || e.tag == "3") {
4159 $.tmpl("smsMeTmpl", e).appendTo("#chatlist");
4160 dbMsgsTmpIds.push(e.id);
4161 dbMsgsTmp.push(e);
4162 } else if (e.tag == "4") {
4163 draftIds.push(e.id);
4164 $("#chat-input", "#smsChatRoom").val(e.content).removeAttr('data-trans');
4165 updateChatInputWordLength();
4166 chatHasDraft = true;
4167 }
4168 } else {
4169 dbMsgsTmpIds.push(e.id);
4170 dbMsgsTmp.push(e);
4171 }
4172 }
4173 $("#chatlist").translate();
4174 if (chatHasDraft) {
4175 $("#chosenUser", "#smsChatRoom").show();
4176 $("#chosenUser1", "#smsChatRoom").addClass("hide");
4177 } else {
4178 $("#chosenUser", "#smsChatRoom").hide();
4179 $("#chosenUser1", "#smsChatRoom").removeClass("hide").html(HTMLEncode(name));
4180 }
4181 config.dbMsgs = dbMsgsTmp.reverse();
4182 if (draftIds.length > 0) {
4183 deleteDraftSms(draftIds, [num]);
4184 } else {
4185 checkSmsCapacityAndAlert();
4186 }
4187
4188 checkSimStatusForSend();
4189 gotoBottom();
4190 chatRoomInLoading = false;
4191 };
4192
4193 function checkSmsCapacityAndAlert() {
4194 var capabilityContainer = $("#smsCapability");
4195 updateSmsCapabilityStatus(capabilityContainer);
4196 addTimeout(function () {
4197 if (!hasCapability) {
4198 showAlert("sms_capacity_is_full_for_send");
4199 }
4200 }, 2000);
4201 }
4202
4203 cleanChatInput = function () {
4204 $("#chat-input", "#smsChatRoom").val($.i18n.prop("chat_input_placehoder")).attr("data-trans", "chat_input_placehoder");
4205 };
4206
4207 //设置为已读
4208 setAsRead = function (num) {
4209 var ids = [];
4210 $.each(config.dbMsgs, function (i, e) {
4211 if (getLastNumber(e.number, config.SMS_MATCH_LENGTH) == getLastNumber(num, config.SMS_MATCH_LENGTH) && e.isNew) {
4212 ids.push(e.id);
4213 e.isNew = false;
4214 }
4215 });
4216 if (ids.length > 0) {
4217 service.setSmsRead({
4218 ids: ids
4219 }, function (data) {
4220 if (data.result) {
4221 $("#smslist-item-" + getLastNumber(num, config.SMS_MATCH_LENGTH) + " .smslist-item-new-count").text("").addClass("hide");
4222 $("#smslist-item-" + getLastNumber(num, config.SMS_MATCH_LENGTH)).removeClass("font-weight-bold");
4223 $("#smslist-item-" + getLastNumber(num, config.SMS_MATCH_LENGTH) + " td:nth-child(2)").removeClass("font-weight-bold");
4224 }
4225 $.each(config.listMsgs, function (i, e) {
4226 if (e.number == num && e.newCount > 0) {
4227 e.newCount = 0;
4228 }
4229 });
4230 });
4231 }
4232 };
4233
4234 //转发按钮点击事件
4235 forwardClickHandler = function (id) {
4236 var selectedContact = syncSelectAndChosen($("select#chosenUserSelect"), $('.search-choice', '#chosenUserSelect_chosen'));
4237 var content = $("#chat-input", "#smsChatRoom").val();
4238 var hasContent = typeof content != "undefined" && content != '' && content != $.i18n.prop('chat_input_placehoder');
4239 if (hasContent) {
4240 saveDraftAction({
4241 content: content,
4242 numbers: selectedContact,
4243 isFromBack: true,
4244 noLoading: true
4245 });
4246 }
4247
4248 clearChatList();
4249 config.currentChatObject = null;
4250
4251 $("#chosenUser1", "#smsChatRoom").addClass("hide");
4252 $("#chosenUser", "#smsChatRoom").show();
4253 for (var j = 0; j < config.dbMsgs.length; j++) {
4254 if (config.dbMsgs[j].id == id) {
4255 var theChatInput = $("#chat-input", "#smsChatRoom");
4256 theChatInput.val(config.dbMsgs[j].content);
4257 setInsertPos(theChatInput[0], config.dbMsgs[j].content.length);
4258 }
4259 }
4260 updateChatInputWordLength();
4261 $("select.chosen-select-deselect").val("").trigger("chosen:updated.chosen");
4262 addTimeout(function () {
4263 $("#chosen-search-field-input").focus();
4264 }, 300);
4265 switchPage('chat');
4266 gotoBottom();
4267 };
4268
4269 //更新剩余字数
4270 updateChatInputWordLength = function () {
4271 var msgInput = $("#chat-input", "#smsChatRoom");
4272 var msgInputDom = msgInput[0];
4273 var strValue = msgInput.val();
4274 var encodeType = getEncodeType(strValue);
4275 var maxLength = encodeType.encodeType == 'UNICODE' ? 335 : 765;
4276 if (strValue.length + encodeType.extendLen > maxLength) {
4277 var scrollTop = msgInputDom.scrollTop;
4278 var insertPos = getInsertPos(msgInputDom);
4279 var moreLen = strValue.length + encodeType.extendLen - maxLength;
4280 var insertPart = strValue.substr(insertPos - moreLen > 0 ? insertPos - moreLen : 0, moreLen);
4281 var reversed = insertPart.split('').reverse();
4282 var checkMore = 0;
4283 var cutNum = 0;
4284 for (var i = 0; i < reversed.length; i++) {
4285 if (getEncodeType(reversed[i]).extendLen > 0) {
4286 checkMore += 2;
4287 } else {
4288 checkMore++;
4289 }
4290 if (checkMore >= moreLen) {
4291 cutNum = i + 1;
4292 break;
4293 }
4294 }
4295 var iInsertToStartLength = insertPos - cutNum;
4296 msgInputDom.value = strValue.substr(0, iInsertToStartLength) + strValue.substr(insertPos);
4297 if (msgInputDom.value.length > maxLength) {
4298 msgInputDom.value = msgInputDom.value.substr(0, maxLength);
4299 }
4300 setInsertPos(msgInputDom, iInsertToStartLength);
4301 msgInputDom.scrollTop = scrollTop;
4302 }
4303 var textLength = 0;
4304 var newValue = $(msgInputDom).val();
4305 var newEncodeType = {
4306 encodeType: 'GSM7_default',
4307 extendLen: 0
4308 };
4309 if (newValue != $.i18n.prop('chat_input_placehoder')) {
4310 newEncodeType = getEncodeType(newValue);
4311 }
4312 var newMaxLength = newEncodeType.encodeType == 'UNICODE' ? 335 : 765;
4313 var $inputCount = $("#inputcount", "#inputpanel");
4314 var $inputItemCount = $("#inputItemCount", "#inputpanel");
4315 if (newValue.length + newEncodeType.extendLen >= newMaxLength) {
4316 $inputCount.addClass("colorRed");
4317 $inputItemCount.addClass("colorRed");
4318 } else {
4319 $("#inputcount", "#inputpanel").removeClass("colorRed");
4320 $("#inputItemCount", "#inputpanel").removeClass("colorRed");
4321 }
4322 if ("" != newValue && $.i18n.prop('chat_input_placehoder') != newValue) {
4323 textLength = newValue.length + newEncodeType.extendLen;
4324 }
4325 $inputCount.html("(" + textLength + "/" + newMaxLength + ")");
4326 $inputItemCount.html("(" + getSmsCount(newValue) + "/5)");
4327 draftListener();
4328 };
4329
4330 //文档内容监听,判断是否修改过
4331 function draftListener() {
4332 var content = $("#chat-input", "#smsChatRoom").val();
4333 if (hasCapability) {
4334 var selectedContact = getSelectValFromChosen($('.search-choice', '#chosenUserSelect_chosen'));
4335 var noContactSelected = !selectedContact || selectedContact.length == 0;
4336 var hasContent = typeof content != "undefined" && content != '' && content != $.i18n.prop('chat_input_placehoder');
4337
4338 if (!hasContent) {
4339 config.resetContentModifyValue();
4340 return;
4341 }
4342 if (hasContent && !noContactSelected) {
4343 config.CONTENT_MODIFIED.modified = true;
4344 config.CONTENT_MODIFIED.message = 'sms_to_save_draft';
4345 config.CONTENT_MODIFIED.callback.ok = saveDraftAction;
4346 config.CONTENT_MODIFIED.callback.no = $.noop;
4347 config.CONTENT_MODIFIED.data = {
4348 content: $("#chat-input", "#smsChatRoom").val(),
4349 numbers: selectedContact
4350 };
4351 return;
4352 }
4353 if (hasContent && noContactSelected) {
4354 config.CONTENT_MODIFIED.modified = true;
4355 config.CONTENT_MODIFIED.message = 'sms_no_recipient';
4356 config.CONTENT_MODIFIED.callback.ok = $.noop;
4357 config.CONTENT_MODIFIED.callback.no = function () {
4358 // 返回true,页面保持原状
4359 return true;
4360 }; //$.noop;
4361 return;
4362 }
4363 } else {
4364 config.resetContentModifyValue();
4365 }
4366 }
4367
4368 //保存草稿回调动作
4369 function saveDraftAction(data) {
4370 var datetime = new Date();
4371 var params = {
4372 index: -1,
4373 currentTimeString: getCurrentTimeString(datetime),
4374 groupId: data.numbers.length > 1 ? datetime.getTime() : '',
4375 message: data.content,
4376 numbers: data.numbers
4377 };
4378 !data.noLoading && showLoading('waiting');
4379 service.saveSMS(params, function () {
4380 if (data.isFromBack) {
4381 getLatestDraftSms(data.numbers);
4382 !data.noLoading && successOverlay('sms_save_draft_success');
4383 } else {
4384 !data.noLoading && successOverlay('sms_save_draft_success');
4385 }
4386 }, function () {
4387 !data.noLoading && errorOverlay("sms_save_draft_failed")
4388 });
4389
4390 //获取最新的草稿信息
4391 function getLatestDraftSms(numbers) {
4392 service.getSMSMessages({
4393 page: 0,
4394 smsCount: 5,
4395 nMessageStoreType: 1,
4396 tags: 4,
4397 orderBy: "order by id desc"
4398 }, function (data) {
4399 if (data.messages && data.messages.length > 0) {
4400 var theGroupId = '',
4401 draftShowName = '',
4402 draftShowNameTitle = '',
4403 i = 0,
4404 drafts = [];
4405 for (; i < data.messages.length; i++) {
4406 var msg = data.messages[i];
4407 for (var k = 0; k < numbers.length; k++) {
4408 var num = numbers[k];
4409 if (getLastNumber(num, config.SMS_MATCH_LENGTH) == getLastNumber(msg.number, config.SMS_MATCH_LENGTH)) { //if (num.indexOf(msg.number) == 0) {
4410 msg.number = num;
4411 }
4412 }
4413 if (theGroupId != '' && theGroupId != msg.groupId) {
4414 break;
4415 }
4416 updateDBMsg(msg);
4417 if (msg.groupId == '') { // 单条草稿
4418 break;
4419 } else { // 多条草稿
4420 theGroupId = msg.groupId;
4421 var showName = getShowNameByNumber(msg.number);
4422 draftShowName += (i == 0 ? '' : ';') + showName;
4423 draftShowNameTitle += (i == 0 ? '' : ';') + showName;
4424 }
4425 drafts.push(msg);
4426 }
4427 if (theGroupId == '') { // 单条草稿
4428 var msg = data.messages[0];
4429 msg.hasDraft = true;
4430 updateMsgList(msg);
4431 } else { // 多条草稿
4432 var msg = data.messages[0];
4433 var len = 10;
4434 if (getEncodeType(draftShowName).encodeType == "UNICODE") {
4435 len = 10;
4436 }
4437 msg.draftShowNameTitle = draftShowNameTitle;
4438 msg.draftShowName = draftShowName.length > len ? draftShowName.substring(0, len) + "..." : draftShowName;
4439 msg.hasDraft = true;
4440 msg.totalCount = i;
4441 groupedDraftsObject[theGroupId] = drafts;
4442 updateMsgList(msg);
4443 }
4444 tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
4445 }
4446 }, function () {
4447 // do nothing
4448 });
4449 }
4450 }
4451
4452 //点击群聊草稿进入草稿发送页面 在进入的过程中会先删掉草稿
4453 draftSmsItemClickHandler = function (groupId) {
4454 if (chatRoomInLoading) {
4455 return false;
4456 }
4457 chatRoomInLoading = true;
4458 var msgs = groupedDraftsObject[groupId];
4459 var numbers = [];
4460 var ids = [];
4461 for (var i = 0; msgs && i < msgs.length; i++) {
4462 numbers.push(getLastNumber(msgs[i].number, config.SMS_MATCH_LENGTH));
4463 ids.push(msgs[i].id + '');
4464 }
4465 $("#chosenUser", "#smsChatRoom").show();
4466 $("#chosenUser1", "#smsChatRoom").addClass("hide").html('');
4467 $("select.chosen-select-deselect").val(numbers).trigger("chosen:updated.chosen");
4468 $("#chat-input", "#smsChatRoom").val(msgs[0].content);
4469 updateChatInputWordLength();
4470 clearChatList();
4471 switchPage('chat');
4472 draftListener();
4473 gotoBottom();
4474 chatRoomInLoading = false;
4475 deleteMultiDraftSms(ids, groupId);
4476 };
4477
4478 //按列表条目删除短消息
4479 deletePhoneMessageClickHandler = function (num) {
4480 showConfirm("confirm_sms_delete", function () {
4481 showLoading('deleting');
4482 var ids = [];
4483 $.each(config.dbMsgs, function (i, e) {
4484 if (e.number == num) {
4485 ids.push(e.id);
4486 }
4487 });
4488 service.deleteMessage({
4489 ids: ids
4490 }, function (data) {
4491 $("#smslist-item-" + getLastNumber(num, config.SMS_MATCH_LENGTH)).hide().remove();
4492 synchSmsList([num], ids);
4493 successOverlay();
4494 tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
4495 }, function (error) {
4496 errorOverlay(error.errorText);
4497 });
4498 });
4499 };
4500
4501 //同步短信列表数据
4502 synchSmsList = function (nums, ids) {
4503 if (nums && nums.length > 0) {
4504 config.listMsgs = $.grep(config.listMsgs, function (n, i) {
4505 return $.inArray(n.number, nums) == -1;
4506 });
4507 }
4508 if (ids && ids.length > 0) {
4509 var dbMsgsTmp = [];
4510 $.each(config.dbMsgs, function (i, e) {
4511 if ($.inArray(e.id, ids) == -1) {
4512 dbMsgsTmp.push(e);
4513 }
4514 });
4515 config.dbMsgs = dbMsgsTmp;
4516 }
4517 };
4518
4519 //确定最后一条短消息距离顶部的距离
4520 function fixScrollTop() {
4521 var items = $(".smslist-item");
4522 var lastOne;
4523 if (items.length > 0) {
4524 lastOne = items[items.length - 1];
4525 } else {
4526 lastOne = items[0];
4527 }
4528 lastItemOffsetTop = lastOne ? lastOne.offsetTop : 600;
4529 }
4530
4531 function loadData() {
4532 if (ready && !scrolling && lastItemOffsetTop < ($(window).scrollTop() + $(window).height())
4533 && $(".smslist-item").length != config.listMsgs.length) {
4534 scrolling = true;
4535 addTimeout(function () {
4536 removeChecked("smslist-checkAll");
4537 changeShownMsgs();
4538 fixScrollTop();
4539 scrolling = false;
4540 }, 100);
4541 }
4542 }
4543
4544 function stopNavigation() {
4545 disableBtn($('#btn-back'));
4546 $('a', '#left').bind("click", function () {
4547 return false;
4548 });
4549 $('a', '#list-nav').bind("click", function () {
4550 return false;
4551 });
4552 }
4553
4554 function restoreNavigation() {
4555 enableBtn($('#btn-back'));
4556 $('a', '#left').unbind("click");
4557 $('a', '#list-nav').unbind("click");
4558 }
4559
4560 function searchTable(key) {
4561 key = $.trim(key);
4562 var $trs = $('tr', '#smslist-table'),
4563 trLength = $trs.length;
4564 if (key == '') {
4565 $trs.show();
4566 return false;
4567 }
4568 $trs.hide();
4569 while (trLength) {
4570 var $tr = $($trs[trLength - 1]),
4571 $tds = $('td', $tr),
4572 tdLength = $tds.length;
4573 while (tdLength - 1) {
4574 var $td = $($tds[tdLength - 1]);
4575 if ($td.text().toLowerCase().indexOf(key.toLowerCase()) != -1) {
4576 $tr.show();
4577 break;
4578 }
4579 tdLength--;
4580 }
4581 trLength--;
4582 }
4583
4584 addTimeout(function () {
4585 $(":checkbox:checked", "#addPhonebookContainer").removeAttr('checked');
4586 vm.selectedItemIds([]);
4587 vm.freshStatus($.now());
4588 renderCheckbox();
4589 }, 300);
4590 return true;
4591 }
4592 updateSearchValue = function (key) {
4593 if (key == "" || key == $.i18n.prop("search")) {
4594 return true;
4595 }
4596 searchTable(key);
4597 };
4598 //清除搜索关键字事件
4599 clearSearchKey = function () {
4600 updateSearchValue($.i18n.prop("search"));
4601 $("#searchInput").addClass("ko-grid-search-txt-default").attr("data-trans", "search");
4602 };
4603 //点击搜索输入框事件
4604 searchTextClick = function () {
4605 var searchText = $("#searchInput");
4606 if (searchText.hasClass("ko-grid-search-txt-default")) {
4607 updateSearchValue("");
4608 searchText.val("");
4609 searchText.removeClass("ko-grid-search-txt-default").removeAttr("data-trans");
4610 }
4611 };
4612 //离开搜索输入框事件
4613 searchTextBlur = function () {
4614 var txt = $.trim($("#searchInput").val()).toLowerCase();
4615 if (txt == "") {
4616 clearSearchKey();
4617 }
4618 };
4619
4620 window.smsUtil = {
4621 changeLocationHandler: function (ele) {
4622 if ($(ele).val() == 'sim') {
4623 window.location.hash = '#msg_sim';
4624 } else {
4625 window.location.hash = '#msg_main';
4626 }
4627 }
4628 };
4629
4630 return {
4631 init: init
4632 };
4633});
4634
4635define("sms_set","underscore jquery knockout set service".split(" "),
4636 function (_, $, ko, config, service) {
4637
4638 var validityModes = _.map(config.SMS_VALIDITY, function (item) {
4639 return new Option(item.name, item.value);
4640 });
4641
4642 function SmsSetViewMode() {
4643 var target = this;
4644 var setting = getSmsSetting();
4645 target.modes = ko.observableArray(validityModes);
4646 target.selectedMode = ko.observable(setting.validity);
4647 target.centerNumber = ko.observable(setting.centerNumber);
4648 target.deliveryReport = ko.observable(setting.deliveryReport);
4649
4650 target.clear = function () {
4651 init();
4652 clearValidateMsg();
4653 };
4654
4655 target.save = function () {
4656 showLoading('waiting');
4657 var params = {};
4658 params.validity = target.selectedMode();
4659 params.centerNumber = target.centerNumber();
4660 params.deliveryReport = target.deliveryReport();
4661 service.setSmsSetting(params, function (result) {
4662 if (result.result == "success") {
4663 successOverlay();
4664 } else {
4665 errorOverlay();
4666 }
4667 });
4668 };
4669 }
4670
4671 //获取短信设置参数
4672
4673 function getSmsSetting() {
4674 return service.getSmsSetting();
4675 }
4676
4677 function init() {
4678 var container = $('#container');
4679 ko.cleanNode(container[0]);
4680 var vm = new SmsSetViewMode();
4681 ko.applyBindings(vm, container[0]);
4682 $('#smsSettingForm').validate({
4683 submitHandler: function () {
4684 vm.save();
4685 },
4686 rules: {
4687 txtCenterNumber: "sms_service_center_check"
4688 }
4689 });
4690 }
4691
4692 return {
4693 init: init
4694 };
4695});
4696
4697define("sms_sim_messages","jquery knockout set service".split(" "),
4698 function ($, ko, config, service) {
4699 var simMsgListTmpl = null;
4700 //每页记录条数
4701 var perPage = 200;
4702
4703 //获取短信分页记录
4704 function getSMSMessages() {
4705 return service.getSMSMessages({
4706 page: 0,
4707 smsCount: perPage,
4708 nMessageStoreType: 0,
4709 tags: 10,
4710 orderBy: "order by id desc"
4711 }, function (data) {
4712 tryToDisableCheckAll($("#simMsgList-checkAll"), data.messages.length);
4713 dealPhoneBooks(data.messages);
4714 }, function (data) {
4715 dealPhoneBooks([]);
4716 });
4717 }
4718
4719 //短信显示联系人名字,并将结果显示在UI
4720 function dealPhoneBooks(messages) {
4721 $.each(messages, function (j, n) {
4722 n.itemId = getLastNumber(n.number, config.SMS_MATCH_LENGTH);
4723 for (var i = 0; i < config.phonebook.length; i++) {
4724 var person = config.phonebook[i];
4725 if (n.itemId == getLastNumber(person.pbm_number, config.SMS_MATCH_LENGTH)) {
4726 n.name = person.pbm_name;
4727 break;
4728 }
4729 }
4730 });
4731 renderSimMessageList(messages);
4732 }
4733
4734 //清楚短信列表内容
4735 cleanSimSmsList = function () {
4736 $("#simMsgList_container").empty();
4737 };
4738
4739 //将短信显示结果显示在UI
4740 function renderSimMessageList(messages) {
4741 if (simMsgListTmpl == null) {
4742 simMsgListTmpl = $.template("simMsgListTmpl", $("#simMsgListTmpl"));
4743 }
4744 cleanSimSmsList();
4745 $("#simMsgList_container").html($.tmpl("simMsgListTmpl", {
4746 data: messages
4747 }));
4748 hideLoading();
4749 }
4750
4751 //初始化电话本信息
4752 function initPhoneBooks(cb) {
4753 service.getPhoneBooks({
4754 page: 0,
4755 data_per_page: 2000,
4756 orderBy: "name",
4757 isAsc: true
4758 }, function (books) {
4759 if ($.isArray(books.pbm_data) && books.pbm_data.length > 0) {
4760 config.phonebook = books.pbm_data;
4761 } else {
4762 config.phonebook = [];
4763 }
4764 cb();
4765 }, function () {
4766 errorOverlay();
4767 });
4768 }
4769
4770 function simSmsViewMode() {
4771 var self = this;
4772 start();
4773 }
4774
4775 //短信删除事件处理
4776 deleteSelectedSimMsgClickHandler = function () {
4777 var checkbox = $("input[name=msgId]:checked", "#simMsgList_container");
4778 var msgIds = [];
4779 for (var i = 0; i < checkbox.length; i++) {
4780 msgIds.push($(checkbox[i]).val());
4781 }
4782 if (msgIds.length == 0) {
4783 return false;
4784 }
4785 showConfirm("confirm_sms_delete", function () {
4786 showLoading('deleting');
4787 service.deleteMessage({
4788 ids: msgIds
4789 }, function (data) {
4790 removeChecked("simMsgList-checkAll");
4791 disableBtn($("#simMsgList-delete"));
4792 var idsForDelete = "";
4793 checkbox.each(function (i, n) {
4794 idsForDelete += ".simMsgList-item-class-" + $(n).val() + ",";
4795 });
4796 if (idsForDelete.length > 0) {
4797 $(idsForDelete.substring(0, idsForDelete.length - 1)).hide().remove();
4798 }
4799 tryToDisableCheckAll($("#simMsgList-checkAll"), $(".smslist-item", "#simMsgList_container").length);
4800 successOverlay();
4801 }, function (error) {
4802 errorOverlay(error.errorText);
4803 });
4804 //删除短信后需要刷新列表
4805 updateSimSmsCapabilityStatus($("#simSmsCapability"));
4806 });
4807 };
4808 //将被checked的条目添加到self.checkedItem中,用于在滚动还原checkbox
4809 function checkboxClickHandler() {
4810 if (getSelectedItemSize() == 0) {
4811 disableBtn($("#simMsgList-delete"));
4812 } else {
4813 enableBtn($("#simMsgList-delete"));
4814 }
4815 }
4816
4817 //获取已选择的条目
4818 function getSelectedItemSize() {
4819 return $("input:checkbox:checked", '#simMsgList_container').length;
4820 }
4821
4822 //模块开始,检查电话本及短信状态并加装页码数据
4823 function start() {
4824 showLoading('waiting');
4825 var getSMSReady = function () {
4826 service.getSMSReady({}, function (data) {
4827 if (data.sms_cmd_status_result == "2") {
4828 hideLoading();
4829 showAlert("sms_init_fail");
4830 } else if (data.sms_cmd_status_result == "1") {
4831 addTimeout(function () {
4832 getSMSReady();
4833 }, 1000);
4834 } else {
4835 if (!config.HAS_PHONEBOOK) {
4836 initSMSList(config.HAS_PHONEBOOK);
4837 } else {
4838 getPhoneBookReady();
4839 }
4840 }
4841 });
4842 };
4843
4844 var getPhoneBookReady = function () {
4845 service.getPhoneBookReady({}, function (data) {
4846 if (data.pbm_init_flag == "6") {
4847 initSMSList(false);
4848 } else if (data.pbm_init_flag != "0") {
4849 addTimeout(function () {
4850 getPhoneBookReady();
4851 }, 1000);
4852 } else {
4853 initSMSList(config.HAS_PHONEBOOK);
4854 }
4855 });
4856 };
4857
4858 var initSMSList = function (isPbmInitOK) {
4859 if (isPbmInitOK) {
4860 initPhoneBooks(function () {
4861 getSMSMessages();
4862 });
4863 } else {
4864 config.phonebook = [];
4865 getSMSMessages();
4866 }
4867 };
4868 getSMSReady();
4869 initSimSmsCapability();
4870 }
4871
4872 //初始化短信容量状态
4873 function initSimSmsCapability() {
4874 var capabilityContainer = $("#simSmsCapability");
4875 updateSimSmsCapabilityStatus(capabilityContainer);
4876 addInterval(function () {
4877 updateSimSmsCapabilityStatus(capabilityContainer);
4878 }, 5000);
4879 }
4880
4881 //更新短信容量状态
4882 function updateSimSmsCapabilityStatus(capabilityContainer) {
4883 service.getSmsCapability({}, function (capability) {
4884 if (capabilityContainer != null) {
4885 capabilityContainer.text("(" + capability.simUsed + "/" + capability.simTotal + ")");
4886 }
4887 });
4888 }
4889
4890 //清除搜索关键字事件
4891 clearSearchKey = function () {
4892 updateSearchValue($.i18n.prop("search"));
4893 $("#searchInput").addClass("ko-grid-search-txt-default").attr("data-trans", "search");
4894 };
4895 //点击搜索输入框事件
4896 searchTextClick = function () {
4897 var searchText = $("#searchInput");
4898 if (searchText.hasClass("ko-grid-search-txt-default")) {
4899 updateSearchValue("");
4900 searchText.val("");
4901 searchText.removeClass("ko-grid-search-txt-default").removeAttr("data-trans");
4902 }
4903 };
4904 //离开搜索输入框事件
4905 searchTextBlur = function () {
4906 var txt = $.trim($("#searchInput").val()).toLowerCase();
4907 if (txt == "") {
4908 clearSearchKey();
4909 }
4910 };
4911
4912 updateSearchValue = function (key) {
4913 if (key == "" || key == $.i18n.prop("search")) {
4914 return true;
4915 }
4916 searchTable(key);
4917 }
4918
4919 function searchTable(key) {
4920 key = $.trim(key);
4921 var $trs = $('tr', '#smslist-table'),
4922 trLength = $trs.length;
4923 if (key == '') {
4924 $trs.show();
4925 return false;
4926 }
4927 $trs.hide();
4928 while (trLength) {
4929 var $tr = $($trs[trLength - 1]),
4930 $tds = $('td', $tr),
4931 tdLength = $tds.length;
4932 while (tdLength - 1) {
4933 var $td = $($tds[tdLength - 1]);
4934 if ($td.text().toLowerCase().indexOf(key.toLowerCase()) != -1) {
4935 $tr.show();
4936 break;
4937 }
4938 tdLength--;
4939 }
4940 trLength--;
4941 }
4942
4943 addTimeout(function () {
4944 $(":checkbox:checked", "#addPhonebookContainer").removeAttr('checked');
4945 vm.selectedItemIds([]);
4946 vm.freshStatus($.now());
4947 renderCheckbox();
4948 }, 300);
4949 return true;
4950 }
4951
4952 //点击短信列表条目
4953 simsmsItemClickHandler = function (tag, id, num) {
4954 if (tag == "1") {
4955 var ids = [];
4956 ids.push(id);
4957 service.setSmsRead({
4958 ids: ids
4959 }, function (data) {
4960 if (data.result) {
4961 $(".simMsgList-item-class-" + id, "#simMsgTableContainer").removeClass('font-weight-bold');
4962 }
4963 });
4964 }
4965 }
4966
4967 //页面事件绑定
4968 function initEventBind() {
4969 $(".smslist-item-msg", "#simMsgTableContainer").die().live("click", function () {
4970 var $this = $(this).addClass('showFullHeight');
4971 $('.smslist-item-msg.showFullHeight', '#simMsgTableContainer').not($this).removeClass('showFullHeight');
4972 });
4973 $("#simMsgList_container p.checkbox, #simMsgListForm #simMsgList-checkAll").die().live("click", function () {
4974 checkboxClickHandler();
4975 });
4976 $("#searchInput").die().live('blur', function () {
4977 searchTextBlur();
4978 }).live('keyup', function () {
4979 updateSearchValue($("#searchInput").val());
4980 });
4981 }
4982
4983 //模块初始化开始
4984 function init() {
4985 var container = $('#container');
4986 ko.cleanNode(container[0]);
4987 var vm = new simSmsViewMode();
4988 ko.applyBindings(vm, container[0]);
4989 initEventBind();
4990 }
4991
4992 window.smsUtil = {
4993 changeLocationHandler: function (ele) {
4994 if ($(ele).val() == 'sim') {
4995 window.location.hash = '#msg_sim';
4996 } else {
4997 window.location.hash = '#msg_main';
4998 }
4999 }
5000 };
5001
5002 return {
5003 init: init
5004 };
5005});