// exists:  Used to check if a jquery selector exists
jQuery.fn.exists = function(){return jQuery(this).length>0;}


// replacePwd:  Replaces a text input with a password input
function replacePwd(obj){
  var newO=document.createElement('input');
  newO.setAttribute('type','password');
  newO.setAttribute('name',obj.getAttribute('name'));
  obj.parentNode.replaceChild(newO,obj);
  newO.focus();
}    

// userLogin:  Logs a user into the site
function userLogin() {
  // Switch to processing
  $("#popoverLoginRegister").fadeOut(250, function() {$("#popoverProcessing").fadeIn(250, function() {
  
  // Clear error messages
  clearPopoverErrors();
  
  // Login details
  var login = $("#loginLogin").val();
  var password = $("#loginPassword").val();
  if($("#loginRememberMe").attr('checked')) {var remember_me = 1;}else {var remember_me = 0;}
  if($("input[name='game_index']").exists()) {var game_index = $("input[name='game_index']").val()} else {var game_index = '';}
  
  // Submit login details
  $.post(
      "/user/login",
      { 'login': login, 'password': password, 'remember_me' : remember_me, 'game_index' : game_index, 'is_ajax' : 'True' },
      function(data) {
        
        // Login was successful
        if(data.status == 'Success') {
        	// Analytics
        	try {pageTracker._trackPageview('/login/success');}catch(err){}
        	// Set user logged in
          isLoggedIn = true;
          // Set user attributes
          $("#userImage").attr('src','/user/image/medium/'+data.username);
          $("#userImage").attr('alt',data.username);
          $("#username").text(data.username);
          $("#userRank").text(data.userRank);
          if($("#userAchievements").exists()) {$("#userAchievements").html(data.userAchievements);}
          // Set user links
          $("#userLoggedOutLinks").hide();
          $("#userLoggedInLinks").show();
          // Set comment form
          if($("#commentLoginRegister").exists()) {$("#commentLoginRegister").hide();}
          if($("#commentLoginRegister").exists()) {$("#commentForm").show();}
          // Close & reset popover
          $.unblockUI();
          $("#popoverProcessing").hide();
          $("#popoverLoginRegister").show();
          // Set game details          
          $.each(data.gameAnswers, function(i,uA){
            try{
              curGame.questions[uA.qID]['userAnswer'] = uA.answer;
              curGame.questions[uA.qID]['userPoints'] = uA.points;
            }
            catch(e){}
          });
          try{
            curGame.userScore = data.gameScore;
            curGame.userRank = data.gameRank;
            curGame.populate();
          }catch(e){}
        }
        // Login had errors
        else {
        	// Analytics
        	try {pageTracker._trackPageview('/login/error');}catch(err){}
        	// Display error messages
          $.each(data.errors, function(i,error){$("#"+error.name).text(error.msg);});
          // Switch to form
          $("#popoverProcessing").fadeOut(250, function() {$("#popoverLoginRegister").fadeIn(250);});
        }
      },
      "json");
  });});
  return false;
}


// userLogout:  Logs a user out of the site
function userLogout() {
  // Analytics
  try {pageTracker._trackPageview('/logout');}catch(err){}
  $.ajax({
    url: "/user/logout?is_ajax=True",
    cache: false,
    success: function(html){
    	// Set user logged out
      isLoggedIn = false;
      // Reset user attributes
      $("#userImage").attr('src','/user/image/medium/');
      $("#userImage").attr('alt','Anonymous');
      $("#username").text('Anonymous');
      $("#userRank").text('white');
      if($("#userAchievements").exists()) {$("#userAchievements").html('');}
      // Reset user links
      $("#userLoggedInLinks").hide();
      $("#userLoggedOutLinks").show();
      // Reset comment form
      if($("#commentLoginRegister").exists()) {$("#commentLoginRegister").show();}
      if($("#commentForm").exists()) {$("#commentForm").hide();} 
      // Reset popover fields
      $("#loginLogin").val('Username or Email');
      $("#loginPassword").val('Password');
      $("#registerUsername").val('Username');
      $("#registerPassword").val('Password');
      $("#registerEmail").val('Email');
      // Reset game
      try{curGame.clear();}catch(e){}
    }
  });
  
  return false;
}

