/* \file app_utilities.js * \brief app_utilities.js page * \author Bram Lentjes, Core|Vision * \version 1.0 * \date 14-06-2013 * * This file contains the app_utilities.js file. */ // Only polling when device is an portal if (portal == 1) { // polling every 50 seconds (must be activity every 60 sec else the session // will be deleted when more tabs are open) setInterval(function () { ajax_post('', '', "?id=" + getURLParam('id') + "&href=app/dummy_poll.php", ''); }, 50000); } // Enable tab apps with tabs var tabEnable; var number_commentsj; var addProfileFlag = true; // Variables to store the translated messages var no_internet_connection_message; var no_server_connection_message; var no_internet_connection_message_ok; var no_internet_camera; var own_gps_location; var upload_failed; var open_text; var download_text; var filesize_mismatch_text; var remove_file_succes; var remove_file_fail; var acceptPrjTransfer_message; var slow_connection; // Variable to store the 'set' answers locally var feedbackStoreAnswers = []; // To refresh the instruction list var refreshInstructionList; /** * Name : getTextAreaValue(id) * Parameters : id * Description : return value of text area */ function getTextAreaValue(id) { var element = document.getElementById(id); var value = element.value; return value; } /******************************************************************************* * Device info ****************************** * * ******************************************************************************/ /** * Name : getDeviceUUID() Parameters : - Description : return UUID */ function getDeviceUUID() { return device.uuid; } /** * Name : getWindowWidth() Parameters : - Description : Return width of * screenSetFontSize */ function getWindowWidth() { var windowWidth = 0; if (typeof (window.innerWidth) == 'number') { windowWidth = window.innerWidth; } else { if (document.documentElement && document.documentElement.clientWidth) { windowWidth = document.documentElement.clientWidth; } else { if (document.body && document.body.clientWidth) { windowWidth = document.body.clientWidth; } } } return windowWidth; } /** * Name : SetFontSize() Parameters : - Description : Set the font size */ function SetFontSize() { if (getWindowWidth() > 400) { document.body.style.fontSize = '24px'; } else { document.body.style.fontSize = '16px'; } } /******************************************************************************* * Navigate to page **************************** * * ******************************************************************************/ // GLOBALS // Store current page var current_page; // Store current sub page {documentation,upload,scan,evaluation} var current_sub_page; // Store script of signlist for the refresh button var scriptorsignlist; /** * Name : loadApp() Parameters : - Description : Load the app that is clicked */ function loadApp(app, toastTilte, toastMessage) { // Check if there's internet connection if (Online) { // Check if toaster must be displayed if ((toastTilte != -1) || (toastMessage != -1)) { // Set toast message setToast(toastTilte, toastMessage); } // open Page location.href = app; } else { // No Internet connection // Set alert setToastAlert(no_internet_connection_message, no_internet_connection_message_ok); } } /** * Name : loadUrlExternalBrowser() Parameters : - Description : Load the app * that is clicked */ function loadUrlExternalBrowser(url) { window.open(url, '_system'); } /** * Name : setCurrentPage(page) Parameters : page Description : Set current page */ function setCurrentPage(page) { // Set current page current_page = page; } /** * Name : getCurrentPage() Parameters : - Description : Return current page */ function getCurrentPage() { // Return current page return current_page; } /** * Name : setCurrentSuBPage(page) Parameters : page Description : Set current * sub page */ function setCurrentSuBPage(page) { // Set current page current_sub_page = page; } /** * Name : getCurrentSuBPage() Parameters : - Description : Return current sub * page */ function getCurrentSuBPage() { // Return current page return current_sub_page; } /** * Name : setScriptOrSignList() Parameters : - Description : store script or * singlist for the refresh button */ function setScriptOrSignList(type) { scriptorsignlist = type; } /** * Name : getScriptOrSignList() Parameters : - Description : get stored script * or singlist for the refresh button */ function getScriptOrSignList() { return scriptorsignlist; } /** * Name : deleteProjectButtons() Parameters : - Description : Delete buttons if * the exist */ function deleteProjectButtons() { // Check if evaluation submit button excist if (document.getElementById('evaluation_submit')) { // Delete evaluation submit button var element_submit = document.getElementById('evaluation_submit'); var element_div_content = document.getElementById('up_scan_but'); element_div_content.removeChild(element_submit); } // Check if evaluation cancel button excist if (document.getElementById('evaluation_cancel')) { // Delete evaluation cancel button var element_cancel = document.getElementById('evaluation_cancel'); var element_div_content = document.getElementById('up_scan_but'); element_div_content.removeChild(element_cancel); } // Check if upload file selection button excist if (document.getElementById('upload_file_selection')) { // Delete evaluation cancel button var element_upload_file = document .getElementById('upload_file_selection'); var element_div_content = document.getElementById('up_scan_but'); element_div_content.removeChild(element_upload_file); } // Check if camera button excist if (document.getElementById('upload_camera')) { // Delete evaluation cancel button var element_upload_camera = document.getElementById('upload_camera'); var element_div_content = document.getElementById('up_scan_but'); element_div_content.removeChild(element_upload_camera); } // Check if my-form excist if (document.getElementById('my-form')) { // Delete evaluation cancel button var element_upload_form = document.getElementById('my-form'); var element_div_content = document.getElementById('up_scan_but'); element_div_content.removeChild(element_upload_form); } // Check if scan button excist if (document.getElementById('scan_button')) { // Delete evaluation cancel button var element_scan_button = document.getElementById('scan_button'); var element_div_content = document.getElementById('up_scan_but'); element_div_content.removeChild(element_scan_button); } }; /** * Name : closeApp() Parameters : Description : Close the App */ function closeApp() { // TODO Remove or fix app closing on Windows if (device.platform == 'windows') { } else { navigator.navigation.exitApp(); } } /** * Name : refreshApp() Parameters : Description : refresh the project page from * App */ function refreshApp() { // Redirect to home di_ap_projects page $.mobile.changePage("#homepage", { transition: "slide", reverse: true }); // refresh the page ajax_post('get_projects_by_name', '', "?id=" + getURLParam('id') + "&href=app/di_app_projects/a_get_projects.php", 'projecten_page'); } /** * Name : deleteProfile() Parameters : Description : Delete profile */ function deleteProfile() { var user_input = {}; // Clear array user_input = {}; // Store qeustion and answer user_input['profile_id'] = $('#profile_id').val(); // Parse array so it can be send with ajax_post var json_user_input = JSON.stringify(user_input); ajax_post(encodeURIComponent(json_user_input), 'delete_profile_final', '?id=' + getURLParam('id') + '&href=app/di_app_profile/store_profile.php', ''); } /******************************************************************************* * Landscape/portait ******************************* * * ******************************************************************************/ // To add meta data to the page ( change from landscape/portait) var viewPortTag = document.createElement('meta'); /** * Name : doOnOrientationChange() Parameters : Description : check orientation * and change meta data form page */ function doOnOrientationChange() { // Seems counter intuitive, breaks landscape mode on iPad } /******************************************************************************* * Animate login screen ******************************* * * ******************************************************************************/ // GLOBALS // variable to cancel an comment upload var abort_comment = false; // variable to check if user is uploading a comment var upload_comment_c = true; /** * Name : scrollToTop(element) Parameters : - element Description : Scroll to * top of page */ function scrollToTop(element) { // Set comment to top of screen // get top of selected document (div) var pos = element.offsetTop; // get bottom position of up_scan_but (buttons "bladeren" and "camera") var offset = $('#up_scan_but').position().top + $('#up_scan_but').outerHeight(true); pos = pos - offset - 4; // Scroll to position $('#loaded_page').animate({ scrollTop: pos }, 1000); } /** * Name : splash(counter) Parameters : - counter Description : Move a logo from * the middle to the top of the screen */ // variable to set the heigth of the DI logo var height_logo = 5; function splash(counter) { document.getElementById('div_logo').style.top = counter + "%"; if (counter > height_logo) { // Recursive call setTimeout('splash(' + (--counter) + ')', '15'); } else { // Fade in the login screen setTimeout("$(\"#div_loginscreen\").fadeIn(1000);", "25"); } } /** * Name : nosplash Parameters : - Description : delete splashscreen when user * try to logged in more then once */ function nosplash() { document.getElementById('div_logo').style.visibility = "hidden"; document.getElementById('div_logo').style.top = height_logo + "%"; $("#div_loginscreen").fadeIn(1000); document.getElementById('div_logo').style.visibility = "visible"; } /** * Name : setToast(title, msg) Parameters : - title - msg Description : Set a * toast message */ function setToast(title, msg) { // Clear toast if there's already a toast on the screen toastr.clear(); $.mobile.showPageLoadingMsg(); /* * // Set options for the toast toastr.options = { positionClass : * "toast-bottom-full-width", fadeIn: 10, timeOut: 0, extendedTimeOut: 0 } * // Display the toast //toastr.info(msg,title); * * toastr.info("
"+ title.toUpperCase() + "
" + msg.toUpperCase() + "
"); */ } /** * Name : setToastAdvanced(title, msg) Parameters : - title - msg Description : * Set a toast message with cancel option (for upload and download files) */ function setToastAdvanced(title, msg) { // Clear toast if there's already a toast on the screen toastr.clear(); // Set options for the toast toastr.options = { positionClass: "toast-bottom-full-width", fadeIn: 10, timeOut: 0, extendedTimeOut: 0 } // Onclick event of toaster toastr.options.onclick = function () { // Clear toast toastr.clear(); // Check if the user want's to cancel a comment upload or file upload if (abort_comment) { // Cancel the file comment download ajax_post('', '', "?id=" + getURLParam('id') + "&href=app/include/upload_abort_comment.php", ''); // $.mobile.showPageLoadingMsg(); // Set to default abort_comment = false; } else { // Cancel the file download try { // abort the download fileTransfer.abort(winAbort, failAbort); // Progress of download progress_element_con = document .getElementById('progress_container'); // hide progress bar progress_element_con.style.display = "none"; // Progress of download progress_element = document.getElementById('progress_bar'); // hide progress bar progress_element.style.width = "0%"; // To resize the loaded page for the progress bar var loaded_p; // Get height of looaded page loaded_p = document.getElementById('loaded_page'); var height_loaded_p = loaded_p.style.height; // Delete the % sign height_loaded_p = height_loaded_p.substring(0, height_loaded_p.length - 1); // Convert string to float var height_loaded_p_float = parseFloat(height_loaded_p, 10); // Decrement die loaded_page with 1 % (the progress bar is 1 %) height_loaded_p_float += 1; // Convert float to string height_loaded_p = height_loaded_p_float.toString(); // Add "%" sign height_loaded_p += "%"; // Change the the height of loaded_page loaded_p.style.height = height_loaded_p + " !important"; } catch (err) { } // To cancel a file upload ajax_post('', '', "?id=" + getURLParam('id') + "&href=app/include/upload_abort_file.php", ''); } } // Display the toast toastr .info("
" + title.toUpperCase() + "
" + msg.toUpperCase() + "
"); } /** * Name : setToastAlert(msg, but_one, but_two, no_internet_click) Parameters : - * msg - but_one - but_two - onclick_but_one - onclick_but_two Description : Set * a toast message with buttons */ function setToastAlert(msg, but_one_text, but_two_text, onclick_but_1, onclick_but_2, height) { // Clear toast if there's already a toast on the screen toastr.clear(); if ($.mobile) { $.mobile.hidePageLoadingMsg(); } // Set options for the toast toastr.options = { debug: false, positionClass: "toast-bottom-full-width", onclick: null, fadeIn: 300, fadeOut: 0, timeOut: 0, extendedTimeOut: 1000 } var onclick_but_one = "toastr.clear();$('div.overlay').fadeOut('fast')"; var onclick_but_two = "toastr.clear();$('div.overlay').fadeOut('fast')"; // Set overlay $("div.overlay").fadeIn("fast"); // Check if onclick but one check onclick is set if (typeof onclick_but_1 == 'undefined') { } else { onclick_but_one += ";" + onclick_but_1; } // Check if onclick but one check onclick is set if (typeof onclick_but_2 == 'undefined') { } else { onclick_but_two += ";" + onclick_but_2; } var style = "style=\"\""; // check if height is set if (height || portal) { // When height is not set if (!height) { height = '100'; } style = "style=\"height:" + height + "px;\""; } if ((typeof but_two_text == 'undefined') || (but_two_text == '')) { // Check if msg is not an string ( so it's an array) if (!(typeof msg === 'string')) { // Copy the correct message (from the toastMessage array) msg = msg[markerMsg]; } // Toast alert with one button // toastr.info("
" + // msg.toUpperCase() + "
"); toastr .info("
" + msg.toUpperCase() + "
"); } else { // Toast alert with two button // toastr.info("
" + // msg.toUpperCase() + "
"); toastr .info("
" + msg.toUpperCase() + "
"); } } /** * Name : winAbort(r) Parameters : r Description : Callback when abort succeed */ function winAbort(r) { // Abort succes // Flag that there's no download active download_file = true; } /** * Name : failAbort(error) Parameters : error Description : Callback when abort * failed */ function failAbort(error) { // Abort fail } /******************************************************************************* * Download and open files ***************************** * * ******************************************************************************/ // GLOBALS // To download a file. And to abort a download on progress var fileTransfer; // To save the info to download and open a file var _url; var _downloadpath; var _mimetype; var _openpath; var _toastTitle; var _toastMessage; // To save the new ( (0), (1), (2) etc..) downloadpath en openpath var filename_down; var filename_open; // Flag that there's no download active var download_file = true; // Flag that there's no upload active var upload_file = true; /** * Name : checkIfFileExists() Parameters : - check_url - check_downloadpath - * check_mimetype - check_openpath - check_toastTitle - check_toastMessage - * filesize Description : To check if the file exist already */ function checkIfFileExists(check_url, check_downloadpath, check_mimetype, check_openpath, check_toastTitle, check_toastMessage, filesize) { // Copy filesize to global sizeOfFile = filesize; // Copy variables to globals _url = check_url; _downloadpath = check_downloadpath; _mimetype = check_mimetype; _openpath = check_openpath; _toastTitle = check_toastTitle; _toastMessage = check_toastMessage; filename_down = check_downloadpath; filename_open = check_openpath; // Always re-download the file fileDoesNotExist(); } /** * Name : fileExists() Parameters : fileEntry Description : Callback when file * exist */ function fileExists(fileEntry) { // Variable to store local file size var fileSize; fileEntry .file(function (fileObj) { // Store local filesize fileSize = fileObj.size; // Check if app is already downloading the file if (download_file) { // Check if local file isn't damaged if ((fileSize > 0) && (fileSize == sizeOfFile)) { // Check device switch (device.platform) { case 'iOS': // File isn't damaged open the file on iOS window.requestFileSystem(LocalFileSystem.PERSISTENT, 10, function (fs) { openFileOnWindows(cordova.file.documentsDirectory + "/" + _downloadpath, _mimetype); }); break; case 'Android': window.requestFileSystem(LocalFileSystem.PERSISTENT, 10, function (fs) { openFileOnWindows(cordova.file.externalDataDirectory + _downloadpath, _mimetype); }); break; case 'windows': window.requestFileSystem(LocalFileSystem.PERSISTENT, 10, function (fs) { openFileOnWindows(fs.root.toURL() + _downloadpath, _mimetype); }); break; default: break; } } else if (fileSize == 0) { // File is damaged // Check if there is internet connection if (Online) { // Progress of download progress_element_con = document .getElementById('progress_container'); // Show progress bar progress_element_con.style.display = "block"; // Download the file again downloadFile(_url, filename_down, _mimetype, filename_open, _toastTitle, _toastMessage); } else { // Set alert setTimeout( 'setToastAlert(no_internet_connection_message,no_internet_connection_message_ok)', 500) } } else if (fileSize != sizeOfFile) { // Local file is changed // Check if there is internet connection if (Online) { // Progress of download progress_element_con = document .getElementById('progress_container'); // Show progress bar progress_element_con.style.display = "block"; // Download or open the file again switch (device.platform) { case 'windows': setToastAlert( '' + filesize_mismatch_text + '', '' + download_text + '', '' + open_text + '', 'downloadFile(_url ,filename_down ,_mimetype , filename_open, _toastTitle, _toastMessage);', 'openFileOnWindows(_downloadpath, _mimetype);'); break; default: setToastAlert( '' + filesize_mismatch_text + '', '' + download_text + '', '' + open_text + '', 'downloadFile(_url ,filename_down ,_mimetype , filename_open, _toastTitle, _toastMessage);', 'openFile(_mimetype,filename_open);'); break; } } else { // Set alert setTimeout( 'setToastAlert(no_internet_connection_message,no_internet_connection_message_ok)', 500) } } } }); } /** * Name : fileDoesNotExist() Parameters : Description : Callback when file does * not exist */ function fileDoesNotExist() { // Check if there is internet connection if (Online) { // Progress of download progress_element_con = document.getElementById('progress_container'); // Show progress bar progress_element_con.style.display = "block"; // File doest not exist downloadFile(_url, filename_down, _mimetype, filename_open, _toastTitle, _toastMessage); } else { // Set alert setTimeout( 'setToastAlert(no_internet_connection_message,no_internet_connection_message_ok)', 500); } } /** * Name : getFSFail() Parameters : - evt Description : Callback error when the * file system can not be reached */ function getFSFail(evt) { // Error with checking if file exist } /** * Name : downloadFile() Parameters : - url - downloadpath - mimetype - openpath - * toastTitle Description : Download a file from a webserver and place the file * on the sdcard of the device */ // Progress of download var progress_element; var progress_element_con; var value_progresss = 0; function downloadFile(url, downloadpath, mimetype, openpath, toastTitle, toastMessage) { // Progress of download progress_element = document.getElementById('progress_bar'); progress_element_con = document.getElementById('progress_container'); // Only download one file at the time if (download_file) { // Check of object exist if ($.mobile) { // Show loader $.mobile.showPageLoadingMsg(); } // Set download variable download_file = false; // Url where the file is stored (on mtinfo server) var url = url; window.requestFileSystem(LocalFileSystem.PERSISTENT, 10, function (fs) { var imagePath; if (device.platform === "windows") { imagePath = fs.root.toURL() + downloadpath; } else if(device.platform === "Android") { imagePath = cordova.file.externalDataDirectory + downloadpath; } else { // full file path (path on phone + path where the file will stored) imagePath = cordova.file.documentsDirectory + "/" + downloadpath; } // Create an object to download a file var filedownload = new FileTransfer(); // Copy filetransfer object to abort the download; fileTransfer = filedownload; // Check if the progress bar excist ( login screen doesn't have a // progress bar) if ((progress_element_con != null) || (progress_element != null)) { // Progress of download fileTransfer.onprogress = function (progressEvent) { // if (progressEvent.lengthComputable) { // this won't work // on iOS. But the total size is stored in sizeOfFile. no // need for progressEvent.total // Calculate the loaded % of loaded file value_progresss = Math.floor(progressEvent.loaded / sizeOfFile * 100); // Set width of div(progress bar) progress_element.style.width = value_progresss + "%"; // } else { // loadingStatus.increment(); // } }; } fileTransfer.download(url, imagePath, function (entry) { // Check if the progress bar excist ( login screen doesn't have // a progress bar) if ((progress_element_con != null) || (progress_element != null)) { // Set to default value sizeOfFile = 0; // Set width of progress bar to 5% progress_element.style.width = "5%"; // Show progress bar progress_element_con.style.display = "none"; } // Check of object exist if ($.mobile) { // Show loader $.mobile.hidePageLoadingMsg(); } // Set download variable download_file = true; cordova.plugins.fileOpener2.open( imagePath, mimetype, { error: function (e) { console.log('Error status: ' + e.status + ' - Error message: ' + e.message); }, success: function () { console.log('file opened successfully'); } } ); }, function (error) { try { // Check of object exist if ($.mobile) { // Hide loader $.mobile.hidePageLoadingMsg(); } // Flag that there's no download active download_file = true; // Cancel the donwload fileTransfer.abort(winAbort, failAbort); // Set to default value sizeOfFile = 0; // Set width of progress bar to 0% progress_element.style.width = "0%"; // Show progress bar progress_element_con.style.display = "none"; // Check if there is internet connection if (!Online) { // Set alert setToastAlert(no_internet_connection_message, no_internet_connection_message_ok); } } catch (err) { // Flag that there's no download active download_file = true; } }); }, failDownload) } } /** * Name : downloadFilePortal(url) Parameters : - url Description : Download file * and show in browser */ function downloadFilePortal(url) { window.open(url); } // ///////////////////////////////////////// This function will be used later /** * Name : downloadAllFiles(doc_array,toastTitle,toastMessage) Parameters : - * doc_array - toastTitle - toastMessage Description : Download all file sfrom a * webserver and place the file on the sdcard of the device */ function downloadAllFiles(doc_array, toastTitle, toastMessage) { // Only download one file at the time if (download_file) { // Set download variable download_file = false; // Url where the file is stored (on mtinfo server) var url = doc_array[0][0]; window.requestFileSystem(LocalFileSystem.PERSISTENT, 10, function (fs) { // full file path (path on phone + path where the file will stored) var imagePath = fs.root.fullPath + "/" + doc_array[0][1]; // Create an object to download a file var filedownload = new FileTransfer(); // Copy filetransfer object to abort the download; fileTransfer = filedownload; fileTransfer.download(url, imagePath, function (entry) { // Set download variable download_file = true; // delete first element of array doc_array.shift(); if (doc_array.length > 0) { downloadAllFiles(doc_array, toastTitle, toastMessage); } else { // alert('done'); } }, function (error) { try { // Flag that there's no download active download_file = true; // Cancel the donwload fileTransfer.abort(winAbort, failAbort); // Clear toast toastr.clear(); } catch (err) { // Flag that there's no download active download_file = true; } }); }, failDownload) } } /** * Name : failDownload() Parameters : - evt Description : Fail function for the * download function */ function failDownload(evt) { // Flag that there's no download active download_file = true; // fail download (no sdcard inserted) setTimeout(function () { setToastAlert(_toastTitle, _toastMessage) }, 500); } /** * Name : openFile(mimetype , path) Parameters : - mimetype - path Description : * Open a file with a native program */ function openFile(mimetype, path) { window.plugins.webintent.startActivity({ action: window.plugins.webintent.ACTION_VIEW, type: mimetype, url: 'file:///' + path }, function () { toastr.clear() }, function () {/* failed to open file */ }); } /******************************************************************************* * Project data ********************************** * * ******************************************************************************/ // Variable to save the selected project id var project_id; // Variable to save the selected period id var period_id; // Variable to save the selected project id var project_name; // Variable to save the selected user id var user_id; /** * Name : setProjectId(id) Parameters : - Description : Set project id of active * project */ function setProjectId(id) { project_id = id; } /** * Name : getProjectId() Parameters : - Description : Get project id of active * project */ function getProjectId() { return project_id; } /** * Name : setPeriodId(id) Parameters : - Description : Set period id of active * project */ function setPeriodId(id) { period_id = id; } /** * Name : getPeriodId() Parameters : - Description : Get period id of active * project */ function getPeriodId() { return period_id; } /** * Name : setProjectName(name) Parameters : - name Description : Set project * name of active project */ function setProjectName(name) { project_name = ""; project_name = name; } /** * Name : getProjectName(id) Parameters : - id Description : Get project name of * active project */ function getProjectName(id) { if (id == 'return') { return project_name; } else { // // Check if size of project name is bigger then 15 // if(project_name.length > 15){ // project_name= project_name.substr(0,15); // project_name += ".."; // } document.getElementById(id).innerHTML = project_name.toUpperCase(); } } /** * Name : setEnqueteId(id) Parameters : - id Description : Set current used * enquete id */ var enqueteId; function setEnqueteId(id) { enqueteId = id; } /** * Name : getEnqueteId() Parameters : Description : Get current used enquete id */ function getEnqueteId() { return enqueteId; } /******************************************************************************* * Status color bar ********************************* * * ******************************************************************************/ /** * Name : deleteOldStatusColor(array) Parameters : - array - number Description : * Delete old status bar colors and set only the first status bar */ function deleteOldStatusColor(array, number) { var old_element; // Unselect al status bar od subbuttons for (var i = 0; i < array.length; i++) { // Get element status bar color old_element = document.getElementById(array[i][1]); old_element.style.background = 'rgb(255,184,100)'; } // Set first status bar of subbuttons old_element = document.getElementById(array[number][1]); old_element.style.background = 'white'; } function deleteOldStatusColorbyClass(id, clas) { $('.' + clas).each(function () { $('#' + this.id).css('background-color', 'rgb(255,184,100)'); }); if (id) { $('#' + id).css('background-color', 'white'); } } // Variable to check the internet connection var Online = true; /** * Name : Internetcheck(e) Parameters : - e Description : Set internet check * flag */ function Internetcheck(e) { // Check if device is offline or online if (e.type == "offline") { // offline // Set internet check flag to false Online = false; } else { // online // Set internet check flag to true Online = true; } } // Set eventListeners to detect internet document.addEventListener("offline", Internetcheck, false); document.addEventListener("online", Internetcheck, false); /** * Name : ajax_post(arg1,arg2,href,div) Parameters : - arg1 - arg2 - href - div * Description : Send a http request to the server and get die result back and * set into a div */ // GLOBALS // Used to check if spinners must be showed var spinning; // var connectionTimeout; function ajax_post(arg1, arg2, href, div, showMsg, ConTimeout) { // Default value if (typeof (ConTimeout) === 'undefined') ConTimeout = 20000; var hr = null; // Set timeout function var connectionTimeout = setTimeout(function () { slowConnection(hr, href) }, ConTimeout); // Check if there's internet connection if (Online) { spinning = true; // Create our XMLHttpRequest object if (hr == null) { try { hr = new XMLHttpRequest(); } catch (e) { // alert('error'); } } // var hr = new XMLHttpRequest(); // Create some variables we need to send to our PHP file var url = href; var fn1 = arg2; var fn2 = arg1; var vars = "project_id=" + fn1 + "&project_name=" + fn2; hr.open("POST", url, true); // Set content type header information for sending url encoded variables // in the request hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // Access the onreadystatechange event for the XMLHttpRequest object hr.onreadystatechange = function () { // Actually execute the request if (hr.readyState == 4) { if (hr.status == 200) { // Clear timeout clearTimeout(connectionTimeout); // Check if device is RS3000 if (RS3000) { // Check if overlay is showed if ($('#rsoverlay').css('display') == 'block') { // Hide overlay $('#rsoverlay').css('display', 'none'); } } var return_data = hr.responseText; if (div && div.length > 0) { // load page in div document.getElementById(div).innerHTML = return_data; spinning = false; $.mobile.hidePageLoadingMsg(); } // Add script runs parseScript(return_data); } else { // Server is not online // Check if device is RS3000 if (RS3000) { // Change text $('#rsoverlay').html(no_server_connection_message); // Show overlay $('#rsoverlay').css('display', 'block'); } } // Assign an empty function to the state handler; hr.onreadystatechange = function () { } // Abort current transfer. This will also call the state // handler, which is not what we want hr.abort(); // Clear object hr = null; } } // Send the data to PHP now... and wait for response to update the // loaded_page div hr.send(vars); // Actually execute the request } else { if ((typeof showMsg != 'undefined') || (showMsg == 0)) { // Set alert setToastAlert(no_internet_connection_message, no_internet_connection_message_ok); } } } function parseScript(strcode) { var scripts = strcode.match(/[\s\S]*?<\/script>/gi); if (scripts) { for (var i = 0; i < scripts.length; i++) { var script = scripts[i].replace(//gi, '').replace(/<\/script>/gi, ''); try { eval(script); } catch (ex) { console.log(ex); } } } } /** * Name : mySpinner() Parameters : Description : Set a spinner if ajax page is * not loaded in 200 ms */ function mySpinner() { if (spinning) { // Set jquery mobile load spinner $.mobile.showPageLoadingMsg(); spinning = false; } } function slowConnection(object, href) { // Check if object exist if ($.mobile) { $.mobile.hidePageLoadingMsg(); } if (object) { // Assign an empty function to the state handler; object.onreadystatechange = function () { }; // Abort current transfer. This will also call the state handler, which // is not what we want object.abort(); // Clear object object = null; } setToastAlert(slow_connection, no_internet_connection_message_ok); // no_internet_connection_message_ok // = OK // (translate) // Only RS3000 app if (RS3000) { var n = href.search("di_app_rs/rs_switching.php"); // Check if the page is die rs_switching page if (n != -1) { // Yes it is! // Refresh switch page ( only for RS3000) $('#rs_page3_content_buttons').css('display', 'block'); // Clear repeat element 1 $('#rs_repeat_element_1').html(''); // Hide input field $('#rs_repeat_element_1').css('display', 'none'); // Show example text $('#rs_repeat_element').css('display', 'table-cell'); // Show container $('#rs_repeat_element_container').css('display', 'table'); // Hide repeat buttons $('#rs_page3_content_buttons_repeat').css('display', 'none'); // Create delay else session var for the logbar isn't ready set setTimeout(function () { ajax_post('', getPeriodId(), '?id=' + getURLParam('id') + '&href=app/di_app_rs/a_get_switch.php', 'rs_page3_content'); }, 1000); } } } /******************************************************************************* * Files ********************************* * * ******************************************************************************/ // GLOBALS // Use to store the filesystem var fileSystem; // Use to put text into a filed var filetext; // Use to read the data form the file var readData = ""; // Size of downloaded file var sizeOfFile = 0; /** * Name : getReadValue() Parameters : - Description : Send readData back */ function getReadValue() { return readData; } /** * Name : readFile(f) Parameters : f Description : Read the data from the file */ function readFile(f) { reader = new FileReader(); reader.onloadend = function (e) { // Read text from file readData = e.target.result; // read data readValue(); } reader.readAsText(f); } /** * Name : doReadFile(e) Parameters : readpath Description : Get file to read */ function doReadFile(readpath) { // create delay of 500 ms. else apple wont read the file setTimeout(function () { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { fileSystem.root.getFile(readpath, { create: true }, gotQuestFileEntry, onError); }, null); }, 500); // fileSystem.root.getFile(readpath, {create:true}, gotQuestFileEntry, // onError); } /** * Name : gotQuestFileEntry(fileEntry) Parameters : fileEntry Description : Need * to fix bug in realse 2.7 */ function gotQuestFileEntry(fileEntry) { fileEntry.file(gotQuestFile, onError); } /** * Name : gotQuestFile(file) Parameters : file Description : Need to fix bug in * realse 2.7 */ function gotQuestFile(file) { readFile(file); } /** * Name : writeFile(f) Parameters : f Description : Get file write en write text * into the file */ function writeFile(f) { f.createWriter(function (writerOb) { // Write data in file writerOb.write(filetext); }) } /** * Name : dowriteFile(e) Parameters : - path - text Description : Get file */ function doWriteFile(path, text) { filetext = text; fileSystem.root.getFile(path, { create: true }, writeFile, onError); } /** * Name : gotFiles(entries) Parameters : entries Description : Get list of all * directories and files */ function gotFiles(entries) { var s = ""; for (var i = 0, len = entries.length; i < len; i++) { // Entry objects include: isFile, isDirectory, name, fullPath s += entries[i].fullPath; s += "
"; } s += "

