/*

js for pgrind

Copyright (C) 2008 Philip Guo

*/

// If the Firebug console is not defined, then define console to be 'false'
// so that shit will still work when Firebug isn't running
if (typeof(window['console']) == "undefined") {
  var console = false;
}


// Sync this to whichever image is currently being displayed
var curImgInfo = undefined;
var curNumImages = undefined; // int

// an ordered array of image IDs (unique_id fields in db)
var imageIDs = [];

// things to do after document loads properly:
//   $(...) is shorthand for $(document).ready(...)
$(function() {

  var hashParam = window.location.hash;
  var preloadFilename = null;
  if (hashParam) {
    preloadFilename = hashParam.substring(1) + '.jpg';
  }

  // I dunno whether GET caching will screw me over
  $.getJSON("db/getImageIDs.php", {},
    function(json) {
      if (json.success) {
        imageIDs = [];
        for (i in json.data) {
          imageIDs.push(parseInt(json.data[i]['unique_id']));
        }

        curNumImages = imageIDs.length;

        if (preloadFilename) {
          // first try by filename, then try random ...
          fetchImageByFilenameOrWeightedRandom(preloadFilename);
        }
        else {
          fetchWeightedRandomImage();
        }
      }
      // If there is no 'json.success', don't do jack squat
    });


  $("#feelinItButton").click(function() {
    feelinIt();
  });

  $("#notFeelinItButton").click(function() {
    notFeelinIt();
  });

  $("#prevImgButton").click(function() {
    fetchPrevImage();
  });

  $("#nextImgButton").click(function() {
    fetchNextImage();
  });

  $("#postCommentButton").click(function() {
    postComment();
  });

});


// If this is > 0, then SOMEBODY is waiting for ajax data to load;
// If this is = 0, then NOBODY is waiting
var numAgentsWaitingForAjaxData = 0;

// Control display and hiding of loadingMsgDiv
function startLoadingData() {
  if (!(numAgentsWaitingForAjaxData >= 0)) {
    if (console) {console.log("SHIT!");}
  }
  if (numAgentsWaitingForAjaxData == 0) {
    //$("#loadingMsgDiv").fadeIn("fast"); // about to load some data
    // keep it simple:
    $("#loadingMsgDiv").show();
  }

  numAgentsWaitingForAjaxData++;
}

function doneLoadingData() {
  if (!(numAgentsWaitingForAjaxData > 0)) {
    if (console) {console.log("SHIT!");}
  }
  numAgentsWaitingForAjaxData--;

  if (numAgentsWaitingForAjaxData == 0) {
    //$("#loadingMsgDiv").fadeOut("normal");
    // keep it simple:
    $("#loadingMsgDiv").hide();
  }
}


function fetchNextImage() {
  if (!curImgInfo) {return;}
  // convert to integer so that we can do math on it
  id = parseInt(curImgInfo.unique_id);

  var ind = $.inArray(id, imageIDs);
  if (ind < 0) {
    if (console) {console.log("SHIT!");}
    return;
  }

  // wrap around if we are at the last image:
  if (ind == imageIDs.length - 1) {
    fetchImgWithID(imageIDs[0]);
  }
  else {
    fetchImgWithID(imageIDs[ind + 1]);
  }
}

function fetchPrevImage() {
  if (!curImgInfo) {return;}
  // convert to integer so that we can do math on it
  id = parseInt(curImgInfo.unique_id);

  var ind = $.inArray(id, imageIDs);
  if (ind < 0) {
    if (console) {console.log("SHIT!");}
    return;
  }

  // wrap around if we are at the first image:
  if (ind == 0) {
    fetchImgWithID(imageIDs[imageIDs.length - 1]);
  }
  else {
    fetchImgWithID(imageIDs[ind - 1]);
  }
}

function fetchImgWithID(id) {
  startLoadingData();
  // I dunno whether GET caching will screw me over
  $.getJSON("db/fetchImageWithID.php", {desired_id: id},
    function(json) {
      doneLoadingData();
      if (json.success) {
        curImgInfo = json.data[0];
        updateAll();
      }
      // If there is no 'json.success', don't do jack squat
    });
}


