/* @todo: run jslint and fix: - unexpected this - unexpected ++ - unused 'i' - ==, != instead of ===, !== - etc - fix undefined checks naar typeof var === 'undefined' */ var loggedin = false; var limit = 100; var _ignoreHashChange = false; /* function APICalls() { "use strict"; this.baseurl = 'https://stage.service.booxtream.com/admin/contract/'; function buildURL(property,method,params) { var url = this.baseurl + '/' + property + '/' + method + '.json'; if(typeof params !== "undefined" && params.length > 0) { for(var i = 0; i < params.length; i++) { if(i === 0) { url += '?'; } else { url += '&'; } url += params[i]['name'] + '+'; url += params[i]['value']; } } return url; } } */ /* Default locale resources */ var locale = 'en/US'; var localizedStrings = { 'en/US': { uploadSuccess: ' succesfully uploaded', uploadExists: ' already exists; if you want to overwrite it, please delete the original first', uploadError: ' occured, please contact support.', deleteSuccess: ' successfully deleted', deleteError: ' could not be deleted: ' } } /* Spinner functions */ function startSpinner(id) { $(id).show(); } function stopSpinner(id) { $(id).hide(); } $.fn.animateRotate = function (angle, duration, easing, complete) { var args = $.speed(duration, easing, complete); var step = args.step; return this.each(function (i, e) { args.step = function (now) { $.style(e, 'transform', 'rotate(' + now + 'deg)'); if (step) return step.apply(this, arguments); }; $({deg: 0}).animate({deg: angle}, args); }); }; // currently active account needed on some pages var currentActiveAccount = null; /* Pagination */ var displayPagination = function () { // pagination var op = this; var pagination = $('.pagination'); pagination.children('li.page').remove(); var start = 1; var end = this.pages; var concatenatedstart = false; var concatenatedend = false; if(this.pages > 22) { if(this.page > 12) { concatenatedstart = true; start = this.page - 11; } if(start + 22 < this.pages) { concatenatedend = true; end = start + 22; } } for (var i = start; i <= end; i++) { var li = $('
  • ').addClass('page'); var text = ''; if(concatenatedstart && i == start) { text += '…'; } text += i; if(concatenatedend && i == end) { text += '…'; } var a = $('').html(text).attr('rel', i); if(i < start + 4 || i > end - 4) { li.addClass('hidesm'); } if(i < start + 9 || i > end - 9) { li.addClass('hidexs'); } if (i == this.page) { li.addClass('active'); } li.append(a); a.click(function (event) { event.preventDefault(); op.getPage($(this).attr('rel')); // create url for pushState op.sURL.parameters.page = op.page; var url = getURL(op.sURL); history.pushState(null,null,url); return false; }); pagination.children('li.next').before(li); } // disable/enable buttons if necessary if(this.page === 1) { pagination.children('.first').addClass('disabled'); pagination.children('.previous').addClass('disabled'); } else { pagination.children('.first').removeClass('disabled'); pagination.children('.previous').removeClass('disabled'); } // if just one page if(this.page === this.pages) { pagination.children('.last').addClass('disabled'); pagination.children('.next').addClass('disabled'); } else { pagination.children('.last').removeClass('disabled'); pagination.children('.next').removeClass('disabled'); } // set hash to current page this._ignoreHashChange = true; } var initPagination = function () { var op = this; var pagination = $('.pagination'); pagination.children('.first').click(function (event) { event.preventDefault(); if(op.page === 1) return false; op.getPage(1); // create url for pushState op.sURL.parameters.page = op.page; var url = getURL(op.sURL); history.pushState(null,null,url); return false; }); pagination.children('.previous').click(function (event) { event.preventDefault(); var i = op.page - 1; if(i < 1) return false; op.getPage(i); // create url for pushState op.sURL.parameters.page = op.page; var url = getURL(op.sURL); history.pushState(null,null,url); return false; }); pagination.children('.next').click(function (event) { event.preventDefault(); var i = op.page + 1; if(i > op.pages) return false; op.getPage(i); // create url for pushState op.sURL.parameters.page = op.page; var url = getURL(op.sURL); history.pushState(null,null,url); return false; }); pagination.children('.last').click(function (event) { event.preventDefault(); if(op.page === op.pages) return false; op.getPage(op.pages); // create url for pushState op.sURL.parameters.page = op.page; var url = getURL(op.sURL); history.pushState(null,null,url); return false; }); } /* Controls presentation of values in table cells */ function getCellHTML (title, value, maxlength, fromEnd) { if (value === null) { return ''; } if (value.length > maxlength) { if (fromEnd !== undefined && fromEnd == true) { var newvalue = '…' + value.substr((value.length - maxlength), value.length); } else { var newvalue = value.substr(0,maxlength)+'…'; } return '' + newvalue +''; } return value; } /* Value padding */ function pad(num) { var norm = Math.abs(Math.floor(num)); return (norm < 10 ? '0' : '') + norm; } /* Fast simple hasher */ function simplehasher(str) { var res = 0, len = str.length; for (var i = 0; i < len; i++) { res = res * 31 + str.charCodeAt(i); res = res & res; } return res; } function formatLocalISODate(date) { var tzo = -date.getTimezoneOffset(); var sign = tzo >= 0 ? '+' : '-'; return date.getFullYear() + '-' + pad(date.getMonth()+1) + '-' + pad(date.getDate()) + 'T' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()) + sign + pad(tzo / 60) + ':' + pad(tzo % 60); } function formatDisplayUTCDate(date, size) { var year = date.getUTCFullYear(); // add 1 to 0-indexed month var month = pad(date.getUTCMonth()+1); var day = pad(date.getUTCDate()); var hour = pad(date.getUTCHours()); var minute = pad(date.getUTCMinutes()); var second = pad(date.getUTCSeconds()); if (size == 'normal') { return year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second; } else { return year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+''; } } // Handydandy urlObject function urlObject(options) { var default_options = {'url':window.location.href,'unescape':true,'convert_num':true}; if(typeof options !== "object") options = default_options; else { for(var index in default_options) { if(typeof options[index] ==="undefined") options[index] = default_options[index]; } } var a = document.createElement('a'); a.href = options['url']; var url_query = a.search.substring(1); var params = {}; var vars = url_query.split('&'); if(vars[0].length > 1) { for(var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); var key = (options['unescape'])?unescape(pair[0]):pair[0]; var val = (options['unescape'])?unescape(pair[1]):pair[1]; if(options['convert_num']) { if(val.match(/^\d+$/)) val = parseInt(val); else if(val.match(/^\d+\.\d+$/)) val = parseFloat(val); } if(typeof params[key] === "undefined") params[key] = val; else if(typeof params[key] === "string") params[key] = [params[key],val]; else params[key].push(val); } } var urlObj = { protocol:a.protocol, hostname:a.hostname, host:a.host, port:a.port, hash:a.hash, pathname:a.pathname, search:a.search, parameters:params }; return urlObj; } function getURL(urlObj) { var url = urlObj.protocol + '//' + urlObj.hostname + urlObj.pathname + '?'; for(var key in urlObj.parameters) { if(key !== '&' && key !== '?' && typeof urlObj.parameters[key] !== "undefined") { url += key + '=' + urlObj.parameters[key] + '&'; } } // remove last ? or & url = url.substr(0,url.length-1); return url; } // used in manualmode and batchmode function handleSuppressExlibrisSpreadCheckbox() { // check exlibris-checkbox when suppressexlibrisspread-checkbox is checked $('#suppressexlibrisspread').change(function() { if ($('#suppressexlibrisspread').is(':checked')) { $('#exlibris').prop('checked', true); } }); // uncheck suppressexlibrisspread-checkbox when exlibris-checkbox is unchecked $('#exlibris').change(function() { if (!$(this).is(':checked')) { $('#suppressexlibrisspread').prop('checked', false); } }); } // used in manualmode and batchmode function displayEpubOptions() { // detect if processed file is an EPUB or a PDF; display checkboxes for EPUB, Mobi, SuppressExlibrisSpread and Disclaimer accordingly if ($('#storedfile').length > 0) { var storedfile = $('#storedfile').text(); if (storedfile.slice(-5) === '.epub') { $('#outputparent').removeClass('hidden'); $('#disclaimer_checkbox').removeClass('hidden'); $('#suppressexlibrisspread_checkbox').removeClass('hidden'); } } else { $('#epubfile').change(function () { if ($(this).val().slice(-5) === '.epub') { $('#outputparent').removeClass('hidden'); $('#disclaimer_checkbox').removeClass('hidden'); $('#suppressexlibrisspread_checkbox').removeClass('hidden'); } else { $('#outputparent').addClass('hidden'); $('#disclaimer_checkbox').addClass('hidden'); $('#suppressexlibrisspread_checkbox').addClass('hidden'); } }); } } // used in Transaction and Support function setSupportTicket(contract) { $('#ticketform input[name="contract_name"]').val(contract.contractname ? contract.contractname : ''); $('#ticketform input[name="support_name"]').val(contract.contactname ? contract.contactname : ''); $('#ticketform input[name="support_email"]').val(contract.contactmail ? contract.contactmail : ''); $('#ticketform input[name="contract_apikey"]').val(contract.apikey ? contract.apikey : ''); } // used in Transaction and Support function handleTicket() { $('#ticketformbutton').click(function(e) { e.preventDefault(); var message = $('#support_message_errors'); message.empty(); var name = $('#ticketform input[name="support_name"]').val(); var email = $('#ticketform input[name="support_email"]').val(); var subject = $('#ticketform input[name="support_subject"]').val(); var support_message = $('#ticketform textarea[name="support_message"]').val(); var errors = ''; var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (name.length < 2) { errors += 'please insert a valid name
    '; } if (name.length > 255) { errors += 'name is too long
    '; } if (email.length < 2 || !regex.test(email)) { errors += 'please insert a valid email
    '; } if (email.length > 255) { errors += 'email is too long
    '; } if (subject.length < 2) { errors += 'please insert a valid subject
    '; } if (subject.length > 255) { errors += 'subject is too long
    '; } if (support_message.length < 2) { errors += 'please insert a valid message
    '; } if (support_message.length > 64000) { errors += 'message is too long
    '; } if (errors.length > 0) { message.prepend($('
    ' + errors + '
    ')); } else { $.ajax({ type: 'POST', url: baseurl + supportticketmethod, data: JSON.stringify({ uid: $('#ticketform input[name="uid"]').val(), name: name, email: email, subject: subject, message: support_message, accountkey: $('#ticketform input[name="accountkey"]').val(), }), beforeSend: function (xhr) { if(typeof authentication === "undefined") { // try to get it from sessionstorage authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if(authentication === null) { authentication = localStorage.getItem("authentication"); // got it from localstorage, now add it to sessionstorage sessionStorage.setItem("authentication", authentication); } } if(authentication === null) { document.location = 'login.php'; } xhr.setRequestHeader("Authorization", "Basic " + authentication); }, error: function () { $('#support').modal('hide'); $('#sent').modal('show'); $('#message').prepend($('
    There was a problem creating your support ticket. Please contact BooXtream at info@booxtream.com or try again.
    ')); }, success: function (data) { $('#support').modal('hide'); // hide support modal at transaction page $('#sent').modal('show').delay(3000).fadeOut(450); setTimeout(function() { $('#sent').modal('hide'); }, 3450); $('#ticketform input[name="support_subject"]').val(''); $('#support_message').val(''); $('#message').html('
    Your support ticket was succesfully created and a confirmation message was sent to the e-mail address ' + email + ' .
    '); } }); } }); } function setYear() { var selectedYear = getSelectedYear(); $('#selectedYear').html(selectedYear); // build list of selectable years var thisYear = new Date().getFullYear(); var year = 2011; while (thisYear >= year) { $('#years').append('
  • ' + thisYear + ''); thisYear--; } // enable selection of year from selectable years $('#yearSelector li').on('click', function(){ selectedYear = $(this).text(); $('#selectedYear').html(selectedYear); sessionStorage.setItem('selectedYearAccounting', JSON.stringify(selectedYear)); }); } function getSelectedYear() { // set selected year from session var selectedYear = JSON.parse(sessionStorage.getItem('selectedYearAccounting')); if (selectedYear == null) { selectedYear = new Date().getFullYear(); } return parseInt(selectedYear); } function showCredits() { $.getJSONCache(baseurl + creditsmethod, function (data) { var credits_available = data.message.response.credits_available; var remaining_days = data.message.response.remaining_days; if ( (credits_available != null && typeof credits_available != 'undefined') && (remaining_days != null && typeof remaining_days != 'undefined') ) { var creditsoverview = credits_available + '   Estimated use: ' + remaining_days + ' days remaining'; if (remaining_days <= 7) { creditsoverview += '   Order credits now!'; } creditsoverview += '   Click here to order additional credits.  Click here to download the current price list'; } else { creditsoverview = 'TEST MODE You can buy and use credits once you\'ve signed and returned our agreements. Please contact Support for more info'; } $('span#creditsoverview').html(creditsoverview); }); } /* Gets JSON and caches for a certain amount of time */ $.getJSONCache = function (url, success, force, minutes) { if(typeof minutes === "undefined" || parseInt(minutes) === 0) { minutes = 1; } // check datastorage in cache and retrieve data from there var data = JSON.parse(sessionStorage.getItem(B64.encode(url+'-data'))); var timeout = JSON.parse(sessionStorage.getItem(B64.encode(url+'-timeout'))); if(typeof force != "undefined") { data = null; } // check data & timeout if(data !== null && timeout !== null) { timeout = new Date(timeout); var now = new Date(); if(now < timeout) { return success(data); } } // save timeout to storage var timeout = new Date(); timeout.setMinutes(timeout.getMinutes()+minutes); sessionStorage.setItem(B64.encode(url+'-timeout'), JSON.stringify(timeout)); // put it in cache and reference the success-function to pass the data on to getJSONAuth function cache(data) { // save data to storage sessionStorage.setItem(B64.encode(url+'-data'), JSON.stringify(data)); success(data); } return $.getJSONAuth(url, cache); } $.clearFromCache = function(url) { sessionStorage.removeItem(B64.encode(url+'-data')); } /* Redefined PUT JSON function with authentication */ $.putJSONAuth = function (url, data, success, error, authentication, jsonp) { if(typeof jsonp === "undefined") { jsonp = false; } if (error == undefined) { error = function (xhr, ajaxOptions, thrownError) { document.location = 'index.php'; } } var ajax = $.ajax({ cache: false, url: url, type: 'PUT', dataType: jsonp ? 'jsonp' : 'json', jsonp: jsonp ? "callback" : undefined, data: data, beforeSend: function (xhr) { if(typeof authentication === "undefined") { // try to get it from sessionstorage authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if(authentication === null) { authentication = localStorage.getItem("authentication"); // got it from localstorage, now add it to sessionstorage sessionStorage.setItem("authentication", authentication); } } if(authentication === null) { document.location = 'login.php'; } xhr.setRequestHeader("Authorization", "Basic " + authentication); }, statusCode: { 401: function() { document.location = 'login.php'; }, 404: function() { data = 'not found'; }, 500: function() { alert('An error occured; the request could not be processed'); } }, xhrFields: { withCredentials: true }, crossDomain: true }).done(success).fail(error); } /* Redefined GET JSON function with authentication */ $.getJSONAuth = function (url, success, error, authentication, jsonp) { if(typeof jsonp === "undefined") { jsonp = false; } if (error == undefined) { error = function (xhr, ajaxOptions, thrownError) { document.location = 'index.php'; } } var ajax = $.ajax({ cache: false, url: url, type: 'GET', dataType: jsonp ? 'jsonp' : 'json', jsonp: jsonp ? "callback" : undefined, beforeSend: function (xhr) { if(typeof authentication === "undefined") { // try to get it from sessionstorage authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if(authentication === null) { authentication = localStorage.getItem("authentication"); // got it from localstorage, now add it to sessionstorage sessionStorage.setItem("authentication", authentication); } } if(authentication === null) { document.location = 'login.php'; } xhr.setRequestHeader("Authorization", "Basic " + authentication); }, statusCode: { 401: function() { document.location = 'login.php'; }, 404: function() { data = 'not found'; }, 500: function() { alert('An error occured; the request could not be processed'); } }, xhrFields: { withCredentials: true }, crossDomain: true }).done(success).fail(error); } // Base64 enc /* Copyright Vassilis Petroulias [DRDigit] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var B64 = { alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', lookup: null, ie: /MSIE /.test(navigator.userAgent), ieo: /MSIE [67]/.test(navigator.userAgent), encode: function (s) { var buffer = B64.toUtf8(s), position = -1, len = buffer.length, nan1, nan2, enc = [, , , ]; if (B64.ie) { var result = []; while (++position < len) { nan1 = buffer[position + 1], nan2 = buffer[position + 2]; enc[0] = buffer[position] >> 2; enc[1] = ((buffer[position] & 3) << 4) | (buffer[++position] >> 4); if (isNaN(nan1)) enc[2] = enc[3] = 64; else { enc[2] = ((buffer[position] & 15) << 2) | (buffer[++position] >> 6); enc[3] = (isNaN(nan2)) ? 64 : buffer[position] & 63; } result.push(B64.alphabet[enc[0]], B64.alphabet[enc[1]], B64.alphabet[enc[2]], B64.alphabet[enc[3]]); } return result.join(''); } else { result = ''; while (++position < len) { nan1 = buffer[position + 1], nan2 = buffer[position + 2]; enc[0] = buffer[position] >> 2; enc[1] = ((buffer[position] & 3) << 4) | (buffer[++position] >> 4); if (isNaN(nan1)) enc[2] = enc[3] = 64; else { enc[2] = ((buffer[position] & 15) << 2) | (buffer[++position] >> 6); enc[3] = (isNaN(nan2)) ? 64 : buffer[position] & 63; } result += B64.alphabet[enc[0]] + B64.alphabet[enc[1]] + B64.alphabet[enc[2]] + B64.alphabet[enc[3]]; } return result; } }, decode: function (s) { var buffer = B64.fromUtf8(s), position = 0, len = buffer.length; if (B64.ieo) { result = []; while (position < len) { if (buffer[position] < 128) result.push(String.fromCharCode(buffer[position++])); else if (buffer[position] > 191 && buffer[position] < 224) result.push(String.fromCharCode(((buffer[position++] & 31) << 6) | (buffer[position++] & 63))); else result.push(String.fromCharCode(((buffer[position++] & 15) << 12) | ((buffer[position++] & 63) << 6) | (buffer[position++] & 63))); } return result.join(''); } else { result = ''; while (position < len) { if (buffer[position] < 128) result += String.fromCharCode(buffer[position++]); else if (buffer[position] > 191 && buffer[position] < 224) result += String.fromCharCode(((buffer[position++] & 31) << 6) | (buffer[position++] & 63)); else result += String.fromCharCode(((buffer[position++] & 15) << 12) | ((buffer[position++] & 63) << 6) | (buffer[position++] & 63)); } return result; } }, toUtf8: function (s) { var position = -1, len = s.length, chr, buffer = []; if (/^[\x00-\x7f]*$/.test(s)) while (++position < len) buffer.push(s.charCodeAt(position)); else while (++position < len) { chr = s.charCodeAt(position); if (chr < 128) buffer.push(chr); else if (chr < 2048) buffer.push((chr >> 6) | 192, (chr & 63) | 128); else buffer.push((chr >> 12) | 224, ((chr >> 6) & 63) | 128, (chr & 63) | 128); } return buffer; }, fromUtf8: function (s) { var position = -1, len, buffer = [], enc = [, , , ]; if (!B64.lookup) { len = B64.alphabet.length; B64.lookup = {}; while (++position < len) B64.lookup[B64.alphabet[position]] = position; position = -1; } len = s.length; while (position < len) { enc[0] = B64.lookup[s.charAt(++position)]; enc[1] = B64.lookup[s.charAt(++position)]; buffer.push((enc[0] << 2) | (enc[1] >> 4)); enc[2] = B64.lookup[s.charAt(++position)]; if (enc[2] == 64) break; buffer.push(((enc[1] & 15) << 4) | (enc[2] >> 2)); enc[3] = B64.lookup[s.charAt(++position)]; if (enc[3] == 64) break; buffer.push(((enc[2] & 3) << 6) | enc[3]); } return buffer; } }; function downloadInvoice() { // add download button $('.download').click(function(e) { e.preventDefault(); // try to get authentication from sessionstorage var authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if (authentication === null) { authentication = localStorage.getItem("authentication"); } var invoice = $(this).data('invoice'); // create form var form = $('
    '); form.append(''); form.append(''); $(this).after(form); // submit and remove form form.submit(); form.remove(); }); }/* Page */ function Page(success) { "use strict"; if(typeof success === "undefined") { success = function () {}; } this.success = success; this.contract = null; this.initialize = function () { // get contract info var op = this; $.getJSONCache(baseurl + infomethod, function (data) { op.contract = data.message.response; if (data.message.response.disabled !== undefined && data.message.response.disabled === 1) { $('div#contract_disabled').show(); } // set name in navbar $('#navbar-contractname').text(op.contract.contractname); // now run success function op.success(); }); // accountdropdown; production accounts before demo accounts $.getJSONCache(baseurl + accountsmethod, function (data) { // create arrays var productionaccountsmanualmode = []; var demoaccountsmanualmode = []; var productionaccountstransactions = []; var demoaccountstransactions = []; var productionaccountsstoredfiles = []; var demoaccountsstoredfiles = []; var productionaccountsbatcher = []; var demoaccountsbatcher = []; var productionaccountsdecoder = []; var demoaccountsdecoder = []; // iterate, fill arrays $.each(data.message.response, function (i, val) { var manualmodeaccounts = $('
  • ' + val.AccountName + '
  • '); var transactionaccounts = $('
  • ' + val.AccountName + '
  • '); var storedfilesaccounts = $('
  • ' + val.AccountName + '
  • '); var batcheraccounts = $('
  • ' + val.AccountName + '
  • '); var decoderaccounts = $('
  • ' + val.AccountName + '
  • '); // fill the transaction-arrays if (val.Demo !== '1') { productionaccountsmanualmode.push(manualmodeaccounts); productionaccountstransactions.push(transactionaccounts); } else { demoaccountsmanualmode.push(manualmodeaccounts); demoaccountstransactions.push(transactionaccounts); } // when there is a FTPUploadUser, fill the storedfiles-arrays if (val.FTPuploadUser) { $('#storedfilesmenuitem').parent().removeClass('hidden'); if (val.Demo !== '1') { productionaccountsstoredfiles.push(storedfilesaccounts); } else { demoaccountsstoredfiles.push(storedfilesaccounts); } } // when accounts have access to Batcher, fill array if (val.Batcher === '1') { if (val.Demo !== '1') { productionaccountsbatcher.push(batcheraccounts); } else { demoaccountsbatcher.push(batcheraccounts); } } // when accounts have access to Decoder, fill array if (val.Decoder === '1') { if (val.Demo !== '1') { productionaccountsdecoder.push(decoderaccounts); } else { demoaccountsdecoder.push(decoderaccounts); } } }); // add items for dropdown menu for Transactions for (var i = 0; i < productionaccountstransactions.length > 0; i++) { $('#navbar-accountdropdown').append(productionaccountstransactions[i]); } if(productionaccountstransactions.length > 0 && demoaccountstransactions.length > 0) { $('#navbar-accountdropdown').append('
  • '); } for (var i = 0; i < demoaccountstransactions.length > 0; i++) { $('#navbar-accountdropdown').append(demoaccountstransactions[i]); } // add items for dropdown menu for manual mode for (var i = 0; i < productionaccountsmanualmode.length > 0; i++) { $('#navbar-manualmodedropdown').append(productionaccountsmanualmode[i]); } if(productionaccountsmanualmode.length > 0 && demoaccountsmanualmode.length > 0) { $('#navbar-manualmodedropdown').append('
  • '); } for (var i = 0; i < demoaccountsmanualmode.length > 0; i++) { $('#navbar-manualmodedropdown').append(demoaccountsmanualmode[i]); } // do the same for Stored Files for (var i = 0; i < productionaccountsstoredfiles.length > 0; i++) { $('#navbar-storedfilesdropdown').append(productionaccountsstoredfiles[i]); } if(productionaccountsstoredfiles.length > 0 && demoaccountsstoredfiles.length > 0) { $('#navbar-storedfilesdropdown').append('
  • '); } for (var i = 0; i < demoaccountsstoredfiles.length > 0; i++) { $('#navbar-storedfilesdropdown').append(demoaccountsstoredfiles[i]); } // and don't let us forget the batcher if(productionaccountsbatcher.length > 0 || demoaccountsbatcher.length > 0) { $('#batcher').show(); } for (var i = 0; i < productionaccountsbatcher.length > 0; i++) { $('#navbar-batchesdropdown').append(productionaccountsbatcher[i]); } if(productionaccountsbatcher.length > 0 && demoaccountsbatcher.length > 0) { $('#navbar-batchesdropdown').append('
  • '); } for (var i = 0; i < demoaccountsbatcher.length > 0; i++) { $('#navbar-batchesdropdown').append(demoaccountsbatcher[i]); } // or the decoder if(productionaccountsdecoder.length > 0 || demoaccountsdecoder.length > 0) { $('#decoder').show(); } for (var i = 0; i < productionaccountsdecoder.length > 0; i++) { $('#navbar-decoderdropdown').append(productionaccountsdecoder[i]); } if(productionaccountsdecoder.length > 0 && demoaccountsdecoder.length > 0) { $('#navbar-decoderdropdown').append('
  • '); } for (var i = 0; i < demoaccountsdecoder.length > 0; i++) { $('#navbar-decoderdropdown').append(demoaccountsdecoder[i]); } }); // logout $('#logout').click(function () { localStorage.clear(); sessionStorage.clear(); document.location = 'login.php'; }); $('button[data-href]').click(function(){ document.location = $(this).data('href'); }); } this.initialize(); } // Contract function Contract() { "use strict"; this.info = null; this.credits = null; this.accounts = null; this.showCredits = function (refresh) { $.getJSONCache(baseurl + creditsmethod, function (data) { var credits_available = data.message.response.credits_available var remaining_days = data.message.response.remaining_days; if (credits_available !== null) { // display creditsavailable and estimateduse $('#creditsinfo .creditsavailable').text(credits_available); var ordernow = ''; if (remaining_days !== null) { var estimated_use = $('#creditsinfo .estimateduse'); estimated_use.text(remaining_days + ' days remaining'); if (remaining_days <= 7) { var order = '
    Order credits now!'; estimated_use.append(order); } } } else { // or remove the headers $('#creditsinfo .header_creditsavailable').text(''); $('#creditsinfo .header_estimateduse').text(''); } }, refresh); } this.showInfo = function () { $.getJSONCache(baseurl + infomethod, function (data) { $('#contractinfo .contactname').text(data.message.response.contactname); $('#contractinfo .contractname').text(data.message.response.contractname); $('#contractinfo .contactmail').text(data.message.response.contactmail); var agreement = $('#contractinfo .agreement'); if (!data.message.response.hasproductionaccounts) { agreement.html('TEST MODE NO SIGNED AGREEMENTS RECEIVED!
    For commercial use, an agreement is required. Please contact Support for more info'); } else if (data.message.response.contractsigneddate !== null) { var contractsigneddate = new Date(data.message.response.contractsigneddate); agreement.text('Signed agreements ' + contractsigneddate.getDate() + '-' + (contractsigneddate.getMonth() + 1) + '-' + contractsigneddate.getFullYear()); } else { agreement.remove(); } }); } this.showNewsContent = function(refresh) { $.getJSONCache(baseurl + newscontentmethod, function (data) { $('#news-content').html(data.message.response.news); $('#hints-content').html(data.message.response.hints); $('#important-content').html(data.message.response.important); $('#newsletters-content').html(data.message.response.newsletters); }, refresh); } this.displayWarning = function() { var warning_agreement = $('#warning_agreement'); $.getJSONCache(baseurl + infomethod, function (data) { if (data.message.response.hasproductionaccounts) { warning_agreement.remove(); } else { // display warning in Credits block warning_agreement.text('You\'re using a free version of BooXtream which can only be used for test and implementation purposes. Any commercial and production usage is prohibited.'); } }); } this.initialize = function () { var oPage = new Page(); this.showInfo(); this.showNewsContent(); this.showCredits(); this.displayWarning(); var op = this; $('#refresh_credits_news').click(function () { $(this).animateRotate(360, 500); op.showCredits(true); op.showNewsContent(true); }); } this.initialize(); } // Login function Login() { "use strict"; var op = this; this.login = function() { var authentication = B64.encode($('input[name="accountname"]').val()+':'+$('input[name="accesskey"]').val()); $.getJSONAuth(baseurl + infomethod, function (data) { // set authentication to sessionstorage sessionStorage.setItem("authentication", authentication); // or if checkbox checked: set it to localstorage if ($('input[name="rememberme"]').is(':checked')) { localStorage.setItem("authentication", authentication); } $.post('session.php', data.message.response, function () { document.location = 'index.php'; }); }, function (data) { // error function (401) $('#alert').slideDown('slow'); setTimeout(function () { $('#alert').slideUp('slow'); }, 5000); }, authentication ); //return false; } this.initialize = function () { $('#loginform').prepend($('

    Oh snap!

    Seems something is wrong with your credentials. Please try again.

    ').hide()); // inlogname and... enter $('#accountname').keydown(function (e){ if(e.keyCode == 13){ op.login(); } }) // password and... enter $('#accesskey').keydown(function (e){ if(e.keyCode == 13){ op.login(); } }) // use login-button $('#login').click(function (e) { op.login(); }); } this.initialize(); } function Transactions() { "use strict"; this.Accounts = []; this.pages = undefined; this.page = undefined; this._ignoreHashChange = false; this.name = null; // AccountName (from accounts table) this.accountname = null; // LoginName (from accounts table) this.accountkey = null; // AuthenticationKey (from accounts table) this.activesearch = false; this.retrievetransactions = transactionsmethod; this.limit = localStorage.getItem("transactionslimit"); if (this.limit == null) { this.limit = 100; } this.displayTransactions = function (transactions, total, credits_available, remaining_days) { this.pages = Math.ceil(total / this.limit); // show transactions $('#transactions-tbody').children('.datarow').remove(); if (credits_available !== null) { $('#credits_available').text('Available credits: ' + credits_available); } if (remaining_days !== null) { $('#estimated_use').text('Estimated use: ' + remaining_days + ' days remaining'); if (remaining_days <= 7) { var order = '
    Order credits now!'; $('#estimated_use').append(order); } } var op = this; $.each(transactions, function (i, val) { var status = ''; if(val.Status === 'failed' || val.Failed === '1') { status += ' '; } else if (val.Status === 'processing') { status += ' '; } else { status += ' '; if (val.DeliveryPlatform === '1') { status += op.getStatusHTML(val.DeliveryStatus, val.ExpireDate, val.TotalDownloads, val.DownloadLimit); } else { status += ' '; } } if(val.Stored == 1) { status += ' '; } // end with a non-breaking space to force the browser to assume the correct line-height // status += ' '; var filename = val.OriginalFilename.replace(/"/g,'"'); filename = getCellHTML('Master file', filename, 50, false); /* 24 */ var reference = getCellHTML('Reference', val.ReferenceID, 30); var customeremailaddress = getCellHTML('Customer Email Address', val.CustomerEmailAddress, 25); var customername = getCellHTML('Customer Name', val.CustomerName, 25); var datetime = ''; var tr = $('').addClass('datarow'); tr.append($('' + datetime + '')); tr.append($('' + status +'')); tr.append($('' + reference + '')); tr.append($('' + customeremailaddress + '')); tr.append($('' + customername + '')); tr.append($('' + filename + '')); // add click to datarow, goes to transaction tr.click(function () { window.location = 'transaction.php?account=' + op.accountname + '&uid=' + val.UID; }); $('#transactions-tbody').append(tr); }); // add tooltips $('tr.datarow [data-toggle~="tooltip"]').tooltip(); // add popovers $('tr.datarow [data-toggle~="popover"]').popover({ placement: 'top', html: true, trigger: 'hover' }); } // creates content for status cell this.getStatusHTML = function (deliverystatus, expiredate, totaldownloads, downloadlimit) { var content = 'Expires on ' + formatDisplayUTCDate(new Date(expiredate)).split(' ')[0] + ' (UTC)
    ' + totaldownloads + ' out of ' + downloadlimit + ' downloads.'; if(deliverystatus === 'expired' || deliverystatus === 'limitreached') { return ' '; } return ' '; } this.getPage = function (pagenumber, search) { startSpinner('#spinner'); this.page = parseInt(pagenumber); // calculate offset based on number of transactions per page (limit) var offset = (this.page - 1) * this.limit; // show selected limit; the default number of rows $('select.limit option[value="' + this.limit + '"]').attr('selected', 'selected'); // build transaction url var url = baseurl + 'account/' + this.accountkey + '/' + this.retrievetransactions + '?offset=' + offset + '&limit=' + this.limit; if(search !== undefined) { url += '&search=' + search; this.activesearch = search; } else if (this.activesearch != false) { url += '&search=' + this.activesearch; } // get and display transactions var op = this; $.getJSONAuth(url, function (data) { op.name = data.message.account.AccountName; if(typeof data.message !== undefined) { if(data.message.total > 0) { op.displayTransactions(data.message.response, data.message.total, data.message.credits_available, data.message.remaining_days); op.displayPagination(); } if(typeof search !== 'undefined' && parseInt(data.message.total) === 0) { $('#searchmessage').html($('

    No results for "'+ search +'"!

    No results found. Please try again.

    ').hide()); $('#alert').slideDown('slow'); setTimeout(function () { $('#alert').slideUp('slow', function () { $(this).remove(); }); }, 5000); } if(typeof search == 'undefined' && parseInt(data.message.total) === 0) { var displaymessage = 'No transactions found!' if (url.includes('failedtransactions')) { displaymessage = 'No errors found!'; } $('.datarow').remove(); $('#searchmessage').html($('

    ' + displaymessage + '

    There are no transactions that can be displayed.

    ').hide()); $('#alert').slideDown('slow'); setTimeout(function () { $('#alert').slideUp('slow', function () { $(this).remove(); }); }, 5000); } $('#accountname').html(data.message.account.AccountName + (data.message.account.Demo === '1' ? ' (test account)' : ' (production account)')); } stopSpinner('#spinner'); }); } this.initButtons = function() { var op = this; // display the right buttons if (op.type == 'errors') { $('.errortransactions').removeClass('btn-default').addClass('btn-primary'); $('#downloadTransactionsCSV').addClass('hidden'); } else { $('.alltransactions').removeClass('btn-default').addClass('btn-primary'); $('#downloadTransactionsCSV').removeClass('hidden'); } $('.transactiontypebutton').click(function() { if($(this).hasClass('errortransactions')) { op.type = 'errors'; $('.alltransactions').removeClass('btn-primary').addClass('btn-default'); $('.errortransactions').removeClass('btn-default').addClass('btn-primary'); op.retrievetransactions = failedtransactionsmethod; op.sURL.parameters.type = 'errors'; $('#downloadTransactionsCSV').addClass('hidden'); } else { op.type = 'all'; $('.errortransactions').removeClass('btn-primary').addClass('btn-default'); $('.alltransactions').removeClass('btn-default').addClass('btn-primary'); op.retrievetransactions = transactionsmethod; op.sURL.parameters.type = 'all'; $('#downloadTransactionsCSV').removeClass('hidden'); } op.sURL.parameters.page = 1; var url = getURL(op.sURL); history.pushState(null,null,url); op.getPage(1); }); // change limit $('select.limit').change(function() { op.limit = $(this).find('option:selected').text(); localStorage.setItem("transactionslimit", op.limit); op.page = 1; op.getPage(1); }); $('#downloadTransactionsCSV').click(function (e) { var datefrom = new Date(new Date().getFullYear(), 0, 1); var dateuntil = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() -1); // datefrom might lie 730 days further in the past var mindatefrom = new Date(datefrom.getTime() - (730 * 24 * 60 * 60 * 1000)); $('#datepicker_datefrom').datepicker('setDate', datefrom) .datepicker('option', 'maxDate', dateuntil) .datepicker('option', 'minDate', mindatefrom) .datepicker('option', 'dateFormat', 'yy-mm-dd') .addClass('placeholder_layout'); $('#datepicker_dateuntil').datepicker('setDate', dateuntil) .datepicker('option', 'maxDate', dateuntil) .datepicker('option', 'minDate', mindatefrom) .datepicker('option', 'dateFormat', 'yy-mm-dd') .addClass('placeholder_layout'); }); // add functionality for downloadbutton $('a#downloadTransactionsCSVButton').click(function(event) { event.preventDefault(); // get dates from modal var datefrom = new Date(Date.parse($('#datepicker_datefrom').datepicker('getDate'))); var dateuntil = new Date(Date.parse($('#datepicker_dateuntil').datepicker('getDate'))); if (datefrom > dateuntil) { var message = 'Start date should be before end date.'; $('#exporterror').html(message).removeClass('hidden'); } else { $('#exporterror').html('').addClass('hidden'); $('#downloadTransactionsCSVModal').modal('hide'); // try to get authentication from sessionstorage var authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if (authentication === null) { authentication = localStorage.getItem("authentication"); } // convert dates from Epoch to yyyy-mm-dd (including leading zero's) datefrom = datefrom.getFullYear() + '-' + ('0' + (datefrom.getMonth() + 1)).slice(-2) + '-' + ('0' + datefrom.getDate()).slice(-2); dateuntil = dateuntil.getFullYear() + '-' + ('0' + (dateuntil.getMonth() + 1)).slice(-2) + '-' + ('0' + dateuntil.getDate()).slice(-2); // create form var form = $('
    '); form.append(''); form.append(''); form.append(''); form.append(''); form.append(''); form.append(''); $(this).after(form); // submit and remove form form.submit(); form.remove(); } }); } // functionality for the search bar this.initSearch = function (search) { var op = this; $('#resetbutton').click(function() { $('#resetbutton').addClass('hidden'); op.activesearch = false; op.sURL.parameters.search = undefined; op.sURL.parameters.page = 1; // create url for pushState var url = getURL(op.sURL); history.pushState(null,null,url); op.getPage(1); }); $('#searchinput').keyup(function(){ if($(this).val().length > 0) { $('#resetbutton').removeClass('hidden'); } else { $('#resetbutton').addClass('hidden'); } }); $('#search').on('submit', function () { if($('#searchinput').val().length > 0) { $('#resetbutton').removeClass('hidden'); } else { $('#resetbutton').addClass('hidden'); } var search = $(this).children('.input-group').children('input[name="search"]').val(); op.getPage(1,search); op.sURL.parameters.search = search; op.sURL.parameters.page = 1; // create url for pushState var url = getURL(op.sURL); history.pushState(null,null,url); return false; }); /* var livesearch = undefined; $('#search input[name="search"]').on('keyup', function () { var search = $('#search').children('.form-group').children('input[name="search"]').val(); clearTimeout(livesearch); console.log(search.length); if(search.length > 3) { livesearch = setTimeout(function () { op.getPage(1,search); }, 1000); } }); */ } this.initPagination = initPagination; this.displayPagination = displayPagination; this.initialize = function () { // initialize page var oPage = new Page(); // get key first this.sURL = urlObject(); var accountname = this.sURL.parameters.account; this.accountname = accountname; this.type = this.sURL.parameters.type; if (this.type == 'errors') { this.retrievetransactions = failedtransactionsmethod; } var op = this; $( '#datepicker_datefrom' ).datepicker(); $( '#datepicker_dateuntil' ).datepicker(); $.getJSONCache(baseurl + accountsmethod, function (data) { op.accountkey = data.message.response; $.each(data.message.response, function (i,val) { op.Accounts[val.LoginName] = val.AuthenticationKey; }); op.accountkey = op.Accounts[accountname]; // see if url has search parameter var search = undefined; if(typeof op.sURL.parameters.search !== "undefined") { $('#resetbutton').removeClass('hidden'); $('#searchinput').val(op.sURL.parameters.search); search = op.sURL.parameters.search; } // get page op.page = 1; if(typeof op.sURL.parameters.page !== "undefined") { op.page = op.sURL.parameters.page; } op.getPage(op.page,search); }); // initialize the rest this.initButtons(); this.initSearch(); this.initPagination(); // handle back-button $(window).bind("popstate", function change(e) { if(!this._ignoreHashChange) { // we need to reset the urlObject op.sURL = new urlObject(); var search = undefined; if(typeof op.sURL.parameters.search !== "undefined") { $('#resetbutton').removeClass('hidden'); $('#searchinput').val(op.sURL.parameters.search); search = op.sURL.parameters.search; } else { op.activesearch = false; if($('#searchinput').val() !== '') { $('#search').get(0).reset(); } } // get page op.page = 1; if(typeof op.sURL.parameters.page !== "undefined") { op.page = op.sURL.parameters.page; } op.getPage(op.page,search); } }); // catch transactions csv error var fromdate = localStorage.getItem('fromdate'); var untildate = localStorage.getItem('untildate'); var message = localStorage.getItem('message'); if (fromdate && untildate && message) { localStorage.removeItem('fromdate'); localStorage.removeItem('untildate'); localStorage.removeItem('message'); $('#downloadTransactionsCSV').click(); $('#datepicker_datefrom').datepicker('setDate', fromdate); $('#datepicker_dateuntil').datepicker('setDate', untildate); $('#exporterror').html(message).removeClass('hidden'); } } this.initialize(); } // Transaction function Transaction() { "use strict"; this.Accounts = []; this.accountkey = null; this.uid = null; this.transaction = null; this.account = null; this.oPage = null; var op = this; this.getTransaction = function () { var op = this; $.getJSONCache(baseurl + 'account/' + this.accountkey + '/' + transactionmethod + '?uid=' + this.uid, function (data) { op.addItems(data.message.response); $('#accountname').html(data.message.account.AccountName + (data.message.account.Demo === '1' ? ' (test account)' : ' (production account)')); op.transaction = data.message.response; op.account = data.message.account; }); } this.emptyTransaction = function () { $('#etransaction').empty(); $('#tech').empty(); $('#errormessages').empty(); $('#identification').empty(); $('#watermarks').empty(); $('#platform').empty(); $('#direct').empty(); } this.addItems = function (transaction) { this.addGroup = function (id, title, border = true) { $('#' + id).append('

    ' + title + '

    ').append('
    ').removeClass('hidden'); if (border) { $('#' + id).append($('
    ')); } return $('#' + id + ' dl'); } // transaction var eltransaction = this.addGroup('etransaction', ' Ebook'); var identification = this.addGroup('identification', ' Identification'); this.addItem(eltransaction,'Master file', transaction.OriginalFilename); if (transaction.Stored === '1') { this.addItem(eltransaction, 'Stored file', 'Yes'); } else { this.addItem(eltransaction, 'Stored file', 'No'); } if (transaction.Source === 'dashboard') { this.addItem(eltransaction, 'Source', 'Dashboard'); } else { this.addItem(eltransaction, 'Source', 'API'); } var d = new Date(transaction.DateTime); var localdate = formatLocalISODate(d); var utcdate = formatDisplayUTCDate(d); var datetime = ''; this.addItem(eltransaction,'Date / Time (UTC)', datetime); this.addItem(eltransaction, 'Language', transaction.LanguageCode + ' / ' + languages[transaction.LanguageCode]); this.addItem(identification,'UID', transaction.UID); this.addItem(identification,'Reference', transaction.ReferenceID); if (transaction.CustomerName != null) { this.addItem(identification,'Customer Name',transaction.CustomerName); } if (transaction.CustomerEmailAddress != null) { this.addItem(identification,'Customer Email',transaction.CustomerEmailAddress); } // Watermarks if(transaction.ExLibris != null || transaction.ExLibrisFile != null || transaction.ChapterFooter != null || transaction.Disclaimer != null || transaction.ShowDate != null) { var watermarks = this.addGroup('watermarks', ' Watermarks'); if (transaction.ExLibris != null) { this.addItem(watermarks,'Ex Libris', transaction.ExLibris == 1 ? 'Yes' : 'No'); } if (transaction.ExLibrisFile != null) { this.addItem(watermarks,'Ex Libris File', transaction.ExLibrisFile); } if (transaction.ChapterFooter != null) { this.addItem(watermarks,'Chapter Footer', transaction.ChapterFooter == 1 ? 'Yes' : 'No'); } if (transaction.Disclaimer != null) { this.addItem(watermarks,'Disclaimer', transaction.Disclaimer == 1 ? 'Yes' : 'No'); } if (transaction.ShowDate != null) { this.addItem(watermarks, 'Show Date', transaction.ShowDate == 1 ? 'Yes' : 'No'); } } // BooXtream Platform // determine if ebook was created with platform or direct stream if (transaction.DeliveryPlatform != null && transaction.DeliveryPlatform === '1') { var platform = this.addGroup('platform', ' Download links'); var editButton = $('').addClass('btn btn-primary pull-right').attr('id', 'editavailability-button').text('Edit availability'); // // disable editButton 730 days after transaction.DateTime or when the request failed var dateLimit = new Date(transaction.DateTime); dateLimit.setDate(dateLimit.getDate() + 730); var currentDate = new Date(); if (currentDate > dateLimit) { editButton = $('').addClass('btn btn-primary pull-right').attr('disabled', 'disabled').text('Cannot reactivate transactions older than 730 days'); } else if (transaction.Status != null && transaction.Status === 'failed') { editButton = $('').addClass('btn btn-primary pull-right').attr('disabled', 'disabled').text('Cannot reactivate transactions with an error.'); } $('#platform').prepend(editButton); var d = new Date(Date.UTC(transaction.ExpireDate.substr(0,4), (transaction.ExpireDate.substr(5,2) - 1), transaction.ExpireDate.substr(8,2), 0, 0, 0)); // format dates var utcdate = formatDisplayUTCDate(d); var localdate = formatLocalISODate(d); var expirydate = ''; // show expiry date and number of downloads, including renewButton and resetButton this.addItem(platform, 'Expiry Date (UTC)', '
    ' + expirydate +'
    '); this.addItem(platform, 'Remaining downloads', (transaction.DownloadLimit - transaction.TotalDownloads) + ' (of ' + transaction.DownloadLimit + ')'); // evaluate Status and DeliveryStatus // transaction.Status can be: processing, completed, failed // transaction.DeliveryStatus (with transaction.DeliveryPlatform) can be: ok, limitreached, expired var status = ''; if (transaction.Status != null) { if (transaction.Status === 'failed') { status += ' Error'; } else if (transaction.Status === 'processing') { status += ' Processing'; } else { switch (transaction.DeliveryStatus) { case 'ok': status += ' Available for download'; break; case 'expired': status += ' Unavailable: Expiry date reached'; break; case 'limitreached': status += ' Unavailable: Download limit reached'; break; } } this.addItem(platform, 'Status', status); platform.append($('
    ')); } // Download links // @todo: geef credentials mee, zodat geen inlogscherm if (transaction.DownloadLinks != null) { var downloadlinks = ''; // append it all platform.append($(downloadlinks)); platform.append($('
    ')); } // check for downloads; add downloads if (transaction.Downloads.length > 0) { platform.append($('

    Download history

    ')); var table = $('
    ').addClass('table table-condensed'); platform.append(table); var th = $(''); th.append($('Date / Time (UTC)')); th.append($('IP Address')); th.append($('Type')); table.append(th); $.each(transaction.Downloads, function (i, val) { // in the past, val.DownloadType was not always specified, but we don't want to show 'null' var type = ''; if (val.DownloadType != null) { type = val.DownloadType; } var d = new Date(val.DateTime); var utcdate = formatDisplayUTCDate(d); var localdate = formatLocalISODate(d); var tr = $(''); tr.append(''); tr.append('' + val.IpAddress + ''); tr.append('' + type + ''); table.append(tr); }); } // activate modal on edit-button $('#editavailability-button').click(function (e) { // names of the months for error message text, to avoid date formatting (20-08-2021, 08/20/2021, etc) const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; // calculate days between dates: translate dates to miliseconds, and miliseconds to number of days // be aware: the dates have local timezones, but that should not matter for the difference in days var transactiondate = new Date(transaction.DateTime); transactiondate.setHours(0,0,0,0); var expirydate = new Date(transaction.ExpireDate); expirydate.setHours(0,0,0,0); var today = new Date(); today.setHours(0, 0, 0, 0); var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); // calculate numbers for datepicker explanation text var expiry_from_transaction_date = Math.round((expirydate.getTime() - transactiondate.getTime()) / (24 * 60 * 60 * 1000)); if (expiry_from_transaction_date > 1) { expiry_from_transaction_date = expiry_from_transaction_date + ' days'; } else { expiry_from_transaction_date = expiry_from_transaction_date + ' day'; } var explanation = 'Expired ' + expiry_from_transaction_date + ' from transaction date.'; if (expirydate > today) { var expiry_from_today = Math.round((expirydate.getTime() - today.getTime()) / (24 * 60 * 60 * 1000)); if (expiry_from_today > 1) { expiry_from_today = expiry_from_today + ' days'; } else { expiry_from_today = expiry_from_today + ' day'; } explanation = 'Expires ' + expiry_from_transaction_date + ' from transaction date, ' + expiry_from_today + ' from today.'; } // get maximum ExpiryDate for DatePicker (730 days after transaction date) var maxdate = new Date(transactiondate.getTime() + (730 * 24 * 60 * 60 * 1000)); // get error message text var errormessage = 'Please insert a date between tomorrow and ' + maxdate. getDate() + ' ' + monthNames[maxdate.getMonth()] + ' ' + maxdate. getFullYear(); // get number of downloads as minimum downloadlimit; use it when the form is submitted var number_of_downloads = 0; if (typeof transaction.Downloads !== 'undefined') { number_of_downloads = transaction.Downloads.length; } // set the transaction date for calculation of a new explanation text, set the downloadlimit for calculating the final downloadlimit after submit $('#editavailabilityform').data('transactiondate', transactiondate).data('number_of_downloads', number_of_downloads); // set datepicker at expiry date; available dates: all dates from today until max expiry date $('#datepicker').datepicker('setDate', expirydate) .datepicker('option', 'minDate', tomorrow) .datepicker('option', 'maxDate', maxdate) .datepicker('option', 'dateFormat', 'yy-mm-dd') .addClass('placeholder_layout'); $('#datepicker_explanation').html(explanation); $('#datepicker_errormessage').html(errormessage); var remaining = transaction.DownloadLimit - transaction.Downloads.length; if (remaining < 0) { remaining = 0; } $('#new_downloadlimit').val('').attr('placeholder', 'Remaining downloads: '+remaining); $('#editavailabilitymodal .modal-body .alert').remove(); $('#editavailabilitymodal .modal-footer .submit').show(); $('#editavailabilitymodal .modal-footer .dismiss').text('Cancel'); $('#editavailabilitymodal').modal(); }); } else { var direct = this.addGroup('direct', ' BooXtream Direct'); if (transaction.Status === 'failed') { var status = ' Error'; } else if (transaction.Status === 'processing') { var status = ' Processing'; } else { // if ebook was created with direct stream, by default status = ok if (transaction.Epub != null) { this.addItem(direct, 'Generated', 'epub'); } else { if (transaction.Mobi != null) { this.addItem(direct, 'Generated', 'mobi'); } } var status = ' OK'; } this.addItem(direct, 'Status', status); } // Technical details (only if there is a plugin callback url) if (transaction.CallbackUrl != null) { var tech = this.addGroup('tech', ' Technical details'); this.addItem(tech, 'Callback Url', transaction.CallbackUrl); } if (transaction.Errors && transaction.Errors.length > 0) { var errors = this.addGroup('errormessages', '
    Errors', false); var table = $('
    ').addClass('table table-condensed').attr('style', 'margin-bottom: 0px;'); var th = $(''); th.append($('Code')); th.append($('Description')); table.append(th); $.each(transaction.Errors, function (i, val) { var Code = parseInt(val.Code); switch(Code) { case 51: Code += ': WordPress plugin error; please contact Support'; break; case 400: Code += ': Bad Request'; break; case 405: Code += ': Not Allowed'; break; case 409: Code += ': Conflict'; break; case 412: Code += ': Precondition Failed'; break; case 422: Code += ': Unprocessable Entity'; break; default: if(Code >= 1000) { Code = Code - 1000; Code += ': Callback failed; ebook watermarked successfully, but BooXtream is unable to respond to the callback url'; } break; } var tr = $(''); tr.append($(''+Code+'')); tr.append($(''+val.Description+'')); table.append(tr); }); errors.append(table); } // allow popovers to function $('#transaction time').popover({ placement: 'top', trigger: 'hover' }); $('dd time').popover({ placement: 'top', trigger: 'hover' }); $('.datarow time').popover({ placement: 'top', trigger: 'hover' }); } this.addItem = function (container, dt, dd) { var eldt = $('
    ' + dt + '
    '); var eldd = $('
    ' + dd + '
    '); container.append(eldt); container.append(eldd); } /* wordt deze code nog wel gebruikt? this.createPanel = function (id, title, icon) { var panel = $('
    ').attr('id', id).addClass('panel panel-default'); var heading = $('
    ').addClass('panel-heading'); var spanicon = $('').addClass('fa fa-'+icon); // add space to title to move it from the icon heading.append(spanicon, ' '+title); panel.append(heading); return panel; } */ this.createSupportTicket = function () { var supportTicket = $('').addClass('btn btn-primary').attr('id', 'support-button').text('Create support ticket'); // $('#buttons').prepend(supportTicket); } this.editAvailability = function () { $('#datepicker').change(function() { // get data $('#datepicker').removeClass('placeholder_layout'); var new_expirydate = Date.parse($('#datepicker').datepicker('getDate')); var transactiondate = Date.parse($('#editavailabilityform').data('transactiondate')); // milliseconds since Unix Epoch, based on localized transaction date var today = new Date(); today.setHours(0, 0, 0, 0); var expiry_from_transaction_date = Math.round((new_expirydate - transactiondate) / (24 * 60 * 60 * 1000)); if (!isNaN(expiry_from_transaction_date) && (expiry_from_transaction_date < 0 || expiry_from_transaction_date > 730)) { $('#datepicker_errormessage').removeClass('hidden'); } else { $('#datepicker_errormessage').addClass('hidden'); } // calculate numbers for datepicker explanation text, datepicker errormessage if (expiry_from_transaction_date > 1) { expiry_from_transaction_date = expiry_from_transaction_date + ' days'; } else { expiry_from_transaction_date = expiry_from_transaction_date + ' day'; } var expiry_from_today = Math.round((new_expirydate - today.getTime()) / (24 * 60 * 60 * 1000)); if (expiry_from_today > 1) { expiry_from_today = expiry_from_today + ' days'; } else { expiry_from_today = expiry_from_today + ' day'; } var explanation = 'Expires ' + expiry_from_transaction_date + ' from transaction date, ' + expiry_from_today + ' from today.'; $('#datepicker_explanation').html(explanation); }); } this.initialize = function () { // initialize page this.oPage = new Page(function () { setSupportTicket(this.contract); handleTicket(); }); $( '#datepicker' ).datepicker(); var url = urlObject(); // get uid this.uid = url.parameters.uid; // get key var accountname = url.parameters.account; var op = this; $.getJSONCache(baseurl + accountsmethod, function (data) { op.accountkey = data.message.response; $.each(data.message.response, function (i,val) { op.Accounts[val.LoginName] = val.AuthenticationKey; }); op.accountkey = op.Accounts[accountname]; op.getTransaction(); op.createSupportTicket(); }); // activate modal on support-button $('#support-button').click(function (e) { // add stuff to modal $('#ticketform input[name="uid"]').val(op.transaction.UID); $('#ticketform input[name="accountkey"]').val(op.accountkey); $('#support').modal(); }); // activate back button $('#goback').click(function () { window.history.back(); }); this.editAvailability(); $('#editavailabilityform').submit(function (e) { var new_expirydate = Date.parse($('#datepicker').datepicker('getDate')); var form = $('#editavailabilityform'); var transactiondate = Date.parse(form.data('transactiondate')); // milliseconds since Unix Epoch, based on localized transaction date var newexpirydays = Math.round((new_expirydate - transactiondate) / (24 * 60 * 60 * 1000)); var number_of_downloads = form.data('number_of_downloads'); var newdownloadlimit = parseInt($('#new_downloadlimit').val()); newdownloadlimit = newdownloadlimit + number_of_downloads; var error = false; if (!isNaN(newexpirydays) && (newexpirydays < 0 || newexpirydays > 730)) { $('#datepicker_errormessage').removeClass('hidden'); error = true; } else { $('#datepicker_errormessage').addClass('hidden'); } if (!isNaN(newdownloadlimit) && (newdownloadlimit < 0 || newdownloadlimit > 255)) { $('#downloadlimit_errormessage').removeClass('hidden'); error = true; } else { $('#downloadlimit_errormessage').addClass('hidden'); } var data = {}; if (!isNaN(newexpirydays)) { data.ExpiryDays = newexpirydays; } if (!isNaN(newdownloadlimit) && newdownloadlimit >= 0) { data.DownloadLimit = newdownloadlimit; } if (!error && Object.keys(data).length > 0) { data = JSON.stringify(data); $.putJSONAuth( baseurl + 'account/' + op.accountkey + '/' + transactionmethod + '?uid=' + op.uid, data, function (data) { // clear the transaction from cache to support refresh! $.clearFromCache(baseurl + 'account/' + op.accountkey + '/' + transactionmethod + '?uid=' + op.uid); // SUCCESS $('#editavailabilitymodal .modal-body').append('
    Availability succesfully updated.
    '); $('#editavailabilitymodal .modal-footer .submit').hide(); $('#editavailabilitymodal .modal-footer .dismiss').text('Close'); op.emptyTransaction(); var transaction = data.message.response; op.addItems(transaction); }, function () { // ERROR $('#editavailabilitymodal .modal-body .alert').remove(); $('#editavailabilitymodal .modal-body').prepend($('
    There was a problem updating this transaction.
    ')); $('#editavailabilitymodal .modal-footer .submit').hide(); $('#editavailabilitymodal .modal-footer .dismiss').text('Close'); return false; }); } // Prevent default click. return false; }); } this.initialize(); } // Credits function Accounting() { "use strict"; var op = this; this.displayCreditOrders = function () { $.getJSONAuth(baseurl + creditordersmethod, function (data) { // show creditorders $('#creditorders-tbody').children('.datarow').remove(); var costs = data.message.response; // filter by selectedYear var selectedYear = getSelectedYear(); costs = costs.filter(function (val) { return new Date(val.DateTime).getFullYear() === selectedYear; }); $.each(costs, function (i, val) { if (val.OrderType === 'Credit order') { // invoice numbers consisting a number of zero's have special meaning; check if invoice is not 0 or not null var invoiceZerosCheck = parseInt(val.Invoice); if (invoiceZerosCheck === 0 || val.Invoice === null) { var downloadLink = ''; } else { downloadLink = val.Invoice + ' '; } // format date, payment received var d = new Date(val.DateTime); var datetimeutcdate = formatDisplayUTCDate(d).split(' ')[0]; var paymentreceivedutcdate = ''; if (val.PaymentReceived != null) { var d = new Date(val.PaymentReceived); paymentreceivedutcdate = formatDisplayUTCDate(d).split(' ')[0]; } // create table row var tr = $('').addClass('datarow'); tr.append($('')); tr.append($('' + val.Credits + '')); tr.append($('' + val.Amount + ' ' + val.Currency + '')); tr.append($('')); tr.append($('' + downloadLink + '')); tr.append($('' + paymentreceivedutcdate + '')); tr.append($('' + val.ClientOrderID + '')); // append table row $('#creditorders-tbody').append(tr); } }); // add download button downloadInvoice(); }); } this.showAccounts = function () { var op = this; var modaldata = {}; $.getJSONCache(baseurl + accountsmethod, function (data) { $('#accounts-tbody').children('.datarow').remove(); $.each(data.message.response, function (i, val) { var tr = $('').addClass('datarow'); // when testaccount, give accountname and creditsused different layout if (parseInt(val.Demo) === 1) { tr.append($('' + val.AccountName + ' (test account)')); tr.append($('' + val.CreditsUsed + '  (free)')); } else { tr.append($('' + val.AccountName + '')); tr.append($('' + val.CreditsUsed + '')); } var numberOfFiles = ''; var totalFileSize = ''; // checks for number and size of stored files if (typeof val.NumberOfFiles !== 'undefined') { // convert size in bytes into megabytes, or (if the total size is equal to or more than 1 GB) into gigabytes var totalFileSize = (parseInt(val.TotalFileSize) / (1024 * 1024)).toFixed(2); if (totalFileSize >= 1024) { totalFileSize = (parseInt(totalFileSize) / 1024).toFixed(2) + ' GB'; } else { totalFileSize = totalFileSize + ' MB'; } numberOfFiles = val.NumberOfFiles; } else if (val.FTPuploadUser != null && val.FTPuploadUser != '') { // display zeros when StoredFiles is enabled but no files are stored yet var numberOfFiles = 0; var totalFileSize = 0; } // expiredays // discount factor // kindlegen / calibre tr.append($('' + numberOfFiles + '')); if (parseInt(val.Demo) === 1) { tr.append($('' + totalFileSize + '  (free)')); } else { tr.append($('' + totalFileSize + '')); } // add a litte bit of space tr.append($('    ')); // check for contact name, contact mail; append them var contact = ''; if(val.ContactMail != null) { contact = ''; if(val.ContactName != null) { contact += val.ContactName + ''; } else { contact += val.ContactMail + ''; } } else if(val.ContactName != null) { contact = val.ContactName; } tr.append($('' + contact + '')); var settings = $(''); modaldata[val.LoginName] = { 'loginname': val.LoginName, 'accesskey': val.AuthenticationKey, 'ftpuser': val.FTPuploadUser, 'ftppass': val.FTPuploadPassword } // place icons of the most used functions to the right if (val.CopyrightHubClientID) { settings.append('ARDITO enabled '); } if (val.Batcher != null && parseInt(val.Batcher) === 1) { if (val.Mailing != null && parseInt(val.Mailing) === 1) { settings.append(' '); } settings.append(' '); } if (val.Decoder != null && parseInt(val.Decoder) === 1) { settings.append(' '); } if (val.FTPuploadUser != null && val.FTPuploadUser != '') { settings.append(' '); } if (parseInt(val.CustomDisclaimer) === 1) { settings.append(' '); } settings.append(' '); tr.append(settings); $('#accounts-tbody').append(tr); }); // modals $('tr.datarow td a.credentials').click(function () { var credentials = modaldata[$(this).data().account]; var html = $('
    '); html.append($('
    API User Name
    ' + credentials.loginname + '
    ')); html.append($('
    API Access Key
    ' + credentials.accesskey + '
    ')); $('#credentials .modal-body').html(html); if(credentials.ftppass != null) { var html = $('
    '); html.append($('
    Ftp Server
    ftp://upload.booxtream.com
    ')); html.append($('
    Ftp User Name
    ' + credentials.ftpuser + '
    ')); html.append($('
    Ftp Password
    ' + credentials.ftppass + '
    ')); $('#credentials .modal-body').append(html); } $('#credentials').modal(); }); }); // add tooltips $('tr.datarow [data-toggle~="tooltip"]').tooltip(); // add popovers $('tr.datarow [data-toggle~="popover"]').popover({ placement: 'top', html: true, trigger: 'hover' }); } this.resetSelectedYear = function () { $(document).ready(function() { var referrer = document.referrer; referrer = referrer.slice(-14); if (!['rkingcosts.php', 'oragecosts.php', 'ilingcosts.php'].includes(referrer)) { // reset stored selectedYear sessionStorage.removeItem('selectedYearAccounting'); $('#selectedYear').html(new Date().getFullYear()); } }); } this.initialize = function () { // initialize page var oPage = new Page(); this.displayCreditOrders(); this.showAccounts(); this.resetSelectedYear(); showCredits(); setYear(); // when the yearSelector dropdown is clicked on this page, reload display creditorders $('#yearSelector li').on('click', function(){ op.displayCreditOrders(); }); } this.initialize(); } function StoredFiles() { "use strict"; this.Accounts = []; this.accountname = null; this.batcheraccount = null; this.accountkey = null; this.pages = undefined; this.page = undefined; this.activesearch = false; this.sURL = undefined; this.CopyrightHubClientID = undefined; this.MetadataModalID = undefined; this._ignoreHashChange = false; this.limit = localStorage.getItem("limit"); this.files = null; this.keysandfiles = []; if (this.limit == null) { this.limit = 100; } this.processingEpubs = 0; this.maxProcessingEpubs = 10; this.firstValidationTimeout = 5000; this.validationTimeout = 2000; var op = this; this.displayStoredFiles = function(storedFiles, total, size) { // convert size in bytes into megabytes, or (if the total size is equal to or more than 1 GB) into gigabytes var totalsize = (parseInt(size) / (1024 * 1024)).toFixed(2); if (totalsize >= 1024) { totalsize = (parseInt(totalsize) / 1024).toFixed(2) + ' GB'; } else { totalsize = totalsize + ' MB'; } this.pages = Math.ceil(total / this.limit); // show total stored files if (total === '1') { $('.storedfiles-total').text('1 file, ' + totalsize); } else { $('.storedfiles-total').text(total + ' files, ' + totalsize); } // create table var op = this; $.each(storedFiles, function (i, val) { // format data var filename = getCellHTML('Filename', val.FileName, 80, true); var datetime = ''; var title = getCellHTML('Title', op.setTitle(val), 40, false); var filesize = (parseInt(val.FileSize) / (1024 * 1024)).toFixed(2) + ' MB'; // validation data and icons var valid = $(''); if (val.StoredFileKey) { var messages = JSON.parse(val.EpubcheckMessages); op.checkValidationStatus(valid, val.EpubcheckStatus, val.FileName, messages); } var validcell = $('').append(valid); // create row; give it a color when it has a StoredFileKey var row = $('').addClass('datarow').attr('id', 'id' + i); if (!val.StoredFileKey) { row.addClass('text-muted'); } var checkcell = $(''); var datetimecell = $('' + datetime + ''); var filesizecell = $('' + filesize + ''); var filenamecell = $('' + filename + ''); var isbncell = $('' + op.setISBN(val) + ''); var titlecell = $('' + title + ''); // give cells a tooltip when it has a StoredFileKey (avoid giving tooltips to the left checkbox and to the right 2 columns); make it clickabe if (val.StoredFileKey) { checkcell.attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', 'Click to edit/view metadata').addClass('clickable'); datetimecell.attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', 'Click to edit/view metadata').addClass('clickable').addClass('callMetadataModal'); filesizecell.attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', 'Click to edit/view metadata').addClass('clickable').addClass('callMetadataModal'); filenamecell.attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', 'Click to edit/view metadata').addClass('clickable').addClass('callMetadataModal'); isbncell.attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', 'Click to edit/view metadata').addClass('clickable').addClass('callMetadataModal'); titlecell.attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', 'Click to edit/view metadata').addClass('clickable').addClass('callMetadataModal'); } // or make it clickable for showing a png if ((val.FileName.substr(-4) == '.png')) { checkcell.addClass('clickable'); datetimecell.addClass('clickable').addClass('callPNGModal text-nowrap'); filesizecell.addClass('clickable').addClass('callPNGModal text-nowrap'); filenamecell.addClass('clickable').addClass('callPNGModal'); isbncell.addClass('clickable').addClass('callPNGModal'); titlecell.addClass('clickable').addClass('callPNGModal'); } // append data cells row.append(checkcell); row.append(datetimecell); row.append(filesizecell); row.append(validcell); row.append(filenamecell); row.append(isbncell); row.append(titlecell); var buttonsmetadata = $(''); var buttonsaction = $(''); // download button buttonsaction.append(''); // make search-link and manual mode available when there is a StoredFileKey if (val.StoredFileKey) { if (val.StoredFileKey.slice(-5) === '.epub') { if (val.EpubcheckStatus === null) { op.addValidateButton(validcell, val.FileName, validcell); } } row.data('modalData', val); if (val.Metadata != null) { var md = val.Metadata; // check for custom metadata var custommetadata = 0; $.each(md, function (key, value) { if (key !== 'DOI' && key !== 'HubKey' && key !== 'ISBN' && key !== 'Title') { custommetadata = 1; } }); // add button for custom metadata if (custommetadata == 1) { op.custommetadatabutton(buttonsmetadata); } // add button for hubkey (if this account has a CopyrightHubClientID) if (op.CopyrightHubClientID !== undefined && md.HubKey !== undefined && md.HubKey !== null && md.HubKey.length > 0) { op.arditobutton(buttonsmetadata); } // add button for doi if (op.setDOI(val).length > 0) { op.doibutton(buttonsmetadata); } } // show action icons buttonsaction.append(' '); buttonsaction.append(' Watermark this ebook'); if (op.batcheraccount) { buttonsaction.append(' Watermark in batch mode'); } } // otherwise, when png: show modal with png if (val.PreSignedUrl) { row.data('modalData', val); } // add button cells row.append($(buttonsmetadata)); row.append($(buttonsaction)); $(buttonsaction).find('*[data-toggle="tooltip"]').tooltip(); $('#storedfiles-tbody').append(row); return i < (op.limit - 1); }); // calculate pages from total and limit and then add pagination op.displayPagination(); // add functionality for downloadbutton $('a.downloadbutton').click(function(event) { event.preventDefault(); // try to get authentication from sessionstorage var authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if (authentication === null) { authentication = localStorage.getItem("authentication"); } // create form var form = $('
    '); form.append(''); form.append(''); form.append(''); $(this).after(form); // submit and remove form form.submit(); form.remove(); }); // add popovers $('tr.datarow [data-toggle~="popover"]').popover({ placement: 'top', html: true, trigger: 'hover' }); // color datarow and check checkbox when cell with checkbox is clicked $('td.checkCell').click(function() { var checkbox = $(this).find('input.checkBox'); var checked = checkbox.is(':checked'); if (checked) { checkbox.prop('checked', false); $(this).parent().removeClass('success'); } else { checkbox.prop('checked', true); $(this).parent().addClass('success'); } op.allowDeleteButton(); }); // color datarow when chechbox is checked $('input.checkBox').click(function() { var checked = $(this).is(':checked'); if (checked) { $(this).prop('checked', false); $(this).parent().parent().removeClass('success'); } else { $(this).prop('checked', true); $(this).parent().parent().addClass('success'); } op.allowDeleteButton(); }); // enable MetadataModal $('.callMetadataModal').click(function() { op.MetadataModalID = $(this).parent().attr('id'); op.showMetadataModal(); }); // enable PNGModal $('.callPNGModal').click(function() { var id = $(this).parent().attr('id'); var data = $('tr#' + id).data('modalData'); $('#showfilename').attr('value', data.FileName); $('#exlibrisimage').attr('src', data.PreSignedUrl); $('#showPNGModal').modal('show'); }); } // get general metadata (doi, hubkey, isbn, title) this.setDOI = function(data) { var doi = ''; if (data.Metadata !== null && data.Metadata !== undefined && data.Metadata.DOI !== null && data.Metadata.DOI.length > 0) { doi = data.Metadata.DOI; } return doi; } this.setISBN = function(data) { var isbn = ''; if (data.Metadata !== null && data.Metadata !== undefined && data.Metadata.ISBN !== null && data.Metadata.ISBN.length > 0) { isbn = data.Metadata.ISBN; } return isbn; } this.setTitle = function(data) { var title = ''; if (data.Metadata !== null && data.Metadata !== undefined && data.Metadata.Title !== null && data.Metadata.Title.length > 0) { title = data.Metadata.Title; } return title; } // add custom metadata input fields this.addCustomMetadataInputFields = function() { var op = this; var metadatapair = $('
    ').addClass('metadatapair'); var keyinput = $('').attr('type', 'text').addClass('form-control metadatakey').attr('placeholder', 'Key').attr('id', 'lastkey'); var valueinput = $('').attr('type', 'text').addClass('form-control metadatavalue').attr('placeholder', 'Value').attr('id', 'lastvalue'); metadatapair.append(keyinput).append(valueinput); $('#custommetadata').append(metadatapair); // if input fields are used, add new input fields $('#lastkey').on('change keyup paste', function() { if ($('#lastkey').val().length > 0) { $('#lastkey').removeAttr('id'); $('#lastvalue').removeAttr('id'); op.addCustomMetadataInputFields(); } }); $('#lastvalue').on('change keyup paste', function() { if ($('#lastvalue').val().length > 0) { $('#lastkey').removeAttr('id'); $('#lastvalue').removeAttr('id'); op.addCustomMetadataInputFields(); } }); } // make delete button clickable when files are checked this.allowDeleteButton = function() { var values = $('input:checkbox:checked.checkBox'); if (values.length > 0) { $('.callDeleteModal').prop('disabled', false); } else { $('.callDeleteModal').prop('disabled', true); } } this.showMetadataModal = function() { // get data object from row; make id global // var data = $('tr#' + id).data('modalData'); // op.MetadataModalID = id; var data = $('tr#' + op.MetadataModalID).data('modalData'); // only show HubKey when this account has CopyrightHub-rights if (op.CopyrightHubClientID !== undefined) { $('.hubkeycontainer').removeClass('hidden'); } $('#editfilename').val(data.FileName); if (data.Metadata != null) { $('#editisbn').val(op.setISBN(data)); $('#editdoi').val(op.setDOI(data)); $('#edithubkey').val(data.Metadata.HubKey); $('#edittitle').val(op.setTitle(data)); } $('#custommetadata').empty(); if (data.Metadata) { $.each(data.Metadata, function (key, value) { if (key !== 'DOI' && key !== 'HubKey' && key !== 'ISBN' && key !== 'Title') { var metadatapair = $('
    ').addClass('metadatapair'); var keyinput = $('').val(key); var valueinput = $('').val(value); metadatapair.append(keyinput).append(valueinput); $('#custommetadata').append(metadatapair); } }); } op.addCustomMetadataInputFields(); $('#editMetadataModal').modal('show'); } // create page this.getPage = function(pagenumber, search) { var op = this; startSpinner('#spinner'); this.page = parseInt(pagenumber); var offset = (this.page - 1) * this.limit; var storedfilestable = $('#tablecontainer table'); var storedfilestbody = $('#storedfiles-tbody'); $('#tablecontainer').append(''); var nofilesmessage = $('#nofilesmessage'); // show selected limit; the default number of rows $('select.limit option[value="' + op.limit + '"]').attr('selected', 'selected'); // build stored files url var url = baseurl + 'account/' + this.accountkey + '/' + storedfileslistmethod + '?offset=' + offset + '&limit=' + this.limit; if (typeof this.orderby != 'undefined' && typeof this.orderdir != 'undefined') { url = url + '&orderby=' + this.orderby + '&orderdir=' + this.orderdir; } else { // orderby: DateTime, FileSize, FileName, ISBN, Title; orderdir: asc, desc url = url + '&orderby=DateTime&orderdir=desc'; } if(typeof search !== "undefined") { url += '&search=' + search; this.activesearch = search; } else if (this.activesearch !== false) { url += '&search=' + this.activesearch; } // get and display stored files $.getJSONAuth(url, function (data) { if (typeof data.message !== "undefined") { // create page new; remove old data, remove "empty table"-message storedfilestbody.children('.datarow').remove(); nofilesmessage.hide(); op.batcheraccount = false; if (data.message.account.Batcher === 1) { op.batcheraccount = true; } if (data.message.total > 0) { storedfilestable.show(); op.displayStoredFiles(data.message.response, data.message.total, data.message.size); op.displayPagination(); } else { nofilesmessage.show(); storedfilestable.hide(); } if (typeof search !== 'undefined' && parseInt(data.message.total) === 0) { $('.storedfiles-total').text('0 files, 0 MB'); $('#searchmessage').html($('

    No results for "'+ search +'"!

    No results found. Please try again.

    ').hide()); $('#alert').slideDown('slow'); setTimeout(function () { $('#alert').slideUp('slow', function () { $(this).remove(); }); }, 5000); } $('#accountname').html(data.message.account.AccountName + (data.message.account.Demo === '1' ? ' (test account)' : ' (production account)')); } stopSpinner('#spinner'); }); } this.arditobutton = function(element) { var arditobutton = $(' ARDITO '); arditobutton.click(function() { op.MetadataModalID = $(this).closest('.datarow').attr('id'); op.showMetadataModal(); }); element.append(arditobutton); } this.doibutton = function(element) { var doibutton = $(' DOI'); doibutton.click(function() { op.MetadataModalID = $(this).closest('.datarow').attr('id'); op.showMetadataModal(); }); element.append(doibutton); } this.custommetadatabutton = function(element) { var custommetadatabutton = $(' Custom'); custommetadatabutton.click(function() { op.MetadataModalID = $(this).closest('.datarow').attr('id'); op.showMetadataModal(); }); element.append(custommetadatabutton); } this.addValidateButton = function(element, storedfile, validatecell) { var validatebutton = $(''); validatebutton.click(function(e) { if (op.processingEpubs < op.maxProcessingEpubs) { op.processingEpubs++; if (op.processingEpubs === op.maxProcessingEpubs) { op.hideEpubValidation(); } // replace validate data icon with spinner validatecell.empty(); var spinner = $('
    '); validatecell.append(spinner); spinner.show(); // execute validation var url = baseurl + 'account/' + op.accountkey + '/' + checkvalidationmethod + '?filename=' + storedfile; op.callValidationStatus(url, storedfile, $(this), validatecell, op.firstValidationTimeout); e.preventDefault(); return false; } }); element.append(validatebutton); } this.hideEpubValidation = function() { $('.validatebutton').attr('disabled', 'disabled'); } this.showEpubValidation = function() { $('.validatebutton').removeAttr('disabled'); } this.checkValidationStatus = function(valid, status, filename, messages) { valid.empty(); var validatedata = null; var version = 'version unknown'; var datacontent = ''; if(messages !== null) { datacontent = 'Validated with epubcheck ' + messages.version + '.'; if (Object.keys(messages).length > 1) { datacontent = datacontent + ' Click to view messages.'; } } if (status === null) { validatedata = $(''); } else if (status === 'valid') { validatedata = $(''); } else if (status === 'invalid') { validatedata = $(''); } else if (status === 'processing' || status === 'mastervalid') { validatedata = $('
    '); validatedata.show(); var url = baseurl + 'account/' + op.accountkey + '/' + checkvalidationmethod + '?filename=' + filename; op.callValidationStatus(url, filename, '', validatedata, op.firstValidationTimeout); } if(messages !== null && Object.keys(messages).length > 1) { validatedata.click(function (e) { var displayErrors = ''; $('#errorsfilename').attr('value', filename); displayErrors += JSON.stringify(messages, null, 3); $('#errorsepub').html(displayErrors); $('#copy').html('').removeClass('btn-success'); $('#showValidationErrors').modal('show'); e.preventDefault(); return false; }); } valid.append(validatedata).removeClass('narrow-spinner'); $('tr.datarow [data-toggle~="popover"]').popover({ placement: 'top', html: true, trigger: 'hover' }); } this.callValidationStatus = function(url, filename, button, validatecell, timeout) { $.getJSONAuth(url, function(data) { var status = data.message.response.status; var messages = data.message.response.messages; var validationtimeout = op.validationTimeout; // give all requests less time than the first one if (status === 'processing' || status === 'mastervalid') { setTimeout( function(){ op.callValidationStatus(url, filename, button, validatecell, validationtimeout); }, timeout); } else { if (button.length > 0) { button.remove(); op.processingEpubs--; if (op.processingEpubs < 10) { op.showEpubValidation(); } } op.checkValidationStatus(validatecell, status, filename, messages) } }); } // add downloadStoredFilesCSV url this.addDownloadStoredFilesCSVUrl = function() { // try to get authentication from sessionstorage, we need this for CSV proxy var authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if (authentication === null) { authentication = localStorage.getItem("authentication"); } var proxy = 'downloadStoredFilesCSV.php?authentication='+authentication+'&accountid='+op.accountkey+'&accountname='+op.accountname; $('#downloadStoredFilesList').attr('href', proxy); } // initialize buttons this.initButtons = function() { // clear previous errors $('.callUploadModal').click(function() { $('#uploaderror').remove(); }); // Button to select all files $('button#selectall').click(function () { var checkbox = $('#selectall').prop('checked'); var selectall = $('#selectall'); var input = $('input'); if (checkbox) { selectall.prop('checked', false); input.prop('checked', false); input.parent().parent().removeClass('success'); op.allowDeleteButton(); } else { selectall.prop('checked', true); input.prop('checked', true); input.parent().parent().addClass('success'); op.allowDeleteButton(); } }); // change limit $('select.limit').change(function() { op.limit = $(this).find('option:selected').text(); localStorage.setItem("limit", op.limit); op.page = 1; op.getPage(1); }); // sort table buttons $('button.sort').click(function() { var icon = $(this).find('.fa'); if($(this).data('orderstate') == 'neutral') { // reset other buttons $('button.sort .fa').removeClass('fa-sort-asc').removeClass('fa-sort-desc').addClass('fa-sort'); $('button.sort').each(function(i) { $(this).attr('data-original-title', $(this).data('asc-title')); $(this).data('orderstate', 'neutral'); }); // set this one to asc icon.removeClass('fa-sort').addClass('fa-sort-asc'); $(this).data('orderstate', 'asc'); op.orderdir = 'asc'; $(this).attr('data-original-title', $(this).data('desc-title')); } else if($(this).data('orderstate') == 'asc') { icon.removeClass('fa-sort-asc').addClass('fa-sort-desc'); $(this).data('orderstate', 'desc'); op.orderdir = 'desc'; $(this).attr('data-original-title', $(this).data('asc-title')); } else { icon.removeClass('fa-sort-desc').addClass('fa-sort-asc'); $(this).data('orderstate', 'asc'); op.orderdir = 'asc'; $(this).attr('data-original-title', $(this).data('desc-title')); } // set the global orderby op.orderby = $(this).data('orderby'); op.getPage(1); }); // clear all selected files, options, etc $('button.closeuploadmodal').click(function() { op.files = null; op.keysandfiles = []; }); $('.submitMetadataModal').click(function(e) { e.preventDefault(); var filename = $('#editfilename').val(); var metadata = { 'Filename' : filename, 'ISBN' : $('#editisbn').val(), 'DOI' : $('#editdoi').val(), 'Title' : $('#edittitle').val() } $('.metadatapair').each(function(i) { var key = $(this).find('.metadatakey').val(); var value = $(this).find('.metadatavalue').val(); // do not add when both don't have content if (key.length > 0 || value.length > 0) { metadata[key] = value; } }); // ajax it $.ajax({ beforeSend: function (xhr) { if(typeof authentication === "undefined") { // try to get it from sessionstorage var authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if(authentication === null) { authentication = localStorage.getItem("authentication"); // got it from localstorage, now add it to sessionstorage sessionStorage.setItem("authentication", authentication); } } if(authentication === null) { document.location = 'login.php'; } xhr.setRequestHeader("Authorization", "Basic " + authentication); }, xhrFields: { withCredentials: true }, crossDomain: true, type: 'POST', url: baseurl + 'account/' + op.accountkey + '/' + storedfilesaddmetadatamethod, processData: false, data: JSON.stringify(metadata), error: function (data) { var error = 'An error'; if(data.status === 401) { error = 'A login error'; } if(data.status === 500) { error = 'A server error'; } }, success: function (data) { var row = $('#' + op.MetadataModalID); // reset custom metadata row.children('td.metadatabuttons').children('.custommetadatabutton').remove(); var custommetadata = 0; // add updated data to original data array metadata = data.message.response; row.data('modalData').Metadata = metadata; // add updated metadata $.each(data.message.response, function (key, value) { if (key === 'ISBN') { row.find('td.isbn').html(value); } else if (key === 'Title') { row.find('td.title').html(value); } else if (key === 'HubKey' && op.CopyrightHubClientID !== undefined) { row.children('td.metadatabuttons').children('.arditobutton').remove(); if (value.length > 0) { op.arditobutton(row.children('td.metadatabuttons')) } } else if (key === 'DOI') { row.children('td.metadatabuttons').children('.doibutton').remove(); if (value.length > 0) { op.doibutton(row.children('td.metadatabuttons')) } } else { custommetadata = 1; } }); if (custommetadata == 1) { op.custommetadatabutton(row.children('td.metadatabuttons')); } // close modal $('#lastkey').remove(); $('#lastvalue').remove(); $('#editMetadataModal').modal('toggle'); } }); // Prevent default click. return false; }); $('.resetMetadataModal').click(function() { $('#editisbn').removeAttr('value'); $('#editdoi').removeAttr('value'); $('#edittitle').removeAttr('value'); $('#custommetadata').empty(); }); } // functionality for the search bar this.initSearch = function (search) { var op = this; $('#resetbutton').click(function() { $('#resetbutton').addClass('hidden'); op.activesearch = false; op.sURL.parameters.search = undefined; op.sURL.parameters.page = 1; // create url for pushState var url = getURL(op.sURL); history.pushState(null,null,url); op.getPage(1); }); $('#searchinput').keyup(function(){ if($(this).val().length > 0) { $('#resetbutton').removeClass('hidden'); } else { $('#resetbutton').addClass('hidden'); } }); $('#search').on('submit', function () { if($('#searchinput').val().length > 0) { $('#resetbutton').removeClass('hidden'); } else { $('#resetbutton').addClass('hidden'); } var search = $(this).children('.input-group').children('input[name="search"]').val(); op.getPage(1,search); op.sURL.parameters.search = search; op.sURL.parameters.page = 1; // create url for pushState var url = getURL(op.sURL); history.pushState(null,null,url); return false; }); } // functionality for upload modal this.handleUploads = function() { // call modal for uploading var progress = $('#progress'); var filechooser = $('#fileChooser'); var uploadbutton = $('#upload'); var filelist = $('#uploadfilelist'); var uploadform = $('#uploadData'); var op = this; $('button.callUploadModal').click(function () { $('#uploadFiles').modal(); // reset form uploadform.get()[0].reset(); uploadbutton.prop('disabled', true); filechooser.prop('disabled', false); // empty and hide stuff filelist.empty(); progress.empty().addClass('hidden'); }); // choose files for upload filechooser.change(function() { var files = $(this).get(0).files; if (typeof files !== "undefined" && files.length > 0) { for (var i = 0, l = files.length; i < l; i++) { var generatedKey = Math.random().toString(36).substring(7); op.keysandfiles.push({ 'key' : generatedKey, 'file' : files[i] }); filelist.append('
  • ' + files[i].name + '
  • '); } if(i === 1) { // just one file, hide filelist filelist.hide(); } } // secure invisibility of the uploadbutton when there are no files if (files.length > 0) { uploadbutton.prop('disabled', false); } else { uploadbutton.prop('disabled', true); } }); // upload the files uploadform.submit(function() { // take the files var files = filechooser.get(0).files; // we don't want the same files uploaded twice uploadbutton.prop('disabled', true); filechooser.prop('disabled', true); // create progress bar var progressbar = $('
    '); var bar = $('').attr('id', 'percentage').html('0%'); progressbar.append(bar); progress.append(progressbar); // make bar active (animation) and visible progress.addClass('active'); progress.removeClass('hidden'); // create formdata-object var data = new FormData(); files = op.keysandfiles; $.each(files, function(key, value) { data.append('files[' + value.key + ']', value.file); }); // ajax it $.ajax({ beforeSend: function (xhr) { if(typeof authentication === "undefined") { // try to get it from sessionstorage var authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if(authentication === null) { authentication = localStorage.getItem("authentication"); // got it from localstorage, now add it to sessionstorage sessionStorage.setItem("authentication", authentication); } } if(authentication === null) { document.location = 'login.php'; } xhr.setRequestHeader("Authorization", "Basic " + authentication); }, xhrFields: { withCredentials: true }, crossDomain: true, xhr: function() { var xhr = $.ajaxSettings.xhr(); //Upload progress xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = Math.ceil((evt.loaded / evt.total)* 100); bar.html(percentComplete + '%'); progressbar.attr('aria-valuenow', percentComplete); progressbar.width(percentComplete + '%'); } }, false); return xhr; }, type: 'POST', url: baseurl + 'account/' + op.accountkey + '/' + storedfilesaddmethod, contentType: false, processData: false, data: data, error: function (data) { var error = 'An error'; if(data.status === 401) { error = 'A login error'; } if(data.status === 500) { error = 'A server error'; } $('#uploadmessage').html('
    ' + error + localizedStrings[locale].uploadError + '
    '); progress.removeClass('active'); progressbar.addClass('progress-bar-danger'); }, success: function (data){ // hide upload-form // $('#') filelist.show(); $.each(data.message.response, function (i, val) { if(val.Upload === 'Success') { filelist.find('li[data-file="' + val.Key + '"]').replaceWith('
  • ' + val.FileName + localizedStrings[locale].uploadSuccess + '
  • '); } else if (val.Upload === 'Failed' && val.Error === 'File exists') { filelist.find('li[data-file="' + val.Key + '"]').replaceWith('
  • ' + val.FileName + localizedStrings[locale].uploadExists + '
  • '); } else { filelist.find('li[data-file="' + val.Key + '"]').replaceWith('
  • ' + val.FileName + '
    ' + localizedStrings[locale].uploadError + '
  • '); } }); progress.removeClass('active'); progressbar.addClass('progress-bar-success'); // refresh page with uploaded files above $('button.sort[data-orderby="DateTime"]').data('orderstate', 'asc').trigger('click') // reset arrays for uploading files op.files = null; op.keysandfiles = []; } }); // Prevent default click. return false; }); } // functionality for delete modal this.handleDeletes = function() { var message = $('#deletemessage'); var confirmButton = $('button#delete4sure'); // var modalBody = $('#deleteModal .modal-body'); var filelist = $('#deletefilelist'); // activate modal $('button.callDeleteModal').click(function () { message.empty(); filelist.empty(); // read checked files var selectedFiles = $('input.checkBox:checked').map(function () { return this.id; }).get(); if (selectedFiles.length == 0) { // users should not be able to see this modal whitout any file selected, but if they do, they can't proceed message.append('No files selected'); confirmButton.addClass('hidden'); } else { // set message if (selectedFiles.length == 1) { message.append('
    Are you sure you want to delete the following file?
    '); } else { message.append('
    Are you sure you want to delete the following files?
    '); } // create list checked files $.each(selectedFiles, function(key, val) { filelist.append('
  • ' + val + '
  • '); }); // show confirm button confirmButton.prop('disabled', false); confirmButton.removeClass('hidden'); } // show modal $('#deleteModal').modal(); // Prevent default click. return false; }); // when confirm is given, pass filelist on and refresh the page confirmButton.click(function () { // we don't want the same files to be deleted again confirmButton.addClass('hidden'); message.html('One moment please...'); startSpinner('#deletespinner'); // read checked files var selectedFiles = $('input.checkBox:checked').map(function () { return this.id; }).get(); // create, fill array var files = ''; var i = 0; $.each(selectedFiles, function(key, value) { i += 1; if (i < selectedFiles.length) { files += 'files[]=' + value + '&'; } else { files += 'files[]=' + value; } }); // build url, retrieve data var url = baseurl + 'account/' + op.accountkey + '/' + storedfilesdeletemethod + '?' + files; $.getJSONAuth(url, function(data) { // create list with results $.each(data.message.response, function (i, val) { var hash = simplehasher(val.FileName); if (val.Delete === 'Success') { filelist.find('li[data-file="' + hash + '"]').replaceWith('
  • ' + val.FileName + localizedStrings[locale].deleteSuccess + '
  • '); } else { filelist.find('li[data-file="' + hash + '"]').replaceWith('
  • ' + val.FileName + localizedStrings[locale].deleteError + val.Error + '
  • '); } }); stopSpinner('#deletespinner'); message.empty(); // refresh page op.getPage(1); }); // Prevent default click. return false; }); // / add url to Export file list button op.addDownloadStoredFilesCSVUrl(); } this.initPagination = initPagination; this.displayPagination = displayPagination; // initialize the page this.initialize = function () { // initialize header var oPage = new Page(); // get key first this.sURL = urlObject(); var accountname = this.sURL.parameters.account; if(typeof accountname === "undefined") { window.location = 'index.php'; } this.accountname = accountname; // fetch http statuscode after failed download var error = this.sURL.parameters.error; if (typeof error != 'undefined') { var message = 'Unable to download stored file; '; // create a more meaningful message switch(error) { case 1: message += 'credentials error' case 401: case 403: message += 'unauthorized request'; break; case 404: message += 'stored file not found'; break; case 408: message += 'time out'; break; case 500: message += 'server error'; break; case 600: message += 'cURL error'; break; default: message += ''; break; } // add error number message += ' error #' + error; // alert message (equal to manualmode error message) alert(message); // remove error-query from url var url = this.sURL.pathname + '?account=' + this.sURL.parameters.account; history.pushState(null, null, url); } var op = this; $.getJSONCache(baseurl + accountsmethod, function (data) { var AccountNames = []; var validaccount = false; $.each(data.message.response, function (i,val) { if(val.LoginName === accountname) { validaccount = true; $('#accountname').html(val.AccountName + (val.Demo === '1' ? ' (test account)' : ' (production account)')); if (!val.FTPuploadUser) { window.location = 'index.php'; } // get CopyrightHubClientID if (val.CopyrightHubClientID) { op.CopyrightHubClientID = val.CopyrightHubClientID; } } AccountNames[val.LoginName] = val.AccountName; op.Accounts[val.LoginName] = val.AuthenticationKey; }); if (!validaccount) { window.location = 'index.php'; } op.accountkey = op.Accounts[accountname]; // see if url has search parameter var search = undefined; if(typeof op.sURL.parameters.search !== "undefined") { $('#resetbutton').removeClass('hidden'); $('#searchinput').val(op.sURL.parameters.search); search = op.sURL.parameters.search; } // get page op.page = 1; if(typeof op.sURL.parameters.page !== "undefined") { op.page = op.sURL.parameters.page; } op.getPage(op.page,search); }); // initialize the rest this.initButtons(); this.initSearch(); this.initPagination(); // handlers this.handleUploads(); this.handleDeletes(); // handle back-button $(window).bind("popstate", function change(e) { if(!this._ignoreHashChange) { // we need to reset the urlObject op.sURL = new urlObject(); var search = undefined; if(typeof op.sURL.parameters.search !== "undefined") { $('#resetbutton').removeClass('hidden'); $('#searchinput').val(op.sURL.parameters.search); search = op.sURL.parameters.search; } else { op.activesearch = false; if($('#searchinput').val() !== '') { $('#search').get(0).reset(); } } // get page op.page = 1; if(typeof op.sURL.parameters.page !== "undefined") { op.page = op.sURL.parameters.page; } op.getPage(op.page,search); } }); // add tooltips $('button[data-toggle="tooltip"]').tooltip(); } this.initialize(); } function ManualMode() { this.Accounts = []; this.accountname = null; this.accountkey = null; this.url = null; this.file = ''; this.handleForm = function() { var progress = $('#progress'); var op = this; // iterate and collect input values (except customeremailaddress and customername) $('form input').each(function() { var e = $(this)[0]; var op = $(this); if(e.name !== "customeremailaddress" && e.name !== "customername") { if(e.type === "file" || e.type === "checkbox") { $(this).change(function() { var parent = op.parent(); var errormessage = parent.find('.errormessage'); if(e.checkValidity()) { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); } else { parent.removeClass('has-success'); parent.addClass('has-error'); errormessage.show(); } }); } else if(e.type ==="number") { $(this).keyup(function(){ var parent = op.parent(); var errormessage = parent.find('.errormessage'); if(e.checkValidity() && parseInt(e.value) > 0) { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); } else { parent.removeClass('has-success'); parent.addClass('has-error'); errormessage.show(); } }); } else { $(this).keyup(function(){ var parent = op.parent(); var errormessage = parent.find('.errormessage'); if(e.checkValidity()) { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); } else { parent.removeClass('has-success'); parent.addClass('has-error'); errormessage.show(); } }); } } }); // get input from select list $('form select').each(function() { var e = $(this)[0]; $(this).change(function(){ var parent = $(this).parent(); var errormessage = parent.find('.errormessage'); // checkvalidity doesn't always fire correctly in safari if(e.value !== "") { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); } else { parent.removeClass('has-success'); parent.addClass('has-error'); errormessage.show(); } }); }); // Special cases; either customeremailaddress or customername should be given $('#customeremailaddress, #customername').keyup(function() { var e = $(this)[0]; var parent = $(this).parent(); var errormessage = $('#customererror'); if(e.name === 'customeremailaddress') { var otherel = $('#customername'); } else { var otherel = $('#customeremailaddress'); } if(e.value === '' && otherel.val() === '') { parent.toggleClass('has-success'); parent.addClass('has-error'); otherel.parent().removeClass('has-success'); otherel.parent().addClass('has-error'); errormessage.show(); } else { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); otherel.parent().removeClass('has-error'); otherel.parent().addClass('has-success'); } }); // Output: one or both can be given, but not none $('#epub, #kf8mobi').change(function() { var e = $(this)[0]; if(e.name === 'epub') { var otherel = $('#kf8mobi')[0]; } else { var otherel = $('#epub')[0]; } var outputerror = $('#outputerror'); var outputparent = $('#outputparent'); if(!e.checked && !otherel.checked) { outputerror.show(); outputparent.removeClass('has-success'); outputparent.addClass('has-error'); } else { outputerror.hide(); outputparent.addClass('has-success'); outputparent.removeClass('has-error'); } }); // submit handler $('button#submit').click(function (e) { e.preventDefault(); var data = new FormData();0 // check stored file, uploaded file for pdf if ($('#storedfile').length > 0) { var storedfile = $('#storedfile').text(); if (storedfile.slice(-4) === '.pdf') { op.url = booxtreampdfmethod; // for pdf, the used StoredFile is given with the payload data.append('filename', storedfile); } else { storedfile = storedfile.slice(0, -5); // for epub, the used StoredFile is referred to in the url op.url = booxtreambaseurl + 'storedfiles/' + storedfile + '.ajax'; } } else { if ($('#epubfile').val().slice(-4) === '.pdf') { op.url = booxtreampdfmethod; } else { op.url = booxtreammethod; } } // Validation comes first! var formvalues = new Array(); var checkedboxes = new Array(); var exlibrisfile = false; var errors = false; $('form input').each(function() { var e = $(this)[0]; var parent = $(this).parent(); var errormessage = parent.find('.errormessage'); if(e.checkValidity()) { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); if(e.type === "file") { if(typeof e.files[0] !== "undefined") { // append exlibrisfile only when this.file is set (to avoid not-.png's to be uploaded) if(e.name === "exlibrisfile") { if (op.file !== '') { exlibrisfile = true; data.append(e.name, e.files[0]); } } else { data.append(e.name, e.files[0]); } } } else if(e.type === "checkbox") { // checkedboxes[e.name] is used for evaluating errors in the form checkedboxes[e.name] = false; // e.value contains data for to BooXtream e.value = 0; if(e.checked) { checkedboxes[e.name] = true; e.value = 1; } data.append(e.name, e.value); } else if(e.type ==="number") { if(e.value !== "" && parseInt(e.value) > 0) { data.append(e.name, e.value); } } else { if(e.value !== "") { data.append(e.name, e.value); } } } else { parent.removeClass('has-success'); parent.addClass('has-error'); errormessage.show(); errors = true; } formvalues[e.name] = e.value; }); $('form select').each(function() { var e = $(this)[0]; var parent = $(this).parent(); var errormessage = parent.find('.errormessage'); if(e.checkValidity()) { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); if(e.value !== "") { // store storedexlibrisfile as exlibrisfile if(e.name === 'storedexlibrisfile') { // check if exlibrisfile is not already been set by file upload if (exlibrisfile) { // throw error errors = true; } else { data.append('exlibrisfile', e.value); } } else { data.append(e.name, e.value); } } } else { parent.removeClass('has-success'); parent.addClass('has-error'); errormessage.show(); errors = true; } formvalues[e.name] = e.value; }); // special cases if(formvalues['customeremailaddress'] === '' && formvalues['customername'] === '') { $('#customeremailaddress').parent().removeClass('has-success'); $('#customeremailaddress').parent().addClass('has-error'); $('#customername').parent().removeClass('has-success'); $('#customername').parent().addClass('has-error'); $('#customererror').show(); errors = true; } var outputerror = $('#outputerror'); var outputparent = $('#outputparent'); if( !checkedboxes.epub && !checkedboxes.kf8mobi && !($('#storedfile').length > 0 && $('#storedfile').text().slice(-4) === '.pdf') && !($('#epubfile').val().slice(-4) === '.pdf') ) { outputerror.show(); outputparent.removeClass('has-success'); outputparent.addClass('has-error'); errors = true; } else { outputerror.hide(); outputparent.addClass('has-success'); outputparent.removeClass('has-error'); } if(errors) { $('#formerror').show(); $('html, body').animate({scrollTop: $("#formerror").offset().top}, 2000); setTimeout(function () { $('#formerror').slideUp('slow'); }, 7000); return false; } // create progress bar var progressbar = $('
    '); var bar = $('').attr('id', 'percentage').html('0%'); progressbar.append(bar); progress.append(progressbar); // make bar active (animation) and visible progress.addClass('active'); progress.show(); // indicate dashboard as source of this request data.append('source', 'dashboard'); // ajax it $.ajax({ beforeSend: function (xhr) { authentication = B64.encode(op.accountname+':'+op.accountkey); xhr.setRequestHeader("Authorization", "Basic " + authentication); }, xhrFields: { withCredentials: true }, crossDomain: true, xhr: function() { var xhr = $.ajaxSettings.xhr(); //Upload progress xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = Math.ceil((evt.loaded / evt.total)* 100); if(percentComplete === 100) { progressbar.addClass('progress-bar-success'); bar.html('File uploaded. Processing...'); $('#booxtreamspinner').show(); } else { bar.html('Uploading: ' + percentComplete + '%'); } progressbar.attr('aria-valuenow', percentComplete); progressbar.width(percentComplete + '%'); } }, false); return xhr; }, headers: { 'Accept': 'application/xml' }, type: 'POST', url: op.url, contentType: false, processData: false, dataType: 'xml', data: data, error: function (data) { bar.html('Error'); progress.removeClass('active'); progressbar.addClass('progress-bar-danger'); stopSpinner('#booxtreamspinner'); if (data.status === 402) { alert('BooXtream watermarking API temporarily disabled.'); } else { alert('Sorry, an error occured, please check transactions'); } }, success: function (data){ // hide upload-form progress.removeClass('active'); progressbar.addClass('progress-bar-success'); stopSpinner('#booxtreamspinner'); bar.html('Transaction completed'); $('#manualmode').slideUp('slow'); $(data).find('DownloadLink').each(function(key,value){ $('#downloadlinks ul').append('
  • '+ $(value).text() +'
  • '); }); $('#downloadlinks').show(); } }); return false; }); } // Changes XML to JSON this.xmlToJson = function(xml) { // Create the return object var obj = {}; if (xml.nodeType == 1) { // element // do attributes if (xml.attributes.length > 0) { obj["@attributes"] = {}; for (var j = 0; j < xml.attributes.length; j++) { var attribute = xml.attributes.item(j); obj["@attributes"][attribute.nodeName] = attribute.nodeValue; } } } else if (xml.nodeType == 3) { // text obj = xml.nodeValue; } // do children if (xml.hasChildNodes()) { for(var i = 0; i < xml.childNodes.length; i++) { var item = xml.childNodes.item(i); var nodeName = item.nodeName; if (typeof(obj[nodeName]) == "undefined") { obj[nodeName] = this.xmlToJson(item); } else { if (typeof(obj[nodeName].push) == "undefined") { var old = obj[nodeName]; obj[nodeName] = []; obj[nodeName].push(old); } obj[nodeName].push(this.xmlToJson(item)); } } } return obj; } // functionality for exlibris upload modal this.handleExlibris = function() { var exlibrisfile = $('#exlibrisfile'); var uploadbutton = $('#upload'); var file = ''; var op = this; // choose file for upload $('#exlibrisfile').change(function(e) { file = $(this).get(0).files; // secure invisibility of the uploadbutton when there is no file, or when file has not a .png-extension if (file.length > 0) { filename = file[0].name; if (filename.substr(filename.length - 4) === '.png') { uploadbutton.prop('disabled', false); } else { uploadbutton.prop('disabled', true); } } }); // set uploaded file, check exlibris-checkbox $('button#upload').click(function() { $('#callUploadModal').html(file[0].name); $('#exlibris').prop('checked', true); $('select#storedfilesexlibris').prop('disabled', true); op.file = file; }); // make exlibris-checkbox checked when stored exlibris file is selected $('select#storedfilesexlibris').change(function() { if ( $(this)[0].selectedIndex === 0 ) { $('#exlibris').prop('checked', false); $('#callUploadModal').prop('disabled', false); } else { $('#exlibris').prop('checked', true); $('#callUploadModal').prop('disabled', true); } }); // reset both uploaded and stored exlibrisfile when exlibris-checkbox is unchecked $('#exlibris').change(function() { if (!$(this).is(':checked')) { // reset modal $('#uploadData').get()[0].reset(); $('#upload').prop('disabled', true); // remove (reference to) upload-file file = ''; op.file = ''; // reset button for modal $('#callUploadModal').html('Upload ExLibris'); $('#callUploadModal').prop('disabled', false); // reset dropdown $('select#storedfilesexlibris').prop('disabled', false); $('select#storedfilesexlibris').find('option:first').attr('selected', 'selected'); } }); } this.initialize = function () { this.oPage = new Page(); // get key first this.sURL = urlObject(); var accountname = this.sURL.parameters.account; if(typeof accountname === "undefined") { window.location = 'index.php'; } this.accountname = accountname; var op = this; $.getJSONCache(baseurl + accountsmethod, function (data) { var AccountNames = []; var validaccount = false; $.each(data.message.response, function (i,val) { if(val.LoginName === accountname) { validaccount = true; $('#accountname').html(val.AccountName + (val.Demo === '1' ? ' (test account)' : ' (production account)')); } AccountNames[val.LoginName] = val.AccountName; op.Accounts[val.LoginName] = val.AuthenticationKey; }); if (!validaccount) { window.location = 'index.php'; } op.accountkey = op.Accounts[accountname]; }); // load stored exlibris files var url = baseurl + 'account/' + this.accountkey + '/' + storedexlibrislistmethod; $.getJSONAuth(url, function (data) { if (data.message.response.length > 0) { // show dropdown list $('select#storedfilesexlibris').parent().removeClass('hidden'); $.each(data.message.response, function (i,val) { var option = ''; $('select#storedfilesexlibris').append(option); }); } }); this.handleForm(); this.handleExlibris(); // call shared function (used in manualmode and batchmode) defined in script.js handleSuppressExlibrisSpreadCheckbox(); // call shared function (used in manualmode and batchmode) for EPUB options display displayEpubOptions(); } this.initialize(); } function Batches() { this.Accounts = []; this.accountname = null; this.accountkey = null; this.url = null; this.Mailing = false; this.Spinner = false; this.buttons = function () { var op = this; $('#newbatch').click(function() { window.location = $(this).attr('href') + op.accountname; return false; }); $('#templates').click(function() { window.location = $(this).attr('href') + op.accountname; return false; }); } this.displayBatches = function (batches, total) { // show batches $('#batches-tbody').children('.datarow').remove(); var ranknr = total; // try to get authentication from sessionstorage, we need this for CSV proxy var authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if (authentication === null) { authentication = localStorage.getItem("authentication"); } var op = this; $.each(batches, function (i, val) { var status = ''; var batchinfo = ''; var filename = ''; var output = ''; var input = ''; var totalRecords = val.TotalRecords; var processedRecords = val.ProcessedRecords; if(val.Success) { if (processedRecords < totalRecords) { status += ' '; } else { status += ' '; } if(val.Mailing) { status += ''; batchinfo += 'Subject line: ' + val.Parameters.subjectline + '
    '; batchinfo += 'Sent from: ' + val.Parameters.sendfromname + ' <'+val.Parameters.sendfromemailaddress + '>'; } else { batchinfo += 'normal batch'; } } else { // the batch might still be running; in that case, val.DateTimeEnd equals null if(val.DateTimeEnd != null) { status += ''; } else { status += ''; batchinfo += 'busy processing, press F5 to refresh'; output += 'Batch busy'; } } // show date and time seperate from status (ok, error, busy) if(val.DateTimeEnd != null) { var dates = ''; } else { var dates = ''; } // give name of epubfile if(typeof val.Parameters.epubfilename !== "undefined") { filename += getCellHTML('Master EPUB File', val.Parameters.epubfilename, 30, false); } if(typeof val.CSVinput !== "undefined") { // parse parameters from url to send to proxy var CSVinput = urlObject({"url": val.CSVinput}); var uid = CSVinput.parameters.uid; var proxy = 'downloadCSV.php?authentication='+authentication+'&uid='+uid+'&account='+op.accountkey+'&type=in'; input = ' .csv'; } if(typeof val.CSVoutput !== "undefined") { // parse parameters from url to send to proxy var CSVoutput = urlObject({"url": val.CSVoutput}); var uid = CSVoutput.parameters.uid; var proxy = 'downloadCSV.php?authentication='+authentication+'&uid='+uid+'&account='+op.accountkey+'&type=out'; output = ' .csv'; } var tr = $('').addClass('datarow'); tr.append($('' + ranknr + '')); tr.append($('' + dates + '')); tr.append($('' + status +'')); tr.append($('' + totalRecords +'')); tr.append($('' + processedRecords +'')); tr.append($('' + batchinfo + '')); tr.append($('' + filename + '')); tr.append($('' + input + '')); tr.append($('' + output + '')); $('#batches-tbody').append(tr); // ranknr-- ranknr -= 1; }); // add tooltips $('tr.datarow [data-toggle~="tooltip"]').tooltip(); // add popovers $('tr.datarow [data-toggle~="popover"]').popover({ placement: 'top', html: true, trigger: 'hover' }); } this.getBatches = function() { startSpinner('#spinner'); // build batches url var url = baseurl + 'account/' + this.accountkey + '/' + batchesmethod; // get and display batches var op = this; $.getJSONAuth(url, function (data) { if(typeof data.message !== undefined) { var count = data.message.response.length; op.displayBatches(data.message.response, count); /* var batchlist = $('#batchlist'); $.each(data.message.response, function (i, val) { op.displayTransactions(data.message.response, count); var batch = $('
    Batch #'+count+'
    '); batch.find('.panel-body dl').append('
    Started
    '+val.DateTimeStart+'
    '); batch.find('.panel-body dl').append('
    Ended
    '+val.DateTimeEnd+'
    '); if(op.Mailing) { if(val.Mailing) { batch.find('.panel-body dl').append('
    Type
    Mailing
    '); } else { batch.find('.panel-body dl').append('
    Type
    Downloadable CSV
    '); } } batchlist.append(batch); count--; }); */ $('#accountname').html(data.message.account.AccountName + (data.message.account.Demo === '1' ? ' (test account)' : ' (production account)')); } stopSpinner('#spinner'); }); } this.initialize = function () { this.oPage = new Page(); this.buttons(); // get key first this.sURL = urlObject(); var accountname = this.sURL.parameters.account; if(typeof accountname === "undefined") { window.location = 'index.php'; } this.accountname = accountname; $('#accountname').html(this.accountname); var op = this; $.getJSONCache(baseurl + accountsmethod, function (data) { var AccountNames = []; var validaccount = false; $.each(data.message.response, function (i,val) { if(val.LoginName === accountname) { validaccount = true; $('#accountname').html(val.AccountName + (val.Demo === '1' ? ' (test account)' : ' (production account)')); // redirect to home page when account does not have permission to view this page // @todo: integer output instead of string if (val.Batcher !== '1') { window.location = 'index.php'; } if (val.Mailing === 1) { op.Mailing = true; $('#templates').removeClass('hidden'); } } AccountNames[val.LoginName] = val.AccountName; op.Accounts[val.LoginName] = val.AuthenticationKey; }); if (!validaccount) { window.location = 'index.php'; } op.accountkey = op.Accounts[accountname]; // account loaded, load batches op.getBatches(); }); } this.initialize(); } function BatchMode() { this.batchfile = ''; this.Accounts = []; this.accountname = null; this.accountkey = null; this.url = null; this.mailformelements = null; this.Mailing = false; this.sendMailing = false; this.exlibrisfile = false; var op = this; this.buttons = function () { /*xs $('#targetMail').click(function() { $('#template').removeAttr('disabled'); $('#sendTestEmail').removeAttr('disabled'); }); $('#targetBatchfile').click(function() { $('#template').prop('disabled', true); $('#sendTestEmail').prop('disabled', true); }); $('#sendTestEmail').click(function() { $('#testEmailModal').modal('show'); }); */ var op = this; $('#batches').click(function() { window.location = $(this).attr('href') + op.accountname; return false; }); $('.templates').click(function() { window.location = $(this).attr('href') + op.accountname; return false; }); $('#batchhelp').click(function() { var op = this; $.ajax({ type: 'GET', url: 'help.php?page=batchspecs', contentType: false, processData: false, dataType: 'json', error: function (data) { $('#modal-title').html('Error'); $('#modal-body').html('Something went wrong; please try again.'); $('#batchspecs').modal(); }, success: function (data){ $('#modal-title').html(data.title); $('#modal-body').html(data.body); $('#batchspecs').modal(); } }); return false; }); $('#template').change(function () { var from_name = $(this).find(':selected').data('from_name') var from_email = $(this).find(':selected').data('from_email') var subject = $(this).find(':selected').data('subject') $('#sendfromname').val(from_name); $('#sendfromemailaddress').val(from_email); $('#subjectline').val(subject); }); } this.handleForm = function() { var progress = $('#progress'); var op = this; if(this.Mailing) { // get the templates var template = $('#template'); var url = baseurl + 'account/' + this.accountkey + '/' + emailtemplatesmethod; $.getJSONAuth(url, function (data) { var Templates = [] $.each(data.message.response, function (i,val) { Templates.push($('')); }); template.append(Templates).prop( "disabled", false); }); // detach fields as a default this.mailformelements = $('#emailfields').detach(); $('#emailfieldscontainer hr').hide(); // handle mode $('input[name=\'batchtype\']').change(function() { var e = $(this)[0]; if(e.id === 'typecsv') { // disable mailform-elements op.sendMailing = false; $('#emailfields').detach(); $('#emailfieldscontainer hr').hide(); } else { // re-enable form-elements op.sendMailing = true; $('#emailfieldscontainer').append(op.mailformelements); $('#emailfieldscontainer hr').show(); } }); } else { $('#batchtype, #emailfieldscontainer').remove(); } // iterate and collect input values $('form input').each(function() { var e = $(this)[0]; var op = $(this); if(e.type === "file" || e.type === "checkbox") { $(this).change(function() { var parent = op.parent(); var errormessage = parent.find('.errormessage'); if(e.checkValidity()) { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); } else { parent.removeClass('has-success'); parent.addClass('has-error'); errormessage.show(); } }); } else if(e.type === "number") { $(this).keyup(function(){ var parent = op.parent(); var errormessage = parent.find('.errormessage'); if(e.checkValidity() && parseInt(e.value) > 0) { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); } else { parent.removeClass('has-success'); parent.addClass('has-error'); errormessage.show(); } }); } else { $(this).keyup(function(){ var parent = op.parent(); var errormessage = parent.find('.errormessage'); if(e.checkValidity()) { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); } else { parent.removeClass('has-success'); parent.addClass('has-error'); errormessage.show(); } }); } }); // get input from select list $('form select').each(function() { var e = $(this)[0]; $(this).change(function(){ var parent = $(this).parent(); var errormessage = parent.find('.errormessage'); // checkvalidity doesn't always fire correctly in safari if(e.value !== "") { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); } else { parent.removeClass('has-success'); parent.addClass('has-error'); errormessage.show(); } }); }); // Output: one or both can be given, but not none $('#epub, #kf8mobi').change(function() { var e = $(this)[0]; if(e.name === 'epub') { var otherel = $('#kf8mobi')[0]; } else { var otherel = $('#epub')[0]; } var outputerror = $('#outputerror'); var outputparent = $('#outputparent'); if(!e.checked && !otherel.checked) { outputerror.show(); outputparent.removeClass('has-success'); outputparent.addClass('has-error'); } else { outputerror.hide(); outputparent.addClass('has-success'); outputparent.removeClass('has-error'); } }); // submit handler $('button#submit').click(function (e) { e.preventDefault(); $('#submit').prop('disabled', true); if(op.sendMailing) { op.url = booxtreambatcherbaseurl + 'mailbatch.ajax'; } else { op.url = booxtreambatcherbaseurl + 'csvbatch.ajax'; } // Validation comes first! var data = new FormData(); var formvalues = new Array(); var checkedboxes = new Array(); var errors = false; // check stored files if ($('#storedfile').text().length > 0) { var storedfile = $('#storedfile').text(); if (storedfile.slice(-5) === '.epub') { // legacy: chop extension off storedfile = storedfile.slice(0, -5); } data.append('storedfile', storedfile); } if(op.batchfile === '') { $('#batchfilegroup').removeClass('has-success'); $('#batchfilegroup').addClass('has-error'); $('#batchfilegroup .errormessage').show(); } $('form input').each(function() { var e = $(this)[0]; var parent = $(this).parent(); var errormessage = parent.find('.errormessage'); if(e.checkValidity()) { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); if(e.type === "file") { if(typeof e.files[0] !== "undefined") { // append exlibrisfile only when this.file is set (to avoid not-.png's to be uploaded) if(e.name === "exlibrisfile") { if (op.file !== '') { op.exlibrisfile = true; data.append(e.name, e.files[0]); } } else if (e.name === 'batchfile') { if (op.batchfile !== '') { op.batchfileset = true; data.append(e.name, e.files[0]); data.append('batchfiledelimiter', op.batchfiledelimiter); } else { errors = true; } } else { data.append(e.name, e.files[0]); } } } else if(e.type === "checkbox") { checkedboxes[e.name] = false; if(e.checked) { checkedboxes[e.name] = true; data.append(e.name, e.value); } } else if(e.type === "number") { if(e.value !== "" && parseInt(e.value) > 0) { data.append(e.name, e.value); } } else { if(e.value !== "") { data.append(e.name, e.value); } } } else { parent.removeClass('has-success'); parent.addClass('has-error'); errormessage.show(); errors = true; } formvalues[e.name] = e.value; }); $('form select').each(function() { var e = $(this)[0]; var parent = $(this).parent(); var errormessage = parent.find('.errormessage'); if(e.checkValidity()) { errormessage.hide(); parent.removeClass('has-error'); parent.addClass('has-success'); if(e.value !== "") { // store storedexlibrisfile as exlibrisfile if(e.name === 'storedexlibrisfile') { // check if exlibrisfile is not already been set by file upload if (op.exlibrisfile) { // throw error errors = true; } else { data.append('exlibrisfile', e.value); } } else { data.append(e.name, e.value); } } } else { parent.removeClass('has-success'); parent.addClass('has-error'); errormessage.show(); errors = true; } formvalues[e.name] = e.value; }); var outputerror = $('#outputerror'); var outputparent = $('#outputparent'); if( !checkedboxes.epub && !checkedboxes.kf8mobi && !($('#storedfile').length > 0 && $('#storedfile').text().slice(-4) === '.pdf') && !($('#epubfile').val().slice(-4) === '.pdf') ) { outputerror.show(); outputparent.removeClass('has-success'); outputparent.addClass('has-error'); errors = true; } else { outputerror.hide(); outputparent.addClass('has-success'); outputparent.removeClass('has-error'); } if(errors) { $('#submit').prop('disabled', false); $('#formerror').show(); $('html, body').animate({scrollTop: $("#formerror").offset().top}, 200); setTimeout(function () { $('#formerror').slideUp('slow'); }, 7000); return false; } // create progress bar var progressbar = $('
    '); var bar = $('').attr('id', 'percentage').html('0%'); progressbar.append(bar); progress.append(progressbar); // make bar active (animation) and visible progress.addClass('active'); progress.show(); // no errors, append accountstuff - werkt als niet cross-domain // data.append('loginname', op.accountname); // data.append('password', op.accountkey); // ajax it $.ajax({ beforeSend: function (xhr) { authentication = B64.encode(op.accountname+':'+op.accountkey); xhr.setRequestHeader("Authorization", "Basic " + authentication); }, xhrFields: { withCredentials: true }, crossDomain: true, xhr: function() { var xhr = $.ajaxSettings.xhr(); //Upload progress xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = Math.ceil((evt.loaded / evt.total)* 100); if(percentComplete === 100) { progressbar.addClass('progress-bar-success'); bar.html('File uploaded. Processing...'); $('#booxtreamspinner').show(); } else { bar.html('Uploading: ' + percentComplete + '%'); } progressbar.attr('aria-valuenow', percentComplete); progressbar.width(percentComplete + '%'); if(percentComplete === 100) { // hide upload-form progress.removeClass('active'); progressbar.addClass('progress-bar-success'); stopSpinner('#booxtreamspinner'); $('#message').append('

    Your upload was successful and your batch is processing, it is not required to keep this page opened. Click here to view status.

    '); $('#batchform').slideUp('slow'); $('#messagebox').show(); } } }, false); return xhr; }, type: 'POST', url: op.url, contentType: false, processData: false, dataType: 'json', data: data, error: function (data) { bar.html('Error'); progress.removeClass('active'); progressbar.addClass('progress-bar-danger'); stopSpinner('#spinner'); if (data.status === 402) { var errorMessage = 'BooXtream watermarking API temporarily disabled.'; } else { var errorMessage = 'Error: ' + data.responseText; } $('#message').append('

    ' + errorMessage + '

    Please contact BooXtream

    '); $('#messageTitle').replaceWith('Error'); $('#submit').prop('disabled', false); }, success: function (data){ if (data.success == 1) { $('#messagebox').addClass('panel-success'); $('#messageTitle').replaceWith('Completed'); } else { $('#messagebox').addClass('panel-danger'); } if (data.error !== undefined) { $('#message .text-info').remove(); $('#message').append('

    Error: ' + data.error + '

    Please contact BooXtream

    '); $('#messageTitle').replaceWith('Error'); } if (data.processedRecords > 0) { // split MySQL datetime strings and construct Javascript Date objects var start = data.datetimeStart.split(/[- :]/); var dateStart = new Date(start[0], start[1]-1, start[2], start[3], start[4], start[5]); var end = data.datetimeEnd.split(/[- :]/); var dateEnd = new Date(end[0], end[1]-1, end[2], end[3], end[4], end[5]); // calculate time var time = Math.round((dateEnd.getTime() - dateStart.getTime()) / 1000); $('#message').append('

    ' + data.processedRecords + ' of ' + data.totalRecords + ' records processed in ' + time + ' seconds.

    '); // try to get authentication from sessionstorage, we need this for CSV proxy var authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if (authentication === null) { authentication = localStorage.getItem("authentication"); } } } }); return false; }); } // functionality for exlibris upload modal this.handleBatchfile = function() { Papa.DefaultDelimiter = ';'; var batchfile = $('#batchfile'); var confirmbutton = $('#batchfileconfirmbutton'); var batchfile = ''; var delimiter = ''; var op = this; var confirm = $('#batchfileconfirm'); confirm.hide(); // choose file for upload $('#batchfile').change(function(e) { $('#batchfilepreview').hide(); $('#batchfilepreviewtable').empty(); // empty and hide error table $('#batchfileerrors table tbody').empty(); $('#batchfileerrors').hide(); $('#batchfileconfirmbutton').prop('disabled', true); $('#batchfileconfirm').hide(); filelist = $(this).get(0).files; // secure invisibility of the uploadbutton when there is no file, or when file has not a .png-extension if (filelist.length === 1) { $('#uploadbatchfile').prop('disabled', false); } else { $('#uploadbatchfile').prop('disabled', true); } }); // set uploaded file $('button#uploadbatchfile').click(function(e) { e.preventDefault(); batchfile = $('#batchfile').get(0).files[0]; var firstRow = true; var row = 0; var table = $('#batchfilepreviewtable'); var errors = $('#batchfileerrors table tbody'); var errorsfound = false; $('#batchfilepreview').show(); table.empty(); errors.empty(); confirmbutton.prop('disabled', false); $('#batchfile').parse({ config: { step: function (results, parser) { error = ''; delimiter = results.meta.delimiter; if (firstRow) { // check the first row header = results.data[0]; if (!(header.length === 3 && header[0] == 'customername' && header[1] == 'customeremailaddress' && header[2].trim() == 'referenceid')) { error = 'Header is incorrect'; if(header.length !== 3) { error += ', length should be 3 but is ' + header.length + '.'; } else { error += ', it did not match the requirements.' } } } else { // check length of row if (results.data[0].length != 3) { error = 'Incorrect row length: ' + results.data[0].length; } } if (row < 11) { tablerow = $(''); if (firstRow) { tablerow.addClass('headerrow'); tablerow.append(''); } else { tablerow.append('' + row.toString() + ''); } $.each(results.data[0], function (i, data) { tablerow.append('' + data.toString() + ''); }); } table.append(tablerow); if (error != '') { errorsfound = true; errors.append('' + row.toString() + '' + error + ''); } if (results.errors.length > 0) { $.each(results.errors, function (i, data) { errorsfound = true; errors.append('' + row.toString() + '' + data.message + ''); }); } firstRow = false; row++; }, skipEmptyLines: true, delimiter: "", header: false // do not parse the header, we use our own custom function }, complete: function() { var rows = row - 1; $('span.batchfilerows').html(rows); // if errors/warnings hide and disable buttons and show errors: if(errorsfound) { confirm.hide(); confirmbutton.prop('disabled', true); confirmbutton.addClass('btn-default'); confirmbutton.removeClass('btn-success'); $('#batchfileerrors').show(); } else { $('#batchfileerrors').hide(); confirmbutton.prop('disabled', false); confirmbutton.addClass('btn-success'); confirmbutton.removeClass('btn-default'); confirm.show(); } } }); return false; }); $('#batchfileconfirmbutton').click(function() { $('#callUploadCSVModal').html(batchfile.name); op.batchfile = batchfile; op.batchfiledelimiter = delimiter; $('#batchfilegroup').removeClass('has-error'); $('#batchfilegroup').addClass('has-success'); $('#batchfilegroup .errormessage').hide(); }); /* reset modal */ $('#batchfilecancelbutton').click(function() { $('#batchfileform').trigger("reset"); $('#batchfile').trigger("change"); }); } // functionality for exlibris upload modal this.handleExlibris = function() { var exlibrisfile = $('#exlibrisfile'); var uploadbutton = $('#exlibrisupload'); var file = ''; var op = this; // choose file for upload $('#exlibrisfile').change(function(e) { file = $(this).get(0).files; // secure invisibility of the uploadbutton when there is no file, or when file has not a .png-extension if (file.length > 0) { filename = file[0].name; if (filename.substr(filename.length - 4) === '.png') { uploadbutton.prop('disabled', false); } else { uploadbutton.prop('disabled', true); } } }); // set uploaded file, check exlibris-checkbox $('button#exlibrisupload').click(function() { $('#callUploadExlibrisModal').html(file[0].name); $('#exlibris').prop('checked', true); $('select#storedfilesexlibris').prop('disabled', true); op.file = file; }); // make exlibris-checkbox checked when stored exlibris file is selected $('select#storedfilesexlibris').change(function() { if ( $(this)[0].selectedIndex === 0 ) { $('#exlibris').prop('checked', false); $('#callUploadExlibrisModal').prop('disabled', false); } else { $('#exlibris').prop('checked', true); $('#callUploadExlibrisModal').prop('disabled', true); } }); // reset both uploaded and stored exlibrisfile when exlibris-checkbox is unchecked $('#exlibris').change(function() { if (!$(this).is(':checked')) { // reset modal $('#uploadExlibrisData').get()[0].reset(); $('#exlibrisupload').prop('disabled', true); // remove (reference to) upload-file file = ''; op.file = ''; // reset button for modal $('#callUploadExlibrisModal').html('Upload ExLibris'); $('#callUploadExlibrisModal').prop('disabled', false); // reset dropdown $('select#storedfilesexlibris').prop('disabled', false); $('select#storedfilesexlibris').find('option:first').attr('selected', 'selected'); } }); } this.initialize = function () { this.oPage = new Page(); this.buttons(); // get key first this.sURL = urlObject(); var accountname = this.sURL.parameters.account; if(typeof accountname === "undefined") { window.location = 'index.php'; } this.accountname = accountname; $('#accountname').html(this.accountname); var op = this; $.getJSONCache(baseurl + accountsmethod, function (data) { var AccountNames = []; var validaccount = false; $.each(data.message.response, function (i,val) { if(val.LoginName === accountname) { validaccount = true; $('#accountname').html(val.AccountName + (val.Demo === '1' ? ' (test account)' : ' (production account)')); // redirect to home page when account does not have permission to view this page // @todo: integer output instead of string if (val.Batcher !== '1') { window.location = 'index.php'; } if (val.Mailing === 1) { op.Mailing = true; $('#templates').removeClass('hidden'); } } AccountNames[val.LoginName] = val.AccountName; op.Accounts[val.LoginName] = val.AuthenticationKey; }); if (!validaccount) { window.location = 'index.php'; } op.accountkey = op.Accounts[accountname]; // account loaded, initialize form op.handleForm(); }); // load stored exlibris files var url = baseurl + 'account/' + this.accountkey + '/' + storedexlibrislistmethod; $.getJSONAuth(url, function (data) { if (data.message.response.length > 0) { // show dropdown list $('select#storedfilesexlibris').parent().removeClass('hidden'); $.each(data.message.response, function (i,val) { var option = ''; $('select#storedfilesexlibris').append(option); }); } }); // load functionality for exlibris modal this.handleExlibris(); this.handleBatchfile(); // call shared function (used in manualmode and batchmode) defined in script.js handleSuppressExlibrisSpreadCheckbox(); // call shared function (used in manualmode and batchmode) for EPUB options display displayEpubOptions(); // reset typemail radiobutton $('#typebatch').prop('checked', true); } this.initialize(); } function Support() { "use strict"; this.oPage = null; this.initialize = function () { this.oPage = new Page(function () { setSupportTicket(this.contract); handleTicket(); }); } this.initialize(); }function DecoderMode() { this.Accounts = []; this.accountname = null; this.accountkey = null; this.url = null; this.handleForm = function() { var progress = $('#progress'); var op = this; var data = new FormData(); // submit handler $('button#submit').click(function (e) { e.preventDefault(); // Validation comes first! var data = new FormData(); var errors = false; var type = null; if ($('#file')[0].files[0] == undefined) { errors = true; } else { var name = $('#file')[0].files[0].name; data.append('file', $('#file')[0].files[0], name); var extension = name.substr(name.lastIndexOf(".") + 1); if (extension === 'pdf') { op.url = booxtreampdfdecodebaseurl; // redirect to pdf watermarker type = 'pdf'; } else { op.url = booxtreamdecoderbaseurl; // epub type = 'epub'; } } if(errors) { $('#formerror').show(); $('html, body').animate({scrollTop: $("#formerror").offset().top}, 2000); setTimeout(function () { $('#formerror').slideUp('slow'); }, 7000); return false; } // create progress bar var progressbar = $('
    '); var bar = $('').attr('id', 'percentage').html('0%'); progressbar.append(bar); progress.append(progressbar); // make bar active (animation) and visible progress.addClass('active'); progress.show(); // ajax it $.ajax({ beforeSend: function (xhr) { authentication = B64.encode(op.accountname+':'+op.accountkey); xhr.setRequestHeader("Authorization", "Basic " + authentication); }, xhrFields: { withCredentials: true }, crossDomain: true, xhr: function() { var xhr = $.ajaxSettings.xhr(); //Upload progress xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = Math.ceil((evt.loaded / evt.total)* 100); if(percentComplete === 100) { progressbar.addClass('progress-bar-success'); bar.html('File uploaded. Processing...'); $('#booxtreamspinner').show(); } else { bar.html('Uploading: ' + percentComplete + '%'); } progressbar.attr('aria-valuenow', percentComplete); progressbar.width(percentComplete + '%'); } }, false); return xhr; }, headers: { 'Accept': 'application/xml', }, type: 'POST', url: op.url, contentType: false, processData: false, dataType: 'xml', data: data, error: function (xhr, data) { progress.removeClass('active'); // if no watermark found, a 404 statuscode is returned; seperate that from other error messages if (xhr.status == 404) { progressbar.addClass('progress-bar-success'); stopSpinner('#booxtreamspinner'); bar.html('Transaction completed'); $('#message').html('No watermark found'); $('#decoderpanel').slideUp('slow'); $('#result').show(); } else { bar.html('Error'); progressbar.addClass('progress-bar-danger'); stopSpinner('#spinner'); $('#message').addClass('text-danger').html('An error occured'); } }, success: function (data){ progress.removeClass('active'); progressbar.addClass('progress-bar-success'); stopSpinner('#booxtreamspinner'); bar.html('Transaction completed'); var message = null; if (type === 'pdf') { message = $('

    This is a booXtreamed PDF.

    '); } else { message = $('

    This is a booXtreamed EPUB.

    '); } var list = $('
      '); message.append(list); var referenceid = $(data).find('ReferenceID').text(); if (referenceid != '') { var listitem = $('
    • Reference ID: ' + referenceid + '
    • '); list.append(listitem); } var name = $(data).find('CustomerName').text(); if (name != '') { var listitem = $('
    • Name: ' + name + '
    • '); list.append(listitem); } var emailaddress = $(data).find('CustomerEmailAddress').text(); if (emailaddress != '') { var listitem = $('
    • Emailaddress: ' + emailaddress + '
    • '); list.append(listitem); } $('#message').html(message); $('#decoderpanel').slideUp('slow'); $('#result').show(); } }); return false; }); } this.initialize = function () { this.oPage = new Page(); // get key first this.sURL = urlObject(); var accountname = this.sURL.parameters.account; if(typeof accountname === "undefined") { window.location = 'index.php'; } this.accountname = accountname; $('#accountname').html(this.accountname); var op = this; $.getJSONCache(baseurl + accountsmethod, function (data) { var AccountNames = []; var validaccount = false; $.each(data.message.response, function (i,val) { if(val.LoginName === accountname) { $('#accountname').html(val.AccountName + (val.Demo === '1' ? ' (test account)' : ' (production account)')); validaccount = true; // redirect to home page when account does not have permission to view this page // @todo: integer output instead of string if (val.Decoder !== '1') { window.location = 'index.php'; } } AccountNames[val.LoginName] = val.AccountName; op.Accounts[val.LoginName] = val.AuthenticationKey; }); if (!validaccount) { window.location = 'index.php'; } op.accountkey = op.Accounts[accountname]; }); this.handleForm(); } this.initialize(); } function Templates() { this.Accounts = []; this.accountname = null; this.accountkey = null; this.checkEmailAddress = function (message, emailaddress) { var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (emailaddress.length > 0 && !regex.test(emailaddress)) { if (message.length > 0) { message += '
      '; } message += 'Email address is not valid'; } return message; } this.buttons = function () { var op = this; $('#batches').click(function() { window.location = $(this).attr('href') + op.accountname; return false; }); $('#newbatch').click(function() { window.location = $(this).attr('href') + op.accountname; return false; }); $('#storeTemplate').click(function(e) { e.preventDefault(); var message = ''; var name = $('#addTemplateName').val(); var emailaddress = $('#addTemplateSenderEmailAddress').val(); if (name.length === 0) { message = 'Name is required'; message = op.checkEmailAddress(message, emailaddress); var messagebox = $('#addTemplateError'); messagebox.html(message); messagebox.fadeIn('slow', function () { messagebox.delay(5000).fadeOut(); }); } else { $.when(op.checkNameExists(name)).then(function (data) { if (data.message.response) { message = 'Name is already in use'; } message = op.checkEmailAddress(message, emailaddress); if (message.length > 0) { var messagebox = $('#addTemplateError'); messagebox.html(message); messagebox.fadeIn('slow', function () { messagebox.delay(5000).fadeOut(); }); } else { data = {}; data['name'] = $('#addTemplateName').val(); data['from_email'] = $('#addTemplateSenderEmailAddress').val(); data['from_name'] = $('#addTemplateSenderName').val(); data['subject'] = $('#addTemplateSubject').val(); data['code'] = $('#addTemplateCode').val(); data['publish'] = $('#addTemplatePublish').is(':checked'); $.ajax({ beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic " + op.getAuthentication()); }, xhrFields: { withCredentials: true }, crossDomain: true, type: 'POST', url: baseurl + 'account/' + op.accountkey + '/' + templatesstoremethod, contentType: false, processData: false, data: JSON.stringify(data), dataType: 'json', error: function (data) { $('#error').collapse('show').html(data.responseText); $('#addTemplate').modal('toggle'); }, success: function (data) { var row = data.message.response; op.addRow(row); op.addOption(row); $('#addTemplate').modal('toggle'); // reset modal $('#addTemplateForm :input').val('').prop('checked', false); } }); } }); } }); $('#updateTemplate').click(function(e) { e.preventDefault(); if (op.validateUpdate()) { var data = {}; var name = $('#editTemplateName').val(); data['name'] = name; data['from_email'] = $('#editTemplateSenderEmailAddress').val(); data['from_name'] = $('#editTemplateSenderName').val(); data['subject'] = $('#editTemplateSubject').val(); data['code'] = $('#editTemplateCode').val(); data['publish'] = $('#editTemplatePublish').is(':checked'); $.ajax({ beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic " + op.getAuthentication()); }, xhrFields: { withCredentials: true }, crossDomain: true, type: 'POST', url: baseurl + 'account/' + op.accountkey + '/' + templatesupdatemethod, contentType: false, processData: false, data: JSON.stringify(data), dataType: 'json', error: function (data) { $('#error').collapse('show').append(data.responseText); $('#editTemplate').modal('toggle'); }, success: function (data) { location.reload(); /* var row = data.message.response; var published_at = 'not published'; var published = false; if (row.published_at != null) { published_at = formatDisplayUTCDate(new Date(row.published_at)); published = true; } var button = $('').click(function(event) { event.preventDefault(); $('#editTemplateName').val(row.name); $('#editTemplateCode').html(row.code); // the following lines don't seem to work... if (published) { $('#editTemplatePublish').prop('checked', true).attr('disabled', 'disabled').checkboxradio('refresh'); } else { $('#editTemplatePublish').prop('checked', published); } }); var tr = $('td:contains("' + name + '")').parent(); tr.find('td.row_updated_at').html(formatDisplayUTCDate(new Date(row.updated_at))); tr.find('td.row_published_at').html(published_at); tr.find('td.row_edit').html(button); $('#editTemplate').modal('toggle'); */ } }); } }); } this.getAuthentication = function () { if(typeof authentication === "undefined") { // try to get it from sessionstorage var authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if(authentication === null) { authentication = localStorage.getItem("authentication"); // got it from localstorage, now add it to sessionstorage sessionStorage.setItem("authentication", authentication); } } if(authentication === null) { document.location = 'login.php'; } return authentication; } this.renderTemplate = function (event) { var data = {}; data['name'] = event.data.name; var url = baseurl + 'account/' + event.data.accountkey + '/' + templatesrendermethod; $.ajax({ beforeSend: function (xhr) { if(typeof authentication === "undefined") { // try to get it from sessionstorage var authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if(authentication === null) { authentication = localStorage.getItem("authentication"); // got it from localstorage, now add it to sessionstorage sessionStorage.setItem("authentication", authentication); } } if(authentication === null) { document.location = 'login.php'; } xhr.setRequestHeader("Authorization", "Basic " + authentication); }, xhrFields: { withCredentials: true }, crossDomain: true, type: 'POST', url: url, contentType: false, processData: false, data: JSON.stringify(data), dataType: 'json', error: function (data) { $('#error').collapse('show').append(data.responseText); $('#renderTemplate').modal('toggle'); }, success: function (data) { var row = data.message.response; var published = false; if (row.published_at != null) { published = true; } $('#renderTemplateName').val(row.name); $('#renderTemplateCode').html(row.code); $('#renderTemplatePublish').prop('checked', published); } }); } this.deleteTemplate = function (event) { var data = {}; var name = event.data.name; data['name'] = name; var url = baseurl + 'account/' + event.data.accountkey + '/' + templatesdeletemethod; $.ajax({ beforeSend: function (xhr) { if(typeof authentication === "undefined") { // try to get it from sessionstorage var authentication = sessionStorage.getItem("authentication"); // or try to get it from localstorage if(authentication === null) { authentication = localStorage.getItem("authentication"); // got it from localstorage, now add it to sessionstorage sessionStorage.setItem("authentication", authentication); } } if(authentication === null) { document.location = 'login.php'; } xhr.setRequestHeader("Authorization", "Basic " + authentication); }, xhrFields: { withCredentials: true }, crossDomain: true, type: 'POST', url: url, contentType: false, processData: false, data: JSON.stringify(data), dataType: 'json', error: function (data) { $('#error').collapse('show').html(data.responseText); }, success: function (data) { $("tr[name='" + name + "']").remove(); $("li[id='" + name + "']").remove(); } }); } this.getTemplates = function() { startSpinner('#spinner'); // build templates url var url = baseurl + 'account/' + this.accountkey + '/' + templateslistmethod; // get and display templates var op = this; $.getJSONAuth(url, function (data) { if(typeof data.message !== undefined) { $.each(data.message.response, function (i, val) { op.addRow(val); op.addOption(val); }); } stopSpinner('#spinner'); }); } this.addRow = function (row) { var op = this; var templates = $('#templates-tbody'); var published_at = 'not published'; var published = false; if (row.published_at != null) { published_at = formatDisplayUTCDate(new Date(row.published_at)); published = true; } var tr = $('').attr('name', row.name); tr.append($('' + row.name + '')); tr.append($('' + formatDisplayUTCDate(new Date(row.created_at)) + '')); tr.append($('' + formatDisplayUTCDate(new Date(row.updated_at)) + '')); tr.append($('' + published_at + '')); var tdedit = $(''); var editbutton = $('').click(function(event) { event.preventDefault(); $('#editTemplateName').val(row.name); $('#editTemplateSenderEmailAddress').val(row.from_email); $('#editTemplateSenderName').val(row.from_name); $('#editTemplateSubject').val(row.subject); $('#editTemplateCode').html(row.code); if (published) { $('#editTemplatePublish').prop('checked', true).attr('disabled', 'disabled'); } else { $('#editTemplatePublish').prop('checked', false).removeAttr('disabled'); } }); tdedit.append(editbutton); tr.append(tdedit); var tdrender = $(''); var renderbutton = $('').on( 'click', { name: row.name, accountkey: op.accountkey }, op.renderTemplate); tdrender.append(renderbutton); tr.append(tdrender); var tddelete = $(''); var deletebutton = $('').on( 'click', { name: row.name, accountkey: op.accountkey }, op.deleteTemplate); tddelete.append(deletebutton); tr.append(tddelete); templates.append(tr); } this.addOption = function(row) { var option = $('
    • '+row.name+'
    • ').click(function(event) { $('#addTemplateName').val('Copy of ' + row.name); $('#addTemplateSenderEmailAddress').val(row.from_email); $('#addTemplateSenderName').val(row.from_name); $('#addTemplateSubject').val(row.subject); $('#addTemplateCode').val(row.code); $('#addTemplate').modal('toggle'); }); $('#templatesdropdown').append(option); } this.checkNameExists = function(name) { var op = this; var data = {}; data['name'] = name; var url = baseurl + 'account/' + this.accountkey + '/' + templatesexistsmethod; return $.ajax({ beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic " + op.getAuthentication()); }, xhrFields: { withCredentials: true }, crossDomain: true, type: 'POST', url: url, contentType: false, processData: false, data: JSON.stringify(data), dataType: 'json' }); } this.validateUpdate = function() { var op = this; var message = ''; var name = $('#editTemplateName').val(); var emailaddress = $('#editTemplateSenderEmailAddress').val(); if (name.length === 0) { message = 'Name is required'; } message = op.checkEmailAddress(message, emailaddress); if (message.length > 0) { var messagebox = $('#editTemplateError'); messagebox.html(message); messagebox.fadeIn('slow', function(){ messagebox.delay(5000).fadeOut(); }); return false; } return true; } this.initialize = function () { this.oPage = new Page(); this.buttons(); var op = this; // get key first this.sURL = urlObject(); var accountname = this.sURL.parameters.account; if(typeof accountname === "undefined") { window.location = 'index.php'; } this.accountname = accountname; $('#accountname').html(this.accountname); $.getJSONCache(baseurl + accountsmethod, function (data) { var AccountNames = []; var validaccount = false; $.each(data.message.response, function (i,val) { if(val.LoginName === accountname) { validaccount = true; $('#accountname').html(val.AccountName + (val.Demo === '1' ? ' (test account)' : ' (production account)')); // redirect to home page when account does not have permission to view this page // @todo: integer output instead of string if (val.Batcher !== '1') { window.location = 'index.php'; } if (val.Mailing === 1) { op.Mailing = true; } } AccountNames[val.LoginName] = val.AccountName; op.Accounts[val.LoginName] = val.AuthenticationKey; }); if (!validaccount) { window.location = 'index.php'; } op.accountkey = op.Accounts[accountname]; // account loaded, get templates op.getTemplates(); }); } this.initialize(); }// Credits function StorageCosts() { "use strict"; var op = this; this.displayStorageCosts = function () { $.getJSONAuth(baseurl + creditordersmethod, function (data) { $('#storagecosts-tbody').children('.datarow').remove(); // display the most recent first var costs = data.message.response; // filter by selectedYear var selectedYear = getSelectedYear(); costs = costs.filter(function (val) { return new Date(val.DateTime).getFullYear() === selectedYear; }); $.each(costs, function (i, val) { if (val.OrderType === 'Storage costs') { // format date var d = new Date(val.DateTime); var datetimeutcdate = formatDisplayUTCDate(d).split(' ')[0]; // create table row var tr = $('').addClass('datarow'); tr.append($('')); tr.append($('' + val.Credits + '')); tr.append($('')); tr.append($('' + val.ClientOrderID + '')); // append table row $('#storagecosts-tbody').append(tr); } }); }); } this.initialize = function () { var oPage = new Page(); this.displayStorageCosts(); showCredits(); setYear(); // when the yearSelector dropdown is clicked on this page, reload display storage costs $('#yearSelector li').on('click', function(){ op.displayStorageCosts(); }); } this.initialize(); } // Credits function MailingCosts() { "use strict"; var op = this; this.displayMailingCosts = function () { $.getJSONAuth(baseurl + creditordersmethod, function (data) { $('#storagecosts-tbody').children('.datarow').remove(); // display the most recent first var costs = data.message.response; // filter by selectedYear var selectedYear = getSelectedYear(); costs = costs.filter(function (val) { return new Date(val.DateTime).getFullYear() === selectedYear; }); $.each(costs, function (i, val) { if (val.OrderType === 'Mailing costs') { // format date var d = new Date(val.DateTime); var datetimeutcdate = formatDisplayUTCDate(d).split(' ')[0]; // create table row var tr = $('').addClass('datarow'); tr.append($('')); tr.append($('' + val.Credits + '')); tr.append($('')); tr.append($('' + val.ClientOrderID + '')); // append table row $('#storagecosts-tbody').append(tr); } }); }); } this.initialize = function () { var oPage = new Page(); this.displayMailingCosts(); showCredits(); setYear(); // when the yearSelector dropdown is clicked on this page, reload display mailing costs $('#yearSelector li').on('click', function(){ op.displayMailingCosts(); }); } this.initialize(); } // Credits function ScriptWatermarkingcosts() { "use strict"; var op = this; this.displayCreditUsage = function () { $.getJSONAuth(baseurl + creditusagemethod, function (data) { $('#creditusage-tbody').children('.datarow').remove(); // display the most recent first var costs = data.message.response; // filter by selectedYear var selectedYear = getSelectedYear(); costs = costs.filter(function (val) { return parseInt(val.year) === selectedYear; }); $.each(costs, function (i, val) { // get this year, this month var this_year = new Date().getFullYear(); var this_month = new Date().getMonth(); this_month = this_month + 1; // get prefix var prefix_month = parseInt(val.month) + 1; // first, cast to integer and calculate var prefix_year = parseInt(val.year); if (prefix_month > 12) { prefix_month = '01'; prefix_year = prefix_year + 1; } prefix_month = prefix_month.toString(); // now, cast to string and add leading zero if (prefix_month.length === 1) { prefix_month = '0' + prefix_month; } var prefix_day = '01'; // get postfix var postfix_month = val.month; if (postfix_month.length === 1) { postfix_month = '0' + postfix_month; } // check if data is about current year, current month var prefix = ''; var description = 'Total monthy watermark transactions'; if (val.year.toString() === this_year.toString() && val.month.toString() === this_month.toString()) { description = 'Current watermark transactions'; } else { prefix = prefix_year + '-' + prefix_month + '-' + prefix_day; } var postfix = val.year + '-' + postfix_month; var value = '-' + val.value; if (val.value == 0) { value = val.value; } // create table row var tr = $('').addClass('datarow'); tr.append($('' + prefix + '')); tr.append($('' + value + '')); tr.append($('')); tr.append($('' + description + ' ' + postfix + '')); // append table row $('#creditusage-tbody').append(tr); }); }); } this.initialize = function () { var oPage = new Page(); this.displayCreditUsage(); showCredits(); setYear(); // when the yearSelector dropdown is clicked on this page, reload display credit usage $('#yearSelector li').on('click', function(){ op.displayCreditUsage(); }); } this.initialize(); }