var checkflag = "false";
var currentXML;
var coockieDelim = "||||";
var coockieValDelim = "||V||";
var allCheckBoxes = new Array();   
var blankFieldIndicator = '*^^blank^^*';
var autoFillBill = false;
var currentid;
var currentEmail;
//var resultText;

var baseuristring = "" + document.location;
var baseuri = "http://" + baseuristring.substring(baseuristring.indexOf('//')+2, baseuristring.indexOf('/',baseuristring.indexOf('//')+2));
// Should the secure pages start with https:// ?
var securebaseuri = "http://" + baseuristring.substring(baseuristring.indexOf('//')+2, baseuristring.indexOf('/',baseuristring.indexOf('//')+2));
var debugmode = true;

function debug(str, xmlbool){
	if (debugmode)
	{
		if (str == null) strXml = 'No value passed to debug function';
		if(xmlbool && str.xml != undefined)
		{
			var strXml = str.xml;
		}
		else if (xmlbool)
		{
			var serializer = new XMLSerializer();
			var strXml = serializer.serializeToString(str);
		}
		else if (str)
		{
			var strXml = str;
		}
		//console.log(str);
		prompt('debug in function: ' + arguments.callee.caller.name, strXml);
	}
}

Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
}


// remember me from login
function checkRememberMe(){
	if(getCookie("remember") == 1){
			var uri = baseuri + "/fccla/~fccla/login";
    		var method = "POST";
		 		var username =getCookie("username");
    		var password = getCookie("password");
    		var body = "";
    		body += "<User>";
				body += "<UserName>" + username + "</UserName>";
				body += "<Password>" + password + "</Password>";
				body += "</User>";
   			var xmlHttpRequest=null;
    		try{
      			xmlHttpRequest=new XMLHttpRequest();
    		} catch (e) {
     			try {
        		xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
      		} catch (e) {
       		 	xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
      		}
    		}        
    		if (xmlHttpRequest) {
     			xmlHttpRequest.open(method, uri, false, username, password);
     		 	xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     		 	body=escape(body); 
     		 	body=body.replace(/\+/g,"%2B");
     			body = "post=" + body;
      		xmlHttpRequest.send(body)
     	 		if(xmlHttpRequest.status != 200) {
        		alert(xmlHttpRequest.status);
      		}
      		var resultXml = xmlHttpRequest.responseXML;
				userid = SelectSingleNode(resultXml,"//User/UserId");
				FCCLAID = SelectSingleNode(resultXml,"//User/FCCLAID");
				var ChapterId = SelectSingleNode(resultXml,"//User/ChapterId");
				if(userid) {
					setCookie('userId',userid.firstChild.nodeValue,30);
					document.location='Main_Menu.htm?userid='+userid.firstChild.nodeValue;
				} else {
					document.getElementById("loginError").innerHTML= "Your user name or password is incorrect. Please try again.";
					return;
				}
				if(ChapterId.firstChild != null) {	
					setCookie('ChapterId',ChapterId.firstChild.nodeValue,30);
				}
				if(FCCLAID.firstChild != null) {	
					setCookie('FCCLAID',FCCLAID.firstChild.nodeValue,30);
				}
	    } else {
      	alert("unable to create request object");
   		}
    	//f.method.selectedIndex=0;
    	return ;
	} else {
		return;
	}
}

function getContactByLastName(){
  var userrole = document.getElementById("userrole").value;
  var lastnamestart = document.getElementById("contact").value;
	document.location='Admin_Manage_Users.htm?lastnamestart='+lastnamestart+"&role="+userrole;
}

function getContactsByLastName(url){
	var fl = getCookie('fcclaidlookup');
	if (fl != null && fl != "")
	{
		delCookie('fcclaidlookup');
	}
	var state = "";
	var tempurl = url;
	if (document.getElementById("state"))
	{
		var state = document.getElementById("state").value;
		setCookie("state",state,30);
		state = "&state=" + state;
	}
	else
	{
		tempurl = url.substring(6);
		//state is not working for state adviser - no cookie
		state = "&state=" + getCookie("state");
	}
	var lastnamestart = document.getElementById("contact").value;
	setCookie("lastnamestart",lastnamestart,30);
	var status = "";
	if (tempurl.split("_")[4] == 'Students')
	{
		status = "affiliated";
	}
	else if (tempurl.split("_")[4] == 'Unaffiliated')
	{
		status = "unaffiliated";
	}
	setCookie("status",status,30);
	status = "&status=" + status;
	if (document.getElementById("state") && (document.getElementById("state").value == "Select State" || lastnamestart == ""))
	{
		alert("You must select a state and lastname character to use this search.");
	}
	else if (lastnamestart == "")
	{
		alert("You must select a lastname character to use this search.");
	}
	else
	{
		document.location = url + '.htm?userid=' + getCookie("userId") + '&lastnamestart=' + lastnamestart + state + status;
	}
	return;
}

function getContactByStatus(){
  var userrole = document.getElementById("userrole").value;
  var lastnamestart = document.getElementById("contact").value;
	var status = document.getElementById("status").value;
	document.location='Admin_Manage_Users.htm?lastnamestart='+lastnamestart+"&role="+userrole+"&status="+status;
}

function getStateContactByLastName(){
  var lastnamestart = document.getElementById("lastnamestart").value;
	document.location='State_Manage_Users.htm?lastnamestart='+lastnamestart+"&userid="+getCookie('userId');
}

function gotoChangePassword(){
  document.location = "Admin_Change_User_Password.htm?contactid=" + contactid;
}

function goToChapterState(){
  var state = document.getElementById("state").value;
  var status = document.getElementById("status").value;
	//check to make sure if status is A that a state has been selected
	if (status == 'a' && state == 'Select State'){
		alert('Please select a state to view active chapters.');
	} else {
		document.location="Admin_Manage_Chapters.htm?state="+state+"&status="+status;
	}
}

function goToAdminState(status){
  var state = document.getElementById("state").value;
  //var status = document.getElementById("status").value;
	//check to make sure if status is A that a state has been selected
	//if (status == 'a' && state == 'Select State'){
	//	alert('Please select a state to view active chapters.');
	//} else {
	if (status == 'affiliated')
	{
		document.location="Admin_Manage_Chapter_Membership_Students.htm?state="+state;
	}
	else
	{
		document.location="Admin_Manage_Chapter_Membership_Unaffiliated.htm?state="+state;
	}
	//}
}

function goToInvoiceId() {
	var chapterid = document.getElementById("chapterid").value;
	document.location="Admin_Receive_Payments.htm?fcclaid=" + chapterid;
}

function goToStateInvoice() {
	var state = document.getElementById("stateid").value;
	document.location="Admin_Receive_Payments.htm?statelookup=" + state;
}

function goToSchoolState(){
  var state = document.getElementById("state").value;
  setCookie('stateVal',state,30);
  var userid = getCookie('userId');
	document.location='Admin_Manage_Schools.htm?state='+state;
}

function checkCountry(){
	var f = document.currentForm;
	var mailingcountry = document.getElementById("mailingaddressInfo_country").value;
	var fields = new Array("mailingaddressInfo_state", "mailingaddressInfo_zip", "billingaddressInfo_state", "billingaddressInfo_zip");
	if (mailingcountry == "US")
	{
		for (var i=0; i<fields.length; i++)
		{
			document.getElementById(fields[i]).disabled = false;
			document.getElementById(fields[i]).className = 'required';
		}
	}
	else
	{
		for (var i=0; i<fields.length; i++)
		{
			document.getElementById(fields[i]).disabled = true;
			document.getElementById(fields[i]).className = '';
			document.getElementById(fields[i]).value = '';
			if (fields[i].substring(fields[i].indexOf("_")+1) == "state")
			{
				//This value might be able to use the variable 'state' <- global
				document.getElementById(fields[i]).value = 'Select State';
			}
		}
	}
}