"; } /** * Name : doDirectoryListing(e) Parameters : e Description : Get directory * reader */ function doDirectoryListing(e) { // Get a directory reader from our FS var dirReader = fileSystem.root.createReader(); dirReader.readEntries(gotFiles, onError); } /** * Name : onFSSuccess(fs) Parameters : fs Description : Store the filesystem so * it can be used in whole the page */ function onFSSuccess(fs) { fileSystem = fs; } /** * Name : onError(e) Parameters : e Description : Generic error handler */ function onError(e) { // error; } /** * Name : CreateNestedDir(fileSystemfs) Parameters : fileSystemfs Description : * Create nested directories */ function CreateNestedDir(fileSystemfs) { // FileSystem fileSystem = fileSystemfs; } function createDir(fileSystemfs, path) { fileSystem = fileSystemfs; fileSystem.root.getDirectory(path, { create: false }, null, function () { createDirectory(path); }); } /** * Name : createDirectory(path) Parameters : path Description : Create * directories */ function createDirectory(path) { // Get dirs var dirs = path.split('/').reverse(); var root = fileSystem.root; // Create dir var createDir = function (dir) { root.getDirectory(dir, { create: true, exclusive: false }, successCB, failCB); }; // Create dir succes var successCB = function (entry) { root = entry; if (dirs.length > 0) { createDir(dirs.pop()); } }; // Create dir fail var failCB = function () { }; createDir(dirs.pop()); } /** * Name : removefile(file) Parameters : file Description : Get file. so the file * can be removed */ function removefile(file) { // Get file {"DI/Downloads/Projects/nieuw_project/Uploads/cdv_photo_012.jpg" // example} fileSystem.root.getFile(file, { create: false, exclusive: false }, gotRemoveFileEntry, fail_removeFile); } /** * Name : gotRemoveFileEntry(fileEntry) Parameters : fileEntry Description : * remove file from file system */ function gotRemoveFileEntry(fileEntry) { fileEntry.remove(success_removefile, fail_removeFile); } /** * Name : success_removefile(entry) Parameters : entry Description : remove file * succeed */ function success_removefile(entry) { // alert("Removal succeeded"); } /** * Name : fail_removeFile(error) Parameters : error Description : remove file * failed */ function fail_removeFile(error) { setToastAlert(remove_file_fail, no_internet_connection_message_ok, ''); } /** * Name : RemoveDirectory() Parameters : Description : Remove whole directory */ function RemoveDirectory(dir) { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail_get_fs_remove_dir); function fail_get_fs_remove_dir(evt) { // fail to get filessystem } function onFileSystemSuccess(fileSystem) { fileSystem.root.getDirectory(dir, { create: true, exclusive: false }, function (entry) { entry.removeRecursively(function () { // Directory succesfully removed setToastAlert(remove_file_succes, no_internet_connection_message_ok, ''); }, fail_get_fs_remove_dir); }, fail_get_fs_remove_dir); } } /******************************************************************************* * Camera functionality ******************************* * * ******************************************************************************/ // GLOBALS // variable to set die description of a document var description; // variable to submit the form on photo succes var ghref; // Variable to load the page via ajax var gdiv; // Get date en time on server when upload a photo var uploadPhoto = false; // variable to store filename of a photo var filename_photo; // variable to store the uriImage of the photo var storeURIimage; // variable to set pathname of camera file var pathname_camera_file; // Store project path var gprojectpath; // variable to check if it's a photo or file var is_photo = false; /** * Name : setDescription Parameters : value Description : Set description ('user * upload' / 'work order') */ function setDescription(value) { description = value; } /** * Name : getDescription Parameters : - Description : Get description ('user * upload' / 'work order') */ function getDescription() { return description; } /** * Name : capturePhoto Parameters : - Description : Call camera of device and * call uploadToServer on succes */ function capturePhoto(description, href, div, projectpath) { // Is photo is_photo = true; // Set description setDescription(description); // Set current form ghref = href; // Set div where ajax load his page gdiv = div; // Store projectname gprojectpath = projectpath; // set boolean to get date on the server side uploadPhoto = true; // Open camera application on device (small picture) // navigator.camera.getPicture(uploadToServer, failCamera_File, { /*quality: // 100,*/ // destinationType: navigator.camera.DestinationType.FILE_URI, sourceType : // Camera.PictureSourceType.CAMERA, targetWidth: 1000/*, targetHeight: // 1000*/}); // Open camera application on device // navigator.camera.getPicture(function(){alert('camera test')}, // failCamera_File, { /* * navigator.camera.getPicture(uploadToServer, failCamera_File, { quality: * 100, sourceType: navigator.camera.PictureSourceType.CAMERA, mediaType: * navigator.camera.MediaType.PICTURE, destinationType: * Camera.DestinationType.FILE_URI, correctOrientation:false/*, * saveToPhotoAlbum:true * * * }); */ // Open camera application on device navigator.camera.getPicture(uploadToServer, failCamera_File, { quality: 100, destinationType: Camera.DestinationType.FILE_URI, sourceType: Camera.PictureSourceType.CAMERA, targetWidth: 1000, correctOrientation: false, targetHeight: 1000 }); } /** * Name : capturePhoto Parameters : id Description : Call camera of device and * call uploadToServer on succes */ var photoId; function capturePhotoOnly(id) { // Store div to place photo in photoId = id; // navigator.camera.getPicture(getPicture, failCamera_File, { quality: 50, // destinationType: Camera.DestinationType.DATA_URL // }); // Open camera application on device navigator.camera.getPicture(getPicture, failCamera_File, { quality: 50, destinationType: Camera.DestinationType.DATA_URL, sourceType: Camera.PictureSourceType.CAMERA, targetWidth: 1000, correctOrientation: false, targetHeight: 1000 }); } /** * Name : getPicture Parameters : - Description : Call camera of device and call * getPicture on succes */ function getPicture(imageData) { $('#' + photoId).css('background-image', 'url(data:image/png;base64,' + imageData + ')'); $('#' + photoId + '_1').val(imageData); } /** * Name : captureFile Parameters : - Description : Call file explorer and let * the user upload a file from the device */ function captureFile(description, href, div) { // No photo ( is file) is_photo = false; // Set description setDescription(description); // Set current form ghref = href; // Set div where ajax load his page gdiv = div; // Open camera explorer on the device navigator.camera.getPicture(uploadToServer, failCamera_File, { quality: 100, destinationType: navigator.camera.DestinationType.NATIVE_URI, sourceType: Camera.PictureSourceType.PHOTOLIBRARY }); } /** * Name : getFilename Parameters : - Description : Get the fullpath name of the * file */ function getFilename(imageURI) { window.resolveLocalFileSystemURI(imageURI, onResolveSuccess, fail_getfilename); } /** * Name : onResolveSuccess Parameters : - Description : Get the fullpath name of * the file */ function onResolveSuccess(fileEntry) { // Upload the file to the server uploadToServer(fileEntry.fullPath); } /** * Name : fail_getfilename Parameters : - Description : Fail to get the fullpath * name of the file */ function fail_getfilename(e) { // fail } /** * Name : CopyFile(entry) Parameters : entry Description : Copy file to other * directory on the device */ function CopyFile(entry) { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSys) { fileSys.root.getDirectory(pathname_camera_file, { create: true, exclusive: false }, function (directory) { entry.moveTo(directory, filename_photo, CopySucces, CopyError); }, CopyError); }, CopyError); } /** * Name : CopyError(entry) Parameters : entry Description : Error callback when * copy failed */ function CopyError(entry) { // Copy error } /** * Name : CopySucces(entry) Parameters : entry Description : Succed callback * when copy succeed */ function CopySucces(entry) { // Copy succeed } /** * Name : uploadToServer(imageURI) Parameters : imageURI Description : Upload * file to server */ function uploadToServer(imageURI) { // Check if there is internet connection if (Online) { // Progress of download progress_element = document.getElementById('progress_bar'); progress_element_con = document.getElementById('progress_container'); // Show progress bar progress_element_con.style.display = "block"; // Show loader $.mobile.showPageLoadingMsg(); // Set flag to false (upload active) upload_file = false; var options = new FileUploadOptions(); options.fileKey = "file"; var filename = imageURI.substr(imageURI.lastIndexOf('/') + 1); // Remove the url parameters from the filename if present var indexOfUrlParamStart = filename.indexOf('?'); if (indexOfUrlParamStart > -1) { filename = filename.substr(0, indexOfUrlParamStart); } options.fileName = filename; // Check if it's a photo or file if (uploadPhoto) { // It's a photo // Set mimetype options.mimeType = "image/jpeg"; } else { // It's a file // Set mimetype options.mimeType = getMimeType(options.fileName); } // $_POST parameters var params = new Object(); params.arg1 = options.fileKey; params.arg2 = getDescription(); // Check if it's a photo or file if (uploadPhoto) { params.arg3 = '1'; } else { params.arg3 = '0'; } // set to default value; uploadPhoto = false; // Set parameters options.params = params; // Create filetransfer object var ft = new FileTransfer(); // Copy filetransfer object to abort the download; fileTransfer = ft; // Check if the progress bar excist ( login screen doesn't have a // progress bar) if ((progress_element_con != null) || (progress_element != null)) { // Progress of upload ft.onprogress = function (progressEvent) { if (progressEvent.lengthComputable) { // Calculate the loaded % of loaded file value_progresss = Math.floor(progressEvent.loaded / progressEvent.total * 100); // Set width of div(progress bar) progress_element.style.width = value_progresss + "%"; } else { // loadingStatus.increment(); } }; } var UserAgent; // Check if device is IOS and manipulate the user agent if (navigator.userAgent.indexOf('MTINFO_APP_IOS') !== -1) { UserAgent = 'MTINFO_APP_IOS'; } else { UserAgent = navigator.userAgent; } // Upload image to server ft .upload(imageURI, getBaseURL() + "?id=" + getURLParam('id') + "&href=app/include/upload_photo.php&" + "latitude=" + GeoLat + "&longitude=" + GeoLon + "&heading=" + GeoHead + "&USER_AGENT=" + UserAgent, succesUpload, failUpload, options); } else { setToastAlert(no_internet_connection_message, no_internet_connection_message_ok); } // Only copy when it's a photo from the camera if (is_photo) { // Get filename of photo filename_photo = imageURI.substr(imageURI.lastIndexOf('/') + 1); // Store url image storeURIimage = imageURI; // Check if there is internet connection if (!Online) { // Default value is_photo = false; // Set pathname pathname_camera_file = "DI/Camera_uploads"; // Copy photo to other directory only when it's a picture window.resolveLocalFileSystemURI(imageURI, CopyFile, CopyError); // Set alert that picture is stored locally setToastAlert(no_internet_connection_message + ". " + no_internet_camera, no_internet_connection_message_ok); } } } /** * Name : win(r) Parameters : r Description : Callback upload image onsucces */ function succesUpload(r) { // Callback on succes // Hide loader $.mobile.hidePageLoadingMsg(); // Set width of div(progress bar) progress_element.style.width = "0%"; // Show progress bar progress_element_con.style.display = "none"; // Set flag to true (no upload active) upload_file = true; // Only copy when it's a photo from the camera if (is_photo) { // Did we get a new filename from server? if (r.response.length > 0) { filename_photo = r.response; } // Default value is_photo = false; // Set pathname pathname_camera_file = gprojectpath; // Copy photo to other directory only when it's a picture window.resolveLocalFileSystemURI(storeURIimage, CopyFile, CopyError); } // refresh page ajax_post(getProjectName('return') + "&is_upload=true", getProjectId(), "?id=" + getURLParam('id') + "&href=" + ghref + "", gdiv); // ajax_post('', getProjectId(),"?id=" + getURLParam('id') + "&href=" + // ghref + "", gdiv); } /** * Name : failUpload(error) Parameters : error Description : Callback upload * image fail */ function failUpload(error) { // Callback on error console.log(error); // Default value is_photo = false; // Set pathname pathname_camera_file = "DI/Camera_uploads"; // Set alert that picture is stored locally setToastAlert(upload_failed.toUpperCase() + ". " + no_internet_camera, no_internet_connection_message_ok); } /** * Name : failCamera_File(error) Parameters : error Description : Callback * camera or file open fail */ function failCamera_File(error) { // Callback on error // alert('Camera error: ' + error); } /** * Name : getBaseURL() Parameters : - Description : Get base url */ function getBaseURL() { var url = location.href; // entire url including querystring - also: // window.location.href; var baseURL = url.substring(0, url.indexOf('/', 14)); baseURL += location.pathname; // Could be a release candidate // Root Url for domain name return baseURL; } /** * Name : getMimeType() Parameters : filename Description : Get mimetype of file */ function getMimeType(filename) { var result = ''; // Get extension of file var split_name = filename.split('.'); var ext = split_name[split_name.length - 1]; switch (ext) { case 'pdf': result = 'application/pdf'; break; case 'doc': result = 'application/msword'; break; case 'docx': result = 'application/msword'; break; case 'odt': result = 'application/vnd.oasis.opendocument.text'; break; case 'ods': result = 'application/vnd.oasis.opendocument.spreadsheet'; break; case 'xls': result = 'application/vnd.ms-excel'; break; case 'mp3': result = 'audio/mpeg'; break; case 'mp4': result = 'video/mp4'; break; case 'txt': result = 'application/msword'; break; case 'jpg': result = 'image/jpeg'; break; case 'jpeg': result = 'image/jpeg'; break; case 'png': result = 'image/png'; break; case 'gif': result = 'image/gif'; break; case 'csv': result = 'text/csv'; break; case 'html': result = 'text/html'; break; case 'flv': result = 'video/x-flv'; break; case 'mpg': result - 'video/mpeg'; break; case 'avi': result - 'video/x-msvideo'; break; case 'wma': result = 'audio/x-ms-wma'; break; default: result = "not supported"; break; } return result; } /******************************************************************************* * GPS functionality ******************************** * * ******************************************************************************/ // GLOBALS // variable to set the latitude var GeoLat = '0'; // variable to set the longitude var GeoLon = '0'; // variable to set the heading var GeoHead = '0'; // variable tom set GPS message var GpsMessage; // variable to get GPS info var watchID; // variable to get GPS info for the free signin app var watchIdSignin = -1; // variable to enable GPS message var enableGpsMessage; /** * Name : setGPS(id) Parameters : id Description : Set GPS to hidden input to * parse with a form */ function setGPS(id) { // Set GPS info in hidden input type to parse in the form to upload a // comment document.getElementById(id).value = GeoLat + ";" + GeoLon; } /** * Name : setGpsMessage(msg) Parameters : msg Description : Set GPS message when * GPS is turned off or weak range */ function setGpsMessage(msg) { // Copy GPs message to global GpsMessage = msg; } /** * Name : onSuccessGeo(position) Parameters : position Description : Get the GPS * information when user wants to take a photo */ var GeoLat_prev = -1; var GeoLon_prev = -1; function onSuccessGeo(position) { // Set GPS indicator (instruction App) $('#' + connection_type_id + '_gps').css('background-image', 'url(app/html/images/app/gps_indicator_on.png)'); // Copy coordinates to Globals GeoLat = position.coords.latitude; GeoLon = position.coords.longitude; GeoHead = position.coords.heading; // Convert to string var GeoLon_to_string = String(GeoLon); var GeoLat_to_string = String(GeoLat); // Cut the coordiantes var GeoLat_cut = GeoLat_to_string.substring(0, 7); var GeoLon_cut = GeoLon_to_string.substring(0, 6); // Only store when GPS coordinates are changed if ((GeoLat_prev != GeoLat_cut) || (GeoLon_prev != GeoLon_cut)) { ajax_post(getGeoLat(), getGeoLon(), "?id=" + getURLParam('id') + "&href=app/di_app_projects/store_gps.php", '', 0); } // Store gps coordinates GeoLat_prev = GeoLat_cut; GeoLon_prev = GeoLon_cut; } /** * Name : onSuccessGeoFreeSignin(position) Parameters : position Description : * Get the GPS information */ function onSuccessGeoFreeSignin(position) { // Set GPS indicator (instruction App) // $('#' + connection_type_id + '_gps').css('background-image', // 'url(app/html/images/app/gps_indicator_on.png)'); // Copy coordinates to Globals GeoLat = position.coords.latitude; GeoLon = position.coords.longitude; GeoHead = position.coords.heading; // Send to database } /** * Name : onSuccessGeoRealtime(position) Parameters : position Description : Get * the GPS information to show a marker in the map of the realtime status */ // Store the lat en lon values var realtimeLat = '-'; var realtimeLon = '-'; function onSuccessGeoRealtime(position) { // Set GPS indicator (realtime App) $('#' + connection_type_id + '_gps').css('background-image', 'url(app/html/images/app/gps_indicator_on.png)'); realtimeLat = position.coords.latitude; realtimeLon = position.coords.longitude; } /** * Name : locationLat(position) Parameters : position Description : Get * the GPS information to show a marker in the map of the location app */ var gpsEnable = false; function onSuccessGeoLocation(position) { // Set GPS indicator (realtime App) $('#connection_type_device_types_gps').css('background-image', 'url(app/html/images/app/gps_indicator_on.png)'); $('#connection_type_devices_gps').css('background-image', 'url(app/html/images/app/gps_indicator_on.png)'); $('#connection_type_location_map_gps').css('background-image', 'url(app/html/images/app/gps_indicator_on.png)'); realtimeLat = position.coords.latitude; realtimeLon = position.coords.longitude; // Gps is enabled gpsEnable = true; } /** * Name : onErrorLocation() Parameters : error Description */ function onErrorLocation(error) { // Clear GPS indicator $('#connection_type_device_types_gps').css('background-image', 'url(app/html/images/app/gps_indicator_off.png)'); $('#connection_type_devices_gps').css('background-image', 'url(app/html/images/app/gps_indicator_off.png)'); $('#connection_type_location_map_gps').css('background-image', 'url(app/html/images/app/gps_indicator_off.png)'); // Gps is disabled gpsEnable = false; } /** * Name : getGeoLat() Parameters : - Description : return the latitude value */ function getGeoLat() { return GeoLat; } /** * Name : getGeoLon() Parameters : - Description : return the longitude value */ function getGeoLon() { return GeoLon; } /** * Name : getGeoLon() Parameters : - Description : return the longitude value */ function getGeoHead() { return GeoHead; } /** * Name : getrealtimeLon(position) Parameters : - Description : return the * latitude value */ function getrealtimeLat() { return realtimeLat; } /** * Name : getrealtimeLon(position) Parameters : - Description : return the * longitude value */ function getrealtimeLon() { return realtimeLon; } /** * Name : onErrorGeo() Parameters : error Description : Set GPS information to * default when user wants to take a photo and GPS is not active */ function onErrorGeo(error) { // Clear GPS indicator $('#' + connection_type_id + '_gps').css('background-image', 'url(app/html/images/app/gps_indicator_off.png)'); // No GPS if (enableGpsMessage) { // setToastAlert(GpsMessage,'OK'); enableGpsMessage = false; } } /** * Name : resumeApp() Parameters : - Description : Called when the App is to the * front */ function resumeApp() { // Get GPS coordinates when GPS changed watchID = navigator.geolocation.watchPosition(onSuccessGeo, onErrorGeo, { timeout: 7000, enableHighAccuracy: true }); } /** * Name : pauseApp() Parameters : - Description : Called when the App is to the * background or the power off */ function pauseApp() { // Stop getting GPS coordinates navigator.geolocation.clearWatch(watchID); } /******************************************************************************* * Comment box *********************************** * * ******************************************************************************/ var prev_id = 'undefined'; var prev_imagePath = '0'; var prev_nrOfComments = '0'; var prev_comment_click; /** * Name : commentBox(id,imagePath, nrOfComments) Parameters : - id - imagePath - * nrOfComments Description : Create a comment box */ function showCommentBox(id, imagePath, nrOfComments) { // Set border and change backgroundColor $('#' + id).css('border-left', '2px solid rgb(0,158,224)'); $('#' + id).css('border-right', '2px solid rgb(0,158,224)'); $('#' + id).css('border-top', '2px solid rgb(0,158,224)'); $('#' + id).css('border-bottom', 'none'); $('#' + id).css('background-color', 'rgb(185,228,255)'); // Set comment to top of screen scrollToTop(document.getElementById(id)); // Change arrow to up document.getElementById("img_arrow_" + id).src = imagePath + "up_arrow.png"; // Show submit comment box document.getElementById('comment_' + id).style.display = 'block'; // Show comments of user document.getElementById('loaded_commments_' + id).style.display = 'block'; } /** * Name : setOpenedCommentbox(id) Parameters : - id Description : Store * commentbox id */ var idOpenCommentbox; function setOpenedCommentbox(id) { idOpenCommentbox = id; } /** * Name : setImagePath(imagepath) Parameters : - imagePath Description : Store * imagepath */ var storeImagePath; function setImagePath(imagepath) { storeImagePath = imagepath; } /** * Name : getImagepath() Parameters : - Description : Get imagepath */ function getImagepath() { return storeImagePath; } /** * Name : showCommentBoxAfterUpload() Parameters : - Description : call * showCommentBox() with paramaters */ function showCommentBoxAfterUpload() { showCommentBox(idOpenCommentbox, storeImagePath, '0'); } /** * Name : deleteCommentBox(id,imagePath,nrOfComments) Parameters : - id - * imagePath - nrOfComments Description : Delete a comment box */ function deleteCommentBox(id, imagePath, nrOfComments) { // Delete previous comment prev_id = 'undefined'; prev_imagePath = '0'; prev_nrOfComments = '0'; // Change arrow to down document.getElementById("img_arrow_" + id).src = imagePath + "down_arrow.png"; // Get element of selected document box var document_box_element = document.getElementById(id); // Delete backgroundColor, border and set old bottom border $('#' + id).css('border-left', 'none'); $('#' + id).css('border-right', 'none'); $('#' + id).css('border-top', 'none'); $('#' + id).css('border-bottom', '1px solid lightgrey'); $('#' + id).css('background-color', 'white'); // Hide submit comment box document.getElementById('comment_' + id).style.display = 'none'; // Hide comments of user document.getElementById('loaded_commments_' + id).style.display = 'none'; } /** * Name : storeCommentClicked(counter) Parameters : - counter Description : * Store which comment is clicked */ function storeCommentClicked(counter) { prev_comment_click = counter; } /** * Name : getstoreCommentClicked() Parameters : - Description : Get the clicked * comment */ function getstoreCommentClicked() { return prev_comment_click; } /** * Name : storeComment(id,imagePath, nrOfComments) Parameters : - id - imagePath - * nrOfComments Description : Store comment info */ function storeComment(id, imagePath, nrOfComments) { // Store last uploaded comment info to open tne comment prev_id = id; prev_imagePath = imagePath; prev_nrOfComments = nrOfComments; } /******************************************************************************* * Connection type ********************************* * * ******************************************************************************/ /** * Name : setConnectionTypeIcon() Parameters : - Description : Check connection * type and set communication icon in the header */ function setConnectionTypeIcon(id, imagespath) { // Get connection type var networkState = navigator.connection.type; // Get previous background image var str = $('#' + id + '_connection').css('background-image'); // Check network state and set correct connection image switch (networkState) { case Connection.WIFI: // Check if background images is already set if (str.search("wifi.png") == -1) { $('#' + id + '_connection').css('background-image', 'url(' + imagespath + 'app/wifi.png)'); // Normal background-color $('.div_header').css('background-color', 'rgb(243,152,0)'); if (RS3000) { // hide overlay $('#rsoverlay').css('display', 'none'); } } break; case Connection.CELL: // Check if background images is already set if (str.search("4G.png") == -1) { $('#' + id + '_connection').css('background-image', 'url(' + imagespath + 'app/data_on.png)'); // Normal background-color $('.div_header').css('background-color', 'rgb(243,152,0)'); } break; case Connection.CELL_2G: // Check if background images is already set if (str.search("2G.png") == -1) { $('#' + id + '_connection').css('background-image', 'url(' + imagespath + 'app/data_on.png)'); // Normal background-color $('.div_header').css('background-color', 'rgb(243,152,0)'); if (RS3000) { // hide overlay $('#rsoverlay').css('display', 'none'); } } break; case Connection.CELL_3G: // Check if background images is already set if (str.search("3G.png") == -1) { $('#' + id + '_connection').css('background-image', 'url(' + imagespath + 'app/data_on.png)'); // Normal background-color $('.div_header').css('background-color', 'rgb(243,152,0)'); if (RS3000) { // hide overlay $('#rsoverlay').css('display', 'none'); } } break; case Connection.CELL_4G: // Check if background images is already set if (str.search("4G.png") == -1) { $('#' + id + '_connection').css('background-image', 'url(' + imagespath + 'app/data_on.png)'); // Normal background-color $('.div_header').css('background-color', 'rgb(243,152,0)'); if (RS3000) { // hide overlay $('#rsoverlay').css('display', 'none'); } } break; case Connection.NONE: // Check if background images is already set if (str.search("no_connection.png") == -1) { $('#' + id + '_connection').css('background-image', 'url(' + imagespath + 'app/no_connection.png)'); // Offline background-color $('.div_header').css('background-color', 'rgb(188,118,15)'); if (RS3000) { // Change text $('#rsoverlay').html(no_internet_connection_message); // show overlay $('#rsoverlay').css('display', 'block'); } } break; default: // Check if background images is already set if (str.search("none") == -1) { $('#' + id + '_connection').css('background-image', 'none'); } break; } } /******************************************************************************* * Realtime App ************************************ * * ******************************************************************************/ // Global variable to store the coordinates and name of the devices var Coordinates = []; // Global var to set interval to refresh the realtime page var realTimeInterval = 0; // Global to countdown to refresh the page var secondTimmer = 10; // Global var to store the opened devices (realtime status info) var openedDevices = []; // initialise an empty array (dynamic array) // Global var to store the opened Materieel (realtime devices) var openedMaterieel = []; // Dynamic associative array to store the selected devices of the realtime app var devices_checked = {}; // Array to store realtime status info to show in the toast alert var toastMessage = []; // variable only bound markers the firsttime or when an new coordinate is added var bounding = true; // The Google map var map; // Number of devices (number coordinates) var number_of_devices; // Variable to store the clicked marker number var markerMsg; // Array for the markers var markerOne = []; // Variable to check all lances when user selects projects var check_all_lances = true; // Check if use ris in RS300 app var RS3000 = false; // To store the scroll position var scrollPostition; /** * Name : HomeControl(controlDiv, map) Parameters : - controlDiv - map * Description : Create Own location button */ function HomeControl(controlDiv, map) { // Set CSS styles for the DIV containing the control // Setting padding to 5 px will offset the control // from the edge of the map controlDiv.style.padding = '5px'; // Set CSS for the control border var controlUI = document.createElement('div'); controlUI.style.backgroundColor = 'white'; controlUI.style.borderStyle = 'solid'; controlUI.style.borderWidth = '1px'; controlUI.style.cursor = 'pointer'; controlUI.style.textAlign = 'center'; controlDiv.appendChild(controlUI); // Set CSS for the control interior var controlText = document.createElement('div'); controlText.style.fontFamily = 'Arial,sans-serif'; controlText.style.fontSize = '12px'; controlText.style.paddingLeft = '4px'; controlText.style.paddingRight = '4px'; controlText.innerHTML = own_gps_location; controlUI.appendChild(controlText); // onclick listener google.maps.event.addDomListener(controlUI, 'click', function () { // Center to own location map.setZoom(15); map.setCenter(markerOne[0].getPosition()); }); } var maps_loaded = false; var mapInterval = true; /** * Name : initializeMap() Parameters : - Description : Initialize the map */ function initializeMap() { // Create map var maps = new GoogleMap(Coordinates); // Coordinates is an global variable // where the coordinates and name of // the selected devices are stored maps.initialize(); // Hide spinner when maps is fully loaded google.maps.event.addListenerOnce(map, 'idle', function () { $.mobile.hidePageLoadingMsg(); maps_loaded = true; // Default mapInterval is true, set to false when there's no need to refresh the map if (mapInterval) { // Hide overlay $('#rsoverlay').css('display', 'none'); // Change color of text $('#rsoverlay').css('color', 'red'); // Clear previous interval window.clearInterval(realTimeInterval); // Show timer direct for the first time refreshRealtimer('Map'); realTimeInterval = setInterval(function () { refreshRealtimer('Map', '?id=' + getURLParam('id') + '&href=app/di_app_realtime/a_get_info_realtime.php'); }, 1000); } }); } /** * Name : loadGoogleMapsScript() Parameters : - Description : Load javascript * asynchronous */ function loadGoogleMapsScript(language) { if ($('script[src^="https://maps.googleapis.com"]').length == 0) { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&&language=' + language + '&sensor=false&' + 'callback=initializeMap'; document.body.appendChild(script); } else { initializeMap(); } } /** * Name : GoogleMap(coordinates_array) Parameters : coordinates_array[][] * coordinates_array[x][0] = latitude coordinates_array[x][1] = longitude * coordinates_array[x][2] = device name coordinates_array[x][3] = icon * Description : Create a map and mark the devices on the map */ var maxLat = 90; var minLat = -90; var maxLon = 180; var minLon = -180; function GoogleMap(coordinates_array) { var zoomValue, latitude, longitude; // Initialize the Google maps this.initialize = function () { var map = showMap(); addMarkersToMap(map, coordinates_array); } // Show the Google maps in the div var showMap = function () { // Default values zoomValue = 3; latitude = 54; longitude = 25; // Is array ? if (coordinates_array[0] instanceof Array) { // Check for valid coordinates if ((coordinates_array[0][0] != '-') && (coordinates_array[0][1] != '-')) { // Check if gps coordinates are valid if ((coordinates_array[0][0] <= maxLat) && (coordinates_array[0][0] >= minLat) && (coordinates_array[0][1] <= maxLon) && (coordinates_array[0][1] >= minLon)) { // Valid gps zoomValue = 15; latitude = coordinates_array[0][0]; longitude = coordinates_array[0][1]; } } } if (map) { for (var key in markerOne) { // Delete all devices from map markerOne[key].setMap(null); delete markerOne[key]; } map.setCenter(new google.maps.LatLng(latitude, longitude)); map.setZoom(zoomValue); // Use the original instance var gmapsInstance = $('#google_maps_instance'); if (gmapsInstance.length > 0) { $('#google_maps').replaceWith(gmapsInstance); gmapsInstance.css('display', 'initial').attr('id', 'google_maps'); } $.mobile.hidePageLoadingMsg(); } else { var mapOptions = { zoom: zoomValue, center: new google.maps.LatLng(latitude, longitude), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("google_maps"), mapOptions); // Disable fullscreen in streetview due to stability issues on Android and Windows var streetview = map.getStreetView(); streetview.setOptions({ fullscreenControl: false }); // Create the DIV to hold the control and // call the HomeControl() constructor passing // in this DIV. var homeControlDiv = document.createElement('div'); var homeControl = new HomeControl(homeControlDiv, map); homeControlDiv.index = 1; map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv); } return map; } } function storeMapInstance() { var mapsDiv = $('#google_maps'); if (mapsDiv.length > 0) { mapsDiv.attr('id', 'google_maps_instance').css('display', 'none').appendTo(mapsDiv.parents('#div_mainscreen')); } } /** * Name : addMarkersToMap(map ,coordinates_array) Parameters : map * ,coordinates_array[][] coordinates_array[x][0] = latitude * coordinates_array[x][1] = longitude coordinates_array[x][2] = device name * coordinates_array[x][3] = icon Description : Add marker on the map */ // Variable to detect double click var dblclick = false; var addMarkersToMap = function (maps, coordinates_array) { // Is array ? if (coordinates_array instanceof Array) { // Number of devices(zkl etc) number_of_devices = coordinates_array.length; // To Zoom out when there are more devices var mapBounds = new google.maps.LatLngBounds(); // Foreach loop for (var key in coordinates_array) { // Check if there are coordinates if ((coordinates_array[key][0] != '-') && (coordinates_array[key][1] != '-')) { // Check if gps coordinates are valid if ((coordinates_array[key][0] <= maxLat) && (coordinates_array[key][0] >= minLat) && (coordinates_array[key][1] <= maxLon) && (coordinates_array[key][1] >= minLon)) { // Create marker var latitudeAndLongitudeOne = new google.maps.LatLng(coordinates_array[key][0], coordinates_array[key][1]); markerOne[key] = new google.maps.Marker({ position: latitudeAndLongitudeOne, map: maps, title: "" + key + "", icon: coordinates_array[key][3] }); google.maps.event.addListener(markerOne[key], "dblclick", function (e) { // Zoom to clicked marker maps.setZoom(15); maps.setCenter(markerOne[this.title].getPosition()); // abuse title to get the marker number // Double click active dblclick = true; }); google.maps.event.addListener(markerOne[key], "click", function (e) { // abuse title to get the marker number markerMsg = this.title; // create delay because else the onclick event of the button of // the toaster will be directly fired. setTimeout(function () { // Check if user click dubbel if (!dblclick) { if (portal) { // Portal app setToastAlert(toastMessage, no_internet_connection_message_ok, '', '', '', '300'); } else { // Normal app setToastAlert(toastMessage, no_internet_connection_message_ok, '', '', '', '150'); } } }, 400); // Double click to default value dblclick = false; }); // Only add the coordinates to the map bounds if they belong to an actual device and not the user location marker if (coordinates_array[key][3].indexOf('own_gps.png') === -1) { mapBounds.extend(latitudeAndLongitudeOne); } } } } // Check if there are more then one devices if (number_of_devices > 1) { if (bounding) { // Zooming out the map to show all markers maps.fitBounds(mapBounds); } } } } /** * Name : refreshMarkersOfExistingMap() Parameters : coordinates_array[][] * coordinates_array[x][0] = latitude coordinates_array[x][1] = longitude * coordinates_array[x][2] = device name coordinates_array[x][3] = icon * Description : Add marker to excisting map */ function refreshMarkersOfExistingMap(coordinates_array) { // loop through all the coordinates for (var key in coordinates_array) { try { // Delete all devices from map markerOne[key].setMap(null); } catch (e) { } } // Check if there is an coordinate added if (number_of_devices != coordinates_array.length) { // Coordinate add bounding = true; } else { // No coordinate add bounding = false; } /* * var mapOptions = { zoom: map.getZoom(), center: map.getCenter(), * mapTypeId: map.getMapTypeId() } */ // Add devices to the map addMarkersToMap(map, coordinates_array); } /** * Name : refreshRealtimer(id) Parameters : - id (div element id) - refreshpage * (page to refresh) Description : countdown timer and refresh the page when * timer is 0 */ function refreshRealtimer(id, refreshpage) { // Check internet connection if (Online) { if (secondTimmer < 1) { // load spinner in the tab $("#countdown_" + id).html(''); // Set back to default // secondTimmer = 10; // Clear interval window.clearInterval(realTimeInterval); // refresh page // parse javascript so it can be send by ajax post var jsonStringRefresh = JSON.stringify(devices_checked); switch (id) { case 'Map': if (RS3000) { // Call a_get_fake_map.php to check if the project is still // released ajax_post('', '', "?id=" + getURLParam('id') + "&href=app/di_app_rs/a_get_fake_map.php", 'rs_page3_fake_content'); } else { ajax_post( 'refresh_page', encodeURIComponent(jsonStringRefresh), "?id=" + getURLParam('id') + "&href=app/di_app_realtime/a_get_info_realtime.php", ''); } break; case 'Realtime': // Check if user use the RS3000 App if (RS3000) { ajax_post('', getPeriodId(), "?id=" + getURLParam('id') + "&href=app/di_app_rs/a_get_rs.php", 'rs_page3_content'); } else { ajax_post( encodeURIComponent(refreshpage), encodeURIComponent(jsonStringRefresh), "?id=" + getURLParam('id') + "&href=app/di_app_realtime/parse_devices_array_in_php.php", 'loaded_page'); } break; case 'Switch': ajax_post('', getPeriodId(), "?id=" + getURLParam('id') + "&href=app/di_app_rs/a_get_switch.php", 'rs_page3_content'); break; case 'SignList': // #40 Stores the expanded sign info items' ids storeExpandedSignInfoItems(); ajax_post(getProjectName('return'), getProjectId(), "?id=" + getURLParam('id') + "&href=app/di_app_projects/a_get_signinlist.php", "loaded_page"); break; default: break; } } else { // show secondTimmer in div $("#countdown_" + id).html(secondTimmer); // Decrement second timer secondTimmer--; } } else { // Clear previous interval window.clearInterval(realTimeInterval); // Set alert that picture is stored locally setToastAlert(no_internet_connection_message, no_internet_connection_message_ok); } } /** * Name : calculateTotalTime(time1, time2, mode) Parameters : - time1 - time2 - * mode Description : Calculate difference between 2 times */ function calculateTotalTime(time1, time2, mode) { var time_1 = 0; var time_2 = 0; var time_dif; var diff_hours; var diff_minutes; // Substract calculate diff date/time mode if (mode == "datetime") { // Check if there is a time set if ($('#' + time1).val().length != 0) { // Get start date and time time_1 = $('#' + time1).val(); // Change format (because Date object (js) works like this) var date_time_1 = time_1.split(" "); // date_time_1[0] = date // date_time_1[1] = time var date_1 = date_time_1[0].split("-"); time_1 = date_1[1] + "/" + date_1[2] + "/" + date_1[0] + " " + date_time_1[1]; } // Check if there is a time set if ($('#' + time2).val().length != 0) { // Get end date and time time_2 = $('#' + time2).val(); // Switch the day and month (because Date object works like this) var date_time_2 = time_2.split(" "); // date_time_2[0] = date // date_time_2[1] = time var date_2 = date_time_2[0].split("-"); time_2 = date_2[1] + "/" + date_2[2] + "/" + date_2[0] + " " + date_time_2[1]; } // Check if both times are set if ((time_1 != 0) && (time_2 != 0)) { // Create Date objects var dt_start = new Date(time_1); var dt_end = new Date(time_2); // Substract start and end date time_dif = dt_end - dt_start; // time_dif is in ms. convert hours diff_hours = parseInt(time_dif / 3600000); // create hours diff_minutes = (time_dif - (diff_hours * 3600000)) / 60000; // create // minutes // Check if diff time is negative if ((diff_minutes < 0) || (diff_hours < 0)) { return -1; } else { // Check if there must be a 0 before the minutes if (diff_minutes < 10) { diff_minutes = '0' + diff_minutes; } } return diff_hours + ":" + diff_minutes; } else { // No calculation return -1; } } // Substract pause mode if (mode == "pause") { // Check if total time is not negative if (time2 != -1) { // Split hours en minuts var hour_min_pause = time1.split(":"); var hour_min_total = time2.split(":"); // Get total hours (total hours - pause hours) var hour_total = hour_min_total[0] - hour_min_pause[0]; // Check if total hours is not negative if (hour_total >= 0) { // Get total minutes (total min - pause min) var min_total = hour_min_total[1] - hour_min_pause[1]; // Check if minutes are negative if (min_total < 0) { hour_total--; min_total = 60 + min_total // min_total is negative. so add // it instead of substract } // Check if there must be a 0 before the minutes if (min_total < 10) { min_total = '0' + min_total; } return hour_total + ':' + min_total; } else { // negative hour value return -1; } } else { // Total time is negative (end - start time) return -1; } } } var searchFlagRT = false; /** * Name : searchDevices(search) Parameters : - search (div element id) - * imagePath Description : search and show the device */ function searchDevices(search, imagePath) { search = search.toUpperCase(); if (searchFlagRT) { if (document.querySelectorAll) { // Get current page var page = getCurrentSuBPage(); if (page.indexOf("a_get_realtime") != -1) { // Search in realtime tab // Get the elements var box_element = document.querySelectorAll(".document_box"); var realtime_status_info_element = document .querySelectorAll('.realtime_status_info'); var text_element = document .querySelectorAll(".document_text_center"); var drop_down_image_element = document .getElementsByName('drop_down_image'); // Check if search is called because the page is refreshed // (every 10 seconds) if (imagePath != '-1') { // Loop through all elements for (var i = 0; i < realtime_status_info_element.length; i++) { if (realtime_status_info_element[i].style.display == 'block') { // Close all realtime status info boxes realtime_status_info_element[i].style.display = 'none'; drop_down_image_element[i].src = imagePath + "/app/down_arrow.png"; // Get lance id var lance_id = drop_down_image_element[i].id .split("_"); // Delete from array (devices that are opened) delete openedDevices[lance_id[2]]; } } } // Loop through all elements for (var i = 0; i < box_element.length; i++) { // Skip first two elements (PROJECTEN, MATERIEEL button) if (i > 1) { text_element[i].innerHTML = text_element[i].innerHTML .toUpperCase(); // Check if string contains another string if (text_element[i].innerHTML.indexOf(search) > -1) { // Match box_element[i].style.display = 'block'; } else { // No match box_element[i].style.display = 'none'; } } } } else if (page.indexOf("a_get_devices") != -1) { // Search in devices tab // Get the elements var sub_document_box_lance_element = document .getElementsByName('sub_document_box_lance'); var document_box_type_lance_element = document .getElementsByName('document_box_type'); var sub_document_box = document .querySelectorAll(".sub_document_box"); var devices_box = document.querySelectorAll(".devices_box"); // Check if the device types must be showed or hide var show = 'none'; if (search == '') { show = 'block'; } // Hide all device types boxes for (var i = 0; i < document_box_type_lance_element.length; i++) { document_box_type_lance_element[i].style.display = show; } // Loop through all lances en check if the must be showed. for (var i = 0; i < sub_document_box_lance_element.length; i++) { sub_document_box_lance_element[i].innerHTML = sub_document_box_lance_element[i].innerHTML .toUpperCase(); // Check if string contains another string if (sub_document_box_lance_element[i].innerHTML .indexOf(search) > -1) { // Match sub_document_box[i].style.display = 'block'; } else { // No match sub_document_box[i].style.display = 'none'; } } // Show the realtime status info box $("[name='sub_document_box_lance']").parent().parent().parent() .css('display', 'block'); } } } } /** * Name : searchProjectsDocuments(searchword) Parameters : - searchword - * selector_1 - selector_2 * * Description : search projects function */ function searchProjectsDocuments(searchword, selector_1, selector_2) { searchword = searchword.toUpperCase(); // Get all elements to search in var searchValues = document.querySelectorAll("." + selector_1); // Get all elements to get the project name var projectNames = document.querySelectorAll("." + selector_2); for (var i = 0; i < searchValues.length; i++) { // Decode var word = htmlspecialchars_decode(projectNames[i].innerHTML); // Check if string contains another string if (word.indexOf(searchword) > -1) { // Match searchValues[i].style.display = 'block'; } else { // No match searchValues[i].style.display = 'none'; } } } /** * Name : htmlspecialchars_decode(str) Parameters : * * Description : htmlspecialchars decode */ function htmlspecialchars_decode(str) { if (typeof (str) == "string") { str = str.replace(/>/ig, ">"); str = str.replace(/</ig, "<"); str = str.replace(/'/g, "'"); str = str.replace(/"/ig, '"'); str = str.replace(/&/ig, '&'); /* must do & last */ } if (typeof (str) == "string") { str = str.replace(/>/ig, ">"); str = str.replace(/</ig, "<"); str = str.replace(/'/g, "'"); str = str.replace(/"/ig, '"'); str = str.replace(/&/ig, '&'); /* must do & last */ } return str; } // To check if the user set his signature var SignatureIsValid; /** * Name : CheckChangesAdministration() Parameters : - * * Description : Check if inputfield changes after signature is set */ function CheckChangesAdministration() { // Check if signature is set if (SignatureIsValid) { // Clear Signature Flag SignatureIsValid = false; // Add image of signature to signature div $('#signature_show_to_user_img').attr('src', 'data: '); // Hide image $('#signature_show_to_user_img').css('display', 'none'); // Clear image in signature $("#sign_div").jSignature("clear"); } } /** * Name : hideMobiscroll() Parameters : - * * Description : Hide the scroller */ function hideMobiscroll(id) { $('#' + id).mobiscroll('hide', true); } /** * Name : onfocusInput(id) Parameters : - * * Description : Focus on input field */ function onfocusInput(id) { // Enable input field (so the user can type again) $('#' + id).attr('readonly', false); // Focus on input field $('#' + id).focus(); } /** * Name : enableCheckChangesAdministration() Parameters : - * * Description : enable the CheckChangesAdministration() function */ // Flag to check if CheckChangesAdministration() must be used var wait_check = true; function enableCheckChangesAdministration() { // Set flag wait_check = true; } // Array to store the question ids var tree = []; // Array to check if project transfer are accepted var accept_project_transfer = []; // Only first time check for project transfers var firsttime_accept_project_transfer = []; /** * Name : AcceptProjectTransfer() Parameters : - * * Description : accept project transfer */ function AcceptProjectTransfer() { var div = document.getElementById('button_54_4'); // Check if div exist (voorblad) if (div) { $("#button_54_4").css('background-color', 'rgb(255,184,100)'); $("#button_54_4_text").html(acceptPrjTransfer_message); } // Store the transfer in the database ajax_post(getProjectId() + '*' + getGeoLat() + ';' + getGeoLon() + '*goedgekeurd', '', "?id=" + getURLParam('id') + "&href=app/include/project_transfer.php", ''); // Store that the accept project transfer accept_project_transfer[getProjectId()] = true; } /** * Name : NotAcceptProjectTransfer() Parameters : - * * Description : accept project transfer */ function NotAcceptProjectTransfer() { // Store the transfer in the database ajax_post(getProjectId() + '*' + getGeoLat() + ';' + getGeoLon() + '*afgekeurd', '', "?id=" + getURLParam('id') + "&href=app/include/project_transfer.php", ''); } // Array to store wich appointments are opened var openedAppointments = new Array(); // initialise an empty array (dynamic // array) var openedAdded = new Array(); // initialise an empty array (dynamic array) /** * Name : ScriptStoreQuestions_script() Parameters : - * * Description : set store flag and make questions readonly for the script */ function ScriptStoreQuestions_script() { // Set 'opgeslagen' flag in db ajax_post(getProjectId(), "script", "?id=" + getURLParam('id') + "&href=app/di_app_projects/store_flag.php", ''); // Make all input fields readonly $('.store').prop('disabled', true); } /** * Name : ScriptStoreQuestions_weco() Parameters : - * * Description : set store flag and make questions readonly for the signlist */ var disable_weco_onclick = {}; function ScriptStoreQuestions_weco() { disable_weco_onclick[getProjectId()] = true; // Set 'opgeslagen' flag in db ajax_post(getProjectId(), "weco", "?id=" + getURLParam('id') + "&href=app/di_app_projects/store_flag.php", ''); // Make all input fields readonly $('.store').prop('disabled', true); } /** * Name : notDeleteItem() Parameters : - * * Description : cancel delete item */ function notDeleteItem() { // Clear load spinner $.mobile.hidePageLoadingMsg(); } /** * Name : deleteItem() Parameters : - * * Description : delete item */ var enquete; var refnr; function deleteItem() { // Delete item ajax_post(refnr, enquete, "?id=" + getURLParam('id') + "&href=app/di_app_projects/delete_item_trash_1.php", ''); } /** * Name : wecoConfirmed() Parameters : - * * Description : weco is confirmed redirect to weco page */ function wecoConfirmed() { ajax_post(weco_enquete, getProjectId(), "?id=" + getURLParam('id') + "&href=app/di_app_projects/a_get_appointmentbook.php", 'loaded_page'); } var weco_enquete; var change_onclick_check_inout = {}; var alreadyConfirmed = {}; var store_i; var buttonText; // own check in button var buttonText_other; // check in button for other user /** * Name : checkMoveTouch(storedCoordinateY , currentCoordinateY, * storedCoordinateX , currentCoordinateX) Parameters : - storedCoordinateY - * currentCoordinateY - storedCoordinateX - currentCoordinateX * * Description : check if user move this finger */ var coordinateY = 0; var coordinateX = 0; function checkMoveTouch(storedCoordinateY, currentCoordinateY, storedCoordinateX, currentCoordinateX) { // Take 2 procent of the width of the screen var moveAccurate = Math.ceil(screen.width * 0.02); // Only for iOS devices if (device.platform == 'iOS') { if (((Math.abs(coordinateY - event.touches[0].clientY)) > moveAccurate) || ((Math.abs(coordinateX - event.touches[0].clientX)) > moveAccurate)) { return true; } return false; } else { return true; } } // function advertisement(id,image){ // //alert(getImagepath() + 'advertisement/' + image); // //$('#' + id).css('background-image', 'url('+ getImagepath() + // 'advertisement/' + image + ')'); // $('#advertisement').css('background-image', // 'url(app/html/images/advertisement/ZKL3000-4_648x391.jpg)'); // } var freeSigninCookie; var mobilenrCookie; var profileCookie; /** * Name : goToStore Parameters : - * * Description : Go to the DI store */ function goToStore() { // Call DI store page loadApp('?id=' + getURLParam('id') + '&href=app/di_store/store_index.php', '-1', '-1'); } // var TimerGpsInterval; // function storeGpsInterval(project_id, mobilenumber, mode){ // if(mode == 1){ // TimerGpsInterval = setInterval(function(){ // alert('gps timer'); // },30000); // }else if(mode == 0){ // clearInterval(TimerGpsInterval); // } // } /** * Name : hideKeyboard Parameters : - * * Description : hide white space */ function hideKeyboard(keyboard) { // Hide white space behind the keyboard $('#' + keyboard).css('display', 'none'); } /** * Name : showKeyboard Parameters : - * * Description : show white space */ function showKeyboard(obj, id, keyboard, extraHeight) { // Show white space behind the keyboard $('#' + keyboard).css('display', 'block'); // Position of div var offset = $(obj).offset().top; // Get scrollTop position var scrollValue = document.getElementById(id).scrollTop; var divheight = $('#' + id).height(); // Check if there is an extra div in the div (instruction app id:upload_scan // div) if (extraHeight) { $('#' + id) .animate( { scrollTop: ((scrollValue + offset) - (divheight / 2) - extraHeight) }, 0); } else { $('#' + id).animate({ scrollTop: ((scrollValue + offset) - (divheight / 2)) }, 0); } } /** * Name : keyboardSpace Parameters : - content - keyboard - extraHeight * * Description : show white space */ function keyboardSpace(content, keyboard, extraHeight) { // /////////////////// When disable keyboardSpace also disbale in the // login.php page // Only for android devices if (device.platform == 'Android') { var text = $('.evaluation_simpletext'); var textarea = $('.evaluation_text'); var set_text = $('.evaluation_set'); var enum_text = $('.evaluation_enum'); // Listeners for al the input text fields text.on("focusin", fin); text.on("focusout", fout); textarea.on("focusin", fin); textarea.on("focusout", fout); set_text.on("focusin", fin); set_text.on("focusout", fout); enum_text.on("focusin", fin); enum_text.on("focusout", fout); // Handler when keyboard is showed (show div) function fin() { // Show white space behind the keyboard showKeyboard(this, content, keyboard, extraHeight); } // Handler when keyboard is hidden (delete div) function fout() { // Hide white space behind the keyboard hideKeyboard(keyboard); } } } // To create event listeners only once for the RS 3000 app var listnersOnceRs = false; var period_time_check = false; // imei of device var imei; /** * Name : setIMEI Parameters : - imei * * Description : store imei */ function setIMEI(imeiCode) { imei = imeiCode; } /** * Name : getIMEI Parameters : - * * Description : get imei */ function getIMEI() { return imei } // var to show the translate message var showTranslateMessage = true; // var to create interval to check if project is released var checkReleaseInterval; // Var to show al the devices (RS3000) var showAllDevices = false; /** * Name : disableBackspace Parameters : - * * Description : disable keyboard backspace event */ function disableBackspace() { // Prevent the backspace key from navigating back. $(document).unbind('keydown').bind( 'keydown', function (event) { var doPrevent = false; if (event.keyCode === 8) { var d = event.srcElement || event.target; if ((d.tagName.toUpperCase() === 'INPUT' && (d.type .toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD' || d.type.toUpperCase() === 'FILE' || d.type.toUpperCase() === 'EMAIL' || d.type.toUpperCase() === 'SEARCH' || d.type .toUpperCase() === 'DATE')) || d.tagName.toUpperCase() === 'TEXTAREA') { doPrevent = d.readOnly || d.disabled; } else { doPrevent = true; } } if (doPrevent) { event.preventDefault(); } }); } /** * Name : disableRefreshF5 Parameters : - * * Description : disable F% refresh event */ function disableRefreshF5() { document.onkeydown = function (e) { return (e.which || e.keyCode) != 116; }; } /** * Name : detectRefreshFromBrowser Parameters : - * * Description : detect if user push the refresh button */ function detectRefreshFromBrowser() { if (window.event) { if (window.event.clientX < 40 && window.event.clientY < 0) { // back button return 1; } else { // refresh button return 2; } } else { if (event.currentTarget.performance.navigation.type == 2) { // back button return 1; } if (event.currentTarget.performance.navigation.type == 1) { // refresh button return 2; } } return 0; } /** * Callback function to store the gps location of an devivce ( location app) */ function storeLocation() { ajax_post(getrealtimeLat() + ',' + getrealtimeLon(), getProjectId(), "?id=" + getURLParam('id') + "&href=app/di_app_location/store_device_location.php", ''); } function openFileOnWindows(path, mimetype) { cordova.plugins.fileOpener2.open( path, mimetype, { error: function (e) { console.log('Error status: ' + e.status + ' - Error message: ' + e.message); }, success: function () { console.log('file opened successfully'); } } ); } function interceptWindowsBackButton(intercept) { if (device.platform == 'windows') { cordova.plugins.WindowsWebview.interceptBackButton(intercept); } } function preventGhostClick(event) { // Prevent ghost click on iOS event.preventDefault(); } /** * The ids of the expanded sign items * @type {string[]} */ var expandedSignItems = []; var signItemForms = []; /** * Stores the ids of the expanded sign info items in order for them to be restored after a refresh */ function storeExpandedSignInfoItems() { if (getScriptOrSignList() == 'SignList') { expandedSignItems = []; signItemForms = []; // Find all expanded sign items and store their ids $('[id^="sign_info_"]:visible').each(function () { expandedSignItems.push($(this).attr('id')); }); $('[id^="accessLevelForm"]').each(function () { signItemForms.push({id: $(this).attr('id'), inputs: $(this).serialize()}); }); } } /** * Restores the expanded sign info items */ function restoreExpandedSignInfoItems() { if (typeof expandedSignItems !== 'undefined' && $.isArray(expandedSignItems)) { for (var exI = 0; exI < expandedSignItems.length; exI++) { // Show the expanded sign item $('#' + expandedSignItems[exI]).show() .siblings('.sub_title_item') // Change to '-' image .children('.added_item_sign').css('background-image', 'url("../app/html/images/app/up_arrow.png")'); } } $('[id^="accessLevelForm"]') .off('focus', 'input[type=number]') .off('blur', 'input[type=number]') .on('focus', 'input[type=number]', function () { // Pause the auto refresh by removing the interval clearInterval(realTimeInterval); }) .on('blur', 'input[type=number]', function () { // Add the interval again after focus is lost realTimeInterval = setInterval("refreshRealtimer('SignList','')", 1000); }); // Restore the form values for (var i = 0; i < signItemForms.length; i++) { var inputs = signItemForms[i].inputs.split('&'), $form = $('#' + signItemForms[i].id); for (var j = 0; j < inputs.length; j++) { var nameAndValue = inputs[j].split('='); var $inputs = $form.find('[name=' + nameAndValue[0] + ']'); if ($inputs.is(':radio')) { // Set the checked property of each radio button $inputs.each(function () { var isChecked = false; if ($(this).val() == nameAndValue[1]) { isChecked = true } $(this).prop('checked', isChecked); }); } else { // Set the value of each input $inputs.val(nameAndValue[1]); } } } }