﻿// 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() };

//Global Rate Data
var VyrIMLow;
var VyrIMHigh;
var XyrIMLow;
var XyrIMHigh;

var thisMonthDate;
var thisMonthDate2;
var thisMonthDate3;
var thisMonthDate4;
var thisMonthDate5;

var variableDate;
var variableDate2;
var variableDate3;
var variableDate4;
var variableDate5;

var effectiveDate;
var effectiveDate2;
var effectiveDate3;
var effectiveDate4;
var effectiveDate5;


//process ref codes
$(document).ready(function () {
    checkForRefCode();
    appendRefCode();
});

/************************ -------------------------- *******************************/
//RATE DATA TABLE
function initRateData() {
    $("#table-loading").show();
    $("#repay-table").hide();

    $("#repay-term .config-btn span.five").click(function () { setRepayTerm('five'); });
    $("#repay-term .config-btn span.ten").click(function () { setRepayTerm('ten'); });
  
    $("#repay-type .config-btn span.immediate").click(function () { setRepayType('immediate'); });

	initRates();
}
function setRepayTerm(term) {
    $("#repay-term .config-btn").removeClass("active").addClass("inactive");
    $("#repay-term .config-btn span." + term).parent().removeClass("inactive").addClass("active");
    setTableData();
}
function setRepayType(type) {
    $("#repay-type .config-btn").removeClass("active").addClass("inactive");
    $("#repay-type .config-btn span." + type).parent().removeClass("inactive").addClass("active");
    setTableData();
}

function setTableData() {
    var term = $("#action-bar .col1 .active").find("span").attr("class");
    var type = $("#action-bar .col2 .active").find("span").attr("class");

    var low;
    var high;

    if (term == "five") {
        if (type == "immediate") {
            low = VyrIMLow; high = VyrIMHigh;
        }
    }
    if (term == "ten") {
        if (type == "immediate") {
            low = XyrIMLow; high = XyrIMHigh;
        }
     }

    buildRateTable(low, high);
}

function initRates(){

   var serviceURL = "http://"+window.location.hostname+"/RPX/RPXWebServiceImplService";
   //var serviceURL = "http://10.127.211.199/RPX/RPXWebServiceImplService"; // use to test on localhost
   //var serviceURL = "http://dev.unionfederalstudentloans.com/RPX/RPXWebServiceImplService"; // use to test on localhost
   getRatesJSON(serviceURL);

}

