//--------------------//
// VSA Financial Aid Cost Estimator/Calculator
// Designed for State of Wisconsin UW-System Schools
// Written by: Daniel M. Frommelt, UW-Platteville
//--------------------//

//--------------------//
//Error checks EFC valus to make sure it is numeric >=0
//--------------------//
function checkData() {
	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.uww.edu/cost/vsa_estimator.php"; //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.uww.edu/cost/vsa/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, parking, 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"))&&(financially==costList[i].getAttribute("financially"))){
			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);
	
	//change names to friendly text
	var resid, academicYear, housingName, aidStatus;
	if(residency=="WI"){resid="Wisconsin";}
	else if(residency=="MN"){resid="Minnesota";}
	else if(residency=="Return-WI"){resid="Return to Wisconsin";}
	else if(residency=="Midwest-Exchange"){resid="Midwest Exchange";}
	else if(residency=="Non-Resident"){resid="Non Resident";}
	
	if(academic=="freshman"){academicYear="Freshman";}
	else if(academic=="sophomore"){academicYear="Sophomore";}
	else if(academic=="junior"){academicYear="Junior";}
	else if(academic=="senior"){academicYear="Senior";}
	
	if(housing=="commuter"){housingName="Living with Parent";}
	else if(housing=="on-campus"){housingName="On Campus";}
	else if(housing=="off-campus"){housingName="Off Campus";}
	
	if(financially=="dependent"){aidStatus="Dependent";}
	else if(financially=="independent"){aidStatus="Independent";}
	
	
	//Insert: user choices from previous page into the form IDs
	document.getElementById('vsa-residency').innerHTML=resid;
	document.getElementById('vsa-academic').innerHTML=academicYear;
	document.getElementById('vsa-financial').innerHTML=aidStatus;
	document.getElementById('vsa-housing').innerHTML=housingName;
	document.getElementById('v-efc').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 we can check for circumstances where
// the award will exceed the need but NOT the EFC. 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. ACG Grant
// 3. Wisconsin State Grant
// 4. Supplemental Educational Opportunity Grant
// 5. Federal Work Study
// 6. Subsidized Stafford Loan
// 7. Non-Resident Grant
// 8. Unsubsidzed Stafford Loan
// 9. Perkins Loan
// 10. PLUS 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. ACG Grant:
// - if awarded a Pell then $750
//--------------------//
	var acg = 0;
	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);

//--------------------//
// 3. 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 = Math.round((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);

//--------------------//
// 4. Supplemental Educational Opportunity Grant:
// - value based on EFC selection and academic year in between the min and max allowed in the XML file
//--------------------//
	var seo = 0;
	// select efc ranges and values
	var efcList2 = xmlDoc.getElementsByTagName("efc2");
	for(var i=0;i<efcList2.length;i++)
	{
		if((efc>=parseInt(efcList2[i].getAttribute("min")))&&(efc<=parseInt(efcList2[i].getAttribute("max")))&&(academic==efcList2[i].getAttribute("academic"))){
				seo = parseInt(efcList2[i].firstChild.nodeValue);
				if(awardAmt<=0){seo=0;awardAmt=0;}
				if((awardAmt>0)&&(awardAmt<=seo)){seo=awardAmt;awardAmt=0;}else{awardAmt-=seo;} //user limit calculation
		}
	}	
	//alert("SEO Grant: $"+seo+"\nRunning Amount: $"+awardAmt);