// Grab an image by filename, and if that fails, grab most recent image:
function fetchImageByFilenameOrMostRecent(fn) {
  startLoadingData();
  // I dunno whether GET caching will screw me over
  $.getJSON("db/fetchImageByFilename.php", {filename: fn},
    function(json) {
      doneLoadingData();
      if (json.success) {
        curImgInfo = json.data[0];
        updateAll();
      }
      // If there is no 'json.success', just grab most recent image:
      else {
        fetchMostRecentImage();
      }
    });
}

function fetchImageByFilenameOrWeightedRandom(fn) {
  startLoadingData();
  // I dunno whether GET caching will screw me over
  $.getJSON("db/fetchImageByFilename.php", {filename: fn},
    function(json) {
      doneLoadingData(); // to get rid of loadingMsgDiv
      if (json.success) {
        curImgInfo = json.data[0];
        updateAll();
      }
      // If there is no 'json.success', just grab most recent image:
      else {
        fetchWeightedRandomImage();
      }
    });
}



// Grab the most recently-added image
function fetchMostRecentImage() {
  startLoadingData();
  // I dunno whether GET caching will screw me over
  $.getJSON("db/fetchMostRecentImage.php", {},
    function(json) {
      doneLoadingData(); // to get rid of loadingMsgDiv
      if (json.success) {
        curImgInfo = json.data[0];
        updateAll();
      }
      // If there is no 'json.success', don't do jack squat
    });
}

function fetchWeightedRandomImage() {
  startLoadingData();
  // I dunno whether GET caching will screw me over
  $.getJSON("db/fetchWeightedRandomImage.php", {},
    function(json) {
      doneLoadingData(); // to get rid of loadingMsgDiv
      if (json.success) {
        curImgInfo = json.data[0];
        updateAll();
      }
      // If there is no 'json.success', don't do jack squat
    });
}

function updateAll() {
  updateMainImage();
  updateFeelinItDisplay();
  updateCurImageCounter();
  updateComments();

  // update the URL so that it makes a discoverable permalink ...
  window.location.hash = curImgInfo.filename.replace('.jpg', '');
}


// Takes current contents of curImgInfo
function updateMainImage() {
  $("#mainImage").attr('src', 'pgrind-images/' + curImgInfo.filename);
}
    
// Takes current contents of curImgInfo
function updateFeelinItDisplay() {
  // Remember that these are strings
  feelinItStr = curImgInfo.num_feelin_it;

  $("#feelinItCounter").empty();

  for (var ind in feelinItStr) {
    numFilename = feelinItStr[ind] + '.jpg';
    $("#feelinItCounter").append('<img class="tight" src="' + numFilename + '"/>');
  }
  $("#feelinItCounter").append('<img class="tight" src="happy-face-small.jpg"/>');


  // Remember that these are strings
  notFeelinItStr = curImgInfo.num_not_feelin_it;

  $("#notFeelinItCounter").empty();

  for (var ind in notFeelinItStr) {
    numFilename = notFeelinItStr[ind] + '.jpg';
    $("#notFeelinItCounter").append('<img class="tight" src="' + numFilename + '"/>');
  }
  $("#notFeelinItCounter").append('<img class="tight" src="sad-face-small.jpg"/>');
}


function updateCurImageCounter() {
  if (!curImgInfo || !curNumImages) {return;}

  $("#curImageID").empty();

  var curInd = $.inArray(curImgInfo.unique_id, imageIDs);
  if (curInd < 0) {
    if (console) {console.log("SHIT!");}
    return;
  }

  // convert to a string and iterate over each digit in turn ...
  curInd += 1; // index by 1, not 0
  var curIndStr = curInd.toString();
  for (var digit in curIndStr) {
    numFilename = curIndStr[digit] + '.jpg';
    $("#curImageID").append('<img class="tight" src="' + numFilename + '"/>');
  }

  $("#totalNumImagesDisp").empty();
  // convert to a string and iterate over each digit in turn ...
  var curTotalStr = curNumImages.toString();
  for (var digit in curTotalStr) {
    numFilename = curTotalStr[digit] + '.jpg';
    $("#totalNumImagesDisp").append('<img class="tight" src="' + numFilename + '"/>');
  }
}


