// JavaScript Document

function getURLparam(paramName) {
	paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]" + paramName + "=([^&#]*)";
 	var regex = new RegExp( regexS );
  	var results = regex.exec( window.location.href );
  	if( results == null ) {
    	return "";
  	} else {
    	return results[1];
	}
};

function replaceNode (dNode,sNode) {
// Clear the destination node, dNode
	if (dNode.hasChildNodes()) {
		var childNodes = dNode.childNodes;
		var i = 0;
		while (childNodes.length>0) {
			dNode.removeChild(childNodes[0]);
			childNodes = dNode.childNodes;
			i++;
		}
	} else {
	}
// Copy nodes from source to destination
	var sClone = sNode.cloneNode(true);	
// Set the ID correctly
	sClone.id = "sourceClone";
	var classNameArray = sClone.className.split(/\s/g);
	sClone.className = "";
	for (var j=0; j<classNameArray.length; j++) {
		if (classNameArray[j].search(/fciHidden/)) {
			sClone.className += classNameArray[j] + " ";
		}
	}
//	Add the clone to the destination node
	dNode.appendChild(sClone);
// Set the ID correctly
};


function logWrite(text) {
	var logSpace = document.getElementById("pageLog");
	logSpace.innerHTML = logSpace.innerHTML + "<p>" + text + "</p>";
};
function logClear(text) {
	var logSpace = document.getElementById("pageLog");
	logSpace.innerHTML = "<p>" + text + "</p>"
};

function loadNode (sNode, dNode) {
	var c = $(sNode).innerHTML;
	if (c.length > 0) {
		replaceNode($(dNode),$(sNode));
	}
};

//		AJAX Functions

function getPdfFileName(courseNumber){
	if (window.XMLHttpRequest){
		xhr = new XMLHttpRequest();
	} else {
		if (window.ActiveXObject){
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {}
		}
	}
	
	if (xhr) {
		var params = "courseNumber=" + courseNumber;
		xhr.open("POST", "../Scripts/getPdf.php" , true);
		xhr.setRequestHeader("Content-type" , "application/x-www-form-urlencoded");
		xhr.setRequestHeader("Content-length", params.length);
		xhr.setRequestHeader("Connection", "close");
		xhr.onreadystatechange = setObjectSource;
		xhr.send(params);
	} else {
		alert ("Unable to create an XMLHttpRequest");
	}
};

function setObjectSource() {
	if (xhr.readyState == 4) {
		if (xhr.status == 200) {
			if(xhr.responseXML && xhr.responseXML.contentType == "text/XML") {
				alert("Invalid data return from AJAX. XML: " + xhr.responseText)
			} else {			
				JSONObject = eval("(" + xhr.responseText +")");
				if (JSONObject.Status == "SUCCESS") {
					if (document.getElementById("pdfPanelObject") != null) {
						viewerPanelElement = document.getElementById("pdfPanelObject");
						// Remove all of the children
						if (viewerPanelElement.hasChildNodes()) {
							while(viewerPanelElement.childNodes.length >= 1) {
								viewerPanelElement.removeChild(viewerPanelElement.firstChild);
							}
						}
						// Create the new children
						var eObject = document.createElement('object');
						eObject.setAttribute('id','pdfViewer');
						eObject.setAttribute('data',
							'../pdfs/courses/' + JSONObject.DisplayName + '.pdf#page=1&view=FitH,0&toolbar=1&statusbar=0&messages=0&navpanes=0&scrollbar=1');
						eObject.setAttribute('type','application/pdf');
						eObject.setAttribute('width', '775');
						eObject.setAttribute('height', '530');
						eObject.setAttribute('style', 'z-index=0;');
						viewerPanelElement.appendChild(eObject);
//						RemoveClassName(document.getElementByID('imageLoading'),"fciHidden");
//						AddClassName(viewerPanelElement, "fciHidden", true);
//						alert("File name" + document.getElementById("pdfViewer").getAttribute('data'));
//		  				if (downloadEstimate < 1000) {
//							downloadEstimate = 1000;
//						}
//						var t=setTimeout("endOfTime()",downloadEstimate);
					} else {
						alert("document.getElementById(pdfPanelObject): " + document.getElementById("pdfPanelObject"));
					}
				} else {
					alert("AJAX ERROR: " + JSONObject.Status);
				}
			}
		} else {
			alert("There was a problem with AJAX request:" + xhr.status);
		}
	}
};

//function endOfTime() {
//	RemoveClassName(document.getElementById("pdfPanelObject"),"fciHidden");
//};
//var SpeedTest = function() {
  /*
  From:  http://techallica.com/kilo-bytes-per-second-vs-kilo-bits-per-second-kbps-vs-kbps/
  256 kbps            31.3 KBps
  384 kbps            46.9 KBps
  512 kbps            62.5 KBps
  768 kbps            93.8 KBps
  1 mbps ~ 1000kbps   122.1 KBps
  */
//};
//SpeedTest.prototype = {
// imgUrl: "../images/logo_watermark.png"    // Where the image is located at
//  ,size: 27000                // bytes
//  ,run: function( options ) {
//
//    if( options && options.onStart )
//      options.onStart();
//
//    var imgUrl = this.imgUrl + "?r=" + Math.random();
//    this.startTime = (new Date()).getTime() ;
//
//    var testImage = new Image();
//    var me = this;
//    testImage.onload = function() {
//      me.endTime = (new Date()).getTime();
//      me.runTime = me.endTime - me.startTime;
//
//      if( options && options.onEnd )
//        options.onEnd( me.getResults() );
//    };
//    testImage.src = imgUrl;
//  }
//
//  ,getResults: function() {
//    if( !this.runTime )
//      return null;
//
//    return {
//      runTime: this.runTime
//      ,Kbps: ( this.size * 8 / 1024 / ( this.runTime / 1000 ) )
//      ,KBps: ( this.size / 1024 / ( this.runTime / 1000 ) )
//    };
//  }
//}


// ----------------------------------------------------------------------------
// HasClassName
//
// Description : returns boolean indicating whether the object has the class name
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function HasClassName(objElement, strClass)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ )
         {

         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper )
            {

            // we found it
            return true;

            }

         }

      }

   // if we got here then the class name is not there
   return false;

   }
