/**
 * Copyright 2006 (C) Jeffrey Palm
 */

// --------------------------------------------------
// Constants
// --------------------------------------------------

var LOCAL = FALSE;
var getURL; // keep around for debugging
var ABBREVIATE = false;

// --------------------------------------------------
// Variables
// --------------------------------------------------

var xmlhttp;              // retrieves XML from my site
var type;                 // "band" | "location"
var bandOrLocationName;   // holds the band or location name for the title
var MAX_ITEMS = ABBREVIATE ? -1 : 15;       // max number of items in the list
var currentIndex;         // current index to search from
var currentSearch;        // current search term
var theShows;             // the current array of shows
var HIDE_CALLOUT = false; // whether we hide the callout



// --------------------------------------------------
// Methods
// --------------------------------------------------

/**
 * Void -> Void
 */
function viewOnopen() {
  gadgetReset();
}

/**
 * Void -> Void
 */
function gadgetReset() {
  setTitle("Please enter an artist or city & state");
  setVisible(loading,false);
  xmlhttp = false; 
  buttonLookup.enabled = true;
  textSource.value = "bloc party";
  mainContent.innerHTML = "";
  if (HIDE_CALLOUT) {
    setVisible("imgCallout",false);
    setVisible("mainContent",false);
  }
  setVisible("buttonMore",false);
  setVisible("buttonBack",false);
}

/**
 * Void -> XMLHttp
 */
function createXMLThingy() {
  try {
    xmlhttp = new XMLHttpRequest();
    if (xmlhttp) return xmlhttp;
  } catch(e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      if (xmlhttp) return xmlhttp;
    } catch(e) {}
  }
  return xmlhttp;
}


/**
 * String -> Void: Sets the title at the top of the callout
 */
function setTitle(str) {
 $("labelTitle").innerHTML = "<b>" + str + "</b>";
}

/**
 * String -> Void: Adds to the title at the top of the callout
 */
function appendTitle(str) {
  $("labelTitle").innerText += str;
}

/**
 * Void -> Void: looks up the text in 'textSource' and displays
 *               it in 'mainContent'
 */
function lookup() {

  currentIndex = 0;
  theShows = false;

  if(xmlhttp && xmlhttp.readyState != 0 && xmlhttp.readyState != 4) return;

  var txt = textSource.value;
  currentSearch = txt;

  doLookUp(txt);
}

function setEnabled(tag,value) {
	$(tag).display = "none";
}

function setVisible(tag,value) {
	$(tag).display = "none";
}

function doLookUp(txt) {

  // create the XML guy (or gal)
  xmlhttp = createXMLThingy();
  setVisible("loading",true);
  setEnabled("buttonLookup",false);
  bandOrLocationName = txt;
  setTitle("looking up " + txt + "...");
  var input = txt;
  //
  // remove white space around comma
  //
  input = input.replace(/,\s+/g,",");
  input = input.replace(/\s+,/g,",");
  input = input.replace(/\s/g,"+");
  input = escape(input);
  //
  // Construct the URL
  //
  if ((icomma = input.indexOf("%2C")) == -1) {
    // -- band
    getURL = "/cgi-bin/pollstar2.pl?band="+input;
    type = "band";
  } else {
    // -- location
    city = input.substring(0,icomma);
    state = input.substr(icomma+3);
    getURL = "/cgi-bin/pollstar.pl?city=" + city + "&state=" + state;
    type = "location";
  }
  //
  // Make the request
  //
  xmlhttp.open("GET",getURL,true);
  xmlhttp.onreadystatechange = lookupDone;
  xmlhttp.send("");
}

/**
 * Void -> Void: Propogates 'mainContent' with the results of the XML query
 */
function lookupDone() {
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    xml = xmlhttp.responseXML.documentElement;
		mainContent.innerHTML = "";
    showShows(theShows = xml.getElementsByTagName("show"));
  } else if( xmlhttp.readyState == 4 ){
    setVisible("loading",false);
    setEnabled("buttonLookup",true);
    alert(xmlhttp.status + "\n" + getURL);
  }
}

function showShows(shows) {
  try {
    
    if (HIDE_CALLOUT) {
      setVisible("imgCallout",true);
      setVisible("mainContent",true);
    }

    setVisible("buttonMore",false);
    setVisible("buttonBack",false);

    removeAllElements();

    needMore = false;
    MAX = currentIndex+MAX_ITEMS;
      
    if (type == "band") {

      setTitle("shows for " + bandOrLocationName);

      for (i=currentIndex; i<shows.length; i++) {

	if (MAX_ITEMS != -1 && i>MAX) {
	  needMore = true;
	  break;
	}

	s = shows[i];

	date = trimDate(s.getAttribute("date"));
	city = s.getAttribute("city");
	venue = s.getAttribute("venue");
	venueLink = s.getAttribute("venueLink");

	str = date + " in " + city + " @ " + venue;
	addContentItem(str);
      }
    } else {

      setTitle("shows in " + bandOrLocationName);

      shows = xml.getElementsByTagName("show");
      lastDate = 0;
      for (i=currentIndex; i<shows.length; i++) {

	if (i>MAX) {
	  needMore = true;
	  break;
	}

	s = shows[i];

	date = trimDate(s.getAttribute("date"));
	artist = s.getAttribute("artist");
	venue = s.getAttribute("venue");
	venueLink = s.getAttribute("venueLink");
	str = date + ": " + artist + " @ " + venue;
	addContentItem(str);
      }
    }

    // add to the title
    if (MAX_ITEMS != -1 && shows.length > MAX_ITEMS) {
      appendTitle(" - " + (currentIndex/MAX_ITEMS+1) + " of " + (roundInt(shows.length/MAX_ITEMS+1)));
    }

    if (needMore) {
      setVisible("buttonMore",true);
      buttonMore.onclick = function() {
				currentIndex += MAX_ITEMS;
				//doLookUp(currentSearch);
				showShows(theShows);
      };
    }
    needLess = currentIndex>0;
    if (needLess) {
      setVisible("buttonBack",true);
      buttonBack.onclick = function() {
				currentIndex -= MAX_ITEMS;
				//doLookUp(currentSearch);
				showShows(theShows);
      };
    }

  } catch (e) {
    alert(e);
    setVisible("loading",false);
    setEnabled("buttonLookup",true);
  }
  setVisible("loading",false);
  setEnabled("buttonLookup",true);
}



/**
 * Void -> Void: Removes all the elements in 'mainContent'
 */
function removeAllElements() {
  mainContent.value = "";
}


/**
 * String -> Void: Adds a String item to 'mainContent'
 */
function addContentItem(item) {
  var N = 40;
  if (ABBREVIATE) {
		if (item.length>N) item = item.substring(0,N) + "...";
	}
  mainContent.innerHTML += item + "<br>";
}

/**
 * String -> String: removes year from date
 */
function trimDate(date) {
  // 12/23/34 -> 12/23
  return date.substring(0,5);
}

// --------------------------------------------------
// Test suite
// --------------------------------------------------

/**
 * String -> Void: Runs one test.
 */
function testRunOne(text) {
  textSource.value = text;
  lookup();
}

/**
 * Void -> Void: Runs a silly stupid 'test suite'
 */
function testSuite() {
  names = ["radiohead",
	   "bloc party",
	   "new orleans, la",
	   "new orleans,la",
	   "new orleans ,la",
	   "new orleans ,LA"
  ];
  function loop(i) {
    testRunOne(names[i]);
    if (i<names.length) loop(i+1);
  }
  loop(0);
}

/**
 * double -> String(int)
 */
function roundInt(i) {
  s = String(i);
  return s.replace(/\..*/,"");
}
