﻿// JScript File common
//refresh the page
//--------------------------------------------
function refresh() {
    window.location.reload();
}

//function $get(control) {
//    return document.getElementById(control);
//}

//--------------------------------------------
//get querystring
function _esc(a) {
    return window.encodeURIComponent ? encodeURIComponent(a) : escape(a)
}

var aP = function(a) {
    return window.decodeURIComponent ? decodeURIComponent(a) : unescape(a)
}
; var _unesc = aP; //--------------------------------------------
function _hesc(a) { return a.replace(/</g, "&lt;").replace(/>/g, "&gt;") }
//--------------------------------------------
function aG() {
    var a = new Object(); var aa = document.location.search.substring(1); var ab = aa.split("&"); for (var ac = 0; ac < ab.length; ac++) { var ad = ab[ac].indexOf("="); if (ad == -1) continue; var ae = ab[ac].substring(0, ad); var af = ab[ac].substring(ad + 1); af = af.replace(/\+/g, " "); a[ae] = _unesc(af) } return a
}

// Parse the input to a given date. Assume that the date is US based
//--------------------------------------------
function ToDateString(sender, eventArgs) {
    var d = new Date(eventArgs.get_value());
    eventArgs.set_value(d.toFormattedString("M"));
}
// return the value of the radio button that is checked by getting an checkbox object, document.forms[0].l_propCouncil
//--------------------------------------------
function getCheckedValue(radioObj) {
    if (!radioObj) return "";
    var radioLength = radioObj.length;
    if (radioLength == undefined) if (radioObj.checked) return radioObj.value;
    else return "";
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

//Get radiobutton value for the Dynamic radio buttons
function getCheckedValueD(radioname) {
    radioObj = document.forms[0].elements[radioname];
    if (!radioObj)
        return "";
    var radioLength = radioObj.length;
    if (radioLength == undefined)
        if (radioObj.checked)
        return radioObj.value;
    else
        return "";
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

// sets the value of the radio button
//--------------------------------------------
function setCheckedValue(radioObj, value) {
    var radioLength = radioObj.length;
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].value + "" == value + "") {
            radioObj[i].checked = true;
        }
    }
}

// sets the value of Dynamic the radio button
//--------------------------------------------
function setCheckedValueD(radioname, value) {
    var radioObj = document.forms[0].elements[radioname];
    var radioLength = radioObj.length;
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].value + "" == value + "") {
            radioObj[i].checked = true;
        }
    }
}

//--------------------------------------------
function setCheckboxValue(checkboxName, value) {
    value = value + "";
    var ChkObj = document.forms[0].elements[checkboxName];
    ChkObj.checked = ((value == "true") ? true : false);
}

//Jump to the next field when the current field's maxlength has been reached
//--------------------------------------------
function checkLen(x, y) {
    if (y.length == x.maxLength) {
        var next = x.tabIndex
        if (next < $get("Form1").length) {
            $get("Form1").elements[next].focus()
        }
    }
}

//popup
var popUp;
var popUpIssues;
//--------------------------------------------
function SetControlValue(controlID, newDate, isPostBack) {
    popUp.close();
    document.forms[0].elements[controlID].value = newDate;
    __doPostBack(controlID, '');
}
//--------------------------------------------
function OpenPopupPage(pageUrl, controlID, isPostBack, size) {
    popUp = window.open(pageUrl + '&controlID=' + controlID + '&isPostBack=' + isPostBack, 'popupcal', size);
}

function OpenIssuesPage(pageUrl, controlID, isPostBack, size) {
    popUpIssues = window.open(pageUrl + '&controlID=' + controlID + '&isPostBack=' + isPostBack, 'popupcal', size);
}

//show tag (div, iframe) and hide all the others in default.aspx
//--------------------------------------------
function showAndHideTag(tagShow, tagHide) {
    var className = "ShowControl";
    if (tagHide != "") {
        var coll = document.all.tags("div");
        if (coll != null) {
            for (i = 0; i < coll.length; i++) {
                if (coll[i].id.indexOf(tagHide) == 0) coll[i].className = "HideControl";
            }
        }
        coll = document.all.tags("iframe");
        if (coll != null) {
            for (i = 0; i < coll.length; i++) {
                if (coll[i].id.indexOf(tagHide) == 0) coll[i].className = "HideControl";
            }
        }
    }
    if (tagShow != "") {
        var myArr = tagShow.split(",");
        var cnt = 0;
        while (cnt < myArr.length) {
            $get(myArr[cnt]).className = "ShowControl";
            cnt += 1;
        }
    }
}

