// JavaScript Includes Document for Homework 9, INP271, Mike Behnke
var jslib = {

	createCookie : function (name,value,expiration,path,domain,secure) {
  	var data = name + "=" + escape(value);
  	if (expiration) { data += "; expires=" + expiration.toGMTString(); }
  	if (path) { data += "; path=" + path; }
  	if (domain) { data += "; domain=" + domain; }
  	if (secure) { data += "; secure"; }
  	document.cookie = data;
	},

	findCookie : function(name) {
    var query = name + "=";
    var querylength = query.length;
    var cookielength = document.cookie.length;
    var i=0;
    while (i < cookielength) {
      var startValue = i + querylength;
      if (document.cookie.substring(i,startValue) == query) {
         return this.findValue(startValue);
      }
      i = document.cookie.indexOf(" ", i) + 1;
      if (i == 0) {break;}
    }
    return null;
  },

  findValue : function(startValue) {
    var endValue = document.cookie.indexOf(";", startValue);
    if (endValue == -1) {
       endValue = document.cookie.length;
    }
    return unescape(document.cookie.substring(startValue,endValue));
  },
  
  deleteCookie : function(name) {
  	if(jslib.findCookie(name)) {
			var data = name + "=";
			data += "; expires=Thu, 01-Jan-70 00:00:01 GMT";
		  document.cookie = data;
		}
	},

	// improve performance by reducing object lookups
	getObj : function(idvalue) {
		return document.getElementById(idvalue);
	},

	getElementsByClass : function (searchClass,node,tag) {
    // this array will hold the nodes that have the desired class
    var classElements = [];
    // if we did not pass the node parameter, assume document
    if (node == null) {node = document;}
    // if we did not pass the tag parameter, grab every node
    if (tag == null) {tag = '*';}
    // gather all the element nodes to look through; by default is everything in document
    var els = node.getElementsByTagName(tag);
    // to improve loop performance, determine the length ahead of time
    var elsLen = els.length;
    // establish the pattern to search for within className
    var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)");
    // look through all the class properties to see if there is a match
    // the j variable is the counter variable that increments each time a
    // match is found and becomes the next item in classElements
    for (var i = 0, j = 0; i < elsLen; i++) {
        if (pattern.test(els[i].className)) {
           classElements[j] = els[i];
           j++;
        }
    }
    // send back the array of elements to whatever variable called this function
    return classElements;
	},

	// associate nodes with events and functions
  addEvent : function(obj, type, func) {
       // W3C approach for non-IE modern browsers
			 if (obj.addEventListener) {obj.addEventListener(type, func, false);}
       // Windows IE approach
       // (had to disable as it would not work in IE and stopped the script entirely
			 //  at the HighlightText on Hover button)
			 /*else if (obj.attachEvent) {
           obj["e" + type + func] = func;
           obj[type + func] = function() {obj["e" + type + func] (window.event);}
					 obj.attachEvent("on" + type, obj[type + func]);
       }*/
			 // browsers supporting neither W3C or IE methods
       else {obj["on" + type] = func;}
   },

   // remove events associated with addEvent
   removeEvent : function (obj, type, func) {
    	// W3C approach for non-IE modern browsers
    	if (obj.removeEventListener) {obj.removeEventListener(type, func, false);}
  	  // Windows IE approach
  	  // (had to disable as it would not work in IE and stopped the script entirely
			 //  at the HighlightText on Hover button)
    	/*else if (obj.detachEvent) {
         obj.detachEvent("on" + type, obj[type + func]);
        	obj[type + func] = null;
        	obj["e" + type + func] = null;
    	}*/
    	// browsers supporting neither W3C or IE methods
    	else {
      	  obj["on" + type] = null;
    	}
	},

  stopDefault : function(e) {
     if (!e) {e = window.event;}
     if (!e.preventDefault) {
        e.preventDefault = function() { this.returnValue = false; }
     }
     e.preventDefault();
     return false;
  },


		// pass the url of the data file, the function that will receive it, and whether data is being posted (optional)
  sendRequest : function(url,func,postData) {

    // xhr will represent the XMLHttpRequest object
    var xhr = jslib.createXMLHttpObject();

    // if that does not work out, then it will be null and the function will exit
    if (!xhr) { return; }

    // if the optional postData is indicated, then use "POST"
    var method = (postData) ? "POST" : "GET";

    // open the request
    xhr.open(method, url, true);

    // set a unique request header for detection purposes
    xhr.setRequestHeader('User-Agent','XHR');

    // if data is being posted, set the appropriate Content-Type
    if (postData) {
      xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    }

    xhr.onreadystatechange = function() {

      // unless the request is Completed, ignore the readystatechange event
      if (xhr.readyState != 4) { return; }

      // if there is an error in the data transmission, show an alert
      if (xhr.status != 200 && xhr.status != 304) {
         alert('HTTP error ' + xhr.status);
         return;
      }

      // pass the XMLHttpRequest object to holdSearchResults()
      func(xhr);
    }

    // if we have already completed the request, stop the function so as not
    // to send it again
    if (xhr.readyState == 4) { return; }

    // if we use "GET" then postData will be null
    xhr.send(postData);
  },

  // all the various cross-browser options for creating the XMLHttpRequest object
  XHRoptions : [
   function () {return new XMLHttpRequest()},
   function () {return new ActiveXObject("Msxml2.XMLHTTP")},
   function () {return new ActiveXObject("Msxml3.XMLHTTP")},
   function () {return new ActiveXObject("Microsoft.XMLHTTP")}
  ],

  // try out each option until one works
  createXMLHttpObject : function() {
    var xmlhttp = false;
    for (var i=0;i<jslib.XHRoptions.length;i++) {
      try { xmlhttp = jslib.XHRoptions[i](); }
      catch (e) { continue; }
      break;
    }
    return xmlhttp;
  }
}