/*!
 * Google Firebase functions for Thorium Mobile projects
 * Version 4.0 April, 2024
 * framework7 v8.x (https://framework7.io)
 * Google firebase (https://firebase.google.com)
 * framework7: MIT Licensed
 * Copyright 2018-2024 Thorium builder.
*/

if (firebase) {
    var firebaseApp = firebase.initializeApp(firebaseConfig);
    if (firebaseApp) {
        thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase] Firebase initialized");
        firebase.auth().useDeviceLanguage();
    } else {
        thoriumapi.logEvent(2,"[com.thoriumbuilder.firebase] Unable to initialize Firebase App");
        app.dialog.alert('Unable to initialize Firebase App ');
    }
} else {
    thoriumapi.logEvent(2,"[com.thoriumbuilder.firebase] Unable to initialize Firebase");
    app.dialog.alert('Unable to initialize Firebase ');
}

var firebasePlugin = {
    name: "Thorium Builder Firebase Plugin",
    bundleid: "com.thoriumbuilder.firebase",
    version: "4.0",
    initialized: false,
    ls: null,
    rsp: null,
    rs: null,
    ps: null,
    avatarChanged: false,
    token : '',
    firestoredb : firebase.firestore(),
    /* -- Firebase Auth Screen Translation --*/
    translatescreen: function () {
        thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase] Translate Firebase Dialogs");
        var resources = getLangResources()["tr"];
        $("*[data-translate]:not(input):not(textarea)").each(function (elt) {
            var t = resources[$(elt).attr("data-translate")];
            if (t) { elt.innerText = t; }
        });
        $("input[data-translate]").each(function (elt) {
            var t = resources[$(elt).attr("data-translate")];
            if (t) { elt.placeholder = t; }
        });
    },
    getTranslatedString(stringId) {
        var resources = getLangResources()["tr"];
        var translation =resources[stringId]||null;
        return translation
    },
    showLoginScreen: function (e) {
        thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase] Loading Login Popup");
        firebasePlugin.ls = app.loginScreen.create({ el: '.login-screen' });
        firebasePlugin.ls.open(true);
        app.emit('onShowLoginScreen',e);
    },

    showRegisterScreen: function (e) {
        if (e) {e.preventDefault();}
        thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase] Loading Register Popup");
        firebasePlugin.rs = app.popup.create({ el: '.register-screen', swipeToClose: true });
        firebasePlugin.rs.open(true);
        app.emit('onShowRegisterScreen',e);
    },

    showResetPwScreen: function (e) {
        if (e) {e.preventDefault();}
        thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase] Loading Reset Password Popup");
        firebasePlugin.rsp = app.popup.create({ el: '.resetpassword-screen', swipeToClose: true });
        $(".firebase_resetpw_email").val($(".firebase_email").val());
        firebasePlugin.rsp.open(true);
        app.emit('onShowResetPwScreen',e);
    },

    updateUserExt: function (e) {
        var user = firebase.auth().currentUser;
        if (user) {
            thoriumapi.logEvent(0, "[com.thoriumbuilder.firebase] Updating user Information");
            if (kShowPreloader==true) {app.preloader.show();}
            var uid = user.uid;
            if (firebasePlugin.avatarChanged == true) {
                var blob = $("#firebase_profile_avatar_input").data("data-blob");
                var localFile = $("#firebase_profile_avatar_input").data("data-file");
                var filename = localFile.name;
                blob.name = filename;
                filename = filename.replace('C:\\fakepath\\', '');
                var extension = filename.substr((filename.lastIndexOf('.') + 1));
                var storage = firebase.storage();
                var storageRef = storage.ref().child(firebaseStoragePath + '/');
                var rnd = app.utils.id("-xxxx-xxxx");
                filename = uid + rnd + "." + extension;
                var url;
                var uploadTask = storageRef.child(filename).put(blob) //localfile
                .catch(function (error) {
                    app.preloader.hide();
                    app.dialog.alert(error.message);
                    return;
                })
                .then(function (e) {
                    // all working for progress bar that in html 
                    // to indicate image uploading... report 
                    e.task.on('state_changed', function (snapshot) {
                            var progress =  (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                            var uploader = document.getElementById('firebase-upload-progress');
                            uploader.value = progress;
                        }, function (error) {
                            app.preloader.hide();
                            app.dialog.alert(error.message);
                        }, function () {

                            var fileRef = storageRef.child(filename);
                            fileRef.getDownloadURL()
                                .then(function (downloadURL) {
                                    
                                    $('.firebase_avatar').attr('src', downloadURL);
                                    user.updateProfile({
                                        photoURL: downloadURL
                                    })
                                    .then(function (e) {
                                        firebasePlugin.setUserShadow(user);
                                    })
                                    .catch(function (error) {
                                        app.preloader.hide();
                                        app.dialog.alert(error.message);
                                    });

                                })
                                .catch(function (error) {
                                    app.preloader.hide();
                                    app.dialog.alert("Error while uploading image: " + error.message);
                                })


                        })
                        .catch(function (error) {
                            app.preloader.hide();
                            app.dialog.alert("Error while uploading image: " + error.message);
                        })



                    e.task.snapshot.ref.getDownloadURL()
                        .then(function (downloadURL) {
                            $('.firebase_avatar').attr('src', downloadURL);
                            user.updateProfile({
                                    photoURL: downloadURL
                                })
                                .then(function (e) {
                                    firebasePlugin.setUserShadow(user);
                                })
                                .catch(function (error) {
                                    app.preloader.hide();
                                    app.dialog.alert(error.message);
                                });
                        });
                });
            };

        };
        var displayName = $("#firebase_profile_displayname").val();
        user.updateProfile({
            displayName: displayName
        }).catch(function (error) {
            app.preloader.hide();
            app.dialog.alert(error.message);
        }).then(function (e) {
            firebasePlugin.setUserShadow(user);
            setTimeout(function () {
                app.preloader.hide();
                firebasePlugin.ps.close();
            }, 1000);
        });

    },

    setUserShadow: function (user) {
        if (!user)  {return;}
        var db = firebasePlugin.firestoredb;
        if (db) {
            var record=db.collection("thorium.users").doc(user.uid);
            record.get()
            .then(function (doc) {
                if (doc.exists) { 
                    thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase]  Update user Shadow Information");
                    var lg=user.pa||'';
                    record.update({
                        displayName:user.displayName,
                        emailVerified:user.emailVerified,
                        language: lg,
                        creationTime :user.metadata.creationTime,
                        lastSignInTime: user.metadata.lastSignInTime,
                        photoURL: user.photoURL,
                        email : user.email,
                        anonymous :user.isAnonymous
                    })
                    .catch(function(error) {
                       var m="[com.thoriumbuilder.firebase] Firebase Plugin: Error writing User document: "+ error.message;
                       thoriumapi.logEvent(2,m);
                       app.dialog.alert(m);
                    });

                } else {
                    thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase] Firebase Plugin: Create user Shadow Information");
                    var lg=user.pa||'';
                    record.set({
                        displayName:user.displayName,
                        emailVerified:user.emailVerified,
                        language: lg,
                        creationTime :user.metadata.creationTime,
                        lastSignInTime: user.metadata.lastSignInTime,
                        photoURL: user.photoURL,
                        email : user.email,
                        anonymous :user.isAnonymous
                    })
                    .catch(function(error) {
                       var m="[com.thoriumbuilder.firebase] Error writing User document: "+ error.message;
                       thoriumapi.logEvent(2,m);
                       app.dialog.alert(m);
                    });


                }
            })
            .catch(function(error) {
               var m="[com.thoriumbuilder.firebase] Error getting User document: "+ error.message;
               thoriumapi.logEvent(2,m);
               app.dialog.alert(m);
            });
        }
    },


    resizeImage : function (file, maxsize) {
        thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase] Resizing Image");
        return new Promise(function (resolve, reject) {
            var dataURL = "x";
            var reader = new FileReader();
            reader.onloadend = function () {
                var buffer = new Image();
                buffer.src = reader.result;
                buffer.onload = function () {
                    var w = buffer.width;
                    var h = buffer.height;
                    if (w > h) {
                        if (w > maxsize) {
                            h *= maxsize / w;
                            w = maxsize;
                        }
                    } else {
                        if (h > maxsize) {
                            w *= maxsize / h;
                            h = maxsize;
                        }
                    }
                    var canvas = document.createElement('canvas');
                    canvas.width = w;
                    canvas.height = h;
                    var ctx = canvas.getContext("2d");
                    ctx.drawImage(this, 0, 0, w, h);
                    var t = file.type || "image/jpg";
                    dataURL = canvas.toDataURL(t);
                    resolve(dataURL);
                };
                buffer.onerror = function (err) {
                    thoriumapi.logEvent(2,"[com.thoriumbuilder.firebase] Image Resize Error " + err);
                    reject("Image Resize Error " + err);
                }
            };
            reader.readAsDataURL(file);
        });
    },


    firebase_handleProfileImage: function (file) {
        firebasePlugin.resizeImage(file,256)
        .then(function (p) {
            var blob = thoriumCorePlugin.dataURItoBlob(p);
            blob.name = p.name;
            var reader = new FileReader();
            reader.onload = function (e) {
                var src = e.target.result;
                $(".firebase_profile_avatar").attr('src', src);
                $("#firebase_profile_avatar_input").data("data-file", file);
                $("#firebase_profile_avatar_input").data("data-blob", blob);
                firebasePlugin.avatarChanged = true;
            }
            reader.readAsDataURL(file);
        });
    },

    resetPasswordExt: function (e) {
        e.preventDefault();
        thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase] Opening Reset Password Dialog");
        const m=firebasePlugin.getTranslatedString("resetpassword")||"Reset Password";
        app.dialog.confirm(m+"?", function () {
            var em = $('.firebase_resetpw_email').val();
            if (em.length > 0) {
                if (kShowPreloader==true) {app.preloader.show();}
                firebase.auth().sendPasswordResetEmail(em)
                    .then(function () {
                        app.preloader.hide();
                        $(".firebase_email").val(em);
                        const m=firebasePlugin.getTranslatedString("emailsent")||"an email has been sent to your address";
                        app.dialog.alert(m);
                        firebasePlugin.rsp.close();
                    })
                    .catch(function (error) {
                        app.preloader.hide();
                        thoriumapi.logEvent(2,"[com.thoriumbuilder.firebase] Reset Password Error: "+error.message);
                        app.dialog.alert(error.message);
                    });
            }
        });
    },

    logoutExt: function (e) {
        app.preloader.show();
        firebase.auth().signOut()
            .then(function () {
                app.preloader.hide();
                thoriumapi.reloadHomePage();
                firebasePlugin.initialize();
                app.emit('onAuthSignOut', e);
                thoriumapi.logEvent(0, "[com.thoriumbuilder.firebase] Logout Command Sent");
            })
            .catch(function (error) {
                app.preloader.hide();
                thoriumapi.logEvent(2, "[com.thoriumbuilder.firebase] Logout Error: " + error.message);
                app.dialog.alert(error.message);
            });
    },

    signInExt: function (e) {
        e.preventDefault();
        if (kShowPreloader==true) {app.preloader.show();}
        var email = $(".firebase_email").val();
        var password = $(".firebase_password").val();
        firebase.auth().signInWithEmailAndPassword(email, password)
        .then(function (e) {
                app.preloader.hide();
                if (firebasePlugin.ls) { firebasePlugin.ls.close(); }
        })
        .catch(function (error) {
                app.preloader.hide();
                thoriumapi.logEvent(2,"[com.thoriumbuilder.firebase] SignIn Error: "+ error.message);
                app.dialog.alert(error.message);
        });
    },

    createUserExt: function (e) {
        if (e) {
            var uid = e.user.uid;
            var displayname = $("#firebase_register_displayname").val();
            var n = $("#firebase_register_displayname").val();
            if (e.user) {
                e.user.updateProfile({
                    displayName: displayname,
                    photoURL: 'img/defaultavatar.png'
                }).catch(function (error) {
                    app.preloader.hide();
                    thoriumapi.logEvent(2,"[com.thoriumbuilder.firebase] Update Error: "+ error.message);
                    app.dialog.alert(error.message);
                });
                firebasePlugin.setUserShadow(e.user);
                app.preloader.hide();
                $("#firebase_email").val($("#firebase_register_email").val());
                $("#firebase_password").val($("#firebase_register_password").val());
                firebasePlugin.rs.close();
                if (firebasePlugin.ls) { firebasePlugin.ls.close(); }
                $(".firebase_avatar").attr('alt', displayname);
                $(".firebase_avatar").attr('title', displayname);
                thoriumapi.showNotification('Welcome ' + displayname);
            }
        }
    },

    registerExt: function (e) {
        e.preventDefault();
        if (kShowPreloader==true) {app.preloader.show();}
        var email = $("#firebase_register_email").val();
        var password = $("#firebase_register_password").val();
        var pwverification = $("#firebase_register_password_verification").val();
        if (password != pwverification) {
            app.preloader.hide();
            const m=firebasePlugin.getTranslatedString("pwmatch")||"Password does not match";
            app.dialog.alert(m);
            thoriumapi.logEvent(1,"[com.thoriumbuilder.firebase] Password does not match");
            $("#firebase_register_password_verification").focus();
            return;
        }
        if (password.length < 6) {
            app.preloader.hide();
            const m=firebasePlugin.getTranslatedString("pwlength")||"Password must contain at least 6 characters";
            app.dialog.alert(m);
            thoriumapi.logEvent(1,"[com.thoriumbuilder.firebase] Password Too Short");
            $("#firebase_register_password").focus();
            return;
        }
        if (kShowPreloader==true) {app.preloader.show();}
        var user = firebase.auth().currentUser;
        if ((user) && (user.isAnonymous == true)) {
            var credential = firebase.auth.EmailAuthProvider.credential(email, password);
            firebase.auth().currentUser.linkWithCredential(credential)
                .catch(function (error) {
                    app.preloader.hide();
                    thoriumapi.logEvent(2,"[com.thoriumbuilder.firebase] linkWithCredential Error: "+ error.message);
                    app.dialog.alert(error.message);
                    return;
                }).then(function (e) {
                    app.preloader.hide();
                    firebasePlugin.createUserExt(e);
                });
        } else {
            firebase.auth().createUserWithEmailAndPassword(email, password)
                .catch(function (error) {
                    app.preloader.hide();
                    thoriumapi.logEvent(2,"[com.thoriumbuilder.firebase] createUserWithEmailAndPassword Error: "+ error.message);
                    app.dialog.alert(error.message);
                    return;
                }).then(function (e) {
                    app.preloader.hide();
                    firebasePlugin.createUserExt(e);
                });
        }
    },

    resetRepeaters: function () {
        thoriumapi.logEvent(0, "[com.thoriumbuilder.firebase] no user connected, reset all Repeaters");
        $(".virtual-list").each(function (field) {
            thoriumapi.logEvent(0, "[com.thoriumbuilder.firebase] Reset Repeater with ID: [" + field.id + "]");
            field.setAttribute("data-loaded", "false");
            var vl = $("#" + field.id);
            var v = app.virtualList.get(vl);
            if (v) {
                v.deleteAllItems();
            }
        });
    },

    handleStateChangedExt: function (user) {
        app.preloader.hide();
       // if ( (kForceInstall==true) && (app.device.webView==false) && (window.location.protocol!="file:") && (app.device.cordova==false)  &&  ( (app.device.ios) ||  (app.device.android) )   ) {  return; }
        if (user) {
            if (user.uid==firebasePlugin.token) {return}
            firebasePlugin.token=user.uid;
            // User is signed in.
            if ((user.isAnonymous == true) && (firebaseAnonymous == false)) {
                firebasePlugin.logoutExt();
                $(".apploader").hide();
                return;
            }
            thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase] Firebase Authentification State Changed - User Connected with UID:["+user.uid+"]");
            var displayName = user.displayName;
            var email = user.email;
            var emailVerified = user.emailVerified;
            var photoURL = user.photoURL;
            var isAnonymous = user.isAnonymous;
            var uid = user.uid;
            var providerData = user.providerData;
            $('.firebase-user-logout').show();
            $('#firebase_login').hide();
            $(".firebase_email").val(user.email);
            $(".firebase_displayname").text(user.displayName);
            if (user.isAnonymous == true) {
                $(".firebase_avatar").attr('src', "img/defaultavatar.png");
                $(".firebase_avatar").attr('alt', "anonymous");
                $(".firebase_avatar").attr('title', "anonymous");
                thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase] Firebase Anonymous User Signed In with UID:["+user.uid+"]");
            } else {
                
                var avt = user.photoURL || "img/defaultavatar.png";
                $(".firebase_avatar").attr('src', avt);
                $(".firebase_avatar").attr('alt', user.displayName);
                $(".firebase_avatar").attr('title', user.displayName);
                firebasePlugin.setUserShadow(user);
            }
            
            $("#view-main").show();
            $(".apploader").hide();
            if (firebasePlugin.ls) { firebasePlugin.ls.close(); }
        } else {
            if (firebasePlugin.token=='none') {$(".apploader").hide(); return;}
            thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase] Firebase User Signed Out");
            // User is signed out.
            $("#auth_name").text("");
            $("#auth_img").attr('src', "");
            $('.firebase-user-logout').hide();
            $('#firebase_login').show();
            $(".firebase_email").val("");
            $(".firebase_displayname").text("");
            $(".firebase_avatar").attr('src', "img/defaultavatar.png");
            $(".firebase_avatar").attr('alt', "");
            $(".firebase_avatar").attr('title', "");
            firebasePlugin.resetRepeaters();
            if (firebaseAnonymous == false) {
                firebasePlugin.token='none';
                firebasePlugin.showLoginScreen();
                setTimeout(function () { $(".apploader").hide();}, 500);
            } else {
                firebase.auth().signInAnonymously()
                .catch(function (error) {
                    firebasePlugin.token='none';
                    thoriumapi.logEvent(2,"[com.thoriumbuilder.firebase] signInAnonymously Error: "+ error.message);
                    firebasePlugin.showLoginScreen();
                    setTimeout(function () { $(".apploader").hide();}, 500);
                })
                .then(function (result) {
                    var user=result.user;
                    if (user) {
                        firebasePlugin.token=user.uid; 
                        thoriumapi.logEvent(0,"[com.thoriumbuilder.firebase] signInAnonymously success with uid: "+ user.uid);
                        setTimeout(function () { $(".apploader").hide();}, 500);
                    } else {
                        firebasePlugin.token='none';
                        thoriumapi.logEvent(2,"[com.thoriumbuilder.firebase] signInAnonymously Error: "+ user.uid);
                    }             
                });
            }
        }
    },

    onFirebaseAvatarChange: function (e) {
        e.preventDefault();
        var f = e.target.files[0];
        firebasePlugin.firebase_handleProfileImage(f);
    },

    showEditProfilePageExt: function (e) {
        if (e) {e.preventDefault();}
        firebasePlugin.ps = app.popup.create({ el: '.profile-screen', swipeToClose: false });
        $(".firebase_resetpw_email").val($(".firebase_email").val());
        var user = firebase.auth().currentUser;
        if (user) {
            firebasePlugin.ps.open(true);
            $(".firebase_profile_displayname").val(user.displayName);
            $(".firebase_profile_email").val(user.email);
            var avt = user.photoURL || "img/defaultavatar.png";
            $(".firebase_profile_avatar").attr("src", avt);
            $('.firebase-displayname').text(user.displayName);
        }
    },

    facebookLoginExt: function (e) {
        // Sign in using a popup.
        if (e) {e.preventDefault();}
        if (thoriumapi.isLocal() == true) {
            var m="[com.thoriumbuilder.firebase] Facebook Authentification not allowed with file: protocol";
            app.dialog.alert(m)
            thoriumapi.logEvent(1,m);
            return;
        }
        var provider = new firebase.auth.FacebookAuthProvider();
        provider.addScope('user_birthday');
        firebase.auth().signInWithPopup(provider)
            .then(function (result) {
                // This gives you a Facebook Access Token.
                var token = result.credential.accessToken;
                var user = result.user;
            })
            .catch(function (error) {
                app.preloader.hide();
                app.dialog.alert(error.message);
            });
    },

    googleLoginExt: function (e) {
        if (e) {e.preventDefault();}
        if (thoriumapi.isLocal() == true) {
            var m="[com.thoriumbuilder.firebase] Google Authentification not allowed with file: protocol";
            app.dialog.alert(m)
            thoriumapi.logEvent(1,m);
            return;
        }
        var provider = new firebase.auth.GoogleAuthProvider();
        provider.addScope('profile');
        provider.addScope('email');
        firebase.auth().signInWithPopup(provider)
            .then(function (result) {
                // This gives you a Google Access Token.
                var token = result.credential.accessToken;
                // The signed-in user info.
                var user = result.user;
            })
            .catch(function (error) {
                app.preloader.hide();
                app.dialog.alert(error.message);
                return;
            });
    },

    twitterLoginExt: function (e) {
        if (e) {e.preventDefault();}
        if (thoriumapi.isLocal() == true) {
            var m="[com.thoriumbuilder.firebase] Twitter Authentification not allowed with file: protocol";
            app.dialog.alert(m)
            thoriumapi.logEvent(1,m);
            return;
        }
        var provider = new firebase.auth.TwitterAuthProvider();
        firebase.auth().signInWithPopup(provider)
            .then(function (result) {
                // This gives you a Google Access Token.
                var token = result.credential.accessToken;
                // The signed-in user info.
                var user = result.user;
            })
            .catch(function (error) {
                app.preloader.hide();
                app.dialog.alert(error.message);
                return;
            });
    },

    setUserAvatar: function (e) {
        var user = firebase.auth().currentUser;
        if (user != null) {
            var avt = user.photoURL || "img/defaultavatar.png";
            $(".firebase_avatar").attr('src', avt);
            $(".firebase_avatar").attr('alt', user.displayName);
            $(".firebase_avatar").attr('title', user.displayName);
        }
    },

    initialize: function () {
        $(".apploader").show();
        firebasePlugin.translatescreen();
        $('.login-screen-title').text(app.name);
        setTimeout(function () {
            $(".apploader").hide();
        }, 2000);
    },

    handleAvatarPopup: function (e,sender) {
        e.preventDefault();
        var user = firebase.auth().currentUser;
        if ((!user) || (user.isAnonymous == true)) {
            var b = firebaseAllowRegister || false;
            if (b == true) { firebasePlugin.showLoginScreen(); }
        } else {
            const lnk =e.target.getAttribute("data-page");
            if (!lnk) {
                $("#firebasecustomprofile").hide();
            } else {
                var t=e.target.getAttribute("data-label");
                $("#firebasecustomprofile").attr("href","/"+lnk+"/");
                $("#firebasecustomprofile").text(t);
                $("#firebasecustomprofile").show();
            }
            var popover = app.popover.open(".firebase-popover", sender, true);
        }
    },

}

