//
//  Copyright Hansen Training Systems, Inc., 2006, 2010, 2011.  All rights reserved.  
//
//  Licensed Material.  Program Property of Hansen Training Systems, Inc. 
//
//
//  Invoked from signon.html
//
var req;
var expiredArray = new Array();
var almostExpiredArray = new Array();
var expiredArrayIndex = 0;
var almostExpiredArrayIndex = 0;
var courseWindow;
document.onkeypress = testKey;

// The following data items are picked up by the next page.
var sessionID = "";
var companyID = "";
var studentID = "";
var studentPW = "";
var newPW     = ""; 
var firstSession = "mainmenu";
var secondSession = "installed";
var startScreen = 0;
var entryViaSearch = false;
var prohibitNextSessionJumps = false;
// End of server data
var browserName = "";
var browserVer  = "";
var browserMinVer = 0;

function init()  {
  //alert("You are using " + window.navigator.userAgent );
  // Perform configuration check and set initial cursor position.
     retrieveAnyPassedData();
     document.getElementById("signon").cID.focus();
}

function testKey(event){
  //Test for Enter in last field.  If so, perform editing.
  var inkey = event.keyCode;
  if (inkey == "13") checkForm();
  event.cancelBubble = true;
}

function checkForm()  {
  //Verify all fields contain data before calling server.
  companyID = document.forms[0].cID.value; 
  studentID = document.forms[0].sID.value;
  studentPW = document.forms[0].sPW.value;
  newPW     = document.forms[0].nPW.value;
  var newPasswordLineDisplayed;
  
  if (document.getElementById("newPWLine").style.visibility == "visible") {
     newPasswordLineDisplayed = true;
  } else {
     newPasswordLineDisplayed = false;
  }
  var readyToGo = true;
  document.getElementById("msgNoCompany").style.display   = "none";
  document.getElementById("msgNoStudent").style.display   = "none";
  document.getElementById("msgNoPassword").style.display  = "none";
  document.getElementById("msgNoNewPW").style.display     = "none";
  document.getElementById("msgBadCompany").style.display  = "none";
  document.getElementById("msgBadStudent").style.display  = "none";
  document.getElementById("msgBadPassword").style.display = "none";
  document.getElementById("msgError").style.display       = "none";
  document.forms[0].cID.focus();

  if (newPasswordLineDisplayed && (isBlank(newPW))) {
	 document.getElementById("msgNoNewPW").style.display = "block";
     document.forms[0].nPW.focus();
     readyToGo = false;
  }
  if (isBlank(studentPW)) {
	 document.getElementById("msgNoPassword").style.display = "block";
     document.forms[0].sPW.focus();
     readyToGo = false;
  }
  if (isBlank(studentID)) {
	 document.getElementById("msgNoStudent").style.display  = "block";
     document.forms[0].sID.focus();
     readyToGo = false;
  }
  if (isBlank(companyID)) {
	 document.getElementById("msgNoCompany").style.display  = "block";
     document.forms[0].cID.focus();
     readyToGo = false;
  }

  if (studentID.toUpperCase() == "STUDENT") {
     document.getElementById("checkBoxLine").style.display  = "none";
     document.forms[0].change.checked = false;
  } else {
	 document.getElementById("checkBoxLine").style.display  = "block";
     if (!newPasswordLineDisplayed && (document.forms[0].change.checked)) {
    	document.getElementById("newPWLine").style.visibility  = "visible";
        document.getElementById("checkBoxLine").style.display  = "none";
        readyToGo = false;
        document.forms[0].nPW.focus();
     }
     if (newPasswordLineDisplayed && (!document.forms[0].change.checked)) {
     	document.getElementById("newPWLine").style.visibility  = "hidden";
   	    document.getElementById("msgNoNewPW").style.display = "none";
     }     
  }
  if (readyToGo) submitToServer(companyID,studentID,studentPW,newPW);
}

