﻿$(document).ready(function () {
    
    $("#pcaErrorMessage").dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        buttons: {
            Ok: function () {
                $(this).dialog('close');
            }
        }
    });
    $("#pcaAddressSelector").dialog({
        autoOpen: false,
        width: 750,
        modal: true,
        resizable: false,
        buttons: {
            Ok: function () {
                $(this).dialog('close');
                var id = $('#pcaAddressSelector select').val();
                if (typeof (id) !== 'undefined' && id !== null) {
                    pcaFetchBegin(id);
                }
            },
            Cancel: function () {
                $(this).dialog('close');
            }
        }
    });
    $('#pcaAddressSelector select').dblclick(function () {
        var id = $(this).val();
        pcaFetchBegin(id);
        $('#pcaAddressSelector').dialog('close');
    });
    $('<input>', {
        type: 'button',
        'class': 'pca_postcodebutton',
        value: 'Find',
        click: function () {
            var postcode = $('#Postcode').val();
            pcaByPostcodeBegin(postcode);
        }
    }).insertAfter('#Postcode.pcaPostcode');
});
function pcaByPostcodeBegin(postcode) {
    $.getJSON("/Address/Find", { "searchTerm": postcode }, pcaByPostcodeEnd);
}
function pcaByPostcodeEnd(response, textStatus) {
    if (response.length == 0) {
        pcaProcessErrorMessage("No matching addresses found", "Please enter the address manually.");
    } else {
        var selectHtml = "";
        for (var i in response) {
            selectHtml += "<option value=" + response[i].Id + ">" + response[i].StreetAddress + "</option>";
        }
        $('#pcaAddressSelector').dialog('open');
        $('#pcaAddressSelector select').html(selectHtml);
    }
}
function pcaFetchBegin(addressId) {
    $.getJSON("/Address/RetrieveById", { "addressId": addressId }, pcaFetchEnd);
}
function pcaFetchEnd(response) {
    if (response.length == 0) {
        pcaProcessErrorMessage("Unable to retrieve address", "Please contact support");
    } else {
        $('#Line1').val(response.Line1);
        $('#Line2').val(response.Line2);
        $('#PostTown').val(response.PostTown);
        $('#County').val(response.County);
    }
}