// 
// HasClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// AddClassName
//
// Description : adds a class to the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function AddClassName(objElement, strClass, blnMayAlreadyExist)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // if the new class name may already exist in list
      if ( blnMayAlreadyExist )
         {

         // get uppercase class for comparison purposes
         var strClassUpper = strClass.toUpperCase();

         // find all instances and remove them
         for ( var i = 0; i < arrList.length; i++ )
            {

            // if class found
            if ( arrList[i].toUpperCase() == strClassUpper )
               {

               // remove array item
               arrList.splice(i, 1);

               // decrement loop counter as we have adjusted the array's contents
               i--;

               }

            }

         }

      // add the new class to end of list
      arrList[arrList.length] = strClass;

      // add the new class to beginning of list
      //arrList.splice(0, 0, strClass);
      
      // assign modified class name attribute
      objElement.className = arrList.join(' ');

      }
   // if there was no class
   else
      {

      // assign modified class name attribute      
      objElement.className = strClass;
   
      }

   }
// 
// AddClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// RemoveClassName
//
// Description : removes a class from the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to remove
//
function RemoveClassName(objElement, strClass)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ )
         {

         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper )
            {

            // remove array item
            arrList.splice(i, 1);

            // decrement loop counter as we have adjusted the array's contents
            i--;

            }

         }

      // assign modified class name attribute
      objElement.className = arrList.join(' ');

      }
   // if there was no class
   // there is nothing to remove

   }
// 
// RemoveClassName
// ----------------------------------------------------------------------------
