/*         File: libquery.js           */
/*         Date: 10/11/2009            */
/*       Author: Stef                  */
/*  Description: JS functions used     */
/*               by the Questionnaire  */
/*                                     */
/*  Rewritten:03/02/2010               */
/*            Too unweildy to maintain */
/*            rewrote to rely          */
/*            on the callback AJAX fun */
/*                                     */
/*  Modification:16/02/2010            */
/*            Added nl_signup function */
/*            for the homepage email   */
/*            gathering box            */
/*                                     */
/*  Modification:18/02/2010            */
/*            Added getTracking()      */
/*            for the download         */
/*            tracking interface       */
/*            and tidied up the code   */
/*                                     */
/*  Modification:02/03/2010            */
/*            Added getBackup()        */
/*            Added getStatistics()    */
/*            Fixed function highlight */
/*            with setSelect(dom_elmt) */
/*                                     */
/*  Modification:12/03/2010            */
/*            Added getTrackingDlds()  */
/*                                     */
/*  Modification:08/04/2010            */
/*            Added submit_form(...)   */
/*                                     */   

/*-----------------------------------------------------------------------------/
|                                                                              |
|  MODULE: AJAXLIB                                                             |
|                                                                              |
|  DESCRIPTION: Contains the code used to asynchronously interact with         |
|               the implemented PHP functions                                  |
|                                                                              |
/-----------------------------------------------------------------------------*/
//--Function getAJAXObjectCallback
//
//This function calls the PHP function 'urlpart' with the supplied
//'arguments' in HTTP GET format.  When the server returns a response
//it passes the returned data to the function passed as 'callback'
//-----------------------------------------------------------------
function getAJAXObjectCallback(urlpart, arguments, callback) { //callback, data, ref, pass) {
  var req;

  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  }
  else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    alert("This shouldn't happen, get Stef to see what's wrong (No XMLHttpRequest object)");
  }
  
  req.onreadystatechange = function() {
    if(req.readyState == 4) {
      callback(req.responseText);
    }
  }
  req.open("GET","/forms/functions/"+urlpart+"?"+arguments+"&randNum="+new Date().getTime(),true);
  req.send(null);
}
//--Functions getRecord / getRecordtoFile
//
//This function calls the function getRecord.php to retrieve the
//record specified by 'ref' from the table 'query'.  It displays
//the returned HTML in the DIV element with id: 'record'
//
//  --External dependencies:
//    
//    Relied upon by /forms/viewer.php
//    Relied upon by /forms/questionnaire/layout *
//
//  --Note: Two functions here for backwards compatibility, To-Do
//
//-----------------------------------------------------------------
//Display The Requested Questionnaire In The record DIV (Used by viewer.php)
function getRecord(query, ref, password) {
  getAJAXObjectCallback('getRecord.php',
                        'q='+query+"&p="+password+"&e="+ref,
                        function(data) {
                          document.getElementById('record').innerHTML = data;
                        });
}
function getRecordtoFile(query, ref, password) {  
  getAJAXObjectCallback('getRecord.php',
                        'q='+query+"&p="+password+"&e="+ref,
                        function(data) {
                          document.getElementById('file').innerHTML = data;
                        });
}
//--Function dlRecord
//
//This function calls the function dlRecord.php to retrieve the
//record specified by 'ref' from the table 'query'.  It sets the
//window location to the php URL
//
//  --External dependencies:
//
//    Relied upon by /forms/questionnaire/layout *
//
//-----------------------------------------------------------------
function dlRecord(query, ref) {
  if (globalPassword == "") {
    alert("You are not logged in");
  } else {
    window.location = "/forms/functions/dlRecord.php?q=" + query + "&p=" + globalPassword + "&e=" + ref; 
  }  
}

//--Function setLoading
//
//Set the contents of the specified dom_element to the loading bar
//if isname = 1 then dom_element is the element id as a string
//----------------------------------------------------------------
function setLoading(dom_element, isname) { 
  var dom_obj = dom_element;
  if(isname == 1) { dom_obj=document.getElementById(dom_element); }
  dom_obj.innerHTML = "<div style=\"width:100%;text-align:center;\"><br /><br /><br />Loading...<br /><br /><img src=\"/img/ajaxload.GIF\" /><br /><br /><br /></div>";
}
//--Functions setSelected / setUnselected / setSelect / setDeselect
//
//Set the specified function to active, all these really do atm
//is change the background color of the tabs 
//----------------------------------------------------------------
function setSelected(dom_element) { 
  dom_obj=document.getElementById(dom_element);
  dom_obj.setAttribute("class", "selected");
  dom_obj.setAttribute("className", "selected");
}
function setUnSelected(dom_element) { 
  dom_obj=document.getElementById(dom_element);
  dom_obj.setAttribute("class", "");
  dom_obj.setAttribute("className", "");
}
function setSelect(dom_element) {
  setDeSelect(); 
  setSelected(dom_element);
}
function setDeSelect() { 
  setUnSelected('navfs');
  setUnSelected('navqs');
  setUnSelected('navtk');
  setUnSelected('navbk');
  setUnSelected('navst');
}

