function toggleCPIDForm(elem)
{
	//toggles the display of the Link CPID form
    var ddl = $(elem)[0];
    $("#attachCPID").hide();    
    if(ddl.options[ddl.selectedIndex].value == "5")
    {
        //check to see if they have already selected their birthdate
        //if so, then set the DOB drop downs to what they've selected
        $("#MyUCR_cphMain_ddlCPIDYear")[0].selectedIndex = $("#MyUCR_cphMain_ddlDOBYear")[0].selectedIndex;
        $("#MyUCR_cphMain_ddlCPIDMonth")[0].selectedIndex = $("#MyUCR_cphMain_ddlDOBMonth")[0].selectedIndex;
        $("#MyUCR_cphMain_ddlCPIDDay")[0].selectedIndex = $("#MyUCR_cphMain_ddlDOBDay")[0].selectedIndex;  
       	$("#attachCPID").show();
    }
}
// Connect the user's CPID to the MyUCR ID Account
function ConnectCPID()
{    

//alert("cute");
	//validates that the DOB entered matches to the CPID/DOB combo in UGAP401A
    var myUCRID = $("#MyUCR_hidMyUCRID").val();
    if(myUCRID == null)
    	myUCRID = $("#MyUCR_cphMain_hidMyUCRID").val(); 
    	
    var cpid = $("#MyUCR_cphMain_txtCPID").val();    
    if(cpid.length > 0)
    {
        var ddl = $("#MyUCR_cphMain_ddlCPIDYear")[0];
        var dobY = ddl.options[ddl.selectedIndex].value;
        ddl = $("#MyUCR_cphMain_ddlCPIDMonth")[0];        
        var dobM = ddl.options[ddl.selectedIndex].value;
        ddl = $("#MyUCR_cphMain_ddlCPIDDay")[0];        
        var dobD = ddl.options[ddl.selectedIndex].value;        
        if(dobY.length > 0 || dobM.length > 0 || dobD.length > 0)
        {
            //get the user's birthdate yyyymmdd
            var dob = dobY + dobM + dobD;
            var url="ajax.aspx?validateCPID=" + cpid + "&dob=" + dob + "&id=" + myUCRID;            
            $.get(url, function(xhr){confirmCPID(xhr);});            
        } 
    }
}

function confirmCPID(xhr)
{
    //if DOB/CPID match, then show the confirmation form
    var jsonObj = returnJson(xhr);
    var msg = jsonObj[0]["msg"];
    var cpid = jsonObj[0]["cpid"];
    var fname = jsonObj[0]["fname"];
    var mname = jsonObj[0]["mname"];
    var lname = jsonObj[0]["lname"];
    var myucrid = jsonObj[0]["myucrid"];    
        
        
    if(msg == "OK") // && (confirmLyr != null) ) //Alvin did it on Sep 15, 2008
    {
    
		$("#cpidConfirmation").html("").css({color:"black"});
        //we have a match, show them the confirmation information
        var msgP = document.createElement("p");
		$("#cpidConfirmation").append($(msgP).append("The following information was found. Please confirm that this is your information."));

        msgP = document.createElement("p");
		$("#cpidConfirmation").append($(msgP).html("First Name: <strong> " + fname + "</strong> Middle Name: <strong>" + mname + "</strong> Last Name: <strong>" + lname + "</strong>"));

        msgP = document.createElement("p");
        $("#cpidConfirmation").append($(msgP).append("If this is correct, click \"Link My Account\""));        

        msgP = document.createElement("p");
        var btnSubmit = document.createElement("input");
        $("#cpidConfirmation").append($(msgP).append($(btnSubmit).attr({type:"button", value: "Link My Account"}).click(function(){LinkCPID($(this));})));

        var btnCancel = document.createElement("input");
        $("#cpidConfirmation").append($(msgP).append($(btnCancel).attr({type:"button", value: "Cancel"}).click(function(){CancelCPID($(this));})));

        var hid = document.createElement("input");
		 $("#cpidConfirmation").append($(msgP).append($(hid).attr({type:"hidden", value: cpid})));
		 
		 
		 // add in Sep 15, 2008
		 var MyUCRID= document.createElement("input");
		 var hidCPID= document.createElement("input");
		 var HSAccountID= document.createElement("input");
		 
		 //var hidMyUCRID =  $("#MyUCR_cphMain_hidMyUCRID").val(); 

		  $("#cpidConfirmation").append($(msgP).append($(MyUCRID).attr({type:"hidden",id:"MyUCRID", value:myucrid  })));
		  
		  $("#cpidConfirmation").append($(msgP).append($(hidCPID).attr({type:"hidden", id:"hidCPID", value: cpid})));
		  
		  $("input#MyUCR_hidCPID").val(cpid);
		 
		  $("#cpidConfirmation").append($(msgP).append($(HSAccountID).attr({type:"hidden", id:"HSAccountID",value: ""})));

        $("#cpidConfirmation").show();
    }
    else
    {
        //show them the error message
        eMsg(msg, _errColor, ""); //confirmLyr);
    }
}

