// Call api to get data//
// HoGo script v 2.0
// 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 GOOGLE_ENVIRONMENT = "production";
//
// Stripe key
//
var stripePuplicKey = "pk_live_Nj8frYtyf3WM1TOFfJrL1ffa";
//var stripePuplicKey = "pk_test_hoCROLJbcrwFP9uoXxbE3ukz";
var supportedFile = ['pdf', 'docx', 'xlsx', 'pptx', 'xlsm']; // 'pptx' for 2.0: pptx
// 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() {
// //console.log(modal);
// 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;
// check user input email or not
var email = $('#emailReferral').val();
if (!email) {
Modal.showAlert({
title: i18n.t('email.send_email.thank_you'),
content: i18n.t('email.send_email.confirm_mail')
});
registerReferralControlsEvent(false);
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);
goog_report_conversion('https://www.hogodoc.com/HoGo/signup?iscomplete=true&ud=' + data.user_id);
// goog_report_conversion('http://localhost:8080/signup/signup?iscomplete=true&ud=' + 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');
}
});
},
registerReferralControlsEvent: registerReferralControlsEvent
};
}(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) {
if (data.status === "OK") {
login = true;
user = data;
} else {
if ($thisObj.fnGetSessionError !== null)
$thisObj.fnGetSessionError(null, data);
}
if ($thisObj.fnGetSessionComplete !== null)
$thisObj.fnGetSessionComplete.call(null, data);
}
});
},
/**
* 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;
} 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 () {
//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());
}
});
},
/**
* 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;
if (sessionData.lang === 'auto' || sessionData.lang === '')
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;
}
};
}(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;
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));
//
// Utilities and much more
//
var HoGoUtils = (function ($) {
var country = new Array("United States", "Canada");
var state = new Array();
state["Canada"] = "Alberta|British Columbia|Manitoba|New Brunswick|Newfoundland|Northwest Territories|Nova Scotia|Nunavut|Ontario|Prince Edward Island|Quebec|Saskatchewan|Yukon Territory";
state["United States"] = "Alabama|Alaska|Arizona|Arkansas|California|Colorado|Connecticut|Delaware|District of Columbia|Florida|Georgia|Hawaii|Idaho|Illinois|Indiana|Iowa|Kansas|Kentucky|Louisiana|Maine|Maryland|Massachusetts|Michigan|Minnesota|Mississippi|Missouri|Montana|Nebraska|Nevada|New Hampshire|New Jersey|New Mexico|New York|North Carolina|North Dakota|Ohio|Oklahoma|Oregon|Pennsylvania|Rhode Island|South Carolina|South Dakota|Tennessee|Texas|Utah|Vermont|Virginia|Washington|West Virginia|Wisconsin|Wyoming";
/**
* Make buttons
* @param {type} type : {1 : Enable | 2: Disable}
* @param {type} selector
* @param {type} opts : {colorClass: class will be change, isArrow : button is arrow or not, isSubmitForm : this is submit or not, handler: function will be execute or nor, textInsde : text will be changed}
* @returns {undefined}
*/
function makeButton(type, selector, opts) {
var _this = $(selector);
switch (type) {
case 1: // Enable
// Remove grey class
_this.removeClass('grey');
// Arrow button or not
if (typeof opts.isArrow !== 'undefined' && opts.isArrow === true) {
_this.removeClass('grey-fw');
}
if (typeof opts.colorClass !== 'undefined' && opts.colorClass !== null) {
_this.addClass(opts.colorClass);
if (typeof opts.isArrow !== 'undefined' && opts.isArrow === true) {
_this.addClass(opts.colorClass + '-fw');
}
} else {
// Default color
_this.addClass('orange');
}
_this.unbind('click', false);
// Remove handler
if (typeof opts.isSubmitForm !== 'undefined' && opts.isSubmitForm === true) {
// Unbind all then bind
_this.addClass('submit_form').unbind('click').bind('click', function () {
var fID = opts.formID;
if (typeof fID !== 'undefined' && fID !== '' && fID !== null) {
$("#" + fID).submit();
} else {
fID = $(this).parents('form').attr('id');
$("#" + fID).submit();
}
});
}
//else {
var handler = opts.handler;
if (typeof handler !== 'undefined' && handler !== '' && handler !== null) {
//Remove all bind click first
_this.unbind('click').bind('click', handler);
}
//}
//Set text inside the button
var textInside = opts.textInside;
if (typeof textInside !== 'undefined' && textInside !== null) {
_this.html(textInside);
}
break;
case 2: // Disable
// Remove current color
var colorClass = opts.colorClass;
_this.addClass('grey');
if (typeof colorClass !== 'undefined' && colorClass !== null) {
_this.removeClass(colorClass);
if (typeof opts.isArrow !== 'undefined' && opts.isArrow === true) {
_this.removeClass(colorClass + '-fw');
_this.addClass('grey-fw');
}
} else {
// Default color be removed
if (_this.hasClass('orange'))
_this.removeClass('orange');
if (_this.hasClass('green'))
_this.removeClass('green');
}
//Remove hanlder
if (_this.hasClass('submit_form')) {
_this.removeClass('submit_form');
}
var handler = opts.handler;
if (typeof handler !== 'undefined' && handler !== '' && handler !== null) {
_this.unbind('click', handler).unbind('click');
} else {
// Remove all handler
_this.unbind('click');
}
_this.bind('click', false);
// Set text inside the button
var textInside = opts.textInside;
if (typeof textInside !== 'undefined' && textInside !== null) {
_this.text(textInside);
}
break;
default:
break;
}
}
return {
// Pattern match email
patternEmail: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
/**
* Check valid email base on regrex in validationEngine
* @param {type} email
* @returns {Boolean}
*/
isValidEmail: function (email) {
return this.patternEmail.test(email);
},
/**
* Check valid list email string which is separated by comma (,)
* @param {type} gEmail concated string email
* @returns {Boolean}
*/
isValidGroupEmail: function (gEmail) {
var array = gEmail.split(',');
for (var i = 0; i < array.length; i++) {
if (this.patternEmail.test($.trim(array[i])) === false) {
return false;
}
}
return true;
},
/**
* Message-Digest algorithm 5 (MD5)
* @param {type} string
* @returns {unresolved}
*/
MD5: function (string) {
function RotateLeft(lValue, iShiftBits) {
return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
}
function AddUnsigned(lX, lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function F(x, y, z) {
return (x & y) | ((~x) & z);
}
function G(x, y, z) {
return (x & z) | (y & (~z));
}
function H(x, y, z) {
return (x ^ y ^ z);
}
function I(x, y, z) {
return (y ^ (x | (~z)));
}
function FF(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
}
;
function GG(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
}
;
function HH(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
}
;
function II(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
}
;
function ConvertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1 = lMessageLength + 8;
var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
var lWordArray = Array(lNumberOfWords - 1);
var lBytePosition = 0;
var lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
}
;
function WordToHex(lValue) {
var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
}
return WordToHexValue;
}
;
function Utf8Encode(string) {
string = string.replace(/\r\n/g, "\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
;
var x = Array();
var k, AA, BB, CC, DD, a, b, c, d;
var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
var S41 = 6, S42 = 10, S43 = 15, S44 = 21;
string = Utf8Encode(string);
x = ConvertToWordArray(string);
a = 0x67452301;
b = 0xEFCDAB89;
c = 0x98BADCFE;
d = 0x10325476;
for (k = 0; k < x.length; k += 16) {
AA = a;
BB = b;
CC = c;
DD = d;
a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
a = AddUnsigned(a, AA);
b = AddUnsigned(b, BB);
c = AddUnsigned(c, CC);
d = AddUnsigned(d, DD);
}
var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
return temp.toLowerCase();
},
/**
* Generate ID
* @returns {String} ID
*/
createUUID: function () {
return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (d) {
var b = Math.random() * 16 | 0,
a = d === "x" ? b : (b & 3 | 8);
return a.toString(16);
});
},
/**
* Detect browser language. Now we just support two language so that if finding a language which isn't two that language, it'll return language default (en)
* @returns {string}
*/
detectBrowserLang: function () {
var lang = window.navigator.browserLanguage || window.navigator.language; // Language code: http://4umi.com/web/html/languagecodes.php || http://msdn.microsoft.com/en-us/library/ie/ms533052.aspx
var language = lang.substr(0, 2);
switch (language) {
case 'en':
case 'ja':
return language;
break;
default:
return HoGoConst.LANG_DEFAULT;
break;
}
},
/**
* Format string number to number format. For example: 2000 => 2,000
* @param {type} nStr : string number
* @returns {String}
*/
formatNumber: function (nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
},
/* Convert cent to $ or free and format number
* @param {number} cent The cent number
* @return {string} $
*/
convertMoneyFomat: function (cent, currency) {
if (cent !== undefined) {
if (cent === 0)
return "0";
else
{
if (currency === 'YEN')
{
return "¥" + this.formatNumber(cent);
} else
{
var usd = "$" + this.formatNumber(cent / 100);
return usd;
}
}
} else
return "";
},
/**
* Make a notify for user after server change somthing
* @param {type} msg
* @returns {undefined}
*/
makeNotifyServer: function (opt) {
var setting = opt || {}, action;
// Content
var bar = $('#notify-wrapper');
if (typeof opt !== 'object') {
action = opt.trim();
if (action === 'hide') {
bar.fadeOut();
}
} else {
// Default options
var defaults = {autoClose: true, msg: "", time: 3000};
var option = $.extend(defaults, setting);
if (bar.length === 0) {
var html = '
' +
'' +
'' + option.msg + '' +
'
';
$(html).insertBefore('#container');
} else {
bar.find('#notify-msg').text(option.msg);
bar.show();
}
if (option.autoClose) {
//Hide after timeout
setTimeout("$('#notify-wrapper').fadeOut();", option.time); // 3s
} else {
// Do something here
}
}
},
/**
* Get current page name
* @returns {String}
*/
getPageName: function () {
var aParts = window.location.pathname.split('/'),
sNameEQ = aParts[aParts.length - 1].replace(/[\/:]/g, "").toLowerCase();
var pageName = "";
if (sNameEQ.indexOf(".html") !== -1)
pageName = sNameEQ;
else {
if (sNameEQ.indexOf(".htm") !== -1) {
pageName = sNameEQ + "l"; // .htm => .html
} else
pageName = sNameEQ + ".html";
}
return pageName;
},
/**
* Get value of specific param. Example: /pagename?name=tmhao#/child => return
* @returns {Array}
*/
getParameter: function () {
var vars = [], hash;
var path = window.location.href.slice(window.location.href.indexOf('?') + 1);
var rPath = path;
// Remove hash if have
if (path.indexOf(location.hash)) {
rPath = path.substring(0, path.indexOf(location.hash));
}
var hashes = rPath.split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
/**
* Enable button
* @param {type} selector
* @param {type} opts : {colorClass (required), isSubmitForm (optional), handler (required if isSubmitForm is false or not specify), isArrow (optional - default: none) textInside (optional)}
* @returns {undefined}
*/
enableButton: function (selector, opts) {
makeButton(1, selector, opts);
},
/**
* Disable buttons
* @param {type} selector
* @param {type} opts {colorClass (required), isArrow (optional - default: none), textInside (optional)}
* @returns {undefined}
*/
disableButton: function (selector, opts) {
makeButton(2, selector, opts);
},
/**
* Validate form ID and set status to status param
* @param {type} formID
* @param {object} obj : This object contains a variable name 'fStatus'
* @returns {undefined}
*/
validateForm: function (formID, obj, opts) {
// Some opts
var position = "topRight"; // Default
if (typeof opts === 'object') {
position = (opts.position) ? opts.position : position;
}
$('form#' + formID).validationEngine({
scroll: false,
validationEventTrigger: "",
promptPosition: position,
onValidationComplete: function (form, status) {
if (typeof obj !== 'undefined') {
obj.fStatus = status;
} else {
formStatus = status;
}
}
});
},
/**
* Show our custom scrollbar
* @param {type} selector
* @returns {undefined}
*/
showScrollBar: function (selector) {
if ($(selector)) {
var e = $(selector);
e.mCustomScrollbar({
//autoHideScrollbar: true,
advanced: {
updateOnContentResize: true
}
});
}
},
/**
* Show calendar and call action callback
* @param {type} json
* @returns {undefined}
*/
showDatePicker: function (json) {
$('#' + json.input_id).datepicker({
autoSize: true,
//appendText: '(mm/dd/yyyy)',
dateFormat: 'mm/dd/yy',
beforeShow: function () {
if (typeof json.radio_id !== 'undefined') {
$('#' + json.radio_id).prop('checked', true).trigger('click');
}
},
onSelect: function () {
// Hide placeholder IE9
if (typeof json.radio_id !== 'undefined') {
$('label[for=' + json.input_id + ']').hide();
}
// Callback after on select
if (typeof json.callback !== 'undefined') {
// Execute function
json.callback();
}
}
// onClose: function() {
// $(this).trigger('blur');
// }
});
},
/**
* Cheking flash install on user's browser or not
* @returns {Boolean}
*/
checkFlashInstall: function () {
var support = false;
//IE only
if (navigator.appVersion.indexOf("MSIE") !== -1) {
try {
var flashObj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
if (flashObj !== null)
support = true;
} catch (e) {
support = false;
}
//W3C, better support in legacy browser
} else {
if (navigator.mimeTypes ["application/x-shockwave-flash"] !== 'undefined')
support = true;
}
return support;
},
/**
* Redirect to buy point
* @returns {undefined}
*/
goBuyPoint: function () {
//Get url
var loc = window.location;
var lpath = loc.pathname.split('/');
var pagename = lpath[lpath.length - 1].replace(/[\/:]/g, "");
var path = pagename + loc.search + loc.hash;
//Redirect
window.location.href = "BuyPoint?returnPath=" + path;
},
/**
* Determine action when user's session timeout
* @param {string} data : Data return from API
* @param {string} textError : Error text will be shown in case of showing popup
* @param {string} pageRedirect : Page name will be redirected to if there's not case of timeout
*/
fnSessionTimeout: function (data, textError, pageRedirect) {
if (data.status === APIConst.sessionIdNotFound || data.status === APIConst.adminSessionRequired) {
// Remove before unload handler
window.onbeforeunload = null;
window.location.href = 'login';
} else {
if (typeof pageRedirect !== 'undefined') {
window.location.href = pageRedirect;
} else {
if (typeof textError === 'undefined' || textError === null || textError === "") {
Modal.showAlert({content: i18n.t('error.unknown')});
} else {
Modal.showAlert({content: textError});
}
}
}
},
disableCalendar: function (idInputCalendar, classCheckValidate) {
if (typeof idInputCalendar !== 'undefined' && typeof classCheckValidate !== 'undefined') {
$('#' + idInputCalendar).removeClass(classCheckValidate).val('');
// Disable placeholder
$('label[for=' + idInputCalendar + ']').css('display', 'block');
// Clear error is displaying
$('.' + idInputCalendar + 'formError').remove();
}
},
enableCalendar: function (idInputCalendar, classCheckValidate) {
if (typeof idInputCalendar !== 'undefined' && typeof classCheckValidate !== 'undefined') {
$('#' + idInputCalendar).val('').addClass(classCheckValidate);
$('label[for=' + idInputCalendar + ']').hide();
}
},
/**
* Create list options for select tag with set of countries
* @param {type} countryID The select ID tag
* @returns {undefined}
*/
getListCountry: function (countryID) {
var option = $('#' + countryID)[0];
option.length = 0;
option.selectedIndex = 0;
for (var i = 0; i < country.length; i++) {
option.options[option.length] = new Option(country[i], country[i]);
}
},
/**
* Create list state for select tag with set of state
* @param {type} stateID The select ID tag
* @param {type} stateName State will be indexed
* @returns {undefined}
*/
getListState: function (stateID, stateName) {
var option = $('#' + stateID)[0];
option.length = 0;
option.selectedIndex = 0;
var state_arr = state[stateName].split("|");
for (var i = 0; i < state_arr.length; i++) {
option.options[option.length] = new Option(state_arr[i], state_arr[i]);
}
},
/**
* Center an elemenet
* @param {type} e : jQuery object
* @returns {undefined}
*/
centerElemlent: function (e) {
var $self = e;
//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;
// cssProp.height = height;
cssProp.top = '50%';
cssProp.marginTop = halfHeight;
// 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);
},
/**
* Create a loading bar center of a page
* @returns {$}
*/
createLoadingBar: function () {
$('
LOADING...
').appendTo('body');
var p = $('.hg-processing');
this.centerElemlent(p);
return p;
},
/**
* Copy to clipboard action
* @param {type} btnSelector : Button copy
* @returns {undefined}
*/
copyLink: function (btnSelector) {
// Check flash install or not
if (ClientInfo.checkFlashPlayerInstall()) {
//Checking flash
var client = new ZeroClipboard($(btnSelector), {
moviePath: "Images/ZeroClipboard.swf"
});
// Loaded
client.on("load", function (client) {
client.on("complete", function (client, args) {
if (args.text !== "") {
// Make a notify
HoGoUtils.makeNotifyServer({
"msg": i18n.t('notification.link_copied.content'),
"autoClose": true,
"time": 400
})
}
});
});
} else {
//Notify the flash not installed
Modal.showAlert({
title: i18n.t('notification.flash_not_installed.title'),
content: i18n.t('notification.flash_not_installed.content')
});
}
},
/**
* Manage actions on whole page
* @param {type} pName
* @returns {undefined}
*/
manageActionsOnPage: function (pName) {
switch (pName) {
// SendWizard context
case 'sendwizard.html':
var sMenu = $("#sendWinzardMenuDiv");
var step = HoGoUtils.getParameter()["step"];
sMenu.find('i.header-sprites').removeClass('icon-menu-send').addClass('icon-menu-send-active');
sMenu.find('span').css('color', '#077194');
if (step !== '4Link' && step !== '5') { // step = 1, 2, 3
sMenu.find('a').removeAttr('href').css('cursor', 'default');
}
break;
// Addressbook context
case 'addressbooklist.html':
case 'addrecipient.html':
case 'recipientdetail.html':
var rMenu = $("#addressbookMenuDiv");
rMenu.find('.header-sprites').removeClass('icon-menu-addressbook').addClass('icon-menu-addressbook-active');
rMenu.find('span').css('color', '#077194');
if (pName === 'addressbooklist.html') {
rMenu.find('a').removeAttr('href');
// Refresh list
rMenu.find('a').bind('click', function () {
AddressBook.getTableList().fnDraw();
});
}
break;
// Document context
case 'mydocumentlist.html':
case 'adddocument.html':
case 'mydocumentdetail.html': // Document page
var dMenu = $("#mydocumentMenuDiv");
dMenu.find('i.header-sprites').removeClass('icon-menu-documents').addClass('icon-menu-documents-active');
dMenu.find('span').css('color', '#077194');
// Remove only this page
if (pName === 'mydocumentlist.html') {
dMenu.find('a').removeAttr('href');
// Refresh list
dMenu.find('a').bind('click', function () {
MyDocument.getTable().fnDraw();
});
}
break;
// History context
case 'history.html':
case 'packagedetaildownload.html':
case 'packagedetaillink.html':
var hMenu = $("#historyMenuDiv");
hMenu.find('i.header-sprites').removeClass('icon-menu-history').addClass('icon-menu-history-active');
hMenu.find('span').css('color', '#077194');
if (pName === 'history.html') {
hMenu.find('a').removeAttr('href');
// Refresh list
hMenu.find('a').bind('click', function () {
History.getTableList().fnDraw();
});
}
break;
}
},
/**
* Make an IP request
* @returns {jqXHR}
*/
makeIPRequset: function () {
return $.ajax({
type: 'GET',
url: 'api/v1/GetCountryCode', //-- We use this api as a free service
dataType: 'json',
timeout: HoGoConst.EXTERNAL_TIMEOUT // 1 min
});
},
/**
*
* @param {type} page
* @param {type} lang
* @returns {undefined}
*/
renderNameBaseLang: function (page, lang) {
switch (page) {
case 'myaccount.html':
{
// Render view depend user's country
var tblAccount = $('table#tbAccountInfo');
var accountForm = $('div#accountInfo');
console.log(lang);
switch (lang) {
case 'ja':
case 'vi':
// First Name
tblAccount.find('tr:eq(0)').replaceWith('
');
accountForm.find('div#cFirstName').insertAfter(accountForm.find('div#cLastName'));
accountForm.find('div#cMiddleName').hide();
break;
default:
// First Name
tblAccount.find('tr:eq(0)').replaceWith('
');
accountForm.find('div#cMiddleName').show();
accountForm.find('div#cFirstName').insertBefore(accountForm.find('div#cMiddleName'));
accountForm.find('div#cLastName').insertAfter(accountForm.find('div#cMiddleName'));
break;
}
break;
}
case 'signup.html':
{
// Render view depend user's country
var signupForm = $('div.form-signup form');
switch (lang) {
case 'ja':
case 'vi':
// First Name
signupForm.find('div:eq(0)').replaceWith('
' +
'
' +
'' +
'
');
// Last Name
signupForm.find('div:eq(3)').replaceWith('
' +
'
' +
'' +
'
');
break;
default:
// First Name
signupForm.find('div:eq(0)').replaceWith('
' +
'' + '
' +
'' +
'
');
// Last Name
signupForm.find('div:eq(3)').replaceWith('
' +
'
' +
'' +
'
');
break;
}
break;
}
case 'recipientdetail.html':
case 'addrecipient.html':
{
// Render view depend user's country
var tblAccount = $('table.info');
switch (lang) {
case 'ja':
case 'vi':
$('#contents').find('div#dvMiddleName').hide();
$('#contents').find('div#dvFirstName').insertAfter($('#contents').find('div#dvLastName'));
// // First Name
// tblAccount.find('tr:eq(0)').replaceWith('
' +
// '
' + i18n.t('addressbook.form.last_name') + '
' +
// '
' +
// '
');
// // Middle Name
// tblAccount.find('tr:eq(1)').hide();
// // Last Name
// tblAccount.find('tr:eq(2)').replaceWith('
' +
// '
' + i18n.t('addressbook.form.first_name') + '
' +
// '
' +
// '
');
break;
default:
// First Name
tblAccount.find('tr:eq(0)').replaceWith('
' +
'
' + i18n.t('addressbook.form.first_name') + '
' +
'
' +
'
');
// Middle Name
tblAccount.find('tr:eq(1)').show();
// Last Name
tblAccount.find('tr:eq(2)').replaceWith('
' +
'
' + i18n.t('addressbook.form.last_name') + '
' +
'
' +
'
');
break;
}
break;
}
}
},
/**
* Write log message if user's browser supports console
* @param {type} message
* @returns {undefined}
*/
writeLog: function (message) {
if (typeof console !== 'undefined') {
}
},
/**
* Parse history code to meaningfultext
* @param {type} historyType
* @returns {String}
*/
parseHistoryTypeToText: function (historyType) {
switch (historyType) {
//405
case HoGoConst.DIRECT_SEND_TYPE:
return i18n.t('history.event.send_direct_type');
//406
case HoGoConst.CREATE_LINK_NONDOWNLOAD_TYPE:
return i18n.t('history.event.create_link_nondownload_type');
//407
case HoGoConst.CREATE_LINK_DOWNLOAD_TYPE:
return i18n.t('history.event.create_link_download_type');
//411
case HoGoConst.LINK_SPECIFY_CREATED_TYPE:
return i18n.t('history.event.create_link_specify_recipient');
//412
case HoGoConst.LINK_ANONYMOUS_CREATED_TYPE:
return i18n.t('history.event.create_link_anonymous');
//408
case HoGoConst.PURCHASE_POINTS_TYPE:
return i18n.t('history.event.package_purchase_type');
//504
case HoGoConst.ADMIN_REFUND_TYPE:
return i18n.t('history.event.admin_refund_type');
//505
case HoGoConst.ADMIN_ADD_POINTS:
return i18n.t('history.event.package_recieve_type');
//403 -- Login
case HoGoConst.LOGIN_TYPE:
return i18n.t('history.event.user_login_type');
//404 -- Logout
case HoGoConst.LOGOUT_TYPE:
return i18n.t('history.event.user_logout_type');
//604 -- Link expired
case HoGoConst.LINK_EXPIRED_TYPE:
return i18n.t('history.event.link_expired_type');
//603 -- Document expired
case HoGoConst.DOCUMENT_EXPIRED_TYPE:
return i18n.t('history.event.document_expired_type');
//200 -- Document added
case HoGoConst.DOCUMENT_ADDED_TYPE:
return i18n.t('history.event.add_document_type');
//202 -- Document deleted
case HoGoConst.DOCUMENT_DELETED_TYPE:
return i18n.t('history.event.delete_document_type');
//102 -- Package deleted
case HoGoConst.PACKAGE_DELETED_TYPE:
return i18n.t('history.event.delete_package_type');
// 601
case HoGoConst.DOCUMENT_VIEWED_TYPE:
return i18n.t('history.event.document_viewed');
// 602
case HoGoConst.DOCUMENT_DOWNLOADED_TYPE:
return i18n.t('history.event.document_downloaded');
// 606
case HoGoConst.DOCUMENT_OPENED_TYPE:
return i18n.t('history.event.document_opened');
//201
case HoGoConst.DOCUMENT_UPDATED_TYPE:
return i18n.t('history.event.document_edited');
// 300
case HoGoConst.RECIPIENT_ADDED_TYPE:
return i18n.t('history.event.recipient_added');
// 301
case HoGoConst.RECIPIENT_UPDATED_TYPE:
return i18n.t('history.event.recipient_edited');
default:
return historyType;//"N/A";
}
},
/**
* Get file extension based on its name
* @param {type} fileName
* @returns {unresolved}
*/
getFileExtension: function (fileName) {
var extension = fileName.substr((fileName.lastIndexOf('.') + 1));
return extension.toLowerCase();
},
/**
* Show document icon from document type
* @param {type} element jQuery object
* @param {type} type type {1, 2, 3, 4}. Refer to HoGoConst to know exactly what it is
*/
drawDocumentIconFromType: function (element, type) {
switch (parseInt(type)) {
case HoGoConst.FILE_PDF_TYPE:
element.addClass('pdf-icon').attr('title', i18n.t('mydocument.type_document.pdf'));
break;
case HoGoConst.FILE_WORD_TYPE:
element.addClass('word-icon').attr('title', i18n.t('mydocument.type_document.word'));
break;
case HoGoConst.FILE_EXCEL_TYPE:
case HoGoConst.FILE_XLSM_TYPE:
element.addClass('excel-icon').attr('title', i18n.t('mydocument.type_document.excel'));
break;
case HoGoConst.FILE_POWERPOINT_TYPE:
element.addClass('powerpoint-icon').attr('title', i18n.t('mydocument.type_document.powerpoint'));
break;
}
},
/**
* Get file extension from file type
* @param {type} type {1, 2, 3, 4}. Refer to HoGoConst to know exactly what it is
* @returns {String}
*/
getExtFromFileType: function (type) {
var ext = null;
switch (parseInt(type)) {
case HoGoConst.FILE_PDF_TYPE:
ext = 'pdf';
break;
case HoGoConst.FILE_WORD_TYPE:
ext = 'docx';
break;
case HoGoConst.FILE_EXCEL_TYPE:
ext = 'xlsx';
break;
case HoGoConst.FILE_POWERPOINT_TYPE:
ext = 'pptx';
break;
case HoGoConst.FILE_XLSM_TYPE:
ext = 'xlsm';
break;
}
return ext;
},
/**
* Get user's local timezone. It supports from IE6 +
* @returns {Number}
*/
getLocalTimeZone: function () {
return (new Date().getTimezoneOffset( ) / 60) * (-1);
},
/**
* Check new node is existed on the list node
* @param {type} listNode
* @param {type} newNode
* @returns {Boolean}
*/
checkNodeExisted: function (listNode, newNode) {
var check = false;
$.each(listNode, function (index, v) {
if (v === newNode) {
check = true;
return check;
}
});
return check;
},
/**
* remove node on list node
* @param {type} listNode
* @param {type} node
* @returns {undefined}
*/
removeNode: function (listNode, node, attr) {
var index = -1;
if (!attr) {
index = $.inArray(node, listNode);
} else {
for (var i in listNode) {
var n = listNode[i];
// Check exist attr
if (attr in node && attr in n) {
// Compare
if (n[attr] == node[attr]) {
index = i;
}
}
}
}
// Push
if (index != -1) {
listNode.splice(index, 1);
}
},
/**
* add node into list node
* @param {type} listNode
* @param {type} node
* @param {type} attr
* @returns {undefined}
*/
addNode: function (listNode, node, attr) {
var index = -1;
if (!attr) {
index = $.inArray(node, listNode);
} else {
for (var i in listNode) {
var n = listNode[i];
// Check exist attr
if (node.hasOwnProperty(attr) && attr in n) {
// Compare
if (n[attr] == node[attr]) {
index = i;
}
}
}
}
// Push
if (index == -1) {
listNode.push(node);
}
}
};
}(jQuery));
//
// Contain API const returned
//
var APIConst = {
/* SessionID not found */
sessionIdNotFound: "SessionIdNotFound",
/* Insuffient point */
INSUFFICIENT_POINT: "InsufficientPoint",
/* 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,
/* 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,
/* 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"
};
//
// 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;
}
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["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;
}
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) {
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) {
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();
}
}
};
//
// 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() + " " + dateObj.getHours() + ":" + dateObj.getMinutes() + ":" + dateObj.getSeconds();
}
} 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
});
}
}
}
});
},
/**
* 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 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]);
}
$(document).trigger('nifty.event');
// 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") {
//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
});
}
}
}
});
},
/**
* 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;
}
}
};
/**
* 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;
default:
html = html + '';
break;
}
// 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();
});
}
// 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 + '
' +
'
' +
'' +
'
' +
'
' +
'' +
'
' +
'
' +
'' +
'' +
'
' +
'
' +
'
' +
'' +
'
' +
'
' +
'' +
'
' +
'
' +
'' +
'
' +
'
' +
'' +
'
' +
'' +
'
' +
'
' +
'
' +
'' +
' ' +
'' +
'
' +
'
' +
'
' +
'
';
mDataProp = [{"mDataProp": "id"}, {"mDataProp": "file_name"}, {"mDataProp": "title"}, {"mDataProp": "type"}, {"mDataProp": "create_date"}];
break;
case 3:
case 4: // Existing recipient
sorting = [[3, 'desc']];
sDom = 'l<"clearfix"fp>irt';
if (opts.type === 3) {
url = 'api/v1/GetRecipientListDetail';
} else {
// Set packageId
RecipientModal.packageId = opts.packageId;
url = 'api/v1/GetRecipientListDetailByPackageId';
// Save state in case buying points
stateSave = true;
}
html = html + '
' +
'
' +
'' +
'
' +
'
' +
'' +
'
' +
'
' +
'' +
'' +
'
' +
'
' +
'
' +
'' +
'
' +
'
' +
'' +
'
' +
'
' +
'' +
'
' +
'' +
'
' +
'
' +
'
' +
'' +
' ' +
'' +
'
' +
'
' +
'
';
mDataProp = [{"mDataProp": "id"}, {"mDataProp": "name"}, {"mDataProp": "email"}, {"mDataProp": "create_date"}];
break;
}
html = html + "
";
// Append to make table
var modal = $(html).appendTo('body').hide();
// Make table
$('#' + opts.tableID).dataTable({// tableID {required}
"aaSorting": sorting, // sorting
"bDestroy": true,
"bInfo": false,
"bLengthChange": false,
"bPaginate": true,
"iDisplayLength": 10,
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"oLanguage": DTUtils.DTLang,
"sDom": sDom, // sDom
"sAjaxSource": url, // url {required}
"bServerSide": true,
"bProcessing": true,
"bStateSave": stateSave,
"fnStateLoad": function (oSettings) {
//Load previous state if just have bought points
if ((opts.type === 2 && $.cookie('l_p') === 'paymentinfo.html' && $.cookie('d_list') !== null) || (opts.type === 4 && $.cookie('l_p') === 'paymentinfo.html' && $.cookie('r_list') !== null)) {
// Get d_list store before
if (opts.type === 2) {
DocumentModal.checkedList = jQuery.parseJSON($.cookie("d_list")); // Document list stored to cookie
} else {
RecipientModal.checkedList = jQuery.parseJSON($.cookie("r_list")); // Recipient list stored to 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;
}
//Set search word on field
if (oData !== null) {
// Previous text search
if (oData.oSearch.sSearch !== null)
$('#' + opts.tableID + '_filter').val(oData.oSearch.sSearch);
else
$('#' + opts.tableID + '_filter').val('');
} else {
//set search null
$('#' + opts.tableID + '_filter').val('');
}
return oData;
} else {
return null;
}
},
"fnServerData": function (sSource, aoData, fnCallback, oSettings) {
// Call to server getting data
$("#unique").addClass('overlay');
var postData = {};
switch (opts.type) { // type {required}
case 1: // Existing document SendWizard
postData = DTUtils.documentListPostData(aoData);
postData["DocumentIDs"] = opts.removedIds.toString();
break;
case 2: // Existing document package - opts.packageId {required}
postData = DTUtils.documentListByPackageIdPostData(aoData, opts.packageId, opts.method);
break;
case 3: // Existing recpient - sendwizad
postData = DTUtils.recipientListPostDataForSendWizard(aoData);
var mailExist = $("#emailInput").val(); //Type of dependancy
postData["emails"] = mailExist;
break;
case 4: // Existing recipient package
postData = DTUtils.recipientListByPackageIdPostData(aoData, opts.packageId);
break;
default:
break;
}
// Make request
var request = $.ajax({
url: sSource,
type: "POST",
dataType: "json",
data: postData,
timeout: HoGoConst.APITimeout,
beforeSend: function () {
// Loading for the first time
if (DocumentModal.iDisplay === false && RecipientModal.iDisplay === false) {
// Not allow scrolling
$('').appendTo('body');
}
}
});
request.done(function (data) {
// Check whether there's any existing popup
if (DocumentModal.iDisplay === false && RecipientModal.iDisplay === false) {
$('body').find('.hogo-bg-overlay-action').remove();
}
// $("#unique").css("opacity", "1");
$("#unique").removeClass("overlay");
// if (DocumentModal.checkedList.length > 0) {
// HoGoUtils.enableButton('#btnAddDoc', {
// colorClass: 'green',
// handler: DocumentModal.addDocumentToExistingTable
// });
// }
if (data.status === 'OK') {
var json = {"sEcho": data.sEcho, "iTotalDisplayRecords": data.totalResult, "aaData": []};
// Show modal
modal.show();
switch (opts.type) {
case 1:
case 2: // Existing document
$.each(data.document_detail, function (key, value) {
json.aaData.push({"id": value.id, "title": value.title, "file_name": value.file_name, "type": value.type, "create_date": value.create_date, "status": value.status});
});
// Set data source
fnCallback(json);
// Display
if (!DocumentModal.iDisplay) {
DocumentModal.iDisplay = true;
modal.reveal({"closeonbackgroundclick": false, scrolltop: currentTop});
}
break;
case 3:
case 4:// Existing recipient {sendwizard}
$.each(data.recipient_detail, function (key, value) {
var name = "";
if (value.middle_name === null) {
name = value.first_name + " " + value.last_name;
} else {
name = value.first_name + " " + value.middle_name + " " + value.last_name;
}
json.aaData.push({"id": value.id, "name": name, "email": value["e-mail"], "create_date": value.create_date, "status": value.status});
});
fnCallback(json);
if (!RecipientModal.iDisplay) {
RecipientModal.iDisplay = true;
modal.reveal({"closeonbackgroundclick": false, scrolltop: currentTop});
}
break;
default:
break;
}
// Translate content
$('.reveal-modal-bg').find('.reveal-modal').i18n();
} else {
fnSessionTimeout(data, null, 'login');
}
});
},
"fnRowCallback": function (nRow, aData) {
// Dispose view
switch (opts.type) {
case 1:
case 2: // Existing document {sendwizard / package}
$("td:eq(0)", nRow).html("");
$("td:eq(1)", nRow).html("
" + aData.file_name + "
");
$("td:eq(2)", nRow).html("
" + aData.title + "
");
$("td:eq(3)", nRow).html("");
var t = $("td:eq(3)", nRow).find('.ft');
HoGoUtils.drawDocumentIconFromType(t, aData.type);
$("td:eq(4)", nRow).html(DateUtils.convertDate(aData.create_date));
$("td:eq(5)", nRow).html("
" + aData.status + "
");
$(nRow).find('td').not('td:eq(0)').on('click', function () {
DTUtils.fnCheckBoxOnRow(nRow);
});
break;
case 3:
case 4: // Existing recipient
$("td:eq(0)", nRow).html("");
$("td:eq(1)", nRow).html("
");
$(nRow).find('td').not('td:eq(0)').on('click', function () {
DTUtils.fnCheckBoxOnRow(nRow);
});
break;
}
},
"aoColumnDefs": [
{'bSortable': false, 'aTargets': [0]}
],
"oScroller": {
"loadingIndicator": true
},
"fnDrawCallback": function (oSettings) {
//Cb custom
$('#' + opts.tableID).find('.ck').customInput();
//Set up stuff
DTUtils.fnSetUpTableControl(oSettings);
switch (opts.type) {
case 1: // Existing document {sendwizard}
DTUtils.checkboxSwitchPage(opts.tableID, "child", "select_all", DocumentModal.checkedList); // checkedList {required}
// Event click on each child TR
$('#' + opts.tableID).find(':checkbox[name=child]').die('click').on('click', function () {
DTUtils.checkboxChildSelectEvent(this, "select_all", DocumentModal.checkedList);
var title = $("#" + this.id).closest('tr').find('td').eq(1).text();
var fName = $("#" + this.id).closest('tr').find('td').eq(2).text();
var cDate = $("#" + this.id).closest('tr').find('td').eq(4).text();
if ($(this).prop('checked')) {
SelectedDocumentList.push(this.id, title, fName, cDate);
} else {
SelectedDocumentList.remove(this.id);
}
//console.log(DocumentModal.checkedList);
if (DocumentModal.checkedList.length > 0) {
HoGoUtils.enableButton('#btnAddDoc', {
colorClass: 'green',
handler: DocumentModal.addDocumentToExistingTable
});
} else {
HoGoUtils.disableButton('#btnAddDoc', {
colorClass: 'green'
});
}
});
break;
case 2: // Package document
DTUtils.checkboxSwitchPage(opts.tableID, "child", "select_all", DocumentModal.checkedList); // checkedList {required}
// Event click on each child TR
$('#' + opts.tableID).find(':checkbox[name=child]').die('click').on('click', function () {
DTUtils.checkboxChildSelectEvent(this, "select_all", DocumentModal.checkedList);
//console.log(DocumentModal.checkedList);
if (DocumentModal.checkedList.length > 0) {
//Enable these buttons
HoGoUtils.enableButton('#btnAddDoc', {
colorClass: 'green',
handler: function () {
Modal.checkLicenseDuplicate(3);
} // Add to package
});
} else {
//Disable
HoGoUtils.disableButton('#btnAddDoc', {
colorClass: 'green'
});
}
});
break;
case 3: // Existing recipient {sendwizard}
DTUtils.checkboxSwitchPage(opts.tableID, "child", "select_all", RecipientModal.checkedList, 'attrEmail');
// Event click on each child TR
$('#' + opts.tableID).find(':checkbox[name=child]').die('click').on('click', function () {
DTUtils.checkboxChildSelectEvent(this, "select_all", RecipientModal.checkedList, 'attrEmail'); // use attrEmail
if (RecipientModal.checkedList.length > 0) {
//Enable save button
HoGoUtils.enableButton('#btnAddRep', {
colorClass: 'green',
handler: RecipientModal.addAddressBookToTextarea
});
} else {
HoGoUtils.disableButton('#btnAddRep', {
colorClass: 'green'
});
}
});
break;
case 4: // Existing recipient {package}
DTUtils.checkboxSwitchPage(opts.tableID, "child", "select_all", RecipientModal.checkedList);
// Event click on each child TR
$('#' + opts.tableID).find(':checkbox[name=child]').die('click').on('click', function () {
DTUtils.checkboxChildSelectEvent(this, "select_all", RecipientModal.checkedList); // use ID
if (RecipientModal.checkedList.length > 0) {
//Enable save button
HoGoUtils.enableButton('#btnAddRep', {
colorClass: 'green',
handler: function () {
Modal.checkLicenseDuplicate(2);
}
});
} else {
HoGoUtils.disableButton('#btnAddRep', {
colorClass: 'green'
});
}
});
break;
}
},
"aoColumns": mDataProp, // mDataProp {required}
"fnInitComplete": function () {
// Find two button actions
var btnCancel = $('.reveal-modal-bg').find('.modal-control').find('.red');
var btnX = $('.reveal-modal-bg').find('.close-reveal-modal');
// Die click first
$(btnCancel).die('click');
$(btnX).die('click');
switch (opts.type) {
case 1:
case 2:
// Select all
if (opts.type === 1) {
$('#' + opts.tableID).find('#cbo_selectall').unbind('click').bind('click', function () {
DTUtils.fnSelectAllCheckBox(this, DocumentModal.checkedList, 'child', 'id', 'btnAddDoc', DocumentModal.addDocumentToExistingTable, 'green');
});
} else {
$('#' + opts.tableID).find('#cbo_selectall').unbind('click').bind('click', function () {
DTUtils.fnSelectAllCheckBox(this, DocumentModal.checkedList, 'child', 'id', 'btnAddDoc', function () {
Modal.checkLicenseDuplicate(3);
}, 'green');
});
}
// Check cancelCallback
$(btnCancel).live('click', function () {
// Close modal
Modal.closeModal();
DocumentModal.resetModal(); // Function name not code
});
$(btnX).live('click', function () {
// Close modal
Modal.closeModal();
DocumentModal.resetModal();
});
break;
case 3:
case 4:
if (opts.type === 3) {
$('#cbo_selectall').unbind('click').bind('click', function () {
DTUtils.fnSelectAllCheckBox(this, RecipientModal.checkedList, 'child', 'attrEmail', 'btnAddRep', RecipientModal.addAddressBookToTextarea, 'green');
});
} else {
$('#cbo_selectall').unbind('click').bind('click', function () {
DTUtils.fnSelectAllCheckBox(this, RecipientModal.checkedList, 'child', 'id', 'btnAddRep', function () {
Modal.checkLicenseDuplicate(2);
}, 'green');
});
}
// Check cancelCallback
$(btnCancel).live('click', function () {
// Close modal
Modal.closeModal();
RecipientModal.resetModal(); // Function name not code
});
$(btnX).live('click', function () {
// Close modal
Modal.closeModal();
RecipientModal.resetModal(); // Function name not code
});
break;
}
}
});
}
/**
* Check duplicated license when add document/ recipient to package
* @param {int} checkType : 2: Add recipient to package, 3: Add document to package
* @returns {undefined}
*/
function checkLicenseDuplicate(checkType) {
var postRecipientID, postDocuments;
var type = parseInt(checkType);
// Check valid
var packageType = Package.getPackageType();
// Not loaded
if (typeof packageType === 'undefined')
return;
// Add recipient
if (type === 2) {
var lDocId = Package.getActiveDocuments();
postRecipientID = RecipientModal.checkedList.toString();
postDocuments = lDocId.join();
}
// Add document
if (type === 3) {
// No check duplicate with create link type
if (packageType == 2) {
DocumentModal.addDocumentToPackage([], DocumentModal.checkedList);
return;
} else {
var lRepId = Package.getActiveRecipients();
postRecipientID = lRepId.join();
postDocuments = DocumentModal.checkedList.toString();
}
}
if (postRecipientID.length > 0) {
// Check duplicate license
var reqGetEmail = $.post('api/v1/GetRecipientDetail', {
SessionID: UserSession.getSessionID(),
RecipientID: postRecipientID
}), chained = reqGetEmail.pipe(function (data) {
var listRepEmail = [], listRepId = [];
// get list email recipient
if (data.status === 'OK') {
$.each(data.detail, function (k, v) {
listRepEmail.push(v["e-mail"]);
listRepId.push(k);
});
return $.post('api/v1/CheckLicenseDuplicate', {
SessionID: UserSession.getSessionID(),
Documents: postDocuments,
Recipients: listRepEmail.join()
}, function (data) {
if (data.status === 'OK') {
if (data.result.length > 0) {
//show duplicate popup
if (type === 2)
WizardCore.showLicenseDuplicatePopup(2, {data: data, listIdRep: listRepId, fnCallback: RecipientModal.addRecipientToPackage});
if (type === 3)
WizardCore.showLicenseDuplicatePopup(3, {data: data, listDocId: DocumentModal.checkedList, fnCallback: DocumentModal.addDocumentToPackage});
} else {
// call add document to package
if (type === 2)
RecipientModal.addRecipientToPackage([], listRepId);
// add recipient to package
if (type === 3)
DocumentModal.addDocumentToPackage([], DocumentModal.checkedList);
}
}
});
} else {
//Session not found
if (data.status === APIConst.sessionIdNotFound) {
window.location.href = 'login';
} else {
Modal.showAlert({content: i18n.t('error.unknown')});
}
/// invalid email
return false;
}
});
} else {
// case new a anonymous package without recipient
DocumentModal.addDocumentToPackage([], DocumentModal.checkedList);
}
}
return {
// Create a custom modal
createModal: function (type, opts) {
makeModal(type, opts);
},
makeDTTable: function (opts) {
makeDataTable(opts);
},
/**
* Trigger close modal
* @returns {undefined}
*/
closeModal: function (m) {
// Reset all modal
this.resetDocumentList();
this.resetRecipientList();
if (m) {
m.trigger('reveal:close');
}
// Remove background modal
var modal = $('.reveal-modal-bg').find('.reveal-modal');
if (modal.length > 0) {
modal.trigger('reveal:close');
}
},
/**
* Show cofirm popup with two buttons {Cancel | OK}. okCallback param is always required
* @param {type} json
* @returns {undefined}
*/
showConfirmPopup: function (json) {
makeModal(3, json);
},
/**
* Show confirm popup with only one button
* @param {type} json
* @returns {undefined}
*/
showConfirmOneButton: function (json) {
makeModal(2, json);
},
/**
* Display a message for user not contains any buttons
* @param {type} json
* @returns {undefined}
*/
showAlert: function (json) {
makeModal(1, json);
},
/**
* Make recipient list
* @returns {undefined}
*/
getAddressBookList: function () {
Modal.makeDTTable({
tableID: 'tblExisitingAddressBook',
type: 3
});
},
/**
* Make document list
* @returns {undefined}
*/
getDocumentList: function (removedIds) {
Modal.makeDTTable({
type: 1,
tableID: 'tblExistingDocument',
removedIds: removedIds
});
},
/**
* Set up default variables document modal
* @returns {undefined}
*/
resetDocumentList: function () {
SelectedDocumentList.removeAll();
DocumentModal.checkedList = [];
DocumentModal.iDisplay = false;
},
/**
* Set up default variables recipient modal
* @returns {undefined}
*/
resetRecipientList: function () {
RecipientModal.checkedList = [];
RecipientModal.iDisplay = false;
},
/**
* Get document detail then add it to existing table
* @param {type} ID : Document's ID
* @param {type} fnBeforeSend : (optional) Function before send
* @returns {jqXHR}
*/
getDocumentDetailThenAppendToTable: function (ID, fnBeforeSend) {
return $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: 'api/v1/GetDocumentDetail',
data: {"DocumentID": ID, "SessionID": UserSession.getSessionID()},
dataType: "json",
beforeSend: function () {
// Indicator
$('').appendTo('#viewWrapper');
if (typeof fnBeforeSend === 'function') {
fnBeforeSend.call();
}
},
success: function (data) {
//Remove overplay
$('.hogo-bg-overlay-action').remove();
if (data.status === 'OK') {
var doc_Content = data.detail;
$.each(doc_Content, function (doc_detailId, doc_detail) {
var title = doc_detail.title;
var description = doc_detail.description;
var fileName = doc_detail.file_name;
var fileType = doc_detail.type;
var t = new Date().getTime();
//Add to parent table
setTimeout(function () {
var trash = '';
var ai = WizardCore.existingTable.fnAddData([trash, '
' + fileName + '
', '
' + title + '
', '
' + fileType + '
', '
' + description + '
']);
var nTR = WizardCore.existingTable.fnSettings().aoData[ai[0]].nTr;
// Set TD
var idTR = "doc" + t;
$(nTR).attr('id', idTR);
$(nTR).find('td').eq(0).attr('id', 'del');
$(nTR).find('td').eq(1).append("");
$(nTR).find('td').eq(3).html("");
var element = $(nTR).find('td').eq(3).find('.ft');
HoGoUtils.drawDocumentIconFromType(element, fileType);
// Setup buttons after appending
WizardCore.setupButtons();
}, 100);
});
}
}
});
},
checkLicenseDuplicate: function (type) {
checkLicenseDuplicate(type);
},
// Get document modal
getDocumentModal: function () {
return DocumentModal;
}
};
}(jQuery));
//
// Handle login
//
var Login = (function ($, u, window) {
// Private method
function goInside(token) {
u.setSessionID(token);
u.getSessionData();
u.fnGetSessionComplete = function (data) {
// Integration with BoxApp
// Query param
var package_id = HoGoUtils.getParameter()["package_id"];
if (package_id) {
window.location.href = "SendWizard?token=" + token + "&package_id=" + package_id + "#/4";
} else {
switch (data.landing_page) {
case 1:
window.location.href = "SendWizard";
break;
case 2:
window.location.href = "MyDocumentList";
break;
case 3:
window.location.href = "History";
break;
case 4:
window.location.href = "AddressBookList";
break;
default:
window.location.href = "SendWizard";
break;
}
}
};
}
// Public method
return {
init: function () {
$("label[for=chk_keepmelogin]").css({"color": "#999", "font-size": "16px"});
$("#button-login").on('click', function () {
Login.login();
});
// Enter event
$('#input_password,#input_username').live('keypress', function (e) {
var k = e.which ? e.which : e.keyCode;
if (k === 13) {
Login.login();
}
});
$('#btnLoginGoogle').on('click', function () {
Login.authWithGoogle();
});
//Referral email
var email = decodeURIComponent(HoGoUtils.getParameter()['mail']);
if (email !== 'undefined' && HoGoUtils.isValidEmail(email)) {
$('#input_username').val(email);
$('#input_username').attr('readonly', true).css('background-color', 'rgb(235, 235, 228)');
}
//Custom Novatium SSO Demo phase#1
var staticToken = HoGoUtils.getParameter()['token'];
if (typeof (staticToken) !== 'undefined') {
if (staticToken.length === 32)
// Clear all session
u.clearSessionID();
// set new ssion
goInside(staticToken);
}
},
fnGoLandingPage: function (userSession) {
var queue_id = HoGoUtils.getParameter()["queue_id"];
if (queue_id)
{
var file_name = HoGoUtils.getParameter()["file_name"];
var file_size = HoGoUtils.getParameter()["file_size"];
console.log("login from fnGoLandingPage: queue_id=" + queue_id + " file_size=" + file_size + " file_name=" + file_name);
window.location.href = "SendWizard?queue_id=" + queue_id + "&file_name=" + file_name + "&file_size=" + file_size;
} else
{
switch (userSession.landing_page) {
case 1:
window.location.href = "SendWizard";
break;
case 2:
window.location.href = "MyDocumentList";
break;
case 3:
window.location.href = "History";
break;
case 4:
window.location.href = "AddressBookList";
break;
default:
window.location.href = "SendWizard";
break;
}
}
},
// Need call Ajax
login: function () {
// Get info login
var email = $.trim($('#input_username').val());
var password = $.trim($('#input_password').val());
var postData = {EmailAddress: email, AdminID: email, Password: HoGoUtils.MD5(password)};
postData["KeepMeLogin"] = false;
if ($('#chk_keepmelogin').is(':checked')) {
postData["KeepMeLogin"] = true;
}
//Check email & password first
if (email === "" || password === "") {
$("#errorText").html(i18n.t('error.wrong_username'));
$("#errorText").show();
return false;
}
// Call API
var request = $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/Login",
beforeSend: function () {
//Disable button & disable click
HoGoUtils.disableButton('#button-login', {textInside: i18n.t('session.buttons.status.logging')});
},
data: postData,
dataType: "json"
});
var chained = request.pipe(function (data) {
if (data.status === 'OK') {
goInside(data.token);
} else {
//Admin here
return $.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/LoginServiceAdmin",
data: postData,
dataType: "json"
});
}
});
chained.done(function (dataAdmin) {
if (dataAdmin)
// data retrieved from url2 as provided by the first request
if (dataAdmin.status === "OK") {
u.setSessionID(dataAdmin.token);
// Redirect to UserList
window.location.href = "UserList";
} 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_username'));
$("#errorText").show();
}
}
});
},
authWithGoogle: function () {
var config = {
'client_id': GoogleConst[GOOGLE_ENVIRONMENT].clientId,
'scope': GoogleConst.scopeProfile,
'immediate': false
};
// Disable button
// HoGoUtils.disableButton('#btnLoginGoogle', {colorClass: 'orange', handler: this.authWithGoogle, textInside: i18n.t('session.buttons.status.logging_google')});
// Authorize
window.gapi.auth.authorize(config, function () {
var tO = gapi.auth.getToken();
var token = tO.access_token;
var postData = {};
postData["AccessToken"] = token;
postData["SocialType"] = 1; // Goolge type
postData["TimeZone"] = parseInt(HoGoUtils.getLocalTimeZone());
// Call API
$.ajax({
type: "POST",
timeout: HoGoConst.APITimeout,
url: "api/v1/LoginSocial",
data: postData,
dataType: "json",
success: function (data) {
if (data.status === "OK") {
goInside(data.token);
} else {
// Failed Login with Social
Modal.showAlert({content: i18n.t("password.message.error")});
}
}
});
});
}
};
}(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() {
$('.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();
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"] = $('#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"] = $('#numberDownload').val();
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;
if (package.print) {
if (package.printLimit === 1) {
postData["number_print"] = package.number_print;
} else {
postData["number_print"] = -1;
}
} else {
postData["number_print"] = 0;
}
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["is_view_browser"] = package.view_br;
postData["wm_text"] = package.wm_text;
postData["wm_color"] = package.wm_color;
postData["wm_position"] = package.wm_position;
if (package.print) {
if (package.printLimit === 1) {
postData["number_print"] = package.number_print;
} else {
postData["number_print"] = -1;
}
} else {
postData["number_print"] = 0;
}
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["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;
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;
if (package.print) {
postData["number_print"] = -1;
} else {
postData["number_print"] = 0;
}
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
});
} else {
// None of document in HttpSession
if (data.status === APIConst.inputParameterErrorStatus) {
HoGoUtils.writeLog(data.status_desc);
Modal.showAlert({content: i18n.t('error.unknown')});
} else {
fnSessionTimeout(data, null, 'login');
}
}
// create packge error because out of point or some other error
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) {
// console.log(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;
}
console.log(postData);
//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) {
console.log("123456");
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 && method !== 4 && method !== 2)
$('#emailInput').val(rep);
switch (method) {
// Set up view map with method
case 2:
case 4: // Create link // Anonymous link
$('#emailWrapper').remove();
$('#tipsySpecifyLink').remove();
$("#emailTags").tagit({
tagLimit : 1,
afterTagAdded: function(event, ui) {
// do something special
var tag = $(ui.tag[0]);
if (!HoGoUtils.isValidEmail(ui.tagLabel)) {
tag.css({'border': '1px solid red'});
}
if(rep){
var listReps = rep.split(",");
if(listReps && listReps.length >= 1){
$('ul#emailTags li input').attr('disabled', true);
HoGoUtils.disableButton('#btnExistingAddressBook', {colorClass: 'orange'});
}
}
},
afterTagRemoved :function(event, ui){
console.log(rep);
if(rep){
var listReps = rep.split(",");
if(!listReps || listReps.length < 1){
$('ul#emailTags li input').attr('disabled', false);
$('#btnExistingAddressBook').attr('disabled', false);
HoGoUtils.enableButton('#btnExistingAddressBook', {colorClass: 'orange', handler: Modal.getAddressBookList});
}
}else{
$('ul#emailTags li input').attr('disabled', false);
$('#btnExistingAddressBook').attr('disabled', false);
HoGoUtils.enableButton('#btnExistingAddressBook', {colorClass: 'orange', handler: Modal.getAddressBookList});
}
},
singleField: true,
singleFieldNode: $('#emailInput') // Value will be added here
});
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 () {
console.log($('#result'));
// 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 () {
$(".fade.in").hide();
$(".ng-joyride-element-non-static").css("z-index", "0");
$(".ng-curtain-class").css("z-index", "0");
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 === 4) {
$('.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 json = {"sEcho": data.sEcho, "iTotalDisplayRecords": data.totalResult, "aaData": []};
$.each(data.history_detail, function (key, value) {
json.aaData.push({"historyID": value.historyID, "historyType": value.historyType, "packageID": value.packID, "documentName": value.documentName, "recipientName": value.recipientName, "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('
';
}
}
}
$('#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);
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
//
var req = $.ajax({
type: 'POST',
url: 'api/v1/GetDistributionStatus',
data: {SessionID: UserSession.getSessionID(), DownloadID: dis.be_download_id}
});
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:
con = '
' +
'
' +
'' +
'
' +
'
';
break;
}
} else {
// Open
if (parseInt(dis.opened_status) === 1) {
emailClass = 'email-open';
}
if (method === HoGoConst.WIZARD_ANONYMOUS_TYPE) { // 4
con = '
' +
'
' +
'' +
'' +
'
' +
'
';
} else {
if (method === HoGoConst.WIZARD_CREATE_LINK_TYPE) {
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');
// 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 {
for (var j = 0; j < documents.length; j++) {
var docid = documents[j].id;
}
// Add header number download
if (method === HoGoConst.WIZARD_ANONYMOUS_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) {
n = n + parseInt(dE.text()); // Caution
}
});
var textDownload = i18n.t('history.package.distribution.downloaded');
//textDownoad
$(this).append('
' + textDownload + ' ' + n + ' )
');
$(this).find('img').css("margin-top", 10);
} else if (method === HoGoConst.WIZARD_SPECIFY_LINK_TYPE) {
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) {
if (n < parseInt(dE.text()))
n = parseInt(dE.text()); // Caution
}
});
var textDownload = i18n.t('history.package.distribution.downloaded');
//textDownoad
$(this).append('
' + textDownload + ' ' + n + ' )
');
$(this).find('img').css("margin-top", 10);
}
}
});
}
}
} 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 + '
';
// 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() {
console.log($('[id="validationCP"]'));
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/GetUserInfoHoGo",
dataType: "json",
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;
console.log(lang);
// Not set before
if (lang === '' || lang === null) {
$('#language').val('auto').selectmenu();
} else {
var lLang = lang.split('-'); // auto-en
var pName = HoGoUtils.getPageName();
console.log($.trim(lLang[0]));
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 (UserSession.getLang() === 'en') {
$('#txtSenderMail').val(detail[key].first_name + " " + detail[key].last_name);
} else if (UserSession.getLang() === 'ja') {
$('#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").unbind('click').on('click', function () {
showChangePasswordPopup();
});
$("#btnChangeEmailAccount").unbind('click').on('click', function () {
showChangeEmailPopup();
});
$('.btn-cancel-normal-popup').live('click', function () {
Modal.closeModal();
});
this.loadingStatistic();
}
};
}(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;
// Allow redirect or not
var redirectable = 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({ontent: 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 () {
console.log(HoGoUtils.getPageName());
//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();
}
});
$("#cancel-purchase").click(function () {
var url = window.location;
var lenghOfBaseUrl = url.href.lastIndexOf('/');
var lenghFullUrl = url.href.length;
var path = url.href.substring(lenghOfBaseUrl + 1, lenghFullUrl);
redirectable = true;
window.location.href = "BuyPoint?returnPath=" + path;
});
},
loadByPointPage: function () {
console.log("load by point page");
// 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) {
console.log(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);
// });
// remove buy with credit card, IDoc is no longer support
$('#creditCardBuy').remove();
//Binding paypal iDOC notify
$('#superPackage,#plusPackage,#basicPackage').on('click', function () {
notifyPaypaliDOCPayment(this);
});
$("#buypointButtonTable").attr("style", "margin-left:226px!important;padding-top: 206px!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) {
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 = "";
// 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())) {
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'];
}
post["SessionID"] = UserSession.getSessionID();
return post;
}
/**
* Load user list
* @param {json} filter : filter options
* @returns {undefined}
*/
function loadUserList(filter) {
oTable = $("#tablepaging").dataTable({
"aaSorting": [[4, 'desc']],
"bInfo": false,
// "bLengthChange": true,
"aLengthMenu": [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "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) {
name = value.firstName + " " + value.lastName;
} else {
name = 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
$("td:eq(5)", nRow).html("");
nRow.ondblclick = function () {
window.location.href = "UserDetail?userID=" + aData.id;
};
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'),
okCallback: fnDeleteUser,
content: i18n.t('user.message.confirm_delete.content')
});
return false;
}
}
/**
* Do delete user
* @returns {Boolean}
*/
function fnDeleteUser() {
if (checkedList.length === 0)
return false;
$.each(checkedList, function (k, v) {
//Call API
$.ajax({
url: "api/v1/DeleteServiceUser",
dataType: "json",
type: "POST",
data: {UserID: v, 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',
isSubmitForm: true
});
}
});
m.find('#btn-export-csv').bind('click', function () {
User.exportUser();
var form = $(this).parents('form');
var param = form.serialize();
$.fileDownload('api/v1/ExportServiceUserList?' + param, {
httpMethod: 'post'
});
});
// });
}
// Import user
function doImport() {
var setting = oTable1.fnSettings();
HoGoUtils.disableButton('#btn-save-csv', {colorClass: 'green', textInside: 'IMPORTING'});
var count = 0;
$.each(setting.aiDisplay, function (k, v) {
var obj = setting.aoData[v]._aData;
var data = {};
data["SessionID"] = UserSession.getSessionID();
data["FirstName"] = obj.first_name;
data["MiddleName"] = obj.middle_name;
data["LastName"] = obj.last_name;
data["EmailAddress"] = obj.email;
data["Company"] = obj.company;
data["Password"] = HoGoUtils.MD5(obj.password);
//Adding
$.ajax({
dataType: 'json',
type: "POST",
url: "api/v1/AddServiceUser",
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");
count++;
if (dt.status === "OK") {
//TODO
} else {
//Find row of each email
errorRows.push(k + 1);
}
// DO after all done
doCount(count);
}
});
});
}
/**
* Do count to know all record whether save or not
* @param {type} v Current saved record
* @returns {undefined}
*/
function doCount(v) {
// Save done
if (oTable1) {
if (v === oTable1.fnSettings().aiDisplay.length) {
// Destroy table
oTable1.fnClearTable();
Modal.closeModal();
if (errorRows.length > 0) {
Modal.showAlert({title: "Duplicate User", content: i18n.t('user.message.exist_user') + errorRows.toString()});
//Clear error rows
errorRows = [];
oTable.fnDraw();
} else {
oTable.fnDraw();
}
}
}
}
/**
* Create table manage import CSV file
* @returns {undefined}
*/
function importCSV() {
//Init table import
oTable1 = $('#tbl-import-user').dataTable({
"aaSorting": [[1, 'desc']],
"bInfo": false,
"bLengthChange": false,
"bPaginate": true,
"bDestroy": true,
"iDisplayLength": 10,
"sPaginationType": "full_numbers",
"oLanguage": DTUtils.DTLang,
"sDom": 'l<"clearfix"<"left"f><"right"p>>irt',
"sAjaxSource": 'api/v1/ImportUser',
"fnServerData": function (sSource, aoData, fnCallback, oSettings) {
var json = {"aaData": []};
$.ajaxFileUpload({
url: sSource,
secureuri: false,
fileElementId: "file",
data: {SessionID: UserSession.getSessionID()},
dataType: 'json',
success: function (data) {
if (data.status === "OK") {
var detail = data.list;
for (var i = 0; i < detail.length; i++) {
var company = "";
if (detail[i].company !== undefined) {
company = detail[i].company;
}
json.aaData.push({"first_name": detail[i].first_name, "middle_name": detail[i].middle_name, "last_name": detail[i].last_name, "password": detail[i].password, "email": detail[i]['e-mail'], "company": company});
}
} else {
if (data.status === APIConst.adminSessionRequired) {
window.location.href = 'login';
} else {
Modal.showAlert({title: 'Invalid Format', content: i18n.t('user.message.wrong_format')});
}
}
fnCallback(json);
},
error: function () {
window.location.href = 'login';
}
});
},
"fnRowCallback": function (nRow, aData) {
$("td:eq(0)", nRow).html("");
var name = "";
if (aData.middle_name !== undefined)
name = aData.first_name + " " + aData.middle_name + " " + aData.last_name;
else
name = aData.first_name + " " + aData.last_name;
//Name field
$("td:eq(1)", nRow).html("
" + name + "
");
//Password field
$("td:eq(2)", nRow).html("");
//nRow.setAttribute("style", "text-align: left");
$("td:eq(3)", nRow).html("
" + aData.email + "
");
$("td:eq(4)", nRow).html("
" + aData.company + "
");
},
"aoColumnDefs": [
{'bSortable': false, 'aTargets': [0, 2]}
],
"fnDrawCallback": function (oSettings) {
//Setting up control
DTUtils.fnSetUpTableControl(oSettings);
if (oSettings.fnRecordsDisplay().length > 0) {
HoGoUtils.disableButton('#btn-save-csv', {colorClass: 'green'});
} else {
HoGoUtils.enableButton('#btn-save-csv', {
colorClass: 'green', handler: doImport, textInside: i18n.t('buttons.save')
});
}
},
"aoColumns": [
{"mDataProp": "first_name"},
{"mDataProp": "first_name"},
{"mDataProp": "password"},
{"mDataProp": "email"},
{"mDataProp": "company"}
],
"fnInitComplete": function (setting) {
if (setting.aoData.length === 0) {
Modal.showAlert({title: 'Invalid Data', content: i18n.t('user.message.no_valid_data')});
} else {
$("#import-popup .modal-control").css('display', 'block');
$('#import-popup').reveal({"closeonbackgroundclick": false});
}
}
});
//Clear file
$("#file").replaceWith($("#file").val('').clone(true));
}
var UserDetail = {
/* Get parameter */
userID: HoGoUtils.getParameter()["userID"],
/* Transaction ID using for refunding */
transID: null,
cP: null,
createDate: null,
amount: 0,
reason: "",
/**
* Get user detail
* @returns {jqXHR}
*/
getUserDetail: function () {
return $.ajax({
dataType: 'json',
type: "POST",
url: "api/v1/GetUserInfo",
data: {UserID: UserDetail.userID, SessionID: UserSession.getSessionID()},
timeout: HoGoConst.APITimeout,
success: function (dt) {
userDetail = dt.detail;
if (dt.status === "OK") {
$.each(dt.detail, function (key, value) {
if (value.status === HoGoConst.ACTIVE_STATUS) {
// Set model & view
$("#firstname").val(fName = value.first_name);
$("#middlename").val(mName = value.middle_name);
$("#lastname").val(lName = value.last_name);
$("#company").val(company = value.company);
$("#email").val(email = value["e_mail"]);
var pointBalance = parseInt(value.points) + parseInt(value.points_free);
$("#point-balance").text(pointBalance + ' ' + i18n.t('session.label.points'));
if (new Date(value.last_login).getFullYear() === "1969" || new Date(value.last_login).getFullYear() === "1970") {
$("#last-login").text("N/A");
} else {
$("#last-login").text(DateUtils.convertDate(value.last_login));
}
$("#registered-date").text(DateUtils.convertDate(value.signup_date));
// Point tooltip
$('#detailBalancePoint').tooltipster({
content: '',
animation: 'fade',
interactive: true,
contentAsHTML: true,
functionInit: function (origin) {
var content = '
");
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();
}
};
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 () {
$('.nav-affiliate').removeClass('item-user-list-deactive').addClass('item-user-list-active');
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 ($) {
function changeAdminPassword() {
$('form#validationCP').find('.formErrorContent').css('white-space', 'nowrap');
if (!Admin.fStatus) {
return false;
}
var postData = {};
var newPassword = $('#password').val().trim();
postData["NewPassword"] = HoGoUtils.MD5(newPassword);
postData["SessionID"] = UserSession.getSessionID();
//TODO ajax
return $.ajax({
type: "POST",
url: "api/v1/UpdateAdminPassword",
data: postData,
timeout: HoGoConst.APITimeout,
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 {
fnSessionTimeout(data);
}
}
});
}
function showChangePasswordPopup() {
$('#change-password-popup').remove();
$.get("ChangePasswordPopup", function (data) {
$('body').append(data);
$('#change-password-popup').i18n();
var m = $('#change-password-popup');
m.reveal({closeonbackgroundclick: false});
m.find('#change-password').bind('click', function () {
var form = $(this).parents('form');
form.submit();
// Do update password
changeAdminPassword();
});
//Validate form change password
HoGoUtils.validateForm('validationCP', Admin);
});
}
return {
fStatus: false,
init: function () {
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');
}
UserSession.getAdminSessionData().done(function (data) {
$.ajax({
dataType: 'json',
type: "POST",
url: "api/v1/GetAdminInfo",
data: {AdminID: data.admin_id, SessionID: UserSession.getSessionID()},
timeout: HoGoConst.APITimeout,
success: function (dt) {
if (dt.status === "OK") {
var admin = dt.admin_detail;
$("#admin-id").text(admin.admin_id);
$("#service-id").text(admin.service_id);
} else {
HoGoUtils.writeLog(data.status_desc);
Modal.showAlert({content: i18n.t('error.unknown')});
}
}
});
});
$('#btnChangePassword').click(function () {
showChangePasswordPopup();
});
$('.btn-cancel-normal-popup').live('click', function () {
Modal.closeModal();
});
}
};
}(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') {
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() {
console.log("wtf");
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) {
console.log("xin loi cuoc doi");
return i18n.init({
lng: lang,
selectorAttr: 'data-hg',
fallbackLng: HoGoConst.LANG_DEFAULT, // fallback
resGetPath: 'Resource/' + lang + '.common.json',
debug: true,
preload: ['en', 'ja']
}, function () {
console.log("doi meo can xin loi");
// Translate whole webpage
$("html").i18n();
// Show
$('.wrapper-page-loader').fadeOut("slow");
initStuffAfterReadyLang();
console.log("Ready...... now......", isLoginState);
// 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)
initObjectsLoginState();
} 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() {
console.log("innit login state");
// 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') {
AddressBook.init();
}
// MyDocument
if (pName === 'mydocumentlist.html' || pName === 'mydocumentdetail.html' || pName === 'adddocument.html') {
MyDocument.init();
}
// History part
if (pName === 'history.html') {
History.init();
History.makeHistoryList();
}
// Package
if (pName === 'packagedetaildownload.html') {
Package.init();
}
// My account
if (pName === 'myaccount.html' || pName === 'paymentinfo.html' || pName === 'newmyaccount.html') {
require(['https://js.stripe.com/v2/']);
if (pName === 'myaccount.html' || pName === 'newmyaccount.html') {
MyAccount.init();
BoxIntegrate.init();
}
Payment.init();
}
if (pName === 'userlist.html' || pName === 'userdetail.html' || pName === 'adduser.html') {
User.init();
}
//Admin
if (pName === "admininformation.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 === 'boxgrantaccess.html') {
BoxGrantAccess.innit();
}
// Navi manage
HoGoUtils.manageActionsOnPage(pName);
}
/**
* 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']);
}
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 () {
UserSession.clearSessionID();
window.location.href = "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
// Check if load DEFAULT LOGIN PAGE
var token_param = HoGoUtils.getParameter()['token'];
var isTokenSet = false;
if (typeof (token_param) !== 'undefined' && HoGoUtils.getPageName() !== "buypoint.html") {
isTokenSet = true;
}
if (($('#loginState').length > 0 || $('#login').length > 0) && isTokenSet === false) {
//
// CHECKING USER SESSION
//
// Get user session
var chain = UserSession.getSessionData().pipe(function (sessionData) {
if (sessionData.status === 'OK') {
if (HoGoUtils.getPageName() === 'login.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') {
// Render admin's information
$('#profileLink').text(data.admin_id);
//Redirect to admin if at login page
if (HoGoUtils.getPageName() === 'login.html')
window.location.href = 'UserList';
else {
// Admin
$.getJSON('Resource/' + HoGoConst.LANG_DEFAULT + '.datatable.json', function (data) {
DTUtils.DTLang = data;
// Admin login state - Using default language
initI18N(HoGoConst.LANG_DEFAULT, true);
});
}
} else {
//Redirect to login if trying to go inside
if ($('#loginState').length > 0)
window.location.href = '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) {
initI18N(lang, true);
},
initDefaultTooltip: function () {
// Tooltipster
$('.tooltip').tooltipster({interactive: true, theme: 'hg-theme'});
}
};
}(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();
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)
if (i18n.lng() === 'ja') {
return "無料";
} else {
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;
};