//show iframe and hide all the others (div) in default.aspx
//--------------------------------------------
function showAndHideFrame(tagShow, frameSrc, tagHide) {
    var className = "ShowControl";
    if (tagHide != "") {
        var coll = document.all.tags("div");
        if (coll != null) {
            for (i = 0; i < coll.length; i++) {
                if (coll[i].id.indexOf(tagHide) == 0) coll[i].className = "HideControl";
            }
        }
    }
    if (tagShow != "") {
        $get(tagShow).src = frameSrc;
        $get(tagShow).className = "ShowControl";
    }
}
//reset query in default
//--------------------------------------------
function textBoxReset(textBoxNames) {
    var myArr = textBoxNames.split(",");
    var cnt = 0;
    while (cnt < myArr.length) {
        $get(myArr[cnt]).value = "";
        cnt += 1;
    }
}
//Hide Object by change style
//--------------------------------------------
function hideObject(nodeID) {
    var node = $get(nodeID);
    if (typeof node != "undefined") {
        node.style.visibility = "hidden";
        node.style.display = 'none';
    }
}
//cookie functions
//--------------------------------------------
function getCookie(sName) {
    var cookie = "" + document.cookie;
    var start = cookie.indexOf(sName);
    if (cookie == "" || start == -1) return "";
    var end = cookie.indexOf(';', start);
    if (end == -1) end = cookie.length;
    return unescape(cookie.substring(start + sName.length + 1, end));
}
//--------------------------------------------
function setCookie(sName, value) {
    document.cookie = sName + "=" + escape(value) + ";path=/;";
}
//--------------------------------------------
function setCookieForever(sName, value) {
    document.cookie = sName + "=" + escape(value) + ";path=/;expires=Fri, 1 Jan 2030 00:00:00 GMT;";
}
//show 2,3,4 applicant's form
//--------------------------------------------
function NextApp(Element, BasedElement) {
    if (BasedElement.checked) {
        if (Element != "") {
            var myArr = Element.split(",");
            var cnt = 0;
            while (cnt < myArr.length) {
                $get(myArr[cnt]).className = "ShowControl";
                cnt += 1;
            }
        }
    }
    else {
        if (Element != "") {
            var myArr = Element.split(",");
            var cnt = 0;
            while (cnt < myArr.length) {
                $get(myArr[cnt]).className = "HideControl";
                cnt += 1;
            }
        }
    }
}

//quick fix for the memory leak <body onunload="fixCircleRefs();"> 
//--------------------------------------------
function fixCircleRefs() {
    if (document.all) {
        var el;
        for (var d = document.all.length; d--; ) {
            el = document.all[d];
            for (var c = cearElementProps.length; c--; ) {
                el[cearElementProps[c]] = null;
            }
        }
    }
}
var cearElementProps = [
    'data',
    'onmouseover',
    'onmouseout',
    'onmousedown',
    'onmouseup',
    'ondblclick',
    'onclick',
    'onselectstart',
    'oncontextmenu'
];

//////////////////////////////////////////////////////////////
///////////////////////for loan
//select all the checkbox in datagrid
//--------------------------------------------
function SelectAll(chkVal, idVal) {
    var frm = document.forms[0];
    for (i = 0; i < frm.length; i++) {
        if (idVal.indexOf('chkSelAll') != -1) {
            if (chkVal == true) {
                frm.elements[i].checked = true;
            }
            else {
                frm.elements[i].checked = false;
            }
        }
        else if (idVal.indexOf('chkSend') != -1) {
            if (frm.elements[i].checked == false) {
                frm.elements[1].checked = false;
            }
        }
    }
}

//show advanced option in default.aspx
//--------------------------------------------
function showOption(spanName, pnlNames) {
    var className = "ShowControl";
    if ($get(spanName).innerHTML == "Show search options") {
        $get(spanName).innerHTML = "Simple";
        className = "ShowControl";
        $get("main_old").className = className;
    }
    else {
        $get(spanName).innerHTML = "Show search options";
        className = "HideControl";
    }
    var myArr = pnlNames.split(",");
    var cnt = 0;
    while (cnt < myArr.length) {
        $get(myArr[cnt]).className = className;
        cnt += 1;
    }
}

