var sortBy="start";

scheduleLoaded = false;
schedule = "";
fillScheduleAfterLoading = false;
class_location = "All";
time_frame = "All"
var date_limit;

today = new Date();


/*
function openCourseWindow(theURL, winName, features) {
  window.open(theURL, winName, features);
}
*/

scheduleLoadFinished = false;
schedulLoadStarted = false;

function loadSchedule() {
  queryString = "sortBy=start";
  request = createXMLHttpRequest(); 
  request.onreadystatechange = receiveSchedule;
  request.open("GET", "/schedule/scheduleQuery?" + queryString, true);
  request.send(null);
  scheduleLoadStarted = true;
}

function receiveSchedule() {
  if (request.readyState == 4 && request.status == 200) {
    courseSchedule = request.responseText;
    scheduleLoadFinished = true;
  }
}

function querySchedule(sb) {
  alert("qeuerySchedule called");
  if (sb) {
    sortBy = sb;
  }
  var queryString = "";
  var list = dojo.byId("vendor_list");
  var opts = list.options;
  var index = list.selectedIndex;
  var vendor = opts.item(index);

  if (index >= 0) {
    queryString += "vendor=" + vendor.text;
  }

  list = dojo.byId("technology_list");
  opts = list.options;
  index = list.selectedIndex;
  var technology = opts.item(index);

  if (index >= 0) {
    if (queryString != "") {
      queryString += "&";
    }
    queryString += "technology=" + technology.text;
  }

  list = dojo.byId("location_list");
  opts = list.options;
  index = list.selectedIndex;
  var location = opts.item(index);
  
  if (index >= 0) {
    if (queryString != "") {
      queryString += "&";
    }
    queryString += "location=" + location.text;
  }

  list = dojo.byId("time_list");
  opts = list.options;
  index = list.selectedIndex;
  var time = opts.item(index);

  if (index >= 0) {
    if (queryString != "") {
      queryString += "&";
    }
    queryString += "time=" + time.value;
  }
  
  if (queryString != "") {
    queryString += "&";
  }
  queryString += "sortBy=" + sortBy;

  makeScheduleQuery(queryString);
}

function getScheduleJSON() {
  var req = createXMLHttpRequest();
  req.onreadystatechange = function() {
     if (req.readyState == 4 && req.status == 200) {
      scheduleJSON = req.responseText;
      schedule = eval(scheduleJSON);
      createScheduleDates();
      scheduleLoaded = true;
      if (fillScheduleAfterLoading) {
        fillScheduleTable();
        var loading = dojo.byId("loading");
        loading.style.visibility="hidden";
      }
    }
  }
  req.open("GET", "/schedule/scheduleJSON");
  req.send(null);
}

function createScheduleDates() {
  for (var i = 0; i < schedule.length; ++i) {
    var start = schedule[i].start;
    var year = parseInt(start.substr(0, 4), 10);
    var month = parseInt(start.substr(5, 2), 10) - 1;
    var day = parseInt(start.substr(8, 2), 10);

    schedule[i].date = new Date(year, month, day);
  }
}

function showSchedulePage() {
  getScheduleDisplay();
  window.location.hash="schedule";
  dojo.byId("scheduleLink").blur();
}

function getScheduleDisplay() {
  var req = createXMLHttpRequest();
  req.onreadystatechange = function() {
    if (req.readyState == 4 && req.status == 200) {
      displaySchedulePage(req.responseText);
    }
  }
  req.open("GET", "/schedule/getScheduleDisplay");
  req.send(null);
}

function displaySchedulePage(responseText) {
  pcDiv = dojo.byId("pageContents");
  pcDiv.innerHTML = responseText;

  setTimeout(fillScheduleTable, 0); 
}

function fillScheduleTable() {
  if (scheduleLoaded) {
    var courseDiv = dojo.byId("courseDivision"); 
    courseDiv.innerHTML = createScheduleTableString();
  }
  else {
    fillScheduleAfterLoading = true;
    var loading = dojo.byId("loading");
    loading.style.visibility="visible";   
  }
}

function matchesScheduleFilter(course, vendor, technology, time_frame) {
  return (vendor == "All" || course.vendor == vendor)
      && (technology == "All" || matchesTechnology(course, technology))
      && (delivery == "All" || course.delivery == delivery);
} 


