function PadToTwoDigits(theInt) {
    return ("0" + theInt.toString()).slice(-2);
}
function formatDetailedDateFromEpoch(theDateNumber, excludeSeconds) {
    // protect from 0 date (the epoch)
    if (theDateNumber == 0) {
        return '';
    }
    if (typeof excludeSeconds === 'undefined') {
        excludeSeconds = false;
    }

    var theDate = new Date();
    theDate.setTime(theDateNumber);

    var hourString = theDate.getHours().toString();
    var hourNotation = 'AM';
    if (theDate.getHours() >= 12) {
        if (theDate.getHours() > 12) {
            hourString = (theDate.getHours() - 12).toString();
        } else {
            hourString = theDate.getHours().toString();
        }
        hourNotation = 'PM';
    }
    var formattedDate = theDate.getDate().toString() + '/' +
        PadToTwoDigits((theDate.getMonth() + 1)) + '/' +
        theDate.getFullYear().toString() + ' ' +
        hourString + ':' +
        PadToTwoDigits(theDate.getMinutes());
    if (!excludeSeconds) {
        formattedDate += ':' + PadToTwoDigits(theDate.getSeconds())
    }
    formattedDate += ' ' + hourNotation;
    return formattedDate;

}

function formatGroup(theGroup) {
    if (theGroup.loading) return theGroup.text;

    var markup = "<div class='select2-result-repository clearfix'>"
    if (theGroup.Code) {
        markup += "<div><b>" + theGroup.Code + "</b></div>";
    }
    if (theGroup.Description) {
        markup += "<div class='select2-result-repository__description'>" + theGroup.Description + "</div>";
    }

    markup += "</div>";

    return markup;
}

function formatGroupSelection(theGroup) {
    //if (theGroup.Description) {
    //    return theGroup.Description;
    //} else {
    //    return theGroup.Code;
    //}
    if (theGroup.Code) {
        return theGroup.Code + ' - ' + theGroup.Description;
    } else {
        return '';
    }
}

function formatUse(theUse) {
    if (theUse.loading) return theUse.text;

    var markup = "<div class='select2-result-repository clearfix'>"
    if (theUse.Description) {
        markup += "<div><b>" + theUse.Description + "</b></div>";
    }
    var theDesc = '';
    if (theUse.ChargeType) {
        theDesc = theUse.ChargeType;
    }
    //if (theUse.CategoryCode) {
    //    if (theDesc !== '') {
    //        theDesc += ' - ';
    //    }
    //    theDesc += theUse.CategoryCode;
    //}
    if (theDesc !== '') {
        markup += "<div class='select2-result-repository__description'>" + theDesc + "</div>";
    }

    markup += "</div>";

    return markup;
}

function formatUseSelection(theUse) {
    if (theUse.Description) {
        return theUse.Description + ' <span style="font-size:9px">[' + theUse.ChargeType + ']</span>';
    } else {
        return '';
    }
}

function hasValidEntries() {
    var groupCode = GetGroupCode();
    if (groupCode == null || typeof (groupCode) === 'undefined' || groupCode === '') {
        $('#groupSelect').focus();
        $('.body-content').append("<div id='dialog' title='Group Code'><br><p>Please select a valid Group Code<p/></div>");
        $("#dialog").dialog();
        //alert("Please select a valid Group Code");
        return false;
    }
    var chargeTypeCode = GetChargeType();
    if (chargeTypeCode == null || typeof (chargeTypeCode) === 'undefined' || chargeTypeCode === '') {
        $('#usesSelect').focus();
        
        $('.body-content').append("<div id='dialog' title='Charge Type'><br><p>Please select a valid Charge Type</p></div>");
        $("#dialog").dialog();
        //alert("Please select a valid Charge Type");
        return false;
    }
    var qty = $('#qtyInput').val();
    if (qty == null) {
        $('#qtyInput').val(0);
    }
    return true;
}

function printClick() {
    if (hasValidEntries()) {
        print();
    }
}

function GetValidTo(calculationDate) {
    var rightNow = new Date();
    if (calculationDate != "")
        rightNow = new Date(calculationDate);
    //var month = rightNow.getMonth() + 1;
    var year = rightNow.getFullYear();
    if (rightNow.getMonth() + 1 > 6) {
        year += 1;
    }
    var endOfFinYearString = "30/06/" + year.toString();

    //return "This fee calculation is valid to " + endOfFinYearString + ".";
    return "This fee estimate is based on current published fees and charges.";
}