function submitToServer(p1,p2,p3,p4) {
   //Build URL and submit data to the server for signon processing.
   var myUrl = "login.ezt";
       myUrl += "?company="     + encodeMe(p1);
       myUrl += "&student_ID="  + encodeMe(p2);
       myUrl += "&student_PW="  + encodeMe(p3);
       myUrl += "&new_PW="      + encodeMe(p4);
   //var myData = "company="    + encodeMe(p1) + "&student_ID="  + encodeMe(p2)
   //        +  "&student_PW="  + encodeMe(p3) + "&new_PW=" + encodeMe(p4);
   req = createXMLHttp();
   req.onreadystatechange = myCallback;
   req.open('GET', myUrl, true);
   req.setRequestHeader("Cache-Control","nocache");
   //alert(myData)
   //req.setRequestHeader("Context-Type", "application/x-www-form-urlencoded");
   req.send(null);
}

function  myCallback() {
  //This function is called after a return from the server.
  if (req.readyState == 4) {
     if (req.status == 200) {
        checkResult(req.responseXML);
     }
  }
}

function encodeMe(value)  {
   //Encode parameters for placement on a URL.
   if (encodeURIComponent) return encodeURIComponent(value);
   if (escape) return escape(value);
   return value;
}

/*
 * Look for:
 * <SIGNON RETURNCODE="0" SESSIONID="abcde"/>
 */

function checkResult(returnObject)  {
  //Receives XML object returned from server.
  //Display appropriate error message or launches a course.
  var returnCodeStr = returnObject.documentElement.getAttribute("RETURNCODE");
  var returnCode = parseInt(returnObject.documentElement.getAttribute("RETURNCODE"));
  sessionID  = returnObject.documentElement.getAttribute("SESSIONID");
  switch (returnCode) {
      case(0):
         expiredArray = returnObject.documentElement.getElementsByTagName("EXPIRED_PRODUCT");
         almostExpiredArray = returnObject.documentElement.getElementsByTagName("ALMOST_EXPIRED_PRODUCT");
         expiredArrayIndex = expiredArray.length;
         almostExpiredArrayIndex = almostExpiredArray.length;
         if ((expiredArrayIndex > 0) || (almostExpiredArrayIndex > 0)) {
            displayExpirationAlert();
         }         
         getAdminOrCourseAnswer(0);
         break;
      case(1):
         document.getElementById("msgBadCompany").style.display  = "block";
         document.forms[0].cID.focus();
         break;
      case(2):
    	 document.getElementById("msgBadStudent").style.display  = "block";
         document.forms[0].sID.focus();
         break;
      case(3):
    	  document.getElementById("msgBadPassword").style.display = "block";
         document.forms[0].sPW.focus();
         break;
      case(4):
         expiredArray = returnObject.documentElement.getElementsByTagName("EXPIRED_PRODUCT");
         expiredArrayIndex = expiredArray.length;
         displayAllExpired();
         break;
      case(10):
         expiredArray = returnObject.documentElement.getElementsByTagName("EXPIRED_PRODUCT");
         almostExpiredArray = returnObject.documentElement.getElementsByTagName("ALMOST_EXPIRED_PRODUCT");
         expiredArrayIndex = expiredArray.length;
         almostExpiredArrayIndex = almostExpiredArray.length;
         if ((expiredArrayIndex > 0) || (almostExpiredArrayIndex > 0)) {
             displayExpirationAlert();
         }
         getAdminOrCourseAnswer(1);
         break;
      default:
         document.getElementById("msgError").style.display = "block";
  }
}

function displayAllExpired() {
   //Displays a message in the main window to indicate that all products have expired.
   var expmsg = "";  
   var beforeHTML = '<br /><center><h1>License Expiration Alert</h1>';
       beforeHTML += "<p>The license has expired for all of your MantaNow products.</p>";
  if (expiredArrayIndex > 0) {      
       beforeHTML += "<p>Following are the affected order numbers:</p>";
       for (var i = 0; i < expiredArrayIndex;i++) {
         expmsg = expmsg + expiredArray[i].firstChild.nodeValue + "<br/>";
       }
  }
   var afterHTML  = "<p>Please call Manta Technologies (800-406-2682) to";
       afterHTML += " renew your license.<br/>We will retain your student information for 60";
       afterHTML += " days after expiration.</p></center>";
   document.getElementById("pageBody").innerHTML = beforeHTML + expmsg + afterHTML;
}

