// // HoGo script v1.5 // Add functions: // - View file type document // - Support uploading new file type (.docx, .xlsx, .pttx) for plupload/Google drive/Dropbox object // - Send wizard support MS office file // - Add new function for ClientInfo object // - Effect drag & drop in uploading documnent // - Fixing animation popup & add scrolltop for model to keep current user's position screen // - And much more update, bugs fixing... // // // Variable for form's status //ExportServiceUserList var formStatus; var pageInitAlready = false; var serverHostAPI = "/enterpriseapp/"; var GOOGLE_ENVIRONMENT = "server_test"; // // Stripe key // //var stripePuplicKey = "pk_live_Nj8frYtyf3WM1TOFfJrL1ffa"; var stripePuplicKey = "pk_test_hoCROLJbcrwFP9uoXxbE3ukz"; var supportedFile = ['pdf', 'docx', 'xlsx', 'pptx', 'xlsm']; // 'pptx' for 2.0: pptx if (document.referrer.indexOf(window.location.hostname) !== -1) { var prePage = document.referrer; } // Google app key var GoogleConst = { production: { /* Prodcution server */ clientId: '6829061683-2nr93rk2djkei7mhi6an1emodi4t264g.apps.googleusercontent.com', appID: 'k3hodIm2xU0ofm-2vm0_BmIi' }, server_test: { clientId: '6829061683-2nr93rk2djkei7mhi6an1emodi4t264g.apps.googleusercontent.com', appID: 'k3hodIm2xU0ofm-2vm0_BmIi' }, local: { /* Google's clientID - Using for localhost*/ clientId: '6829061683-2nr93rk2djkei7mhi6an1emodi4t264g.apps.googleusercontent.com', appID: 'k3hodIm2xU0ofm-2vm0_BmIi' // clientId: '480888213599-56dh0vh33uq6i2nscjj582bq6ca5cre6.apps.googleusercontent.com', // appID: '480888213599' }, /* Google drive scope */ scopeDrive: ["https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"], /* Google profile scope */ scopeProfile: ["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"], /* Google contact scope */ scopeContact: ["https://www.google.com/m8/feeds"] }; // // Some important plugins must be initilized before our app get started // (function ($) { //Store last page for using datatable var aParts = window.location.pathname.split('/'), sNameEQ = aParts[aParts.length - 1].replace(/[\/:]/g, "").toLowerCase(); var pageName = ""; if (sNameEQ.indexOf(".html") !== -1) pageName = sNameEQ; else pageName = sNameEQ + ".html"; $(window).bind('beforeunload', function (e) { $.cookie("l_p", pageName); }); // // PLUG-INS. Here are some common plug-ins which is used in our application // /* * jQuery Reveal Plugin 1.0. Modify something by tmhao * www.ZURB.com * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ $.fn.reveal = function (opts) { var defaults = { header: null, size: null, modalclassname: 'reveal-modal', animation: 'fadeAndPop', //fade, fadeAndPop, none --- We can create many animation here animationspeed: 400, //how fast animtions are closeonbackgroundclick: true, //if you click background will modal close? dismissmodalclass: 'close-reveal-modal', //the class of a button or element that will close an open modal modalbgclass: 'reveal-modal-bg modal', scrolltop: $(document).scrollTop() // Get current scrolltop }; //Extend dem' options var options = $.extend({}, defaults, opts); return this.each(function () { // Get current top var currentTop = options.scrolltop; // Global Variables var modalHTML = $(this).detach(), locked = false, modalBG = $('.' + options.modalbgclass); var modal; var size = (options.size === "large" || options.size === "lg") ? "modal-large" : ""; // Check modal first if (!modalHTML.find(".modal-dialog").length) { $(this).wrapAll(''); modal = $(this).parents(".modal-dialog"); } else { modal = modalHTML; } // Not allow scrolling $('body').addClass('modal-open'); //Create Modal BG if (modalBG.length === 0) { modalBG = $('
').append(modal); $('body').append(modalBG); } else { // Move to another place //modalBG.find('.' + options.modalclassname).appendTo('body'); modalBG.html('').append(modal); } //Open & Close Animations modal.bind('reveal:open', function () { // $('#container').css('top', -currentTop + 'px'); modalBG.unbind('click.modalEvent'); $('.' + options.dismissmodalclass).unbind('click.modalEvent'); if (!locked) { lockModal(); if (options.animation === "fadeAndPop") { modal.css({'opacity': 0}); //, 'display': 'block', 'top': '0px' // We'll get the width of text inside - Got real width // var sensor = $('
').append(modal.clone()).css({'float': 'left', 'visibility': 'hidden'}); // How to calculate the length of long text // $('body').append(sensor); // var width = sensor.width(); // sensor.remove(); modalBG.fadeIn(options.animationspeed / 2); // Calculate width/heigth here //var x = (modal.parent().outerHeight() - (modal.outerHeight()))/2; // Parent is modal-background // var x = ($(window).height() - (modal.outerHeight())) / 2; // Parent is modal-background // modal.css({'width': width + 'px'}); modal.delay(options.animationspeed / 2).animate({ "opacity": 1 // , 'margin-top': "" + x + "px" }, options.animationspeed, unlockModal()); // For resizing // $(window).resize(function() { // var m = $('.' + options.modalbgclass).find('.' + options.modalclassname); // var x = (m.parent().outerHeight(true) - (m.outerHeight())) / 2; // m.css({'margin-top': "" + x + "px"}); // }); } if (options.animation === "fade") { }// Implement later if (options.animation === "none") { }// Implement later } modal.unbind('reveal:open'); }); // modal.bind('reveal:resize', function () { var m = $('.' + options.modalbgclass).find('.' + options.modalclassname); var x = (m.parent().outerHeight(true) - (m.outerHeight())) / 2; //m.css({'margin-top' : ""+ x +"px", 'display': 'block'}); m.delay(options.animationspeed / 2).animate({ "opacity": 1, 'margin-top': "" + x + "px" }, options.animationspeed, unlockModal()); }); //Closing Animation modal.bind('reveal:close', function () { if (!locked) { lockModal(); if (options.animation === "fadeAndPop") { //modalBG.delay(options.animationspeed).fadeOut(options.animationspeed); modal.animate({ "opacity": 0//, "margin-top": "250px" }, 0, function () { //modal.css({'opacity' : 1, 'display' : 'none'}); unlockModal(); modal.unbind('reveal:close'); modalBG.remove(); // Remove preventing scroll $('body').removeClass('modal-open'); // Scroll // $(document).scrollTop(currentTop); }); } else { modal.unbind('reveal:close'); modalBG.remove(); $('body').removeClass('modal-open'); // Scroll // $(document).scrollTop(currentTop); } } }); //Open Modal Immediately modal.trigger('reveal:open'); //Close Modal Listeners $('.' + options.dismissmodalclass).bind('click.modalEvent', function () { modal.trigger('reveal:close'); }); if (options.closeonbackgroundclick) { modalBG.bind('click.modalEvent', function (event) { // Prevent click from parent //event.stopPropagation(); var t = $(event.target); // Click on the modal if (t.parents('.reveal-modal').length === 1 || t.hasClass(options.modalclassname)) { // Click inside modal } else { // Click outside the modal :( modal.trigger('reveal:close'); } }); } $('body').keyup(function (e) { if (e.which === 27) { modal.trigger('reveal:close'); } // 27 is the keycode for the Escape key }); //Animations Locks function unlockModal() { locked = false; } function lockModal() { locked = true; } }); }; /** * jQuery Cookie Plugin. https://github.com/carhartl/jquery-cookie * @param {type} key * @param {type} value * @param {type} options * @returns {String|Array} */ $.cookie = function (key, value, options) { // key and at least value given, set cookie... if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) { options = $.extend({}, options); if (value === null || value === undefined) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } value = String(value); return (document.cookie = [ encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // key and possibly options given, get cookie... options = value || {}; var decode = options.raw ? function (s) { return s; } : decodeURIComponent; var pairs = document.cookie.split('; '); for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) { if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined } return null; }; /*-------------------------------------------------------------------- * jQuery plugin: customInput() * by Maggie Wachs and Scott Jehl, http://www.filamentgroup.com * Copyright (c) 2009 Filament Group * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses. * Article: http://www.filamentgroup.com/lab/accessible_custom_designed_checkbox_radio_button_inputs_styled_css_jquery/ * Usage example below (see comment "Run the script..."). --------------------------------------------------------------------*/ $.fn.limitInput = function (options) { var options = options || {}; var cbfs = this; // establish checkbox container var cbs = this.find('input:checkbox'); var maxnum = options.max ? options.max : 2; cbs.each(function () { $(this).bind('click', function () { if ($(this).is(':checked')) { if (cbs.filter(':checked').length === maxnum) { cbs.not(':checked').each(function () { $(this).attr('disabled', 'true'); if (options.disablelabels) { var thisid = $(this).attr('id'); $('label[for="' + thisid + '"]').addClass('disabled'); } }); } } else { cbs.removeAttr('disabled'); if (options.disablelabels) { cbfs.find('label.disabled').removeClass('disabled'); } } }); }); return this; }; // // Custom our input (checkbox) make it more beautiful // $.fn.customInput = function () { $(this).each(function (i) { if ($(this).is('[type=checkbox]')) { // ,[type=radio] var input = $(this); var id = input.attr('id'); // get the associated label using the input's id var label = $('label[for=' + input.attr('id') + ']'); //get type, for classname suffix var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio'; if (label.length > 0) { input.add(label).wrapAll('
'); } else { label = $(""); $('
').insertBefore(input).append(input, label); } //var chklabel = forlabel.text(); //forlabel.hide(); // wrap the input + label in a div //$('
').insertBefore(input).append(input, label); // find all inputs in this set using the shared name attribute if (input.is(':disabled')) { if (inputType === 'checkbox' && input.is(':checked')) { label.addClass(' checkedDisabled '); } else { label.addClass(' disabled '); } } // necessary for browsers that don't support the :hover pseudo class on labels label.hover( function () { if (!input.is(':disabled')) { $(this).addClass('hover'); } if (inputType === 'checkbox' && input.is(':checked') && !input.is(':disabled')) { $(this).addClass('checkedHover'); } }, function () { $(this).removeClass('hover checkedHover focus'); } ); //bind custom event, trigger it, bind click,focus,blur events input.bind('updateState', function () { if (input.is(':checked') && !input.is(':disabled')) { if (input.is(':radio')) { var allInputs = $('input[name=' + input.attr('name') + ']'); allInputs.each(function () { $('label[for=' + $(this).attr('id') + ']').removeClass('checked'); }); } ; label.addClass('checked '); } else { label.removeClass('checked checkedHover checkedFocus '); } }) .trigger('updateState') .click(function () { $(this).trigger('updateState'); }) .focus(function () { label.addClass('focus'); if (inputType === 'checkbox' && input.is(':checked')) { $(this).addClass('checkedFocus'); } }) .blur(function () { label.removeClass('focus checkedFocus'); }); } }); }; /** * @author Alexandre Magno * @desc Center a element with jQuery * @version 1.0 * @example * $("element").center({ * * vertical: true, * horizontal: true * * }); * @obs With no arguments, the default is above * @license free * @param bool vertical, bool horizontal * @contribution Paulo Radichi * */ $.fn.center = function (params) { var options = { vertical: true, horizontal: true }; var op = jQuery.extend(options, params); return this.each(function () { //initializing variablesDownload var $self = jQuery(this); //get the dimensions using dimensions plugin var width = $self.width(); var height = $self.height(); //get the paddings var paddingTop = parseInt($self.css("padding-top")); var paddingBottom = parseInt($self.css("padding-bottom")); //get the borders var borderTop = parseInt($self.css("border-top-width")); var borderBottom = parseInt($self.css("border-bottom-width")); //get the media of padding and borders var mediaBorder = (borderTop + borderBottom) / 2; var mediaPadding = (paddingTop + paddingBottom) / 2; //get the type of positioning var positionType = $self.parent().css("position"); // get the half minus of width and height var halfWidth = (width / 2) * (-1); var halfHeight = ((height / 2) * (-1)) - mediaPadding - mediaBorder; // initializing the css properties var cssProp = { position: 'fixed' }; //Set display in font any element cssProp["z-index"] = 100; if (op.vertical) { // cssProp.height = height; cssProp.top = '50%'; cssProp.marginTop = halfHeight; } if (op.horizontal) { // cssProp.width = width; cssProp.left = '50%'; cssProp.marginLeft = halfWidth; } //check the current position if (positionType === 'static') { $self.parent().css("position", "relative"); } //aplying the css $self.css(cssProp); }); }; /* Written by Kentaro SATO (kentaro@ranvis.com). */ $.datepicker.regional['ja'] = { monthNames: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], monthNamesShort: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], dayNames: ['日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日'], dayNamesShort: ['日', '月', '火', '水', '木', '金', '土'], dayNamesMin: ['日', '月', '火', '水', '木', '金', '土'], dateFormat: 'mm/dd/yy', firstDay: 0, prevText: '<前', prevStatus: '', prevJumpText: '<<', prevJumpStatus: '', nextText: '次>', nextStatus: '', nextJumpText: '>>', nextJumpStatus: '', currentText: '今日', currentStatus: '', todayText: '今日', todayStatus: '', clearText: '-', clearStatus: '', closeText: '閉じる', closeStatus: '', yearStatus: '', monthStatus: '', weekText: '週', weekStatus: '', dayStatus: 'DD d MM', defaultStatus: '', isRTL: false }; //$.datepicker.setDefaults($.datepicker.regional['en-GB']); /* * Turn On/Off Sorting capability (offline sort) * @param {object} oSettings DataTables settings object * @param {array} | {string} aiColumns Array of columns or string === '_all' * @param {boolean} bOn True to enable, false to disable */ if ($.fn.dataTableExt) { $.fn.dataTableExt.oApi.fnSortOnOff = function (oSettings, aiColumns, bOn) { var cols = typeof aiColumns === 'string' && aiColumns === '_all' ? oSettings.aoColumns : aiColumns; for (var i = 0, len = cols.length; i < len; i++) { if (bOn) { //console.log(oSettings.aoColumns[ i ].nTh.childNodes[1]); //oSettings.aoColumns[ i ].nTh.childNodes[1].style.cursor = "pointer"; } else { oSettings.aoColumns[i].nTh.className = ""; //oSettings.aoColumns[ i ].nTh.childNodes[1].style.cursor = "default"; } oSettings.aoColumns[ i ].bSortable = bOn; } }; } // // File ajax upload // $.extend({ createUploadIframe: function (id, uri) { //create frame var frameId = 'jUploadFrame' + id; var iframeHtml = '
', size: "large" }); } else { if (data.status === 'waiting') { Modal.showAlert({ title: i18n.t('mydocument.waiting.title'), // Should support multiple langue (i18n.t('modal.change_password_title')) content: i18n.t('mydocument.waiting.waiting_desc') }); } else { Modal.showAlert({ title: i18n.t('mydocument.error.title'), // Should support multiple langue (i18n.t('modal.change_password_title')) content: "
i18n.t('mydocument.error.content')
" }); } } }); } ; /** * Add document to session * @returns {undefined} */ function fnAddDocumentToSession() { console.log("abcds"); var json = {u_id: s.getSessionID(), doc: checkedList.toString()}; $.cookie('doc', JSON.stringify(json)); window.location.href = "SendWizard"; } /** * Show warning popup to delete document * @returns {Boolean} */ function fnWarningDeleteDocument() { if (checkedList.length === 0) { return false; } else { Modal.showConfirmPopup({ title: i18n.t('mydocument.message.confirm_delete.title'), content: i18n.t('mydocument.message.confirm_delete.content'), okCallback: fnDeleteDocument }); return false; } } /** * Do delete * @returns {undefined} */ function fnDeleteDocument() { // Call API $.ajax({ dataType: 'json', type: "POST", url: "api/v1/DeleteDocument", data: {DocumentId: checkedList.toString(), SessionId: s.getSessionID(), UserID: HoGoUtils.getParameter()["userID"]}, timeout: HoGoConst.APITimeout, beforeSend: function () { appendLoadingWithText("iDeleteDocument", "#wizard", i18n.t('loader.delete'), true); // Disable button send and delete DTUtils.fnDisableControl(lDisableButton); }, success: function (dt) { removeLoading("iDeleteDocument"); //Clear error list checkedList = []; if (dt.status === "OK") { $('#cbo_selectall').prop('checked', false); $('label[for=cbo_selectall]').removeClass('checked'); // Redraw table if (oTable) { oTable.fnDraw(); } if (ffTable) { ffTable.fnDraw(); } } else { Modal.showAlert({content: i18n.t('mydocument.message.fail_delete')}); } } }); } /** * MyDocumentDetail page * @type type */ var MyDocumentDetail = { isChanged: false, fileID: false, result: false, isThumbnailChanged: false, documentTitle: null, documentDescription: null, documentFolderName: null, repList: [], listRepId: [], docID: HoGoUtils.getParameter()["documentId"], folderID: HoGoUtils.getParameter()["folderId"], //Get document detail getDocumentDetail: function () { var postDataLoadDocument = {}; postDataLoadDocument["DocumentID"] = HoGoUtils.getParameter()["documentId"]; postDataLoadDocument["SessionID"] = s.getSessionID(); postDataLoadDocument["UserID"] = HoGoUtils.getParameter()["userID"]; postDataLoadDocument["FolderID"] = HoGoUtils.getParameter()["folderId"]; $.ajax({ url: 'api/v1/GetDocumentDetail', type: 'POST', data: postDataLoadDocument, dataType: "json", success: function (data) { // console.log('doc detail'); if (data.status === "OK") { $.each(data.detail, function (key, value) { //Set data on view $("#documentTitle").val(value.title); $("#documentDescription").val(value.description); $("#folder_name").html((value.folderName !== "") ? value.folderName : "All files"); MyDocumentDetail.documentTitle = value.title; MyDocumentDetail.documentDescription = value.description; MyDocumentDetail.documentFolderName = value.folderName; $("#doc_create_date").html(value.create_date); var fileSize = value.file_size; var sizeUnit = "KB"; fileSize = Math.round(fileSize / 1024); if (fileSize > 1024) { fileSize = Math.round(fileSize / 1024); sizeUnit = "MB"; } $("#fileSize").html(fileSize + sizeUnit); $("#fileType").html(""); var t = $("#fileType").find('.ft'); HoGoUtils.drawDocumentIconFromType(t, value.type); // #protect document (parseInt(value.is_encrypt) === 0) ? $('#protect').prop('checked', false) : $('#protect').prop('checked', true); if (parseInt(value.is_encrypt) === 0) { $("#documentTabs").addClass('hide'); $("input#fileName").prop('disabled', true); } }); } else { // console.log('doc detail'); fnSessionTimeout(data, null, "MyDocumentList"); } }, error: function () { window.location.href = "MyDocumentList"; } }); }, //Get history for document getHistoryOfDocument: function () { var _this = MyDocumentDetail; //GET HISTORY LIST $('#tablepaging').dataTable({ "aaSorting": [[0, 'desc']], "bFilter": false, "bInfo": false, "bLengthChange": false, "bPaginate": true, "iDisplayLength": 10, "sPaginationType": "full_numbers", "oLanguage": DTUtils.DTLang, "sDom": 'pli<"clear">tr', "bServerSide": true, "bProcessing": true, "sAjaxSource": "api/v1/GetHistoryForRecipientDocument", "fnServerData": function (sSource, aoData, fnCallback, oSettings) { $.ajax({ "dataType": 'json', "type": "POST", "url": sSource, "timeout": HoGoConst.APITimeout, "data": historyRecipientDocumentPostData(aoData, "undefined", HoGoUtils.getParameter()["documentId"]), "success": function (data) { var json = {"sEcho": data.sEcho, "iTotalDisplayRecords": data.totalResult, "aaData": []}; if (data.status === "OK") { // Reset first _this.listRepId = []; var newIds = []; // Get ids from doc list $.each(_this.repList, function (i, d) { _this.listRepId.push(d.recipient_id); }); $.each(data.history_detail, function (key, value) { json.aaData.push({"package_id": value.package_id, "history_id": value.history_id, "recipient_id": value.recipient_ids, "history_type": value.history_type, "create_date": DateUtils.convertFullDate(DateUtils.convertUTCToLocalTime(value.create_date, s.getTimeZone())), "status": ""}); if (value.history_type === HoGoConst.DOCUMENT_VIEWED_TYPE || value.history_type === HoGoConst.DOCUMENT_OPENED_TYPE) { if ($.inArray(value.recipient_ids, _this.listRepId) === -1) { if (value.recipient_ids.length === 32) newIds.push(value.recipient_ids); } } }); if (newIds.length > 0) { _this.listRepId = newIds; } else { // No new id _this.listRepId = []; } } fnCallback(json); } }); }, "fnRowCallback": function (nRow, aData) { var content = HoGoUtils.parseHistoryTypeToText(aData.history_type); switch (aData.history_type) { case HoGoConst.DOCUMENT_VIEWED_TYPE: content = i18n.t('history.event.document_viewed'); if (aData.recipient_id) $("td:eq(1)", nRow).html(content + ' ' + '' + aData.recipient_id + ''); else $("td:eq(1)", nRow).html(content); if (UserSession.getAdminObject() === null) { $("td:eq(2)", nRow).html(""); } else { $("td:eq(2)", nRow).html(""); } nRow.ondblclick = function () { //Go detail if (UserSession.getAdminObject() === null) { window.location.href = "PackageDetailDownload?packageId=" + aData.package_id } else { window.location.href = "PackageDetailDownloadAdmin?packageId=" + aData.package_id + "&userID=" + HoGoUtils.getParameter()["userID"] + "&documentId=" + HoGoUtils.getParameter()["documentId"]; } }; break; case HoGoConst.DOCUMENT_OPENED_TYPE: console.log(aData); content = i18n.t('history.event.document_opened'); if (UserSession.getAdminObject() === null) { $("td:eq(1)", nRow).html(content + ' '); $("td:eq(2)", nRow).html(""); } else { $("td:eq(1)", nRow).html(content + ' '); $("td:eq(2)", nRow).html(""); } nRow.ondblclick = function () { //Go detail if (UserSession.getAdminObject() === null) { window.location.href = "PackageDetailDownload?packageId=" + aData.package_id } else { window.location.href = "PackageDetailDownloadAdmin?packageId=" + aData.package_id + "&userID=" + HoGoUtils.getParameter()["userID"] + "&documentId=" + HoGoUtils.getParameter()["documentId"]; } }; break; case HoGoConst.DIRECT_SEND_TYPE: case HoGoConst.CREATE_LINK_NONDOWNLOAD_TYPE: case HoGoConst.CREATE_LINK_DOWNLOAD_TYPE: case HoGoConst.LINK_SPECIFY_CREATED_TYPE: case HoGoConst.LINK_ANONYMOUS_CREATED_TYPE: $("td:eq(1)", nRow).html(content); if (UserSession.getAdminObject() === null) { $("td:eq(2)", nRow).html(""); } else { $("td:eq(2)", nRow).html(""); } // $("td:eq(2)", nRow).html(""); nRow.ondblclick = function () { //Go detail if (UserSession.getAdminObject() === null) { window.location.href = "PackageDetailDownload?packageId=" + aData.package_id } else { window.location.href = "PackageDetailDownloadAdmin?packageId=" + aData.package_id + "&userID=" + HoGoUtils.getParameter()["userID"] + "&documentId=" + HoGoUtils.getParameter()["documentId"]; } }; break; default: $("td:eq(1)", nRow).html(content); break; } }, "aoColumnDefs": [ //{"sType": "date-hogo", 'aTargets': [ 0 ]}, {'bSortable': false, 'aTargets': [1, 2]} ], "fnDrawCallback": function (oSettings) { // DTUtils.fnSetUpTableControl(oSettings); if (_this.listRepId.length > 0) { $.post('api/v1/GetRecipientDetail?time=' + new Date().getTime(), {SessionID: s.getSessionID(), RecipientID: _this.listRepId.toString(), Delete: true, UserID: HoGoUtils.getParameter()["userID"]}, function (data) { if (data.status === 'OK') { $.each(data.detail, function (key, value) { var jrep = {recipient_id: key, first_name: value.first_name, last_name: value.last_name, email: value['e-mail'], status: value.status}; // Push to doc list MyDocumentDetail.repList.push(jrep); }); console.log(MyDocumentDetail.repList); // Render on view again $.each(MyDocumentDetail.repList, function (key, value) { // Find all element which content docId $.each($('.sent-info').find('.mark-content-link'), function (i, e) { if ($(e).attr('rep-id') === value.recipient_id) { if (s.getLang() === 'ja') // Set up new content $(e).text(value.last_name + ' ' + value.first_name); else $(e).text(value.first_name + ' ' + value.last_name); if (value.status === HoGoConst.REMOVED_STATUS) { $(e).removeAttr('href').removeClass('mark-content-link').addClass('mark-content-delete').attr('title', 'This recipient has been deleted'); } } }); }); } }); } else { // Render on view again $.each(MyDocumentDetail.repList, function (key, value) { // Find all element which content docId $.each($('.sent-info').find('.mark-content-link'), function (i, e) { if ($(e).attr('rep-id') === value.recipient_id) { if (s.getLang() === 'ja') // Set up new content $(e).text(value.last_name + ' ' + value.first_name); else $(e).text(value.first_name + ' ' + value.last_name); if (value.status === HoGoConst.REMOVED_STATUS) { $(e).removeAttr('href').removeClass('mark-content-link').addClass('mark-content-delete').attr('title', 'This recipient has been deleted'); } } }); }); } }, "aoColumns": [ {"mDataProp": "create_date"}, {"mDataProp": "history_type"}, {"mDataProp": "status"} ] }); }, fnDeleteDocument: function () { //Post data var postDataDel = {}; postDataDel["DocumentId"] = MyDocumentDetail.docID; postDataDel["SessionId"] = s.getSessionID(); postDataDel["UserID"] = HoGoUtils.getParameter()["userID"]; //Do Delete $.ajax({ url: 'api/v1/DeleteDocument', type: 'POST', data: postDataDel, dataType: "json", beforeSend: function () { appendLoadingWithText("iDeleteDocument", "#wizard", i18n.t('loader.delete'), true); }, success: function (data) { removeLoading("iDeleteDocument"); if (data.status === "OK") { if (HoGoUtils.getPageName() === 'mydocumentdetailadmin.html') { // console.log("UserDetail?userID=" + HoGoUtils.getParameter()["userID"]); window.location.href = "UserDetail?userID=" + HoGoUtils.getParameter()["userID"] + "#/document-list"; } else { window.location.href = "MyDocumentList"; } } else { fnSessionTimeout(data, null, "MyDocumentList"); } } }); }, /** * Update document with specific changes * @returns {jqXHR} */ updateDocument: function () { if (!formStatus) { return false; } var $this = MyDocumentDetail; //Update thumbnail if have any changed if ($this.isThumbnailChanged) { var dataImage = {}; dataImage["DocumentID"] = HoGoUtils.getParameter()["documentId"]; dataImage["SessionID"] = s.getSessionID(); dataImage["FileID"] = $this.fileID; dataImage["userID"] = HoGoUtils.getParameter()["userID"]; $.ajax({ url: 'api/v1/UpdateThumbnail', type: 'POST', data: dataImage, dataType: "json", timeout: HoGoConst.APITimeout, beforeSend: function () { //Opacity $("#documentThumbnail").css({opacity: 0.25}); //Dispay loader $('.thumbnail-container>.indicator').css({'background-size': '20px'}); }, success: function (data) { if (data.status === "OK") { //TODO } else if (data.status === "NotSupport") { Modal.showAlert({content: i18n.t('mydocument.updatethumbnail')}); } else { HoGoUtils.writeLog(data.status_desc); Modal.showAlert({content: i18n.t('error.unknown')}); } }, complete: function () { //Opacity $("#documentThumbnail").css({'opacity': 1}); //Dispay loader $('.thumbnail-container>.indicator').css({'background-size': 0}); }, error: function () { Modal.showAlert({content: i18n.t('error.unknown')}); //Opacity $("#documentThumbnail").css({'opacity': 1}); //Dispay loader $('.thumbnail-container>.indicator').css({'background-size': 0}); } }); } //Submit value change var postDataDocument = {}; postDataDocument["SessionID"] = s.getSessionID(); postDataDocument["DocumentID"] = MyDocumentDetail.docID; postDataDocument["Title"] = $.trim($("#documentTitle").val()); postDataDocument["Description"] = $.trim($('#documentDescription').val()); postDataDocument["UserID"] = HoGoUtils.getParameter()["userID"]; return $.ajax({ url: 'api/v1/UpdateDocument', type: 'POST', data: postDataDocument, dataType: "json", beforeSend: function () { //Disable btn save HoGoUtils.disableButton('#update-document', {colorClass: 'green'}); //Display loader $("#validation .actionBar>.loader").show('fast'); }, success: function (data) { $("#validation .actionBar>.loader").hide('slow'); if (data.status === "OK") { $this.isChanged = false; $this.getDocumentDetail(); } else { fnSessionTimeout(data, null, "MyDocumentList"); } } }); }, uploadThumbnail: function () { //Opacity $("#documentThumbnail").css({opacity: 0.25}); //Dispay loader $('.thumbnail-container>.indicator').css({'background-size': '20px'}); //Send $.ajaxFileUpload({ url: "api/v1/UploadThumbnail?SessionID=" + s.getSessionID() + '&UserID=' + HoGoUtils.getParameter()["userID"], secureuri: true, fileElementId: "fileName", dataType: 'json', beforeSend: function () { $("#documentThumbnail").css({opacity: 0.25}); $('.thumbnail-container>.indicator').css({'background-size': '20px'}); }, success: function (data) { //Opacity $("#documentThumbnail").css({'opacity': 1}); //Dispay loader $('.thumbnail-container>.indicator').css({'background-size': 0}); if (data.status === 'OK') { MyDocumentDetail.fileID = data.file_id; $("#documentThumbnail").attr("src", "api/v1/GetUploadedFile?FileID=" + MyDocumentDetail.fileID + "&SessionID=" + s.getSessionID() + "&userID=" + HoGoUtils.getParameter()["userID"]); //Update changed MyDocumentDetail.isChanged = true; MyDocumentDetail.isThumbnailChanged = true; //Enable btn submit HoGoUtils.enableButton('#update-document', {colorClass: 'green', isSubmitForm: true}); } else if (data.status === APIConst.maxFileErrorStatus) { Modal.showAlert({ title: i18n.t('mydocument.message.invalid_file.title'), content: i18n.t('mydocument.message.invalid_file.content') }); return false; } }, error: function () { //Opacity $("#documentThumbnail").css({'opacity': 1}); //Dispay loader $('.thumbnail-container>.indicator').css({'background-size': 0}); } }); }, uploadFile: function () { var current_file_name = ""; var name = document.getElementById("fileName"); // Check select file if (typeof name === "undefined") { return; } else { if (typeof name.value === "undefined" || name.value === "") { return; } else { //Check file type current_file_name = basename(name.value); var extension = current_file_name.substr((current_file_name.lastIndexOf('.') + 1)).toLowerCase(); if (extension !== "JPEG" && extension !== "JPG" && extension !== "jpeg" && extension !== "jpg") { Modal.showAlert({ title: i18n.t('mydocument.message.invalid_format.title'), content: i18n.t('mydocument.message.invalid_format.content') }); return; } else { //Do upload MyDocumentDetail.uploadThumbnail(); } } } }, sendToWizard: function () { var json = {u_id: s.getSessionID(), doc: this.docID}; $.cookie('doc', JSON.stringify(json)); console.log($.cookie('doc', JSON.stringify(json))); window.location.href = "SendWizard"; }, exportAccessReport: function () { $('#btn_report').bind('click', function () { var param = {}; param["SessionID"] = UserSession.getSessionID(); param["DocumentId"] = MyDocumentDetail.docID; if (UserSession.getAdminObject() !== null) { param["UserID"] = HoGoUtils.getParameter()['userID']; } console.log(param); $.fileDownload('api/v1/ExportAccessDocementDetail?' + $.param(param), { httpMethod: 'get' }).then(function () { }, function (errorText) { // JSON.parse( $(errorText).text() ); Modal.showAlert({ title: i18n.t('history.package.modal.access_modal_title'), text: i18n.t('history.package.modal.access_modal_content') }); }); }); } }; /** * get User folder document list * @returns {undefined} */ function makeFolderList(fnCallback) { fTable = $('#tablefolderpaging').dataTable({ "aaSorting": [[3, 'desc']], "bInfo": false, "bLengthChange": false, "bPaginate": true, "iDisplayLength": 10, "sPaginationType": "full_numbers", "oLanguage": DTUtils.DTLang, "sDom": '<"right"f>l<"inline"p>irt', "sAjaxSource": "api/v1/GetDocumentFolderList", "bServerSide": true, "bProcessing": true, "fnServerData": function (sSource, aoData, fnCallback, oSettings) { $.ajax({ url: sSource, type: "GET", dataType: "json", data: DTUtils.folderListPostData(aoData), timeout: HoGoConst.APITimeout, success: function (data) { if (data.status === "OK") { var json = {"sEcho": data.sEcho, "iTotalDisplayRecords": data.totalResult, "aaData": []}; $.each(data.document_folder, function (key, value) { json.aaData.push({"id": value.folder_id, "folder_name": value.folder_name, "description": value.description, "create_date": value.create_date, "num_files": value.num_files, "status": value.status}); }); } else { //window.location.reload(); } fnCallback(json); } }); }, "fnRowCallback": function (nRow, aData) { $("td:eq(1)", nRow).html("
" + aData.folder_name + "
"); $("td:eq(2)", nRow).html("
" + aData.description + "
"); $("td:eq(3)", nRow).html(DateUtils.convertDate(aData.create_date)); $("td:eq(0)", nRow).html(""); $("td:eq(4)", nRow).html("" + aData.num_files + ""); if (UserSession.getAdminObject() === null) { var contentHtml = " "; } else { var contentHtml = " "; } // var contentHtml = " "; $("td:eq(5)", nRow).html(contentHtml); nRow.ondblclick = function () { window.location.href = "MyDocumentFolderDetail?folderId=" + aData.id; }; }, // Restore state of document pages (before redirect to document detail) "bStateSave": true, "fnStateLoad": function (oSettings) { if ($.cookie('l_p') === 'mydocumentdetail.html') { var sData = this.oApi._fnReadCookie(oSettings.sCookiePrefix + oSettings.sInstance); var oData; try { oData = (typeof $.parseJSON === 'function') ? $.parseJSON(sData) : eval('(' + sData + ')'); } catch (e) { oData = null; } if (oData !== null) if (oData.oSearch.sSearch !== null) $('#filter').val(oData.oSearch.sSearch); return oData; } else { return null; } }, "aoColumnDefs": [ {'bSortable': false, 'aTargets': [0, 4]} ], "oScroller": { "loadingIndicator": true }, "fnDrawCallback": function (oSettings) { $('#tablefolderpaging .ck').customInput(); //Control stuff // DTUtils.fnSetUpTableControl(oSettings); //Clear array if (oSettings.bSorted) { folderCheckedList.splice(0, folderCheckedList.length); //Disable DTUtils.fnDisableControl(lDisableButtonFolder); } //Checkbox event DTUtils.checkboxSwitchPage("tablefolderpaging", "child", "select_all_folder", folderCheckedList); //Evnet click after that $(':checkbox[name=child]').on('click', function () { DTUtils.checkboxChildSelectEvent(this, "select_all_folder", folderCheckedList); //Enable/Disable button if (folderCheckedList.length > 0) { //Enable DTUtils.fnEnableControl(lEnableBtnFolder); } else { //Disable DTUtils.fnDisableControl(lDisableButtonFolder); } }); }, "aoColumns": [ {"mDataProp": "id"}, {"mDataProp": "folder_name"}, {"mDataProp": "description"}, {"mDataProp": "create_date"}, {"mDataProp": "num_files"}, {"mDataProp": "status"} ], "fnInitComplete": function (s) { $('#' + s.sTableId).i18n(); $('#' + s.sTableId + '_length').find('select').selectmenu(); if (typeof fnCallback === 'function') { fnCallback.call(); } }, "bDestroy": true }); } ; function showAddNewDocumentFolder() { Modal.createModal(2, { title: i18n.t('password.change_password.title'), // Should support multiple langue (i18n.t('modal.change_password_title')) preventClose: true, onLoad: function () { HoGoUtils.validateForm('validationCP', MyDocument); }, templateUrl: "Template/add_new_document_folder.html", okCallback: function (modal) { // Call submit form var form = modal.find('form'); form.submit(); doAddNewDocumentFolder(); } }); } ; function doAddNewDocumentFolder() { $('form#validationCP').find('.formErrorContent').css('white-space', 'nowrap'); if (!MyDocument.fStatus) { return; } var postData = {}; postData["folder_name"] = $('#folder_name').val().trim(); postData["description"] = $('#description').val().trim(); postData["session_id"] = s.getSessionID(); //TODO ajax return $.ajax({ type: "POST", url: "api/v1/AddDocumentFolder", data: postData, beforeSend: function () { Modal.closeModal(); }, success: function (data) { if (data.status === 'OK') { HoGoUtils.makeNotifyServer({ "msg": i18n.t('modal.create_folder.success'), "autoClose": true, "time": 1000 }); //Update table fTable.fnDraw(); } else if (data.status === 'FolderExisted') { Modal.showAlert({content: i18n.t('modal.create_folder.exist')}); } else { fnSessionTimeout(data); } } }); } ; function fnWarningDeleteFolderDocument() { if (folderCheckedList.length === 0) { return false; } else { Modal.showConfirmPopup({ title: i18n.t('mydocument.message.confirm_delete.title'), content: i18n.t('mydocument.message.confirm_delete.content'), okCallback: fnDeleteFolder }); return false; } } ; function fnDeleteFolder() { // Call API $.ajax({ dataType: 'json', type: "POST", url: "api/v1/DeleteDocumentFolder", data: {folder_ids: folderCheckedList.toString(), session_id: s.getSessionID(), UserID: HoGoUtils.getParameter()["userID"]}, timeout: HoGoConst.APITimeout, beforeSend: function () { appendLoadingWithText("iDeleteDocument", "#wizard", i18n.t('loader.delete'), true); // Disable button send and delete DTUtils.fnDisableControl(lDisableButton); }, success: function (dt) { removeLoading("iDeleteDocument"); //Clear error list folderCheckedList = []; if (dt.status === "OK") { // problem with checker, handle later $('#cbo_selectall_folder').prop('checked', false); $('label[for=cbo_selectall_folder]').removeClass('checked'); // Redraw table fTable.fnDraw(); } else { Modal.showAlert({content: i18n.t('mydocument.message.fail_delete')}); } } }); } var MyDocumentFolderDetail = { isChanged: false, folderName: null, description: null, folderId: HoGoUtils.getParameter()["folderId"], getDocumentFolderDetail: function () { var postDataLoadFolder = {}; postDataLoadFolder["folder_id"] = HoGoUtils.getParameter()["folderId"]; postDataLoadFolder["session_id"] = s.getSessionID(); postDataLoadFolder["user_id"] = HoGoUtils.getParameter()["userID"]; $.ajax({ url: 'api/v1/GetDocumentFolderDetail', type: 'GET', data: postDataLoadFolder, dataType: "json", success: function (data) { if (data.status === "OK") { var value = data.results; //Set data on view $("#folder_name").val(value.folderName); $("#folder_description").val(value.description); MyDocumentFolderDetail.folderName = value.folderName; MyDocumentFolderDetail.description = value.description; $("#folder_create_date").html(value.createDate); } else { fnSessionTimeout(data, null, "MyDocumentList"); } }, error: function () { window.location.href = "MyDocumentList"; } }); }, getDocumentFolderListFile: function () { ffTable = $('#tablepaging').dataTable({ "aaSorting": [[4, 'desc']], "bInfo": false, "bLengthChange": false, "bPaginate": true, "iDisplayLength": 10, "sPaginationType": "full_numbers", "oLanguage": DTUtils.DTLang, "sDom": '<"right"f>l<"inline"p>irt', "sAjaxSource": "api/v1/GetDocumentFolderListFiles", "bServerSide": true, "bProcessing": true, "fnServerData": function (sSource, aoData, fnCallback, oSettings) { $.ajax({ url: sSource, type: "GET", dataType: "json", data: DTUtils.documentFolderListFilesPostData(aoData), timeout: HoGoConst.APITimeout, success: function (data) { if (data.status === "OK") { var json = {"sEcho": data.sEcho, "iTotalDisplayRecords": data.totalResult, "aaData": []}; $.each(data.document_detail, function (key, value) { json.aaData.push({"id": value.id, "title": value.title, "file_name": value.file_name, "type": value.type, "create_date": value.create_date, "status": value.status, "is_encrypt": value.is_encrypt, "file_path": value.file_path, "folderId": value.folderId}); }); } else { //window.location.reload(); } fnCallback(json); } }); }, "fnRowCallback": function (nRow, aData) { $("td:eq(1)", nRow).html("
" + aData.file_name + "
"); $("td:eq(2)", nRow).html("
" + aData.title + "
"); $("td:eq(3)", nRow).html(""); var t = $("td:eq(3)", nRow).find('.ft'); HoGoUtils.drawDocumentIconFromType(t, aData.type); $("td:eq(4)", nRow).html(DateUtils.convertDate(aData.create_date)); $("td:eq(0)", nRow).html(""); if (UserSession.getAdminObject() === null) { var contentHtml = " "; } else { var contentHtml = " "; } if (parseInt(aData.is_encrypt) === 0) { if (parseInt(aData.type) !== HoGoConst.FILE_ORTHER_TYPE) contentHtml += ""; else contentHtml += ""; } else { contentHtml += ""; } $("td:eq(5)", nRow).html(contentHtml); nRow.ondblclick = function () { window.location.href = "MyDocumentFolderDetail?folderId=" + aData.id; }; $("td:eq(5)", nRow).find('a.btn-view-online').bind('click', function () { viewOnlineNonProtectDocument(aData.title, aData.id, aData.type); }); }, // Restore state of document pages (before redirect to document detail) "bStateSave": true, "fnStateLoad": function (oSettings) { // if ($.cookie('l_p') === 'mydocumentfolderdetail.html') { // var sData = this.oApi._fnReadCookie(oSettings.sCookiePrefix + oSettings.sInstance); // var oData; // // try { // oData = (typeof $.parseJSON === 'function') ? // $.parseJSON(sData) : eval('(' + sData + ')'); // } catch (e) { // oData = null; // } // if (oData !== null) // if (oData.oSearch.sSearch !== null) // $('#filter').val(oData.oSearch.sSearch); // return oData; // } else { // return null; // } }, "aoColumnDefs": [ {'bSortable': false, 'aTargets': [0, 5]} ], "oScroller": { "loadingIndicator": true }, "fnDrawCallback": function (oSettings) { $('#tablepaging .ck').customInput(); //Control stuff // DTUtils.fnSetUpTableControl(oSettings); //Clear array if (oSettings.bSorted) { checkedList.splice(0, checkedList.length); //Disable DTUtils.fnDisableControl(lDisableButton); } DTUtils.checkboxSwitchPage("tablepaging", "child", "select_all", checkedList); //Evnet click after that $(':checkbox[name=child]').on('click', function () { DTUtils.checkboxChildSelectEvent(this, "select_all", checkedList); //Enable/Disable button if (checkedList.length > 0) { //Enable DTUtils.fnEnableControl(lEnableButton); } else { //Disable DTUtils.fnDisableControl(lDisableButton); } }); }, "aoColumns": [ {"mDataProp": "id"}, {"mDataProp": "file_name"}, {"mDataProp": "title"}, {"mDataProp": "type"}, {"mDataProp": "create_date"}, {"mDataProp": "status"} ], "fnInitComplete": function (s) { $('#' + s.sTableId).i18n(); $('#' + s.sTableId + '_length').find('select').selectmenu(); } }); }, updateDocumentFolderInfo: function () { var postDataFolder = {}; postDataFolder["session_id"] = s.getSessionID(); postDataFolder["folder_id"] = MyDocumentFolderDetail.folderId; postDataFolder["folder_name"] = $.trim($('#folder_name').val()); postDataFolder["description"] = $.trim($('#folder_description').val()); postDataFolder["UserID"] = HoGoUtils.getParameter()["userID"] return $.ajax({ url: 'api/v1/UpdateDocumentFolder', type: 'POST', data: postDataFolder, dataType: "json", beforeSend: function () { //Disable btn save HoGoUtils.disableButton('#update-folder', {colorClass: 'green'}); //Display loader $("#validation .actionBar>.loader").show('fast'); }, success: function (data) { $("#validation .actionBar>.loader").hide('slow'); if (data.status === "OK") { MyDocumentFolderDetail.isChanged = false; MyDocumentFolderDetail.getDocumentFolderDetail(); } else { fnSessionTimeout(data, null, "MyDocumentList"); } } }); }, deleteFolderDocument: function () { // Call API $.ajax({ dataType: 'json', type: "POST", url: "api/v1/DeleteDocumentFolder", data: {folder_ids: HoGoUtils.getParameter()["folderId"], session_id: s.getSessionID(), UserID: HoGoUtils.getParameter()["userID"]}, timeout: HoGoConst.APITimeout, beforeSend: function () { appendLoadingWithText("iDeleteDocument", "#wizard", i18n.t('loader.delete'), true); // Disable button send and delete DTUtils.fnDisableControl(lDisableButton); }, success: function (dt) { removeLoading("iDeleteDocument"); //Clear error list folderCheckedList = []; if (dt.status === "OK") { Modal.showAlert({content: i18n.t('mydocument.message.succeed_delete')}); if (dt.status === 'OK') { HoGoUtils.makeNotifyServer({ "msg": i18n.t('show_message.delete_success'), "autoClose": true, "time": 1000 }); } fnSessionTimeout(dt, null, "MyDocumentList"); } else { Modal.showAlert({content: i18n.t('mydocument.message.fail_delete')}); } } }); } }; function addMoveFilestoFolder(data) { var folderIdSelect; Modal.createModal(2, { title: i18n.t('modal.move_add_folder_title'), // Should support multiple langue (i18n.t('modal.change_password_title')) preventClose: true, onLoad: function () { HoGoUtils.validateForm('validationCP', MyDocument); var options = { valueNames: ['foldername', 'createdate', 'nofiles', {data: ['id']}], item: '
  • ' + '
    ' + '
    ' + '
    ' + '
  • ' // page: 3, // pagination: true }; // HoGoUtils.disableButton('.btn-ok', {colorClass: 'green'}); var values = data; // console.log(values); // Init list var listFolders = new List('listfolders', options, values); var editBtns = $('.item-select'); editBtns = $(editBtns.selector); editBtns.click(function () { // remove all select firt editBtns.removeClass("folder_selected"); folderIdSelect = $(this).attr('data-id'); // re check selected $(this).addClass("folder_selected"); $("#warning-select").hide(); }); }, templateUrl: "Template/folder_list.html", okCallback: function (modal) { if (folderIdSelect) { // console.log(folderIdSelect); // do add checkedList.push(HoGoUtils.getParameter()["documentId"]); doAddDocumentToFolder(checkedList, folderIdSelect); } else { // console.log("not seletect"); $("#warning-select").show(); } } }); } ; function getUserFolderList(cb, error) { var params = {}; params["SessionID"] = s.getSessionID(); params["UserID"] = HoGoUtils.getParameter()["userID"]; $.ajax({ url: 'api/v1/GetUserDocumentFolderList?time=' + new Date().getTime(), type: 'GET', data: params, dataType: "json", success: function (data) { if (data.status === "OK") { cb && cb(data.list_folders); } else { error && error(); } }, error: function () { window.location.href = "MyDocumentList"; } }); } function showUserFoldersList() { getUserFolderList(function (list_folder) { // get sucess if (list_folder.length > 0) { var values = []; $.each(list_folder, function (idx, val) { values.push({id: val.folder_id, foldername: val.folder_name, createdate: DateUtils.convertDate(val.create_date), nofiles: val.no_files}); }); addMoveFilestoFolder(values); } else { Modal.showAlert({"content": i18n.t('show_message.add_no_folder')}); } }, function () { // can not get list folders Modal.showAlert({"content": i18n.t('show_message.error.get_folder')}); }); } function doAddDocumentToFolder(documentIds, folderId) { var postData = {}; postData["folder_id"] = folderId; postData["doc_ids"] = documentIds.toString(); postData["session_id"] = s.getSessionID(); postData["UserID"] = HoGoUtils.getParameter()["userID"]; //TODO ajax return $.ajax({ type: "POST", url: "api/v1/AddMoveFilesDocumentFolder", data: postData, beforeSend: function () { Modal.closeModal(); }, success: function (data) { if (data.status === 'OK') { HoGoUtils.makeNotifyServer({ "msg": i18n.t('show_message.move_add_success'), "autoClose": true, "time": 800 }); if (fTable) fTable.fnDraw(); if (HoGoUtils.getPageName() === "mydocumentdetail.html") { MyDocumentDetail.getDocumentDetail(); } } else { Modal.showAlert(i18n.t('show_message.error.move_file')); } } }); } return { fStatus: false, /** * Get datatable manage document list * @returns {unresolved} */ getTable: function () { return oTable; }, updateDocument: function () { MyDocumentDetail.updateDocument(); }, makeListDocument: function (readOnlyMode, fnCallback) { makeListDocument(readOnlyMode, fnCallback); }, getDocumentFolerList: function () { MyDocumentFolderDetail.getDocumentFolderListFile(); }, getFolderTable: function () { return fTable; }, makeFolderList: function (fnCallback) { makeFolderList(fnCallback); }, updateDocumentFolderInfo: function () { MyDocumentFolderDetail.updateDocumentFolderInfo(); }, viewOnlineNonProtectDocument: viewOnlineNonProtectDocument, /** * Init elements * @returns {undefined} */ init: function () { var pName = HoGoUtils.getPageName(); if (pName === 'mydocumentlist.html' || pName === 'userdetail.html') { // Initialize MyDocumentList page if ($('#myDocumentList').length > 0) { if (pName !== "userdetail.html") makeListDocument(false); $("#filter").keyup(function () { DTUtils.fnDisableControl(lDisableButton); oTable.fnFilter($("#filter").val()); }); $('#myDocumentList #cbo_selectall').on('click', function () { DTUtils.checkboxSelectAllEvent(this, "child", checkedList); if (checkedList.length > 0) { DTUtils.fnEnableControl(lEnableButton); } else { DTUtils.fnDisableControl(lDisableButton); } }); } if ($('#myFolderList').length > 0) { if (pName !== "userdetail.html") makeFolderList(); $("#filter").keyup(function () { DTUtils.fnDisableControl(lDisableButtonFolder); oTable.fnFilter($("#filter").val()); }); $('#listFolderWrapper #cbo_selectall_folder').on('click', function () { DTUtils.checkboxSelectAllEvent(this, "child", folderCheckedList); if (folderCheckedList.length > 0) { DTUtils.fnEnableControl(lEnableBtnFolder); } else { DTUtils.fnDisableControl(lDisableButtonFolder); } }); $('#btn_add_folder').on('click', function () { showAddNewDocumentFolder(); }); } } if (pName === "mydocumentdetail.html" || pName === "mydocumentdetailadmin.html") { // Initialize MyDocumentDetail page if (pName === "mydocumentdetailadmin.html") { HoGoUtils.makeLeftMenuAdmin(); HoGoUtils.makeHrefHeaderAdmin(); //Click back button console.log('here'); console.log(prePage); $('#btn-back-document-detail').on('click', function () { // console.log(HoGoUtils.getParameter()["userID"]); // window.location.href = "UserDetail?userID=" + HoGoUtils.getParameter()["userID"] + "#/document-list"; $("#btn-back-document-detail").attr("href", prePage); }); } if ($('#myDocumentDetail').length > 0) { MyDocumentDetail.exportAccessReport(); $('#imageTipsy').tipsy({gravity: 'nw', className: 'image-tipsy'}); // Event onchange thumbnail $('#fileName').live('change', function () { MyDocumentDetail.uploadFile(); return false; }); // Event on change image button $("span.file-wrapper").mouseover(function () { $("span#textChangeImage").removeClass("orange").addClass("green-upload-image"); }); $("span.file-wrapper").mouseleave(function () { $("span#textChangeImage").removeClass("green-upload-image").addClass("orange"); }); MyDocumentDetail.getDocumentDetail(); MyDocumentDetail.getHistoryOfDocument(); /* Text change */ $('#documentTitle, #documentDescription').bind('keyup focusout', (function () { if (MyDocumentDetail.documentTitle !== $.trim($('#documentTitle').val()) || MyDocumentDetail.documentDescription !== $.trim($('#documentDescription').val())) { MyDocumentDetail.isChanged = true; HoGoUtils.enableButton('#update-document', {colorClass: 'green', isSubmitForm: true}); } else { MyDocumentDetail.isChanged = false; HoGoUtils.disableButton('#update-document', {colorClass: 'green'}); } })); //Dispay loader $('.thumbnail-container>.indicator').css({'background-size': '20px'}); //Get thumbnail from HoGo Bookend $("#documentThumbnail").css({opacity: 0.25}).attr("src", "api/v1/GetThumbnailFile?DocumentID=" + HoGoUtils.getParameter()["documentId"] + "&SessionID=" + s.getSessionID() + "&UserID=" + HoGoUtils.getParameter()["userID"]).load(function () { //Opacity $("#documentThumbnail").css({'opacity': 1}); //Dispay loader $('.thumbnail-container>.indicator').css({'background-size': 0}); }); //Click back button console.log(prePage); $('#btn-back-document').on('click', function () { if (MyDocumentDetail.isChanged === true) { //Get thumbnail from HoGo Bookend $("#documentThumbnail").css({opacity: 0.25}).attr("src", "api/v1/GetThumbnailFile?DocumentID=" + HoGoUtils.getParameter()["documentId"] + "&SessionID=" + s.getSessionID() + "&UserID=" + HoGoUtils.getParameter()["userID"]).load(function () { //Opacity $("#documentThumbnail").css({'opacity': 1}); //Dispay loader $('.thumbnail-container>.indicator').css({'background-size': 0}); }); Modal.showConfirmPopup({ okCallback: function () { $('#validation').submit(); }, cancelCallback: function () { window.location.href = "MyDocumentList"; }, content: i18n.t('mydocument.message.confirm_save') }); return false; } else // window.location.href = "UserDetail?userID=" + HoGoUtils.getParameter()["userID"]; $("#btn-back-document").attr("href", prePage); }); $('#btn-back-folder').on('click', function () { console.log('herere'); if (myDocumentFolderDetail.isChanged === true) { $('body').find(".formError").remove(); Modal.showConfirmPopup({ okCallback: function () { $('#validation').submit(); }, cancelCallback: function () { window.location.href = "MyDocumentList"; }, content: i18n.t('mydocument.message.confirm_save') }); return false; } else window.location.href = "MyDocumentList"; }); //Click delete button $('#btn_delete').on('click', function () { //Clean up error $("body").find(".formError").each(function () { $(this).remove(); }); MyDocumentDetail.isChanged = false; Modal.showConfirmPopup({ title: i18n.t('mydocument.message.confirm_delete.title'), content: i18n.t('mydocument.message.confirm_delete.content'), okCallback: MyDocumentDetail.fnDeleteDocument }); return false; }); //Click button change folder $('#btn_move_folder').on('click', function () { // console.log("click here.."); getUserFolderList(function (list_folder) { // get sucess if (list_folder.length > 0) { var values = []; $.each(list_folder, function (idx, val) { values.push({id: val.folder_id, foldername: val.folder_name, createdate: DateUtils.convertDate(val.create_date), nofiles: val.no_files}); }); addMoveFilestoFolder(values); } else { Modal.showAlert({"content": i18n.t('show_message.add_no_folder')}); } }, function () { // can not get list folders Modal.showAlert({"content": i18n.t('show_message.error.get_folder')}); }); }); //Click send button $('#btn_send').on('click', function () { MyDocumentDetail.sendToWizard(); }); } } if (pName === 'mydocumentfolderdetail.html' || pName === 'mydocumentfolderdetailadmin.html') { if (pName === 'mydocumentfolderdetailadmin.html') HoGoUtils.makeLeftMenuAdmin(); // Only admin page need to make menu MyDocumentFolderDetail.getDocumentFolderDetail(); $('#folder_name, #folder_description').bind('keyup focusout', (function () { if (MyDocumentFolderDetail.folderName !== $.trim($('#folder_name').val()) || MyDocumentFolderDetail.description !== $.trim($('#folder_description').val())) { MyDocumentFolderDetail.isChanged = true; HoGoUtils.enableButton('#update-folder', {colorClass: 'green', isSubmitForm: true}); } else { MyDocumentFolderDetail.isChanged = false; HoGoUtils.disableButton('#update-folder', {colorClass: 'green'}); } })); //Delete Folder $('#btn_delete_folder').on('click', function () { Modal.showConfirmPopup({ title: i18n.t('mydocument.message.confirm_delete.title'), content: i18n.t('mydocument.message.confirm_delete.content'), okCallback: function (modal) { // Call submit form var form = modal.find('form'); form.submit(); MyDocumentFolderDetail.deleteFolderDocument(); } }); }); // get list file MyDocumentFolderDetail.getDocumentFolderListFile(); $("#filter").keyup(function () { DTUtils.fnDisableControl(lDisableButton); oTable.fnFilter($("#filter").val()); }); $('#cbo_selectall').on('click', function () { DTUtils.checkboxSelectAllEvent(this, "child", checkedList); if (checkedList.length > 0) { DTUtils.fnEnableControl(lEnableButton); } else { DTUtils.fnDisableControl(lDisableButton); } }); } ; }// close init function };// close return }(jQuery, UserSession)); // // Manage basic setting account // var MyAccount = (function ($, s) { // Variables store orignal value var txtFirstName, txtMidtName, txtLastName, txtSenderMail, txtCompany, txtTimeZone, notify, newNotifyInt, oLandPage, nLandPage, lang; /** * Check or uncheck on checkbox with list notifycation 1/0 * @param {type} lstNotifycation * @returns {undefined} */ function setCheckedCheckbox(lstNotifycation) { for (i = 0; i < lstNotifycation.length; i++) { if (lstNotifycation[i] === "1") { var index = i + 1; var id = '#notify' + index; $(id).attr('checked', true); var maskLabel = $(id).parent().children("label"); maskLabel.addClass('checked'); } } } /** * Display on view which landing page is * @param {number} pageNumber The number presents for the page. [SendWizard: 1; MyDocument: 2; History: 3; AddressBook: 4] * @returns {Boolean} */ function setLandingPage(pageNumber) { switch (pageNumber) { case 1: $('#rSend').prop('checked', true); $('label[for=rSend]').addClass('checked'); break; case 2: $('#rMyDocument').prop('checked', true); $('label[for=rMyDocument]').addClass('checked'); break; case 3: $('#rHistory').prop('checked', true); $('label[for=rHistory]').addClass('checked'); break; case 4: $('#rAddressBook').prop('checked', true); $('label[for=rAddressBook]').addClass('checked'); break; } } /** * Check whether user info has been changed or not * @returns {Boolean} */ function isChangeDetail() { if (txtFirstName !== $.trim($('#txtFirstName').val()) || txtMidtName !== $.trim($('#txtMidtName').val()) || txtLastName !== $.trim($('#txtLastName').val()) || txtCompany !== $.trim($('#txtCompany').val()) || txtTimeZone !== $('#txtTimeZone').val() || txtSenderMail !== $.trim($('#txtSenderMail').val()) || lang !== $('#language').val() || notify !== newNotifyInt || parseInt(oLandPage) !== parseInt(nLandPage)) { HoGoUtils.enableButton("#btnSaveSetting", {colorClass: 'green', isSubmitForm: true}); return true; } else { HoGoUtils.disableButton("#btnSaveSetting", {colorClass: 'green'}); return false; } } /** * Make a request to save setting * @param {array} postData Data will be saved * @returns {jqXHR} */ function makeSaveRequest(postData) { postData['Lang'] = HoGoUtils.detectBrowserAutoLang(postData['Lang']); return $.ajax({ type: "POST", url: "api/v1/UpdateUserInfo", data: postData, dataType: "json", beforeSend: function () { //Disable btn save HoGoUtils.disableButton('#btnSaveSetting', {colorClass: 'green'}); $("#validation .actionBar>.loader").show('fast'); }, success: function (data) { $("#validation .actionBar>.loader").hide('slow'); var status = data.status; if (status === "OK") { MyAccount.loadingDataSetting().done(function (data) { var userInfo = data.detail; for (var key in userInfo) { var dt = userInfo[key]; var newLang = dt.lang; var lLang = newLang.split('-'); var isAuto = ($.trim(lLang[0]) === "auto") ? true : false; //Translate content if set another language s.updateUserInfo(isAuto); } }); } else if (data.status === APIConst.sessionIdNotFound) { window.location = "login"; } } }); } /** * Submit all info changed */ function submitSetting() { if (!formStatus) { return false; } var postData = {}; postData = $('form#validation').serializeObject(); postData["SessionID"] = s.getSessionID(); //If there's nothing change if (newNotifyInt === "") { newNotifyInt = notify; } postData['Notification'] = newNotifyInt; if ($.trim($('#language').val()) === 'auto') { postData['Lang'] = 'auto-' + HoGoUtils.detectBrowserLang(); } makeSaveRequest(postData); } /** * Make request data in order to get point history * @param {type} aoData * @returns {object} */ function pointHistoryPostData(aoData) { var post = {}; var colSort; var sortType; $.each(aoData, function (x, y) { if (y.name === "sEcho") { post["sEcho"] = y.value; } if (y.name === "iDisplayStart") { post["DisplayStart"] = y.value; } if (y.name === "iDisplayLength") { post["DisplayLength"] = y.value; } if (y.name === "sSearch") { post["SearchString"] = y.value; } if (y.name === "iSortCol_0") { colSort = y.value; } if (y.name === "sSortDir_0") { sortType = y.value; } }); switch (colSort) { case 1: if (sortType === "asc") post["SortType"] = 2; else post["SortType"] = 1; break; case 2: if (sortType === "asc") post["SortType"] = 4; else post["SortType"] = 3; break; case 3: if (sortType === "asc") post["SortType"] = 6; else post["SortType"] = 5; case 4: if (sortType === "asc") post["SortType"] = 8; else post["SortType"] = 7; break; } if (HoGoUtils.getPageName() === 'userdetail.html') { post["UserID"] = HoGoUtils.getParameter()['userID']; } post["SessionID"] = UserSession.getSessionID(); return post; } /** * Create table statistic history points * @param {type} fnCallback callback after table has been initilized * @returns {undefined} */ function loadingPointsHistory(fnCallback) { var l = 'en'; if (s.getUserObject() !== null) { l = s.getLang(); } $('#tblPointHistory').dataTable({ "aaSorting": [[1, 'desc']], "bInfo": false, "bLengthChange": false, "bPaginate": true, "iDisplayLength": 10, "sPaginationType": "full_numbers", "oLanguage": DTUtils.DTLang, "sDom": 'pli<"clear">r', "sAjaxSource": "api/v1/GetHistoryPoints", "bServerSide": true, "bDestroy": true, "bProcessing": true, "fnServerData": function (sSource, aoData, fnCallback, oSettings) { $.ajax({ url: sSource, type: "POST", dataType: "json", data: pointHistoryPostData(aoData), timeout: HoGoConst.APITimeout, success: function (data) { $("#tblPointHistory_wrapper").height(1); $("#tblPointHistory_paginate").css({"visibility": "visible", "float": "right", "padding-top": "0px", "padding-bottom": "15px"}); if (data.status === "OK") { var json = {"sEcho": data.sEcho, "iTotalDisplayRecords": data.totalResult, "aaData": []}; $.each(data.historyDetail, function (key, value) { json.aaData.push({"id": value.id, "type": value.type, "points": value.points, "cost": value.cost, "createDate": DateUtils.convertFullDate(value.createDate), "currency": value.currency, "paymentType": value.paymentType}); }); } else { } fnCallback(json); } }); }, "fnRowCallback": function (nRow, aData) { $("td:eq(0)", nRow).html(""); $("td:eq(1)", nRow).html("
    " + DateUtils.convertFullDate(aData.createDate) + "
    "); $("td:eq(2)", nRow).html("
    " + aData.points + "
    "); $("td:eq(3)", nRow).html("
    " + convertCentToUSD(aData.cost, aData.currency) + "
    "); $("td:eq(4)", nRow).html("
    " + Payment.convertPaymentTypeToText(aData.paymentType) + "
    "); nRow.setAttribute("style", "text-align: left"); }, "fnDrawCallback": function (oSettings) { DTUtils.determinePaging(oSettings); //Set up stuff // DTUtils.fnSetUpTableControl(oSettings); }, "aoColumnDefs": [ {'bSortable': false, 'aTargets': [0]} ], "aoColumns": [ {"mDataProp": "points"}, {"mDataProp": "points"}, {"mDataProp": "cost"}, {"mDataProp": "createDate"}, {"mDataProp": "createDate"} ], "fnInitComplete": function (s) { $('#' + s.sTableId).i18n(); if (typeof fnCallback === 'function') { fnCallback.call(); } } }); } // Loading data statistic on month function loadingStatisticOnMonth() { var postDataMonth = {}; postDataMonth["Days"] = 30; postDataMonth["SessionID"] = s.getSessionID(); $.ajax({ url: "api/v1/GetStatistics", type: "POST", dataType: "json", data: postDataMonth, timeout: HoGoConst.APITimeout, success: function (data) { if (data.status === "OK") { $("#numberDocumentUploadedMonth").html(data.numberUploadedDocuments); $("#numberDocumentSendDirectMonth").html(data.numberDocumentSendDirect); $("#numberRecipientSendDirectMonth").html(data.numberRecipientSendDirect); $("#numberDocumentDownloadCreateLinkMonth").html(data.numberDocumentDownloadCreateLink); $("#numberOfCreateLinkMonth").html(data.numberOfCreateLink); } else { $("#numberDocumentUploadedMonth").html(0); $("#numberDocumentSendDirectMonth").html(0); $("#numberRecipientSendDirectMonth").html(0); $("#numberDocumentDownloadCreateLinkMonth").html(0); $("#numberOfCreateLinkMonth").html(0); } } }); } // Loading data statistic on year function loadingStatisticOnYear() { var postDataYear = {}; postDataYear["Days"] = 365; postDataYear["SessionID"] = s.getSessionID(); $.ajax({ url: "api/v1/GetStatistics", type: "POST", dataType: "json", data: postDataYear, timeout: HoGoConst.APITimeout, success: function (data) { if (data.status === "OK") { $("#numberDocumentUploadedYear").html(data.numberUploadedDocuments); $("#numberDocumentSendDirectYear").html(data.numberDocumentSendDirect); $("#numberRecipientSendDirectYear").html(data.numberRecipientSendDirect); $("#numberDocumentDownloadCreateLinkYear").html(data.numberDocumentDownloadCreateLink); $("#numberOfCreateLinkYear").html(data.numberOfCreateLink); } else { $("#numberDocumentUploadedYear").html(0); $("#numberDocumentSendDirectYear").html(0); $("#numberRecipientSendDirectYear").html(0); $("#numberDocumentDownloadCreateLinkYear").html(0); $("#numberOfCreateLinkYear").html(0); } } }); } // Show password popup function showChangePasswordPopup() { Modal.createModal(2, { title: i18n.t('password.change_password.title'), // Should support multiple langue (i18n.t('modal.change_password_title')) preventClose: true, onLoad: function () { HoGoUtils.validateForm('validationCP', MyAccount); }, templateUrl: "Template/change_password.html", okCallback: function (modal) { // Call submit form var form = modal.find('form'); form.submit(); MyAccount.doChangePassword(); } }); } function showChangeEmailPopup() { Modal.createModal(2, { title: i18n.t('email.change_email.title'), // Should support multiple langue (i18n.t('modal.change_email_title')) preventClose: true, onLoad: function () { HoGoUtils.validateForm('validationCE', MyAccount); }, templateUrl: "Template/change_email.html", okCallback: function (modal) { // Call submit form var form = modal.find('form'); form.submit(); MyAccount.doChangeEmail(); } }); } return { // Form status fStatus: false, /* * Loading data for setting account * This Function will respone data info of current user */ loadingDataSetting: function () { return $.ajax({ type: "POST", url: "api/v1/GetUserInfo", // removed api GetUserInfoHogo dataType: "json", data: {UserID: HoGoUtils.getParameter()["userID"], SessionID: UserSession.getSessionID()}, timeout: HoGoConst.APITimeout, success: function (data) { var detail = data.detail; //Render on view depend on language/country for (var key in detail) { // Language lang = detail[key].lang; // Not set before if (lang === '' || lang === null) { $('#language').val('auto').selectmenu(); } else { var lLang = lang.split('-'); // auto-en var pName = HoGoUtils.getPageName(); if ($.trim(lLang[0]) === 'auto') { $('#language').val('auto').selectmenu(); HoGoUtils.renderNameBaseLang(pName, HoGoUtils.detectBrowserLang()); // lang = lLang[1]; } else { $('#language').val(lang).selectmenu(); HoGoUtils.renderNameBaseLang(pName, lang); } } $('#txtFirstName').val(detail[key].first_name); $('#txtMidtName').val(detail[key].middle_name); $('#txtLastName').val(detail[key].last_name); $('#txtCompany').val(detail[key].company); $('#txtEmail').val(detail[key].e_mail); if (typeof detail[key].user_sender_mail === 'undefined') { if (lang !== 'ja') { $('#txtSenderMail').val(detail[key].first_name + " " + detail[key].last_name); } else { $('#txtSenderMail').val(detail[key].last_name + " " + detail[key].first_name); } } else { $('#txtSenderMail').val(detail[key].user_sender_mail); } // Timezone $('#txtTimeZone').val(detail[key].time_zone).selectmenu(); // Get notify notify = newNotifyInt = detail[key].notification; // On checkbox setCheckedCheckbox(notify); // Set value to model // Set landing page oLandPage = nLandPage = detail[key].landing_page; setLandingPage(detail[key].landing_page); txtFirstName = $.trim($('#txtFirstName').val()); txtMidtName = $.trim($('#txtMidtName').val()); txtLastName = $.trim($('#txtLastName').val()); txtCompany = $.trim($('#txtCompany').val()); txtTimeZone = $.trim($('#txtTimeZone').val()); txtSenderMail = $.trim($('#txtSenderMail').val()); } /* Text change */ $('#txtFirstName, #txtMidtName, #txtLastName, #txtCompany, #txtSenderMail').bind('keyup focusout', (function () { isChangeDetail(); })); } }); }, loadingStatistic: function () { loadingPointsHistory(); loadingStatisticOnMonth(); loadingStatisticOnYear(); }, loadingPointsHistory: function (fnCallback) { loadingPointsHistory(fnCallback); }, /** * Do save user after changing * @returns {undefined} */ doSaveUser: function () { submitSetting(); }, //Submit form doChangePassword: function () { $('form#validationCP').find('.formErrorContent').css('white-space', 'nowrap'); if (!MyAccount.fStatus) { return; } var postData = {}; var newPassword = $('#password').val().trim(); postData["NewPassword"] = HoGoUtils.MD5(newPassword); postData["SessionID"] = s.getSessionID(); //TODO ajax return $.ajax({ type: "POST", url: "api/v1/UpdatePassword", data: postData, beforeSend: function () { Modal.closeModal(); }, success: function (data) { if (data.status === 'OK') { HoGoUtils.makeNotifyServer({ "msg": i18n.t('password.message.save_success'), "autoClose": true, "time": 400 }); //Reset user session Cookie if (data.new_session_id !== "") { var newsessionID = data.new_session_id; s.setSessionID(newsessionID); } } else { fnSessionTimeout(data); } } }); }, //Submit form doChangeEmail: function () { $('form#validationCE').find('.formErrorContent').css('white-space', 'nowrap'); if (!MyAccount.fStatus) { return; } //Collect data for request on services var postData = {}; postData["SessionID"] = s.getSessionID(); postData["OldEmailAddress"] = $('#txtEmail').val(); postData["NewEmailAddress"] = $('#email').val(); var newEmail = $('#email').val(); //Calling services return $.ajax({ type: "POST", url: "api/v1/InitiateEmailAddressChange", data: postData, timeout: HoGoConst.APITimeout, dataType: "json", beforeSend: function () { Modal.closeModal(); }, success: function (data) { var result = data.status; if (result === "OK") { //Set value for template email $("#emailTitle").html(newEmail); $("#emailBody").html(newEmail); var title = i18n.t('email.send_email.we_send_email'); var confirm = i18n.t('email.send_email.confirm'); var click_link = i18n.t('email.send_email.click_link'); var check_email = i18n.t('email.send_email.check_your_email'); //Update dialog popup var htmlEmail = "

    " + title + "

    " + newEmail + "

    " + confirm + "


    " + click_link + "

    " + check_email + "

    "; Modal.showAlert({content: htmlEmail}); //Reset user session Cookie var newsessionID = data.newSessionID; s.setSessionID(newsessionID); } else if (result === APIConst.sessionIdNotFound) { window.location = "login"; } else { Modal.showAlert({content: i18n.t('email.message.exist_email')}); } } }); }, init: function () { // User info this.loadingDataSetting().done(function () { //Drop downlist change $("#txtTimeZone, #language").change(function () { isChangeDetail(); }); //Notification change $('.checkbox').change(function () { newNotifyInt = $('input:checkbox').map(function () { if ($(this).is(':checked')) return '1'; else return '0'; }).get().toString().replace(/\,/g, ''); isChangeDetail(); }); // Landing page select action $('.radio :input[type=radio]').on('click', function () { nLandPage = $(this).val(); isChangeDetail(); }); }); //Change password button Tab $("#btnChangePasswordAccount").live('click', function () { showChangePasswordPopup(); }); $("#btnChangeEmailAccount").on('click', function () { showChangeEmailPopup(); }); $('.btn-cancel-normal-popup').live('click', function () { Modal.closeModal(); }); } }; }(jQuery, UserSession)); // // Manage payement process // var Payment = (function ($) { /* Variables for store orginal value */ var cardNumber, exp_month, exp_year, cvc, FirstName, LastName, Address1, Address2, City, State, ZipCode, Country; /* Check card exist or not */ var cardExist = false; /* Submitting or not */ var submitting = false; /** * Set card format on view base on last 4 number that stripe provide us * @param {string} last4 : 4 last number recieved from stripe * @param {string} typeCard : type of card * @return {string} format card */ function setCardFormat(last4, typeCard) { var refix = null; if (typeCard === "Visa" || typeCard === "MasterCard" || typeCard === "Discover" || typeCard === "American Express" || typeCard === "JCB") refix = "**** **** **** "; else refix = "**** **** *** "; return refix + last4; } /** * Get path return after purchase successfully * @returns {unresolved} */ function getReturnPath() { var hashes = window.location.href.split('returnPath'); var url = hashes[1].substr(1, hashes[1].length); return url; } /** * Reset form & its value after saving * @returns {undefined} */ function resetForm() { // Reset form $('#validationBL').find('input').each(function () { $(this).val(''); }); cardNumber = cvc = FirstName = LastName = Address1 = Address2 = City = ZipCode = ''; $('#validationBL').find('select').each(function () { $(this).prop('selectedIndex', 0); $(this).selectmenu(); }); // Reset exp_month = $("#expdate_month").val(); exp_year = $("#expdate_year").val(); State = $("#state").val(); Country = $("#country").val(); } /** * Check whether card info has been changed or not * @returns {Boolean} */ function isChangeDetail() { if ((cardNumber !== $.trim($('#creditCardNumber').val()) || cvc !== $.trim($('#cvv2Number').val()) || FirstName !== $.trim($('#firstName').val()) || LastName !== $.trim($('#lastName').val()) || Address1 !== $.trim($('#address1').val()) || Address2 !== $.trim($('#address2').val()) || City !== $.trim($('#city').val()) || State !== $.trim($('#state').val()) || ZipCode !== $.trim($('#zip').val()) || exp_month !== $.trim($('#expdate_month').val()) || exp_year !== $.trim($('#expdate_year').val()) || Country !== $.trim($('#country').val()) || State !== $.trim($('#state').val())) && submitting === false) { HoGoUtils.enableButton("#submit", {colorClass: 'green', isSubmitForm: true}); return true; } else { // Always enable button PURCHASE if card is existed if (HoGoUtils.getPageName() === 'paymentinfo.html' && cardExist === true) { // No need to disable return false; } else { HoGoUtils.disableButton("#submit", { colorClass: 'green' }); return false; } } } /** * Do delete card info * @returns {jqXHR} */ function fnDeleteCard() { return $.ajax({ type: "POST", timeout: HoGoConst.APITimeout, url: "api/v1/DeleteCard", dataType: "json", data: {SessionID: UserSession.getSessionID()}, beforeSend: function () { $('
    ').appendTo("#billingContent"); }, success: function (data) { $('#billingContent').find('.hogo-bg-overlay-action').remove(); if (data.status === 'OK') { $('#tblPaymentInfo p').each(function () { $(this).text(""); $('#btnDeleteCard').hide(); }); } else { // Session timeout if (data.status === APIConst.sessionIdNotFound) { window.location.href = 'login'; } else { Modal.showAlert({content: i18n.t('error.unknown')}); } } } }); } /** * Load card info * @returns {jqXHR} */ function loadExistCardInfo() { return $.ajax({ type: "POST", timeout: HoGoConst.APITimeout, url: "api/v1/GetExistCardInfo", dataType: "json", data: {SessionID: UserSession.getSessionID()}, beforeSend: function () { $('#wrapperLoading').show('fast'); }, success: function (data) { $('#wrapperLoading').hide(); if (data.status === 'OK') { if (data.card_info !== null || data.card_info !== "") { //Put data on view var card = data.card_info; $("#card_type").text(card.type); $("#card_number").text(setCardFormat(card.last4, card.type)); $("#exp_date").text(card.expMonth + "/" + card.expYear); $("#fullname").text(card.name); $("#card_address").text(card.addressLine1 + ", " + card.addressCity + ", " + card.addressCountry + ", " + card.addressZip); $("#country1").text(card.addressCountry); // Card exist cardExist = true; // Enable button purchase if (HoGoUtils.getPageName() === 'paymentinfo.html') { HoGoUtils.enableButton("#submit", {colorClass: 'green', isSubmitForm: true}); } else { //For button delete $('#btnDeleteCard').text(i18n.t('payment.buttons.delete_card')).show('fast'); } } } else { $('#tblPaymentInfo p').each(function () { $(this).text(""); }); } } }); } /** * Callback after do create card * @param {type} status * @param {type} response * @returns {undefined} */ function stripeResponseHandler(status, response) { if (response.error) { // Invalid card Modal.showAlert({ title: i18n.t('payment.message.invalid_card.title'), content: i18n.t('payment.message.invalid_card.content') }); $("#validationBL .actionBar>.loader").hide('slow'); HoGoUtils.enableButton("#submit", { colorClass: 'green', isSubmitForm: true, textInside: i18n.t('buttons.save') }); } else { // Reset form resetForm(); // Token contains id, last4, and card type var token = response['id']; // Purchase context if (HoGoUtils.getPageName() === 'paymentinfo.html') { doBuyPoints(token); } else { //Update card info for user submitBilling(token); } } } /** * Do update card * @param {type} token * @returns {undefined} */ function submitBilling(token) { //post data var postDataBilling = {}; postDataBilling["CardToken"] = token; postDataBilling["SessionID"] = UserSession.getSessionID(); //Post to buy points $.ajax({ type: "POST", timeout: HoGoConst.APITimeout, url: "api/v1/UpdateCard", data: postDataBilling, dataType: "json", success: function (data) { $("#validationBL .actionBar>.loader").hide('slow'); if (data.status === 'OK') { loadExistCardInfo(); } else if (data.status === APIConst.sessionIdNotFound) { window.location.href = "login"; } else { HoGoUtils.writeLog(data.status_desc); Modal.showAlert({ontent: i18n.t('error.unknown')}); } }, error: function () { Modal.showAlert({content: i18n.t('error.unknown')}); $("#validationBL .actionBar>.loader").hide('slow'); } }); } /** * Purchase at our API * @param {type} token : Token provided from Stripe * @returns {undefined} */ function doBuyPoints(token) { //post data var postData = {}; postData["CardToken"] = token; postData["SessionID"] = UserSession.getSessionID(); postData["priceId"] = HoGoUtils.getParameter()["PriceId"]; //Post to buy points var req = $.ajax({ type: "POST", timeout: HoGoConst.APITimeout, url: "api/v1/HoGoBuyPoints", data: postData, dataType: "json", beforeSend: function () { $('
    ').appendTo('#purchaseWrapper'); HoGoUtils.disableButton("#submit", { colorClass: 'green', textInside: i18n.t('buttons.status.purchasing') }); $("#validationBL .actionBar>.loader").show('fast'); submitting = true; } }); req.done(function (data) { // Append background overlay $('#purchaseWrapper').find('.hogo-bg-overlay-action').remove(); $("#validationBL .actionBar>.loader").hide('slow'); submitting = false; if (data.status === 'OK') { HoGoUtils.enableButton("#submit", { colorClass: 'green', isSubmitForm: true, textInside: i18n.t('buttons.purchase') }); //Get current points map on view UserSession.updateUserInfo(); //Update card information if there's something changes if (cardExist === false) { loadExistCardInfo(); } Modal.showConfirmPopup({ title: i18n.t('payment.message.purchase_success.title'), content: i18n.t('payment.message.purchase_success.content'), okTitle: i18n.t('buttons.done'), okCallback: function () { window.location.href = getReturnPath(); }, cancelTitle: i18n.t('buttons.back') }); } else { // Session timeout if (data.status === APIConst.sessionIdNotFound) { window.location.href = 'login'; } else { HoGoUtils.disableButton("#submit", { colorClass: 'green', textInside: i18n.t('buttons.status.purchasing') }); // Invalid card Modal.showAlert({ title: i18n.t('payment.message.invalid_card.title'), content: i18n.t('payment.message.invalid_card.content') }); } } }); } //GMO Payment function notifyGMOPayment(obj) { Modal.showConfirmPopup({ title: i18n.t('payment.GMO_payment.title'), content: i18n.t('payment.GMO_payment.message'), okCallback: function () { // var btn_id = $(obj).attr("id"); switch (btn_id) { case "package1": window.location = "GMOPayment?Code=JPP20&SessionID=" + UserSession.getSessionID(); break; case "package2": window.location = "GMOPayment?Code=JPP100&SessionID=" + UserSession.getSessionID(); break; case "package3": window.location = "GMOPayment?Code=JPP300&SessionID=" + UserSession.getSessionID(); } }, cancelCallback: function () { window.location.href = getReturnPath(); } }); } //Paypal iDOC Payment function notifyPaypaliDOCPayment(obj) { Modal.showConfirmPopup({ title: i18n.t('payment.GMO_payment.title'), content: i18n.t('payment.GMO_payment.messagePaypal'), okCallback: function () { var btn_id = $(obj).attr("id"); switch (btn_id) { case "superPackage": window.location = "setExpressCheckout?type=super&location=jp"; break; case "plusPackage": window.location = "setExpressCheckout?type=plus&location=jp"; break; case "basicPackage": window.location = "setExpressCheckout?type=basic&location=jp"; } }, cancelCallback: function () { window.location.href = getReturnPath(); } }); } return { /* Validate form */ fStatus: false, /** * Do creating card by using Stripe js * @returns {undefined} */ submitCreateCardToken: function () { // Check valid form if (!Payment.fStatus) { return false; } $("#validationBL .actionBar>.loader").show('fast'); HoGoUtils.disableButton("#submit", { colorClass: 'green' }); Stripe.setPublishableKey(stripePuplicKey); Stripe.createToken({ number: $("#creditCardNumber").val(), cvc: $("#cvv2Number").val(), exp_month: $("#expdate_month").val(), exp_year: $("#expdate_year").val(), currency: "usd", name: $("#firstName").val() + " " + $("#lastName").val(), address_line1: $("#address1").val(), address_line2: $("#address2").val(), address_city: $("#city").val(), address_zip: $("#zip").val(), address_state: $("#state").val(), address_country: $("#country").val() }, stripeResponseHandler); }, /** * Do purchase for PaymentInfo page context * @returns {Boolean} */ doPurchase: function () { if (cardExist === false) { // Check valid form if (!Payment.fStatus) { return false; } } // If both form & card exist is true. We will purchase with existing card as higher priority // Do purchase if (Payment.fStatus === true) { // Create new card cardExist = false; Payment.submitCreateCardToken(); } else { if (cardExist === true && isChangeDetail() === false) { //Remove all form error $("body").find(".formError").each(function () { $(this).remove(); }); // Using existing card doBuyPoints(''); } } }, convertPaymentTypeToText: function (paymentType) { switch (paymentType) { case 1: return "Paypal"; break; case 2: return "Stripe"; break; case 3: return "GMO Payment"; break; default: return ""; break; } }, init: function () { //Get dropdownlist country and state map with country HoGoUtils.getListCountry('country'); //State HoGoUtils.getListState('state', $('#country').val()); // Do load card loadExistCardInfo().done(function () { // Load done set value for the first time cardNumber = $("#creditCardNumber").val(); exp_month = $("#expdate_month").val(); exp_year = $("#expdate_year").val(); cvc = $("#cvv2Number").val(); FirstName = $("#firstName").val(); LastName = $("#lastName").val(); Address1 = $("#address1").val(); Address2 = $("#address2").val(); City = $("#city").val(); State = $("#state").val(); ZipCode = $("#zip").val(); Country = $("#country").val(); /* Text change */ $('#creditCardNumber, #cvv2Number, #firstName, #lastName, #address1, #address2, #city, #zip').bind('keyup focusout', (function () { isChangeDetail(); })); //Drop expired month change $("#expdate_month, #expdate_year, #state").change(function () { isChangeDetail(); }); // Confirm delete card $('#btnDeleteCard').die('click').live('click', function () { Modal.showConfirmPopup({ title: i18n.t('payment.message.delete_card.title'), content: i18n.t('payment.message.delete_card.content'), okCallback: fnDeleteCard }); }); }); //Validate form HoGoUtils.validateForm('validationBL', Payment); // Selectmenu $('select#state').selectmenu({ style: 'popup', transferClasses: true, width: "100%" }); $('select#country').selectmenu({ style: 'popup', transferClasses: true, width: "100%", select: function (event, options) { if (options.value === 'United States') { //US HoGoUtils.getListState('state', options.value); } else { // Canada HoGoUtils.getListState('state', options.value); } // Refresh $('select#state').selectmenu(); isChangeDetail(); } }); }, loadByPointPage: function () { // update menu and major title var majorTitle = '<%=LanguageManager.getInstance().getText("HG13HoGoPoints", request)%>'; var linkImageTitle = 'Images/menu/Header_HoGoPoint.png'; updateCssMenu_Title("none", linkImageTitle, majorTitle); // update link for response var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1); var redirectLinkpackage1 = "PaymentInfo?PriceId=1&" + hashes; var redirectLinkpackage2 = "PaymentInfo?PriceId=2&" + hashes; var redirectLinkpackage3 = "PaymentInfo?PriceId=3&" + hashes; // console.log("get languate: "+UserSession.getLang()); HoGoUtils.makeIPRequset().done(function (data) { if (data.Country === 'JP') { $("#buyPointImgID").attr("style", "background: #F9F9F9 url(Images/PointBitmapJP.png) no-repeat center center!important;"); //Binding GMO Credit notify $('#package1,#package2,#package3').on('click', function () { notifyGMOPayment(this); }); //Binding paypal iDOC notify $('#superPackage,#plusPackage,#basicPackage').on('click', function () { notifyPaypaliDOCPayment(this); }); $("#buypointButtonTable").attr("style", "margin-left:226px!important;"); } else { //Default Credit card $("#package1").attr("href", redirectLinkpackage1); $("#package2").attr("href", redirectLinkpackage2); $("#package3").attr("href", redirectLinkpackage3); //Default Paypal $("#superPackage").attr("href", "setExpressCheckout?type=super"); $("#plusPackage").attr("href", "setExpressCheckout?type=plus"); $("#basicPackage").attr("href", "setExpressCheckout?type=basic"); } }); if (UserSession.getLang() === 'ja') { $("#package1").attr("style", "font-size:10px!important;"); $("#package2").attr("style", "font-size:10px!important;"); $("#package3").attr("style", "font-size:10px!important;"); $("#buypointButtonTable").attr("style", "width:456px!important;margin-left:222px!important;"); } //Set return page for Paypal payment UserSession.setReturnPaypalURL(hashes.slice(hashes.indexOf('=') + 1)); }, // completedGMOPayment completedGMOPayment: function () { window.location = UserSession.getReturnPaypalURL(); }, // Do submit confirm buy point from paypal doSubmitByPoint: function () { //post data var postData = {}; postData["PayerID"] = HoGoUtils.getParameter()["PayerID"]; postData["token"] = HoGoUtils.getParameter()["token"]; postData["SessionID"] = UserSession.getSessionID(); postData["type"] = HoGoUtils.getParameter()["type"]; postData["location"] = HoGoUtils.getParameter()["location"]; //Post to buy points return $.ajax({ type: "POST", url: "DoExpressCheckout", data: postData, dataType: "json", beforeSend: function () { HoGoUtils.disableButton("#submit", {colorClass: "green"}); $("#validationBL .actionBar>.loader").show('fast'); }, success: function (data) { $("#validationBL .actionBar>.loader").hide('slow'); HoGoUtils.enableButton("#submit", {colorClass: 'green', isSubmitForm: true}); var status = data.status; if (status === "OK") { Modal.showConfirmPopup({ title: i18n.t('payment.message.purchase_success.title'), content: i18n.t('payment.message.purchase_success.content'), okTitle: i18n.t('buttons.done'), cancelTitle: i18n.t('buttons.back'), okCallback: function () { window.location.href = UserSession.getReturnPaypalURL(); }, cancelCallback: function () { window.location.href = UserSession.getReturnPaypalURL(); } }); } else { // Session timeout if (data.status === APIConst.sessionIdNotFound) { window.location.href = 'login'; } else { HoGoUtils.disableButton("#submit", {colorClass: "green"}); /// Notify Modal.showAlert({ title: i18n.t('payment.message.invalid_card.title'), content: i18n.t('payment.message.invalid_card.content') }); } } } }); } }; }(jQuery)); // // Handle tooltips // var ToolTip = (function ($) { var setTip = function (ID, title, type, isWrapContent) { var oTitle = "
    " + title + "
    "; if (typeof type !== 'undefined' && type !== null) { oTitle = "
    " + title + "
    "; } if (typeof type !== 'undefined' && isWrapContent) { oTitle = "
    " + title + "
    "; } $(ID).attr('original-title', oTitle); }; return { init: function () { // set attributes of tooltip with small-tool-tip $('#pointTipsy, #imageTipsy, #imageAffTipsy,#importCsvTipsy, #tooltipExportRecipients, a#securityCodeTipsy').tooltipster({ content: '', animation: 'fade', autoClose: true, interactive: true, position: 'bottom-left', maxWidth: '200', arrow: false, contentAsHTML: true, offsetY: -32 }); // Set content for tooltip $('#pointTipsy').tooltipster('content', i18n.t('header.tooltip.point')); $('#imageTipsy').tooltipster('content', i18n.t('mydocument.tooltip.image_size')); $('#imageAffTipsy').tooltipster('content', i18n.t('affiliate.tooltip.image_size')); $('#importCsvTipsy').tooltipster('content', i18n.t('addressbook.tooltip.csv_format')); $('#tooltipExportRecipients').tooltipster('content', i18n.t('history.package.tooltip.export_recipient')); $('a#securityCodeTipsy').tooltipster('content', i18n.t('myaccount.account_billing.tooltip.security_code')); }, wizardTooltip: function () { // Step 3 // Specify recipient block setTip('#specifyRecTipsy', i18n.t('send_wizard.step_3.blocks.specify_recipient.tooltips.t1')); // Download part setTip('#downloadTipsy', i18n.t('send_wizard.step_3.blocks.download.tooltips.t1'), null, true); $('#mailAddressTipsy,#expiryDateTipsy,#expiryDocumentTipsy,#numberCopyTipsy,#passwordTipsy,#localCopyTipsy,#folderTipsy,#numberCopyTipsy').tooltipster({ content: '', animation: 'fade', autoClose: true, interactive: true, position: 'bottom-right', maxWidth: '350', arrow: false, contentAsHTML: true, offsetY: -40 }); $('#mailAddressTipsy').tooltipster('content', i18n.t('send_wizard.step_3.blocks.specify_recipient.tooltips.t2')); $('#expiryDateTipsy').tooltipster('content', i18n.t('send_wizard.step_3.blocks.link_expiry.tooltips.t1')); //$('#downloadTipsy').tooltipster('content', i18n.t('send_wizard.step_3.blocks.download.tooltips.t1')); $('#expiryDocumentTipsy').tooltipster('content', i18n.t('send_wizard.step_3.blocks.download.tooltips.t2')); $('#passwordTipsy').tooltipster('content', i18n.t('send_wizard.step_3.blocks.password.tooltips.t1')); $('#localCopyTipsy').tooltipster('content', i18n.t('send_wizard.step_3.blocks.local_copies.tooltips.t1')); $('#numberCopyTipsy').tooltipster('content', i18n.t('send_wizard.step_3.blocks.local_copies.tooltips.t2')); $('#folderTipsy').tooltipster('content', i18n.t('send_wizard.step_3.blocks.folder.tooltips.t1')); // Step 4 // set attributes of tooltip with medium-tool-tip $('a#mailAddressStep4TipAnonymous, a#mailAddressStep4TipSpecify').tooltipster({ content: '', animation: 'fade', autoClose: true, interactive: true, position: 'bottom-left', maxWidth: '200', arrow: false, contentAsHTML: true, offsetY: -40 }); $('a#mailAddressStep4TipSpecify').tooltipster('content', i18n.t('send_wizard.step_4.blocks.send_email.tooltips.t1')); $('a#mailAddressStep4TipAnonymous').tooltipster('content', i18n.t('send_wizard.step_4.blocks.send_email.tooltips.t2')); } }; }(jQuery)); // // Manage notification // var Notification = (function ($) { //var init = false; /* This class using only for NotificationInbox page. */ var MessageList = { messageList: [], currentItem: 0, urgentItem: 0, normalItem: 0, urgentItemUnread: 0, normalItemUnread: 0, fnComplete: null, fnCompleteUpdateStatus: null, isLoaded: false, //Get message from Server getListMessage: function (sessionID) { return $.ajax({ type: "POST", timeout: HoGoConst.APITimeout, url: "api/v1/GetListMessage", //async: false, data: {'SessionID': sessionID}, dataType: "json", success: function (data) { if (data.status === "OK") { //Push data here $.each(data.list_notification, function (k, v) { if (v.type !== 600) MessageList.messageList.push({"messageID": v.messageID, "title": v.title, "body": v.body, "type": v.type, "status": v.status, "createDate": v.createDate}); if (v.status === HoGoConst.MESSAGE_UNREAD_TYPE) { if (v.type === HoGoConst.ADMIN_SENT_MESSAGE_TYPE) { MessageList.urgentItemUnread++; } else { MessageList.normalItemUnread++; } } }); } }, complete: function () { MessageList.isLoaded = true; //DO any method is set onComplete if (MessageList.fnComplete !== null) MessageList.fnComplete(); } }); }, resetList: function () { MessageList.currentItem = 0; MessageList.urgentItemUnread = 0; MessageList.normalItemUnread = 0; MessageList.isLoaded = false; MessageList.fnComplete = null; MessageList.fnCompleteUpdateStatus = null; MessageList.messageList.splice(0, MessageList.messageList.length); }, size: function () { return MessageList.messageList.length; }, get: function (i) { return MessageList.messageList[i]; }, next: function () { //console.log(MessageList.currentItem); var item = null; if (MessageList.currentItem <= MessageList.size() - 1) { MessageList.currentItem++; item = MessageList.get(MessageList.currentItem); } return item; }, previous: function () { //console.log(MessageList.currentItem); var item = null; if (MessageList.currentItem >= 1) { MessageList.currentItem--; item = MessageList.get(MessageList.currentItem); } return item; }, getCurrentItem: function () { return MessageList.get(MessageList.currentItem); }, updateRead: function (i, sessionID) { //Get message ID var obj = MessageList.get(i); //Update $.ajax({ type: "POST", timeout: HoGoConst.APITimeout, url: "api/v1/UpdateStatusMessage", data: {'SessionID': sessionID, 'MessageID': obj.messageID, 'MessageCode': obj.type}, dataType: "json", success: function (data) { if (data.status === "OK") { //Push data here obj.status = HoGoConst.MESSAGE_READ_TYPE; //Read //console.log("Updated"); } else { //console.log("Update failed"); } }, error: function () { }, complete: function () { if (MessageList.fnCompleteUpdateStatus !== null) MessageList.fnCompleteUpdateStatus(); } }); }, onComplete: function (_fnOnComplete) { MessageList.fnComplete = _fnOnComplete; }, onCompleteUpdateStatus: function (_fnOnCompleteUpdate) { MessageList.fnCompleteUpdateStatus = _fnOnCompleteUpdate; } }; /** * Show inbox popup */ function showNotificationPopup() { //Draw on view if (MessageList.size() > 0) { //Show popup $('#notifyContainer').remove(); // Create var inbox = '
    ' + '
    ' + '' + '
    ' + '' + '
    ' + '
    ' + '' + '' + '
    ' + '' + '' + '
    ' + '
    '; $('body').append(inbox); // Translate $('#notifyContainer').i18n(); $('#notifyContainer').reveal({closeonbackgroundclick: false}); // Render content drawMessageOnView(MessageList.getCurrentItem()); Notification.init(); } else { Modal.showAlert({ title: i18n.t('notification.message.no_message.title'), content: i18n.t('notification.message.no_message.content') }); } } /** * Update notifcation while loading page */ function updateNotification() { //Get message MessageList.getListMessage(UserSession.getSessionID()); MessageList.onComplete(showNotifcationStatus); } function showNaviButton() { //Previous button if (MessageList.currentItem === 0) { $('#btnNIPrevious').removeClass('ws_prev'); } else { $('#btnNIPrevious').addClass('ws_prev'); } //Next button if (MessageList.currentItem === MessageList.size() - 1) { $('#btnNINext').removeClass('ws_next'); } else { $('#btnNINext').addClass('ws_next'); } } /** * Draw message info on View * @param message : Message obj */ function drawMessageOnView(message) { $("#bodyNI").mCustomScrollbar("destroy"); var value = message; showNaviButton(); if (value.status === HoGoConst.MESSAGE_UNREAD_TYPE) { MessageList.updateRead(MessageList.currentItem, UserSession.getSessionID()); } if (value !== null) { if (value.type === HoGoConst.ADMIN_SENT_MESSAGE_TYPE) { //Unread if (value.status === HoGoConst.MESSAGE_UNREAD_TYPE) { $('#titleNI').html("" + value.title + ""); } else { $('#titleNI').html(value.title); } $('#bodyNI').html(value.body); $('#createDateNI').html(value.createDate); } else { if (value.status === HoGoConst.MESSAGE_UNREAD_TYPE) { var s = i18n.t('notification.title1'); $('#titleNI').html("" + s + ""); } else { $('#titleNI').html(i18n.t('notification.title1')); } var message = getNotficaionByCode(value.type); //Set message $('#bodyNI').html(message); $('#createDateNI').html(value.createDate); } $('#pageNumber').html((MessageList.currentItem + 1) + '/' + MessageList.size()); $("#bodyNI").mCustomScrollbar(); } } /** * Showing notfication on view */ function showNotifcationStatus() { if (MessageList.urgentItemUnread > 0) { $('#urgentNotify').show(); $('#normalNotify').hide(); $('#noNotify').hide(); } else { //Hide $('#urgentNotify').hide(); $('#noNotify').hide(); //Show normal $('#normalNotify').show(); if (MessageList.normalItemUnread > 0) { // } else { // No new notification $('#noNotify').show(); $('#normalNotify').hide(); $('#urgentNotify').hide(); } } } /** * Get message map with mCode * @param {string} mCode : The message code * @return message */ function getNotficaionByCode(mCode) { var message = ""; switch (mCode) { case 600: message = i18n.t('notification.list.out_of_point'); break; case 401: message = i18n.t('notification.list.user_updated'); break; case 602: message = i18n.t('notification.list.document_downloaded'); break; case 604: message = i18n.t('notification.list.link_expired'); break; case 605: message = i18n.t('notification.list.reach_max_download'); break; case 601: message = i18n.t('notification.list.document_viewed_online'); break; case 603: message = i18n.t('notification.list.document_expried'); break; default: break; } return message; } return { init: function () { // Get notfication MessageList.resetList(); updateNotification(); $('#btnNINext').unbind('click').on('click', function () { drawMessageOnView(MessageList.next()); }); $('#btnNIPrevious').unbind('click').bind('click', function () { drawMessageOnView(MessageList.previous()); }); //Notification window popup event $('#urgentNotify,#normalNotify,#noNotify').unbind('click').bind('click', function () { //Check Message has loaded before or not if (!MessageList.isLoaded) { //Refresh notifcation box MessageList.getListMessage(UserSession.getSessionID()); //Show MessageList.onComplete(showNotificationPopup); } else { showNotificationPopup(); } }); $('#closeNotification').on('click', function () { //Clear list MessageList.resetList(); //Update new updateNotification(); }); } }; }(jQuery)); // // Manage all user // var User = (function ($) { //Checklist contains UserID for checkbox event var checkedList = []; //Using for user list var oTable, pTable; //Using for import list var oTable1; // Error list var errorRows = []; //User model var fName = "", mName = "", lName = "", email = "", company = "", serviceId, syncWithBox; // Allow redirect or not var redirectable = false; //Init start/stop date var startDate = convertFromDateObject(new Date(0)) + ' 00:00:00'; var stopDate = convertFromDateObject(new Date()) + ' 23:59:59'; var userDetail = {}; /** * Check model property has changed or not * @returns {Boolean} */ function hasChanged() { if ($.trim(fName) !== $.trim($('#firstname').val()) || $.trim(mName) !== $.trim($('#middlename').val()) || $.trim(lName) !== $.trim($('#lastname').val()) || $.trim(company) !== $.trim($('#company').val()) || $.trim(email) !== $.trim($('#email').val()) || ((!syncWithBox) === $('#syncBox :checkbox').is(':checked'))) { HoGoUtils.enableButton('#btnSave', {colorClass: 'green', isSubmitForm: true, formID: 'validation'}); return true; } else { HoGoUtils.disableButton('#btnSave', {colorClass: 'green'}); return false; } } // Create json button will be disable and enable var lEnableButton = {'list_button': []}; lEnableButton.list_button.push({'id': "btnSendMessage", 'color': 'orange', 'submit': false, 'handler': fnSendMessage, "form_id": null}); lEnableButton.list_button.push({'id': "btnDelete", 'color': 'orange', 'submit': false, 'handler': fnWarningDeleteUser, "form_id": null}); lEnableButton.list_button.push({'id': "btnExport", 'color': 'orange', 'submit': false, 'handler': fnExport, "form_id": null}); var lDisableButton = {'list_button': []}; lDisableButton.list_button.push({'id': "btnSendMessage", 'color': 'orange', 'handler': fnSendMessage}); lDisableButton.list_button.push({'id': "btnDelete", 'color': 'orange', 'handler': fnWarningDeleteUser}); lDisableButton.list_button.push({'id': "btnExport", 'color': 'orange', 'handler': fnExport}); // Contain information selected user var SelectedUserList = { Userlist: [], push: function (id, name, name_id) { var isExist = false; $.each(SelectedUserList.Userlist, function (index, value) { if (value.ID === id) isExist = true; }); if (!isExist) SelectedUserList.Userlist.push({'ID': id, 'full_name': name, 'name_id': name_id}); }, remove: function (id) { for (var index = 0; index < SelectedUserList.Userlist.length; index++) { if (SelectedUserList.Userlist[index].ID === id) SelectedUserList.Userlist.splice(index, 1); //Remove } }, removeAll: function () { SelectedUserList.Userlist.splice(0, SelectedUserList.Userlist.length); }, getUserList: function () { return SelectedUserList.Userlist; } }; /** * Make array post data to get user list * @param {type} aoData * @param {type} filter * @param {type} startDate * @param {type} stopDate * @returns parameters json */ function makeListParam(aoData, filter, startDate, stopDate) { var post = {}; var colSort; var sortType; $.each(aoData, function (x, y) { if (y.name === "sEcho") { post["sEcho"] = y.value; } if (y.name === "iDisplayStart") { post["DisplayStart"] = y.value; } if (y.name === "iDisplayLength") { post["DisplayLength"] = y.value; } if (y.name === "sSearch") { post["SearchString"] = $.trim(y.value); } if (y.name === "iSortCol_0") { colSort = y.value; } if (y.name === "sSortDir_0") { sortType = y.value; } }); switch (colSort) { case 1: if (sortType === "asc") post["SortType"] = 1; else post["SortType"] = 2; break; case 2: if (sortType === "asc") post["SortType"] = 3; else post["SortType"] = 4; break; case 3: if (sortType === "asc") post["SortType"] = 5; else post["SortType"] = 6; break; case 4: if (sortType === "asc") post["SortType"] = 7; else post["SortType"] = 8; break; case 5: if (sortType === "asc") post["SortType"] = 9; else post["SortType"] = 10; break; } if (typeof filter !== 'undefined') { post["HistoryType"] = filter.h_code; post["StartDate"] = filter.s_date; post["StopDate"] = filter.e_date; // Payment type if (filter.payment_type !== "") post["PaymentType"] = filter.payment_type; } else { post["StartDate"] = startDate; post["StopDate"] = stopDate; } // Using for affiliate detail if (HoGoUtils.getPageName() === 'affiliatedetail.html') { post["AffiliateID"] = HoGoUtils.getParameter()['affiliateID']; } if (HoGoUtils.getPageName() === 'companydetail.html') { post["CompanyID"] = HoGoUtils.getParameter()['companyID']; } post["SessionID"] = UserSession.getSessionID(); return post; } /** * Load user list * @param {json} filter : filter options * @returns {undefined} */ function loadUserList(filter) { // console.log(UserSession.getAdminLang()); var adminLang = UserSession.getAdminLang(); var parentId = HoGoUtils.getParameter()['parentId']; var self = HoGoUtils.getParameter()['self']; var url = 'UserDetail?userID=%uid'; if (typeof parentId !== 'undefined' && parentId !== '') { url += '&parentId=' + parentId; } if (typeof self !== 'undefined' && self !== '') { url += '&self=' + self; } oTable = $("#tablepaging").dataTable({ "aaSorting": [[4, 'desc']], "bInfo": false, // "bLengthChange": true, "aLengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, i18n.t('company.list.all')] ], "bPaginate": true, "iDisplayLength": 10, "sPaginationType": "full_numbers", "bDestroy": true, "oLanguage": DTUtils.DTLang, "sDom": '<"inline relative"<"right search-absolute"f>><"inline"<"right"p><"left"l>>itr', "sAjaxSource": "api/v1/GetListUserDetail", "bServerSide": true, "bProcessing": true, "fnServerData": function (sSource, aoData, fnCallback, oSettings) { $.ajax({ url: sSource, type: "POST", dataType: "json", data: makeListParam(aoData, filter, startDate, stopDate), timeout: HoGoConst.APITimeout, success: function (data) { if (data.status === "OK") { var json = {"sEcho": data.sEcho, "iTotalDisplayRecords": data.totalResult, "aaData": []}; $.each(data.user_detail, function (key, value) { var name = ""; if (value.middleName === null || typeof value.middleName === 'undefined') { name = (adminLang === "ja") ? value.lastName + " " + value.firstName : value.firstName + " " + value.lastName; } else { name = (adminLang === "ja") ? value.lastName + " " + value.firstName : value.firstName + " " + value.middleName + " " + value.lastName; } var company = (value.company === undefined) ? "" : value.company; json.aaData.push({"id": value.id.userId, "name": name, "email": value.mailAddress, "company": company, "create_date": value.signupDate, "status": value.status}); }); } else { fnSessionTimeout(data, null, "UserList"); } fnCallback(json); } }); }, "fnRowCallback": function (nRow, aData) { $("td:eq(0)", nRow).html(""); $("td:eq(1)", nRow).html("
    " + aData.name + "
    "); $("td:eq(2)", nRow).html("
    " + aData.email + "
    "); $("td:eq(3)", nRow).html("
    " + aData.company + "
    "); $("td:eq(4)", nRow).html(DateUtils.convertDate(aData.create_date)); //It's fake data on view var _url = url.replace('%uid', aData.id); $("td:eq(5)", nRow).html(""); nRow.ondblclick = function () { window.location.href = _url; }; nRow.onclick = function () { DTUtils.fnCheckBoxOnRow(this); }; }, "aoColumnDefs": [ {'bSortable': false, 'aTargets': [0, 5]} //Not sort for col 0,5 ], "bStateSave": true, "fnStateLoad": function (oSettings) { //Only from RecipientDetail. Load previous state if ($.cookie('l_p') === 'userdetail.html') { var sData = this.oApi._fnReadCookie(oSettings.sCookiePrefix + oSettings.sInstance); var oData; try { oData = (typeof $.parseJSON === 'function') ? $.parseJSON(sData) : eval('(' + sData + ')'); } catch (e) { oData = null; } //Set search word on field if (oData !== null) if (oData.oSearch.sSearch !== null) $('#filter').val(oData.oSearch.sSearch); else $('#filter').val(''); else { //set search null $('#filter').val(''); } return oData; } else { return null; } }, "fnDrawCallback": function (oSettings) { // Setup control // DTUtils.fnSetUpTableControl(oSettings); //Draw checkbox $('#tablepaging .ck').customInput(); //Set up sort paginate // DTUtils.fnSetUpTableControl(oSettings); //Clear checklist when sorting if (oSettings.bSorted) { //Clear checklist checkedList.splice(0, checkedList.length); //Clear send list SelectedUserList.removeAll(); //Disable button DTUtils.fnDisableControl(lDisableButton); } //Checkbox event switching page DTUtils.checkboxSwitchPage("tablepaging", "child", "select_all", checkedList); //Event click child checkbox $(':checkbox[name=child]').on('click', function () { //Update checkedList DTUtils.checkboxChildSelectEvent(this, "select_all", checkedList); //Insert to user list (Using for send message) var full_name = $("#" + this.id).closest('tr').find('div.full-name').text(); if ($(this).prop('checked')) { SelectedUserList.push(this.id, full_name, full_name.toLowerCase().replace(/ /g, '')); } else { SelectedUserList.remove(this.id); } //Enable/Disable button if (checkedList.length > 0) { //Enable these buttons DTUtils.fnEnableControl(lEnableButton); } else { //Disable DTUtils.fnDisableControl(lDisableButton); } }); }, //Map properties from json to view sequentially "aoColumns": [ {"mDataProp": "id"}, {"mDataProp": "name"}, {"mDataProp": "email"}, {"mDataProp": "company"}, {"mDataProp": "create_date"}, {"mDataProp": "status"} ], "fnInitComplete": function (s) { $('#' + s.sTableId).i18n(); $('#' + s.sTableId + '_length').find('select').selectmenu(); } }); } /** * Show confirm delete user * @returns {Boolean} */ function fnWarningDeleteUser() { if (checkedList.length === 0) { return false; } else { Modal.showConfirmPopup({ title: i18n.t('user.message.confirm_delete.title'), content: i18n.t('user.message.confirm_delete.content'), okCallback: function () { fnDeleteUser(checkedList.toString()); } }); return false; } } /** * Do delete user * @param {type} ID * @returns {Boolean} */ function fnDeleteUser(ID) { //Call API $.ajax({ url: "api/v1/DeleteServiceUser", dataType: "json", type: "POST", data: {UserIDs: ID, SessionID: UserSession.getSessionID()}, beforeSend: function () { $('
    ').appendTo('#content'); }, success: function (data) { $('.hogo-bg-overlay-action').remove(); if (data.status === "OK") { //Draw again oTable.fnDraw(); //Splice list checkedList.splice(0, checkedList.length); } else { Modal.showAlert({title: i18n.t('error.unknown')}); } }, error: function () { Modal.showAlert({title: i18n.t('error.unknown')}); } }); } /** * Do send message * @returns {undefined} */ function fnSendMessage() { if (checkedList.length > 0) { $('#inbox-popup').remove(); var boxpanel = ''; // $.get("SendMessagePopup", function(data) { // Display $('body').append(boxpanel); var inbox = $('#inbox-popup'); inbox.i18n(); inbox.reveal({closeonbackgroundclick: false}); // Append list to field name var listUser = SelectedUserList.getUserList(); $("#emailTags").tagit(); $('ul#emailTags li input').attr('disabled', true); for (var index = 0; index < listUser.length; index++) { var v = listUser[index]; // var u = "" + v.full_name + ""; // $('#field-name').append(u); $("#emailTags").tagit("createTag", v.ID, v.full_name); } // Bind event inbox.find('#btn-send-msg').bind('click', function () { var form = $(this).parents('form'); form.submit(); }); // Validation form HoGoUtils.validateForm('validationSM'); // }); } } //replace special character to html character function htmlEscape(str) { return String(str) .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, ''') .replace(//g, '>'); } /** * Do export user * @returns {undefined} */ function fnExport() { //Check all as default when loading $('#export-user-popup :checkbox').prop("checked", true); $('#export-user-popup :checkbox').each(function () { $('label[for=' + $(this).attr("id") + ']').addClass("checked"); }); //Check whether selected or not if (checkedList === 0) { HoGoUtils.disableButton('#btn-export-csv', {colorClass: 'green'}); } else { HoGoUtils.enableButton('#btn-export-csv', {colorClass: 'green', isSubmitForm: true}); showExportUserPopup(); } } /** * Show export popup */ function showExportUserPopup() { $('#export-user-popup').reveal({closeonbackgroundclick: false}); // Make sure unique ID $('#export-user-popup').remove(); var boxpanel = '
    ' + '
    ' + '' + '
    ' + '' + '
    ' + '' + '
    ' + '
    ' + '' + '
    ' + '' + '
    ' + '' + '
    ' + '' + '
    ' + '' + '
    ' + '
    ' + '
    ' + '' + '
    ' + '
    ' + '
    ' + '
    '; // $boxpanel.get("ExportUserPopup", function(data) { $('body').append(boxpanel); var m = $('#export-user-popup'); m.i18n(); m.reveal(); m.find('.ck').prop('checked', true).customInput('udpateState'); // Event click opts Export modal $("#export-user-popup :checkbox").bind("click", function () { var m = $("#export-user-popup"); if (m.find(":checkbox:checked").length === 0) { HoGoUtils.disableButton('#btn-export-csv', { colorClass: 'green' }); } else { HoGoUtils.enableButton('#btn-export-csv', { colorClass: 'green', handler: _doSendRequestExport }); } }); // do init handler for export button HoGoUtils.enableButton('#btn-export-csv', { colorClass: 'green', handler: _doSendRequestExport }); } // just use to export company list by reseller function _doSendRequestExport() { User.exportUser(); var form = $(this).parents('form'); var param = form.serialize(); param += "&CurrentLang=" + i18n.lng(); $.fileDownload('api/v1/ExportServiceUserList?' + param, { httpMethod: 'post' }); } function print(array, numBreak) { var str = ''; for (var i = 0; i < array.length; i++) { if ((i + 1) % numBreak === 0) { ; str += array[i] + '
    '; } else { str += array[i] + ', '; } } return str; } // Import user function doImport() { // console.log("iimport csv"); var setting = oTable1.fnSettings(); HoGoUtils.disableButton('#btn-save-csv', {colorClass: 'green', textInside: 'IMPORTING'}); var data = {}; var listObj = []; $.each(setting.aiDisplay, function (k, v) { var obj = {}; // setting.aoData[v]._aData obj.first_name = setting.aoData[v]._aData.first_name; obj.middle_name = setting.aoData[v]._aData.middle_name; obj.last_name = setting.aoData[v]._aData.last_name; obj.email = setting.aoData[v]._aData.email; obj.company = setting.aoData[v]._aData.company; obj.password = HoGoUtils.MD5(setting.aoData[v]._aData.password); listObj.push(obj); }); var total = setting.aiDisplay.length; data["ListUser"] = JSON.stringify(listObj); data["SessionID"] = UserSession.getSessionID(); Modal.closeModal(); //Adding $.ajax({ dataType: 'json', type: "POST", url: "api/v1/AddServiceUsers", data: data, timeout: HoGoConst.APITimeout, beforeSend: function () { $('#import-popup, .reveal-modal-bg ').remove(); appendLoadingWithText("iAddingRecipient", "body", i18n.t('loader.add'), true); }, success: function (dt) { removeLoading("iAddingRecipient"); if (dt.status === "OK") { if (oTable1) { // Destroy table oTable1.fnClearTable(); if (dt.list_exist_user.length > 0 || dt.list_fail_import_user.length > 0) { var totalFail = dt.list_exist_user.length + dt.list_fail_import_user.length; Modal.showAlert({ title: i18n.t('addressbook.message.import_fail.title'), content: "
    " + "
    " + "" // lang + "
    " + "
    " + "" + total + "" + "
    " + "
    " + "
    " + "
    " + "" // lang + "
    " + "
    " + "" + totalFail + "" + "
    " + "
    " + "
    " + "
    " + "" // lang + "
    " + "
    " + "" + print(dt.list_exist_user, 3) + "" + "
    " + "
    " + "
    " + "
    " + "" // lang + "
    " + "
    " + "" + print(dt.list_fail_import_user, 3) + "" + "
    " + "
    " }); // i18n.t('user.message.exist_user') } // else if (dt.list_fail_import_user.length !== 0) { // Modal.showAlert({content: i18n.t('company_recipient.message.import_fail')}); // } else { HoGoUtils.makeNotifyServer({ "msg": i18n.t('company_recipient.message.import_sucess'), "autoClose": true, "time": 2000 }); } oTable.fnDraw(); } } else { console.log(dt.status_desc); if (dt.status_desc === "This email already existed") { Modal.showAlert({ title: i18n.t('company_recipient.message.exist_email.title'), content: i18n.t('company_recipient.message.exist_email.content') }); } else if (dt.status_desc === "Can't add user because your account is limit user") { Modal.showAlert({content: i18n.t('user.message.limit_user')}); } else { Modal.showAlert({title: 'Invalid Format', content: i18n.t('user.message.wrong_format')}); } } } }); } /** * Do count to know all record whether save or not * @param {type} v Current saved record * @returns {undefined} */ // function doCount(v) { // // // Save done // if (oTable1) { // // if (v === oTable1.fnSettings().aiDisplay.length) { // // // Destroy table // oTable1.fnClearTable(); // // Modal.closeModal(); // // if (errorRows.length > 0) { // // Modal.showAlert({title: "Duplicate User", content: i18n.t('user.message.exist_user') + errorRows.toString()}); // // //Clear error rows // errorRows = []; // // oTable.fnDraw(); // } else { // oTable.fnDraw(); // } // } // } // } /** * Create table manage import CSV file * @returns {undefined} */ var maxCurrentUser = {}; function importCSV() { // console.log("importcsv"); var adminLang = UserSession.getAdminLang(); //Init table import oTable1 = $('#tbl-import-user').dataTable({ "aaSorting": [[0, 'desc']], "bInfo": false, "bLengthChange": false, "bPaginate": true, "bDestroy": true, "iDisplayLength": 10, "sPaginationType": "full_numbers", "oLanguage": DTUtils.DTLang, "sDom": 'l<"clearfix"<"left"f><"right"p>>irt', "sAjaxSource": 'api/v1/ImportUser', "fnServerData": function (sSource, aoData, fnCallback, oSettings) { var json = {"aaData": []}; $.ajaxFileUpload({ url: sSource, secureuri: false, fileElementId: "file", data: {SessionID: UserSession.getSessionID()}, dataType: 'json', success: function (data) { if (data.status === "OK") { console.log(data); maxCurrentUser = { maxUser: data.max_user, currentUser: data.user_current }; console.log("here2"); var detail = data.list; console.log(detail); for (var i = 0; i < detail.length; i++) { var company = ""; if (detail[i].company !== undefined) { company = detail[i].company; } var name = ""; if (detail[i].middle_name !== undefined) { name = (adminLang === "ja") ? detail[i].last_name + " " + detail[i].middle_name + " " + detail[i].first_name : detail[i].first_name + " " + detail[i].middle_name + " " + detail[i].last_name; } else { name = (adminLang === "ja") ? detail[i].last_name + " " + detail[i].first_name : detail[i].first_name + " " + detail[i].last_name; } // json.aaData.push({"first_name": detail[i].first_name, "middle_name": detail[i].middle_name, "last_name": detail[i].last_name, "password": detail[i].password, "email": detail[i]['e-mail'], "company": company}); json.aaData.push({"id": i, "name": name, "first_name": detail[i].first_name, "middle_name": detail[i].middle_name, "last_name": detail[i].last_name, "password": detail[i].password, "email": detail[i]['e-mail'], "company": company}); } } else { if (data.status === APIConst.adminSessionRequired) { window.location.href = 'login'; } else { Modal.showAlert({title: 'Invalid Format', content: i18n.t('user.message.wrong_format')}); $("#import-popup").remove(); } } fnCallback(json); }, error: function () { window.location.href = 'login'; } }); }, "fnRowCallback": function (nRow, aData) { $("td:eq(0)", nRow).html(""); // var name = ""; // // if (aData.middle_name !== undefined) // name = (adminLang === "ja") ? aData.last_name + " " + aData.middle_name + " " + aData.first_name : aData.first_name + " " + aData.middle_name + " " + aData.last_name; // else // name = (adminLang === "ja") ? aData.last_name + " " + aData.first_name : aData.first_name + " " + aData.last_name; //Name field $("td:eq(1)", nRow).html("
    " + aData.name + "
    "); //Password field $("td:eq(2)", nRow).html("
    "); //nRow.setAttribute("style", "text-align: left"); $("td:eq(3)", nRow).html("
    " + aData.email + "
    "); //$("td:eq(4)", nRow).html("
    " + aData.company + "
    "); }, "aoColumnDefs": [ {'bSortable': false, 'aTargets': [0, 2]} ], "fnDrawCallback": function (oSettings) { //Setting up control // DTUtils.fnSetUpTableControl(oSettings); var currentUser = oSettings.aiDisplay.length + maxCurrentUser.currentUser; if (oSettings.fnRecordsDisplay().length > 0 || currentUser > maxCurrentUser.maxUser) { if (currentUser > maxCurrentUser.maxUser) { $('#alertWarning').show().html(i18n.t('addressbook.message.import_fail.larger_user') + currentUser + i18n.t('addressbook.message.import_fail.pack_user') + maxCurrentUser.maxUser + ' '); } HoGoUtils.disableButton('#btn-save-csv', {colorClass: 'green'}); } else { $('#alertWarning').hide(); HoGoUtils.enableButton('#btn-save-csv', { colorClass: 'green', handler: doImport, textInside: i18n.t('buttons.save') }); } }, "aoColumns": [ {"mDataProp": "id"}, {"mDataProp": "name"}, {"mDataProp": "password"}, {"mDataProp": "email"}, //{"mDataProp": "company"} ], "fnInitComplete": function (setting) { if (setting.aoData.length === 0) { console.log("here"); Modal.showAlert({title: i18n.t('user.message.invalid_data_title'), content: i18n.t('user.message.no_valid_data')}); } else { $("#import-popup .modal-control").css('display', 'block'); $('#import-popup').reveal({"closeonbackgroundclick": false}); } } }); //Clear file $("#file").replaceWith($("#file").val('').clone(true)); } var UserDetail = { /* Get parameter */ userID: HoGoUtils.getParameter()["userID"], /* Transaction ID using for refunding */ transID: null, cP: null, createDate: null, amount: 0, reason: "", /** * Get user detail * @returns {jqXHR} */ getUserDetail: function () { return $.ajax({ dataType: 'json', type: "POST", url: "api/v1/GetUserInfo", data: {UserID: UserDetail.userID, SessionID: UserSession.getSessionID()}, timeout: HoGoConst.APITimeout, success: function (dt) { userDetail = dt.detail; if (dt.status === "OK") { $.each(dt.detail, function (key, value) { if (value.status === HoGoConst.ACTIVE_STATUS || HoGoConst.INACTIVE_STATUS) { serviceId = value.service_id; // var userLang = value.lang; // var lLang = userLang.split('-'); // auto-en // var pName = HoGoUtils.getPageName(); // if ($.trim(lLang[0]) === 'auto') { // HoGoUtils.renderNameBaseLang(pName, HoGoUtils.detectBrowserLang()); // } else { // HoGoUtils.renderNameBaseLang(pName, userLang); // } // Set model & view $("#firstname").val(fName = value.first_name); $("#middlename").val(mName = value.middle_name); $("#lastname").val(lName = value.last_name); $("#company").val(company = value.company); $("#email").val(email = value["e_mail"]); var pointBalance = parseInt(value.points) + parseInt(value.points_free); $("#point-balance").text(pointBalance + ' ' + i18n.t('session.label.points')); if (new Date(value.last_login).getFullYear() === "1969" || new Date(value.last_login).getFullYear() === "1970") { $("#last-login").text("N/A"); } else { $("#last-login").text(DateUtils.convertDate(value.last_login)); } $("#registered-date").text(DateUtils.convertDate(value.signup_date)); // Point tooltip $('#detailBalancePoint').tooltipster({ content: '', animation: 'fade', interactive: true, contentAsHTML: true, functionInit: function (origin) { var content = '
    • ' + i18n.t('user.form.point_free') + ' : ' + value.points_free + '
    • ' + i18n.t('user.form.purchased_point') + ' : ' + value.points + '
    '; return $(content); } }); // sync with box syncWithBox = (value.sync_with_box === 1) ? true : false; $('#syncBox :checkbox').prop('checked', syncWithBox); } else { Modal.showAlert({content: i18n.t('error.unknown')}); } }); } else { Modal.showAlert({content: i18n.t('error.unknown')}); } } }); }, /** * Update user info * @returns {Boolean|jqXHR} */ updateUser: function () { if (!formStatus) { return false; } var postData = {}; postData["UserID"] = this.userID; postData["SessionID"] = UserSession.getSessionID(); $('form').find(':input').each(function () { postData[$(this).attr('name')] = $(this).val().trim(); }); postData["SyncBox"] = $('#syncBox :checkbox').is(':checked'); postData['Lang'] = HoGoUtils.detectBrowserAutoLang(postData['Lang']); // Call API return $.ajax({ type: "POST", url: "api/v1/UpdateUserInfo", data: postData, dataType: "json", beforeSend: function () { //Disable btn save HoGoUtils.disableButton('#btnSave', {colorClass: 'green'}); //Display loader $(".actionBar>.loader").show('fast'); }, success: function (data) { //Remove load $(".actionBar>.loader").hide('slow'); if (data.status === "OK") { UserDetail.getUserDetail(); } else { fnSessionTimeout(data, null, "UserList"); } } }); }, /** * Update password for user * @returns {Boolean|jqXHR} */ doChangePassword: function () { $('form#validationCP').find('.formErrorContent').css('white-space', 'nowrap'); if (!User.fStatus) { return false; } var postData = {}; var newPassword = $('#password').val().trim(); postData["NewPassword"] = HoGoUtils.MD5(newPassword); postData["PasswordRaw"] = newPassword; //If update specific user postData["UserID"] = HoGoUtils.getParameter()["userID"]; postData["SessionID"] = UserSession.getSessionID(); //TODO ajax return $.ajax({ type: "POST", url: "api/v1/UpdatePassword", data: postData, beforeSend: function () { Modal.closeModal(); }, success: function (data) { if (data.status === 'OK') { HoGoUtils.makeNotifyServer({ "msg": i18n.t('password.message.save_success'), "autoClose": true, "time": 600 }); } else { fnSessionTimeout(data); } } }); }, /** * Credit user point * @returns {jqXHR} */ credit: function () { if (!User.fStatus) { return; } var postData = {}; var point = $.trim($('#points').val()); postData["UserID"] = this.userID; postData["SessionID"] = UserSession.getSessionID(); postData["Points"] = point; return $.ajax({ type: "POST", url: "api/v1/AddUserPoint", data: postData, dataType: "json", timeout: HoGoConst.APITimeout, beforeSend: function () { Modal.closeModal(); }, success: function (data) { if (data.status === "OK") { HoGoUtils.makeNotifyServer({ "msg": i18n.t('user.message.success_credit'), "autoClose": true, "time": 400 }); //Load some new information was updated on parent view UserDetail.getUserDetail(); //Refresh page History.getTableList().fnDraw(true); } else { if (data.status === APIConst.adminSessionRequired || data.status === APIConst.sessionIdNotFound) { window.location.href = 'login'; } else { Modal.showAlert({content: i18n.t('error.unknown')}); } } } }); }, /** * Get popup modal & display it * @returns {jqXHR} */ showChangePasswordPopup: function () { $('#change-password-popup').remove(); var boxpanel = '
    ' + '
    ' + '' + '
    ' + '' + '
    ' + '' + '
    ' + '' + '
    ' + '
    ' + '
    '; // return $.get("ChangePasswordPopup", function(data){ $('body').append(boxpanel); $('#change-password-popup').i18n(); var m = $('#change-password-popup'); m.reveal({closeonbackgroundclick: false}); m.find('#change-password').bind('click', function () { var form = $(this).parents('form'); form.submit(); // Do update UserDetail.doChangePassword(); }); //Validate form change password HoGoUtils.validateForm('validationCP', User); // }); }, /** * Get credit popup & display it * @returns {jqXHR} */ showManualCreditPopup: function () { $('#manual-credit-popup').remove(); var boxpanel = '
    ' + '
    ' + '' + '' + '
    ' + '' + '
    ' + '' + '
    ' + '' + '
    ' + '
    ' + '
    '; // return $.get("ManualCreditPopup", function(data){ $('body').append(boxpanel); $('#manual-credit-popup').i18n(); var m = $('#manual-credit-popup'); m.reveal({closeonbackgroundclick: false}); m.find('#btnAddPoint').bind('click', function () { var form = $(this).parents('form'); form.submit(); // Credit point UserDetail.credit(); }); //Validate form change password HoGoUtils.validateForm('validationMC', User); // }); }, /** * Get history detail * @param {type} historyId * @param {type} type * @returns {jqXHR} */ showHistoryDetail: function (historyId, type) { // var historyId = $(itself).attr('his-id'); // var hTable = History.getTableList(); // // var aPos = hTable.fnGetPosition($(this).closest('tr').get(0) ); // // // Get current TR // UserDetail.cP = aPos; // // var hID = hTable.fnSettings().aoData[aPos]._aData.historyID; // Call API to get info return $.ajax({ dataType: 'json', type: "POST", url: "api/v1/GetHistoryDetail", data: {HistoryID: historyId, SessionID: UserSession.getSessionID(), UserID: UserDetail.userID}, timeout: HoGoConst.APITimeout, success: function (dt) { if (dt.status === "OK") { $.each(dt.detail, function (k, v) { UserDetail.transID = v.transmission_id; UserDetail.createDate = v.create_date; UserDetail.amount = v.cost; UserDetail.reason = v.reason; }); //Display pp UserDetail.showRefundPopup(UserDetail.createDate, UserDetail.amount, type, UserDetail.reason); } else { if (dt.status === APIConst.adminSessionRequired || dt.status === APIConst.sessionIdNotFound) { window.location.href = 'login'; } else { // Can't display refund pp HoGoUtils.writeLog(data.status_desc); Modal.showAlert({content: i18n.t('error.unknown')}); } } } }); }, /** * Show refund popup * @param {type} createDate * @param {type} amount * @param {type} type * @param {type} reason * @returns {jqXHR} */ showRefundPopup: function (createDate, amount, type, reason) { $('#refundPopup').remove(); return $.get("RefundPopup", function (data) { $('body').append(data); $('#refundPopup').i18n(); var m = $('#refundPopup'); m.reveal({closeonbackgroundclick: false}); $('#refundDate').text(DateUtils.convertFullDate(createDate)); $('#amount').text(convertCentToUSD(amount)); $('#reason').show(); if (type === HoGoConst.ADMIN_REFUND_TYPE) { $('.modal-title').html(i18n.t('user.refund.message.title')); $('.modal-control').remove(); $('#reason').hide(); $('#reasonResult').html(reason); } m.find('#btnRefund').bind('click', function () { var form = $(this).parents('form'); form.submit(); UserDetail.doRefund(); }); //Validate form change password HoGoUtils.validateForm('validationRf', User); }); }, /** * function is used to do refund user by admin * @returns {jqXHR} */ doRefund: function () { //Collect data for request on services var postData = {}; postData["SessionID"] = UserSession.getSessionID(); postData["TransmissionID"] = UserDetail.transID; postData["UserID"] = UserDetail.userID; postData["Reason"] = $('#reason').val(); //Calling services return $.ajax({ type: "POST", url: "api/v1/RefundUserPayment", beforeSend: function () { Modal.closeModal(); HoGoUtils.disableButton('#btnRefund', {}); }, data: postData, timeout: HoGoConst.APITimeout, dataType: "json", success: function (data) { if (data.status === "OK") { History.getTableList().fnDraw(); } else { if (data.status === APIConst.adminSessionRequired || data.status === APIConst.sessionIdNotFound) { window.location.href = 'login'; } else if (data.status === APIConst.INSUFFICIENT_POINT) { Modal.showAlert({content: i18n.t('user.refund.message.out_of_purchase_point')}); } else { Modal.showAlert({content: i18n.t('user.refund.message.fail_refund')}); } } } }); } }; var NewUser = { /** * Add user service * @returns {jqXHR|Boolean} */ addUser: function () { //Check form status first if (!formStatus) { return false; } var postData1 = {}; postData1["EmailAddress"] = $('#email').val(); var passHash = $('#passwordCon').val().trim(); postData1["Password"] = HoGoUtils.MD5(passHash); postData1["FirstName"] = $('#firstname').val(); postData1["MiddleName"] = $('#middlename').val(); postData1["LastName"] = $('#lastname').val(); //postData1["Company"] = $('#company').val(); postData1["SessionID"] = UserSession.getSessionID(); postData1["SyncBox"] = $('#syncBox :checkbox').is(':checked'); // Post data to server return $.ajax({ type: "POST", timeout: HoGoConst.APITimeout, url: "api/v1/AddServiceUser", data: postData1, dataType: "json", beforeSend: function () { //Disable btn save HoGoUtils.disableButton('#btnSave', {colorClass: 'green'}); //Display loader $("#validation .actionBar>.loader").show('fast'); }, success: function (data) { //Remove load $("#validation .actionBar>.loader").hide('slow'); var status = data.status; if (status === "OK") { redirectable = true; window.location.href = "UserList"; } else { if (status === APIConst.userAlreadyExistStatus) { HoGoUtils.enableButton('#btnSave', { colorClass: 'green', isSubmitForm: true, formID: 'validation' }); Modal.showAlert({content: i18n.t('user.message.exist_email')}); } else { if (data.status_desc === "Can't add user because your account is limit user") { HoGoUtils.enableButton('#btnSave', { colorClass: 'green', isSubmitForm: true, formID: 'validation' }); Modal.showAlert({content: i18n.t('user.message.limit_user')}); } else { fnSessionTimeout(data); } } } } }); } }; function makeRequestParamUsedPoint(aoData) { var post = {}; $.each(aoData, function (k, v) { if (v.name === "sEcho") { post["sEcho"] = v.value; } if (v.name === "iDisplayStart") { post["displayStart"] = v.value; } if (v.name === "iDisplayLength") { post["displayLength"] = v.value; } }); if (HoGoUtils.getPageName() === 'userdetail.html') { post["UserID"] = HoGoUtils.getParameter()['userID']; } post["SessionID"] = UserSession.getSessionID(); return post; } return { // Form status fStatus: false, /** * Trash item on poppup window * @param _itself item itself */ trashItem: function (_itself) { // Get the position of the current data from the node var aPos = oTable1.fnGetPosition(_itself.closest('tr').get(0)); //Delete the row oTable1.fnDeleteRow(aPos); //Check if delete all data if (oTable1.fnGetData().length === 0) { HoGoUtils.disableButton('#btn-save-csv', {colorClass: 'green', handler: doImport}); } }, /** * export user to csv file * @returns {undefined) */ exportUser: function () { var id = checkedList.toString(); $('#session-id').attr('value', UserSession.getSessionID()); var form = $("#formExport"); var fileFormat = $("").attr("type", "hidden").attr("name", "FileFormat").attr("value", 1); var listID = $("").attr("type", "hidden").attr("name", "ListUserID").attr("value", id); form.append(listID); form.append(fileFormat); var username = $("").attr("type", "hidden").attr("name", "UserName"); var company = $("").attr("type", "hidden").attr("name", "Company"); var email = $("").attr("type", "hidden").attr("name", "EmailAddress"); var registeredDate = $("").attr("type", "hidden").attr("name", "RegisteredDate"); var point = $("").attr("type", "hidden").attr("name", "PointBalance"); var lastActiveDate = $("").attr("type", "hidden").attr("name", "LastActiveDate"); $("#export-user-popup :input[type=checkbox]").each(function () { switch ($(this).attr("name")) { case "user-name": if ($(this).is(":checked")) form.append(username.attr("value", true)); else form.append(username.attr("value", false)); break; case "email-address": if ($(this).is(":checked")) form.append(email.attr("value", true)); else form.append(email.attr("value", false)); break; case "company": if ($(this).is(":checked")) form.append(company.attr("value", true)); else form.append(company.attr("value", false)); break; case "registered-date": if ($(this).is(":checked")) form.append(registeredDate.attr("value", true)); else form.append(registeredDate.attr("value", false)); break; case "point-balance": if ($(this).is(":checked")) form.append(point.attr("value", true)); else form.append(point.attr("value", false)); break; case "last-active-date": if ($(this).is(":checked")) form.append(lastActiveDate.attr("value", true)); else form.append(lastActiveDate.attr("value", false)); break; default: break; } }); //Close pp Modal.closeModal(); }, /** * Send message from admin to checked user list * @returns {jqXHR|Boolean} */ sendMessage: function () { //No user to send if ($('ul#emailTags').find('li.tagit-choice').length === 0) { //OFF Modal.closeModal(); return false; } //Valid form if (!formStatus) { return false; } //Sending var sentList = []; $('ul#emailTags li.tagit-choice').find('input').each(function (k, v) { var id = $(this).val(); //Add sentList.push(id); }); var title = $("#msg-title").val().trim(); var titleHTML = htmlEscape(title); var body = $('#msg-body').val().trim(); var bodyHTML = htmlEscape(body); //Declare data to send var pData = {}; pData["SessionID"] = UserSession.getSessionID(); pData["Type"] = HoGoConst.ADMIN_SENT_MESSAGE_TYPE; //777 pData["UserIDs"] = sentList.toString(); pData["Title"] = titleHTML; pData["Body"] = bodyHTML; return $.ajax({ url: "api/v1/SendMessage", dataType: "json", type: "POST", data: pData, //async: false, beforeSend: function () { Modal.closeModal(); }, success: function (data) { if (data.status === "OK") { HoGoUtils.makeNotifyServer({ "msg": i18n.t('user.message.success_sent_msg'), "autoClose": true, "time": 400 }); } else { Modal.showAlert({title: "Sending Failed", content: "There's an error while sending"}); } } }); }, /** * Remove user TR * @param {object} itself Remove its TR in popup table */ removeUser: function (itself) { itself.parent().remove(); }, /** * public function update user * @returns {undefined} */ updateUser: function () { UserDetail.updateUser(); }, addUser: function () { NewUser.addUser(); }, showHistoryDetail: function (historyId, type) { UserDetail.showHistoryDetail(historyId, type); }, doRefund: function () { UserDetail.doRefund(); }, /** * Do filter user * @returns {undefined} */ filterUser: function () { if (!formStatus) return; var p = History.makeParamFilter(); loadUserList(p); }, init: function () { // change href header console Admin HoGoUtils.makeHrefHeaderAdmin(); // Prevent hacking if (UserSession.getAdminObject() === null) { window.location.href = 'login'; return; } HoGoUtils.renderNameBaseLang(HoGoUtils.getPageName(), i18n.lng()); //Nav $('.nav-user').removeClass('item-user-list-deactive').addClass('item-left-menu'); HoGoUtils.makeLeftMenuAdmin(); var pName = HoGoUtils.getPageName(); // console.log(pName); if (pName === 'userlist.html') { //Event onchange CSV $('#file').live('change', function () { User.uploadCSVFile(); return false; }); //Update Icon header updateHeader(i18n.t('user.title'), 'Images/icon_userlist.png'); // Create options $('#pointType').tooltipster({ // autoClose: false, interactive: true, content: $('
    PaypalStripeGMO
    '), functionReady: function (o, t) { // Reset all var lFilter = $('#filterBlock').find('.active'); if (lFilter.length === 0) { $(t).find('.filter-item-child').removeClass('active'); } } }); // control download csv template ja if (i18n.lng() === 'ja') { $('#csvTemplate').attr('href', 'data/Hogo_CSV_File_Template_ja.csv'); } //History.initForUser(); loadUserList(); $('span.filter-item,.filter-item-child').die('click').live('click', function () { $(this).toggleClass('active'); if ($('.wrapper-filter-child').find('span.active').length > 0) { // Active parent payment $('#pointType').addClass('active'); } else { //$('#pointType').removeClass('active'); } // Submit $("#validation").submit(); }); $('#cbo_selectall').on('click', function () { DTUtils.checkboxSelectAllEvent(this, "child", checkedList); //We can't base on 'checkedList' because our app checks multiple page. if ($(this).prop('checked')) { //Insert to user list (Using for send message) $(':checkbox[name=child]').each(function () { var full_name = $("#" + this.id).closest('tr').find('div.full-name').text(); SelectedUserList.push(this.id, full_name, full_name.toLowerCase().replace(/ /g, '')); }); } else { //Remove $(':checkbox[name=child]').each(function () { SelectedUserList.remove(this.id); }); } if (checkedList.length > 0) { DTUtils.fnEnableControl(lEnableButton); } else { DTUtils.fnDisableControl(lDisableButton); } }); // Click save import popup $('#btn-save-csv').on('click', function () { doImport(); }); //Submit form upload CSV file & display popup $("#frm-import-user").submit(function (e) { //Prevent default click e.preventDefault(); importCSV(); }); } if (pName === 'userdetail.html') { // Init history for specify user History.init(); UserDetail.getUserDetail().done(function () { $('form#validation').find(':input').bind('keyup focusout', (function () { hasChanged(); })); $(window).bind('beforeunload', function () { if (hasChanged() === true && redirectable === false) { return "If you leave this page. Your selected data will be discard!"; } }); //set href for btn back var admin = UserSession.getAdminObject(); if (parseInt(admin.service_level) === HoGoConst.SYSTEM_ADMIN || parseInt(admin.service_level) === HoGoConst.DISTRIBUTOR) { var parentId = HoGoUtils.getParameter()['parentId']; var self = HoGoUtils.getParameter()['self']; var url = 'CompanyDetail?companyID=' + serviceId; if (typeof parentId !== 'undefined' && parentId !== '') { url += '&parentId=' + parentId; } if (typeof self !== 'undefined' && self !== '') { url += '&self=' + self; } $("#btn-back").prop("href", url); } }); // Validation filter form $('form#fValidation').validationEngine({ scroll: false, validationEventTrigger: "", focusFirstField: false, onValidationComplete: function (form, status) { UserDetail.fFStatus = status; } }); // Click manual credit button $("#btnCredit").on("click", function () { UserDetail.showManualCreditPopup(); }); // Click change password button $("#btnChangePassword").on("click", function () { UserDetail.showChangePasswordPopup(); }); $("#syncBox :checkbox").on('change', function () { hasChanged(); }); //here console.log(prePage, "user detail"); $('#btn-back').on('click', function () { $("#btn-back").attr("href", prePage); }); } if (pName === 'adduser.html') { $(window).bind('beforeunload', function () { if (hasChanged() === true && redirectable === false) { return "If you leave this page. Your selected data will be discard!"; } }); $('form#validation').find(':input').bind('keyup focusout', (function () { hasChanged(); })); } if (pName === 'packagedetaillinkadmin.html') { Package.initForUser(); } $('.btn-cancel-normal-popup').live('click', function () { Modal.closeModal(); }); }, //Upload CSV file from PC uploadCSVFile: function () { var name = document.getElementById("file"); var current_file_name = basename(name.value); var extension = current_file_name.substr((current_file_name.lastIndexOf('.') + 1)).toLowerCase(); if (extension !== 'csv') { Modal.showAlert({title: i18n.t('show_message.error.title_wrong_format'), content: i18n.t('user.message.wrong_format')}); return false; } else { // Make sure unique ID $('#import-popup').remove(); var boxpanel = '
    ' + '
    ' + '' + '
    ' + '
    ' + '' + '' + '' + '' + '' + '' + '' + '' + // '' + '' + '' + '
    ' + '' + '' + '' + '' + '' + '' + '' + // '' + // '
    ' + '
    ' + '
    ' + '' + '
    ' + '
    '; // $.get("ImportUserPopup", function(data) { $('body').append(boxpanel); $('#import-popup').i18n(); $("#frm-import-user").trigger("submit"); // }); } }, initForAffiliate: function () { loadUserList(); $('#cbo_selectall').on('click', function () { DTUtils.checkboxSelectAllEvent(this, "child", checkedList); //We can't base on 'checkedList' because our app checks multiple page. if ($(this).prop('checked')) { //Insert to user list (Using for send message) $(':checkbox[name=child]').each(function () { var full_name = $("#" + this.id).closest('tr').find('div.full-name').text(); SelectedUserList.push(this.id, full_name, full_name.toLowerCase().replace(/ /g, '')); }); } else { //Remove $(':checkbox[name=child]').each(function () { SelectedUserList.remove(this.id); }); } if (checkedList.length > 0) { DTUtils.fnEnableControl(lEnableButton); } else { DTUtils.fnDisableControl(lDisableButton); } }); // Clikc Delete button $('#btn-green-popup').on('click', function () { fnDeleteUser(); }); //Event search field $("#filter").keyup(function () { //checkedList = []; //SelectedUserList.removeAll(); oTable.fnFilter($("#filter").attr('value')); }); // Click save import popup $('#btn-save-csv').on('click', function () { doImport(); }); //Submit form upload CSV file & display popup $("#frm-import-user").submit(function (event) { //Prevent default click event.preventDefault(); importCSV(); }); // click cancel import popup and cancel export popup $('#btn-cancel-import-popup, .btn-cancel-normal-popup').live('click', function () { Modal.closeModal(); }); }, /** * Make tracking history points table * @param {type} fnCallback callback after initilized * @returns {undefined} */ trackingPoint: function (fnCallback) { var l = 'en'; pTable = $('#tablepaging1').dataTable({ "bInfo": false, // "bLengthChange": false, "aLengthMenu": [ [10, 50, 100, 200, -1], [10, 50, 100, 200, "All"] ], "bPaginate": true, "iDisplayLength": 10, "sPaginationType": "full_numbers", "oLanguage": DTUtils.DTLang, "sDom": '<"inline"<"right"p><"left"l>>itr', "sAjaxSource": "api/v1/TrackUsedPointHistory", "bServerSide": true, "bProcessing": true, "fnServerData": function (sSource, aoData, fnCallback, oSettings) { $.ajax({ url: sSource, type: 'POST', timeout: HoGoConst.APITimeout, dataType: "json", data: makeRequestParamUsedPoint(aoData), success: function (data) { if (data.status === "OK") { var json = {"sEcho": data.sEcho, "iTotalDisplayRecords": data.totalResult, "aaData": []}; $.each(data.history_used_point_detail, function (key, value) { json.aaData.push({"packageID": value.packageID, "historyType": value.historyType, "documentNumber": value.documentNumber, "recipientNumber": value.recipientNumber, "download": value.download, "pointUsed": value.pointUsed, "totalPoint": value.totalPoint, "total": value.total, "nullValue": ""}); }); var txtPoint = i18n.t('session.label.points'); $('#usedPoint, #point-used').html(data.usedPoint + ' ' + txtPoint); $('#point-purchase').html(data.purchasePoint + ' ' + txtPoint); } else { //Session not found if (data.status === APIConst.sessionIdNotFound) { window.location.href = 'login'; } else { HoGoUtils.writeLog(data.status_desc); Modal.showAlert({content: i18n.t('error.unknown')}); } } fnCallback(json); } }); }, "bStateSave": true, "fnRowCallback": function (nRow, aData) { var historyType = aData.historyType; $("td:eq(0)", nRow).html(''); $("td:eq(1)", nRow).html('
    ' + aData.packageID + '
    '); $("td:eq(2)", nRow).html('
    ' + convertSentMethodToText(aData.historyType) + '
    '); $("td:eq(3)", nRow).html('
    ' + aData.documentNumber + '
    '); $("td:eq(4)", nRow).html('
    ' + aData.recipientNumber + '
    '); $("td:eq(5)", nRow).html('
    ' + aData.download + '
    '); $("td:eq(6)", nRow).html('
    ' + aData.pointUsed + '
    '); if (parseInt(aData.pointUsed) > 5 && parseInt(aData.pointUsed) <= 20) { $('td:eq(6)', nRow).addClass('top20'); } else if (parseInt(aData.pointUsed) > 20 && parseInt(aData.pointUsed) <= 50) { $('td:eq(6)', nRow).addClass('top50'); } else if (parseInt(aData.pointUsed) > 50) { $('td:eq(6)', nRow).addClass('minium50'); } if (aData.packageID) { // if (historyType !== deleteDocumentType && historyType !== deletePackageType) { $("td:eq(7)", nRow).html(""); nRow.ondblclick = function () { if (UserSession.getAdminObject() === null) { window.location.href = "PackageDetailDownload?packageId=" + aData.package_id; } else { window.location.href = "PackageDetailDownloadAdmin?packageId=" + aData.packageID + "&userID=" + UserDetail.userID; } }; // } // else { // $("td:eq(7)", nRow).html(""); // } } }, "fnDrawCallback": function (oSettings) { // Setup control // DTUtils.fnSetUpTableControl(oSettings); }, "aoColumns": [ {"mDataProp": "packageID"}, {"mDataProp": "historyType"}, {"mDataProp": "documentNumber"}, {"mDataProp": "recipientNumber"}, {"mDataProp": "download"}, {"mDataProp": "pointUsed"}, {"mDataProp": "totalPoint"}, {"mDataProp": "nullValue"} ], "aoColumnDefs": [ {'bSortable': false, 'aTargets': [0, 1, 2, 3, 4, 5, 6, 7]} ], "fnInitComplete": function (s) { $('#' + s.sTableId).i18n(); $('#' + s.sTableId + '_length').find('select').selectmenu(); // Call callback if (typeof fnCallback === 'function') { fnCallback.call(); } } }); }, /** * Render user's points information on view * @returns {jqXHR} */ showPointOnUserDetail: function () { // Get points return $.post('api/v1/TrackUsedPointHistory', {SessionID: UserSession.getSessionID(), UserID: HoGoUtils.getParameter()['userID']}, function (data) { // if (parseInt(data.used_points) === 0) { // // Hide detail // $('#detailUsedPoint').hide(); // } // else { // $('#detailUsedPoint').show(); // } if (parseInt(data.purchased_points) === 0) { // Hide detail $('#detailPurchase').hide(); } else { $('#detailPurchase').show(); } var pointsT = i18n.t('session.label.points'); $('#point-used').text(data.used_points + ' ' + pointsT); $('#point-purchase').text(data.purchased_points + ' ' + pointsT); }); } }; }(jQuery)); // // Manage affiliates // var Affiliate = (function ($) { //Checklist contains UserID for checkbox event var checkedList = []; //Using for user list var oTable, redirectable = false; // Create variables as Model var name = "", email = "", website = "", address = "", phone = "", referralCode, referralLink, createDate, numberUser, logo = "aff_default_thumb.jpg"; /** * Return collection parameters to get list * @param {type} aoData * @returns {_L1.makeParameter.post} */ function makeParameter(aoData) { var post = {}; var colSort; var sortType; $.each(aoData, function (x, y) { if (y.name === "sEcho") { post["sEcho"] = y.value; } if (y.name === "iDisplayStart") { post["DisplayStart"] = y.value; } if (y.name === "iDisplayLength") { post["DisplayLength"] = y.value; } if (y.name === "sSearch") { post["SearchString"] = $.trim(y.value); } if (y.name === "iSortCol_0") { colSort = y.value; } if (y.name === "sSortDir_0") { sortType = y.value; } }); switch (colSort) { case 1: if (sortType === "asc") post["SortType"] = 1; else post["SortType"] = 2; break; case 2: if (sortType === "asc") post["SortType"] = 3; else post["SortType"] = 4; break; case 3: if (sortType === "asc") post["SortType"] = 5; else post["SortType"] = 6; break; case 4: if (sortType === "asc") post["SortType"] = 7; else post["SortType"] = 8; break; } post["SessionID"] = UserSession.getSessionID(); post["Delete"] = false; return post; } /** * Show confirm delete user * @returns {Boolean} */ function fnWarningDeleteAffiliate() { if (checkedList.length === 0) { return false; } else { Modal.showConfirmPopup({ title: "Delete Affiliate", content: i18n.t('affiliate.message.confirm_delete'), okCallback: function () { fnDeleteAffiliate(checkedList.toString()); } }); return false; } } /** * Do delete Affiliate * @param {type} ID * @returns {jqXHR} */ function fnDeleteAffiliate(ID) { return $.ajax({ type: "POST", url: "api/v1/DeleteAffiliate", dataType: 'json', data: {AffiliateID: ID, SessionID: UserSession.getSessionID()}, timeout: HoGoConst.APITimeout, beforeSend: function () { $('
    ').appendTo('#contents'); }, success: function (data) { if (data.status === 'OK') { if (HoGoUtils.getPageName() === 'affiliatelist.html') { $('.hogo-bg-overlay-action').remove(); checkedList = []; oTable.fnDraw(); } else { // Move to list setTimeout("window.location.href='AffiliateList'", 300); } } else { HoGoUtils.writeLog(data.status_desc); Modal.showAlert({content: i18n.t('error.unknown')}); } } }); } /** * Check whether input value has changed or not * @returns {Boolean} */ function hasChangeElement() { if ($.trim(name) !== $.trim($('#affiliateName').val()) || $.trim(email) !== $.trim($('#email').val()) || $.trim(website) !== $.trim($('#website').val()) || $.trim(address) !== $.trim($('#address').val()) || $.trim(phone) !== $.trim($('#phone').val()) || $.trim(logo) !== $.trim($('#file_id').val())) { HoGoUtils.enableButton('#btnSave', { colorClass: 'green', isSubmitForm: true, formID: 'validationAff' }); // Value has changed return true; } else { HoGoUtils.disableButton('#btnSave', { colorClass: 'green' }); return false; } } /** * Make a affiliate list * @returns {datatable} */ function makeAffiliateList() { return oTable = $("#tablepaging").dataTable({ "aaSorting": [[4, 'desc']], "bInfo": false, "bLengthChange": false, "bPaginate": true, "iDisplayLength": 10, "sPaginationType": "full_numbers", "bDestroy": true, "oLanguage": DTUtils.DTLang, "sDom": 'l<"right"f><"right inline"p>irt', "sAjaxSource": "api/v1/GetAffiliateList", "bServerSide": true, "bProcessing": true, "fnServerData": function (sSource, aoData, fnCallback, oSettings) { $.ajax({ url: sSource, type: "POST", dataType: "json", data: makeParameter(aoData), timeout: HoGoConst.APITimeout, success: function (data) { if (data.status === "OK") { var json = {"sEcho": data.sEcho, "iTotalDisplayRecords": data.totalResult, "aaData": []}; $.each(data.affiliate_list, function (key, value) { json.aaData.push({ "id": value.affiliate_id, "name": value.name, "email": value.email, "number_of_user": value.number_of_user, "create_date": value.create_date, "status": value.status }); }); } else { fnSessionTimeout(data); } fnCallback(json); } }); }, "fnRowCallback": function (nRow, aData) { $("td:eq(0)", nRow).html(""); $("td:eq(1)", nRow).html("
    " + aData.name + "
    "); $("td:eq(2)", nRow).html("
    " + aData.email + "
    "); $("td:eq(3)", nRow).html("
    " + aData.number_of_user + "
    "); $("td:eq(4)", nRow).html(DateUtils.convertDate(aData.create_date)); //It's fake data on view $("td:eq(5)", nRow).html(""); nRow.ondblclick = function () { setTimeout("window.location.href='AffiliateDetail?affiliateID=" + aData.id + "'", 300); }; nRow.onclick = function () { DTUtils.fnCheckBoxOnRow(this); }; }, "aoColumnDefs": [ {'bSortable': false, 'aTargets': [0, 5]} //Not sort for col 0,5 ], "bStateSave": true, "fnStateLoad": function (oSettings) { //Only from RecipientDetail. Load previous state if ($.cookie('l_p') === 'affiliatedetail.html') { var sData = this.oApi._fnReadCookie(oSettings.sCookiePrefix + oSettings.sInstance); var oData; try { oData = (typeof $.parseJSON === 'function') ? $.parseJSON(sData) : eval('(' + sData + ')'); } catch (e) { oData = null; } //Set search word on field if (oData !== null) if (oData.oSearch.sSearch !== null) $('#filter').val(oData.oSearch.sSearch); else $('#filter').val(''); else { //set search null $('#filter').val(''); } return oData; } else { return null; } }, "fnDrawCallback": function (oSettings) { //Draw checkbox $('#tablepaging .ck').customInput(); //Set up sort paginate // DTUtils.fnSetUpTableControl(oSettings); //Clear checklist when sorting // if (oSettings.bSorted) { // //Clear checklist // checkedList.splice(0, checkedList.length); // } //Checkbox event switching page DTUtils.checkboxSwitchPage("tablepaging", "child", "select_all", checkedList); //Event click child checkbox $(':checkbox[name=child]').on('click', function () { //Update checkedList DTUtils.checkboxChildSelectEvent(this, "select_all", checkedList); //Enable/Disable button if (checkedList.length > 0) { //Enable these buttons HoGoUtils.enableButton("#btnDelete", { colorClass: 'orange', handler: fnWarningDeleteAffiliate }); } else { //Disable HoGoUtils.disableButton("#btnDelete", {colorClass: 'orange'}); } }); }, //Map properties from json to view sequentially "aoColumns": [ {"mDataProp": "id"}, {"mDataProp": "name"}, {"mDataProp": "email"}, {"mDataProp": "number_of_user"}, {"mDataProp": "create_date"}, {"mDataProp": "status"} ] }); } /** * Affiliate detail object * @type object */ var AffilateDetail = { /* This param is required */ affiliateID: HoGoUtils.getParameter()['affiliateID'], /** * Get affiliate detail * @returns {jqXHR} */ getAffiliateDetail: function () { var $this = this; //Get recipient detail return $.ajax({ dataType: 'json', type: "POST", url: "api/v1/GetAffiliateDetail", data: {AffiliateID: $this.affiliateID, SessionID: UserSession.getSessionID()}, timeout: HoGoConst.APITimeout, success: function (dt) { if (dt.status === "OK") { if (dt.detail.length > 0) { $.each(dt.detail, function (key, value) { if (value.status === 1) { //Set info value name = value.name; email = decodeURIComponent(value.email); address = value.address; phone = value.phone_number; website = decodeURIComponent(value.website); referralCode = value.referral_code; referralLink = decodeURIComponent(value.referral_link); numberUser = value.number_of_user; createDate = DateUtils.convertDate(value.create_date); logo = value.logo; // Render // Get logo $("#affLogo").attr("src", "api/v1/GetAffiliateThumbnail?FileID=" + logo); $("#affiliateName").val(name); $("#email").val(email); $("#website").val(website); $("#address").val(address); $("#phone").val(phone); $("#referralCode").val(referralCode); $("#referralLink").val(referralLink); $("#registeredDate").html(createDate); $("#numberUser").html(numberUser); $("#file_id").val(logo); } else { window.location = "AffiliateList"; } }); } else { // Invalid Affiliate window.location = "AffiliateList"; } } else { window.location = "AffiliateList"; } } }); }, /** * Update an affiliate * @returns {Boolean|jqXHR} */ updateAffiliate: function () { if (!Affiliate.fStatus) return false; var pData = {}; $('#validationAff').find(':input').each(function (i, v) { pData[$(v).attr('name')] = $(v).val(); }); pData['SessionID'] = UserSession.getSessionID(); pData['AffiliateID'] = this.affiliateID; return $.ajax({ type: "POST", url: "api/v1/UpdateAffiliate", dataType: 'json', data: pData, timeout: HoGoConst.APITimeout, beforeSend: function () { $('#container').find('.loader').show('fast'); HoGoUtils.disableButton('#btnSave', { colorClass: 'green' }); }, success: function (data) { $('#container').find('.loader').hide('slow'); if (data.status === 'OK') { AffilateDetail.getAffiliateDetail(); } else { HoGoUtils.enableButton('#btnSave', { colorClass: 'green', isSubmitForm: true, formID: 'validationAff' }); // Error HoGoUtils.writeLog(data.status_desc); Modal.showAlert({content: i18n.t('error.unknown')}); } } }); } }; /** * New an affiliate * @type object */ var NewAffiliate = { /** * Add a new affiliate * @returns {Boolean|jqXHR} */ addAffiliate: function () { if (!Affiliate.fStatus) return false; var pData = {}; $("#validationAff").find(':input').each(function () { pData[$(this).attr('name')] = $.trim($(this).val()); }); pData["SessionID"] = UserSession.getSessionID(); return $.ajax({ dataType: 'json', type: "POST", url: "api/v1/AddAffiliate", data: pData, timeout: HoGoConst.APITimeout, beforeSend: function () { $('#container').find('.loader').show('fast'); HoGoUtils.disableButton('#btnSave', { colorClass: 'green' }); }, success: function (dt) { //Remove load $('#container').find('.loader').hide('slow'); if (dt.status === "OK") { redirectable = true; window.location.href = "AffiliateList"; } else { HoGoUtils.enableButton('#btnSave', { colorClass: 'green', isSubmitForm: true }); if (dt.status === APIConst.AFFILIATE_ALREADY_EXIST) { Modal.showAlert({ title: "Exist Email", content: i18n.t('affiliate.message.exist_email') }); } else { fnSessionTimeout(dt); } } } }); } }; var Report = { //History list table hTable: null, //Type history. Init get all. typeHistory: "", //Init start/stop date startDate: convertFromDateObject(new Date(0)) + ' 00:00:00', endDate: convertFromDateObject(new Date()) + ' 23:59:59', makeRequestParam: function (aoData, startDate, endDate) { var post = {}; var colSort; var sortType; $.each(aoData, function (x, y) { if (y.name === "sEcho") { post["sEcho"] = y.value; } if (y.name === "iDisplayStart") { post["DisplayStart"] = y.value; } if (y.name === "iDisplayLength") { post["DisplayLength"] = y.value; } if (y.name === "sSearch") { post["SearchString"] = $.trim(y.value); } if (y.name === "iSortCol_0") { colSort = y.value; } if (y.name === "sSortDir_0") { sortType = y.value; } }); switch (colSort) { case 0: if (sortType === "asc") post["SortType"] = 1; else post["SortType"] = 2; break; case 1: if (sortType === "asc") post["SortType"] = 3; else post["SortType"] = 4; break; case 2: if (sortType === "asc") post["SortType"] = 5; else post["SortType"] = 6; break; case 3: if (sortType === "asc") post["SortType"] = 7; else post["SortType"] = 8; break; case 4: if (sortType === "asc") post["SortType"] = 9; else post["SortType"] = 10; break; } post["StartDate"] = startDate; post["EndDate"] = endDate; post["AffiliateID"] = HoGoUtils.getParameter()['affiliateID']; post["SessionID"] = UserSession.getSessionID(); return post; }, /** * Set filter date before make a request * @returns {undefined} */ setDate: function () { var $this = this; //Check validate picker if ($('#datepickerStart').val().trim() !== "") { $this.startDate = $('#datepickerStart').val() + ' 00:00:00'; } else { //Set min date $this.startDate = convertFromDateObject(new Date(0)) + ' 00:00:00'; } if ($('#datepickerEnd').val().trim() !== "") { $this.endDate = $('#datepickerEnd').val() + ' 23:59:59'; } else { $this.endDate = convertFromDateObject(new Date()) + ' 23:59:59'; } }, /** * Make a report list * @returns {undefined} */ makeReportList: function () { var $this = this; $this.setDate(); $this.hTable = $('#tablepaging').dataTable({ "aaSorting": [[0, 'desc']], "bInfo": false, "bDestroy": true, // "bLengthChange": false, "aLengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ], "bPaginate": true, "iDisplayLength": 10, "sPaginationType": "full_numbers", "oLanguage": DTUtils.DTLang, "sDom": 'pli<"clear-right">tr', "sAjaxSource": "api/v1/ReportHistoryPoint", "bServerSide": true, "bProcessing": true, "fnServerData": function (sSource, aoData, fnCallback, oSettings) { $.ajax({ url: sSource, type: 'POST', timeout: HoGoConst.APITimeout, dataType: "json", data: $this.makeRequestParam(aoData, $this.startDate, $this.endDate), success: function (data) { if (data.status === "OK") { var json = {"sEcho": data.sEcho, "iTotalDisplayRecords": data.totalResult, "aaData": [], "totalYen": data.totalYen, "totalUSD": data.totalUSD}; $.each(data.history_point, function (key, value) { var name = ""; if (value.middle_name === null) { name = value.first_name + " " + value.last_name; } else { name = value.first_name + " " + value.middle_name + " " + value.last_name; } json.aaData.push({ "date": value.create_date, "name": name, "email": value.mail_address, "point": value.point, "cost": value.cost, "currency": value.currency }); }); if (data.totalResult > 0) { $('.wrapper-amount').show(); $('#totalUSD').text(HoGoUtils.convertMoneyFomat(data.totalUSD, 'USD')); $('#totalYen').text(HoGoUtils.convertMoneyFomat(data.totalYen, 'YEN')); } else { // Hide amount $('.wrapper-amount').hide(); } } else { fnSessionTimeout(data); } fnCallback(json); } }); }, "bStateSave": true, "fnRowCallback": function (nRow, aData) { //Edit data on drawing $("td:eq(0)", nRow).html(DateUtils.convertFullDate(aData.date)); $("td:eq(1)", nRow).html("
    " + aData.name + "
    "); $("td:eq(2)", nRow).html("
    " + aData.email + "
    "); $("td:eq(3)", nRow).html("
    " + aData.point + "
    "); $("td:eq(4)", nRow).html("
    " + convertCentToUSD(aData.cost, aData.currency) + "
    "); //var method = (aData.currency == null || aData.currency == 'USD') ? 'Paypal' : 'GMO'; //$("td:eq(5)", nRow).html("
    "+ method +"
    "); nRow.setAttribute("style", "text-align: left"); }, "aoColumnDefs": [ //{'bSortable': false, 'aTargets': [ 0,5 ]} ], "fnDrawCallback": function (oSettings) { //Clear array // DTUtils.fnSetUpTableControl(oSettings); DTUtils.determinePaging(oSettings); }, "aoColumns": [ {"mDataProp": "date"}, {"mDataProp": "name"}, {"mDataProp": "email"}, {"mDataProp": "point"}, {"mDataProp": "cost"} //{ "mDataProp": "currency" } ] }); }, /** * Filter history points * @returns {undefined} */ filterReport: function () { if (!formStatus) return false; this.setDate(); this.hTable.fnDraw(); } }; function isCompanyAdmin(admin) { if (parseInt(admin.service_level) === HoGoConst.COMPANY_ADMIN) { return true; } else return false; } return { /* Validation status */ fStatus: false, /** * Update affiliate * @returns {ajaxFileUpload} */ uploadThumbnail: function () { return $.ajaxFileUpload({ url: 'api/v1/UploadAffiliateThumbnail', secureuri: false, fileElementId: "fileLogo", data: {SessionID: UserSession.getSessionID()}, dataType: 'json', success: function (data) { if (data.status === 'OK') { // Set new image $("#affLogo").attr("src", "api/v1/GetAffiliateThumbnail?FileID=" + data.file_id); $('#file_id').val(data.file_id); // Check after change hasChangeElement(); } else { HoGoUtils.writeLog(data.status_desc); Modal.showAlert({content: i18n.t('error.unknown')}); } } }); }, doUpdate: function () { AffilateDetail.updateAffiliate(); }, doAdd: function () { NewAffiliate.addAffiliate(); }, init: function () { // Prevent hacking if (UserSession.getAdminObject() === null) { window.location.href = 'login'; return; } if (!isCompanyAdmin(UserSession.getAdminObject())) { var admin = UserSession.getAdminObject(); if (parseInt(admin.service_level) === HoGoConst.SYSTEM_ADMIN) { window.location.href = serverHostAPI + 'Distributor'; } if (parseInt(admin.service_level) === HoGoConst.DISTRIBUTOR) { window.location.href = serverHostAPI + 'Service'; } return; } $('.nav-affiliate').removeClass('item-user-list-deactive').addClass('item-user-list-active'); HoGoUtils.makeLeftMenuAdmin(); HoGoUtils.validateForm('validationAff', Affiliate); // Event changing logo $('#fileLogo').live('change', function () { Affiliate.uploadThumbnail(); return false; }); if ($('#affiliateList').length > 0) { makeAffiliateList(); $('#cbo_selectall').on('click', function () { DTUtils.checkboxSelectAllEvent(this, "child", checkedList); if (checkedList.length > 0) { HoGoUtils.enableButton("#btnDelete", { colorClass: 'orange', handler: fnWarningDeleteAffiliate }); } else { HoGoUtils.disableButton("#btnDelete", { colorClass: 'orange' }); } }); } var pName = HoGoUtils.getPageName(); if (pName === 'affiliatedetail.html' || pName === 'addaffiliate.html') { $(window).bind('beforeunload', function () { if (hasChangeElement() === true && redirectable === false) { return "If you leave this page. Your selected data will be discard!"; } }); } if (pName === 'affiliatedetail.html') { User.initForAffiliate(); //Copy link action // HoGoUtils.copyLink('#btnCopyLink'); // Get detail AffilateDetail.getAffiliateDetail().done(function () { $('form#validationAff').find(':input').bind('keyup focusout', (function () { hasChangeElement(); })); }); $('#reportHistoryPoint').bind('click', function () { window.location.href = "ReportHistoryAffiliate?affiliateID=" + AffilateDetail.affiliateID; }); } if (pName === 'addaffiliate.html') { $('form#validationAff').find(':input').bind('keyup focusout', (function () { hasChangeElement(); })); } if (pName === "reporthistoryaffiliate.html") { AffilateDetail.getAffiliateDetail().done(function () { Report.makeReportList(); }); $('#filterHistoryPoint').bind('click', function () { Report.filterReport(); }); } } }; })(jQuery); // // Admin's information // var Admin = (function ($) { var pTable; var disComName = "", disemail = "", disFirstName = "", disLastName = "", disMiddleName = "", discreateDate = "", disphoneNumber = "", disreferallLink = "", dislang, disCurrency = "", billing_cycle; var name = "", email = "", password = "", companykey = "", createdate, status, adminFName = "", adminMName = "", adminLname = "", phoneNumber = "", address1 = "", address2 = "", cancelPayment = false, conPassword = "", department = "", city = "", state = "", country = "", zipcode = "", lang = "", paymentTerm = "", usagePlan = "", paymentTermDes = "", billingCycle = "", currency = "", checkAutoSetNewPayment = "", billingCycles = ''; function hasChangeElement() { if ($.trim(conPassword) !== $.trim($('#passwordCon').val()) || $.trim(password) !== $.trim($('#password').val()) || $.trim(name) !== $.trim($('#companyName').val()) || $.trim(email) !== $.trim($('#adminEmail').val()) || $.trim(adminFName) !== $.trim($('#adminFName').val()) || $.trim(adminLname) !== $.trim($('#adminLName').val()) || $.trim(adminMName) !== $.trim($('#adminMName').val()) || lang !== $('#language').val() ) { HoGoUtils.enableButton('#btnSave', {colorClass: 'green', isSubmitForm: true, formID: 'validationCom'}); return true; } else { HoGoUtils.disableButton('#btnSave', {colorClass: 'green'}); return false; } } function hasChangePaymentInfo() { if ($.trim(usagePlan) !== $.trim($("input[name=plan]:checked").val()) || $.trim(address2) !== $.trim($('#address2').val()) || $.trim(adminMName) !== $.trim($('#adminMName').val()) || $.trim(department) !== $.trim($('#department').val()) || $.trim(city) !== $.trim($('#city').val()) || $.trim(state) !== $.trim($('#stateProvince').val()) || $.trim(country) !== $.trim($('#country').val()) || $.trim(zipcode) !== $.trim($('#zipcode').val()) || $.trim(phoneNumber) !== $.trim($('#PhoneNumber').val()) || $.trim(address1) !== $.trim($('#address1').val()) || ((!checkAutoSetNewPayment) === $('#checkAutoSetNewPayment :checkbox').is(':checked'))) { HoGoUtils.enableButton('#btnChangePayment', {colorClass: 'green', isSubmitForm: true, formID: 'validationPay'}); return true; } else { HoGoUtils.disableButton('#btnChangePayment', {colorClass: 'green'}); return false; } } function hasChangeElementDis() { if ($.trim(disComName) !== $.trim($('#disComName').val()) || $.trim(disFirstName) !== $.trim($('#disFName').val()) || $.trim(disLastName) !== $.trim($('#disLName').val()) || $.trim(disMiddleName) !== $.trim($('#disMName').val()) || $.trim(disemail) !== $.trim($('#disEmail').val()) || $.trim(disphoneNumber) !== $.trim($('#disPhone').val()) || dislang !== $.trim($('#language').val()) || $.trim(disCurrency) !== $.trim($("#currentcy").val()) || billingCycles !== serializeBillingCycle()) { HoGoUtils.enableButton('#btnSave', {colorClass: 'green', isSubmitForm: true, formID: 'validationDis'}); return true; } else { HoGoUtils.disableButton('#btnSave', {colorClass: 'green'}); return false; } } function serializeBillingCycle() { var billingCycles = ''; $.each($('.ms-drop input:checkbox'), function (key, value) { billingCycles += $(value).is(':checked') ? '1' : '0'; }); return billingCycles; } function getAdminSessionData() { //Get recipient detail return $.ajax({ dataType: 'json', type: "POST", url: "api/v1/GetCompanyDetail", data: {SessionID: UserSession.getSessionID()}, timeout: HoGoConst.APITimeout, success: function (dt) { if (dt.status === "OK") { if (dt.detail.length > 0) { $.each(dt.detail, function (key, value) { //Set info value name = value.name; email = decodeURIComponent(value.admin); companykey = value.service_key; createdate = DateUtils.convertDate(value.create_date); adminFName = value.admin_fName; adminLname = value.admin_lName; adminMName = value.admin_mName; var numberUser = value.number_user; lang = value.lang; // Load company payment info var paymentInfo = value.payment_info; address1 = paymentInfo.address1; address2 = paymentInfo.address2; department = paymentInfo.department; city = paymentInfo.city; state = paymentInfo.state; phoneNumber = paymentInfo.phoneNumber; country = paymentInfo.country; zipcode = paymentInfo.zipCode; usagePlan = value.usage_plan; billingCycle = paymentInfo.billingCycle; currency = paymentInfo.currentcy; // $('#currentcy').val(currency).selectmenu(); if (lang === '' || lang === null) { $('#language').val('auto').selectmenu(); } else { var lLang = lang.split('-'); // auto-en var pName = HoGoUtils.getPageName(); if ($.trim(lLang[0]) === 'auto') { $('#language').val($.trim(lLang[0])).selectmenu(); HoGoUtils.renderNameBaseLang(pName, HoGoUtils.detectBrowserLang()); } else { $('#language').val(lang).selectmenu(); HoGoUtils.renderNameBaseLang(pName, lang); } } switch (parseInt(value.status)) { case 1: status = 1; $("#status").html('' + i18n.t("status.active") + ''); break; case 4: status = 4; $("#status").html('' + i18n.t("status.pending") + ''); break; case 7: status = 7; $("#status").html('' + i18n.t("status.trial") + ''); } if (paymentInfo.type === 7 || paymentInfo.type === 4) { $("#checkAutoSetNewPayment").show(); } else { $("#checkAutoSetNewPayment").hide(); } checkAutoSetNewPayment = paymentInfo.setNewPaymentAfterTrial; $("#checkAutoSetNewPayment :checkbox").prop('checked', checkAutoSetNewPayment); // Render $("#companyName").val(name); $("#companykey").html(companykey); $("#createDate").html(createdate); $("#PhoneNumber").val(phoneNumber); $("#adminEmail").val(email); $("#adminFName").val(adminFName); $("#adminLName").val(adminLname); $("#adminMName").val(adminMName); $('#numberUser').html(numberUser); // payment info $("#department").val(department); $("#address1").val(address1); $("#address2").val(address2); $("#city").val(city); $("#stateProvince").val(state); $("#country").val(country); $("#zipcode").val(zipcode); $('#lblBillingCycle').text(billingCycle); $('#billingCycle').val(billingCycle).selectmenu(); cancelPayment = paymentInfo.cancelPayment; if (status === HoGoConst.ACTIVE_STATUS) { if (cancelPayment) { $('#btnCancelPaymentCycle').addClass('hide'); $('#btnDisableCancelPaymentCycle').removeClass('hide'); } else { $('#btnCancelPaymentCycle').removeClass('hide'); $('#btnDisableCancelPaymentCycle').addClass('hide'); } } else { $('#btnCancelPaymentCycle').addClass('hide'); $('#btnDisableCancelPaymentCycle').addClass('hide'); } var paymentUsagePlan = paymentInfo.id.paymentId; if (usagePlan !== paymentUsagePlan) { var content = (currency === "yen") ? i18n.t('payment_package.package' + paymentUsagePlan + '_ja') : i18n.t('payment_package.package' + paymentUsagePlan); $('#currUsagePlan').text(content); $('#usagePlanAlert').removeClass('hide'); } else { $('#usagePlanAlert').addClass('hide'); } // Load Payment term and usage plan $("input[name=plan][value=" + usagePlan + "]").click(); }); } else { } } else { // } } }); } // function get resller admin info function getDistributorDetail() { //Get recipient detail return $.ajax({ dataType: 'json', type: "POST", url: "api/v1/GetDistributorDetail", data: {SessionID: UserSession.getSessionID()}, timeout: HoGoConst.APITimeout, success: function (dt) { if (dt.status === "OK") { if (dt.list_distributor.length > 0) { $.each(dt.list_distributor, function (key, value) { disComName = value.service_name; disFirstName = value.admin_fName; disLastName = value.admin_lastName; disMiddleName = value.admin_mName; disemail = value.admin_email; discreateDate = DateUtils.convertDate(value.create_date); disreferallLink = value.referall_link; disCurrency = value.currency; billingCycles = value.billing_cycle; var selectVal = []; for (var i = 0; i < billingCycles.length; i++) { if (billingCycles.charAt(i) === '1') { selectVal.push(i); } } $('#ddBillingCycles').multipleSelect('setSelects', selectVal); $("#currentcy").val(disCurrency).selectmenu(); // //Set info value // // Render dislang = value.admin_lang; if (dislang === '' || dislang === null) { $('#language').val('auto').selectmenu(); } else { var lLang = dislang.split('-'); // auto-en var pName = HoGoUtils.getPageName(); if ($.trim(lLang[0]) === 'auto') { $('#language').val($.trim(lLang[0])).selectmenu(); HoGoUtils.renderNameBaseLang(pName, HoGoUtils.detectBrowserLang()); } else { $('#language').val(dislang).selectmenu(); HoGoUtils.renderNameBaseLang(pName, dislang); } } $("#serviceId").val(value.service_id); $("#disComName").val(disComName); $("#disLink").val(disreferallLink); $("#createDate").html(discreateDate); $("#disEmail").val(disemail); $("#disFName").val(disFirstName); $("#disMName").val(disMiddleName); $("#disLName").val(disLastName); $("#numberCompany").html(value.number_company); switch (parseInt(value.status)) { case 1: $("#status").html("
    Active
    "); break; default: $("#status").html("
    Deactive
    "); break; } }); } else { } } else { // window.location = "Distributor"; } } }); } function getAdminDetail() { $("#adminEmail").html(UserSession.getAdminObject().admin_email); } function changePasswordCompanyAdmin() { if (!Admin.fStatus) { return false; } var companyId = HoGoUtils.getParameter()['companyID']; var password = $('#passwordCon').val().trim(); return $.ajax({ type: "POST", url: "api/v1/ChangeAdminCompanyPassword", data: {ServiceID: companyId, SessionID: UserSession.getSessionID(), Password: HoGoUtils.MD5(password)}, beforeSend: function () { Modal.closeModal(); }, success: function (data) { if (data.status === 'OK') { HoGoUtils.makeNotifyServer({ "msg": i18n.t('password.message.save_success'), "autoClose": true, "time": 1000 }); } else { Modal.showAlert({ title: i18n.t('password.change_password.error'), content: i18n.t('password.change_password.error') }); } } }); } // Show password popup function showChangePasswordPopupCom() { Modal.createModal(2, { title: i18n.t('password.change_password.title'), // Should support multiple langue (i18n.t('modal.change_password_title')) preventClose: true, onLoad: function () { HoGoUtils.validateForm('validationCP', Admin); }, templateUrl: "Template/change_password.html", okCallback: function (modal) { // Call submit form var form = modal.find('form'); form.submit(); changePasswordCompanyAdmin(); } }); } function changePasswordDistributorAdmin() { if (!Admin.fStatus) { return false; } var companyId = HoGoUtils.getParameter()['serviceID']; var password = $('#passwordCon').val().trim(); return $.ajax({ type: "POST", url: "api/v1/ChangeAdminDistributorPassword", data: {ServiceID: companyId, SessionID: UserSession.getSessionID(), Password: HoGoUtils.MD5(password)}, beforeSend: function () { Modal.closeModal(); }, success: function (data) { if (data.status === 'OK') { HoGoUtils.makeNotifyServer({ "msg": i18n.t('password.message.save_success'), "autoClose": true, "time": 400 }); } else { Modal.showAlert({ title: i18n.t('password.change_password.error'), content: i18n.t('password.change_password.error') }); } } }); } function showChangePasswordPopup( ) { Modal.createModal(2, { title: i18n.t('password.change_password.title'), // Should support multiple langue (i18n.t('modal.change_password_title')) preventClose: true, onLoad: function () { HoGoUtils.validateForm('validationCP', Admin); }, templateUrl: "Template/change_password.html", okCallback: function (modal) { // Call submit form var form = modal.find('form'); form.submit(); changePasswordDistributorAdmin(); } }); } function updateCompany() { if (!Admin.fStatus) return false; var pData = {}; $('#validationCom').find(':input').each(function (i, v) { pData[$(v).attr('name')] = $(v).val(); }); pData['SessionID'] = UserSession.getSessionID(); pData['ServiceID'] = this.companyID; pData['Lang'] = HoGoUtils.detectBrowserAutoLang(pData['Lang']); // use for company update ifself return $.ajax({ type: "POST", url: "api/v1/UpdateCompany", dataType: 'json', data: pData, timeout: HoGoConst.APITimeout, beforeSend: function () { $('#detail').find('.loader').show('fast'); HoGoUtils.disableButton('#btnSave', { colorClass: 'green' }); }, success: function (data) { $('#detail').find('.loader').hide('slow'); if (data.status === 'OK') { getAdminSessionData().done(function () { UserSession.updateAdminInfo(); }); } else if (data.status === 'LimittedUser') { Modal.showAlert({content: i18n.t('company.message.limit_user')}); } else { HoGoUtils.enableButton('#btnSave', { colorClass: 'green', isSubmitForm: true, formID: 'validationCom' }); // Error HoGoUtils.writeLog(data.status_desc); Modal.showAlert({content: i18n.t('error.unknown')}); } } }); } function updateDistributor() { if (!Admin.fStatus) return false; var pData = {}; $('#validationDis').find(':input').each(function (i, v) { pData[$(v).attr('name')] = $(v).val(); }); pData['SessionID'] = UserSession.getSessionID(); pData['ServiceID'] = this.serviceID; pData['BillingCycle'] = serializeBillingCycle(); pData['Lang'] = HoGoUtils.detectBrowserAutoLang(pData['Lang']); // use for distributor update itself return $.ajax({ type: "POST", url: "api/v1/UpdateDistributor", dataType: 'json', data: pData, timeout: HoGoConst.APITimeout, beforeSend: function () { $('#container').find('.loader').show('fast'); HoGoUtils.disableButton('#btnSave', { colorClass: 'green' }); }, success: function (data) { $('#container').find('.loader').hide('slow'); if (data.status === 'OK') { // getDistributorDetail().done(function () { // UserSession.updateAdminInfo(); // }); Admin.loadDistributorAdminInfo(); UserSession.updateAdminInfo(); } else { HoGoUtils.enableButton('#btnSave', { colorClass: 'green', isSubmitForm: true, formID: 'validationDis' }); // Error HoGoUtils.writeLog(data.status_desc); Modal.showAlert({content: i18n.t('error.unknown')}); } } }); } function updateCompanyPaymentInfo() { if (!Admin.fStatus) return false; var pData = {}; $('#validationPay').find(':input').each(function (i, v) { pData[$(v).attr('name')] = $(v).val(); }); var paymentTerm = $('input[name=paymentTerm]:checked').val(); switch (paymentTerm) { case "1": case "2": case "3": pData["PaymentTerm"] = $.trim(paymentTerm); break; case "4": paymentTerm = $("#otherPaymentTerm").val(); pData["PaymentTerm"] = $.trim(paymentTerm); } pData["UsagePlan"] = $('input[name=plan]:checked').val(); pData["billingCycle"] = $('#billingCycle').val(); pData['SessionID'] = UserSession.getSessionID(); pData['ServiceID'] = this.companyID; // pData["Currentcy"] = $("#currentcy").val(); // if ($('#checkAutoSetNewPayment :checkbox').is(':checked')) { // pData['checkAutoSetNewPayment'] = HoGoConst.SET_NEW_PAYMENT_AFTER_TRIAL; // } else { // pData['checkAutoSetNewPayment'] = HoGoConst.NOT_SET_NEW_PAYMENT_AFTER_TRIAL; // } if (usagePlan > pData.UsagePlan) { var modal = { title: i18n.t('payment_package.message.confirm_downgrade_title'), content: i18n.t('payment_package.message.confirm_downgrade'), okCallback: function () { ajaxUpdatePayment(pData); } }; Modal.showConfirmPopup(modal); } else { ajaxUpdatePayment(pData); } } function ajaxUpdatePayment(pData) { if (!Admin.fStatus) return false; $.ajax({ type: "POST", url: "api/v1/UpdateCompanyPayment", dataType: 'json', data: pData, timeout: HoGoConst.APITimeout, beforeSend: function () { $('#billingInfo').find('.loader').show('fast'); HoGoUtils.disableButton('#btnChangePayment', { colorClass: 'green' }); }, success: function (data) { $('#billingInfo').find('.loader').hide('slow'); if (data.status === 'OK') { getAdminSessionData(); } else if (data.status === "LimittedUser") { Modal.showAlert({content: i18n.t('company.message.limit_user')}); HoGoUtils.enableButton('#btnChangePayment', { colorClass: 'green', isSubmitForm: true, formID: 'validationPay' }); } else { HoGoUtils.enableButton('#btnChangePayment', { colorClass: 'green', isSubmitForm: true, formID: 'validationPay' }); // Error HoGoUtils.writeLog(data.status_desc); Modal.showAlert({content: i18n.t('error.unknown')}); } } }); } function getCompanyPaymentCurrent() { //Get recipient detail return $.ajax({ dataType: 'json', type: "POST", url: "api/v1/GetCompanyPaymentCurrent", data: {SessionID: UserSession.getSessionID()}, timeout: HoGoConst.APITimeout, success: function (dt) { if (dt.status === "OK") { var currentPayment = dt.current_payment; // Render $("#paymentDate").html(DateUtils.convertDate(currentPayment.payment_service.registerDate)); $("#dueDate").html(DateUtils.convertDate(currentPayment.payment_service.dueDate)); $("#transaction").html(currentPayment.number_transaction); var currentcyHis = currentPayment.currentcy; var currentcyIcon, currentcyDis; switch (currentcyHis) { case 'yen': currentcyIcon = "¥"; currentcyDis = i18n.t('currentcy.ja_currentcy'); // should translate break; default : currentcyIcon = "$"; currentcyDis = i18n.t('currentcy.us_currentcy'); // should translate break; } $("#currentcyHis").html(currentcyDis); $("#unitPrice").html(currentcyIcon + currentPayment.unit_price); $("#totalAmount").html(currentcyIcon + currentPayment.total_amount); } else { // window.location = "Service"; } } }); } /** * Return collection parameters to get list * @param {type} aoData * @returns {_L1.makePaymentHistoryParameter.post} */ function makePaymentHistoryParameter(aoData) { var post = {}; var colSort; var sortType; $.each(aoData, function (x, y) { if (y.name === "sEcho") { post["sEcho"] = y.value; } if (y.name === "iDisplayStart") { post["DisplayStart"] = y.value; } if (y.name === "iDisplayLength") { post["DisplayLength"] = y.value; } if (y.name === "iSortCol_0") { colSort = y.value; } if (y.name === "sSortDir_0") { sortType = y.value; } }); switch (colSort) { case 0: if (sortType === "asc") post["SortType"] = 1; else post["SortType"] = 2; break; case 1: if (sortType === "asc") post["SortType"] = 3; else post["SortType"] = 4; break; case 2: if (sortType === "asc") post["SortType"] = 5; else post["SortType"] = 6; break; case 3: if (sortType === "asc") post["SortType"] = 5; else post["SortType"] = 6; break; case 4: if (sortType === "asc") post["SortType"] = 5; else post["SortType"] = 6; break; } // User for distrubutor if (HoGoUtils.getPageName() === 'companydetail.html') { post["CompanyID"] = HoGoUtils.getParameter()['companyID']; } post["SessionID"] = UserSession.getSessionID(); return post; } function getCompanyPaymentHistory() { return pTable = $("#paymentHistoryTb").dataTable({ "aaSorting": [[1, 'desc']], "bInfo": false, "bLengthChange": false, "bPaginate": true, "iDisplayLength": 10, "sPaginationType": "full_numbers", "bDestroy": true, "oLanguage": DTUtils.DTLang, "sDom": 'l<"right"><"right inline"p>irt', "sAjaxSource": "api/v1/GetCompanyPaymentHistory", "bServerSide": true, "bProcessing": true, "fnServerData": function (sSource, aoData, fnCallback, oSettings) { $.ajax({ url: sSource, type: "POST", dataType: "json", data: makePaymentHistoryParameter(aoData), timeout: HoGoConst.APITimeout, success: function (data) { if (data.status === "OK") { var json = {"sEcho": data.sEcho, "iTotalDisplayRecords": data.totalResult, "aaData": []}; $.each(data.payment_history, function (key, value) { json.aaData.push({ "payment_date": value.payment_date, "due_date": value.due_date, "name": value.name, "transaction": value.total_transaction, "total_amount": value.total_amount, "id": value.payment_info_id, "currentcy": value.currentcy }); }); } else { fnSessionTimeout(data); } fnCallback(json); } }); }, "fnRowCallback": function (nRow, aData) { var payId = aData.name; var currentcy = aData.currentcy; var paymentName; var currentcyIcon = (currentcy === "yen") ? "¥" : "$"; switch (payId) { case 1: paymentName = (currentcy === "yen") ? i18n.t('payment_package.package1_ja') : i18n.t('payment_package.package1'); break; case 2: paymentName = (currentcy === "yen") ? i18n.t('payment_package.package2_ja') : i18n.t('payment_package.package2'); break; case 3: paymentName = (currentcy === "yen") ? i18n.t('payment_package.package2_ja') : i18n.t('payment_package.package3'); break; case 4: paymentName = (currentcy === "yen") ? i18n.t('payment_package.package2_ja') : i18n.t('payment_package.package4'); break; default: break; } // get payment package name $("td:eq(0)", nRow).html(DateUtils.convertDate(aData.payment_date)); $("td:eq(1)", nRow).html(DateUtils.convertDate(aData.due_date)); $("td:eq(2)", nRow).html("
    " + paymentName + "
    "); $("td:eq(3)", nRow).html("
    " + aData.transaction + "
    "); $("td:eq(4)", nRow).html("
    " + currentcyIcon + aData.total_amount + "
    ") $("td:eq(5)", nRow).html("").bind('click', function () { downloadPaymentReceipt(aData.id); }); nRow.ondblclick = function () { setTimeout(downloadPaymentReceipt(aData.id), 300); }; // nRow.onclick = function () { // DTUtils.fnCheckBoxOnRow(this); // }; }, "aoColumnDefs": [ {'bSortable': false, 'aTargets': [5]} ], "bStateSave": true, "fnStateLoad": function (oSettings) { //Only from RecipientDetail. Load previous state // if ($.cookie('l_p') === 'service.html') { // // var sData = this.oApi._fnReadCookie(oSettings.sCookiePrefix + oSettings.sInstance); // // var oData; // try { // oData = (typeof $.parseJSON === 'function') ? // $.parseJSON(sData) : eval('(' + sData + ')'); // } catch (e) { // oData = null; // } //Set search word on field // if (oData !== null) // if (oData.oSearch.sSearch !== null) // $('#filter').val(oData.oSearch.sSearch); // else // $('#filter').val(''); // else { // //set search null // $('#filter').val(''); // } // return oData; // } else { // return null; // } }, "fnDrawCallback": function (oSettings) { //Draw checkbox // $('#paymentHistoryTb .ck').customInput(); //Set up sort paginate // DTUtils.fnSetUpTableControl(oSettings); //Clear checklist when sorting // if (oSettings.bSorted) { // //Clear checklist // checkedList.splice(0, checkedList.length); // } //Checkbox event switching page // DTUtils.checkboxSwitchPage("paymentHistoryTb", "child", "select_all", checkedList); //Event click child checkbox // $(':checkbox[name=child]').on('click', function () { // // //Update checkedList // DTUtils.checkboxChildSelectEvent(this, "select_all", checkedList); // // //Enable/Disable button // if (checkedList.length > 0) { //// HoGoUtils.enableButton("#btnExport", { //// colorClass: 'orange', //// handler: exportAcessReport //// }); // //Enable these buttons // HoGoUtils.enableButton("#btnDelete", { // colorClass: 'orange', // handler: fnWarningDeleteCompany // }); // } else { // //Disable // HoGoUtils.disableButton("#btnDelete", {colorClass: 'orange'}); // } // }); }, //Map properties from json to view sequentially "aoColumns": [ {"mDataProp": "payment_date"}, {"mDataProp": "due_date"}, {"mDataProp": "name"}, {"mDataProp": "transaction"}, {"mDataProp": "total_amount"}, {"mDataProp": "id"} ] }); } function downloadPaymentReceipt(payInfoID) { var param = {}; param["SessionID"] = UserSession.getSessionID(); param["payInfoID"] = payInfoID; if (UserSession.getAdminObject().adminlang === 'auto-en' || UserSession.getAdminObject().adminlang === 'auto-ja') { param["lang"] = navigator.language.split('-')[0]; } else { param["lang"] = UserSession.getAdminObject().adminlang; } $.fileDownload('api/v1/downloadPaymentReceipt?' + $.param(param), { httpMethod: 'GET' }).then(function () { }, function (errorText) { Modal.showAlert({ title: i18n.t('payment.error.title'), // #translate text: i18n.t('payment.error.text') }); }); } // Change email popup for company admin function showChangeCompanyAdminPopup() { Modal.createModal(2, { title: i18n.t('email.change_email.title'), // Should support multiple langue (i18n.t('modal.change_email_title')) preventClose: true, onLoad: function () { HoGoUtils.validateForm('validationCE', Admin); }, templateUrl: "Template/change_email.html", okCallback: function (modal) { // Call submit form var form = modal.find('form'); form.submit(); changeEmailCompanyAdmin(); } }); } function changeEmailCompanyAdmin() { if (!Admin.fStatus) { return false; } var companyId = HoGoUtils.getParameter()['companyID']; console.log(companyId); if (!companyId) { companyId = ""; } var email = $('#email').val().trim(); return $.ajax({ type: "POST", url: "api/v1/ChangeAdminCompanyEmail", data: {ServiceID: companyId, SessionID: UserSession.getSessionID(), Email: email}, beforeSend: function () { Modal.closeModal(); }, success: function (data) { if (data.status === 'OK') { $("#companyAdmin").html(data.new_email); HoGoUtils.makeNotifyServer({ "msg": i18n.t('email.message.save_success'), "autoClose": true, "time": 400 }); getAdminSessionData(); } else { switch (data.status) { case APIConst.userAlreadyExistStatus: Modal.showAlert({content: i18n.t('email.message.exist_email')}); break; default : Modal.showAlert({content: i18n.t('email.message.error')}); break; } } } }); } function updateCancelPaymentCycle() { return $.ajax({ type: "POST", url: "api/v1/UpdateCancelPaymentCycle", dataType: 'json', data: {"SessionID": UserSession.getSessionID(), "CurrentCancelPayment": cancelPayment}, timeout: HoGoConst.APITimeout, beforeSend: function () { $('#container').find('.loader').show('fast'); HoGoUtils.disableButton('#btnCancelPaymentCycle,#btnDisableCancelPaymentCycle', { colorClass: 'green' }); }, success: function (data) { $('#container').find('.loader').hide('slow'); if (data.status === 'OK') { getAdminSessionData(); } else { // Error HoGoUtils.writeLog(data.status_desc); Modal.showAlert({content: i18n.t('error.unknown')}); } HoGoUtils.enableButton('#btnCancelPaymentCycle,#btnDisableCancelPaymentCycle', { colorClass: 'orange' }); } }); } function _registerChangeLogoListener() { var pName = HoGoUtils.getPageName(); $('#btnChangeLogo').on('click', function () { // show popup change logo Modal.createModal(2, { title: i18n.t('myaccount.account_info.change_logo_title'), preventClose: true, templateUrl: "Template/change_logo_image.html", onLoad: function () { switch (pName) { case 'companydetail.html': UserSession.updateLogoImg('#currentLogo', '', true, HoGoUtils.getParameter()['companyID']); break; case 'distributordetail.html': case 'resellermanagerdetail.html': UserSession.updateLogoImg('#currentLogo', '', true, HoGoUtils.getParameter()['serviceID']); break; default: UserSession.updateLogoImg('#currentLogo'); } HoGoUtils.disableButton('.btn-ok', {colorClass: 'green'}); }, okCallback: function () { _ajaxUploadLogo(); } }); }); var _ajaxUploadLogo = function () { var post = {}; post.SessionID = UserSession.getSessionID(); if (pName === 'companydetail.html') { post.ServiceId = HoGoUtils.getParameter()['companyID']; } else if (pName === 'distributordetail.html') { post.ServiceId = HoGoUtils.getParameter()['serviceID']; } switch (pName) { case 'companydetail.html': post.ServiceId = HoGoUtils.getParameter()['companyID']; break; case 'distributordetail.html': case 'resellermanagerdetail.html': post.ServiceId = HoGoUtils.getParameter()['serviceID']; break; } $.ajaxFileUpload({ url: 'api/v1/UpdateLogoImage', secureuri: false, fileElementId: "inputLogoImg", data: post, dataType: 'json', success: function (data) { if (data.status === "OK") { Modal.closeModal(); HoGoUtils.makeNotifyServer({ "msg": i18n.t('myaccount.account_info.change_logo_success'), "autoClose": true, "time": 400 }); // just update itself if (pName !== 'companydetail.html' && pName !== 'distributordetail.html' && pName !== 'resellermanagerdetail.html') { UserSession.updateLogoImg('img#logoImg', data.file_name); } } else { HoGoUtils.makeNotifyServer({ "msg": i18n.t('myaccount.account_info.change_logo_error'), "autoClose": true, "time": 400 }); } } }); }; // trigger choose logo image $('#inputLogoImg').live('change', function () { var self = this; if (self.files && self.files[0]) { var windowUrl = window.URL || window.webkitURL; var image = new Image(); image.onload = function () { // check valid logo image size if (this.width > HoGoConst.MAX_LOGO_WIDTH || this.height > HoGoConst.MAX_LOGO_HEIGHT) { var mgs = $('#invalidImg').text() .replace('%w', HoGoConst.MAX_LOGO_WIDTH + 'px') .replace('%h', HoGoConst.MAX_LOGO_HEIGHT + 'px'); $('#invalidImg').text(mgs).show(); $('#txtChoose').show(); $('#newLogo').hide(); // disable button update logo HoGoUtils.disableButton('.btn-ok', {colorClass: 'green'}); } else { $('#txtChoose').hide(); $('#newLogo').show(); $('#invalidImg').hide(); // preview image var reader = new FileReader(); reader.onload = function (e) { $('#newLogo').attr('src', e.target.result); }; reader.readAsDataURL(self.files[0]); // enable button update logo HoGoUtils.enableButton( '.btn-ok', { colorClass: 'green', handler: function () { _ajaxUploadLogo(); } }); } }; image.src = windowUrl.createObjectURL(self.files[0]); } }); } return { fStatus: false, doUpdate: function () { updateCompany(); }, doUpdateDistributor: function () { updateDistributor(); }, doUpdateCompanyPayment: function () { updateCompanyPaymentInfo(); }, loadCompanyAdminInfo: function () { getAdminSessionData().done(function () { HoGoUtils.loadPaymentPackage(currency).done(function () { $("input[name=plan][value=" + usagePlan + "]").click(); $('form#validationCom').find(':input').bind('keyup focusout', (function () { hasChangeElement(); })); $("#language").change(function () { hasChangeElement(); }); $("form#validationPay input[name=paymentTerm]").on("change", function () { var newPaymentTerm = $("input[name=paymentTerm]:checked").val(); if (parseInt(newPaymentTerm) === 4) { $("#otherPaymentTerm").prop("disabled", false).val(paymentTermDes); } else { $("#otherPaymentTerm").prop("disabled", true); $("#otherPaymentTerm").val(''); } // check change value hasChangePaymentInfo(); }); // check change value of usage plan $("form#validationPay input[name=plan]").on("change", function () { hasChangePaymentInfo(); }); $('#billingCycle').change(function () { hasChangePaymentInfo(); }); $('form#validationPay').find(':input').bind('keyup focusout', (function () { hasChangePaymentInfo(); })); $("#checkAutoSetNewPayment :checkbox").on('change', function () { hasChangePaymentInfo(); }); // // getCompanyPaymentCurrent(); // getCompanyPaymentHistory(); }); }); }, loadDistributorAdminInfo: function () { HoGoUtils.validateForm('validationDis', Admin); $("#ddBillingCycles").multipleSelect({ selectAll: false, selectAllText: i18n.t('myaccount.billing_cycle.select_all_text'), allSelected: i18n.t('myaccount.billing_cycle.all_selected'), countSelected: i18n.t('myaccount.billing_cycle.count_selected'), noMatchesFound: i18n.t('myaccount.billing_cycle.no_matches_found') }); // Get detail getDistributorDetail().done(function () { $('form#validationDis').find(':input').bind('keyup focusout', (function () { hasChangeElementDis(); })); $("#language, #currentcy, #billingCycle, .cbBilling").change(function () { hasChangeElementDis(); }); $(".ms-drop input:checkbox").change(function () { var self = $(this); if (!self.is(':checked')) { // check must large than 1 billing cycle if ($('#ddBillingCycles').multipleSelect('getSelects').length === 0) { Modal.showAlert({ title: '', content: i18n.t('myaccount.billing_cycle.select_one_mgs'), onClose: function () { // reshow dropdown when close modal setTimeout(function () { $('.ms-choice').click(); }, 100); } }); // set select value before uncheck $('#ddBillingCycles').multipleSelect('setSelects', [self.val()]); } } hasChangeElementDis(); }); // HoGoUtils.copyLink('#d_clip_button'); }); $(window).bind('beforeunload', function () { if (hasChangeElement() === true && redirectable === false) { return "If you leave this page. Your selected data will be discard!"; } }); }, registerChangeLogoListener: function () { _registerChangeLogoListener(); }, init: function () { // change href header console Admin HoGoUtils.makeHrefHeaderAdmin(); updateHeader('${title}', 'Images/icon_admin.png'); if ($('.left-admin-menu li').hasClass('item-user-list-active')) { $('.left-admin-menu li').addClass('item-user-list-deactive'); } var pName = HoGoUtils.getPageName(); HoGoUtils.makeLeftMenuAdmin(); if (pName === 'systemadmininformation.html') { getAdminDetail(); $("#btnChangePassword").on("click", function () { showChangePasswordPopup(); }); } if (pName === 'distributoradmininformation.html') { Admin.loadDistributorAdminInfo(); // Click change password button $("#btnChangePassword").on("click", function () { showChangePasswordPopup(); }); _registerChangeLogoListener(); // init function for change email $("#btnChangeEmailAccount").live('click', function () { showChangeAdminEmailPopup(); }); } if (pName === 'admininformation.html') { HoGoUtils.validateForm('validationCom', Admin); HoGoUtils.validateForm('validationPay', Admin); Admin.loadCompanyAdminInfo(); $('#btnChangePasswordAdminCompany').on("click", function () { showChangePasswordPopupCom(); }); $('#btnCancelPaymentCycle,#btnDisableCancelPaymentCycle').live('click', function () { Modal.showConfirmPopup({ title: '', content: i18n.t('company.change_cancel_payment'), okCallback: function () { updateCancelPaymentCycle(); } }); }); $('.btn-cancel-normal-popup').live('click', function () { Modal.closeModal(); }); $("#btnChangeEmail").live('click', function () { showChangeCompanyAdminPopup(); }); _registerChangeLogoListener(); } } }; }(jQuery)); // // Manage init objects on HoGo app after language has been initilized // var HoGoObjects = (function ($, i18n) { var init = false; var readyLang = false; /** * Init some controls after I18 is ready to use. Using for both Login/Logout state. * @returns {undefined} */ function initStuffAfterReadyLang() { readyLang = true; // Validation language & regrex. https://github.com/posabsolute/jQuery-Validation-Engine $.fn.validationEngineLanguage = function () { }; $.validationEngineLanguage = { newLang: function () { if (i18n.lng() === 'ja') { $.validationEngineLanguage.allRules = { "required": {// Add your regex rules here, you can take telephone as an example "regex": "none", "alertText": "* 必須項目です", "alertTextCheckboxMultiple": "* 選択してください", "alertTextCheckboxe": "* チェックボックスをチェックしてください" }, //Create by tmhao2005 "validGroupEmail": { "regrex": "none", "alertText": "* 無効なメールアドレスか空欄です" }, "requiredInFunction": { "func": function (field, rules, i, options) { return (field.val() === "test") ? true : false; }, "alertText": "* Field must equal test" }, "minSize": { "regex": "none", "alertText": "* ", "alertText2": "文字以上にしてください" }, "groupRequired": { "regex": "none", "alertText": "* You must fill one of the following fields" }, "maxSize": { "regex": "none", "alertText": "* ", "alertText2": "文字以下にしてください" }, "min": { "regex": "none", "alertText": "* ", "alertText2": " 以上の数値にしてください" }, "max": { "regex": "none", "alertText": "* ", "alertText2": " 以下の数値にしてください" }, "past": { "regex": "none", "alertText": "* ", "alertText2": " より過去の日付にしてください" }, "future": { "regex": "none", "alertText": "* ", "alertText2": " より最近の日付にしてください" }, "maxCheckbox": { "regex": "none", "alertText": "* チェックしすぎです" }, "minCheckbox": { "regex": "none", "alertText": "* ", "alertText2": "つ以上チェックしてください" }, "equals": { "regex": "none", "alertText": "* 入力された値が一致しません" }, "creditCard": { "regex": "none", "alertText": "* 無効なクレジットカード番号" }, "phone": { // credit: jquery.h5validate.js / orefalo "regex": /^([\+][0-9]{1,3}([ \.\-])?)?([\(][0-9]{1,6}[\)])?([0-9 \.\-]{1,32})(([A-Za-z \:]{1,11})?[0-9]{1,4}?)$/, "alertText": "* 電話番号が正しくありません" }, "email": { // Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/ //"regex": /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "regex": HoGoUtils.patternEmail, "alertText": "* メールアドレスが正しくありません" }, "integer": { "regex": /^[\-\+]?\d+$/, "alertText": "* 整数を半角で入力してください" }, "number": { // Number, including positive, negative, and floating decimal. credit: orefalo "regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/, "alertText": "* 数値を半角で入力してください" }, "date": { //"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/, "regex": /^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/, // mm/dd/yyyy "alertText": "* 日付は半角で MM/DD/YYYY の形式で入力してください" }, "ipv4": { "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/, "alertText": "* IPアドレスが正しくありません" }, "url": { "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i, "alertText": "* URLが正しくありません" }, "onlyNumberSp": { "regex": /^[0-9\ ]+$/, "alertText": "* 半角数字で入力してください" }, "onlyLetterSp": { "regex": /^[a-zA-Z\ \']+$/, "alertText": "* 半角アルファベットで入力してください" }, "onlyLetterNumber": { "regex": /^[0-9a-zA-Z]+$/, "alertText": "* 半角英数で入力してください" }, // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings "ajaxUserCall": { "url": "ajaxValidateFieldUser", // you may want to pass extra data on the ajax call "extraData": "name=eric", "alertText": "* This user is already taken", "alertTextLoad": "* Validating, please wait" }, "ajaxNameCall": { // remote json service location "url": "ajaxValidateFieldName", // error "alertText": "* This name is already taken", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* This name is available", // speaks by itself "alertTextLoad": "* Validating, please wait" }, "validate2fields": { "alertText": "* 『HELLO』と入力してください" }, "notAllowSpecialCharacters": { "regex": "none", "alertText": "* 記号など特殊文字は使用できません" }, "notAllowSpecialCharactersFolder": { "regex": "none", "alertText": "* フォルダー名には次の文字は使用できません。: /\:*?”<>|" } }; } else { $.validationEngineLanguage.allRules = { "required": {// Add your regex rules here, you can take telephone as an example "regex": "none", "alertText": "* This field is required", "alertTextCheckboxMultiple": "* Please select an option", "alertTextCheckboxe": "* This checkbox is required", "alertTextDateRange": "* Both date range fields are required" }, "dateRange": { "regex": /^(Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-](3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-]\d{4}$/, "alertText": "* Invalid ", "alertText2": "Date Range" }, //Create by tmhao2005 "validGroupEmail": { "regrex": "none", "alertText": "* This field contains an invalid E-mail address or is empty" }, "dateTimeRange": { "regex": /^(Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-](3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-]\d{4}$/, "alertText": "* Invalid ", "alertText2": "Date Time Range" }, "minSize": { "regex": "none", "alertText": "* Minimum ", "alertText2": " characters required" }, "maxSize": { "regex": "none", "alertText": "* Maximum ", "alertText2": " characters allowed" }, "groupRequired": { "regex": "none", "alertText": "* You must fill one of the following fields", "alertTextCheckboxMultiple": "* Please select an option", "alertTextCheckboxe": "* This checkbox is required" }, "min": { "regex": "none", "alertText": "* Minimum value is " }, "max": { "regex": "none", "alertText": "* Maximum value is " }, "past": { "regex": /^(Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-](3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-]\d{4}$/, "alertText": "* Date prior to " }, "future": { "regex": /^(Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-](3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-]\d{4}$/, "alertText": "* Date past " }, "maxCheckbox": { "regex": "none", "alertText": "* Maximum ", "alertText2": " options allowed" }, "minCheckbox": { "regex": "none", "alertText": "* Please select ", "alertText2": " options" }, "equals": { "regex": "none", "alertText": "* Fields do not match" }, "phone": { // credit: jquery.h5validate.js / orefalo "regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/, "alertText": "* Invalid phone number" }, "email": { // Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/ // "regex": /^((([a-z]|\d|[a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))*@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "regex": HoGoUtils.patternEmail, // "regex": /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/, "alertText": "* Invalid email address" }, "integer": { "regex": /^[\-\+]?\d+$/, "alertText": "* Not a valid integer" }, "number": { // Number, including positive, negative, and floating decimal. credit: orefalo //"regex": /^[\-\+]?(([0-9]+)([\.,]([0-9]+))?|([\.,]([0-9]+))?)$/, //integer only // "regex": /^[0-9]{1,2}$/, "regex": /^[0-9]+$/, "alertText": "* Invalid floating decimal number" }, "date": { //"regex": /^(Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-](3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-]\d{4}$/, "regex": /^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/, // mm/dd/yyyy "alertText": "* Invalid date, must be in MM/DD/YYYY format" }, "ipv4": { "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/, "alertText": "* Invalid IP address" }, "url": { "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i, "alertText": "* Invalid URL" }, "onlyNumberSp": { "regex": /^[0-9\ ]+$/, "alertText": "* Numbers only" }, "onlyLetterSp": { "regex": /^[a-zA-Z\ \']+$/, "alertText": "* Letters only" }, "onlyLetterNumber": { "regex": /^[0-9a-zA-Z]+$/, "alertText": "* No special characters allowed" }, "notAllowSpecialCharacters": { "regex": "none", "alertText": "* No special characters allowed" }, "notAllowSpecialCharactersFolder": { "regex": "none", "alertText": "* The folder name can't contain any of the following characters: /\\:*?”<>|" }, // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings "ajaxUserCall": { "url": "ajaxValidateFieldUser", // you may want to pass extra data on the ajax call "extraData": "name=eric", "alertText": "* This user is already taken", "alertTextLoad": "* Validating, please wait" }, "ajaxUserCallPhp": { "url": "ajaxvalidate/ajaxValidateFieldUser.php", // you may want to pass extra data on the ajax call "extraData": "name=eric", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* This username is available", "alertText": "* This user is already taken", "alertTextLoad": "* Validating, please wait" }, "ajaxNameCall": { // remote json service location "url": "ajaxValidateFieldName", // error "alertText": "* This name is already taken", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* This name is available", // speaks by itself "alertTextLoad": "* Validating, please wait" }, "ajaxNameCallPhp": { // remote json service location "url": "ajaxvalidate/ajaxValidateFieldName.php", // error "alertText": "* This name is already taken", // "alertTextOk": "* This name is available", // speaks by itself "alertTextLoad": "* Validating, please wait" }, "ajaxEmailCallPhp": { // remote json service location "url": "ajaxvalidate/ajaxValidateFieldEmail.php", // error "alertText": "* This name is already taken", // speaks by itself "alertTextLoad": "* Validating, please wait" }, "validate2fields": { "alertText": "* Please input HELLO" }, //tls warning:homegrown not fielded "dateFormat": { //"regex": /^(Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-](3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-]\d{4}$/, "regex": /^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/, "alertText": "* Invalid Date" }, //tls warning:homegrown not fielded "dateTimeFormat": { "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/, "alertText": "* Invalid Date or Date Format", "alertText2": "Expected Format: ", "alertText3": "mm/dd/yyyy hh:mm:ss AM|PM or ", "alertText4": "yyyy-mm-dd hh:mm:ss AM|PM" } }; } } }; $.validationEngineLanguage.newLang(); // Custom all class .ck $('.ck,.chkbox,.checkAll').customInput(); // ,input:radio // Should init all login-state object HoGoUtils.validateForm('validation'); // To avoid load resource files after validationEngine (vE) has loaded before $("#validation").validationEngine('updateOptions', {allrules: $.validationEngineLanguage.allRules}); // Datepicker var reg = (i18n.lng() === 'ja') ? 'ja' : 'en-GB'; $.datepicker.setDefaults($.datepicker.regional[reg]); $("input.datepicker").datepicker({//Refer API: http://api.jqueryui.com/datepicker/ autoSize: true, dateFormat: 'mm/dd/yy', //changeMonth: true, //changeYear: true, onSelect: function (dateText, inst) { // var date = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings); // var dateText1 = $.datepicker.formatDate("D, d M yy", date, inst.settings); // date.setDate(date.getDate() + 7); // var dateText2 = $.datepicker.formatDate("D, d M yy", date, inst.settings); } // onClose: function(){ // $(this).trigger('blur'); // } }); var pName = HoGoUtils.getPageName(); if (pName === 'signup.html' || pName === 'adduser.html') { HoGoUtils.renderNameBaseLang(HoGoUtils.getPageName(), i18n.lng()); } // Error notice if (pName === 'errornotice.html') { ErrorNotice.init(); } if (pName === 'onlineview.html') { ViewOnline.init(); } if (pName === 'activationpage.html') { Registration.activateUser(); } // Placeholder $('input').placeholder(); // A default tooltip apply for all element has class ".tooltip" HoGoObjects.initDefaultTooltip(); } /** * Setup object for user login state & render user's information on view * @param sessionData : user's session * @returns {undefined} */ function setupLoginState(sessionData) { if (typeof i18n !== 'undefined') { // Render name/points UserSession.renderNameAndPoint(sessionData); var lang = sessionData.lang; var browserLang = HoGoUtils.detectBrowserLang(); var needForUpdate = true; // If user is not set language setting before. // (=>) First time login -> Update lang setting for this user (background task - Should not notify user of this change) if (typeof lang === 'undefined' || lang === '') { // New lang need for update lang = 'auto-' + browserLang; // Example: auto-en // Using auto as default initI18N(browserLang, true); } else { // Update language for this user if they change their language on browser. This task only works for auto options var lLang = lang.split('-'); if (lLang[0] === 'auto') { if (typeof lLang[1] === 'undefined') { // Check user has changed their browser's language or not. // undefined case???? // Call to update lang = 'auto-' + browserLang; } else { if (lLang[1] !== browserLang) { // Call to update lang = 'auto-' + browserLang; } else needForUpdate = false; } // Using auto as default initI18N(browserLang, true); } else { // Specify language needForUpdate = false; // Init specify language initI18N(UserSession.getLang(), true); } } // Submit as default setting for user if (needForUpdate) { $.ajax({ type: "POST", url: "api/v1/UpdateUserInfo", data: {SessionID: UserSession.getSessionID(), Lang: lang, SendMail: false}, dataType: "json" }); } } } /** * Setup view for logout state * @returns {undefined} */ function setupLogoutState() { initI18N(HoGoUtils.detectBrowserLang(), false); } /** * Init I18N object. Current implementation, we just support for 2 language [en/jp]. If user sets another language, we'll set default (en) * @param {string} lang Lang will be initialized * @param {boolean} isLoginState User is in login state or not * @returns {boolean} */ function initI18N(lang, isLoginState, isAuto) { return i18n.init({ lng: lang, selectorAttr: 'data-hg', fallbackLng: HoGoConst.LANG_DEFAULT, // fallback resGetPath: 'Resource/' + lang + '.common.json', debug: true, preload: ['en', 'ja'] }, function () { // Translate whole webpage $("html").i18n(); // Show $('.wrapper-page-loader').fadeOut("slow"); initStuffAfterReadyLang(); // Login state if (isLoginState) { // Check UserSession is valid or not before do init again. Avoid init logout state if (UserSession.getUserObject() !== null || UserSession.getAdminObject() !== null) { if (!pageInitAlready) { initObjectsLoginState(); } else { if (isAuto) { $("#language").val('auto').selectmenu(); } else $("#language").val(lang).selectmenu(); var pageName = HoGoUtils.getPageName(); BoxIntegrate.init(); if (pageName === "admininformation.html") Admin.loadCompanyAdminInfo(); if (pageName === "distributoradmininformation.html") Admin.loadDistributorAdminInfo(); } } } else { initObjectLogoutState(); } // Warning when user is using IE8 // var browserVersion = ClientInfo.getBrowserVersion(); if (ClientInfo.getBrowser() === 'IE') { // Old browser if (browserVersion === '8.0' || browserVersion === '7.0' || browserVersion === '6.0') { // Warning... setTimeout(function () { Modal.showAlert({ title: i18n.t('notification.warning_old_browser.title'), content: i18n.t('notification.warning_old_browser.content') }); }, 300); } } }); } ; /** * Init specify object for specify page. This function is using for login state * @returns {undefined} */ function initObjectsLoginState() { // Login state if ($('#loginState').length > 0) { //Init class need to be loaded after Internationalization totally loaded. Login state ToolTip.init(); // Notification using only for user if (UserSession.getUserObject() !== null) Notification.init(); } // Get page name var pName = HoGoUtils.getPageName(); // Addressbook if (pName === 'addressbooklist.html' || pName === 'recipientdetail.html' || pName === 'addrecipient.html' || pName === 'recipientdetailadmin.html' || pName === 'addgrouprecipient.html' || pName === 'grouprecipientdetail.html') { AddressBook.init(); } // MyDocument if (pName === 'mydocumentlist.html' || pName === 'mydocumentdetail.html' || pName === 'adddocument.html' || pName === 'mydocumentfolderdetail.html' || pName === 'mydocumentdetailadmin.html' || pName === 'mydocumentfolderdetailadmin.html') { MyDocument.init(); } // History part if (pName === 'history.html') { History.init(); History.makeHistoryList(); } // Package if (pName === 'packagedetaildownload.html' || pName === 'packagedetaildownloadadmin.html') { Package.init(); } // My account if (pName === 'myaccount.html' || pName === 'paymentinfo.html') { require(['https://js.stripe.com/v2/']); if (pName === 'myaccount.html') { MyAccount.init(); BoxIntegrate.init(); } // Payment.init(); } if (pName === 'userlist.html' || pName === 'userdetail.html' || pName === 'adduser.html') { User.init(); } //Admin if (pName === "admininformation.html" || pName === "distributoradmininformation.html" || pName === "systemadmininformation.html") { Admin.init(); } if (pName === 'buypoint.html' || pName === 'buypoint.htm' || pName === 'buypoint') { Payment.loadByPointPage(); } if (pName === 'gmopaymentcompleted.html' || pName === 'gmopaymentcompleted.htm' || pName === 'gmopaymentcompleted') { Payment.completedGMOPayment(); } // Affiliate if (pName === 'affiliatelist.html' || pName === 'affiliatedetail.html' || pName === 'addaffiliate.html' || pName === "reporthistoryaffiliate.html") { Affiliate.init(); } if (pName === 'packagedetaildownloadadmin.html' || pName === 'packagedetaillinkadmin.html') { User.init(); } if (pName === 'service.html' || pName === "addservice.html" || pName === "companydetail.html" || pName === "dashboard.html") { if (pName === 'companydetail.html') { Admin.registerChangeLogoListener(); } CompanyService.init(); } if (pName === 'distributorreports.html') { CompanyReports.init(); } if (pName === 'resellermanagerlist.html' || pName === 'addresellermanager.html' || pName === 'resellermanagerdetail.html') { ResellerAdmin.init(); } if (pName === 'companydashboard.html') { CompanyDashboard.init(); } if (pName === 'distributor.html' || pName === "adddistributor.html" || pName === "distributordetail.html") { if (pName === 'distributordetail.html') { Admin.registerChangeLogoListener(); } Distributor.init(); } if (pName === 'boxgrantaccess.html') { BoxGrantAccess.innit(); } if (pName === 'boxenablesyncnotice.html') { BoxEnableSync.innit(); } //Company Recipient if (pName === 'companyrecipientlist.html' || pName === 'companyrecipientdetail.html' || pName === 'addcompanyrecipient.html') { CompanyRecipient.init(); } if (pName === 'companyreport.html') { CompanyUserReports.init(); } if (pName === 'companyhistory.html') { CompanyHistory.init(); } // innit company dashboard if (pName === "dashboardcompany.html" || pName === "companyreport.html" || pName === "companyhistory.html") { HoGoUtils.makeLeftMenuAdmin(); } // Navi manage HoGoUtils.manageActionsOnPage(pName); // Already init pageInitAlready = true; } /** * Init object related logout state & some controls using for both state * @returns {undefined} */ function initObjectLogoutState() { // Login page if ($('#login').length > 0) { Login.init(); //require(['https://apis.google.com/js/client.js']); } var pName = HoGoUtils.getPageName(); if (pName === 'downloadpdf.html') { HoGoDownload.init(); } if (pName === 'signup.html' || pName === 'referral.html') Registration.init(); require(['https://apis.google.com/js/client.js']); if (pName === 'signupcom.html') { SignupCompany.init(); } } return { isLangReady: function () { return readyLang; }, /** * Init entire HoGo's object * @returns {undefined} */ init: function () { if (init === false) { /**================== CUSTOM OUR STYLE ============== **/ // Selectmenu $('select').not("select.chzn-select,select[multiple],select#box1Storage,select#box2Storage,select#country,select#state").selectmenu({ // style: 'popup' }); // Default class for submit form $('a.submit_form').on('click', function () { var form_id = $(this).parents('form').attr('id'); $("#" + form_id).submit(); }); // Mask input {datepicker / numberphone} $('.phone').mask('(999) 999-9999'); // $('.datepicker').mask('99/99/9999'); // mm/dd/yy // Logout $('#logoutLink').click(function () { $.ajax({ type: "POST", data: {SessionID: UserSession.getSessionID()}, timeout: HoGoConst.APITimeout, url: "api/v1/Logout", dataType: "json", success: function () { if (UserSession.getUserObject()) { UserSession.clearSessionID(); $.cookie('boxToken', ""); $.cookie("c_folderId", null); window.location.href = "login"; } else { UserSession.clearSessionID(); $.cookie('boxToken', ""); window.location.href = "admin/login"; } } }); }); $('.wrapper-profile a').hover( function () { $(this).find('i').removeClass('bg-bt-profile-setting-off').addClass('bg-bt-profile-setting-on'); }, function () { $(this).find('i').removeClass('bg-bt-profile-setting-on').addClass('bg-bt-profile-setting-off'); }); // Login state if ($('#loginState').length > 0 || $('#login').length > 0) { // // CHECKING USER SESSION // // Get user session var chain = UserSession.getSessionData().pipe(function (sessionData) { if (sessionData.status === 'OK') { if (HoGoUtils.getPageName() === 'login.html' || HoGoUtils.getPageName() === 'administrator.html') { Login.fnGoLandingPage(sessionData); } else { // Get datatable information $.getJSON('Resource/' + UserSession.getLang() + '.datatable.json', function (data) { // Set value to DTUtils DTUtils.DTLang = data; // User login state setupLoginState(sessionData); }); } } else { return UserSession.getAdminSessionData(); } }); // Admin data chain.done(function (data) { if (typeof data !== 'undefined') { if (data.status === 'OK') { var name = ""; var lang; var lLang = data.adminlang.split('-'); if (lLang[0] === 'auto' || data.adminlang === '') lang = HoGoUtils.detectBrowserLang(); else lang = data.adminlang; if (lang === 'ja') { name = data.last_name + " " + data.first_name + " 様"; } else { name = data.first_name + " " + data.last_name; } // Render admin's information $('#profileLink').text(name); //Redirect to admin if at login page if (HoGoUtils.getPageName() === 'administrator.html' || HoGoUtils.getPageName() === 'login.html') { switch (parseInt(data.service_level)) { case HoGoConst.SYSTEM_ADMIN: window.location.href = serverHostAPI + 'Distributor'; break; case HoGoConst.COMPANY_ADMIN: window.location.href = serverHostAPI + 'UserList'; break; case HoGoConst.DISTRIBUTOR: window.location.href = serverHostAPI + 'Service'; break; default : break; } } else { var lang = data.adminlang; var browserLang = HoGoUtils.detectBrowserLang(); var needForUpdate = true; // If user is not set language setting before. // (=>) First time login -> Update lang setting for this user (background task - Should not notify user of this change) if (typeof lang === 'undefined' || lang === '') { // New lang need for update lang = 'auto-' + browserLang; // Example: auto-en // Using auto as default initI18N(browserLang, true); } else { // Update language for this user if they change their language on browser. This task only works for auto options var lLang = lang.split('-'); if (lLang[0] === 'auto') { if (typeof lLang[1] === 'undefined') { // Check user has changed their browser's language or not. // undefined case???? // Call to update lang = 'auto-' + browserLang; } else { if (lLang[1] !== browserLang) { // Call to update lang = 'auto-' + browserLang; } else needForUpdate = false; } // Using auto as default // initI18N(browserLang, true); $.getJSON('Resource/' + browserLang + '.datatable.json', function (data) { DTUtils.DTLang = data; // Admin login state - Using default language initI18N(browserLang, true); }); } else { // Specify language needForUpdate = false; // Init specify language // initI18N(UserSession.getLang(), true); $.getJSON('Resource/' + UserSession.getAdminLang() + '.datatable.json', function (data) { DTUtils.DTLang = data; // Admin login state - Using default language initI18N(UserSession.getAdminLang(), true); }); } } } // Render top bar color switch (parseInt(data.service_level)) { case HoGoConst.COMPANY_ADMIN: $(".logo-admin-console").css({"background": "url(Images/menu/company-topbar.jpg) repeat"}); break; case HoGoConst.DISTRIBUTOR: $(".logo-admin-console").css({"background": "url(Images/menu/reseller-topbar.jpg) repeat"}); break; default : break; } } else { //Redirect to login if trying to go inside if ($('#loginState').length > 0) window.location.href = 'admin/login'; else // Logout state setupLogoutState(); } } }); } else { // Logout state // Logout state setupLogoutState(); } init = true; return init; } else { return init; } }, /** * Re-init language & HoGo's objects * @param {type} lang * @returns {undefined} */ translateAndInitLoginState: function (lang, isAuto) { initI18N(lang, true, isAuto); }, initDefaultTooltip: function () { // Tooltipster $('.tooltip').tooltipster({interactive: true, theme: 'hg-theme'}); }, translateAndInitLogoutState: function (lang) { initI18N(lang, false); } }; }(jQuery, i18n)); // // Starting objects after DOM get ready // $(function () { // Display while loading if ($('.wrapper-page-loader').length === 0) $('
    ').appendTo('body'); // Once DOM is ready, we will show body again, we don't want user see anything when DOM is not ready so that we set CSS (reset - display: none) HoGoObjects.init(); }); //Get base name from file function basename(path, suffix) { var b = path.replace(/^.*[\/\\]/g, ''); if (typeof (suffix) === 'string' && b.substr(b.length - suffix.length) === suffix) { b = b.substr(0, b.length - suffix.length); } return b; } /** * Determine action when user's session timeout * @param {string} data : Data return from API * @param {string} msg (optional): Error text will be shown in case of showing popup * @param {string} pageRedirect (optional) : Page name will be redirected to if there's not case of timeout */ function fnSessionTimeout(data, msg, pageRedirect) { if (data.status === APIConst.sessionIdNotFound || data.status === APIConst.adminSessionRequired) { window.onbeforeunload = null; window.location.href = 'login'; } else { if (typeof pageRedirect !== 'undefined') { window.location.href = pageRedirect; } else { if (typeof msg === 'undefined' || msg === null || msg === '') { HoGoUtils.writeLog(data.status_desc); Modal.showAlert({content: i18n.t('error.unknown')}); } else { Modal.showAlert({content: msg}); } } } } /** * Collect required data send to server in recipient/document history list table * @param {object}: aoData datatable object contains data to send out * @param {String}: recipientID recipient ID * @param {String}: documentID document ID * @return {object} */ function historyRecipientDocumentPostData(aoData, recipientID, documentID) { var post = {}; var colSort; var sortType; $.each(aoData, function (x, y) { if (y.name === "sEcho") { post["sEcho"] = y.value; } if (y.name === "iDisplayStart") { post["DisplayStart"] = y.value; } if (y.name === "iDisplayLength") { post["DisplayLength"] = y.value; } if (y.name === "iSortCol_0") { colSort = y.value; } if (y.name === "sSortDir_0") { sortType = y.value; } }); switch (colSort) { case 0: if (sortType === "asc") post["SortType"] = 1; else post["SortType"] = 2; break; // case 1: // if (sortType === "asc") // post["SortType"] = 3; // else // post["SortType"] = 4; // break; // case 2: // if (sortType === "asc") // post["SortType"] = 5; // else // post["SortType"] = 6; // break; } if (documentID === "undefined") post["RecipientID"] = recipientID; else post["DocumentID"] = documentID; post["SessionID"] = UserSession.getSessionID(); post["UserID"] = HoGoUtils.getParameter()["userID"]; return post; } /** * Get returnPath from sent page */ function getReturnPath() { var hashes = window.location.href.split('returnPath'); var url = hashes[1].substr(1, hashes[1].length); return url; } /* * This function is used to convert date to HoGo format date MMM/dd/yyyy * @param {String}: date string date * @return {String}: Date string with format {MMM/dd/yyyy} */ function convertDate(date) { var months = new Array( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); if (date !== undefined) { var dateObj = new Date(date); if (Object.prototype.toString.call(dateObj) === "[object Date]") { if (isNaN(dateObj.getTime())) { return date; } else { return months[dateObj.getMonth()] + "/" + ("0" + dateObj.getDate()).slice(-2) + "/" + dateObj.getFullYear(); } } else { //Not format date object return "N/A"; } } else { return "N/A"; } } /** * Convert date object to string format date (MM/dd/yyyy) * @param {Date}: dateObj Input date * @return {string} string format date (MM/dd/yyyy) */ function convertFromDateObject(dateObj) { if (Object.prototype.toString.call(dateObj) === "[object Date]") { return ("00" + (dateObj.getMonth() + 1)).slice(-2) + "/" + ("00" + dateObj.getDate()).slice(-2) + "/" + dateObj.getFullYear(); } else { return "N/A"; } } /* Convert cent to $ or free * @param {number} cent The cent number * @return {string} $ */ function convertCentToUSD(cent, currency) { if (cent !== undefined) { if (cent === 0) return "FREE"; else { if (currency === 'YEN') { return "¥" + cent; } else { var usd = "$" + cent / 100; return usd; } } } else return ""; } /** * This function is used to convert date from MMM/dd/yyyy to normal format date * @param {String}: date string date * @returns {String}: date with format {MM/dd/yyyy} */ function convertToDate(date) { //Mar/31/2014 to 31/03/2014 var d = {}; d = date.split("/"); var months = {}; months["Jan"] = "01"; months["Feb"] = "02"; months["Mar"] = "03"; months["Apr"] = "04"; months["May"] = "05"; months["Jun"] = "06"; months["Jul"] = "07"; months["Aug"] = "08"; months["Sep"] = "09"; months["Oct"] = "10"; months["Nov"] = "11"; months["Dec"] = "12"; return d[1] + "/" + months[d[0]] + "/" + d[2]; } /** * Calculate the days before * @param {number}: days Number of days will be decreased * @return {object} Date */ function calculateDateBefore(days) { var d = new Date(); return convertDate(new Date(d.getFullYear(), d.getMonth(), d.getDate() - days, d.getHours(), d.getMinutes(), d.getSeconds())); } /** * This function is used to convert status of address book history from number to text * @param {int}: statusNumber send method status */ function convertSentMethodToText(statusNumber) { switch (statusNumber) { case 1: return i18n.t('history.method.sent_method_download'); break; case 2: return i18n.t('history.method.sent_method_online'); break; case 3: return i18n.t('history.method.send_method_specify'); break; case 4: return i18n.t('history.method.send_method_anonymous'); break; default: return "Unknown"; break; } } /** * This function is used to display loading indicator on view when page is loaded * @param {String}: idElement element ID created * @param {String}: parentSelector parent contains idElement */ function appendLoading(idElement, parentSelector) { $(parentSelector).append(""); $("#" + idElement).center(); } /** * This function is used to display loading indicator on view when page is loaded * @param {String}: idElement element ID created * @param {String}: parentSelector parent contains idElement * @param {String}: message message show when loading * @param {boolean}: disable or not background. It's optional param */ function appendLoadingWithText(idElement, parentSelector, message, disable) { if ($(parentSelector).find('#' + idElement).length === 0) { var p = "
    " + message + "
    "; //$(parentSelector).append(p); if (disable !== undefined && disable !== null) { var x = $('
    ').append(p); $(parentSelector).append(x); } else { // No background overplay $(parentSelector).append(p); } $("#" + idElement).show(); } else { $('#' + idElement).show(); } } /* * This function is used to remove indicator when processing stopped * @param {String}: idLoading id is removed from page */ function removeLoading(idLoading) { //Remove overplay if ($(".hogo-bg-overlay").length > 0) $(".hogo-bg-overlay").remove(); $("#" + idLoading).remove(); } /** * Create iframe * @param {String}: src source iframe * @param {int}: width witdh iframe * @param {int}: height heigh iframe * @param {String}: parentContainIframeID the ID of parent contains this iframe */ function createIframe(src, width, height, parentContainIframeID) { var i = document.createElement("iframe"); i.src = src; i.scrolling = "no"; i.frameborder = "0"; i.width = width; i.height = height; document.getElementById(parentContainIframeID).appendChild(i); return i; } // Check and replace href www.hogodoc.com to www.hogodoc.com/ja/ if language is japanese function replaceURLJapanseVersion() { var lang = window.navigator.browserLanguage || window.navigator.language; var language = lang.substr(0, 2); switch (language) { case 'ja': $('a').each(function () { var url = this.href; if (url.indexOf("www.hogodoc.com") > 0 && url.indexOf("login") < 0 && url.indexOf("signup") < 0 && url.indexOf("forgotPassword") < 0) { url = url.replace('www.hogodoc.com', 'www.hogodoc.com/ja'); $(this).attr('href', url); } }); break; default: break; } } /** * Convert file size from byte * @param {type} bytes * @returns {String} */ function bytesToSize(bytes) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; if (bytes === 0) return 'n/a'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); if (i === 0) return bytes + ' ' + sizes[i]; return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i]; } ; Object.size = function (obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; (function ($) { $(document).ajaxSend(function (event, jqxhr, settings) { var url = settings.url; var newUrl = serverHostAPI + url; settings.url = newUrl; // Try to avoid json string contain control characters like tab or new line if (settings.dataType === "json") { settings.dataFilter = function (response, type) { var original = response; try { var response = JSON.stringify(response); response = response.replace(/\\t/g, "\\t").replace(/\\n/g, "\\n"); var normalize = JSON.parse(response); return normalize; } catch (e) { return original; } }; } }); }(jQuery));