function ResetResults() {
    $('#results').html("");
    $('#resultsAsAt').html("");
    $('#validTo').html("");
    $('#calculateButton').disabled = false;
}

function calculateClick() {
    if (!hasValidEntries()) {
        return;
    }
    var groupCode = GetGroupCode();
    var comboId = GetChargeType();

    var chargeTypeCode = getChargeTypeFromComboId(comboId);
    var categoryCode = getCategoryCodeFromComboId(comboId);

    var qty = GetQuantityValue();

    $('#calculateButton').disabled = true;
    $('#loadingImage').removeClass('hide');
    //var calculateUrl = '@(DevelopmentServicesCalculator.Handlers.Configs.GetPropertyApiBaseUrl())' + '/api/DSCalculator/Calculate';
    var calculateUrl = /*$('#APIBaseUrl').val() +*/ '/api/DSCalculator/Calculate';
    $.ajax({
        url: calculateUrl,
        type: 'GET',
        data: { chargeType: chargeTypeCode, qty: qty, groupCode: groupCode },
        dataType: 'json',
        success: function (data) {
            //            var dateMade = new Date(data.CalculationTimeTicks);
            var formattedDate = formatDetailedDateFromEpoch(data.CalculationTimeTicks);
            formattedDate = formattedDate.replace(' AM', '&nbsp;AM').replace(' PM', '&nbsp;PM');
            var amount = data.Amount;
            var formattedAmount = amount.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
            $('#results').html("$" + formattedAmount);
            $('#resultsAsAt').html(formattedDate);
            $('#validTo').html(GetValidTo(data.CalculationTime));
            $('#calculateButton').disabled = false;
            $('#loadingImage').addClass('hide');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            
            $('.body-content').append("<div id='dialog' title='Calculation failed'><br><p>Calculation failed. Please try again later : [Info]" + textStatus + "</p></div>");
            $("#dialog").dialog();
            //alert("Calculation failed. Please try again later : [Info]" + textStatus);
            $('#results').html("Error");
            $('#resultsAsAt').html("");
            $('#validTo').html("");
            $('#calculateButton').disabled = false;
            $('#loadingImage').addClass('hide');
        }
    });
}

function checkEnter(e) {
    if (e.keyCode == 13) {
        calculateClick();
    }
}

function getCategoryCodeFromComboId(comboId) {
    var parts = comboId.split('~');
    if (parts.length == 2) {
        return parts[1];
    }
    return null;
}

function getChargeTypeFromComboId(comboId) {
    var parts = comboId.split('~');
    return parts[0];
}

function showSelectedDescription(chargeNcategoryComboId) {
    //var selectedUseUrl = '@(DevelopmentServicesCalculator.Handlers.Configs.GetPropertyApiBaseUrl())' + '/api/DSCalculator/GetUse';
    var chargeType = getChargeTypeFromComboId(chargeNcategoryComboId);
    var categoryCode = getCategoryCodeFromComboId(chargeNcategoryComboId);
    var selectedUseUrl = /*$('#APIBaseUrl').val() +*/ '/api/DSCalculator/GetUse';

    $.ajax({
        url: selectedUseUrl,
        type: 'GET',
        data: { chargeType: chargeType, groupCode: GetGroupCode(), categoryCode: categoryCode },
        dataType: 'json',
        success: function (data) {
            if (data.Units == "Flat Fee") {
                $('#qtyInput').prop('disabled', true);
            }
            var useDetails = "<b>" + data.Description + "</b><br/>" + data.ChargeType;
            useDetails += " [" + data.CategoryCode + "]";
            if (data.CalculationType && data.CalculationType != "Unknown") {
                useDetails += "<br/>Type:" + data.CalculationType;
            }
            $("#useDetails").html(useDetails);

            $("#unitLabel").html("<b>" + data.Units + "</b>")
        },
        error: function (jqXHR, textStatus, errorThrown) {
            $('.body-content').append("<div id='dialog' title='Charge Type'><br><p>Charge Type fetch failed. Please try again later : [Info]" + textStatus + "</p></div>");
            $("#dialog").dialog();
            //alert("Charge Type fetch failed. Please try again later : [Info]" + textStatus);
            $('#qtyInput').prop('disabled', false);
        }
    });
}

