
/////// global vars.../////////////
var username = "";
var password = "";
var userAskedToRegisterAlready = false; // only ask once..
var status = "initialized";


//
// called from the register page...once it is shown...set the cookie to show "declinedregistration"
//
function updateCookieToNotAskThemToRegisterAgain()
{
    username = "declinedregistration";
    password = "declinedregistration";
            
    // now set the cookie with these login value...
    setTheCookie();
}


//
// set the login status
//
function setLoginStatus( val )
{
    //alert("login.js setLoginStatus() - login status being set to " + val);
    status = val;
}

//
// set the login status
//
function getLoginStatus()
{
    //alert("login.js getLoginStatus() - login status is " + status);
    return status;
}



//
// launched when a logged in user clicks on the logout link (which is also the registration link initially)
// 
function handleLogoutEvent()
{

    //console.log(" handleLogoutEvent() - called...username is: " + username + " password is " + password);

    // call logout service
    var queryString = "services/userLogout_Service.php?";

    //console.log("  handleLogoutEvent() - calling userLogout_service with the following values " + queryString);

    $.getJSON(queryString,
	    function( responseData ) { 
	      var returncode     = responseData.data.returncode;
	      if (returncode != "success") 
		{
		    //console.log (" handleLogoutEvent() - logout failed!");
		  return;
		}
	      else
		  {
		      //console.log (" handleLogoutEvent() - logout succeeded");
		      finishLogoutEvents();
		  }

	    }
	);
}


//
// this nulls the cookie, and updates the text on the nav bar...
//
function finishLogoutEvents()
{
    // first null out the username and password fields
    username = "loggedout";
    password = "loggedout";

    // now set the cookie with these login value...
    setTheCookie();

    setLoginStatus( "loggedout" );

    // update text on the nav bar...
    resetLoginTextOnNavBar();
    setLogoutTextOnNavBarToRegister();
}

function setUsername( user )
{
    username = user;
}


function getUsername()
{
    return username;
}


function setPassword( pass )
{
    password = pass;
}

function getPassword()
{
    return password;
}


function setLogoutTextOnNavBarToRegister()
{
    // now update register button to have logout on it...
    var registerString = "<a href=\"register.php\" id=\"register\" >register</a>";
    $('#logout').replaceWith( registerString );
}

function setRegisterTextOnNavBarToLogout()
{
    // now update register button to have logout on it...
    var logoutString = "<a href=\"\" onClick=\"javascript:handleLogoutEvent(); return false;\" id=\"logout\" >" + "logout" + "</a>";
    $('#register').replaceWith( logoutString );
}


function setLoginTextOnNavBar()
{
    // now try to update the "register" id text on the main nav bar with [ Welcome, user ], and turn off any href (click events).
    var welcomeString = "<a href=\"#\" id=\"login\" >" + "welcome, " + username + "!" + "</a>";
    $('#login').replaceWith( welcomeString );
    $("#login").css({'color' : '#FFB00F', 'text-decoration' : 'none'});
}

function resetLoginTextOnNavBar()
{
    // next, update the Login link on the nav bar...
    var loginString = "<a href=\"login.php\" id=\"login\" >" + "login" + "</a>";
    $('#login').replaceWith( loginString );
}


//
// utility functions
// 
function validUser()
{
   if (getUsername() == "" || getUsername() == "declinedregistration" || getUsername() == "loggedout")
     {
       return false;
     }

   return true;
}


//
//
// name of cookies
function getCookieName(){
   return 'fgcookie';
}

function getSessionName()
{
  return 'PHPSESSID';
}

//
// expiration of the cookie is one year out...
// 
function getExpirationDate(){
   var aYear = 31536000000; // one year in milliseconds to set cookies ahead...
   var timeToKeep = aYear;
   
   var expires = new Date();
   
   expires.setTime(expires.getTime() + timeToKeep);
   
   return expires;
}


//
// here is how the information is stored.
// 
function getCookieFieldToStore(){
   var cookieFieldToStore = username + ":" + password;
   
   return cookieFieldToStore;
}

//
// actually set the cookie..
// 
function setTheCookie(){
   set_cookie(getCookieName(), getCookieFieldToStore(), getExpirationDate());
}


function doesCookieExist(){
   var field_1 = get_cookie(getCookieName());
   
   if (field_1 != null) {
       //alert("cookie DOES exist");
       return true;
   }
   
   //alert("cookie does NOT exist");
   return false;
}


//
//  assumption is that user has checked for existence of cookie via doesCookieExist() prior to calling...
// 
function getTheCookie(){
   var field_1 = get_cookie(getCookieName());
   //console.log("getTheCookie() - returned the cookie value of " + field_1);
   
   // there is a colon delimiter between username and password
   var delimiterIndex = field_1.search(/:/);
   username = field_1.substr(0, delimiterIndex);
   
   var stringLength = field_1.length;
   password = field_1.substr(delimiterIndex + 1, stringLength);
   
   // alert("username: " + username + " password: " + password);
}


//
//  get session data from PHPSESSID
// 
function getThePHPSessionID()
{
  var sessionID = get_cookie(getSessionName());

  // alert('index.php session id is ' + sessionID);

  return sessionID;
}


function deleteThecookie(){
   del_cookie(getCookieName());
}

//       $(".about_info:visible").fadeOut("slow", function(){
//           $("#" + tab).fadeIn("slow");
//       });


function login(){
    user = $('#username').val();
    pass = $('#password').val();

    //console.log("login() - called...");

    var queryString = "services/userLoginJSON.php?username=" + user + "&password=" + pass;
    
    $.getJSON(queryString, function(responseData){
	    //console.log("login() - got back responseData");
        
        var response = responseData.data.response;
        var user = responseData.data.user.username;
        
        //console.log("login() - response was: " + response);
        //console.log("login() - user is : "     + user);
        
        if (response == "failure") {
            // failed login!!!
            // alert("Invalid Username/Password - Please try again.");

	    // now try to update the "register" id text on the main nav bar with [ Welcome, user ]
	    var welcomeString = "<a href=\"#\" id=\"register\" >" + "Invalid login!" + "</a>";
	    $('#register').replaceWith( welcomeString );
        }
        else {
            // successful login!!!
            // console.log("login() - user successfully logged in - user  : "     + user);

            $("#username").val("");
            $("#password").val("");
            
            // update the global vars...
            username = user;
            password = pass;
            
            // now set the cookie with these login value...
            setTheCookie();

	    // now try to update the "register" id text on the main nav bar with [ Welcome, user ]
	    var welcomeString = "<a href=\"#\" id=\"register\" >" + "welcome - " + username + "</a>";
	    $('#register').replaceWith( welcomeString );
	    $("#register").css({'color' : '#FFB00F', 'text-decoration' : 'none'});
        }
    });
}