function LinkCPID()
{
    //makes a call to ajax.aspx to insert the CPID into the MyUCR_Login table
    var myUCRID ;
    var myCPID;
    
    // modified by 09/17/2008 
    // no myucrid, cpid was populated into the form element since the dom was modified by the Ajax only
    // var IDs = new GetIdentifiers();
    //var myUCRID = $("input#MyUCR_hidMyUCRID").val(); //IDs.MyUCRID;
    //var myCPID = $("input#MyUCR_hidCPID").val(); // IDs.CPID;
    // end by 09/17/2008
    
       
    // DOM value work for both CreatAccount.aspx and Profile.aspx

    myUCRID = $("input#MyUCRID").val(); 
    myCPID = $("input#hidCPID").val(); 
    
    
    // DOM value from Profile.aspx only
     if(myUCRID ==null)
    {
       myUCRID = $("input#MyUCR_hidMyUCRID").val(); 
       myCPID = $("input#MyUCR_hidCPID").val(); 
    }
    
    var url = "ajax.aspx?linkCPID=" + myCPID + "&id=" + myUCRID;
    ajaxCall("GET",url,"finalizeCPID()");
}

function finalizeCPID()
{
    //display confirmation, or error after linking the CPID
    var myJSON = req.responseText;
    var func = new Function("return " + myJSON);
    var jsonObj = func();
    var retVal = jsonObj[0]["returnValue"];        
    if(parseInt(retVal) != 1)    
    {        
        eMsg("We're sorry, there was an error, please try again.", _errColor, "globalErr");
    }
    else
    {
        //dont' know what page they'll be coming from, so check if the elements are null or not.        
        if($UCR('cpidConfirmation') != null)
            $UCR('cpidConfirmation').style.display = 'none';
        if($UCR('attachCPID') != null)
            $UCR('attachCPID').style.display = 'none';
        
        if($UCR('pnlLinkCPID') != null)
            $UCR('pnlLinkCPID').innerHTML = "Your account has been linked up.";
        if($UCR('pnlAcctMaint') != null)
            $UCR('pnlAcctMaint').style.display = 'none';
        if($UCR('pnlAcctMaintDisplay') != null)
            $UCR('pnlAcctMaintDisplay').style.display = 'block';
        if($UCR('linkedCPID') != null)
            $UCR('linkedCPID').style.display = 'inline';
        if($UCR('linkCPIDli') != null)            
            $UCR('linkCPIDli').style.display = 'none';

        //display the personal information
        $("#MyUCR_cphMain_lblUGAPfName").html(jsonObj[0]["FNAME"]);
        $("#MyUCR_cphMain_lblUGAPmName").html(jsonObj[0]["MNAME"]);
        $("#MyUCR_cphMain_lblUGAPlName").html(jsonObj[0]["LNAME"]);
        $("#MyUCR_cphMain_lblUGAPeMail").html(jsonObj[0]["EMAIL"]);
        $("#MyUCR_cphMain_lblUGAPDOB").html(jsonObj[0]["DOB"]);  
        $("#MyUCR_cphMain_lblLSTR1").html(jsonObj[0]["LSTR1"]);  
        $("#MyUCR_cphMain_lblPSTR1").html(jsonObj[0]["PSTR1"]);  
        $("#MyUCR_cphMain_lblLSTR2").html(jsonObj[0]["LSTR2"]);         
        $("#MyUCR_cphMain_lblPSTR2").html(jsonObj[0]["PSTR2"]);                 
        $("#MyUCR_cphMain_lblLCITY").html(jsonObj[0]["LCITY"]);  
        $("#MyUCR_cphMain_lblPCITY").html(jsonObj[0]["PCITY"]);  
        $("#MyUCR_cphMain_lblLST").html(jsonObj[0]["LST"]); 
        $("#MyUCR_cphMain_lblPST").html(jsonObj[0]["PST"]); 
        $("#MyUCR_cphMain_lblLZIP").html(jsonObj[0]["LZIP"]); 
        $("#MyUCR_cphMain_lblPZIP").html(jsonObj[0]["PZIP"]); 
        $("#MyUCR_cphMain_lblLCNTRY").html(jsonObj[0]["LCNTRY"]); 
        $("#MyUCR_cphMain_lblPCNTRY").html(jsonObj[0]["PCNTRY"]); 
        $("#MyUCR_cphMain_lblLPHONE").html(jsonObj[0]["LPHONE"]); 
        $("#MyUCR_cphMain_lblPPHONE").html(jsonObj[0]["PPHONE"]); 
        $("#MyUCR_cphMain_pnlChangeUserName").hide();
        $("#MyUCR_cphMain_pnlAcctMaint").hide();
        $("#MyUCR_cphMain_pnlAcctMaintDisplay").show();
        //make an ajax call to the server to run the refresh routine
        var url = "ajax.aspx?refreshPop=1";
        ajaxCall("GET",url,"functionStub()");            
    }
}

function functionStub()
{
    return false;
}
function CancelCPID()
{
    $UCR('cpidConfirmation').style.display = 'none';
}

/*MyUCR Account Creation functions */
function CheckNewAccountEntries(elem)
{
	//validate the required form fields
	var rtg = false;
	$("#btnSubmit").attr("disabled","disabled");	
	if($("input.txtFirstName").val().length == 0) return;	
	if($("input.txtLastName").val().length == 0) return;
	if($("select.ddlDescribesYou")[0].options[$("select.ddlDescribesYou")[0].selectedIndex].value.length == 0) return;
			
	var dob = $("select.ddlDOBYear")[0].options[$("select.ddlDOBYear")[0].selectedIndex].value;
	dob += $("select.ddlDOBMonth")[0].options[$("select.ddlDOBMonth")[0].selectedIndex].value;
	dob += $("select.ddlDOBDay")[0].options[$("select.ddlDOBDay")[0].selectedIndex].value;
	if(!validDOB(dob)) return;
	
	$("#btnSubmit").removeAttr("disabled");		

}

