// Relys on JQuery to be loaded first
/* Currency Formatter */
(function(A){A.fn.extend({currency:function(B){var C={s:",",d:".",c:2};C=A.extend({},C,B);return this.each(function(){var D=(C.n||A(this).text());D=(typeof D==="number")?D:((/\./.test(D))?parseFloat(D):parseInt(D)),s=D<0?"-":"",i=parseInt(D=Math.abs(+D||0).toFixed(C.c))+"",j=(j=i.length)>3?j%3:0;A(this).text(s+(j?i.substr(0,j)+C.s:"")+i.substr(j).replace(/(\d{3})(?=\d)/g,"$1"+C.s)+(C.c?C.d+Math.abs(D-i).toFixed(C.c).slice(2):""));return this})}})})(jQuery);jQuery.currency=function(){var A=jQuery("<span>").text(arguments[0]).currency(arguments[1]);return A.text()};

//Determine the current page and set the nav arrow
$(document).ready(function(){
  setNav();
  appendRefCode();
});
//Determine the current page and set the nav arrow
function setNav(){
var path = window.location.pathname;
    if(path == "/features-and-benefits.htm")
    {
        $("#nav-features a").addClass("active");
        $("#nav-features").attr("style","height:76px;");
    }
    if(path == "/smart-borrowing.htm")
    {
        $("#nav-smart a").addClass("active");
        $("#nav-smart").attr("style","height:76px;");
    }
    if(path == "/rates-and-repayment.htm")
    {
        $("#nav-rates a").addClass("active");
        $("#nav-rates").attr("style","height:76px;");
    }
    if(path == "/before-you-apply.htm")
    {
        $("#nav-before a").addClass("active");
        $("#nav-before").attr("style","height:76px;");
    }
}

function initExamples(){
    var repaySelBar = $("#repay-select");
    var sel = $("#repay-selected div.sel");
    var plans = $("#repayment-plans");
    var examples = $("#repayment-examples");
    var imm = $("#view-immediate");
    var sta = $("#view-starter");
    var varfix = $("#fixed-var-select");
    
    $("#plans-select,#plan-link").click(function(){sel.attr("style","left:5px;").show(); plans.show(); examples.hide(); });
    $("#examples-select,#rate-link").click(function(){sel.attr("style","left:230px;").show(); plans.hide(); examples.show();});
    
    $("#variable").click(function(){
        varfix.attr("style","background-position:0 -4px");$("#variable").attr("style","width:150px");$("#fixed").attr("style","width:155px");
        if($("table.starter").is(':visible') || $("table.starter-fixed").is(':visible'))
        {
            studentStarter(imm,sta);
        }
        else
        {
            immediateRepay(imm,sta);
        }
    });
    $("#fixed").click(function(){
        varfix.attr("style","background-position:0 -65px");$("#variable").attr("style","width:155px");$("#fixed").attr("style","width:150px");
        if($("table.starter").is(':visible') || $("table.starter-fixed").is(':visible'))
        {
            studentStarter(imm,sta);
        }
        else
        {
            immediateRepay(imm,sta);
        }
    });
    
    //For footnote class=fn-frss perform the #fixed OnClick action and then load the Student Starter Table
    $(".fn-frss").click(function(){//bind to every element with the class fn-frss an perform the following onClick
	//set the focus
	document.getElementById('repay-select').scrollIntoView(); 

	//Show the Examples pane
        sel.attr("style","left:230px;").show(); plans.hide(); examples.show();
        //Set the Variable / Fixed toggle button image to show the Fixed side as selected.
        varfix.attr("style","background-position:0 -65px");$("#variable").attr("style","width:155px");$("#fixed").attr("style","width:150px");
        //Load the Student Starter table view
        studentStarter(imm,sta);
    });
    //end For footnote
    
    imm.click(function(){
        immediateRepay(imm,sta);
        });
        
    sta.click(function(){
             studentStarter(imm,sta);
        });
}
function studentStarter(imm,sta){
sta.removeClass("view").addClass("viewing");
        imm.removeClass("viewing").addClass("view");
        $(".col-2 img").addClass("down");
            //if Variable is selected
            if($("#variable").width() == 150){
                $("table.immediate").hide(); $("table.starter").show();
                $("table.immediate-fixed").hide(); $("table.starter-fixed").hide();
                $("#foot-variable-imm").hide(); $("#foot-variable-stu").show(); $("#foot-fixed-imm").hide(); $("#foot-fixed-stu").hide();
            }
            else{//Fixed is selected
                $("table.immediate-fixed").hide(); $("table.starter-fixed").show();
                $("table.immediate").hide(); $("table.starter").hide();
                $("#foot-variable-imm").hide(); $("#foot-variable-stu").hide(); $("#foot-fixed-imm").hide(); $("#foot-fixed-stu").show();
            }
}
function immediateRepay(imm,sta){
imm.removeClass("view").addClass("viewing"); 
        sta.removeClass("viewing").addClass("view"); 
        $(".col-2 img").removeClass("down");
            if($("#variable").width() == 150){
                $("table.immediate").show(); $("table.starter").hide();
                $("table.immediate-fixed").hide(); $("table.starter-fixed").hide();
                $("#foot-variable-imm").show(); $("#foot-variable-stu").hide(); $("#foot-fixed-imm").hide(); $("#foot-fixed-stu").hide();
            }
            else{
                $("table.immediate-fixed").show(); $("table.starter-fixed").hide();
                $("table.immediate").hide(); $("table.starter").hide();
                $("#foot-variable-imm").hide(); $("#foot-variable-stu").hide(); $("#foot-fixed-imm").show(); $("#foot-fixed-stu").hide();
            }
}
function initRates(){

   var serviceURL = "http://"+window.location.hostname+"/RPX/RPXWebServiceImplService";
 //   var serviceURL = "http://dev.collegiatecustomchoice.com/RPX/RPXWebServiceImplService";  use to test on localhost
    getRatesJSON(serviceURL);
    
}
function getRatesJSON(serviceURL){
var url = serviceURL;
var linkID = "CCCFAO1";
var resType = "JSON";
var data = '<FMMessage><FMHeader><SourceComponent>JSCleint</SourceComponent><MessageType version="1.0">RepayExample Request</MessageType>'+
'</FMHeader><FMBody><RepayExampleRequest><LinkId>'+linkID+'</LinkId><ResponseFormat>'+resType+'</ResponseFormat></RepayExampleRequest></FMBody></FMMessage>';			
var req = '<S:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:getCalc xmlns:ns2="http://webservice.rpx.fmer.com/"><arg0>'+encode(data)+'</arg0></ns2:getCalc></S:Body></S:Envelope>'
	
	$.ajax({ 
			url: url, 
			data: req,
			type: "post", 
			contentType: 'text/xml; charset="utf-8"',
			async: true,
			success: function(res) {processRates(res);}, 
			error: function(e , msg){ $("#examples-loading").html("<h2>Error loading current rates</h2><h3>Please try again later.</h3>");}
	      }); 
}

