﻿/// <reference path="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.2-vsdoc.js" />
/// <reference path="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.js" />

function IsInteger(szValue) {
    var validChars = "0123456789";
    var IsInteger = true;
    var ch;

    if (isNaN(szValue) || szValue.length == 0)
        IsInteger = false;

    for (i = 0; i < szValue.length && IsInteger == true; i++) {
        ch = szValue.charAt(i);
        if (validChars.indexOf(ch) == -1)
            IsInteger = false;
    }
    return IsInteger;
}

function calcCourseHandicap() {
    var txtHI = $(".HIValue");
    var txtSlope = $(".Slope");
    var pCH = $(".CHP");
    var pWarning = $(".HLWarning");

    var ch = calcCH(txtHI.val(), txtSlope.val(), pWarning);

    if (ch) {
        var lblCH = $(".CH");
        lblCH.html(ch);
        pCH.css("display", "block");
    }
    else
        pCH.css("display", "none");
}
    
function calcCH(hi, slope, pWarning) {
    var error = "";

    var hiRegEx = /^[0-9\+]+(?:\.[0-9])?[RMLrml]?/

    if (hi) {
        if (hiRegEx.test(hi)) {
            hi = hi.replace('+', '-');

            hi = parseFloat(hi);

            if (hi < -9.9 || hi > 40.4)
                error = "Please enter a Handicap Index between +9.9 and 40.4.";
            else if (IsInteger(slope)) {
                slope = parseInt(slope, 10);
                if (slope < 55 || slope > 155) error = "Please enter a slope rating between 55 and 155.";
            }
            else
                error = "Please enter a valid slope rating.";
        }
        else
            error = "Please enter a valid Handicap Index.";
    }
    else
        error = "Please enter a valid Handicap Index.";

    if (error.length == 0) {
        if (pWarning) pWarning.css("display", "none");

        //calculate the CH
        var ch = hi * slope / 113;
        ch = Math.round(ch);

        if (ch < 0) ch = "+" + Math.abs(ch);
        return ch;
    }
    else {
        if (pWarning) {
            pWarning.css("display", "block");
            pWarning.html(error);
        }
        return null;
    }
}

