cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External CSS

These stylesheets will be added in this order and before the code you write in the CSS editor. You can also add another Pen here, and it will pull the CSS from it. Try typing "font" or "ribbon" below.

Quick-add: + add another resource

Add External JavaScript

These scripts will run in this order and before the code in the JavaScript editor. You can also link to another Pen here, and it will run the JavaScript from it. Also try typing the name of any popular library.

Quick-add: + add another resource

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              html
	head
		title Game On
		link(href="stylesheets/css/jquery.mb.YTPlayer.min.css", media="all", rel="stylesheet", type="text/css")
		link(href="https://fonts.googleapis.com/css?family=Squada+One|Ubuntu+Condensed" rel="stylesheet")
		link(rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon")
		link(rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css")
		link(rel="stylesheet" href="/stylesheets/style.css" type="text/css")

		script(src="http://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js")
		script(src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous")

		

		script(type='text/javascript' src='/javascripts/script.js')

	body
p.introduction Only for demonstration purpose click the lick below to see the live site!

		div.main-content-wrapper.container
			div.container.first-page
		
		div.main-content-wrapper.container
			div.first-section.container.text-center
				div.row
					div.col-xs-2.col-xs-offset-10.col-sm-2.col-sm-offset-10.col-md-2.col-md-offset-10.log-in-container
				div.row
					div.game-on.col-xs-2-offset-5.col-sm-2-offset-5.col-md-2-offset-5
						h1 
							span#game GAME 
							span#on ON
						
			
				div.row
					div.game-on.game-on-fade.col-xs-2-offset-5.col-sm-2-offset-5.col-md-2-offset-5
						h3#experience A Data Visualization Experience
					div.row
						div.game-on.game-on-fade.col-xs-2-offset-5.col-sm-2-offset-5.col-md-2-offset-5
							button.about-button(type="button"  data-toggle="modal" data-target="#about") About 
								span#button-tag GAME ON
							
			div.second-section.container
				a(href='/')
					img#back-arrow(src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDhTPOqr8RKHMZaDJ6NOwFyEmql5fL9DwFbOC04R2N3CPWdIyCTA")
				div.row
					div.sign-up-form-container
						form.sign-up.col-xs-4.col-xs-offset-4.col-sm-4.col-sm-offset-4.col-md-4.col-md-offset-4.text-center(action="/signUp" method="post")
							div.form-group.signupform
								label.index-label User Name
								input.index-input(type='text' placeholder='User Name' name="username")
							div.form-group.signupform
								label.index-label  Email
								input.index-input(type='email' placeholder='Email' name="email")
							div.form-group.signupform
								label.index-label  Password
								input.index-input(type='password' placeholder='Password' name="password")
							div.form-group
								label.index-label  
							button.save-btn(type='submit') Submit
					div.login-form-container
						form.login.col-xs-4.col-xs-offset-4.col-sm-4.col-sm-offset-4.col-md-4.col-md-offset-4.text-center(action='/login' method="post")
							div.form-group.login-form
								label.index-label Email
								input.index-input(type='email' placeholder='Email' name="email") 
							div.form-group.login-form
								label.index-label Password
								input.index-input(type='password' placeholder='Password' name="password")
							button.save-btn(type='submit') Submit



			div#about.modal.fade(tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel")
				div.modal-dialog(role="document")
					div.modal-content
						div.modal-header
							button.close(type="button" data-dismiss="modal" aria-label="Close")
							h4.modal-title#gridSystemModalLabel About
						div.modal-body
							div.row
								div.col-xs-10.col-xs-offset-1.col-sm-10.col-sm-offset-1.col-md-10.col-md-offset-1
									p Game On is a full stack web app used to visualize sports data. It allows users to visualize player and team stats like never before and perform analyses that have previously been difficult to render. Users can log in with a user name and password, save favorite players, and build visualization charts from player data. Users also get an automatically-updated news feed for timely inspiration of players to compare stats on.
											
						div.modal-footer
							button.cancel-btn(type="button" data-dismiss="modal") Close
            
          
!
            
              body {
  font: 14px Verdana, Helvetica, Arial, sans-serif;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  height: 100vh;
  width: 100vw;
  background-color: #333335 ;
  background: linear-gradient(black, #333335);
}
::-webkit-scrollbar {
    width: 0;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}
a {
  color: #00B7FF ;
}
.introduction{
  color:#fffcf7;
}
#player-image {
  width: auto;
  /*height:  100%;*/
  margin-left: -15px;
  background: url('http://198.1.111.123/~theinscr/wp-content/uploads/2016/12/nba-logo-on-wood.jpg');
  background-size: contain;
}

#back-arrow{
  position: fixed;
  left: 10px;
  top: 10px;
  height: 50px;
  width: 50px;
  border-radius: 100%;
  border: 1px solid white;
}

h1{
  font-family: 'Squada One', sans-serif;    
  text-align: center;
  color: white;
  padding-top: 330px;
  font-size: 8rem;  
  text-shadow: 2px 3px black;
}

#game{
   animation: connect 2s 1;
    position: relative;
    animation-timing-function: ease-in-out;
    animation-delay: 200ms;
}

@keyframes connect {
  0%   {left: -900px;}
  30%  {left: 0;}
  60% {left: 0;}
  80% {left: 0px;}
  100% {left: 0;}
}

#on{
  animation: on 2s 1;
    position: relative;
    animation-timing-function: ease-in-out;
    animation-delay: 200ms;
}

