//--------------------//
// VSA Financial Aid Cost Estimator/Calculator
// Designed for State of Wisconsin UW-System Schools
// Written by: Daniel M. Frommelt, UW-Platteville
// Thursday July 24, 2008
//--------------------//

//--------------------//
//Error checks EFC valus to make sure it is numeric >=0
//--------------------//
function checkData() {
	var efcInput = document.getElementById("efc").value;
	if(document.getElementById("efc").value.substring(0,1)=="$"){ //scrub the $
		document.getElementById("efc").value=efcInput.substring(1,efcInput.length);
		efcInput=efcInput.substring(1,efcInput.length);
	}
	if (parseFloat(document.getElementById("efc").value)>=0)
		{sendData()} //Continue
   else
      {alert("You must enter a correct EFC value.");return false;} //Fail
}

//--------------------//
//Creates URL with variables attached and loads result page
//--------------------//
function sendData() {
	var urlDest = "http://www.uwlax.edu/finaid/calc/vsa_estimator.html"; //location of results page
	urlDest += "?residency="+document.getElementById("residency").value;
	urlDest += "&academic="+document.getElementById("academic").value;
	urlDest += "&financially="+document.getElementById("financially").value;
	urlDest += "&housing="+document.getElementById("housing").value;
	urlDest += "&efc="+document.getElementById("efc").value;
	document.location=urlDest; //Go to new URL/results page
}

//--------------------//
//Global variables
//--------------------//
var residency,academic,financially,housing,efc,xmlDoc,xmlhttp;

//--------------------//
//Grabs data from URL and loads XML file
//--------------------//
function getData() {
	getString = document.URL;
	var parms = getString.split('?');
	parms = parms[1].split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {parms[i] = parms[i].substring(pos+1);}
	}
	residency = document.getElementById("residency").value=parms[0];
	academic = document.getElementById("academic").value=parms[1];
	financially = document.getElementById("financially").value=parms[2];
	housing = document.getElementById("housing").value=parms[3];
	efc = document.getElementById("efc").value=parms[4];
	var XMLlocation = "http://www.uwlax.edu/finaid/calc/VSA.xml";  //only 1 XML file needed
	loadXML(XMLlocation);
}

//--------------------//
//Loading XML file [uses init()]
//--------------------//
function loadXML(xmlFile){
	xmlhttp=null;	
	if (window.ActiveXObject) {// code for IE5 and IE6
	  xmlhttp=new ActiveXObject("MSXML2.XMLHTTP.3.0");
	  }
	else if (window.XMLHttpRequest) {// code for all new browsers
	  xmlhttp=new XMLHttpRequest();
	  }
	
	if (xmlhttp!=null) {
		xmlhttp.onreadystatechange=state_Change;
		xmlhttp.open("GET",xmlFile,true);
		xmlhttp.send(null);
		init();
	}
	else {alert("Your browser does not support XMLHTTP.");}
}

//--------------------//
//Waits for XML file to fully load before continuing
//--------------------//
function state_Change() {
	if (xmlhttp.readyState==4) {// 4 = "loaded"
	if ((xmlhttp.status==200) || (xmlhttp.status==304)) {parseXML(xmlhttp);}
	else {alert("Problem retrieving XML data");}
  }
}