/* -- Edit Profile Profile Image Management --*/
$("html").on("drop", function (e) { e.preventDefault(); });
$("html").on("dragover", function (e) { e.preventDefault(); });
$(document).on('dragenter', '.firebase_profile_avatar', function (e) {
    e.preventDefault();
    $(this).css("opacity", "0.5");
    e.stopPropagation();
});
$(document).on('dragleave', '.firebase_profile_avatar', function (e) {
    e.preventDefault();
    $(this).css("opacity", "1");
    e.stopPropagation();
});
$(document).on('drop', '.firebase_profile_avatar', function (e) {
    e.preventDefault();
    var f = e.dataTransfer.files[0];
    $(this).css("opacity", "1");
    firebasePlugin.firebase_handleProfileImage(f);
    e.stopPropagation();
});
$(document).on('click', '.firebase_profile_avatar', function (e) {	 /*-- Click on user Profile Image --*/
    e.preventDefault;
    if ((thoriumapi.isLocal()== true) && ((app.device.ios) || (app.device.android))) {
        var iconTooltip = app.tooltip.create({
            targetEl: $(this),
            text: 'Drop your file here',
        });
        iconTooltip.show();
    }
    $('.firebase_profile_avatar_input').trigger('click');
});

$(document).on('change', '.firebase_profile_avatar_input', function (e) {
    firebasePlugin.onFirebaseAvatarChange(e);
});