// login and return current state, user id, chapter id, country, fccla id
function loginRequest() {      
    var f=document.login;
    var uri = baseuri + "/fccla/~fccla/login";
    var method = "POST";
    var username = f.userName.value;
    var password = f.password.value;
    var rm = f.remember;
    if(rm.checked)
    {
    	setCookie('remember',1,30);
    	setCookie('username',username,30);
    	setCookie('password',password,30);
    }
    var body = "";
    body += "<User>";
	  body += "<UserName>" + username + "</UserName>";
	  body += "<Password>" + password + "</Password>";
	  body += "</User>";
    var xmlHttpRequest=null;
    try
    {
      xmlHttpRequest=new XMLHttpRequest();
    }
    catch (e)
    {
      try
      {
        xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e)
      {
        xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }        
    if (xmlHttpRequest)
    {
      xmlHttpRequest.open(method, uri, false, username, password);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      body=escape(body); 
      body=body.replace(/\+/g,"%2B");
      body = "post=" + body;

      xmlHttpRequest.send(body)
      if(xmlHttpRequest.status != 200)
      {
        alert(xmlHttpRequest.status);
      }
			var resultXml = xmlHttpRequest.responseXML;
			var userid = SelectSingleNode(resultXml,"//User/UserId");
			var FCCLAID = SelectSingleNode(resultXml,"//User/FCCLAID");
			var ChapterId = SelectSingleNode(resultXml,"//User/ChapterId");
			var country = SelectSingleNode(resultXml,"//User/Country");
			var state = SelectSingleNode(resultXml,"//User/State");
			var chapterName = SelectSingleNode(resultXml,"//User/ChapterName");
			var UnaffiliatedMembers = SelectSingleNode(resultXml,"//User/UnaffiliatedMembers");	
			var unaffiliatedMembersMessage = SelectSingleNode(resultXml,"//User/UnaffiliatedMembersMessage");	
			var primaryAdviser = SelectSingleNode(resultXml,"//User/PrimaryAdviser");	
			var primaryAdviserMessage = SelectSingleNode(resultXml,"//User/PrimaryAdviserMessage");
			var roleId = SelectSingleNode(resultXml,"//User/RoleId");
			var isMiddleLevel = SelectSingleNode(resultXml,"//User/IsMiddleLevel");
			
			if(chapterName){
				if(chapterName.firstChild != null){	
					setCookie('chapterName',chapterName.firstChild.nodeValue,30);
				}
			}
			if(ChapterId){
				if(ChapterId.firstChild != null){	
					setCookie('ChapterId', ChapterId.firstChild.nodeValue, 30);
				}
			}
			if(FCCLAID){
				if(FCCLAID.firstChild != null){	
					setCookie('FCCLAID',FCCLAID.firstChild.nodeValue,30);
				}
			}
			if(state){
				if(state.firstChild != null){	
					setCookie('state',state.firstChild.nodeValue,30);
				}
			}
			if(country){
				if(country.firstChild != null){	
					setCookie('country',country.firstChild.nodeValue,30);
				}
			}
			if(country){
				if(country.firstChild == null){	
					setCookie('country','US',30);
				}
			}
			if(isMiddleLevel){
				if(isMiddleLevel.firstChild != null){	
					setCookie('isMiddleLevel',isMiddleLevel.firstChild.nodeValue,30);
				}
			}
    } else {
      alert("unable to create request object");
    }
    f.method.selectedIndex=0;
    
		if (typeof(userid) != 'undefined'){
			if(userid){
			//debug("role: " + roleId + " primaryAdviser: " + primaryAdviser);
			//alert("role: " + roleId.firstChild.nodeValue + " primaryAdviser: " + primaryAdviser.firstChild.nodeValue);
			//return;
				if(roleId.firstChild.nodeValue != '1' || (roleId.firstChild.nodeValue == '1' && primaryAdviser.firstChild.nodeValue == 'True')){
					if(UnaffiliatedMembers){
						if(UnaffiliatedMembers.firstChild != null){	
							if(UnaffiliatedMembers.firstChild.nodeValue == 'True'){
								alert(unaffiliatedMembersMessage.firstChild.nodeValue);
								//alert('Account currently has Unaffiliated Members');
							}
						}
					}
					setCookie('userId',userid.firstChild.nodeValue,30);
					document.location='Main_Menu.htm?userid='+userid.firstChild.nodeValue;
				}
				else
				{
					document.getElementById("loginError").innerHTML = primaryAdviserMessage.firstChild.nodeValue;
				return;
				}
			}
			else{
				document.getElementById("loginError").innerHTML = "Your user name or password is incorrect. Please try again.";
				return;
			}
		}
    return;
  }  
  
function logout(){
	delCookie('remember');
  delCookie('username');
  delCookie('password');
	document.location =baseuri + "/davinci/fccla/default.htm";
}

function getContactByFcclaID(){
 var fcclaid = document.getElementById('fcclaid').value;
 document.location = "State_Adviser_Manage_Chapter_Membership_Students.htm?fcclaid="+fcclaid;
}
// credit card errors
function getErrors(quid){
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      uri = baseuri + "/fccla/~fccla/store/" +quid;
			if(uri.indexOf ("?") != -1){
        	uri = uri + "&rand=" + new Date().getTime()
      	}	else {
        	uri = uri + "?rand=" + new Date().getTime()
      	}
      xmlHttpRequest.open("GET", uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      body="";
      xmlHttpRequest.send(body)
      if(xmlHttpRequest.status != 200)
      {
        //alert(xmlHttpRequest.status);
      }else{
       currentXML = xmlHttpRequest.responseXML;          
      }      
      success = true;
    }
    else
    {
      alert("unable to create request object");
      success =  false;
    }
    var mainError = SelectSingleNode(currentXML,"//importerrors/fatalerror");
    if(mainError){
    	var errorResponse = "<h3 class='mainError'>"+mainError.firstChild.nodeValue+"</h3><br/>";
    }
    else{
    	var errorResponse = "";
    }
    var errors=xmlHttpRequest.responseXML.getElementsByTagName("importerror");
    for(var i=0;i<errors.length;i++){		
			errorResponse+="<p class='subError'>"+errors[i].firstChild.nodeValue+"</p><br/>";
		}	
		document.getElementById("errors").innerHTML= errorResponse;
	    
}

function getFCCLAID(){
	document.getElementById("fcclaid").innerHTML = getCookie("FCCLAID");
}

function setUserAdminRole(){
  document.getElementById('userroleid').value = '5';
}

// sets the fee id in a cookie
function editFee(id, url){
  setCookie('feeid',id,30); 
  document.location = baseuri +'/davinci/fccla/'+ url;
}

function stripTimeFromDate(){
  var lateDate = document.getElementById('lateDate');
  if(lateDate){
    lateDate.value = lateDate.value.split(" ")[0];
  }
  var dueDate = document.getElementById('dueDate');
  if(dueDate){
    dueDate.value = dueDate.value.split(" ")[0];
  }
}

function getSchoolPage(){
 var schoolid = document.getElementById('schoolInfo_schoolid').value;
 document.location = "Chapter_Adviser_School_Information_Update_Request.htm?schoolid="+schoolid;
}

function getManageFees(){ 
  var id = document.getElementById('membershiptype').value
  setCookie('feetypeid',id,30); 
  document.location = baseuri + "/davinci/fccla/Admin_Manage_Fees.htm?feetypeid="+id;
}

function setFeeSelect(){
	document.getElementById(getCookie('feetypeid')).selected = true;
}
function downloadPDF(type, guid){
	if(type == 'invoice')
	{
		document.location = baseuri + "/davinci/createpdf.aspx?url=davinci/fccla/invoice.htm?userid="+getCookie("userId")+"%26invoiceid="+guid+"&downloadName=Invoice";
	}
	if(type == 'statement')
	{
		document.location = baseuri + "/davinci/createpdf.aspx?url=davinci/fccla/statement.htm?userid="+ getCookie('userId')+"&downloadName=Statement";
	}

}

function downloadStatement(type, guid){
	if(type == 'invoice')
	{
		document.location = baseuri + "/davinci/createpdf.aspx?url=davinci/fccla/invoice.htm?userid="+getCookie("userId")+"%26invoiceid="+guid;
	}
	if(type == 'statement')
	{
		document.location = baseuri + "/davinci/createpdf.aspx?url=davinci/fccla/state-statement.htm?state="+ getCookie('state');
	}

}

function getInvoice(){
  
  //userid = dde67591-db67-45f6-8f75-67ea63ddc82a
  //invoiceid = 1ab3c549-fa09-4014-aad7-91cced699d5c
  //davinci/fccla/invoice.htm?userid=dde67591-db67-45f6-8f75-67ea63ddc82a&invoiceid=1ab3c549-fa09-4014-aad7-91cced699d5c;
	//http://pilotmembership.fccla.com/davinci/createpdf.aspx?url=http://pilotmembership.fccla.com/davinci/fccla/invoice.htm?userid=dde67591-db67-45f6-8f75-67ea63ddc82a&invoiceid=1ab3c549-fa09-4014-aad7-91cced699d5c;
	document.location = baseuri + "/davinci/createpdf.aspx?url=davinci/fccla/invoice.htm?userid="+getCookie("userId")+"%26invoiceid="+getCookie("newInvoiceId")+"&downloadName=Invoice";
}

function viewInvoice(invoiceid) {
	document.location = baseuri + "/davinci/createpdf.aspx?url=davinci/fccla/invoice.htm?userid="+getCookie("userId")+"%26invoiceid="+invoiceid+"&downloadName=Invoice";
}

function getExcelInvoice(){
	getReportSimpleExcel('detailedinvoice','fccla-report-detailed-invoice','','invoice',getCookie("newInvoiceId"))
}

function getReportSimpleExcel(report, stylesheet, service, param, value){
	var servicename = 'report%3freportname=';	
	if (service != '' && typeof(service) != 'undefined'){
		servicename = '';
		report += '%3fx';
	}
	if (param != '' && typeof(param) != 'undefined'){
		param = '%26' + param + '=' + value;
	} else {
		param = '';
	}
	var reporturl = baseuri + "/fccla/xsltransform.aspx?xmlurl=fccla/~fccla/" + servicename + report + param + "&xslurl=davinci/fccla/stylesheets/" + stylesheet + ".xsl"; 
	//alert(reporturl);
	document.location = reporturl;
}

function getReportExcel(report, stylesheet, datesrequired, service, param, value){
	var startdate = $('#startdate').val();
  var enddate = $('#enddate').val();
	var state = getCookie('state');
	var servicename = 'report%3freportname=';
	if (datesrequired == 'true' && (startdate == '' || typeof(startdate) == 'undefined' || enddate == '' || typeof(enddate) == 'undefined'))
	{
		alert('You must select start and end dates to run this report');
		return;
	}
	if (param != '' && typeof(param) != 'undefined'){
		param = '%26' + param + '=' + value;
	} else {
		param = '';
	}
	if (service != '' && typeof(service) != 'undefined'){
		servicename = '';
		report += '%3fx';
	}
	var reporturl = baseuri + "/fccla/xsltransform.aspx?xmlurl=fccla/~fccla/" + servicename + report + "%26startdate=" + startdate + "%26enddate=" + enddate + param + "%26state=" + state + "&xslurl=davinci/fccla/stylesheets/" + stylesheet + ".xsl"; 
	//alert(reporturl);
	document.location = reporturl;
}

function getStateInvoice(){
	document.location = baseuri + "/davinci/createpdf.aspx?url=davinci/fccla/state_invoice.htm?userid="+getCookie("userId")+"%26invoiceid="+getCookie("newInvoiceId")+"&downloadName=Invoice";
}

function getStateAdviserReportPage(){
  document.location = "State_Adviser_Report.htm?state=" + getCookie('state');
}

function getStateAdviserReport(){
  var report = $('#reports').val();
  var startdate = $('#startdate').val();
  var enddate = $('#enddate').val();
  var state = getCookie('state'); 
  //alert(baseuri + "/davinci/createpdf.aspx?url=davinci/fccla/"+ report +".htm?state="+state+"%26startdate="+startdate+"%26enddate="+enddate)
  document.location = baseuri + "/davinci/createpdf.aspx?url=davinci/fccla/"+ report +".htm%3Fstate="+state+"%26startdate="+startdate+"%26enddate="+enddate+"&downloadName="+report;
	}
	
function getStateReportExcel(report, stylesheet, datesrequired, service, param, value){
	var startdate = $('#startdate').val();
  var enddate = $('#enddate').val();
	var state = getCookie('state');
	var servicename = 'report%3freportname=';
	if (datesrequired == 'true' && (startdate == '' || typeof(startdate) == 'undefined' || enddate == '' || typeof(enddate) == 'undefined'))
	{
		alert('You must select start and end dates to run this report');
		return;
	}
	if (param != '' && typeof(param) != 'undefined'){
		param = '%26' + param + '=' + value;
	} else {
		param = '';
	}
	if (service != '' && typeof(service) != 'undefined'){
		servicename = '';
		report += '%3fx';
	}
	var reporturl = baseuri + "/fccla/xsltransform.aspx?xmlurl=fccla/~fccla/" + servicename + report + "%26startdate=" + startdate + "%26enddate=" + enddate + param + "%26state=" + state + "&xslurl=davinci/fccla/stylesheets/" + stylesheet + ".xsl"; 
	//alert(reporturl);
	document.location = reporturl;
}
	
function getAdminReport(){
  var report = $('#reports').val();
  var startdate = $('#startdate').val();
  var enddate = $('#enddate').val();
  //alert(baseuri + "/davinci/createpdf.aspx?url=davinci/fccla/"+ report +".htm%3Fstartdate="+startdate+"%26enddate="+enddate)
	document.location = baseuri + "/davinci/createpdf.aspx?url=davinci/fccla/admin_"+ report +".htm%3Fstartdate="+startdate+"%26enddate="+enddate+"&downloadName="+report;
}

function getAdminReportExcel(report, stylesheet, datesrequired, service, param, value){
	var startdate = $('#startdate').val();
  var enddate = $('#enddate').val();
	var servicename = 'report%3freportname=';
	if (datesrequired == 'true' && (startdate == '' || typeof(startdate) == 'undefined' || enddate == '' || typeof(enddate) == 'undefined'))
	{
		alert('You must select start and end dates to run this report');
		return;
	}
	if (param != '' && typeof(param) != 'undefined'){
		param = '%26' + param + '=' + value;
	} else {
		param = '';
	}
	if (service != '' && typeof(service) != 'undefined'){
		servicename = '';
		report += '%3fx';
	}
	var reporturl = baseuri + "/fccla/xsltransform.aspx?xmlurl=fccla/~fccla/" + servicename + report + "%26startdate=" + startdate + "%26enddate=" + enddate + param + "&xslurl=davinci/fccla/stylesheets/" + stylesheet + ".xsl"; 
	//alert(reporturl);
	document.location = reporturl;
}

function getStatementView(type, guid){
  if(type == 'statement')
	{
		window.open(baseuri + "/davinci/fccla/state-statement.htm?state="+ getCookie('state'));
	}
	if(type == 'invoice')
	{
		window.open(baseuri + "/davinci/fccla/invoice.htm?userid="+getCookie("userId")+"&invoiceid="+guid);
	}
	
}

function getView(type, guid){
	if(type == 'invoice')
	{
		window.open(baseuri + "/davinci/fccla/invoice.htm?userid="+getCookie("userId")+"&invoiceid="+guid);
	}
	if(type == 'statement')
	{
	  //window.location = baseuri + "/davinci/fccla/statement.htm?userid="+ getCookie('userId');
		window.open(baseuri + "/davinci/fccla/statement.htm?userid="+ getCookie('userId'));
	}
	if(type == 'state-statement')
	{
	  //window.location = baseuri + "/davinci/fccla/statement.htm?userid="+ getCookie('userId');
		window.open(baseuri + "/davinci/fccla/state-statement.htm?state="+ getCookie('state'));
	}
}

function getChapterAdivserPage(){
	var userid = getCookie('userId');
	var chapterid = getCookie('ChapterId');
	document.location='Chapter_Adviser_Edit_Chapter_Properties.htm?userid='+userid+"&chapterid="+chapterid;
}

function getEditStudentPage(id){
	setCookie('contactid',id,30);
	var chapterid = getCookie('ChapterId');
	document.location='Chapter_Adviser_Edit_Student.htm?userid='+id+"&chapterid="+chapterid;
}

function editAdmin(id){
	setCookie('contactid',id,30);
	document.location='Admin_Edit_Administrator.htm?userid='+id;
}

function getEditStateAdviserStudentPage(id,chapterid){
	setCookie('contactid',id,30);
	//var chapterid = getCookie('ChapterId');
	document.location='State_Adviser_Edit_Student.htm?userid='+id+"&chapterid="+chapterid;
}

function getEditAdminStudentPage(id,chapterid){
	setCookie('contactid',id,30);
	// can't use cookie to get chapter id for admins (or probably states) - need another way
	//var chapterid = getCookie('ChapterId');
	document.location='Admin_Edit_Student.htm?userid='+id+"&chapterid="+chapterid;
}

function getAddStudentPage(){
	var userid = getCookie('userId');
	var chapterid = getCookie('ChapterId');
	document.location='Chapter_Adviser_Add_Students.htm?userid='+userid+"&chapterid="+chapterid;
}

// slavs function todo find?
function getNewGridXML(uri, id){
	var method = "GET";
    var xmlHttpRequest=null;
    try
    {
      xmlHttpRequest=new XMLHttpRequest();
    }
    catch (e)
    {
      try
      {
        xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e)
      {
        xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }        
    if (xmlHttpRequest)
    {
    	
      	uri = uri +  id;
      
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
      	//alert(getCookie('meetingid'));
		xmlHttpRequest.open(method, uri, true);
 		xmlHttpRequest.onreadystatechange=function() 
 		{
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
   				createCheckboxArray();
  			}
  		}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return ;
}

function getMeetingGridXML(uri){
  //uri = uri + getCookie('userId') +"?meetingid="+getCookie('meetingid');
	var method = "GET";
    var xmlHttpRequest=null;
    try
    {
      xmlHttpRequest=new XMLHttpRequest();
    }
    catch (e)
    {
      try
      {
        xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e)
      {
        xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }        
    if (xmlHttpRequest)
    {
    	
      uri = uri + getCookie('userId')+"&meetingid="+getCookie('meetingId');
      
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
      	//alert(getCookie('meetingid'));
			xmlHttpRequest.open(method, uri, true);
			xmlHttpRequest.onreadystatechange=function() 
			{
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
   				createCheckboxMeetingArray();
  			}
  		}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return ;
}

/* handle checkboxes */
function checkList(){
	var field = document.currentForm.list;
	if (checkflag == "false") {
  		for (i = 0; i < field.length; i++) {
  			field[i].checked = true;}
  			checkflag = "true";
  			return "Uncheck all"; 
  		}
	else {
  		for (i = 0; i < field.length; i++) {
  			field[i].checked = false; }
  			checkflag = "false";
  			return "Check all"; 
  		}
}

function check() {
	//alert(checkflag);
	var field = document.currentForm.list;
	if (checkflag == "false") {
  		for (i = 0; i < field.length; i++) {
  			field[i].checked = true;}
  			checkflag = "true";
  			selectAllCheckBoxes();
  			//return "Uncheck all"; 
  		}
	else {
  		for (i = 0; i < field.length; i++) {
  			field[i].checked = false; }
  			checkflag = "false";
  			deselectAllCheckBoxes();
  			//return "Check all"; 
  		}
}

function checkCheckboxes(){
	var field = document.currentForm.onOff
	var list = document.currentForm.list;
	if(field)
	{
	if(field.checked)
	{
		for (i = 0; i < list.length; i++) 
		{
			if(getSelectedValue(list[i].value))
			{
				list[i].checked = true;
			}
		}
	}
	else
	{
		for (i = 0; i < list.length; i++) 
		{
			if(!getSelectedValue(list[i].value))
			{
				list[i].checked = false;
			}
		}
	}
	}
}

function getSelectedValue(val){
	for(var i=0;i<allCheckBoxes.length;i++)
		{		
			if(allCheckBoxes[i][0] == val)
			{
				return allCheckBoxes[i][1];
			}
		}	
}
	
function createCheckboxArray(){
	for(var t=0;t<currentXML.firstChild.childNodes.length;t++)
		{	
			var val = currentXML.childNodes[0].childNodes[t].childNodes[0].firstChild.nodeValue;
			allCheckBoxes[allCheckBoxes.length] = [val, false];
		}	
}

function createCheckboxMeetingArray(){
	for(var t=0;t<currentXML.firstChild.childNodes.length;t++)
		{	
			var val = currentXML.childNodes[0].childNodes[t].childNodes[1].firstChild.nodeValue;
			allCheckBoxes[allCheckBoxes.length] = [val, false];
		}	
}

function selectAllCheckBoxes(){
	for(var i=0;i<allCheckBoxes.length;i++)
		{	
			allCheckBoxes[i][1] = true;
		}	
}

function deselectAllCheckBoxes(){
	for(var i=0;i<allCheckBoxes.length;i++)
		{	
			allCheckBoxes[i][1] = false;
		}	
}

function setCheck(val){
	//document.currentForm.onOff.checked = false;
	//checkflag = false;
	for(var i=0;i<allCheckBoxes.length;i++)
		{	
		  
			if(allCheckBoxes[i][0] == val)
			{
				if(allCheckBoxes[i][1])
				{
					allCheckBoxes[i][1] = false;
				}
				else
				{
					allCheckBoxes[i][1] = true;
				}
				
			}
		}	
	
}

function getCheckBox(){  
	
	if (allCheckBoxes.length == 0){
		alert('You must have unaffiliated members in order to affiliate.');
		return currentXML;
	}
	var j=0;
	for(var i=0;i<allCheckBoxes.length;i++)
	{
		
		if (!allCheckBoxes[i][1]) // if checkbox is not selected...
		{	
			var listValue = allCheckBoxes[i][0]; //get the checkbox id
			
			for(var t=0;t<currentXML.firstChild.childNodes.length;t++) //for each checkbox
			{	
				if(currentXML.childNodes[0].childNodes[t].childNodes[0].firstChild.nodeValue == listValue)
				{
					y=currentXML.childNodes[0].childNodes[t];
					currentXML.documentElement.removeChild(y);		
					j++;
				}
			}	
		}
	}	
	//alert ('j: ' + j + ' i: ' + i);
	if (j == i)
	{
		alert('You must select at least one student to affiliate.\n\nClick here to reload your page.');
	}
		return currentXML;
}

function getCheckBoxMeeting(){  
	
	for(var i=0;i<allCheckBoxes.length;i++)
		{
		if(!allCheckBoxes[i][1])
		{	
			var listValue = allCheckBoxes[i][0];	
			
			for(var t=0;t<currentXML.firstChild.childNodes.length;t++)
			{	
				if(currentXML.childNodes[0].childNodes[t].childNodes[1].firstChild.nodeValue == listValue)
				{
					y=currentXML.childNodes[0].childNodes[t];
					currentXML.documentElement.removeChild(y);					
				}
			}			
		}		
	}		
	return currentXML;
}


/* end handle checkboxes */


/* forms */

function parsePaymentXML(xml) {
    if( window.ActiveXObject && window.GetObject ) {
        var dom = new ActiveXObject( 'Microsoft.XMLDOM' );
        dom.loadXML( xml );
        return dom;
    }
    if( window.DOMParser ){
        return new DOMParser().parseFromString( xml, 'text/xml' );
       }
    throw new Error( 'No XML parser available' );
} 
    
function getFormXML(uri) {
    uri = baseuri + uri;
    var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      if(uri == baseuri + '/fccla/~fccla/chapterfee/chapterstate/')
      {
    		var state = getCookie("state");
     		uri = uri +  state;
      }
      else if(uri == baseuri + '/fccla/~fccla/school/' && currentid != null)
      {
    		//uri == baseuri + '/fccla/~fccla/school/'
				var school = currentid;
     		uri = uri +  school;
      }
			else if(uri == baseuri + '/fccla/~fccla/school/')
      {
    		var school = getCookie("schoolid");
     		uri = uri +  school;
      }
      else 
    	{
    		var userid = getCookie('userId');
     		uri = uri +  userid;
				var email = true;
     	}
    	if(uri.indexOf ("?") != -1)
			{
				uri = uri + "&rand=" + new Date().getTime()
			}
			else
			{
				uri = uri + "?rand=" + new Date().getTime()
			}
			//debug(uri);
			//code to modify
			xmlHttpRequest.open(method, uri, true);
			xmlHttpRequest.onreadystatechange=function() 
			{
				if (xmlHttpRequest.readyState==4) 
				{
					currentXML = xmlHttpRequest.responseXML;
					var f = document.currentForm;
					setFormValues(f,currentXML);
					if (email == true){
						getCurrentEmail();
					}
				}
			}
  		xmlHttpRequest.send(null);
    }
    else
    {
      alert("unable to create request object");
    }
    return ;
}

function getFormSchoolXML(uri) {
    //debug(uri)
    uri = baseuri + uri;
    var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
		    xmlHttpRequest.open(method, uri, true);
 		    xmlHttpRequest.onreadystatechange=function() 
 		  {
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
   				var f = document.currentForm;
				  setFormValues(f,currentXML);
  			}
  		}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return ;
}

function getContactFormXML(uri) {
    uri = baseuri + uri + contactid;
    var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
			if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
			xmlHttpRequest.open(method, uri, true);
			xmlHttpRequest.onreadystatechange=function() 
			{
				if (xmlHttpRequest.readyState==4) 
				{
					currentXML = xmlHttpRequest.responseXML;
					var f = document.currentForm;
					setFormValues(f,currentXML);
				}
			}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return;
}






function getPaymentXML(uri){
    var f = document.currentForm;
    var xml = parsePaymentXML(getCookie('xml'));
    currentXML = xml;
		//debug(currentXML, true);
		setFormValues(f,xml);
		
		document.getElementById('NationalDues').value = formatCurrency(document.getElementById('NationalDues').value)
    if(document.getElementById('StateDues'))
    {
        document.getElementById('StateDues').value = formatCurrency(document.getElementById('StateDues').value)
        document.getElementById('StateMinimum').value = formatCurrency(document.getElementById('StateMinimum').value)
    }
		document.getElementById('Fees').value = formatCurrency(document.getElementById('Fees').value)
		document.getElementById('NationalMinimum').value = formatCurrency(document.getElementById('NationalMinimum').value)
		//SelectSingleNode(currentXML,"//chapterpayment/Total");
		//alert(SelectSingleNode(currentXML,"//ChapterAdvisorsContributing").firstChild.nodeValue);
		if (SelectSingleNode(currentXML,"//ChapterAdvisorsContributing")){
			if (SelectSingleNode(currentXML,"//ChapterAdvisorsContributing").firstChild.nodeValue != 'true'){
				document.getElementById('ChapterAdvisorContributionFee').value = '0';
			}
		}
		if (SelectSingleNode(currentXML,"//NationalAdvisorsContributing")){
			if (SelectSingleNode(currentXML,"//NationalAdvisorsContributing").firstChild.nodeValue != 'true'){
				document.getElementById('NationalAdvisorContributionFee').value = '0';
			}
		}
		document.getElementById('NationalAdvisorContributionFee').value = formatCurrency(document.getElementById('NationalAdvisorContributionFee').value)
    if(document.getElementById('ChapterAdvisorContributionFee'))
    {
        document.getElementById('ChapterAdvisorContributionFee').value = formatCurrency(document.getElementById('ChapterAdvisorContributionFee').value)
    }
		document.getElementById('Total').value = formatCurrency(document.getElementById('Total').value)
		
		//alert(document.getElementById('Total').value); --> 0.00
		// if (document.getElementById('Total').value == '0.00'){
			// document.getElementById('NationalAdvisorContributionFee').value = '0.00';
			// document.getElementById('ChapterAdvisorContributionFee').value = '0.00';
		// }
}

function getStatePaymentXML(uri){
    var f = document.currentForm;
    var xml = parsePaymentXML(getCookie('xml'));
    currentXML = xml;
		//debug(currentXML, true);
		
		var node = SelectSingleNode(currentXML,"//chapterpayment/ChapterAdvisorContributionFee");			
		node.firstChild.nodeValue = '';
		
		//debug(currentXML, true);
		setFormValues(f,currentXML);
}

function getFormPaymentXML(uri) {
    var middle = getCookie('isMiddleLevel');
		// if (middle == '1' || middle == 'True' || middle == 'true' || middle == true){
			// $('#NationalMinimum').hide();
			// $('#StateMinimum').hide();
			// $('#NationalDues').hide();
			// $('#StateDues').hide();
			// $('#NationalMiddleDues').show();
			// $('#StateMiddleDues').show();
		// }
		
		uri = baseuri + uri;
    var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
    		var userid = getCookie('userId');
     		uri = uri +'userid/'+  userid;
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
        
		    xmlHttpRequest.open(method, uri, true);
 		    xmlHttpRequest.onreadystatechange=function() 
 		  {
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
          
   				var Total = SelectSingleNode(currentXML,"//chapterpayment/Total");
   			  var doesNotRequirePayment = SelectSingleNode(currentXML,"//chapterpayment/DoesNotRequirePayment");
   			  if(doesNotRequirePayment){
   				   var paymentRequired = parseFloat(Total.firstChild.nodeValue);
   				} else {
   				   var paymentRequired = 'false';
   				}
   				if(Total){
   				  setCookie('total', Total.firstChild.nodeValue,30);
   				  var totalDues = parseFloat(Total.firstChild.nodeValue);
   				}
   				if(totalDues > 0 && paymentRequired === 'false'){
   				  showPaymentType();
   				}
   				
   				var chapterAdviserContributionFee = SelectSingleNode(currentXML,"//chapterpayment/ChapterAdvisorContributionFee");
		      if(chapterAdviserContributionFee) {
		        document.getElementById('chapterAdvisorsContributingFee').innerHTML = formatCurrency(chapterAdviserContributionFee.firstChild.nodeValue);
		        document.getElementById('ChapterAdvisorsContributing').checked = false;
		        document.getElementById('ChapterAdvisorContributionFee').value = formatCurrency(chapterAdviserContributionFee.firstChild.nodeValue);
			      setCookie('chapterAdviserContributionFee', chapterAdviserContributionFee.firstChild.nodeValue,30);
		      }
		      
		      var nationalAdvisorContributionFee = SelectSingleNode(currentXML,"//chapterpayment/NationalAdvisorContributionFee");
		      if(nationalAdvisorContributionFee) {
		        document.getElementById('nationalAdvisorsContributingFee').innerHTML = formatCurrency(nationalAdvisorContributionFee.firstChild.nodeValue);
		        document.getElementById('NationalAdvisorsContributing').checked = false;
		        document.getElementById('NationalAdvisorContributionFee').value = formatCurrency(nationalAdvisorContributionFee.firstChild.nodeValue);
			      setCookie('nationalAdvisorContributionFee', nationalAdvisorContributionFee.firstChild.nodeValue,30);
		      }
		      
		      var total = SelectSingleNode(currentXML,"//chapterpayment/Total");
		      if(total){
			      setCookie('total', total.firstChild.nodeValue,30);
						if (total.firstChild.nodeValue == '0'){
							$('#nationalAdviser').css("display","none");
							$('#stateChapterAdviser').css("display","none");
						}
		      }
					
					//alert(total);
		      
   				var f = document.currentForm;
				  setFormValues(f,currentXML);
					
					if (middle == '1' || middle == 'True' || middle == 'true' || middle == true) {
						document.getElementById('NationalMinimum').value = 0;
						document.getElementById('StateMinimum').value = 0;
						document.getElementById('NationalDues').value = 0;
						document.getElementById('StateDues').value = 0;
					}
					
					document.getElementById('NationalMinimum').value = formatCurrency(document.getElementById('NationalMinimum').value)
					document.getElementById('StateMinimum').value = formatCurrency(document.getElementById('StateMinimum').value)
					document.getElementById('NationalDues').value = formatCurrency(document.getElementById('NationalDues').value)
					document.getElementById('StateDues').value = formatCurrency(document.getElementById('StateDues').value)
					document.getElementById('MiddleLevelNationalFee').value = formatCurrency(document.getElementById('MiddleLevelNationalFee').value)
					document.getElementById('MiddleLevelStateFee').value = formatCurrency(document.getElementById('MiddleLevelStateFee').value)
					
					document.getElementById('Fees').value = formatCurrency(document.getElementById('Fees').value)
					document.getElementById('Total').value = formatCurrency(document.getElementById('Total').value)				 
				
  			}
  		}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return ;
}

function updateXml(){
	//debug(currentXML,true);
	var nacf = 0;
	var f = document.currentForm;
	var path;
	
	var fcclaids = new Array();
	var chapternode = SelectSingleNode(currentXML,"//chapterpayment/chaptername");
	
	if (chapternode.hasChildNodes){
		for (var i = 0; i < chapternode.childNodes.length; i++)
		{
			fcclaids[i] = chapternode.childNodes[i].childNodes[0].nodeValue;
		}
	}
	
	var node = SelectSingleNode(currentXML,"//chapterpayment/NationalAdvisorContributionFee");					
	for (chk = 0; chk < f.elements.length; chk++){
		if (f.elements[chk].type == 'checkbox'){
			if (f.elements[chk].checked){
				nacf++;
			} else {
				//debug();
				var fcclaid = f.elements[chk].name.split('_');
				//var fcclaid = fcclaidpre[1].split('_');
				//debug(fcclaid[1]);
				if (fcclaids.contains(fcclaid[1])) {
					//remove the node from currentXML
					//debug('got here');
					path = '//chapterpayment/chaptername[fcclaid=' + fcclaid[1] + ']/fcclaid';
					var nodetoremove = SelectSingleNode(currentXML,path);
					nodetoremove.parentNode.removeChild(nodetoremove);
				}
			}
		}
	}
	node.firstChild.nodeValue = parseFloat(document.getElementById('NationalAdvisorContributionFee').value) * nacf;
	document.getElementById('NationalAdvisorContributionFee').value = node.firstChild.nodeValue;
	if (nacf > 0){
		document.getElementById('NationalAdvisorsContributing').value = true;
	}
	else
	{
		document.getElementById('NationalAdvisorsContributing').value = false;
	}
	//debug(currentXML,true);
}

function updateTotal(id,checkboxid){
  if(id === 'NationalAdvisorContributionFee'){
     if(document.getElementById(checkboxid).checked){
				//alert(parseFloat(document.getElementById('NationalAdvisorContributionFee').value)); //remove when done
        updateTotalAffiliationCost(parseFloat(document.getElementById('NationalAdvisorContributionFee').value));
        document.getElementById(checkboxid).value = "true";
				// //debug(currentXML, true);
				// var nacfNode = SelectSingleNode(currentXML,"//chapterpayment/NationalAdvisorContributionFee");					
				// nacfNode.firstChild.nodeValue = parseFloat(document.getElementById('NationalAdvisorContributionFee').value);
				// //debug(currentXML, true);
     } else {
				//alert(- parseFloat(document.getElementById('NationalAdvisorContributionFee').value)); //remove when done
				updateTotalAffiliationCost(- parseFloat(document.getElementById('NationalAdvisorContributionFee').value));
        document.getElementById(checkboxid).value = "false";
				// //debug(currentXML, true);
				// var nacfNode = SelectSingleNode(currentXML,"//chapterpayment/NationalAdvisorContributionFee");					
				// nacfNode.firstChild.nodeValue = 0;
				// //debug(currentXML, true);
     }
  }
  if(id === 'ChapterAdvisorContributionFee'){
     if(document.getElementById('ChapterAdvisorsContributing').checked){
        updateTotalAffiliationCost(parseFloat(document.getElementById('ChapterAdvisorContributionFee').value));
        document.getElementById('ChapterAdvisorsContributing').value = "true";
     } else {
        updateTotalAffiliationCost(- parseFloat(document.getElementById('ChapterAdvisorContributionFee').value));
        document.getElementById('ChapterAdvisorsContributing').value = "false";
     }
  }
}

