
var http_request = false;

function ProcessAJAXCall(Page, ProcessFunction) {

	//alert(FormElement.options[FormElement.selectedIndex].value);
    http_request = false;
    
    //alert(Page + ProcessFunction); 
    
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
 
    if(http_request!=null) {
			
	  if(ProcessFunction!=null)
	   http_request.onreadystatechange = ProcessFunction;
      //alert(ProcessFunction);
      http_request.open("GET", Page,  true);
      http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      http_request.send(null);
    }
    return false;
}

// add/Remove control from client-side validation
function ToggleValidation(ItemName, enable) {
    //alert(ItemName);
	if (enable && document.getElementById('required_' + ItemName)) {
		//show the red *
		document.getElementById('required_' + ItemName).style.display='';
	}
	else if (document.getElementById('required_' + ItemName)) {
		//Hide the red *
		document.getElementById('required_' + ItemName).style.display='none';
	}

	if (typeof Page_Validators != "undefined") {
	
		var i;
		for (i = 0; i < Page_Validators.length; i++) {
			if (Page_Validators[i].controltovalidate == ItemName) {
				ValidatorEnable(Page_Validators[i], enable);

			}
		}
	}
}

// controller for Zipcode
function AddressTextBoxController(controlClientId) {

	var self = this;
	// public members
	this.controlClientId = controlClientId;
	this.visible = true;

	// public methods
	this.Validation = Validation;
	this.init = init;
	
	function init(value) {
		this.visible = value;
	}
	
	function Validation(filter) {
		if (document.getElementById(controlClientId)) {
			if ((filter.indexOf('US') == -1) && (filter.indexOf('CAN') == -1)) {
				//alert('hello');
				ToggleValidation(controlClientId, false);
				//Hide the red *
				if ( document.getElementById('required_' + controlClientId) ) {
					document.getElementById('required_' + controlClientId).style.display='none';
				}
			}
			else {
				//Loop through the validators to change RexExpr for Canada and US
				if (typeof Page_Validators != "undefined") {
					var i;
					for (i = 0; i < Page_Validators.length; i++) {
						if (Page_Validators[i].controltovalidate == controlClientId) {
							if (Page_Validators[i].evaluationfunction != 'RequiredFieldValidatorEvaluateIsValid') {
								if (filter.indexOf('US') == -1) {
									// CANADA
									Page_Validators[i].enabled=false;
									//Page_Validators[i].validationexpression=/[ABCEGHJKLMNPRSTVXY]\d[A-Za-z] \d[A-Za-z]\d/;
								}
								else {
									// US
									Page_Validators[i].enabled=true;
									Page_Validators[i].validationexpression=/^\d{5}(-\d{4})?$/;
								}
								//alert(Page_Validators[i].validationexpression);
								ValidatorValidate(Page_Validators[i]);
								ValidatorUpdateIsValid();
								if (document.getElementById('required_' + controlClientId)) {
									document.getElementById('required_' + controlClientId).style.display='';	
								}
							}
						}
					}
				}
			}
		}
	}
}

