/*

  Woot Watcher AJAX code Version 0.1
  Version   0.1 8/17/2006

  Debugging note:
        This program will insert the resulting cache into the page if
        there is a section there to receive it. That section looks like
        this:

        <TEXTAREA id="cache" name="cache" rows="20" cols="80">
          cache response goes here.  Debug only, normally hidden.
        </TEXTAREA>
*/

// This stores the path to the WootOff Cache web service. This *must* be
// on the same server as index.html or you will violate the AJAX
// security model. However, it does not need to be in the same directory
// as I have it here.
//
// We use this to build URLs based on the current form settings.
// We append the current time to keep IE from cacheing the results.
// The requestTime parameter is not actually used by the web service.
var WWAL_publishWebServiceURL = "wootcache.php?extended=1&requestTime=";

// This global is used to store the active XMLHttpRequest object
// Currently we only have and use one of these at a time.  Because of IE
// this object is destroyed and recreated for every request (you cannot use
// the IE XMLHTTP obect more than once reliably).
var WWAL_http_request = false;

// This global stores the current percentage completed.  We use this as a
// clue as to whether things are happening right now.
var WWAL_percentageCompleted = 0;

// This global stores the type of query that we are doing. Currently the
// only request type that is valid is "cache".
var WWAL_requestType = null;

// This function is from simpler logger by Philip McCarthy, phil@chimpen.com
// It writes the log messages to firebug in FireFox.
function printfire ()
  {
    if (document.createEvent)
      {
        printfire.args = arguments;
        var ev = document.createEvent("Events");
        ev.initEvent("printfire", false, true);
        if (window.dispatchEvent)
          {
            dispatchEvent(ev);
          }
      }
  }

function logMessage (msg)
  {
    printfire("TWAL: " + msg);
  }

function logError (msg)
  {
    printfire("TWAL ERROR: " + msg);
  }

// Initialize an XMLHttpRequest().  Creates and initializes the object
// and stores it in the global WWAL_http_request variable.
function makeRequest (requestType, url)
  {
    WWAL_http_request = false;

    // Set the global state.
    WWAL_requestType = requestType;

    if (window.XMLHttpRequest) // Mozilla, Safari,...
      {
        WWAL_http_request = new XMLHttpRequest();
        if (WWAL_http_request.overrideMimeType)
          {
            WWAL_http_request.overrideMimeType('text/plain');
            // See note below about this line
          }
      }
    else if (window.ActiveXObject) // IE
      {
        try
          {
            WWAL_http_request = new ActiveXObject("Msxml2.XMLHTTP");
          }
        catch (e)
          {
            try
              {
                WWAL_http_request = new ActiveXObject("Microsoft.XMLHTTP");
              }
            catch (e)
              {}
          }
      }

    if (!WWAL_http_request)
      {
        logError('Giving up :( Cannot create an XMLHTTP instance');
        return false;
      }

    // Set the cursor to a wait cursor for the whole document while we
    // are processing the request.
    if (document.body && document.body.style)
      document.body.style.cursor = "wait";

    WWAL_http_request.onreadystatechange = alertContents;
    WWAL_http_request.open('GET', url, true);
    WWAL_http_request.send(null);
  }

function displayMessage (message)
  {
    if (message.length > 0)
      {
        errorMessageDiv = document.getElementById("errorMessage");
        errorMessageDiv.innerHTML = message;
      }
  }

function unixTimeToDate (timestamp)
{
	return(new Date(timestamp * 1000).toLocaleString());
}

