/* \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.
*/
var number_commentsj;
// Variables to store the translated messages
var no_internet_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;
/**
* 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;
/**
* Name : loadApp()
* Parameters : -
* Description : Load the app that is clicked
*/
function loadApp(app,toastTilte,toastMessage){
// Check if there's internet connection
if(window.navigator.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 : 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(){
navigator.app.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');
}
/********************************* 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(){
// check orientation
switch(window.orientation)
{
case -90:
case 90:
viewPortTag.id="viewport";
viewPortTag.name = "viewport";
viewPortTag.content = "user-scalable=no, initial-scale=1, width=device-width, height=device-width";
document.getElementsByTagName('head')[0].appendChild(viewPortTag);
break;
default:
viewPortTag.id="viewport";
viewPortTag.name = "viewport";
viewPortTag.content = "user-scalable=no, initial-scale=1, width=device-width, height=device-height";
document.getElementsByTagName('head')[0].appendChild(viewPortTag);
break;
}
}
/********************************* 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
load_in_div = false;
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
load_in_div = false;
ajax_post('','',"?id=" + getURLParam('id') + "&href=app/include/upload_abort_file.php", '');
}
}
// Display the toast
toastr.info("" + 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();
// 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){
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() + "
");
}else{
// Toast alert with two button
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;
var _device;
// 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){
// Check and set device
if(check_mimetype == 'iOS'){
_device = 'iOS';
}else{
_device = 'Android';
}
// 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;
// Open file system to check if the file already exist
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
fileSystem.root.getFile(check_downloadpath, { create: false }, fileExists, fileDoesNotExist);
}, getFSFail); //of requestFileSystem
}
/**
* 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){
case 'Android':
// File isn't damaged open the file on Android
openFile(_mimetype,filename_open);
break;
case 'iOS':
// File isn't damaged open the file on iOS
ExternalFileUtil.openWith(_downloadpath,'');
break;
default:
break;
}
}else if(fileSize == 0){
// File is damaged
// Check if there is internet connection
if(window.navigator.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(window.navigator.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
setToastAlert(''+ filesize_mismatch_text +'',''+ download_text +'',''+ open_text +'','downloadFile(_url ,filename_down ,_mimetype , filename_open, _toastTitle, _toastMessage);','openFile(_mimetype,filename_open);');
}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(window.navigator.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)
{
// 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) {
// full file path (path on phone + path where the file will stored)
var imagePath = fs.root.fullPath +"/"+ 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 0%
progress_element.style.width = "5%";
// Show progress bar
progress_element_con.style.display= "none";
}
// Set download variable
download_file = true;
// Check device
switch(_device){
case 'Android':
// Open the file
openFile(mimetype,openpath);
break;
case 'iOS':
ExternalFileUtil.openWith(downloadpath,'');
break;
default:
break;
}
}, function (error) {
try{
// 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(!window.navigator.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)
}
}
/////////////////////////////////////////// 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 project id
var project_name;
/**
* 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 : 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();
}
}
/*********************************** 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';
}
// GLOBALS
// Used to check if spinners must be showed
var spinning;
// Var to load ajaxpost in div or not
var load_in_div = true;
// XMLHttpRequest object
var hr = null;
/**
* 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
*/
function ajax_post(arg1,arg2,href,div){
// Check if there's internet connection
if(window.navigator.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 && hr.status == 200) {
if(hr.readyState == 4) {
if(hr.status == 200) {
var return_data = hr.responseText;
if(load_in_div){
// load page in div
document.getElementById(div).innerHTML = return_data;
spinning = false;
$.mobile.hidePageLoadingMsg();
}
// Add script runs
parseScript(return_data);
}
load_in_div = true;
// 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{
// Set alert
setToastAlert(no_internet_connection_message,no_internet_connection_message_ok);
}
}
function parseScript(strcode) {
// Array which will store the script's code
var scripts = new Array();
// Strip out tags
while(strcode.indexOf(" -1) {
var s = strcode.indexOf("", e);
// Add to scripts array
scripts.push(strcode.substring(s_e+1, e));
// Strip from strcode
strcode = strcode.substring(0, s) + strcode.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i";
}
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;
}
/**
* 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 : 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(getFilename, failCamera_File, { quality: 100,
destinationType: navigator.camera.DestinationType.FILE_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) {
/*
imageURI = "/sdcard/Android/data/com.dualinventive.holdingbv/cache/1386757758505.jpg";
window.imageResizer.getImageSize(function(data) {
//var image = document.getElementById('myImage');
//image.src = "data:image/jpeg;base64," + data.imageData;
alert('gelukt data:' + data.width);
}, function (error) {
alert("Error : \r\n" + error);
}, imageURI, {imageType : ImageResizer.IMAGE_DATA_TYPE_URL });
alert('etet');
//file:///storage/emulated/0/Android/data/com.dualinventive.holdingbv/cache/arerereere.jpg
window.imageResizer.resizeImage(
function(data) {
//var image = document.getElementById('myImage');
//image.src = "data:image/jpeg;base64," + data.imageData;
alert("gelukt: " + data.width);
}, function (error) {
alert("Error : \r\n" + error);
}, imageURI, 0.5, 0.5, {resizeType:ImageResizer.RESIZE_TYPE_FACTOR, imageType:ImageResizer.IMAGE_DATA_TYPE_URL, format: ImageResizer.FORMAT_JPG});
*/
// Check if there is internet connection
if (window.navigator.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";
// Set flag to false (upload active)
upload_file = false;
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
// 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 (!window.navigator.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
// 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'), getProjectId(),"?id=" + getURLParam('id') + "&href=" + ghref + "", gdiv);
}
/**
* Name : failUpload(error)
* Parameters : error
* Description : Callback upload image fail
*/
function failUpload(error) {
// Callback on error
// 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(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 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
*/
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;
}
/**
* 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 : getGeoLat()
* Parameters : -
* Description : return the latitude value
*/
function getGeoLat(){
return GeoLat;
}
/**
* Name : getGeoLon()
* Parameters : -
* Description : return the longitude value
*/
function getGeoLon(){
return GeoLon;
}
/**
* 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 : 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.network.connection.type;
// Get previous background image
var str = $('#'+id).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)');
}
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)');
}
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)');
}
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)');
}
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)');
}
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)
// 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;
/**
* 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());
});
}
/**
* 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();
// Clear jquery mobile load spinner
$.mobile.hidePageLoadingMsg();
}
/**
* Name : loadGoogleMapsScript()
* Parameters : -
* Description : Load javascript asynchronous
*/
function loadGoogleMapsScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' + 'callback=initializeMap';
document.body.appendChild(script);
}
/**
* 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
*/
function GoogleMap(coordinates_array){
// Initialize the Google maps
this.initialize = function(){
var map = showMap();
addMarkersToMap(map,coordinates_array);
}
// Show the Google maps in the div
var showMap = function(){
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(coordinates_array[0][0], coordinates_array[0][1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("google_maps"), mapOptions);
// 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;
}
}
/**
* 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 dubbelclick
var dblclick = false;
var addMarkersToMap = function(maps ,coordinates_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();
// Loop through all the selected devices
for (var i = 0; i < number_of_devices; i++) {
// Check if there are coordinates
if((coordinates_array[i][0] != '-') && (coordinates_array[i][1] != '-')){
// Create marker
var latitudeAndLongitudeOne = new google.maps.LatLng(coordinates_array[i][0],coordinates_array[i][1]);
markerOne[i] = new google.maps.Marker({
position: latitudeAndLongitudeOne,
map: maps,
title: "" + i + "",
icon: coordinates_array[i][3]
});
google.maps.event.addListener(markerOne[i], "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[i], "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){
setToastAlert(toastMessage,no_internet_connection_message_ok,'','','','150');
}
},400)
// Double click to default value
dblclick = false;
});
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){
// Clear all markers
for (var j = 0; j < number_of_devices; j++) {
markerOne[j].setMap(null);
}
// 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()
}*/
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 (window.navigator.onLine){
if(secondTimmer < 0){
// load spinner in the tab
$("#countdown_" + id).html('
');
// Set back to default
//secondTimmer = 10;
// Clear interval
window.clearInterval(realTimeInterval);
// refresh page
// Do not load in div
load_in_div = false;
// parse javascript so it can be send by ajax post
var jsonStringRefresh = JSON.stringify(devices_checked);
switch(id){
case 'Map':
//load_in_div = true;
ajax_post('refresh_page',jsonStringRefresh,"?id=" + getURLParam('id') + "&href=app/di_app_realtime/a_get_info_realtime.php",'loaded_page');
break;
case 'Realtime':
ajax_post(encodeURIComponent(refreshpage),jsonStringRefresh,"?id=" + getURLParam('id') + "&href=app/di_app_realtime/parse_devices_array_in_php.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){
//if(projectNames[i].innerHTML.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;
}