function displayExpirationAlert() {
  var expMsg1  = "The license has expired for the following MantaNow products. ";
      expMsg1 += "They are not listed in your menu.\n";
  var expMsg2  = "\nThe license for the following products will expire in less than a month.\n";
  var expMsg3  = "\nPlease call Manta Technologies (800-406-2682) to renew your license.";
      expMsg3 += "\nWe will retain your student information for 60 days after expiration.";
  var expmsg = "";
  if (expiredArrayIndex > 0) {
     expmsg = expmsg + expMsg1;
     for (var i = 0; i < expiredArrayIndex;i++) {
        expmsg = expmsg + "  " + expiredArray[i].firstChild.nodeValue + "\n";
     }
   }
   if (almostExpiredArrayIndex > 0) {
      expmsg = expmsg + expMsg2;
      for (var j = 0; j < almostExpiredArrayIndex;j++) {
            expmsg = expmsg + "  " + almostExpiredArray[j].firstChild.nodeValue + "\n";
      }
   }
  expmsg = expmsg + expMsg3;
  alert(expmsg);
}

function isBlank(str) {
  if (!str || (str == null) || (stringAllBlank(str))) {
     return true;
  } else {
     return false;
  }
}

function stringAllBlank(str) {
    for (var i = 0; i < str.length; i++) {
       if (str.charAt(i) != " ") return false;  
    }
    return true;
}

function retrieveAnyPassedData()  {
// This function is used for customers with a learning management system
// who pass us the company name, studentID, optional password, and optional session path.
// It is also used for a sample session.
// The function parses the input string to extract these values.
   var url = self.location.href;
   var indexa = url.indexOf("?");
   var indexb = url.indexOf("#");
   var inputData = "";
   if (indexb > indexa) indexa = indexb;
   if (indexa > -1) {
      inputData = url.substr(indexa+1);
   }
   var companyID = document.forms[0].cID.value = getParameter(inputData,"COMPANY=").toLowerCase();
   var studentID = getParameter(inputData,"STUDENT_ID=");
   var studentPW = getParameter(inputData,"STUDENT_PW=");
   if (studentPW == "*SID") studentPW = studentID;
   document.forms[0].cID.value = companyID;
   document.forms[0].sID.value = studentID;
   document.forms[0].sPW.value = studentPW;
}

function getParameter(inString,inParm) {
// This function searches inString for inParm.  It returns subsequent characters,
// ending when '%20', ' ', '&', or the end of the line is encountered.
// If a parameter is not specified, "" is returned.
   var capString = inString.toUpperCase();
   var index1 = capString.indexOf(inParm);
   var index2;
   if (index1 !=-1) {
      index1 = index1 + inParm.length;
      index2 = capString.indexOf("%20",index1);
      if (index2 == -1) {
         index2 = capString.indexOf(" ",index1);
         if (index2 == -1) {
            index2 = capString.indexOf("&",index1);
            if (index2 == -1) {
               return inString.substring(index1);
            } else {
               return inString.substring(index1,index2);
            }
         } else {
            return inString.substring(index1,index2);
         }
      } else {
         return inString.substring(index1,index2);
      }
   } else {
      return "";
   }
}

function getAdminOrCourseAnswer(n) {
   var htmlOut  = '<br/><center><IMG id=mlogo src="images/mantalgo.png" align="absmiddle" height="240px" width="640px" hspace="9"/>';
       htmlOut += '</br></br></br></br></br></br><table>';
       htmlOut += "<tr><td class='MENU'><input type='image' src='images/go.png' ";    
       htmlOut += "onClick='adminChoice(0)' value='GO'/></td><td class='MENU'>"; 
       htmlOut += "<input type='button' class='PLAIN'";   
       htmlOut += "onClick='adminChoice(0)') value='Take a course.'/></td></tr>";
       htmlOut += "<tr><td class='MENU'><input type='image' src='images/go.png' ";    
       htmlOut += "onClick='adminChoice(2)' value='GO'/></td><td class='MENU'>"; 
       htmlOut += "<input type='button' class='PLAIN'";   
       htmlOut += "onClick='adminChoice(2)') value='Search the Manta Library.'/></td></tr>";
   if (n == 1) {    
       htmlOut += "<tr><td class='MENU'><input type='image' src='images/go.png'";    
       htmlOut += "onClick='adminChoice(1)' value='GO'/></td><td class='MENU'>"; 
       htmlOut += "<input type='button' class='PLAIN'";   
       htmlOut += "onClick='adminChoice(1)') value='Access the Student Administration functions.'/></td></tr>";
   }
       htmlOut += '</table></center>';
   document.getElementById("pageBody").innerHTML = htmlOut;
} 