// controller for AjaxDropDownList
function AjaxDropDownController(controlClientId, lookupName, baseUrl)
{
	var self = this;
	
	// public members
	this.controlClientId = controlClientId;
	this.hiddenId = "__" + self.controlClientId;
	this.lookupName = lookupName;
	this.baseUrl = baseUrl;
	this.delimiter = '|';
	this.visible = true;

	
	// array to store observer list
	var observers = [];			

	// public methods
	this.getSource = getSource;
	this.addObserver = addObserver;
	this.notify = notify;
	this.load = load;
	this.init = init;
	this.persist = persist;

	// call XMLHTTP to get source data
	function getSource(filter)
	{
		var requestUrl;
		if (baseUrl.indexOf('?') == -1) {
			requestUrl = baseUrl + "?id=" + self.lookupName;
		}
		else {
			requestUrl = baseUrl + "&id=" + self.lookupName;
		} 
		if (filter != undefined && filter != "")
		{
			requestUrl += "&filter=" + filter;
		}
		
		ProcessAJAXCall(requestUrl, doReadyStateChange);
			
	}
	
	// process the response from XMLHTTP
	function doReadyStateChange()
	{
		if (http_request.readyState == 4)
		{
			if (http_request.status == 200)
			{
				eval("var d=" + http_request.responseText);
				if (d != null)
				{
					populateList(d);
				}
			}
			else
			{
				alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
			}
		}			
	}
	
	// populate dropdownlist
	function populateList(namevalue)
	{
		if (document.getElementById(self.controlClientId))
		{
			oSelect = document.getElementById(self.controlClientId)
			var content = "";
			var controlClientName = oSelect.name;
			var oHidden;
			
			// clear dropdownlist
			if (oSelect.type == 'select-one') {
				for(var i=oSelect.length-1; i>=0; i--)
				{
					oSelect.options[i] = null;
				}
			}
			
			var parentObj = oSelect.parentNode;
			
			// if we have more than one item in the drop down list then
			if (namevalue.length > 1) {
				// display drop down and label
				if (parentObj.style.display == 'none') {
					parentObj.style.display = '';
					//TODO: display the previous cell
				}
				else {
					if (parentObj.parentNode) {
						if (parentObj.parentNode.style.display == 'none') {
							parentObj.parentNode.style.display = '';
						}
					}
				}
				
				// If it's a input element, change it to a select
				if (oSelect.type == 'text' || oSelect.type =='hidden') {

					var inputSel = document.createElement("SELECT");
					inputSel.setAttribute("name",controlClientName);
					inputSel.setAttribute("id",self.controlClientId);
					parentObj.replaceChild(inputSel, oSelect) ;
					oSelect = document.getElementById(self.controlClientId);
					init();
					
					// enable any validation
					ToggleValidation(self.controlClientId, true) 
				}

				// populate dropdownlist from name-value object
				for(var i=0; i<namevalue.length; i++)
				{
					if (namevalue[i].value == undefined)
					{
						oSelect.options[oSelect.length] = new Option(namevalue[i].name);
						content += namevalue[i].name + self.delimiter + namevalue[i].name + self.delimiter;
					}
					else
					{
						opt = new Option(namevalue[i].name, namevalue[i].value);
						oSelect.options[oSelect.length] = opt;
						content += namevalue[i].name + self.delimiter + namevalue[i].value + self.delimiter;
					}
					
				}
				// persist the content of dropdownlist as
				// value-delimited string in hidden field
				if (content.substr(content.length-1,1) == self.delimiter)
				{
					content = content.substr(0, content.length-1);
				}
				
				if (oHidden = document.getElementById(self.hiddenId))
				{
					oHidden.value = content;
				}
				
				if (oSelect.selectedIndex > -1){
					if (oSelect.fireEvent)
					{
						oSelect.fireEvent("onchange");
					}
					else if(oSelect.dispatchEvent)
					{
						var oEvent = document.createEvent("HTMLEvents"); 
						oEvent.initEvent("change", true, true);
						oSelect.dispatchEvent(oEvent);
					}
				}
				
				if (!self.visible) {
					//show the label
				}
			}
			else if (oSelect.type != 'text' ) {
				// Clear out the hidden field
				if (oHidden = document.getElementById(self.hiddenId))
				{
					oHidden.value = content;
				}
				
				// No data returned and no existing text box so create a text box
				var inputEl = document.createElement("INPUT");
				inputEl.setAttribute("id", self.controlClientId);
				inputEl.setAttribute("name", controlClientName);
				inputEl.setAttribute("size", 20);
				inputEl.setAttribute("value", namevalue);
				
				if (self.visible) {
					inputEl.setAttribute("type", "text");
				}
				else {
					//hidden field
					inputEl.setAttribute("type", "hidden");
					// hide the row
					// TODO: only hide the previous cell instead
					if (parentObj.parentNode) {
						if (parentObj.parentNode.style.display == '') {
							parentObj.parentNode.style.display = 'none';
						}
					}
				}
				
				parentObj.replaceChild(inputEl,oSelect);
				
				// disable any validation
				ToggleValidation(self.controlClientId, false) 
				
				// hide the label
			}

		}
	}

	// add observer
	function addObserver(obj)
	{
		var length = observers.length;
		var found = false;
		for (var i=0; i<length; i++)
		{
			if (observers[i] == obj)
			{
				found = true;
				break;
			}
		}
		if (!found)
		{
			observers[observers.length] = obj;
		}			
	}
	
	// notify all observers
	function notify()
	{
		var filter = "";
		var oSelect = document.getElementById(self.controlClientId);
		if (oSelect != null && oSelect.selectedIndex != -1 && oSelect.options[oSelect.selectedIndex].value != '')
		{
			filter = self.lookupName + "," + oSelect.options[oSelect.selectedIndex].value;
					
			for(i=0; i<observers.length; i++)
			{
				var exists;
				eval('exists = typeof ' + observers[i]);
				//alert(observers[i]);
				if (exists != 'undefined' ) {
					//var exists
					if (eval(observers[i] + ' instanceof AjaxDropDownController')) {
						eval(observers[i] + '.load(filter);');
					}
					else {
						//alert('eval ' + observers[i]);
						eval(observers[i] + '.Validation(filter);');
					}
				}
			}
		}	
	}
	
	// load the source data for corresponding dropdownlist
	function load(filter)
	{
		this.getSource(filter);
	}
	
	// initialize corresponding dropdownlist
	function init(value)
	{
		this.visible = value;
		if ((oSelect = document.getElementById(self.controlClientId)))
		{
			if (oSelect.type == 'select-one')  {
			
				// create hidden field to store dropdownlist content
				
				//saifi:Check If Hidden field Already Added
				var stateHidden =document.getElementById(self.hiddenId);
				if(typeof stateHidden =='undefined')
				if (!(hidden = document.getElementById(self.hiddenId)))
				{
					hidden = document.createElement("input");
					hidden.id = self.hiddenId;
					hidden.name = self.hiddenId;
					hidden.type = "hidden";
					oSelect.form.appendChild(hidden);
				}				

				// load source data if dropdownlist is empty,
				// otherwise persist existing content
				if (oSelect.options.length == 0)
				{
					//this.load();
				}
				else
				{
					this.persist(oSelect);
				}
				
				// attach notify event handler to onchange event
				if (oSelect.attachEvent)
				{
					oSelect.attachEvent("onchange", notify);
				}
				else if (oSelect.addEventListener)
				{
					oSelect.addEventListener("change", notify, false);
				}
				else
				{
					oSelect.onchange = notify;
				}
			}
		}
	}
	
	// persist existing content of dropdownlist to hidden field
	function persist(oSelect)
	{
		var content = "";
		for(var i=0; i<oSelect.options.length; i++)
		{
			content += oSelect.options[i].text + self.delimiter + oSelect.options[i].value + self.delimiter;
		}
		
		if (content.substr(content.length-1,1) == self.delimiter)
		{
			content = content.substr(0, content.length-1);
		}
		
		if ((hidden = document.getElementById(self.hiddenId)))
		{
			hidden.value = content;
		}
	}
}
