var g_arr_commands;
var g_cur_cmd_idx = 0;
var g_cmd_count = 0;
var g_xhr = false;
var g_rawText = "";
var g_Form = false;
var g_URL = "";
var g_Method = "POST";
var g_quit_on_failure = true;
var g_error = false;  //set to true if any command fails  

/**
  * Call this to start the process
  *     Function initGlobals needs to be called first
  *
  * @param cmds Comma delimited list of commands to call in order
  * @param recall Boolean Set to false when calling for the first time
  *
  * @see initGlobals
  */
function sendCommands(cmds, recall)
{
    //if we are calling for the first time
    if( recall == false)
    {
        disable_controls();
        g_arr_commands = cmds.split(",");
        g_cur_cmd_idx = 0;
        g_cmd_count = g_arr_commands.length;
    }else{
        g_cur_cmd_idx = g_cur_cmd_idx + 1;
    }
    
    //if we have sent all commands 
    if(g_cur_cmd_idx == g_cmd_count) 
    {
        enable_controls();
        return true;
    }
    
    //form required to have a hidden element action
    //  <input id="action" type="hidden" name="action" value=""/>
    var elAction = document.getElementById('xhr_action_cmd');
    elAction.value = trimWhitespace(g_arr_commands[g_cur_cmd_idx]);
    
    //create request, initialize and call
    g_xhr = new scks_XHR();             //initialize class
    g_xhr.setForm(g_Form);              //required for getting form values
    g_xhr.setURL(g_URL);                //url of server script to call
    g_xhr.setCallback(xhrCallback);     //handles the xhr return
    g_xhr.setMethod(g_Method);          //POST or GET
    g_xhr.sendRequest();                //send the request

}

/**
  * Need to initialize globals seperately as they
  * will be used for all calls.
  *  Required to be called before sendCommands is
  *     called the first time
  * Form required to have results area
  *    <div id="results"></div>
  *
  * @param frm Form object
  * @param url Server script to call
  * @param method POST or GET
  * @param qfail true: stops calling commands if one fails; false: continues list of commands even if one fails
  *
  * @see sendCommands
  */
function initGlobals(frm, url, method, qfail, results_id)
{                 
    g_Form = frm;
    g_URL = url;
    g_Method = method;
    g_quit_on_failure = qfail;
    //form required to have results area
    //  <div id="results"></div>
    //clear it for new call
    var results = document.getElementById(results_id);
    if( results )
    {
        results.innerHTML = "&nbsp;";
    }
}

/**
  * Put your information handling code here
  *  I use double bars to delinate the return
  *  value. It's as easy as spitting the return into
  *  an array and processing from there.
  *  
  * Example Return System:
  *  The first two values returned need to be the action and result code
  *     Example: action||0
  *  Result code "0" is success
  *  Result code !="0" indicates failure and failure string should be the third value
  *     Example: action||1||error_string
  *  After that it's up to you what you return 
  *
  * This function can be edited to process the return anyway you want
  */