//--------------------//
//Function to help non IE browsers load XML nodes via XPath
//--------------------//
function init() {
	// mozXPath [http://km0ti0n.blunted.co.uk/mozxpath/] km0ti0n@gmail.com
	// Code licensed under Creative Commons Attribution-ShareAlike License
	// http://creativecommons.org/licenses/by-sa/2.5/
	if ( document.implementation.hasFeature("XPath", "3.0") ) {
		XMLDocument.prototype.selectNodes = function(cXPathString, xNode) {
			if( !xNode ) { xNode = this; }
			var oNSResolver = this.createNSResolver(this.documentElement)
			var aItems = this.evaluate(cXPathString, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
			var aResult = [];
			for( var i = 0; i < aItems.snapshotLength; i++) {
				aResult[i] =  aItems.snapshotItem(i);
			}
			return aResult;
		}
		XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode) {
			if ( !xNode ) { xNode = this; }
			var xItems = this.selectNodes(cXPathString, xNode);
			if( xItems.length > 0 ) {
				return xItems[0];
			}
			else {
				return null;
			}
		}
		Element.prototype.selectNodes = function(cXPathString) {
			if (this.ownerDocument.selectNodes) {
				return this.ownerDocument.selectNodes(cXPathString, this);
			}
			else {
				throw "For XML Elements Only";
			}
		}
		Element.prototype.selectSingleNode = function(cXPathString) {
			if (this.ownerDocument.selectSingleNode){
				return this.ownerDocument.selectSingleNode(cXPathString, this);
			}
			else {
				throw "For XML Elements Only";
			}
		}
	}
}