// userRegister:  Registers a user for the site
function userRegister() {
  // Switch to processing
  $("#popoverLoginRegister").fadeOut(250, function() {$("#popoverProcessing").fadeIn(250, function() {
  
  // Clear error messages
  clearPopoverErrors();
  
  // Register details
  var username = $("#registerUsername").val();
  var password = $("#registerPassword").val();
  var email = $("#registerEmail").val();
  if($("#registerRememberMe").attr('checked')) {var remember_me = 1;}else {var remember_me = 0;}
    
  // Submit register details
  $.post(
      "/user/register",
      { 'username': username, 'password': password, 'email' : email, 'remember_me' : remember_me, 'is_ajax' : 'True' },
      function(data) {
        
        // Register was successful
        if(data.status == 'Success') {
        	// Analytics
        	try {pageTracker._trackPageview('/register/success');}catch(err){}
        	// Set user logged in
          isLoggedIn = true;
          // Set user attributes
          $("#userImage").attr('src','/user/image/medium/'+data.username);
          $("#userImage").attr('alt',data.username);
          $("#username").text(data.username);
          $("#userRank").text(data.userRank);
          if($("#userAchievements").exists()) {$("#userAchievements").text(data.userAchievements);}
          // Set user links
          $("#userLoggedOutLinks").hide();
          $("#userLoggedInLinks").show();
          // Set comment form
          if($("#commentLoginRegister").exists()) {$("#commentLoginRegister").hide();}
          if($("#commentLoginRegister").exists()) {$("#commentForm").show();}
          // Close & popover
          $.unblockUI();
          $("#popoverProcessing").hide();
          $("#popoverLoginRegister").show();
        }
        // Register had errors
        else {
        	// Analytics
        	try {pageTracker._trackPageview('/register/error');}catch(err){}
        	// Display error messages
          $.each(data.errors, function(i,error){$("#"+error.name).text(error.msg);});  
          // Switch to form
          $("#popoverProcessing").fadeOut(250, function() {$("#popoverLoginRegister").fadeIn(250);});
        }
      },
      "json");
  });});
  return false;
}


// clearPopoverErrors: Clears the error messages in the popover
function clearPopoverErrors() {
	// Clear login error messages
	$("#loginLoginError").text('');
	$("#loginPasswordError").text('');
	$("#loginGeneralError").text('');
	
	// Clear register error messages
	$("#registerUsernameError").text('');
	$("#registerPasswordError").text('');
	$("#registerEmailError").text('');
	$("#registerGeneralError").text('');
}

// convertToTime:  Converts from integer to time
function convertToTime(secs){
  var mins = Math.floor(secs / 60);
  secs = secs % 60;
  return (mins < 10 ? "0" + mins : mins) + ":" + (secs < 10 ? "0" + secs : secs);
}


// convertFromTime: Converts from time to integer
function convertFromTime(time)  {
  var valid = /^\d\d:\d\d$/;
  if(valid.test(time) == true) {
    var timeSplit=time.split(':');
    var secs = 0;
    secs += parseInt(timeSplit[0])*60;
    secs += parseInt(timeSplit[1]);
    return secs;
  }
  else {
    return 0;
  }
}



// newComment: Fades in each new comment
function newComment() {
  $(".commentNew:first").fadeIn(750, function(){
    $(this).attr("class","comment")
    if($(".commentNew:first").exists()) {newComment();}
  });
}


