[T106][ZXW-22]7520V3SCV2.01.01.02P42U09_VEC_V0.8_AP_VEC origin source commit
Change-Id: Ic6e05d89ecd62fc34f82b23dcf306c93764aec4b
diff --git a/ap/app/zte_webui/js/sim_device.js b/ap/app/zte_webui/js/sim_device.js
new file mode 100755
index 0000000..06fbd32
--- /dev/null
+++ b/ap/app/zte_webui/js/sim_device.js
@@ -0,0 +1,5005 @@
+define("sim_abnormal","jquery knockout service set main opmode".split(" "),
+ function ($, ko, service, config, home, opmode) {
+
+ function init() {
+ var container = $('#container')[0];
+ ko.cleanNode(container);
+ var vm = new simViewMode();
+ ko.applyBindings(vm, container);
+
+ $('#frmPUK').validate({
+ submitHandler: function () {
+ vm.enterPUK();
+ },
+ rules: {
+ txtNewPIN: "pin_check",
+ txtConfirmPIN: {
+ equalToPin: "#txtNewPIN"
+ },
+ txtPUK: "puk_check"
+ }
+ });
+
+ $('#frmPIN').validate({
+ submitHandler: function () {
+ vm.enterPIN();
+ },
+ rules: {
+ txtPIN: "pin_check"
+ }
+ });
+ }
+
+ function simViewMode() {
+ var target = this;
+ var staInfo = service.getStatusInfo();
+ var curCableMode = "PPPOE" == staInfo.blc_wan_mode || "AUTO_PPPOE" == staInfo.blc_wan_mode;
+ target.hasRj45 = config.RJ45_SUPPORT;
+ target.hasSms = config.HAS_SMS;
+ target.hasPhonebook = config.HAS_PHONEBOOK;
+ target.isSupportSD = config.SD_CARD_SUPPORT;
+ if (config.WIFI_SUPPORT_QR_SWITCH) {
+ var wifiInfo = service.getWifiBasic();
+ target.showQRCode = config.WIFI_SUPPORT_QR_CODE && wifiInfo.show_qrcode_flag;
+ } else {
+ target.showQRCode = config.WIFI_SUPPORT_QR_CODE;
+ }
+ target.qrcodeSrc = './pic/qrcode_ssid_wifikey.png?_=' + $.now();
+ target.hasParentalControl = ko.observable(config.HAS_PARENTAL_CONTROL && curCableMode);
+ target.pageState = {
+ NO_SIM: 0,
+ WAIT_PIN: 1,
+ WAIT_PUK: 2,
+ PUK_LOCKED: 3,
+ LOADING: 4
+ };
+ target.isHomePage = ko.observable(false);
+ if (window.location.hash == "#main") {
+ target.isHomePage(true);
+ }
+
+ var info = service.getLoginData();
+ target.PIN = ko.observable();
+ target.newPIN = ko.observable();
+ target.confirmPIN = ko.observable();
+ target.PUK = ko.observable();
+ target.pinNumber = ko.observable(info.pinnumber);
+ target.pukNumber = ko.observable(info.puknumber);
+
+ var state = computePageState(info);
+ target.page = ko.observable(state);
+ if (state == target.pageState.LOADING) {
+ addTimeout(refreshPage, 500);
+ }
+ target.showOpModeWindow = function () {
+ showSettingWindow("change_mode", "opmode_popup", "opmode_popup", 400, 300, function () {});
+ };
+ target.isLoggedIn = ko.observable(false);
+ target.enableFlag = ko.observable(false);
+ //更新当前工作模式状态信息
+ target.refreshOpmodeInfo = function () {
+ var staInfo = service.getStatusInfo();
+ target.isLoggedIn(staInfo.isLoggedIn);
+
+ if (!curCableMode && checkCableMode(staInfo.blc_wan_mode)) { //如果有线,则重新加载
+ 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) {
+ window.location.reload();
+ }
+ }
+
+ curCableMode = checkCableMode(staInfo.blc_wan_mode);
+ target.hasParentalControl(config.HAS_PARENTAL_CONTROL && curCableMode);
+ if (curCableMode && staInfo.ethWanMode.toUpperCase() == "DHCP") {
+ target.enableFlag(true);
+ } else if ((!curCableMode && staInfo.connectStatus != "ppp_disconnected") || (curCableMode && staInfo.rj45ConnectStatus != "idle" && staInfo.rj45ConnectStatus != "dead")) {
+ target.enableFlag(false);
+ } else {
+ target.enableFlag(true);
+ }
+ var mode = (staInfo.blc_wan_mode == "AUTO_PPP" || staInfo.blc_wan_mode == "AUTO_PPPOE") ? "AUTO" : staInfo.blc_wan_mode;
+ var currentOpMode = "";
+ switch (mode) {
+ case "PPP":
+ currentOpMode = "opmode_gateway";
+ break;
+ case "PPPOE":
+ currentOpMode = "opmode_cable";
+ break;
+ case "AUTO":
+ currentOpMode = "opmode_auto";
+ break;
+ default:
+ break;
+ }
+ $("#opmode").attr("data-trans", currentOpMode).text($.i18n.prop(currentOpMode));
+ }
+ //刷新页面状态
+ function refreshPage() {
+ var data = service.getLoginData();
+ var state = computePageState(data);
+ if (state == target.pageState.LOADING) {
+ addTimeout(refreshPage, 500);
+ } else {
+ target.page(state);
+ target.pinNumber(data.pinnumber);
+ target.pukNumber(data.puknumber);
+ }
+ }
+ //输入PUK设置新PIN事件处理
+ target.enterPUK = function () {
+ showLoading();
+ target.page(target.pageState.LOADING);
+ var newPIN = target.newPIN();
+ var confirmPIN = target.confirmPIN();
+ var params = {};
+ params.PinNumber = newPIN;
+ params.PUKNumber = target.PUK();
+ service.enterPUK(params, function (data) {
+ if (!data.result) {
+ hideLoading();
+ if (target.pukNumber() == 2) {
+ showAlert("last_enter_puk", function () {
+ refreshPage();
+ });
+ } else {
+ showAlert("puk_error", function () {
+ refreshPage();
+ if (target.page() == target.pageState.PUK_LOCKED) {
+ hideLoading();
+ }
+ });
+ }
+ target.PUK('');
+ target.newPIN('');
+ target.confirmPIN('');
+ } else {
+ refreshPage();
+ if (target.page() == target.pageState.PUK_LOCKED) {
+ hideLoading();
+ }
+ }
+ });
+ };
+ //验证输入PIN事件处理
+ target.enterPIN = function () {
+ showLoading();
+ target.page(target.pageState.LOADING);
+ var pin = target.PIN();
+ service.enterPIN({
+ PinNumber: pin
+ }, function (data) {
+ if (!data.result) {
+ hideLoading();
+ if (target.pinNumber() == 2) {
+ showAlert("last_enter_pin", function () {
+ refreshPage();
+ });
+ } else {
+ showAlert("pin_error", function () {
+ refreshPage();
+ });
+ }
+ target.PIN('');
+ }
+ refreshPage();
+ if (target.page() == target.pageState.WAIT_PUK) {
+ hideLoading();
+ }
+ });
+ };
+
+ if (target.hasRj45) {
+ target.refreshOpmodeInfo();
+ addInterval(function () {
+ target.refreshOpmodeInfo();
+ }, 1000);
+ }
+ //根据登录状态和SIM卡状态设置页面状态
+ function computePageState(data) {
+ var state = data.modem_main_state;
+ if (state == "modem_undetected" || state == "modem_sim_undetected" || state == "modem_sim_destroy") {
+ return target.pageState.NO_SIM;
+ } else if (state == "modem_waitpin") {
+ return target.pageState.WAIT_PIN;
+ } else if ((state == "modem_waitpuk" || data.pinnumber == 0) && (data.puknumber != 0)) {
+ return target.pageState.WAIT_PUK;
+ } else if ((data.puknumber == 0 || state == "modem_sim_destroy") && state != "modem_sim_undetected" && state != "modem_undetected") {
+ return target.pageState.PUK_LOCKED;
+ } else if ($.inArray(state, config.TEMPORARY_MODEM_MAIN_STATE) != -1) {
+ return target.pageState.LOADING;
+ } else {
+ location.reload();
+ }
+ }
+
+ }
+
+ return {
+ init: init
+ };
+});
+
+define("ota_update", "jquery jq_fileinput service knockout set statusBar".split(" "),
+
+ function ($, fileinput, service, ko, config, status) {
+
+ function FotaUpdateViewModel() {
+ var target = this;
+ var setting = service.getOTAUpdateSetting();
+
+ target.allowRoamingUpdate = ko.observable(setting.allowRoamingUpdate);
+ target.hasDdns = config.DDNS_SUPPORT;
+ target.hasUpdateCheck = config.HAS_UPDATE_CHECK;
+ target.hasUssd = config.HAS_USSD;
+ target.isDataCard = config.PRODUCT_TYPE == 'DATACARD';
+ target.lastCheckTime = ko.observable('');
+ target.updateIntervalDay = ko.observable(setting.updateIntervalDay);
+ target.updateMode = ko.observable(setting.updateMode);
+ target.updateType = ko.observable(service.getUpdateType().update_type);
+
+
+ // 自动检测设置按钮事件
+ target.apply = function () {
+ var updateSettingInfo = {
+ updateMode: target.updateMode(),
+ updateIntervalDay: target.updateIntervalDay(),
+ allowRoamingUpdate: target.allowRoamingUpdate()
+ };
+ showLoading();
+ service.setOTAUpdateSetting(updateSettingInfo, function (settingInfo) {
+ if (settingInfo && settingInfo.result == "success") {
+ setting.allowRoamingUpdate = target.allowRoamingUpdate();
+ successOverlay();
+ } else {
+ errorOverlay();
+ }
+ });
+ };
+
+
+ // 按钮【检测】点击事件处理接口
+ target.checkNewVersion = function () {
+ var newVersionState = service.getNewVersionState();
+ if(newVersionState.fota_package_already_download == "yes"){
+ showAlert("fota_package_already_download");
+ return;
+ }
+
+ if(config.UPGRADE_TYPE=="FOTA"){
+ var checkingState = ["checking"];
+ if ($.inArray(newVersionState.fota_current_upgrade_state, checkingState) != -1) {
+ showAlert("ota_update_running");
+ return;
+ }
+ }
+
+ // FOTA开始下载前,判断当前是否已经在下载过程中,防止错误清空fota_new_version_state状态
+ var statusInfo = service.getStatusInfo();
+ if (newVersionState.fota_current_upgrade_state == "prepare_install") {
+ showInfo('ota_download_success');
+ return;
+ }
+
+ var upgradingState = ["downloading", "confirm_dowmload"];
+ if ($.inArray(newVersionState.fota_current_upgrade_state, upgradingState) != -1) {
+ status.showOTAAlert();
+ return;
+ }
+
+ if (statusInfo.roamingStatus) {
+ showConfirm("ota_check_roaming_confirm", function () {
+ checkNewVersion();
+ });
+ } else {
+ checkNewVersion();
+ }
+ // 检测是否有新版本
+ function checkNewVersion() {
+ showLoading("ota_new_version_checking");
+ function checkNewVersionResult() {
+ var result = service.getNewVersionState();
+ if (result.hasNewVersion) {
+ if(result.fota_new_version_state == "already_has_pkg"&&result.fota_current_upgrade_state !="prepare_install"&&result.fota_current_upgrade_state !="low_battery")
+ {
+ addTimeout(checkNewVersionResult, 1000);
+ }
+ else
+ {
+ status.showOTAAlert();
+ }
+ } else if (result.fota_new_version_state == "no_new_version") {
+ showAlert("ota_no_new_version");
+ }else if (result.fota_new_version_state == "check_failed" ) {
+ errorOverlay("ota_check_fail");
+ } else if ( result.fota_new_version_state == "bad_network"){
+ errorOverlay("ota_connect_server_failed");
+ }else {
+ addTimeout(checkNewVersionResult, 1000);
+ }
+ }
+
+ service.setUpgradeSelectOp({selectOp: 'check'}, function (result) {
+ if (result.result == "success") {
+ checkNewVersionResult();
+ } else {
+ errorOverlay();
+ }
+ });
+ }
+ };
+
+
+
+ // 确认按钮状态:可用/灰化
+ target.fixPageEnable = function () {
+ var connectStatusInfo = service.getStatusInfo();
+ var opModeData = service.getOpMode();
+ if (checkConnectedStatus(connectStatusInfo.connectStatus, opModeData.rj45_state, connectStatusInfo.connectWifiStatus)) {
+ enableBtn($("#btnCheckNewVersion"));
+ } else {
+ disableBtn($("#btnCheckNewVersion"));
+ }
+ };
+
+ target.clickAllowRoamingUpdate = function () {
+ var checkedbox = $("#chkUpdateRoamPermission:checked");
+ if (checkedbox && checkedbox.length == 0) {
+ target.allowRoamingUpdate("1");
+ } else {
+ target.allowRoamingUpdate("0");
+ }
+ };
+
+ service.getOTAlastCheckTime({}, function(info){
+ target.lastCheckTime(info.dm_last_check_time);
+ });
+
+ }
+ // 获取升级文件大小
+ function getFileSize(object){
+ var fileLenth = 0;
+ var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
+ if (isIE) { //如果是ie
+ var objectValue = object.value;
+ try {
+ var fso = new ActiveXObject("Scripting.FileSystemObject");
+ fileLenth = parseInt(fso.GetFile(objectValue).size);
+ } catch (e) {
+ fileLenth = 1;
+ }
+ }else{ //对于非IE获得要上传文件的大小
+ try{
+ fileLenth = parseInt(object.files[0].size);
+ }catch (e) {
+ fileLenth = 1; //获取不到取-1
+ }
+ }
+ return fileLenth/1024/1024;
+ }
+
+ function init() {
+ var container = $('#container')[0];
+ ko.cleanNode(container);
+ var fwVm = new FotaUpdateViewModel();
+ ko.applyBindings(fwVm, container);
+
+ if(fwVm.updateType() == "mifi_fota"){
+ fwVm.fixPageEnable();
+ addInterval(function () {
+ fwVm.fixPageEnable();
+ }, 1000);
+ }else{
+ if ($(".customfile").length == 0) {
+ $("#fileField").customFileInput();
+ }
+ }
+
+ $('#frmOTAUpdate').validate({
+ submitHandler: function () {
+ fwVm.apply();
+ }
+ });
+ }
+
+ return {
+ init: init
+ };
+});
+
+// SD卡 模块
+
+define("sd", "jquery set service knockout".split(" ") , function($, config, service, ko) {
+
+ // 基目录。感觉此根目录不显示给用户会更友好
+ var basePath = config.SD_BASE_PATH;
+
+ function SDCardViewModel() {
+ var target = this;
+ var SDConfiguration = service.getSDConfiguration();
+
+ target.selectedMode = ko.observable(SDConfiguration.sd_mode);
+ target.orignalMode = ko.observable(SDConfiguration.sd_mode);
+ target.sdStatus = ko.observable(SDConfiguration.sd_status);
+ target.orignalSdStatus = ko.observable(SDConfiguration.sd_status);
+ target.sdStatusInfo = ko.observable("sd_card_status_info_" + SDConfiguration.sd_status);
+ target.selectedShareEnable = ko.observable(SDConfiguration.share_status);
+ target.selectedFileToShare = ko.observable(SDConfiguration.file_to_share);
+ target.selectedAccessType = ko.observable(SDConfiguration.share_auth);
+
+ var path = SDConfiguration.share_file.substring(basePath.length);
+
+ target.pathToShare = ko.observable(path);
+ target.isInvalidPath = ko.observable(false);
+ target.checkEnable = ko.observable(true);
+
+
+ addInterval(function(){
+ target.refreshSimStatus();
+ }, 3000);
+
+ // 检查共享路径是否有效
+ target.checkPathIsValid = ko.computed(function () {
+ if (target.orignalMode() == 0 && target.selectedShareEnable() == '1' && target.selectedFileToShare() == '0'
+ && target.pathToShare() != '' && target.pathToShare() != '/') {
+ service.checkFileExists({
+ "path": basePath + target.pathToShare()
+ }, function (info) {
+ if (info.status != "exist") {
+ target.isInvalidPath(true);
+ } else {
+ target.isInvalidPath(false);
+ }
+ });
+ } else {
+ target.isInvalidPath(false);
+ }
+ });
+
+
+ target.disableApplyBtn = ko.computed(function(){
+ return target.selectedMode() == target.orignalMode() && target.selectedMode() == '1';
+ });
+
+ // 文件共享方式radio点击事件
+ target.fileToShareClickHandle = function(){
+ if(target.selectedFileToShare() == "1"){
+ target.pathToShare("/");
+ }
+ return true;
+ };
+
+ // T卡热插拔时状态监控,拔插卡重刷界面
+ target.refreshSimStatus = function(){
+ if(target.checkEnable()){
+ var SDConfiguration = service.getSDConfiguration();
+ if(SDConfiguration.sd_status && (SDConfiguration.sd_status != target.orignalSdStatus())){
+ if(SDConfiguration.sd_status != '1'){
+ target.sdStatusInfo("sd_card_status_info_" + SDConfiguration.sd_status);
+ target.sdStatus(SDConfiguration.sd_status);
+ target.orignalSdStatus(SDConfiguration.sd_status);
+ $("#sd_card_status_info").translate();
+ }else{
+ clearTimer();
+ clearValidateMsg();
+ init();
+ }
+ }
+ }
+ }
+
+
+
+
+
+ // 表单submit事件处理
+ target.save = function(){
+ showLoading('waiting');
+ target.checkEnable(false);
+ if(target.orignalMode() == target.selectedMode()){
+ showAlert("setting_no_change");
+ } else {
+ service.setSdCardMode({
+ mode : target.selectedMode()
+ }, function(info) {
+ if(info.result){
+ target.orignalMode(target.selectedMode());
+ if(info.result == "processing"){
+ errorOverlay("sd_usb_forbidden");
+ }else{
+ successOverlay();
+ }
+ } else {
+ if (target.selectedMode() == "0") {
+ errorOverlay("sd_not_support");
+ } else {
+ errorOverlay();
+ }
+ }
+ }, function(error) {
+ if (target.selectedMode() == "0") {
+ errorOverlay("sd_not_support");
+ } else {
+ errorOverlay();
+ }
+ });
+ }
+ target.checkEnable(true);
+ return true;
+ };
+
+
+
+ // 保存详细配置信息
+ target.saveShareDetailConfig = function() {
+ showLoading('waiting');
+ target.checkEnable(false);
+ var param = {
+ share_status : target.selectedShareEnable(),
+ share_auth : target.selectedAccessType(),
+ share_file : basePath + target.pathToShare()
+ };
+
+ if (target.selectedShareEnable() == "0") {
+ setSdCardSharing(param);
+ } else {
+ service.checkFileExists({
+ "path" : param.share_file
+ }, function(info) {
+ if (info.status != "exist" && info.status != "processing") {
+ errorOverlay("sd_card_share_setting_" + info.status);
+ } else {
+ setSdCardSharing(param);
+ }
+ }, function(){
+ errorOverlay();
+ });
+ }
+
+ target.checkEnable(true);
+ return true;
+ }
+
+ // 设置SD卡共享信息
+ function setSdCardSharing(param){
+ service.setSdCardSharing(param, function(result) {
+ if (isErrorObject(result)) {
+ if (result.errorType == "no_sdcard") {
+ errorOverlay("sd_card_share_setting_no_sdcard");
+ } else {
+ errorOverlay();
+ }
+ } else {
+ successOverlay();
+ }
+ });
+ }
+ }
+
+ // 将配置的option项转换成Option数组
+ // {Array} configItem [{name: "name1", value: "val1"},{name: "name2", value: "val2"}]
+ function getOptionArray(configItem) {
+ var arr = [];
+ for ( var i = 0; i < configItem.length; i++) {
+ arr.push(new Option(configItem.name, configItem.value));
+ }
+ return arr;
+ }
+
+ function init() {
+ var container = $('#container')[0];
+ ko.cleanNode(container);
+ var fwVm = new SDCardViewModel();
+ ko.applyBindings(fwVm, container);
+ $("#sd_card_status_info").translate();
+ $('#sdmode_form').validate({
+ submitHandler : function() {
+ fwVm.save();
+ }
+ });
+ $('#httpshare_form').validate({
+ submitHandler : function() {
+ fwVm.saveShareDetailConfig();
+ },
+ rules : {
+ path_to_share : "check_file_path"
+ }
+ });
+ }
+
+ return {
+ init : init
+ };
+});
+
+// SD卡 HttpShare模块
+
+define("sd_httpshare","jquery underscore jq_fileinput set service knockout".split(" ") ,
+
+ function($, _, fileinput, config, service, ko) {
+
+ // 每页记录条数
+ // 不能够设置每页数据个数,默认:10
+ // 默认值不可修改
+ var perPage = 10;
+
+ // 当前页
+ var activePage = 1;
+
+ // 当前目录,默认根目录""
+ var currentPath = "";
+
+ // 基目录。是否需要显示给用户?用户友好度
+ var basePath = config.SD_BASE_PATH;
+
+ // 前置路径,发现有的设备会将sd卡数据显示在web目录
+ // prePath = "/usr/conf/web";
+ var prePath = "";
+
+ // 是否隐藏重命名按钮
+ var readwrite = true;
+
+ // 文件列表模板
+ var sdFileItemTmpl = null;
+
+ // 分页模板
+ var pagerTmpl = null;
+ // 配置信息原始状态
+ var originalStatus = null;
+
+ var zoneOffsetSeconds = new Date().getTimezoneOffset() * 60;
+
+ var shareFilePath = '';
+
+ var sdIsUploading = false;//SD卡是否正在上传文件
+
+ // 生成分页数据数组
+ // @method generatePager
+ // @param {Integer} totalSize 总记录数
+ // @param {Integer} perPageNum 每页记录条数
+ // @param {Integer} currentPage 当前页
+ // @return {Array} 分页数据数组
+ function generatePager(totalSize, perPageNum, currentPage) {
+ if (totalSize == 0) {
+ return [];
+ }
+ var pagersArr = [];
+ var totalPages = getTotalPages(totalSize, perPageNum);
+ pagersArr.push({
+ pageNum: currentPage - 1,
+ isActive: false,
+ isPrev: true,
+ isNext: false,
+ isDot: false
+ });
+ if (currentPage == 6) {
+ pagersArr.push({
+ pageNum: 1,
+ isActive: false,
+ isPrev: false,
+ isNext: false,
+ isDot: false
+ });
+ } else if (currentPage > 5) {
+ pagersArr.push({
+ pageNum: 1,
+ isActive: false,
+ isPrev: false,
+ isNext: false,
+ isDot: false
+ });
+ pagersArr.push({
+ pageNum: 0,
+ isPrev: false,
+ isNext: false,
+ isActive: false,
+ isDot: true
+ });
+ }
+ var i;
+ var startPage = currentPage - 4 > 0 ? currentPage - 4 : 1;
+ var endPage = currentPage + 4;
+ for (i = startPage; i <= endPage && i <= totalPages; i++) {
+ pagersArr.push({
+ pageNum: i,
+ isActive: i == currentPage,
+ isPrev: false,
+ isNext: false,
+ isDot: false
+ });
+ }
+ if (currentPage + 5 == totalPages) {
+ pagersArr.push({
+ pageNum: totalPages,
+ isPrev: false,
+ isNext: false,
+ isActive: false,
+ isDot: false
+ });
+ } else if (currentPage + 3 <= totalPages && i - 1 != totalPages) {
+ pagersArr.push({
+ pageNum: 0,
+ isPrev: false,
+ isNext: false,
+ isActive: false,
+ isDot: true
+ });
+ pagersArr.push({
+ pageNum: totalPages,
+ isPrev: false,
+ isNext: false,
+ isActive: false,
+ isDot: false
+ });
+ }
+ pagersArr.push({
+ pageNum: parseInt(currentPage, 10) + 1,
+ isPrev: false,
+ isNext: true,
+ isActive: false,
+ isDot: false
+ });
+ return pagersArr;
+ }
+
+ function getTotalPages(total, perPage){
+ var totalPages = Math.floor(total / perPage);
+ if (total % perPage != 0) {
+ totalPages++;
+ }
+ return totalPages;
+ }
+
+ // 整理文件列表数据,并用模板显示
+ function showFileSet(files) {
+ var i = 0;
+ var shownFiles = $.map(files, function(n) {
+ var obj = {
+ fileName : HTMLEncode(n.fileName),
+ fileType : n.attribute == 'document' ? 'folder' : getFileType(n.fileName),
+ fileSize : getDisplayVolume(n.size, false),
+ filePath : basePath + getCurrentPath() + "/" + n.fileName,
+ lastUpdateTime : transUnixTime((parseInt(n.lastUpdateTime, 10) + zoneOffsetSeconds) * 1000),
+ trClass : i % 2 == 0 ? "even" : "",
+ readwrite : readwrite
+ };
+ i++;
+ return obj;
+ });
+
+ if(sdFileItemTmpl == null){
+ sdFileItemTmpl = $.template("sdFileItemTmpl", $("#sdFileItemTmpl"));
+ }
+ $("#fileList_container").html($.tmpl("sdFileItemTmpl", {data: shownFiles}));
+ }
+
+ // HttpShareViewModel
+ function HttpShareViewModel() {
+ var isGuest = false;
+ if(window.location.hash == "#httpshare_guest"){
+ isGuest = true;
+ }
+ readwrite = true;
+ activePage = 1;
+ setCurrentPath('');
+ basePath = config.SD_BASE_PATH;
+ showLoading('waiting');
+ service.getSDConfiguration({}, function(data){
+ originalStatus = data;
+ shareFilePath = data.share_file;
+ if(shareFilePath.charAt(shareFilePath.length - 1) == '/'){//如果路径中有/,则去掉
+ shareFilePath = shareFilePath.substring(0, shareFilePath.length - 1);
+ }
+
+ if(data.sd_status == '1' && data.sd_mode == '0'){ //共享
+ if(isGuest && data.share_status == '1'){// guest and share
+ basePath = shareFilePath;
+ if(data.share_auth == '0'){ // readonly
+ readwrite = false;
+ $("#uploadSection, #delete_file_button, .sd_guest_hide_th", "#httpshare_form").hide();
+ }else{
+ $("#uploadSection, #delete_file_button, .sd_guest_hide_th", "#httpshare_form").show();
+ }
+ $("#go_to_login_button").removeClass("hide");
+ $('#sd_menu').hide();
+ $('.form-note').hide();
+ if ($(".customfile").length == 0) {
+ $("#fileField").customFileInput();
+ }
+ pagerItemClickHandler(1);
+ } else if(isGuest && data.share_status == '0'){ // guest not share
+ $(".form-body .content", "#httpshare_form").hide().remove();
+ $(".form-title", "#httpshare_form").attr("data-trans", "httpshare").html($.i18n.prop("httpshare"));
+ $(".form-note", "#httpshare_form").attr("data-trans", "note_http_share_cannot_access").html($.i18n.prop("note_http_share_cannot_access"));
+ hideLoading();
+ } else {
+ if ($(".customfile").length == 0) {
+ $("#fileField").customFileInput();
+ }
+ pagerItemClickHandler(1);
+ }
+ } else { // usb
+ $(".form-body .content", "#httpshare_form").hide().remove();
+ $(".form-title", "#httpshare_form").attr("data-trans", "httpshare").html($.i18n.prop("httpshare"));
+ $(".form-note", "#httpshare_form").attr("data-trans", "note_http_share_usb_access").html($.i18n.prop("note_http_share_usb_access"));
+ $(".form-note", "#httpshare_form").addClass("margintop10");
+ hideLoading();
+ }
+ }, function(){
+ errorOverlay();
+ $(".form-body .content", "#httpshare_form").hide().remove();
+ $(".form-title", "#httpshare_form").attr("data-trans", "httpshare").html($.i18n.prop("httpshare"));
+ $(".form-note", "#httpshare_form").attr("data-trans", "note_http_share_cannot_access").html($.i18n.prop("note_http_share_cannot_access"));
+ });
+
+ addInterval(function(){
+ !sdIsUploading && self.checkSdStatus();
+ }, 3000);
+
+ // T卡热插拔时状态监控,拔插卡重刷界面
+ self.checkSdStatus = function(){
+ var data = service.getSDConfiguration();
+ if(data.sd_status && (data.sd_status != originalStatus.sd_status)){
+ if(data.sd_status == '1'){
+ window.location.reload();
+ }else{
+ clearTimer();
+ clearValidateMsg();
+ init();
+ }
+ }
+ }
+ }
+
+ // 页码点击事件处理
+ pagerItemClickHandler = function(num) {
+ activePage = num;
+ refreshFileList(getCurrentPath(), activePage);
+ };
+
+ function checkConfiguration(){
+ var data = service.getSDConfiguration();
+ if(!_.isEqual(originalStatus, data)){
+ showAlert('sd_config_changed_reload', function(){
+ init();
+ });
+ return false;
+ }
+ return true;
+ }
+
+ //检查操作路径是否为共享路径,如果是共享路径,给用户提示
+ function inSharePath(path, wording) {
+ var tmpShareFilePath = shareFilePath + '/';
+ var tmpPath = path + '/';
+ if (originalStatus.share_status == '1' && shareFilePath != '' && shareFilePath != '/' && tmpShareFilePath.indexOf(tmpPath) != -1) {
+ showAlert(wording);
+ return true;
+ }
+ return false;
+ }
+
+ // 进入文件夹
+ enterFolder = function(name) {
+ if(!checkConfiguration()){
+ return false;
+ }
+ var path;
+ if (name == "") {
+ path = "";
+ } else {
+ path = getCurrentPath() + '/' + name;
+ }
+ refreshFileList(path, 1);
+ return true;
+ };
+
+ // 回到上一级目录
+ backFolder = function() {
+ if(!checkConfiguration()){
+ return false;
+ }
+ var path = getCurrentPath().substring(0, getCurrentPath().lastIndexOf("/"));
+ refreshFileList(path, 1);
+ return true;
+ };
+
+ // 更新按钮状态
+ refreshBtnsStatus = function() {
+ if (getCurrentPath() == "") {
+ $("#rootBtnLi, #backBtnLi").hide();
+ } else {
+ $("#rootBtnLi, #backBtnLi").show();
+ }
+ if (readwrite) {
+ $("#createNewFolderLi").hide();
+ $("#createNewFolderLi").find(".error").hide();
+ $("#newFolderBtnLi").show();
+ $("#newFolderName").val('');
+ $("#createNewFolderErrorLabel").removeAttr('data-trans').text('');
+ } else {
+ $("#newFolderBtnLi, #createNewFolderLi").hide().remove();
+ }
+ checkDeleteBtnStatus();
+ };
+
+
+ // 刷新文件列表
+ refreshFileList = function(path, index, alertShown) {
+ if(!alertShown){
+ showLoading('waiting');
+ }
+ service.getFileList({
+ path : prePath + basePath + path,
+ index : index
+ }, function(data) {
+ if (isErrorObject(data)) {
+ showAlert(data.errorType);
+ return;
+ }
+ setCurrentPath(path);
+ $("#sd_path").val(path);
+ activePage = index;
+ totalSize = data.totalRecord;
+ showFileSet(data.details);
+ pagination(totalSize); //测试分页时可以将此处totalSize调大
+ refreshBtnsStatus();
+ updateSdMemorySizes();
+ if(!alertShown){
+ hideLoading();
+ }
+ });
+ };
+
+
+ // 显示新建文件夹按钮点击事件
+ openCreateNewFolderClickHandler = function() {
+ $("#newFolderBtnLi").hide();
+ $("#newFolderName").show();
+ $("#createNewFolderLi").show();
+ };
+
+ // 取消显示新建文件夹按钮点击事件
+ cancelCreateNewFolderClickHandler = function() {
+ $("#createNewFolderLi").hide();
+ $("#newFolderName").val('');
+ $("#newFolderBtnLi").show();
+ $("#createNewFolderLi").find(".error").hide();
+ };
+
+ // 新建文件夹按钮点击事件
+ createNewFolderClickHandler = function() {
+ if(!checkConfiguration()){
+ return false;
+ }
+ var newFolderName = $.trim($("#newFolderName").val());
+ var newPath = prePath + basePath + getCurrentPath() + "/" + newFolderName;
+ showLoading('creating');
+ service.checkFileExists({
+ path : newPath
+ }, function(data1) {
+ if (data1.status == "noexist" || data1.status == "processing") {
+ service.createFolder({
+ path : newPath
+ }, function(data) {
+ if (isErrorObject(data)) {
+ showAlert(data.errorType);
+ return false;
+ } else {
+ successOverlay();
+ refreshFileList(getCurrentPath(), 1);
+ }
+ });
+ } else if (data1.status == "no_sdcard") {
+ showAlert("no_sdcard", function(){
+ window.location.reload();
+ });
+ } else if (data1.status == "exist") {
+ $("#createNewFolderErrorLabel").attr('data-trans', 'sd_card_share_setting_exist').text($.i18n.prop("sd_card_share_setting_exist"));
+ hideLoading();
+ }
+ }, function(){
+ errorOverlay();
+ });
+ return true;
+ };
+
+ // 重命名按钮点击事件
+ renameBtnClickHandler = function(oldName) {
+ var oldPath = prePath + basePath + getCurrentPath() + "/" + oldName;
+ if(inSharePath(oldPath, 'sd_share_path_cant_rename')){
+ return false;
+ }
+ showPrompt("sd_card_folder_name_is_null", function() {
+ renamePromptCallback(oldName);
+ }, 160, oldName, checkPromptInput);
+ };
+
+ function renamePromptCallback(oldName){
+ if(!checkConfiguration()){
+ return false;
+ }
+ var promptInput = $("div#confirm div.promptDiv input#promptInput");
+ var newFolderName = $.trim(promptInput.val());
+ var newPath = prePath + basePath + getCurrentPath() + "/" + newFolderName;
+ service.checkFileExists({
+ path : newPath
+ }, function(data1) {
+ if (data1.status == "noexist" || data1.status == "processing") {
+ hideLoadingButtons();
+ var oldPath = prePath + basePath + getCurrentPath() + "/" + oldName;
+ service.fileRename({
+ oldPath : oldPath,
+ newPath : newPath,
+ path : prePath + basePath + getCurrentPath()
+ }, function(data) {
+ if (isErrorObject(data)) {
+ showAlert($.i18n.prop(data.errorType));
+ if(data.errorType == "no_exist"){
+ var alertShown = true;
+ refreshFileList(getCurrentPath(), 1, alertShown);
+ } else if(data.errorType == "processing"){
+ //
+ }
+ } else {
+ refreshFileList(getCurrentPath(), 1);
+ successOverlay();
+ }
+ showLoadingButtons();
+ return true;
+ });
+ } else if (data1.status == "no_sdcard") {
+ showAlert("no_sdcard", function(){
+ window.location.reload();
+ });
+ return false;
+ } else if (data1.status == "exist") {
+ $(".promptErrorLabel").text($.i18n.prop("sd_card_share_setting_exist"));
+ return false;
+ }
+ return true;
+ }, function(){
+ errorOverlay();
+ });
+ return false;
+ }
+
+ // Prompt弹出框INPUT校验函数
+ function checkPromptInput(){
+ var promptInput = $("div#confirm div.promptDiv input#promptInput");
+ var newFileName = $.trim(promptInput.val());
+ var newPath = (prePath + basePath + getCurrentPath() + "/" + newFileName).replace("//", "/");
+ var checkResult = checkFileNameAndPath(newFileName, newPath);
+ if (1 == checkResult) {
+ $(".promptErrorLabel").text($.i18n.prop("sd_upload_rename_null"));//tip filena is null
+ return false;
+ }else if (2 == checkResult) {
+ $(".promptErrorLabel").text($.i18n.prop("sd_card_path_too_long"));
+ return false;
+ }else if (3 == checkResult) {
+ $(".promptErrorLabel").text($.i18n.prop("check_file_path"));
+ return false;
+ }else{
+ $(".promptErrorLabel").text("");
+ return true;
+ }
+ return true;;
+ }
+
+ hideLoadingButtons = function () {
+ $(".buttons", "#confirm").hide();
+ };
+
+ showLoadingButtons = function () {
+ $(".buttons", "#confirm").show();
+ };
+
+ // 删除按钮点击事件
+ deleteBtnClickHandler = function() {
+ if(!checkConfiguration()){
+ return false;
+ }
+ var files = $("input:checkbox:checked", "#fileList_container");
+ var fileNames = "";
+ if (!files || files.length == 0) {
+ return false;
+ }
+ var hasSharePath = false;
+ $.each(files, function (i, n) {
+ var theFile = $(n).val();
+ if (inSharePath(prePath + basePath + getCurrentPath() + "/" + theFile, {msg: 'sd_share_path_cant_delete', params: [theFile]})) {
+ hasSharePath = true;
+ return false;
+ }
+ return true;
+ });
+ if (hasSharePath) {
+ return false;
+ }
+ showConfirm("confirm_data_delete", function(){
+ $.each(files, function(i, n) {
+ fileNames += $(n).val() + "*";
+ });
+ var thePath = prePath + basePath + getCurrentPath();
+ service.deleteFilesAndFolders({
+ path : thePath,
+ names : fileNames
+ }, function(data) {
+ if (data.status == "failure") {
+ showAlert("delete_folder_failure");
+ }
+ else if(data.status == "no_sdcard"){
+ showAlert("no_sdcard");
+ }
+ else if(data.status == "processing"){
+ showAlert("sd_file_processing_cant_delete");
+ }
+ else if(data.status == "success"){
+ successOverlay();
+ }
+ refreshFileList(getCurrentPath(), 1);
+ }, function(){
+ errorOverlay();
+ });
+ });
+ return true;
+ };
+
+ // 文件上传按钮点击事件
+ fileUploadSubmitClickHandler = function(ifReName) {
+ if(ifReName){
+ var fileName = $.trim($("div#confirm div.promptDiv input#promptInput").val());
+ }else{
+ var fileName = $(".customfile").attr('title');
+ }
+ var newPath = (basePath + getCurrentPath() + "/" + fileName).replace("//", "/");
+ var fileSize = getFileSize($("#fileField")[0]);
+ if(!checkuploadFileNameAndPath(fileName, newPath, fileSize)){
+ return false;
+ }
+ doCheckAndUpload(fileName, newPath, fileSize);
+ };
+
+ function doCheckAndUpload(fileName, newPath, fileSize){
+ service.getSdMemorySizes({}, function(data) {
+ if (isErrorObject(data)) {
+ showAlert(data.errorType);
+ return false;
+ }
+ if (data.availableMemorySize < fileSize) {
+ showAlert("sd_upload_space_not_enough");
+ return false;
+ }
+ $.modal.close();
+ showLoading('uploading', '<span data-trans="note_uploading_not_refresh">' + $.i18n.prop('note_uploading_not_refresh') + '</span>');
+ service.checkFileExists({
+ path : newPath
+ }, function(data1) {
+ if (data1.status == "noexist") {
+ $("#fileUploadForm").attr("action", "/cgi-bin/httpshare/" + URLEncodeComponent(fileName));
+ var currentTime = new Date().getTime();
+ $("#path_SD_CARD_time").val(transUnixTime(currentTime));
+ $("#path_SD_CARD_time_unix").val(Math.round((currentTime - zoneOffsetSeconds * 1000) / 1e3));
+ if(!iframeLoadBinded){
+ bindIframeLoad();
+ }
+ sdIsUploading = true;
+ $("#fileUploadForm").submit();
+ } else if (data1.status == "no_sdcard") {
+ showAlert("no_sdcard", function(){
+ window.location.reload();
+ });
+ } else if (data1.status == "processing") {
+ showAlert("sd_upload_file_is_downloading");//("system is downloading,try later!");
+ }else if (data1.status == "exist") {
+ showPrompt("sd_upload_rename",function(){
+ fileUploadSubmitClickHandler(true);
+ },160, fileName, checkPromptInput, clearUploadInput);
+ }
+ }, function(){
+ errorOverlay();
+ });
+ return true;
+ });
+ }
+
+ var iframeLoadBinded = false;
+ function bindIframeLoad(){
+ iframeLoadBinded = true;
+ $('#fileUploadIframe').load(function() {
+ sdIsUploading = false;
+ var txt = $('#fileUploadIframe').contents().find("body").html().toLowerCase();
+ var alertShown = false;
+ if (txt.indexOf('success') != -1) {
+ successOverlay();
+ } else if (txt.indexOf('space_not_enough') != -1) {
+ alertShown = true;
+ showAlert('sd_upload_space_not_enough');
+ } else if (txt.indexOf('data_lost') != -1) {
+ alertShown = true;
+ showAlert('sd_upload_data_lost');
+ } else {
+ errorOverlay();
+ }
+
+ clearUploadInput();
+ refreshFileList(getCurrentPath(), 1, alertShown);
+ });
+ }
+
+ // 更新SD卡容量显示数据
+ updateSdMemorySizes = function() {
+ service.getSdMemorySizes({}, function(data) {
+ if (isErrorObject(data)) {
+ showAlert(data.errorType);
+ return false;
+ }
+ var total = getDisplayVolume(data.totalMemorySize, false);
+ var used = getDisplayVolume(data.totalMemorySize - data.availableMemorySize, false);
+ $("#sd_volumn_used").text(used);
+ $("#sd_volumn_total").text(total);
+ return true;
+ });
+ };
+
+ // 翻页
+ pagination = function(fileTotalSize) {
+ var pagers = generatePager(fileTotalSize, perPage, parseInt(activePage, 10));
+ if(pagerTmpl == null){
+ pagerTmpl = $.template("pagerTmpl", $("#pagerTmpl"));
+ }
+ $(".pager", "#fileListButtonSection").html($.tmpl("pagerTmpl", {data: {pagers : pagers, total : getTotalPages(fileTotalSize, perPage)}}));
+ renderCheckbox();
+ $(".content", "#httpshare_form").translate();
+ };
+
+ // 下载文件是检查文件路径是否包含特殊字符
+ checkFilePathForDownload = function(path){
+ if(!checkConfiguration()){
+ return false;
+ }
+ var idx = path.lastIndexOf('/');
+ var prePath = path.substring(0, idx+1);
+ var name = path.substring(idx+1, path.length);
+ if(checkFileNameChars(prePath, true) && checkFileNameChars(name, false)){
+ return true;
+ }
+ showAlert('sd_card_invalid_chars_cant_download');
+ return false;
+ };
+
+ gotoLogin = function(){
+ window.location.href="#entry";
+ };
+
+ // 事件绑定
+ function bindEvent(){
+ $('#createNewFolderForm').validate({
+ submitHandler : function() {
+ createNewFolderClickHandler();
+ },
+ rules : {
+ newFolderName : {sd_card_path_too_long:true,check_filefold_name: true}
+ }
+ });
+ $("p.checkbox", "#httpshare_form").die().live('click', function () {
+ addTimeout(function () {
+ checkDeleteBtnStatus();
+ }, 100);
+ });
+ $(".icon-download", "#httpshare_form").die().live("click", function () {
+ return checkFilePathForDownload($(this).attr("filelocal"));
+ });
+ $(".folderTd", "#httpshare_form").die().live("click", function () {
+ return enterFolder($(this).attr("filename"));
+ });
+ $(".fileRename", "#httpshare_form").die().live("click", function () {
+ return renameBtnClickHandler($(this).attr("filename"));
+ });
+ iframeLoadBinded = false;
+ }
+
+
+ // 刷新删除按钮状态
+ function checkDeleteBtnStatus(){
+ var checkedItem = $("p.checkbox.checkbox_selected", '#fileListSection');
+ if(checkedItem.length > 0){
+ enableBtn($('#delete_file_button'));
+ } else {
+ disableBtn($('#delete_file_button'));
+ }
+ }
+
+
+ // 文件名和路径检查
+ function checkFileNameAndPath(filename, path) {
+ if (filename == "" || filename.length > 25) {
+ return 1;
+ }
+ if (path.length >= 200) {
+ return 2;
+ }
+ if (!checkFileNameChars(filename, false)) {
+ return 3;
+ }
+ }
+
+ // 文件名特殊字符检查
+ function checkFileNameChars(filename, isIncludePath) {
+ var ASCStringInvalid = '+/:*?<>\"\'\\|#&`~';
+ if(isIncludePath){
+ ASCStringInvalid = '+:*?<>\"\'\\|#&`~';
+ }
+ var flag = false;
+ var dotFlag = false;
+ var reg = /^\.+$/;
+ for ( var filenamelen = 0; filenamelen < filename.length; filenamelen++) {
+ for ( var ACSlen = 0; ACSlen < ASCStringInvalid.length; ACSlen++) {
+ if (filename.charAt(filenamelen) == ASCStringInvalid.charAt(ACSlen)) {
+ flag = true;
+ break;
+ }
+ }
+ if (reg.test(filename)) {
+ dotFlag = true;
+ }
+ if (flag || dotFlag) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+
+ function checkuploadFileNameAndPath(fileName, newPath, fileSize){
+ if(!checkConfiguration()){
+ return false;
+ }
+
+ if (typeof fileName == "undefined" || fileName == '' || fileName == $.i18n.prop("no_file_selected")) {
+ showAlert("sd_no_file_selected");
+ return false;
+ }
+ if (newPath.length >= 200) {
+ showAlert("sd_card_path_too_long");
+ return false;
+ }
+
+ if (fileSize/1024/1024/1024 > 2){ //no more than 2G
+ showAlert("sd_file_size_too_big");
+ return false;
+ }
+
+ if (fileName.indexOf('*') >= 0){ //no *
+ showAlert("sd_file_name_invalid");
+ return false;
+ }
+ return true;
+ }
+
+
+ //清空上传控件
+ function clearUploadInput(){
+ $("#fileField").closest('.customfile').before('<input id="fileField" name="filename" maxlength="200" type="file" dir="ltr"/>').remove();
+ addTimeout(function(){
+ $("#fileField").customFileInput();
+ }, 0);
+ $("#uploadBtn", "#uploadSection").attr("data-trans", "browse_btn").html($.i18n.prop('browse_btn'));
+ $(".customfile", "#uploadSection").removeAttr("title");
+ $(".customfile span.customfile-feedback", "#uploadSection")
+ .html('<span data-trans="no_file_selected">'+$.i18n.prop('no_file_selected')+'</span>')
+ .attr('class', 'customfile-feedback');
+ }
+
+
+ function getCurrentPath(){
+ return currentPath;
+ }
+
+ function setCurrentPath(path){
+ if(path.lastIndexOf("/") == path.length - 1){
+ currentPath = path.substring(0, path.length - 1);
+ } else {
+ currentPath = path;
+ }
+ }
+
+
+ function getFileSize(object){
+ var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
+ if (isIE) { //如果是ie
+ var objValue = object.value;
+ try {
+ var fileSysObj = new ActiveXObject("Scripting.FileSystemObject");
+ fileLenth = parseInt(fileSysObj.GetFile(objValue).size);
+ } catch (e) { //('IE内核取不到长度');
+ fileLenth = 1;
+ }
+ }else{ //其他
+ try{//对于非IE获得要上传文件的大小
+ fileLenth = parseInt(object.files[0].size);
+ }catch (e) {
+ fileLenth=1; //获取不到取-1
+ }
+ }
+ return fileLenth;
+ }
+
+ function init() {
+ var container = $('#container')[0];
+ ko.cleanNode(container);
+ var fwVm = new HttpShareViewModel();
+ ko.applyBindings(fwVm, container);
+ bindEvent();
+ }
+
+
+ jQuery.validator.addMethod("check_filefold_name", function(value, element, param) {
+ var result = checkFileNameChars(value, false);
+ return this.optional(element) || result;
+ });
+
+ jQuery.validator.addMethod("sd_card_path_too_long", function(value, element, param) {
+ var newFolderName = $.trim($("#newFolderName").val());
+ var newPath = prePath + basePath + getCurrentPath() + "/" + newFolderName;
+ var result = true;
+ if (newPath.length >= 200) {
+ result = false;
+ }
+ return this.optional(element) || result;
+ });
+
+ return {
+ init : init
+ };
+});
+
+define("ussd","set service knockout jquery".split(" "), function (set, fnc, libko, libjq) {
+ var time_interval = 0;
+ var initFlg = true;
+ var numTimeout = 0;
+ var replyFlg = false;
+ var ussd_action = 1;
+
+ function init() {
+ var container = libjq('#container')[0];
+ libko.cleanNode(container);
+ var vm = new vmUSSD();
+ libko.applyBindings(vm, container);
+
+ }
+ var USSDLocation = {
+ SEND: 0,
+ REPLY: 1
+ };
+ function vmUSSD() {
+ var target = this;
+
+ target.hasUpdateCheck = set.HAS_UPDATE_CHECK;
+ target.ussd_action = libko.observable(ussd_action);
+ target.USSDLocation = libko.observable(USSDLocation.SEND);
+ target.USSDReply = libko.observable("");
+ target.USSDSend = libko.observable("");
+ target.hasDdns = set.DDNS_SUPPORT;
+
+ function checkTimeout() {
+ if (replyFlg) {
+ replyFlg = true;
+ window.clearInterval(time_interval);
+ numTimeout = 0;
+ } else {
+ if (numTimeout > 28) {
+ replyFlg = true;
+ window.clearInterval(time_interval);
+ showAlert("ussd_operation_timeout");
+ target.USSDReply("");
+ target.USSDSend("");
+ target.USSDLocation(USSDLocation.SEND);
+ numTimeout = 0;
+
+ } else {
+ numTimeout++;
+ }
+
+ }
+ };
+
+ target.sendToNet = function () {
+ numTimeout = 0;
+ window.clearInterval(time_interval);
+ var command = target.USSDSend();
+
+ var idx_t = 0;
+ var indexChar;
+ for (idx_t = 0; idx_t < command.length; ) { //corem0418, delte left blanks and right blanks
+ indexChar = command.charAt(idx_t);
+ if (indexChar == ' ') {
+ if (command.length > 1) {
+ command = command.substr(idx_t + 1);
+ } else {
+ command = ''; // string is filled with blank
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+
+ for (idx_t = command.length - 1; idx_t >= 0 && command.length > 0; --idx_t) {
+ indexChar = command.charAt(idx_t);
+ if (indexChar == ' ') {
+ if (command.length > 1) {
+ command = command.substr(0, idx_t);
+ } else {
+ command = ''; // string is filled with blank
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+
+ if (('string' != typeof(command)) || ('' == command)) {
+ showAlert("ussd_error_input");
+ return;
+ }
+
+ showLoading('waiting');
+
+ var tmp = {};
+ tmp.operator = "ussd_send";
+ tmp.strUSSDCommand = command;
+ tmp.sendOrReply = "send";
+
+ fnc.getUSSDResponse(tmp, function (result, content) {
+ hideLoading();
+ if (result) {
+ USSD_reset();
+ target.USSDLocation(USSDLocation.REPLY);
+ target.ussd_action(content.ussd_action);
+ libjq("#USSD_Content").val(decodeMessage(content.data, true));
+ replyFlg = false;
+ numTimeout = 0;
+ } else {
+ showAlert(content);
+ }
+ });
+ };
+
+ target.replyToNet = function () {
+ numTimeout = 0;
+ window.clearInterval(time_interval);
+ var command = target.USSDReply();
+
+ var idx_t = 0;
+ var indexChar;
+ for (idx_t = 0; idx_t < command.length; ) { //corem0418, delte left blanks and right blanks
+ indexChar = command.charAt(idx_t);
+ if (indexChar == ' ') {
+ if (command.length > 1) {
+ command = command.substr(idx_t + 1);
+ } else {
+ command = ''; // string is filled with blank
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+
+ for (idx_t = command.length - 1; idx_t >= 0 && command.length > 0; --idx_t) {
+ indexChar = command.charAt(idx_t);
+ if (indexChar == ' ') {
+ if (command.length > 1) {
+ command = command.substr(0, idx_t);
+ } else {
+ command = ''; // string is filled with blank
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+
+ if (('string' != typeof(command)) || ('' == command)) {
+ showAlert("ussd_error_input");
+ return;
+ }
+
+ showLoading('waiting');
+
+ var tmp = {};
+ tmp.operator = "ussd_reply";
+ tmp.strUSSDCommand = command;
+ tmp.sendOrReply = "reply";
+
+ fnc.getUSSDResponse(tmp, function (result, content) {
+ hideLoading();
+ if (result) {
+ target.ussd_action(content.ussd_action);
+ libjq("#USSD_Content").val(decodeMessage(content.data, true));
+ replyFlg = false;
+ USSD_reset();
+ numTimeout = 0;
+ } else {
+ showAlert(content);
+ }
+ });
+ };
+
+ USSD_reset = function () {
+ target.USSDReply("");
+ target.USSDSend("");
+ };
+ USSD_cancel = function () {
+ fnc.USSDReplyCancel(function (result) {});
+ };
+
+ target.noReplyCancel = function () {
+ numTimeout = 0;
+ replyFlg = true;
+ window.clearInterval(time_interval);
+ fnc.USSDReplyCancel(function (result) {
+ if (result) {
+ USSD_reset();
+ target.USSDLocation(USSDLocation.SEND);
+ } else {
+ showAlert("ussd_fail");
+ }
+ });
+ };
+
+ //如果首次进入USSD菜单,先发送USSD取消命令,进行初始化
+ if (initFlg) {
+ USSD_cancel();
+ initFlg = false;
+ }
+ }
+
+ return {
+ init: init
+ };
+});
+
+
+define("phonebook","underscore jquery knockout set service jq_chosen".split(" "),
+
+ function (_, $, ko, config, service, chosen) {
+
+ var locationValue = {
+ SIM: "0",
+ DEVICE: "1"
+ };
+ var pageState = {
+ LIST: 0,
+ NEW: 1,
+ EDIT: 2,
+ VIEW: 3,
+ SEND_MSM: 4
+ };
+ //存储位置选项
+ var saveLocationOpts = function (hasSIMCard) {
+ var opts = [];
+ opts.push(new Option($.i18n.prop("device_book"), locationValue.DEVICE));
+ if (hasSIMCard) {
+ opts.push(new Option($.i18n.prop("sim_book"), locationValue.SIM));
+ }
+ return opts;
+ };
+
+ function getCurrentGroup() {
+ return $("#selectedFilterGroup").val();
+ }
+ //列表模板对应的Columns
+ var templateColumns = {
+ cardColumns: [{
+ rowText: "index",
+ display: false
+ }, {
+ rowText: "name"
+ }, {
+ rowText: "mobile_phone_number"
+ }, {
+ rowText: "home_phone_number"
+ }
+ ],
+ listColumns: [{
+ columnType: "checkbox",
+ headerTextTrans: "number",
+ rowText: "index",
+ width: "10%"
+ }, {
+ headerTextTrans: "name",
+ rowText: "name",
+ width: "25%",
+ sortable: true
+ }, {
+ columnType: "image",
+ headerTextTrans: "save_location",
+ rowText: "imgLocation",
+ width: "20%",
+ sortable: true
+ }, {
+ headerTextTrans: "mobile_phone_number",
+ rowText: "mobile_phone_number",
+ width: "30%",
+ sortable: true
+ }, {
+ headerTextTrans: "group",
+ rowText: "transGroup",
+ width: "15%",
+ sortable: true,
+ needTrans: true
+ }
+ ]
+ };
+ //分组选项
+ var groupOpts = function () {
+ var opts = [];
+ opts.push(new Option($.i18n.prop("common"), "common"));
+ opts.push(new Option($.i18n.prop("family"), "family"));
+ opts.push(new Option($.i18n.prop("friend"), "friend"));
+ opts.push(new Option($.i18n.prop("colleague"), "colleague"));
+ return opts;
+ };
+
+ var _phoneBookStopSMSSending = false;
+
+ function pbViewMode() {
+ var target = this;
+
+ //property for common
+ target.pageState = ko.observable(pageState.LIST);
+ target.initFail = ko.observable(true);
+ target.hasSms = ko.observable(config.HAS_SMS);
+
+ var smsHasCapability = true;
+ var smsLeftCount = 0;
+
+ //property for list
+ var capacity = {
+ simMaxNameLen: 0,
+ simMaxNumberLen: 0,
+ IsSimCardFull: true,
+ IsDeviceFull: true,
+ Used: 0,
+ Capacity: 0,
+ Ratio: "(0/0)"
+ };
+ target.capacity = ko.observable(capacity);
+ target.phoneBookCapacity = ko.observable(capacity.Ratio);
+ target.books = ko.observableArray();
+ //列表模板创建
+ target.gridTemplate = new ko.simpleGrid.viewModel({
+ tableClass: "table-fixed",
+ data: target.books(),
+ idName: "index",
+ columns: templateColumns.listColumns,
+ defaultSortField: "name",
+ defaultSortDirection: "ASC",
+ pageSize: 10,
+ tmplType: 'list',
+ searchColumns: ["name", "mobile_phone_number"],
+ primaryColumn: "mobile_phone_number",
+ showPager: true,
+ rowClickHandler: function (dataId) {
+ target.editBooks(dataId, 'view');
+ },
+ deleteHandler: function (dataId) {
+ target.deleteOneBook(dataId);
+ },
+ changeTemplateHandler: function () {
+ target.changeTemplate();
+ }
+ });
+
+ //property for edit or new
+ target.locations = ko.observableArray();
+ target.originLocation = "";
+ target.selectedLocation = ko.observable(locationValue.DEVICE);
+ target.locationTrans = ko.observable();
+ target.locationTransText = ko.observable();
+ target.index = ko.observable(-1);
+ target.name = ko.observable("");
+ target.nameMaxLength = ko.computed(function () {
+ var max = getNameMaxLength();
+ var name = target.name().substring(0, max);
+ target.name(name);
+ return getNameMaxLength();
+ });
+ function getNameMaxLength() {
+ var max = 22;
+ if (target.selectedLocation() == locationValue.DEVICE) {
+ var encodeType = getEncodeType(target.name());
+ if ("UNICODE" == encodeType.encodeType || encodeType.extendLen > 0) {
+ max = 11;
+ } else {
+ max = 22;
+ }
+ //max = 22;
+ } else {
+ //对"^"需要按照2个字符处理
+ var encodeType = getEncodeType(target.name());
+ if ("UNICODE" == encodeType.encodeType || encodeType.extendLen > 0) {
+ max = (target.capacity().simMaxNameLen / 2) - 1;
+ } else {
+ max = target.capacity().simMaxNameLen;
+ }
+ }
+ return max;
+ }
+
+ target.mobile_phone_number = ko.observable("");
+ target.mobileMaxLength = ko.computed(function () {
+ var max = getMobileMaxLength();
+ var mobileNumber = target.mobile_phone_number().substring(0, max);
+ target.mobile_phone_number(mobileNumber);
+ return getMobileMaxLength();
+ });
+ function getMobileMaxLength() {
+ var max = 40;
+ if (target.selectedLocation() == locationValue.DEVICE) {
+ max = 40;
+ } else {
+ max = target.capacity().simMaxNumberLen;
+ }
+ return max;
+ }
+
+ target.home_phone_number = ko.observable("");
+ target.office_phone_number = ko.observable("");
+ target.mail = ko.observable("");
+ target.transEditAreaTitle = ko.dependentObservable(function () {
+ var state = target.pageState();
+ if (state == pageState.EDIT) {
+ return "edit";
+ } else if (state == pageState.NEW) {
+ return "new";
+ } else if (state == pageState.VIEW) {
+ return "view";
+ }
+ });
+ var groups = groupOpts();
+ target.groups = ko.observableArray(groups);
+ target.selectedGroup = ko.observable();
+ target.groupTrans = ko.observable();
+ target.groupTransText = ko.observable();
+
+ target.selectedFilterGroup = ko.observable('all');
+ target.selectedFilterGroupChangeHandler = function () {
+ target.selectedFilterGroup($("#selectedFilterGroup").val());
+ getPhoneBookReady();
+ };
+
+ //property for sendMessage
+ target.showErrorInfo = ko.observable(false);
+ target.messageContent = ko.observable("");
+ target.messageCount = ko.computed(function () {
+ var msgInput = $("#txtSmsContent", "#sendMessage");
+ var msgInputDom = msgInput[0];
+ target.messageContent();
+ var strValue = msgInput.val();
+ var encodeType = getEncodeType(strValue);
+ var maxLength = encodeType.encodeType == 'UNICODE' ? 335 : 765;
+ if (strValue.length + encodeType.extendLen > maxLength) {
+ var scrollTop = msgInputDom.scrollTop;
+ var insertPos = getInsertPos(msgInputDom);
+ var moreLen = strValue.length + encodeType.extendLen - maxLength;
+ var insertPart = strValue.substr(insertPos - moreLen > 0 ? insertPos - moreLen : 0, moreLen);
+ var reversed = insertPart.split('').reverse();
+ var checkMore = 0;
+ var cutNum = 0;
+ for (var i = 0; i < reversed.length; i++) {
+ if (getEncodeType(reversed[i]).extendLen > 0) {
+ checkMore += 2;
+ } else {
+ checkMore++;
+ }
+ if (checkMore >= moreLen) {
+ cutNum = i + 1;
+ break;
+ }
+ }
+ var iInsertToStartLength = insertPos - cutNum;
+
+ target.messageContent(strValue.substr(0, iInsertToStartLength) + strValue.substr(insertPos));
+ if (target.messageContent().length > maxLength) {
+ target.messageContent(target.messageContent().substr(0, maxLength));
+ }
+ setInsertPos(msgInputDom, iInsertToStartLength);
+ msgInputDom.scrollTop = scrollTop;
+ }
+ pbDraftListener();
+ var newValue = $(msgInputDom).val();
+ var newEncodeType = getEncodeType(newValue);
+ var newMaxLength = newEncodeType.encodeType == 'UNICODE' ? 335 : 765;
+ if (newValue.length + newEncodeType.extendLen >= newMaxLength) {
+ $("#msgCount").addClass("colorRed");
+ } else {
+ $("#msgCount").removeClass("colorRed");
+ }
+ return "(" + (newValue.length + newEncodeType.extendLen) + "/" + newMaxLength + ")" + "(" + getSmsCount(newValue) + "/5)";
+ });
+
+ target.clear = function (isNeedInit) {
+ if (target.pageState() == pageState.SEND_MSM) {
+ smsPageCheckDraft(clearPhonebookForm, isNeedInit);
+ } else {
+ clearPhonebookForm(isNeedInit);
+ }
+ config.resetContentModifyValue();
+ };
+
+ //通过按钮返回列表状态事件处理
+ target.btnClear = function (isNeedInit) {
+ if (target.pageState() == pageState.SEND_MSM) {
+ smsPageCheckDraft(clearPhonebookForm, isNeedInit);
+ config.resetContentModifyValue();
+ } else if ((target.pageState() == pageState.NEW || target.pageState() == pageState.EDIT) && (target.preContent.location != target.selectedLocation()
+ || target.preContent.name != target.name()
+ || target.preContent.mobile_phone_number != target.mobile_phone_number()
+ || target.preContent.home_phone_number != target.home_phone_number()
+ || target.preContent.office_phone_number != target.office_phone_number()
+ || target.preContent.mail != target.mail()
+ || target.preContent.group != target.selectedGroup())) {
+ showConfirm("leave_page_info", {
+ ok: function () {
+ clearPhonebookForm(isNeedInit);
+ config.resetContentModifyValue();
+ },
+ no: function () {
+ return false;
+ }
+ });
+ } else {
+ clearPhonebookForm(isNeedInit);
+ config.resetContentModifyValue();
+ }
+ };
+
+ function clearPhonebookForm(isNeedInit) {
+ $("#frmPhoneBook").hide();
+ target.pageState(pageState.LIST);
+ target.index(-1);
+ target.name("");
+ target.mobile_phone_number("");
+ target.home_phone_number("");
+ target.office_phone_number("");
+ target.mail("");
+ target.messageContent("");
+ if (true == isNeedInit) {
+ refreshPage();
+ }
+ target.gridTemplate.clearAllChecked();
+ clearValidateMsg();
+ $("#books ").translate();
+ $("#frmPhoneBook").show();
+ }
+
+ //检查SIM卡状态
+ target.checkHasSIMCard = function (showMsg) {
+ var status = service.getStatusInfo();
+ if (status.simStatus != "modem_init_complete") {
+ if (showMsg) {
+ showAlert("sim_removed", function () {
+ target.pageState(pageState.LIST);
+ target.clear(true);
+ });
+ }
+ return false;
+ }
+ return true;
+ };
+
+ //保存电话本事件
+ target.save = function () {
+ var saveBook = function (index) {
+ var isSaveInSIM = (location == locationValue.SIM);
+ if (isSaveInSIM) {
+ if (!target.checkHasSIMCard(true)) {
+ return;
+ }
+ }
+ if (target.pageState() == pageState.NEW || (target.pageState() == pageState.EDIT && location != target.originLocation)) {
+ if (isSaveInSIM) {
+ if (target.capacity().IsSimCardFull) {
+ showAlert("sim_full");
+ return;
+ }
+ } else {
+ if (target.capacity().IsDeviceFull) {
+ showAlert("device_full");
+ return;
+ }
+ }
+ }
+ var name = target.name();
+ var mobile_phone_number = target.mobile_phone_number();
+ if ($.trim(name) == "" || $.trim(mobile_phone_number) == "") {
+ return;
+ }
+ showLoading('saving');
+ var params = {};
+ params.location = location;
+ params.index = index;
+ params.name = name;
+ params.mobile_phone_number = mobile_phone_number;
+ if (!isSaveInSIM) {
+ params.home_phone_number = target.home_phone_number();
+ params.office_phone_number = target.office_phone_number();
+ params.mail = target.mail();
+ params.group = target.selectedGroup();
+ }
+ if (target.selectedLocation() != target.originLocation) {
+ params.delId = target.index();
+ }
+ service.savePhoneBook(params, target.callback);
+ }
+ var location = target.selectedLocation();
+ var editIndex = (location == target.originLocation) ? target.index() : -1;
+ if (location == locationValue.SIM && target.originLocation == locationValue.DEVICE) {
+ showConfirm("change_device_to_sim_confirm", function () {
+ saveBook(editIndex);
+ });
+ } else {
+ saveBook(editIndex);
+ }
+ };
+ //打开添加电话本记录页面事件
+ target.openNewPage = function () {
+ if (target.pageState() == pageState.SEND_MSM) {
+ pbDraftListener();
+ smsPageCheckDraft(openNewPageAct, false);
+ } else if (target.pageState() == pageState.EDIT && (target.preContent.location != target.selectedLocation()
+ || target.preContent.name != target.name()
+ || target.preContent.mobile_phone_number != target.mobile_phone_number()
+ || target.preContent.home_phone_number != target.home_phone_number()
+ || target.preContent.office_phone_number != target.office_phone_number()
+ || target.preContent.mail != target.mail()
+ || target.preContent.group != target.selectedGroup())) {
+ showConfirm("leave_page_info", {
+ ok: function () {
+ openNewPageAct(false);
+ },
+ no: function () {
+ return false;
+ }
+ });
+ } else {
+ openNewPageAct(false);
+ }
+ };
+ function openNewPageAct(isNeedInit) {
+ target.pageState(pageState.NEW);
+ target.selectedLocation(locationValue.DEVICE);
+ target.originLocation = "";
+ if (target.checkHasSIMCard(false)) {
+ target.locations(saveLocationOpts(true));
+ } else {
+ target.locations(saveLocationOpts(false));
+ }
+ var group = getCurrentGroup();
+ if (group != "all") {
+ target.selectedGroup(group);
+ } else {
+ target.selectedGroup("common");
+ }
+ target.name("");
+ target.mobile_phone_number("");
+ target.home_phone_number("");
+ target.office_phone_number("");
+ target.mail("");
+ target.index(-1);
+ target.dynamicTranslate();
+ preOpenEditPage();
+ }
+ //打开添加电话本记录编辑页面事件
+ target.openPage = function (option) {
+ var index;
+ if (target.pageState() == pageState.LIST) {
+ var result = target.checkSelect(option);
+ if (!result.isCorrectData)
+ return;
+ index = result.selectedIds[0];
+ } else {
+ index = target.index();
+ }
+ target.editBooks(index, option);
+ };
+ //打开添加电话本记录查看页面事件
+ target.openViewPage = function () {
+ target.openPage("view");
+ };
+ //打开添加电话本记录查看页面事件
+ target.openEditPage = function () {
+ target.openPage("edit");
+ if ($.browser.mozilla) {
+ $("#txtName, #txtMobile").removeAttr('maxlength');
+ }
+ preOpenEditPage();
+ };
+ //编辑电话本事件处理
+ target.editBooks = function (selectedId, option) {
+ if (!selectedId)
+ return;
+
+ if (target.checkHasSIMCard(false)) {
+ target.locations(saveLocationOpts(true));
+ } else {
+ target.locations(saveLocationOpts(false));
+ }
+ var data = target.books();
+ for (var i = 0; i < data.length; i++) {
+ var n = data[i];
+ if (n.index == selectedId) {
+ target.index(n.index);
+ target.selectedLocation(n.location);
+ target.originLocation = n.location;
+ var trans = (n.location == locationValue.DEVICE) ? "device" : "sim";
+ target.locationTrans(trans);
+ var transText = $.i18n.prop("trans");
+ target.locationTransText(transText);
+ target.name(n.name);
+ target.mobile_phone_number(n.mobile_phone_number);
+ target.home_phone_number(n.home_phone_number);
+ target.office_phone_number(n.office_phone_number);
+ target.mail(n.mail);
+ target.selectedGroup(n.group);
+ target.groupTrans("group_" + n.group);
+ target.groupTransText($.i18n.prop(target.groupTrans()));
+ if (option == "edit") {
+ target.pageState(pageState.EDIT);
+ } else {
+ target.pageState(pageState.VIEW);
+ }
+ break;
+ }
+ }
+ target.dynamicTranslate();
+
+ if (target.selectedLocation() == locationValue.SIM) {
+ target.checkHasSIMCard(true)
+ }
+ };
+ //翻译编辑区域
+ target.dynamicTranslate = function () {
+ $("#container").translate();
+ };
+ //删除一条电话本事件处理(card模式使用)
+ target.deleteOneBook = function (index) {
+ showConfirm("confirm_pb_delete", function () {
+ showLoading('deleting');
+ var params = {};
+ params.indexs = [String(index)];
+ service.deletePhoneBooks(params, target.callback);
+ });
+ return false;
+ };
+ //删除一条电话本事件处理
+ target.deleteBook = function () {
+ target.deleteOneBook(target.index());
+ };
+ //删除一条或多条电话本事件处理
+ target.deleteBooks = function () {
+ var result = target.checkSelect("delete");
+ if (!result.isCorrectData)
+ return;
+ showConfirm("confirm_pb_delete", function () {
+ showLoading('deleting');
+ var params = {};
+ params.indexs = result.selectedIds;
+ service.deletePhoneBooks(params, target.callback);
+ });
+ };
+ //判断电话本选中
+ target.checkSelect = function (pState) {
+ var ids;
+ if ("send" == pState) {
+ ids = target.gridTemplate.selectedPrimaryValue();
+ } else {
+ ids = target.gridTemplate.selectedIds();
+ }
+
+ var isCorrectData = true;
+ if (ids.length == 0) {
+ showAlert("no_data_selected");
+ isCorrectData = false;
+ } else if ("edit" == pState || "view" == pState) {
+ if (ids.length > 1) {
+ showAlert("too_many_data_selected");
+ isCorrectData = false;
+ }
+ } else if ("send" == pState) {
+ if (ids.length > 5) {
+ showAlert("max_send_number");
+ isCorrectData = false;
+ }
+ }
+ return {
+ selectedIds: ids,
+ isCorrectData: isCorrectData
+ };
+ };
+ //全部删除电话本事件处理
+ target.deleteAllBooks = function () {
+ showConfirm("confirm_data_delete", function () {
+ showLoading('deleting');
+ var group = getCurrentGroup();
+ var params = {};
+ if (group == "all") {
+ params.location = 2;
+ service.deleteAllPhoneBooks(params, target.callback);
+ } else {
+ params.location = 3;
+ params.group = group;
+ service.deleteAllPhoneBooksByGroup(params, target.callback);
+ }
+ });
+ };
+
+ target.callback = function (data) {
+ if (data && data.result == "success") {
+ target.clear(true);
+ $("#books ").translate();
+ renderCheckbox();
+ successOverlay(null, true);
+ } else {
+ errorOverlay();
+ }
+ };
+ //变换显示方式事件处理
+ target.changeTemplate = function () {
+ if (target.gridTemplate.tmplType == "card") {
+ target.gridTemplate.tmplType = "list";
+ target.gridTemplate.pageSize = 10;
+ target.gridTemplate.columns = templateColumns.listColumns;
+ } else {
+ target.gridTemplate.tmplType = "card";
+ target.gridTemplate.pageSize = 10;
+ target.gridTemplate.columns = templateColumns.cardColumns;
+ }
+ refreshPage();
+ $("#books ").translate();
+ };
+ //显示发送短信页面
+ target.openSendMessagePage = function () {
+ if (pageState.SEND_MSM == target.pageState()) {
+ return;
+ }
+ if ((target.pageState() == pageState.EDIT || pageState.NEW == target.pageState()) && (target.preContent.location != target.selectedLocation()
+ || target.preContent.name != target.name()
+ || target.preContent.mobile_phone_number != target.mobile_phone_number()
+ || target.preContent.home_phone_number != target.home_phone_number()
+ || target.preContent.office_phone_number != target.office_phone_number()
+ || target.preContent.mail != target.mail()
+ || target.preContent.group != target.selectedGroup())) {
+ showConfirm("leave_page_info", {
+ ok: function () {
+ openSendMessagePageAct();
+ },
+ no: function () {
+ return false;
+ }
+ });
+ } else {
+ openSendMessagePageAct();
+ }
+ };
+
+ function openSendMessagePageAct() {
+ if (pageState.NEW == target.pageState()) {
+ target.pageState(pageState.SEND_MSM);
+ showAlert("no_data_selected");
+ target.clear();
+ return;
+ }
+ var selectedNumber = null;
+ if (pageState.LIST == target.pageState()) {
+ var result = target.checkSelect("send");
+ if (!result.isCorrectData)
+ return;
+ selectedNumber = result.selectedIds;
+ } else {
+ selectedNumber = target.mobile_phone_number();
+ }
+
+ var select = $("#chosenUserList .chosen-select-deselect");
+ select.empty();
+ var options = [];
+ var tmp = [];
+ for (var j = 0; j < config.phonebook.length; j++) {
+ var book = config.phonebook[j];
+ if ($.inArray(book.pbm_number, tmp) == -1) {
+ options.push(new Option(book.pbm_name + "/" + book.pbm_number, book.pbm_number, false, true));
+ tmp.push(book.pbm_number);
+ } else {
+ for (var i = 0; i < options.length; i++) {
+ if (options[i].value == book.pbm_number) {
+ options[i].text = book.pbm_name + "/" + book.pbm_number;
+ break;
+ }
+ }
+ }
+ }
+ var opts = "";
+ $.each(options, function (i, e) {
+ opts += "<option value='" + HTMLEncode(e.value) + "'>" + HTMLEncode(e.text) + "</option>";
+ });
+ select.append(opts);
+ select.chosen({
+ max_selected_options: 5,
+ search_contains: true,
+ width: '545px'
+ });
+ $("#chosenUserSelect").val(selectedNumber);
+ $("#chosenUserSelect").trigger("chosen:updated.chosen");
+ config.resetContentModifyValue();
+ pbDraftListener();
+ target.pageState(pageState.SEND_MSM);
+ }
+
+ //发送短信
+ target.sendMessage = function () {
+ service.getSmsCapability({}, function (capability) {
+ var hasCapability = capability.nvUsed < capability.nvTotal;
+ if (!hasCapability) {
+ showAlert("sms_capacity_is_full_for_send");
+ return false;
+ }
+ var numbers = syncSelectAndChosen($("select#chosenUserSelect"), $('.search-choice', '#chosenUserSelect_chosen'));
+ if (numbers.length + capability.nvUsed > capability.nvTotal) {
+ showAlert({
+ msg: "sms_capacity_will_full_just",
+ params: [capability.nvTotal - capability.nvUsed]
+ });
+ return false;
+ }
+ target.sendMessageAction();
+ return true;
+ });
+ };
+
+ target.sendMessageAction = function () {
+ var numbers = syncSelectAndChosen($("select#chosenUserSelect"), $('.search-choice', '#chosenUserSelect_chosen'));
+
+ if (!numbers || numbers.length == 0) {
+ target.showErrorInfo(true);
+ var timer = addTimeout(function () {
+ target.showErrorInfo(false);
+ window.clearTimeout(timer);
+ }, 5000);
+ return;
+ }
+ var content = target.messageContent();
+ var sentCount = 0;
+ var failCount = 0;
+ if (numbers.length > 1) {
+ showLoading("sending", "<button id='btnStopSending' onclick='phoneBookStopSMSSending();' class='btn btn-primary'>"
+ + $.i18n.prop("sms_stop_sending")
+ + "</button>");
+ } else {
+ showLoading('sending');
+ }
+ var callback = function (data) {
+ sentCount++;
+ if (sentCount == numbers.length) {
+ $("#chosenUserSelect").val("");
+ target.messageContent("");
+ config.CONTENT_MODIFIED.modified = false;
+ if (failCount == 0) {
+ successOverlay();
+ location.hash = "#msg_list";
+ } else {
+ var msg = $.i18n.prop("success_info") + $.i18n.prop("colon") + (sentCount - failCount)
+ + "<br/>" + $.i18n.prop("error_info") + $.i18n.prop("colon") + (failCount);
+ showAlert(msg, function () {
+ location.hash = "#msg_list";
+ });
+ }
+
+ } else {
+ sendSMS();
+ }
+ }
+ _phoneBookStopSMSSending = false;
+ var sendSMS = function () {
+ if (_phoneBookStopSMSSending) {
+ hideLoading();
+ return;
+ }
+ if ((sentCount + 1) == numbers.length) {
+ $("#loading #loading_container").html("");
+ }
+ service.sendSMS({
+ number: numbers[sentCount],
+ message: content,
+ id: -1
+ }, function (data) {
+ callback(data);
+ }, function (data) {
+ failCount++;
+ callback(data);
+ });
+ };
+ sendSMS();
+ };
+ //清除搜索关键字事件
+ target.clearSearchKey = function () {
+ target.gridTemplate.searchInitStatus(true);
+ target.gridTemplate.searchKey($.i18n.prop("search"));
+ $("#ko_grid_search_txt").addClass("ko-grid-search-txt-default").attr("data-trans", "search");
+ };
+ //点击搜索输入框事件
+ target.searchTextClick = function () {
+ var searchText = $("#ko_grid_search_txt");
+ if (searchText.hasClass("ko-grid-search-txt-default")) {
+ target.gridTemplate.searchKey("");
+ target.gridTemplate.searchInitStatus(false);
+ searchText.removeClass("ko-grid-search-txt-default").removeAttr("data-trans");
+ }
+ };
+ //离开搜索输入框事件
+ target.searchTextBlur = function () {
+ var txt = $.trim(target.gridTemplate.searchKey()).toLowerCase();
+ if (txt == "") {
+ target.clearSearchKey();
+ }
+ };
+ //当前表格是否有数据
+ target.hasData = ko.computed(function () {
+ return target.gridTemplate.afterSearchData().length > 0;
+ });
+ //当前表格是否有选中的数据
+ target.hasChecked = ko.computed(function () {
+ return target.gridTemplate.checkedCount() > 0;
+ });
+ //是否可以点击发送按钮
+ target.canSend = ko.computed(function () {
+ var checked = target.gridTemplate.checkedCount();
+ if (!target.checkHasSIMCard(false)) {
+ return false;
+ }
+ return (checked > 0 && checked <= 5);
+ });
+
+ //发送短信时,选择用户变化的监控事件
+ target.draftListenerEvent = function () {
+ pbDraftListener();
+ };
+ //文档内容监听,判断是否修改过
+ function pbDraftListener() {
+ var smsHasCapability = true;
+ if (smsHasCapability) {
+ var content = target.messageContent();
+ var hasContent = false;
+ var numbers = getSelectValFromChosen($('.search-choice', '#chosenUserSelect_chosen'));
+ var noContactSelected = !(numbers && numbers.length > 0);
+ if (typeof content == "undefined" || content == '') {
+ config.resetContentModifyValue();
+ return false;
+ } else {
+ hasContent = true;
+ }
+ if (hasContent && !noContactSelected) {
+ config.CONTENT_MODIFIED.modified = true;
+ config.CONTENT_MODIFIED.message = 'sms_to_save_draft';
+ config.CONTENT_MODIFIED.callback.ok = saveDraftAction;
+ config.CONTENT_MODIFIED.callback.no = $.noop;
+ config.CONTENT_MODIFIED.data = {
+ content: content,
+ numbers: numbers
+ };
+ return false;
+ }
+ if (hasContent && noContactSelected) {
+ config.CONTENT_MODIFIED.modified = true;
+ config.CONTENT_MODIFIED.message = 'sms_no_recipient';
+ config.CONTENT_MODIFIED.callback.ok = $.noop;
+ config.CONTENT_MODIFIED.callback.no = function () {
+ // 返回true,页面保持原状
+ return true;
+ };
+ return false;
+ }
+ }
+ /*else { cov_2
+ config.resetContentModifyValue();
+ }*/
+ }
+
+ function saveDraftAction(data) {
+ var datetime = new Date();
+ var params = {
+ index: -1,
+ currentTimeString: getCurrentTimeString(datetime),
+ groupId: data.numbers.length > 1 ? datetime.getTime() : '',
+ message: data.content,
+ numbers: data.numbers
+ };
+ service.saveSMS(params, function () {
+ successOverlay('sms_save_draft_success');
+ }, function () {
+ errorOverlay("sms_save_draft_failed")
+ });
+ }
+ function smsPageCheckDraft(clearCallback, isNeedInit) {
+ if (config.CONTENT_MODIFIED.message != 'sms_to_save_draft') {
+ if (config.CONTENT_MODIFIED.modified) {
+ showConfirm(config.CONTENT_MODIFIED.message, {
+ ok: function () {
+ config.CONTENT_MODIFIED.callback.ok(config.CONTENT_MODIFIED.data);
+ clearCallback(isNeedInit);
+ },
+ no: function () {
+ if (config.CONTENT_MODIFIED.message == 'sms_to_save_draft') {
+ clearCallback(isNeedInit);
+ }
+ return false;
+ }
+ });
+ return false;
+ } else {
+ clearCallback(isNeedInit);
+ }
+ } else {
+ config.CONTENT_MODIFIED.callback.ok(config.CONTENT_MODIFIED.data);
+ clearCallback(isNeedInit);
+ }
+ }
+
+ //重新获取页面数据并显示
+ function getPhoneBookReady() {
+ service.getPhoneBookReady({}, function (data) {
+ if (data.pbm_init_flag == "6") {
+ target.initFail(true);
+ hideLoading();
+ showAlert("phonebook_init_fail");
+ } else if (data.pbm_init_flag != "0") {
+ addTimeout(getPhoneBookReady, 1000);
+ } else {
+ target.initFail(false);
+ var capacity = getCapacity();
+ target.capacity(capacity);
+ target.phoneBookCapacity(capacity.Ratio);
+ var phoneBooks = getBooks(capacity.Used);
+ target.books(phoneBooks);
+ target.gridTemplate.data(phoneBooks);
+ $('#books').find('tbody').translate();
+ hideLoading();
+ }
+ });
+ }
+
+ showLoading('waiting');
+ addTimeout(getPhoneBookReady, 200);
+
+ //重新获取页面数据并显示
+ function refreshPage() {
+ showLoading();
+ var capacity = getCapacity();
+ target.phoneBookCapacity(capacity.Ratio);
+ target.capacity(capacity);
+ var books = getBooks(capacity.Used);
+ target.books(books);
+ target.gridTemplate.data(books);
+ hideLoading();
+ }
+
+ target.preContent = {};
+ //保存编辑前的内容
+ function setPreContent() {
+ target.preContent.location = target.selectedLocation();
+ target.preContent.name = target.name();
+ target.preContent.mobile_phone_number = target.mobile_phone_number();
+ target.preContent.home_phone_number = target.home_phone_number();
+ target.preContent.office_phone_number = target.office_phone_number();
+ target.preContent.mail = target.mail();
+ target.preContent.group = target.selectedGroup();
+ }
+
+ //检测数据是否改变
+ function checkContentChang() {
+ var changed = (target.preContent.location != target.selectedLocation()
+ || target.preContent.name != target.name()
+ || target.preContent.mobile_phone_number != target.mobile_phone_number()
+ || target.preContent.home_phone_number != target.home_phone_number()
+ || target.preContent.office_phone_number != target.office_phone_number()
+ || target.preContent.mail != target.mail()
+ || target.preContent.group != target.selectedGroup());
+ config.CONTENT_MODIFIED.modified = changed;
+ }
+
+ function preOpenEditPage() {
+ config.resetContentModifyValue();
+ setPreContent();
+ config.CONTENT_MODIFIED.checkChangMethod = checkContentChang;
+ }
+ }
+
+ //设置停止发送标志为true
+ phoneBookStopSMSSending = function () {
+ _phoneBookStopSMSSending = true;
+ $("#loading #loading_container").html($.i18n.prop("sms_cancel_sending"));
+ }
+
+ //获取电话本
+ function getBooks(capacity) {
+ var para = {};
+ para.page = 0;
+ para.data_per_page = capacity;
+ para.orderBy = "name";
+ para.isAsc = true;
+ var books = [];
+ var group = getCurrentGroup();
+ if (config.HAS_SMS) {
+ books = service.getPhoneBooks(para);
+ config.phonebook = books.pbm_data;
+ if (group != "all") {
+ books = {
+ "pbm_data": _.filter(books.pbm_data, function (item) {
+ return item.pbm_group == group;
+ })
+ };
+ }
+ } else {
+ if (group != "all") {
+ para.group = group;
+ books = service.getPhoneBooksByGroup(para);
+ } else {
+ books = service.getPhoneBooks(para);
+ }
+ }
+ return translateData(books.pbm_data);
+ }
+
+ //获取电话本容量信息
+ function getCapacity() {
+ var sim = service.getSIMPhoneBookCapacity();
+ var device = service.getDevicePhoneBookCapacity();
+ return {
+ simUsed: sim.simPbmUsedCapacity,
+ deviceUsed: device.pcPbmUsedCapacity,
+ simCapacity: sim.simPbmTotalCapacity,
+ deviceCapacity: device.pcPbmTotalCapacity,
+ simMaxNameLen: sim.maxNameLen,
+ simMaxNumberLen: sim.maxNumberLen,
+ IsSimCardFull: (sim.simPbmUsedCapacity == sim.simPbmTotalCapacity),
+ IsDeviceFull: (device.pcPbmUsedCapacity == device.pcPbmTotalCapacity),
+ Used: sim.simPbmUsedCapacity + device.pcPbmUsedCapacity,
+ Capacity: sim.simPbmTotalCapacity + device.pcPbmTotalCapacity,
+ Ratio: "(" + (sim.simPbmUsedCapacity + device.pcPbmUsedCapacity) + "/" + (sim.simPbmTotalCapacity + device.pcPbmTotalCapacity) + ")"
+ };
+ }
+
+ function translateData(books) {
+ var ret = [];
+ var group = getCurrentGroup();
+ var hasFilter = (group != "all");
+ if (books) {
+ for (var i = 0; i < books.length; i++) {
+ if (hasFilter) {
+ var currentGroup = books[i].pbm_group;
+ if (books[i].pbm_location == locationValue.SIM || currentGroup != group) {
+ continue;
+ }
+ }
+ var temp = {
+ index: books[i].pbm_id,
+ location: books[i].pbm_location,
+ imgLocation: books[i].pbm_location == locationValue.SIM ? "pic/simcard.png" : "pic/res_device.png",
+ name: books[i].pbm_name,
+ mobile_phone_number: books[i].pbm_number,
+ home_phone_number: books[i].pbm_anr,
+ office_phone_number: books[i].pbm_anr1,
+ mail: books[i].pbm_email,
+ group: books[i].pbm_group,
+ transGroup: (!books[i].pbm_group) ? "group_null" : "group_" + books[i].pbm_group
+ };
+ ret.push(temp);
+ }
+ }
+ return ret;
+ }
+ //初始化ViewModel并进行绑定
+ function init() {
+ var container = $('#container');
+ ko.cleanNode(container[0]);
+ var vm = new pbViewMode();
+ ko.applyBindings(vm, container[0]);
+ $("#txtSmsContent").die().live("contextmenu", function () {
+ return false;
+ });
+ $('#frmPhoneBook').validate({
+ submitHandler: function () {
+ vm.save();
+ },
+ rules: {
+ txtMail: "email_check",
+ txtName: "name_check",
+ txtMobile: "phonenumber_check",
+ txtHomeNumber: "phonenumber_check",
+ txtOfficeNumber: "phonenumber_check"
+ }
+ });
+
+ }
+
+ return {
+ init: init
+ };
+});
+
+define("sms_list","underscore jquery knockout set service jq_chosen".split(" "),
+ function (_, $, ko, config, service, chosen) {
+
+ var currentPage = 1;
+ //数据是否加载完成
+ var ready = false,
+ //聊天室信息正在加载中
+ chatRoomInLoading = false;
+ //快速添加联系人模板
+ var addPhonebookTmpl = null,
+ //短消息模板
+ smsTableTmpl = null,
+ //接收短消息模板
+ smsOtherTmpl = null,
+ //发送短消息模板
+ smsMeTmpl = null,
+ //群聊草稿
+ groupDrafts = [],
+ //短消息列表显示群聊草稿
+ groupDraftItems = [],
+ //短消息列表显示群聊草稿及其草稿群聊细节
+ groupedDraftsObject = {},
+ //短消息容量信息
+ smsCapability = {},
+ //短消息是否还有存储空间
+ hasCapability = true;
+ //获取全部短消息,并将短信通过回调函数getPhoneBooks,与电话本进行关联
+ function getSMSMessages(callback) {
+ return service.getSMSMessages({
+ page: 0,
+ smsCount: 500,
+ nMessageStoreType: 1,
+ tags: 10,
+ orderBy: "order by id desc"
+ }, function (data) {
+ tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), data.messages.length);
+ config.dbMsgs = data.messages;
+ config.listMsgs = groupSms(config.dbMsgs);
+ callback();
+ }, function () {
+ tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), 0);
+ config.dbMsgs = [];
+ config.listMsgs = [];
+ cleanSmsList();
+ });
+ }
+
+ //清楚短消息列表内容
+ cleanSmsList = function () {
+ $("#smslist-table").empty();
+ };
+
+ //关联后的短消息根据电话号码进行分组
+ function groupSms(messages) {
+ var peoples = {},
+ theSortedPeoples = [];
+ config.listMsgs = [];
+ groupDrafts = [];
+ $.each(messages, function (i, e) {
+ if (e.tag == '4' && e.groupId != '') { // 群聊草稿
+ groupDrafts.push(e);
+ return;
+ }
+ e.target = e.number;
+ if (parseInt(e.id, 10) > config.smsMaxId) {
+ config.smsMaxId = e.id;
+ }
+ var last8 = getLastNumber(e.number, config.SMS_MATCH_LENGTH);
+ if (last8 in peoples) {
+ peoples[last8].push(e);
+ } else {
+ peoples[last8] = [e];
+ theSortedPeoples.push(e);
+ }
+ });
+ theSortedPeoples = _.sortBy(theSortedPeoples, function (ele) {
+ return 0 - parseInt(ele.id + "", 10);
+ });
+ $.each(theSortedPeoples, function (s_i, sp) {
+ var people = getLastNumber(sp.number, config.SMS_MATCH_LENGTH);
+ var newCount = 0;
+ var hasDraft = false;
+ for (var i = 0; i < peoples[people].length; i++) {
+ if (peoples[people][i].isNew) {
+ newCount++;
+ }
+ if (peoples[people][i].tag == '4' && peoples[people][i].groupId == '') { // 单条草稿
+ hasDraft = true;
+ }
+ }
+ config.listMsgs.push({
+ id: peoples[people][0].id,
+ name: "",
+ number: peoples[people][0].number,
+ latestId: peoples[people][0].id,
+ totalCount: peoples[people].length,
+ newCount: newCount,
+ latestSms: peoples[people][0].content,
+ latestTime: peoples[people][0].time,
+ checked: false,
+ itemId: getLastNumber(people, config.SMS_MATCH_LENGTH),
+ groupId: peoples[people][0].groupId,
+ hasDraft: hasDraft
+ });
+ });
+ return config.listMsgs;
+ }
+
+ //获取电话本信息,并与短消息关联
+ function getPhoneBooks() {
+ var books = service.getPhoneBooks({
+ page: 0,
+ data_per_page: 2000,
+ orderBy: "name",
+ isAsc: true
+ });
+ if ($.isArray(books.pbm_data) && books.pbm_data.length > 0) {
+ config.phonebook = books.pbm_data;
+ }
+ dealPhoneBooks();
+ }
+
+ //双异步获取设备侧和sim卡侧的短信息,并将其合并
+ function dealPhoneBooks() {
+ var select = $("#chosenUserList .chosen-select-deselect");
+ select.empty();
+ var options = [];
+ var tmp = [];
+ var pbTmp = [];
+ for (var j = 0; j < config.phonebook.length; j++) {
+ var book = config.phonebook[j];
+ var last8Num = getLastNumber(book.pbm_number, config.SMS_MATCH_LENGTH);
+ if (last8Num && $.inArray(last8Num, pbTmp) == -1) {
+ options.push(new Option(book.pbm_name + "/" + book.pbm_number, last8Num, false, true));
+ if ($.inArray(last8Num, tmp) == -1) {
+ tmp.push(last8Num);
+ }
+ pbTmp.push(last8Num);
+ } else {
+ for (var i = 0; i < options.length; i++) {
+ if (options[i].value == last8Num) {
+ options[i].text = book.pbm_name + "/" + book.pbm_number;
+ break;
+ }
+ }
+ }
+ }
+ var groupIds = [];
+ for (var k = 0; k < groupDrafts.length; k++) { // 将草稿做对象Map封装,供草稿组点击后的草稿分解
+ if ($.inArray(groupDrafts[k].groupId, groupIds) == -1) {
+ groupIds.push(groupDrafts[k].groupId);
+ var draft = groupDrafts[k];
+ groupedDraftsObject[groupDrafts[k].groupId] = [draft];
+ } else {
+ var draft = groupDrafts[k];
+ groupedDraftsObject[groupDrafts[k].groupId].push(draft);
+ }
+ var itemId = getLastNumber(groupDrafts[k].number, config.SMS_MATCH_LENGTH);
+ if ($.inArray(itemId, tmp) == -1) {
+ options.push(new Option(groupDrafts[k].number, itemId));
+ tmp.push(itemId);
+ }
+ }
+ for (var g in groupedDraftsObject) { // 处理列表显示的草稿信息
+ var drafts = groupedDraftsObject[g];
+ var draftItem = drafts[drafts.length - 1];
+ draftItem.draftShowName = '';
+ draftItem.draftShowNameTitle = '';
+ $.each(drafts, function (i, n) {
+ var showName = getShowNameByNumber(n.number);
+ draftItem.draftShowName += (i == 0 ? '' : ';') + showName;
+ draftItem.draftShowNameTitle += (i == 0 ? '' : ';') + showName;
+ });
+
+ var len = 10;
+ if (getEncodeType(draftItem.draftShowName).encodeType == "UNICODE") {
+ len = 10;
+ }
+ draftItem.draftShowName = draftItem.draftShowName.length > len ? draftItem.draftShowName.substring(0, len) + "..." : draftItem.draftShowName;
+ draftItem.totalCount = drafts.length;
+ draftItem.hasDraft = true;
+ draftItem.latestTime = draftItem.time;
+ groupDraftItems.push(draftItem);
+ }
+ for (var i = 0; i < config.listMsgs.length; i++) {
+ var smsItem = config.listMsgs[i];
+ for (var j = config.phonebook.length; j > 0; j--) {
+ var book = config.phonebook[j - 1];
+ var last8Num = getLastNumber(book.pbm_number, config.SMS_MATCH_LENGTH);
+ if (smsItem.itemId == last8Num) {
+ smsItem.name = book.pbm_name;
+ for (var k = 0; k < options.length; k++) {
+ if (last8Num == options[k].value) {
+ options[k].value = getLastNumber(smsItem.number, config.SMS_MATCH_LENGTH);
+ options[k].text = book.pbm_name + '/' + smsItem.number;
+ break;
+ }
+ }
+ break;
+ }
+ }
+ if ($.inArray(smsItem.itemId, tmp) == -1) {
+ options.push(new Option(smsItem.number, getLastNumber(smsItem.number, config.SMS_MATCH_LENGTH)));
+ tmp.push(smsItem.itemId);
+ }
+ }
+
+ var opts = "";
+ $.each(options, function (i, e) {
+ opts += "<option value='" + HTMLEncode(e.value) + "'>" + HTMLEncode(e.text) + "</option>";
+ });
+ select.append(opts);
+ select.chosen({
+ max_selected_options: 5,
+ search_contains: true,
+ width: '740px'
+ });
+ showSmsListData();
+ showMultiDraftListData();
+ //changeShownMsgs();
+ ready = true;
+ }
+
+ function showSmsListData() {
+ if (smsTableTmpl == null) {
+ smsTableTmpl = $.template("smsTableTmpl", $("#smsTableTmpl"));
+ }
+ cleanSmsList();
+ $.tmpl("smsTableTmpl", {
+ data: config.listMsgs
+ }).translate().appendTo("#smslist-table");
+
+ if (config.HAS_PHONEBOOK) {
+ $(".sms-add-contact-icon").removeClass("hide");
+ } else {
+ $(".sms-add-contact-icon").addClass("hide");
+ }
+ }
+ //群组草稿列表显示
+ function showMultiDraftListData() {
+ if (groupDraftItems.length == 0) {
+ return false;
+ }
+ if (smsTableTmpl == null) {
+ smsTableTmpl = $.template("smsTableTmpl", $("#smsTableTmpl"));
+ }
+ $.tmpl("smsTableTmpl", {
+ data: groupDraftItems
+ }).translate().prependTo("#smslist-table");
+ }
+
+ // 页面发生滚动后,改变页面显示的短消息
+ function changeShownMsgs() {
+ var shownMsgsTmp = [];
+ var range = _.range((currentPage - 1) * 5, currentPage * 5);
+ $.each(range, function (i, e) {
+ if (config.listMsgs[e]) {
+ shownMsgsTmp.push(config.listMsgs[e]);
+ }
+ });
+ //shownMsgsTmp = config.listMsgs;
+ currentPage++;
+
+ if (smsTableTmpl == null) {
+ smsTableTmpl = $.template("smsTableTmpl", $("#smsTableTmpl"));
+ }
+ $.tmpl("smsTableTmpl", {
+ data: shownMsgsTmp
+ }).translate().appendTo("#smslist-table");
+
+ renderCheckbox();
+ if (shownMsgsTmp.length == 0) {
+ disableBtn($("#smslist-delete-all"));
+ tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), 0);
+ } else {
+ enableBtn($("#smslist-delete-all"));
+ tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), 1);
+ }
+ if (currentPage == 2 && window.innerHeight == $("body").height()) {
+ changeShownMsgs();
+ }
+ return shownMsgsTmp;
+ }
+
+ //将被checked的条目添加到self.checkedItem中,用于在滚动还原checkbox
+ checkboxClickHandler = function (id) {
+ checkDeleteBtnStatus();
+ };
+
+ //获取已选择的条目
+ getSelectedItem = function () {
+ var selected = [];
+ var checkedItem = $("#smslist-table input:checkbox:checked");
+ checkedItem.each(function (i, e) {
+ selected.push($(e).val());
+ });
+ return selected;
+ };
+
+ //删除按钮是否禁用
+ checkDeleteBtnStatus = function () {
+ var size = getSelectedItem().length;
+ if (size == 0) {
+ disableBtn($("#smslist-delete"));
+ } else {
+ enableBtn($("#smslist-delete"));
+ }
+ };
+
+ //刷新短消息列表
+ refreshClickHandler = function () {
+ $("#smslist-table").empty();
+ disableBtn($("#smslist-delete"));
+ disableCheckbox($("#smslist-checkAll", "#smsListForm"));
+ init();
+ renderCheckbox();
+ };
+
+ //删除全部短消息
+ deleteAllClickHandler = function () {
+ showConfirm("confirm_data_delete", function () {
+ showLoading('deleting');
+ service.deleteAllMessages({
+ location: "native_inbox"
+ }, function (data) {
+ cleanSmsList();
+ tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), 0);
+ successOverlay();
+ }, function (error) {
+ errorOverlay(error.errorText);
+ });
+ });
+ };
+
+ //删除选中的短消息
+ deleteSelectClickHandler = function () {
+ showConfirm("confirm_sms_delete", function () {
+ showLoading('deleting');
+ var items = getIdsBySelectedIds();
+ service.deleteMessage({
+ ids: items.ids
+ }, function (data) {
+ renderAfterDelete(items);
+ disableBtn($("#smslist-delete"));
+ $("#checkbox-all").removeAttr("checked");
+ renderCheckbox();
+ successOverlay();
+ }, function (error) {
+ errorOverlay(error.errorText);
+ });
+ });
+
+ function renderAfterDelete(items) {
+ var ids = items.ids;
+ var nums = [];
+ $.each(config.dbMsgs, function (i, e) {
+ if ($.inArray(e.id, items.normalIds) != -1) {
+ nums.push(e.number);
+ }
+ });
+ nums = _.uniq(nums);
+ $.each(nums, function (i, e) {
+ $("#smslist-item-" + getLastNumber(e, config.SMS_MATCH_LENGTH)).hide().remove();
+ });
+ $.each(items.groups, function (i, e) {
+ $("#smslist-item-" + e).hide().remove();
+ });
+ synchSmsList(nums, ids);
+ }
+
+ function getIdsBySelectedIds() {
+ var nums = [];
+ var resultIds = [];
+ var normalIds = [];
+ var groups = [];
+ var selectedItem = getSelectedItem();
+ $.each(selectedItem, function (i, e) {
+ var checkbox = $("#checkbox" + e);
+ if (checkbox.attr("groupid")) {
+ groups.push(checkbox.attr("groupid"));
+ } else {
+ nums.push(getLastNumber(checkbox.attr("number"), config.SMS_MATCH_LENGTH));
+ }
+ });
+
+ $.each(config.dbMsgs, function (i, e) {
+ if ($.inArray(getLastNumber(e.number, config.SMS_MATCH_LENGTH), nums) != -1 && (typeof e.groupId == "undefined" || _.isEmpty(e.groupId + ''))) {
+ resultIds.push(e.id);
+ normalIds.push(e.id);
+ } else if ($.inArray(e.groupId + '', groups) != -1) { //删除草稿组
+ resultIds.push(e.id);
+ }
+ });
+ resultIds = _.uniq(resultIds);
+ return {
+ ids: resultIds,
+ groups: groups,
+ normalIds: normalIds
+ };
+ }
+ };
+
+ //新短信按钮点击
+ newMessageClickHandler = function () {
+ $("#chosenUser1", "#smsChatRoom").addClass("hide");
+ $("#chosenUser", "#smsChatRoom").show();
+
+ cleanChatInput();
+ checkSmsCapacityAndAlert();
+ $("select.chosen-select-deselect").val("").trigger("chosen:updated.chosen");
+ switchPage('chat');
+ gotoBottom();
+ clearChatList();
+ };
+
+ //返回聊天室列表
+ chatCancelClickHandler = function () {
+ if (config.CONTENT_MODIFIED.modified) {
+ var confirmMessage = 'sms_to_save_draft';
+ var selectedContact = syncSelectAndChosen($("select#chosenUserSelect"), $('.search-choice', '#chosenUserSelect_chosen'));
+ var noContactSelected = !selectedContact || selectedContact.length == 0;
+ if (noContactSelected) {
+ confirmMessage = 'sms_no_recipient';
+ }
+ if (noContactSelected) {
+ showConfirm(confirmMessage, {
+ ok: function () {
+ if (!noContactSelected) {
+ saveDraftAction({
+ content: $("#chat-input", "#smsChatRoom").val(),
+ numbers: selectedContact,
+ isFromBack: true
+ });
+ }
+ config.resetContentModifyValue();
+ backToSmsListMainPage();
+ },
+ no: function () {
+ if (noContactSelected) {
+ return true;
+ }
+ config.resetContentModifyValue();
+ backToSmsListMainPage();
+ }
+ });
+ } else {
+ saveDraftAction({
+ content: $("#chat-input", "#smsChatRoom").val(),
+ numbers: selectedContact,
+ isFromBack: true
+ });
+ config.resetContentModifyValue();
+ backToSmsListMainPage();
+ }
+ return false;
+ }
+ backToSmsListMainPage();
+ };
+
+ //跳转页面至SIM卡侧、设置界面
+ toOtherClickHandler = function (href) {
+ config.CONTENT_MODIFIED.checkChangMethod();
+ if (config.CONTENT_MODIFIED.modified) {
+ draftListener();
+ if (config.CONTENT_MODIFIED.message == 'sms_to_save_draft') {
+ config.CONTENT_MODIFIED.callback.ok(config.CONTENT_MODIFIED.data);
+ config.resetContentModifyValue();
+ window.location.hash = href;
+ } else {
+ showConfirm(config.CONTENT_MODIFIED.message, {
+ ok: function () {
+ config.CONTENT_MODIFIED.callback.ok(config.CONTENT_MODIFIED.data);
+ config.resetContentModifyValue();
+ window.location.hash = href;
+ },
+ no: function () {
+ var result = config.CONTENT_MODIFIED.callback.no(config.CONTENT_MODIFIED.data);
+ if (!result) {
+ window.location.hash = href;
+ config.resetContentModifyValue();
+ }
+ }
+ });
+ }
+ return false;
+ } else {
+ window.location.hash = href;
+ }
+ };
+
+ function backToSmsListMainPage() {
+ $("select.chosen-select-deselect").val("").trigger("chosen:updated.chosen");
+ config.currentChatObject = null;
+ $(".smslist-btns", "#smslist-main").removeClass('smsListFloatButs');
+ switchPage('list');
+ }
+
+ function switchPage(page) {
+ if (page == 'chat') {
+ $("#smslist-main").hide();
+ $("#smsChatRoom").show();
+ } else {
+ $("#smsChatRoom").hide();
+ $("#smslist-main").show();
+ }
+ }
+
+ var sendSmsErrorTimer = null;
+ //添加发送错误消息
+ addSendSmsError = function (msg) {
+ if (sendSmsErrorTimer) {
+ window.clearTimeout(sendSmsErrorTimer);
+ sendSmsErrorTimer = null;
+ }
+ $("#sendSmsErrorLi").text($.i18n.prop(msg));
+ sendSmsErrorTimer = addTimeout(function () {
+ $("#sendSmsErrorLi").text("");
+ }, 5000);
+ };
+
+ //发送短消息
+ sendSmsClickHandler = function () {
+ if (!hasCapability) {
+ showAlert("sms_capacity_is_full_for_send");
+ return;
+ }
+ var inputVal = $("#chat-input", "#smsChatRoom");
+ var msgContent = inputVal.val();
+ if (msgContent == $.i18n.prop("chat_input_placehoder")) {
+ inputVal.val("");
+ msgContent = "";
+ }
+ var nums = syncSelectAndChosen($("select#chosenUserSelect"), $('.search-choice', '#chosenUserSelect_chosen'));
+ if ($.isArray(nums)) {
+ nums = $.grep(nums, function (n, i) {
+ return !_.isEmpty(n);
+ });
+ }
+ if (!nums || nums.length == 0) {
+ addSendSmsError("sms_contact_required");
+ return;
+ }
+ if (nums.length + smsCapability.nvUsed > smsCapability.nvTotal) {
+ showAlert({
+ msg: "sms_capacity_will_full_just",
+ params: [smsCapability.nvTotal - smsCapability.nvUsed]
+ });
+ return;
+ }
+ if (nums.length == 1) {
+ config.currentChatObject = getLastNumber(nums[0], config.SMS_MATCH_LENGTH);
+ showLoading('sending');
+ } else if (nums.length > 1) {
+ showLoading("sending", "<button id='sms_cancel_sending' onclick='cancelSending()' class='btn btn-primary'>"
+ + $.i18n.prop("sms_stop_sending")
+ + "</button>");
+ config.currentChatObject = null;
+ }
+ var i = 0;
+ var leftNum = nums.length;
+ couldSend = true;
+ disableBtn($("#btn-send", "#inputpanel"));
+ sendSms = function () {
+ if (!couldSend) {
+ hideLoading();
+ return;
+ }
+ var newMsg = {
+ id: -1,
+ number: nums[i],
+ content: msgContent,
+ isNew: false
+ };
+
+ if (leftNum == 1) {
+ $("#loading #loading_container").html("");
+ }
+
+ leftNum--;
+ service.sendSMS({
+ number: newMsg.number,
+ message: newMsg.content,
+ id: -1
+ }, function (data) {
+ var latestMsg = getLatestMessage() || {
+ id: parseInt(config.smsMaxId, 10) + 1,
+ time: transUnixTime($.now()),
+ number: newMsg.number
+ };
+ config.smsMaxId = latestMsg.id;
+ newMsg.id = config.smsMaxId;
+ newMsg.time = latestMsg.time;
+ newMsg.tag = 2;
+ newMsg.hasDraft = false;
+ if (nums.length > 1) {
+ newMsg.targetName = getNameOrNumberByNumber(newMsg.number);
+ }
+ addSendMessage(newMsg, i + 1 != nums.length);
+ updateDBMsg(newMsg);
+ updateMsgList(newMsg);
+ tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
+ gotoBottom();
+ if (i + 1 == nums.length) {
+ updateChatInputWordLength();
+ enableBtn($("#btn-send", "#inputpanel"));
+ hideLoading();
+ return;
+ }
+ i++;
+ sendSms();
+ }, function (error) {
+ var latestMsg = getLatestMessage() || {
+ id: parseInt(config.smsMaxId, 10) + 1,
+ time: transUnixTime($.now()),
+ number: newMsg.number
+ };
+ config.smsMaxId = latestMsg.id;
+ newMsg.id = config.smsMaxId;
+ newMsg.time = latestMsg.time;
+ newMsg.errorText = $.i18n.prop(error.errorText);
+ newMsg.tag = 3;
+ newMsg.target = newMsg.number;
+ newMsg.hasDraft = false;
+ if (nums.length > 1) {
+ newMsg.targetName = getNameOrNumberByNumber(newMsg.number);
+ }
+ addSendMessage(newMsg, i + 1 != nums.length);
+ updateDBMsg(newMsg);
+ updateMsgList(newMsg);
+ tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
+ gotoBottom();
+ if (i + 1 == nums.length) {
+ updateChatInputWordLength();
+ enableBtn($("#btn-send", "#inputpanel"));
+ hideLoading();
+ return;
+ }
+ i++;
+ sendSms();
+ });
+ };
+ sendSms();
+ };
+
+ var couldSend = true;
+
+ //取消剩余短信发送操作
+ cancelSending = function () {
+ couldSend = false;
+ $("#loading #loading_container").html($.i18n.prop('sms_cancel_sending'));
+ };
+
+ //获取最新的短消息
+ getLatestMessage = function () {
+ var data = service.getSMSMessages({
+ page: 0,
+ smsCount: 5,
+ nMessageStoreType: 1,
+ tags: 10,
+ orderBy: "order by id desc"
+ });
+ if (data.messages.length > 0) {
+ for (var i = 0; i < data.messages.length; i++) {
+ if (data.messages[i].tag == '2' || data.messages[i].tag == '3') {
+ return data.messages[i];
+ }
+ }
+ return null;
+ } else {
+ return null;
+ }
+ };
+
+ //发送短信后,更新短信数据对象
+ function updateDBMsg(msg) {
+ if (config.dbMsgs.length == 0) {
+ config.dbMsgs = [msg];
+ } else {
+ /* cov_2
+ for(var j = 0; j < config.dbMsgs.length; j++){
+ if(config.dbMsgs[j].id == msg.id){
+ config.dbMsgs[j] = msg;
+ return;
+ } else {
+ var newMsg = [msg];
+ $.merge(newMsg, config.dbMsgs);
+ config.dbMsgs = newMsg;
+ return;
+ }
+ }
+ */
+ if (config.dbMsgs[0].id == msg.id) {
+ config.dbMsgs[0] = msg;
+ return;
+ } else {
+ var newMsg = [msg];
+ $.merge(newMsg, config.dbMsgs);
+ config.dbMsgs = newMsg;
+ return;
+ }
+ }
+ }
+
+ //发送短信后,更新短信列表, number不为空做删除处理,为空做增加处理
+ function updateMsgList(msg, number, counter) {
+ if ((!msg || !msg.number) && !number) {
+ return;
+ }
+ var itemId = '';
+ if (msg && typeof msg.groupId != "undefined" && msg.groupId != '') {
+ itemId = msg.groupId;
+ } else {
+ itemId = getLastNumber((number || msg.number), config.SMS_MATCH_LENGTH);
+ }
+ var item = $("#smslist-item-" + itemId);
+ if (item && item.length > 0) {
+ var totalCountItem = item.find(".smslist-item-total-count");
+ var count = totalCountItem.text();
+ count = Number(count.substring(1, count.length - 1));
+ if (number) {
+ if (count == 1 || msg == null) {
+ item.hide().remove();
+ return;
+ } else {
+ totalCountItem.text("(" + (count - (counter || 1)) + ")");
+ item.find(".smslist-item-draft-flag").addClass('hide');
+ }
+ } else {
+ totalCountItem.text("(" + (count + 1) + ")");
+ if (msg.tag == '4') {
+ item.find(".smslist-item-draft-flag").removeClass('hide');
+ }
+ }
+ item.find(".smslist-item-checkbox p.checkbox").attr("id", msg.id);
+ item.find(".smslist-item-checkbox input:checkbox").val(msg.id).attr("id", "checkbox" + msg.id);
+ var contentHtml = msg.content;
+ var msgContent;
+ if (msg.tag == '4') {
+ //contentHtml = '<span class="smslist-item-draft-flag colorRed" data-trans="draft"></span>: ' + contentHtml;
+ msgContent = item.find(".smslist-item-msg").html('<span class="smslist-item-draft-flag colorRed" data-trans="draft"></span>: ' + HTMLEncode(contentHtml)); //.addClass("font-weight-bold");
+ } else {
+ msgContent = item.find(".smslist-item-msg").html(HTMLEncode(contentHtml)); //.addClass("font-weight-bold");
+ }
+ //var msgContent = item.find(".smslist-item-msg").html(HTMLEncode(contentHtml)); //.addClass("font-weight-bold");
+ msgContent.closest('td').prop('title', msg.content);
+ item.find(".smslist-item-repeat span").die().click(function () {
+ forwardClickHandler(msg.id);
+ });
+ item.find("span.clock-time").text(msg.time);
+ var tmpItem = item;
+ item.hide().remove();
+ $("#smslist-table").prepend(tmpItem.show());
+ } else {
+ if (smsTableTmpl == null) {
+ smsTableTmpl = $.template("smsTableTmpl", $("#smsTableTmpl"));
+ }
+ msg.checked = false;
+ msg.newCount = 0;
+ msg.latestId = msg.id;
+ msg.latestSms = msg.content;
+ msg.latestTime = msg.time;
+ if (msg.groupId == '' || typeof msg.groupId == "undefined") {
+ msg.totalCount = 1;
+ }
+ if (!msg.hasDraft) {
+ msg.hasDraft = false;
+ }
+ msg.itemId = itemId;
+ msg.name = getNameByNumber(msg.number);
+ $.tmpl("smsTableTmpl", {
+ data: [msg]
+ }).translate().prependTo("#smslist-table");
+ }
+ if (config.HAS_PHONEBOOK) {
+ $(".sms-add-contact-icon").removeClass("hide");
+ } else {
+ $(".sms-add-contact-icon").addClass("hide");
+ }
+ $("#smslist-table").translate();
+ renderCheckbox();
+ }
+
+ //增加发送内容到聊天室, notCleanChatInput 是否清除输入框内容
+ addSendMessage = function (sms, notCleanChatInput) {
+ if (smsMeTmpl == null) {
+ smsMeTmpl = $.template("smsMeTmpl", $("#smsMeTmpl"));
+ }
+ $.tmpl("smsMeTmpl", sms).appendTo("#chatlist");
+ $("#chatlist").translate();
+ if (!notCleanChatInput) {
+ cleanChatInput();
+ }
+ clearMySmsErrorMessage(sms.id);
+ };
+
+ //清楚错误消息,避免翻译问题
+ clearMySmsErrorMessage = function (id) {
+ addTimeout(function () {
+ $("div.error", "#talk-item-" + id).text("");
+ }, 3000);
+ };
+
+ //快速添加联系人overlay是否打开
+ var isPoped = false;
+
+ //关闭快速添加联系人overlay
+ hidePopup = function () {
+ $(".tagPopup").remove();
+ isPoped = false;
+ };
+
+ //清空聊天室内容
+ clearChatList = function () {
+ $("#chatlist").empty();
+ updateChatInputWordLength();
+ };
+
+ //过滤短消息内容
+ dealContent = function (content) {
+ if (config.HAS_PHONEBOOK) {
+ return HTMLEncode(content).replace(/(\d{3,})/g, function (word) {
+ var r = (new Date().getTime() + '').substring(6) + (getRandomInt(1000) + 1000);
+ return "<a id='aNumber" + r + "' href='javascript:openPhoneBook(\"" + r + "\", \"" + word + "\")'>" + word + "</a>";
+ });
+ } else {
+ return HTMLEncode(content);
+ }
+
+ };
+
+ //打开快速添加联系人overlay
+ openPhoneBook = function (id, num) {
+ var target = null;
+ var outContainer = "";
+ var itemsContainer = null;
+ var isChatRoom = false;
+ if (!id) {
+ target = $("#listNumber" + getLastNumber(num, config.SMS_MATCH_LENGTH));
+ outContainer = ".smslist-item";
+ itemsContainer = $("#addPhonebookContainer");
+ } else {
+ target = $("#aNumber" + id);
+ outContainer = ".msg_container";
+ itemsContainer = $("#chatlist");
+ isChatRoom = true;
+ }
+ if (isPoped) {
+ hidePopup();
+ }
+ isPoped = true;
+ $("#tagPopup").remove();
+
+ if (addPhonebookTmpl == null) {
+ addPhonebookTmpl = $.template("addPhonebookTmpl", $("#addPhonebookTmpl"));
+ }
+ $.tmpl("addPhonebookTmpl", {
+ number: num
+ }).appendTo(itemsContainer);
+ var p = target.position();
+ var msgContainer = target.closest(outContainer);
+ var msgP = msgContainer.position();
+ var _left = 0,
+ _top = 0;
+ if (isChatRoom) {
+ var containerWidth = itemsContainer.width();
+ var containerHeight = itemsContainer.height();
+ var pop = $("#innerTagPopup");
+ _left = msgP.left + p.left;
+ _top = msgP.top + p.top + 20;
+ if (pop.width() + _left > containerWidth) {
+ _left = containerWidth - pop.width() - 20;
+ }
+ if (containerHeight > 100 && pop.height() + _top > containerHeight) {
+ _top = containerHeight - pop.height() - 5;
+ }
+ } else {
+ _left = p.left;
+ _top = p.top;
+ }
+ $("#innerTagPopup").css({
+ top: _top + "px",
+ left: _left + "px"
+ });
+ $('#quickSaveContactForm').translate().validate({
+ submitHandler: function () {
+ quickSaveContact(isChatRoom);
+ },
+ rules: {
+ name: "name_check",
+ number: "phonenumber_check"
+ }
+ });
+ };
+
+ //快速添加联系人
+ quickSaveContact = function () {
+ var name = $(".tagPopup #innerTagPopup #name").val();
+ var number = $(".tagPopup #innerTagPopup #number").val();
+ var newContact = {
+ index: -1,
+ location: 1,
+ name: name,
+ mobile_phone_number: number,
+ home_phone_number: "",
+ office_phone_number: "",
+ mail: ""
+ };
+ var device = service.getDevicePhoneBookCapacity();
+ if (device.pcPbmUsedCapacity >= device.pcPbmTotalCapacity) {
+ showAlert("device_full");
+ return false;
+ }
+ showLoading('waiting');
+ service.savePhoneBook(newContact, function (data) {
+ if (data.result == "success") {
+ config.phonebook.push({
+ pbm_name: name,
+ pbm_number: number
+ });
+ updateItemShowName(name, number);
+ hidePopup();
+ successOverlay();
+ } else {
+ errorOverlay();
+ }
+ }, function (data) {
+ errorOverlay();
+ });
+ };
+
+ function updateItemShowName(name, number) {
+ var lastNum = getLastNumber(number, config.SMS_MATCH_LENGTH);
+ $("span.smslist-item-name2", "#smslist-item-" + lastNum).text(name);
+ $("#listNumber" + lastNum).hide();
+ }
+
+ //聊天室删除单条消息
+ deleteSingleItemClickHandler = function (id, resendCallback) {
+ if (resendCallback) {
+ deleteTheSingleItem(id);
+ } else {
+ showConfirm("confirm_sms_delete", function () {
+ showLoading('deleting');
+ deleteTheSingleItem(id);
+ });
+ }
+
+ function deleteTheSingleItem(id) {
+ service.deleteMessage({
+ ids: [id]
+ }, function (data) {
+ var target = $(".smslist-item-delete", "#talk-item-" + id).attr("target");
+ $("#talk-item-" + id).hide().remove();
+
+ synchSmsList(null, [id]);
+ updateMsgList(getPeopleLatestMsg(target), target);
+ if (resendCallback) {
+ resendCallback();
+ } else {
+ hideLoading();
+ }
+ tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
+ }, function (error) {
+ if (resendCallback) {
+ resendCallback();
+ } else {
+ hideLoading();
+ }
+ });
+ }
+ };
+
+ //删除草稿
+ function deleteDraftSms(ids, numbers) {
+ stopNavigation();
+ service.deleteMessage({
+ ids: ids
+ }, function (data) {
+ updateSmsCapabilityStatus(null, function () {
+ draftListener();
+ restoreNavigation();
+ });
+ for (var i = 0; i < numbers.length; i++) {
+ updateMsgList(getPeopleLatestMsg(numbers[i]), numbers[i], ids.length);
+ }
+ synchSmsList(null, ids);
+ tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
+ }, function (error) {
+ restoreNavigation();
+ // Do nothing
+ });
+ }
+
+ //删除群聊草稿草稿
+ function deleteMultiDraftSms(ids, groupId) {
+ service.deleteMessage({
+ ids: ids
+ }, function (data) {
+ synchSmsList(null, ids);
+ $("#smslist-item-" + groupId).hide().remove();
+ checkSmsCapacityAndAlert();
+ tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
+ }, function (error) {
+ // Do nothing
+ });
+ }
+
+ getCurrentChatObject = function () {
+ var nums = $("select.chosen-select-deselect").val();
+ if (!nums) {
+ config.currentChatObject = null;
+ } else if (nums.length == 1) {
+ config.currentChatObject = getLastNumber(nums, config.SMS_MATCH_LENGTH);
+ } else if (nums.length > 1) {
+ config.currentChatObject = null;
+ }
+ return config.currentChatObject;
+ };
+
+ //获取当前聊天对象最新的短消息
+ getPeopleLatestMsg = function (number) {
+ for (var j = 0; j < config.dbMsgs.length; j++) {
+ if (!config.dbMsgs[j].groupId && getLastNumber(config.dbMsgs[j].number, config.SMS_MATCH_LENGTH) == getLastNumber(number, config.SMS_MATCH_LENGTH)) {
+ return config.dbMsgs[j];
+ }
+ }
+ return null;
+ };
+
+ //重新发送,复制消息到发送框
+ resendClickHandler = function (id) {
+ if (!hasCapability) {
+ showAlert("sms_capacity_is_full_for_send");
+ return;
+ }
+ showLoading('sending');
+ $("div.error", "#talk-item-" + id).text($.i18n.prop("sms_resending"));
+ var targetNumber = $("div.smslist-item-resend", "#talk-item-" + id).attr("target");
+ var content = $("div.J_content", "#talk-item-" + id).text();
+ for (var j = 0; j < config.dbMsgs.length; j++) {
+ if (config.dbMsgs[j].id == id) {
+ content = config.dbMsgs[j].content;
+ }
+ }
+
+ disableBtn($("#btn-send", "#inputpanel"));
+ var newMsg = {
+ id: -1,
+ number: targetNumber,
+ content: content,
+ isNew: false
+ };
+ service.sendSMS({
+ number: newMsg.number,
+ message: newMsg.content,
+ id: -1
+ }, function (data) {
+ var latestMsg = getLatestMessage() || {
+ id: parseInt(config.smsMaxId, 10) + 1,
+ time: transUnixTime($.now()),
+ number: newMsg.number
+ };
+ config.smsMaxId = latestMsg.id;
+ newMsg.id = config.smsMaxId;
+ newMsg.time = latestMsg.time;
+ newMsg.tag = 2;
+ newMsg.target = latestMsg.number;
+ newMsg.targetName = getNameOrNumberByNumber(targetNumber);
+ updateDBMsg(newMsg);
+ updateMsgList(newMsg);
+ deleteSingleItemClickHandler(id, function () {
+ addSendMessage(newMsg, true);
+ updateChatInputWordLength();
+ enableBtn($("#btn-send", "#inputpanel"));
+ hideLoading();
+ gotoBottom();
+ });
+ }, function (error) {
+ var latestMsg = getLatestMessage() || {
+ id: parseInt(config.smsMaxId, 10) + 1,
+ time: transUnixTime($.now()),
+ number: newMsg.number
+ };
+ config.smsMaxId = latestMsg.id;
+ newMsg.id = config.smsMaxId;
+ newMsg.time = latestMsg.time;
+ newMsg.errorText = $.i18n.prop("sms_resend_fail");
+ newMsg.tag = 3;
+ newMsg.target = latestMsg.number;
+ newMsg.targetName = getNameOrNumberByNumber(targetNumber);
+ updateDBMsg(newMsg);
+ updateMsgList(newMsg);
+ deleteSingleItemClickHandler(id, function () {
+ addSendMessage(newMsg, true);
+ updateChatInputWordLength();
+ enableBtn($("#btn-send", "#inputpanel"));
+ hideLoading();
+ gotoBottom();
+ });
+ });
+ };
+
+ //滚动到底部
+ gotoBottom = function () {
+ $("#chatpanel .clear-container").animate({
+ scrollTop: $("#chatlist").height()
+ });
+ };
+
+ //最后一条短消息距离顶部的距离
+ var lastItemOffsetTop = 0;
+ //页面是否处于滚动中
+ var scrolling = false;
+ //初始化页面状态信息
+ function initStatus() {
+ currentPage = 1;
+ ready = false;
+ shownMsgs = [];
+ scrolling = false;
+ lastItemOffsetTop = 0;
+ groupDrafts = groupDraftItems = [];
+ groupedDraftsObject = {};
+ config.dbMsgs = [];
+ config.listMsgs = null;
+ config.smsMaxId = 0;
+ config.phonebook = [];
+ }
+
+ function getReadyStatus() {
+ showLoading('waiting');
+ config.currentChatObject = null;
+ var getSMSReady = function () {
+ service.getSMSReady({}, function (data) {
+ if (data.sms_cmd_status_result == "2") {
+ $("input:button", "#smsListForm .smslist-btns").attr("disabled", "disabled");
+ hideLoading();
+ showAlert("sms_init_fail");
+ } else if (data.sms_cmd_status_result == "1") {
+ addTimeout(getSMSReady, 1000);
+ } else {
+ if (config.HAS_PHONEBOOK) {
+ getPhoneBookReady();
+ } else {
+ initSMSList(false);
+ }
+ }
+ });
+ };
+
+ var getPhoneBookReady = function () {
+ service.getPhoneBookReady({}, function (data) {
+ if (data.pbm_init_flag == "6") {
+ initSMSList(false);
+ } else if (data.pbm_init_flag != "0") {
+ addTimeout(getPhoneBookReady, 1000);
+ } else {
+ initSMSList(true);
+ }
+ });
+ };
+
+ var initSMSList = function (isPbmInitOK) {
+ initStatus();
+ if (isPbmInitOK) {
+ getSMSMessages(function () {
+ getPhoneBooks();
+ hideLoading();
+ });
+ } else {
+ getSMSMessages(function () {
+ config.phonebook = [];
+ //if(config.HAS_PHONEBOOK){
+ dealPhoneBooks();
+ //}
+ hideLoading();
+ });
+ }
+ bindingEvents();
+ fixScrollTop();
+ window.scrollTo(0, 0);
+ initSmsCapability();
+ };
+
+ getSMSReady();
+ }
+
+ //初始化短信容量状态
+ function initSmsCapability() {
+ var capabilityContainer = $("#smsCapability");
+ updateSmsCapabilityStatus(capabilityContainer);
+ checkSimStatusForSend();
+ addInterval(function () {
+ updateSmsCapabilityStatus(capabilityContainer);
+ checkSimStatusForSend();
+ }, 5000);
+ }
+
+ //SIM卡未准备好时,禁用发送按钮
+ function checkSimStatusForSend() {
+ var data = service.getStatusInfo();
+ if (data.simStatus != 'modem_init_complete') {
+ disableBtn($("#btn-send"));
+ $("#sendSmsErrorLi").html('<span data-trans="no_sim_card_message">' + $.i18n.prop('no_sim_card_message') + '</span>');
+ $("#chatpanel .smslist-item-resend:visible").hide();
+ } else {
+ enableBtn($("#btn-send"));
+ $("#chatpanel .smslist-item-resend:hidden").show();
+ }
+ }
+
+ //更新短信容量状态
+ function updateSmsCapabilityStatus(capabilityContainer, callback) {
+ service.getSmsCapability({}, function (capability) {
+ if (capabilityContainer != null) {
+ capabilityContainer.text("(" + (capability.nvUsed > capability.nvTotal ? capability.nvTotal : capability.nvUsed) + "/" + capability.nvTotal + ")");
+ }
+ hasCapability = capability.nvUsed < capability.nvTotal;
+ smsCapability = capability;
+ if ($.isFunction(callback)) {
+ callback();
+ }
+ });
+ }
+
+ //初始化页面及VM
+ function init() {
+ getReadyStatus();
+ }
+
+ //事件绑定
+ bindingEvents = function () {
+ var $win = $(window);
+ var $smsListBtns = $("#smslist-main .smslist-btns");
+ var offsetTop = $("#mainContainer").offset().top;
+ $win.unbind("scroll").scroll(function () {
+ if ($win.scrollTop() > offsetTop) {
+ $smsListBtns.addClass("smsListFloatButs marginnone");
+ } else {
+ $smsListBtns.removeClass("smsListFloatButs marginnone");
+ }
+ //loadData(); //由于目前数据显示是全显示,不做动态加载,因此暂时注释掉
+ });
+
+ $("#smslist-table p.checkbox").die().live("click", function () {
+ checkboxClickHandler($(this).attr("id"));
+ });
+
+ $("#smslist-checkAll", "#smsListForm").die().live("click", function () {
+ checkDeleteBtnStatus();
+ });
+
+ $("#chat-input", "#smsChatRoom").die().live("drop", function () {
+ $("#inputpanel .chatform").addClass("chatformfocus");
+ var $this = $(this);
+ $this.removeAttr("data-trans");
+ if ($this.val() == $.i18n.prop("chat_input_placehoder")) {
+ $this.val("");
+ }
+ updateChatInputWordLength();
+ }).live("focusin", function () {
+ $("#inputpanel .chatform").addClass("chatformfocus");
+ var $this = $(this);
+ $this.removeAttr("data-trans");
+ if ($this.val() == $.i18n.prop("chat_input_placehoder")) {
+ $this.val("");
+ }
+ updateChatInputWordLength();
+ }).live("focusout", function () {
+ $("#inputpanel .chatform").removeClass("chatformfocus");
+ var $this = $(this);
+ if ($this.val() == "" || $this.val() == $.i18n.prop("chat_input_placehoder")) {
+ $this.val($.i18n.prop("chat_input_placehoder")).attr("data-trans", "chat_input_placehoder");
+ }
+ updateChatInputWordLength();
+ }).live("keyup", function () {
+ updateChatInputWordLength();
+ }).live("paste", function () {
+ window.setTimeout(function () {
+ updateChatInputWordLength();
+ }, 0);
+ }).live("cut", function () {
+ window.setTimeout(function () {
+ updateChatInputWordLength();
+ }, 0);
+ }).live("drop", function () {
+ window.setTimeout(function () {
+ updateChatInputWordLength();
+ }, 0);
+ }).live("contextmenu", function () {
+ return false;
+ });
+
+ $("#name").die().live("drop", function () {
+ updateNameInputWordLength();
+ }).live("focusin", function () {
+ updateNameInputWordLength();
+ }).live("focusout", function () {
+ updateNameInputWordLength();
+ }).live("keyup", function () {
+ updateNameInputWordLength();
+ }).live("paste", function () {
+ updateNameInputWordLength();
+ }).live("cut", function () {
+ updateNameInputWordLength();
+ }).live("dragend", function () {
+ updateNameInputWordLength();
+ }).live("contextmenu", function () {
+ return false;
+ });
+
+ $("select.chosen-select-deselect", "#smsChatRoom").die().live('change', function () {
+ draftListener();
+ });
+ $("#searchInput").die().live('blur', function () {
+ searchTextBlur();
+ }).live('keyup', function () {
+ updateSearchValue($("#searchInput").val());
+ });
+ };
+
+ //更新剩余字数
+ updateNameInputWordLength = function () {
+
+ var msgInput = $("#name", "#quickSaveContactForm");
+ var msgInputDom = msgInput[0];
+ var strValue = msgInput.val();
+ var encodeType = getEncodeType(strValue);
+ var maxLength = encodeType.encodeType == 'UNICODE' ? 11 : 22;
+ while (strValue.length + encodeType.extendLen > maxLength) {
+ strValue = strValue.substring(0, strValue.length - 1);
+ msgInputDom.value = strValue;
+ encodeType = getEncodeType(strValue);
+ maxLength = encodeType.encodeType == 'UNICODE' ? 11 : 22;
+ }
+ };
+
+//获取聊天对象的名字
+ getNameByNumber = function (num) {
+ for (var i = config.phonebook.length; i > 0; i--) {
+ if (getLastNumber(config.phonebook[i - 1].pbm_number, config.SMS_MATCH_LENGTH) == getLastNumber(num, config.SMS_MATCH_LENGTH)) {
+ return config.phonebook[i - 1].pbm_name;
+ }
+ }
+ return "";
+ };
+ //获取聊天对象的名字和号码
+ getShowNameByNumber = function (num) {
+ for (var i = config.phonebook.length; i > 0; i--) {
+ if (getLastNumber(config.phonebook[i - 1].pbm_number, config.SMS_MATCH_LENGTH) == getLastNumber(num, config.SMS_MATCH_LENGTH)) {
+ return config.phonebook[i - 1].pbm_name /* + "/" + num*/;
+ }
+ }
+ return num;
+ };
+
+ //获取聊天对象的名字,如果没有名字,则显示号码
+ getNameOrNumberByNumber = function (num) {
+ for (var i = config.phonebook.length; i > 0; i--) {
+ if (config.phonebook[i - 1].pbm_number == num) {
+ return config.phonebook[i - 1].pbm_name;
+ }
+ }
+ for (var i = config.phonebook.length; i > 0; i--) {
+ if (getLastNumber(config.phonebook[i - 1].pbm_number, config.SMS_MATCH_LENGTH) == getLastNumber(num, config.SMS_MATCH_LENGTH)) {
+ return config.phonebook[i - 1].pbm_name;
+ }
+ }
+ return num;
+ };
+
+ //点击短信列表条目,进入聊天室页面
+ smsItemClickHandler = function (num) {
+ if (chatRoomInLoading) {
+ return false;
+ }
+ chatRoomInLoading = true;
+ if (smsOtherTmpl == null) {
+ smsOtherTmpl = $.template("smsOtherTmpl", $("#smsOtherTmpl"));
+ }
+ if (smsMeTmpl == null) {
+ smsMeTmpl = $.template("smsMeTmpl", $("#smsMeTmpl"));
+ }
+
+ var name = getShowNameByNumber(num);
+ $("#chosenUser", "#smsChatRoom").hide();
+ $("#chosenUser1", "#smsChatRoom").addClass("hide");
+
+ config.currentChatObject = getLastNumber(num, config.SMS_MATCH_LENGTH);
+ setAsRead(num);
+ cleanChatInput();
+ clearChatList();
+ var userSelect = $("select.chosen-select-deselect", "#smsChatRoom");
+ var ops = $("option", userSelect);
+ var numberExist = false;
+ for (var i = 0; i < ops.length; i++) {
+ var n = ops[i];
+ if (getLastNumber(n.value, config.SMS_MATCH_LENGTH) == config.currentChatObject) {
+ num = n.value;
+ numberExist = true;
+ break;
+ }
+ }
+ if (!numberExist) {
+ userSelect.append("<option value='" + HTMLEncode(num) + "' selected='selected'>" + HTMLEncode(num) + "</option>");
+ }
+ $("select.chosen-select-deselect").val(num).trigger("chosen:updated.chosen");
+ switchPage('chat');
+ config.dbMsgs = _.sortBy(config.dbMsgs, function (e) {
+ return 0 - e.id;
+ });
+ var draftIds = [];
+ var dbMsgsTmp = [];
+ var dbMsgsTmpIds = [];
+ var chatHasDraft = false;
+ for (var i = config.dbMsgs.length - 1; i >= 0; i--) {
+ var e = config.dbMsgs[i];
+ if (_.indexOf(dbMsgsTmpIds, e.id) != -1) {
+ continue;
+ }
+ if (getLastNumber(e.number, config.SMS_MATCH_LENGTH) == config.currentChatObject && _.isEmpty(e.groupId)) {
+ e.isNew = false;
+ e.errorText = '';
+ e.targetName = '';
+ if (e.tag == "0" || e.tag == "1") {
+ $.tmpl("smsOtherTmpl", e).appendTo("#chatlist");
+ dbMsgsTmpIds.push(e.id);
+ dbMsgsTmp.push(e);
+ } else if (e.tag == "2" || e.tag == "3") {
+ $.tmpl("smsMeTmpl", e).appendTo("#chatlist");
+ dbMsgsTmpIds.push(e.id);
+ dbMsgsTmp.push(e);
+ } else if (e.tag == "4") {
+ draftIds.push(e.id);
+ $("#chat-input", "#smsChatRoom").val(e.content).removeAttr('data-trans');
+ updateChatInputWordLength();
+ chatHasDraft = true;
+ }
+ } else {
+ dbMsgsTmpIds.push(e.id);
+ dbMsgsTmp.push(e);
+ }
+ }
+ $("#chatlist").translate();
+ if (chatHasDraft) {
+ $("#chosenUser", "#smsChatRoom").show();
+ $("#chosenUser1", "#smsChatRoom").addClass("hide");
+ } else {
+ $("#chosenUser", "#smsChatRoom").hide();
+ $("#chosenUser1", "#smsChatRoom").removeClass("hide").html(HTMLEncode(name));
+ }
+ config.dbMsgs = dbMsgsTmp.reverse();
+ if (draftIds.length > 0) {
+ deleteDraftSms(draftIds, [num]);
+ } else {
+ checkSmsCapacityAndAlert();
+ }
+
+ checkSimStatusForSend();
+ gotoBottom();
+ chatRoomInLoading = false;
+ };
+
+ function checkSmsCapacityAndAlert() {
+ var capabilityContainer = $("#smsCapability");
+ updateSmsCapabilityStatus(capabilityContainer);
+ addTimeout(function () {
+ if (!hasCapability) {
+ showAlert("sms_capacity_is_full_for_send");
+ }
+ }, 2000);
+ }
+
+ cleanChatInput = function () {
+ $("#chat-input", "#smsChatRoom").val($.i18n.prop("chat_input_placehoder")).attr("data-trans", "chat_input_placehoder");
+ };
+
+ //设置为已读
+ setAsRead = function (num) {
+ var ids = [];
+ $.each(config.dbMsgs, function (i, e) {
+ if (getLastNumber(e.number, config.SMS_MATCH_LENGTH) == getLastNumber(num, config.SMS_MATCH_LENGTH) && e.isNew) {
+ ids.push(e.id);
+ e.isNew = false;
+ }
+ });
+ if (ids.length > 0) {
+ service.setSmsRead({
+ ids: ids
+ }, function (data) {
+ if (data.result) {
+ $("#smslist-item-" + getLastNumber(num, config.SMS_MATCH_LENGTH) + " .smslist-item-new-count").text("").addClass("hide");
+ $("#smslist-item-" + getLastNumber(num, config.SMS_MATCH_LENGTH)).removeClass("font-weight-bold");
+ $("#smslist-item-" + getLastNumber(num, config.SMS_MATCH_LENGTH) + " td:nth-child(2)").removeClass("font-weight-bold");
+ }
+ $.each(config.listMsgs, function (i, e) {
+ if (e.number == num && e.newCount > 0) {
+ e.newCount = 0;
+ }
+ });
+ });
+ }
+ };
+
+ //转发按钮点击事件
+ forwardClickHandler = function (id) {
+ var selectedContact = syncSelectAndChosen($("select#chosenUserSelect"), $('.search-choice', '#chosenUserSelect_chosen'));
+ var content = $("#chat-input", "#smsChatRoom").val();
+ var hasContent = typeof content != "undefined" && content != '' && content != $.i18n.prop('chat_input_placehoder');
+ if (hasContent) {
+ saveDraftAction({
+ content: content,
+ numbers: selectedContact,
+ isFromBack: true,
+ noLoading: true
+ });
+ }
+
+ clearChatList();
+ config.currentChatObject = null;
+
+ $("#chosenUser1", "#smsChatRoom").addClass("hide");
+ $("#chosenUser", "#smsChatRoom").show();
+ for (var j = 0; j < config.dbMsgs.length; j++) {
+ if (config.dbMsgs[j].id == id) {
+ var theChatInput = $("#chat-input", "#smsChatRoom");
+ theChatInput.val(config.dbMsgs[j].content);
+ setInsertPos(theChatInput[0], config.dbMsgs[j].content.length);
+ }
+ }
+ updateChatInputWordLength();
+ $("select.chosen-select-deselect").val("").trigger("chosen:updated.chosen");
+ addTimeout(function () {
+ $("#chosen-search-field-input").focus();
+ }, 300);
+ switchPage('chat');
+ gotoBottom();
+ };
+
+ //更新剩余字数
+ updateChatInputWordLength = function () {
+ var msgInput = $("#chat-input", "#smsChatRoom");
+ var msgInputDom = msgInput[0];
+ var strValue = msgInput.val();
+ var encodeType = getEncodeType(strValue);
+ var maxLength = encodeType.encodeType == 'UNICODE' ? 335 : 765;
+ if (strValue.length + encodeType.extendLen > maxLength) {
+ var scrollTop = msgInputDom.scrollTop;
+ var insertPos = getInsertPos(msgInputDom);
+ var moreLen = strValue.length + encodeType.extendLen - maxLength;
+ var insertPart = strValue.substr(insertPos - moreLen > 0 ? insertPos - moreLen : 0, moreLen);
+ var reversed = insertPart.split('').reverse();
+ var checkMore = 0;
+ var cutNum = 0;
+ for (var i = 0; i < reversed.length; i++) {
+ if (getEncodeType(reversed[i]).extendLen > 0) {
+ checkMore += 2;
+ } else {
+ checkMore++;
+ }
+ if (checkMore >= moreLen) {
+ cutNum = i + 1;
+ break;
+ }
+ }
+ var iInsertToStartLength = insertPos - cutNum;
+ msgInputDom.value = strValue.substr(0, iInsertToStartLength) + strValue.substr(insertPos);
+ if (msgInputDom.value.length > maxLength) {
+ msgInputDom.value = msgInputDom.value.substr(0, maxLength);
+ }
+ setInsertPos(msgInputDom, iInsertToStartLength);
+ msgInputDom.scrollTop = scrollTop;
+ }
+ var textLength = 0;
+ var newValue = $(msgInputDom).val();
+ var newEncodeType = {
+ encodeType: 'GSM7_default',
+ extendLen: 0
+ };
+ if (newValue != $.i18n.prop('chat_input_placehoder')) {
+ newEncodeType = getEncodeType(newValue);
+ }
+ var newMaxLength = newEncodeType.encodeType == 'UNICODE' ? 335 : 765;
+ var $inputCount = $("#inputcount", "#inputpanel");
+ var $inputItemCount = $("#inputItemCount", "#inputpanel");
+ if (newValue.length + newEncodeType.extendLen >= newMaxLength) {
+ $inputCount.addClass("colorRed");
+ $inputItemCount.addClass("colorRed");
+ } else {
+ $("#inputcount", "#inputpanel").removeClass("colorRed");
+ $("#inputItemCount", "#inputpanel").removeClass("colorRed");
+ }
+ if ("" != newValue && $.i18n.prop('chat_input_placehoder') != newValue) {
+ textLength = newValue.length + newEncodeType.extendLen;
+ }
+ $inputCount.html("(" + textLength + "/" + newMaxLength + ")");
+ $inputItemCount.html("(" + getSmsCount(newValue) + "/5)");
+ draftListener();
+ };
+
+ //文档内容监听,判断是否修改过
+ function draftListener() {
+ var content = $("#chat-input", "#smsChatRoom").val();
+ if (hasCapability) {
+ var selectedContact = getSelectValFromChosen($('.search-choice', '#chosenUserSelect_chosen'));
+ var noContactSelected = !selectedContact || selectedContact.length == 0;
+ var hasContent = typeof content != "undefined" && content != '' && content != $.i18n.prop('chat_input_placehoder');
+
+ if (!hasContent) {
+ config.resetContentModifyValue();
+ return;
+ }
+ if (hasContent && !noContactSelected) {
+ config.CONTENT_MODIFIED.modified = true;
+ config.CONTENT_MODIFIED.message = 'sms_to_save_draft';
+ config.CONTENT_MODIFIED.callback.ok = saveDraftAction;
+ config.CONTENT_MODIFIED.callback.no = $.noop;
+ config.CONTENT_MODIFIED.data = {
+ content: $("#chat-input", "#smsChatRoom").val(),
+ numbers: selectedContact
+ };
+ return;
+ }
+ if (hasContent && noContactSelected) {
+ config.CONTENT_MODIFIED.modified = true;
+ config.CONTENT_MODIFIED.message = 'sms_no_recipient';
+ config.CONTENT_MODIFIED.callback.ok = $.noop;
+ config.CONTENT_MODIFIED.callback.no = function () {
+ // 返回true,页面保持原状
+ return true;
+ }; //$.noop;
+ return;
+ }
+ } else {
+ config.resetContentModifyValue();
+ }
+ }
+
+ //保存草稿回调动作
+ function saveDraftAction(data) {
+ var datetime = new Date();
+ var params = {
+ index: -1,
+ currentTimeString: getCurrentTimeString(datetime),
+ groupId: data.numbers.length > 1 ? datetime.getTime() : '',
+ message: data.content,
+ numbers: data.numbers
+ };
+ !data.noLoading && showLoading('waiting');
+ service.saveSMS(params, function () {
+ if (data.isFromBack) {
+ getLatestDraftSms(data.numbers);
+ !data.noLoading && successOverlay('sms_save_draft_success');
+ } else {
+ !data.noLoading && successOverlay('sms_save_draft_success');
+ }
+ }, function () {
+ !data.noLoading && errorOverlay("sms_save_draft_failed")
+ });
+
+ //获取最新的草稿信息
+ function getLatestDraftSms(numbers) {
+ service.getSMSMessages({
+ page: 0,
+ smsCount: 5,
+ nMessageStoreType: 1,
+ tags: 4,
+ orderBy: "order by id desc"
+ }, function (data) {
+ if (data.messages && data.messages.length > 0) {
+ var theGroupId = '',
+ draftShowName = '',
+ draftShowNameTitle = '',
+ i = 0,
+ drafts = [];
+ for (; i < data.messages.length; i++) {
+ var msg = data.messages[i];
+ for (var k = 0; k < numbers.length; k++) {
+ var num = numbers[k];
+ if (getLastNumber(num, config.SMS_MATCH_LENGTH) == getLastNumber(msg.number, config.SMS_MATCH_LENGTH)) { //if (num.indexOf(msg.number) == 0) {
+ msg.number = num;
+ }
+ }
+ if (theGroupId != '' && theGroupId != msg.groupId) {
+ break;
+ }
+ updateDBMsg(msg);
+ if (msg.groupId == '') { // 单条草稿
+ break;
+ } else { // 多条草稿
+ theGroupId = msg.groupId;
+ var showName = getShowNameByNumber(msg.number);
+ draftShowName += (i == 0 ? '' : ';') + showName;
+ draftShowNameTitle += (i == 0 ? '' : ';') + showName;
+ }
+ drafts.push(msg);
+ }
+ if (theGroupId == '') { // 单条草稿
+ var msg = data.messages[0];
+ msg.hasDraft = true;
+ updateMsgList(msg);
+ } else { // 多条草稿
+ var msg = data.messages[0];
+ var len = 10;
+ if (getEncodeType(draftShowName).encodeType == "UNICODE") {
+ len = 10;
+ }
+ msg.draftShowNameTitle = draftShowNameTitle;
+ msg.draftShowName = draftShowName.length > len ? draftShowName.substring(0, len) + "..." : draftShowName;
+ msg.hasDraft = true;
+ msg.totalCount = i;
+ groupedDraftsObject[theGroupId] = drafts;
+ updateMsgList(msg);
+ }
+ tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
+ }
+ }, function () {
+ // do nothing
+ });
+ }
+ }
+
+ //点击群聊草稿进入草稿发送页面 在进入的过程中会先删掉草稿
+ draftSmsItemClickHandler = function (groupId) {
+ if (chatRoomInLoading) {
+ return false;
+ }
+ chatRoomInLoading = true;
+ var msgs = groupedDraftsObject[groupId];
+ var numbers = [];
+ var ids = [];
+ for (var i = 0; msgs && i < msgs.length; i++) {
+ numbers.push(getLastNumber(msgs[i].number, config.SMS_MATCH_LENGTH));
+ ids.push(msgs[i].id + '');
+ }
+ $("#chosenUser", "#smsChatRoom").show();
+ $("#chosenUser1", "#smsChatRoom").addClass("hide").html('');
+ $("select.chosen-select-deselect").val(numbers).trigger("chosen:updated.chosen");
+ $("#chat-input", "#smsChatRoom").val(msgs[0].content);
+ updateChatInputWordLength();
+ clearChatList();
+ switchPage('chat');
+ draftListener();
+ gotoBottom();
+ chatRoomInLoading = false;
+ deleteMultiDraftSms(ids, groupId);
+ };
+
+ //按列表条目删除短消息
+ deletePhoneMessageClickHandler = function (num) {
+ showConfirm("confirm_sms_delete", function () {
+ showLoading('deleting');
+ var ids = [];
+ $.each(config.dbMsgs, function (i, e) {
+ if (e.number == num) {
+ ids.push(e.id);
+ }
+ });
+ service.deleteMessage({
+ ids: ids
+ }, function (data) {
+ $("#smslist-item-" + getLastNumber(num, config.SMS_MATCH_LENGTH)).hide().remove();
+ synchSmsList([num], ids);
+ successOverlay();
+ tryToDisableCheckAll($("#smslist-checkAll", "#smsListForm"), $(".smslist-item", "#smslist-table").length);
+ }, function (error) {
+ errorOverlay(error.errorText);
+ });
+ });
+ };
+
+ //同步短信列表数据
+ synchSmsList = function (nums, ids) {
+ if (nums && nums.length > 0) {
+ config.listMsgs = $.grep(config.listMsgs, function (n, i) {
+ return $.inArray(n.number, nums) == -1;
+ });
+ }
+ if (ids && ids.length > 0) {
+ var dbMsgsTmp = [];
+ $.each(config.dbMsgs, function (i, e) {
+ if ($.inArray(e.id, ids) == -1) {
+ dbMsgsTmp.push(e);
+ }
+ });
+ config.dbMsgs = dbMsgsTmp;
+ }
+ };
+
+ //确定最后一条短消息距离顶部的距离
+ function fixScrollTop() {
+ var items = $(".smslist-item");
+ var lastOne;
+ if (items.length > 0) {
+ lastOne = items[items.length - 1];
+ } else {
+ lastOne = items[0];
+ }
+ lastItemOffsetTop = lastOne ? lastOne.offsetTop : 600;
+ }
+
+ function loadData() {
+ if (ready && !scrolling && lastItemOffsetTop < ($(window).scrollTop() + $(window).height())
+ && $(".smslist-item").length != config.listMsgs.length) {
+ scrolling = true;
+ addTimeout(function () {
+ removeChecked("smslist-checkAll");
+ changeShownMsgs();
+ fixScrollTop();
+ scrolling = false;
+ }, 100);
+ }
+ }
+
+ function stopNavigation() {
+ disableBtn($('#btn-back'));
+ $('a', '#left').bind("click", function () {
+ return false;
+ });
+ $('a', '#list-nav').bind("click", function () {
+ return false;
+ });
+ }
+
+ function restoreNavigation() {
+ enableBtn($('#btn-back'));
+ $('a', '#left').unbind("click");
+ $('a', '#list-nav').unbind("click");
+ }
+
+ function searchTable(key) {
+ key = $.trim(key);
+ var $trs = $('tr', '#smslist-table'),
+ trLength = $trs.length;
+ if (key == '') {
+ $trs.show();
+ return false;
+ }
+ $trs.hide();
+ while (trLength) {
+ var $tr = $($trs[trLength - 1]),
+ $tds = $('td', $tr),
+ tdLength = $tds.length;
+ while (tdLength - 1) {
+ var $td = $($tds[tdLength - 1]);
+ if ($td.text().toLowerCase().indexOf(key.toLowerCase()) != -1) {
+ $tr.show();
+ break;
+ }
+ tdLength--;
+ }
+ trLength--;
+ }
+
+ addTimeout(function () {
+ $(":checkbox:checked", "#addPhonebookContainer").removeAttr('checked');
+ vm.selectedItemIds([]);
+ vm.freshStatus($.now());
+ renderCheckbox();
+ }, 300);
+ return true;
+ }
+ updateSearchValue = function (key) {
+ if (key == "" || key == $.i18n.prop("search")) {
+ return true;
+ }
+ searchTable(key);
+ };
+ //清除搜索关键字事件
+ clearSearchKey = function () {
+ updateSearchValue($.i18n.prop("search"));
+ $("#searchInput").addClass("ko-grid-search-txt-default").attr("data-trans", "search");
+ };
+ //点击搜索输入框事件
+ searchTextClick = function () {
+ var searchText = $("#searchInput");
+ if (searchText.hasClass("ko-grid-search-txt-default")) {
+ updateSearchValue("");
+ searchText.val("");
+ searchText.removeClass("ko-grid-search-txt-default").removeAttr("data-trans");
+ }
+ };
+ //离开搜索输入框事件
+ searchTextBlur = function () {
+ var txt = $.trim($("#searchInput").val()).toLowerCase();
+ if (txt == "") {
+ clearSearchKey();
+ }
+ };
+
+ window.smsUtil = {
+ changeLocationHandler: function (ele) {
+ if ($(ele).val() == 'sim') {
+ window.location.hash = '#msg_sim';
+ } else {
+ window.location.hash = '#msg_main';
+ }
+ }
+ };
+
+ return {
+ init: init
+ };
+});
+
+define("sms_set","underscore jquery knockout set service".split(" "),
+ function (_, $, ko, config, service) {
+
+ var validityModes = _.map(config.SMS_VALIDITY, function (item) {
+ return new Option(item.name, item.value);
+ });
+
+ function SmsSetViewMode() {
+ var target = this;
+ var setting = getSmsSetting();
+ target.modes = ko.observableArray(validityModes);
+ target.selectedMode = ko.observable(setting.validity);
+ target.centerNumber = ko.observable(setting.centerNumber);
+ target.deliveryReport = ko.observable(setting.deliveryReport);
+
+ target.clear = function () {
+ init();
+ clearValidateMsg();
+ };
+
+ target.save = function () {
+ showLoading('waiting');
+ var params = {};
+ params.validity = target.selectedMode();
+ params.centerNumber = target.centerNumber();
+ params.deliveryReport = target.deliveryReport();
+ service.setSmsSetting(params, function (result) {
+ if (result.result == "success") {
+ successOverlay();
+ } else {
+ errorOverlay();
+ }
+ });
+ };
+ }
+
+ //获取短信设置参数
+
+ function getSmsSetting() {
+ return service.getSmsSetting();
+ }
+
+ function init() {
+ var container = $('#container');
+ ko.cleanNode(container[0]);
+ var vm = new SmsSetViewMode();
+ ko.applyBindings(vm, container[0]);
+ $('#smsSettingForm').validate({
+ submitHandler: function () {
+ vm.save();
+ },
+ rules: {
+ txtCenterNumber: "sms_service_center_check"
+ }
+ });
+ }
+
+ return {
+ init: init
+ };
+});
+
+define("sms_sim_messages","jquery knockout set service".split(" "),
+ function ($, ko, config, service) {
+ var simMsgListTmpl = null;
+ //每页记录条数
+ var perPage = 200;
+
+ //获取短信分页记录
+ function getSMSMessages() {
+ return service.getSMSMessages({
+ page: 0,
+ smsCount: perPage,
+ nMessageStoreType: 0,
+ tags: 10,
+ orderBy: "order by id desc"
+ }, function (data) {
+ tryToDisableCheckAll($("#simMsgList-checkAll"), data.messages.length);
+ dealPhoneBooks(data.messages);
+ }, function (data) {
+ dealPhoneBooks([]);
+ });
+ }
+
+ //短信显示联系人名字,并将结果显示在UI
+ function dealPhoneBooks(messages) {
+ $.each(messages, function (j, n) {
+ n.itemId = getLastNumber(n.number, config.SMS_MATCH_LENGTH);
+ for (var i = 0; i < config.phonebook.length; i++) {
+ var person = config.phonebook[i];
+ if (n.itemId == getLastNumber(person.pbm_number, config.SMS_MATCH_LENGTH)) {
+ n.name = person.pbm_name;
+ break;
+ }
+ }
+ });
+ renderSimMessageList(messages);
+ }
+
+ //清楚短信列表内容
+ cleanSimSmsList = function () {
+ $("#simMsgList_container").empty();
+ };
+
+ //将短信显示结果显示在UI
+ function renderSimMessageList(messages) {
+ if (simMsgListTmpl == null) {
+ simMsgListTmpl = $.template("simMsgListTmpl", $("#simMsgListTmpl"));
+ }
+ cleanSimSmsList();
+ $("#simMsgList_container").html($.tmpl("simMsgListTmpl", {
+ data: messages
+ }));
+ hideLoading();
+ }
+
+ //初始化电话本信息
+ function initPhoneBooks(cb) {
+ service.getPhoneBooks({
+ page: 0,
+ data_per_page: 2000,
+ orderBy: "name",
+ isAsc: true
+ }, function (books) {
+ if ($.isArray(books.pbm_data) && books.pbm_data.length > 0) {
+ config.phonebook = books.pbm_data;
+ } else {
+ config.phonebook = [];
+ }
+ cb();
+ }, function () {
+ errorOverlay();
+ });
+ }
+
+ function simSmsViewMode() {
+ var self = this;
+ start();
+ }
+
+ //短信删除事件处理
+ deleteSelectedSimMsgClickHandler = function () {
+ var checkbox = $("input[name=msgId]:checked", "#simMsgList_container");
+ var msgIds = [];
+ for (var i = 0; i < checkbox.length; i++) {
+ msgIds.push($(checkbox[i]).val());
+ }
+ if (msgIds.length == 0) {
+ return false;
+ }
+ showConfirm("confirm_sms_delete", function () {
+ showLoading('deleting');
+ service.deleteMessage({
+ ids: msgIds
+ }, function (data) {
+ removeChecked("simMsgList-checkAll");
+ disableBtn($("#simMsgList-delete"));
+ var idsForDelete = "";
+ checkbox.each(function (i, n) {
+ idsForDelete += ".simMsgList-item-class-" + $(n).val() + ",";
+ });
+ if (idsForDelete.length > 0) {
+ $(idsForDelete.substring(0, idsForDelete.length - 1)).hide().remove();
+ }
+ tryToDisableCheckAll($("#simMsgList-checkAll"), $(".smslist-item", "#simMsgList_container").length);
+ successOverlay();
+ }, function (error) {
+ errorOverlay(error.errorText);
+ });
+ //删除短信后需要刷新列表
+ updateSimSmsCapabilityStatus($("#simSmsCapability"));
+ });
+ };
+ //将被checked的条目添加到self.checkedItem中,用于在滚动还原checkbox
+ function checkboxClickHandler() {
+ if (getSelectedItemSize() == 0) {
+ disableBtn($("#simMsgList-delete"));
+ } else {
+ enableBtn($("#simMsgList-delete"));
+ }
+ }
+
+ //获取已选择的条目
+ function getSelectedItemSize() {
+ return $("input:checkbox:checked", '#simMsgList_container').length;
+ }
+
+ //模块开始,检查电话本及短信状态并加装页码数据
+ function start() {
+ showLoading('waiting');
+ var getSMSReady = function () {
+ service.getSMSReady({}, function (data) {
+ if (data.sms_cmd_status_result == "2") {
+ hideLoading();
+ showAlert("sms_init_fail");
+ } else if (data.sms_cmd_status_result == "1") {
+ addTimeout(function () {
+ getSMSReady();
+ }, 1000);
+ } else {
+ if (!config.HAS_PHONEBOOK) {
+ initSMSList(config.HAS_PHONEBOOK);
+ } else {
+ getPhoneBookReady();
+ }
+ }
+ });
+ };
+
+ var getPhoneBookReady = function () {
+ service.getPhoneBookReady({}, function (data) {
+ if (data.pbm_init_flag == "6") {
+ initSMSList(false);
+ } else if (data.pbm_init_flag != "0") {
+ addTimeout(function () {
+ getPhoneBookReady();
+ }, 1000);
+ } else {
+ initSMSList(config.HAS_PHONEBOOK);
+ }
+ });
+ };
+
+ var initSMSList = function (isPbmInitOK) {
+ if (isPbmInitOK) {
+ initPhoneBooks(function () {
+ getSMSMessages();
+ });
+ } else {
+ config.phonebook = [];
+ getSMSMessages();
+ }
+ };
+ getSMSReady();
+ initSimSmsCapability();
+ }
+
+ //初始化短信容量状态
+ function initSimSmsCapability() {
+ var capabilityContainer = $("#simSmsCapability");
+ updateSimSmsCapabilityStatus(capabilityContainer);
+ addInterval(function () {
+ updateSimSmsCapabilityStatus(capabilityContainer);
+ }, 5000);
+ }
+
+ //更新短信容量状态
+ function updateSimSmsCapabilityStatus(capabilityContainer) {
+ service.getSmsCapability({}, function (capability) {
+ if (capabilityContainer != null) {
+ capabilityContainer.text("(" + capability.simUsed + "/" + capability.simTotal + ")");
+ }
+ });
+ }
+
+ //清除搜索关键字事件
+ clearSearchKey = function () {
+ updateSearchValue($.i18n.prop("search"));
+ $("#searchInput").addClass("ko-grid-search-txt-default").attr("data-trans", "search");
+ };
+ //点击搜索输入框事件
+ searchTextClick = function () {
+ var searchText = $("#searchInput");
+ if (searchText.hasClass("ko-grid-search-txt-default")) {
+ updateSearchValue("");
+ searchText.val("");
+ searchText.removeClass("ko-grid-search-txt-default").removeAttr("data-trans");
+ }
+ };
+ //离开搜索输入框事件
+ searchTextBlur = function () {
+ var txt = $.trim($("#searchInput").val()).toLowerCase();
+ if (txt == "") {
+ clearSearchKey();
+ }
+ };
+
+ updateSearchValue = function (key) {
+ if (key == "" || key == $.i18n.prop("search")) {
+ return true;
+ }
+ searchTable(key);
+ }
+
+ function searchTable(key) {
+ key = $.trim(key);
+ var $trs = $('tr', '#smslist-table'),
+ trLength = $trs.length;
+ if (key == '') {
+ $trs.show();
+ return false;
+ }
+ $trs.hide();
+ while (trLength) {
+ var $tr = $($trs[trLength - 1]),
+ $tds = $('td', $tr),
+ tdLength = $tds.length;
+ while (tdLength - 1) {
+ var $td = $($tds[tdLength - 1]);
+ if ($td.text().toLowerCase().indexOf(key.toLowerCase()) != -1) {
+ $tr.show();
+ break;
+ }
+ tdLength--;
+ }
+ trLength--;
+ }
+
+ addTimeout(function () {
+ $(":checkbox:checked", "#addPhonebookContainer").removeAttr('checked');
+ vm.selectedItemIds([]);
+ vm.freshStatus($.now());
+ renderCheckbox();
+ }, 300);
+ return true;
+ }
+
+ //点击短信列表条目
+ simsmsItemClickHandler = function (tag, id, num) {
+ if (tag == "1") {
+ var ids = [];
+ ids.push(id);
+ service.setSmsRead({
+ ids: ids
+ }, function (data) {
+ if (data.result) {
+ $(".simMsgList-item-class-" + id, "#simMsgTableContainer").removeClass('font-weight-bold');
+ }
+ });
+ }
+ }
+
+ //页面事件绑定
+ function initEventBind() {
+ $(".smslist-item-msg", "#simMsgTableContainer").die().live("click", function () {
+ var $this = $(this).addClass('showFullHeight');
+ $('.smslist-item-msg.showFullHeight', '#simMsgTableContainer').not($this).removeClass('showFullHeight');
+ });
+ $("#simMsgList_container p.checkbox, #simMsgListForm #simMsgList-checkAll").die().live("click", function () {
+ checkboxClickHandler();
+ });
+ $("#searchInput").die().live('blur', function () {
+ searchTextBlur();
+ }).live('keyup', function () {
+ updateSearchValue($("#searchInput").val());
+ });
+ }
+
+ //模块初始化开始
+ function init() {
+ var container = $('#container');
+ ko.cleanNode(container[0]);
+ var vm = new simSmsViewMode();
+ ko.applyBindings(vm, container[0]);
+ initEventBind();
+ }
+
+ window.smsUtil = {
+ changeLocationHandler: function (ele) {
+ if ($(ele).val() == 'sim') {
+ window.location.hash = '#msg_sim';
+ } else {
+ window.location.hash = '#msg_main';
+ }
+ }
+ };
+
+ return {
+ init: init
+ };
+});