// Com function 
//#region normal function 
function getId(id){
    return document.getElementById(id);
}

function getIdV(id){
    return document.getElementById(id).value;
}

function com_OpTxtById(id){

    var a = document.getElementById(id);
    return a.options[a.selectedIndex].text;

}

function com_inhtml(id , text){
    document.getElementById(id).innerHTML = text;
}


// byName
function getN(name){
    return document.getElementsByName(name)[0];
}

function getNv(name){
    return document.getElementsByName(name)[0].value;
}

function com_name_inhtml(name , text){

    document.getElementsByName(name)[0].innerHTML = text;

}

function com_OpTxtByName(name){
    var a = document.getElementsByName(name)[0];
    return a.options[a.selectedIndex].text;
}



function com_htmlEntities(str) {

    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');

}

function com_stripScripts(text) {

	var SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
	while (SCRIPT_REGEX.test(text)) {
		text = text.replace(SCRIPT_REGEX, "");
	}
	return text;
}


function com_callnull(data,data2){

    console.log("action done");

}

function com_call_success_stay(data,data2){

    Swal.fire({
        title: "Update Success!",
        text: "",
        icon: "success",
        timer: 3000,
    
        onOpen: function() {
            Swal.showLoading()
        },
        willClose: () => {
         

          }
    }).then(function(result) {
        if (result.dismiss === "timer") {
     
        }
    })


}



function com_call_success(data,data2){

    Swal.fire({
        title: "Update Success!",
        text: "Auto reload in 3 seconds.",
        icon: "success",
        timer: 3000,
    
        onOpen: function() {
            Swal.showLoading()
        },
        willClose: () => {
            location.reload();

          }
    }).then(function(result) {
        if (result.dismiss === "timer") {
            location.reload();
        }
    })


}


function com_create_success(data,data2){

    Swal.fire({
        title: "Create Success!",
        text: "Auto reload in 3 seconds.",
        icon: "success",
        timer: 3000,
    
        onOpen: function() {
            Swal.showLoading()
        }
    }).then(function(result) {
        if (result.dismiss === "timer") {
            location.reload();
        }else{
            location.reload();
        }
    })


}

function addClassName(removetarget , id){
    var element = document.getElementById(id);
    element.classList.add(removetarget);
}

function removeClassName(removetarget , id){
    var element = document.getElementById(id);
    element.classList.remove(removetarget);
}

function com_call_failed(data,data2){

    Swal.fire({
        title: "Update Failed",
        text: "Auto reload in 3 seconds.",
        icon: "error",
        timer: 3000,
     
        onOpen: function() {
            Swal.showLoading()
        },
        willClose: () => {
            location.reload();

          }
    }).then(function(result) {
        if (result.dismiss === "timer") {
            location.reload();
        }else{
            location.reload();
        }
    })

}

function com_create_failed(data,data2){

    Swal.fire({
        title: "Create Failed",
        text: "Auto reload in 3 seconds.",
        icon: "error",
        timer: 3000,
     
        onOpen: function() {
            Swal.showLoading()
        },
        willClose: () => {
            location.reload();

          }
    }).then(function(result) {
        if (result.dismiss === "timer") {
            location.reload();
        }
    })

}

function com_call_failed_stay(data,data2){

    console.log("call failed stay");
    notif("error","Success Updated","Auto Close in 3 seconds.");

}

function com_call_success_stay(data,data2){

    console.log("call success stay");
    notif("success","Success Updated","Auto Close in 3 seconds.");
 

}

function com_get_failed_stay(data,data2){

    Swal.fire({
        title: "Retrive Data Failed",
        text: "Auto Close in 3 seconds.",
        icon: "error",
        timer: 3000,
     
        onOpen: function() {
            Swal.showLoading()
        }
    }).then(function(result) {
        if (result.dismiss === "timer") {
           
        }
    })

}


function com_get_failed(data,data2){

    Swal.fire({
        title: "Retrive Data Failed",
        text: "Auto reload in 3 seconds.",
        icon: "error",
        timer: 3000,
     
        onOpen: function() {
            Swal.showLoading()
        }
    }).then(function(result) {
        if (result.dismiss === "timer") {
            location.reload();
        }
    })

}



function com_selectElement_value(id, valueToSelect) {    

    let element = document.getElementById(id);
    element.value = valueToSelect;

}

// sleep
function com_sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// sleep and run function
function com_fullsleep(ms,fn){

    com_sleep(ms).then(()=> { 
        fn();
    });

}

function com_fullsleepReload(ms){

    com_sleep(ms).then(()=> { 
        location.reload();
    });

}



function com_removeArrayItemAll(arr, value) {
    var i = 0;
    while (i < arr.length) {
      if (arr[i] === value) {
        arr.splice(i, 1);
      } else {
        ++i;
      }
    }
    return arr;
}