//--------------------------------------------
//Pass a date string and the function returns Date Value in formet: dd/mm/yyyy
function getDateValue(strDate, strFormat) {
    var strResult = "";

    if (strDate != "" && strDate != null) {
        var D = new Date(strDate);
        var strYear = D.getFullYear();
        var strMonth = ((D.getMonth()) * 1 + 1) + "";
        var strDay = D.getDate() + "";
        if (strMonth.length == 1) strMonth = "0" + strMonth;
        if (strDay.length == 1) strDay = "0" + strDay;

        switch (strFormat) {
            case "ddmmyyyy":
                strResult = strDay + "/" + strMonth + "/" + strYear;
                break;
            case "mmddyyyy":
                strResult = strMonth + "/" + strDay + "/" + strYear;
                break;
            case "yyyymmdd":
                strResult = strYear + "/" + strMonth + "/" + strDay;
                break;
            case "UTC":
                strResult = D.toUTCString();
                break;
            case "LocaleString":
                strResult = D.toLocaleString();
                break;
            default:
                strResult = strDay + "/" + strMonth + "/" + strYear;
                break;
        }
    }
    else {
        strResult = "";
    }
    return strResult;
}
//Hide and Show a Panel
//The clas is initialized like this:
//var dHandler = new DisplayHander($get("showAddTaskButton"), $get("divAddTask"), 'Hide Panel', 'Show Panel', 'Add');
//It requires 2 Css classes that change the look of the button control
//the Cssclasses Name show consist of a prefix and '_Hide' or '_Show'
/*Example
<a class="Add_Show" id="showAddTaskButton" onclick="dHandler.Cycle()">Show Add</a>
<div id="divAddTask" style="border-top: solid 1px black; border-bottom: solid 1px black; width: 90%; display: none">
button Control,panel to show or hide,Text displayed when the panel is hidden,opposite of hidetext, Cssclass prefix*/
function DisplayHander(ctrl1, ctrl2, hideText, showText, classPrefix) {
    this.button = ctrl1;
    this.panel = ctrl2;
    this.HideText = hideText;
    this.ShowText = showText;
    this.ClassPrefix = classPrefix;


    this.Cycle = function() {
        if (this.panel.style.display == 'none') {
            this.panel.style.display = '';
            this.button.innerText = this.HideText;
            this.button.className = this.ClassPrefix + '_Hide';

        }
        else {
            this.panel.style.display = 'none';
            this.button.innerText = this.ShowText;
            this.button.className = this.ClassPrefix + '_Show';
        }
    };

    this.ShowPanel = function() {
        this.panel.style.display = '';
        this.button.innerText = this.HideText;
        this.button.className = this.ClassPrefix + '_Hide';
    };

    this.HidePanel = function() {
        this.panel.style.display = 'none';
        this.button.innerText = this.ShowText;
        this.button.className = this.ClassPrefix + '_Show';
    };
};

//Validation Functions
function onlyNumeric() {
    if ((event.keyCode < 48) || (event.keyCode > 57)) event.returnValue = false;
}
//-----------------------------------

function onlyMoney() {
    if ((event.keyCode < 48 && event.keyCode != 46) || (event.keyCode > 57)) event.returnValue = false;
}
//-----------------------------------

function onlyDate() {
    if ((event.keyCode < 48 && event.keyCode != 47) || (event.keyCode > 57)) event.returnValue = false;
}
//-----------------------------------

function onlyAlphabetic() {
    if ((event.keyCode == 32) || (event.keyCode > 64 && event.keyCode < 91) || (event.keyCode > 96 && event.keyCode < 123) || (event.keyCode == 45)) event.returnValue = true;
    else event.returnValue = false;
}
//-----------------------------------

function onlyTel() {
    if (!((event.keyCode < 48) || (event.keyCode > 57)) || (event.keyCode == 32)) event.returnValue = true;
    else event.returnValue = false;
}
//-----------------------------------

function intOnKeyUp(ctrl) {
    if (!isFinite($get(ctrl).value)) {
        $get(ctrl).value = "";
        $get(ctrl).focus();
    }
}
//-----------------------------------

function moneyOnKeyUp(ctrl) {
    if (!isFinite($get(ctrl).value) && ($get(ctrl).value != '.')) {
        $get(ctrl).value = "";
        $get(ctrl).focus();
    }
}
//-----------------------------------

