
    function handleEnrollmentResponse(){
       try{
          // Pop-up the "loading" box in middle of screen.
          if ( xmlHttp.readyState == 1 ){
              showLoadingPleaseWait(null);
          }

          // Handle completed response
          if ( xmlHttp.readyState == 4 ){
              log("readyState: " + xmlHttp.readyState + ", status:"+ xmlHttp.status );

              // Hide the "loading" box in middle of screen.
              var obj = document.getElementById('_LoadingPleaseWaitDiv');
              obj.style.display='none';

              // log('ReadyState: ' + xmlHttp.readyState );
              log("xmlHttp.responseText: " + xmlHttp.responseText + ", xmlHttp.responseXML: " + xmlHttp.responseXML);

	      if ( xmlHttp.responseXML== null ){
                 alert('Null XML received, aborting.');
                 return;
              }
            
              // Process enrollment result
              if ( xmlHttp.status == 200){
                 log("Handling success");
                 processEnrollmentSuccess( xmlHttp.responseXML);
              }else{
                 log("Handling failure");
                 processEnrollmentFailure( xmlHttp.responseXML);
              }
          }
       }catch(exc){
          alert('handleAjaxResponse() Error: ' + exc.description );
       }
    }

    function processEnrollmentSuccess(xmlDoc){
       log("Success, xmldoc="+xmlDoc);
       var theUrl = xmlDoc.documentElement.getElementsByTagName('url');
       log("theUrl: " + theUrl );
       var patientId = xmlDoc.documentElement.getElementsByTagName('patientID');
       log("patientID: " + patientId );
       var cardholderID = xmlDoc.documentElement.getElementsByTagName('cardholderID');
       log("cardholderID: " + cardholderID );
         
       if ( theUrl != null && theUrl.length > 0 ){
            theUrl = drugCardUrl + unescape( theUrl[0].firstChild.data );
           patientId = unescape( patientId[0].firstChild.data );
           cardholderID = unescape( cardholderID[0].firstChild.data );
           if ( null != popup('cardWin',theUrl,800,600) ){
              // Route to questionaire
              log("Routing to questionaire");

              // Capture form details.
              var firstName = document.getElementById(prefix + 'txtFirstName');
              var lastName = document.getElementById(prefix + 'txtLastName');
              var address = document.getElementById(prefix + 'txtAddress');
              var city = document.getElementById(prefix + 'txtCity');
              var state  = document.getElementById(prefix + 'comboState');
              var zip = document.getElementById(prefix + 'txtZip');
              var email = document.getElementById(prefix + 'txtEmail');
              var phone = document.getElementById(prefix + 'txtPhone');
              var optOutEmail = "";
              if(document.getElementById(prefix + 'oCheckBoxOptOutEmail'))
              {
                  optOutEmail = document.getElementById(prefix + 'oCheckBoxOptOutEmail').checked;
              }
		
              var args ='UserQuestionaire.aspx'
                 + '?fn=' + escape(firstName.value) 
                 + '&ln=' + escape(lastName.value)
                 + '&address=' + escape(address.value)
                 + '&city=' + escape(city.value)
                 + '&state=' + escape(state.value)
                 + '&zip=' + escape(zip.value)
                 + '&email=' + escape(email.value)
                 + '&phone=' + escape(phone.value)
                 + '&cardholderID=' + escape(cardholderID)
                 + '&patientID=' + escape(patientId);
              if(optOutEmail || !optOutEmail)
              {
                  args += '&optOutEmail=' + escape(optOutEmail);
              }
              window.location= args;
           }
       }else{
           alert("Enrollment succeeded without target URL");
       }
    }

    function processEnrollmentFailure(xmlDoc){
       var errors = xmlDoc.getElementsByTagName('error');
       log("errors.length: " + errors.length );

       if ( errors.length > 0 ){
          // Show errors in list
          log("removing errorsUL children");
          var errorDiv = document.getElementById('errorsDiv');
          var errorsUL = document.getElementById('errorsUL');

          while( errorsUL.hasChildNodes() ){
             errorsUL.removeChild( errorsUL.firstChild );
          }
                      
          log("adding errorsUL children");

          for( var i=0; i<errors.length; ++i ){
             var elem = document.createElement('li');
             var txt = document.createTextNode(errors[i].firstChild.data);
             log("error text: " + errors[i].firstChild.data );
             elem.appendChild(txt);
             errorsUL.appendChild( elem );
          }

          log("setting errorDiv display to block");
          errorDiv.style.display='block';
       }else{
          alert("Enrollment Failed with unspecified error.");
       }
       log("Done processing");
    }

    function createAjaxObject(){
        //generic code (www.w3schools.com (http://www.w3schools.com))
        var ajaxCall = null;
        try{
            // Firefox, Opera 8.0+, Safari, IE 7+ (IE 6+?)
            ajaxCall = new XMLHttpRequest(); 
        }catch (e){
            // Internet Explorer
            try{
                ajaxCall = new ActiveXObject('Msxml2.XMLHTTP'); 
            }catch (e){
                try{
                    ajaxCall = new ActiveXObject('Microsoft.XMLHTTP'); 
                }catch (e){
                    alert('Your browser does not support AJAX!');
                    return null;
                }
            }
        }

        log("returning created xmlHttp object");
        return ajaxCall;
    }


    function popupCard(){
        try{
	    prefix = document.getElementById('hidden_TextBox1').value.replace('txtFirstName','');
	    var errorDiv = document.getElementById('errorsDiv');
	    errorDiv.style.display='none';

	    log('Kicking off popup card function: ' + prefix );
        
	    // prefix = thePrefix;
            var firstName   = document.getElementById(prefix + 'txtFirstName');
            var lastName    = document.getElementById(prefix + 'txtLastName');
            var email       = document.getElementById(prefix + 'txtEmail');
            var dobYear     = document.getElementById(prefix + 'txtDobYear');
            var dobMonth    = document.getElementById(prefix + 'txtDobMonth');
            var dobDay      = document.getElementById(prefix + 'txtDobDay');
            var address     = document.getElementById(prefix + 'txtAddress');
            var city        = document.getElementById(prefix + 'txtCity');
            var state       = document.getElementById(prefix + 'comboState');
            var zip         = document.getElementById(prefix + 'txtZip');
            var phone       = document.getElementById(prefix + 'txtPhone');
            var optOutEmail = "";
            if(document.getElementById(prefix + 'oCheckBoxOptOutEmail'))
            {
                optOutEmail = document.getElementById(prefix + 'oCheckBoxOptOutEmail');
            }

            var args='firstName=' + escape(firstName.value)
                    + '&lastName=' + escape(lastName.value)
                    + '&email=' + escape(email.value)
                    + '&dobYear=' + escape(dobYear.value)
                    + '&dobMonth=' + escape(dobMonth.value)
                    + '&dobDay=' + escape(dobDay.value)
                    + '&address=' + escape(address.value)
                    + '&city=' + escape(city.value)
                    + '&state=' + escape(state.value)
                    + '&zip=' + escape(zip.value)
                    + '&phone=' + escape(phone.value)
                    + '&host=' + host
                    + '&groupId=' + groupId
                    + '&planId=' + planId
                    + '&requested_firstname=' + requested_firstname
                    + '&requested_lastname=' + requested_lastname
                    + '&requested_zip=' + requested_zip
                    + '&requested_address=' + requested_address
                    + '&requested_city=' + requested_city
                    + '&requested_email=' + requested_email
                    + '&requested_phone=' + requested_phone;
            
            if(optOutEmail!="")
            {
                args += '&optOutEmail=' + escape(optOutEmail.checked);
            }
            
            var method = 'POST';
            var url = 'EnrollHTA.xml';
            var async=true;

            xmlHttp = createAjaxObject();
            xmlHttp.open( method, url, async);
            xmlHttp.onreadystatechange=handleEnrollmentResponse;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            log(method + '-ing to ' + url);
            xmlHttp.send(args);
        }catch( exc ){
            alert( 'error: ' + exc.description );
        }
        
        return false;
    }


    function popupCard2( prefixId, fieldId ){
        try{
	        prefix = document.getElementById( prefixId ).value.replace(fieldId,'');
            var theDdl= document.getElementById(prefix + fieldId);

            if ( theDdl != null ){
                var theUrl = selectedValue( theDdl );
                if ( theUrl == null || theUrl.length == 0 ){
                    alert("Please select a card");
                    return;
                }

                basic_popup( 'TemporaryCard', theUrl )
            }

        }catch(exc){
            alert( 'error: ' + exc.description );
        }
        
        return false;
    }
    
    function raw_popup( title, url, top, left, width, height ){
       try{
          var win = window.open( url, title, 'top=' + top + ',left=' + left + ',width=' + width + ',height=' + height + ',status=no,toolbar=no,menubar=no,location=no,resizable=yes,directories=no,scrollbars=yes' );

          win.focus();
          return win;
       }catch ( exception ){
            alert( 'Could not open popup window to ' + url + '. Please enable pop up windows for this site and try again.');
            alert( exception.message );
            return null;
       }
    }

    function basic_popup( title, url ){
       try{
          var win = window.open( url, title );

          win.focus();
          return win;
       }catch ( exception ){
            alert( 'Could not open popup window to ' + url + '. Please enable pop up windows for this site and try again.');
    alert( exception.message );
            return null;
       }
    }


    function popup( title, url, width, height )
    {
       try
       {
          /* Default popup window values */
          var top = 110;
          var left = 190;

          /* Center window on screen */
          var left = (screen.width - width) / 2.0;
          var top = (screen.height - height) / 2.0;
          var win = raw_popup( title, url, top, left, width, height );

          return win;
       }
       catch ( exception )
       {
            alert( 'Could not open popup window. Please enable pop up windows for this site and try again.');
            return null;
       }
    }


    function log( msg )
    {
       if ( debug == 1)
       {
          alert( "DEBUG: " + msg );
       }
    }
    
    //Toggling from * Email to Email and vice versa when opt-out email checkbox is checked or unchecked
    function ToggleRequiredEmail()
    {
    	prefix = document.getElementById('hidden_TextBox1').value.replace('txtFirstName','');
    	//* Email into Email
    	if(document.getElementById(prefix + 'oLBLEmail'))
    	{
    	     if(document.getElementById(prefix + 'oLBLEmail').innerText == "* Email" && document.getElementById(prefix + 'oCheckBoxOptOutEmail').checked == true)
    	     {
    	     	 document.getElementById(prefix + 'oLBLEmail').innerHTML = "<normal>Email</normal>";
    	     }
    	     else if(document.getElementById(prefix + 'oLBLEmail').innerText == "Email" && document.getElementById(prefix + 'oCheckBoxOptOutEmail').checked == false)
    	     {
    	     	 document.getElementById(prefix + 'oLBLEmail').innerHTML = "<b>* Email</b>";
    	     }
    	}
    }
    