function validatePassword(elem1, elem2)
{
    //password validation; 
    $("#errPassword").hide();
    var p1 = $(elem1).val();
    var p2 = $(elem2).val();
    $(elem1).attr("valid", true);
    $(elem2).attr("valid", true);
    $("select.ddlDescribesYou").removeAttr("disabled");
    if(p1.length > 0 && p2.length > 0)
    {
        if(p1 != p2)
        {
            eMsg("Passwords do not match.", _errColor, "errPassword");
            $(elem1).attr("valid", false);
            $(elem2).attr("valid", false);            
            $("#btnSubmit").attr("disabled","disabled");
            $("select.ddlDescribesYou").attr("disabled","disabled");
        }
        else
        {
            //this function may be called from the profile page, where the username cannot be changed            
            if($UCR('txtUsername') != null && p1.toLowerCase() == $UCR('txtUsername').value.toLowerCase())
            {
                eMsg("Password cannot be the same as Username.", _errColor, "errPassword");
	            $(elem1).attr("valid", false);
	            $(elem2).attr("valid", false);            
                $("#btnSubmit").attr("disabled","disabled");
	            $("select.ddlDescribesYou").attr("disabled","disabled");                
            }
            if(p1.length < 6)
            {
                eMsg("Password must be at least 6 characters.", _errColor, "errPassword");
	            $(elem1).attr("valid", false);
	            $(elem2).attr("valid", false);            
	            $("#btnSubmit").attr("disabled","disabled");	            
	            $("select.ddlDescribesYou").attr("disabled","disabled");	            
            }
        }
    }
}
/*zip code and city validation */
function GetCityZipCodes(elem)
{
    //makes a call to the server to get a list of all zip codes for the selected city
    if(!elem){return false;}
    city = $(elem).val();
    if(city.length > 0)
    {        
        url="ajax.aspx?ziplookup=1&zipCity=" + city;
        $.get(url, function(xhr){fillZipCodes(xhr);});
    }        
}

function fillZipCodes(xhr)
{
    //fills the select element with the zip codes returned
    var jsonObj = returnJson(xhr);
    var ddlZip = $("select.ddlZips")[0];
    var ddlState = $("select.ddlState")[0];  
    $("#errZipcode").hide();
    $("#otherZipP").hide();
    if(ddlZip != null && jsonObj.length > 0)
    {
        var origZip = '';
        if(ddlZip.selectedIndex > 0) //store the previously selected zipcode
            origZip = ddlZip.options[ddlZip.selectedIndex].value;

        ddlZip.options.length = 0;       
        var selState = '';
        if(ddlState.selectedIndex > 0)
        {
            var stArr = ddlState.options[ddlState.selectedIndex].value.split('~');
            if(stArr.length > 1)
                selState = stArr[1];
        }

        ddlZip.options[ddlZip.options.length] = new Option("Select Zipcode","");
        ddlZip.options[ddlZip.options.length] = new Option("--------------","");
        
        for(var i=0; i<jsonObj.length; i++)
        {
            var optSel = false;
            var myZip = jsonObj[i]["ZIP"];
            var myState = jsonObj[i]["STATE"];
            if(myZip == origZip){optSel = true;}                
            ddlZip.options[ddlZip.options.length] = new Option(myZip,myZip); 

            if(myState == selState)
				ddlZip.options[i].selected = true;                                           

            else
            {
                var zipOption = myZip + " (" + myState + ")";                    
                ddlZip.options[ddlZip.options.length] = new Option(zipOption,myZip);
            }
        }
        ddlZip.options[ddlZip.options.length] = new Option("--------------","-1");
        ddlZip.options[ddlZip.options.length] = new Option("Not listed","-1");
        ddlZip.style.display = 'inline';
        
        if($("input.txtOtherZipcode").val().length > 0)
            checkZipcode($("input.txtOtherZipcode"),'errZipcode');
    }
    else
    {
    	$("select.ddlZips").hide();
        eMsg("No zipcodes were found for the city you entered. Please try again.",_errColor,"errZipcode");
    }    
}

function showOtherZip()
{
	//show the "other zipcode" text box if needed
    var ddlZip = $("select.ddlZips")[0];
    
    if(ddlZip != null)
    {
        if(ddlZip.options[ddlZip.selectedIndex].value == '-1')
            $("input.txtOtherZipcode").show();
        else
        {
            $("input.txtOtherZipcode").hide();
            $("#otherZipP").hide();
        }
    }
}
function Zipcode(zip){this.zipCode=zip;this.message="";this.valid=false;}
function checkZipcode(elem, errDiv)
{   //calls the validateZipCode method   
    $("#otherZipP").hide();
    var zip = new Zipcode($(elem).val());
    var rtg = zip.validateZipcode();
    if(!zip.valid)
    {
        $("#otherZipP").show();
        eMsg(zip.message,_errColor,'errOtherZipcode')
    }    
}

Zipcode.prototype.validateZipcode=validateZipcode;
function validateZipcode()
{
    if(this.zipCode == null || this.zipCode.length != 5)
    {
        this.message = "Make sure the zip code does not contain any spaces and is 5 characters long.";
        this.valid = false;
        return;
    }
    //validate the zip code
    regex=/^\d{5}$/;
    _match = regex.exec(this.zipCode);    
    if(! _match){this.valid=false;}else{this.valid=true;}
}

