/*****************************************************************************************************************************************************
    truAjax(theFormName, CFCPath, cfcMethod, idOfElementToPostInfoTo [, idList]) - Runs an ajax request
    @theFormName = name of the form that info is being submitted from, usually "this.form.name"; used to ensure that cf validation runs before ajax script
    @cfcPath = path to the cfc from calling page, extension optional, defaulted to ".cfc" (Ex: home.cfm points to "home.cfm" in same directory; Ex: cfcs/news points to "news.cfc" in the "cfcs" directory)
    @cfcMethod = method to call inside of cfc; leave blank if using ".cfm" file
    @idOfElementToPostInfoTo = id of the element to post data back to; '' if no postback is needed
    @[idList] = comma delimited list of element IDs or parameter/variable pair to extract data from; all values sent to page specified in CFCPath; Ex: "userID,userName" or "'userID=7',password,'userName=Jack'"
    
    NOTES
    :: debugging must be disabled in ajax accessed file
    :: cfc access attribute must be "remote"
    :: browser must have javascript enabled
******************************************************************************************************************************************************/
function truAjax(theFormName, cfcPath, cfcMethod, idOfElementToPostInfoTo){
    try{
        gebid('LoadingZone').style.display='none'; // clear loading box
        gebid('LoadingZone').style.visibility='hidden';
    } catch(err){
        var truAjaxLoadingZone = document.createElement("div"); // create a loading div
        truAjaxLoadingZone.id = "LoadingZone";
        truAjaxLoadingZone.style.backgroundColor = "red";
        truAjaxLoadingZone.style.position = "fixed";
        truAjaxLoadingZone.style.zIndex = 10000;
        truAjaxLoadingZone.style.padding = '2px';
        truAjaxLoadingZone.style.right = '2px';
        truAjaxLoadingZone.style.top = '2px';
		truAjaxLoadingZone.style.textDecoration = 'blink';
        truAjaxLoadingZone.style.color = "white";
        truAjaxLoadingZone.style.fontWeight = "bold";
        document.body.appendChild(truAjaxLoadingZone);
        ih('LoadingZone','Loading...');
        te('LoadingZone');
    } // end catch
    
    var truMsg = "";
    var cfcPath = cfcPath.toString();
    
    if(theFormName.length) // if form name was passed in
            if(eval('_CF_check'+ theFormName + '(' + theFormName + ')')==false) return false; // run cf validation
        
    if(arguments.length < 4){ // if not all required parameters are present
        alert(truMsg + 'CFC path, method, and postback element required');
        return false;
    } // end if
    
    var http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) http_request.overrideMimeType('text/xml');
    } // end mozilla
    else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {alert(truMsg + 'Caught Exception: ' + e.description);}
        } // end try
    } // end IE

    if (!http_request) { // if the request failed to initialize
        alert(truMsg + 'Cannot create an XMLHTTP instance.\nTry using Internet Explorer or Firefox'); // throw an error
        return false;
    } // end if
    
    if(idOfElementToPostInfoTo.length > 0){ // if there is an element to post back to
        try{
            var divToReturnTo = document.getElementById(idOfElementToPostInfoTo).value;
        } catch (e) {alert(truMsg + 'Element "' + idOfElementToPostInfoTo + '" does not exist!'); return false;}
    } // end if
    

    http_request.onreadystatechange = function() { // eventListner
        if(http_request.readyState < 4) { // request is processing
            gebid('LoadingZone').style.display='';  // show loading div
            gebid('LoadingZone').style.visibility='visible';
        } // end if
        else if(http_request.readyState == 4) { // the data transfer has been completed
            gebid('LoadingZone').style.display='none'; // clear loading box
            gebid('LoadingZone').style.visibility='hidden';
            
            if (http_request.status == 200){ // request completed successfully
                
                var hrt = http_request.responseText; // source code of ajax retrieved page

                if(idOfElementToPostInfoTo.length > 0) // if there is an element to post back to
                    ih(idOfElementToPostInfoTo, hrt); // fill the element with response text
                
                for(var scriptCount = 0; scriptCount < hrt.length; scriptCount++){ // loop thru the response text in search of script tags
                    var startHere = hrt.indexOf('<' + 'script', scriptCount); // character position of the beginning of the script
                    var stopHere = hrt.indexOf('</' + 'script' + '>', startHere); // character position of the end of the script
                    
                    scriptCount = startHere; // set scriptCount to the position of ending script tag
                    
                    if(startHere >= 0) // use of javascript is present
                        eval(hrt.substring(startHere + hrt.substring(startHere, stopHere).indexOf('>') + 1, stopHere)); // process any javascript
                    else
                        break;
                } // end for
                
            } // end if
            else
                ih(idOfElementToPostInfoTo, http_request.responseText); // show error
        } // end else if
    } // end function()
    
    var formfieldIDs = ''; // default formfieldIDs to the method thats being called
    for(var i = 4; i < arguments.length; i++){ // loop thru submited arguments starting AFTER mandatory parameters
        if(typeof(arguments[i]) == 'object'){ // if argument is a object
            if(arguments[i].type == undefined){ // if argument is a radio button or a check box try this
                var radioCheckBoxArray = arguments[i]; // set variable to NodeList object type
                var selectedItemlist = ''; // create var for holding a list of selected items in a check box or radio button
                
                for(var j=0; j < radioCheckBoxArray.length; j++){ // loop thru radio/check array
                    if(radioCheckBoxArray[j].checked == true){ // if its checked
                        selectedItemlist += ',' + radioCheckBoxArray[j].value; // set selectedItemList to all values from radioCheckBoxArray (comma delimited)
                    } // end if
                } // end for
                if(selectedItemlist != ''){ // if selectedItemlist is not blank
                    var theObject = arguments[i]; // create a variable to hold the object
                    formfieldIDs += '&' + theObject[0].name + '=' + selectedItemlist.substring(1,selectedItemlist.length); // append name/value to formfieldIDs
                } // end if
            } // end if
            else{
                if(arguments[i].type.substring(0,6) == 'select'){ // check if object is a select box
                    var selectBoxArray = arguments[i]; // set variable to NodeList object type
                    var selectedItemlist=''; // create var for holding a list of selected items in a check box or radio button
                    
                    for(var j=0; j < selectBoxArray.length; j++){ // loop thru radio/check array
                        if(selectBoxArray[j].selected == true){ // if its checked
                            selectedItemlist += ',' + selectBoxArray[j].value; // set radioPosition to the loop count
                        } // end for
                    } // end for
                    
                    if(selectedItemlist != ''){ // if selectedItemlist is not blank
                        formfieldIDs += '&' + arguments[i].name + '=' + selectedItemlist.substring(1,selectedItemlist.length); // append name/value to formfieldIDs
                    } // end if
                } // end if
                else // if object is not a radio/check/select
                    formfieldIDs += '&' + arguments[i].name + '=' + arguments[i].value; // append name/value to formfieldIDs
            }// end else
        } // end if
        else if(typeof(arguments[i]) == 'string'){ // if argument is a string
            if(arguments[i].indexOf('=') == -1){ // if the variable pair is not valid, containing "=" (Ex: userID=7)
                alert(truMsg + '1) Element "' + arguments[i] + '" does not exist! Check your spelling and ensure that the field name exists.\nOR\n2)Invalid variable pair! (Ex: "userID=7")');
                return false; // exit function
            } // end if
            else
                formfieldIDs += '&' + arguments[i]; // append name/value to formfieldIDs
        } // end else if
    } // end for

    if(cfcPath.indexOf('.cf') == -1) // no ".cfc" or ".cfm" specified in path
        cfcPath = cfcPath + '.cfc'; // append ".cfc"

    http_request.open('POST', cfcPath + '?method=' + cfcMethod, true); // open new request; invoke cfc thru url
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // multipart/form-data or application/x-www-form-urlencoded
    http_request.setRequestHeader("Content-length", formfieldIDs.length); // notify request of length
    http_request.setRequestHeader("Connection", "close"); // close connection
    http_request.send(formfieldIDs); // send parameter(s)
} // end truAjax