function processRates(data){
    var JSON = $.parseJSON(data.text);
    if(JSON == null || typeof(JSON)=='undefined')
    { JSON = $.parseJSON(data.firstChild.textContent);}
    
    var commonData = JSON.commonPricingData;
    var rateMargins = JSON.rateMarginsDTOList;
    
    var VIVariableLow;
    var VIVariableHigh;
    var VPVariableLow;
    var VPVariableHigh;
    var XVIVariableLow;
    var XVIVariableHigh;
    var XVPVariableLow;
    var XVPVariableHigh;
    var VIFixedLow;
    var VIFixedHigh;
    var VPFixedLow;
    var VPFixedHigh;
    var XVIFixedLow;
    var XVIFixedHigh;
    var XVPFixedLow;
    var XVPFixedHigh;
    for(var i = 0; i < JSON.rpxCalcRespDTOList.length; i++)
    {
        //VARIABLE
        if(JSON.rpxCalcRespDTOList[i].rateIndexCode != "FIXED"){
            //IMMEDIATE
            if(JSON.rpxCalcRespDTOList[i].calcType == "IM"){
                //5 YEAR
                if(JSON.rpxCalcRespDTOList[i].monthsInRepayment == 60){
                    if(VIVariableLow == null){VIVariableLow = JSON.rpxCalcRespDTOList[i];}else{VIVariableHigh = JSON.rpxCalcRespDTOList[i];}
                }
                //15 YEAR
                if(JSON.rpxCalcRespDTOList[i].monthsInRepayment == 180){
                    if(XVIVariableLow == null){XVIVariableLow = JSON.rpxCalcRespDTOList[i];}else{XVIVariableHigh = JSON.rpxCalcRespDTOList[i];}
                }
            }
            //PARTIAL
            if(JSON.rpxCalcRespDTOList[i].calcType == "PI"){
                //5 YEAR
                if(JSON.rpxCalcRespDTOList[i].monthsInRepayment == 60){
                    if(VPVariableLow == null){VPVariableLow = JSON.rpxCalcRespDTOList[i];}else{VPVariableHigh = JSON.rpxCalcRespDTOList[i];}
                }
                //15 YEAR
                if(JSON.rpxCalcRespDTOList[i].monthsInRepayment == 180){
                    if(XVPVariableLow == null){XVPVariableLow = JSON.rpxCalcRespDTOList[i];}else{XVPVariableHigh = JSON.rpxCalcRespDTOList[i];}
                }
            }
        }
        else{
        //FIXED
            //IMMEDIATE
            if(JSON.rpxCalcRespDTOList[i].calcType == "IM"){
                //5 YEAR
                if(JSON.rpxCalcRespDTOList[i].monthsInRepayment == 60){
                    if(VIFixedLow == null){VIFixedLow = JSON.rpxCalcRespDTOList[i];}else{VIFixedHigh = JSON.rpxCalcRespDTOList[i];}
                }
                //15 YEAR
                if(JSON.rpxCalcRespDTOList[i].monthsInRepayment == 180){
                    if(XVIFixedLow == null){XVIFixedLow = JSON.rpxCalcRespDTOList[i];}else{XVIFixedHigh = JSON.rpxCalcRespDTOList[i];}
                }
            }
            //PARTIAL
            if(JSON.rpxCalcRespDTOList[i].calcType == "PI"){
                //5 YEAR
                if(JSON.rpxCalcRespDTOList[i].monthsInRepayment == 60){
                    if(VPFixedLow == null){VPFixedLow = JSON.rpxCalcRespDTOList[i];}else{VPFixedHigh = JSON.rpxCalcRespDTOList[i];}
                }
                //15 YEAR
                if(JSON.rpxCalcRespDTOList[i].monthsInRepayment == 180){
                    if(XVPFixedLow == null){XVPFixedLow = JSON.rpxCalcRespDTOList[i];}else{XVPFixedHigh = JSON.rpxCalcRespDTOList[i];}
                }
            }
        }
        
    }
    //Disbursment Date
    var dt = reformatDate(VIVariableLow.disbSchedule[0].disbDate);
    //Effective Dates
    //Override to display day 1 of the current month
    /*
    var VarEffectiveDate = reformatDate(commonData.intRateEffectiveDateForVariable);
    var FixedEffectiveDate = reformatDate(commonData.intRateEffectiveDateForFixed);
    var BaseRateDate = reformatDate(commonData.baseRateStartDate);
    */
    var currDate = new Date();
    var VarEffectiveDate = currDate.getMonth()+1+"/1/"+currDate.getFullYear();
    var FixedEffectiveDate = currDate.getMonth()+1+"/1/"+currDate.getFullYear();
    var BaseRateDate = currDate.getMonth()+1+"/1/"+currDate.getFullYear();
	var VariableMarginEffectiveDate = reformatDate(commonData.intRateEffectiveDateForVariable);
    var FixedMarginEffectiveDate = reformatDate(commonData.intRateEffectiveDateForFixed);
	
	/* 
	   5/31/11 - We need to introduce a couple more dates.  These dates are to be used in the variable, 
	   or fixed, or even non-specific type areas of the website where we need to place a date
	   that represents when the last time the rates changed.  The logic is to compare the dates
	   of the margin for that type (fixed/variable) to the LIBOR effective dates.  The LIBOR 
	   date for Suntrust is always no longer in the past than the 1st day of the month you 
	   are in.  That is why I am using the BaseReateDate that was already calculated above 
	   in the comparison and comparing that to either the fixed effective date from above or
	   the variable effective date from above.
	   
	   The currDate function returns the MM value as one digit if the month is less than 10.
	   We need that date to be padded with a zero to compare with the margin eff dates.  Those
	   dates are in the format = yyyy-MM-DD.  If the 6th digit of curr date = - that means there
	   is only one digit in the MM field so I place a zero in front of it.
	*/
	
	var rawDate = currDate.getFullYear()+"-"+eval(currDate.getMonth()+1)+"-01";
	if (rawDate.charAt(6) == "-")
	   {
		   var CompareBaseRateDate = currDate.getFullYear()+"-0"+eval(currDate.getMonth()+1)+"-01";
	   }
	else
	  {
		   var CompareBaseRateDate = currDate.getFullYear()+"-"+eval(currDate.getMonth()+1)+"-01";
	  }
	
	
	
	if  (CompareBaseRateDate > commonData.intRateEffectiveDateForVariable)
	    {
		  var GreaterVariableDate = currDate.getMonth()+1+"/1/"+currDate.getFullYear();
		}
	else
		{ 
		  var GreaterVariableDate = VariableMarginEffectiveDate;
		}
    if  (CompareBaseRateDate > commonData.intRateEffectiveDateForFixed)
	    {
		  var GreaterFixedDate = currDate.getMonth()+1+"/1/"+currDate.getFullYear();
		}
	else
		{ 
		  var GreaterFixedDate = FixedMarginEffectiveDate;
		}
		
	//Testing Dates to Display
   
    $(".CompareDt").text(CompareBaseRateDate);
	$(".VarInt").text(commonData.intRateEffectiveDateForVariable);
	$(".FixInt").text(commonData.intRateEffectiveDateForFixed);

	
    //Competitive Rates Box
    $(".vardate").text(VarEffectiveDate);
    //Variable
    $(".comp-variable-rate").text(VIVariableLow.borrMarginRepay.toFixed(2)+"%, currently a "+VIVariableLow.borrRepayIntRate.toFixed(3)+"%");
    $(".comp-variable-apr").html(" interest rate and <span style=\"font-weight:bold;\">"+VIVariableLow.apr.toFixed(3)+"% APR<sup><a href=\"#twocarr\" style=\"color:#fff;\">^^</a></sup></span>");
    //Fixed
    $(".comp-fixed-rate").text(VIFixedLow.borrRepayIntRate.toFixed(3)+"%");
    $(".comp-fixed-apr").html(" currently a <span style=\"font-weight:bold;\">"+VIFixedLow.apr.toFixed(3)+"% APR<sup><a href=\"#footcross\" style=\"color:#fff;\">&dagger;&dagger;</a></sup></span>");
    
    $(".rate-date").text("Rates as of "+VarEffectiveDate);
	$(".greater-rate-date").text("Rates as of "+GreaterVariableDate);
    $(".ratedate").text(VarEffectiveDate+" ");

    //TABLE RATES
    
    //Immediate Repayment Variable
    $("table.immediate td.amt-low").text(XVIVariableLow.disbSchedule[0].netDisbAmt+XVIVariableLow.disbSchedule[1].netDisbAmt).currency().prepend("$");
    $("table.immediate td.amt-high").text(XVIVariableHigh.disbSchedule[0].netDisbAmt+XVIVariableHigh.disbSchedule[1].netDisbAmt).currency().prepend("$");
    $("table.immediate td.type-low").text(XVIVariableLow.rateIndexCode == 'FIXED' ? 'Fixed':'Variable');
    $("table.immediate td.type-high").text(XVIVariableHigh.rateIndexCode == 'FIXED' ? 'Fixed':'Variable');
    $("table.immediate td.int-low").text(XVIVariableLow.borrRepayIntRate.toFixed(3)+"%").append("<sup><a href=\"#foot2\">2</a></sup>");
    $("table.immediate td.int-high").text(XVIVariableHigh.borrRepayIntRate.toFixed(3)+"%").append("<sup><a href=\"#foot2\">2</a></sup>");
    $("table.immediate td.apr-low").text(XVIVariableLow.apr.toFixed(3)+"%").append("<sup><a href=\"#foot3\">3</a></sup>");
    $("table.immediate td.apr-high").text(XVIVariableHigh.apr.toFixed(3)+"%").append("<sup><a href=\"#foot3\">3</a></sup>");
    $("table.immediate td.ofee-low").text(XVIVariableLow.origFeeAmt).currency().prepend(XVIVariableLow.origFeePct+"%<sup><a href=\"#foot4\">4</a></sup><br />$");
    $("table.immediate td.ofee-high").text(XVIVariableHigh.origFeeAmt).currency().prepend(XVIVariableHigh.origFeePct+"%<sup><a href=\"#foot4\">4</a></sup><br />$");
    $("table.immediate td.moPaySchool-low").text(XVIVariableLow.monthlyPmtPreGrad).currency().prepend("$").append("<sup><a href=\"#foot5\">5</a></sup>");
    $("table.immediate td.moPaySchool-high").text(XVIVariableHigh.monthlyPmtPreGrad).currency().prepend("$").append("<sup><a href=\"#foot5\">5</a></sup>");
    $("table.immediate td.moPay-low").text(XVIVariableLow.monthlyPmtPostGrad).currency().prepend("$").append("<sup><a href=\"#foot6\">6</a></sup>");
    $("table.immediate td.moPay-high").text(XVIVariableHigh.monthlyPmtPostGrad).currency().prepend("$").append("<sup><a href=\"#foot6\">6</a></sup>");
    $("table.immediate td.def-low").text(XVIVariableLow.monthsInDeferment).append("<sup><a href=\"#foot7\">7</a></sup>");
    $("table.immediate td.def-high").text(XVIVariableHigh.monthsInDeferment).append("<sup><a href=\"#foot7\">7</a></sup>");
    $("table.immediate td.rep-low").text(XVIVariableLow.monthsInRepayment);
    $("table.immediate td.rep-high").text(XVIVariableHigh.monthsInRepayment);
    $("table.immediate td.tot-low").text(XVIVariableLow.totalPmtAmt).currency().prepend("$").append("<sup><a href=\"#foot8\">8</a></sup>");
    $("table.immediate td.tot-high").text(XVIVariableHigh.totalPmtAmt).currency().prepend("$").append("<sup><a href=\"#foot8\">8</a></sup>");
    
    //Partial Interest Variable
    $("table.starter td.amt-low").text(XVPVariableLow.disbSchedule[0].netDisbAmt+XVPVariableLow.disbSchedule[1].netDisbAmt).currency().prepend("$");
    $("table.starter td.amt-high").text(XVPVariableHigh.disbSchedule[0].netDisbAmt+XVPVariableHigh.disbSchedule[1].netDisbAmt).currency().prepend("$");
    $("table.starter td.type-low").text(XVPVariableLow.rateIndexCode == 'FIXED' ? 'Fixed':'Variable');
    $("table.starter td.type-high").text(XVPVariableHigh.rateIndexCode == 'FIXED' ? 'Fixed':'Variable');
    $("table.starter td.int-low").text(XVPVariableLow.borrRepayIntRate.toFixed(3)+"%").append("<sup><a href=\"#fvs2\">2</a></sup>");
    $("table.starter td.int-high").text(XVPVariableHigh.borrRepayIntRate.toFixed(3)+"%").append("<sup><a href=\"#fvs2\">2</a></sup>");
    $("table.starter td.apr-low").text(XVPVariableLow.apr.toFixed(3)+"%").append("<sup><a href=\"#fvs3\">3</a></sup>");
    $("table.starter td.apr-high").text(XVPVariableHigh.apr.toFixed(3)+"%").append("<sup><a href=\"#fvs3\">3</a></sup>");
    $("table.starter td.ofee-low").text(XVPVariableLow.origFeeAmt).currency().prepend(XVPVariableLow.origFeePct+"%<sup><a href=\"#fvs4\">4</a></sup><br />$");
    $("table.starter td.ofee-high").text(XVPVariableHigh.origFeeAmt).currency().prepend(XVPVariableHigh.origFeePct+"%<sup><a href=\"#fvs4\">4</a></sup><br />$");
    $("table.starter td.moPaySchool-low").text(XVPVariableLow.monthlyPmtPreGrad).currency().prepend("$").append("<sup><a href=\"#fvs5\">5</a></sup>");
    $("table.starter td.moPaySchool-high").text(XVPVariableHigh.monthlyPmtPreGrad).currency().prepend("$").append("<sup><a href=\"#fvs5\">5</a></sup>");
    $("table.starter td.moPay-low").text(XVPVariableLow.monthlyPmtPostGrad).currency().prepend("$").append("<sup><a href=\"#fvs6\">6</a></sup>");
    $("table.starter td.moPay-high").text(XVPVariableHigh.monthlyPmtPostGrad).currency().prepend("$").append("<sup><a href=\"#fvs6\">6</a></sup>");
    $("table.starter td.def-low").text(XVPVariableLow.monthsInDeferment);
    $("table.starter td.def-high").text(XVPVariableHigh.monthsInDeferment);
    $("table.starter td.rep-low").text(XVPVariableLow.monthsInRepayment);
    $("table.starter td.rep-high").text(XVPVariableHigh.monthsInRepayment);
    $("table.starter td.tot-low").text(XVPVariableLow.totalPmtAmt).currency().prepend("$").append("<sup><a href=\"#fvs7\">7</a></sup>");
    $("table.starter td.tot-high").text(XVPVariableHigh.totalPmtAmt).currency().prepend("$").append("<sup><a href=\"#fvs7\">7</a></sup>");
    
    //Immediate Repayment Fixed
    $("table.immediate-fixed td.amt-low").text(XVIFixedLow.disbSchedule[0].netDisbAmt+XVIFixedLow.disbSchedule[1].netDisbAmt).currency().prepend("$");
    $("table.immediate-fixed td.amt-high").text(XVIFixedHigh.disbSchedule[0].netDisbAmt+XVIFixedHigh.disbSchedule[1].netDisbAmt).currency().prepend("$");
    $("table.immediate-fixed td.type-low").text(XVIFixedLow.rateIndexCode == 'FIXED' ? 'Fixed':'Variable');
    $("table.immediate-fixed td.type-high").text(XVIFixedHigh.rateIndexCode == 'FIXED' ? 'Fixed':'Variable');
    $("table.immediate-fixed td.int-low").text(XVIFixedLow.borrRepayIntRate.toFixed(3)+"%").append("<sup><a href=\"#ffi2\">2</a></sup>");
    $("table.immediate-fixed td.int-high").text(XVIFixedHigh.borrRepayIntRate.toFixed(3)+"%").append("<sup><a href=\"#ffi2\">2</a></sup>");
    $("table.immediate-fixed td.apr-low").text(XVIFixedLow.apr.toFixed(3)+"%").append("<sup><a href=\"#ffi3\">3</a></sup>");
    $("table.immediate-fixed td.apr-high").text(XVIFixedHigh.apr.toFixed(3)+"%").append("<sup><a href=\"#ffi3\">3</a></sup>");
    $("table.immediate-fixed td.ofee-low").text(XVIFixedLow.origFeeAmt).currency().prepend(XVIFixedLow.origFeePct+"%<sup><a href=\"#ffi4\">4</a></sup><br />$");
    $("table.immediate-fixed td.ofee-high").text(XVIFixedHigh.origFeeAmt).currency().prepend(XVIFixedHigh.origFeePct+"%<sup><a href=\"#ffi4\">4</a></sup><br />$");
    $("table.immediate-fixed td.moPaySchool-low").text(XVIFixedLow.monthlyPmtPreGrad).currency().prepend("$").append("<sup><a href=\"#ffi5\">5</a></sup>");
    $("table.immediate-fixed td.moPaySchool-high").text(XVIFixedHigh.monthlyPmtPreGrad).currency().prepend("$").append("<sup><a href=\"#ffi5\">5</a></sup>");
    $("table.immediate-fixed td.moPay-low").text(XVIFixedLow.monthlyPmtPostGrad).currency().prepend("$").append("<sup><a href=\"#ffi6\">6</a></sup>");
    $("table.immediate-fixed td.moPay-high").text(XVIFixedHigh.monthlyPmtPostGrad).currency().prepend("$").append("<sup><a href=\"#ffi6\">6</a></sup>");
    $("table.immediate-fixed td.def-low").text(XVIFixedLow.monthsInDeferment).append("<sup><a href=\"#ffi7\">7</a></sup>");
    $("table.immediate-fixed td.def-high").text(XVIFixedHigh.monthsInDeferment).append("<sup><a href=\"#ffi7\">7</a></sup>");
    $("table.immediate-fixed td.rep-low").text(XVIFixedLow.monthsInRepayment);
    $("table.immediate-fixed td.rep-high").text(XVIFixedHigh.monthsInRepayment);
    $("table.immediate-fixed td.tot-low").text(XVIFixedLow.totalPmtAmt).currency().prepend("$").append("<sup><a href=\"#ffi8\">8</a></sup>");
    $("table.immediate-fixed td.tot-high").text(XVIFixedHigh.totalPmtAmt).currency().prepend("$").append("<sup><a href=\"#ffi8\">8</a></sup>");
    
    //Partial Interest Fixed
    $("table.starter-fixed td.amt-low").text(XVPFixedLow.disbSchedule[0].netDisbAmt+XVPFixedLow.disbSchedule[1].netDisbAmt).currency().prepend("$");
    $("table.starter-fixed td.amt-high").text(XVPFixedHigh.disbSchedule[0].netDisbAmt+XVPFixedHigh.disbSchedule[1].netDisbAmt).currency().prepend("$");
    $("table.starter-fixed td.type-low").text(XVPFixedLow.rateIndexCode == 'FIXED' ? 'Fixed':'Variable');
    $("table.starter-fixed td.type-high").text(XVPFixedHigh.rateIndexCode == 'FIXED' ? 'Fixed':'Variable');
    $("table.starter-fixed td.int-low").text(XVPFixedLow.borrRepayIntRate.toFixed(3)+"%").append("<sup><a href=\"#ffs2\">2</a></sup>");
    $("table.starter-fixed td.int-high").text(XVPFixedHigh.borrRepayIntRate.toFixed(3)+"%").append("<sup><a href=\"#ffs2\">2</a></sup>");
    $("table.starter-fixed td.apr-low").text(XVPFixedLow.apr.toFixed(3)+"%").append("<sup><a href=\"#ffs3\">3</a></sup>");
    $("table.starter-fixed td.apr-high").text(XVPFixedHigh.apr.toFixed(3)+"%").append("<sup><a href=\"#ffs3\">3</a></sup>");
    $("table.starter-fixed td.ofee-low").text(XVPFixedLow.origFeeAmt).currency().prepend(XVPFixedLow.origFeePct+"%<sup><a href=\"#ffs4\">4</a></sup><br />$");
    $("table.starter-fixed td.ofee-high").text(XVPFixedHigh.origFeeAmt).currency().prepend(XVPFixedHigh.origFeePct+"%<sup><a href=\"#ffs4\">4</a></sup><br />$");
    $("table.starter-fixed td.moPaySchool-low").text(XVPFixedLow.monthlyPmtPreGrad).currency().prepend("$").append("<sup><a href=\"#ffs5\">5</a></sup>");
    $("table.starter-fixed td.moPaySchool-high").text(XVPFixedHigh.monthlyPmtPreGrad).currency().prepend("$").append("<sup><a href=\"#ffs5\">5</a></sup>");
    $("table.starter-fixed td.moPay-low").text(XVPFixedLow.monthlyPmtPostGrad).currency().prepend("$").append("<sup><a href=\"#ffs6\">6</a></sup>");
    $("table.starter-fixed td.moPay-high").text(XVPFixedHigh.monthlyPmtPostGrad).currency().prepend("$").append("<sup><a href=\"#ffs6\">6</a></sup>");
    $("table.starter-fixed td.def-low").text(XVPFixedLow.monthsInDeferment);
    $("table.starter-fixed td.def-high").text(XVPFixedHigh.monthsInDeferment);
    $("table.starter-fixed td.rep-low").text(XVPFixedLow.monthsInRepayment);
    $("table.starter-fixed td.rep-high").text(XVPFixedHigh.monthsInRepayment);
    $("table.starter-fixed td.tot-low").text(XVPFixedLow.totalPmtAmt).currency().prepend("$").append("<sup><a href=\"#ffs7\">7</a></sup>");
    $("table.starter-fixed td.tot-high").text(XVPFixedHigh.totalPmtAmt).currency().prepend("$").append("<sup><a href=\"#ffs7\">7</a></sup>");
    
    //FOOTNOTES
    //Variable
    $(".vardate").text(VarEffectiveDate);
    $(".var-rate-low-i").text(XVIVariableLow.borrRepayIntRate.toFixed(3)+"%");
    $(".var-rate-high-i").text(XVIVariableHigh.borrRepayIntRate.toFixed(3)+"%");
    $(".var-rate-low-s").text(XVPVariableLow.borrRepayIntRate.toFixed(3)+"%");
    $(".var-rate-high-s").text(XVPVariableHigh.borrRepayIntRate.toFixed(3)+"%");
    $(".base-rate").text(commonData.baseRate+"%");
    $(".base-rate-date").text(BaseRateDate);
	$(".greater-variable-date").text(GreaterFixedDate);
	$(".var-margin-effective-date").text(VariableMarginEffectiveDate);
    $(".var-margin-low").text(XVIVariableLow.borrMarginRepay.toFixed(2)+"%");
    $(".var-margin-high").text(XVIVariableHigh.borrMarginRepay.toFixed(2)+"%");
    $(".var-margin-low-a").text(XVPVariableLow.borrMarginRepay.toFixed(2)+"%");
    $(".var-margin-high-a").text(XVPVariableHigh.borrMarginRepay.toFixed(2)+"%");
    
    //Common Footnotes
    $(".fixed-month-payment").text(VIFixedLow.monthlyPmtPreGrad).currency().prepend("$");
    $(".fixed-int-low").text(VIFixedLow.borrRepayIntRate.toFixed(3)+"%");
    $(".fixed-int-high").text(VIFixedHigh.borrRepayIntRate.toFixed(3)+"%");
	$(".fixed-margin-effective-date").text(FixedMarginEffectiveDate);
	$(".greater-fixed-date").text(GreaterFixedDate);
    
    var fixed20IR = getRateMargin(rateMargins,"IM","FIXED","240");
    var fixed20IRMax = fixed20IR.split('|')[1];
    $(".fixed-20-ir-max").text(fixed20IRMax+"%");
    
    var fixed5IO = getRateMargin(rateMargins,"IO","FIXED","60");
    var fixed5IOMin = fixed5IO.split('|')[0];
    $(".fixed-5-io-min").text(fixed5IOMin+"%");
    
    var fixed20DF = getRateMargin(rateMargins,"DF","FIXED","240");
    var fixed20DFMax = fixed20DF.split('|')[1];
    $(".fixed-20-df-max").text(fixed20DFMax+"%");
    
    var var20IR = getRateMargin(rateMargins,"IM","VARIABLE","240");
    var var20IRMax = var20IR.split('|')[1];
    $(".var-20-ir-max").text(var20IRMax+"%");
    
    var var5IO = getRateMargin(rateMargins,"IO","VARIABLE","60");
    var var5IOMin = var5IO.split('|')[0];
    $(".var-5-io-min").text(var5IOMin+"%");
    
    var var20DF = getRateMargin(rateMargins,"DF","VARIABLE","240");
    var var20DFMax = var20DF.split('|')[1];
    $(".var-20-df-max").text(var20DFMax+"%");

  //  $(".orig-fee-low").text(VIFixedLow.origFeePct+"%");
 //  $(".orig-fee-high").text(VIFixedHigh.origFeePct+"%");
    $(".orig-fee-low-fixed").text(commonData.minOrigFeeForFixed+"%");
	$(".orig-fee-high-fixed").text(commonData.maxOrigFeeForFixed+"%");

    $(".fixed-date").text(FixedEffectiveDate+" ");
    $(".variable-month-payment").text(VIVariableLow.monthlyPmtPreGrad).currency().prepend("$");
    $(".var-margin-low-b").text(VIVariableLow.borrMarginRepay.toFixed(2)+"%");
    $(".var-margin-high-b").text(VIVariableHigh.borrMarginRepay.toFixed(2)+"%");

    //Hide loader
    $("#examples-loading").hide();
    //Show tables
    $("#examples").show();
}