function updateTotalAffiliationCost(addNumber){
  var total = document.getElementById('Total').value;
  var tempTotal = addNumber + parseFloat(total.replace(/,/,''));
	var newTotal = addCommas(tempTotal.toFixed(2));
  document.getElementById('Total').value = newTotal;
}

function getFormPaymentStateXML(uri) {
    uri = baseuri + uri + getCookie('state');
    var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
    		
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
        
		    xmlHttpRequest.open(method, uri, true);
 		    xmlHttpRequest.onreadystatechange=function() 
 		  {
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
          
   				var natDues = SelectSingleNode(currentXML,"//chapterpayment/NationalDues").firstChild.nodeValue;
					var natFees = SelectSingleNode(currentXML,"//chapterpayment/NationalMinimum").firstChild.nodeValue;
					var natMin = SelectSingleNode(currentXML,"//chapterpayment/StateMinimum").firstChild.nodeValue;
					
					var Total = parseInt(natDues) + parseInt(natFees) + parseInt(natMin);
   			  var doesNotRequirePayment = SelectSingleNode(currentXML,"//chapterpayment/DoesNotRequirePayment");
   			  if(doesNotRequirePayment){
   				   var paymentRequired = parseFloat(Total);
   				} else {
   				   var paymentRequired = 'false';
   				}
   				if(Total){
						setCookie('total', Total,30);
   				  var totalDues = parseFloat(Total);
   				}
   				if(totalDues > 0 && paymentRequired === 'false'){
   				  showPaymentType();
   				}
		      
		      var nationalAdvisorContributionFee = SelectSingleNode(currentXML,"//chapterpayment/NationalAdvisorContributionFee");
		      if(nationalAdvisorContributionFee) {
		        document.getElementById('nationalAdvisorsContributingFee').innerHTML = "$"+nationalAdvisorContributionFee.firstChild.nodeValue;
			      setCookie('nationalAdvisorContributionFee', nationalAdvisorContributionFee.firstChild.nodeValue,30);
		      }

					var totalNode = SelectSingleNode(currentXML,"//chapterpayment/Total");					
					totalNode.firstChild.nodeValue = Total;
					
					// var nacfNode = SelectSingleNode(currentXML,"//chapterpayment/NationalAdvisorContributionFee");					
					// nacfNode.firstChild.nodeValue = document.getElementById('nationalAdvisorsContributingFee').innerHTML;
					
					var f = document.currentForm;
				  setFormValues(f,currentXML);
				  //debug(currentXML, true);
  			}
  		}
  		xmlHttpRequest.send(null);
			getPendingAffiliation(getCookie('state'));
    }
    else
    {
      alert("unable to create request object");
    }
    return ;
}

function showTextField(textfield){
   $('#'+textfield).show();
}
function hideTextField(textfield){
   $('#'+textfield).hide();
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


function showPaymentType(){
      showTextField('paymenttype_rule');
   	  showTextField('paymenttype');
}
function hidePaymentType(){
      hideTextField('paymenttype_rule');
   	  hideTextField('paymenttype');
}
function getFormRegistrationXML(uri) {
    uri = baseuri + uri +"?meetingid="+getCookie('meetingId')+"&chapterid="+getCookie('ChapterId');
    var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
		    xmlHttpRequest.open(method, uri, true);
 		    xmlHttpRequest.onreadystatechange=function() 
 		  {
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
   				var f = document.currentForm;
				setFormValues(f,currentXML);
  			}
  		}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return ;
}


function getPendingAffiliation(state) {
	$.ajax({
		type: 'GET',
		url: baseuri + '/fccla/~fccla/pendingaffiliation/chapterstate/' + state + '&rand=' + new Date().getTime(),
		async: false,
		dataType: 'xml',
		error: function(){
			alert('Error loading XML document');
		},
		success: function(chapterxml){
			//debug(currentXML, true);
			var i = 0;
			var row = '';
			var chapterid = new Array();
			$(chapterxml).find('UNAFFILIATED').each(function(){
				var fcclaid = $(this).find('fcclaid').text();
				var chaptername = $(this).find('name').text();
				var firstname = $(this).find('firstname').text();
				var lastname = $(this).find('lastname').text();
				var nacf = $(this).find('nationalContributionFee').text()
				
				if (!chapterid.contains(fcclaid)) {
					//debug(nacf);
					if (nacf == 'True'){
						row = '<tr><td>' + fcclaid + '</td><td>' + chaptername + '</td><td><input disabled="disabled" id="nacf_' + fcclaid + '_' + lastname + '_' + firstname + '" name="nacf_' + fcclaid + '_' + lastname + '_' + firstname + '" type="checkbox" onchange="updateTotal(\'NationalAdvisorContributionFee\',\'nacf_' + fcclaid + '_' + lastname + '_' + firstname + '\');"/></td></tr>';
					} else {
						//add chapterid to currentXML
						var node = SelectSingleNode(currentXML,"//chaptername");
						try
						{
						newNode = currentXML.createNode(1, "fcclaid", "");
						txtnode = currentXML.createTextNode(fcclaid);
						newNode.appendChild(txtnode);
						node.appendChild(newNode);
						}
						catch (e)
						{
							newNode = currentXML.createElement("fcclaid");						
							txtnode = currentXML.createTextNode(fcclaid);
							newNode.appendChild(txtnode);
							node.appendChild(newNode);
						}
						row = '<tr><td>' + fcclaid + '</td><td>' + chaptername + '</td><td><input id="nacf_' + fcclaid + '_' + lastname + '_' + firstname + '" name="nacf_' + fcclaid + '_' + lastname + '_' + firstname + '" type="checkbox" onchange="updateTotal(\'NationalAdvisorContributionFee\',\'nacf_' + fcclaid + '_' + lastname + '_' + firstname + '\');"/></td></tr>';
					}
					$('#NationalAdvisorContributionChapters').append(row);					
					chapterid[i] = fcclaid;
					i++;				
				}				
			});
			//debug(currentXML,true);
			$('#NationalAdvisorContributionChapters').css("display","block");				
		}			
	});
}

function getGridXML(uri) {

    uri = baseuri + uri;

    var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();   
    if (xmlHttpRequest)
    {
      if(uri == baseuri + '/fccla/~fccla/unaffiliated/chapterstate/' || uri == baseuri + '/fccla/~fccla/student/chapterstate/')
      {
    		var state = getCookie("state");
     		uri = uri + state;
      }
			else if(uri == baseuri + '/fccla/~fccla/studentshort')
			{
				var state = "?state=" + getCookie("state");
				var lastnamestart = "&lastnamestart=" + getCookie("lastnamestart");
				var fcclaid = "&fcclaidlookup=" + getCookie("fcclaidlookup");
				var status = "&status=" + getCookie("status");
				uri = uri + state + lastnamestart + fcclaid + status;
				//alert(uri);
				delCookie('lastnamestart');
				delCookie('fcclaidlookup');
				delCookie('status');
			}
      else if(uri != baseuri + '/fccla/~fccla/store/')
    	{
    		var userid = getCookie('userId');
     		uri = uri + userid;
     	}
      	
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
      	//alert(getCookie('meetingid'));
		    xmlHttpRequest.open(method, uri, true);
 		    xmlHttpRequest.onreadystatechange=function() 
			{
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
   				//debug(currentXML,true);
					createCheckboxArray();
					//alert("got here");
  			}
  		}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return ;
}



// Meetings   

function getMeetingFeeXML(uri){ 
     var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
    	 var feeID = getCookie('feeID');
    	 
      	uri = uri + feeID;
      	
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
		    xmlHttpRequest.open(method, uri, true);
 	      xmlHttpRequest.onreadystatechange=function() 
 		{
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
   				var f = document.currentForm;
				  setFormValuesFromXML(f,currentXML);
  			}
  		}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return ; 

}

function setFormValuesFromXML(f,xml){
	for (var i=0; i<f.elements.length; i++)
	{
		if (f.elements[i].type=="text" || f.elements[i].type=="textarea" || f.elements[i].type=="password" || f.elements[i].type=="hidden")
		{
			var elementName = f.elements[i].name;
			if(elementName === 'meetingid'){
			  document.getElementById('meetingid').value= getCookie('meetingId');
			}
			if(elementName != null)
			{
				elementName = "//" +elementName.replace(/_/g, "/");
				if(SelectSingleNode(xml,elementName) != null && SelectSingleNode(xml,elementName).firstChild != null)
				{
					document.getElementById(f.elements[i].name).value=SelectSingleNode(xml,elementName).firstChild.nodeValue;
				}
			}
		}
		else if(f.elements[i].type=="checkbox" && f.elements[i].name != "billingsameaddress"){
		  var elementName = f.elements[i].name;
		  elementName = "//" +elementName.replace(/_/g, "/");
		  if(SelectSingleNode(xml,elementName) != null && SelectSingleNode(xml,elementName).firstChild != null){
		      if(SelectSingleNode(xml,elementName).firstChild.nodeValue == 'True'){
		        document.getElementById(f.elements[i].name).checked = true;
		      } else if (SelectSingleNode(xml,elementName).firstChild.nodeValue == 'False'){
		        document.getElementById(f.elements[i].name).checked = false;
		      }
			} else {
			  document.getElementById(f.elements[i].name).checked = false;
			}
		}
		else if (f.elements[i].type == "select-one")
		{
			var elementName = f.elements[i].name;
			
			var curElementName = elementName
			
			if(elementName == 'starttime' || elementName == 'endtime'){
				elementName = "//" +elementName.replace(/_/g, "/");
				if(SelectSingleNode(xml,elementName) != null && SelectSingleNode(xml,elementName).firstChild != null){
					for (var t=0; t<document.getElementById(f.elements[i].name).length; t++){
							//split the timestamp and select the right drop down element.
							var dt = SelectSingleNode(xml,elementName).firstChild.nodeValue;
							var arr = dt.split(" ")
							if(arr[1].split(":",2).join(":") == document.getElementById(f.elements[i].name).options[t].value){
								document.getElementById(f.elements[i].name).options[t].selected = true
							}
					}
				}
			}
			else if(elementName != null)
			{
				elementName = "//" +elementName.replace(/_/g, "/");
				if(SelectSingleNode(xml,elementName) != null && SelectSingleNode(xml,elementName).firstChild != null){
					for (var t=0; t<document.getElementById(f.elements[i].name).length; t++){
					    console.log(document.getElementById(f.elements[i].name).options[t].value)
							if(SelectSingleNode(xml,elementName).firstChild.nodeValue == document.getElementById(f.elements[i].name).options[t].value){
								document.getElementById(f.elements[i].name).options[t].selected = true
							}
					}
				}
			}
		}
	}
	return;
}

function deleteMeetingFee(id, x, method){

	if (confirm('Are you sure you want to delete this fee?')) 
	{ 
		uri = baseuri + '/fccla/~fccla/meetingfee/' + id;
		var success = false;
		var xmlHttpRequest=getXMLHttpRequest();
    	if (xmlHttpRequest)
    	{
				if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
				xmlHttpRequest.open(method, uri, false);
   	 		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    		xmlHttpRequest.send(null);
    		window.location.reload();
    	}
    	else
   		{
      		alert("unable to create request object");
    	}
    	
    	return;
	} else { 
			
		return;
	};
	
}


function deleteChapter(id, x){
	if (confirm('Are you sure you want to delete this chapter?')) 
	{ 
		uri = baseuri + '/fccla/~fccla/chapter/' + id;
		var success = false;
		var xmlHttpRequest=getXMLHttpRequest();
    	if (xmlHttpRequest)
    	{
				xmlHttpRequest.open('DELETE', uri, false);
   	 		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    		xmlHttpRequest.send(null);
    		window.location.reload();
    	}
    	else
   		{
      		alert("unable to create request object");
    	}
    	
    	return;
	} else { 
			
		return;
	};
	
}

function manageMeetingFee(feeID){
  setCookie('feeID',feeID,30);
	document.location='Admin_Edit_Meeting_Fee_Properties.htm';
}

function getMeetingXML(uri){
 
  var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
    	 var meetingId = getCookie('meetingId');
      	uri = uri + meetingId+"?view=full";
      	
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
		    xmlHttpRequest.open(method, uri, true);
 		    xmlHttpRequest.onreadystatechange=function() 
 		{
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
   				var f = document.currentForm;
				setFormValues(f,currentXML);
  			}
  		}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return ; 
}

function getMeetingEventXML(uri){
  var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
    	 var feeEventID = getCookie('feeEventID');
      	uri = uri + feeEventID+"?view=full";
      	
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
		    xmlHttpRequest.open(method, uri, true);
 		    xmlHttpRequest.onreadystatechange=function() 
 		{
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
   				var f = document.currentForm;
				setFormValues(f,currentXML);
  			}
  		}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return ; 
}

function manageMeeting(id){
	setCookie('meetingId',id,30);
	document.location='Admin_Manage_Meeting_Menu.htm';
}

function manageMeetingOption(id){
  setCookie('optionid',id,30);
  getMeetingPage('Admin_Edit_Option_Properties.htm');
}

function deleteMeetingOption(id, x, method){

	if (confirm('Are you sure you want to delete this meeting option?')) 
	{ 
		uri = baseuri + '/fccla/~fccla/meetingoption/' + id;
		var success = false;
		var xmlHttpRequest=getXMLHttpRequest();
    	if (xmlHttpRequest)
    	{
				xmlHttpRequest.open(method, uri, false);
   	 		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    		xmlHttpRequest.send(null);
    		window.location.reload();
    	}
    	else
   		{
      		alert("unable to create request object");
    	}
    	
    	return;
	} else { 
			
		return;
	};
	
}

function getMeetingPage(URL){
  document.location=URL+'?meetingid='+getCookie('meetingId');
}

function submitMeetingFeeFormXML(uri,URL,method){ 
	if($('#currentForm').valid())
	{
		var f = document.currentForm;
		var xml = getMeetingFormValues(f,currentXML);	
	
		if(submitMeetingFeeXML(uri,xml,method))
		{
       
					getMeetingPage(URL);
			
		}
		else
		{
			//alert('failed');
		}
	} else {
		scroll(0,0);
	}
	
    return;
}

function submitMeetingFeeXML(uri,xml,method){
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      var feeID = getCookie('feeID');
     	uri = uri + "/" +feeID;
     
      xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      if(method == "POST")
      {
      	if(xml.xml != undefined)
      	{
      		var strXml = xml.xml;
      	}
      	else 
      	{
      		var serializer = new XMLSerializer();
      		var strXml = serializer.serializeToString(xml);
		    }
      	 body=escape(strXml); 
      	 body=body.replace(/\+/g,"%2B");
      	 body = "post=" + body;
      	 xmlHttpRequest.send(body)
      }
      else
      {  
	      	xmlHttpRequest.send(xml);
      }
      if(xmlHttpRequest.status != 200)
      {
	  	  alert(xmlHttpRequest.status);
      }
	  else
	  {
      success = true;
      var resultText = null;
      if(xmlHttpRequest.responseText){
        resultText = xmlHttpRequest.responseText;
      } else {
        var resultXml = SelectSingleNode(xmlHttpRequest.responseXML,"//Error");
        if(resultXml){
          resultText = resultXml.innerText;
        }
      }
      
      if(xmlHttpRequest.responseText.indexOf('<Error>Duplicate contact found') != -1 ) {
        alert('A record aleady exists with the same combination of First name, Middle name and Last Name. Please edit one of these and try again.');
        success = false;
      }
	  }
      //var resultXml = xmlHttpRequest.responseXML; 
      
    }
    else
    {
      alert("unable to create request object");
      success =  false;
    }
    return success;
}

function submitMeetingFormXML(uri,URL,method){ 
	if($('#currentForm').valid())
	{
		var f = document.currentForm;
		var xml = getMeetingFormValues(f,currentXML);	
	
		if(submitMeetingXML(uri,xml,method))
		{
       
				document.location = URL;
			
		}
		else
		{
			//alert('failed');
		}
	}
    return ;
}

function submitHotelFormXML(uri,URL,method){ 
	if($('#currentForm').valid())
	{
		var f = document.currentForm;
		var xml = getMeetingFormValues(f,currentXML);	
		if(submitHotelXML(uri,xml,method))
		{
				getMeetingPage(URL)
		}
	}else {
		scroll(0,0);
	}
    return ;
}

function submitHotelXML(uri,xml,method){
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      var hotelID = getCookie('hotelID');
     	uri = uri + "/" +hotelID;
			if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
      xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      if(method == "POST")
      {
      	if(xml.xml != undefined)
      	{
      		var strXml = xml.xml;
      	}
      	else 
      	{
      		var serializer = new XMLSerializer();
      		var strXml = serializer.serializeToString(xml);
		    }
      	 body=escape(strXml); 
      	 body=body.replace(/\+/g,"%2B");
      	 body = "post=" + body;
      	 xmlHttpRequest.send(body)
      }
      else
      {  
	      	xmlHttpRequest.send(xml);
      }
      if(xmlHttpRequest.status != 200)
      {
	  	  alert(xmlHttpRequest.status);
      }
	  else
	  {
      success = true;
      var resultText = null;
      if(xmlHttpRequest.responseText){
        resultText = xmlHttpRequest.responseText;
      } else {
        var resultXml = SelectSingleNode(xmlHttpRequest.responseXML,"//Error");
        if(resultXml){
          resultText = resultXml.innerText;
        }
      }
      
      if(xmlHttpRequest.responseText.indexOf('<Error>Duplicate contact found') != -1 ) {
        alert('A record aleady exists with the same combination of First name, Middle name and Last Name. Please edit one of these and try again.');
        success = false;
      }
	  }
    }
    else
    {
      alert("unable to create request object");
      success =  false;
    }
    return success;
}

function submitMeetingXML(uri,xml,method){
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      var meetingId = getCookie('meetingId');
     	uri = uri + "/" +meetingId;
     
			if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
      xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      if(method == "POST")
      {
      	if(xml.xml != undefined)
      	{
      		var strXml = xml.xml;
      	}
      	else 
      	{
      		var serializer = new XMLSerializer();
      		var strXml = serializer.serializeToString(xml);
		    }
      	 body=escape(strXml); 
      	 body=body.replace(/\+/g,"%2B");
      	 body = "post=" + body;
      	 xmlHttpRequest.send(body)
      }
      else
      {  
	      	xmlHttpRequest.send(xml);
      }
      if(xmlHttpRequest.status != 200)
      {
	  	  alert(xmlHttpRequest.status);
      }
	  else
	  {
      success = true;
      var resultText = null;
      if(xmlHttpRequest.responseText){
        resultText = xmlHttpRequest.responseText;
      } else {
        var resultXml = SelectSingleNode(xmlHttpRequest.responseXML,"//Error");
        if(resultXml){
          resultText = resultXml.innerText;
        }
      }
      
      if(xmlHttpRequest.responseText.indexOf('<Error>Duplicate contact found') != -1 ) {
        alert('A record aleady exists with the same combination of First name, Middle name and Last Name. Please edit one of these and try again.');
        success = false;
      }
	  }
      //var resultXml = xmlHttpRequest.responseXML; 
      
    }
    else
    {
      alert("unable to create request object");
      success =  false;
    }
    return success;
}

function getMeetingFormValues(f,xml){
	for (var i=0; i<f.elements.length; i++){
		if (f.elements[i].type=="text" || f.elements[i].type=="textarea" || f.elements[i].type=="password" || f.elements[i].type=="hidden" || f.elements[i].type == "select-one" || f.elements[i].type == "checkbox"){
			var elementName = f.elements[i].name;
      if(elementName != 'chapterid'){
        if(elementName != null)
        {			
          elementName = "//" +elementName.replace(/_/g, "/");
          var node = SelectSingleNode(xml,elementName);
          
          if(!node) {
            var nodeNames = f.elements[i].name.split('_');
            node = createXPathNodes(xml, xml.firstChild, nodeNames, 0, "//" + nodeNames[0]);					
          }
          if(node){
            if(node.firstChild){
               node.firstChild.nodeValue = (f.elements[i].value == '' ? blankFieldIndicator : f.elements[i].value);
            } else	{
              var textToSave = (f.elements[i].value == '' ? blankFieldIndicator : f.elements[i].value);
              var textnode = xml.createTextNode(textToSave);
           
              node.appendChild(textnode)
            }
          }
        }
      }
    }
	}
	return xml;
}

function managaeHotel(hotelID){
  setCookie('hotelID',hotelID,30);
	document.location='Admin_Edit_Hotel_Properties.htm';
}

function deleteEventFee(id, x, method){

	if (confirm('Are you sure you want to delete this breakout event?')) 
	{ 
		uri = baseuri + '/fccla/~fccla/meetingevent/' + id;
		var success = false;
		var xmlHttpRequest=getXMLHttpRequest();
    	if (xmlHttpRequest)
    	{
				if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
				xmlHttpRequest.open(method, uri, false);
   	 		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    		xmlHttpRequest.send(null);
    		window.location.reload();
    	}
    	else
   		{
      		alert("unable to create request object");
    	}
    	
    	return;
	} else { 
			
		return;
	};
	
}

function manageEventFee(feeEventID){
  setCookie('feeEventID',feeEventID,30);
	getMeetingPage('Admin_Edit_Breakout_Event.htm?meetingid='+getCookie('meetingId'));
}