/* username validation */
function UserName(u){this.userName=u;this.message="";this.valid=false;}
function validateUserName()
{
    this.valid = true;
    //basic check for null, zero-length string and absence of spaces
    if(this.userName == null || this.userName.length == 0 || this.userName.indexOf(" ", 0) > -1 || this.userName.length < 8)
    {
        this.message="Make sure your username does not contain any spaces.";
        if(this.userName.length < 8)
        {
            this.message="Usernames must be at least 8 characters.";
        }
        this.valid = false;
        return;
    }
}
//Make validate() an instance method of the UserName object
UserName.prototype.validateUserName=validateUserName;
function checkUserName(elem, errDiv)
{
    var chkVal = $(elem).val();
    $("input.txtUsername").attr("valid", true);
    if(chkVal.length > 0)
    {
        var u = new UserName(chkVal);    
        u.validateUserName();
        var rtg = u.valid;    
        if(!rtg)
        {
        	eMsg(u.message,_errColor,errDiv);
        	$("input.txtUsername").attr("valid", false);
       		$("#btnSubmit").attr("disabled","disabled");
			$("#MyUCR_cphMain_ddlDescribesYou").attr("disabled","disabled");
        };
        if(rtg)
        {
            //if the hidden field already has a value (MyUCRID), then the account has been created. 
            //pass in the value so we know not to create a new account, the newly created MyUCRID will be returned
            var myUCRID = $("#MyUCR_cphMain_hidMyUCRID").val();
            if(myUCRID.length == 0 || myUCRID == "0")
                url="ajax.aspx?chkUserName=1&username=" + encodeURIComponent(chkVal);
            else
                url="ajax.aspx?chkUserName=2&username=" + encodeURIComponent(chkVal) + "&MyUCRID=" + myUCRID;
            
            $.get(url, function(xhr){isUsernameAvailable(xhr, errDiv);});                
        }
    }
}

function isUsernameAvailable(xhr, errDiv)
{
    //calls ajax.aspx.cs to see if username is available. if it is, record has been created and
    //MyUCRID is returned. If not, then displays suggested usernames.
    var jsonObj = returnJson(xhr);
    
    if(jsonObj.length > 0)
    {
        if(jsonObj[0]["returnValue"] == "false")
        {
            if(getPageType() == "profile")
                suggestRISUserName();
            else
            {
                suggestUsername(errDiv);    
                $("input.txtUsername").attr("valid","false");
            }
        }    
        else
        {
            myUCRID = jsonObj[0]["myucrid"];
            $("#MyUCR_cphMain_hidMyUCRID").val(myUCRID);
            $("#MyUCR_cphMain_ddlDescribesYou").removeAttr("disabled");
        }
    }
}

function suggestRISUserName()
{
    var myUCRID = $("#MyUCR_hidMyUCRID").val();
    url = "ajax.aspx?suggestRISUserName=" + myUCRID;
    $.get(url, function(xhr){displaySuggestedRISUserNames(xhr);});    
}

function displaySuggestedRISUserNames(xhr)
{
    var jsonObj = returnJson(xhr);
    if(jsonObj.length > 0)
    {
        var ul = document.createElement("ul");
        $("div.sugUserNames").empty().append($(ul));
        for(var i=0;i<jsonObj.length;i++)
        {
            var li = document.createElement("li");
            $(ul).append($(li).css("cursor","pointer").append(jsonObj[i]["username"]).click(function(){AcceptUserName($(this));}));
        }
        $("#otherUsernameP").slideDown(1000);
    }
}

function AcceptUserName(elem)
{
    $("#txtUserName").val($(elem).html());
    $("#otherUsernameP").slideUp(1000);
}

function ChangeUN(elem)
{
    var uName = $("#txtUserName").val();    
    var myUCRID = $("#MyUCR_hidMyUCRID").val();
    url = "ajax.aspx?changeRISUserName=" + myUCRID + "&uName=" + encodeURIComponent(uName);
    $.get(url, function(xhr){ChangeUNComplete(xhr);});        
}

function ChangeUNComplete(xhr)
{
    var jsonObj = returnJson(xhr);
    if(jsonObj.length > 0)
    {
        if(jsonObj[0]["response"] != "0")
        {
            $("#txtUserName").parents("ul").slideUp(1000);
            $("#errUsername").hide();
            $("#btnChangeUN").hide();
            $("#unChanged").html("Your Username has been changed to " + jsonObj[0]["response"]);
        }
    }
}

function suggestUsername(errDiv)
{
    //makes a call to ajax.cs to suggest 5 usernames
    //passes in any information the user has input up to this point
    var origUN = $("input.txtUsername").val();
    
    var ddl = $("select.ddlDOBYear")[0];	
    var dob;
    if(ddl.selectedIndex > -1)
	    dob = ddl.options[ddl.selectedIndex].value;
    if(dob.length <= 0) {dob = "~";}
    
	ddl = $("select.ddlZips")[0];
    var zip = "~";
    if(ddl.selectedIndex > -1)
    	zip = ddl.options[ddl.selectedIndex].value;

    if(zip.length <= 0) {zip = "~";}
    
    var fN = $("input.txtFirstName").val();
    if(fN.length <= 0) fN = "~";
    
    var lN = $("input.txtLastName").val();
    if(lN.length <= 0) lN = "~";
    
    url = "ajax.aspx?suggestUserName=1&origUN=" + encodeURIComponent(origUN) + "&dob=" + encodeURIComponent(dob);
    url += "&zip=" + zip + "&fN=" + encodeURIComponent(fN) + "&lN=" + encodeURIComponent(lN);
    $.get(url, function(xhr){displaySuggestedUserNames(xhr, errDiv);});    
}