/************************ Min and Max Rate Finder *******************************/
//Returns Min Rate and Max Rate Pipe separated (ex: 6.88|13.9 )
function getRateMargin(rateMargins,repayCode,varCode,repayTerm){
    for(var i = 0; i < rateMargins.length; i++)
    {
        if(rateMargins[i].repaycode == repayCode && rateMargins[i].variabilityCode == varCode
            && rateMargins[i].maxRepayTerm == repayTerm)
            {
                return rateMargins[i].minBorrMarginRepayIntRate.toFixed(3)+"|"+rateMargins[i].maxBorrMarginRepayIntRate.toFixed(3);
            }
    }
}

/************************ Smart Borrowing Calculator *******************************/
function initCalculator(){
$("#calculator input").change(function(){
    CalcTotal();
    });
}
function CalcTotal(){
checkForBlanks();
var tuition = getFloatVal("#tb-tuition");
var books = getFloatVal("#tb-books");
var transportation = getFloatVal("#tb-transportation");
var room = getFloatVal("#tb-room");
var other = getFloatVal("#tb-other");
var savings = getFloatVal("#tb-savings");
var expenses = tuition+books+transportation+room+other;
var needed = expenses - savings;

    $("#expense-total").html(Currency("$",expenses));
 /*   $("#borrow-total").html(Currency("$",needed)); */
if (needed > 0)	
    {  
          $("#borrow-total").html(Currency("$",needed));
	}
	else  
	{
		$("#borrow-total").html("$0");
	}




}