@keyframes on {
  0%   {right: -700px;}
  30%  {right: -700px;}
  60%  {right: 0;}
  80%  {right: 0px;}
  100% {right: 0px;}
}

h3{
    font-family: Verdana, sans-serif;
    text-align: center;
    font-size: 3rem;
    font-weight: 600;
    color: #fac51c ;
}

.game-on-fade{
   animation: fadein 6s;
}

@keyframes fadein {
  from {opacity: 0;}
  to {opacity: 1;}
}

#experience{
    font-family: Verdana, sans-serif;
    text-align: center;
    text-shadow: 1px 1px black;
    font-size: 25px;
    font-weight: 600;
    color: #fac51c ;
}

p, h5 {
  font-size: 1.5rem;
}

.message {
  color: #AF1B3F;
}

.log-in{
    font-size: 20px;
    color: #fac51c ;    
    border: none;
    border-radius: 50%;
    background-color: transparent;
    float: right;
    margin-bottom: 5px;
    text-shadow: .5px .5px black;
}

.main-content-container {
  width: 100vw;
  padding: 5px;
}

.sign-up-form-container, .login-form-container {
  margin-top: 320px;
  padding: 0;
}

.signupform, .login-form {
  float: right;
}

.index-input {
  background-color: #dcdcdc;
  color: #666666;
  border: none;
  font-size: 18px;
}

.index-label  {
  color: #dcdcdc;
  text-shadow: 1px 2px black;
  font-size: 18px;
}

.settings-button {
  border: none;
    border-radius: 50%;
    background-color: transparent;
    float: right;
    margin-top: 10px;
    color: #dcdcdc;
}

.settings-button:hover {
  color: white;
  background-color: transparent;
}

.settings-button:focus {
  color: #dcdcdc;
  background-color: transparent;
  outline: none;
}


.log-in:hover{
    opacity: 0.5;
}

#start-btn{
  background-color: rgba(35, 35, 35, .6);
  font-size: 23px;
  font-weight: 700;
  color: white;
  text-shadow: 1px 2px black;
  border: 1px solid black;
}
#start-btn:focus{
  outline: none;   
}

.begin-container{
    text-align: center;
    height: 60px;

}

.form-container{
    text-align: center;
  margin-top: 100px;
}

/*.form-group {
  margin: 15px;
}*/

label {
  margin-right: 15px;
}

.second-section{
    display: none;
}
.first-section{
    transition: all;
}

.nav-bar, .option-panel-container, .charts-container, .news-container {
  border:  1px solid black;
}

.option-panel-container {
  padding: 1rem;
}

.nav-bar {
  width:  100%;
  height: 50px;
  background-color: #333335 ;
  background: linear-gradient(black, #333335);
}


.option-panel {
  width: 100%;
  /*margin: 5px;*/
  height:100%;
  padding: 0;
}

.option-panel-container, .charts-container, .news-container {
  height: 100%;
  /* width:  50%; */
  background-color: #333335 ;
  background: linear-gradient(#333335, black);
}

.option-panel-container h3,h5, .news-container h3{
  color: #77fc2a ;
}

.option-panel h3, .news-container h3{
  font-family: 'Permanent Marker', cursive;
}


/*.pic, .info {
  width: 90%;
  height: 30%;
}*/
/*.pic-container {
  margin: 5px;
}*/
.pic {
  margin-top: 10px;
  /*border: 1px solid white;*/
  background-color: #333335;
  max-width: 100%;
  overflow: hidden;
}

input {
  background-color: #777777;
  color: #dcdcdc;
  border: none;
  font-size: 18px;
}


select {
  background-color: #666666;
  color: #dcdcdc;
  border: none;
  margin-right: 10px;
  font-size: 18px;
}

.compare-btn {
  background-color: #666666;
  color: #dcdcdc;
  border: none;
  font-size: 18px;
}

#comparison-message{
  font-family: 'Acme', sans-serif;
  font-size: 2rem; 
}

#compare-submit {
  margin-left: 5px;
  margin-top: 10px;
}
.info{
  border: none;
  color: white;
  color: #77fc2a ;
}

