var _ms_XMLHttpRequest_ActiveX = ""; // Holds type to instantiate
var _ajax;                           // global XMLHTTPRequest object
var _logger = true;                  // write to the Activity Log
var _status_area;                    // point to the area to write status messages 


function AJAXRequest( method, url, data, process, async, dosend) {

    // self = this; creates a pointer to the current function
    // the pointer will be used to create a "closure". A closure
    // allows a subordinate function to contain an object reference to the
    // calling function. We can't just use "this" because in our anonymous
    // function later, "this" will refer to the object that calls the function 
    // during runtime, not the AJAXRequest function that is declaring the function
    // clear as mud, right?
    // Java this ain't
    
    var self = this;

	
    // check the dom to see if this is IE or not
    if (window.XMLHttpRequest) {
		// Not IE
        self.AJAX = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
		
		// Hello IE!
        // Instantiate the latest MS ActiveX Objects
        if (_ms_XMLHttpRequest_ActiveX) {
            self.AJAX = new ActiveXObject(_ms_XMLHttpRequest_ActiveX);
        } else {
	    
	    // loops through the various versions of XMLHTTP to ensure we're using the latest
	    var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
                        "Microsoft.XMLHTTP"];

            for (var i = 0; i < versions.length ; i++) {
                try {
		    // try to create the object
		    // if it doesn't work, we'll try again
		    // if it does work, we'll save a reference to the proper one to speed up future instantiations
                    self.AJAX = new ActiveXObject(versions[i]);

                    if (self.AJAX) {
                        _ms_XMLHttpRequest_ActiveX = versions[i];
                        break;
                    }
                }
                catch (objException) {
                // trap; try next one
                } ;
            }

            ;
        }
    }
    
    // if no callback process is specified, then pass a default which executes the code returned by the server
    if (typeof process == 'undefined' || process == null) {
        process = executeReturn;
    }

    self.process = process;

    // create an anonymous function to log state changes
    self.AJAX.onreadystatechange = function( ) {
        logger("AJAXRequest Handler: State =  " + self.AJAX.readyState);
        self.process(self.AJAX);
    }

    // if no method specified, then default to POST
    if (!method) {
        method = "POST";
    }

    method = method.toUpperCase();

    if (typeof async == 'undefined' || async == null) {
        async = true;
    }

	
    logger("----------------------------------------------------------------------");
    logger("AJAX Request: " + ((async) ? "Async" : "Sync") + " " + method + ": URL: " + url + ", Data: " + data);

    self.AJAX.open(method, url, async);

    if (method == "POST") {
        self.AJAX.setRequestHeader("Connection", "close");
        self.AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        self.AJAX.setRequestHeader("Method", "POST " + url + "HTTP/1.1");
    }

    // if dosend is true or undefined, send the request
    // only fails is dosend is false
    // you'd do this to set special request headers
    if ( dosend || typeof dosend == 'undefined' ) {
	    if ( !data ) data=""; 
	    self.AJAX.send(data);
    }

    return self.AJAX;
}



// executeReturn
function executeReturn( AJAX ) {
   
   if (AJAX.readyState == 4) {
        
        if (AJAX.status == 200) {
            logger('AJAXRequest is complete: ' + AJAX.readyState + "/" + AJAX.status + "/" + AJAX.statusText);
	    
	    	if ( AJAX.responseText ) {
			    logger(AJAX.responseText);
			    logger("-----------------------------------------------------------");
			    
			    eval(AJAX.responseText);
			    
	    	}
		}
    }
}

// encode text
// 
function encode( uri ) {
    if (encodeURIComponent) {
        return encodeURIComponent(uri);
    }

    if (escape) {
        return escape(uri);
    }
}

// decode text
//
function decode( uri ) {
    uri = uri.replace(/\+/g, ' ');

    if (decodeURIComponent) {
        return decodeURIComponent(uri);
    }

    if (unescape) {
        return unescape(uri);
    }

    return uri;
}

// log information to the status area textfield
function logger( text, clear ) {
    if (_logger) {
        if (!_status_area) {
            _status_area = document.getElementById("status_area");
        }

        if (_status_area) {
            if (clear) {
                _status_area.value = "";
            }

            var old = _status_area.value;
            _status_area.value = text + ((old) ? "\r\n" : "") + old;
        }
    }
}

// base method for calling the get_select servlet
// takes dataset such as customers, cities, states, etc

function getSelectData( site, key, target,context,select_list ) {
    return new AJAXRequest("POST", "/ms/AjaxServlet", "SITE=" + site + "&__SQL_KEY=" + key + "&TARGET=" + target + "&MS_CONTEXT=" + context + "&SELECT_LIST=" + select_list);
//    return new AJAXRequest("POST", "/ms/AjaxServlet", "SITE=" + site + "&key=" + key + "&target=" + target);
}