function GetGroupCode() {
    try {
        return $('#groupSelect').select2('data')[0].Code;
    }
    catch (ex) {
        return null;
    }
}

function GetGroupText() {
    var ddlData = $('#groupSelect').data('select2');
    if (ddlData) {
        return ddlData.$selection.text();
    }
    return '';
}

function GetChargeType() {
    return $('#usesSelect').val();
}

function GetQuantityValue() {
    var qty = $('#qtyInput').val();
    if (qty == null) {
        $('#qtyInput').val(0);
        return 0;
    }
    return qty;
}

function GetSearchTerm(curParamTerm) {
    var term = $('#usesSelect').data('select2').dropdown.$search.val();
    return term;
}

function CreateuthorizationToken(time, key) {
    var message = 'DACalculator' + time + key;
    var hash = md5(message);

    return hash;
}

function SetUpGroupSelector() {
    var groupCommandUrl = /*$('#APIBaseUrl').val() +*/ '/api/DSCalculator/GetGroups';
    var pageSize = 20;
    var currentTime = new Date().getTime();
    $('#groupSelect').select2(
    {
        theme: 'bootstrap',
        width: '100%',
        placeholder: 'Select application type',
        allowClear: false,
        minimumResultsForSearch: Infinity,
        ajax: {
            delay: 250,
            url: groupCommandUrl,
            crossDomain: true,
            //headers: { 'X-Apitoken': 'hello' },
            dataType: 'json',
            results: function (data, page) {
                return { results: data };
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $('.body-content').append("<div id='dialog' title='Application Type'><br><p>Application Type fetch failed. Please try again later : [Info]" + textStatus + "</p></div>");
                $("#dialog").dialog();
                //alert("Application Type fetch failed. Please try again later : [Info]" + textStatus);

            }
        },

        escapeMarkup: function (markup) { return markup; },
        templateResult: formatGroup,
        templateSelection: formatGroupSelection,
        containerCss: function (element) {
            var style = $(element)[0].style;
            return {
                display: style.display
            };
        },
        query: function (query) {
            self = this;
            var key = 'groups';
            if (typeof (self.cacheDataSource) === 'undefined') {
                self.cacheDataSource = [];
            }
            var cachedData = self.cacheDataSource[key];

            if (cachedData) {
                query.callback({ results: cachedData });
                return;
            } else {
                $.ajax({
                    url: groupCommandUrl,
                    crossDomain: true,
                    dataType: 'json',
                    type: 'GET',

                    success: function (data) {
                        var results = [];
                        $.each(data.Results, function (index, groupRecord) {
                            results.push({ id: groupRecord.Id, Code: groupRecord.Code, Description: groupRecord.Description });
                        });
                        self.cacheDataSource[key] = results;
                        query.callback({ results: results });

                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $('.body-content').append("<div id='dialog' title='Application Type'><br><p>Application Type fetch failed. Please try again later : [Info]" + textStatus + "</p></div>");
                        $("#dialog").dialog();
                        //alert("Application Type fetch failed. Please try again later : [Info]" + textStatus);
                    }
                });
            }
        }
    })
    .focus(function () { $(this).select2('open'); })
    ;

    $('#groupSelect').hide();
    $('#groupSelect').select2('open');
    $('#groupSelect').select2('close');
    $('#groupSelect').show();

}


