﻿var arrLTVMax = new Array();
arrLTVMax[1] = 85; //R
arrLTVMax[2] = 85; //BTL
arrLTVMax[3] = 85; //P
arrLTVMax[4] = 85; //FTB
arrLTVMax[5] = 85; //SCRem
arrLTVMax[6] = 85; //SCOth
arrLTVMax[7] = 85; //AdvRem
arrLTVMax[8] = 85; //AdvOther

function FormatMoneyColon(val) {
    c = '';
    val = val + '';

    a = val.split('.');
    b = a[0];

    if (a.length > 1) {
        c = '.' + a[1];
    }

    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(b)) {
        b = b.replace(rgx, '$1' + ',' + '$2');
    }

    return b + c;
}

function FormatMoney(obj) {
    var strVal = obj.value.replace(/,/g, "").replace(/£/g, "");

    if (strVal != "") {

        if (!isNaN(Number(strVal))) {

            obj.value = "£" + FormatMoneyColon(Number(strVal));
        }
    }
}

function ValidateFormBrokerSearch(controlPrefix) {

    if (!ValidateLTV(controlPrefix)) {
        return false;
    }

    if (!(ValidateUKPostcode(document.getElementById(controlPrefix + "_txtPostcode").value.trim()))) {
        return false;
    }

    if (document.getElementById(controlPrefix + "_ddlMortgageType").value.trim() == '') {
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtRequiredMortgage").value.trim() == '') {
        return false;
    }

    if (document.getElementById(controlPrefix + "_txtValueOfProperty").value.trim() == '') {
        return false;
    }    

    return true;
}

function ValidateLTV(controlPrefix) {
    var MaxLTV = arrLTVMax[GetMortgageType(controlPrefix)];
    var ltv = ((parseFloat(document.getElementById(controlPrefix + "_txtRequiredMortgage").value.replace(/[^0-9.]*/g, ""), 10) / parseFloat(document.getElementById(controlPrefix + "_txtValueOfProperty").value.replace(/[^0-9.]*/g, ""), 10)) * 100.0);

    //alert(ltv + ' > ' + MaxLTV);

    if (ltv > MaxLTV) {

        return false;
    }

    return true;
}


//sam
function ShowLTV() {
    var controlPrefix = 'ctl00_ctl00_cphCont2_ContentPlaceHolder2_MortgageForm1';
    var MaxLTV = '85'; //  arrLTVMax[GetMortgageType(controlPrefix)];
    var ltv = ((parseFloat(document.getElementById(controlPrefix + "_txtRequiredMortgage").value.replace(/[^0-9.]*/g, ""), 10) / parseFloat(document.getElementById(controlPrefix + "_txtValueOfProperty").value.replace(/[^0-9.]*/g, ""), 10)) * 100.0);


    if (ltv > '75'  && ltv < MaxLTV) {

        document.getElementById("divShowLtvInfo").style.display = "block";
        return true;
    }

    document.getElementById("divShowLtvInfo").style.display = "none";
    return false;
}

function divClose() {
    document.getElementById("divShowLtvInfo").style.display = "none";
}

function ValidateUKPostcode(p) {
    var postcodeRegEx = /[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}/i;

    return postcodeRegEx.test(p);
}

function DoOnChange(controlPrefix, ipAddress) {
       
    if (ValidateFormBrokerSearch(controlPrefix)) {        

        xmlHttp = GetXmlHttpObject();

        if (xmlHttp == null) {
            alert("Your browser does not support AJAX!");
            return;
        }

        // ======================= build a URL with QueryString =========================================
        var url = "/Common/BrokerRequest.aspx";
        var queryString = "";

        queryString += "?Type=Mortgage";        
        queryString += "&mortgageType=" + jQuery("[id$=ddlMortgageType]").val();
        queryString += "&mortageAmount=" + jQuery("input[id$=txtRequiredMortgage]").val();
        queryString += "&propertyValue=" + jQuery("input[id$=txtValueOfProperty]").val();             
        queryString += "&firstTimeBuyer=" + YN_to_10(jQuery("input[name$=rblFirstTimeBuyer]:checked").val());
        queryString += "&selfCertified=" + YN_to_10(jQuery("input[name$=rblSelfCertify]:checked").val());

        if (IsBadCredit())
        { queryString += "&badCreditRating=1"; }
        else
        { queryString += "&badCreditRating=0"; }

        queryString += "&postCode=" + jQuery("input[id$=txtPostcode]").val();
        queryString += "&ipAddress=" + ipAddress;
        queryString += "&affiliateId=" + jQuery("input[id$=hidAffiliateId]").val();

        url = url + queryString;

        // ======================= END build a URL with QueryString =====================================

        //alert(url);

        // make an async call
        xmlHttp.onreadystatechange = stateChanged;
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
    }
}