function feelinIt() {
  if (!curImgInfo) {return;}
  alert("Awesome!  You're feelin' it!!!");

  // I dunno whether GET caching will screw me over
  $.getJSON("db/incrementFeelinIt.php", {cur_id: curImgInfo.unique_id, field_to_inc: 'num_feelin_it'},
    function(json) {
      if (json.success) {
        curImgInfo = json.data[0];
        // this is adequate
        updateFeelinItDisplay();
      }
      // If there is no 'json.success', don't do jack squat
    });
}

function notFeelinIt() {
  if (!curImgInfo) {return;}
  alert("Sorry you're not feelin' it :(");

  // I dunno whether GET caching will screw me over
  $.getJSON("db/incrementFeelinIt.php", {cur_id: curImgInfo.unique_id, field_to_inc: 'num_not_feelin_it'},
    function(json) {
      if (json.success) {
        curImgInfo = json.data[0];
        // this is adequate
        updateFeelinItDisplay();
      }
      // If there is no 'json.success', don't do jack squat
    });
}

function omg(i) {
  if (i == 1) {
    return "jdi";
  }
  else if (i == 8) {
    var a = Array('k', 's', 'l', 'e', 'h', 'q');
    return a.reverse().join('');
  }
  else if (i == 2) {
    return "dfhk" + "emxc";
  }
}

function postComment() {
  if (!curImgInfo) {return;}

  username = $("#usernameInput").val();
  comment = $("#commentTextarea").val();

  // strip trailing spaces to make sure it's not empty
  if (comment.replace(/\s+$/g, '').length == 0) {
    alert("Please enter a comment before posting.");
    return;
  }

  // do some filtering on maximum lengths
  if (username.length > 30) {
    alert("Sorry, name must be less than 30 characters long.");
    return;
  }
  if (comment.length > 1000) {
    alert("Sorry, your comment must be less than 1000 characters long.");
    return;
  }


  // Take some lightweight precautions to prevent automated comment spam ...
  // humans can easily bypass this but hopefully not a lazy program
  var x = omg(1);
  var y = omg(8);
  var z = omg(2);

  $.post("db/" + x + y + z + ".php", {filename: curImgInfo.filename,
                                      username: username,
                                      comment: comment},
        function(data, status) {
          // retrieve new comments
          alert("Thanks for posting your comment.");
          updateComments();
        });

}

function updateComments() {
  // I dunno whether GET caching will screw me over
  $.getJSON("db/fetchCommentsForFile.php", {filename: curImgInfo.filename},
    function(json) {
      if (json.success) {
        commentEntries = json.data;

        // This is inefficient because we're re-rendering ALL the
        // comments, but oh well ... there shouldn't be *that* many comments!
        $("#commentsDiv").empty();

        if (commentEntries.length > 0) {
          for (var ind in commentEntries) {
            entry = commentEntries[ind];

            // Do a crazy string construction!!!  Assume that strings are cleaned 
            // since they should have been sanitized by php strip_tags() before 
            // entering the mySQL db, but be a bit paranoid still:
            //var s = entry.comment.replace('<', '&lt;').replace('>', '&gt;').replace(/\n/g, "<br/>").replace(/ /g, "&nbsp;");
            // hmmm, on second thought, don't convert spaces into &nbsp;
            // because it won't word wrap properly for some reason.
            var s = entry.comment.replace('<', '&lt;').replace('>', '&gt;').replace(/\n/g, "<br/>")

            htmlStr = '<div class="commentEntry"><div class="commentHeader">From ' + entry.username + ' (' + entry.comment_timestamp.split(' ')[0] + '):</div><div class="commentBody">' + s + '</div></div>'
            $("#commentsDiv").append(htmlStr);
          }
        }
        // if there are no comments yet
        else {
          htmlStr = '<div class="commentEntry"><div class="commentBody">No comments yet.  Be the first one!</div></div>'
          $("#commentsDiv").append(htmlStr);

        }

      }
      // If there is no 'json.success', don't do jack squat
    });
}


/*
var subtitles = ["don't get your hopes up ...",
                 "time to lower your expectations ...",
                 "could be short for Pimp Grind (or not) ...",
                 ]
*/

