﻿//*********************************************
//wei yu -- 07-04-2009
//Display lessons using Ajax
     
var theForm = document.forms['aspnetForm'];
if (!theForm) {
    theForm = document.aspnetForm;
}

//called when a post back is required. post the form back to server.
//not finished yet.
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
      theForm.__EVENTTARGET.value = eventTarget;
      theForm.__EVENTARGUMENT.value = eventArgument;
      theForm.submit();
    }
}
             
function __addHiddenInputField(formElement, fieldName, fieldValue) {   
    if (document.getElementById(fieldName).checked==false) {
        var inputElement = document.createElement("input");
        inputElement.setAttributeNode(createHtmlAttribute("type", "hidden"));  
        inputElement.setAttributeNode(createHtmlAttribute("name", fieldName+"delete"));  
        inputElement.setAttributeNode(createHtmlAttribute("value", fieldValue));
        document.forms['aspnetForm'].appendChild(inputElement);
        return;
    }
}
                    
function createHtmlAttribute(name, value) {  
    var attribute = document.createAttribute(name);
    attribute.nodeValue = value;  
    return attribute;
}
    
var _currentPage;
if (!_currentPage) {
   _currentPage = 1;
}

var lessonID = "0";
if (Request.QueryString("Lid").Count > 0) {
    lessonID = Request.QueryString("Lid").Item(1);
}

var clientID = "0";
if (Request.QueryString("client").Count > 0) {
    clientID = Request.QueryString("client").Item(1);
}

//Dispaly the page, hide other pages, turn on or off the next/back buttons.
function display(_currentPage, _totalpageno)
{        
         //if the current page is the first page, hide the back button                
         if ( _currentPage == 1)
         {
            backdiv = document.getElementById("ctl00_ContentPlaceHolder1_backBtn").style.display = "none";
            backbtmdiv = document.getElementById("ctl00_ContentPlaceHolder1_backBtnBtm").style.display = "none";
         }
         //if the current page is not the first page, show the back button   
         else
         {
            backdiv = document.getElementById("ctl00_ContentPlaceHolder1_backBtn").style.display = "block";
            backbtmdiv = document.getElementById("ctl00_ContentPlaceHolder1_backBtnBtm").style.display = "block";
         }
         
         //display the currentpage.          
         mydiv = document.getElementById("page" + _currentPage);
         mydiv.style.display = "block"; 
         //set the left nav buffon to currentpage.
         leftnavdiv = document.getElementById("leftnav"+_currentPage);
         leftnavdiv.className = "currentPage";    
}

//function to display the currentpage when page loads up.
function onPageLoad()
{ 
    if (Request.QueryString("pageid").Count > 0) {
        _currentPage = parseInt(Request.QueryString("pageid").Item(1));
    }
    else {
        var hf_currentpageno = document.getElementById("ctl00_ContentPlaceHolder1_hf_currentpageno");
        _currentPage = parseInt(hf_currentpageno.value);
    }
    
    //get the total page number from hidden field
    var hf_pageno = document.getElementById("ctl00_ContentPlaceHolder1_hf_totalpageno");
    var _totalpageno = hf_pageno.value;
         
    /*
    if the current page is the last page, hide the next button
    TO directly output the action plan to word doc instead of showing action plan on a page, use the blow code to replace __doPostBack('','') method.
    window.open('http://'+location.host+'/outputActionPlan.aspx?LID='+lessonID+'&ClientID='+clientID,'NewWindow','width=400,height=200,toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no');
    */     
    if ( _currentPage == _totalpageno ) {
               nextdiv = document.getElementById("ctl00_ContentPlaceHolder1_nextBtn");
               nextdiv.style.display = "none"; 
               nextbtmdiv = document.getElementById("ctl00_ContentPlaceHolder1_nextBtnBtm");
               nextbtmdiv.style.display = "none";
         }
         //if the current page is not the last page, show the next button      
         else {
               nextdiv = document.getElementById("ctl00_ContentPlaceHolder1_nextBtn");
               nextdiv.style.display = "block";
               nextbtmdiv = document.getElementById("ctl00_ContentPlaceHolder1_nextBtnBtm");
               nextbtmdiv.style.display = "block"; 
    }
    
    display(_currentPage, _totalpageno);
}

