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