/*
 * getSelected
 *
 * receive the id to a selected list and returns a string whose values are separated by the passed
 * in delimiter.
 * ------------------------------------------------------------------------------------------------
 * 112505 CHR created
 */
function getSelected(list_id, delimiter)
{

	var select_list = "";
	var current_target = document.getElementById(list_id)
    
    for (var c=0; c < current_target.length; c++) {
    	if (current_target[c].selected) {
    		if (select_list.length == 0) {
    			select_list = current_target[c].value;
    		} else {
    			select_list = select_list + delimiter + current_target[c].value;
    		}
    	}
    }

	return select_list
	
} // end getSelected

/*
 * getOptionList
 *
 * Makes Ajax call to get the javascript to build an option list based on the selecteions made in a second 
 * select list. If currently selected values are passed they will be retained and placed at top of list
 * --------------------------------------------------------------------------------------------------------
 * 112505 CHR created
 */
function getOptionList( site, key, target, context ) {
    
    var key_list = getSelected(key, "','");
    
    var select_list = getSelected(target, "|");
    
    return new AJAXRequest("POST", "/ms/AjaxServlet", "SITE=" + site + "&OPTION_LIST=TRUE&__SQL_KEY=" + key_list + "&TARGET=" + target + "&MS_CONTEXT=" + context + "&SELECT_LIST=" + select_list);
    
    //crtemp return getSelectData( site, key_list, target, context,select_list );
    
} // end getOptionList

/*
 * getCatList
 *
 * Makes Ajax call to get the javascript to build option lists in a CAT_LIST vector. 
 * --------------------------------------------------------------------------------------------------------
 * 071907 LS created
 */
function getCatList( site, option_lists, context ) {
    
    return new AJAXRequest("POST", "/ms/AjaxServlet", "SITE=" + site + "&CAT_LIST=TRUE&OPTION_LISTS=" + option_lists + "&MS_CONTEXT=" + context);
    
} // end getCatList

/*
 * getOptionListWithParams
 *
 * Makes Ajax call to get the javascript to build an option list based on the selections made, with 
 * additional parameters to be placed in the URL.  The result will be built in a second select list. If 
 * currently selected values are passed they will be retained and placed at top of list.
 * --------------------------------------------------------------------------------------------------------
 * 060806 JRN created
 */
function getOptionListWithParams( site, key, target, context, params ) {
    
    var key_list = getSelected(key, "','");
    
    var select_list = getSelected(target, "|");
    
    return new AJAXRequest("POST", "/ms/AjaxServlet", "SITE=" + site + "&OPTION_LIST=TRUE&__SQL_KEY=" + key_list + "&TARGET=" + target + "&MS_CONTEXT=" + context + "&SELECT_LIST=" + select_list + params);
    
} // end getOptionListWithParams

/*
 * getView
 *
 * Makes Ajax call to get the javascript to populate various fields on a page based on the key selected in some
 * manner - most likely select box
 * --------------------------------------------------------------------------------------------------------
 * 112505 CHR created
 */
function getView( site, key, key_value, context ) {
        
    return new AJAXRequest("POST", "/ms/AjaxServlet", "SITE=" + site + "&VIEW=TRUE" + "&" + key + "=" + key_value + "&MS_CONTEXT=" + context);
    
} // end getOptionList

/*
 * clearMessage
 *
 * clear out the message display on page.
 * 
 * --------------------------------------------------------------------------------------------------------
 * 020206 CHR created
 */
function clearMessage() {

	document.getElementById("message_id").innerHTML="";
}

/*
 * getXMap
 *
 * Makes server call to get xml representation of a context map of data requested from server.
 * --------------------------------------------------------------------------------------------------------
 * 013106 C Roskos created
 */
function getXMap( site, key, key_value, ptype, tbody, context ) {

  return new AJAXRequest("POST", "/ms/AjaxServlet", "SITE=" + site + "&XMAP=TRUE" + "&" + key + "=" + key_value + "&PTYPE=" + ptype + "&TBODY=" + tbody + "&MS_CONTEXT=" + context, xMapResults);

} // end getXMap

  
/*
 * xMapResults
 *
 * Recives an xml document that represents a map of data returned from the server. It will take these rows
 * and columns of infomration and build one tr for each record that consists of a tr and td for each 
 * column in the result set. 
 * -----------------------------------------------------------------------------------------------------
 * 020206 CHR created
 */ 