/* -- SIGN IN FORM --*/
$(document).on('submit', '.firebase-signin-form', function (e) {
    firebasePlugin.signInExt(e);
});

/* -- AUTH EVENTS HANDLERS --*/
$(document).on('click', '.firebase_register', function (e) {
    firebasePlugin.showRegisterScreen(e);
});

$(document).on('click', '.firebase_resetpasswword', function (e) {
    firebasePlugin.showResetPwScreen(e);
});

$(document).on('click', '.firebase_editprofile', function (e) {
    firebasePlugin.showEditProfilePageExt(e);
});
$(document).on('click', '.firebase-user-logout', function (e) {
    e.preventDefault();
    const m=firebasePlugin.getTranslatedString("logout")||"Logout";
    app.dialog.confirm(m+'?', function () {
        firebasePlugin.logoutExt();
    });
});

$(document).on('click', '.firebase_fb_login', function (e) {
    firebasePlugin.facebookLoginExt(e);
});

$(document).on('click', '.firebase_google_login', function (e) {
    firebasePlugin.googleLoginExt(e);
});

$(document).on('click', '.firebase_twitter_login', function (e) {
    firebasePlugin.twitterLoginExt(e);
});

$(document).on('click', '.firebase_avatar', function (e) {
    firebasePlugin.handleAvatarPopup(e,$(this));
});

