//
// 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 = '';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function (id, fileElementId, data) {
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('');
if (data)
{
for (var i in data)
{
jQuery('').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function (s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if (s.global && !jQuery.active++)
{
jQuery.event.trigger("ajaxStart");
}
var requestDone = false;
// Create the request object
var xml = {}
if (s.global)
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function (isTimeout)
{
var io = document.getElementById(frameId);
try
{
if (io.contentWindow)
{
xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
} else if (io.contentDocument)
{
xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
}
} catch (e)
{
jQuery.handleError(s, xml, null, e);
}
if (xml || isTimeout === "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout !== "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if (status !== "error")
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData(xml, s.dataType);
// If a local callback was specified, fire it and pass it the data
if (s.success)
s.success(data, status);
// Fire the global callback
if (s.global)
jQuery.event.trigger("ajaxSuccess", [xml, s]);
} else
jQuery.handleError(s, xml, status);
} catch (e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if (s.global)
jQuery.event.trigger("ajaxComplete", [xml, s]);
// Handle the global AJAX counter
if (s.global && !--jQuery.active)
jQuery.event.trigger("ajaxStop");
// Process result
if (s.complete)
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function ()
{
try
{
jQuery(io).remove();
jQuery(form).remove();
} catch (e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if (s.timeout > 0)
{
setTimeout(function () {
// Check to see if the request is still happening
if (!requestDone)
uploadCallback("timeout");
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if (form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
} else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch (e)
{
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback);
return {abort: function () {
}};
},
uploadHttpData: function (r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if (type == "script")
jQuery.globalEval(data);
// Get the JavaScript object, if JSON is used.
if (type == "json")
eval("data = " + data);
// evaluate scripts within html
if (type == "html")
jQuery("
").html(data).evalScripts();
return data;
},
handleError: function (s, xhr, status, e) {
// If a local callback was specified, fire it
if (s.error) {
s.error.call(s.context || window, xhr, status, e);
}
// Fire the global callback
if (s.global) {
(s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
}
}
});
//
// The plugin code using drag/drop event. Avoid calling many times when drag/drop elements
//
$.fn.draghover = function (options) {
return this.each(function () {
var collection = $(),
self = $(this);
self.on('dragover', function (e) {
if (collection.length === 0) {
self.trigger('draghoverstart');
}
// console.log( e.type )
// Make sure this list has only DOM at a time
if (collection.length > 1)
collection = $();
// if ( collection.index( e.target ) === -1 )
collection = collection.add(e.target);
});
self.on('dragleave drop', function (e) {
if (collection.index(e.target) === -1) {
// Clear collection
collection = $();
} else {
collection = collection.not(e.target);
}
// wait if mouseover on another element
var timeout = window.setTimeout(function () {
if (collection.length === 0) {
self.trigger('draghoverend');
}
// clear
window.clearTimeout(timeout);
}, 300);
});
$(window).on('dragenter', function (e) {
e.preventDefault();
});
});
};
//
// A small plugin jQuery to serialize to json
//
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
//
// Overlay mask
//
$.fn.overlayMask = function (opt) {
var setting = opt || {};
var defaults = {
top: 50,
text: "Checking..."
};
// Action and options
var action, options;
// Get action
if (typeof setting !== 'object') {
// Action
action = setting;
} else {
options = $.extend(defaults, setting);
}
return this.each(function () {
// Create overlay mask
var anchor = $(this);
if (options) {
//
if ($('body').find('.hogo-bg-overlay-action').length === 0) {
$('').appendTo(anchor);
}
} else {
if (action === 'destroy') {
// Remove overlay
$('body').find('.hogo-bg-overlay-action').remove();
}
}
});
};
}(jQuery));
//
// Ajax Queue
//
(function ($) {
// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});
$.ajaxQueue = function (ajaxOpts) {
var jqXHR,
dfd = $.Deferred(),
promise = dfd.promise();
// queue our ajax request
ajaxQueue.queue(doRequest);
// add the abort method
promise.abort = function (statusText) {
// proxy abort to the jqXHR if it is active
if (jqXHR) {
return jqXHR.abort(statusText);
}
// if there wasn't already a jqXHR we need to remove from queue
var queue = ajaxQueue.queue(),
index = $.inArray(doRequest, queue);
if (index > -1) {
queue.splice(index, 1);
}
// and then reject the deferred
dfd.rejectWith(ajaxOpts.context || ajaxOpts, [promise, statusText, ""]);
return promise;
};
// run the actual query
function doRequest(next) {
jqXHR = $.ajax(ajaxOpts)
.done(dfd.resolve)
.fail(dfd.reject)
.then(next, next);
}
return promise;
};
})(jQuery);
//
// Get client information such as their browser type, version browser...
//
var ClientInfo = (function (window) {
// Here's some method checking client info from BE
return {
getOS: function (params) {
// navigatorオブジェクト(テストのため入れ替えられるようにしてあります)
var nav = navigator;
// パラメータ処理
if (params == undefined) {
params = {};
}
var pack_ios = params.pack_ios ? true : false;
if (params.navigator != undefined) {
nav = params.navigator;
}
// OS判定
if (nav.platform.indexOf('Win') != -1) {
return "Windows";
} else if (nav.platform.indexOf('Mac') != -1) {
return "Mac";
} else if (nav.platform.indexOf('iPhone') != -1 || nav.appVersion.indexOf('iPhone') != -1) {
return pack_ios ? "iOS" : "iPhone";
} else if (nav.platform.indexOf('iPad') != -1 || nav.appVersion.indexOf('iPad') != -1) {
return pack_ios ? "iOS" : "iPad";
} else if (nav.platform.indexOf('iPod') != -1 || nav.appVersion.indexOf('iPod') != -1) {
return pack_ios ? "iOS" : "iPod";
} else if (nav.appVersion.indexOf('Android') != -1) {
return "Android";
}
return "Other";
},
getOSVersion: function (params) {
// navigatorオブジェクト(テストのため入れ替えられるようにしてあります)
var nav = navigator;
var version = "";
// パラメータ処理
if (params === undefined) {
params = {};
}
var unique_name = params.unique_name ? true : false;
if (params.navigator !== undefined) {
nav = params.navigator;
}
// バージョン取得
var _ver = null;
switch (ClientInfo.getOS(params)) {
// Windows
case "Windows":
_ver = nav.oscpu ?
nav.oscpu.match(/Windows NT ((\d+\.?)+)/) : // Firefox
nav.appVersion.match(/Windows NT ((\d+\.?)+)/); // IE, Safari, Chrome, Opera
if (_ver) {
version = _ver[1];
}
// 名称に変換
if (unique_name) {
switch (version) {
case "6.3":
version = "8.1";
break;
case "6.2":
version = "8";
break;
case "6.1":
version = "7";
break;
case "6.0":
version = "Vista";
break;
case "5.1":
version = "XP";
break;
case "5.0":
version = "2000";
break;
}
}
break;
// Mac
case "Mac":
if (window.opera) {
_ver = nav.appVersion.match(/Intel Mac OS X ((\d+\.?)+)/); // Opera
} else {
_ver = nav.oscpu ?
nav.oscpu.match(/Intel Mac OS X ((\d+\.?)+)/) : // Firefox
nav.appVersion.match(/Intel Mac OS X ((\d+_?)+)/); // Safari, Chrome
}
if (_ver) {
version = _ver[1].replace(/_/g, ".");
}
break;
// Android
case "Android":
_ver = nav.appVersion.match(/Android ((\d+\.?)+)/);
if (_ver) {
version = _ver[1];
}
break;
// iOS
case "iPhone":
case "iPod":
_ver = nav.appVersion.match(/iPhone OS ((\d+_?)+)/);
if (_ver) {
version = _ver[1].replace(/_/g, ".");
}
break;
case "iPad":
_ver = nav.appVersion.match(/OS ((\d+_?)+)/);
if (_ver) {
version = _ver[1].replace(/_/g, ".");
}
break;
}
return version;
},
getBrowser: function (params) {
// navigatorオブジェクト(テストのため入れ替えられるようにしてあります)
var nav = navigator;
// パラメータ処理
if (params == undefined) {
params = {};
}
if (params.navigator != undefined) {
nav = params.navigator;
}
// "appName" include "Internet Explorer"
if (nav.appName.indexOf("Internet Explorer") != -1 || nav.appVersion.match(/rv:((\d+\.?)+)/) != null) {
if (nav.cpuClass == "x64") {
return "IE64";
}
return "IE";
}
// "appName" include "Opera"
else if (nav.appName.indexOf("Opera") != -1) {
if (nav.appVersion.indexOf("Opera Mini") != -1) {
return "Opera Mini";
} else if (nav.appVersion.indexOf("Opera Mobi") != -1) {
return "Opera Mobile";
} else {
return "Opera";
}
}
// "appName" include "Netscape"
else if (nav.appName == "Netscape") {
// for minor browsers
// *Thease browser check first bcause many browsers have same UserAgent for Chrome, Firefox, Safari.
if (nav.appVersion.indexOf("iLunascape") != -1) {
return "iLunascape";
} else if (nav.appVersion.indexOf("Mercury") != -1) {
return "Mercury";
}
// Google Chrome
// *The string "CriOS" used on the iOS.
else if (nav.appVersion.indexOf("Chrome") != -1 || nav.appVersion.indexOf("CriOS") != -1) {
return "Chrome";
}
// Firefox
else if (nav.userAgent.indexOf("Firefox") != -1) {
return "Firefox";
}
// Safari
// *Most browsers matched this.
else if (nav.appVersion.indexOf("Safari") != -1) {
return "Safari";
}
// 旧バージョンの beobj.js と互換性を取るための判定
else if (nav.vendor.indexOf("Apple") != -1) {
return "Safari";
}
}
return "Other";
},
getBrowserVersion: function (params) {
// navigatorオブジェクト(テストのため入れ替えられるようにしてあります)
var nav = navigator;
// パラメータ処理
if (params === undefined) {
params = {};
}
if (params.navigator != undefined) {
nav = params.navigator;
}
var version = "";
switch (ClientInfo.getBrowser( {
navigator: nav})) {
case "IE":
case "IE64":
var _ver = nav.appVersion.match(/MSIE ((\d+\.?)+)/); // IE10以下の場合
if (_ver == null) {
_ver = nav.appVersion.match(/rv:((\d+\.?)+)/)
} // IE11の場合
if (_ver) {
version = _ver[1];
}
break;
case "Opera":
var _ver = nav.userAgent.match(/Version\/((\d+\.?)+)/);
if (_ver) {
version = _ver[1];
}
break;
case "Safari":
var _ver = nav.appVersion.match(/Version\/((\d+\.?)+)/);
if (_ver) {
version = _ver[1];
}
break;
case "Chrome":
var _ver = nav.appVersion.match(/Chrome\/((\d+\.?)+)/);
if (_ver) {
version = _ver[1];
}
break;
case "Firefox":
var _ver = nav.userAgent.match(/Firefox\/((\d+\.?)+)/);
if (_ver) {
version = _ver[1];
}
break;
}
return version;
},
getAdobeFlashPlayerVersion: function () {
var ver = "";
navigator.plugins.refresh(false);
if (ClientInfo.getBrowser() === "IE") {
try {
var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
ver = axo.GetVariable("$version").split(" ")[1].split(",").join(".");
} catch (e) {
}
} else {
navigator.plugins.refresh(false);
var x = navigator.plugins["Shockwave Flash"];
if (x && x.description) {
ver = x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".");
}
}
return ver;
},
checkFlashPlayerInstall: function () {
var flashPlayerVer = ClientInfo.getAdobeFlashPlayerVersion();
if (flashPlayerVer.length === 0) {
return false;
} else
return true;
}
};
}(this));
//
// Create user and activate user
//
var Registration = (function ($) {
/* Using for referral page */
var referralCode = null;
//
// Bind or unbind event on controls related to referral fucntions
//
function registerReferralControlsEvent(bind, userId) {
if (bind) {
// Enable button first
HoGoUtils.enableButton('#btnOK', {colorClass: 'green'});
// Register event
$('#btnOK').bind('click', function () {
// Register click button
referralPoints(userId);
});
// Enter event
$('#emailReferral').bind('keypress', function (e) {
var k = e.which ? e.which : e.keyCode;
if (k === 13) {
$(this).blur();
referralPoints(userId);
}
});
} else {
// Unbind
HoGoUtils.disableButton('#btnOK', {colorClass: 'green'});
$('#emailReferral').unbind('keypress');
}
}
//
// Do referral
//
function referralPoints(userId) {
// Call submit to see error fields
$('form#validationSU').submit();
// Invalid value
if (!formStatus)
return;
// All valid
// Disable referral button
registerReferralControlsEvent(false);
return $.post('api/v1/UpdateReferralUser', {EmailReferral: $('#emailReferral').val(), UserID: userId}, function (rData) {
if (rData.status === 'OK') {
Modal.showAlert({
title: i18n.t('registration.message.referral_success.title'),
content: i18n.t('registration.message.referral_success.content')
});
} else {
// Enable button submit again
registerReferralControlsEvent(true, userId);
// Enable button
if (rData.status === APIConst.USER_NOT_FOUND) {
Modal.showAlert({
title: i18n.t('registration.message.ref_user_not_found.title'),
content: i18n.t('registration.message.ref_user_not_found.content')
});
} else if (rData.status === APIConst.INVALID_EMAIL) {
Modal.showAlert({
title: i18n.t('registration.message.invalid_email.title'),
content: i18n.t('registration.message.invalid_email.content')
});
} else {
Modal.showAlert({content: i18n.t('error.unknown')});
}
}
});
}
/**
* Create user method
* @returns {jqXHR|undefined}
*/
function createUser() {
// Checking form to get formStatus accuracy value
$('form#validation').submit();
if (!formStatus)
return;
var postData = {};
// set current timeZone for user signUp
var date = new Date();
var timezone = -date.getTimezoneOffset() / 60;
postData["TimeZone"] = timezone;
postData["ServiceID"] = HoGoConst.SERVICE_ID;
postData["ServiceKey"] = HoGoConst.SERVICE_KEY;
postData["EmailAddress"] = $('#email').val();
var passHash = $.trim($('#password').val());
postData["Password"] = HoGoUtils.MD5(passHash);
postData["FirstName"] = $('#firstname').val();
postData["MiddleName"] = $('#middlename').val();
postData["LastName"] = $('#lastname').val();
postData["Company"] = $('#company').val();
postData["Lang"] = 'auto-' + HoGoUtils.detectBrowserLang(); //i18n.lng();
if (HoGoUtils.getPageName() === 'referral.html')
postData['ReferralCode'] = referralCode;
return $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/CreateUser",
beforeSend: function () {
// Processing
// Disable submit button
HoGoUtils.disableButton('#btnSubmit', {colorClass: 'green'});
HoGoUtils.disableButton('#btnSignupGoogle', {colorClass: 'green'});
},
data: postData,
dataType: "json",
success: function (data) {
if (data.status === 'OK') {
// Showing with animation
$('.signup').remove();
$('.send-mail-signup').hide().removeClass('hid').fadeIn('slow');
// Register form referral
// Validation referral form
HoGoUtils.validateForm('validationSU');
//
// Event referral button
//
registerReferralControlsEvent(true, data.user_id);
} else {
// Enable button
HoGoUtils.enableButton('#btnSubmit', {
colorClass: 'green',
isSubmitForm: true, // Validate form again. If it requires onsubmit attribute. Otherwise, must set handler opt
handler: createUser //
});
HoGoUtils.enableButton('#btnSignupGoogle', {
colorClass: 'green',
isSubmitForm: true,
handler: signupGoogle
});
if (data.status === APIConst.userAlreadyExistStatus) {
Modal.showAlert({
title: i18n.t('registration.message.exist_email.title'),
content: i18n.t('registration.message.exist_email.content')
});
} else {
Modal.showAlert({content: i18n.t('error.unknown')});
}
}
}
});
}
function signupGoogle() {
HoGoUtils.disableButton('#btnSubmit', {colorClass: 'green'});
HoGoUtils.disableButton('#btnSignupGoogle', {colorClass: 'green'});
Login.authWithGoogle();
}
/**
* Get affiliate info
* @returns {jqXHR}
*/
function getAffiliateByCode() {
referralCode = HoGoUtils.getParameter()['code'];
return $.ajax({
type: 'POST',
url: 'api/v1/GetAffiliateInfo',
data: {ReferralCode: referralCode},
timeout: HoGoConst.APITimeout
});
}
return {
init: function () {
var pName = HoGoUtils.getPageName();
if (pName === 'referral.html') {
var email = decodeURIComponent(HoGoUtils.getParameter()['mail']);
if (email !== 'undefined' && HoGoUtils.isValidEmail(email)) {
$('#email').val(email);
$('#email').attr('readonly', true).css('background-color', 'rgb(235, 235, 228)');
}
getAffiliateByCode().done(function (data) {
$('#affName').html(data.affiliate_detail.name);
$("#affLogo").attr("src", "api/v1/GetAffiliateThumbnail?FileID=" + data.affiliate_detail.logo);
});
}
// Submit event
$('#btnSubmit').on('click', function () {
createUser();
});
// Validation
HoGoUtils.validateForm('validationSU');
$('#btnSignupGoogle').on('click', function () {
signupGoogle();
});
// $('#emailReferral').change(function(){
// if ($('#emailReferral').val() !== "") {
// HoGoUtils.enableButton("#btnOK", {colorClass: 'green', isSubmitForm: true});
// return true;
// }
// else {
// HoGoUtils.disableButton("#btnOK", {colorClass: 'green'});
// return false;
// }
// });
},
activateUser: function () {
var activationCode = HoGoUtils.getParameter()["ac"];
//Activate
return $.ajax({
url: 'api/v1/ActivateUser',
type: 'POST',
timeout: HoGoConst.APITimeout,
data: {"ActivationCode": activationCode},
dataType: "json",
success: function (data) {
if (data.status === 'OK') {
// Render view
$('#failActivate').addClass('hid');
// Remove img error
$('.img-error').addClass('hid');
} else {
$('#activeSignUp').addClass('hid');
switch (data.status) {
case APIConst.ACTIVATION_CODE_EXPIRED: // Expire link
$('.invalidLink').addClass('hid');
break;
default: // Invalid link
$('.expiredLink').addClass('hid');
break;
}
}
$('#subpage_one').show('fast');
}
});
}
};
}(jQuery));
//
// User session management
//
var UserSession = (function ($) {
/* User's model */
var user = null;
/* Admin model */
var admin = null;
var login = false;
return {
/* Session key store at Cookie */
sessionKey: "_sessionToken",
/* Login or not */
isLogin: function () {
return login;
},
/* Complete callback for both user & admin */
fnGetSessionComplete: null,
/* BeforeSend callback for both user & admin */
fnGetSessionBeforeSend: null,
/* Error callback for both user & admin */
fnGetSessionError: null,
/* PayPal URL key store to cookie */
paypalReturnURL: "_paypalReturnURL",
getUserObject: function () {
return user;
},
getAdminObject: function () {
return admin;
},
/**
* Get user's session data
* @returns {jqXHR}
*/
getSessionData: function () {
var $thisObj = this;
// Call API
return $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/GetSession",
data: {'SessionID': UserSession.getSessionID()},
dataType: "json",
beforeSend: function () {
if ($thisObj.fnGetSessionBeforeSend !== null)
$thisObj.fnGetSessionBeforeSend.call(null);
},
success: function (data) {
// console.log("success..", data);
if (data.status === "OK") {
login = true;
user = data;
UserSession.updateLogoImg('img#logoImg', user.logo_img);
} else {
if ($thisObj.fnGetSessionError !== null)
$thisObj.fnGetSessionError(null, data);
}
if ($thisObj.fnGetSessionComplete !== null)
$thisObj.fnGetSessionComplete.call(null, data);
}
});
},
updateLogoImg: function (imgLogoId, path, isRequestServer, serviceId) {
if (isRequestServer) {
// load from server
// use to load current logo image of a service
$.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/GetLogoImageName",
data: {'ServiceId': serviceId},
dataType: "json",
success: function (data) {
if (data.status === "OK") {
if (data.logo_img !== null && data.logo_img !== '') {
$(imgLogoId).attr('src', '/data/' + data.logo_img);
}
}
}
});
} else {
// load from client
if (typeof path !== 'undefined' && path !== null && path !== '') {
$(imgLogoId).attr('src', '/data/' + path);
// update logo path to admin
// user can't change logo img so don't care user case
if (admin !== null) {
admin.logo_img = path;
}
} else {
if (admin !== null && admin.logo_img !== null && admin.logo_img !== '') {
// try to pass logo img from admin object
$(imgLogoId).attr('src', '/data/' + admin.logo_img);
}
}
}
},
/**
* Get admin's session data
* @returns {jqXHR}
*/
getAdminSessionData: function () {
// Call API
return $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/GetAdminSession",
data: {'SessionID': this.getSessionID()},
dataType: "json",
beforeSend: function () {
if (UserSession.fnGetSessionBeforeSend !== null)
UserSession.fnGetSessionBeforeSend();
},
success: function (data) {
if (data.status === "OK") {
login = true;
admin = data;
UserSession.updateLogoImg('img#logoImg');
} else {
if (UserSession.fnGetSessionError !== null)
UserSession.fnGetSessionError(data);
}
if (UserSession.fnGetSessionComplete !== null)
UserSession.fnGetSessionComplete(data);
}
});
},
/**
* Call getting session for both User & Admin
* @returns {jqXHR}
*/
fnGetData: function () {
return $.when($.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/GetSession",
data: {'SessionID': UserSession.getSessionID()},
dataType: "json"
}),
$.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/GetAdminSession",
data: {'SessionID': UserSession.getSessionID()},
dataType: "json"
})
);
},
/**
* Store session to cookie of user's browser
* @param {type} sessionID
* @returns {undefined}
*/
setSessionID: function (sessionID) {
var days = 7;// 1 week
if (sessionID !== null) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = this.sessionKey + "=" + sessionID + expires + "; path=/";
}
},
/**
* Get sessionID stored at client browser
* @returns {string}
*/
getSessionID: function () {
var sessionID = this.sessionKey + "=";
var cookkies = document.cookie.split(';');
for (var i = 0; i < cookkies.length; i++) {
var c = cookkies[i];
while (c.charAt(0) === ' ')
c = c.substring(1, c.length);
if (c.indexOf(sessionID) === 0)
return c.substring(sessionID.length, c.length);
}
return null;
},
/**
* Remove session from cookie
* @returns {undefined}
*/
clearSessionID: function () {
//Remove cookie
document.cookie = this.sessionKey + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
},
/**
* Get username
* @returns {user.name}
*/
getName: function () {
if (user !== null)
return user.name;
else
return null;
},
/**
* Get user's timezone
* @returns {user.time_zone|Number}
*/
getTimeZone: function () {
if (user !== null)
return user.time_zone;
else
return -5;
},
/**
* Get user's point
* @returns {user.points}
*/
getPoints: function () {
if (user !== null)
return user.points;
else
return null;
},
/**
* Get user's langding page
* @returns {user.landing_page}
*/
getLandingPage: function () {
if (user !== null)
return user.landing_page;
else
return null;
},
/**
* Get user's language. It will return user's language standard code refer this link (http://4umi.com/web/html/languagecodes.php)
* However, if language is auto, it detects user's browser language
* @returns {user.lang}
*/
getLang: function () {
if (user !== null) {
//Specify language
if (user.lang.length === 2) { //Follow standard 2 chars
return user.lang;
} else {
return HoGoUtils.detectBrowserLang();
}
} else
return null;
},
/**
* Update user info on view by calling getSessionData again
* @returns {undefined}
*/
updateUserInfo: function (isAuto) {
//Get session data
this.getSessionData().done(function (sessionData) {
// Init with new lang
var session = UserSession;
session.renderNameAndPoint(sessionData);
if (session.getLang() !== i18n.lng()) {
HoGoObjects.translateAndInitLoginState(session.getLang(), isAuto);
}
});
},
/**
* Render only username and points base on user's language
* @param {json} sessionData User's session data
* @returns {undefined}
*/
renderNameAndPoint: function (sessionData) {
// Render name/points
var name;
var lang;
var lLang = sessionData.lang.split("-");
if ($.trim(lLang[0]) === 'auto' || $.trim(lLang[0]) === '')
lang = HoGoUtils.detectBrowserLang();
else
lang = sessionData.lang;
if (lang === 'ja') {
// Last name + first name
$('#profileLink').text(sessionData.last_name + ' ' + sessionData.first_name + " 様");
} else {
// Another language
name = sessionData.first_name;
if (sessionData.middle_name === null) {
name = name + ' ';
} else {
name = name + ' ' + sessionData.middle_name;
}
name = name + ' ' + sessionData.last_name;
$('#profileLink').text(name);
}
// Points
$('#pointNumber').text(sessionData.points);
},
/**
* Set PayPal url to cookie
* @param {type} _url
* @returns {undefined}
*/
setReturnPaypalURL: function (_url) {
var days = 7;// 1 week
if (_url !== null) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = this.paypalReturnURL + "=" + _url + expires + "; path=/";
}
},
/**
* Get url PayPal from cookie
* @returns {unresolved}
*/
getReturnPaypalURL: function () {
var _url = this.paypalReturnURL + "=";
var cookkies = document.cookie.split(';');
for (var i = 0; i < cookkies.length; i++) {
var c = cookkies[i];
while (c.charAt(0) === ' ')
c = c.substring(1, c.length);
if (c.indexOf(_url) === 0)
return c.substring(_url.length, c.length);
}
return null;
},
//-----------
// Admin
//-----------
getAdminID: function () {
if (admin !== null)
return admin.admin_id;
},
getAdminTimezone: function () {
if (admin !== null)
return admin.time_zone;
},
getAdminLang: function () {
if (admin !== null) {
//Specify language
if (admin.adminlang.length === 2) { //Follow standard 2 chars
return admin.adminlang;
} else {
return HoGoUtils.detectBrowserLang();
}
} else
return null;
},
updateAdminInfo: function () {
//Get session data
this.getAdminSessionData().done(function (sessionData) {
// Init with new lang
var session = UserSession;
if (session.getAdminLang() !== i18n.lng()) {
HoGoObjects.translateAndInitLoginState(session.getAdminLang());
}
// render admin name
var name, lang;
var lLang = sessionData.adminlang.split("-");
if ($.trim(lLang[0]) === 'auto' || $.trim(lLang[0]) === '') {
lang = HoGoUtils.detectBrowserLang();
} else {
lang = sessionData.lang;
}
if (lang === 'ja') {
// Last name + first name
$('#profileLink').text(sessionData.last_name + ' ' + sessionData.first_name + " 様");
} else {
// Another language
name = sessionData.first_name;
if (typeof sessionData.middle_name === 'undefined') {
name = name + ' ';
} else {
name = name + ' ' + sessionData.middle_name;
}
name = name + ' ' + sessionData.last_name;
$('#profileLink').text(name);
}
});
}
};
}(jQuery));
//
// Error page
//
var ErrorNotice = (function ($) {
// Error number
var errorNo;
return {
drawErrorView: function (errorNo) {
// List error
switch (errorNo) {
case APIConst.LINK_EXPIRED_CODE:
$('.error-message').text(i18n.t('download.message.link_expiry'));
break;
case APIConst.DOCUMENT_EXPIRED_CODE:
$('.error-message').text(i18n.t('download.message.document_expiry'));
break;
case APIConst.LIST_EMPTY_CODE:
$('.error-message').text(i18n.t('download.message.list_document_empty'));
break;
case APIConst.PACKAGE_NOT_FOUND:
$('.error-message').text(i18n.t('history.package.message.package_deleted.content'));
break;
default:
$('.error-message').text(i18n.t('error.error_occur'));
break;
}
},
init: function () {
// Getting param
errorNo = HoGoUtils.getParameter()["error"];
// List error
ErrorNotice.drawErrorView(errorNo);
}
};
}(jQuery));
//
// Handle view online
//
var ViewOnline = (function ($) {
//
function be_onauthok(msg) {
//
BEObj.getPdfState('contents', onChangePdfState);
//
BEObj.execKrPdfJs('contents', ["KRNS.t.numPages"], function (ret) {
$("#pdf_page_num").text("/" + ret[0]);
});
}
//
function be_onpageopen(msg) {
//
if (msg.result === "true") {
BEObj.getPdfState('contents', onChangePdfState);
}
}
//
function onChangePdfState(obj) {
BEObj.log("onChangePdfState: " + BEObj.inspect(obj));
if (obj.zoom) {
setZoomNum(obj.zoom);
}
if (obj.page) {
setPageNum(obj.page);
}
}
// set Page Number
function setPageNum(page) {
$("#pdf_page").val(page - 0 + 1);
}
function getPageNum() {
return $('#pdf_page').val() - 1;
}
// Zoom
function setZoomNum(zoom) {
$("#pdf_zoom").val(zoom);
}
function getZoomNum() {
return $('#pdf_zoom').val() - 0;
}
return {
init: function () {
// Gettting required parameter
var accessCode = HoGoUtils.getParameter()["code"];
if (accessCode === 'undefined') {
return;
}
var DocumentID = '';
var PackageID = '';
if (accessCode === 'NotUsed') {
DocumentID = HoGoUtils.getParameter()["DocumentID"];
PackageID = HoGoUtils.getParameter()["PackageID"];
}
// beobj.js
var _kr_host_bookend = "bookend.keyring.net";
var postfix = "?" + new Date().getTime();
var linkBE = 'https://' + _kr_host_bookend + '/js/beobj.js' + postfix;
// Require BE lib
require([linkBE], function () {
// Load done
try {
//var kr_hosts = "https://" + location.host + "/HoGo/";
var aParts = window.location.pathname.split('/');
// Delete page name
delete aParts[aParts.length - 1];
// Get sub domain
var path = aParts.join('/');
var kr_hosts = location.protocol + "//" + location.host + path;
var urlGetFile = kr_hosts + "api/v1/GetLinkedDocumentFileViewOnline/" + accessCode;
if (DocumentID !== '' && PackageID !== '')
urlGetFile = kr_hosts + "api/v1/GetLinkedDocumentFileViewOnline/" + accessCode + "?DocumentID=" + DocumentID + "&PackageID=" + PackageID;
// get link document file
$.ajax({
type: "GET",
timeout: HoGoConst.APITimeout,
url: urlGetFile,
dataType: "json",
success: function (data) {
if (data.status === 'OK') {
var linkFile = data.link + "#toolbar=0";
BEObj.createProtectedContents(
{TargetElement: "contents", LoadingSWF: "", OnAuthOK: be_onauthok, OnPageOpen: be_onpageopen},
{src: linkFile, style: "width:100%; height:95%;"}, 0);
}
}
});
} catch (e) {
Modal.showAlert({content: e.message});
}
});
$("#pdf_print_bt1").click(function (e) {
BEObj.execKrPdfJs('contents', ["KRNS.t.print()"]);
});
//
$("#pdf_zoomtype").click(function (e) {
BEObj.setPdfZoomType('contents', 'FitPage', onChangePdfState);
});
//
$("#pdf_zoom").keypress(function (e) {
if (e.which === 13) {
BEObj.setPdfZoom('contents', getZoomNum(), onChangePdfState);
}
});
$("#pdf_zoom_d").click(function (e) {
BEObj.setPdfZoom('contents', getZoomNum() - 10, onChangePdfState);
});
$("#pdf_zoom_u").click(function (e) {
BEObj.setPdfZoom('contents', getZoomNum() + 10, onChangePdfState);
});
//
$("#pdf_page").keypress(function (e) {
if (e.which === 13) {
BEObj.setPdfPageNum('contents', getPageNum(), onChangePdfState);
}
});
$("#pdf_page_d").click(function (e) {
BEObj.setPdfPageNum('contents', getPageNum() - 1, onChangePdfState);
});
$("#pdf_page_u").click(function (e) {
BEObj.setPdfPageNum('contents', getPageNum() + 1, onChangePdfState);
});
//
$("#page_single").click(function (e) {
BEObj.setPdfLayout('contents', 'SinglePage', onChangePdfState);
});
$("#page_twocolumn").click(function (e) {
BEObj.setPdfLayout('contents', 'TwoPageLeft', onChangePdfState);
});
//
$("#pdf_search_bt").click(function (e) {
BEObj.searchPdf('contents', $('#pdf_search').val());
});
$("#pdf_search").keypress(function (e) {
if (e.which === 13) {
$("#pdf_search_bt").click();
}
});
}
};
}(jQuery));
//
// Contain API const returned
//
var APIConst = {
/* SessionID not found */
sessionIdNotFound: "SessionIdNotFound",
/* Insuffient point */
INSUFFICIENT_POINT: "InsufficientPoint",
/* Max Transaction */
MAX_TRANSACTION: "maxTransaction",
/* Admin's session not found */
ADMIN_SESSION_REQUIRED: "AdminSessionRequired",
/* User already exist */
userAlreadyExistStatus: "UserAlreadyExist",
/* Recipient already exist */
RECIPIENT_ALREADY_EXIST: "RecipientAlreadyExist",
/* Invalid parameter */
invalidParameterStatus: "InvalidParameter",
/* Activation code exprired */
ACTIVATION_CODE_EXPIRED: "ActivationCodeExpired",
/* Input param error */
inputParameterErrorStatus: "InputParameterError",
/* Invalid max download */
invalidMaxDownloadValue: "InvalidMaxDownloadValue",
/* Reset code expired */
RESET_CODE_EXPIRED: "ResetCodeExpired",
/* Password protected file */
passwordProtected: "PasswordProtect",
/* Max file size */
maxFileSize: "MaxFileSizeExceeded",
maxFileErrorStatus: "MaxFileError",
AFFILIATE_ALREADY_EXIST: "AffiliateAlreadyExist",
/* Document not support for zero method */
DOCUMENT_NOT_SUPPORT_ZERO_METHOD: "DocumentNotSupportZeroMethod",
/* Download function has been disbaled */
DOWNLOAD_DISABLED: "DownloadDisabled",
MAX_DOWNLOAD: "MaxDownload",
DOCUMENT_EXPIRED: "DocumentExpired",
REGISTER_EMAIL_ERROR: "RegisterEmailError",
WRONG_PASSWORD: 'WrongPassword',
PACKAGE_NOT_FOUND: "PackageNotFound",
DISTRIBUTION_NOT_FOUND: "DistributionNotFound",
USER_NOT_FOUND: "UserNotFound",
DOCUMENT_EXPIRED_CODE: "DocumentExpired",
LINK_EXPIRED_CODE: "LinkExpired",
LIST_EMPTY_CODE: "ListEmpty",
INVALID_EMAIL: "InvalidEmail",
PAYPAL_METHOD_PAYMENT: 1,
STRIPE_METHOD_PAYMENT: 2,
GMO_METHOD_PAYMENT: 3
};
//
// Contain constants using entire HoGo app such as default language...
//
var HoGoConst = {
ACTIVE_STATUS: 1,
REMOVED_STATUS: 2,
DEACTIVE_STATUS: 3,
INACTIVE_STATUS: 8,
/* Ajax's timeout */
APITimeout: 300000, // 5mins
EXTERNAL_TIMEOUT: 60000, // Anycall from outside
/* Language detault */
LANG_DEFAULT: 'en',
/* Default service key */
SERVICE_KEY: '123456',
/* Default service ID */
SERVICE_ID: 'hogo',
/* Max date <=> No limit */
MAX_DATE: '9999/12/31 23:59:59',
/* Wizard type */
WIZARD_DIRECT_SEND_TYPE: 1,
WIZARD_CREATE_LINK_TYPE: 2,
WIZARD_SPECIFY_LINK_TYPE: 3,
WIZARD_ANONYMOUS_TYPE: 4,
/*FILE TYPE */
FILE_PDF_TYPE: 1,
FILE_WORD_TYPE: 2,
FILE_EXCEL_TYPE: 3,
FILE_POWERPOINT_TYPE: 4,
FILE_XLSM_TYPE: 5,
FILE_ORTHER_TYPE: 6,
/* History code */
DIRECT_SEND_TYPE: 405,
CREATE_LINK_NONDOWNLOAD_TYPE: 406,
CREATE_LINK_DOWNLOAD_TYPE: 407,
LINK_SPECIFY_CREATED_TYPE: 411,
LINK_ANONYMOUS_CREATED_TYPE: 412,
PACKAGE_CREATED_TYPE: 100,
PACKAGE_UPDATED_TYPE: 101,
PACKAGE_DELETED_TYPE: 102,
DOCUMENT_ADDED_TYPE: 200, // Document
DOCUMENT_UPDATED_TYPE: 201, // Document
DOCUMENT_DELETED_TYPE: 202, // Document
RECIPIENT_ADDED_TYPE: 300, // Recipient
RECIPIENT_UPDATED_TYPE: 301, // Recipient
RECIPIENT_DELETED_TYPE: 302, // Recipient
USER_CREATED_TYPE: 400,
USER_DELETED_TYPE: 402,
LOGIN_TYPE: 403,
LOGOUT_TYPE: 404,
DOCUMENT_EXPIRED_TYPE: 603, // Document
LINK_EXPIRED_TYPE: 604,
DOCUMENT_DOWNLOADED_TYPE: 602, // Document
LINK_MAX_DOWNLOAD_TYPE: 605,
DOCUMENT_VIEWED_TYPE: 601, // Document
DOCUMENT_OPENED_TYPE: 606, // Document
INSUFFICIENT_POINT_TYPE: 600,
USER_UPDATED_TYPE: 401,
ADMIN_ADD_POINTS: 505,
PURCHASE_POINTS_TYPE: 408,
ADMIN_REFUND_TYPE: 504,
ADMIN_SENT_MESSAGE_TYPE: 777,
MESSAGE_UNREAD_TYPE: 0,
MESSAGE_READ_TYPE: 1,
// Distribution status
DISTRIBUTION_WAIT_DOWNLOAD_ID: "Waiting",
DISTRIBUTION_DOWNLOAD_ID_ERROR: "Error",
DISTRIBUTION_NO_ACCESS_CODE: "NoAccessCode",
DISTRIBUTION_HAS_BEEN_DELETED: "HasBeenDeleted",
DISTRIBUTION_NOT_USED: "NotUsed",
// System service level
SYSTEM_ADMIN: 1,
DISTRIBUTOR: 2,
COMPANY_ADMIN: 3,
NOMAL_USER: 4,
//auto set new payment after trial
NOT_SET_NEW_PAYMENT_AFTER_TRIAL: 0,
SET_NEW_PAYMENT_AFTER_TRIAL: 1,
MAX_LOGO_WIDTH: 60,
MAX_LOGO_HEIGHT: 34,
// Account Type
TRIAL_ACCOUNT: "trial",
ACTIVE_ACCOUNT: "active",
// reseller role
RESELLER_ADMIN: 1,
RESELLER_MANAGER: 2
};
//
// Provide methods concerning with datatable
//
var DTUtils = {
// I18N
DTLang: {},
/**
* Collect required data send to server in document list table
* @param {object}: aoData datatable object contains data to send out
* @return {object}
*/
documentListPostData: function (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"] = 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 (HoGoUtils.getPageName() === 'userdetail.html') {
post["UserID"] = HoGoUtils.getParameter()['userID'];
}
post["SessionID"] = UserSession.getSessionID();
return post;
},
recipientListPostData: function (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"] = 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;
}
post["GroupID"] = HoGoUtils.getParameter()["group_recipient_id"];
post["SessionID"] = UserSession.getSessionID();
post["UserID"] = HoGoUtils.getParameter()["userID"];
return post;
},
groupRecipientListPostData: function (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"] = 1;
else
post["SortType"] = 2;
break;
case 2:
if (sortType === "asc")
post["SortType"] = 3;
else
post["SortType"] = 4;
break;
}
post["sessionID"] = UserSession.getSessionID();
return post;
},
/**
* Make request data in order to get recipient list in send wizard section
* @param {type} aoData
* @returns {object}
*/
recipientListPostDataForSendWizard: function (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"] = 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"] = 7;
else
post["SortType"] = 8;
break;
case 4:
if (sortType === "asc")
post["SortType"] = 9;
else
post["SortType"] = 10;
break;
}
post["SessionID"] = UserSession.getSessionID();
return post;
},
recipientListByPackageIdPostData: function (aoData, packageId) {
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"] = 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;
}
post["packageId"] = packageId;
post["SessionID"] = UserSession.getSessionID();
return post;
},
/**
* This function is used to return data send to service for MyDocumentList
* @param {type} aoData
* @param {type} packageId
* @param {type} method
* @returns {object}
*/
documentListByPackageIdPostData: function (aoData, packageId, method) {
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"] = 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;
}
post["SessionID"] = UserSession.getSessionID();
post['packageId'] = packageId;
// PDF method
if (method === HoGoConst.WIZARD_DIRECT_SEND_TYPE || method === HoGoConst.WIZARD_CREATE_LINK_TYPE) {
post['FileType'] = HoGoConst.FILE_PDF_TYPE; // 1
} else {
// All type
post['FileType'] = '1,2,3,4';
}
return post;
},
/**
* Event click select all record (Each record is checkbox)
* @param {object} btnSelectAll
* @param {array} checkedList
* @param {string} childName : Child name of each child
* @param {string} attrValue : attribute name from checkedList
* @param {string} btnWillBeDisable : selector (button) will be disabled
* @param {function} funName : Function will be disabled
* @param {string} btnColor : Button's color
* @returns {undefined}
*/
fnSelectAllCheckBox: function (btnSelectAll, checkedList, childName, attrValue, btnWillBeDisable, funName, btnColor) {
this.checkboxSelectAllEvent(btnSelectAll, childName, checkedList, attrValue);
if (checkedList.length > 0) {
//Enable these buttons
//enableButton(btnWillBeDisable, btnColor, false, funName);
HoGoUtils.enableButton('#' + btnWillBeDisable, {
colorClass: btnColor,
handler: funName
});
} else {
//disableButton(btnWillBeDisable, btnColor, funName);
HoGoUtils.disableButton('#' + btnWillBeDisable, {
colorClass: btnColor
});
}
},
/**
* This function is used to implement event click on checkbox all.
* @param {object}: itself the checkbox is checked
* @param {object}: cbChildName the checkbox parent
* @param {array}: checkedList the list contains ID selected
* @param {string}: attrName this attribute-name will be used instead of 'ID' if it's set
*/
checkboxSelectAllEvent: function (itself, cbChildName, checkedList, attrName) {
// console.log("dau xanh...");
var _this = $(itself);
var tID = _this.parents('table').attr('id');
$('#' + tID + ' :checkbox[name=' + cbChildName + ']').prop("checked", _this.prop("checked"));
if (_this.prop("checked")) {
$('#' + tID + ' label[class="checker"]').addClass("checked");
$('#' + tID + ' :checkbox[name=' + cbChildName + ']').each(function () {
var attr = (attrName === undefined || attrName === '') ? $(this).attr("id") : $(this).attr(attrName);
if (jQuery.inArray(attr, checkedList) === -1) {
checkedList.push(attr);//Add
}
});
} else {
$('#' + tID + ' label').each(function () {
if ($(this).hasClass('checked'))
$(this).removeClass('checked');
});
$('#' + tID + ' :checkbox[name=' + cbChildName + ']').each(function () {
var index = (attrName === undefined || attrName === '') ? jQuery.inArray($(this).attr("id"), checkedList) : jQuery.inArray($(this).attr(attrName), checkedList);
checkedList.splice(index, 1); //Remove
});
}
return checkedList;
},
/**
* This function is used to implemnet event checkbox is still select when switching page
* @param {String}: tableId the ID of table paging
* @param {object}: cbChildName the checkbox is checked
* @param {object}: cbParentName the checkbox parent
* @param {array}: checkedList the list contains ID selected
* @param {string}: attrName this attribute-name is used instead of 'ID' if it's set
*/
checkboxSwitchPage: function (tableId, cbChildName, cbParentName, checkedList, attrName) {
$("#" + tableId).find("input:checkbox[name=" + cbChildName + "]").each(function () {
var attr = (attrName === undefined || attrName === '') ? $(this).attr("id") : $(this).attr(attrName);
if (jQuery.inArray(attr, checkedList) !== -1) {
$(this).prop("checked", true);
$('label[for=' + $(this).attr("id") + ']').addClass("checked");
} else {
$(this).prop("checked", false);
$('label[for=' + $(this).attr("id") + ']').removeClass("checked");
}
//Check all or not
var _this = $(this);
var _selectall = _this.prop("checked");
if (_selectall) {
$(':checkbox[name=' + cbChildName + ']').each(function () {
_selectall = $(this).prop("checked");
return _selectall;
});
}
var pID = $(':checkbox[name=' + cbParentName + ']').attr('id');
if (_selectall) {
$('label[for=' + pID + ']').addClass("checked");
} else {
$('label[for=' + pID + ']').removeClass("checked");
}
$(':checkbox[name=' + cbParentName + ']').prop("checked", _selectall);
});
},
/*
* This function is used to implement event each checkbox child is selected or unselected
* @param {object}: itself the checkbox is checked
* @param {object}: cbParentName the checkbox parent
* @param {array}: checkedList the list contains ID selected
* @param {string}: attrName this attribute-name is used instead of 'ID' if it's set
*/
checkboxChildSelectEvent: function (itself, cbParentName, checkedList, attrName) {
var attr = (attrName === undefined || attrName === '') ? $(itself).attr("id") : $(itself).attr(attrName);
if (jQuery.inArray(attr, checkedList) !== -1) {
var index = jQuery.inArray(attr, checkedList);
checkedList.splice(index, 1);
} else {
if (attr !== 'tablepaging') {
checkedList.push(attr);
}
}
//Check all or not
var _this = $(itself);
var _selectall = _this.prop("checked");
if (_selectall) {
$(':checkbox[name=' + _this.attr("name") + ']').each(function () {
_selectall = $(this).prop("checked");
return _selectall;
});
}
var pID = $(':checkbox[name=' + cbParentName + ']').attr('id');
if (_selectall) {
$('label[for=' + pID + ']').addClass("checked");
} else {
$('label[for=' + pID + ']').removeClass("checked");
}
$(':checkbox[name=' + cbParentName + ']').prop("checked", _selectall);
},
/**
* Setup table control such as (Length, Filter ...) for table using datatable plugin
* @param {type} oSettings datatable's setting
* @returns {undefined}
*/
fnSetUpTableControl: function (oSettings) {
//Make sure table have data
if (oSettings.fnRecordsDisplay() <= 1) {
for (var i = 0, len = oSettings.aoColumns.length; i < len; i++) {
var th = $(oSettings.aoColumns[i].nTh);
if (th.hasClass('sorting') || th.hasClass('sorting_asc') || th.hasClass('sorting_desc')) {
th.addClass('sorting_disabled');
}
oSettings.aoColumns[ i ].bSortable = false;
}
} else {
for (var i = 0, len = oSettings.aoColumns.length; i < len; i++) {
// oSettings.aoColumns[i].nTh.className = "";
var th = $(oSettings.aoColumns[i].nTh);
if (th.hasClass('sorting_disabled') && th.hasClass('sorting')) {
th.removeClass('sorting_disabled');
}
if (th.hasClass('sorting_disabled') && th.hasClass('sorting') && (th.hasClass('sorting_asc') || th.hasClass('sorting_desc'))) {
th.removeClass('sorting_disabled');
//Remove sorting to apply new css
th.removeClass('sorting');
}
if (th.hasClass('sorting_disabled') && (th.hasClass('sorting_asc') || th.hasClass('sorting_desc'))) {
th.removeClass('sorting_disabled');
}
//
if (th.hasClass('sorting') && (th.hasClass('sorting_asc') || th.hasClass('sorting_desc'))) {
th.removeClass('sorting');
//Remove sorting to apply new css
}
if (th.hasClass('sorting')) {
oSettings.aoColumns[ i ].bSortable = true;
}
}
}
//Pagination
if (oSettings._iDisplayLength >= oSettings.fnRecordsDisplay() || oSettings._iDisplayLength === -1) {
setTimeout(function () {
// Hide pagination
$('#' + oSettings.sInstance + '_paginate').hide();
// Hide length
//if (oSettings._iDisplayLength >= oSettings.fnRecordsDisplay())
//$('#' + oSettings.sInstance + '_length').hide();
}, 100);
} else {
// Show again
$('#' + oSettings.sInstance + '_length').show();
$('#' + oSettings.sInstance + '_paginate').show();
}
// Resize
$('.reveal-modal-bg .reveal-modal').trigger('reveal:resize');
},
/**
* Trigger click event checkbox on the row
* @param {object} row :The row contains checkbox
*/
fnCheckBoxOnRow: function (row) {
//console.log(row);
var $this = $(row);
var cb = $this.find(':checkbox');
if (cb.is(':checked')) {
cb.prop('checked', false).triggerHandler('click');
} else {
cb.prop('checked', true).triggerHandler('click');
}
},
/**
* Enable mutiple buttons
* @param {string} json with format: {list_button [id: "btnSend", color: "orange", submit: "false", fn: "fnAddRecipientToSession", form_id: null], ....}
*/
fnEnableControl: function (json) {
var fn = json.list_button;
$.each(fn, function (k, v) {
HoGoUtils.enableButton('#' + v.id, {colorClass: v.color, isSubmitForm: v.submit, handler: v.handler, formID: v.form_id});
});
},
/**
* Disable multiple buttons with the same options to fnEnableControl method
* @param {type} json
* @returns {undefined}
*/
fnDisableControl: function (json) {
var fn = json.list_button;
$.each(fn, function (k, v) {
HoGoUtils.disableButton('#' + v.id, {colorClass: v.color});
});
},
/*
* Using to paginate or not. If there's more than 1 page, it will be paginated.
* @param {object}: oSettings datable object settings
*/
determinePaging: function (oSettings) {
if ((oSettings._iDisplayLength >= oSettings.fnRecordsDisplay()) || oSettings._iDisplayLength === -1) {
setTimeout(function () {
$('#' + oSettings.sTableId + '_paginate').hide();
}, 300);
} else {
$(".dataTables_paginate").show();
}
},
folderListPostData: function (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"] = 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;
}
if (HoGoUtils.getPageName() === 'userdetail.html') {
post["UserID"] = HoGoUtils.getParameter()['userID'];
}
post["SessionID"] = UserSession.getSessionID();
return post;
},
documentFolderListFilesPostData: function (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"] = 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;
}
post["folder_id"] = HoGoUtils.getParameter()['folderId'];
post["SessionID"] = UserSession.getSessionID();
post["UserID"] = HoGoUtils.getParameter()['userID'];
return post;
},
companyAddressListPostData: function (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["sort_type"] = 1;
else
post["sort_type"] = 2;
break;
case 2:
if (sortType === "asc")
post["sort_type"] = 3;
else
post["sort_type"] = 4;
break;
case 3:
if (sortType === "asc")
post["sort_type"] = 5;
else
post["sort_type"] = 6;
break;
}
post["session_id"] = UserSession.getSessionID();
post["emails"] = "";
return post;
}
};
//
// Provide methods checking date/convert date
//
var DateUtils = {
/**
* String object format date
* @param {type} date
* @returns {String} example output: 04/10/2014 (mm/dd/yyyy)
*/
convertDate: function (date) {
if (typeof date !== 'undefined') {
var dateObj = new Date(date);
if (Object.prototype.toString.call(dateObj) === "[object Date]") {
if (isNaN(dateObj.getTime())) {
return date;
} else {
return ("0" + (dateObj.getMonth() + 1)).slice(-2) + "/" + ("0" + dateObj.getDate()).slice(-2) + "/" + dateObj.getFullYear();
}
} else {
//Not format date object
return "Invalid Date";
}
} else {
return "undefined";
}
},
/**
* String object format date
* @param {type} date
* @returns {String} example output: 04/10/2014 00:00:00 (mm/dd/yyyy hh:mm:ss)
*/
convertFullDate: function (date) {
if (typeof date !== 'undefined') {
var dateObj = new Date(date);
if (Object.prototype.toString.call(dateObj) === "[object Date]") {
if (isNaN(dateObj.getTime())) {
return date;
} else {
return ("0" + (dateObj.getMonth() + 1)).slice(-2) + "/" + ("0" + dateObj.getDate()).slice(-2) + "/" + dateObj.getFullYear() + " " + ("0" + dateObj.getHours()).slice(-2) + ":" + ("0" + dateObj.getMinutes()).slice(-2) + ":" + ("0" + dateObj.getSeconds()).slice(-2);
}
} else {
return "Invalid format date";
}
} else {
return null;
}
},
/*
* Convert UTC date to local timezone
* @param {type} date: Date type
* @param {type} timezone: int type
* @returns {Date}
*/
convertUTCToLocalTime: function (date, timezone) {
var dateLocalTime = new Date(new Date(date).getTime() + timezone * 60 * 1000 * 60);
return dateLocalTime;
},
convertToDBDate: function (date) {
var tSuffix = '23:59:59'; // Max time
var dPrefix = '9999/12/31'; // Max day
if (date !== undefined && date !== '') {
var array = date.split("/");
var month = array[0];
// array of month by number
var months = new Array(
"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
// array of month by text
var monthStrings = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
for (var index = 0; index < months.length; index++) {
if (monthStrings[index] === month)
array[0] = months[index];
}
// Create date obj
var dateObj = new Date(array[2] + "/" + array[0] + "/" + array[1]);
if (!isNaN(dateObj.getTime())) {
return dateObj.getFullYear() + "/" + (dateObj.getMonth() + 1) + "/" + dateObj.getDate() + " " + tSuffix;
} else
// Return max date
return dPrefix + ' ' + tSuffix;
} else {
// Return max date
return dPrefix + ' ' + tSuffix;
}
},
convertFromDateObject: function (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";
}
},
convertToNormalDate: function (date) { //May/01/2013 to 05/01/2013
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 months[d[0]] + "/" + d[1] + "/" + d[2];
},
/**
* Calculate date before with specific days
* @param {type} days
* @returns {String|type}
*/
calculateDateBefore: function (days) {
var d = new Date();
return DateUtils.convertDate(new Date(d.getFullYear(), d.getMonth(), d.getDate() - days, d.getHours(), d.getMinutes(), d.getSeconds()));
},
/**
* Check whether date string is valid or not
* @param {type} dateString
* @returns {Boolean}
*/
isValidDate: function (dateString) {
// Conver to date object
var date = new Date(dateString);
if (isNaN(date.getTime()) === false) {
return true;
} else {
return false;
}
}
};
//
// Create modal for HoGo such as existing addressbook modal...
//
var Modal = (function ($) {
var SelectedDocumentList = {
DocumentList: [],
push: function (id, title, file_name, create_date) {
var isExist = false;
$.each(SelectedDocumentList.DocumentList, function (index, value) {
if (value.ID === id)
isExist = true;
});
if (!isExist)
SelectedDocumentList.DocumentList.push({'ID': id, 'title': title, 'file_name': file_name, "create_date": create_date});
},
remove: function (id) {
for (var index = 0; index < SelectedDocumentList.DocumentList.length; index++) {
if (SelectedDocumentList.DocumentList[index].ID === id)
SelectedDocumentList.DocumentList.splice(index, 1); //Remove
}
},
removeAll: function () {
if (SelectedDocumentList.DocumentList.length > 0)
SelectedDocumentList.DocumentList.splice(0, SelectedDocumentList.DocumentList.length);
},
getDocumentList: function () {
return SelectedDocumentList.DocumentList;
}
};
// Existing document object
var DocumentModal = {
eTable: null, iDisplay: false, checkedList: [], packageId: null,
cbAfterSelect: void 0,
checkDocumentSelected: function (documentid) {
var isExist = false;
$("#my_result2>tr:visible").find("#DocumentID").each(function () {
if ($(this).val() === documentid)
isExist = true;
});
return isExist;
},
// Get document list
getDocumentExist: function ( ) {
var documentExist = [];
$("#my_result2>tr:visible").find("#DocumentID").each(function () {
documentExist.push($(this).val());
});
return documentExist.toString();
},
/**
* Add selected documents to existing table - STEP 1 context
* @returns {undefined}
*/
addDocumentToExistingTable: function () {
var that = DocumentModal;
// Callback
that.cbAfterSelect && that.cbAfterSelect(that.checkedList);
Modal.closeModal();
// Removed function from v2.0
// $.each(DocumentModal.checkedList, function (i, v) {
// Modal.getDocumentDetailThenAppendToTable(v).done(function () {
// // Off modal
// Modal.closeModal();
// DocumentModal.resetModal();
// });
// });
},
/**
* Add document to a package
* @param {type} listDocDelDup
* @param {type} listIdNotDup
* @returns {jqXHR}
*/
addDocumentToPackage: function (listDocDelDup, listIdNotDup) {
var $this = DocumentModal;
var listDocIdDel = [];
// get list documentId have license duplicate
if (listDocDelDup.length > 0) {
$.each(listDocDelDup, function (k, v) {
listDocIdDel.push(v.id);
});
}
var lDocPost = $.merge($.merge([], listDocIdDel), listIdNotDup);
var postData = {};
postData["PackageID"] = $this.packageId;
postData["DocumentID"] = lDocPost.toString();
postData["SessionID"] = UserSession.getSessionID();
//Call API
return $.ajax({
url: 'api/v1/AddPackageDocument',
type: 'POST',
timeout: HoGoConst.APITimeout,
data: postData,
dataType: "json",
beforeSend: function () {
$('').appendTo('#contents');
Modal.closeModal();
},
success: function (data) {
// Remove mask
$('body').find('.hogo-bg-overlay-action').remove();
if (data.status === "OK") {
//Add to distribution list
Package.showDistributionTable();
// Update package detail
Package.drawPackage();
// Redraw points
UserSession.updateUserInfo();
// Delete duplicate license recipient if have
if (listDocDelDup.length > 0) {
WizardCore.deleteLicenseDuplicate($this.packageId, listDocDelDup, 3);
}
// Reset modal
$this.resetModal();
Modal.closeModal();
} else {
if (data.status === APIConst.INSUFFICIENT_POINT) {
// Store selected document list
$.cookie("d_list", JSON.stringify($this.checkedList));
//Warning BuyPoint
Modal.showConfirmPopup({
title: i18n.t('history.package.message.insuffient_point.title'),
content: i18n.t('history.package.message.insuffient_point.content'),
cancelCallback: $this.resetModal, // clear cookie {d_list} & close modal
okCallback: HoGoUtils.goBuyPoint // go buy points
});
}
if (data.status === APIConst.MAX_TRANSACTION) {
// Show popup confirm
Modal.showAlert({
title: i18n.t('send_wizard.step_3.message.max_transaction.title'),
content: i18n.t('send_wizard.step_3.message.max_transaction.content')
});
}
}
}
});
},
/**
* Close modal depend on current context
* @returns {undefined}
*/
resetModal: function () {
var $this = DocumentModal;
$this.iDisplay = false;
$this.checkedList = [];
// sendwizard context
if ($this.packageId === null) {
SelectedDocumentList.removeAll();
} else {
// package context
$.cookie("d_list", null);
$this.packageId = null;
}
}
};
var ComRecipientModal = {
checkedList: [], iDisplay: false, documentsSelected: [], aTable: null, packageId: null,
/**
* Add email to text area in step 3 or step 4 {SenWizard} page
* @returns {Boolean}
*/
addShareAddressBookToTextarea: function () {
if (ComRecipientModal.checkedList.length === 0) {
return false;
}
// Using tagit plugin
for (var i = 0; i < ComRecipientModal.checkedList.length; i++) {
$("#emailTags").tagit("createTag", ComRecipientModal.checkedList[i], ComRecipientModal.checkedList[i]);
}
// Off modal
ComRecipientModal.resetModal();
Modal.closeModal();
},
/**
* Reset value
* @returns {undefined}
*/
resetModal: function () {
var $this = ComRecipientModal;
$this.iDisplay = false;
$this.checkedList = [];
// sendwizard context
if ($this.packageId === null) {
//SelectedDocumentList.removeAll();
} else {
// package context
$.cookie("r_list", null);
$this.packageId = null;
}
}
};
var RecipientModal = {
checkedList: [], iDisplay: false, documentsSelected: [], aTable: null, packageId: null,
/**
* Add email to text area in step 3 or step 4 {SenWizard} page
* @returns {Boolean}
*/
addAddressBookToTextarea: function () {
if (RecipientModal.checkedList.length === 0) {
return false;
}
// Using tagit plugin
for (var i = 0; i < RecipientModal.checkedList.length; i++) {
$("#emailTags").tagit("createTag", RecipientModal.checkedList[i], RecipientModal.checkedList[i]);
}
// Off modal
RecipientModal.resetModal();
Modal.closeModal();
},
/**
* Add recipient to package
* @param {type} listRepDelDup
* @param {type} listIdNotDup
* @returns {undefined}
*/
addRecipientToPackage: function (listRepDelDup, listIdNotDup) {
var $this = RecipientModal;
var listIdRepDel = [];
if (listRepDelDup.length > 0) {
$.each(listRepDelDup, function (k, v) {
listIdRepDel.push(v.id);
});
}
// merge 2 list
var lRepPost = $.merge($.merge([], listIdRepDel), listIdNotDup);
var postData = {};
postData["PackageID"] = $this.packageId;
postData["RecipientID"] = lRepPost.join();
postData["SessionID"] = UserSession.getSessionID();
//Call API
$.ajax({
url: 'api/v1/AddPackageRecipient',
type: 'POST',
timeout: HoGoConst.APITimeout,
data: postData,
dataType: "json",
beforeSend: function () {
$('').appendTo("#contents");
Modal.closeModal();
},
success: function (data) {
//removeLoading('iAddingRecipient');
$('body').find('.hogo-bg-overlay-action').remove();
if (data.status === "OK") {
console.log("AddPackageRecipient");
//Add to distribution list
Package.showDistributionTable();
// Update package detail
Package.drawPackage();
// Redraw points on header
UserSession.updateUserInfo();
// Delete duplicate license recipient if have
if (listRepDelDup.length > 0) {
WizardCore.deleteLicenseDuplicate($this.packageId, listRepDelDup, 2);
}
// Reset modal
$this.resetModal();
} else {
// Insuffient points
if (data.status === APIConst.INSUFFICIENT_POINT) {
// Store selected document list
$.cookie("r_list", JSON.stringify($this.checkedList));
//Warning BuyPoint
Modal.showConfirmPopup({
title: i18n.t('history.package.message.insuffient_point.title'),
content: i18n.t('history.package.message.insuffient_point.content'),
cancelCallback: $this.resetModal, // clear cookie {d_list} & close modal
okCallback: HoGoUtils.goBuyPoint // go buy points
});
}
if (data.status === APIConst.MAX_TRANSACTION) {
// Show popup confirm
Modal.showAlert({
title: i18n.t('send_wizard.step_3.message.max_transaction.title'),
content: i18n.t('send_wizard.step_3.message.max_transaction.content')
});
}
}
}
});
},
/**
* Reset value
* @returns {undefined}
*/
resetModal: function () {
var $this = RecipientModal;
$this.iDisplay = false;
$this.checkedList = [];
// sendwizard context
if ($this.packageId === null) {
//SelectedDocumentList.removeAll();
} else {
// package context
$.cookie("r_list", null);
$this.packageId = null;
}
}
};
var GroupModel = {
checkedList: [], iDisplay: false, documentsSelected: [], aTable: null, packageId: null,
addFolderToTable: function () {
// console.log("here 3");
var that = GroupModel;
// Callback
that.cbAfterSelect && that.cbAfterSelect(that.checkedList);
Modal.closeModal();
},
resetModal: function () {
var $this = GroupModel;
$this.iDisplay = false;
$this.checkedList = [];
},
addAddressBookInGroupToTextarea: function () {
var params = {};
params["SessionID"] = UserSession.getSessionID();
params["GroupID"] = GroupModel.checkedList.toString();
$.ajax({
url: 'api/v1/GetEmailRecipientByGroupId',
type: 'POST',
data: params,
dataType: "json",
success: function (data) {
if (data.status === "OK") {
for (var i = 0; i < data.address.length; i++) {
$("#emailTags").tagit("createTag", data.address[i], data.address[i]);
}
} else {
error && error();
}
},
error: function () {
// window.location.href = "addressbooklist";
}
});
if (GroupModel.checkedList.length === 0) {
return false;
}
// Using tagit plugin
// for (var i = 0; i < GroupModel.checkedList.length; i++) {
//
// $("#emailTags").tagit("createTag", "donhulinh95@gmail.com", "donhulinh95@gmail.com");
// }
// Off modal
GroupModel.resetModel();
Modal.closeModal();
},
resetModel: function () {
var $this = GroupModel;
$this.iDisplay = false;
$this.checkedList = [];
// sendwizard context
if ($this.packageId === null) {
//SelectedDocumentList.removeAll();
} else {
// package context
$.cookie("r_list", null);
$this.packageId = null;
}
}
};
/**
* Make message modal. There're 3 type {1: Alert, 2: Confirm with one button, 3: Confirm with 2 button}
* @param {type} type
* @param {type} json
* @returns {undefined}
*/
function makeModal(type, json) {
var opts = json;
// Remove modal bg
$('.reveal-modal-bg').remove();
// Reinit
var title = opts.title || i18n.t('modal.default_title'),
closeTitle = i18n.t('modal.close_title'),
content = opts.content || opts.text || opts.msg;
var ok = opts.okTitle || i18n.t('buttons.ok');
var cancel = opts.cancelTitle || i18n.t('buttons.cancel');
var size = opts.size || 'medium'; // // Size {large | medium | small}
var isCloseOnClickBG = opts.closeClickBG || false;
// Prevent close when click OK. In this case you need to close manually
var preventClose = opts.preventClose || false;
// On load callback
var onLoad = opts.onLoad;
if (size === "large" || size === "lg")
size = "modal-lg";
// Modal object
var modal;
// Do show then bind the event to all buttons
function showThenBindEvent(contentHTML) {
// Make html
var html = '
' +
'
' +
'
' +
'
' +
'
' + title + '
' +
'
' +
'' +
'
' +
'
' +
'
' + contentHTML + '
';
// Display control or not
switch (type) {
case 1: // Alert none buttons
// Remove buttons
html = html + '
';
modal = $(html);
break;
case 2:
case 3: // Confirm 2 buttons
html = html + '' +
'
';
modal = $(html);
break;
case 5: // Confirm 2 buttons
var html = '
' +
'
' +
'
' +
'
' +
'
' + title + '
' +
'
' +
'' +
'
' +
'
' +
'
' + contentHTML + '
';
html = html + '' +
'
';
modal = $(html);
break;
case 4: // Alert none buttons
// Remove buttons
html = html + '' +
'';
modal = $(html);
default:
html = html + '';
break;
}
console.log(html);
// Tranlsate modal
modal.i18n();
// Input modal
modal.find(".ck").customInput();
// Show modal
modal.reveal({
closeonbackgroundclick: isCloseOnClickBG
});
// Execute when modal loaded
onLoad && onLoad(modal);
// Find all buttons
var btnX = modal.find('.close-reveal-modal'), btnOK = modal.find('.btn-ok'), btnCancel = modal.find('.btn-cancel');
// Bind event callback
btnOK && $(btnOK).on('click', function () {
// Close pp first
!preventClose && Modal.closeModal();
// Run this function
json.okCallback && json.okCallback(modal);
});
// Cancel callback
btnCancel && $(btnCancel).on('click', function () {
// Close modal
Modal.closeModal();
json.cancelCallback && json.cancelCallback(modal);
});
$(btnX).on('click', function () {
// Close modal
Modal.closeModal();
opts.onClose && opts.onClose();
});
}
// Support read modal from template
if (opts.templateUrl) {
$.get(opts.templateUrl, function (data) {
showThenBindEvent(data);
});
} else {
showThenBindEvent(content);
}
}
/**
* Make datatable popup
* @param {type} opts : There're many type {1: Existing document, 2: Existing addressbook, 3: }
* @returns {undefined}
*/
function makeDataTable(opts) {
// Make html first
var html = '
' +
'
' +
'
' +
'
';
var mDataProp = [];
var url = '', sDom = '', sorting = [], stateSave = false;
// Get current top of document
var currentTop = $(document).scrollTop();
switch (opts.type) {
case 1:
case 2: // Existing document {SendWizard/PackageDetail}
sorting = [[4, 'desc']];
if (opts.type === 1) {
url = 'api/v1/GetDocumentListDetail';
} else {
// Set packageId
DocumentModal.packageId = opts.packageId;
url = 'api/v1/GetDocumentListDetailByPackageId';
// Save state in case buying points
stateSave = true;
}
sDom = 'l<"clearfix"fp>irt';
html = html + '
";
}
$(".input-email").addClass("hide");
$('#list-service').html(wrapperContent);
$("#service0").prop("checked", "checked");
// When user only belong to 1 service we hide the list service
if (parseInt(data.totalResult) === 1) {
$('#service-content').addClass("hide");
} else {
$('#service-content').removeClass("hide");
}
$(".input-password").removeClass("hide");
$("#input_password").focus();
// Show back button
$(".back-btn").removeClass("hide");
//$(".admin-login-page").addClass("hide");
$("#errorText").hide();
} else {
HoGoUtils.enableButton('#button-login', {colorClass: 'orange', handler: Login.login, textInside: i18n.t('session.buttons.login')});
$("#errorText").html(i18n.t('error.wrong_username'));
$("#errorText").show();
}
} else {
HoGoUtils.enableButton('#button-login', {colorClass: 'orange', handler: Login.login, textInside: i18n.t('session.buttons.login')});
$("#errorText").html(i18n.t('error.wrong_username'));
$("#errorText").show();
}
});
},
loginServiceAdmin: function () {
// get login infor
var postData = Login.makeParamsLogin();
var request = $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/LoginServiceAdmin",
data: postData,
dataType: "json"
});
request.done(function (dataAdmin) {
if (dataAdmin) {
// data retrieved from url2 as provided by the first request
if (dataAdmin.status === "OK") {
u.setSessionID(dataAdmin.token);
switch (parseInt(dataAdmin.service_level)) {
case HoGoConst.SYSTEM_ADMIN:
window.location.href = serverHostAPI + "Distributor";
break;
case HoGoConst.DISTRIBUTOR:
window.location.href = serverHostAPI + "Service";
break;
case HoGoConst.COMPANY_ADMIN:
window.location.href = serverHostAPI + "UserList";
break;
default :
break;
}
} else {
HoGoUtils.enableButton('#button-login', {colorClass: 'orange', handler: Login.login, textInside: i18n.t('session.buttons.login')
});
if (dataAdmin.status === APIConst.WRONG_PASSWORD || dataAdmin.status === APIConst.inputParameterErrorStatus) {
$("#errorText").html(i18n.t('error.wrong_password'));
$("#errorText").show();
}
}
}
});
}
};
}(jQuery, UserSession, window));
//
// Manage entire send wizard process from encode to deliver to recipients
//
var WizardCore = (function ($, s) {
// Check whether has email or not
var hasEmail = false;
var isSubmitting = false;
var checkLicense = false;
var lRepDeleteOldLicense = [];
var lEmailRepRemain = [];
/**
* Checking tagit value is valid list email or not. It shows prompt when it's invalid and stop program. Otherwise, remove error prompt
* @returns {undefined}
*/
function checkTagit() {
z
$('.tagit-new').find('input').blur();
// Need to check before send
var c = HoGoUtils.isValidGroupEmail($("#emailInput").val());
if (!c) { // Need to be specify recipient
$('.tagit-new').find('input').focus();
$('#emailTags').validationEngine('showPrompt', $.validationEngineLanguage.allRules.validGroupEmail.alertText, 'red', 'topRight', true);
return false; // stop
} else {
// Remove it's unnecessary now
$('.emailTagsformError').remove();
return true;
}
}
/**
*
* @param {type} listObject
* @param {type} type
* @returns {Array}
*/
function getListIdOrMailFromObject(listObject, type) {
var lDup = [];
if (listObject.length > 0) {
$.each(listObject, function (k, v) {
if (type === 'email')
lDup.push(v.email);
if (type === 'id')
lDup.push(v.id);
});
}
return lDup;
}
/**
* Submit form to create package for 4 method
* @returns {Boolean}
*/
function doSubmit(package, cb, error) {
var pModel = WizardCore.getPackageModel();
// console.log(pModel);
var documents = pModel.getDocument();
var method = pModel.getMethod();
// Check license duplicate
var request = $.post('api/v1/CheckLicenseDuplicate', {
SessionID: s.getSessionID(),
Documents: documents.toString(),
Recipients: lEmailRepRemain.join()
}, function (data) {
// normally, lnewEmail always has value (b/c validate email filed)
var check = false;
if (data.status === 'OK') {
if (data.result.length > 0) {
// Have email duplicate
$.each(data.result, function (k, v) {
// if new duplicated email exists in list duplicated recipient
if (lEmailRepRemain.indexOf(v.mail_address) !== -1) {
check = true;
return check;
}
});
} else {
checkLicense = true;
}
if (check) {
// Stop code
error && error();
checkLicense = false;
showLicenseDuplicatePopup(1, {data: data});
}
}
});
request.done(function () {
if (checkLicense) {
// create package
var url = 'api/v1/CreatePackage';
var postData = {};
// Prepare to create package
postData["SessionID"] = s.getSessionID();
postData["Method"] = method;
postData["Documents"] = documents.toString();
if (package === null) {
var docExp = $("#dCalendar").val();
postData["DocumentExpireDate"] = DateUtils.convertToDBDate(docExp);
switch (method) {
case 1: // Direct send - This method isn't now using CreatePackage API//
postData["Recipients"] = $("#emailInput").val();
postData["Printing"] = $("#checkboxPrint").prop('checked');
postData["LocalCopies"] = $("#num_share").val();
postData["Folder"] = $("#folderName").val(); // Use folder
break;
case 2: // Create link
postData["Printing"] = $("#checkbox7").prop('checked');
postData["LocalCopies"] = $("#num_share").val();
postData["Folder"] = $("#folderName").val();
postData["LinkExpireDate"] = DateUtils.convertToDBDate($("#lCalendar").val());
postData["MaxDownloads"] = 999; //$('#numberDownload').val();
postData["Downloadable"] = $('#allow-download').prop('checked');
postData["Password"] = $('#newpassword').val();
break;
case 3:
case 4:// Anoymous - Specify
postData["Recipients"] = $("#emailInput").val();
postData["Printing"] = $("#checkboxPrint").prop('checked');
postData["LocalCopies"] = 2;
postData["Folder"] = "";
postData["Password"] = $("#newpassword").val();
postData["LinkExpireDate"] = DateUtils.convertToDBDate($("#lCalendar").val());
postData["MaxDownloads"] = 999;
postData["Downloadable"] = true; //Always "true" at this method
postData["Editable"] = ($('#editable').prop('checked')) ? 1 : 0;
default:
// Wrong method or not specify method
break;
}
} else {
postData["DocumentExpireDate"] = DateUtils.convertToDBDate(package.doc_expiry_date);
switch (method) {
case 1: // Direct send - This method isn't now using CreatePackage API//
postData["Recipients"] = package.emails;
postData["Printing"] = package.print;
postData["LocalCopies"] = package.local_copy;
postData["Folder"] = package.folder_name; // Use folder
// add new param
postData["is_view_browser"] = package.view_br;
postData["wm_text"] = package.wm_text;
postData["wm_color"] = package.wm_color;
postData["wm_position"] = package.wm_position;
break;
case 2: // Create link
postData["Printing"] = package.print;
postData["LocalCopies"] = package.local_copy;
postData["Folder"] = package.folder_name;
postData["LinkExpireDate"] = DateUtils.convertToDBDate(package.link_expiry_date);
postData["MaxDownloads"] = package.number_download;
postData["Downloadable"] = true;//false
postData["Password"] = package.link_password;
postData["PackageOption"] = package.package_option;
postData["ZipPassword"] = package.pass_file_zip;
// add new param
postData["is_view_browser"] = package.view_br;
postData["wm_text"] = package.wm_text;
postData["wm_color"] = package.wm_color;
postData["wm_position"] = package.wm_position;
break;
case 3:
case 4:// Anoymous - Specify
postData["Recipients"] = package.emails;
postData["Printing"] = package.print;
postData["LocalCopies"] = 2;
postData["Folder"] = "";
postData["Password"] = package.link_password;
postData["ZipPassword"] = package.pass_file_zip;
postData["LinkExpireDate"] = DateUtils.convertToDBDate(package.link_expiry_date);
postData["MaxDownloads"] = package.number_download;
postData["Downloadable"] = true; //Always "true" at this method
postData["Editable"] = (package.edit_save) ? 1 : 0;
if (method === 4 && package.package_type === 2) {
// Package contain only non protect document
// Remove all document protect setting
postData["DocumentExpireDate"] = DateUtils.convertToDBDate("");
postData["Printing"] = true;
postData["Editable"] = 1;
}
postData["PackageOption"] = package.package_option;
postData["is_view_browser"] = package.view_br;
postData["wm_text"] = package.wm_text;
postData["wm_color"] = package.wm_color;
postData["wm_position"] = package.wm_position;
default:
// Wrong method or not specify method
break;
}
}
// Request
var request = $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: url,
data: postData,
dataType: "json",
beforeSend: function () {
isSubmitting = true;
// Append mask
//appendLoadingWithText("iGettingDoc", "body", i18n.t('loader.create_package'), true);
$('').insertAfter(".wrapper_section");
// Show indicator
$("#validation .loader").show();
// Disable button
HoGoUtils.disableButton('#btnnext', {
colorClass: 'green',
isArrow: true,
textInside: i18n.t('send_wizard.step_3.buttons.status.creating')
});
}
});
// Promise request
request.done(function (data) {
isSubmitting = false;
if (data.status === 'OK') {
// Update new points
UserSession.getSessionData().done(function (data) {
UserSession.renderNameAndPoint(data);
});
if (lRepDeleteOldLicense.length > 0) {
// Delete License Duplicate
deleteLicenseDuplicate(data.package_id, lRepDeleteOldLicense, 1);
}
// $rootScope
var pm = WizardCore.getPackageModel();
switch (method) {
case 1:
if ($("#emailInput").length > 0 && $("#emailInput").val() !== "") // Update new value selected by user
pm.setRecipient($("#emailInput").val());
pm.setID(data.package_id);
var emailAddress = $("#emailInput").val();
sendMailDirectSend(data.package_id, emailAddress);
break;
case 2:
case 3:
case 4:
if ($("#emailInput").length > 0 && $("#emailInput").val() !== "") // Update new value selected by user
pm.setRecipient($("#emailInput").val());
pm.setID(data.package_id);
// Redirect to step 4
// $('.s4').click();
break;
default:
break;
}
// Callback
cb && cb(data);
} else {
$('#step-3').find('.hogo-bg-overlay-action').remove();
$("#validation .loader").hide();
// Enable NEXT button
HoGoUtils.enableButton('#btnnext', {
colorClass: 'green',
isArrow: true,
isSubmitForm: true,
textInside: i18n.t('buttons.next')
});
if (data.status === APIConst.INSUFFICIENT_POINT) {
// Show popup confirm
Modal.showConfirmPopup({
title: i18n.t('send_wizard.step_3.message.insuffient_point.title'),
content: i18n.t('send_wizard.step_3.message.insuffient_point.content'),
okCallback: goBuyingPoints
});
// Stop code
error && error();
} else if (data.status === APIConst.MAX_TRANSACTION) {
// Show popup
Modal.showAlert({
title: i18n.t('send_wizard.step_3.message.max_transaction.title'),
content: i18n.t('send_wizard.step_3.message.max_transaction.content')
});
// Stop code
error && error();
} else {
// None of document in HttpSession
if (data.status === APIConst.inputParameterErrorStatus) {
HoGoUtils.writeLog(data.status_desc);
// console.log('aaaaaa');
Modal.showAlert({content: i18n.t('error.unknown')});
} else {
fnSessionTimeout(data, null, 'login');
}
// Stop code
error && error();
}
}
});
}
});
}
/**
* get one element from duplicated license filter array
* @param {type} id
* @param {type} filter
* @returns {_L5925.getElement.filter}
*/
function getElement(id, filter) {
for (var i in filter) {
if (id === filter[i].id || id === filter[i].email)
return filter[i];
}
}
/**
* show Duplicated License Popup
* @param {type} type
* @param {type} json
* @returns {undefined}
*/
function showLicenseDuplicatePopup(type, json) {
var lDocDeleteOldLicense = [];
if (type === 2) {
lRepDeleteOldLicense = [];
}
// Filter data
var filter = [], data = json.data, typeCheck = parseInt(type);
// For send wizard and add recipient to package
if (typeCheck === 1 || typeCheck === 2) {
// change structure json data
for (var i in data.result) {
var x = data.result[i];
var y = getElement(x.recipient_id, filter);
if (y) {
if (y.docs)
y.docs.push({doc_id: x.document_id, pack_id: x.package_id, title: x.title});
} else {
filter.push({id: x.recipient_id, email: x.mail_address, docs: [{doc_id: x.document_id, pack_id: x.package_id, title: x.title}]});
}
}
}
// For add document to package and download page
if (typeCheck === 3 || typeCheck === 4) {
// change structure json data
for (var i in data.result) {
var x = data.result[i],
obj = getElement(x.document_id, filter);
if (obj) {
if (obj.reps)
obj.reps.push({rep_id: x.recipient_id, pack_id: x.package_id, email: x.mail_address});
} else {
filter.push({id: x.document_id, title: x.title, reps: [{rep_id: x.recipient_id, pack_id: x.package_id, email: x.mail_address}]});
}
}
}
// draw modal html
// $('.license-duplicate').remove();
var title = i18n.t("send_wizard.step_3.duplicate_license.title");
var html = '
' +
'
' +
'' +
'
' +
'
' +
'
' +
'' +
'' +
'' +
'' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' + //??
'
' + //??
'
';
var number_check = 0;
// var modal = $( html );
Modal.createModal(3, {
title: title,
content: html,
size: "large",
onLoad: function (modal) {
// For craete package and add recipient to package
if (typeCheck === 1 || typeCheck === 2) {
// show license duplicate to view
$.each(filter, function (key, value) {
var d = '
';
d += '
' + value.email + '
';
$.each(value.docs, function (k, v) {
d += '
' + v.title + '
';
});
d += '
';
$.each(value.docs, function (k1, v1) {
var page = 'PackageDetailDownload?packageId=' + v1.pack_id;
d += '
';
});
d += '
' +
'' +
'
';
modal.find('.content').append(d);
});
}
// add document to package
if (typeCheck === 3 || typeCheck === 4) {
$.each(filter, function (key, value) {
var d = '
';
$.each(value.reps, function (k, v) {
d += '
' + v.email + '
';
});
d += '
' + value.title + '
';
$.each(value.reps, function (k1, v1) {
var page = 'PackageDetailDownload?packageId=' + v1.pack_id;
d += '
';
});
d += '
' +
'' +
'
';
modal.find('.content').append(d);
});
}
// Custom control again
modal.find('.content .ck').customInput();
// bind check event to resend checkbox
$('.t-body').find('input').on('click', function () {
var $this = $(this);
var row = $this.closest('.divRow');
var id = (typeCheck === 1 || typeCheck === 2) ? row.attr('rep-id') : row.attr('doc-id');
var element = getElement(id, filter);
// if checked
if ($this.is(":checked")) {
row.addClass('activeRow');
number_check++;
if (typeCheck === 1 || typeCheck === 2)
HoGoUtils.addNode(lRepDeleteOldLicense, element, 'id');
if (typeCheck === 3 || typeCheck === 4) {
HoGoUtils.addNode(lDocDeleteOldLicense, element, 'id');
}
} else {
row.removeClass('activeRow');
number_check--;
if (typeCheck === 1 || typeCheck === 2)
HoGoUtils.removeNode(lRepDeleteOldLicense, element, 'id');
if (typeCheck === 3 || typeCheck === 4) {
HoGoUtils.removeNode(lDocDeleteOldLicense, element, 'id');
}
}
// check all
if (parseInt(number_check) === parseInt($('.t-body').find('input').length)) {
$('input#del').attr('checked', true);
$('label[for=del]').addClass("checked");
} else {
$('input#del').attr('checked', false);
$('label[for=del]').removeClass("checked");
}
});
// check all button
$('input#del').on('click', function () {
var checkboxlist = $('.t-body').find('input');
checkboxlist.each(function () {
var $this = $(this);
var row = $this.closest('.divRow');
var id = (typeCheck === 1 || typeCheck === 2) ? row.attr('rep-id') : row.attr('doc-id');
var element = getElement(id, filter);
if ($('input#del').is(":checked")) {
$this.attr('checked', true);
$('label[for=del' + id + ']').addClass("checked");
// For create package and add recipient to package
if (typeCheck === 1 || typeCheck === 2)
HoGoUtils.addNode(lRepDeleteOldLicense, element, 'id');
// For add document to package
if (typeCheck === 3 || typeCheck === 4)
HoGoUtils.addNode(lDocDeleteOldLicense, element, 'id');
number_check = checkboxlist.length;
$this.closest('.divRow').addClass('activeRow');
} else {
$this.attr('checked', false);
$('label[for=del' + id + ']').removeClass("checked");
// For create package and add recipient to package
if (typeCheck === 1 || typeCheck === 2)
HoGoUtils.removeNode(lRepDeleteOldLicense, element, 'id');
// For add document to package
if (typeCheck === 3 || typeCheck === 4)
HoGoUtils.removeNode(lDocDeleteOldLicense, element, 'id');
number_check = 0;
$this.closest('.divRow').removeClass('activeRow');
}
});
});
},
cancelCallback: function (modal) {
if (typeCheck === 4) {
// set value for multidownload and multidownloading
HoGoDownload.setisMultipleDownload(false);
HoGoDownload.setisMultiDownloading(false);
}
},
okCallback: function (modal) {
// create package
if (typeCheck === 1) {
// list email from filter object
var lEFilter = getListIdOrMailFromObject(filter, 'email');
var lEDup = getListIdOrMailFromObject(lRepDeleteOldLicense, 'email');
// remove recipient tag isn't selected to resend
for (var i in lEFilter) {
if (lEDup.indexOf(lEFilter[i]) === -1) {
$("#emailTags").tagit("removeTagByLabel", lEFilter[i]);
}
}
// remove list email filter from list email remain
for (var i in lEFilter) {
HoGoUtils.removeNode(lEmailRepRemain, lEFilter[i]);
}
checkLicense = true;
}
// add recipient to package
if (typeCheck === 2) {
var listIdNotDup = json.listIdRep;
var lIdFilter = getListIdOrMailFromObject(filter, 'id');
// get list recipientId not duplicate
for (var i in lIdFilter) {
HoGoUtils.removeNode(listIdNotDup, lIdFilter[i]);
}
if (lRepDeleteOldLicense.length > 0 || listIdNotDup.length > 0) {
json.fnCallback(lRepDeleteOldLicense, listIdNotDup);
}
}
// add document to package and download anonymous
if (typeCheck === 3 || typeCheck === 4) {
var listIdNotDup = json.listDocId;
var lIdFilter = getListIdOrMailFromObject(filter, 'id');
// get list documenttId not duplicate
for (var i in lIdFilter) {
HoGoUtils.removeNode(listIdNotDup, lIdFilter[i]);
}
if (lDocDeleteOldLicense.length > 0 || listIdNotDup.length > 0) {
// add doc to package
if (typeCheck === 3)
json.fnCallback(lDocDeleteOldLicense, listIdNotDup);
// download anonymous
else if (typeCheck === 4) {
if (json.isMultipleDownload) {
// download multiple documents
json.fnForMultiDownload(lDocDeleteOldLicense, listIdNotDup);
} else {
var docId = getListIdOrMailFromObject(lDocDeleteOldLicense, 'id');
// download one document (ether lDocDeleteOldLicense or listIdNotDup is empty)
json.fnForDownload(lDocDeleteOldLicense, docId.toString(), $("a[docid='" + docId + "']"));
}
}
}
}
}
});
}
/**
* delete duplicated license
* @param {type} packageId
* @param {type} lDeleteOldLicense
* @param {type} type
* @returns {undefined}
*/
function deleteLicenseDuplicate(packageId, lDeleteOldLicense, type) {
// parse data
var postData = [];
// post data return: [ "documentId1_emailAddress1", "documentId2_emailAddress2",..]
// 1: Create package, 2: Add recipient to package
if (parseInt(type) === 1 || parseInt(type) === 2) {
$.each(lDeleteOldLicense, function (key, value) {
var emailAddress = value.email;
$.each(value.docs, function (k, v) {
postData.push(v.doc_id + '_' + emailAddress);
});
});
}
// Add document to package
if (parseInt(type) === 3) {
$.each(lDeleteOldLicense, function (key, value) {
var id = value.id;
$.each(value.reps, function (k, v) {
postData.push(id + '_' + v.email);
});
});
}
$.post('api/v1/DeleteLicenseDuplicate', {
SessionID: s.getSessionID(),
PackageId: packageId,
Data: postData.join()
}, function (data) {
if (data.status !== 'OK') {
HoGoUtils.writeLog(data.status_desc);
Modal.showAlert({content: i18n.t('error.unknown')});
}
});
}
/**
* Do send email job. Should be used when DOM is ready
* @returns {Boolean}
*/
function doSendMail(sendEmailModal, cb) {
var pModel = WizardCore.getPackageModel();
var method = pModel.getMethod();
var pID = pModel.getID();
if (sendEmailModal === null) {
if (method === 2 || method === 3 || method === 4) {
// Blur input
$('.tagit-new').find('input').blur();
// List email will be sent
if ($.trim($('#emailInput').val()).length > 0) {
// Check valid list email
if (checkTagit() === false)
return;
hasEmail = true;
} else {
hasEmail = false;
}
}
} else {
if (sendEmailModal.emails !== null) {
hasEmail = true
} else {
hasEmail = false;
}
}
//Have email
if (hasEmail) {
if (sendEmailModal === null) {
var sEmail = null;
if (method === 2 || method === 3 || method === 4) {
sEmail = $.trim($('#emailInput').val());
}
var postData = {};
postData["PackageID"] = pID;
postData["EmailAddress"] = sEmail;
postData["SessionID"] = s.getSessionID();
postData["Language"] = $.trim($('#languageSelect').val());
//Get subject & message
var subject = $.trim($('#emailSubject').val());
var message = $.trim($('#emailMessage').val());
if (subject !== '') {
postData["Subject"] = subject;
}
if (message !== '') {
postData["Message"] = message;
}
//Posting to package notice for sending email
var request = $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/SendPackageNotice",
data: postData,
dataType: "json",
beforeSend: function () {
isSubmitting = true;
$("#validation .loader").show('fast');
$('').insertAfter(".wrapper_section");
HoGoUtils.disableButton('#btnFinish', {
colorClass: 'green',
textInside: i18n.t('send_wizard.step_4.buttons.status.sending')
});
}
});
// Promise request
request.done(function (data) {
isSubmitting = false;
if (data.status === "OK") {
// Redirect to step 5 (Congratulation)
$('.s5').click();
} else {
if (data.status === APIConst.sessionIdNotFound) {
window.location.href = 'login';
} else {
// Handle error
$('#step-4').find('.hogo-bg-overlay-action').remove();
HoGoUtils.enableButton('#btnFinish', {
colorClass: 'green',
isSubmitForm: true,
textInside: i18n.t('send_wizard.step_4.buttons.finish')
});
}
}
// Callback
cb && cb(data);
});
} else {
var sEmail = sendEmailModal.emails;
var postData = {};
postData["PackageID"] = pID;
postData["EmailAddress"] = sEmail;
postData["SessionID"] = s.getSessionID();
postData["Language"] = $.trim($('#languageSelect').val());
if (sendEmailModal.subject !== '') {
postData["Subject"] = sendEmailModal.subject;
}
if (sendEmailModal.message !== '') {
postData["Message"] = sendEmailModal.message;
}
//Posting to package notice for sending email
var request = $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/SendPackageNotice",
data: postData,
dataType: "json",
beforeSend: function () {
}
});
// Promise request
request.done(function (data) {
// isSubmitting = false;
//
// if (data.status === "OK") {
// // Redirect to step 5 (Congratulation)
// $('.s5').click();
// }
// else {
// if (data.status === APIConst.sessionIdNotFound) {
// window.location.href = 'login';
// }
// else {
// // Handle error
// $('#step-4').find('.hogo-bg-overlay-action').remove();
// HoGoUtils.enableButton('#btnFinish', {
// colorClass: 'green',
// isSubmitForm: true,
// textInside: i18n.t('send_wizard.step_4.buttons.finish')
// });
// }
// }
// Callback
cb && cb(data);
});
}
} else {
// Redirect to step 5 (Congratulation)
cb && cb();
}
}
/**
* Send an email to specific emails after creating package
* @param {type} pID
* @param {type} Emails
* @param {type} cb Callback after sending
* @returns {jqXHR}
*/
function sendMailDirectSend(pID, Emails, cb) {
var postData = {};
postData["PackageID"] = pID;
postData["EmailAddress"] = Emails;
postData["SessionID"] = s.getSessionID();
//Posting to package notice for sending email
var request = $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/SendPackageNotice",
data: postData,
dataType: "json"
});
// Promise request
request.done(function (data) {
// Redirect to step 5 (Congratulation)
// $('.s5').click();
cb && cb(data);
});
}
/**
* Redirect to buy point page
* @returns {undefined}
*/
function goBuyingPoints() {
var l = window.location;
var path = l.pathname;
var page = path.substring(path.lastIndexOf('/') + 1, path.length);
// Get path
var hash = l.hash;
var currentpage = page + hash;
// Store current state
var pModel = WizardCore.getPackageModel();
var rep = ($('#emailInput').length > 0) ? $('#emailInput').val() : "";
pModel.setRecipient(rep);
var m = JSON.stringify(pModel);
var json = JSON.parse(m);
json['u_id'] = s.getSessionID();
var scope = WizardCore.getScope("#step-1");
var package = scope.package;
// Store current package setting
var n = JSON.stringify(package);
var packageJson = JSON.parse(n);
packageJson['u_id'] = s.getSessionID();
$.cookie('step3', JSON.stringify(json));
$.cookie('package_step2', JSON.stringify(packageJson));
// Remove beforeunload event
window.onbeforeunload = null;
window.location.href = "BuyPoint?returnPath=" + currentpage;
}
/**
* Check valid documents for method before move to settings
* @returns {undefined}
*/
function checkPackage() {
// Method
var method;
$('input:radio[name=method]').each(function () {
if ($(this).attr('checked')) {
method = $(this).val();
}
});
var m = parseInt(method);
// Set package to $rootScope
var pModel = WizardCore.getPackageModel();
pModel.setMethod(m);
// ZERO type
if (m === 3 || m === 4) {
var checkPK = $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: 'api/v1/CheckValidDocuments',
data: {Method: m, DocumentIDs: pModel.getDocument().toString()},
dataType: "json",
beforeSend: function () {
isSubmitting = true;
// Disable button
HoGoUtils.disableButton('#btnnext', {colorClass: 'green', isArrow: true, textInside: i18n.t('buttons.status.checking')});
}
});
// Checking
checkPK.done(function (data) {
isSubmitting = false;
if (data.status === 'OK') {
switch (m) {
case 1: // Direct
$('.s3-push').click();
break;
case 2: // Link
$('.s3-online').click();
break;
case 3: // Adobe
$('.s3-zero').click();
break;
default:
$('.s1').click();
break;
}
//window.location.href = url;
} else {
// Unsupport files
if (data.status === APIConst.DOCUMENT_NOT_SUPPORT_ZERO_METHOD) {
//Show confirm
Modal.showAlert({
title: i18n.t('history.package.message.unsupported_files.title'),
content: i18n.t('history.package.message.unsupported_files.content')
});
//Enable buttons for choosing another method
HoGoUtils.enableButton('#btnnext', {colorClass: 'green', isArrow: true, handler: checkPackage, textInside: i18n.t('buttons.next')});
} else {
$('.s1').click();
}
}
});
} else {
switch (m) {
case 1: // Direct
$('.s3-push').click();
break;
case 2: // Link
$('.s3-online').click();
break;
}
//window.location.href = url;
}
}
/**
* Event drag file on our upload file block
* @returns {undefined}
*/
function dragEnter() {
$('#container').css({"opacity": 0.3, "filter": "alpha(opacity=30)"});
HoGoUtils.makeNotifyServer({
"msg": i18n.t('notification.drop_file'),
"autoClose": false
});
}
/**
* Event leave file our upload file block
* @returns {undefined}
*/
function dragLeave() {
$('#container').css({"opacity": "", "filter": ""});
HoGoUtils.makeNotifyServer({
"msg": i18n.t('notification.drop_file'),
"autoClose": true,
"time": 100
});
}
// Public method
return {
//
// Check validate form for any step
//
fStatus: false,
//
// Step 1 - Table new upload
//
nTable: null,
//
// Step 1 - Existing table
//
existingTable: null,
//
// Return the submitting status
//
isSubmit: function () {
return isSubmitting;
},
/**
* Check whether disable/enable buttons NEXT & CANCEL. This function is using for both context {SendWizard/AddDocument}
* @returns {undefined}
*/
setupButtons: function () {
var nDT = WizardCore.nTable;
if (HoGoUtils.getPageName() === 'sendwizard.html') {
var eDT = WizardCore.existingTable;
// No record available
if (nDT.fnSettings().fnRecordsTotal() === 0 && eDT.fnSettings().fnRecordsTotal() === 0) {
// Disable button
HoGoUtils.disableButton('#btnnext', {
colorClass: 'green',
isArrow: true,
textInside: i18n.t('buttons.next')
});
HoGoUtils.disableButton('#btnWarningCancelUploadOrEncode', {colorClass: 'red'});
} else {
// Check process upload is done or not
if (checkProcessUpload(HoGoUpload.uploader.files)) {
HoGoUtils.enableButton('#btnnext', {
colorClass: 'green',
isArrow: true,
isSubmitForm: true,
textInside: i18n.t('buttons.next')
});
}
//if (nDT.fnSettings().fnRecordsTotal() > 0) {
//Enable
HoGoUtils.enableButton('#btnWarningCancelUploadOrEncode', {
colorClass: 'red',
handler: HGEncode.cancelUploadDocument
});
//}
}
} else {
// AddDocument
if (nDT.fnSettings().fnRecordsTotal() === 0) {
// Disable button
HoGoUtils.disableButton('#btnnext', {
colorClass: 'green',
isArrow: true,
textInside: i18n.t('buttons.next')
});
HoGoUtils.disableButton('#btnWarningCancelUploadOrEncode', {
colorClass: 'red'
});
} else {
// Check process upload is in process or not
if (checkProcessUpload(HoGoUpload.uploader.files)) {
HoGoUtils.enableButton('#btnnext', {
colorClass: 'green',
isArrow: true,
isSubmitForm: true,
textInside: i18n.t('buttons.next')
});
}
HoGoUtils.enableButton('#btnWarningCancelUploadOrEncode', {
colorClass: 'red',
handler: HGEncode.cancelUploadDocument
});
}
}
},
//
// Encode document step 1
//
encodeDocument: function () {
HGEncode.encodeDocument();
},
//
// Do create package
//
doSubmit: doSubmit,
//
// Do send email
//
doSendMail: doSendMail,
/**
* Draw on view step 4 depend on method number
* @param {type} method
* @param {type} rep : Recipient's email
* @returns {undefined}
*/
setupView: function (method, rep) {
if (rep !== null)
$('#emailInput').val(rep);
switch (method) {
// Set up view map with method
case 2:
case 4: // Create link // Anonymous link
$('#emailWrapper').remove();
$('#tipsySpecifyLink').remove();
break;
case 3: // Specify recipient
var lR = rep.split(",");
$('#btnExistingAddressBook').remove();
$("#tipsyAnonymousLink").remove();
if (lR.length > 0) {
hasEmail = true;
// Tag it but readonly
$("#emailTags").tagit({
singleField: true,
singleFieldNode: $('#emailInput') // Value will be added here
});
$('ul#emailTags li input').attr('disabled', true);
}
break;
}
},
//
// Manage uploading, encoding
//
setupStep1: function () {
// Has tooltip
ToolTip.wizardTooltip();
// Set position for tooltips
$('#mailAddressTipsy,#expiryDateTipsy,#downloadTipsy,#expiryDocumentTipsy,#numberCopyTipsy,#passwordTipsy,#localCopyTipsy,#folderTipsy,#numberCopyTipsy').tipsy({
gravity: 'ne' // North - East
});
// Anable tool tip specify
$('#specifyRecTipsy').tipsy({
gravity: 'nw', // North - West
className: 'spec-recipient'
});
// Now that we have a plugin, we can listen for the new events
$('#uploader_drophere').unbind().draghover().on({
'draghoverstart': function () {
dragEnter();
},
'draghoverend': function () {
dragLeave();
}
});
// Request get existing documents
var getExistingDocument = $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/CheckDocumentList",
data: {'SessionID': s.getSessionID()},
dataType: "json"
});
// Check GUI: Display existing file or not - Promise
getExistingDocument.done(function (data) {
if (data.status === "OK") { //Has document
// TODO
} else {
// Hide button section
var t = $('#btnUploadFile').parents('table');
t.find('td').eq(2).remove();
t.find('td').eq(2).remove();
}
});
// Set recipient
lRepDeleteOldLicense = [];
lEmailRepRemain = [];
var lEmailDeleteOldLicense = getListIdOrMailFromObject(lRepDeleteOldLicense, 'email');
// Existing addressbook
if ($('#btnExistingAddressBook').length > 0) {
// Display existing recipients
// $('#btnExistingAddressBook').unbind('click').on('click', function () {
// Modal.getAddressBookList();
// });
// Autocomplete - Email suggestion - Create source
var autoCompelete = $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/GetMailAddress",
data: {sessionID: s.getSessionID()},
dataType: "json"
});
autoCompelete.done(function (data) {
var address = data.address; // Source for the list
$("#emailTags").tagit({
//tagSource: [ {value: 'email1@gmail.com', label: 'Hao: email1@gmail.com'}, {value: 'email2@gmail.com', label: 'Loan: email2@gmail.com'}, {value: 'email3@gmail.com', label: 'XA: email3@gmail.com'}],
availableTags: address,
afterTagAdded: function (event, ui) {
var tag = $(ui.tag[0]);
// Invalid email, we set border in red
if (!HoGoUtils.isValidEmail(ui.tagLabel)) {
tag.css({'border': '1px solid red'});
}
// check email exist or not in two list
if (!HoGoUtils.checkNodeExisted(lEmailDeleteOldLicense, ui.tagLabel) && !HoGoUtils.checkNodeExisted(lEmailRepRemain, ui.tagLabel)) {
lEmailRepRemain.push(ui.tagLabel);
}
},
afterTagRemoved: function (evt, ui) {
// update list
lEmailDeleteOldLicense = getListIdOrMailFromObject(lRepDeleteOldLicense, 'email');
// email belongs to list remain
if (!HoGoUtils.checkNodeExisted(lEmailDeleteOldLicense, ui.tagLabel)) {
HoGoUtils.removeNode(lEmailRepRemain, ui.tagLabel);
} else {
// email belongs to deleted license recipient list
HoGoUtils.removeNode(lEmailDeleteOldLicense, ui.tagLabel);
HoGoUtils.removeNode(lRepDeleteOldLicense, getElement(ui.tagLabel, lRepDeleteOldLicense), 'id');
}
},
singleField: true,
singleFieldNode: $('#emailInput') // Value will be set here
});
});
}
// Only using for Zero
$('#specifyRecipient').change(function () {
if ($(this).prop('checked')) {
$('.emailInputformError').remove();
// $('#textSpecifyMail').css({'opacity': 0.4, 'filter': 'alpha(opacity=40)'}); //IE9
// Remove all tag & disable it
$('#emailTags').tagit("removeAll");//.css('background-color', '#F1F1F1');
// $('ul#emailTags li input').css('background-color', '#F1F1F1!important');
// HoGoUtils.disableButton('#btnExistingAddressBook', {colorClass: 'orange'});
HoGoUtils.enableButton('#btnExistingAddressBook', {colorClass: 'orange', handler: Modal.getAddressBookList});
} else {
// Enable button
$('#textSpecifyMail').css('opacity', 1);
//Enable new tag
$('ul#emailTags li input').attr('disabled', false).css('background-color', '#fff');
;
$('#emailTags').css('background-color', '#FFF');
HoGoUtils.enableButton('#btnExistingAddressBook', {colorClass: 'orange', handler: Modal.getAddressBookList});
}
});
},
//
// Sending package notice
//
setupStep4: function () {
// Unbind events on this element such as drag & drop
$('#uploader_drophere').unbind();
// Has tooltip
ToolTip.wizardTooltip();
var pModel = WizardCore.getPackageModel();
// Get package information
if (pModel.getMethod() !== 1) { // Method has a link
$('').appendTo('#viewWrapper');
$.post('api/v1/GetPackageDetail', {PackageID: pModel.getID(), SessionID: s.getSessionID()}, function (data) {
$('.hogo-bg-overlay-action').remove();
var detail = data.detail;
$.each(detail, function (id, p) {
$('#fe_text').val(p.link_url);
});
});
}
// Enable button finish
HoGoUtils.enableButton('#btnFinish', {colorClass: 'green', isSubmitForm: true});
// Existing addressbook
if ($('#btnExistingAddressBook').length > 0) {
// Display existing recipients
$('#btnExistingAddressBook').unbind('click').on('click', function () {
$('body').find(".formError").remove();
Modal.getAddressBookList();
});
// Autocomplete - Email suggestion - Create source
var autoCompelete = $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/GetMailAddress",
data: {sessionID: s.getSessionID()},
dataType: "json"
});
autoCompelete.done(function (data) {
var address = data.address; // Source for the list
// Refer to: https://github.com/aehlke/tag-it
$("#emailTags").tagit({
availableTags: address,
afterTagAdded: function (event, ui) {
var tag = $(ui.tag[0]);
if (!HoGoUtils.isValidEmail(ui.tagLabel)) {
tag.css({'border': '1px solid red'});
}
},
singleField: true,
singleFieldNode: $('#emailInput') // Value will be set here
});
});
}
// Prevent enter action subject input
$('#emailSubject').keydown(function (event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
// Enter button
if (keycode === 13) {
return false;
}
});
// Check flash installed or not
// HoGoUtils.copyLink('#d_clip_button');
},
/**
* Get scope for each step (Get angular controller contains this element) using angular
* @param {type} selector : Element is contained by controller
* @returns {angular scope}
*/
getScope: function (selector) {
return angular.element($(selector)).scope();
},
/**
* Get package model that use for send wizard (Stored at $rootScope)
* @returns {Package model}
*/
getPackageModel: function () {
return this.getScope('#container').getPack();
},
showLicenseDuplicatePopup: function (type, json) {
showLicenseDuplicatePopup(type, json);
},
deleteLicenseDuplicate: function (packageId, lRepDeleteOldLicense, type) {
deleteLicenseDuplicate(packageId, lRepDeleteOldLicense, type);
}
};
}(jQuery, UserSession));
//
// Manage showing history
//
var History = (function ($, s) {
//History list table
var oTable;
//Type history. Init get all.
var typeHistory = "";
var userId = HoGoUtils.getParameter()['userID'];
//Init start/stop date
var startDate = convertFromDateObject(new Date(0)) + ' 00:00:00';
var stopDate = convertFromDateObject(new Date()) + ' 23:59:59';
// Current filter item
var cItem = null;
/**
* Get all history code behind item hasClass(filter-item) in filter History block.
*/
function getAllHistoryCode() {
var hCode = [];
$.each($('.filter-item'), function (k, v) {
hCode.push($(v).attr('history-code'));
});
return hCode.toString();
}
function makeRequestParam(aoData, type, startDate, stopDate) {
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;
}
});
post["Type"] = type;
post["StartDate"] = startDate;
post["StopDate"] = stopDate;
if (HoGoUtils.getPageName() === 'userdetail.html') {
post["UserID"] = HoGoUtils.getParameter()['userID'];
}
post["SessionID"] = s.getSessionID();
return post;
}
/**
* Filter history
* @returns {Boolean}
*/
function fHistory() {
//FStatus) return false; Check valid form
if (!History.fStatus)
return false;
var _this = cItem;
var p = makeParamFilter(_this);
startDate = p.s_date;
stopDate = p.e_date;
typeHistory = p.h_code;
//Write on Cookie
var hFilter = [];
hFilter.push(p);
$.cookie("h_filter", JSON.stringify(hFilter));
//Draw again
oTable.fnDraw();
}
/**
* Create a post parameters for filtering by history type and range date
* @returns json params object
*/
function makeParamFilter() {
var sDate = convertFromDateObject(new Date(0)) + ' 00:00:00';
var eDate = convertFromDateObject(new Date()) + ' 23:59:59';
//Check validate picker
if ($.trim($('#datepickerStart').val()) !== "")
sDate = $('#datepickerStart').val() + ' 00:00:00';
if ($.trim($('#datepickerEnd').val()) !== "")
eDate = $('#datepickerEnd').val() + ' 23:59:59';
//Count active group
var countActive = 0;
var type = [];
var groupFilter = [];
var paymentType = [];
//Get hisotry code
$.each($('.filter-item'), function (i, item) {
if ($(item).hasClass('active')) {
groupFilter.push(i);
countActive++;
type.push($(item).attr('history-code'));
}
});
// Get payment type
$.each($('.filter-item-child'), function (i, item) {
if ($(item).hasClass('active')) {
paymentType.push($(item).attr('type'));
}
});
//Back to ogrinal state
if (countActive === 3) {
$('.filter-item').removeClass('active');
countActive = 0;
}
//In case of reset
if (type.length === 0) {
//Clear all params to server
typeHistory = getAllHistoryCode();
} else {
//Filter history by posting entensial params
typeHistory = type.toString();
}
// Return param
return {"h_code": typeHistory, "s_date": sDate, "e_date": eDate, "group": groupFilter.toString(), "payment_type": paymentType.toString()};
}
return {
//Form status
fStatus: false,
/**
* Get datatable history list
* @returns {unresolved}
*/
getTableList: function () {
return oTable;
},
makeParamFilter: makeParamFilter,
/**
* Init element for History page
* @returns {undefined}
*/
init: function () {
// Validation filter form
HoGoUtils.validateForm('fValidation', History);
},
makeHistoryList: function (fnCallback) {
$("input.datepicker").datepicker({//Refer API: http://api.jqueryui.com/datepicker/
autoSize: true,
dateFormat: 'mm/dd/yy'
});
$('span.filter-item').die('click').live('click', function () {
//Toggle button
$(this).toggleClass('active');
$("#fValidation").submit();
});
//Get all type
typeHistory = getAllHistoryCode();
// Identify admin or user
var l = 'en';
if (s.getUserObject() !== null) {
l = s.getLang();
}
oTable = $('#tablepaging').dataTable({
"bInfo": false,
"bLengthChange": false,
"bPaginate": true,
"iDisplayLength": 10,
"sPaginationType": "full_numbers",
"oLanguage": DTUtils.DTLang,
"sDom": 'pli<"clear-right">tr',
"sAjaxSource": "api/v1/GetAllHistory",
"bServerSide": true,
"bProcessing": true,
"fnServerData": function (sSource, aoData, fnCallback, oSettings) {
$.ajax({
url: sSource,
type: 'POST',
timeout: HoGoConst.APITimeout,
dataType: "json",
data: makeRequestParam(aoData, typeHistory, startDate, stopDate),
success: function (data) {
if (data.status === "OK") {
var lang = i18n.lng();
var json = {"sEcho": data.sEcho, "iTotalDisplayRecords": data.totalResult, "aaData": []};
$.each(data.history_detail, function (key, value) {
var nameRecipient = "";
if (lang === "ja") {
nameRecipient = value.recipientNameJa;
if (nameRecipient === 'Recipient New') {
nameRecipient = value.repMailAddress;
}
} else {
nameRecipient = value.recipientName;
if (nameRecipient === 'New Recipient') {
nameRecipient = value.repMailAddress;
}
}
json.aaData.push({"historyID": value.historyID, "historyType": value.historyType, "packageID": value.packID, "documentName": value.documentName, "recipientName": nameRecipient, "createDate": DateUtils.convertFullDate(value.createDate), "point": value.point, "paymentType": value.paymentType, "nullValue": ""});
});
} 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,
"fnStateLoad": function (oSettings) {
//Only from package detail. Load previous state
if ($.cookie('l_p') === 'packagedetaillink.html' || $.cookie('l_p') === 'packagedetaildownload.html') {
//Read our Cookie
var fT = jQuery.parseJSON($.cookie("h_filter"));
if (fT !== undefined && fT !== null) {
var group;
$.each(fT, function (k, v) {
//Set value.
startDate = v.s_date;
stopDate = v.e_date;
typeHistory = v.h_code;
group = v.group;
//Draw on view
if (startDate !== "01/01/1970 00:00:00")
$('#datepickerStart').val(DateUtils.convertDate(startDate));
if (stopDate !== (convertFromDateObject(new Date()) + ' 23:59:59'))
$('#datepickerEnd').val(DateUtils.convertDate(stopDate));
});
//Draw selected
var lG = group.split(",");
if (lG.length > 0) {
$.each(lG, function (k1, v1) {
$.each($('.filter-item'), function (i) {
if (parseInt(v1) === i)
$(this).addClass('active');
});
});
}
}
//Read from Datatable cookie
var sData = this.oApi._fnReadCookie(oSettings.sCookiePrefix + oSettings.sInstance);
var oData;
try {
oData = (typeof $.parseJSON === 'function') ?
$.parseJSON(sData) : eval('(' + sData + ')');
} catch (e) {
oData = null;
}
return oData;
} else {
$.cookie('h_filter', null);
}
},
"fnRowCallback": function (nRow, aData) {
var historyType = aData.historyType;
var pointsT = i18n.t('session.label.points');
var sendWizardImage = "Images/1.1/Icon/Dark/send.png";
var inforImage = "Images/1.1/Icon/Dark/info.png";
var shoppingBasketImage = "Images/1.1/Icon/Dark/shopping.png";
var documentImage = "Images/1.1/Icon/Dark/document.png";
//Each type
switch (historyType) {
//405
case HoGoConst.DIRECT_SEND_TYPE:
$("td:eq(0)", nRow).html('');
$("td:eq(2)", nRow).html('
' + i18n.t('history.event.send_direct_type') + '
');
$("td:eq(3)", nRow).html('
' + aData.documentName + '
');
$("td:eq(4)", nRow).html('
' + aData.recipientName + '
');
break;
//406
case HoGoConst.CREATE_LINK_NONDOWNLOAD_TYPE:
$("td:eq(0)", nRow).html('');
$("td:eq(2)", nRow).html('
';
}
}
}
} else {
// Has been removed
nTR = nTR + '
' + v.email + '
';
}
// }
}
$('#dis1>tbody').append(nTR);
});
// We have to separate Direct Send, Zero with Create Link to draw distribution
// There's recipients
if (recipients.length > 0) {
// Draw distribution
for (var i = 0; i < recipients.length; i++) {
var nTR = "";
if (i % 2 === 0) {
nTR = nTR + '
';
} else {
nTR = nTR + '
';
}
//Count number removed
var iRemoved = 0;
var requests = [],
listDist = [];
for (var j = 0; j < documents.length; j++) {
// Getting status of document
var docIsRemoved = Distribution.isRemovedColumn(documents[j].id),
dis = Distribution.find(documents[j].id, recipients[i].id);
s
if (typeof dis === 'undefined') {
// Create fake data
if (docIsRemoved) {
dis = Distribution.createFakeDis(2); // Removed
} else {
dis = Distribution.createFakeDis(1); // Active
}
}
// Check open or not & not admin's view
if (typeof dis !== 'undefined' && dis.opened_status === 0 && isAdminLogged === false) {
// Valid DownloadID
if (dis.be_download_id !== null && dis.be_download_id.length === 32) {
//
// Checking time opened here
// Put as queue
// Only check status for protect document
if (parseInt(dis.is_encrypt) === 1) {
var req = $.ajax({
type: 'POST',
url: 'api/v1/GetDistributionStatus',
data: {SessionID: UserSession.getSessionID(), DownloadID: dis.be_download_id, UserID: HoGoUtils.getParameter()["userID"]}
});
requests.push(req);
listDist.push(dis);
}
}
}
// Check distribution object
if (dis) {
console.log(dis.status);
switch (dis.status) {
case 1: // Active
var emailClass = 'email';
var con = '';
// Invalid download ID
if (dis.be_download_id === null || dis.be_download_id.length !== 32) { // No access code
switch (dis.be_download_id) {
case HoGoConst.DISTRIBUTION_WAIT_DOWNLOAD_ID: // Waiting
con = '
' +
'
' +
'' +
'
' +
'
';
break;
case HoGoConst.DISTRIBUTION_DOWNLOAD_ID_ERROR: // Error distribution
// We should allow user re-active their distribution
con = '
' +
'
' +
'' +
'' +
'
' +
'
';
break;
default:
if (parseInt(dis.is_encrypt) === 1) {
console.log(dis.num_of_download);
con = '
' +
'
' +
'' +
'' +
'
' +
'
';
} else {
con = '
' +
'
' +
'
' +
'
';
}
break;
}
} else {
// Open
if (parseInt(dis.opened_status) === 1) {
emailClass = 'email-open';
}
if (method === HoGoConst.WIZARD_ANONYMOUS_TYPE) { // 4
if (parseInt(dis.is_encrypt) === 1) {
con = '
' +
'
' +
'' +
'' +
'
' +
'
';
} else {
con = '
' +
'
' +
'' +
'' +
'
' +
'
';
}
} else {
if (method === HoGoConst.WIZARD_CREATE_LINK_TYPE) {
if (parseInt(dis.is_encrypt) === 1) {
con = '
';
}
iRemoved++;
break;
case 3: // De-active
if (method === HoGoConst.WIZARD_ANONYMOUS_TYPE) { // 4
nTR = nTR + '
' +
'
' +
'' +
'' +
'
' +
'
';
} else {
nTR = nTR + '
' +
'
' +
'' +
'' +
'' +
'
' +
'
';
}
break;
case 4:
// Waiting
var con = '
' +
'
' +
'' +
'
' +
'
';
nTR = nTR + con;
break;
case 5:
// Error
var con = '
' +
'
' +
'' +
'' +
'
' +
'
';
nTR = nTR + con;
break;
}
}
}
$.when(requests).done(function (array) {
$.each(array, function (i, dfd) {
var dis = listDist[i];
dfd.done(function (data) {
if (data.status === "OK") {
if (data.open === 'true') {
var disImg = $('.distribution').find('img[dl-id=' + dis.be_download_id + ']');
disImg.removeClass('email').addClass('email-open');
// Update distribution on tootip
var tt = $(disImg).parents('.dis-wrapper').find('.tooltipstered');
var disObj = JSON.parse(tt.attr('data-dis'));
// Update content
disObj['opened_date'] = data.open_date;
disObj['opened_status'] = (data.open === 'true') ? 1 : 0;
// Remove invisible state if it's in this state
tt.removeClass('invisible');
// console.log("dfghjk");
// Update recipient info // Using only create link
if (method === HoGoConst.WIZARD_CREATE_LINK_TYPE) {
// New attribute
disObj['real_id'] = data.recipient_id;
disImg.attr('real-id', data.recipient_id);
// Set real id using for revoke
var anonymousID = disObj.id;
$('.distribution').find('#' + anonymousID).text(data.email);
}
// Other methods
tt.attr('data-dis', JSON.stringify(disObj));
}
}
});
});
});
nTR = nTR + '
';
// Remove one 1 row
if (iRemoved === documents.length) {
var tr = $('table#dis1').find('tr').eq(i + 1);
tr.addClass("removed");
tr.find('img').removeAttr('onclick').addClass('unclickable');
}
// Append to table
$('#dis2>tbody').append(nTR);
// At the last line
if (i === recipients.length - 1) {
$('table#dis2 th div').each(function (k, v) {
var docID = $(v).find('.doc-header').attr('doc-id');
// Removed column
if (Distribution.isRemovedColumn(docID)) {
$(v).closest('th').addClass('removed').find('img').removeAttr('onclick').addClass('unclickable');
} else {
// console.log(v);
// Add header number download
if (method === HoGoConst.WIZARD_ANONYMOUS_TYPE || HoGoConst.WIZARD_SPECIFY_LINK_TYPE) { // 4
var n = 0;
$('table#dis2 tbody tr td:nth-child(' + (k + 1) + ')').each(function (k, v) {
var dE = $(v).find('.dl-time');
if (dE.length > 0) {
switch (method) {
case HoGoConst.WIZARD_ANONYMOUS_TYPE:
n = n + parseInt(dE.text());
break;
case HoGoConst.WIZARD_SPECIFY_LINK_TYPE:
n = parseInt(dE.text()); // Caution
break;
default:
break;
}
}
});
var textDownoad = i18n.t('history.package.distribution.downloaded');
console.log(checkIsSync);
if (checkIsSync === 0) {
$(this).append('
' + textDownoad + ' ' + n + ' )
');
$(this).find('img').css("margin-top", 10);
} else {
$(this).find('img');// #Remove
}
}
}
});
}
}
} else {
// In case, create link distribution has no recipient - We display anonymous user (But just one row)
$('table#dis2 th').each(function (k, v) {
var docID = $(v).find('.doc-header').attr('doc-id');
// Check whether column is removed or not
if (Distribution.isRemovedColumn(docID)) {
$(v).addClass('removed').find('img').removeAttr('onclick').addClass('unclickable');
}
});
// Get i18n lang
var t = i18n.t('history.package.distribution.table.no_record');
$('table#dis1').append("
");
$('table#dis2').append("
" + t + "
");
}
//
// Display list with animation & remove loader
//
var disWrapper = $('#distributionWrapper');
disWrapper.removeClass('hid').css('display', 'none').fadeIn('slow');
$('#wrapperLoading').hide();
// Tooltip text
var openedT = i18n.t('history.package.label.opened_time'),
activeT = i18n.t('history.package.label.active'),
deactiveT = i18n.t('history.package.label.deactive'),
locationT = i18n.t('history.package.label.opened_location');
// Create options with tooltipster
if (!readonlyMode)
$('.dis-expand').each(function (i, item) {
$(item).tooltipster({
arrow: false,
interactive: true,
minWidth: 120,
content: "",
theme: 'distribution-menu',
offsetY: -10,
offsetX: -5,
position: 'bottom-right',
functionInit: function (origin) {
// First time init tt
// Remove tooltip if method CreateLink & not opened time
var dis = JSON.parse(origin.attr('data-dis'));
// Admin's visual
// if (isAdminLogged) {
// // Create dynamic content
// if (parseInt(dis.opened_status) === 0) {
// // Hide tooltip
//// $(origin).addClass('invisible');
// }
// } else { // User's view
if (method === HoGoConst.WIZARD_CREATE_LINK_TYPE) {
if (parseInt(dis.opened_status) === 0) {
// Hide tooltip
$(origin).addClass('invisible');
}
}
// }
},
functionBefore: function (origin, continueTooltip) {
// Get distribution object
var dis = JSON.parse(origin.attr('data-dis'));
// Find IMG
var wp = $(origin).parents('.dis-wrapper').find('.status');
// Admin's view
// if (isAdminLogged) {
// // View only item which has opened time
// if (parseInt(dis.opened_status) === 1) { // Opened
// var newContent = '
';
// Set new content
origin.tooltipster('content', $(newContent));
} else {
if (dis.status === 1) {
// Disable opened time
if (parseInt(dis.number_open) > 0) {
newContent = '
' + openHtml + revokeHtml + locationHtml + '
';
} else {
newContent = '
' + openHtml + revokeHtml + '
';
}
// Revoked
if (wp.hasClass('revoked')) {
newContent = '
' + openHtml + activeHtml + '
';
}
} else {
// Deactive or remove have no option
newContent = '
' + openHtml + locationHtml + '
';
}
}
} else {
// Others method not Create Link
if (parseInt(dis.opened_status) === 0) {
// Disable opened time
newContent = '
' + revokeHtml + '
';
// newContent = '
' + openHtml + revokeHtml + locationHtml + '
';;
// Revoked
if (wp.hasClass('revoked')) {
newContent = '
';
}
// Revoked
if (wp.hasClass('revoked')) {
if (parseInt(dis.number_open) > 0) {
newContent = '
' + openHtml + activeHtml + locationHtml + '
';
} else {
newContent = '
' + openHtml + activeHtml + '
';
}
}
}
}
// }
// Provide re-send method if any error
if (dis.status === 5) {
newContent = '
' + resendHtml + '
';
}
// CHeck content
if (newContent) {
// Set new content
origin.tooltipster('content', $(newContent));
}
// Continue
continueTooltip();
},
functionReady: function (origin, tooltip) {
// Manage new content here. Here's the combination between tooltipster & UI menu
$(tooltip).find('.dis-menu').menu({
select: function (event, ui) {
// Get distribution value
// Add feature Google Map tracking
var dis = JSON.parse(origin.attr('data-dis'));
var location = dis.location;
var item = ui.item, cmd = item.attr('cmd');
var disImg = $(origin).parents('.dis-wrapper').find('img.status');
switch (cmd) {
case 'open':
// Show opened time
if (parseInt(dis.number_open) > 0) {
Modal.showAlert({
title: i18n.t('history.package.message.opened_time.title'), // lang
content: "
");
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: "
");
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));