function com_filter2arrayByIndex(recordIndex ,TextArrayDisplay ){

    return recordIndex.map((item) => TextArrayDisplay[item]);

}

function com_convertSpecialString(str){
    // str = str.replace(/&/g, "");
    str = str.replace(/>/g, "");
    str = str.replace(/</g, "");
    str = str.replace(/"/g, "");
    str = str.replace(/'/g, "");
    str = str.replace(/,/g, "");
    return str;
}




function makeid(length) {
    var result           = '';
    var characters       = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * 
        charactersLength));
    }
    return result;
 }



 function com_trimAll(input_string){


    let str = input_string;
    str = str.replace(/ +/g, "");

    return str;


 }


//#endregion




//#region textAjax

// ajax callback text with parameter value 
function ajaxtext_prmvalue_callback(url , dataJson , finishCallBack){


    $.ajax ({
        type: "POST",
        dataType: 'text',
        url: url,
        data: dataJson,
        success: function(data) {
          
          finishCallBack(dataJson,data);
        
        },
        error: function(data) {
          alert("Error!" + data);
        }
    });
 
}

// ajax callback text with parameter value , load html to table id
function ajaxtext_prmvalue_loadtable_callback(url , dataJson ,  tableId , finishCallBack){


    $.ajax ({
        type: "POST",
        dataType: 'text',
        url: url,
        data: dataJson,
        success: function(data) {
          
            $(tableId).html(data);
            finishCallBack(dataJson,data);
        
        },
        error: function(data) {
          alert("Error!" + data);
        }
    });
 
}


// ajax load html to table id
function ajaxtext_loadtable(url , dataJson ,  tableId){

    $.ajax ({
        type: "POST",
        dataType: 'text',
        url: url,
        data: dataJson,
        success: function(data) {
          
          $(tableId).html(data);
        
        },
        error: function(data) {
          console.log(data);
          alert("Error!" + data);
        }
    });
 
}


//#endregion



//#region jsonAjax

// upload image with data
function ajaxjson_withImage_callback(url , dataJson , notifText , successCallback ,failedCallback ){


    $.ajax ({
        type: "POST",
        dataType: 'json',
        url: url,
        data: dataJson,
        async: true,   
        cache: false,
        contentType: false,
        processData: false,
        success: function(data) { 
          if(data.resp == "done"){ 

            if(notifText != null){
                notif("success" , "" , notifText);  
            }
           

            successCallback(dataJson,data);
          }else{
 
            notif("error" , "" , "Please contact support."); 
            failedCallback(dataJson,data);
          }

        },
        error: function(data) {
          alert(" Error!" + data);

          console.log("rc_ajaxPostJson_simple error");
        }
    });
 
}


// super simple 
function ajaxjson_oneway(url , dataJson){

    console.log("call ajaxjson_oneway ");
    $.ajax ({
        type: "POST",
        dataType: 'json',
        url: url,
        data: dataJson,
        success: function(data) { 
          if(data.resp == "done"){ 
            console.log("done");
          }else{
            console.log("failed");
          }

        },
        error: function(data) { 
          console.log("rc_ajaxPostJson_simple error");
        }
    });
 

}

// simple upload
function ajaxjson_callback(url , dataJson , dataArray , notifText , successCallback ,failedCallback ){

    console.log("call ajaxjson call back");
    $.ajax ({
        type: "POST",
        dataType: 'json',
        url: url,
        data: dataJson,
        success: function(data) { 
          if(data.resp == "done"){ 
          
            if(notifText != null){
                notif("success" , "" , notifText);  
            } 

            successCallback(dataArray , data);
          }else{

            notif("error" , "" , "Please contact support."); 
            failedCallback(dataArray , data);
          }

        },
        error: function(data) {
          alert(" Error!" + data);

          console.log("rc_ajaxPostJson_simple error");
        }
    });
 
}




// simple upload
function ajaxjson_simple_callback(url , dataJson , notifText , successCallback ,failedCallback ){


    $.ajax ({
        type: "POST",
        dataType: 'json',
        url: url,
        data: dataJson,
        success: function(data) { 
          if(data.resp == "done"){ 
          
            if(notifText != null){
                notif("success" , "" , notifText);  
            } 
            successCallback(dataJson , data);

          }else{

            if(notifText != null){
                notif("error" , "" , "Please contact support."); 
            } 
         

            failedCallback(dataJson , data);
          }

        },
        error: function(data) {
          console.log("Error!"); 
          console.log(data); 
          console.log("rc_ajaxPostJson_simple error");
        }
    });
 
}




//#endregion


//#region Swal and notif