//    if(document.getElementById('hidden_TextBox1'))
//    {
//        prefix = document.getElementById('hidden_TextBox1').value.replace('txtFirstName','');
//	    document.getElementById(prefix + 'txtPhone').value = '(xxx-xxx-xxxx)';
//	}
    
    function ClearPhoneField()
    {
	    prefix = document.getElementById('hidden_TextBox1').value.replace('txtFirstName','');
	    document.getElementById(prefix + 'txtPhone').value = '';
    }
    
    function CheckFieldEmpty() {
	    prefix = document.getElementById('hidden_TextBox1').value.replace('txtFirstName', '');
	    if (document.getElementById(prefix + 'txtPhone').value == '') {
	        document.getElementById(prefix + 'txtPhone').value = "(xxx-xxx-xxxx)";
	    }
	}
    
//******************************************
// POPUP Stuff
//******************************************
    window.onload = registerEvents;
    
    function registerEvents() {
      if (window.Event) {
        document.captureEvents(Event.MOUSEMOVE);
      }
      document.onmousemove = recordCursorPosition;
    }

    var cursor_x, cursor_y;
    
    function recordCursorPosition(e) {
      cursor_x = (window.Event) ? e.pageX : event.clientX;
      cursor_y = (window.Event) ? e.pageY : event.clientY;
    } 


	function ShowPopup(popup){
		var hp = null;
		
		hp = document.getElementById(getByIdSuffix(popup));

		if(hp!=null){
		
			//Move the popup to where the cursor is
			if(cursor_y!=null){
				hp.style.top = cursor_y; }
			if(cursor_x!=null){
				hp.style.left = cursor_x; }
			// Set popup to visible
			hp.style.visibility = "Visible";
		}else{
			alert('Popup not found!');
		}
	}

	function HidePopup(popup){
		hp = document.getElementById(getByIdSuffix(popup));
		hp.style.visibility = "Hidden";	
	}