/************************************
    trim(string) - Trims a String
    @theElement = element ID
    @elementBody = data to put in element
************************************/
function trim(s){
       while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r')) // remove leading spaces and carriage returns
        s = s.substring(1,s.length);
       
     while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r')) // Remove trailing spaces and carriage returns
         s = s.substring(0,s.length-1);
     
       return s;
} // end trim
 
 
/************************************
    ih(theElement,elementBody) - Fills an element with information
    @theElement = element ID
    @elementBody = data to put in element
************************************/
function ih(theElement,elementBody){
    document.getElementById(theElement).innerHTML = elementBody; // fill element with specified content
} // end ih()


/************************************
    cv(theElement,elementValue) - Changes an elements value
    @theElement = element ID
    @elementValue = data to put in element
************************************/
function cv(theElement,elementValue){
    document.getElementById(theElement).value = elementValue; // fill element with specified content
} // end cv()


/************************************
    de(theElement) - Disables an element
    @theElement = element ID
************************************/
function de(theElement){
    document.getElementById(theElement).disabled = true; // disable the element
} // end de()


/************************************
    te(elementIDList) - Toggles visibility of an element
    @elementIDList[-h/-hide,-s/-show] = list of element ID's [-hide,show] - force hide/show
************************************/
function te(elementIDList){
    toggleList = elementIDList.split(','); // get id's to loop thru
    for(var tgl = 0; tgl < toggleList.length; tgl++){
		
		var toggleListElement = toggleList[tgl]; // set the element in the list to toggleListElement
		var hideOrShow = ""; // default hideOrShow
				
		if(toggleListElement.split('-').length > 1){ // if there is a "-hide" or "-show" parameter with the id
			toggleListElement = toggleListElement.split('-'); // set the id name to toggleListElement
			hideOrShow = toggleListElement[1]; // set hideOrShow to [h,s] or [hide,show]
			toggleListElement = toggleListElement[0]; // set toggleListElement to the id
		} // end if

		elementToToggle = document.getElementById(toggleListElement).style; // set elementToToggle
		if( (hideOrShow == 's' || hideOrShow == 'show') || ((elementToToggle.display == 'none' || elementToToggle.visibility == 'hidden') && hideOrShow == '') ){
			elementToToggle.visibility = 'visible'; // show the element
			elementToToggle.display = ''; // show the element
		} // end if
		else if( (hideOrShow == 'h' || hideOrShow == 'hide') || ((elementToToggle.display != 'none' || elementToToggle.visibility == 'visible') && hideOrShow == '') ){
			elementToToggle.visibility = 'hidden'; // hide the element
			elementToToggle.display = 'none'; // hide the element **does not work in safari**
		} // end else

	} // end for
} // end toggle()




/************************************
    gebid(theElement) - Get the object type by id
    @theElement = element ID
************************************/
function gebid(theElement){
    return document.getElementById(theElement);
}


/************************************
    gebn(theElement) - Get the object type by name
    @theElement = element ID
************************************/
function gebn(theElement){
    return document.getElementsByName(theElement);
}


/************************************
    refresh(seconds) - Refreshes the page in specified amount of seconds
    @[seconds] = number of seconds to wait before refreshing
************************************/
function refresh(seconds){
    if(seconds == undefined) seconds = 0; // if no value is specified, refresh immediately
    setTimeout("window.location=location;",seconds*1000);
}