//--Function managerLogin
//
//Called on login attempt - Calls the function login.php, and then 
//evaluates the returned javascript, updating the password value at
//the same time
//-----------------------------------------------------------------
function managerLogin(dom_element, password) {
  globalPassword = password;
  document.password_form.azrights_password.disabled = true;
  getAJAXObjectCallback("login.php",
                        "p="+password, 
                        function(data) {
                          eval(data);
                        });
}
//--Function nl_register
//
//Executes an AJAX newsletter registration, replacing the passed
//dom element contents with the response from the server
//Although this is called nl_register, and calls a function referred to
//as newsletter-registration, the actual purpose is to send the
//user an email with links to the E-Book downloads
//-----------------------------------------------------------------
function nl_register(name, email, referrer, dom_id) {
  var dom_element = document.getElementById(dom_id);
  setLoading(dom_element, 0);
  getAJAXObjectCallback('newsletter-registration.php', 
                        'name='+name+'&email='+email+'&referrer='+referrer,
                        function(data) {
                          dom_element.innerHTML = data;
                        });
}
//--Function nl_signup
//
//The real newsletter registration function
//sends the submitted name and email address into the
//database
//-----------------------------------------------------------------
function nl_signup(name, email, dom_id) {
  var dom_element = document.getElementById(dom_id);
  setLoading(dom_element, 0);
  getAJAXObjectCallback('email_signup.php',
                        'name='+name+'&email='+email,
                        function(data) {
                          dom_element.innerHTML = data;
                        });
}
/*-----------------------------------------------------------------------------/
|  END MODULE: AJAXLIB                                                         |
/------------------------------------------------------------------------------/


                                 |||      |||    
                                 | |  __  | |
                  |-|_____-----/   |_|  |_|   \-----_____|-|
                  |_|_________{   }|  (^) |{  }__________|_|  
                   ||          |_| |   ^  | |_|          ||  
                   |              \|  /\  |/              |  
                   |               \ |--| /               |    
                   =               \ |__| /               =    
                   +               \      /               +
                                    \    /    
                                    \    /    
                                     \  /
                                     \  /
                                     \  /
                                     \  /
                                     \  /    
                                     \  /
                                      \/
                                                            


/------------------------------------------------------------------------------/
|                                                                              |
|  MODULE: FREE SEARCH MANAGEMENT                                              | 
|                                                                              |
/-----------------------------------------------------------------------------*/
//--Function getApplications
//
//Checks to see if the user is logged in by consulting globalPassword
//Then calls the PHP function getApplications.php to retrieve a list
//of free search applications. The returned HTML is placed into the
//appcontainer DIV object
//-----------------------------------------------------------------
function getApplications() { 
  if (globalPassword == "") {
    alert("You are not logged in");
  } else {
  closeClientFile();
  getAJAXObjectCallback('getApplications.php', 
                        'p='+globalPassword,
                        function(data) {
                          document.getElementById('appcontainer').innerHTML = data;
                          setSelect('navfs');
                        });
  }
}
//--Functions addNote, addNoteRaw
//
//Add the note passed as a string to the client file specified by id
//addNote is included for backwards compatibility
function addNote(id, password) { addNoteRaw(id, password, document.file_notes_form.file_notes_input.value); }
function addNoteRaw(id, password, note) {
    getAJAXObjectCallback('fileNotes.php'
                        ,'q=add&data='+note+'&e='+id+'&p='+password,
                        function(data) {
                          document.getElementById('file_notes').innerHTML = data;
                        });
}
//--Function changeStatus
//
//Used by the Status dialog box (launched by /js/util.js) to update
//the status of a free search client file. Calls the clientStatus.php
//function with the new StatusID, and then calls the fileNotes.php
//function to update the client notes
//-----------------------------------------------------------------
function changeStatus(dialog, id, status, password, fun)
{
  setLoading(dialog, 0);
  arguments = "data="+status+"&id="+id+"&pass="+password;
  getAJAXObjectCallback("clientStatus.php", arguments, fun);
                                                 
  switch(status) {
    case '0':
      addNoteRaw(id, password, 'Status changed to <span class="status_uns">Unstarted</span>');
      break;
    case '1':
      addNoteRaw(id, password, 'Status changed to <span class="status_ip">In Progress</span>');
      break;
    case '2':
      addNoteRaw(id, password, 'Status changed to <span class="status_cp">Complete</span>');
      break;
    default: break;
  }
}
//--Function getFile
//
//Calls the getRecord.php function to retrieve a free search client
//file, and places the returned HTML into the 'file' div container
//
//The query argument specifies the SQL table to lookup - here it will
//generally be "free_search_file".  The ref is the client ID
//-----------------------------------------------------------------
function getFile(query, ref, password) {
  getAJAXObjectCallback('getRecord.php',
                        'q='+query+"&p="+password+"&e="+ref,
                        function(data) {
                          document.getElementById('file').innerHTML = data;
                        });
}
/*-----------------------------------------------------------------------------/
|  END MODULE: FREE SEARCH MANAGEMENT                                          |
/------------------------------------------------------------------------------/

           _          __________                              _,
       _.-(_)._     ."          ".      .--""--.          _.-{__}-._
     .'________'.   | .--------. |    .'        '.      .:-'`____`'-:.
    [____________] /` |________| `\  /   .'``'.   \    /_.-"`_  _`"-._\
    /  / .\/. \  \|  / / .\/. \ \  ||  .'/.\/.\'.  |  /`   / .\/. \   `\
    |  \__/\__/  |\_/  \__/\__/  \_/|  : |_/\_| ;  |  |    \__/\__/    |
    \            /  \            /   \ '.\    /.' / .-\                >/-.
    /'._  --  _.'\  /'._  --  _.'\   /'. `'--'` .'\/   '._-.__--__.-_.'
  \/_   `""""`   _\/_   `""""`   _\ /_  `-./\.-'  _\'.    `""""""""`'`\
  (__/    '|    \ _)_|           |_)_/            \__)|        '        
    |_____'|_____|   \__________/|;                  `_________'________`;-'
    s'----------'    '----------'   '--------------'`--------------------`
       S T A N          K Y L E        K E N N Y         C A R T M A N


/------------------------------------------------------------------------------/
|                                                                              |
|  MODULE: REGISTRATION / DL TRACKING INTERFACE                                | 
|                                                                              |
/-----------------------------------------------------------------------------*/
//--Function getTracking
//
//Checks to see if the user is logged in by consulting globalPassword
//Then calls the PHP function getTracking.php to load the tracking
//interface for E-Book downloads and registrations. The returned HTML is 
//placed into the appcontainer DIV object
//-----------------------------------------------------------------
function getTracking() { 
  if (globalPassword == "") {
    alert("You are not logged in");
  } else {
  closeClientFile();
  getAJAXObjectCallback('getTracking.php', 
                        'p='+globalPassword,
                        function(data) {
                          document.getElementById('appcontainer').innerHTML = data;
                          setSelect('navtk');
                        });
  }
}
function getTrackingEBOOK() { 
  if (globalPassword == "") {
    alert("You are not logged in");
  } else {
  getAJAXObjectCallback('tracking/layout_tracking_ebook.php', 
                        'p='+globalPassword,
                        function(data) {
                          document.getElementById('appcontainer').innerHTML = data;
                        });
  }
}
function getTrackingDownloads() { 
  if (globalPassword == "") {
    alert("You are not logged in");
  } else {
  getAJAXObjectCallback('tracking/layout_tracking_download.php', 
                        'p='+globalPassword,
                        function(data) {
                          document.getElementById('appcontainer').innerHTML = data;
                        });
  }
}
/*-----------------------------------------------------------------------------/
|  END MODULE: REGISTRATION / DL TRACKING INTERFACE                            |
/-----------------------------------------------------------------------------*/