// cancelbutton and confirm button callbackvalue
function CSwalValue(Title , Text , Type , color , valueArray , ButtonCText , ButtonRText , callbackComfirm , CallbackReject){

    if(color == null){
        color = "#dc3545";
    }

    Swal.fire({
        title: Title,
        text: Text,
        icon: Type ,
        showCancelButton: true,
        confirmButtonColor: color,
        confirmButtonText: ButtonCText,
        cancelButtonText: ButtonRText,
        reverseButtons: true
    }).then(function(result) {
        if (result.value) {
            callbackComfirm(valueArray);
            // result.dismiss can be "cancel", "overlay",
            // "close", and "timer"
        } else if (result.dismiss === "cancel") {
            CallbackReject(valueArray);
        }
    });

    // swal({
    //     title: Title,
    //     text: Text,
    //     type: Type,
    //     showCancelButton: true,
    //     confirmButtonColor: color,
    //     confirmButtonText: ButtonCText,
    //     cancelButtonText: ButtonRText,
    //     closeOnConfirm: true,
    //     closeOnCancel: true
    // }, function (isConfirm) {
    //     if (isConfirm) {
    //         callbackComfirm(valueArray);
    //     } else{
    //         CallbackReject(valueArray);
    //     }
    // });


}

// no return parameter value
function CSwal(Title , Text , Type , color , ButtonCText , ButtonRText , callbackComfirm , CallbackReject){

    if(color == null){
        color = "#dc3545";
    }


    
    Swal.fire({
        title: Title,
        text: Text,
        icon: Type ,
        showCancelButton: true,
        confirmButtonText: ButtonCText,
        cancelButtonText: ButtonRText,
        reverseButtons: true
    }).then(function(result) {
        if (result.value) {
            callbackComfirm();
            // result.dismiss can be "cancel", "overlay",
            // "close", and "timer"
        } else if (result.dismiss === "cancel") {
            CallbackReject();
        }
    });


    // swal({
    //     title: Title,
    //     text: Text,
    //     type: Type,
    //     showCancelButton: true,
    //     confirmButtonColor: color,
    //     confirmButtonText: ButtonCText,
    //     cancelButtonText: ButtonRText,
    //     closeOnConfirm: true,
    //     closeOnCancel: true
    // }, function (isConfirm) {
    //     if (isConfirm) {
    //         callbackComfirm();
    //     } else{
    //         CallbackReject();
    //     }
    // });


  }



  
// function notif(context , position , message){
			
//     //$context = $(this).data('context');
//    // $message = $(this).data('message'); 
//     //$position = $(this).data('position');
//     $message =message;
//     $position = position;
//     $context = context;
    
//     if ($context === '') {
//         $context = 'info';
//     }

//     if ($position === '') {
//         $positionClass = 'toast-top-right';
//     } else {
//         $positionClass = 'toast-' + $position;
//     }

//     toastr.remove();
//     toastr[$context]($message, '', {
//         positionClass: $positionClass
//     });
    
// }