// This function processes the task state XMl document.
function processCacheResults (cacheText)
  {
    // Sample extended cache version 1.1 (added condition):
    // 0                 1    2                                     3           4                              5        6                                    7                                        8    9  10 11      12
    // #BMSG#1155873497||24%||Hitachi LCD Entertainment Projector ||1155873480||/WantOne.aspx?WootSaleId=2395||$499.99||/Forums/ViewPost.aspx?PostID=659018||Hitachi_LCD_Entertainment_Projector_CIW||jpg||2||new||0.4879||0||

    var cache_array = cacheText.split("||");

    // Update the current state on the page
    var productName     = document.getElementById("productName");
    var price           = document.getElementById("price");
    var condition	    = document.getElementById("condition");
    var photo           = document.getElementById("photo");
    var purchaseLink    = document.getElementById("purchaseLink");
    var forumLink       = document.getElementById("forumLink");
    var photoLink       = document.getElementById("photoLink");
    var timestring      = document.getElementById("timestring");
    var timestamp       = document.getElementById("timestamp");
    var age             = document.getElementById("age");
    var percentComplete = document.getElementById("percentComplete");

    if (cache_array.length == 1)
      {
        productName.innerHTML = "An error occurred in the web service (we will try again in 30 seconds).";
        return;
      }

    purchaseLink.href = "http://www.woot.com" + cache_array[4];
    forumLink.href    = "http://www.woot.com" + cache_array[6];

    photoLink.href    = cache_array[7] + "-standard." + cache_array[8];
    photo.src         = cache_array[7] + "-thumbnail." + cache_array[8];

    condition.innerHTML = "(Condition: " + cache_array[10] + ")";

    productName.innerHTML     = cache_array[2];
    price.innerHTML           = cache_array[5];
    timestring.innerHTML      = unixTimeToDate(cache_array[3]);

    timestamp.value = cache_array[3];

    ageInSeconds = Math.round(((new Date()).getTime()/1000)-cache_array[3]);

    age.innerHTML             = ageInSeconds;

    WWAL_percentageCompleted = parseInt(cache_array[1]);

    percentage = cache_array[1];
    if (percentage == "0%")
      {
        percentage = "SOLD OUT";
      }
    else if ((percentage != "N/A"))
      {
        percentage += " Left";
      }

    percentComplete.innerHTML = percentage;

    document.title = percentage + "- Woot Off AJAX Client";

    var progressMeterBar = document.getElementById('progressMeterBarDone');

    progressMeterBar.style.width = cache_array[1];
  }

// This is the Ajax callback function.  This is where the work of
// loading the cache starts.
function alertContents()
  {
    if (WWAL_http_request.readyState == 4)
      {
        // Set the cursor back to auto since we either got a result or
        // an error.
        document.body.style.cursor = "auto";

        if (WWAL_http_request.status == 200)
          {
            // document.write(WWAL_http_request.responseText);
            var cacheText = WWAL_http_request.responseText;

            logMessage("Request Type = " + WWAL_requestType);

            if (WWAL_requestType == "cache")
              {
                processCacheResults(cacheText);
              }
            else
              {
                processCacheResults(cacheText)
              }

            // Debugging code
            cacheField = document.getElementById("cache");
            if (cacheField != null)
              cacheField.value = cacheText;
          }
        else
          {
            logError('There was a problem with the request.');
          }
      }
  }

function updateCache ()
  {
    logMessage("Getting Cache");
    makeRequest("cache", WWAL_publishWebServiceURL + (new Date().getTime()));

    // Call myself again in 30 seconds if the woot has just started
    // and in 5 seconds if the woot is near completion.
    if (WWAL_percentageCompleted > 15)
      setTimeout('updateCache();', 30000);
    else
      setTimeout('updateCache();', 15000);
  }

function updateAge ()
  {
    var timestamp = document.getElementById("timestamp");
    var age       = document.getElementById("age");

    lastTimeStamp = parseInt(timestamp.value);

    if (lastTimeStamp < 100)
      return;

    ageInSeconds = Math.round(((new Date()).getTime()/1000)-lastTimeStamp);
    age.innerHTML = ageInSeconds;

    setTimeout('updateAge();', 1000);
  }

setTimeout('updateCache(); updateAge();', 1000);