function YN_to_10(input) {
    if (input == 'Y')
        return '1';
    if (input == 'N')
        return '0';

    return '0';
}

//============================= creates XmlHttp object for different browsers ==================================================
function GetXmlHttpObject() {
    var xmlHttp = null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

//========================== The stateChanged() function executes every time the state of the XMLHTTP object changes.==============
function stateChanged() {
    /* ============ XML structure ====================
    <root>
    <strErrorCode>num</strErrorCode>" +
    <strErrorMessage>string</strErrorMessage>" +
    <strSessionId>string</strSessionId>" +
    <strDisplayText>string</strDisplayText>" +
    <strLeadPrice>num<strLeadPrice>
    </root>      
    ============ END XML structure ================= */
    //alert("Hello");

    // if a response has been received from the server
    if (xmlHttp.readyState == 4) {
        if (window.ActiveXObject) {
            var doc = new ActiveXObject("Microsoft.XMLDOM");
            doc.async = "false";
            doc.loadXML(xmlHttp.responseText);
        }
        // code for Mozilla, Firefox, Opera, etc.
        else {
            var parser = new DOMParser();
            var textXml = xmlHttp.responseText;
            var doc = parser.parseFromString(textXml, "text/xml");
        }

        // documentElement always represents the root node  
        var xmlDoc = doc.documentElement;

        //check the errocode xml node
        if (xmlDoc.childNodes[0].childNodes[0].nodeValue == "0") {
            // display success message
            document.getElementById("brokerText").innerHTML = "Based on your requirements we have selected the FSA regulated broker to help you with your enquiry. <strong>" + xmlDoc.childNodes[3].childNodes[0].nodeValue + "</strong> Click 'Compare Now' to confirm that you are happy to be contacted by telephone or email regarding your mortgage policy.";

            if (xmlDoc.childNodes[3].childNodes[0].nodeValue.toString().indexOf("Ocean Finance") != -1) {
            
                document.getElementById("brokerText").innerHTML += "<br ><br />Arranging a mortgage and giving you individual advice from a fully qualified mortgage adviser will normally require the payment of a fee.  However this will only be payable if you accept the mortgage offer and it completes. Furthermore you will be provided with a FREE no obligation quotation before you decide to proceed, by our mortgage partner Ocean.  If you have any questions on this please call 0800 916 9143."
            }

            document.getElementById("divResult").style.display = "block";
            document.getElementById("hidBrokerGuid").value = xmlDoc.childNodes[5].childNodes[0].nodeValue;
        }
        else {
            // display error message
            //document.getElementById("brokerText").innerHTML          = "There has been a problem trying to find an FSA regulated broker to pass on your mortgage details.";
            document.getElementById("brokerText").innerHTML = "There has been a problem trying to find an FSA regulated broker: "
                + xmlDoc.childNodes[1].childNodes[0].nodeValue;
            document.getElementById("divResult").style.display = "block";
            //document.getElementById("hidBrokerGuid").value           = xmlDoc.childNodes[5].childNodes[0].nodeValue;
        }
    }
}

function IsBadCredit() {    

     if (jQuery("[id$=cblCCJHistory_0]").is(":checked"))
        { 
            return true;
        } else {

            return false;
        }
}

function IsSelfCert() {
    
    if (jQuery("input[name$=rblSelfCertify]:checked").val() == 'Y') {
        
        return true;
    } 

    return false;
}

function IsFTB() {
    
    if (jQuery("input[name$=rblFirstTimeBuyer]:checked").val()) {
        
        return true;    
    }

    return false;
}

function GetMortgageType(controlPrefix) {
    var intMT;
    var objMT = document.getElementById(controlPrefix + "_ddlMortgageType");

    if (objMT.value == '2') {
        
        intMT = 2; //BTL

        if (IsBadCredit()) {
            intMT = 8;
        }        
    } 

    if (objMT.value == '1') {
        
        intMT = 1; //Rem

        if (IsSelfCert()) {
            intMT = 5; //SelfCerRem
        }

        if (IsBadCredit()) {
            intMT = 7; //AdvRem
        }        
    }

    if (objMT.value == '3') {
        
        intMT = 3; //Purch

        if (IsFTB()) {
            intMT = 4;
            
            if (IsSelfCert()) {
                intMT = 6; //SelfCerOther
            }

            if (IsBadCredit()) {
                intMT = 8; //AdvOther
            }  
        }        
    }

    return intMT;
}