function notif(context , title , message){
			
    //$context = $(this).data('context');
   // $message = $(this).data('message'); 
    //$position = $(this).data('position');
  

    toastr.options = {
        "closeButton": true,
        "debug": false,
        "newestOnTop": true,
        "progressBar": true,
        "positionClass": "toastr-top-right",
        "preventDuplicates": false,
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "3000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
    
    if(context == "success"){
        toastr.success(message, title);
    }else if(context == "error"){
        toastr.error(message, title); 
    }



    // switch(context){
    //     case "success": break;
    //     case "info": toastr.info(message, title); console.log("info");break;
    //     case "warning" :   toastr.warning(message, title); console.log("warning");break;
    //     case "error" : toastr.error(message, title); console.log("error");break;
    //     default : toastr.success(message, title); console.log("default");break;
    // }
  
    
}


 



//#endregion



//#region imagephotoupload


function comUploadPhotoWithProgressBar(fileID , ButtonId , firstValuePassedArray , progressbarIDarray, storePathArray ,uploadUrl ,completedActionCallBack ){

    if( getId(fileID).files.length == 0 ){
        console.log("no files selected");
        swal('Please upload file.','','error');
        return false

    }else{ 
        
        var tempRecordOldValue = getId(ButtonId).innerHTML;
        getId(ButtonId).innerHTML = "Uploading...";
        getId(ButtonId).disabled = true;
        var formData = new FormData();
        formData.append('photosUpload', 0);
        formData.append('imgid', $('#'+fileID)[0].files[0]);
        formData.append('fileDBstoreArray', storePathArray);
        formData.append('firstValuePassedArray', firstValuePassedArray);
        // for( x in firstValuePassedArray){
        //     formData.append(x, firstValuePassedArray[x]);
        // }

        var prog_val_app = progressbarIDarray[0];
        var uplprgw_app = progressbarIDarray[1];
        var uplprg_app = progressbarIDarray[2];

        console.log("prog_val_app : "  + prog_val_app);
        $.ajax({
            xhr: function () {

                var xhr = new window.XMLHttpRequest();
                var setprogressbar = $("#"+uplprg_app).css("display");
                
                if(setprogressbar == "none"){
                    $("#"+uplprg_app).css("display", "block");
                }
                
                
                xhr.upload.addEventListener("progress", function (evt) {
                    if (evt.lengthComputable) {
                        
                        var percentComplete = evt.loaded / evt.total;
                        console.log(percentComplete);
                        
                        document.getElementById(prog_val_app).innerHTML =((percentComplete) * 100).toFixed(2) + "%";
                        $("#"+uplprgw_app).css("width", ((percentComplete-0.02) * 100) + "%");
                        
                        //$('[data-plugin="progress"]').asProgress('go',(percentComplete - 0.02) * 100);
                
                        if (percentComplete === 1) {
                            
                            $("#"+uplprgw_app).css("width", "100%");
                            
                        }
                        


                    }
                }, false);
        
                return xhr;
            },
            url: uploadUrl,
            type: "POST",
            data:formData,
            dataType: "JSON",
            async: true,   
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
             
                if(data['notAllowextentiontype'] != ""){

                    var ftyp = data['notAllowextentiontype'];
                    console.log( ftyp + ' is not allow.');
                    
                } 
            
            },
            
            complete:function(data){
                console.log('complete');
                
                completedActionCallBack(data);
                
                setTimeout(function(){ 

                    $("#"+uplprg_app).css("display", "none");
                    $("#"+uplprgw_app).css("width", "0%");
                    getId(ButtonId).innerHTML = tempRecordOldValue;
                    //document.getElementById("viewpay").style.display = "";
                    //document.getElementById(ButtonId).innerHTML = "上传新照片";
                    getId(ButtonId).disabled = false;
                    
                }, 2000);

            },
            error: function(data) {
                console.log('File upload error...');
                document.getElementById(ButtonId).disabled = false;
                return false;
            } 
        }); 




    }

}

 

//#endregion


//#region  firebase

//#endregion


// promise

function runPromiseAJX(url,dataJson){
    return new Promise(function(resolve,rejected){
        $.ajax ({
            type: "POST",
            dataType: 'json',
            url: url,
            data: dataJson,
            success: function(data) {
              
                resolve({
                    ajx_data : data,
                    def_data : dataJson
                });
            
            },
            error: function(data) {
                rejected({
                    ajx_data : data,
                    def_data : dataJson
                })
            }
        }); 
    });
}


function clearInputValue(arrayId){

    arrayId.forEach( function(data,index){
        getId(data).value = "";

    });

}

  

function createToken(data,secret){
    let header = {
    "alg": "HS256",
    "typ": "JWT"
  };
  
  let stringifiedHeader = CryptoJS.enc.Utf8.parse(JSON.stringify(header));
  let encodedHeader = base64url(stringifiedHeader);
   
  let stringifiedData = CryptoJS.enc.Utf8.parse(JSON.stringify(data));
  let encodedData = base64url(stringifiedData);
  let token = encodedHeader + "." + encodedData;
  let signature = CryptoJS.HmacSHA256(token, secret);
  signature = base64url(signature);

  return signedToken = token + "." + signature;

}


function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));

return JSON.parse(jsonPayload);
};

function base64url(source) {
// Encode in classical base64
encodedSource = CryptoJS.enc.Base64.stringify(source);
// Remove padding equal characters
encodedSource = encodedSource.replace(/=+$/, '');
// Replace characters according to base64url specifications
encodedSource = encodedSource.replace(/\+/g, '-');
encodedSource = encodedSource.replace(/\//g, '_');

return encodedSource;
}

//nav_actlog({"act":"Update","desc":"halloworld","frompage":"project","lvlname":"admin"})
function nav_actlog(jsondata){
 

    // let fdata = {
    //     "test":"test",
    //     "test":"test"
    // }

    // const headers = { type: 'application/json' }; 
    // const blobx = new Blob([JSON.stringify(fdata)], headers);


    let formData = new FormData();
    formData.append("addlog",true);
    formData.append("actIE",jsondata.act); 
    formData.append("logdesc",jsondata.desc); 
    formData.append("frompage",jsondata.frompage);
    formData.append("levelname",jsondata.lvlname);

    let respone = navigator.sendBeacon("action/actlog.php",formData);
    return respone;

}

function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}

function rc_shownumb(num){
    return (Math.round(num * 100) / 100).toFixed(2);
}