function DateOnKeyUp(ctrl) {
    if (event.keyCode != 8) {
        switch ($get(ctrl).value.length) {
            case 2: $get(ctrl).value += "/"; break;
            case 5: $get(ctrl).value += "/"; break;
        }
    }
}
//-----------------------------------

function Trim(StrValue) {
    var st = StrValue;
    while ((st.length > 0) && (st.charAt(0) == " "))
        st = st.substring(1, st.length);
    while ((st.length > 0) && (st.charAt(st.length - 1) == " "))
        st = st.substring(0, st.length - 1);
    return st;
}
//-----------------------------------

function blnCheckEmail(pstrEmail) {
    var k, intFirstAtSignPos, intFirstDotPos, strLastDomainInAddress
    var strValidChar = new String("abcdefghijklmnopqrstuvwxyz1234567890-_.@");
    pstrEmail = Trim(pstrEmail);
    for (k = 0; k <= pstrEmail.length; k++)
        if (strValidChar.indexOf((pstrEmail.substr(k, 1)).toLowerCase()) == -1) return false;
    if (pstrEmail.indexOf("..") >= 0) return false;
    intFirstAtSignPos = pstrEmail.indexOf("@")
    if (intFirstAtSignPos < 1) return false;
    if (pstrEmail.indexOf("@", (intFirstAtSignPos + 1)) >= 0) return false;
    intFirstDotPos = pstrEmail.indexOf(".")
    if (intFirstDotPos < 0) return false;
    if (pstrEmail.indexOf("_", intFirstAtSignPos) != -1) return false;
    strLastDomainInAddress = pstrEmail.substr((pstrEmail.lastIndexOf(".") + 1))
    if (strLastDomainInAddress.length < 2 || strLastDomainInAddress.length > 4) return false;
    return true;
}
//-----------------------------------

function CheckDate(ctrl) {
    if ($get(ctrl).value.length == 10) {
        var strDate = $get(ctrl).value;
        var day = strDate.substring(0, 2);
        var month = strDate.substring(3, 5);
        var year = strDate.substring(6, 10);

        if (day * 1 > 31 || day * 1 < 1 || (day * 1 == 31 && (month * 1 == 2 || month * 1 == 4 || month * 1 == 6 || month * 1 == 9 || month * 1 == 11))) {
            return false;
        }
        else if (month * 1 > 12 || month * 1 < 1) {
            return false;
        }
        else if (year * 1 < 1900) {
            return false;
        }
        else {
            return true;
        }
    }
    else {
        return false;
    }
}

//-----------------------------------
var one_day = 1000 * 60 * 60 * 24;
var one_month = 1000 * 60 * 60 * 24 * 30;
var one_year = 1000 * 60 * 60 * 24 * 30 * 12;