function createScheduleTableString() {
  var rowStrings = new Array();
  var rowParity = 1;

  var rowNumber = 0;

  var prevClass = null;

  var nameCell = "";
  var titleCell = "";

  for (var i = 0; i < schedule.length; ++i) {
    var cl = schedule[i];

    if ((vendor == "All" || cl.vendor == vendor) 
        && (technology == "All" || matchesTechnology(cl, technology))
        && (class_location == "All" 
             || cl.display_name == class_location)
        && (time_frame == "All" ||  cl.date.getTime() <= date_limit.getTime())) {

      var evenOdd;

      name = cl.course.replace(/-/g, "_");

      if (prevClass == null 
          || prevClass.course != cl.course) {
        rowParity = 1 - rowParity;
        evenOdd = (rowParity == 0) ? "ctdeven" : "ctdodd";

        nameCell = "<td class=\"" + evenOdd + " ctdcol_1\">"
                   + "<a href=\"javascript:;\" onclick=\"openCourseWindow('/catalog/showcourse?name=" + cl.course + "', '" + name + "', 'scrollbars=yes,width=410,height=500')\">"
                   + cl.course
                   + "</a>"
                   + "</td>";

        titleCell = "<td class=\"" + evenOdd + " ctdcol_2\">"
                   + "<a href=\"javascript:;\" onclick=\"openCourseWindow('/catalog/showcourse?name=" + cl.course + "', '" + name + "', 'scrollbars=yes,width=410,height=500')\">"
                   + cl.title
                   + "</a>"
                   + "</td>";

      }
      else {
        evenOdd = (rowParity == 0) ? "ctdeven" : "ctdodd";
        nameCell = "<td class=\"" + evenOdd + " ctdcol_1\">&nbsp;</td>"
        titleCell = "<td class=\"" + evenOdd + " ctdcol_2\">&nbsp;</td>"
      }


      locationCell = "<td class=\"" + evenOdd + " ctdcol_1\">"
	+ "<a href=\"javascript:;\" onclick=\"openCourseWindow('/catalog/showcourse?name=" + cl.course + "', '" + name + "', 'scrollbars=yes,width=410,height=500')\">"
	+ cl.display_name
	+ "</a>"
	+ "</td>";

      dateCell = "<td class=\"" + evenOdd + " ctdcol_1\">"
	+ "<a href=\"javascript:;\" onclick=\"openCourseWindow('/catalog/showcourse?name=" + cl.course + "', '" + name + "', 'scrollbars=yes,width=410,height=500')\">"
	+ cl.start
	+ "</a>"
	+ "</td>";


      rowStrings[rowNumber] = "<tr>"
	+ nameCell
	+ titleCell
	+ "<td class=\"" + evenOdd + " ctdcol_3\">"
	//	+ cl.display_name
	+ locationCell
	+ "</td>"
	+ "<td class=\"" + evenOdd + " ctdcol_4\">"
	//	+ cl.start
	+ dateCell
	+ "</td>"
	+ "</tr>";

      rowNumber++;

      prevClass = schedule[i];
    }
  }

  if (rowNumber > 0) {
    return "<table id='scheduleTable' cellspacing='0' cellpadding='0'>" + rowStrings.join("") + "</table>"; 
  }
  else {
    return "<table id='catalogTable'><tr><td>&nbsp;</td><td>&nbsp</td><td>&nbsp;</td><td>&nbsp</td></tr></table>";
  }
}

function compareByCourse(c1, c2) {
  return c1.course.localeCompare(c2.course);
}

function compareByLocation(c1, c2) {
  var result = compareLocations(c1.display_name, c2.display_name);
	
  return result != 0 ? result : compareByCourse(c1, c2);
}

function compareLocations(l1, l2) {  
  var d1 = l1.split(",");
  var d2 = l2.split(",");

  var isBE1 = isBridgeLocation(l1);
  var isBE2 = isBridgeLocation(l2);

  if (d1.length == 1 && d2.length == 1) {
    return 0;				
  }
  else if (d2.length == 1) {
    return -1;
  }
  else if (d1.length == 1) {
    return 1;
  }
  else if (isBE1 && !isBE2) {
    return -1;
  }
  else if (isBE2 && !isBE1) {
    return 1;
  }
  else {
    d1[1] = d1[1].slice(1,3);
    d2[1] = d2[1].slice(1,3);

    var stcmp = d1[1].localeCompare(d2[1]);
    if (stcmp != 0) {
      return stcmp;
    }
    
    return d1[0].localeCompare(d2[0]);
  }
}

function isBridgeLocation(loc) {
  return loc == "Baltimore, MD (Columbia)"
      || loc == "Portland, ME (Westbrook)"
      || loc == "Arlington, VA (DC)"
}

function compareByStart(c1, c2) {
  var result = c1.start.localeCompare(c2.start);
  return result != 0 ? result : compareByCourse(c1, c2);
}

function sortSchedule(comparefn) {
  schedule.sort(comparefn);
  filterSchedule()
}

function filterSchedule() {
  var list = dojo.byId("vendor_list");
  var opts = list.options;
  var index = list.selectedIndex;
  vendor = opts.item(index).text;

  list = dojo.byId("technology_list");
  opts = list.options;
  index = list.selectedIndex;
  technology = opts.item(index).text;

  list = dojo.byId("location_list");
  opts = list.options;
  index = list.selectedIndex;
  class_location = opts.item(index).text;

  list = dojo.byId("time_list");
  opts = list.options;
  index = list.selectedIndex;
  time_frame = opts.item(index).value;
  if (time_frame != "All") {
    date_limit = new Date(today.getFullYear(), today.getMonth(), 
                          today.getDate() + parseInt(time_frame));
  }


/*  var catalogTable = dojo.byId("catalogTable"); */

  fillScheduleTable();
}

function makeScheduleQuery(query) {
  var loading = dojo.byId("loading");
  loading.style.visibility="visible";
  request = createXMLHttpRequest();

  request.onreadystatechange = showScheduleReply;
  request.open("GET", "/schedule/scheduleQuery?" + query, true);
  request.send(null);
}

function createXMLHttpRequest() {
  var v;
  try {
    v = new ActiveXObject("Microsoft.XMLHTTP");
  } 
  catch (e) {
    v = new XMLHttpRequest();
  }
  
  return v;

}

function showScheduleReply() {
  if (request.readyState == 4 && request.status == 200) {
    var catdiv = dojo.byId("courseDivision");
    catdiv.innerHTML = request.responseText;
    var loading = dojo.byId("loading");
    loading.style.visibility="hidden";
  }
}

function selectVendor() {
  vlist = dojo.byId("vendor_list");
  opts = vlist.options;
  index = vlist.selectedIndex;
  selection = opts.item(index);
  self.location = "/catalog?vendor=" + selection.text;
}

function selectTechnology() {
  vlist = dojo.byId("technology_list");
  opts = vlist.options;
  index = vlist.selectedIndex;
  selection = opts.item(index);
  self.location = "/catalog?technology=" + selection.text;
}