function checkForBlanks(){
    $("#calculator input").each(function(){
        if (trim($(this).val().replace("$", "").replace(",", "")) == ""){
            $(this).val("0.00");
            }
        });
}

function getFloatVal(ctrl){
return parseFloat($(ctrl).val().replace("$", "").replace(",", ""));
}
/************************ -------------------------- *******************************/
//REF CODE Functions
function checkForRefCode(){
    var q = getParameterByName("q");
    if(q != null && q != ""){
        eraseCookie("ccc_refCode");
        createCookie("ccc_refCode",q,14);
        appendRefCode();
    }   
}
//any <a> tag with a class of 'apply-link' will get the apply link + the ref code appended
function appendRefCode(){
    var code = readCookie("ccc_refCode");
    //clear codes first
        $(".apply-link").each(function(){
                if($(this).attr("href").indexOf("&referrer_link") > -1)
                {
                    newlink = $(this).attr("href").substr(0,$(this).attr("href").indexOf("&referrer_link="));
                    $(this).attr("href",newlink);
                }
        });
        
    if(code != null){
        var newlink;
        $(".apply-link").each(function(){
            newlink = $(this).attr("href")+"&referrer_link="+code;
            $(this).attr("href",newlink);
        });
    }
    else{
    //Append the organic code per domain
        var newlink;
        var code = "";
        var hostname = window.location.hostname.toLowerCase().replace(/^www\./i,'');
        switch (hostname){
            case "collegiatestudentloans.com":
            code = "CSLSITE";
            break;
            case "collegiatecustomchoice.com":
            code = "CCCSITE";
            break;
            case "collegiatechoiceloans.com":
            code = "CCLSITE";
            break;
            case "collegiatecustomchoiceloans.com":
            code = "CCCLSITE";
            break;
            case "localhost":
            code = "DEV";
            break;
            default:
            code = "ORGANIC";
            break;
        }
        $(".apply-link").each(function(){
            newlink = $(this).attr("href")+"&referrer_link="+code;
            $(this).attr("href",newlink);
        });
        
    }
}
/************************ -------------------------- *******************************/

// HTML Encode Functions
function encode(me) {
  return me.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};
function decode(me) {
  return me.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
};

function round(num){
  return Math.round(num*100)/100;
}
/************************ -------------------------- *******************************/
//Cookie Functions
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/************************ -------------------------- *******************************/
//helper function to trim whitespace
function trim(str) {
    if (str == null) return "";
    var newstr;
    newstr = str.replace(/^\s*/, "").replace(/\s*$/, "");
    newstr = newstr.replace(/\s{2,}/, " ");
    return newstr;
}
//helper function to return currency format
function Currency(sSymbol, vValue) {
    aDigits = vValue.toFixed(2).split(".");
    aDigits[0] = aDigits[0].split("").reverse().join("").replace(/(\d{3})(?=\d)/g, "$1,").split("").reverse().join("");
    return sSymbol + aDigits.join(".");
}
//helper function to reformat date to xx/xx/xxxx
function reformatDate(d){
    var tmpd = d.split('-');
    return tmpd[1]+"/"+tmpd[2]+"/"+tmpd[0];
}
//Retrieve a query string parameter
function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