function deleteHotel(id, x, method){

	if (confirm('Are you sure you want to delete this hotel?')) 
	{ 
		uri = baseuri + '/fccla/~fccla/meetinghotel/' + id;
		var success = false;
		var xmlHttpRequest=getXMLHttpRequest();
    	if (xmlHttpRequest)
    	{
				if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
				xmlHttpRequest.open(method, uri, false);
   	 		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    		xmlHttpRequest.send(null);
    		window.location.reload();
    	}
    	else
   		{
      		alert("unable to create request object");
    	}
    	
    	return;
	} else { 
			
		return;
	};
	
}

function getHotelXML(uri){
      
     var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
    	 var hotelID = getCookie('hotelID');
      	uri = uri + hotelID;
        if(uri.indexOf ("?") != -1)
          {
            uri = uri + "&rand=" + new Date().getTime()
          }
          else
          {
            uri = uri + "?rand=" + new Date().getTime()
          }
          xmlHttpRequest.open(method, uri, true);
          xmlHttpRequest.onreadystatechange=function() 
 		  {
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
   				var f = document.currentForm;
				  setFormValues(f,currentXML);
  			}
  		}
  		xmlHttpRequest.send(null);
    }
    else
    {
      alert("unable to create request object");
    }
    return ; 

}

function registerStudent(id){
  setCookie('meetingId',id,30);
	window.location = 'Chapter_Adviser_Specify_Attendees.htm?userid='+getCookie('userId')+"&meetingid="+id;
}

// function for breadcrumb to call Chapter_Adviser_Specify_Attendees.htm page
function getRegisteredStudent(){
  window.location = 'Chapter_Adviser_Specify_Attendees.htm?userid='+getCookie('userId')+"meetingid="+getCookie('meetingId');
}

function submitMeetingOptions(uri,URL,method, id){   
	if($('#currentForm').valid())
	{
		var f = document.currentForm;
		var xml = getMeetingFormValues(f,currentXML);
		currentXML = xml;
		removeNode('contactidInfo');
	  xml = currentXML;
		if(submitIdXML(uri,xml,method,id)){
			getMeetingPage(URL);
		} 
	}else {
		scroll(0,0);
	}
  return ;
}

function submitMeeting(uri,URL,method, id){ 
	if($('#currentForm').valid())
	{
		var f = document.currentForm;
		var xml = getMeetingFormValues(f,currentXML);
		if(submitIdXML(uri,xml,method,id)){
				getMeetingPage(URL);
		}
	}else {
		scroll(0,0);
	}
    return ;
}

function submitIdXML(uri,xml,method,id){
 
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      if(id !== ''){
     	  uri = uri + "/" +getCookie(id);
     	}
			if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
      xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      if(method == "POST")
      {
      	if(xml.xml != undefined)
      	{
      		var strXml = xml.xml;
      	}
      	else 
      	{
      		var serializer = new XMLSerializer();
      		var strXml = serializer.serializeToString(xml);
		    }
      	 body=escape(strXml); 
      	 body=body.replace(/\+/g,"%2B");
      	 body = "post=" + body;
      	 xmlHttpRequest.send(body)
      }
      else
      {  
	      	xmlHttpRequest.send(xml);
      }
      if(xmlHttpRequest.status != 200)
      {
	  	  alert(xmlHttpRequest.status);
      }
	  else
	  {
      success = true;
      var resultText = null;
      if(xmlHttpRequest.responseText){
        resultText = xmlHttpRequest.responseText;
      } else {
        var resultXml = SelectSingleNode(xmlHttpRequest.responseXML,"//Error");
        if(resultXml){
          resultText = resultXml.innerText;
        }
      }
      
      if(xmlHttpRequest.responseText.indexOf('<Error>Duplicate contact found') != -1 ) {
        alert('A record aleady exists with the same combination of First name, Middle name and Last Name. Please edit one of these and try again.');
        success = false;
      }
	  }
      //var resultXml = xmlHttpRequest.responseXML; 
      
    }
    else
    {
      alert("unable to create request object");
      success =  false;
    }
    return success;
}


// load the XML for a form
// @uri the web service
// @id  the cookie name
function loadFormXMLId(uri,id){
    $.ajax({
        type: "GET",
        url: uri + "/" + getCookie(id),
        data: "view=full" + "&rand=" + new Date().getTime(),
        async: false,
        success: function(xml){
          currentXML = xml;
          var f = document.currentForm;
          setFormValues(f,currentXML);
        }
      }); 
}
function getManageSchools(){
  document.location='Admin_Manage_Schools.htm?state='+state+"&status="+status;
}
function loadSchoolXMLId(uri,id){
  	var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest){
      uri = uri + id;	
    	if(uri.indexOf ("?") != -1){
        	uri = uri + "&rand=" + new Date().getTime()
      	}	else 	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
		    xmlHttpRequest.open(method, uri, true);
 		    xmlHttpRequest.onreadystatechange=function() {
  			if (xmlHttpRequest.readyState==4) {
   				var xml = xmlHttpRequest.responseXML;
   				var f = document.currentForm;
				  setSchoolFormValues(f,xml);
  			}
  		}
  		xmlHttpRequest.send(null)
    } else {
      alert("unable to create request object");
    }
    return; 
}

function loadChapterXMLId(uri,id){
  	var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest){
      uri = uri + id;	
    	if(uri.indexOf ("?") != -1){
        	uri = uri + "&rand=" + new Date().getTime()
      	}	else 	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
		    xmlHttpRequest.open(method, uri, true);
 		    xmlHttpRequest.onreadystatechange=function() {
  			if (xmlHttpRequest.readyState==4) {
   				var xml = xmlHttpRequest.responseXML;
   				var f = document.currentForm;
				  setChapterFormValues(f,xml);
  			}
  		}
  		xmlHttpRequest.send(null)
    } else {
      alert("unable to create request object");
    }
    return; 
}

function loadChapterXMLIdAdmin(uri,id){
  	var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest){
      uri = uri + id;	
    	if(uri.indexOf ("?") != -1){
        	uri = uri + "&rand=" + new Date().getTime()
      	}	else 	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
		    xmlHttpRequest.open(method, uri, true);
 		    xmlHttpRequest.onreadystatechange=function() {
  			if (xmlHttpRequest.readyState==4) {
   				var xml = xmlHttpRequest.responseXML;
   				var f = document.currentForm;
				  setChapterFormValuesAdmin(f,xml);
  			}
  		}
  		xmlHttpRequest.send(null)
    } else {
      alert("unable to create request object");
    }
    return; 
}

function setSchoolFormValues(f,xml){
	for (i=6; i<f.elements.length; i++){
		if (f.elements[i].type=="text" || f.elements[i].type=="textarea" || f.elements[i].type=="password" || f.elements[i].type=="hidden"){
			var elementName = f.elements[i].name;
			if(elementName != null)	{
				elementName = elementName.replace(/schoolInfo_/g, "");
				elementName = "//" +elementName.replace(/_/g, "/");
				if(SelectSingleNode(xml,elementName) != null && SelectSingleNode(xml,elementName).firstChild != null)	{
					document.getElementById(f.elements[i].name).value=SelectSingleNode(xml,elementName).firstChild.nodeValue;
				}
			}
		}
	}
	autoFillBilling();
	return;
}
  
function setChapterFormValues(f,xml){
  if(SelectSingleNode(xml,'//CHAPTER/chapterid') != null && SelectSingleNode(xml,'//CHAPTER/chapterid').firstChild != null)	{
	  document.getElementById('chapterid').value=SelectSingleNode(xml,'//CHAPTER/chapterid').firstChild.nodeValue;
	  document.getElementById('chaptername').value=SelectSingleNode(xml,'//CHAPTER/name').firstChild.nodeValue;	
	}
	return;
}
function setChapterFormValuesAdmin(f,xml){
  if(SelectSingleNode(xml,'//CHAPTER/chapterid') != null && SelectSingleNode(xml,'//CHAPTER/chapterid').firstChild != null)	{
	  document.getElementById('chapteridInfo_chapterid').value=SelectSingleNode(xml,'//CHAPTER/chapterid').firstChild.nodeValue;
	  document.getElementById('chapteridInfo_name').value=SelectSingleNode(xml,'//CHAPTER/name').firstChild.nodeValue;	
	}
	return;
}
    
function searchByFcclaId(url){
	var fcclaid = document.getElementById('fcclaid').value;
	if (fcclaid == ""){
		alert("Please enter a Chapter ID to use this search.");
		return;
	}
  if (url.split("_")[0] != 'State')
	{
		delCookie('state');
	}
  delCookie('lastnamestart');
	setCookie("fcclaidlookup",fcclaid,30);
	var tempurl = url;
	if (url.split("_")[0] == 'State')
	{
		tempurl = url.substring(6);
	}
	//var status = getCookie('status');
	var status = "";
	if (tempurl.split("_")[4] == 'Students')
	{
		status = 'affiliated';
	}
	else if (tempurl.split("_")[4] == 'Unaffiliated')
	{
		status = 'unaffiliated';
	}
	if (status != "")
	{
		status = "&status=" + status;
		setCookie('status',status,30);
	}
	//document.location ="Admin_Manage_Chapters.htm?fcclaidlookup="+fcclaid;
	document.location = url + ".htm?userid=" + getCookie("userId") + "&fcclaidlookup=" + fcclaid + status;
}

function specifyMeetingOption(id,URL){
   setCookie('meetingattendeeid',id,30);
  getMeetingPage('Chapter_Adviser_Specify_Attendee_Options.htm');
}

function submitMeetingAttendeesXML(uri,URL,method){ 
	uri = uri + "?meetingid=" + getCookie('meetingId');
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
			xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      //debug(currentXML,true);
      currentXML = getCheckBoxMeeting()
      removeNode('firstname');
      removeNode('lastname');
      removeNode('middlename');
      //debug(currentXML,true);
      var xml = getXMLString(currentXML);
      //debug(xml);
      body=escape(xml); 
      body=body.replace(/\+/g,"%2B");
      body = "post=" + body;
      xmlHttpRequest.send(body)
    	
    	if(xmlHttpRequest.status != 200){
       		alert(xmlHttpRequest.status);
   	 	} else {
				success = true;
				getMeetingPage(URL);
			}
      
      //getMeetingPage(URL);
   	 	success = true;
   	 	
    } else {
      alert("unable to create request object");
      success =  false;
    }
  return success;
} 

function removeNode(nn){
  
  
  for(var t=0;t<currentXML.firstChild.childNodes.length;t++){	
  
    if(currentXML.childNodes[0].childNodes[t].nodeName === nn){
       y=currentXML.childNodes[0].childNodes[t];
       currentXML.childNodes[0].removeChild(y);
       
    } else {
    
    for(var i=0;i<currentXML.childNodes[0].childNodes[t].childNodes.length;i++){	
      if(currentXML.childNodes[0].childNodes[t].childNodes[i].nodeName === nn){
        
        y=currentXML.childNodes[0].childNodes[t].childNodes[i];
        currentXML.childNodes[0].childNodes[t].removeChild(y);
      }
    }
   }
  }	
  
}

// Meetings


function getXMLSchemaSetID(uri , id){
    var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest){
    	    // if(uri.indexOf ("?") != -1)
					// {
						// uri = uri + "&rand=" + new Date().getTime()
					// }
					// else
					// {
						// uri = uri + "?rand=" + new Date().getTime()
					// }
					xmlHttpRequest.open(method, uri, true);
          xmlHttpRequest.onreadystatechange=function() {
  			  if (xmlHttpRequest.readyState==4) {
   				  currentXML = xmlHttpRequest.responseXML;
   				  var f = document.currentForm;
				    setFormValuesFromXML(f,currentXML);
  			  }
  		}
  		xmlHttpRequest.send(null);
    }else{
      alert("unable to create request object");
    }
    var id = id +"id";
    document.getElementById(id).value = getCookie(id);
    return ; 
}

function updateStateList(state, status, guid){



	if (state != "" && status != ""){
		if(document.getElementById(state) == null || document.getElementById(status) == null){
			//document.location = baseuri+"/davinci/fccla/Admin_Manage_Chapters.htm?state="
		} else {
			document.getElementById(state).selected = true;
			document.getElementById(status).selected = true;
		}
	}
}

function updateContactList(lastnamestart, guid){
  document.getElementById(lastnamestart).selected = true;
}

function updateUserSelectOptions(x,y){
	if (document.getElementById('userrole') && document.getElementById('userrole') != null)
	{
   document.getElementById('userrole').selected = true;
	}
	if (document.getElementById('lastnamestart') && document.getElementById('lastnamestart') != null)
	{
   document.getElementById('lastnamestart').selected = true;
	}
}

function updateStateUserSelectOptions(x,y){
	if (document.getElementById('lastnamestart') != null)
	{
   document.getElementById('lastnamestart').selected = true;
	}
}


function getXMLSchema(uri){
    var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest){
					// if(uri.indexOf ("?") != -1)
					// {
						// uri = uri + "&rand=" + new Date().getTime()
					// }
					// else
					// {
						// uri = uri + "?rand=" + new Date().getTime()
					// }
    	    xmlHttpRequest.open(method, uri, true);
          xmlHttpRequest.onreadystatechange=function() {
  			  if (xmlHttpRequest.readyState==4) {
   				  currentXML = xmlHttpRequest.responseXML;
   				  var f = document.currentForm;
				    setFormValuesFromXML(f,currentXML);
  			  }
  		}
  		xmlHttpRequest.send(null);
    }else{
      alert("unable to create request object");
    }
    return ; 
}

function checkForDuplicateContact(uri,redirect,method) {
	if($('#currentForm').valid())
	{
		var f=document.currentForm;
		var chapterid = getCookie('ChapterId');
		var firstname = f["firstname"].value;
		var middlename = f["middlename"].value;
		var lastname = f["lastname"].value;	
		
		$.ajax({
			type: "GET",
			url: baseuri + "/fccla/~fccla/ContactDuplicate?chapterid=" + chapterid + "&firstname=" + firstname + "&middlename=" + middlename + "&lastname=" + lastname + "&rand=" + new Date().getTime(),
			async: false,
			success: function(xml){
				var duplicate = SelectSingleNode(xml, "//DuplicateContact");
				if (duplicate.firstChild.nodeValue == 'True')
				{	
					alert("You are attempting to add a duplicate record, if you have two students with the same first, last, and middle name please change the middle name of one student to an initial to add them.");
					return false;
				}
				
				else submitFormXML(uri,redirect,method);
			}
		});
	}
}

function submitFormXML(uri,URL,method){ 
	if($('#currentForm').valid()){
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);
		if(submitXML(uri,xml,method)){
			if(URL == "Chapter_Adviser_Add_Students.htm"){
				getAddStudentPage();
			}
			else{
				getLocation(URL);
			}
		}	else {
			alert('failed');
		}
	} else {
		scroll(0,0);
	}
    return;
}

function submitPWXML(uri,URL,method){ 
	if($('#currentForm').valid())
	{
		var f = document.currentForm;
		var contactid = getCookie('userId');

		$('#contactid').val(contactid);
		var xml = getFormValues(f,currentXML);

		var xmlstring = '<CONTACT>';
		for (i = 0;i < f.elements.length; i++){
			xmlstring += '<' + f.elements[i].name + '>' + f.elements[i].value + '</' + f.elements[i].name + '>';
		}
		xmlstring += '</CONTACT>';

		try
		{
			xmlobject=new ActiveXObject("Microsoft.XMLDOM");
			xmlobject.async="false";
			xmlobject.loadXML(xmlstring);
		}
		catch(e)
		{
			parser = new DOMParser();
			xmlobject = parser.parseFromString(xmlstring, "text/xml");
		}
		//var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml");
		
		if (submitXML(uri,xmlobject,method))
		{
			getLocation(URL);
		}
		else
		{
			//alert('failed');
		}
	} else {
		scroll(0,0);
	}
  return;
}

function createNewXmlDoc(rootTagName,namespaceURL){

		if (!rootTagName) rootTagName = "";
		if (!namespaceURL) namespaceURL = "";
		if (document.implementation && document.implementation.createDocument) {
			// This is the W3C standard way to do it
			return document.implementation.createDocument(namespaceURL, rootTagName, null);
		}
		else { // This is the IE way to do it
			// Create an empty document as an ActiveX object
			// If there is no root element, this is all we have to do
			var doc = new ActiveXObject("MSXML2.DOMDocument");
			// If there is a root tag, initialize the document
			if (rootTagName) {
				// Look for a namespace prefix
				var prefix = "";
				var tagname = rootTagName;
				var p = rootTagName.indexOf(':');
				if (p != -1) {
					prefix = rootTagName.substring(0, p);
					tagname = rootTagName.substring(p+1);
				}
				// If we have a namespace, we must have a namespace prefix
				// If we don't have a namespace, we discard any prefix
				if (namespaceURL) {
					if (!prefix) prefix = "a0"; // What Firefox uses
				}
				else prefix = "";
				// Create the root element (with optional namespace) as a
				// string of text
				var text = "<" + (prefix?(prefix+":"):"") +  tagname +
						(namespaceURL
						 ?(" xmlns:" + prefix + '="' + namespaceURL +'"')
						 :"") +
						"/>";
				// And parse that text into the empty document
				doc.loadXML(text);
			}
			return doc;
		}
	}


function submitPaymentForm(uri,URL,method){ 
	if($('#currentForm').valid() || document.getElementById('Total').value == '0.00' || document.getElementById('Total').value == '0')
	{
	
	
	  document.getElementById('NationalDues').value = filterNum(document.getElementById('NationalDues').value)
    if(document.getElementById('StateDues'))
    {
      document.getElementById('StateDues').value = filterNum(document.getElementById('StateDues').value)
      document.getElementById('StateMinimum').value = filterNum(document.getElementById('StateMinimum').value)
    }
		document.getElementById('Fees').value = filterNum(document.getElementById('Fees').value)
		document.getElementById('NationalMinimum').value = filterNum(document.getElementById('NationalMinimum').value)
		document.getElementById('NationalAdvisorContributionFee').value = filterNum(document.getElementById('NationalAdvisorContributionFee').value)
    if(document.getElementById('ChapterAdvisorContributionFee'))
    {
      document.getElementById('ChapterAdvisorContributionFee').value = filterNum(document.getElementById('ChapterAdvisorContributionFee').value)
    }
		document.getElementById('Total').value = filterNum(document.getElementById('Total').value)
	  
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);
		//debug(xml, true);
    if(xml.xml != undefined)
    {
      var strXml = xml.xml;
    }
    else 
    {
      var serializer = new XMLSerializer();
      var strXml = serializer.serializeToString(xml);
    }
		if(submitPaymentXML(uri,xml,method)) {
			var ui = getCookie('userId');
			var ii = getCookie('newInvoiceId'); 
      if(URL != null) {
        document.location= baseuri + "/davinci/fccla/" + URL +'?userid='+ui+"&invoiceid="+ii;
      }
		} else {
			alert('failed');
		}
	}else {
		scroll(0,0);
	}
  return ;
}

function submitPaymentChapterState(uri,URL,method){ 
	if($('#currentForm').valid()){
    var uri = uri +'/'+ getCookie('state');
		var f = document.currentForm;
    //debug(currentXML,true);
		var xml = getFormValues(f,currentXML);
    //debug("uri= " + uri);
		//debug("method= " + method);
		//debug(xml,true);
    //return ;
		if(submitPaymentChapterStateXML(uri,xml,method)){
			var ui = getCookie('userId');
			var ii = getCookie('newInvoiceId');
			if (getCookie('all').length > 0)
			{
				delCookie('all');
			}
			document.location= baseuri + "/davinci/fccla/" + URL +'?userid='+ui+"&invoiceid="+ii;
		}
		else
		{
			alert('failed');
		}
	}else {
		scroll(0,0);
	}
    return ;
}

function submitPaymentChapterStateXML(uri,xml,method){
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      //debug("method= " + method);
			//debug("uri= " + uri);
			//return;
			xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      if(method == "POST")
      {
      	if(xml.xml != undefined)
      	{
      		var strXml = xml.xml;
      	}
      	else 
      	{
      		var serializer = new XMLSerializer();
      		var strXml = serializer.serializeToString(xml);
      	}
        
      	body=escape(strXml); 
      	body=body.replace(/\+/g,"%2B");
      	body = "post=" + body;
      	//debug(body);
				//return;
      	xmlHttpRequest.send(body)
      }
      else
      {
      	xmlHttpRequest.send(xml);
      }
      if(xmlHttpRequest.status != 200)
      {
        alert(xmlHttpRequest.status);
      }
      var resultXml = xmlHttpRequest.responseXML;
      invoiceid = SelectSingleNode(resultXml,"//chapterpayment/invoiceid");
		if(invoiceid.firstChild != null)
		{	
			setCookie('newInvoiceId',invoiceid.firstChild.nodeValue,30);
		}
      success = true;
    }
    else
    {
      alert("unable to create request object");
      success =  false;
    }
    return success;
}

function submitPaymentXML(uri,xml,method){
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      var userid = getCookie('userId');
      uri = uri + "userid/" + userid;     
      xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      if(method == "POST")
      {
      	if(xml.xml != undefined)
      	{
      		var strXml = xml.xml;
      	}
      	else 
      	{
      		var serializer = new XMLSerializer();
      		var strXml = serializer.serializeToString(xml);
      	}
      	 body=escape(strXml); 
      	 body=body.replace(/\+/g,"%2B");
      	 body = "post=" + body;
      	//debug(strXml, false); 
      	xmlHttpRequest.send(body)
      }
      else
      {
      	xmlHttpRequest.send(xml);
      }
      if(xmlHttpRequest.status != 200)
      {
        alert(xmlHttpRequest.status);
      }
      var resultXml = xmlHttpRequest.responseXML;
			//debug(resultXml,true);
      invoiceid = SelectSingleNode(resultXml,"//chapterpayment/invoiceid");
			if(invoiceid)
			{	
				setCookie('newInvoiceId',invoiceid.firstChild.nodeValue,30);
			}
      success = true;
    }
    else
    {
      alert("unable to create request object");
      success =  false;
    }
    return success;
}