//******************************************
// END POPUP Stuff
//******************************************

//******************************************
// DOM Searching Stuff
//******************************************
    // Finds the element that end with the specified string, by going through all the elements
    // and matching the Id suffix.
    // This is useful for finding controls whose Id is generated at run-time, which is the 
    // case with most ASP.NET stuff.
    function getByNameSuffix(objSuffix){
        var str = '';
	
        for(i=0; i<document.all.length; i++){
            obj = document.all[i];
            if(obj!=null){
                //str+= '\n' + obj.id;
                //Check if the suffix matches
	        	if(obj.name!=null){
	        	    if(obj.id!=''){	        	    
    	                if(obj.name.substr(obj.name.length-objSuffix.length, objSuffix.length)==objSuffix){
	                    return obj.name
	                    }
	                }
		        }   
            }
        }
        //alert(str);
	    return null;
    }

    //********************************************************************************
    // Checks for existance of the object with the id either equal to objSuffix,
    // OR id equal getClientPrefix() + objSuffix. In order for this to work, the page
    // must include the ClientIDTracker control. ClientIDTracker control implements
    // the getClientPrefix() function and provides the ClientPrefix value.
    //********************************************************************************
    var s123 = '';
    var sElement = '';

    function getByIdSuffix(objSuffix){
        //Try getting element by just objSuffix
        //Reset sElement name
        sElement = '';
        findElementInTree(document,objSuffix);
        if(sElement!=null){ return sElement; }
        alert ("Object '" + objSuffix + "' not found!");
    }
    
    // Traverses the node tree, looking for the object whose name or id suffix matches objSuffix variable.
    // If found, it assigns it to the global var sElement.
    function findElementInTree(node, objSuffix){
        if(node.childNodes.length>0){
            for(var i=0; i< node.childNodes.length; i++){
                //s123+="<br/>i=" + i + "(" + node.childNodes.length + "); node.tagName=" + node.tagName + "; node.id=" + node.id+ "; node.name=" + node.name;
                var childNode = node.childNodes[i];
                if(childNode!=null){
                    //Check name
                    if(childNode.name!=null){
	                    if(childNode.name.substr(childNode.name.length-objSuffix.length, objSuffix.length)==objSuffix){
        	                sElement = childNode.name;
        	                return;
                        }
	                }
	                //Check id
                    if(childNode.id!=null){
	                    if(childNode.id.substr(childNode.id.length-objSuffix.length, objSuffix.length)==objSuffix){
        	                sElement = childNode.id;
        	                return;
                        }
	                }
	            }
                findElementInTree(childNode, objSuffix);
	        }
	    }
    }
