var xmlhttp=false;

try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }

if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	try {
		xmlhttp = new XMLHttpRequest();
	} catch (e) {
		xmlhttp=false;
	}
}
if (!xmlhttp && window.createRequest) {
	try {
		xmlhttp = window.createRequest();
	} catch (e) {
		xmlhttp=false;
	}
}

var JSON = function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        if (!x.hasOwnProperty || x.hasOwnProperty(i)) {
                            v = x[i];
                            f = s[typeof v];
                            if (f) {
                                v = f(v);
                                if (typeof v == 'string') {
                                    if (b) {
                                        a[a.length] = ',';
                                    }
                                    a.push(s.string(i), ':', v);
                                    b = true;
                                }
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };
    return {
/*
    Stringify a JavaScript value, producing a JSON text.
*/
        stringify: function (v) {
            var f = s[typeof v];
            if (f) {
                v = f(v);
                if (typeof v === 'string') {
                    return v;
                }
            }
            return;
        },
/*
    Parse a JSON text, producing a JavaScript value.
    It returns false if there is a syntax error.
*/
        parse: function (text) {
            try {
                return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                        text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
                    eval('(' + text + ')');
            } catch (e) {
                return false;
            }
        }
    };
}();
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// AJAX Interaction function, which separates object creation, request, and callback.
// This function allows passing of parameters to whatever is specified as the callback() function.
// Requirements:
// - url: the URL of the asp page that loads the data in the background
// - callback: the function to call when the AJAX load is complete
// - destinationobject: the object to pass to the callback function, which is to receive the data
// - param1: an additional parameter that will be passed to the callback function. This could carry
// anything you like. For select boxes, it carries a possible preselect value.
// - It is also required that the destinationobject has a corresponding <DIV> tag with an
// ID value of "<destinationobjectname>AJAXloading". This is for the display of an animated
// .GIF beside the destinationobject.
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function AJAXInteraction(url, callback, destinationobject, param1) {
	var MySelectBox;

	if (document.getElementById(destinationobject)) { 
		MySelectBox = document.getElementById(destinationobject);
	} 
    
	var http_request = init();
	
	http_request.onreadystatechange = processRequest;
    
	function init() {
	  if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	  } else if (window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	  }
	}
	
	//The function needs to check for the state of the request. If the state has the value of 4, that means that the full 
	//server response is received and it's OK for you to continue processing it.
	//The full list of the readyState values is as follows:
	//* 0 (uninitialized)
	//* 1 (loading)
	//* 2 (loaded)
	//* 3 (interactive)
	//* 4 (complete) 
	// Not all of these readyState values behave as expected in different browser. In fact, only 0 and 4 are truly reliable.

	function processRequest () {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				if (MySelectBox) {
					MySelectBox.disabled=false;
				}
				
				if (callback) callback(http_request.responseText, destinationobject, param1);
				
			}
		}
		else {
			if (MySelectBox) {
				MySelectBox.disabled=true;
			}
		}
	}

	this.doGet = function() {
	  http_request.open('GET', url, false);
	  http_request.send(null);
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				if (MySelectBox) {
					MySelectBox.disabled=false;
				}
				if (callback) callback(http_request.responseText, destinationobject, param1);
			}
		}
		else {
			if (MySelectBox) {
				MySelectBox.disabled=true;
			}
		}
	}
	
	this.doPost = function(body) {
	  http_request.open("POST", url, false);
	  http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	  http_request.send(body);
	  
        if (http_request.readyState == 4) {
	        if (http_request.status == 200) {
		        if (MySelectBox) {
			        MySelectBox.disabled=false;
		        }
        		
		        if (callback) callback(http_request.responseText, destinationobject, param1);
        		
	        }
        }
        else {
	        if (MySelectBox) {
		        MySelectBox.disabled=true;
	        }
        }
	}
}

function clearCombo(oList)
{
  for (var i = oList.options.length - 1; i >= 0; i--)
  {
    oList.options[i] = null;
  }
  oList.selectedIndex = -1;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Global AJAX Request handler. Use this function to set up a call to retrieve data via AJAX.
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function AJAXRequest(url, outputfunction, destinationobject, param1) {
	var ai = new AJAXInteraction(url, eval(outputfunction), destinationobject, param1);
	ai.doGet();
	ai = null;
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Global LoadSelectBox handler. Use this function to load up any SelectBox via AJAX.
// Requirements:
// - destinationobject - the select box to receive the JSON data.
// - preselect - the index of the select box item to be preselected, if any.
// - Data being returned must be JSON format.
// - The existence of a <DIV> tag on the calling page, with an ID of "<destinationobject ID>AJAXloading"
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function LoadSelectBox(JSONData, destinationobject, preselect) {
	var SelectBoxName = destinationobject;  //First value is always the name of the object being populated (REQUIRED)
	var SelectBoxSelectItemID = preselect; //Second value is always the ID value of the item that is to be preselected (OPTIONAL)
	var MySelectBox;
	var nPreselectIndex;
	
	if (document.getElementById(SelectBoxName)) { 
		MySelectBox = document.getElementById(SelectBoxName);
	}
	var myJSONtext = JSONData;
	var objData = JSON.parse(myJSONtext);
	
	clearCombo(MySelectBox);

	if (MySelectBox) {
		MySelectBox.options.length= 0;
		// Old method of populating select boxes that while not using DOM, works on all browsers, except Opera 5.02. Works fine on later Operas.
		//myOption = new Option("[Select]", "", true, true); //Text, Value, Selected, Default Selected. The last two appear to be dead ducks in most browsers.
		//MySelectBox.options[MySelectBox.options.length] = myOption;

	}
	nPreselectIndex = -1;

	if (objData) {
		for(i=0;i<objData.items.length;i++) {
			// Old method of populating select boxes that while not using DOM, works on all browsers, except Opera 5.02. Works fine on later Operas.
			if (objData.items[i].id==SelectBoxSelectItemID){
				myOption = new Option(objData.items[i].name, objData.items[i].id, false, false); //Text, Value, Selected, Default Selected. The last two appear to be dead ducks in most browsers.
				myOption.selected = true; //Preselect this item on the fly. Works on most browsers

				//Some browsers require the setting of a flag, in order to force the preselect of a chosen option, after the whole <Select> has finished building.
				//One example is Opera. 
				nPreselectIndex = i; // i + 1 if we already added an option called [select]
			}
			else {
				myOption = new Option(objData.items[i].name, objData.items[i].id, false, false); //Text, Value, Selected, Default Selected. The last two appear to be dead ducks in most browsers.
			}
			MySelectBox.options[MySelectBox.options.length] = myOption;
			MySelectBox.select

		}

		//Force a preselect here, after building the select box. Required on browsers like Opera which won't preselect elements on the fly.
		if (nPreselectIndex > -1) {
			MySelectBox.options[nPreselectIndex].selected = true; //This forces a preselect if necessary.
		}
	}
	
	myOption = null;
	MySelectBox = null;
	objData = null;
}	
function UpdateDiv(responseText, destinationobject, param1) {
	document.getElementById(destinationobject).innerHTML = responseText; 
}