function adminChoice(x) {
	   if (window.localStorage) {
			window.localStorage.setItem("sessionID",sessionID);
			window.localStorage.setItem("companyID",companyID);
			window.localStorage.setItem("studentID",studentID);
			window.localStorage.setItem("firstSession",firstSession);
			window.localStorage.setItem("secondSession",secondSession);
			window.localStorage.setItem("prohibitNextSessionJumps","" + prohibitNextSessionJumps);
			window.localStorage.setItem("entryViaSearch","false");
			window.localStorage.setItem("startScreen","0");
		}
   if (x == 0) {
	   if (!configCheck()) {
           newWindow();
           displayCopyright();
	   }
    } else {
    	if (x == 2) {
    	   var searchWindow = window.open("search.htm","_blank","width=800px,scrollbars=yes,resizable=yes,tollbar=no;");
    	   displayCopyright();    		
    	} else {
    		window.document.location = "adminPassThru.admin;jsessionid=" + sessionID;
        } 
    }    
}

function displayCopyright() {
   //Replace the signon screen.
   var htmlOut  = '<center><IMG id=mlogo src="images/mantalgo.png" align="absmiddle" height="240px" width="640px" hspace="9"/>';
       htmlOut += '<p>Course material copyright &#169; Manta Technologies Inc. 1994-2011.  All rights reserved.';
       htmlOut += '<br/>EasyTutor&#8482;, Copyright &#169; 1990-2011, Hansen Training Systems, Inc.';
       htmlOut += '<br/>Licensed Material.  Program Property of MTI and HTS.</p></center>';
       htmlOut += '<br/><br/><div style="text-align:center"><p>You have successfully signed on.';
       htmlOut += 'The Manta training should have popped up in a second window.';
       htmlOut += '</p><p>Click the appropriate link if you experience one of these errors:</p>';
       htmlOut += '<p><a href="javascript:msgPopup()">The second window never appeared.</a></p>';
       htmlOut += '<p><a href="javascript:msgTab()">The Manta training appeared as another tab, rather than as a second window.</a></p>';
       htmlOut += '</div><br/><br/>';
       htmlOut += '<center><p><a class="ON" href="signon.html">Sign on again</a>';
       document.getElementById("pageBody").innerHTML = htmlOut;
}

function newWindow() {
   var IE = false;
   if (window.navigator.appName.indexOf("Microsoft") != -1) {IE = true;}
   var popupMessage = "The Manta software is unable to run because your browser is ";
       popupMessage += "blocking pop-up windows.  To allow the Manta software to run, ";
       popupMessage += "click the OK button to close this window, open the Internet Explorer Tools ";
       popupMessage += 'pull-down menu, select the Pop-Up Blocker option, and then select "Always Allow Pop-ups from This Site...".';
   if (!courseWindow || courseWindow.closed) {
	  if (IE) {
		  var courseWindow = window.open("mantanow.html","_blank","width=1010px,height=668px,top=0,left=0,dependent,hotkeys,menubar=0,toolbar=0,titlebar=0,status=0,resizable=0")
	  } else {
	      var courseWindow = window.open("mantanow.html","_blank","width=1014px,height=672px,top=0,left=0,dependent,hotkeys,menubar=0,toolbar=0,titlebar=0,status=0,resizable=0")
	  }
   } else {
       courseWindow.focus();
   }
   if (!courseWindow || courseWindow.closed) {alert(popupMessage);}
}

