var xmlFile;
var category;
var DEFAULT = "Actors";
var tbody;
var tr;
var COLUMNS = 4;
var columnCount = 1;
var descriptionRow = new Array();
var finalRowIncluded = false;
var begin = 0;
var end;

/*
 *
 * This method parses an XML file based on the input file specified.
 *
 */
function parseXML(fileName) {
  try {
    // Using Internet Explorer.
    xmlFile = new ActiveXObject("Microsoft.XMLDOM");
  }
  catch(e) {
    try {
      // Using Modzilla FireFox or other.
      xmlFile = document.implementation.createDocument("", "", null);
    } catch(e) {
      // Unable to detect broswer type.
      alert(e.message);
      return;
    }
  }
  xmlFile.async = false;
  xmlFile.load(fileName);  
}


/*
 *
 * This method is used to determine what output to display on the
 * page by using the appropiate filter.
 *
 */
function init() {
  var gotoPage = searchBar();
  
  if (gotoPage == null || gotoPage.length == 0) {
    gotoPage = DEFAULT;
  } else {
	gotoPage = getCategory();
  }

  filter(gotoPage);
  generateMenu();
}


/**
  *
  * This method retrieves the URL in the address bar and returns
  * everything after the '?' e.g. file.html?hello returns 'hello'
  *
  */
function searchBar() {
  //window.location.search // returns detail starting from ? 
  return unescape((window.location.search).substring(1)); 
}

/**
  * Returns everything from position 0 up to the "&" sign
  *
  */
function getCategory() {
	return searchBar().substring(0, searchBar().indexOf("&"));
}

/**
  * Returns the page number from the adress bar
  *
  */
function getPageNumber() {
	var pageNum = searchBar().substring(searchBar().indexOf("Page=") + 5);
	return pageNum;
}


/*
 *
 * This method takes in an object of an xml result and converts
 * it to an Array(), where the following format is maintained
 * position [0] = thumbnail image.
 * position [1] = source of actual image.
 * position [2] = width of actual image.
 * position [3] = height of actual image.
 * position [4] = alt text of the actual image.
 * position [5] = description of the object(image, drawing etc...)
 *
 */
function objectToArray(object) {
  var transformation = new Array(6);
  
  transformation[0] = object.getElementsByTagName("thumb")[0].childNodes[0].nodeValue;
  var image = object.getElementsByTagName("image")[0];
  transformation[1] = image.childNodes[0].nodeValue;
  transformation[2] = image.getAttribute("width");
  transformation[3] = image.getAttribute("height");
  transformation[4] = image.getAttribute("alt");
  transformation[5] = object.getElementsByTagName("desc")[0].childNodes[0].nodeValue;

  return transformation;
}


/*
 *
 * This method is used to sort the objects into categorys 
 * based on the criteria specified e.g. 'Film' will display
 * all objects with the category film. 
 *
 */
function filter(criteria) {

  var objects = xmlFile.getElementsByTagName("object");
  
  document.getElementById("tableCaption").innerHTML = criteria.bold();
  
  tbody = document.getElementById("tableBody")
  tr = tbody.insertRow(tbody.rows.length);
    
  for (i = 0; i < objects.length; i++) {
  
    category = objects[i].getAttribute("category");

    if (category == criteria) {
    
      var output = objectToArray(objects[i]);
       
      row1(output[0], output[1], output[2], output[3], output[4], output[5]);
    }
  }
  
  if (finalRowIncluded == false) {
    tr = tbody.insertRow(tbody.rows.length);
    for (begin; begin < end; begin++) {
      var td = tr.insertCell(tr.cells.length);
      td.innerHTML = descriptionRow[begin];
    }
  }
  
  //relocateTable();
}

/*
 *
 * This method determines how the results of a query or filter
 * should be displayed.
 *
 */
function row1(thumb, src, width, height, alt, desc) {
  
  descriptionRow[columnCount - 1] = desc;
  finalRowIncluded = false; // assume this row will not have the right number of columns
  
  var td = tr.insertCell(tr.cells.length);
  td.innerHTML = "<img src=\"" + thumb + "\" "
               + "onclick=\"openImage(\'" + src + "\', \'" + width + "\', \'" + height + "\', "
               + "\'" + alt + "\')\" alt=\"" + alt + "\" title=\"" + alt + "\" onmouseover=\"transition(this, 100);\" "
               + "onmouseout=\"transition(this, 70);\">";
  td.setAttribute("id", "imageTD");
  
  end = columnCount;
  
  if (columnCount % COLUMNS == 0) {
    tr = tbody.insertRow(tbody.rows.length);
    finalRowIncluded = true;
    for (begin; begin < end; begin++) {
      var td = tr.insertCell(tr.cells.length);
      td.innerHTML = descriptionRow[begin];
    }
    begin = end;
    tr = tbody.insertRow(tbody.rows.length);
  }
  columnCount++;
}