//******************************************
// END DOM Searching Stuff
//******************************************
    

//******************************************
// HTA CC Processing Stuff
//******************************************
    // Index of the section open in confirm_Edit mode.
    var openSectionIdx = -1;

    //------------------------------------------------------------------------------------
    // Checks to see if Signup button is enabled, and alerts the user to save all changes
    // before proceeding.
    //------------------------------------------------------------------------------------
    function checkEnabled(){
        var button = document.getElementById(getByNameSuffix('oIB_Submit'));
        if(button.src.indexOf('button_signmeup_off.gif')>0){
            alert('Please save all data before proceeding!');
            return false;
        }
        return true;
    }
    
    //------------------------------------------------------------------------------------
    // Checks if any other sections are in confirm_Edit mode.
    // If so, throws a warning to close(save) whatever current section the user's editing.
    // If not, it's all good.
    //------------------------------------------------------------------------------------
    function checkOnlyEditedSection(obj){
        var arrIsEditMode = new Array();
        
        for(var i=0; i<5; i++){
            arrIsEditMode[i] = new Array(3);
        }
        arrIsEditMode[0][0] = 'oSPS_SPS_oIB_Edit';
        arrIsEditMode[0][1] = false;
        arrIsEditMode[0][2] = 'Package Selected';
        
        arrIsEditMode[1][0] = 'oCCI_CCInfo_oIB_Edit';
        arrIsEditMode[1][1] = false;
        arrIsEditMode[1][2] = 'Payment Information';
        
        arrIsEditMode[2][0] = 'oPI_PI_oIB_Edit';
        arrIsEditMode[2][1] = false;
        arrIsEditMode[2][2] = 'Member Info';
        
        arrIsEditMode[3][0] = 'oAI_ShippingAddress_oIB_Edit';
        arrIsEditMode[3][1] = false;
        arrIsEditMode[3][2] = 'Shipping Address';
        
        arrIsEditMode[4][0] = 'oAI_BillingAddress_oIB_Edit';
        arrIsEditMode[4][1] = false;
        arrIsEditMode[4][2] = 'Billing Address';        
        
        for(var i=0; i<5; i++){
            var Button = document.getElementById(getByIdSuffix(arrIsEditMode[i][0]));
            if(Button!=null){
                if(Button.src.indexOf('button_save.gif')>0 && obj.id.indexOf(arrIsEditMode[i][0])<0){
                    arrIsEditMode[i][1] = true; 
                }
            }
        }
        //If any other section is open (except this one), error out
        if(isAnyElementTrue(arrIsEditMode, obj)==true){
            alert('Please save ' + arrIsEditMode[openSectionIdx][2] + ' section before attempting to edit this one!');
            return false;
        }
        return true;
    }
    
    //------------------------------------------------------------------------------------
    // Goes through an array and checks if any element is set to true.
    // Ignores the element that you're currently trying to edit.
    //------------------------------------------------------------------------------------
    function isAnyElementTrue(arr, obj){
        openSectionIdx = -1;
        for (i=0; i<arr.length; i++){
            if(arr[i][1]==true && arr[i][0]!=obj.name){ 
                openSectionIdx = i;
                return true; 
            }
        }
        return false;
    }