/*
function middleLevelCheck(url, middleUrl){
	var middle = getCookie('isMiddleLevel');
	if (middle == '1' || middle == 'true' || middle == 'True' || middle == 'TRUE' || middle == true)
	{
		//check if they have submitted students previously (ajax)
		$.ajax({
			type: 'GET',
			url: baseuri + '/fccla/~fccla/chapterfee/userid/' + getCookie('userId'),
			async: false,
			dataType: 'xml',
			error: function(){
				alert('Error loading XML document');
			},
			success: function(xml){
				$(xml).find('chapterpayment').each(function(){
					MLNF = $(this).find('MiddleLevelNationalFee').text();
					MLSF = $(this).find('MiddleLevelStateFee').text();
					MLFAP = $(this).find('MiddleLevelFeesAlreadyPaid').text();
					if (parseInt(MLFAP) >= (parseInt(MLNF) + parseInt(MLSF))){
						//if they have previously submitted students, submit students (no payment)
						submitMiddleLevelStudents(middleUrl);
					} else {
						//if they have NOT submitted previously, redirect to normal payment process
						getLocation(url);
					}
				});
			}			
		});
	} else {
		getLocation(url);
	}
}
*/

/*
function submitMiddleLevelStudents(middleUrl) {
	alert('This chapter has previously submitted students.');
	//post to new middle level chapter fee resource
	$.ajax({
		type: 'POST',
		url: baseuri + '/fccla/~fccla/middlechapterfee/userid/' + getCookie('userid'),
		data: currentXML,
		async: false,
		datatype: 'xml',
		error: function(){
			alert('Error POSTing XML document');
		},
		success: function(){
			getLocation(middleUrl);
		}
	});
	
}
*/

function submitUnaffiliatedXML(uri,URL,method){ 
	//need to add a check for middle level and an ajax call to see if they've submitted any students
	//basically need to know if they have any invoices.
	//if the chapter has invoices, we need to break out of this function and just add the students.
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      var userid = getCookie('userId');
      uri = uri + "/userid/" + userid;   
      xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      var xml = getCheckBox();
				
			var strXml;
			if(xml.xml != undefined)
			{
				strXml = xml.xml;
			}
			else 
			{
				var serializer = new XMLSerializer();
				strXml = serializer.serializeToString(xml);
			}
			body=escape(strXml);
			//alert(body);
			//return;
			if (body != '%3CRoot/%3E%0D%0A' && body != '%3CRoot/%3E')
			{
				body=body.replace(/\+/g,"%2B");
				body = "post=" + body;
				xmlHttpRequest.send(body)
			 
				if(xmlHttpRequest.status != 200)
				{
						alert(xmlHttpRequest.status);
				}
				getLocation(URL);
				success = true;
			}
			else document.location = document.location;
    }
    else
    {
      alert("unable to create request object");
      success =  false;
    }
    return success;
}


function getAllUnaffiliated(state){
	
	$.ajax({
		type: 'GET',
		url: baseuri + '/fccla/~fccla/studentshort',
		data: 'state=' + state + '&status=unaffiliated&rand=' + new Date().getTime(),
		async: false,
		dataType: 'xml',
		error: function(){
			alert('Error loading XML document');
		},
		success: function(xml){
			currentXML = xml;
		}
	});
	return currentXML;
}


function submitStateUnaffiliatedXML(uri,URL,method,quantity){ 

	var success = false
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      var state = getCookie("state");
      uri = uri + "/" + state;   
      xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			// if state == 'ALL' then XML = get ALL unaffiliated students for a state that are not deleted
			var xml;
			if (quantity == 'all')
			{
				if (confirm('You are about to affiliate all of the unaffiliated students in your state, would you like to continue?')){
				xml = getAllUnaffiliated(state);
				setCookie('all','true',30);
				}
				else return;
			}
			else
			{
				xml = getCheckBox();
				if (getCookie('all').length > 0)
				{
					delCookie('all');
				}
			}
			
			//REMOVE NEXT TWO LINES OF DEBUGGING CODE
			//debug (xml, true);
			//return;
			var strXml;
			if(xml.xml != undefined)
			{
				strXml = xml.xml;
			}
			else 
			{
				var serializer = new XMLSerializer();
				strXml = serializer.serializeToString(xml);
			}
			body=escape(strXml); 
			if (body != '%3CRoot/%3E%0D%0A' && body != '%3CRoot/%3E')
			{
				body=body.replace(/\+/g,"%2B");
				body = "post=" + body;
				xmlHttpRequest.send(body)
				
				if(xmlHttpRequest.status != 200)
				{
						alert(xmlHttpRequest.status);
				}
				if (quantity == 'all')
				{
					document.location = URL + '?state=' + getCookie('state') + '&all=true';
				}
				else
				{
					document.location = URL + '?state=' +getCookie('state');
				}
				success = true;
			}
			else document.location = document.location;
    }
    else
    {
      alert("unable to create request object");
      success =  false;
    }
    return success;
}

function getCurrentEmail(){
  if (document.getElementById('emailaddress')){
		currentEmail = document.getElementById('emailaddress').value;
	}
	if (document.getElementById('primaryadviserInfo_emailaddress')){
		currentEmail = document.getElementById('primaryadviserInfo_emailaddress').value;
	}
	//currentEmail = document.getElementById('emailaddress').value;
	//debug(currentEmail);
}

function submitChapterAdviserAccount(uri,URL,method,id){ 
	//debug(currentEmail);
	//debug(document.getElementById('emailaddress').value);
	if($('#currentForm').valid()) {
	  if(currentEmail != document.getElementById('emailaddress').value) {
	    if (confirm('You are about to change your email address, this will change the user name you use to log into the system, proceed?')) { 
	      var f = document.currentForm;
		    var xml = getFormValues(f,currentXML);	
		    if(submitXMLWithID(uri,xml,method,id)){
			  	getLocation(URL);
	      } 
	    } else {
	      return;
	    }
	  } else {
	    var f = document.currentForm;
		  var xml = getFormValues(f,currentXML);	
		  if(submitXMLWithID(uri,xml,method,id)){
			 	getLocation(URL);
		  }
		}
	}else {
		scroll(0,0);
	}
  return;
}


function submitFormXMLWithID(uri,URL,method,id){ 
	if($('#currentForm').valid()){
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);	
		if(submitXMLWithID(uri,xml,method,id)){
				getLocation(URL);
		}
	}else {
		scroll(0,0);
	}
  return;
}

// delete when cookies are gone. submit the form and go to a page document.location = 
function submitFormXMLDocLocation(uri,URL,method,id){ 
	if($('#currentForm').valid()){
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);	
		if(submitXMLWithID(uri,xml,method,id)){
				document.location= URL;
		}
	}else {
		scroll(0,0);
	}
  return;
}


// submit the form and go to a page document.location = 
function formSubmit(uri,URL,method,id){ 
	if($('#currentForm').valid()){
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);	
		//debug(xml, true);
		if(xmlSubmit(uri,xml,method,id)){
				//console.log(URL);
				document.location= URL;
		}
	}else {
		scroll(0,0);
	}
  return;
}

// submit the form and go to a page document.location = 
function formStateUserSubmit(uri,URL,method,id){ 
	if($('#currentForm').valid()){
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);	
		if(xmlSubmit(uri,xml,method,id)){
				//console.log(URL);
				document.location= URL+"?userid="+getCookie('userId');
		}
	}else {
		scroll(0,0);
	}
  return;
}



function xmlSubmit(uri,xml,method,id){
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest) {
      var uri = uri + id;
      xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      if(method == "POST"){
      	if(xml.xml != undefined){
      		var strXml = xml.xml;
      	} else {
      		var serializer = new XMLSerializer();
      		var strXml = serializer.serializeToString(xml);
		    }
      	 body=escape(strXml); 
      	 body=body.replace(/\+/g,"%2B");
      	 body = "post=" + body;
      	 xmlHttpRequest.send(body)
      } else{  
	      	xmlHttpRequest.send(xml);
      } if(xmlHttpRequest.status != 200){
		    alert(xmlHttpRequest.status);
    } else {
		  success = true;
      var resultText = null;
      if(xmlHttpRequest.responseText){
        resultText = xmlHttpRequest.responseText;
      } else {
        var resultXml = SelectSingleNode(xmlHttpRequest.responseXML,"//Error");
        if(resultXml) {
          resultText = resultXml.innerText;
        }
      } if(xmlHttpRequest.responseText.indexOf('<Error>Duplicate contact found') != -1 ) {
        alert('A record aleady exists with the same combination of First name, Middle name and Last Name. Please edit one of these and try again.');
        success = false;
      }
	  }
   } else {
      alert("unable to create request object");
      success =  false;
   }
   return success;
}


function submitXMLWithID(uri,xml,method,id){
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest) {
      var uri = uri + "/" + getCookie(id);
      xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      if(method == "POST"){
      	if(xml.xml != undefined){
      		var strXml = xml.xml;
      	} else {
      		var serializer = new XMLSerializer();
      		var strXml = serializer.serializeToString(xml);
		    }
      	 body=escape(strXml); 
      	 body=body.replace(/\+/g,"%2B");
      	 body = "post=" + body;
      	 xmlHttpRequest.send(body)
      } else {  
				xmlHttpRequest.send(xml);
      } 
			if(xmlHttpRequest.status != 200){
		    alert(xmlHttpRequest.status);
			} else {
		  success = true;
      var resultText = null;
      if(xmlHttpRequest.responseText){
        resultText = xmlHttpRequest.responseText;
      } else {
        var resultXml = SelectSingleNode(xmlHttpRequest.responseXML,"//Error");
        if(resultXml) {
          resultText = resultXml.innerText;
        }
      } if(xmlHttpRequest.responseText.indexOf('<Error>Duplicate contact found') != -1 ) {
        alert('A record aleady exists with the same combination of First name, Middle name and Last Name. Please edit one of these and try again.');
        success = false;
      }
	  }
   } else {
      alert("unable to create request object");
      success =  false;
   }
   return success;
}



function submitXML(uri,xml,method){
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();

    if (xmlHttpRequest){
      var userid = getCookie('userId');
      uri = uri + "/userid/" + userid; 
			
      xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      if(method == "POST") {
      	if(xml.xml != undefined)
      	{
      		var strXml = xml.xml;
      	}
      	else 
      	{
      		var serializer = new XMLSerializer();
      		var strXml = serializer.serializeToString(xml);
				}
      	 body=escape(strXml); 
      	 body=body.replace(/\+/g,"%2B");
      	 body = "post=" + body;
				 
      	xmlHttpRequest.send(body)
      }
      else
      {  
				xmlHttpRequest.send(xml);
      }
      if(xmlHttpRequest.status != 200)
      {
			
      }
			else
			{
				success = true;
				var resultText = null;
				if(xmlHttpRequest.responseText)
				{
					resultText = xmlHttpRequest.responseText;
				}
				else
				{
					var resultXml = SelectSingleNode(xmlHttpRequest.responseXML,"//Error");
					if(resultXml)
					{
						resultText = resultXml.innerText;
					}
				}
				
				if(xmlHttpRequest.responseText.indexOf('<Error>Duplicate contact found') != -1 )
				{
					alert('A record aleady exists with the same combination of First name, Middle name and Last Name. Please edit one of these and try again.');
					success = false;
				}
			}
      //var resultXml = xmlHttpRequest.responseXML; 
      
    }
    else
    {
      alert("unable to create request object");
      success = false;
    }
    return success;
}

function submitXMLNoId(uri,xml,method){
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      if(method == "POST")
      {
      	if(xml.xml != undefined)
      	{
      		var strXml = xml.xml;
      	}
      	else 
      	{
      		var serializer = new XMLSerializer();
      		var strXml = serializer.serializeToString(xml);
				}
      	 body=escape(strXml); 
      	 body=body.replace(/\+/g,"%2B");
      	 body = "post=" + body;
      	 
      	xmlHttpRequest.send(body)
      }
      else
      {  
	      	xmlHttpRequest.send(xml);
      }
      if(xmlHttpRequest.status != 200)
      {
				alert(xmlHttpRequest.status);
      }
			else
			{
				success = true;
				var resultText = null;
				if(xmlHttpRequest.responseText)
				{
					resultText = xmlHttpRequest.responseText;
				}
				else
				{
					var resultXml = SelectSingleNode(xmlHttpRequest.responseXML,"//Error");
					if(resultXml)
					{
						resultText = resultXml.innerText;
					}
				}
				
				if(xmlHttpRequest.responseText.indexOf('<Error>Duplicate contact found') != -1 )
				{
					alert('A record aleady exists with the same combination of First name, Middle name and Last Name. Please edit one of these and try again.');
					success = false;
				}
			}
      //var resultXml = xmlHttpRequest.responseXML; 
      
    }
    else
    {
      alert("unable to create request object");
      success =  false;
    }
    return success;
}

function hideButtons()
{
	document.getElementById("buttons").style.display = 'none';
}


function setFormValues(f,xml){
	for (var i=0; i<f.elements.length; i++)
	{

		if (f.elements[i].type=="text" || f.elements[i].type=="textarea" || f.elements[i].type=="password" || f.elements[i].type=="hidden")
		{
			var elementName = f.elements[i].name;
			if(elementName != null)
			{
				elementName = "//" +elementName.replace(/_/g, "/");
				if(SelectSingleNode(xml,elementName) != null && SelectSingleNode(xml,elementName).firstChild != null)
				{
				  if(f.elements[i].name == 'amount'){
				     document.getElementById(f.elements[i].name).value= formatCurrency(SelectSingleNode(xml,elementName).firstChild.nodeValue);
				  } else if(f.elements[i].name == 'latefee'){
				     document.getElementById(f.elements[i].name).value= formatCurrency(SelectSingleNode(xml,elementName).firstChild.nodeValue);
				  } else {
					  document.getElementById(f.elements[i].name).value=SelectSingleNode(xml,elementName).firstChild.nodeValue;
					}
				}
			}
		}
		else if(f.elements[i].type=="checkbox" && f.elements[i].name != "billingsameaddress"){
      
		  var elementName = f.elements[i].name;
      if(elementName.split("_")[0] != "nacf")
      {
          elementName = "//" +elementName.replace(/_/g, "/");
      }
		  if(SelectSingleNode(xml,elementName) != null && SelectSingleNode(xml,elementName).firstChild != null){
		      
		      if(SelectSingleNode(xml,elementName).firstChild.nodeValue == 'True'){
		        document.getElementById(f.elements[i].name).checked = true;
		      } else if (SelectSingleNode(xml,elementName).firstChild.nodeValue == 'False'){
		        document.getElementById(f.elements[i].name).checked = false;
		      }
			} else {
			  document.getElementById(f.elements[i].name).checked = false;
			}
		}
		else if (f.elements[i].type == "select-one")
		{
			var elementName = f.elements[i].name;
			var curElementName = elementName
			if(elementName != null)
			{
				elementName = "//" +elementName.replace(/_/g, "/");
				if(SelectSingleNode(xml,elementName) != null && SelectSingleNode(xml,elementName).firstChild != null)
				{
					for (var t=0; t<document.getElementById(f.elements[i].name).length; t++)
					{
							if(SelectSingleNode(xml,elementName).firstChild.nodeValue == document.getElementById(f.elements[i].name).options[t].value)
							{
								document.getElementById(f.elements[i].name).options[t].selected = true
							}
					}
				}
				
				if(curElementName == 'mailingaddressInfo_state' && SelectSingleNode(xml,elementName).firstChild == null){
					
					for (var t=0; t<document.getElementById(f.elements[i].name).length; t++)
					{
							if(getCookie('state') == document.getElementById(f.elements[i].name).options[t].value)
							{
								document.getElementById('mailingaddressInfo_state').options[t].selected = true
							}
					}
				}
				
				if(curElementName == 'mailingaddressInfo_country' && SelectSingleNode(xml,elementName).firstChild == null){
					
					for (var t=0; t<document.getElementById(f.elements[i].name).length; t++)
					{
							if(getCookie('country') == document.getElementById(f.elements[i].name).options[t].value)
							{
                
								document.getElementById('mailingaddressInfo_country').options[t].selected = true
							}
							//else{
								//document.getElementById('US').options[t].selected = true
							//}
					}
				}
			}
		}
	}
	return;
}
  
function getFormValues(f,xml){
	//debug(xml, true);
	for (var i=0; i<f.elements.length; i++){
		if (f.elements[i].type=="text" || f.elements[i].type=="textarea" || f.elements[i].type=="password" || f.elements[i].type=="hidden" || f.elements[i].type=="hidden-use-inline-value"  || f.elements[i].type=="checkbox" || f.elements[i].type == "select-one" || f.elements[i].type=="select"  && f.elements[i].name != "billingsameaddress"  /*&& f.elements[i].name != "passwordConfirm"*/){
			var elementName = f.elements[i].name;
			//alert("elementName: " + elementName + "elementType: " + f.elements[i].type); //-> name
			if(elementName != null)
			{
				//debug(elementName.substring(0,5));
				if (elementName.substring(0,5) != 'nacf_') {
					//debug(elementName);
					elementName = "//" +elementName.replace(/_/g, "/");
					var node = SelectSingleNode(xml,elementName);
					if(!node){
						var nodeNames = f.elements[i].name.split('_');
						node = createXPathNodes(xml, xml.firstChild, nodeNames, 0, "//" + nodeNames[0]);					
					}
					var elementVal = "";
					if(node){
						//***debug
						// var linetype = f.elements[i].type;
						// var firstchild = (node.firstChild ? true : false);
						// var linevalue = f.elements[i].value;
						// var lineid = f.elements[i].name;
						// var str = lineid + " firstChild: " + firstchild + " " + linetype + " " + linevalue;
						// debug(str);
						//***debug
						if(node.firstChild){
							 if(f.elements[i].type=="checkbox"){
									elementVal = f.elements[i].checked; 
									if(elementVal == 'True' || elementVal == true ){
										elementVal = 'true';
									} else {
										elementVal = 'false';
									}
									 node.firstChild.nodeValue = (elementVal == '' ? false : elementVal);
								} else {								
									elementVal = f.elements[i].value;
									//debug('elementName: ' + elementName + ' elementType: ' + f.elements[i].type + ' elementValue: ' + elementVal);
									node.firstChild.nodeValue = (elementVal == '' ? blankFieldIndicator : elementVal);
								}
						} else {
							if(f.elements[i].type=="checkbox"){
									elementVal = f.elements[i].checked;
									//***debug
									//var testtext = f.elements[i].name + " " + elementVal
									//debug(testtext);
									//***debug
									if(elementVal == 'True' || elementVal == true ){
										elementVal = 'true';
									} else {
										elementVal = 'false';
									}
									//alert(elementVal);
									//node.firstChild.nodeValue = (elementVal == '' ? false : elementVal);
								} else {
									elementVal = f.elements[i].value;
									//debug(elementVal);
									//node.firstChild.nodeValue = (elementVal == '' ? blankFieldIndicator : elementVal);
								}
							var textToSave = (elementVal == '' ? blankFieldIndicator : elementVal);
							var textnode = xml.createTextNode(textToSave);
							node.appendChild(textnode)
						}
					}
				}
			}
		}
	}
	//debug(xml,true)
	return xml;
}

function getMemberXML(uri) {
    var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
    	var contactid = getCookie('contactid');
      	uri = uri + contactid;
      	
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
		xmlHttpRequest.open(method, uri, true);
 		xmlHttpRequest.onreadystatechange=function() 
 		{
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
   				var f = document.currentForm;
				setFormValues(f,currentXML);
  			}
  		}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return ;
}