/*
 * 
 * This method returns the results of a query based on a search by 
 * a user.
 *
 */
function queryRecords() {
  var query = searchBar();
  document.getElementById("SearchBox").value = query;
  
  var text = "Results for \"" + document.getElementById("SearchBox").value + "\"";
  document.getElementById("tableCaption").innerHTML = text.bold();
  
  var list = new Array();
  var index = 0;
  
  var objects = xmlFile.getElementsByTagName("object");
   
  for (i = 0; i < objects.length; i++) {
  
    var strToCheck = objects[i].getElementsByTagName("desc")[0].childNodes[0].nodeValue;
    var expr = new RegExp(query, "i");

    if (expr.exec(strToCheck) != null) {
      list[index] = objects[i];
      index++;
    }
  }

  tbody = document.getElementById("tableBody")
  tr = tbody.insertRow(tbody.rows.length);

  if (list.length > 0) {

    for (j = 0; j < list.length; j++) {
      var output = objectToArray(list[j]);
      
      row1(output[0], output[1], output[2], output[3], output[4], output[5]);
    }
    
    if (finalRowIncluded == false) {
      tr = tbody.insertRow(tbody.rows.length);
      for (begin; begin < end; begin++) {
        var td = tr.insertCell(tr.cells.length);
        td.innerHTML = descriptionRow[begin];
      }
    }
    
  }
  else {
    //tr = tbody.insertRow(tbody.rows.length);
    //var td = tr.insertCell(tr.cells.length);
    //document.getElementById("tableCaption").innerHTML = text.bold();
    //td.innerHTML = "No Results to display for \"" + query + "\"";
  }

  generateMenu();
}


/*
 *
 * This method gets the value the user has entered for a search and
 * formats it to the appropiate page where a query will be executed. 
 *
 */
function executeQuery() {
  var input = document.getElementById("SearchBox").value;
  if (input == null || input.length == 0) {
    alert("Please Enter a search word!");
  }
  else {
    var redirectTo = "results.html?" + input;
    location.href = redirectTo;
  }
}


/*
 *
 * This method prints out the menu.
 *
 */
function generateMenu() {

  var men = document.getElementById("leftBar");

  var objects = xmlFile.getElementsByTagName("object");
  var menu = new Array();
  menu[0] = objects[0].getAttribute("category");
  var menuIndex = 1;
  var found = false;
  
  for (i = 1; i < objects.length; i++) {
  
    category = objects[i].getAttribute("category");
    
	for (j = 0; j < menu.length; j++) {
		if (category == menu[j]) {
			found = true;
		}
	}
	
	if (found == false) {
		menu[menuIndex] = category;
		menuIndex++;
	}
	found = false;
  }
	
  var tempCategory;
  if (getCategory() == null || getCategory().length == 0) {
	tempCategory = DEFAULT;
  } else {
    tempCategory = getCategory();
  }
		
  men.innerHTML += "<ul>";
  for (k = 0; k < menu.length; k++) {
	//alert(menu[k] + "\tCat: " + getCategory());
	//var text = "<em id=\"firstLetter\">" + menu[k].substring(0, 1) + "</em>" + menu[k].substring(1);
	if (menu[k].toString() == tempCategory) {
		men.innerHTML += "<li><a href=\"index.html?" + menu[k] + "&Page=1\" id=\"currentTab\">" + menu[k] + "<//a>";
	} else { 
		men.innerHTML += "<li><a href=\"index.html?" + menu[k] + "&Page=1\">" + menu[k] + "<//a>";
	}
  }
  men.innerHTML += "<li><a href=\"Javascript:cover();\">Email Me<//a>";
  men.innerHTML += "<li><a href=\"links.html?links&\">Links<//a>"
  men.innerHTML += "<//ul>";
}


function randomPortrait() {

	var objects = xmlFile.getElementsByTagName("object");
	
	var randomNumber = Math.floor(Math.random() * objects.length);
		
	var output = objectToArray(objects[randomNumber]); 
	var randomPortrait = "Random Portrait".bold();
	var title = "<br/>" + output[5];
	
	document.getElementById("randomPortrait").innerHTML = randomPortrait + "<br/><img src=\"" + output[0] + "\" "
               + "onclick=\"openImage(\'" + output[1] + "\', \'" + output[2] + "\', \'" + output[3] + "\', "
               + "\'" + output[4] + "\')\" alt=\"" + output[4] + "\" title=\"" + output[4] + "\" id=\"randomPicture\">"
               + title;
 
}