//******************************************
// END HTA CC Processing Stuff
//******************************************    
    

//******************************************
// EMAIL Validation
//******************************************
    function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		var errMsg = "Invalid E-mail Address!"
		
		if (str.indexOf(at)==-1){
		    alert(errMsg)
		    return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		    alert(errMsg)
		    return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert(errMsg)
		    return false
		}

        if (str.indexOf(at,(lat+1))!=-1){
		    alert(errMsg)
		    return false
		}

        if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert(errMsg)
            return false
        }

		if (str.indexOf(dot,(lat+2))==-1){
		    alert(errMsg)
		    return false
		}
		
		if (str.indexOf(" ")!=-1){
		    alert(errMsg)
		    return false
		}

 		return true					
	}

    function validateEmail(elementName){
	    var obj=document.getElementById(getByNameSuffix(elementName));
    	
	    if ((obj.value==null)||(obj.value=="")){
		    alert("Please Enter your Email Address!")
		    obj.focus()
		    return false
	    }
	    if (echeck(obj.value)==false){
		    obj.value=""
		    obj.focus()
		    return false
	    }
	    return true
     }
//******************************************
// END EMAIL Validation
//******************************************

//******************************************
// AJAX Stuff
//******************************************
    //Browser Support Code
    function ajaxFunction(){
	    var ajaxRequest;  // The variable that makes Ajax possible!
    	
	    try{
		    // Opera 8.0+, Firefox, Safari
		    ajaxRequest = new XMLHttpRequest();
	    } catch (e){
		    // Internet Explorer Browsers
		    try{
			    ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		    } catch (e) {
			    try{
				    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			    } catch (e){
				    // Something went wrong
				    alert("Your browser doesn't support AJAX!");
				    return false;
			    }
		    }
	    }
	    // Create a function that will receive data sent from the server
	    ajaxRequest.onreadystatechange = function(){
		    if(ajaxRequest.readyState == 4){
		        //Put response handler code here
			    //document.myForm.time.value = ajaxRequest.responseText;
		    }
	    }
    }
    
    function sendAJAXRequest(url){
	    //Send out ajax request
	    ajaxRequest.open("GET", url, true);
	    ajaxRequest.send(null); 
    }


//******************************************
// END AJAX Stuff
//******************************************