//--------------------//
// 5. Federal Work Study:
// - awarded based on academic level, need must meet minimum to get aid
//--------------------//
	var workStudy = 0;
	//select work study information of this user
	var workStudyList = xmlDoc.getElementsByTagName("workStudy");
	for(var i=0; i<workStudyList.length; i++) 
	{
		if(academic==workStudyList[i].getAttribute("academic")) {
			workStudyMin = parseInt(workStudyList[i].selectNodes("min")[0].firstChild.nodeValue);
			workStudyMax = parseInt(workStudyList[i].selectNodes("max")[0].firstChild.nodeValue);
		}
	}
	if(awardAmt<=0){workStudy=0;}	
	if((awardAmt>0)&&(awardAmt>=workStudyMin)){
		if(awardAmt<=workStudyMax){workStudy = awardAmt; awardAmt = 0;}else{workStudy = workStudyMax;awardAmt-=workStudy;} //user limit calculation		
	}else{ 
		workStudy=0;
	}
	//alert("Work Study: $"+workStudy+"\nRunning Amount: $"+awardAmt);

//--------------------//
// 6. Subsidized Stafford Loan:
// - dependent upon academic and financial status in XML
// - minimum need $200 currently not calulated
// - data in XML also contains the info for step 8
//--------------------//
	var subStafford = 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")){
			var subStaffordMax = parseInt(staffordList[i].selectNodes("subsidized")[0].firstChild.nodeValue);
			//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")){
					var unsubStaffordMax = parseInt(unsubStaffordList[j].firstChild.nodeValue);
				}
			}
		}
	}
	if(awardAmt<=0){subStafford=0;}
	if((awardAmt>0)&&(awardAmt<=subStaffordMax)){subStafford=awardAmt;awardAmt=0;}else{subStafford=subStaffordMax;awardAmt-=subStafford;} //user limit calculation
	//check total need if negitive sub =0
	if(totalNeed<=0){subStafford=0;}
	//alert("Subsidized Stafford Loan: $"+subStafford+"\nRunning Amount: $"+awardAmt);

//--------------------//
// 7. Non-Resident Grant:
// - 2000 for Freshmen and Sophomores, 1500 for Juniors and Seniors
// - need based (for UW-Whitewater)
//--------------------//

	var nonr = 0;
	if((residency=="Non-Resident") || (residency=="Midwest-Exchange")){
		if((academic=="freshman")||(academic=="sophomore")){nonr=2000;}
		if((academic=="junior")||(academic=="senior")){nonr=1500;}
	
		if(awardAmt<=0){nonr=0;}
		if((awardAmt>0)&&(awardAmt<=nonr)){nonr=awardAmt;awardAmt=0;}else{awardAmt-=nonr;} //user limit calculation
	}
	//alert("ACG Grant: $"+acg+"\nRunning Amount: $"+awardAmt);



//--------------------//
// 8. Unsubsidized Stafford Loan:
// - data was grabbed back in step 6, so this section only limits the amount
// - calculation based on how the difference between the unsub and sub combined can not exceed the maximum, 
//	 but if less than the max was given in sub the unsub can fill up to max for the combined total (for UW-Whitewater)
// - not tied in any way to need but awardTotal can't exceed totalCost (for UW-Whitewater)
//--------------------//

	// get current aid amount
	var subAwardTotal = pell+acg+wiGrant+seo+workStudy+subStafford;
	// get current maximum of aid allowed 
	if(subStafford==0){unsubStaffordMax=unsubStaffordMax+subStaffordMax;}
	if((subStafford>0)&&(subStafford<subStaffordMax)){ unsubStaffordMax = unsubStaffordMax + (subStaffordMax-subStafford);}
	var maxAllow = totalCost-subAwardTotal;
	if(efc==0) {
		if(awardAmt<=0){unsubStafford=0;}
		if((awardAmt>0)&&(awardAmt<=unsubStaffordMax)){unsubStafford=awardAmt;awardAmt=0;}else{unsubStafford=unsubStaffordMax;awardAmt-=unsubStafford;} //user limit calculation
	}else{
		if((awardAmt<=0)||(subAwardTotal==totalCost)){unsubStafford=0;}
		if(subAwardTotal<totalCost){
			if(unsubStaffordMax>=maxAllow){unsubStafford=maxAllow;awardAmt-=unsubStafford;}else{unsubStafford=unsubStaffordMax;awardAmt-=unsubStafford;}			
		}
	}
	//alert("Unsubsidized Stafford Loan: $"+unsubStafford+"\nMax Allowable: $"+maxAllow);