function configCheck() {
   browserCheck();
   var notAllOkay = false;
   var colorDepth;
   var aHeight;
   var aWidth;
   var colorAction = "none";
   var resolutionAction = "none";
   var colorMessage = "Your screen display mode does not use enough colors to properly"
   + " display the figures in this course as they were intended."
   + "  We recommend that you change the display to use 24-bit color or higher."
   + "  To do so, perform the following steps:"
   + "<ol><li>Use your mouse to right-click any blank area of the desktop.</li>"
   + '<li>Click "Properties".</li>'
   + '<li>Click the "Settings" tab.</li>'
   + '<li>Change the "Colors" to 24-bit or higher.</li>'
   + '<li>Click "OK".</li>'
   + '</ol><p>If you are given the option, apply the new color setting without rebooting your system.</p>';
   var resolutionMessage = "Your screen display mode is not at a high enough resolution to properly"
   + " display the text, figures, and screen examples in this course."
   + "  You must change the display to use 1024 x 768 resolution or greater."
   + "  To do so, perform the following steps:"
   + "<ol><li>Use your mouse to right-click any blank area of the desktop.</li>"
   + '<li>Click "Properties".</li>'
   + '<li>Click the "Settings" tab.</li>'
   + '<li>Change the "Screen area" to 1024 x 768 pixels or greater.</li>'
   + '<li>Click "OK".</li></ol>'
   + '<p>Some browsers, including Internet Explorer, let you enlarge the browser window by reducing its '
   + 'resolution.  (This is done by holding <b>Alt</b> while turning the mouse wheel.)  '
   + 'In this case, you screen may be fine, but it is reporting a lower resolution.</p>';   
   var browserMsg = "We do not recognize the browser that you are using.  "
   +  "The Manta software has been tested with Internet Explorer, FireFox, Chrome, Opera, and Safari.  "   
   +  "If you find that the Manta software works with your browser, please contact Manta technical "
   +  "support and we will add it to the list.";
   var browserVerMsg = "You are using an older version of your browser than the version we tested.  "
   +  "As a result, not all features may work.  In particular, older browsers do not support the HTML "
   +  "audio tag that we use to play audio files.  We recommend upgrading your browser.  "
   +  "If you decide to continue, please let us know about any problems that you experience."
   var myHTML =  '<center><h1>Configuration Problem</h1>';
       myHTML += "<p>A configuration setting or the browser you are using may give you less than optimal performance.</p>"
       myHTML += '<table border="1px" cellpadding="8px" cellspacing="0px">';
       myHTML += '<tr>';
       myHTML += '<td><b>Configuration Item</b></td>';
       myHTML += '<td><b>Requirement</b></td>';
       myHTML += '<td><b>You have</b></td>';
       myHTML += '<td><b>Recommended Action</b></td>';

   // Color settings
   colorDepth = screen.colorDepth;
   if (colorDepth < 24) {
      colorAction = colorMessage;
      notAllOkay = true;
      myHTML += '</tr><tr>';
      myHTML += '<td>Display Colors</td>';
      myHTML += '<td>24-bit or greater</td>';
      myHTML += '<td>' + colorDepth + '</td>';
      myHTML += '<td>' + colorAction + '</td>';
   }

   // Screen resolution
   aHeight = screen.height;
   aWidth = screen.width;
   if ((aHeight < 768) || aWidth < 1024) {
      resolutionAction = resolutionMessage;
      notAllOkay = true;
      myHTML += '</tr><tr>';
      myHTML += '<td>Display Resolution</td>';
      myHTML += '<td>1024 x 768 or greater</td>';
      myHTML += '<td>' + aWidth +' x ' + aHeight + '</td>';
      myHTML += '<td>'+ resolutionAction + '</td>';
   }
   if ((browserName != "Internet Explorer") && 
	   (browserName != "FireFox") &&
	   (browserName != "Opera") &&
	   (browserName != "Chrome") &&
	   (browserName != "Safari") &&
	   (browserName != "Safari Mobile")) {
	   notAllOkay = true;
	   myHTML += '</tr><tr>';
	   myHTML += '<td>Browser Used</td>';
	   myHTML += '<td>Internet Explorer, FireFox, Chrome, Opera, Safari, or Sarafi Mobile</td>';
	   myHTML += '<td>' + browserName + '</td>';
	   myHTML += '<td>'+ browserMsg + '</td>';	   
   }

   if (parseInt(browserVer) < parseFloat(browserMinVer)){
	   notAllOkay = true;
	   myHTML += '</tr><tr>';
	   myHTML += '<td>Browser Version</td>';
		   myHTML += '<td>' + browserName + '<br/>' + browserMinVer + '</td>';
		   myHTML += '<td>' + browserName + '<br/>' + browserVer + '</td>';
		   myHTML += '<td style="text-align:left;">'+ browserVerMsg + '</td>';	   
	   }

   myHTML += '</tr>';
   myHTML += '</table><br/><br/>';
   myHTML += '<input type="button" onclick="newWindow();" Value="Continue anyway"/>&nbsp;&nbsp;';
   myHTML += '<input type="button" onclick="window.close();" Value="Exit"/>&nbsp;&nbsp;';
   myHTML += '</center><br/><br/>';

  if (notAllOkay) {
     window.document.getElementById('pageBody').innerHTML = myHTML;
  }

  return notAllOkay;
}

