﻿// JScript File

function IsValidGuid(strGuid){
    if(strGuid == "" || strGuid == null) return false;
    
    var reg = /^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$/
    return reg.test(strGuid);
}

function IsUserLoggedIn(){

    SetSiteParameters();
        
    if(IsValidGuid(readCookie(strTrackerCookieName)))
    {
        return true;        
    }
    
    //this is an invalid session. Redirect to the login page
    alert('User not logged in. Redirecting to login page');    
    window.location.href = GetSiteParam('site_url');
    
    return false;
}

//Purpose:  creates an object who's members represent the arguments
//			in the URL
function getArgsObject()
{
    try
    {
        var args = new Object();
        var query = location.search.substring(1); //get the query string skipping the '?'
        var pairs = query.split('&');
        var base = location.href.split('?');
          
        args["[-base url-]"] = base[0];
        
        for(var i = 0; i < pairs.length; i++)
        {
            var item = pairs[i].split('=');

            if(item.length >= 2)
            {
                args[item[0]] = item[1];
            }
        }

        return args;

    }
    catch(err)
    {
        alert('Exception caught: ' + err);
    }

    return null;
}   
         
function loadTrackerParams()
{            
    //check for the ID being passed into the page
    var objArgs = getArgsObject();
    if(objArgs != null)
    {
        var strID = objArgs["id"];
        if(strID != null)
        {
            //get current cookie (if it exists)
            var cookieID = readCookie(strTrackerCookieName);
            if(cookieID != null)
            {
                //clean out the current cookie
                eraseCookie(strTrackerCookieName);
            }
            
            //store the user's database ID in the cookie
            createCookie(strTrackerCookieName,strID);                                   
        }else
        {
            alert('Error: missing ID');
        }     
    }   
} 

function GetXmlHttpObject(bUseSecondary)
{
    //use a singleton pattern
    var httpObj = null;
    
    if(bUseSecondary)
    {     
        if(xmlhttp2 != null)
        {
            return xmlhttp2;
        }
        
        xmlhttp2=null;
        
    }else
    {
        if(xmlhttp != null)
        {
            return xmlhttp;
        }
        
        xmlhttp=null;
    }            
    
    try
      {
          // Firefox, Opera 8.0+, Safari
          httpObj=new XMLHttpRequest();
      }
    catch (e)
      {
          // Internet Explorer
          try
            {
                httpObj=new ActiveXObject("Msxml2.XMLHTTP");
            }
          catch (e)
            {
                httpObj=new ActiveXObject("Microsoft.XMLHTTP");
            }
      }
      
    if(httpObj == null)
    {
        alert('Ajax is not supported by your browser');
    }
          
    if(bUseSecondary)
    {     
        xmlhttp2 = httpObj;
    }else
    {
        xmlhttp = httpObj;
    }
              
    return httpObj;
}
        
function LogStartTime(id)
{       
    var strUserId = readCookie(strTrackerCookieName);        
    var objHTTP = GetXmlHttpObject();
    var strURL = GetSiteParam('services_url') + "/Services.asmx/LogStartTime?strUserID=" + strUserId + "&strID=" + id;
    //objHTTP.onreadystatechange=onLogStartTimeCompleted;    
    objHTTP.open("GET", strURL, false);
    objHTTP.send(null); 
    
    //save the current section since this will allow us to do "instant" time on the 
    //credit screen
    
    var strSectionID = readCookie(strTrackerSectionCookieName);
    if(strSectionID != null || strSectionID != "")
    {
        eraseCookie(strTrackerSectionCookieName);
    }

    //store the log section ID in the cookie
    createCookie(strTrackerSectionCookieName,id);  
    
    onLogStartTimeCompleted();  
}