function displaySuggestedUserNames(xhr, errDiv)
{
    //displays the suggested usernames generated on the server
    var jsonObj = returnJson(xhr);
    if(jsonObj.length > 0)
    {        
        var ddl = $("select.ddlOtherUsername")[0];
        ddl.options.length = 0;
        ddl.options[ddl.options.length] = new Option("Select Username", "");    
        for(var i=0; i<jsonObj.length; i++)
        {
            var myUName = jsonObj[i]["username"];
            ddl.options[ddl.options.length] = new Option(myUName, myUName);
        }    
        $("#otherUsernameP").show();
        ddl.focus();  
        var erMsg = "This user name is not available. Here are some suggestions, or enter another username.";
        $("#"+errDiv).hide().css({color:_errColor}).html(erMsg).show();		
    }
}

function chooseSelectedUsername(elem)
{
    var ddlUsername = $(elem)[0];
    var uName = ddlUsername.options[ddlUsername.selectedIndex].value;
    $("input.txtUsername").val(uName).attr("valid", "true");
	$("#otherUsernameP").hide();	
    $("#errUsername").hide();
	$("select.ddlDescribesYou").removeAttr("disabled");
}

/*phone number validation */
function PhoneNumber(pn){this.phoneNumber=pn;this.message="";this.valid = false;}
function validatePhonenumber()
{
    //basic check for null, zero-length string
    if(this.phoneNumber == null || this.phoneNumber.length == 0)
    {
        this.message="Please enter your telephone number.";
    }
    //validate the phonenumber is correct for US phones
    regex=/^\(?\d{3}\)?\s|-\d{3}-\d{4}$/;
    _match = regex.exec(this.phoneNumber);
    if(_match){this.valid=true;}
    else
    {
        //this may be an international number, validate it
        regex=/^\d(\d|-){7,20}/;
        _match = regex.exec(this.phoneNumber);
        if(_match){this.valid=true;}
        else
        {
            this.message="This does not appear to be a valid telephone number. Please try again.";
            this.valid = false;
            return;
        }
    }
}
function checkPhoneNumber(elem, errDiv)
{
    $("#errPhone").hide();
    $("#errCellphone").hide();
    var chkVal = $(elem).val();
    if(chkVal.length > 0)
    {
        var pn = new PhoneNumber(chkVal);
        pn.validatePhonenumber();
        var rtg = pn.valid;    
        if(!rtg){eMsg(pn.message,_errColor,errDiv);};    
    }   
}

//make validate() and instance method of the PhoneNumber object
PhoneNumber.prototype.validatePhonenumber=validatePhonenumber;
/*email validation */
function Email(e)
{
    this.emailAddr=e;
    this.message="";
    this.valid = false;
}
function validateEmail()
{
    //basic check for null, zero-length string, ".","@" and absence of spaces
    if(this.emailAddr == null || this.emailAddr.length == 0 || this.emailAddr.indexOf(".", 0) == -1 || this.emailAddr.indexOf("@", 0) == -1 || this.emailAddr.indexOf(" ", 0) > -1)
    {
        this.message="Make sure the email address does not contain any spaces and is otherwise valid.";
        this.valid = false;
        return;
    }
    //get the local part of the email address
    regex=/(^\w{1,}\.?\w{1,})@/;
    _match = regex.exec(this.emailAddr);
    if(_match){user=RegExp.$1;}
    else
    {
        this.message="Make sure the user name is at least two characters, does not begin or end with a period (.), or is not otherwise invalid.";
        this.valid = false;
        return;
    }
    //get the domain part of the email address
    regex=/@(\[\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}\])$/;
    _match = regex.exec(this.emailAddr);
    if(_match){domain=RegExp.$1;this.valid=true;}    
    else
    {
        regex=/@(\w{2,}\.(\w{2,}\.)?[a-zA-Z]{2,3})$/;
        _match = regex.exec(this.emailAddr);
        if(_match){domain=RegExp.$1;}
        else
        {
            this.message="The domain portion of the email has less than 2 characters or was otherwise invalid.";
            this.valid=false;
            return;
        }
    }
    this.valid=true;
}
//make validate() an instance method of the Email object
Email.prototype.validateEmail=validateEmail;

function checkEmailAddr(elem)
{
    $("#errEmail").hide();
    $(elem).attr("valid", "true");
    var chkVal = $(elem).val();
    if(chkVal.length > 0)
    {                
        var eml = new Email(chkVal);
        eml.validateEmail();
        var rtg = eml.valid;    
        if(!rtg)
        {
			$("#errEmail").hide().html(eml.message).css({color:_errColor}).show();
        	$(elem).attr("valid", "false");
        	$("#btnSubmit").attr("disabled","disabled");
        }
        if(rtg)
        {
            url="ajax.aspx?chkEmail=1&email=" + encodeURIComponent(chkVal);
			$.get(url, function(xhr){isEmailAvailable(xhr);});           
        }
    }
}

