$(document).ready(function(){ $('#signout').click(function(){ firebase.auth().signOut().then(function() { window.location.replace('../') }).catch(function(error) { showAlert("Failed to sign out") }); }) firebase.auth().onAuthStateChanged(function(user) { if (user) { console.log(user) $("#sign").hide() $("#signed").show() } }); // var url = window.location.href; // var url = window.location.href; if( url.search( 'productid' ) > 0 ) { option = url.match(/productid=(.*)/)[1]; $.getJSON("../products.json", function(result){ var size = (Object.keys(result).length) if(option > -1 && option < size) { loadProduct(option); } else { showErrorDiv() } }) } else { loadAllProducts() } function loadProduct (productid) { $('#loader').empty(); $.getJSON("../products.json", function(result){ // console.log(result[productid]) str = ""; for(i=0; i< Object.keys(result[productid].productDescription).length; i++) { str += ('
  • ' + result[productid].productDescription[i] + '
  • '); } firebase.auth().onAuthStateChanged(function(user) { var cartRef = firebase.database().ref('userCart/' + user.uid + '/' + productid); cartRef.on('value', function(snapshot) { // console.log(snapshot.val()) if(snapshot.val() != null) { $('#loader').append('

    '+result[productid].productName+'

    $'+result[productid].productPrice+'

    '); } else { $('#loader').append('

    '+result[productid].productName+'

    $'+result[productid].productPrice+'

    '); } $('.clickAdd').click(function(){ // console.log(productid) var cartRef = firebase.database().ref('userCart/' + user.uid + '/' + productid); cartRef.set({ name : result[productid].productName, price : result[productid].productPrice }) $('#loader').empty(); $('#loader').append('

    '+result[productid].productName+'

    $'+result[productid].productPrice+'

    '); showAlert("Product added in cart. You can view your cart and check out now.") }) }); }); }) } function showErrorDiv() { $('#loader').empty(); $('#loader').append('

    This product does not exist.

    Click here to go home

    '); } function loadAllProducts() { $('#loader').empty(); $.getJSON("../products.json", function(result){ // console.log(result) var size = (Object.keys(result).length) for(i = 0; i < size ; i++) { $('#loader').append('

    '+result[i].productName+'

    $'+result[i].productPrice+'
    View Product
    ') } }); } $('#cart').click(function(){ window.location.replace('cart'); }) })