function GetAge(yr, mon, day, countunit, decimals, rounding) {
    var Age;

    today = new Date();
    var pastdate = new Date(yr, mon - 1, day);

    finalunit = (countunit == "days") ? one_day : (countunit == "months") ? one_month : one_year;
    decimals = (decimals <= 0) ? 1 : decimals * 10;

    if (countunit != "years") {
        if (rounding == "rounddown")
            Age = Math.floor((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals;
        else
            Age = Math.ceil((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals;
    }
    else {
        yearspast = today.getFullYear() - yr - 1
        tail = (today.getMonth() > mon - 1 || today.getMonth() == mon - 1 && today.getDate() >= day) ? 1 : 0
        pastdate.setFullYear(today.getFullYear())
        pastdate2 = new Date(today.getFullYear() - 1, mon - 1, day)
        tail = (tail == 1) ? tail + Math.floor((today.getTime() - pastdate.getTime()) / (finalunit) * decimals) / decimals : Math.floor((today.getTime() - pastdate2.getTime()) / (finalunit) * decimals) / decimals
        Age = yearspast + tail;
    }

    return Age;
}

//-----------------------------------
function CalculateDate(years, months) {
    if (years == "" || years == null) years = 0;
    if (months == "" || months == null) months = 0;
    var totalmonths = years * 12 + months * 1;

    years = Math.floor(totalmonths / 12);
    months = totalmonths % 12;
    var strDate = "";
    today = new Date();

    var currY = today.getFullYear();
    var currM = today.getMonth() + 1;
    var currD = today.getDate();

    var finalY = 0, finalM = 0, finalD;
    finalD = currD;

    finalY = currY * 1 - years * 1;
    finalM = currM * 1 - months * 1;

    if (finalM <= 0) {
        finalY = finalY - 1;
        finalM = 12 - (months * 1 - currM * 1);
    }
    if (finalM == 0) finalM = 1;

    switch (finalM) {
        case 2: if (finalD > 28) finalD = 1; finalM += 1; break;
        case 4: if (finalD > 30) finalD = 1; finalM += 1; break;
        case 6: if (finalD > 30) finalD = 1; finalM += 1; break;
        case 9: if (finalD > 30) finalD = 1; finalM += 1; break;
        case 11: if (finalD > 30) finalD = 1; finalM += 1; break;
    }
    strDate = finalD + "/" + finalM + "/" + finalY;

    return strDate;
}

//-----------------------------------

//Hide and show the overlay. The document must contain a div with id=overlay and class=overlay
//El1 is optional and it is used to center the control this is in the overlay
function ShowOverLay(elName, el1Name) {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    }
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    }
    else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    if (elName)
        el = document.getElementById(elName);
    else
        el = document.getElementById("overlay");
    el.style.width = myWidth;
    el.style.height = 1500;

    if (el1Name) {
        try {
            var el1 = document.getElementById(el1Name);
            //		alert(myHeight);
            //		alert(el1.style.height);
            var el1Height = el1.clientWidth;
            el1.style.paddingTop = (myHeight - el1Height) / 2;
        }
        catch (e) {

        }
    }
    el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}

function FixIEPNG() {
    var arVersion = navigator.appVersion.split("MSIE")
    var version = parseFloat(arVersion[1])

    if ((version >= 5.5) && (document.body.filters)) {
        for (var i = 0; i < document.images.length; i++) {
            var img = document.images[i]
            var imgName = img.src.toUpperCase()
            if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
                var imgID = (img.id) ? "id='" + img.id + "' " : ""
                var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                var imgStyle = "display:inline-block;" + img.style.cssText
                if (img.align == "left") imgStyle = "float:left;" + imgStyle
                if (img.align == "right") imgStyle = "float:right;" + imgStyle
                if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                var strNewHTML = "<span " + imgID + imgClass + imgTitle
			 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
                img.outerHTML = strNewHTML
                i = i - 1
            }
        }
    }
}


function ModuleHideShow(ctrl1, ctrl2) {
    if ($get(ctrl1) && $get(ctrl2)) {
        if ($get(ctrl1).className == 'module collapsed') {
            $get(ctrl1).className = 'module expanded';
        }
        else {
            $get(ctrl1).className = 'module collapsed';
        }

        if ($get(ctrl2).style.display == 'none') {
            $get(ctrl2).style.display = '';
        }
        else {
            $get(ctrl2).style.display = 'none';
        }
    }
}

function Mid(str, start, len) {
    /***
    start - our string's starting position (0 based!!)
    len - how many characters from start we want to get

    RETVAL: The substring from start to start+len
    ***/
    if (start < 0 || len < 0) return "";

    var iEnd, iLen = String(str).length;
    if (start + len > iLen)
        iEnd = iLen;
    else
        iEnd = start + len;

    return String(str).substring(start, iEnd);
}

function GetDebtHistory(debtHistory, ArrLast3, ArrLast12) {
    if (debtHistory == "") debtHistory = "000000000000";
    if (ArrLast3 == "") ArrLast3 = "0";
    if (ArrLast12 == "") ArrLast12 = "0";
    var numLast3 = ArrLast3 * 1;
    var numLast12 = ArrLast12 * 1;
    if (numLast12 < numLast3)
        numLast12 = numLast3;

    var History = debtHistory;
    numLast12 = numLast12 - numLast3;

    for (var i = 1; i <= numLast12; i++) {
        History = ReplaceChar(History, 12 - i, i);
    }
    for (var i = 1; i <= numLast3; i++) {
        History = ReplaceChar(History, i - 1, i);
    }

    return History;
}

function GetDebtHistoryOLD(debtHistory, currArr, PastArr) {
    if (debtHistory == "") debtHistory = "000000000000";
    var strHisP1 = "", strHisP2 = "";
    var HasPastArr = false;

    if (currArr != "") {
        strHisP2 = Mid(debtHistory, currArr * 1, (12 - currArr * 1));
        debtHistory = "";
        for (var i = 0; i < currArr * 1; i++) {
            debtHistory += (currArr * 1 - i) + "";
        }
        debtHistory += strHisP2;
    }
    if (PastArr != "") {
        if (currArr != "") {
            if (PastArr * 1 > currArr * 1)
                HasPastArr = true;
            else
                HasPastArr = false;
        }
    }

    if (HasPastArr) {
        var Minus = PastArr * 1 - currArr * 1;
        strHisP1 = Mid(debtHistory, (12 - Minus), Minus);

        debtHistory = Mid(debtHistory, 0, (12 - Minus));
        for (var i = 0; i < Minus * 1; i++) {
            debtHistory += "1";
        }
    }

    return debtHistory;
}
//-----------------------------------

function displayurl(urltxt) {
    if (urltxt == '*') {
        BarToolTip.style.visibility = 'hidden';
    }
    else {
        BarToolTip.innerHTML = urltxt;
        BarToolTip.style.left = event.x - 10 + document.body.scrollLeft;
        BarToolTip.style.top = event.clientY + 10 + document.body.scrollTop;
        BarToolTip.style.visibility = '';
    }
}
//-----------------------------------

function CheckTelNo(pstrTelNo) {
    pstrTelNo = Trim(pstrTelNo);
    if (pstrTelNo.length < 10) {
        return false;
    }
    else if (pstrTelNo.length >= 4) {
        if (pstrTelNo.substring(0, 4) == "0704" || pstrTelNo.substring(0, 1) != "0")
            return false;
        else
            return true;
    }
    else {
        return true;
    }
}
//-----------------------------------

function MakeCapital(ctrl) {
    var strVal = $get(ctrl).value;
    if (strVal.length > 0) {
        strVal = Mid(strVal, 0, 1).toUpperCase() + Mid(strVal, 1, strVal.length);
    }
    $get(ctrl).value = strVal;

    return strVal;
}
//-----------------------------------

function ReplaceChar(pstrString, index, pstrReplaceText) {
    var strText = "";
    for (var k = 0; k < pstrString.length; k++) {
        if (k == index)
            strText += pstrReplaceText;
        else
            strText += pstrString.charAt(k);
    }
    //pstrString = pstrString.replace(pstrString.charAt(index),pstrReplaceText)
    pstrString = strText;
    return pstrString;
}
//-----------------------------------

function IsNumeric(strString) {
    var strValidChars = "0123456789.-";
    var strChar;
    var blnResult = true;

    if (strString.length == 0) return false;
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}
//-----------------------------------

function Debug(_isDebug) {
    var isDebug = _isDebug;

    this.OnError = function(error) {
        if (isDebug)
            alert("ErrorMessage: " + error.get_message() + "\n Stack Trace: " + error.get_stackTrace() + "\nError Type : " + error.get_exceptionType());
        else
            alert("There was a server error. The system may not work correctly. Try refreshing the page");
    }

    this.OnTimeOut = function(msg) {
        if (isDebug)
            alert(msg.get_message());
        else
            alert("Operation timed out. Please try again.");
    }

    this.DummyComplete = function() {

    }
}

var Debugger = new Debug(true);

//Calculate Apr and helper functions
function roundOff(value, precision) {
    if (value.substring(0, 1) == 0) {
        result = value;
    }
    else {
        value = "" + value //convert value to string
        precision = parseInt(precision);
        var whole = "" + Math.round(value * Math.pow(10, precision));
        var decPoint = whole.length - precision;
        if (decPoint != 0) {
            result = whole.substring(0, decPoint);
            result += ".";
            result += whole.substring(decPoint, whole.length);
        }
        else {
            result = whole;
        }
    }
    return result;
}

function OnlyCalcPayment(loanMonthlyRate, loanTerm, loanAmount) {
    //debugger;
    var lPay;
    var MIR = loanMonthlyRate / 100;
    var OneplusMIRTerm = Math.pow((1 + MIR), loanTerm);
    var TotalRepayment = loanAmount * loanTerm * MIR * OneplusMIRTerm / ((OneplusMIRTerm) - 1);
    lPay = TotalRepayment / loanTerm;
    //alert(TotalRepayment);
    MIR = OneplusMIRTerm = TotalRepayment = null;
    return lPay;
}

function GetCompletionFees(lenderId, Amount, loanName, hasDiscount, countryID) {
    var fees = 0;
    switch (lenderId) {
        case "com1":
            break;
        case "com2":
            break;
        case "com3":
            break;
            break;
        case "com4":
            if (Amount >= 25500)
                fees = 595;
            else
                fees = 250;
            break;
        case "com5":
            if (Amount < 30000) {
                fees = 0.025 * Amount;
                if (fees < 150)
                    fees = 150;
                if (fees > 395)
                    fees = 395;
            }
            else if (Amount >= 30000 && Amount < 50000) {
                fees = 595;
            }
            else if (Amount >= 50000 && Amount < 100000) {
                fees = 795;
            }
            else if (Amount >= 100000) {
                fees = 995;
            }
            break;

        case "com6":


            if (Amount >= 30000 && Amount <= 50000) {
                fees = 595;
            }

            else if (Amount > 50000 && Amount <= 100000) {
                fees = 795;
            }

            else if (Amount > 100000) {
                fees = 995;
            }


            else if (Amount < 30000) {
                if ((countryID == 4) || (countryID == 3)) {
                    fees = 395;
                }

                else {
                    var temp_fee = (Amount * 1 / 40);    //2.5%
                    if (temp_fee < 150) {
                        fees = 150;
                    }

                    else if (temp_fee > 395) {
                        fees = 395;
                    }

                    else {
                        fees = temp_fee;
                    }
                }
            }

            break;

        case "com7":
            if (Amount > 25000)
                fees = 250;
            else
                fees = 150;
            break;
        case "com8":
            if (Amount > 25000)
                fees = 500;
            else
                fees = 250;
            break;
        case "com9":
            if (Amount > 25000)
                fees = 499;
            else
                fees = 250;
            break;
        case "com10":

            break;
        case "com11":
            if ((loanName.indexOf("Prime A1") != -1) || (loanName.indexOf("Prime A2") != -1) || (loanName.indexOf("Prime A3") != -1) ||
					(loanName.indexOf("Prime A4") != -1) || (loanName.indexOf("Mild B1") != -1) || (loanName.indexOf("Mild B2") != -1) ||
					(loanName.indexOf("Mild B3") != -1)) {
                fees = 295;
            }
            else if ((loanName.indexOf("Medium C1") != -1) || (loanName.indexOf("Medium C2") != -1) || (loanName.indexOf("Medium C3") != -1) ||
						(loanName.indexOf("Heavy D1") != -1) || (loanName.indexOf("Heavy D2") != -1)) {
                fees = 495;
            }
            else if ((loanName.indexOf("Prime RA1") != -1) || (loanName.indexOf("Prime RA2") != -1) || (loanName.indexOf("Prime RA3") != -1) ||
				  (loanName.indexOf("Prime RA4") != -1) || (loanName.indexOf("Mild RB1") != -1) || (loanName.indexOf("Mild RB3") != -1) ||
				  (loanName.indexOf("Medium RC1") != -1) || (loanName.indexOf("Medium RC2") != -1) || (loanName.indexOf("Medium RC3") != -1)) {
                fees = 400;
            }
            else {
                fees = 595;
            }
            break;
    }
    return fees;
}

function calculateapr(comId, Term, Amount, BrokerFee, AccFee, MonthlyRep, Rate) {
    var loanamount, a, loanamount1;
    var monthlyrate;
    var term = Term, term1, term9;
    var a4;
    var repayment1 = 0.00;
    var apr, apr1, mapr;
    var firstq, firstq1, firstq2, firstq3 = 0.00, firstq4 = 0.00, qterm, qterm1, advance, defterm, defint, totalloan1;
    var secondq, secondq1, secondq2, secondq3 = 0.00, secondq4 = 0.00, hterm, hterm1;
    var thirdq, thirdq1, thirdq2, thirdq3 = 0.00, thirdq4 = 0.00, tqterm, tqterm1, Q1, Q2, Q3;
    var totalloan = Amount + BrokerFee + AccFee;
    var docfee = 0.00;
    var netpresentvalue = 0;
    var totalnpv = 0;
    var pymt = 0;
    var totalderiv = 0;
    var diff;
    var currentapr = 1.00;
    var prevapr = 0.00;
    var repayment = 0.00;
    var iorepayment = 0.00;
    if (!MonthlyRep) {
        MonthlyRep = OnlyCalcPayment(Rate, Term, Amount + BrokerFee + AccFee);
    }
    //if (comId != "com2")
    {
        //test figures variable
        var rate = 1.001;
        var ppp = 0;
        var productdesc = "NONE";

        advance = Amount + BrokerFee + AccFee;
        repayment = MonthlyRep;
        loanamount = advance;
        loanamount1 = Amount;
        monthlyrate = Rate; //1.5;
        iorepayment = 0;

        while (currentapr != prevapr) {
            repayment1 = repayment;
            prevapr = apr;

            apr = (rate - 1) * 100;
            apr1 = apr;

            apr = parseFloat(apr.toFixed(1));
            currentapr = apr;
            //calculate netpresent value for each month of the term
            //month 1 will always include the document fee
            for (var i = 1; i <= term; i++) {
                if (i == 1) {
                    pymt = repayment1;
                }
                else {
                    pymt = repayment1;
                }
                netpresentvalue = pymt * (Math.pow((rate), (0 - (i / 12))));
                totalnpv = totalnpv + netpresentvalue;
                derivative = (pymt / (Math.pow(Math.pow(rate, (i / 12)), 2)) * (i / 12) * (Math.pow(rate, (i / 12) - 1)))
                totalderiv = totalderiv + derivative;
            }

            switch (totalnpv) {
                case 0:
                    rate = rate;
                    break;
                default:
                    diff = parseFloat(totalnpv - loanamount1);
                    rate = rate + (diff / totalderiv);
            }

            totalnpv = 0;
            totalderiv = 0;
        }
        return parseFloat(roundOff(apr.toFixed(2), 2));
    }
    //else
    {
        //return CalcAPRParagon(comId, Term, Amount, BrokerFee, AccFee, MonthlyRep, Rate);
    }
}

function CalcAPRParagon(comId, Term, Amount, BrokerFee, AccFee, MonthlyRep, Rate) {
    //Amount = Amount + PPPAmount;
    //MonthlyRep = 240.90;
    var loGuess, guess, hiGuess;
    var loNPV, guessNPV, hiNPV, gradient, initialSum = 0;
    var keepGoing = true;
    var count = 0;
    var cashflows = new Array(Term + 1)
    var monthlyNo = Rate / 100;
    for (var i = 0; i <= Term; i++) {
        cashflows[i] = ((i == 0) ? Amount : MonthlyRep * -1);
    }

    for (var i = 0; i < cashflows.length; i++) {
        initialSum += cashflows[i];
    }
    if ((initialSum * cashflows[0]) > 0) {
        guess = 0;
    }
    else {
        guess = 0;
        while (keepGoing) {
            loGuess = guess - Math.pow(10, -4);
            hiGuess = guess + Math.pow(10, -4);
            guessNPV = calculateNetPresentValue(cashflows, guess);
            loNPV = calculateNetPresentValue(cashflows, loGuess);
            hiNPV = calculateNetPresentValue(cashflows, hiGuess);

            if (((Math.abs(guessNPV) < Math.abs(loNPV)) && (Math.abs(guessNPV) < Math.abs(hiNPV))) || (count > 50)) {
                keepGoing = false;
                guess = (Math.pow(1 + guess / 1200, 12) - 1) * 100;
            }
            else {
                gradient = (hiNPV - loNPV) / (hiGuess - loGuess);
                guess = (gradient * guess - guessNPV) / gradient;
                count++;
            }
        }
    }

    return parseFloat(roundOff(guess.toFixed(2), 1));
}

function calculateNetPresentValue(cashflows, rate) {
    var npv = 0;
    var numberMonths = cashflows.length - 1;

    for (var mthnum = 0; mthnum <= numberMonths; mthnum++) {
        npv += cashflows[mthnum] / Math.pow((1 + rate / 1200), mthnum);
    }
    return npv;
}
//---------------

function replaceIt(sString, sReplaceThis, sWithThis) {
    if (sReplaceThis != "" && sReplaceThis != sWithThis) {
        var counter = 0;
        var start = 0;
        var before = "";
        var after = "";
        while (counter < sString.length) {
            start = sString.indexOf(sReplaceThis, counter);
            if (start == -1) {
                break;
            }
            else {
                before = sString.substr(0, start);
                after = sString.substr(start + sReplaceThis.length, sString.length);
                sString = before + sWithThis + after;
                counter = before.length + sWithThis.length;
            }
        }
    }
    return sString;
}
//---------------