function xhrCallback()
{
    var arr_ret;
    var results = document.getElementById('results');
    var req = g_xhr.XHR();
    //var outputText = results.innerHTML;
    var outputText = ""; 
    if (req.readyState == 4) 
    { 
        if(req.status == 200)
        {
            //store raw return so it can be accessed if needed
            g_rawText = req.responseText;
            
            /**************************************************************/
            /* START: Edit in here to handle response from server         */
            /**************************************************************/
            
            //explode the response string into an array
            arr_ret = req.responseText.split("||"); 
            
            //grab the action 
            var action = trimWhitespace(arr_ret[0]);
            
            //store success/error value
            var error = arr_ret[1];
            
            //if something other than 0 is returned then it is an error
            if(error != "0")
            {
                
                if( action != 'validate_user_email' || action != 'validate_user_email' )
                {
                    //handle error here
                    g_error = true;
                    //var outputText += "<span class='error'>" + arr_ret[2] + "</span>";
                    if( results )
                    {
                        results.innerHTML = outputText;
                    }
                    if(g_quit_on_failure)
                    {
                        //make sure we enable the controls here
                        //since no further processing is done
                        enable_controls();
                        return false;
                    }else{
                        sendCommands("",true);
                        return true;
                    }
                }
            }    
            //otherwise we had a successful call
            outputText += "<span class='success'>"; 
            //process return based on action sent in
            switch(action)
            {
                case 'validate_user_name':
                {
                    var el_results = document.getElementById('user_name_results');
                    var el_img = document.getElementById('user_name_img');  
                    el_results.innerHTML = arr_ret[3]
                    el_img.src = arr_ret[2];
                    break;
                }
                case 'validate_user_email':
                {
                    var el_results = document.getElementById('user_email_results');
                    var el_img = document.getElementById('user_email_img');  
                    el_results.innerHTML = arr_ret[3]
                    el_img.src = arr_ret[2];
                    break;
                }
                case 'validate_account_domain':
                {
                    //validate_account_domain||0||[img.src]||[result.string]||[user.name]||[lock_passwords]||[lock_passwords_message]
                    var el_results = document.getElementById('account_domain_results');
                    var el_img = document.getElementById('account_domain_img');
                    var el_account_name = document.getElementById('account_system_user');
                    var el_password = document.getElementById('account_system_password'); 
                    var el_password_verify = document.getElementById('account_system_password_verify'); 
                    el_results.innerHTML = arr_ret[3];
                    el_img.src = arr_ret[2];
                    if( arr_ret[4] != "unused" )
                    {
                        el_account_name.value = arr_ret[4];
                    } else {
                        el_account_name.value = ""; 
                    }
                    if( arr_ret[5] == "1" )
                    {
                        el_password.disabled = true;
                        el_password_verify.disabled = true;
                        if( el_account_name.value.length != 0 )
                        {
                            el_password_verify.value = "existing_account"; 
                            el_password.value = "existing_account";
                        } else {
                            el_password_verify.value = ""; 
                            el_password.value = "";
                        }   
                    } else if( arr_ret[5] == "0" ) {
                        el_password.disabled = false;
                        el_password_verify.disabled = false;
                    }
                    break;
                }   
                //case 'action':...
                default:
                {
                    g_error = true;
                    outputText = "Unrecognized Action: " + action;
                    if(g_quit_on_failure)
                    {
                        //make sure we enable the controls here
                        //since no further processing is done
                        enable_controls();
                        return false;
                    }else{
                        sendCommands("",true);
                        return true;
                    }
                    return false;
                    
                }
                
            } 

            if( results )
            {
                results.innerHTML = outputText + '</span>'; 
            }
            
            /**************************************************************/
            /* END: Edit in here to handle response from server           */
            /**************************************************************/
            
            //Recall function to send the next command
            //  sendCommands will evaluate whether it needs 
            //  to create another request or exit
            sendCommands("",true); 
        }else{
            //status.innerHTML = gXMLhttp.status;
            //progress_bar.src = pic_progress_static.src; 
        }
        
        
         
    }

}

/**
  * Code to disable any controls the user should not
  *  be able to use during the request
  */
function disable_controls()
{
    /*var obj = document.getElementById('lstGroups');
    obj.disabled = true;
    
    obj = document.getElementById('img_delete_group');
    gDeleteImage = obj.src;
    obj.src = 'images/garbage_disabled.gif';
    obj = document.getElementById('lnk_delete_group');
    obj.disabled = true;*/
    
}

/**
  * Code to enable any controls disabled
  *  when the request was started
  */
function enable_controls()
{
    /*var obj = document.getElementById('lstGroups');
    obj.disabled = false;
    
    obj = document.getElementById('img_delete_group');
    obj.src = gDeleteImage;
    obj = document.getElementById('lnk_delete_group');
    obj.disabled = false;*/
    
    
} 


// Remove leading and trailing whitespace from a string
function trimWhitespace(string) {
   var newString  = '';
   var substring  = '';
   beginningFound = false;
   
   // copy characters over to a new string
   // retain whitespace characters if they are between other characters
   for (var i = 0; i < string.length; i++) {
      
      // copy non-whitespace characters
      if (string.charAt(i) != ' ' && string.charAt(i) != '\n' && string.charCodeAt(i) != 9) {
         
         // if the temporary string contains some whitespace characters, copy them first
         if (substring != '') {
            newString += substring;
            substring = '';
         }
         newString += string.charAt(i);
         if (beginningFound == false) beginningFound = true;
      }
      
      // hold whitespace characters in a temporary string if they follow a non-whitespace character
      else if (beginningFound == true) substring += string.charAt(i);
   }
   return newString;
}