.info #add-player{
  color: black;
}
.news-container {
  overflow: scroll;
}

#compare-search-input{
    display: none;
    margin-top: 10px;
    margin-bottom: 10px;
}
#search-input {
  width:90%;
}

#submit{
  margin-left: 8px;
}

#charts{
  margin-top: 15px;
  height:500px;
}


#stats-table {
  color: #D75F57 ;
}

.table{
  color: #D75F57 ;

}
#data-table {
  margin-bottom: 0;
}

tr{
  text-align: center;
}

.modal-content {
  background-color: rgba(50, 50, 50, .9);
  color: #dcdcdc;
}

.modal-header {
  color: #dcdcdc;
}

.modal-table {
  color: #dcdcdc;
}

.table-hover tbody tr:hover td, .table-hover tbody tr:hover th {
  background-color: rgba(40, 40, 40, 1);
  border-bottom: none;
  border-top: none;
}

.edit-btn, .remove-btn {
  background-color: #666666;
  color: #dcdcdc;
  border: none;
  border-radius: 0;
}



.save-btn {
  background-color: green;
  color: #dcdcdc;
  border: none;
  border-radius: 0;
  font-size: 18px;
  margin-left: 15px;
}

.save-btn:hover {
  background-color: #77FC2A;
  color: #666666;
}

.cancel-btn {
  background-color: #dcdcdc;
  color: #666666;
  border: none;
  border-radius: 0;
  font-size: 18px;
  margin-right: 15px;
}

#nav-header{
  font-family: 'Squada One', sans-serif;    
  color: white;
  font-size: 33px;  
  text-shadow: 2px 3px black;
  float: left;
  margin-top: 5px;
  margin-left: 10px;
}

#logout-link{
  font-family: 'Squada One', sans-serif;    
  color: white;
  font-size: 33px;  
  text-shadow: 2px 3px black;
  float: left;
  margin-top: 5px;
  margin-left: 10px; 
}

#logout-link:hover{
  text-decoration: none;
}


.about-button{
    font-family: Verdana, sans-serif; 
    font-size: 16px;
    background: transparent;
    text-shadow: 1px 1px black;
    /* background-color: rgba(35, 35, 35, .5); */
    color: white ;
    margin-top: 20px;
    border: solid 1px black;
}

ul {
  list-style-type: none;
  padding: 0;
  font-family: 'Acme', sans-serif; 
}

#list-name, #list-team, #list-position{
  font-size: 2rem;   
}

#button-tag{
    font-family: 'Squada One', sans-serif;    
  text-align: center;
    color: white;
    font-size: 25px;  
  text-shadow: 2px 2px black;
}

#first-player{
    color: #2B908F;
}

#second-player{
    color: #90EE7E;
}

#table-lables{
    color: #E0E0E3;
}

#table-title{
    color: #E0E0E3;
}

@media (max-width: 768px){
  .option-panel-container{
    height: 95%;
  }
  #tweets{
    display: none;
  }
}
@media (min-width: 768px){
  .search-bar {
  margin: 0.8rem;
  }
  .pic-container {
    margin-left:0.3rem;
  }
  .info {
    margin-left: 1rem;
  }
  .info ul{
    padding: 0;
  }
  .fav-form-container{
    margin-left: 1rem;
  }

  .compare-btn {
    font-size: 2rem;
  }
}

@media only screen and (max-width: 555px){
    #table-lables{
        font-size: 10px;
    }
    #first-player{
        font-size: 10px;
    }
    #second-player{
        font-size: 10px;
    }
    #table-title{
        font-size: 12px;
    }
}


.news-container{
  height: 100vh;
}

.tweet-container {
  display: flex;
  justify-content: center;
  width: 100%
}
            
          
!
            
              var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var btoa = require('btoa');
var bcrypt = require('bcrypt-nodejs');
var serverInfo = require('../config/config');
var array = [];
var request = require('request');
var newsApiKey = serverInfo.newApiKey;
var Twitter = require('twitter');



// =====Go to HOME page ====
router.get('/', function(req, res, next) {
    res.render('index', {sessionInfo: req.session});
});

// ===  Connec to local database ====
var connection = mysql.createConnection({
    host: serverInfo.host,
    user: serverInfo.username,
    password: serverInfo.password,
    database: serverInfo.database
});
connection.connect();