function getRatesJSON(serviceURL){
var url = serviceURL;
var linkID = "PRPGTEUF1";
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){ $("#table-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;



    for (var i = 0; i < JSON.rpxCalcRespDTOList.length; i++) {
        //IMMEDIATE
        if (JSON.rpxCalcRespDTOList[i].calcType == "IM") {
            //5 YEAR
            if (JSON.rpxCalcRespDTOList[i].monthsInRepayment == 60) {
                if (VyrIMLow == null) { VyrIMLow = JSON.rpxCalcRespDTOList[i]; } else { VyrIMHigh = JSON.rpxCalcRespDTOList[i]; }
            } 
            //10 YEAR
            if (JSON.rpxCalcRespDTOList[i].monthsInRepayment == 120) {
                if (XyrIMLow == null) { XyrIMLow = JSON.rpxCalcRespDTOList[i]; } else { XyrIMHigh = JSON.rpxCalcRespDTOList[i]; }
            }
		}
      
    }

    buildRateTable(XyrIMLow, XyrIMHigh);
	
	//Footnotes
	$("#libor-rate").text(JSON.commonPricingData.baseRate + "%");
	$("#margin-low").text(VyrIMLow.borrMarginRepay.toFixed(2) + "%");

	$("#apr-low").text(VyrIMLow.apr.toFixed(3) + "%");
	$("#apr-high").text(XyrIMHigh.apr.toFixed(3) + "%");
	
	$("#int-low").text(VyrIMLow.borrRepayIntRate.toFixed(3) + "%");
	$("#int-high").text(XyrIMHigh.borrRepayIntRate.toFixed(3) + "%");
	
	$("#im-pmt-low").text(VyrIMLow.monthlyPmtPostGrad).currency().prepend("$");
	$("#im-pmt-high").text(XyrIMHigh.monthlyPmtPostGrad).currency().prepend("$");
	
	$("#orig-fee-low").text(VyrIMLow.origFeePct.toFixed(3) + "%");
	$("#orig-fee-high").text(XyrIMHigh.origFeePct.toFixed(3) + "%");
	// Below 2 are used for the include orig_fee.htm footnote
	$("#inc-orig-fee-low").text(VyrIMLow.origFeePct.toFixed(3) + "%");
	$("#inc-orig-fee-high").text(XyrIMHigh.origFeePct.toFixed(3) + "%");
	// Below is the commonData return of the low orig fee
	$("#inc2-orig-fee-low").text(commonData.minOrigFeeForVariable + "%");
	
	
	$("#im-5yr-low-int").text(VyrIMLow.borrRepayIntRate.toFixed(3) + "%");
	$("#5yr-int-low").text(VyrIMLow.borrRepayIntRate.toFixed(3) + "%");
	$("#5yr-int-high").text(XyrIMHigh.borrRepayIntRate.toFixed(3) + "%");
	$("#im-5yr-int-high").text(XyrIMHigh.borrRepayIntRate.toFixed(3) + "%");
	//Rates for bullet items on the index.htm page of features-and-benefits
	//These rates are used in the footnotes so we need new instances of them for this page	
	 var lowRateWithoutLibor = (VyrIMLow.borrRepayIntRate.toFixed(3)  - JSON.commonPricingData.baseRate.toFixed(3));
	 $("#feature-int-low").text(lowRateWithoutLibor.toFixed(3) + "%");
	 var highRateWithoutLibor = (XyrIMHigh.borrRepayIntRate.toFixed(3)  - JSON.commonPricingData.baseRate.toFixed(3));		
	$("#feature-int-high").text(highRateWithoutLibor.toFixed(3) + "%");
	$("#feature-apr-low").text(VyrIMLow.apr.toFixed(3) + "%");
	$("#feature-apr-high").text(XyrIMHigh.apr.toFixed(3) + "%");
	$("#feature-orig-fee-low").text(commonData.minOrigFeeForVariable + "%");
	//Rate for minimum orig fee on the information about prepgate page
	$("#info-orig-fee-low").text(commonData.minOrigFeeForVariable + "%");
	//Rates and repayment page bulleted items 
	$("#rates-int-low").text(VyrIMLow.borrRepayIntRate.toFixed(3) + "%");
	$("#rates-apr-low").text(VyrIMLow.apr.toFixed(3) + "%");
	$("#rates-orig-fee-low").text(commonData.minOrigFeeForVariable + "%");
	
	
	
	//Footnote Effective Date
	//Ritacco - 110311 - Added effective date 2, 3 because if more than one effective date is used  
	//anywhere on the same page a new name had to be used.  Using the same var name gave the result
	//that the first occurence would be fine, then all occurences after that would show up blank.
	//I also needed to add in all these new names above in the VAR definition section.
	var today = new Date();
	variableDate = new Date(reformatDate(commonData.intRateEffectiveDateForVariable));
	thisMonthDate = new Date((today.getMonth()+1)+"/1/"+today.getFullYear());
	
	if(variableDate > thisMonthDate){effectiveDate = variableDate;}else{effectiveDate = thisMonthDate;}
	$("#effective-date").text((effectiveDate.getMonth()+1)+"/"+effectiveDate.getDate()+"/"+effectiveDate.getFullYear());
	
    var today2 = new Date();
	variableDate2 = new Date(reformatDate(commonData.intRateEffectiveDateForVariable));
	thisMonthDate2 = new Date((today2.getMonth()+1)+"/1/"+today2.getFullYear());

    if(variableDate2 > thisMonthDate2){effectiveDate2 = variableDate2;}else{effectiveDate2 = thisMonthDate2;}
	$("#effective-date2").text((effectiveDate2.getMonth()+1)+"/"+effectiveDate2.getDate()+"/"+effectiveDate2.getFullYear());
   
    var today3 = new Date();
	variableDate3 = new Date(reformatDate(commonData.intRateEffectiveDateForVariable));
	thisMonthDate3 = new Date((today3.getMonth()+1)+"/1/"+today3.getFullYear());

    if(variableDate3 > thisMonthDate3){effectiveDate3 = variableDate3;}else{effectiveDate3 = thisMonthDate3;}
	$("#effective-date3").text((effectiveDate3.getMonth()+1)+"/"+effectiveDate3.getDate()+"/"+effectiveDate3.getFullYear());	
    
	var today4 = new Date();
	variableDate4 = new Date(reformatDate(commonData.intRateEffectiveDateForVariable));
	thisMonthDate4 = new Date((today4.getMonth()+1)+"/1/"+today4.getFullYear());

    if(variableDate4 > thisMonthDate2){effectiveDate4 = variableDate4;}else{effectiveDate4 = thisMonthDate4;}
	$("#effective-date4").text((effectiveDate4.getMonth()+1)+"/"+effectiveDate4.getDate()+"/"+effectiveDate4.getFullYear());	

    var today5 = new Date();
	variableDate5 = new Date(reformatDate(commonData.intRateEffectiveDateForVariable));
	thisMonthDate5 = new Date((today5.getMonth()+1)+"/1/"+today5.getFullYear());

    if(variableDate5 > thisMonthDate5){effectiveDate5 = variableDate5;}else{effectiveDate5 = thisMonthDate5;}
	$("#effective-date5").text((effectiveDate5.getMonth()+1)+"/"+effectiveDate5.getDate()+"/"+effectiveDate5.getFullYear());	




    //Hide loader
    $("#table-loading").hide();
    //Show tables
    $("#repay-table").show();
    }

function buildRateTable(low, high) {
    $("#repay-table td.amt-low").text(low.disbSchedule[0].netDisbAmt + low.disbSchedule[1].netDisbAmt).currency().prepend("$");
    $("#repay-table td.amt-high").text(high.disbSchedule[0].netDisbAmt + high.disbSchedule[1].netDisbAmt).currency().prepend("$");
    $("#repay-table td.type-low").text(low.rateIndexCode == 'FIXED' ? 'Fixed' : 'Variable');
    $("#repay-table td.type-high").text(high.rateIndexCode == 'FIXED' ? 'Fixed' : 'Variable');
    $("#repay-table td.int-low").text(low.borrRepayIntRate.toFixed(3) + "%");
    $("#repay-table td.int-high").text(high.borrRepayIntRate.toFixed(3) + "%");
    $("#repay-table td.apr-low").text(low.apr.toFixed(3) + "%");
    $("#repay-table td.apr-high").text(high.apr.toFixed(3) + "%");
    $("#repay-table td.ofee-low").text(low.origFeeAmt).currency().prepend(low.origFeePct + "%<br />$");
    $("#repay-table td.ofee-high").text(high.origFeeAmt).currency().prepend(high.origFeePct + "%<br />$");
    $("#repay-table td.moPaySchool-low").text(low.monthlyPmtPreGrad).currency().prepend("$");
    $("#repay-table td.moPaySchool-high").text(high.monthlyPmtPreGrad).currency().prepend("$");
    $("#repay-table td.moPay-low").text(low.monthlyPmtPostGrad).currency().prepend("$");
    $("#repay-table td.moPay-high").text(high.monthlyPmtPostGrad).currency().prepend("$");
    $("#repay-table td.def-low").text(low.monthsInDeferment);
    $("#repay-table td.def-high").text(high.monthsInDeferment);
    $("#repay-table td.rep-low").text(low.monthsInRepayment);
    $("#repay-table td.rep-high").text(high.monthsInRepayment);
    $("#repay-table td.tot-low").text(low.totalPmtAmt).currency().prepend("$");
    $("#repay-table td.tot-high").text(high.totalPmtAmt).currency().prepend("$");
}


/************************ 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);
            }
    }
}
/*---------------------------------------------------------------------------------*/


/************************ -------------------------- *******************************/
//REF CODE Functions
function checkForRefCode() {
    var q = getParameterByName("q");
    if (q != null && q != "") {
        eraseCookie("prepG_refCode");
        createCookie("prepG_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("prepG_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) {
            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;
}
//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, " "));
}

//Determine the current page and set the nav arrow
function setNav() {
    var path = decode(window.location.pathname);

    if (path == "/features-and-benefits/") {
        $("#fb1").addClass("active");
    }
    if (path == "/features-and-benefits/why-prepgate.htm") {
        $("#fb2").addClass("active");
    }
    if (path == "/features-and-benefits/information-about-prepgate.htm") {
        $("#fb3").addClass("active");
    }
    if (path == "/features-and-benefits/before-applying.htm") {
        $("#fb4").addClass("active");
    }
    if (path == "/rates-and-repayment/") {
        $("#rp1").addClass("active");
    }
    if (path == "/rates-and-repayment/what-to-expect.htm") {
        $("#rp2").addClass("active");
    }
    if (path == "/faq/") {
        $("#f1").addClass("active");
    }
    if (path == "/faq/how-to-apply.htm") {
        $("#f2").addClass("active");
    }
}
function decode(str) {
    return unescape(str.replace(/\+/g, " "));
}
//helper function to reformat date to xx/xx/xxxx
function reformatDate(d){
    var tmpd = d.split('-');
    return tmpd[1]+"/"+tmpd[2]+"/"+tmpd[0];
}
//Determine the current page and set the nav arrow
function setNav() {
    var path = decode(window.location.pathname);

    if (path == "/features-and-benefits/") {
        $("#lifeatures-and-benefits").addClass("active");
    }
    if (path == "/features-and-benefits/why-union-federal.htm") {
        $("#liwhy-union-federal").addClass("active");
    }
    if (path == "/features-and-benefits/information-for-students.htm") {
        $("#liinformation-for-students").addClass("active");
    }
    if (path == "/features-and-benefits/before-applying.htm") {
        $("#libefore-applying").addClass("active");
    }
    if (path == "/rates-and-repayment/") {
        $("#lirates-and-repayment").addClass("active");
    }
    if (path == "/rates-and-repayment/repayment-options.htm") {
        $("#liwhat-to-expect").addClass("active");
    }
    if (path == "/frequently-asked-questions/") {
        $("#lifrequently-asked-questions").addClass("active");
    }
    if (path == "/frequently-asked-questions/how-to-apply.htm") {
        $("#lihow-to-apply").addClass("active");
    }
    if (path == "/frequently-asked-questions/financial-aid-help.htm") {
        $("#lifinancial-aid-help").addClass("active");
    }
}
function decode(str) {
    return unescape(str.replace(/\+/g, " "));
}