function SelectSingleNode(xmlDoc, elementPath){
        if(window.ActiveXObject)
        {
          return xmlDoc.selectSingleNode(elementPath);
        }
        else
        {
          var xpe = new XPathEvaluator();
          var nsResolver = xpe.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
          var results = xpe.evaluate(elementPath,xmlDoc,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
          return results.singleNodeValue; 
        }
    }
    
    
    
    
/* end forms */

function getAdviser() {
	var f = document.currentForm;
	for(var i = 0; i < f.primaryadviser.options.length; i++)
	{	
		if(f.primaryadviser.options[i].selected)
		{
			if (f.email){
				f.email.value = f.primaryadviser.options[i].id;
			}
			if (f.primaryadviserInfo_emailaddress){
				f.primaryadviserInfo_emailaddress.value = f.primaryadviser.options[i].id;
			}
		}
	}
}

function deleteMeeting(id, x, method){

	if (confirm('Are you sure you want to delete this meeting?')) 
	{ 
		uri = baseuri + '/fccla/~fccla/meeting/' + id;
		var success = false;
		var xmlHttpRequest=getXMLHttpRequest();
    	if (xmlHttpRequest)
    	{
			xmlHttpRequest.open(method, uri, false);
   	 		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    		xmlHttpRequest.send(null);
    		window.location.reload();
    	}
    	else
   		{
      		alert("unable to create request object");
    	}
    	
    	return;
	} else { 
			
		return;
	};
	
}

function checkForPrimaryAdviser(id){

	var success;
	$.ajax({
		type: 'GET',
		url: baseuri + '/fccla/~fccla/chapterbyprimaryadviser?userid=' + id + '&rand=' + new Date().getTime(),
		async: false,
		dataType: 'xml',
		error: function(){
			alert('Error loading XML document');
		},
		success: function(xml){
			$(xml).find('Root').each(function(){
				success = $(this).find('PrimaryAdviser').text();
			});
		}			
	});
	return success;
}

function restoreUser(id)
{
	if (confirm('Are you sure you want to restore this user?')) {
		$.ajax({
		 type: 'PUT',
		 url: baseuri + '/fccla/~fccla/contactrestore?userid=' + id,
		 async: false,
		 dataType: 'xml',
		 data: '<root/>',
		 success: function(){
			 //alert( "Data Saved: " + msg );
			 document.location = document.location;
		 }
	 });
	} else {
		return;
	}
}
 
function deleteRequest(id, uri, method, payment){
	var userid = getCookie('userId');
	// if(userid == id){
		// alert('You cannot delete the primary adviser.');
		// return;
	// }
	if(userid == id){
		alert('You cannot delete your own account.');
		return;
	}
	// FIND OUT IF USER IS A CURRENT PRIMARY ADVISER
	var primaryadviser = checkForPrimaryAdviser(id);
	// IF SO,...
	if (primaryadviser == 'True'){
		var message = 'You cannot delete a primary adviser.\n\nPlease update the chapter\'s primary adviser and try your delete again.';
		alert(message);
		return;
	}
	
	if (confirm('Are you sure you want to delete?')) {
		var returnmessage = 'Deleted';
		if (typeof(payment) != 'undefined'){
			returnmessage = checkAffiliation(id);
		}
		if (returnmessage){
			uri = uri + id;
			var xmlHttpRequest=getXMLHttpRequest();
				if (xmlHttpRequest){
					xmlHttpRequest.open('DELETE', uri, false);
					xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
					xmlHttpRequest.send(null);
					window.location.reload();
				}	else {
						alert("Unable to create request object");
				}
			alert(returnmessage);
			return;
		}
		else 
		{
			alert('Unable to create payment record.');
			return;
		}
	} else { 
		return;
	};
	
}

function checkAffiliation(id){
	var message = '';
	var uri = baseuri + "/fccla/~fccla/DeleteCredit";
	var method = "POST";
	var xmlHttpRequest=getXMLHttpRequest();
	if (xmlHttpRequest)
	{
		xmlHttpRequest.open(method, uri, false);
		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		
		currentXML = '<DELETECREDIT><userid>' + id + '</userid></DELETECREDIT>';
		
		body=escape(currentXML); 
		body=body.replace(/\+/g,"%2B");
		body = "post=" + body;
		 
		xmlHttpRequest.send(body);
		
		if(xmlHttpRequest.status != 200)
		{
			alert(xmlHttpRequest.status);
			return false;
		}
		else
		{
			//alert('Payment / Credit Processed');
			currentXML = xmlHttpRequest.responseXML;
			var message = SelectSingleNode(currentXML, "//message").firstChild.nodeValue;
			return message;
		}		
	}
	else
	{
		alert("Unable to create request object");
		return false;
	}	
}

function deleteAdmin(id, uri, method){

	var userid = getCookie('userId');
	
	if(userid == id){
		alert('You cannot delete this Admin.');
		return;
	}
	
	if (confirm('Are you sure you want to delete?')) { 
		uri = uri + id;
		var success = false;
		var xmlHttpRequest=getXMLHttpRequest();
    	if (xmlHttpRequest){
				xmlHttpRequest.open('DELETE', uri, false);
   	 		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    		xmlHttpRequest.send(null);
    	//	window.location.reload();
    	} else {
      		alert("unable to create request object");
    	}
    	return;
	} else { 
		return;
	};
}

function deleteAll(){
if (confirm('You are about to delete more than one user - are you sure?')) 
	{
	for(var i=0;i<allCheckBoxes.length;i++){
		if(allCheckBoxes[i][1])
		{
			if(getCookie("userId") != allCheckBoxes[i][0])
			{
				uri = baseuri + "/fccla/~fccla/contact/" + allCheckBoxes[i][0];
				var success = false;
				var xmlHttpRequest=getXMLHttpRequest();
    			if (xmlHttpRequest)
    			{
					xmlHttpRequest.open("DELETE", uri, false);
   	 				xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    				xmlHttpRequest.send(null);
    			}
    			else
   				{
      				alert("unable to create request object");
    			}
    		}
    		else
    		{
    			alert("You cannot delete the primary adviser.");
    		}
    	
		}
	}
	window.location.reload();
	}
}
function editRequest(id, locationURL){
	setCookie('contactid',id,30);
	document.location=locationURL+'?userid='+id;
}

function editContact(id, locationURL){
	document.location=locationURL+'?contactid='+id;
}


function autoFillBilling(){
	if(!autoFillBill){
	var f=document.currentForm;
	f.schoolInfo_billingaddressInfo_address1.value = f.schoolInfo_mailingaddressInfo_address1.value
	f.schoolInfo_billingaddressInfo_address2.value  = f.schoolInfo_mailingaddressInfo_address2.value
	f.schoolInfo_billingaddressInfo_city.value  = f.schoolInfo_mailingaddressInfo_city.value
	f.schoolInfo_billingaddressInfo_state.value  = f.schoolInfo_mailingaddressInfo_state.value
	f.schoolInfo_billingaddressInfo_zip.value  = f.schoolInfo_mailingaddressInfo_zip.value
	f.schoolInfo_billingaddressInfo_country.value  = f.schoolInfo_mailingaddressInfo_country.value
	autoFillBill = true;
	}
	else{
		autoFillBill = false;
	}
}

function autoFillBillingSchool(){
	if(!autoFillBill){
	var f=document.currentForm;
	f.billingaddressInfo_address1.value = f.mailingaddressInfo_address1.value
	f.billingaddressInfo_address2.value  = f.mailingaddressInfo_address2.value
	f.billingaddressInfo_city.value  = f.mailingaddressInfo_city.value
	f.billingaddressInfo_state.value  = f.mailingaddressInfo_state.value
	f.billingaddressInfo_zip.value  = f.mailingaddressInfo_zip.value
	f.billingaddressInfo_country.value  = f.mailingaddressInfo_country.value
	autoFillBill = true;
	}
	else{
		autoFillBill = false;
	}
}

function getXMLString(xml){
	return xml.xml ? xml.xml : (new XMLSerializer()).serializeToString(xml); 
}

function getXMLHttpRequest(){
		try
    	{
      		xmlHttpRequest=new XMLHttpRequest();
   	 	}
    	catch (e)
   		{
      		try
      		{
        		xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP"); 
      		}
      		catch (e)
      		{
       			xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
      		}
    	}   
    	return xmlHttpRequest;
}


function createXPathNodes(xml, immediateParentNode, nodeNames, currentNodeNameIndex, currentXpath){
	var newNode = SelectSingleNode(xml, currentXpath);
	if(!newNode)
	{
		try
    	{
      newNode = xml.createNode(1, nodeNames[currentNodeNameIndex], "");
			immediateParentNode.appendChild(newNode);
    	}
    	catch (e)
    	{
   			newNode = xml.createElement(nodeNames[currentNodeNameIndex]);
			
   			txtnode = xml.createTextNode("");
   			newNode.appendChild(txtnode);
   			immediateParentNode.appendChild(newNode);

    	}
	}
	currentNodeNameIndex++;
	if(currentNodeNameIndex < nodeNames.length)
	{
		currentXpath += '/' + nodeNames[currentNodeNameIndex];
		newNode = createXPathNodes(xml, newNode, nodeNames, currentNodeNameIndex, currentXpath);
	 }
	 return newNode;
}


function delCookie(cookie_name){
	//alert("got here");
  //var cookie_date = new Date();  // current date & time

  //cookie_date.setTime ( cookie_date.getTime() - 1 );

  //document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
  document.cookie = cookie_name += "=; expires=Thu, 01-Jan-70 00:00:01 GMT;";

}

function setCookie(c_name,value,expiredays){
 var exdate=new Date();exdate.setDate(exdate.getDate()+expiredays);
 document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());

}

function getCookie(c_name){ 
 if (document.cookie.length>0){ 

  c_start=document.cookie.indexOf(c_name + "=");

  if (c_start!=-1){   

   c_start=c_start + c_name.length+1; 

   c_end=document.cookie.indexOf(";",c_start);

   if (c_end==-1) c_end=document.cookie.length;

    return unescape(document.cookie.substring(c_start,c_end));

  } 

 }

 return "";

} 

function setCookie2(c_name,value,expiredays){ 
 var test = document.cookie;		

 var cookieItems = test.split(coockieDelim);

 var coockieSet = false; 

 if(cookieItems != null){

  for (var i=0; i<cookieItems.length; i=i+1){

     if((cookieItems[i] != null)&&(cookieItems[i].length > 0)){       

      var cookieValues = cookieItems[i].split(coockieValDelim);

      if(cookieValues[0] == c_name){

       cookieValues[1] = value;

       cookieItems[i] = c_name + coockieValDelim + value;

       coockieSet = true; 

       break;

      } 

     }

  }

 }

 if(coockieSet){

  for (var i=0; i<cookieItems.length; i=i+1){

   if((cookieItems[i] != null)&&(cookieItems[i].length > 0)){       

    var cookieValues = cookieItems[i].split(coockieValDelim);

    document.cookie = document.cookie + coockieDelim + cookieValues[0] + coockieValDelim + cookieValues[1];

   } 

  }  

 }else{

  document.cookie = document.cookie + coockieDelim + c_name + coockieValDelim + value;

 }  

}

function getCookie2(c_name){
 var answer = "43ab10c5-ecad-4fcc-a290-cf70de4648871ca"; 
 var test = document.cookie;		

 var cookieItems = test.split(coockieDelim); 

 if(cookieItems != null){

  for (var i=0; i<cookieItems.length; i=i+1){    

   if((cookieItems[i] != null)&&(cookieItems[i].length > 0)){     

    var cookieValues = cookieItems[i].split(coockieValDelim);

    alert(cookieValues[0]+' - '+ cookieValues[1]);

    if(cookieValues[0] == c_name){

     alert('in: '+cookieValues[0]+' - '+ cookieValues[1]);

     //answer = cookieValues[1] = value;

     break;

    }    

   }   

  }
 }  
 return answer;
}

function getLocation(URL){
	var ui = getCookie('userId');
	var chapterid = getCookie('ChapterId');
	var state = getCookie('state');
	var all = getCookie('all');
	var role = URL.split('_',1)
	if (URL.indexOf('?') != -1) URL = URL.split('?',1);
	
	if (URL == "Main_Menu.htm")
	{
		delCookie('fcclaidlookup');
	}
	
	if(URL == "Chapter_Adviser_Payment_CreditCard.htm")
  {
     URL = securebaseuri + "/davinci/fccla/" + URL + "?userid=" + ui;
  }
	
	else if (URL == "Admin_Manage_Chapter_Membership_Unaffiliated.htm")
	{
		URL = baseuri + "/davinci/fccla/" + URL + "?userid=" + ui + "&state=xx";
	}
	
	else if (URL == "Admin_Manage_Chapter_Membership_Students.htm")
	{
		URL = baseuri + "/davinci/fccla/" + URL + "?userid=" + ui + "&state=xx";
	}
	
	else if (URL == "State_Adviser_Manage_Chapter_Membership_Unaffiliated.htm"){
		URL = baseuri + "/davinci/fccla/" + URL + "?userid=" + ui + "&state=" + state + "&lastnamestart=a";
		if (all.length > 0 || all == true)
		{
			delCookie('all');
		}
	}
	
	else if (URL == "State_Adviser_Affiliate_Members.htm")
	{
		URL = baseuri + "/davinci/fccla/" + URL + "?userid=" + ui + "&state=" + state + "&lastnamestart=a";
	}
	
	else
  {
     URL = baseuri + "/davinci/fccla/" + URL + "?userid=" + ui;
  }
	
	// else
	// {
		// switch(URL)
		// {
			// case "Chapter_Adviser_Payment_CreditCard.htm":
				// URL = securebaseuri + "/davinci/fccla/" + URL + "?userid=" + ui;
			// break;
			
			// case "Admin_Manage_Chapter_Membership_Unaffiliated.htm":
				// URL = baseuri + "/davinci/fccla/" + URL + "?userid=" + ui + "&state=ak";
			// break;
			
			// case "State_Adviser_Affiliate_Members.htm":
				// URL = baseuri + "/davinci/fccla/" + URL + "?userid=" + ui + "&state=" + state + "&lastnamestart=a";
			// break;
			
			// default:
				// URL = baseuri + "/davinci/fccla/" + URL + "?userid=" + ui;
		// }
	// }
  // if(URL == "Chapter_Adviser_Payment_CreditCard.htm")
  // {
     // URL = securebaseuri + "/davinci/fccla/" + URL + "?userid=" + ui;
  // }
	// else if (URL == "Admin_Manage_Chapter_Membership_Unaffiliated.htm")
	// {
		// URL = baseuri + "/davinci/fccla/" + URL + "?userid=" + ui + "&state=ak";
	// }
	// else if (URL == "State_Adviser_Manage_Chapter_Membership_Unaffiliated.htm")
	// {
		// URL = baseuri + "/davinci/fccla/" + URL + "?userid=" + ui + "&state=" + getCookie('state') + "&lastnamestart=a";
	// }
	// else if (URL == "State_Adviser_Affiliate_Members.htm")
	// {
		// URL = baseuri + "/davinci/fccla/" + URL + "?userid=" + ui + "&state=" + getCookie('state') + "&lastnamestart=a";
	// }
  // else
  // {
     // URL = baseuri + "/davinci/fccla/" + URL + "?userid=" + ui;
  // }
  
	//URL+='?userid='+ui;
	
	if (chapterid.length > 0)
	{
		URL += '&chapterid='+chapterid;
	}
	
	if (all.length > 0)
	{
		URL += '&all=true';
	}
	
	switch(role)
	{
	case 'Admin':
	break;
	
	case 'State':
		URL += '&state='+state;
	break;
	
	case 'Chapter':
	break;

	default:
	}
	document.location=URL;
}

function findChapterByZip(){
	var zip = document.getElementById('zip').value;
	document.location = baseuri + "/davinci/fccla/Request_Chapter_School_List.htm?zip=" + zip;
}

function stateFindChapterByZip(){
	var zip = document.getElementById('zip').value;
	document.location = baseuri + "/davinci/fccla/State_School_List.htm?zip=" + zip;
}

function adminFindChapterByZip(){
	var zip = document.getElementById('zip').value;
	document.location = baseuri + "/davinci/fccla/Admin_School_List.htm?zip=" + zip;
}

function receivePayment(URL){
	//validate form ?
	
	
	//get form data
  var invoicenumber = $('#rpinvoicenumber').val();
	var checknumber = $('#rpchecknumber').val();
	var amount = $('#rpamount').val();
	var note = $('#rpnote').val();
	
	if (invoicenumber == '' || checknumber == '' || amount == '')
	{
		alert('You must enter a value for Invoice, Check and Amount');
		return;
	}
	
	//get payment schema and update with current values
	$.ajax({
		type: 'GET',
		url: baseuri + '/fccla/~fccla/ReceivedPayment/schema',
		async: false,
		dataType: 'xml',
		error: function(){
			alert('Error loading XML document');
		},
		success: function(xml){
			$(xml).find('RECEIVEDPAYMENT').each(function(){
				$(this).find('invoicenumber').text(invoicenumber);
				$(this).find('checknumber').text(checknumber);
				$(this).find('amount').text(amount);
				$(this).find('memo').text(note);
			});
			if(xml.xml != undefined)
				{
					currentXML = xml.xml;
				}
				else
				{
					var serializer = new XMLSerializer();
					currentXML = serializer.serializeToString(xml);
				}
		}				
	});
	//post xml to ReceivedPayment service
	var uri = baseuri + "/fccla/~fccla/ReceivedPayment";
	var method = "POST";
	var xmlHttpRequest=getXMLHttpRequest();
	if (xmlHttpRequest)
	{
		xmlHttpRequest.open(method, uri, false);
		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		
		body=escape(currentXML); 
		body=body.replace(/\+/g,"%2B");
		body = "post=" + body;
		 
		xmlHttpRequest.send(body)
		
		if(xmlHttpRequest.status != 200)
		{
			alert(xmlHttpRequest.status);
		}
		else
		{
			alert('Payment / Credit Processed');
			if (typeof(fcclaid) == 'undefined'){
				document.location = baseuri + '/davinci/fccla/' + URL + '?statelookup=' + statelookup;
			} else {
				document.location = baseuri + '/davinci/fccla/' + URL + '?fcclaid=' + fcclaid;
			}
		}		
	}
	else
	{
		alert("Unable to create request object");
	}		
}

function getLocationLookup() {
	//$('#chapterid_row').css("display","none");
	$('#rpinvoicenumber_row').hide();
	$('#rpchecknumber_row').hide();
	$('#rpamount_row').hide();
	$('#rpnote_row').hide();
	$('#zip_row').show();
	$('#btnlookupzip').show();
	$('#btnlookup').hide();
	$('#btngetinvoices').hide();
	$('#btnexit').hide();
	$('#btnlookupcancel').show();
	$('#btneditpayment').hide();
}

function cancelLocationLookup() {
	//$('#chapterid_row').css("display","block");
	$('#rpinvoicenumber_row').show();
	$('#rpchecknumber_row').show();
	$('#rpamount_row').show();
	$('#rpnote_row').show();
	$('#zip_row').hide();
	$('#btnlookupzip').hide();
	$('#btnlookup').show();
	$('#btngetinvoices').show();
	$('#btnexit').show();
	$('#schoollist').hide();
	$('#chapterlist').hide();
	$('#btnlookupcancel').hide();
	$('#btneditpayment').hide();
	$('#paydate_row').hide();
	$('#paycheck_row').hide();
	$('#payamount_row').hide();
	$('#paynote_row').hide();
}

function getPayment() {
	$('#btneditpayment').show();
	$('#rpinvoicenumber_row').hide();
	$('#rpchecknumber_row').hide();
	$('#rpamount_row').hide();
	$('#rpnote_row').hide();
	$('#zip_row').hide();
	$('#btnlookupzip').hide();
	$('#btnlookup').hide();
	$('#btngetinvoices').hide();
	$('#btnexit').hide();
	$('#schoollist').hide();
	$('#chapterlist').hide();
	$('#btnlookupcancel').show();
	$('#paydate_row').show();
	$('#paycheck_row').show();
	$('#payamount_row').show();
	$('#paynote_row').show();
}

function editPayment(paymentId) {
	$.ajax({
		type: 'GET',
		url: baseuri + '/fccla/~fccla/payment/' + paymentId + '&rand=' + new Date().getTime(),
		async: false,
		dataType: 'xml',
		error: function(){
			alert('Error loading XML document');
		},
		success: function(xml){
			$(xml).find('PAYMENT').each(function(){
				var date = $(this).find('date').text();
				var checknumber = $(this).find('checknumber').text();
				var amount = $(this).find('amount').text();
				var note = $(this).find('note').text();
				
				$('#paydate').val(date);
				$('#paynum').val(paymentId); 
				$('#paycheck').val(checknumber);
				$('#payamount').val(amount);
				$('#paynote').val(note);
				
				$('#paydate').datepicker({dateFormat: "mm/dd/yy"});
				
				if(xml.xml != undefined)
				{
					currentXML = xml.xml;
				}
				else
				{
					var serializer = new XMLSerializer();
					currentXML = serializer.serializeToString(xml);
				}
			});
			getPayment();
			//debug(currentXML);
		}	
	});
}

function updatePayment(URL) {
	//getFormValues(f,currentXML);
	var paymentId = $('#paynum').val();
	var date = $('#paydate').val();
	var checknumber = $('#paycheck').val();
	var amount = $('#payamount').val();
	var note = $('#paynote').val();
	//debug('paymentid= ' + paymentId + ' checknumber= ' + checknumber + ' amount= ' + amount + ' note= ' + note);
	//modify currentXML to include form values
	try
	{
		xmlobject=new ActiveXObject("Microsoft.XMLDOM");
		xmlobject.async="false";
		xmlobject.loadXML(currentXML);
	}
	catch(e)
	{
		parser = new DOMParser();
		xmlobject = parser.parseFromString(currentXML, "text/xml");
	}
	//currentXML = (new DOMParser()).parseFromString(currentXML, "text/xml");
	currentXML = xmlobject;
	//debug(currentXML,true);
	var checkNode = SelectSingleNode(currentXML, "//checknumber");
	if (checkNode.firstChild) {
		checkNode.firstChild.nodeValue = '';
	}
	var newchecknode = currentXML.createTextNode(checknumber);       
	checkNode.appendChild(newchecknode);
	
	var dateNode = SelectSingleNode(currentXML, "//date");
	if (dateNode.firstChild) {
		dateNode.firstChild.nodeValue = '';
	}
	var newdatenode = currentXML.createTextNode(date);       
	dateNode.appendChild(newdatenode);
	
	var amountNode = SelectSingleNode(currentXML, "//amount");
	if (amountNode.firstChild) {
		amountNode.firstChild.nodeValue = '';
	}
	var newamountnode = currentXML.createTextNode(amount);       
	amountNode.appendChild(newamountnode);
	
	var noteNode = SelectSingleNode(currentXML, "//note");
	if (noteNode.firstChild) {
		noteNode.firstChild.nodeValue = '';
	}
	var newnotenode = currentXML.createTextNode(note);       
	noteNode.appendChild(newnotenode);
	//PUT currentXML to payment service
	//debug(currentXML, true);
	submitXML(baseuri + '/fccla/~fccla/PAYMENT/' + paymentId, currentXML, "PUT");
	//Redirect to page with FCCLAID
	if (typeof(fcclaid) == 'undefined'){
		document.location = baseuri + '/davinci/fccla/' + URL + '?statelookup=' + statelookup;
	} else {
		document.location = baseuri + '/davinci/fccla/' + URL + '?fcclaid=' + fcclaid;
	}
}