function SetUpUseSelector() {
    //var usesCommandUrl = '@(DevelopmentServicesCalculator.Handlers.Configs.GetPropertyApiBaseUrl())' + '/api/DSCalculator/GetUses';
    var usesCommandUrl = /*$('#APIBaseUrl').val() +*/ '/api/DSCalculator/GetUses';
    var pageSize = 20;

    $('#usesSelect').select2(
    {
        theme: 'bootstrap',
        width: '100%',
        placeholder: 'Start typing the charge type',
        minimumInputLength: 0,
        allowClear: true,
        disabled: true,
        ajax: {
            delay: 250,
            url: usesCommandUrl,
            crossDomain: true,
            dataType: 'json',
            data: function (params) {
                return {
                    pageSize: pageSize,
                    pageNum: params.page || 1,
                    searchTerm: GetSearchTerm(params.term),
                    groupCode: GetGroupCode()
                };
            },
            processResults: function (data, params) {
                var results = [];
                $.each(data.Results, function (index, useRecord) {
                    results.push({ id: useRecord.ChargeType + '~' + useRecord.CategoryCode, Description: useRecord.Description, ChargeType: useRecord.ChargeType, CategoryCode: useRecord.CategoryCode });
                });
                return {
                    results: results,
                    pagination: { more: (params.page || 1) * pageSize < data.Total }
                };
            },
            results: function (data, page) {
                var isMore = (page * pageSize) < data.Total;
                return { results: data.Results, more: isMore };
            }
        },

        escapeMarkup: function (markup) { return markup; },
        templateResult: formatUse,
        templateSelection: formatUseSelection

    })
    .focus(function () { $(this).select2('open'); })
    ;
}

var last_search = '';
function BindUIEvents() {

    $('#qtyInput').bind('keyup', function (e) {
        ResetResults();
        if (e.which) {
            if (e.which == 13) {
                calculateClick();
            }
        } else if (e.keyCode) {
            if (e.keyCode == 13) {
                calculateClick();
            }
        }
    });

    $('#qtyInput').bind('change', function (e) {
        ResetResults();
    });

    $('#qtyInput').bind('mousewheel', function (e) {
        if ($('#qtyInput').is(":focus")) {
            ResetResults();
        }
    });




    // Need to track the last search manually so we can
    // reload the values

    $('#usesSelect').on('select2:open', function (e) {

        if (last_search && last_search.length > 0) {
            var $search = $('#usesSelect').data('select2').dropdown.$search;
            $search.val(last_search);
            $search.trigger('keyup');
        }
    });
    $('#usesSelect').on('select2:closing', function (e) {
        last_search = $('.select2-search').find('input').val();
    });
    $('#usesSelect').on('select2:select', function (e) {
        var selectedDesc = $('#usesSelect').find(':selected').data('data').Description;
        var selectedTitle = $('#usesSelect').find(':selected').data('data').ChargeType;
        $("#useDetails").html("<b>" + selectedTitle + "</b><br/>" + selectedDesc + "<br/>..fetching details...");

        showSelectedDescription($('#usesSelect').val());
        $('#unitInput').show();
        $('#qtyInput').prop('disabled', false);
        $('#calculateButton').prop('disabled', false);

        //$("#results").html("");
        //$("#resultsAsAt").html("");
        //$("#validTo").html("");
        ResetResults();
    });

    $('#usesSelect').on('select2:unselect', function (e) {
        $('#qtyInput').prop('disabled', true);
        $('#calculateButton').prop('disabled', true);
        $('#unitLabel').html("");
        $("#useDetails").html("");
        //$("#results").html("");
        //$("#resultsAsAt").html("");
        //$("#validTo").html("");
        ResetResults();
    }
    );

    $('#groupSelect').on('select2:select',
        function (e) {
            $('#usesSelect').prop('disabled', false);
            //$('#usesSelect').val("").trigger('change');

            //$('#select2-usesSelect-results').empty();
            //$('#usesSelect').html('').select2().data({ id: null, text: null });
            //$('#usesSelect').focus();
            //$('#select2-usesSelect-results').empty();
            //$('#usesSelect').html('');
            //$('#usesSelect').select2().data().select2.$results.empty();
            //$('#usesSelect').data('select2').dropdown.$element.find('option').remove();
            //$('#usesSelect').data('select2').dropdown.$dropdown.find('.select2-results__option').remove();
            $('#usesSelect').data('select2').dropdown.$dropdown.find('.select2-results__option').css('display', 'none');
            $('#usesSelect').val(null).trigger('change');

            $('#qtyInput').prop('disabled', true);
            $('#calculateButton').prop('disabled', true);

            $('#unitLabel').html("");
            $("#useDetails").html("");
            //$("#results").html("");
            //$("#resultsAsAt").html("");
            //$("#validTo").html("");
            ResetResults();

            $("#helpButtonLink").data('title', GetGroupText());

        }
     );
}