// === Get request for USER page =====
router.get('/user', (req, res)=>{

  // === Condition for deciding which player stats to load ===
  var screen_name;
    if (req.session.currentPlayer != undefined){
      screen_name = req.session.currentTwitter;
      randomGoodPlayer = req.session.currentPlayer;
    } else if (req.session.fav_player != undefined) {
        bestPlayerIds = req.session.favPlayer;
        randomGoodPlayer = bestPlayerIds[Math.floor(Math.random() * bestPlayerIds.length)].player_id;
    } else {
        bestPlayerIds = [106, 129, 187, 20, 236, 231, 372, 477, 291, 450, 278, 182, 134, 386];
        randomGoodPlayer = bestPlayerIds[Math.floor(Math.random() * 14)];
    }
  // ==== MySQL Query for getting photos from local database ======

  var news = [];
  var averagePlayerId = 519;
    var selectQuery = `SELECT photo, team, position, first_name, last_name, twitter_name FROM player_info WHERE (id = ${randomGoodPlayer}) OR (id = ${averagePlayerId});`;
    connection.query(selectQuery, (error, results)=>{
      if(error) throw error;
      var photoUrl = results[0].photo;
      var teamName = results[0].team;
      var position = results[0].position;
      var firstName = results[0].first_name;
      var lastName = results[0].last_name;
      screen_name = results[0].twitter_name;
      var fullName = firstName + ' ' + lastName;
      var compName = results[1].first_name + ' ' + results[1].last_name;

      // ==== Making JSON Request for news feed =====

      var newsUrl = `http://api.nytimes.com/svc/search/v2/articlesearch.json?q=${fullName}&page=2&sort=newest&api-key=${newsApiKey}`;
      request.get(newsUrl, (err, response, newsData)=>{
        var newsData = JSON.parse(newsData);
        if (err) throw err;
        for (let i = 0; i < newsData.response.docs.length; i ++){
          news.push([newsData.response.docs[i].headline.main, newsData.response.docs[i].web_url]);
        }

        // === Setting up Twitter ===

      
      var tweet;
      var T = new Twitter(serverInfo);
      var params = {
        screen_name: screen_name,
        result_type: 'recent',
        lang: 'en',
        include_rts: "false",
      }

      T.get('statuses/user_timeline', params, function(err, data, response){
        if(!err){
          // res.json(data);
            tweetUrl = `https://twitter.com/NBA/status/${data[0].id_str}`;
            // console.log(tweet);
            var options = {
              url: tweetUrl,
              lang:"en",
              theme:"dark",
              link_color:"#2B7BB9",
              hide_media:"true",
              include_rts: "false",
            }
            T.get('statuses/oembed', options, function(err, data, response){
                if(!err){ 
                  console.log(data.url);
                   tweet = data.url;
                }else{
                  console.log(err);
                }

      


        // === Getting player stats from per_game table ====

        var rankQuery = `SELECT PPGrank, ASSrank, STLrank, REBrank, MINrank, THREErank,total_points, assists, steals, rebounds, minutes, three_points FROM per_game WHERE (id = ${randomGoodPlayer}) OR (id = ${averagePlayerId});`;
        connection.query(rankQuery, (error, results)=> {
          console.log(results[0]);
          var PPGrank = Math.round((results[0].PPGrank/517)*10000)/100;
          var ASSrank = Math.round((results[0].ASSrank/517)*10000)/100;
          var STLrank = Math.round((results[0].STLrank/517)*10000)/100;
          var REBrank = Math.round((results[0].REBrank/517)*10000)/100;
          var MINrank = Math.round((results[0].MINrank/517)*10000)/100;
          var THREErank = Math.round((results[0].THREErank/517)*10000)/100;
          var total_points = results[0].total_points;
          var assists = results[0].assists;
          var steals = results[0].steals;
          var rebounds = results[0].rebounds;
          var minutes = Math.round(results[0].minutes * 100) / 100;
          var three_points = results[0].three_points;

          var compPPGrank = Math.round((results[1].PPGrank/517)*10000)/100;
          var compASSrank = Math.round((results[1].ASSrank/517)*10000)/100;
          var compSTLrank = Math.round((results[1].STLrank/517)*10000)/100;
          var compREBrank = Math.round((results[1].REBrank/517)*10000)/100;
          var compMINrank = Math.round((results[1].MINrank/517)*10000)/100;
          var compTHREErank = Math.round((results[1].THREErank/517)*10000)/100;
          var comptotal_points = results[1].total_points;
          var compassists = results[1].assists;
          var compsteals = results[1].steals;
          var comprebounds = results[1].rebounds;
          var compminutes = Math.round(results[1].minutes * 100) / 100;
          var compthree_points = results[1].three_points;

          // ===== Creating full name array for autocomplete function for the search bar =====
          array = [];
          var nameQuery = "SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM player_info;";
          connection.query(nameQuery, (error, results)=>{
            if(error) throw error;
              for (let i = 0; i < results.length; i++){
                array.push(results[i].full_name);
              }

              // ====== Getting user's favorite players list from fav_player table ====

              var userFaves = [];
              var faveQuery = `SELECT CONCAT(player_info.first_name, ' ',
                          player_info.last_name)
                          AS player_full_name
                         FROM player_info
                         INNER JOIN fav_player ON player_info.id = fav_player.player_id WHERE user_email = '${req.session.email}';`;
              connection.query(faveQuery, (error, results)=> {
                for (let i = 0; i < results.length; i++) { 
                  userFaves.push(results[i].player_full_name);
              }
              var sessionInfo = req.session;
              res.render('user-page', {
                photoUrl: photoUrl,
                teamName: teamName,
                position: position,
                fullName: fullName,
                sessionInfo: sessionInfo,
                total_points: total_points,
                assists: assists,
                steals: steals,
                rebounds: rebounds,
                minutes: minutes,
                three_points: three_points,
                PPGrank: PPGrank,
                ASSrank: ASSrank,
                STLrank: STLrank,
                REBrank: REBrank,
                MINrank: MINrank,
                THREErank: THREErank,
                nameArray: array,
                id: randomGoodPlayer,
                userFaves: userFaves,
                news:news,
                compPPGrank: compPPGrank,
                compASSrank: compASSrank,
                compSTLrank: compSTLrank,
                compREBrank: compREBrank,
                compMINrank: compMINrank,
                compTHREErank: compTHREErank,
                comptotal_points: comptotal_points,
                compassists: compassists,
                compsteals: compsteals,
                comprebounds: comprebounds,
                compminutes: compminutes,
                compthree_points: compthree_points,
                compName: compName,
                tweets: tweet,
                twitterName: screen_name
              });
              });
            });
          });
          });
        }else{
          console.log(err);
        }
        });
      });
    });
  });