//set up the page number on the top right cornor. 
//e.g page 1 of 14.  ( 1 is the currentage, 14 is the totalpage number)             
function changePageNumbering(_currentPage, _totalpageno)
{
    var pagenoLit = document.getElementById("pageNo");
    pagenoLit.innerHTML = "page " + _currentPage + " of " + _totalpageno; 
}
                
//changePage function
//when the next/back buffon is clicked or one of the left navigation buttons is clicked,
//this function is called.  It displays/hides the buttons and pages.
function changePage(eventTarget, eventArgument) {
         //Used by resetting the reconnect count to restart the reconnect process.
         //May interfere with other functions, makre sure no other var called count.
         if (count != 0) count=0;
         
         var hf_currentpageno = document.getElementById("ctl00_ContentPlaceHolder1_hf_currentpageno");
         _currentPage = parseInt(hf_currentpageno.value);
         //Display a message "answer is being saved"
         var saveStatus = document.getElementById("saveStatus");
         saveStatus.innerHTML = "Saving Answers, Wating for response...";
           
         //triggring a asyncronous post that and the data back to server and save the answers to the database
         asyncPostBack(_currentPage);
         
         //Display a message "answer saved"
         //saveStatus.innerHTML = "Answers Saved";
         
         //get the total page number from hidden field
         var hf_pageno = document.getElementById("ctl00_ContentPlaceHolder1_hf_totalpageno");
         var _totalpageno = hf_pageno.value;
         
         //get the current page div tag and set its style to none to hide it          
         mydiv = document.getElementById("page"+_currentPage);
         mydiv.style.display = "none";
         //change the left nav button's style to "page" as user is leaving the page.
         leftnavdiv = document.getElementById("leftnav"+_currentPage);
         leftnavdiv.className = "page";
         
         //if the next button from top or bottom is click, set next page number to be the currernt page number
         if (eventTarget.id == 'ctl00_ContentPlaceHolder1_Next' || eventTarget.id == 'ctl00_ContentPlaceHolder1_NextBottom') {
                   _currentPage += 1;
         }
         //if the back button from top or bottom is click, set next page number to be the currernt page number
         else if (eventTarget.id == 'ctl00_ContentPlaceHolder1_Back' || eventTarget.id == 'ctl00_ContentPlaceHolder1_BackBottom') {
                   _currentPage -= 1;
         }
         //none of the buttons is clicked, so the left nav button must be clicked. set the currentpage number.
         else {
                   _currentPage = eventArgument;
         }
         hf_currentpageno.value = _currentPage;
        
         //change the page number display.
         changePageNumbering(_currentPage, _totalpageno);
         
         /*
        if the current page is the last page, hide the next button
        TO directly output the action plan to word doc instead of showing action plan on a page, use the blow code to replace __doPostBack('','') method.
        window.open('http://'+location.host+'/outputActionPlan.aspx?LID='+lessonID+'&ClientID='+clientID,'NewWindow','width=400,height=200,toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no');
        */     
        if ( _currentPage == _totalpageno ) {
               nextdiv = document.getElementById("ctl00_ContentPlaceHolder1_nextBtn");
               nextdiv.style.display = "none"; 
               nextbtmdiv = document.getElementById("ctl00_ContentPlaceHolder1_nextBtnBtm");
               nextbtmdiv.style.display = "none";
               __doPostBack('','actionplan');
         }
         //if the current page is not the last page, show the next button      
         else {
               nextdiv = document.getElementById("ctl00_ContentPlaceHolder1_nextBtn");
               nextdiv.style.display = "block";
               nextbtmdiv = document.getElementById("ctl00_ContentPlaceHolder1_nextBtnBtm");
               nextbtmdiv.style.display = "block"; 
         }
         
         display(_currentPage, _totalpageno);
}

//functions used for xmlhttprequest postback
                
//trim the string, remove all white space chars.
function trim(str) {
    return str.replace(/^\s+|\s+$/g,"");
}
            
//Create xmlDocument and load the string in
//return error message if fails to create
function createXMLFromString (string) {
    var xmlDocument;
    try {
                xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
                xmlDocument.async = false;
                xmlDocument.loadXML(string);
                return xmlDocument;
    }
    catch (e) {
                output("Can't create XML document.");
                return null;
    }
}
            