function xMapResults(AJAX) {

	if (AJAX.readyState == 4) {

		if (AJAX.status == 200) {
			logger('AJAXRequest is complete: ' + AJAX.readyState + "/" + AJAX.status + "/" + AJAX.statusText);

			if ( AJAX.responseXML ) {

				var results= AJAX.responseXML; //will need to set some other way?

				var record = null;
				var dataNodes = "";
				var tableRow = null;
				var rowIdx = ""; //cr102406 - in this base model no rowIdx is used but must be passed

				var pType = results.getElementsByTagName("PTYPE")[0].firstChild.nodeValue;
				var tBody = results.getElementsByTagName("TBODY")[0].firstChild.nodeValue;

				var records = results.getElementsByTagName("ROW");

				clearTable(tBody);

				for (var i=0; i < records.length; i++) {

					record = records[i];

					dataNodes = record.getElementsByTagName("COL");

					tableRow = createTableRow(dataNodes, pType, rowIdx);		//cr102406 pass rowIdx	

					document.getElementById(tBody).appendChild(tableRow);

				}

			}
		}
	}

	return; 
	
} // end of xMapResults

/*
 * xMapResultsRowIdx
 *
 * Recives an xml document that represents a map of data returned from the server. It will take these rows
 * and columns of infomration and build one tr for each record that consists of a tr and td for each 
 * column in the result set. 
 * -----------------------------------------------------------------------------------------------------
 * 020206 CHR created
 */ 
function xMapResultsRowIdx(AJAX) {

	if (AJAX.readyState == 4) {

		if (AJAX.status == 200) {
			logger('AJAXRequest is complete: ' + AJAX.readyState + "/" + AJAX.status + "/" + AJAX.statusText);

			if ( AJAX.responseXML ) {

				var results= AJAX.responseXML; //will need to set some other way?

				var record = null;
				var dataNodes = "";
				var tableRow = null;
				var rowIdx = ""; //cr102406 - in this base model no rowIdx is used but must be passed

				var pType = results.getElementsByTagName("PTYPE")[0].firstChild.nodeValue;
				var tBody = results.getElementsByTagName("TBODY")[0].firstChild.nodeValue;

				var records = results.getElementsByTagName("ROW");

				clearTable(tBody);

				for (var i=0; i < records.length; i++) {

					record = records[i];

					dataNodes = record.getElementsByTagName("COL");

					rowIdx = "_" + i;
					tableRow = createTableRow(dataNodes, pType, rowIdx);		//cr102406 pass rowIdx	

					document.getElementById(tBody).appendChild(tableRow);

				}

			}
		}
	}

	return; 
	
} // end of xMapResultsRowIdx
  
  	
/*
 * createTableRow
 *
 * creates a row to be placed in a table that is will include a row for each column on the xml document
 * for example for 1 row with 2 cols: <tr> <tr><td>col1</td></tr> <tr><td>col2</td></tr> </tr> 
 * -----------------------------------------------------------------------------------------------------
 * 020206 CHR created
 * 102406 CR rowIdx
 */ 
function createTableRow(dataNodes, pType, rowIdx) {

	var row;
	var cell;

	var tableRow = document.createElement("tr");
	tableRow.setAttribute("BGCOLOR", "white");

	for (var i=0; i < dataNodes.length; i++) {

		column = dataNodes[i];

		row = document.createElement("tr");

		cell = createLabel(column);
		row.appendChild(cell);

		cell = createInputCell(column, rowIdx);		//cr102506 rowIdx
		row.appendChild(cell);


		tableRow.appendChild(row);

	}

	return tableRow;


} // end createTableRow
  	
  	
/*
 * createInputCell
 *
 * creates a td cell for input either textarea or text
 * ------------------------------------------------------------------------------------------------
 * 020206 CHR created
 * 102406 CR rowIdx
 */
function createInputCell(column, rowIdx) {

	var cell = document.createElement("td");

	if (column.getElementsByTagName("TYPE")[0].firstChild.nodeValue == "textarea") {

		var textNode = document.createElement("TEXTAREA");
		textNode.setAttribute("name", column.getElementsByTagName("NAME")[0].firstChild.nodeValue + rowIdx);
		textNode.setAttribute("id", column.getElementsByTagName("NAME")[0].firstChild.nodeValue + rowIdx + "_id");
		textNode.value=decode(column.getElementsByTagName("VALUE")[0].firstChild.nodeValue);
		textNode.setAttribute("rows", "30");
		textNode.setAttribute("cols", "65");

	} else {

		var textNode = document.createElement("INPUT");
		textNode.setAttribute("type", "text");
		textNode.setAttribute("name", column.getElementsByTagName("NAME")[0].firstChild.nodeValue + rowIdx);
		textNode.setAttribute("id", column.getElementsByTagName("NAME")[0].firstChild.nodeValue  + rowIdx + "_id");
		textNode.setAttribute("value", decode(column.getElementsByTagName("VALUE")[0].firstChild.nodeValue));
		textNode.setAttribute("size", "50");

	}

	cell.appendChild(textNode);
	return cell;

} // end createInputCell
  
  
/*
 * createLabel
 *
 * creates a TextNode using the Label element of the xml document returned
 * ------------------------------------------------------------------------------------------------
 * 020206 CHR created
 */