/*-----------------------------------------------------------------------------/
|                                                                              |
|  MODULE: QUESTIONNAIRE VIEWER                                                | 
|                                                                              |
/-----------------------------------------------------------------------------*/
//--Function getQuestionnaire
//
//Checks to see if the user is logged in by consulting globalPassword
//Then calls the PHP function getQuestionnaire.php to load the viewer
//for submitted questionnaires (e.g. client/presearch). The returned HTML is 
//placed into the appcontainer DIV object
//-----------------------------------------------------------------
function getQuestionnaire() {  //Client Questionnaire
  if (globalPassword == "") {
    alert("You are not logged in");
  } else {
  closeClientFile();
  getAJAXObjectCallback('getQuestionnaire.php', 
                        'p='+globalPassword,
                        function(data) {
                          document.getElementById('appcontainer').innerHTML = data;
                          setSelect('navqs');
                        });
  }
}
function getQuestionnairePreSearch() {  //Pre-Search Questionnaire
  if (globalPassword == "") {
    alert("You are not logged in");
  } else {
  getAJAXObjectCallback('questionnaire/layout_questionnaire_presearch.php', 
                        'p='+globalPassword,
                        function(data) {
                          document.getElementById('appcontainer').innerHTML = data;
                        });
  }
}
function getQuestionnaireDesign() {  //Design Questionnaire
  if (globalPassword == "") {
    alert("You are not logged in");
  } else {
  getAJAXObjectCallback('questionnaire/layout_questionnaire_design.php', 
                        'p='+globalPassword,
                        function(data) {
                          document.getElementById('appcontainer').innerHTML = data;
                        });
  }
}        
/*-----------------------------------------------------------------------------/
|  END MODULE: QUESTIONNAIRE VIEWER                                            |
/-----------------------------------------------------------------------------*/         