//--------------------//
//Parse XML data and display
//--------------------//
function parseXML(xmlhttp){
	var xmlDoc = xmlhttp.responseXML;
	var tuition, books, room, board, misc, travel;
	
	//Select costs based on residency and housing
	var costList = xmlDoc.getElementsByTagName("cost");
	for(var i=0;i<costList.length;i++){
		if((residency==costList[i].getAttribute("residency"))&&(housing==costList[i].getAttribute("housing"))){
			tuition = parseInt(costList[i].selectNodes("tuition")[0].firstChild.nodeValue);
			books = parseInt(costList[i].selectNodes("books")[0].firstChild.nodeValue);
			room = parseInt(costList[i].selectNodes("room")[0].firstChild.nodeValue);
			board = parseInt(costList[i].selectNodes("board")[0].firstChild.nodeValue);
			misc = parseInt(costList[i].selectNodes("misc")[0].firstChild.nodeValue);
			travel = parseInt(costList[i].selectNodes("travel")[0].firstChild.nodeValue);
		}
	}
	
	var totalCost = tuition + books + room + board + misc + travel;
	var costOfAttendance = totalCost;
	var totalNeed = totalCost - efc;
	if (totalNeed<0){totalNeed=0;}
	
	//alert("Tuition: $"+tuition);
	//alert("Books: $"+books);
	//alert("Room: $"+room);
	//alert("Board: $"+board);
	//alert("Misc: $"+misc);
	//alert("Travel: $"+travel);
	//alert("EFC : $"+efc);
	//alert("Total Cost: $"+totalCost);
	//alert("Cost of Attendance: $"+costOfAttendance);
	//alert("Total Need: $"+totalNeed);
	
	//Insert: user choices from previous page into the form IDs
	document.getElementById('vsa-residency').innerHTML=residency;
	document.getElementById('vsa-academic').innerHTML=academic;
	document.getElementById('vsa-financial').innerHTML=financially;
	document.getElementById('vsa-housing').innerHTML=housing;
	document.getElementById('vsa-efc1').innerHTML="$"+efc;

	//Insert: Estimated Cost of Attendance & Need Calculation into IDs
	document.getElementById('VSA-tuition').innerHTML="$"+tuition;
	document.getElementById('VSA-books').innerHTML="$"+books;
	document.getElementById('VSA-room').innerHTML="$"+room;
	document.getElementById('VSA-board').innerHTML="$"+board;
	document.getElementById('VSA-misc').innerHTML="$"+misc;
	document.getElementById('VSA-travel').innerHTML="$"+travel;
	document.getElementById('VSA-totalCost').innerHTML="$"+totalCost;
	document.getElementById('VSA-coa').innerHTML="$"+costOfAttendance;
	document.getElementById('VSA-efc').innerHTML="$"+efc;
	document.getElementById('VSA-need').innerHTML="$"+totalNeed;

//--------------------//
// Award Calculation Rules:
// Calculate total need then apply the following based on need, since you may
// not over award the user. The awards are given in the following order.
// Note: the variable "awardAmt" is the limit for the award for the user.
// 1. Pell Grant
// 2. Wisconsin State Grant
// 3. ACG Grant
// 4. Supplemental Educational Opportunity Grant
// 5. Subsidized Stafford Loan
// 6. Perkins Loan
// 7. Federal Work Study
// 8. Unsubsidzed Stafford Loan
//--------------------//
	var awardAmt = totalNeed;
	//alert("Needed Award Amount: $"+awardAmt);
	
//--------------------//
// 1. Pell Grant:
// - value based on EFC selection in between the min and max allowed in the XML file
//--------------------//
	var pell = 0;
	var efcList = xmlDoc.getElementsByTagName("efc");
	for(var i=0;i<efcList.length;i++){
		if((efc>=parseInt(efcList[i].getAttribute("min")))&&(efc<=parseInt(efcList[i].getAttribute("max")))){
				pell = parseInt(efcList[i].firstChild.nodeValue);
				if(awardAmt<=0){pell=0;awardAmt=0;}
				if((awardAmt>0)&&(awardAmt<=pell)){pell=awardAmt;awardAmt=0;}else{awardAmt-=pell;} //user limit calculation
		}
	}
	//alert("Pell Grant: $"+pell+"\nRunning Amount: $"+awardAmt);

//--------------------//
// 2. Wisconsin State Grant:
// - Must be WI resident
// - Forumla is: (5960 - EFC) * .5
// 	Max is $2980
// 	Min is $674
// 	if (EFC > 4612) then grant is $0
//--------------------//
	var wiGrant = 0;
	if ((awardAmt>0)&&(residency == "WI")){
		var temp = (5960 - efc)*.5;
		wiGrant = temp;
		if(temp>=2980){wiGrant=2980;} //Max is $2980
		if(temp<=674){wiGrant=674;}	//Min is $674
		if(efc>4612){wiGrant=0;}		//EFC > 4612 then grant is $0
	}
	if(awardAmt<=0){wiGrant=0;}
	if((awardAmt>0)&&(awardAmt<=wiGrant)){wiGrant=awardAmt;awardAmt=0;}else{awardAmt-=wiGrant;} //user limit calculation
	//alert("Wisconsin State Grant: $"+wiGrant+"\nRunning Amount: $"+awardAmt);

//--------------------//
// 3. ACG Grant:
// - if awarded a Pell then $750
//--------------------//
	var acg = 0;
	//if((academic=="freshman")||(academic=="sophomore")){
	//Modified by TJ Teegan on 9/22/2008
	if(academic=="freshman"){
		if(pell>0){acg=750;}
	}
	if(awardAmt<=0){acg=0;}
	if((awardAmt>0)&&(awardAmt<=acg)){acg=awardAmt;awardAmt=0;}else{awardAmt-=acg;} //user limit calculation
	//alert("ACG Grant: $"+acg+"\nRunning Amount: $"+awardAmt);

//--------------------//
// 4. Supplemental Educational Opportunity Grant:
// - if awarded a Pell then $500 (for UW-Platteville)
//--------------------//
	var seo = 0;
	//if(pell>0){seo=500;}
	//Modified by TJ 9/22/2008
	if(pell>0&&(efc >=0 && efc<=700)){seo=402;}
	if(pell>0&&(efc >=701 && efc<=1500)){seo=352;}
	if(pell>0&&(efc >=1501 && efc<=2300)){seo=302;}
	if(pell>0&&(efc >=2301 && efc<=3100)){seo=252;}
	if(pell>0&&(efc >=3101 && efc<=4041)){seo=202;}
	if(pell>0&&efc>4041){seo=0;}
	if(awardAmt<=0){seo=0;}
	if((awardAmt>0)&&(awardAmt<=seo)){seo=awardAmt;awardAmt=0;}else{awardAmt-=seo;} //user limit calculation
	//alert("ACG Grant: $"+seo+"\nRunning Amount: $"+awardAmt);
	
//--------------------//
// 7. Federal Work Study:
// - awarded up to $2000 if needed (for UW-Platteville)
//--------------------//
	var workStudy = 1500;
	//if(awardAmt<=0){workStudy=0;}
	//Modified by TJ 9/22/2008
	if(awardAmt<=0 || efc>2500){workStudy=0;}
	if((awardAmt>0)&&(awardAmt<=workStudy)){workStudy=awardAmt;awardAmt=0;}else{awardAmt-=workStudy;} //user limit calculation
	//alert("Perkins Loan: $"+workStudy+"\nRunning Amount: $"+awardAmt);

//--------------------//
// 5. Subsidized Stafford Loan:
// - dependent upon academic and financial status in XML
// - data in XMl also contains the info for step 8
// - students with NO need (totalNeed=0) can get the loan
// - BUT it must be added to the unsubsidized step 8
//--------------------//
	var subStafford, staffordDiff = 0;
	var unsubStafford = 0; //setting data for step 8, but it's value is limited last
	//Select stafford loan information for this user
	var staffordList = xmlDoc.getElementsByTagName("staffordMax");
	for(var i=0;i<staffordList.length;i++){
		if(academic==staffordList[i].getAttribute("academic")){
			subStafford = parseInt(staffordList[i].selectNodes("subsidized")[0].firstChild.nodeValue);
			//Modified by TJ Teegan
			var orig_subStafford = subStafford;
			//Next grab the unsubsidized info while we're in the XML used in step 8
			var unsubStaffordList = staffordList[i].getElementsByTagName("unsubsidized");
			for(var j=0;j<unsubStaffordList.length;j++){
				if(financially==unsubStaffordList[j].getAttribute("financially")){
					unsubStafford = parseInt(unsubStaffordList[j].firstChild.nodeValue);
				}
			}
		}
	}
	if (totalNeed==0){unsubStafford+=subStafford;subStafford=0;}
	if((awardAmt<=0)&&(totalNeed!=0)){subStafford=0;}
	if((awardAmt>0)&&(awardAmt<=subStafford)){
		staffordDiff=parseInt(subStafford-awardAmt);
		subStafford=awardAmt;
		awardAmt=0;
	}else{awardAmt-=subStafford;} //user limit calculation
	//alert("Subsidized Stafford Loan: $"+subStafford+"\nRunning Amount: $"+awardAmt);

//--------------------//
// 6. Perkins Loan:
// - awarded up to $2500 if needed (for UW-Platteville)
//--------------------//
	var perkinsLoan = 2500;
	//if(awardAmt<=0){perkinsLoan=0;}
	//Modified by TJ 9/22/2008
	if(awardAmt<=0 || efc>2500){perkinsLoan=0;}
	if((awardAmt>0)&&(awardAmt<=perkinsLoan)){perkinsLoan=awardAmt;awardAmt=0;}else{awardAmt-=perkinsLoan;} //user limit calculation
	//alert("Perkins Loan: $"+perkinsLoan+"\nRunning Amount: $"+awardAmt);

//--------------------//
// 8. Unsubsidized Stafford Loan:
// - data was grabbed back in step 5, so this section only limits the amount
// - students with NO need (totalNeed=0) can get the loan
// - students can be awarded if award amount was met (including any portion not 
//   awarded in the subStafford but not to exceed the EFC value
//--------------------//
	/*alert("Unsubsidized Stafford Loan: $"+unsubStafford+"\nRunning Amount: $"+awardAmt);
	//Modified by TJ
	var orig_unsubStafford = unsubStafford;
	if((totalNeed>0)&&(awardAmt==0)){ //user is awarded unsubStafford if need was met
		unsubStafford = (unsubStafford>efc)?parseInt(efc):parseInt(unsubStafford+staffordDiff);
	}
	alert("Unsubsidized Stafford Loan: $"+unsubStafford+"\nRunning Amount: $"+awardAmt);
	if((awardAmt>0)&&(awardAmt<=unsubStafford)){unsubStafford=awardAmt;awardAmt=0;}else{awardAmt-=unsubStafford;} //user limit calculation
	//Modified by TJ Teegan on 9/24/2008
	if(costOfAttendance>=totalNeed){unsubStafford=costOfAttendance-(pell+wiGrant+acg+seo+subStafford+perkinsLoan+workStudy);}
	if(subStafford<orig_subStafford){unsubStafford = unsubStafford+orig_subStafford-subStafford;}
	alert("Unsubsidized Stafford Loan: $"+unsubStafford+"\nRunning Amount: $"+awardAmt);
	if(unsubStafford>orig_unsubStafford){unsubStafford=orig_unsubStafford;}
	alert("Unsubsidized Stafford Loan: $"+unsubStafford+"\nRunning Amount: $"+awardAmt);*/
	
	//alert("Unsubsidized Stafford Loan: $"+unsubStafford+"\nRunning Amount: $"+awardAmt);

	var orig_unsubStafford = unsubStafford;
	var maxStafford = orig_unsubStafford+orig_subStafford-subStafford;
	if(efc>costOfAttendance){maxStafford=orig_unsubStafford;}
	var awardTally = pell+wiGrant+acg+seo+subStafford+perkinsLoan+workStudy;
	if(awardTally>=costOfAttendance){unsubStafford=0;}
	
	//alert("Unsubsidized Stafford Loan: $"+unsubStafford+"\nRunning Amount: $"+awardAmt);

	if(awardTally<costOfAttendance){
		if((awardTally + maxStafford) > costOfAttendance){unsubStafford = costOfAttendance-awardTally;}
		if((awardTally +maxStafford) <= costOfAttendance){unsubStafford = maxStafford;}
	}
	
	//alert("Unsubsidized Stafford Loan: $"+unsubStafford+"\nRunning Amount: $"+awardAmt);

	
	awardAmt = awardAmt-unsubStafford;
	if(awardAmt<0){awardAmt=0;}

	
	
//--------------------//
// Unmet need
// - whatever value is left in awardAmt is the unmet need
//--------------------//
	var unmetNeed = awardAmt;
	if(unmetNeed<0){unmetNeed=0;}
	var awardTotal = pell+wiGrant+acg+seo+subStafford+perkinsLoan+workStudy+unsubStafford;
	//alert("Award Total: $"+awardTotal+"\nUnmet Need: $"+unmetNeed);
	//Modified by TJ Teegan on 9/23/2008
	//if(awardTotal > costOfAttendance){awardTotal=costOfAttendance;unsubStafford=costOfAttendance-awardTotal;}

//--------------------//
//Award Eligibility Display
//--------------------//	
	var newHTML = "<table style='width:80%;' class='blackBorder' summary=''><tr><th colspan='2' style='background:silver'>Estimated Award Eligibility</th></tr>";
	newHTML +="<tr><td>Pell Grant</td><td class='values'>$"+pell+"</td></tr>";
	newHTML +="<tr><td>Wisconsin State Grant</td><td class='values'>$"+wiGrant+"</td></tr>";
	newHTML +="<tr><td>ACG Grant</td><td class='values'>$"+acg+"</td></tr>";
	newHTML +="<tr><td>Supplemental Educational Opportunity Grant</td><td class='values'>$"+seo+"</td></tr>";
	newHTML +="<tr><td>Subsidized Stafford Loan</td><td class='values'>$"+subStafford+"</td></tr>";
	newHTML +="<tr><td>Perkins Loan</td><td class='values'>$"+perkinsLoan+"</td></tr>";
	newHTML +="<tr><td>Federal Work Study</td><td class='values'>$"+workStudy+"</td></tr>";
	newHTML +="<tr><td>Unsubsidized Stafford Loan</td><td class='values'>$"+unsubStafford+"</td></tr>";
	newHTML +="<tr style='font-weight:bold;' class='totals'><td>Award Total</td><td class='values'>$"+awardTotal+"</td></tr>";
	newHTML +="<tr><td>Unmet Need</td><td class='values'>$"+unmetNeed+"</td></tr>";
	newHTML +="</table>";
	document.getElementById('VSA-awards').innerHTML=newHTML;
}