function adminLookupSchool(URL)
{
	$('#btnlookupzip').hide();
	var zip = document.getElementById('zip').value;
	$.ajax({
		type: 'GET',
		url: baseuri + '/fccla/~fccla/schoollist',
		data: 'zip=' + zip + '&rand=' + new Date().getTime(),
		async: false,
		dataType: 'xml',
		error: function(){
			alert('Error loading XML document');
		},
		success: function(schoolxml){
			var textToInsert = '';
			$(schoolxml).find('SCHOOL').each(function(){
				var schoolid = $(this).find('schoolid').text();
				var schoolname = $(this).find('name').text();
				textToInsert = '<tr><td><a href="#" onclick="adminLookupChapter(\'' + schoolid + '\',\'' + URL + '\')">' + schoolname + '</a></td></tr>';
				$('#schoollist_table').append(textToInsert);
			});
			$('#schoollist').css("display","block");				
		}			
	});
}

function adminLookupChapter(schoolid,URL)
{
	$.ajax({
		type: 'GET',
		url: baseuri + '/fccla/~fccla/chaptershort',
		data: 'schoolid=' + schoolid + '&rand=' + new Date().getTime(),
		async: false,
		dataType: 'xml',
		error: function(){
			alert('Error loading XML document');
		},
		success: function(chapterxml){
			var textToInsert = '';
			$(chapterxml).find('CHAPTER').each(function(){
				var chaptername = $(this).find('name').text();
				var fcclaid = $(this).find('fcclaid').text();
				var status = $(this).find('status').text();
				textToInsert = '<tr><td><a href="#" onclick="adminSetChapterId(\'' + fcclaid + '\',\'' + URL + '\')">' + chaptername + '</a></td><td>' + fcclaid + '</td><td>' + status + '</td></tr>';
				$('#chapterlist_table').append(textToInsert);
			});
			$('#chapterlist').css("display","block");				
		}			
	});
}

function adminSetChapterId(fcclaid,URL){
	//debug(fcclaid);
	$('#chapterid').attr("value",fcclaid);
	cancelLocationLookup();
	//call function (ajax) to populate page form
	getInvoicesId(URL);
	//adminGetInvoices();
}

function getInvoicesId(URL){
	var chapterid = $('#chapterid').val();
	//debug(chapterid);
	var ui = getCookie('userId');
	URL = baseuri + "/davinci/fccla/" + URL;
	URL += '?userid=' + ui + '&fcclaid=' + chapterid;
	//debug(URL);
	document.location = URL;
}

function deletePayment(paymentid,x){
	if (confirm('Are you sure you wish to delete this payment?')) 
	{ 
		uri = baseuri + '/fccla/~fccla/payment/' + paymentid;
		var success = false;
		var xmlHttpRequest=getXMLHttpRequest();
    	if (xmlHttpRequest)
    	{
				xmlHttpRequest.open('DELETE', uri, false);
   	 		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    		xmlHttpRequest.send(null);
    		window.location.reload();
    	}
    	else
   		{
      		alert("unable to create request object");
    	}
    	return;
	} else { 
		return;
	};
}

// function adminGetInvoices() {
	// var chapterid = $('#chapterid').value;
	// $.ajax({
		// type: 'GET',
		// url: baseuri + '/fccla/~fccla/invoiceshort',
		// data: 'fcclaid=' + chapterid,
		// async: false,
		// dataType: 'xml',
		// error: function(){
			// alert('Error loading XML document');
		// },
		// success: function(chapterxml){
			// var textToInsert = '';
			// $(chapterxml).find('INVOICE').each(function(){
				// var invoiceid = $(this).find('invoiceid').text();
				// var invoicenumber = $(this).find('invoicenumber').text();
				// var date = $(this).find('date').text();
				// var documentnbr = $(this).find('documentnbr').text();
				// var type = $(this).find('type').text();
				// var amount = $(this).find('amount').text();
				// var note = $(this).find('note').text();
				// var ponumber = $(this).find('ponumber').text();
				// var checknumber = $(this).find('checknumber').text();
				// var cardtype = $(this).find('cardtype').text();
				// var paymentconfirmed = $(this).find('paymentconfirmed').text();
				// if (paymentconfirmed == 1){
					// paymentconfirmed = 'Yes';
				// } else {
					// paymentconfirmed = 'No';
				// }
				// var chapterid = $(this).find('chapterid').text();
				// var chaptername = $(this).find('name').text();
				// textToInsert = '<tr><td><a href="#" onclick="adminGetInvoice(' + invoiceid + ')">' + invoicenumber + '</a></td><td>' + date + '</td>';
				// textToInsert += '<td>' + documentnbr + '</td><td>' + type + '</td><td>' + amount + '</td>';
				// if (ponumber != null) textToInsert += '<td>PO: ' + ponumber + '</td>';
				// if (checknumber != null) textToInsert += '<td>Check: ' + checknumber + '</td>';
				// if (cardtype != null) textToInsert += '<td>Card: ' + cardtype + '</td>';
				// textToInsert += '<td>' + paymentconfirmed + '</td>';
				// textToInsert += '</tr>';
				// $('#chapterlist_table').append(textToInsert);
			// });
			// $('#chapterlist').css("display","block");				
		// }			
	// });
// }

// function adminGetInvoice(fcclaid) {
	// //do something
// }

 
// find 
function accountType(){
	var f=document.currentForm;
    var accountType = f.account_type.value;
    document.location = accountType;
}


// don't need this find
function GoToUrl(locationURL){	 
 document.location=locationURL;
}

// don't need this find
function GoToUrlId(locationURL,name,id){	
 //var temp = '?'+name+'='+id;
 var temp = '?userid='+id;
 setCookie('realid',temp,30); 
 document.location=locationURL+temp;
}

// don't need this find
function GoToUrlRealId(locationURL){	 
	document.location=locationURL+getCookie('realid');
} 


// find
function getURLParameter(strParamName){

 var strReturn = "";

 var strHref = window.location.href;

 if ( strHref.indexOf("?") > -1 ){ 

  var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase(); 

  var aQueryString = strQueryString.split("&"); 

  for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){ 

   if ( aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){  

    var aParam = aQueryString[iParam].split("="); 

    strReturn = aParam[1];

    break; 

   }

  }

 }

 return unescape(strReturn);

}


// find this
function getGeneralXML(uri,filterId) {
    var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
    	var contactid = getCookie('contactid');
    	if(filterId == null){
      	uri = uri+"/userid/" + contactid;
     }else{
      uri = uri+filterId+"/userid/" + contactid;
     } 	
      	
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
		xmlHttpRequest.open(method, uri, true);
 		xmlHttpRequest.onreadystatechange=function() 
 		{
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
   				var f = document.currentForm;
					setFormValues(f,currentXML);
  			}
  		}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return ;
}

function EditContact(id, locationURL){
 	setCookie('prevUrl',document.location,30); 
	setCookie('contactid',id,30);
	document.location=locationURL+'?userid='+id;
}

function EditChapter(id, locationURL){
	var state = getCookie('state');
	document.location=locationURL+"?chapterid="+id+"&state="+state+"&status="+status;
}

function RequestLogin(id, locationURL)
{
	document.location=locationURL;
}

function stateRequestLogin(id, locationURL)
{
	document.location = locationURL + '?userid=' + getCookie('contactid');
}

function getManageChaptersPage(){
	document.location='Admin_Manage_Chapters.htm?state='+state+"&status="+status;
}

function getStateManageChaptersPage(){
	document.location='State_Manage_Chapters.htm?userid=' + getCookie('userId');
}

function editSchool(id, locationURL){
	setCookie('schoolid',id,30);
	document.location = locationURL + '?schoolid=' + id;
}

function stateEditSchool(id, locationURL){
	document.location = locationURL + '?currentid=' + id;
}

function stateSelectSchool(locationURL){
	document.location = locationURL + '?currentid=' + currentid;
}

function deleteSchool(id, x){
	if (confirm('Are you sure you want to delete this school?')) 
	{ 
		uri = baseuri + '/fccla/~fccla/school/' + id;
		var success = false;
		var xmlHttpRequest=getXMLHttpRequest();
    	if (xmlHttpRequest)
    	{
				xmlHttpRequest.open('DELETE', uri, false);
   	 		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    		xmlHttpRequest.send(null);
    		window.location.reload();
    	}
    	else
   		{
      		alert("unable to create request object");
    	}
    	return;
	} else { 
		return;
	};
	
}

function GetBack(){
 document.location = getCookie('prevUrl'); 
}

/* to delete
function EditRequest(id, locationURL){
 setCookie('prevUrl',document.location,30); 
	setCookie('contactid',id,30);
	document.location=locationURL+'?userid='+id;
}
*/

function submitInvoiceFormXML(uri,URL,method){ 
	if($('#currentForm').valid())
	{
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);	
		if(submitInvoiceXML(uri,xml,method))
		{
				getLocation(URL);
		}
	}else {
		scroll(0,0);
	}
    return ;
}

function submitInvoiceXML(uri,xml,method){
	var success = false;
  var uri = baseuri + uri; 
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      xmlHttpRequest.open(method, uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      if(method == "POST")
      {
      	if(xml.xml != undefined)
      	{
      		var strXml = xml.xml;
      	}
      	else 
      	{
      		var serializer = new XMLSerializer();
      		var strXml = serializer.serializeToString(xml);
				}
      	 body=escape(strXml); 
      	 body=body.replace(/\+/g,"%2B");
      	 body = "post=" + body;
      	xmlHttpRequest.send(body)
      }
      else
      {  
	      	xmlHttpRequest.send(xml);
      }
      if(xmlHttpRequest.status != 200)
      {
		    alert("No invoice was found that corresponded to the entered invoice number.");
      }
	  else
	  {
		success = true;
		var resultText = null;
		if(xmlHttpRequest.responseText)
		{
			resultText = xmlHttpRequest.responseText;
		}
		else
		{
			var resultXml = SelectSingleNode(xmlHttpRequest.responseXML,"//Error");
			if(resultXml)
			{
				resultText = resultXml.innerText;
			}
		}
		
		if(xmlHttpRequest.responseText.indexOf('<Error>Duplicate contact found') != -1 )
		{
			alert('A record aleady exists with the same combination of First name, Middle name and Last Name. Please edit one of these and try again.');
			success = false;
		}
	  }
      //var resultXml = xmlHttpRequest.responseXML; 
      
    }
    else
    {
      alert("unable to create request object");
      success =  false;
    }
    return success;
}

function selectPaymentType(val){
	//alert(document.getElementById('Total').value);
	if($('#currentForm').valid() || document.getElementById('Total').value == '0.00' || document.getElementById('Total').value == '0')
	{
	  document.getElementById('NationalDues').value = filterNum(document.getElementById('NationalDues').value)
    if(document.getElementById('StateDues'))
    {
        document.getElementById('StateDues').value = filterNum(document.getElementById('StateDues').value)
        document.getElementById('StateMinimum').value = filterNum(document.getElementById('StateMinimum').value)
    }
		document.getElementById('Fees').value = filterNum(document.getElementById('Fees').value)
		document.getElementById('NationalMinimum').value = filterNum(document.getElementById('NationalMinimum').value)
		document.getElementById('Total').value = filterNum(document.getElementById('Total').value)
    if(document.getElementById('ChapterAdvisorContributionFee'))
    {
        document.getElementById('ChapterAdvisorContributionFee').value = filterNum(document.getElementById('ChapterAdvisorContributionFee').value)
    }
		document.getElementById('NationalAdvisorContributionFee').value = filterNum(document.getElementById('NationalAdvisorContributionFee').value)
	  
		//alert(document.getElementById('StateDues').value);
		//return;
	  
		var f = document.currentForm;
	  getFormValues(f,currentXML);
	  var xml = getXMLString(currentXML);
		//remove the following two lines to go live
		//debug(xml);
		//return;
	  setCookie('xml', xml, 30);
	  var totalVal = parseFloat(f.Total.value)
    if(totalVal > 0){
      getLocation(val);
    }
    else {
      submitPaymentForm('/fccla/~fccla/chapterfee/','Chapter_Adviser_Membership_Confirmation_Check.htm', 'POST');
    }
	}else {
		scroll(0,0);
	}
}

function selectStatePaymentType(val){
	if($('#currentForm').valid())
	{
	  
	  
	  document.getElementById('NationalDues').value = filterNum(document.getElementById('NationalDues').value)
    if(document.getElementById('StateDues'))
    {
        document.getElementById('StateDues').value = filterNum(document.getElementById('StateDues').value)
        document.getElementById('StateMinimum').value = filterNum(document.getElementById('StateMinimum').value)
    }
		document.getElementById('Fees').value = filterNum(document.getElementById('Fees').value)
		document.getElementById('NationalMinimum').value = filterNum(document.getElementById('NationalMinimum').value)
		document.getElementById('Total').value = filterNum(document.getElementById('Total').value)
    if(document.getElementById('ChapterAdvisorContributionFee'))
    {
        document.getElementById('ChapterAdvisorContributionFee').value = filterNum(document.getElementById('ChapterAdvisorContributionFee').value)
    }
		document.getElementById('NationalAdvisorContributionFee').value = filterNum(document.getElementById('NationalAdvisorContributionFee').value)
	  
	  
		var f = document.currentForm;
	  getFormValues(f,currentXML);
	  var xml = getXMLString(currentXML);
	  setCookie('xml', xml, 30);
	  var totalVal = parseFloat(f.Total.value)
    if(totalVal > 0){
      getLocation(val);
    }
    else {
      submitPaymentChapterState('/fccla/~fccla/chapterfee/chapterstate','State_Adviser_Membership_Confirmation_Check.htm', 'POST');
    }
	}else {
		scroll(0,0);
	}
}

function StoreXML2(URL){ 
	var xmlString = getXMLString(currentXML)
 //var xmlString = currentXML.xml ? currentXML.xml : (new XMLSerializer()).serializeToString(currentXML);  
 setCookie("store",xmlString,30);
 setCookie("prevUrl",document.location,30);
 getLocation(URL);
}

function GetChapterFee(uri) {
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      var userid = getCookie('userId');
      uri+=userid;
			if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
      xmlHttpRequest.open("GET", uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      body="";
      	 
      xmlHttpRequest.send(body)
      if(xmlHttpRequest.status != 200)
      {
        //alert(xmlHttpRequest.status);
      }else{
       currentXML = xmlHttpRequest.responseXML;       
       var f = document.currentForm;
       setFormValues(f,currentXML);       
      }      
      success = true;
    }
    else
    {
      alert("unable to create request object");
      success =  false;
    }
    var members=xmlHttpRequest.responseXML.getElementsByTagName("UNAFFILIATED");
    var count = members.length;
    var f=document.currentForm;
    if(count * 3 < 81)
    {
      var nationalDues=81;
    }
    else
    {
      var nationalDues=count * 3;
    }
    if(count * 9 < 27)
    {
      var stateDues=27;
    }
    else
    {
      var stateDues=count * 9;
    }
    f["NationalDues"].value= formatCurrency(nationalDues);
    f["StateDues"].value= formatCurrency(stateDues);
    f["Fees"].value=formatCurrency(0);
    f["Total"].value=formatCurrency(nationalDues + stateDues);
    return success;
}    

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + '.' + cents);
}


function reformatCurrencyMembershipFees(){
 document.getElementById('amount').value = filterNum(document.getElementById('amount').value);
 document.getElementById('latefee').value = filterNum(document.getElementById('latefee').value);
}

function filterNum(str) {
  re = /^\$|,/g;
  return str.replace(re, "");
}

function SubmitChapterFee(){
 var f = document.currentForm;
 getFormValues(f,currentXML);
 submitXML(baseuri + '/fccla/~fccla/CHAPTERFEE/userid/'+getCookie('userId'),currentXML,"PUT");
 document.location = 'Chapter_Adviser_Membership_Confirmation.htm';
}
/* to delete
function DeleteRequest(id, uri){
	uri = uri + id;
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
 if (xmlHttpRequest){
  xmlHttpRequest.open("DELETE", uri, false);
  xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
  xmlHttpRequest.send(null);
  window.location.reload();
 }else{ alert("unable to create request object"); }
 return ;
}
 */
function submitFormXMLReal(uri,URL,method){ 
	var f = document.currentForm;
	var xml = getFormValues(f,currentXML);
	if(submitXML(uri,xml,method))
	{
		GoToUrlRealId(URL);
	}
	else
	{
		alert('failed');
	}
    return ;
}

function simpleFormSubmit(){
	document.getElementById("loading").style.display = "block";
	var f = document.currentForm;
	var userid = getCookie('userId');
	f.action += '?userid=' + userid + '&chapterid=' + getCookie('ChapterId');	
	f.submit();
}

function submitChapterPropertiesChange(){

	var f = document.currentForm;
	var primaryAdviserControl = document.getElementById('primaryadviser');
	if(primaryAdviserControl)
	{
		var primaryAdviserXmlNode = SelectSingleNode(currentXML, "//primaryadviser");
    if(primaryAdviserXmlNode.firstChild)
    {
			
      if(primaryAdviserXmlNode && (primaryAdviserXmlNode.firstChild.nodeValue != primaryAdviserControl.value))
      {
        
				
				var returnValue = confirm("You are attempting to change the Primary Adviser to be someone else.  Note that if you continue, you will be automatically logged out of this application, and you will have to login with the user name (email address) of the new primary adviser that you have chosen.  The password will remain the same as the one with which you are currently logged on.  Click 'Ok' if you wish to continue.");
        if(returnValue == true)
        {
          returnValue = confirm("Are you certain that you want to make this change?  Click 'Ok' to confirm.");
          if(returnValue == true)
          {
            var returnValue = submitFormXMLAndReturn(baseuri + "/fccla/~fccla/chapter" ,  "PUT");
            if(returnValue == true)
            {
              //getLocation("default.htm");
							logout();
            }
            else
            {
              alert("There was a failure during the save of your data.  Please try again.");
            }
            return;
          }
        }
      }
      else
      {
        submitFormXML(baseuri + "/fccla/~fccla/chapter", "Update_Successful_Edit_Chapter_Properties.htm",  "PUT");			
      }
    }
    else
    {
      submitFormXML(baseuri + "/fccla/~fccla/chapter", "Update_Successful_Edit_Chapter_Properties.htm",  "PUT");			
    }
	}
	else
	{
		alert("The current web page has been corrupted in some way.  Please refresh the page and try your changes again.  If this problem persists, please contact your system admin.");
		return;
	}
	return;
}
	
function addChapter(){
  submitChapterXML(baseuri + "/fccla/~fccla/chapter", "POST");
  return;
}

function addAdviserChapter(redirect){
  submitAdviserChapterXML(baseuri + "/fccla/~fccla/chapterprov", "POST", redirect);
  return;
}

function addProvChapter(){
	submitProvChapterXML(baseuri + "/fccla/~fccla/chapterprov", "POST");
	return;
}

function addSchool(){
	var f = document.currentForm;
	
	var statusnode = SelectSingleNode(currentXML, "//status");
  var textnode = currentXML.createTextNode('A');       
  statusnode.appendChild(textnode);
	var xml = getFormValues(f,currentXML);
	
	if(submitXMLNoId(baseuri + "/fccla/~fccla/school",xml,"POST")){
		document.location = "Admin_Manage_Schools.htm?state="+getCookie('stateVal');
	}
  return;
}

function adviserAddSchool(status, redirect){
  if($('#currentForm').valid()) {
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);
		var statusnode = SelectSingleNode(xml, "//status");
		if (statusnode.firstChild) {
			statusnode.firstChild.nodeValue = '';
		}
    var textnode = xml.createTextNode(status);       
    statusnode.appendChild(textnode);
		var uri = baseuri + "/fccla/~fccla/school";
		var method = "POST";
		var xmlHttpRequest=getXMLHttpRequest();
		if (xmlHttpRequest)
		{
			xmlHttpRequest.open(method, uri, false);
			xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			
			if(xml.xml != undefined)
			{
				var strXml = xml.xml;
			}
			else 
			{
				var serializer = new XMLSerializer();
				var strXml = serializer.serializeToString(xml);
			}
			
			body=escape(strXml); 
			body=body.replace(/\+/g,"%2B");
			body = "post=" + body;
			 
			xmlHttpRequest.send(body)
			
			if(xmlHttpRequest.status != 200)
			{
				alert(xmlHttpRequest.status);
			}
			else
			{
				var schoolid = SelectSingleNode(xmlHttpRequest.responseXML,"//schoolid").firstChild.nodeValue;
				switch (status)
				{
					case 'P':
						if (redirect == null){
						editSchool(schoolid,"Prov_Add_Chapter.htm");
						} else {
							stateEditSchool(schoolid,redirect);
						}
						break;
					case 'U':
						getLocation("School_Update_Thank_You.htm");
						break;
					case 'A':
						stateEditSchool(schoolid,redirect);
						break;
					default:
						getLocation("default.htm");
				}
			}		
		}
		else
		{
			alert("Unable to create request object");
		}
  } else {
		scroll(0,0);
	}
	return;
}

function updateSchool(url, role){
  if($('#currentForm').valid()) {
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);
		if (role == 'ca'){
			removeNode('chapterid');
		}
		//debug(xml, true);
		//return;
		if(submitXMLWithID(baseuri + "/fccla/~fccla/school",xml,'PUT','schoolid')) { 
	    if (typeof(url)!='undefined'){
				document.location=url+'.htm?userid='+getCookie('userId')+'&chapterid='+getCookie('ChapterId');
			}
			else
			{
				document.location='Admin_Manage_Schools.htm?state='+getCookie('stateVal');
			}
		} else {
		  alert('submit did not work');
		}
	} else {
		scroll(0,0);
	}
    return;
}

function stateSubmitChapterPropertiesChange(){
	formSubmit(baseuri + "/fccla/~fccla/chapter/","State_Manage_Chapters.htm?userid="+getCookie('userId'),"PUT",chapterid)
}
	
function adminSubmitChapterPropertiesChange(){
	formSubmit(baseuri + "/fccla/~fccla/chapter/",'Admin_Manage_Chapters.htm?state='+document.getElementById('schoolInfo_mailingaddressInfo_state').value,'PUT',chapterid)
}