function isEmailAvailable(xhr)
{
    var jsonObj = returnJson(xhr);
    if(parseInt(jsonObj[0]["returnValue"]) > 0)
    {
		var msg = "This email address is already in the system. Please try again, or click <a href=\"index.aspx\">here</a> to login.";
		msg += "<br/><br/><a href=\"lostcredentials.aspx\">Forgot your username or password?</a>";
    	$("#errEmail").hide().html(msg).show();
    }    
}

/* cancels the account creation process. Deletes the records in MyUCR_Login, MyUCR_Info tables if needed */
function cancelAccount()
{
    var msg = "Are you sure you want to cancel?";
    if(confirm(msg)){
        var hidMyUCRID = $UCR('hidMyUCRID');
        if(hidMyUCRID.value.length > 0)
        {
            var MyUCRID = hidMyUCRID.value;
            url = "ajax.aspx?cancelAccount=1&MyUCRID=" + MyUCRID;
            ajaxCall("GET",url,"cancelAccountFinish()");
        }
    }
}
function cancelAccountFinish()
{
    xmlReturnVal = req.responseXML;
    returnValue = xmlReturnVal.getElementsByTagName("returnValue")[0];
    if(returnValue.childNodes[0].data == "1")
    {
        document.location.href = "landing.aspx";
    }
}

function cancelAccountQuiet()
{
    var hidMyUCRID = $UCR('hidMyUCRID');
    if(hidMyUCRID.value.length > 0)
    {
        var MyUCRID = hidMyUCRID.value;
        url = "ajax.aspx?cancelAccount=1&MyUCRID=" + MyUCRID;
        ajaxCall("GET",url,"cancelAccountFinish()");
    }
}

function validDOB(dob)
{	
	if(dob.length != 8)
		return false;

	for(var i = 0;i<dob.length;i++)		
	{
		if(isNaN(dob.charAt(i)))
			return false;
	}
	return true;
}

function updateAccount()
{
	//updates the account tables when user clicks the Create Account button
	$("#errDOB").hide();
   	$("#errUsername").hide();	
	$("#errPassword").hide();   	
	$("#errFName").hide();	
	$("#errLName").hide();
	var ddl;
	var rtg = true;
    var MyUCRID = $("#MyUCR_cphMain_hidMyUCRID").val();    
    if(MyUCRID.length > 0)
    {     
        var fName = $("input.txtFirstName").val(); 
        if(fName.length <= 0) 
        {
        	rtg = false;
        	$("#errFName").html("Enter your first name").show();
        }
        
        var lName = $("input.txtLastName").val(); 
		if(lName.length <= 0)
        {
        	rtg = false;
        	$("#errLName").html("Enter your last name").show();
        }
		var mi = $("input.txtMI").val();

		ddl = $("select.ddlSuffix")[0];
		var suf = ddl.options[ddl.selectedIndex].value;
		
		var email = $("input.txtEmail").val();
		if(email.length <= 0)
        {
        	rtg = false;
        	$("#errEmail").html("Enter your email address").show();
        }

        var username = $("input.txtUsername").val();
		if(username.length <= 0)
        { 	
        	rtg = false;
        	$("#errUsername").show();
        }
        var password = $("input.txtPass1").val();
		if(password.length <= 0)
        {
        	rtg = false;
        	$("#errPassword").html("Enter a password").show();
        }
		
		ddl = $("select.ddlDOBYear")[0];
        var dob = ddl.options[ddl.selectedIndex].value;

        ddl = $("select.ddlDOBMonth")[0];        
        dob += ddl.options[ddl.selectedIndex].value;

        ddl = $("select.ddlDOBDay")[0];        
        dob += ddl.options[ddl.selectedIndex].value;
        if(!validDOB(dob))
        {
        	rtg = false;
        	$("#errDOB").html("Please enter a valid birthdate").show();
        }
        var gender = "";
        if($("#MyUCR_cphMain_rblGender_0").checked){gender="m";}
        if($("#MyUCR_cphMain_rblGender_1").checked){gender="f";}
        
        var addr1 = $("input.txtAddr1").val();
        var addr2 = $("input.txtAddr2").val();
        var city = $("input.txtCity").val();
        
        var state;
        ddl = $("select.ddlState")[0];
        if(ddl.selectedIndex > -1)
			state = ddl.options[ddl.selectedIndex].value;
        
        var zip;
        ddl = $("select.ddlZips")[0];
        if(ddl.selectedIndex > -1)
        	zip = ddl.options[ddl.selectedIndex].value;
        
        if($("input.txtOtherZipcode").css("style") != null && $("input.txtOtherZipcode").css("style").indexOf("block") >= 0){ zip = $("input.txtOtherZipcode").val();}        
        var phone = $("input.txtPhone").val();        
        var cellphone = $("input.txtCellPhone").val();
        var txtMsg = "false";if($("#MyUCR_cphMain_chkTxtMessage").attr("checked") != null){txtMsg = "true";}
        
		var describesYou;
        ddl = $("select.ddlDescribesYou")[0];
        if(ddl.selectedIndex > -1)
        	describesYou = ddl.options[ddl.selectedIndex].value;
        
		var enterSemester;
        ddl = $("#MyUCR_cphMain_ddlUCRTerm")[0];
        if(ddl.selectedIndex > -1)
        	enterSemester = ddl.options[ddl.selectedIndex].value;        
        
		var enterYear;
        ddl = $("#MyUCR_cphMain_ddlUCREnterYear")[0];
        if(ddl.selectedIndex > -1)
        	enterYear = ddl.options[ddl.selectedIndex].value;
        if(rtg)
        {
	        var url = "ajax_post.aspx";
	        var postVals = "finishAccount=" + MyUCRID + "&fName=" + encodeURIComponent(fName) + "&lName=" + encodeURIComponent(lName) + "&mi=" + encodeURIComponent(mi);
	        postVals += "&suffix=" + encodeURIComponent(suf) + "&email=" + encodeURIComponent(email) + "&username=" + encodeURIComponent(username) + "&pass=" + encodeURIComponent(password);
	        postVals += "&dob=" + dob + "&gender=" + gender + "&addr1=" + encodeURIComponent(addr1) + "&addr2=" + encodeURIComponent(addr2);
	        postVals += "&city=" + encodeURIComponent(city) + "&state=" + state + "&zip=" + encodeURIComponent(zip) + "&phone=" + encodeURIComponent(phone);
	        postVals += "&cellphone=" + encodeURIComponent(cellphone) + "&txtMsg=" + txtMsg + "&describesYou=" + describesYou;  
	        postVals += "&enterSemester=" + enterSemester + "&enterYear=" + enterYear + "&v21=0";      
			$.post(url, postVals, function(xhr){updateAccountFinish(xhr);});
        }
        else
		{ 
			eMsg("Please check your entries.",_errColor,'globalErr');		
		}
    }
}