function msgPopup(){
   alert("The Manta software is unable to run because your browser is " +
         "blocking pop-up windows.  Please unblock pop-ups for www.mantanow.com." +
         "\n\nIn addition to the pop-up blocker that is built into " +
         "your browser, other pop-up blockers are contained in most virus checkers " +
         "and various browser toolbar " +
         "add-ons, including those provided by Google, Yahoo, Comcast, AOL, and others. " +
         "You will need to look carefully at the " +
         "toolbar to determine which product is doing the blocking." +
         "\n\nPlease e-mail support@mantatech.com if you need further assistance."  );
}

function msgTab() {
   alert("The Manta courseware will not run as intended in a tab.  It needs to run in an " +
         "independent window.  While it will normally do so with the default browser settings, your " +
         "browser has been set up to force all pop-ups to use a tab." +
         "\n\nYou can perform the following steps to correct the problem in Internet Explorer." +
         "\n1.  Click the 'Tools' pull-down menu." +
         "\n2.  Select 'Internet Options.'" +
         "\n3.  On the 'General' page, click the Tabs 'Settings' button." +    
         "\n4.  Select 'Let Internet Explorer decide how pop-ups should open.'" +   
         "\n5.  Click 'OK' twice." +      
         "\n6.  Close the current browser tabs and sign-on again.");
}
function createXMLHttp() {
	// This function instantiates a new Ajax object.
	  if (typeof XMLHttpRequest != "undefined") {
	      return new XMLHttpRequest();
	  } else {
	     if (window.ActiveXObject) {
	        var aVersions = ["Msxml2.XMLHTTP.5.0","Msxml2.XMLHTTP.4.0",
	                         "Msxml2.XMLHTTP.3.0","Msxml2.XMLHTTP",
	                        "Microsoft.XMLHTTP"];
	        for (var i = 0; i < aVersions.length; i++) {
	           try {
	              var oXmlHttp = new ActiveXObject(aVersions[i]);
	              return oXmlHttp; 
	           } catch (e) {
	           }
	        }
	     }
	  }
	  alert('XMLHTTP is not available.  You have an obsolete or damaged browser.');
}
function browserCheck() {
	//Determines browser name and release.  Sets browserName and browserVer.
	var longName = window.navigator.userAgent;

	// Check for IE
	if (longName.indexOf("MSIE") != -1) {
		browserName = "Internet Explorer";
		browserVer  = longName.substr(longName.indexOf("MSIE")+5,4);
		browserMinVer = 7.0;
		return;
	}
		// Check for FireFox
	if (longName.indexOf("Firefox") != -1) {
		browserName = "FireFox";
		browserVer  = longName.substr(longName.indexOf("Firefox")+8,3);
		browserMinVer = 3.5;
		return;
	}
	// Check for Opera
	if (longName.indexOf("Opera") != -1) {
		browserName = "Opera";
		browserVer  = longName.substr(longName.indexOf("Version")+8,4);
		browserMinVer = 10.5;
		return;
	}
	// Check for Chrome
	if (longName.indexOf("Chrome") != -1) {
		browserName = "Chrome";
		browserVer  = longName.substr(longName.indexOf("Chrome")+7,4);
		browserMinVer = 3.0;
		return;
	}
	// Check for Safari
	if (longName.indexOf("Safari") != -1) {
		browserName = "Safari";
		if (longName.indexOf("Mobile") != -1) {
			browserName = "Safari Mobile";
		}
		browserVer  = longName.substr(longName.indexOf("Version")+8,4);
		browserMinVer = 3.0;	
		return;	
	}

	browserName = longName;
	broserVer = browserVer;
	browserMinVer = 0;
}