//--------------------//
// 9. Perkins Loan:
// - awarded if needed min $500 up to $1000 (for UW-Whitewater)
//--------------------//
	var perkinsLoan = 0;
	var perkinsLoanMin = 500;
	var perkinsLoanMax = 1000;
	if(awardAmt<=0){perkinsLoan=0;}
	if((awardAmt>0)&&(awardAmt>=perkinsLoanMin)){
		if(awardAmt<=perkinsLoanMax){perkinsLoan = awardAmt; awardAmt = 0;}else{perkinsLoan = perkinsLoanMax;awardAmt-=perkinsLoan;} //user limit calculation		
	}else{ 
		perkinsLoan=0;
	}
	//alert("Perkins Loan: $"+perkinsLoan+"\nRunning Amount: $"+awardAmt);

//--------------------//
// 10. PLUS Loan:
// - awarded if needed min $1000 up to $19500, dependent students only (for UW-Whitewater)
//--------------------//
	var plusLoan = 0;
	var plusLoanMin = 1000;
	var plusLoanMax = 19500;
	var subAwardTotal2 = pell+acg+wiGrant+seo+workStudy+subStafford+nonr+unsubStafford+perkinsLoan;
	var maxAllow2 = totalCost-subAwardTotal2;
	if(financially=="dependent"){
		if((awardAmt<=0)||(subAwardTotal2==totalCost)){plusLoan=0;}
		if(subAwardTotal<totalCost){
			if(plusLoanMax>=maxAllow2){plusLoan=maxAllow2;awardAmt-=plusLoan;}else{plusLoan=plusLoanMax;awardAmt-=plusLoan;} //user limit calculation		
		}
	}
	//alert("PLUS Loan: $"+plusLoan+"\nRunning Amount: $"+awardAmt);

//--------------------//
// Unmet COA
// - since it's impossible for a student to get 
//--------------------//
	var awardTotal = pell+acg+wiGrant+seo+workStudy+subStafford+nonr+unsubStafford+perkinsLoan+plusLoan;
	var unmetCoa = totalCost-awardTotal;
	//alert("Award Total: $"+awardTotal+"\nUnmet Need: $"+unmetNeed);

//--------------------//
//Award Eligibility Display
//--------------------//	
	
	if(pell==0){ $("#v-pell").remove(); }else{document.getElementById('pell').innerHTML="$"+pell;}
	if(acg==0){ $("#v-acg").remove(); }else{ document.getElementById('acg').innerHTML="$"+acg;}
	if(wiGrant==0){ $("#v-wheg").remove(); }else{document.getElementById('wheg').innerHTML="$"+wiGrant;}
	if(seo==0){ $("#v-seog").remove(); }else{document.getElementById('seog').innerHTML="$"+seo;}
	if(workStudy==0){ $("#v-fws").remove(); }else{document.getElementById('fws').innerHTML="$"+workStudy;}
	if(subStafford===0){ $("#v-substafford").remove(); }else{document.getElementById('substafford').innerHTML="$"+subStafford;}
	if(nonr!=0){document.getElementById('nonr').innerHTML="$"+nonr;}else{$("#v-nonr").remove();}
	if(unsubStafford==0){ $("#v-unsubstafford").remove(); }else{document.getElementById('unsubstafford').innerHTML="$"+unsubStafford;}
	if(perkinsLoan==0){ $("#v-perkins").remove(); }else{document.getElementById('perkins').innerHTML="$"+perkinsLoan;}
	if(plusLoan==0){ $("#v-plus").remove(); }else{document.getElementById('plus').innerHTML="$"+plusLoan;}
	document.getElementById('award').innerHTML="$"+awardTotal;
	document.getElementById('unmet-coa').innerHTML="$"+unmetCoa;

}