﻿

$(document).ready(function() {
    $(function() {
        $("#dialog-paymentCalculator").dialog(
                {
                    autoOpen: false
                    , height: 240
                    , width: 500
                    , modal: false
                    , draggable: true
                    , resizable: false
                });
    });

    // Hookup datepicker
    $(function() {
        $("[id$='calFirstStartDate']")
            .datepicker({ dateFormat: 'dd-M-yy'
                , appendText: '(dd-MMM-yyyy)'
                , beforeShowDay: $.datepicker.noWeekends
                , minDate: '+2D'
                , maxDate: '+52W'
                , defaultDate: +2
                , buttonImage: '/images/CalendarButton.png'
            });
    });

    $("#btnWeekly").click(function() {
        var bValid = true;
        var amount = $("#txtWeekly")
            , paymentResult = $("#paycalResults")
            , firstPaymentDate = $("#calFirstStartDate");

        resetAllErrors();
        paymentResult.html("");

        bValid = bValid && checkLength(amount, "weekly spend", 1, 25);
        bValid = bValid && checkLength(firstPaymentDate, "first payment day", 1, 25);

        if (!bValid)
            return;

        updateResults('Calculating results. Please wait....|||');
        $("#txtMonthly").val("");
        $("#txtFortnightly").val("");
        $("#txtTotal").val("");

        var returnResult = "{ 'a':'" + amount.asNumber()
            + "', 'b':'" + firstPaymentDate.val()
            + "'}";

        $.ajax({
            type: "POST",
            url: "../PaymentCalculator.aspx/GetWeekly",
            data: returnResult,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                // Replace this div's content with the page method's return.
                updateResults(msg.d);
            }
        });
    });

    $("#btnFortnight").click(function() {
        var bValid = true;
        var amount = $("#txtFortnightly")
            , paymentResult = $("#paycalResults")
            , firstPaymentDate = $("#calFirstStartDate");

        resetAllErrors();
        paymentResult.html("");

        bValid = bValid && checkLength(amount, "fortnightly spend", 1, 25);
        bValid = bValid && checkLength(firstPaymentDate, "first payment day", 1, 25);

        if (!bValid)
            return;

        updateResults('Calculating results. Please wait....|||');
        $("#txtMonthly").val("");
        $("#txtTotal").val("");
        $("#txtWeekly").val("");

        var returnResult = "{ 'a':'" + amount.asNumber()
            + "', 'b':'" + firstPaymentDate.val()
            + "'}";

        $.ajax({
            type: "POST",
            url: "../PaymentCalculator.aspx/GetFortnightly",
            data: returnResult,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                // Replace this div's content with the page method's return.
                updateResults(msg.d);
            }
        });
    });

    $("#btnMonthly").click(function() {
        var bValid = true;
        var amount = $("#txtMonthly")
            , paymentResult = $("#paycalResults")
            , firstPaymentDate = $("#calFirstStartDate");

        resetAllErrors();
        paymentResult.html("");

        bValid = bValid && checkLength(amount, "monthly spend", 1, 25);
        bValid = bValid && checkLength(firstPaymentDate, "first payment day", 1, 25);

        if (!bValid)
            return;

        updateResults('Calculating results. Please wait....|||');
        $("#txtTotal").val("");
        $("#txtFortnightly").val("");
        $("#txtWeekly").val("");

        var returnResult = "{ 'a':'" + amount.asNumber()
            + "', 'b':'" + firstPaymentDate.val()
            + "'}";

        $.ajax({
            type: "POST",
            url: "../PaymentCalculator.aspx/GetMonthly",
            data: returnResult,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                // Replace this div's content with the page method's return.
                updateResults(msg.d);
            }
        });
    });

    $("#btnTotal").click(function() {
        var bValid = true;
        var amount = $("#txtTotal")
        , paymentResult = $("#paycalResults")
        , firstPaymentDate = $("#calFirstStartDate");

        resetAllErrors();
        paymentResult.html("");

        bValid = bValid && checkLength(amount, "total spend", 1, 25);
        bValid = bValid && checkLength(firstPaymentDate, "first payment day", 1, 25);

        if (!bValid)
            return;

        updateResults('Calculating results. Please wait....|||');
        $("#txtMonthly").val("");
        $("#txtFortnightly").val("");
        $("#txtWeekly").val("");

        var returnResult = "{ 'a':'" + amount.asNumber()
            + "', 'b':'" + firstPaymentDate.val()
            + "'}";

        $.ajax({
            type: "POST",
            url: "../PaymentCalculator.aspx/GetTotals",
            data: returnResult,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                // Replace this div's content with the page method's return.
                //$("#paycalResults").html(msg.d);
                updateResults(msg.d);
            }
        });
    });

    function updateResults(r) {
        var rWeekly = $("#pcrWkly")
        , rFortnightly = $("#pcrFrtly")
        , rMonthly = $("#pcrMthly")
        , rTotal = $("#pcrTot")
        , errs = $("#paycalResults");

        var results = r.toString().split('|');
        if (results.length == 1) {
            errs.html(results[0]);
        }
        else {
            rWeekly.html(results[0]);
            rFortnightly.html(results[1]);
            rMonthly.html(results[2]);
            rTotal.html(results[3]);
        }
    }

    function updateTips(t) {
        var paymentResult = paymentResult = $("#paycalResults");

        paymentResult
		    .text(t)
		    .addClass('ui-state-highlight');
        setTimeout(function() {
            paymentResult.removeClass('ui-state-highlight', 1500);
        }, 500);
    }

    function checkLength(o, n, min, max) {
        var results = checkEmpty(o, n);
        if (results) {
            if (o.val().length > max || o.val().length < min) {
                o.addClass('ui-state-error');
                updateTips("Length of '" + n + "' must be between " + min + " and " + max + ".");
                results = false;
            } else {
                results = true;
            }
        }

        return results;
    }

    function checkEmpty(o, n) {
        if (o.val().length == 0) {
            o.addClass('ui-state-error');
            updateTips("You must enter a " + n + ".");
            return false;
        } else {
            return true;
        }
    }

    function resetAllErrors() {
        var t = $("#txtTotal")
            , m = $("#txtMonthly")
            , f = $("#txtFortnightly")
            , w = $("#txtWeekly")
            , sd = $("#calFirstStartDate")
            , allFields = $([]).add(t).add(m).add(f).add(w).add(sd);

        allFields.removeClass('ui-state-error');
    }

    function callRecal() {
        // Determine which field has value and call.
        t = $("#txtTotal")
        , m = $("#txtMonthly")
        , f = $("#txtFortnightly")
        , w = $("#txtWeekly")

        if (w.val().length > 0) {
            $("#btnWeekly").click();
        }
        else if (f.val().length > 0) {
            $("#btnFortnight").click();
        }
        else if (m.val().length > 0) {
            $("#btnMonthly").click();
        }
        else if (t.val().length > 0) {
            $("#btnTotal").click();
        }
    }

    $("#calFirstStartDate").blur(function() { callRecal(); });
    $("#txtTotal").blur(function() { if( $("#txtTotal").val().length > 0) { $("#btnTotal").click(); } });
    $("#txtMonthly").blur(function() { if( $("#txtMonthly").val().length > 0 ) { $("#btnMonthly").click(); } });
    $("#txtFortnightly").blur(function() { if( $("#txtFortnightly").val().length > 0 ) { $("#btnFortnight").click(); } });
    $("#txtWeekly").blur(function() { if( $("#txtWeekly").val().length > 0 ) { $("#btnWeekly").click(); } });
});

function openPaymentCalculator() {
    var startDate = $("[id$='hfStartDate']")
        , totalAmount = $("[id$='hfAmountTtl']")
        , defaultAmount = 1000;

    if (totalAmount.asNumber() == 0) {
        defaultAmount = 1000;
    }
    else{
        defaultAmount = totalAmount.asNumber();
    }

    $("#calFirstStartDate").val(startDate.val());
    $("#txtTotal").val(defaultAmount.toString());
    $("#dialog-paymentCalculator").dialog('open');
    $("#btnTotal").click();
}