/*-----------------------------------------------------------------------------/
|                                                                              |
|  MODULE: BACKUP INTERFACE                                                    | 
|                                                                              |
/-----------------------------------------------------------------------------*/
//--Function getBackup
//
//Checks to see if the user is logged in by consulting globalPassword
//Then calls the PHP function getBackup.php to display the backup
//interface. 
//-----------------------------------------------------------------
function getBackupLayout() {          //PLACEHOLDER FOR BACKUP INTERFACE LAYOUT
  if (globalPassword == "") {
    alert("You are not logged in");
  } else {
  getAJAXObjectCallback('getBackup.php', 
                        'p='+globalPassword,
                        function(data) {
                          document.getElementById('appcontainer').innerHTML = data;
                        });
  }
}
function getBackup() { 
  if (globalPassword == "") {
    alert("You are not logged in");
  } else {window.location = "/forms/functions/backup.php?p=" + globalPassword; }
}
/*-----------------------------------------------------------------------------/
|  END MODULE: BACKUP INTERFACE                                                |
/-----------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------/
|                                                                              |
|  MODULE: STATISTICS INTERFACE                                                | 
|                                                                              |
/-----------------------------------------------------------------------------*/
//--Function getStatistics
//
//Checks to see if the user is logged in by consulting globalPassword
//Then calls the PHP function getStatistics.php to display statistics
//from the Database. 
//-----------------------------------------------------------------
function getStatistics() {          
  if (globalPassword == "") {
    alert("You are not logged in");
  } else {
  closeClientFile();
  getAJAXObjectCallback('getStatistics.php', 
                        'p='+globalPassword,
                        function(data) {
                          document.getElementById('appcontainer').innerHTML = data;
                          setSelect('navst');
                        });
  }
}
/*-----------------------------------------------------------------------------/
|  END MODULE: STATISTICS INTERFACE                                            |
/-----------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------/
|                                                                              |
|  MODULE: EMAIL FORM SUBMISSION                                               | 
|                                                                              |
/-----------------------------------------------------------------------------*/
//--Function formSubmit
//
//Calls the PHP function submitForm.php to track the form submission  
//and send out the email specified by ID.  The function returns some
//HTML, thanking the user, this is placed in the specified dom element. 
//---------------------------------------------------------------------

function form_submit(ref, email, subemail, subname, dom_id) {
  var dom_element = document.getElementById(dom_id);
  setLoading(dom_element, 0);
  getAJAXObjectCallback('submitForm.php', 
                        'ref='+ref+'&email='+email+'&subemail='+subemail+'&subname='+subname,
                        function(data) {
                          dom_element.innerHTML = data;
                        });
}                    
//--DOM Form Functions 
//
//This function grabs the data from the form specified, validates it
//and sends it to the server using the above form_submit(...)
//--------------------------------------------------------------------
function emailformsubmit(theform, dom_id, email, ref) {
        nameval = theform.subname.value;
        emailval = theform.subemail.value;        
        atindex = emailval.indexOf("@");
        subvalue = emailval.substr(atindex + 1);
        dotindex = subvalue.indexOf(".");        
        if (emailval=="") {
            alert("Please Enter Your Email Address");
            return false
        } 
        if (!((dotindex > 0) && (atindex > 0))) {
            alert("Please Enter a Valid Email Address");
            return false        
        } 
        
        if (nameval=="") {
            alert("Please Enter Your Name");
            return false
        }
        form_submit(ref, email, emailval, nameval, dom_id);
}
/*-----------------------------------------------------------------------------/
|  END MODULE: EMAIL FORM SUBMISSION                                           |
/-----------------------------------------------------------------------------*/