function clearChecks(id)
{
	document.getElementById(id).checked = false;
}

function activateChapter(chapterid){
	var contact;
	var fcclaid;
	//get chapter info
	$.ajax({
			type: "GET",
			url: baseuri + "/fccla/~fccla/chapter/" + chapterid + "&rand=" + new Date().getTime(),
			async: false,
			success: function(xml){
				//set vars - contact, fcclaid
				contact = SelectSingleNode(xml, "//createdby").firstChild.nodeValue;
				fcclaid = SelectSingleNode(xml, "//fcclaid").firstChild.nodeValue;
				//set chapter status to 'N' for New Chapter Request. It will be reset to 'A' in the service
				var statusnode = SelectSingleNode(xml, "//status");
				if (statusnode.firstChild){
					statusnode.firstChild.nodeValue = '';
				}
				var newstatus = xml.createTextNode('N');
				statusnode.appendChild(newstatus);
				//put chapter info
				submitXML(baseuri + '/fccla/~fccla/CHAPTER/' + chapterid, xml, "PUT");
			}
		});
	//email contact with fcclaid
	//alert('Email to Contact: ' + contact + 'with FCCLAID: ' + fcclaid);
	//var url = 'sendEmail.php?contactid=' + contact + '&fcclaid=' + fcclaid + '&redirectToPage=Admin_Manage_Chapters.htm&state=' + state + '&status=p';
	//document.location = url;
	//reload page
	document.location = 'Admin_Manage_Chapters.htm?state=' + state + '&status=p';
}

function submitProvChapterXML(uri, method){ 
	if($('#currentForm').valid()) {
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);
		var chapterstatus = SelectSingleNode(currentXML, "//status");
		if (chapterstatus.firstChild) {
			chapterstatus.firstChild.nodeValue = '';
		} 
		var provchapterstatus = currentXML.createTextNode('P');       
		chapterstatus.appendChild(provchapterstatus);
		
		if(submitXMLNoId(uri,xml,method)) { 
	    document.location='Chapter_Adviser_Thank_You.htm';
		} else {
		  alert('submit did not work');
		}
	} else {
		scroll(0,0);
	}
    return;
}

function activateContact(contactid){
	// set contact status from P to A
	// and email user (in service)
	$.ajax({
			type: "GET",
			url: baseuri + "/fccla/~fccla/contact/" + contactid + "&rand=" + new Date().getTime(),
			async: false,
			success: function(xml){
				//set vars - contact, fcclaid
				//contact = SelectSingleNode(xml, "//createdby").firstChild.nodeValue;
				//fcclaid = SelectSingleNode(xml, "//fcclaid").firstChild.nodeValue;
				//set contact status to 'N' for New Contact Request. It will be reset to 'A' in the service
				var statusnode = SelectSingleNode(xml, "//status");
				if (statusnode.firstChild){
					statusnode.firstChild.nodeValue = '';
				}
				var newstatus = xml.createTextNode('N');
				statusnode.appendChild(newstatus);
				//put contact info
				submitXML(baseuri + '/fccla/~fccla/CONTACT/' + contactid, xml, "PUT");
			}
		});
	//email contact with fcclaid
	//alert('Email to Contact: ' + contact + 'with FCCLAID: ' + fcclaid);
	//var url = 'sendEmail.php?contactid=' + contact + '&fcclaid=' + fcclaid + '&redirectToPage=Admin_Manage_Chapters.htm&state=' + state + '&status=p';
	//document.location = url;
	//reload page
	document.location = 'Admin_Manage_Users.htm?status=p';
	
}

function submitXMLWithNoId(uri, URL, method){ 
	if($('#currentForm').valid()) {
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);
		if(submitXMLNoId(uri,xml,method)) { 
	    document.location=URL;
		} else {
		  alert('submit did not work');
		}
	} else {
		scroll(0,0);
	}
    return;
}


function submitAdviserChapterXML(uri, method, redirect){ 
	if($('#currentForm').valid()) {
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);	
		var addState = '';
		if(submitXML(uri,xml,method)) {
			if (redirect == 'State_Manage_Chapters.htm'){
				addState = "&state=" + getCookie('stateVal');
			}
	    document.location = redirect + '?userid=' + getCookie('userId') + addState;
		} else {
		  alert('submit did not work');
		}
	} else {
		scroll(0,0);
	}
    return;
}

function submitChapterXML(uri, method){ 
	if($('#currentForm').valid()) {
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);	
		if(submitXML(uri,xml,method)) { 
	    document.location='Admin_Manage_Chapters.htm?userid='+getCookie('userId')+"&state="+getCookie('stateVal');
		} else {
		  alert('submit did not work');
		}
	} else {
		scroll(0,0);
	}
    return;
}

function checkForDuplicateEmail(){

	var emailTextBox = document.getElementById('emailaddress').value; 
	var success;
	$.ajax({
		type: 'GET',
		url: baseuri + '/fccla/~fccla/emaillookup?email=' + emailTextBox + '&rand=' + new Date().getTime(),
		async: false,
		dataType: 'xml',
		error: function(){
			alert('Error loading XML document');
		},
		success: function(xml){
			$(xml).find('Root').each(function(){
				success = $(this).find('EmailExists').text();
			});
		}			
	});
	return success;
}

function checkForMultiplePrimaryAdvisors(){

	var chapterTextBox = document.getElementById('chapterid').value; 
	var success;
	$.ajax({
		type: 'GET',
		url: baseuri + '/fccla/~fccla/primaryadviserlookup?chapterid=' + chapterTextBox + '&rand=' + new Date().getTime(),
		async: false,
		dataType: 'xml',
		error: function(){
			alert('Error loading XML document');
		},
		success: function(xml){
			$(xml).find('Root').each(function(){
				success = $(this).find('PrimaryAdviserExists').text();
			});
		}			
	});
	return success;
}

function getContactId(){

	var emailTextBox = document.getElementById('email').value; 
	var xmlHttpRequest=getXMLHttpRequest();
	var contactid;
	if (xmlHttpRequest)  {
			var uri = baseuri +'/fccla/~fccla/contactbyemail?email=' + emailTextBox;
			if(uri.indexOf ("?") != -1){
				uri = uri + "&rand=" + new Date().getTime()
			}	else {
				uri = uri + "?rand=" + new Date().getTime()
			}
			xmlHttpRequest.open('GET', uri, true);
			xmlHttpRequest.onreadystatechange=function() 
		{
			if (xmlHttpRequest.readyState==4) {
				currentXML = xmlHttpRequest.responseXML;
				contactid = SelectSingleNode(currentXML,"//contactid").nodeValue;
			}
		}
		xmlHttpRequest.send(null)
	} else {
		alert("unable to create request object");
	}
	return contactid;
}

function addContact(){
	if($('#currentForm').valid()) {
		var duplicateEmail = checkForDuplicateEmail();
		if (duplicateEmail == "False") {
			if (submitContactXML(baseuri + "/fccla/~fccla/contact", "POST", "Admin_Manage_Users")) {
			}
			return;
		} else {
			alert("You have entered an email address that already exists in the system.\n\nPlease re-enter your email address.\n\nIf you need assistance please contact affiliation@fcclainc.org.");
		}
	} else {
		scroll(0,0);
	}
}

/*
function addStateContact(){
  submitContactXML(baseuri + "/fccla/~fccla/contact", "POST", "State_Manage_Users");
  return;
}
*/

function addStateContact(){
	if($('#currentForm').valid()) {
		var duplicateEmail = checkForDuplicateEmail();
		var multiplePrimaryAdvisers = checkForMultiplePrimaryAdvisors();
		var role = $('#userroleid').val();
		if (duplicateEmail == "False" && (multiplePrimaryAdvisers == "False" || role != "1")) {
			if (submitContactXML(baseuri + "/fccla/~fccla/contact", "POST", "State_Manage_Users")) {
			}
			return;
		} else {
			if (duplicateEmail == "True"){		
				alert("You have entered an email address that already exists in the system.\n\nPlease re-enter your email address.\n\nIf you need assistance please contact affiliation@fcclainc.org.");
			}
			if (multiplePrimaryAdvisers == "True" && role == "1"){
				alert("This chapter already has a primary adviser,\nyou may create this user as a secondary adviser only.\n\nIf you need assistance please contact affiliation@fcclainc.org.");				
			}
		}
	} else {
		scroll(0,0);
	}
}

function addPrimaryAdviser(){
	if($('#currentForm').valid()) {
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);
    var fcclaid = document.getElementById('fcclaid').value;
    var primaryadviser = "";
    var success = false;
	  var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest) {
      uri = baseuri + "/fccla/~fccla/fcclaidlookup?fcclaid=" +fcclaid;
			if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
      xmlHttpRequest.open("GET", uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      body="";
      xmlHttpRequest.send(body)
      if(xmlHttpRequest.status != 200){
        //alert(xmlHttpRequest.status);
      }else{
        currentXML = xmlHttpRequest.responseXML;  
        success = true;
      }      
    }  else {
      alert("unable to create request object");
      success =  false;
    }
    var exist = SelectSingleNode(currentXML,"//FcclaIDExists");
    // Check to see if primaryadviser contains a guid
    if(exist.firstChild != null){	
			var exists = exist.firstChild.nodeValue;
      if(exists == 'True'){
         var success = false;
         var xmlHttpRequest=getXMLHttpRequest();
          if (xmlHttpRequest) {
            uri = baseuri + "/fccla/~fccla/chapter?fcclaid=" +fcclaid;
						if(uri.indexOf ("?") != -1)
						{
							uri = uri + "&rand=" + new Date().getTime()
						}
						else
						{
							uri = uri + "?rand=" + new Date().getTime()
						}
            xmlHttpRequest.open("GET", uri, false);
            xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            body="";
            xmlHttpRequest.send(body)
            if(xmlHttpRequest.status != 200){
              //alert(xmlHttpRequest.status);
            } else {
							var chapterxml = xmlHttpRequest.responseXML;  
							// Check to see if primaryadviser contains a guid
							primaryadviser = SelectSingleNode(chapterxml, "//primaryadviser");
							if(primaryadviser.childNodes.length > 0) {
								var paFirstName = SelectSingleNode(chapterxml, "//primaryadviserInfo/firstname").firstChild.nodeValue;
								var paLastName = SelectSingleNode(chapterxml, "//primaryadviserInfo/lastname").firstChild.nodeValue;
								var paName = paFirstName + " " + paLastName;
								alert("The chapter you entered is already associated with a valid Primary Adviser. Please work with " + paName + 
											" to gain access to the system, the primary adviser can modify the account to grant you access.\n\n" +
											"If you are unable to contact the primary adviser and they are no longer serving your chapter, please contact FCCLA at affiliation@fcclainc.org");
							} else {
								// TODO: include chapter guid in xml
								var chapterid = SelectSingleNode(chapterxml, "//chapterid").firstChild.nodeValue;
								//debug(xml,true);
                if(!SelectSingleNode(xml, "//chapterid"))
                {
                  // append chapterid node to xml
                  try
                  {
                    rootNode = xml.documentElement;
                    newNode = xml.createNode(1, "chapterid", "");
                    rootNode.appendChild(newNode);
                  }
                  catch (e)
                  {
                    rootNode = xml.documentElement;
                    newNode = xml.createElement("chapterid");						
                    rootNode.appendChild(newNode);
                  }
                }
                var contactchapterid = SelectSingleNode(xml, "//chapterid");
								var textnode = xml.createTextNode(chapterid);       
								contactchapterid.appendChild(textnode);
								//var contactxml = submitXML(baseuri + "/fccla/~fccla/contact",xml,"POST");
								//if (contactxml){
								//debug(xml, true);
								//return;
								if(submitXML(baseuri + "/fccla/~fccla/contact",xml,"POST")) {
									// Get contact ID for primary adviser node in chapterxml
									// TODO: Replace / Add contactid as primaryadviser in chapterxml
									//var contactid = SelectSingleNode(contactxml, "//contactid").firstChild.nodeValue;
									//var panode = chapterxml.createTextNode(contactid);
									//primaryadviser.appendChild(panode);
									//debug(chapterxml, true);
									//TODO: PUT the chapterxml back with the new contactid as the primaryadviser
									//submitXML(baseuri + '/fccla/~fccla/chapter/' + chapterid, chapterxml, "PUT");
									document.location='Chapter_Adviser_User_Account_Thank_You.htm';
								} else {
									alert('submit did not work');
								}
							}
            }      
            success = true;
          }  else {
            alert("unable to create request object");
            success =  false;
          }
          var exist = SelectSingleNode(currentXML,"//FcclaIDExists");
        
		  } else {
        alert('There is no chapter with that chapter id.');
     }
    }
	} else {
		scroll(0,0);
	}
   return;
}

function setStatus(){
  document.getElementById('status').value = 'P';
}
function adminSubmitContactPropertiesChange(){
  submitContactXML(baseuri + "/fccla/~fccla/contact", "PUT", "Admin_Manage_Users");			
  return;
}

function submitContactXML(uri, method, redirect){ 
	if($('#currentForm').valid()) {
		var f = document.currentForm;
		currentXML = getFormValues(f,currentXML);	
		removeNode('chaptername');
		var xml = currentXML
		if(submitXML(uri,xml,method)) {
				document.location= redirect + '.htm?userid='+getCookie('userId');
		} else {
		  alert('submit did not work');
		}
	} else {
		scroll(0,0);
	}
    return;
}


function submitFormXMLAndReturn(uri,method){ 
	if($('#currentForm').valid())
	{
		var f = document.currentForm;
		var xml = getFormValues(f,currentXML);
		return submitXML(uri,xml,method);
	}else {
		scroll(0,0);
		return;
	}
}

function getStoredErrors(uri){

	var storageid = getCookie('storageid');
	var method = "GET";
    var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      	uri = uri + storageid;      	
    	if(uri.indexOf ("?") != -1)
      	{
        	uri = uri + "&rand=" + new Date().getTime()
      	}
      	else
      	{
        	uri = uri + "?rand=" + new Date().getTime()
      	}
		xmlHttpRequest.open(method, uri, true);
 		xmlHttpRequest.onreadystatechange=function() 
 		{
  			if (xmlHttpRequest.readyState==4) 
  			{
   				currentXML = xmlHttpRequest.responseXML;
   				var f = document.currentForm;
				displayErrors(f,currentXML);
  			}
  		}
  		xmlHttpRequest.send(null)
    }
    else
    {
      alert("unable to create request object");
    }
    return ;

}

function displayErrors(f, errorXML){
	var displayDiv = document.getElementById('divDisplayErrors');
	if(displayDiv)
	{
		if(errorXML.xml)
		{
			var errorDisplayHtml = '';
			var errorNodeList =  errorXML.getElementsByTagName('importerror');	
			for(var i=0;i<errorNodeList.length;i++)
			{
				errorDisplayHtml += '<br>' + errorNodeList.item(i).text;			
			}			

			displayDiv.innerHTML = errorDisplayHtml;
		}
		else
		{
			alert('not ready for ff yet');
		}
	}
	else
	{
		alert('Error: there is no div called divDisplayErrors');
	}
}

function retrievePassword(){
	if($('#currentForm').valid())
	{	
		var emailTextBox = document.getElementById('email').value; 
		var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)  {
     		var uri = baseuri +'/fccla/~fccla/emaillookup/?email=' + emailTextBox;
    		if(uri.indexOf ("?") != -1){
        	uri = uri + "&rand=" + new Date().getTime()
      	}	else {
        	uri = uri + "?rand=" + new Date().getTime()
      	}
		    xmlHttpRequest.open('GET', uri, true);
 		    xmlHttpRequest.onreadystatechange=function() 
 		  {
  			if (xmlHttpRequest.readyState==4) {
   				currentXML = xmlHttpRequest.responseXML;
   				var EmailExists = SelectSingleNode(currentXML,"//EmailExists");
   				if(EmailExists.firstChild.nodeValue == 'True') {
						sendPassword(emailTextBox);
						var url = 'Password_Reset_Confirmation.htm';		
						document.location = url;
					} else {
						alert("That email address does not exist in our system.")
					}
  			}
  		}
  		xmlHttpRequest.send(null)
  		
    } else {
      alert("unable to create request object");
    }
		
	} else {
		scroll(0,0);
	}
}

function sendPassword(email)
{
	var success = false;
	var xmlHttpRequest=getXMLHttpRequest();
    if (xmlHttpRequest)
    {
      uri = baseuri + "/fccla/~fccla/PasswordRequest?email=" + email;
			if(uri.indexOf ("?") != -1){
        	uri = uri + "&rand=" + new Date().getTime()
      	}	else {
        	uri = uri + "?rand=" + new Date().getTime()
      	}
      xmlHttpRequest.open("GET", uri, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      body="";
      xmlHttpRequest.send(body)
      if(xmlHttpRequest.status != 200)
      {
        //alert(xmlHttpRequest.status);
      }
			else
			{
				currentXML = xmlHttpRequest.responseXML;          
      }      
      success = true;
			return;
    }
    else
    {
      alert("unable to create request object");
      success =  false;
			document.location = 'default.htm';
    }
}

function SubmitCCPayment(){
if($('#currentForm').valid())
	{
		$('#buttons').hide();
		//return;
		f = document.currentForm;
		var queryString = GetFormValuesAsQueryString(f);
		var returnValue = SendCCPayment(securebaseuri +"/davinci/fccla/submitPayment.asp" + queryString);
    returnValue = returnValue.split('|');
		if(returnValue[2] == '0000')
		{
			submitPaymentForm(securebaseuri + '/fccla/~fccla/chapterfee/',null, 'POST');
			submitPaymentForm(securebaseuri + '/fccla/~fccla/payment/','Chapter_Adviser_Membership_Confirmation_Credit_Card.htm', 'POST');
		}
		else
		{
      var ci = chapterid = getCookie('ChapterId');
			var ui = getCookie('userId');
      document.location=securebaseuri +"/davinci/fccla/Chapter_Adviser_Payment_CreditCard.htm?userid=" + ui + "&chapterid=" + ci + "&errmsg=" + returnValue[3];
		}
	}else {
		scroll(0,0);
	}
}

function updateContributionFee(xml){
	var fcclaids = '';
	var chapternode = SelectSingleNode(xml,"//chaptername");
	if (chapternode.hasChildNodes){
		for (var i = 0; i < chapternode.childNodes.length; i++)
		{
			fcclaids += chapternode.childNodes[i].childNodes[0].nodeValue + ':';
		}
		fcclaids = fcclaids.substr(0,fcclaids.length-1);
	}
	
	$.ajax({
		type: 'put',
		url: baseuri + '/fccla/~fccla/contributionfee?fcclaids=' + fcclaids + '&rand=' + new Date().getTime(),
		async: false,
		datatype: 'xml',
		error: function(){
			alert('error inserting xml document');
		},
		success: function(xml){
		}			
	});
}
	



function SubmitCCPaymentStateAdviser(){
if($('#currentForm').valid())
	{
		$('#buttons').hide();
		f = document.currentForm;
		var queryString = GetFormValuesAsQueryString(f);
		var returnValue = SendCCPayment(securebaseuri +"/davinci/fccla/submitPayment.asp" + queryString);
    returnValue = returnValue.split('|');
		if(returnValue[2] == '0000')
		{
			updateContributionFee(currentXML);
			submitPaymentForm(securebaseuri + '/fccla/~fccla/chapterfee/chapterstate/' + getCookie('state'),null, 'POST');
			submitPaymentForm(securebaseuri + '/fccla/~fccla/payment/','State_Adviser_Membership_Confirmation_Credit_Card.htm', 'POST');
		}
		else
		{
      var ci = chapterid = getCookie('ChapterId');
			var ui = getCookie('userId');
      document.location=securebaseuri +"/davinci/fccla/State_Adviser_Payment_Creditcard.htm?userid=" + ui + "&chapterid=" + ci + "&errmsg=" + returnValue[3];
		}
	}else {
		scroll(0,0);
	}
}

function xSubmitCCPayment(){
if($('#currentForm').valid())
	{
		f = document.currentForm;
		var queryString = GetFormValuesAsQueryString(f);
    var ui = getCookie('userId');
    var ii = getCookie('newInvoiceId');
    //document.location = securebaseuri +"/davinci/fccla/submitPayment.asp" + queryString + "ui=" + ui + "&ii=" +ii;
    document.location = baseuri + "/davinci/fccla/submitPayment.asp" + queryString + "ui=" + ui + "&ii=" +ii;
  }else {
		scroll(0,0);
	}
}

function SendCCPayment(url){
	var xmlHttpRequest=getXMLHttpRequest();
	var returnValue = null;
    if (xmlHttpRequest)
    {      
      if(url.indexOf ("?") != -1){
        	url = url + "&rand=" + new Date().getTime()
      	}	else {
        	url = url + "?rand=" + new Date().getTime()
      	}
			xmlHttpRequest.open("GET", url, false);
      xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      body="";
      xmlHttpRequest.send(body)
      if(xmlHttpRequest.status != 200)
      {
        alert(xmlHttpRequest.status);
      }
      else
      {
       returnValue = xmlHttpRequest.responseText;    
      }    
    }
    else
    {
      alert("unable to create request object");
    }
	return returnValue;
}

function GetFormValuesAsQueryString(f){
	var queryString = "?";
	for (var i=0; i<f.elements.length; i++){
		if (f.elements[i].type=="text" || f.elements[i].type=="textarea" || f.elements[i].type=="password" || f.elements[i].type=="hidden" || f.elements[i].type == "select-one"){
			var elementName = f.elements[i].name;
			if(elementName != null)
			{	
				queryString	+= elementName + '=' + f.elements[i].value + '&';
				// NOTE: may need to add code here to hanld blankFieldIndicator
			}
		}
	}
	return queryString;
}