// global: Used to determine if getComments is running
var isGettingComments = false;
// getComments:  Checks for new comments
function getComments() {
  // Check the global variable
  if(isGettingComments == true) {return false;} else {isGettingComments = true;}
  
	// Analytics
  try {pageTracker._trackPageview('/comments/get');}catch(err){}
  // Verify fields exists
  $("img#refresh").hide(); $("img#animated-refresh").show();
  if($("#lookupType").exists()) {var lookupType = $("#lookupType").val();} else {var lookupType = '';}
  if($("#lookupValue").exists()) {var lookupValue = $("#lookupValue").val();} else {var lookupValue = '';}
  if($(".timestamp:last").exists()) {var timestamp = $(".timestamp:last").attr("name")} else {var timestamp = '0';}
  
  // Get comments by ajax
  if(lookupType.length > 0 && lookupValue.length > 0 && timestamp.length > 0) {
    
       $("img#refresh").hide(); $("img#animated-refresh").show("fast", function () {
        $.ajax({
          url: "/comments/?lookupType="+lookupType+"&lookupValue="+lookupValue+"&timestamp="+timestamp+"&is_ajax=True",
          cache: false,
          success: function(html){
            // Comments exist, put at end
            if($(".comment:last").exists()) {$(".comment:last").after(html);}
            // No comments, put at beginning
            else {$("#comments").html(html);}
            // Fade in new comments
            if($(".commentNew:first").exists()) {newComment();}
            // Fade out loading message
           $("img#animated-refresh").hide(); $("img#refresh").show();
          }
        });
      });
  }
  // Unset the global variable
  isGettingComments = false;
  return false;
}


// submitComment:  Submits a comment through an ajax post
function submitComment() {
  // Disable comment submit button
  $('#commentButton').attr("disabled", true); 
  // Set the global getting comments variable
  isGettingComments = true;
  
  // Disable submit button
  $('#target').attr("disabled", true); 
  
  // Validation
  if($("#lookupType").exists()) {var lookupType = $("#lookupType").val();} else {var lookupType = '';}
  if($("#lookupValue").exists()) {var lookupValue = $("#lookupValue").val();} else {var lookupValue = '';}
  if($("#comment").exists()) {var comment = $("#comment").val();} else {var comment = '';}
  
  // All required fields exists
  if(lookupType.length > 0 && lookupValue.length > 0 && comment.length > 1) {
  	// Analytics
    try {pageTracker._trackPageview('/comments/submit');}catch(err){}
    
    // Post comment
    $.post("/comments/", { 'lookupType' : lookupType, 'lookupValue' : lookupValue, 'comment' : comment},
        function(data){
          if(data.status == 'Error') {
            // Display error message
            alert(data.msg);
          }
          else if(data.status == 'Success') {
            // Clear comment input
            $("#comment").val('')
            // Get new comments
            getComments();
          }
        }
    , "json");
  }
  // Comment is not long enough
  else if(comment.length < 2) {
    alert('Your comment must be at least 2 characters');
  }
  // Unsets the global comment variable
  isGettingComments = false;
  // Enable comment submit button
  $('#commentButton').removeAttr("disabled");
}


// submitTopic:  Submits a comment through an ajax post
function submitTopic() {
	// Switch to processing
  $("#topicForm").fadeOut(250, function() {$("#topicProcessing").fadeIn(250, function() {
  	
  // Validation
  if($("#newTopicTopic").exists()) {var topic = $("#newTopicTopic").val();} else {var topic = '';}
  if($("#newTopicComment").exists()) {var comment = $("#newTopicComment").val();} else {var comment = '';}
  
  
  // All required fields exist
  if(topic.length > 1 && comment.length > 1) {
  	// Analytics
    try {pageTracker._trackPageview('/topic/submit');}catch(err){}
    
    // Post topic
    $.post("/forum/", { 'topic' : topic, 'comment' : comment },
        function(data){
          if(data.status == 'Error') {
            // Display error messages
            $("#topicProcessing").fadeOut(250, function() {$("#topicForm").fadeIn(250, function() {alert(data.msg);});});
          }
          else if(data.status == 'Success') {
            // Close window
            $.unblockUI();
            $("#topicProcessing").hide();
            $("#topicForm").show();
            
            // Clear inputs
            $("#newTopicTopic").val('')
            $("#newTopicComment").val('')
            
            // Insert new topic into page
            if($(".row:first").exists()) {$(".row:first").before(data.msg);}
            else {$(".rows h2").after(data.msg);}
            
            // Fade row in
            $(".row:first").fadeIn(750) 
          }
        }
    , "json");
  }
  // Topic or comment is not long enough
  else {
  	// Display error messages
    $("#topicProcessing").fadeOut(250, function() {$("#topicForm").fadeIn(250, function() {alert('Your topic & comment must be at least 2 characters');});});
  }
  });});
  return false;
}