function onLogStartTimeCompleted()
{
    var objHTTP = GetXmlHttpObject();

    if (objHTTP.readyState==4)
    {
        if (objHTTP.status==200)
        {            
            var strMsg = objHTTP.responseXML.documentElement.childNodes[0].nodeValue;
            
            if(strMsg != "" && strMsg != null)
            {
                var arrParts = strMsg.split('|');
                
                if(arrParts.length >= 2)
                {
                    if(arrParts[0].indexOf("error_no_user") != -1)
                    {
                        window.location.href = GetSiteParam('services_url') + "/Error.aspx?message=" + escape("Invalid User");
                    }else if(arrParts[0].indexOf("error") != -1)
                    {
                        window.location.href = GetSiteParam('services_url') + "/Error.aspx?message=" + escape("Error setting time");
                    }else if(arrParts[0].indexOf("id") != -1)
                    {
                        //we have the log id store it in a variable.
                                                
                        //get current cookie (if it exists)
                        var cookieID = readCookie(strTrackerLogIdCookieName);
                        if(cookieID != null)
                        {
                            //clean out the current cookie
                            eraseCookie(strTrackerLogIdCookieName);
                        }
                        
                        //store the log database ID in the cookie
                        createCookie(strTrackerLogIdCookieName,arrParts[1]);                            
                    }
               }
            }
        }
        else
        {
            alert("Problem retrieving XML data:" + objHTTP.statusText);
        }        
    }                  
}
             
function LogEndTime(id)
{        
    var strUserId = readCookie(strTrackerCookieName);            
    var strLogId = readCookie(strTrackerLogIdCookieName);    
    if(strLogId == null || strLogId == "") { alert('no logid'); return; }
    
    var objHTTP = GetXmlHttpObject();
    var strURL = GetSiteParam('services_url') + "/Services.asmx/LogEndTime?strLogID=" + strLogId + "&strUserID=" + strUserId + "&strID=" + id;
    //objHTTP.onreadystatechange=onLogEndTimeCompleted;    
    objHTTP.open("GET", strURL, false);
    objHTTP.send(null);   
    
    onLogEndTimeCompleted();
    
    //we need to erase these cookies so that if someone just 
    //happens to have the credit screen still up and they goto a non-protocol page
    //then the time will stop incrementing on the LAST
    //protocol section visited.
    if(readCookie(strTrackerLogIdCookieName) != null)
    {   
        eraseCookie(strTrackerLogIdCookieName);
    }
    
    if(readCookie(strTrackerSectionCookieName) != null)
    {
        //clean out the current cookie
        eraseCookie(strTrackerSectionCookieName);
    }   
} 
   
function onLogEndTimeCompleted()
{
    var objHTTP = GetXmlHttpObject();
        
    if (objHTTP.readyState==4)
    {
        if (objHTTP.status==200)
        {
           var strMsg = objHTTP.responseXML.documentElement.childNodes[0].nodeValue;
            
            if(strMsg != "" && strMsg != null)
            {
                var arrParts = strMsg.split('|');
                
                if(arrParts.length >= 2)
                {
                    if(arrParts[0].indexOf("error_no_user") != -1)
                    {
                        window.location.href = GetSiteParam('services_url') + "/Error.aspx?message=" + escape("Invalid User");
                    }else if(arrParts[0].indexOf("error") != -1)
                    {                        
                        window.location.href = GetSiteParam('services_url') + "/Error.aspx?message=" + escape("Error setting time");
                    }
                }
            }
        }
        else
        {
            alert("Problem retrieving XML data:" + objHTTP.statusText);
        }        
    }                  
}

function GetCurrentUserTimeDelta(id)
{
    var strUserId = readCookie(strTrackerCookieName);
    var strLogId = readCookie(strTrackerLogIdCookieName);
    var strSectionId = readCookie(strTrackerSectionCookieName);
    
    //if there is no log then just provide the cumulative amount
    //if section ID doesnt match the current section then also show the cumulative amount
    if(strLogId == null || strLogId == "" || strSectionId != id)
    { 
        strLogId ="00000000-0000-0000-0000-000000000000"; 
    }
    
    if(strUserId == null)
    { 
        alert('no user cookie'); return; 
    }
           
    var objHTTP = GetXmlHttpObject();
    var strURL = GetSiteParam('services_url') + "/Services.asmx/GetUserTimeDelta?strUserID=" + strUserId + "&strID=" + id + "&strTimeSegmentID=" + strLogId;
    //objHTTP.onreadystatechange=onGetCurrentUserTimeDeltaCompleted;    
    objHTTP.open("GET", strURL, false);
    objHTTP.send(null);   
    
    return onGetCurrentUserTimeDeltaCompleted();    
}


