/* contains functions and variables that are common to all nikeplus pages */

/******************************************************************************
 * CHANGE LOG
 *
 * 2009-07-02  Started this  change log
 *
 *             Added a "rnd" param to ajax calls ensure uniqueness.  Modified
 *             "getUserChallengeDetails" and "getUserDetails".  Also added
 *             "getUnixTimestamp"
 *
 *             Added "doUpdate" param to any methods that call
 *             "toggleUserProfile", and to "toggleUserProfile" itself. This
 *             indicates that a user profile needs to be "refreshed" in the
 *             db since it was last updated several hours ago.
 *****************************************************************************/

var isIE = false;

String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g,"");
}

function getUnixTimestamp() {
   return parseInt(new Date().getTime().toString().substring(0, 10))
}

function toggleVisibility(theID, theToggleID, forceShow, setFocusObj) {
   var theSectionElement = document.getElementById(theID);

   var theToggleElement = theToggleID ? document.getElementById(theToggleID) : null;

   var showMe = forceShow || theSectionElement.style.display == 'none';

   if (!showMe) {
      theSectionElement.style.display =  'none';

      if (theToggleElement) theToggleElement.innerHTML= 'show';
   }
   else {
      theSectionElement.style.display = '';
      if (setFocusObj) setFocusObj.focus();
      if (theToggleElement) theToggleElement.innerHTML= 'hide';

   }
}

function toggleUserProfileVisibility(userID, visibilityElemID, visibilityElemIDIsRow, profileContentID, challengeContentID, doUpdate) {

   var elem = document.getElementById(visibilityElemID);
   if (visibilityElemIDIsRow && elem.className == 'visible' )
      elem.className = 'notvisible';
   else if (!visibilityElemIDIsRow && elem.style.display == '' )
      elem.style.display =  'none';
   else {
      var dataElem = document.getElementById(profileContentID);
      if (!dataElem.innerHTML)
         getUserDetails(userID, profileContentID,challengeContentID, doUpdate );

      if (visibilityElemIDIsRow)
         elem.className = 'visible';
      else
         elem.style.display =  '';
   }
}


function makeRequest(url, contentID, postFunction) {
 var httpRequest;

 if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      httpRequest= new XMLHttpRequest();
      if (httpRequest.overrideMimeType) {
          httpRequest.overrideMimeType('text/xml');
          // See note below about this line
      }
   }
   else if (window.ActiveXObject) { // IE
      try {
         httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e) {
         try {
            httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch (e) {}
      }
   }

   if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
   }

   httpRequest.onreadystatechange = function() { writeContents(httpRequest, contentID, postFunction); };

   try {
      httpRequest.open('GET', url, true);
      httpRequest.send('');
   }
   catch (e) {
      alert('Caught Exception: ' + e.toString());
   }
}

function writeContents(httpRequest, contentID, postFunction) {

   if (httpRequest.readyState == 4) {
      var idiv = window.document.getElementById(contentID);
      if (httpRequest.status == 200) {
         //alert(httpRequest.responseText);
         //alert(httpRequest.responseText.length);
         if (idiv && httpRequest.responseText.length>2)
            idiv.innerHTML = httpRequest.responseText;
         else
            idiv.innerHTML = '<p>Request timed out while waiting for nikeplus.nike.com.  Please try again later.</p>';

       }
      else {
          if (idiv) idiv.innerHTML = 'There was a problem with the request.';
          //alert('There was a problem with the request.');
      }
      idiv = window.document.getElementById(contentID + "-load-status");
      if (idiv) idiv.style.display='none';

      idiv = window.document.getElementById(contentID + "-loading-indicator");
      if (idiv) idiv.innerHTML = '';
      if (postFunction)  postFunction();
   }
}

function retrieveData(url, contentID, statusMsg, pageMsg, postFunction) {

   window.status = statusMsg;

   var idiv = window.document.getElementById(contentID + "-load-status");
   if (idiv) idiv.style.display='';

   idiv = window.document.getElementById(contentID + "-loading-indicator");
   if (idiv)
      idiv.innerHTML = '<img src="/nikeplus/images/loading.gif" alt="Loading indicator"/> Retrieving ...'; //+ pageMsg;
   else {
      idiv = window.document.getElementById(contentID);
      if (idiv)
         idiv.innerHTML = '<div class="loading-indicator"><img src="/nikeplus/images/loading.gif" alt="Loading indicator"/>' + pageMsg + "</div>";
   }

   makeRequest(url, contentID, postFunction);
}

function getUserDetails(userID, contentID, challengeContentID, doUpdate) {

   retrieveData("getUserDetail.php?u=" +  userID + "&doUpdate=" + doUpdate + "&_rnd=" + getUnixTimestamp(),
                contentID,
                "Retrieving details for user " + userID,
                "Retrieving user profile...");

   if (challengeContentID) getUserChallengeDetails(userID, challengeContentID);
}

function getUserChallengeDetails(userID, challengeContentID) {
   retrieveData("getUserChallenges.php?u=" +  userID + "&_rnd=" + getUnixTimestamp(),
                challengeContentID,
                "Retrieving challenges for user " + userID,
                "Retrieving challenges for user...");
}


document.getElementsByClassName = function(clsName){
    var retVal = [];
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++){
        if(elements[i].className.indexOf(" ") >= 0){
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++){
                if(classes[j] == clsName)
                    retVal.push(elements[i]);
            }
        }
        else if(elements[i].className == clsName)
            retVal.push(elements[i]);
    }
    return retVal;
}