// ============= Post request from add favortite players button =========
router.post('/add_fav', (req,res)=>{
    var fav = req.body.favorite;
    var user_email = req.session.email;
    req.session.registered = false;
    var favQuery = "INSERT INTO fav_player(user_email, player_id) VALUES (?, ?);";
    var alreadyAddedQuery = `SELECT player_id, user_email FROM fav_player WHERE user_email = '${user_email}' AND player_id = '${fav}';`;

    connection.query(alreadyAddedQuery, (error, results)=>{
        if(error)throw error;
        //console.log(results);
        if(results.length > 0){
            req.session.currentPlayer = fav;
            res.redirect(`/user?msg=addedPlayer`);
        }else{
            connection.query(favQuery,[user_email, fav], (error, results)=>{
                if(error)throw error;
                req.session.currentPlayer = fav;
                res.redirect(`/user?msg=addedPlayer`);
            });
        }
    });
});

  router.get('/fav_load/:val', (req, res)=>{
    var fullName = req.params.val;
    console.log(fullName);
    var nameArray = fullName.split(' ');
    var idQuery = `SELECT id, twitter_name FROM player_info WHERE (first_name = '${nameArray[0]}' AND last_name = '${nameArray[1]}');`; 
    connection.query(idQuery, (error, results)=>{
      if(error) throw error;
      console.log(results);
      var idToLoad = results[0].id;
      var twitterToLoad = results[0].twitter_name;
      req.session.currentPlayer = idToLoad;
      req.session.currentTwitter = twitterToLoad;
      res.redirect('/user?msg=loadFav');
    });
  });
/////////////////////

// ================= Post request from user page ===========