function onGetCurrentUserTimeDeltaCompleted()
{
    var objHTTP = GetXmlHttpObject();
        
    if (objHTTP.readyState==4)
    {
        if (objHTTP.status==200)
        {
           var strMsg = objHTTP.responseXML.documentElement.childNodes[0].nodeValue;
            
            if(strMsg != "" && strMsg != null)
            {
                var arrParts = strMsg.split('|');
                
                if(arrParts.length >= 2)
                {
                    if(arrParts[0].indexOf("error_no_user") != -1)
                    {
                        window.location.href = GetSiteParam('services_url') + "/Error.aspx?message=" + escape("Invalid User");
                    }else if(arrParts[0].indexOf("error") != -1)
                    {
                        //window.location.href = escape(GetSiteParam('services_url') + "/Error.aspx?message=Error setting time");
                        alert('error: ' + arrParts[1]);
                    }else
                    {
                        return arrParts[1];
                    }
                }
            }
        }
        else
        {
            alert("Problem retrieving XML data:" + objHTTP.statusText);
        }        
    }       
    
    return "";           
}
 
function GetCurrentUserInfo(onCompleted)
{
    var strUserId = readCookie(strTrackerCookieName);
    
    if(strUserId == null)
    { 
        alert('no user cookie'); return; 
    }   
           
    var objHTTP = GetXmlHttpObject();
    var strURL = GetSiteParam('services_url') + "/Services.asmx/GetUserInfo?strUserID=" + strUserId;
    objHTTP.onreadystatechange=onCompleted;
    objHTTP.open("GET", strURL, true);
    objHTTP.send(null);   
}


//called when the GetCurrentUserInfo AJAX method completes.
function onGetCurrentUserInfoCompleted()
{
    var objHTTP = GetXmlHttpObject();
        
    if (objHTTP.readyState==4)
    {
        if (objHTTP.status==200)
        {
           var strMsg = objHTTP.responseXML.documentElement.childNodes[0].nodeValue;
            
            if(strMsg != "" && strMsg != null)
            {
                var arrParts = strMsg.split('|');
                
                if(arrParts.length >= 2)
                {
                    if(arrParts[0].indexOf("error_no_user") != -1)
                    {
                        window.location.href = GetSiteParam('services_url') + "/Error.aspx?message=" + escape("Invalid User");
                    }else if(arrParts[0].indexOf("error") != -1)
                    {
                        //window.location.href = escape(GetSiteParam('services_url') + "/Error.aspx?message=Error setting time");
                        alert('error: ' + arrParts[1]);
                    }else
                    {
                        //we got the info ..parse it out and assign it to the fields.
                        var arrStrFields = arrParts[1].split('~');
                        
                        for(var i = 0; i < arrStrFields.length; i++)
                        {
                            var arrItems = arrStrFields[i].split('^');
                            if(arrItems.length >= 2)
                            {
                                var strField = arrItems[0].toLowerCase();
                                //email field is an exception to the naming convention
                                if(strField == 'email')
                                {
                                    strField = 'email_address';
                                }
                                                                                               
                                var frmField = MM_findObj(strField);
                                if(frmField != null)
                                {
                                    frmField.value = arrItems[1];
                                }
                            }
                        }                             
                    }
                }
            }
        }
        else
        {
            alert("Problem retrieving XML data:" + objHTTP.statusText);
        }        
    }       
    
    return "";           
}