function createLabel(column) {

	var cell = document.createElement("td");
	cell.setAttribute("CLASS", "tablelabel");

	var textNode = document.createTextNode(decode(column.getElementsByTagName("LABEL")[0].firstChild.nodeValue));
	cell.appendChild(textNode);

	return cell;

} // end createLabel
  
  	
/*
 * clearTable
 *
 * clears the tBody element of previous values
 * ------------------------------------------------------------------------------------------------
 * 020206 CHR created
 */
function clearTable(tBody) {

	var tableBody = document.getElementById(tBody);

	while (tableBody.childNodes.length > 0) {
		tableBody.removeChild(tableBody.childNodes[0]);
	}

} // end clearTable
  	
/*
 * pullSearchArgs
 *
 * 	will only load those fields with an id (way to control number of vars to just those required for searching) and place
 * into a string to be sent to server
 *
 */
function pullSearchArgs(formName) {

	var args = "";
	var fieldType = "";
	var fieldName = "";

	for(i=0; i<document[formName].elements.length; i++) {

		fieldType = document[formName].elements[i].type;
		fieldName = document[formName].elements[i].name;

		if (document.getElementById(fieldName+'_id') != undefined) {

			if(fieldType == 'select-multiple')	{ 

				if (document[formName].elements[i].length > 0) {

					var selectList = document[formName].elements[i];
					var chosen = "";
					for (var k = 0; k < selectList.length; k++) {

							if (selectList[k].selected == true) {
								chosen = chosen + selectList.options[k].value + ",";
							}						
					} //end for

					args +=  "&" + fieldName + "=" + encode(chosen);
				} // end if length > 0
			}
			else if(fieldType == 'checkbox' || fieldType == 'radio') {
				if (document[formName].elements[i].checked) { 
					args += "&" + fieldName  + "=" +  document[formName].elements[i].value;
				}
			}
			else { 
				args += "&" + fieldName  + "=" +  document[formName].elements[i].value;
			}

		}
	} // end for loop

	return args;

 } //end pullSearchArgs

 /*
 * getXMapRtnFctn
 *
 * Makes server call to get xml representation of a context map allows for passing of retunr function
 * --------------------------------------------------------------------------------------------------------
 * 101006 CR created
 */
function getXMapRtnFctn( site, key, key_value, ptype, tbody, context, rtn_fctn ) {

  return new AJAXRequest("POST", "/ms/AjaxServlet", "SITE=" + site + "&XMAP=TRUE" + "&" + key + "=" + key_value + "&PTYPE=" + ptype + "&TBODY=" + tbody + "&MS_CONTEXT=" + context, rtn_fctn);

} // end getXMap

  
/*
 * xEMailMsgText
 *
 * Put custom text on page fro CM_COMPOSE_EMAIL
 * -----------------------------------------------------------------------------------------------------
 * 101006 CR created
 */ 
function xEMailMsgText(AJAX) {

	if (AJAX.readyState == 4) {

		if (AJAX.status == 200) {
			logger('AJAXRequest is complete: ' + AJAX.readyState + "/" + AJAX.status + "/" + AJAX.statusText);

			if ( AJAX.responseXML ) {

				var results= AJAX.responseXML; //will need to set some other way?
				var column = results.getElementsByTagName("ROW")[0].getElementsByTagName("COL")[0];

				document.getElementById("mail_message0").value=decode(column.getElementsByTagName("VALUE")[0].firstChild.nodeValue);

			}
		}
	}

	return; 
	
} // end of xMailerMsgText

  
/*
 * xMailerMsgText
 *
 * Put custom text on page fro CM_CREATE_MAILER
 * -----------------------------------------------------------------------------------------------------
 * 101006 CR created
 */ 
function xMailerMsgText(AJAX) {

	if (AJAX.readyState == 4) {

		if (AJAX.status == 200) {
			logger('AJAXRequest is complete: ' + AJAX.readyState + "/" + AJAX.status + "/" + AJAX.statusText);

			if ( AJAX.responseXML ) {

				var results= AJAX.responseXML; //will need to set some other way?
				var column = results.getElementsByTagName("ROW")[0].getElementsByTagName("COL")[0];

				document.getElementById("MESSAGE_TEXT_id").value=decode(column.getElementsByTagName("VALUE")[0].firstChild.nodeValue);

			}
		}
	}

	return; 
	
} // end of xMailerMsgText


 