router.post('/user', (req, res)=>{
  var fullName = req.body.search;
  var nameArray = req.body.search.split(' ');
  var compName = req.body.compare;
  var compNameArray = req.body.compare.split(' ');
  var compareId;
  var playerId;
  var news = [];
  var newsUrl = `http://api.nytimes.com/svc/search/v2/articlesearch.json?q=${fullName}&page=2&sort=newest&api-key=${newsApiKey}`;
  var idQuery = `SELECT id FROM player_info WHERE (first_name = '${nameArray[0]}' AND last_name = '${nameArray[1]}')
  OR (first_name = '${compNameArray[0]}' AND last_name = '${compNameArray[1]}');`;
  request.get(newsUrl, (err, response, newsData)=>{
    var newsData = JSON.parse(newsData);
    if (err) throw err;
    for (let i = 0; i < newsData.response.docs.length; i ++){
      news.push([newsData.response.docs[i].headline.main, newsData.response.docs[i].web_url]);
    }
    // console.log(news);
    connection.query(idQuery,(error, results)=> {
      if (error) throw error;
      playerId = results[0].id;
      compareId = results[1].id;

      // console.log(typeof(playerId));
      var selectQuery = `SELECT photo, team, position, twitter_name FROM player_info WHERE id = '${playerId}';`;

        connection.query(selectQuery, (error, results)=>{
          if(error) throw error;
          var photoUrl = results[0].photo;
          var teamName = results[0].team;
          var position = results[0].position;
          var screen_name = results[0].twitter_name;
          console.log(screen_name);
          // === Setting up Twitter ===

      
      var tweet;
      var T = new Twitter(serverInfo);
      var params = {
        screen_name: screen_name,
        result_type: 'recent',
        lang: 'en',
        include_rts: "false",
      }

      T.get('statuses/user_timeline', params, function(err, data, response){
        if(!err){
          // res.json(data);
            tweetUrl = `https://twitter.com/NBA/status/${data[0].id_str}`;
            // console.log(tweet);
            var options = {
              url: tweetUrl,
              lang:"en",
              theme:"dark",
              link_color:"#2B7BB9",
              hide_media:"true",
              include_rts: "false",
            }
            T.get('statuses/oembed', options, function(err, data, response){
                if(!err){ 
                  console.log(data.url);
                   tweet = data.url;
                }else{
                  console.log(err);
                }
          
          var rankQuery = `SELECT PPGrank, ASSrank, STLrank, REBrank, MINrank, THREErank, total_points, assists, steals, rebounds, minutes, three_points FROM per_game WHERE (id = '${playerId}') OR (id = '${compareId}');`;

          connection.query(rankQuery, (error, results)=> {
            var PPGrank = Math.round((results[0].PPGrank/517)*10000)/100;
            var ASSrank = Math.round((results[0].ASSrank/517)*10000)/100;
            var STLrank = Math.round((results[0].STLrank/517)*10000)/100;
            var REBrank = Math.round((results[0].REBrank/517)*10000)/100;
            var MINrank = Math.round((results[0].MINrank/517)*10000)/100;
            var THREErank = Math.round((results[0].THREErank/517)*10000)/100;
            var total_points = results[0].total_points;
            var assists = results[0].assists;
            var steals = results[0].steals;
            var rebounds = results[0].rebounds;
            var minutes = Math.round(results[0].minutes * 100) / 100;
            var three_points = results[0].three_points;

            var compPPGrank = Math.round((results[1].PPGrank/517)*10000)/100;
            var compASSrank = Math.round((results[1].ASSrank/517)*10000)/100;
            var compSTLrank = Math.round((results[1].STLrank/517)*10000)/100;
            var compREBrank = Math.round((results[1].REBrank/517)*10000)/100;
            var compMINrank = Math.round((results[1].MINrank/517)*10000)/100;
            var compTHREErank = Math.round((results[1].THREErank/517)*10000)/100;
            var comptotal_points = results[1].total_points;
            var compassists = results[1].assists;
            var compsteals = results[1].steals;
            var comprebounds = results[1].rebounds;
            var compminutes = Math.round(results[1].minutes * 100) / 100;
            var compthree_points = results[1].three_points;

              var userFaves = [];
              var faveQuery = `SELECT CONCAT(player_info.first_name, ' ',
                          player_info.last_name)
                          AS player_full_name
                         FROM player_info
                         INNER JOIN fav_player ON player_info.id = fav_player.player_id WHERE user_email = '${req.session.email}';`;
              connection.query(faveQuery, (error, results)=> {

                  for (let i = 0; i < results.length; i++) {
                      userFaves.push(results[i].player_full_name);
                  }

            res.render('user-page', {
                photoUrl: photoUrl,
                teamName: teamName,
                position: position,
                fullName: fullName,
                sessionInfo: req.session,
                PPGrank: PPGrank,
                ASSrank: ASSrank,
                STLrank: STLrank,
                REBrank: REBrank,
                MINrank: MINrank,
                THREErank: THREErank,
                nameArray: array,
                total_points: total_points,
                assists: assists,
                steals: steals,
                rebounds: rebounds,
                minutes: minutes,
                three_points: three_points,
                id: playerId,
                news: news,
                compPPGrank: compPPGrank,
                compASSrank: compASSrank,
                compSTLrank: compSTLrank,
                compREBrank: compREBrank,
                compMINrank: compMINrank,
                compTHREErank: compTHREErank,
                comptotal_points: comptotal_points,
                compassists: compassists,
                compsteals: compsteals,
                comprebounds: comprebounds,
                compminutes: compminutes,
                compthree_points: compthree_points,
                compName: compName,
                userFaves: userFaves,
                tweets: tweet,
                twitterName: screen_name
            });
            });
          });
          });
        }else{
          console.log(err);
        }
        });
        });
      });
    });
  });

  router.post("/signUp", (req, res)=>{

    var message = req.query.msg;
    var username = req.body.username;
    var password = req.body.password;
    var email = req.body.email;
    var hash = bcrypt.hashSync(password);
    var selectQuery = "SELECT * FROM users WHERE email = ?;";
    
    connection.query(selectQuery, [email], (error, results)=> {
      if (results.length == 0){
        var insertQuery = "INSERT INTO users(username, password, email) VALUES(?,?,?);";
        connection.query(insertQuery, [username, hash, email], (error, results)=> {
          if(error) throw error;
          req.session.username = username;
          req.session.email = email;
          req.session.favPlayer = results;
          req.session.loggedin = true;
          req.session.registered = true;
          res.redirect('/user?msg=registered');
        });
      } else {
        res.redirect('/?msg=existingUser')
      }
    })
  });
    
    router.post('/login', (req, res)=> {
      console.log(req.body)
      var email = req.body.email;
      var password = req.body.password;
      var hash = bcrypt.hashSync(password);
      var selectQuery = "SELECT * FROM users WHERE email = ?;";
      connection.query(selectQuery, [email], (error, results)=> {
        if(error) throw error;
        if (results.length == 1){
            var match = bcrypt.compareSync(password, results[0].password);
            if (match){
              var username = results[0].username;
              var favPlayerIdQuery = `SELECT player_id FROM fav_player WHERE user_email = '${email}';`;
              connection.query(favPlayerIdQuery, (error, results)=>{
                if (error) throw error;
                req.session.email = email;
                req.session.favPlayer = results;
                req.session.loggedin = true;
                req.session.registered = false;
                req.session.username = username;
                res.redirect('/user?msg=loggedin');
              });
          } else {
          res.redirect('/?msg=invalid')
          }
        };
      });
    });

    router.get('/logout',(req,res)=>{
      req.session.email = undefined; 
      req.session.favPlayer = undefined; 
      req.session.loggedin= false; 
      req.session.registered= undefined;
      req.session.username= undefined;
      // console.log(req.session.favPlayer); 

                
      res.redirect('/');
    });

    router.get('/delete/:val', (req, res)=>{
      console.log(req.params.val);
      var fullName = req.params.val;
      var nameArray = fullName.split(' ');
      var idQuery = `SELECT id FROM player_info WHERE (first_name = '${nameArray[0]}' AND last_name = '${nameArray[1]}');`; 
      connection.query(idQuery, (error, results)=>{
        if(error) throw error;
        var idToDelete = results[0].id;
        var deleteQuery = `DELETE FROM fav_player WHERE player_id = '${idToDelete}' AND user_email = '${req.session.email}';`;
        connection.query(deleteQuery, (error, results)=>{
        if (error) throw error;
          res.redirect('/user?msg=deleted');
        });
      });
    });
    router.post('/changeUsername', (req,res)=>{
      var newUsername = req.body.newUsername;
      var updateQuery = `UPDATE users SET username='${newUsername}' WHERE email='${req.session.email}';`;
      connection.query(updateQuery, (error, results)=>{
        if(error) throw error;
        req.session.username = newUsername;
        res.redirect('/user?msg=changedUsername');
      });
    });