/* -- RESET PASSWORD FORM --*/
$(document).on('click', '.resetpassword-submit', function (e) {
    e.preventDefault;
    if (document.getElementById('firebase-resetpw-form').checkValidity()==true) {
        firebasePlugin.resetPasswordExt(e);
    }
});

/*-- Edit Profile Submit --*/
$(document).on('click', '.submit_firebase-profile', function (e) {
    e.preventDefault;
    firebasePlugin.updateUserExt(e);
});

/* -- REGISTER FORM --*/
$(document).on('click', '.submit_firebase-register', function (e) {
    e.preventDefault;
    firebasePlugin.registerExt(e);
});

$(document).on('input', '.firebase_profile_displayname', function (e) {
    $('.firebase-displayname').text($('.firebase_profile_displayname').val());
});
/* -- AUTH EVENTS HANDLERS --*/

window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
    thoriumapi.logEvent(2, "[com.thoriumbuilder.core] An error occured: " + errorMsg + 'url=' + url + " line" + lineNumber);
    return false;
}


$(document).on('page:init', function (e) {
    firebasePlugin.setUserAvatar(e);
})

/* -- Auth Listener --*/
firebase.auth().onAuthStateChanged(function (user) {
    app.emit('onAuthStateChanged', user);
    var username;
    if (user) {
        if (user.isAnonymous = true) { username = "Anonymous" } else { username = user.displayName; }
    } else { username = "no session" }
    thoriumapi.logEvent(0, "[com.thoriumbuilder.firebase] onAuthStateChanged [" + username + "]");
    firebasePlugin.handleStateChangedExt(user);
    if (typeof googleMapPlugin !== 'undefined') {
        googleMapPlugin.initializePlugin();
    }
    if ( (typeof firestorePlugin !== 'undefined') && (user) ) {
        $(".firebase-single-form").each(function (form) {
            firestorePlugin.singleRecordFormInit(form);
        });
        if ((user.isAnonymous == true) && (firebaseAnonymous == false)) {
            thoriumapi.logEvent(0, "[com.thoriumbuilder.firestore] Current User is Anonymous");
        } else {
            firestorePlugin.firebase_initFirebaseVirtualLists(true);
            firestorePlugin.firebase_initFirebaseDisplayers(true);
            if (typeof openStreetMapPlugin != 'undefined') {
                thoriumapi.logEvent(0, "[com.thoriumbuilder.firestore] openStreetMapPlugin detected, initializing Maps");
                setTimeout(function () { openStreetMapPlugin.reloadAllMaps(); }, 100);
            }
        }
    }
});