function updateAccountFinish(xhr)
{
    //if successful on creating the account, ajax.cs will set the authentication session vars, then return "1"
    //if returnValue == 1, go to the landing page
    var goBack = $("#MyUCR_cphMain_hidGoBack").val();
    var jsonObj = returnJson(xhr);
    var retVal = jsonObj[0]["returnValue"];
    if(parseInt(retVal) == 2)
    {
    	document.location.href="landing.aspx";
    }
	else
	{ 
		eMsg("We're sorry, an error occured. Please check your entries.",_errColor,'globalErr');		
	}
}

function validateOrigPassword(elem)
{
    var myUCRID = $("#MyUCR_hidMyUCRID").val();
    var origPW = $(elem).val();
    if(myUCRID.length > 0 && origPW.length > 0)
    {
        url = "ajax.aspx?chkOrigPW=" + encodeURIComponent(origPW) + "&id=" + myUCRID;
        $.get(url, function(xhr){validOrigPassword(xhr);});
    }
}
function validOrigPassword(xhr)
{       
    var jsonObj = returnJson(xhr);
    var retVal = jsonObj[0]["returnValue"];    
    $("#MyUCR_cphMain_hidInvalidPW").val(retVal);
    if(parseInt(retVal) != 1)
        eMsg("This is not your current password, please try again.", _errColor, "errPassword");
}

function ChangePW()
{	
	//allows user to change their password
	var badPW = $("#MyUCR_cphMain_hidInvalidPW").val();
	var origPW = $("#MyUCR_cphMain_txtOrigPassword").val();
	var pass1 = $("#MyUCR_cphMain_txtPass1").val();
	var pass2 = $("#MyUCR_cphMain_txtPass2").val();	
    var myUCRID = $("#MyUCR_hidMyUCRID").val();
    	
	if(badPW == "1" && pass1.length >= 6 && pass1 == pass2)    
    {           
        var url = "ajax.aspx?chgPW=" + encodeURIComponent(pass1) + "&id=" + myUCRID + "&origPW=" + encodeURIComponent(origPW);
        $.get(url, function(xhr){passwordChanged(xhr);});        
    }
}

function passwordChanged(xhr)
{
    //notification of changing password
    var jsonObj = returnJson(xhr);
    var retVal = jsonObj[0]["returnValue"];    
    $("#MyUCR_cphMain_hidInvalidPW").val("0");
    if(parseInt(retVal) != 1)
        eMsg("We're sorry. Something went wrong, please try again.", _errColor, "errPassword");
    else
    {
        eMsg("Your password has been changed.", _successColor, 'pwChanged');  
        $("#MyUCR_cphMain_txtPass1").val("");
        $("#MyUCR_cphMain_txtPass2").val("");
        $("#MyUCR_cphMain_txtOrigPassword").val("");
    }
}