// ===========Code that used to create our own database from the mysportsfeeds API =======
// var getData = function(callback) {
//     'use strict';
        
//     const httpTransport = require('https');
//     const responseEncoding = 'utf8';
//     const httpOptions = {
//         hostname: 'www.mysportsfeeds.com',
//         port: '443',
//         path: 'https://www.mysportsfeeds.com/api/feed/pull/nba/2016-regular/cumulative_player_stats.json?playerstats=PTS/G,AST/G,STL/G,REB/G,MIN/G,3PM/G',
//         method: 'GET',
//         headers: {"Authorization":"Basic " + btoa('henaege' + ":" + 'DigitalCrafts')},
//     };
//     httpOptions.headers['User-Agent'] = 'node ' + process.version;
 
//     const request = httpTransport.request(httpOptions, (res) => {
//         let responseBufs = [];
//         let responseStr = '';
        
//         res.on('data', (chunk) => {
//             if (Buffer.isBuffer(chunk)) {
//                 responseBufs.push(chunk);
//             }
//             else {
//                 responseStr = responseStr + chunk;            
//             }
//         }).on('end', () => {
//             responseStr = responseBufs.length > 0 ? 
//                 Buffer.concat(responseBufs).toString(responseEncoding) : responseStr;
            
//             callback(null, res.statusCode, res.headers, responseStr);
//         });
        
//     })
//     .setTimeout(0)
//     .on('error', (error) => {
//         callback(error);
//     });
//     request.write("")
//     request.end();


// }((error, statusCode, headers, body) => {
//     console.log('ERROR:', error); 
//     console.log('STATUS:', statusCode);
//     console.log('HEADERS:', JSON.stringify(headers));
//     // console.log(body);
//     APIdata = JSON.parse(body);