function GetExamStatus(id,returnpage,onCompleted)
{
    var strUserId = readCookie(strTrackerCookieName);
    strTrackerExamReturnPageName = returnpage;
    
  /*  if(readCookie(strTrackerExamReturnPageName) != null)
    {
        eraseCookie(strTrackerExamReturnPageName);
    }
    
    createCookie(strTrackerExamReturnPageName,returnpage);
    
    alert(returnpage);*/
    
    if(strUserId == null)
    { 
        alert('no user cookie'); return; 
    }    
           
    var objHTTP = GetXmlHttpObject(true);
    var strURL = GetSiteParam('services_url') + "/Services.asmx/GetExamStatus?strUserID=" + strUserId + "&strID=" + id;
    
    objHTTP.onreadystatechange=onCompleted;
    objHTTP.open("GET", strURL, true);
    objHTTP.send(null);   
}

//called when the HasUserPassedExam AJAX method completes.
function onGetExamStatusCompleted()
{
    var objHTTP = GetXmlHttpObject(true);
    var strReturnPage = strTrackerExamReturnPageName;
               
    if (objHTTP.readyState==4)
    {
        if (objHTTP.status==200)
        {
           var strMsg = objHTTP.responseXML.documentElement.childNodes[0].nodeValue;
            
            if(strMsg != "" && strMsg != null)
            {
                var arrParts = strMsg.split('|');                               
                
                if(arrParts.length >= 2)
                {                              
                    if(arrParts[0].indexOf("error_no_user") != -1)
                    {                        
                        window.location.href=(GetSiteParam('services_url') + "/ErrorNoButton.aspx?message=" + escape("Invalid User."));                        
                    }else if(arrParts[0].indexOf("error") != -1)
                    {
                        //window.location.href = escape(GetSiteParam('services_url') + "/Error.aspx?message=Error setting time");
                        alert('error: ' + arrParts[1]);
                    }else if(arrParts[1] == "too_many_attempts")
                    {
                        window.location.href = (GetSiteParam('services_url') + "/ErrorNoButton.aspx?message=" + escape("You have exceeded the 3 attempts to receive a passing score."));
                        
                       /* if(strReturnPage != null && strReturnPage != "")
                        {
                            window.location.href = strReturnPage; 
                        }*/
                        
                    }else if(arrParts[1] == "passed")
                    {
                        window.location.href = (GetSiteParam('services_url') + "/ErrorNoButton.aspx?message=" + escape("You have already passed this exam."));
                        /*
                        if(strReturnPage != null && strReturnPage != "")
                        {
                            window.location.href = strReturnPage; 
                        }*/
                    }
                }
            }
        }
        else
        {
            alert("Problem retrieving XML data:" + objHTTP.statusText);
        }        
    }       
    
    return "";           
}

function onLoadExamPage(id,returnpage)
{  
    SetSiteParameters();
    
    //setup the url specific settings
    var frmMain = MM_findObj('frmMain');
    var hidUserId = MM_findObj('userid');
    
    if(hidUserId == null)
    {
        return;    
    }
    
    hidUserId.value = readCookie(strTrackerCookieName);    

    if(!IsValidGuid(hidUserId.value))
    {
        //this is an invalid session. Redirect to the login page
        alert('User not logged in. Redirecting to login page');
        window.location.href = GetSiteParam('site_url');
        return;
    }
    
    if(frmMain != null)
    {        
        frmMain.action = GetSiteParam('services_url') + "/Score.aspx";
    }
    
    var onSuccess = MM_findObj('on_success');
    
    if(onSuccess != null)
    {
        onSuccess.value = GetSiteParam('site_url') + "/assets/html/passed_test.html";
    }   
    
     //asynchronously grab the user info and the exam status and use the default handlers
    GetCurrentUserInfo(onGetCurrentUserInfoCompleted);       
    //this method uses a secondary http object so it can be called concurrently with GetCurrentUserInfo 
    GetExamStatus(id,returnpage,onGetExamStatusCompleted);          
}  
      
var strTrackerExamReturnPageName = "ALPH_071206_Enterline_Web_ExamReturnPage";    
var strTrackerCookieName = 'ALPH_071206_Enterline_Web';    
var strTrackerLogIdCookieName = 'ALPH_071206_Enterline_Web_LogId';  
var strTrackerSectionCookieName = 'ALPH_071206_Enterline_Web_Section';     
var xmlhttp = GetXmlHttpObject();
var xmlhttp2 = GetXmlHttpObject(true);