function updateProfile()
{
	//updates the users profile information from the My Profile page
    $("#errDOB").hide();
    var rtg = true;
    var MyUCRID = $("#MyUCR_hidMyUCRID").val();
    if(MyUCRID.length <= 0)
        return;
    
    var fName = $("#MyUCR_cphMain_txtFirstName").val();        
    var lName = $("#MyUCR_cphMain_txtLastName").val();    
    var mi = $("#MyUCR_cphMain_txtMI").val();
    
    var ddl = $("#MyUCR_cphMain_ddlSuffix")[0];
    var suf = ddl.options[ddl.selectedIndex].value;
    
    var email = $("#MyUCR_cphMain_txtEmail").val();
    
    ddl = $("#MyUCR_cphMain_ddlDOBYear")[0];
    var y = ddl.options[ddl.selectedIndex].value;
    ddl = $("#MyUCR_cphMain_ddlDOBMonth")[0];
    var m = ddl.options[ddl.selectedIndex].value;
    ddl = $("#MyUCR_cphMain_ddlDOBDay")[0];
    var d = ddl.options[ddl.selectedIndex].value;
    
    if(y.length > 0 && m.length > 0 && d.length > 0)
        var dob = y + m + d;
    
    if(!validDOB(dob))
    {
        rtg = false;
	    $("#errDOB").html("Please enter a valid birthdate").show();
    }   
    var gender = "";
    if($("MyUCR_cphMain_rblGender_0").attr("checked") != undefined)
        gender = "m";
    if($("MyUCR_cphMain_rblGender_1").attr("checked") != undefined)
        gender = "f";
    
    var addr1 = $("#MyUCR_cphMain_txtAddr1").val();
    var addr2 = $("#MyUCR_cphMain_txtAddr2").val();
    var city = $("#MyUCR_cphMain_txtCity").val();
    
    ddl = $("#MyUCR_cphMain_ddlState")[0];
    var state = "";
    var stateArr = ddl.options[ddl.selectedIndex].value.split('~'); 
    if(stateArr.length == 2)
        state = stateArr[0];
    
    var city = $("#MyUCR_cphMain_txtCity").val();
    
    ddl = $("#MyUCR_cphMain_ddlZips")[0];
    var zip = ddl.options[ddl.selectedIndex].value;
    var otherZip = $("#MyUCR_cphMain_txtOtherZipcode")[0];
    if(otherZip.style.display != "none" && otherZip.value.length > 0)
        zip = otherZip.value.length;    
    
    var phone = $("#MyUCR_cphMain_txtPhone").val();    
    var cellphone = $("#MyUCR_cphMain_txtCellPhone").val();
    
    ddl = $("#MyUCR_cphMain_ddlDescribesYou")[0];
    var describesYou = ddl.options[ddl.selectedIndex].value;
    
    var url = "ajax_post.aspx";
    var postVals = "updateAccount=" + MyUCRID + "&fName=" + encodeURIComponent(fName) + "&lName=" + encodeURIComponent(lName) + "&mi=" + encodeURIComponent(mi);
    postVals += "&suf=" + encodeURIComponent(suf) + "&email=" + encodeURIComponent(email);
    postVals += "&dob=" + encodeURIComponent(dob) + "&gender=" + encodeURIComponent(gender) + "&addr1=" + encodeURIComponent(addr1) + "&addr2=" + encodeURIComponent(addr2);
    postVals += "&city=" + encodeURIComponent(city) + "&state=" + state + "&zip=" + encodeURIComponent(zip) + "&phone=" + encodeURIComponent(phone);
    postVals += "&cellphone=" + encodeURIComponent(cellphone) + "&describeYou=" + encodeURIComponent(describesYou);
    
    if(rtg)
        $.post(url, postVals, function(xhr){updateProfileFinish(xhr);});        
  
}

function updateProfileFinish(xhr)
{
	//profileChanged
    //if successful on creating the account, ajax.cs will set the authentication session vars, then return "2"
    //if returnValue == 2, go to the landing page
    var jsonObj = returnJson(xhr);
    var returnValue = jsonObj[0]["returnValue"];
    
    if(returnValue.length > 0)
    {
        if(returnValue == "1")
        {
            var myDiv = 'ajaxStatus';
            var pg = document.location.href.split('/');
            if(pg[pg.length -1].indexOf("profile") > -1)
                myDiv = 'profileChanged';
            eMsg("Your profile has been updated.", _successColor, myDiv);  
            //loop through the returned query string to update the hidden values          
            UpdateProfileLabels(jsonObj);
            return;
        } 
        if(returnValue == "2")
        {
            if($UCR('hidGoBack').value != "")
            {
                var u = $UCR('hidGoBack').value + '?status=1&id=' + $UCR('hidMyUCRID').value;
                if($UCR('hidEvent').value != "")
                {
                    u = u + '&eventid=' + $UCR('hidEvent').value;
                }
                document.location.href=u;
            }
            else
            {
                document.location.href="landing.aspx";
            }
            
            return;
        }
        if(returnValue != "1" || returnValue != "2")
        {
           if($UCR('hidGoBack').value != "")
           {
                var u = $UCR('hidGoBack').value + '?status=0&id=' + $UCR('hidMyUCRID').value;
                document.location.href=u;
           }
           else
           {
                eMsg("We're sorry, an error occured.",_errColor,'globalErr');
           }
           return;
        }
    }
}

function UpdateProfileLabels(jsonObj)
{
    for(var lbl in jsonObj[0])
    {
        var elem = $UCR(lbl);
        if(elem != null)
            elem.value = jsonObj[0][lbl];
    }    
}

function calculation(id)
{
	// Set Variables
	var ucrcost = 22407;
	var efc = $UCR('efc').value;
	var newstring = parseFloat(efc).toString(); 
	var InpValid=1; 
	
	if (efc.length == newstring.length && newstring != "NaN") 
	{ 		
		//Do Calculations
	    var eligibility = ucrcost - efc
	
	    if (eligibility <= 0) 
		{
			$UCR('zero').style.display = "block";
			$UCR(id).innerHTML = '0';
		} 
	    else 
		{
			$UCR('zero').style.display = "none";
			$UCR(id).innerHTML = eligibility;
		}
		
	} 
    else 
	{ 
	    $UCR(err).innerHTML = "Please enter an amount that is rounded to the nearest whole dollar and does not contain commas or dollar signs.";
	    InpValid=0; 
	    $UCR(id).innerHTML = 'N/A';
	}	
}