// });
// router.get('/user', function(req, res, next){
//   var array = [];
//   var playerName = req.body.search;
//   var selectQuery = "SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM player_info;";
//   connection.query(selectQuery, (error, results)=>{
//     if(error) throw error;
//     for (let i = 0; i < results.length; i++){
//       array.push(results[i].full_name);
//     }
//     // console.log(array);
//     res.render('user-page', {playersFullName: array, sessionInfo: req.session});
//   });
//   // res.render('user-page', { });
// });


// var APIdata;


  // APIdata = JSON.parse(APIdata);
  // console.log(APIdata);
  // =======================Getting player Stats from the API database======================
    // var players = APIdata.cumulativeplayerstats.playerstatsentry;
    // // res.json(players);

    // // console.log(players[0].stats.PtsPerGame['#text']);
    // for(let i = 0; i < players.length; i++){
  //      var points = parseFloat(players[i].stats.PtsPerGame['#text']);
  //      var assists = parseFloat(players[i].stats.AstPerGame['#text']);
  //      var steals = parseFloat(players[i].stats.StlPerGame['#text']);
  //      var rebounds = parseFloat(players[i].stats.RebPerGame['#text']);
  //      var minutes = parseFloat(players[i].stats.MinSecondsPerGame['#text']) / 60;
  //      var threePoints = parseFloat(players[i].stats.Fg3PtMadePerGame['#text']);
  //      var insertQuery = `INSERT INTO per_game (total_points, assists, steals, rebounds, minutes, three_points) VALUES ('${points}', '${assists}', '${steals}', '${rebounds}', '${minutes}', '${threePoints}');`;
  //      connection.query(insertQuery, (error, results)=>{
  //        if(error) throw error;
  //      });
  //    }

  // ===================Getting player information from the API database ===============
  // var players = APIdata.cumulativeplayerstats.playerstatsentry;
  // console.log(players[0]);
  // for(let i = 0; i < players.length; i++){
 //     var first_name = players[i].player.FirstName.match(/[a-zA-z]+/);
 //     var last_name = players[i].player.LastName.match(/[a-zA-z]+/);
 //     var team = players[i].team.Name;
 //     var position = players[i].player.Position;
 //     var insertQuery = `INSERT INTO player_info (first_name, last_name, team, position) VALUES ('${first_name}', '${last_name}', '${team}', '${position}');`;
 //     connection.query(insertQuery, (error, results)=>{
 //       if(error) throw error;
 //     });
 //    }
   // =============================End of for loop===========================================

  // for(let i = 0; i < APIdata.playerstatsentry.length; i++){
    // res.render('test', {data: APIdata.cumulativeplayerstats.playerstatsentry[1].player.LastName});
  // =============================== Getting rank for each per_game data =========================
//   var array = [];
//   var playerName = req.body.search;
//   var selectQuery = "SELECT id FROM per_game ORDER BY three_points ASC;";
//   connection.query(selectQuery, (error, results)=>{
//     if(error) throw error;
//     for (let i = 0; i < results.length; i++){
//       array.push(results[i].id);
//     }
//     console.log(array);
//     for (let j = 0; j < array.length; j++){
//       var rank = j + 1;
//       var insertQuery = `UPDATE per_game SET THREErank = ${rank} WHERE id = ${parseInt(array[j])};`;
//       connection.query(insertQuery, (error, results)=>{
//       if (error) throw error;

//     });
//     }
// });
  //  ====================================END ======================================================
// ============= Creating database of username for player's twitter account ==========
// router.get('/', function(req, res, next) {
//       var fullNameQuery = "SELECT CONCAT(player_info.first_name, ' ', player_info.last_name) AS player_full_name, id FROM player_info;";
//       var array = []
//       connection.query(fullNameQuery, (err, results)=>{
//         if(err) throw err;
//         array = results;
//         for(let i = 0; i < twitterList.length; i++){
//           var twitterName = twitterList[i].Twitter;
//           var playerNameFromTwitterList = twitterList[i].Player;
//           playerNameFromTwitterList = playerNameFromTwitterList.split('\\');
//           playerNameFromTwitterList = playerNameFromTwitterList[0];
//           // console.log(playerNameFromTwitterList)
//           for(let j = 0; j < array.length; j++){
//             console.log(playerNameFromTwitterList);
//             if(playerNameFromTwitterList == array[j].player_full_name){
//                 var insertQuery = `UPDATE player_info SET twitter_name = '${twitterName}' WHERE id = ${array[j].id}`;
//                 connection.query(insertQuery, (err, results)=>{
//                   if (err) throw err;
//                   // res.render('index');
//                 });
//                 break;
//             }
//           }
//         }
//       });
                        
// });
            
          
!
999px
Loading ..................

Console