// a utility function that returns true if a string contains only
// whitespace characters
function isblank(s)
{
    for (var i=0; i < s.length; i++)
    {
                    var c = s.charAt(i);
                    if ((c!=' ') && (c!='\n') && (c!= '')) return false;
    }
    return true;
}

//when user is going to the next or previous page. the asyncPostBack function is called to
//send the date to server and save it without triggering a full post back.
function asyncPostBack(_currentPage)
{
     //create a xmlhttpobj
     var xmlHttpObj;
	 if (window.ActiveXObject)
	 {
	     try
	     {
	        xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
	     }
	     catch (e)
	     {
	        xmlHttpObj = new ActiveXObject("Msxm12.XMLHTTP");
	     }
	 }
	 else
	 {
	     xmlHttpObj = new XMLHttpRequest();
	 }

     if ( !xmlHttpObj ) return false; //Usually alert something

     xmlHttpObj.open('POST', "../PSL/XML/getAjax.aspx", true);
                   
     var s = "moduleid=" + lessonID;
     var loop1;
     
//                                      
//                    for (loop1 = 0; loop1 < formdata.length; loop1++)
//                    {
//                        var e = formdata.elements[loop1];

//                        //Question input name always begin with 'a'
//                        //NOTE: running inside master page means controls have 'ctl00_ContentPlaceHolder1_a' added to them
//                        if (e.name.charAt(0) == "a")
//                        {
//                            var respId;
//                            respId = e.name.substring(1);

//                            if ( e.type == "checkbox" )
//                            {
//                                if ( e.checked == true )
//                                {
//                                      s += "&responsea" + respId + "=" + e.value;
//                                }
//                            }
//                            
//                            if ( e.type == "textarea" || e.type == "text" )
//                            {
//                                if ( e.value != ""  && e.value != null && !isblank(e.value) )
//                                {
//                                      s += "&responsea" + respId + "=" + e.value;
//                                }
//                            }
//                        }
//                    }
                    
     //only sending the div tag was targeted.
     //above commented out code was for sending whole page.(all the Qs and As) 
     
     //target the div tag of current page.
     var div = document.getElementById('page'+_currentPage);
     s += "&pageno=" + _currentPage;
     //traget all elements inside the div tag
     var elms = div.getElementsByTagName("*");
     
     //loop through all the elements inside the div tag of current page
     for(var i = 0, maxI = elms.length; i < maxI; ++i) {
        
        var elm = elms[i];
        
        //check whether the element has a form element type
        //"text" "textarea" "hidden" "radio" "checkbox" "select-one" "select-multiple":
        switch(elm.type) 
        {
              case "text":
              case "textarea":
              case "hidden":
              case "radio":
              case "checkbox":
              case "select-one":
              case "select-multiple":
              if (elm.name.charAt(0) == "a")
              {
                  var respId;
                  respId = elm.name.substring(1);
                  
                  //write response in checkbox to the string
                  if ( elm.type == "checkbox" )
                  {
                        if ( elm.checked == true )
                        {
                             s += "&responsea" + respId + "=" + elm.value;
                        }
                  }
                  
                  //write response in textarea to the string.      
                  if ( elm.type == "textarea" || elm.type == "text" )
                   {
                       if ( elm.value != ""  && elm.value != null && !isblank(elm.value) )
                       {
                            s += "&responsea" + respId + "=" + elm.value;
                       }
                   }
                   
                   //write response in radio button to the string.      
                  if ( elm.type == "radio" )
                   {
                       if ( elm.checked == true )
                       {
                            s += "&responsea" + respId + "=" + elm.value;
                       }
                   }
              }
          }
      }
                    
      //xmlHttpObj.setRequestHeader("Content-Type", "text/xml")
      xmlHttpObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    
      xmlHttpObj.onreadystatechange = function()
      {
           //Checks the state of the object if any action should be taken
           if ( xmlHttpObj.readyState == 4 ) //4 equals to complete
           {
               if ( xmlHttpObj.responseText == "1" )
               {
                 var saveStatus = document.getElementById("saveStatus");
                 saveStatus.innerHTML = "Answers Saved";
               }
               else
               {
                 var saveStatus = document.getElementById("saveStatus");
                 saveStatus.innerHTML = "Answers were NOT saved, bad request.";
               }
           }
      }

       //Send the string data.                
       xmlHttpObj.send(s);
}
