@using Telerik.Web.Mvc.UI
@using ProspectiveAdvantage.ViewModels
@using PA.ViewModel.ExtensionHelpers
@model ProspectiveAdvantage.ViewModels.MemberProvider
@{
    ViewBag.Title = String.Format("Update Member Provider - {0}", @Model.Member.GetDisplayName());
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@ViewBag.Title</h2>
@{
    Html.RenderPartial("MemberInformationHeader", @Model.Member);
}
<h3>Current Provider Information</h3>
@(Html.Telerik().Grid(Model.PCP).Name("PCPGrid")
.Columns(columns =>
{
    columns.Bound(prac => prac.DisplayName).HeaderTemplate("Name");
    columns.Bound(prac => prac.NPI).HeaderTemplate("NPI");
    columns.Bound(prac => prac.SpecialtyName).HeaderTemplate("Specialty");
    columns.Bound(prac => prac.DisplayAddress).HeaderTemplate("Address");
    columns.Bound(prac => prac.Phone).HeaderTemplate("Phone");
}
).ClientEvents(events => events.OnDataBound("PCPGRIDDatabinding")))
<h3>
    Locate New Provider</h3>
@{Html.BeginForm("PractitionerGridAjaxBinding", "MemberProvider", FormMethod.Post);
    <text>Last Name</text> @Html.TextBox("providerName", "", new { @class = "textBoxLarge" }) 
    <text>Specialty </text>@Html.DropDownList("Specialties", @Model.Specialties, "Choose One", new { id = "ddlPractitionerSpecialties", name = "ddlPractitionerSpecialties" });
    <text>State </text>@Html.DropDownList("States", @Model.States, "Choose One", new { id = "ddlStates", name = "ddlStates" });
    <input type="button" value="Search" id="btnProviderSearch" name="btnProviderSearch" />
    Html.EndForm();}
@(
 Html.Telerik().Grid(Model.PractitionerDisplayItems).Name("PractitionersGrid").Pageable(pager => pager.Total(Model.TotalPractitionerRecords)).Sortable()
             .DataBinding(dataBinding => dataBinding.Ajax().Select("PractitionerGridAjaxBinding", "MemberProvider"))
             .Columns(columns =>
             {
                 columns.Bound(prac => prac.PractitionerId).ClientTemplate("<input type='checkbox' name='chkPractitioner' value='<#= PractitionerId #>' onclick='handleProviderSelected(this)' />").Width(45).HeaderTemplate(" ");
                 columns.Bound(prac => prac.LastName).ClientTemplate("<#= LastName #>");
                 columns.Bound(prac => prac.FirstName);
                 columns.Bound(prac => prac.NPI);
                 columns.Bound(prac => prac.SpecialtyName).HeaderTemplate("Specialty");
                 columns.Bound(prac => prac.Address1).HeaderTemplate("Address");
                 columns.Bound(prac => prac.City);
                 columns.Bound(prac => prac.StateCode).HeaderTemplate("State").Width(25);
                 columns.Bound(prac => prac.PostalCode).HeaderTemplate("Zip Code").Width(25);
                 columns.Bound(prac => prac.Phone).Width("55");
             }).Selectable().ClientEvents(events => events.OnRowSelect("handleOnRowSelect"))
)
<div id="divSpecifyProvider">
    <form action="" method="" id="frmSpecifyProvider">
    Specify a Provider
    <input type="text" class="textBoxLarge" id="txtSpecifyProvider" name="txtSpecifyProvider" />
    <br />
    <span class="formhint">Enter first and last name (Customize name for a provider in the
        list)</span>
    </form>
</div>
<div id="divNoProviders">
    <input type="checkbox" id="chkNoneApply" name="chkNoneApply" />
    <label for="chkNoneApply">
        None of the above providers apply</label>
</div>
<div id="divAddProviderForm">
    @{Html.BeginForm("AddProvider", "MemberProvider", FormMethod.Post, new { id = "addProviderForm", name = "addProviderForm" });
        <h3>
            Enter Provider Information</h3>
        <div class="fieldWrapper">
            <label for="txtFirstName">
                First Name:</label>
            <input type="text" name="txtFirstName" id="txtFirstName" class="textBoxMedium" />
        </div>
        <div class="fieldWrapper">
            <label for="txtLastName">
                Last Name:</label>
            <input type="text" name="txtLastName" id="txtLastName" class="textBoxMedium" />
        </div>
        <div class="fieldWrapper">
            <label for="txtPhone">
                Phone:</label>
            <input type="text" name="txtPhone" id="txtPhone" class="textBoxMedium" />
        </div>
        <br style="clear: left;" />

        <div class="fieldWrapper">
            <label for="txtAddress1">
                Address 1:</label>
            <input type="text" name="txtAddress1" id="txtAddress1" class="textBoxMedium" />
        </div>
        <div class="fieldWrapper">
            <label for="txtAddress2">
                Address 2:</label>
            <input type="text" name="txtAddress2" id="txtAddress2" class="textBoxMedium" />
        </div>
        <div class="fieldWrapper">
            <label for="txtCity">
                City*:</label>
            <input type="text" name="txtCity" id="txtCity" class="textBoxLarge" style="display:block" />
            
        </div>
        <br style="clear: left;" />
        <div class="fieldWrapper">
            <label for="ddlState">
                State*:</label><br />
            @Html.DropDownList("ddProviderState", @Model.States, "Choose One", new { id = "ddProviderState", name = "ddlProviderState" })
        </div>
        <br style="clear: both;" />
        <span class="formhint" style="float:left">*Mandatory if any information entered</span><br />
        <input type="reset" value="Reset" />
        Html.EndForm();}
</div>
<div id="divButtonPanel" style="float:right">
    <input type="button" value="Save" id="btnSave" name="btnSave" />
</div>
<script type="text/javascript">

    var saveState = {
        NewProvider: 'new_provider',
        UpdateExistingProvider: 'update_existing_provider',
        UpdateExistingProviderAttribute: 'update_provider_attribute',
        MemberId :  @Model.Member.MemberID,



        saveLocation: '',
        SelectedProviderId: '0',

        GetSelectedProviderId: function () {
            var providerId = saveState.SelectedProviderId;
            if (null === providerId || null == providerId) {
                saveState.SelectedProviderId = 0;
                return saveState.SelectedProviderId;
            }

            if (undefined === providerId || typeof providerId === 'undefined') {
                saveState.SelectedProviderId = 0;
                return saveState.SelectedProviderId;
            }

            return providerId;
        },

        SetSelectedProviderId: function (providerId) {
            saveState.SelectedProviderId = providerId;
        }
    }


    $(document).ready(function () {
        initsaveState();
        initEvents();
        initGridEvents();
    });


    function initGridEvents(){


        $('a.t-refresh').click(
            function(event){
             //event.preventDefault();

             //clear the textbox and select lists
         /*    $('#providerName').val('');
             var practitionerList = $('#ddlPractitionerSpecialties');
             var stateList = $('#ddlStates');
             practitionerList.val($('option:first', practitionerList).val());
             stateList.val($('option:first', stateList).val());
             */
             //Rebind the grid
             debugger;
             var grid =  $("#PCPGrid").data("tGrid");
             console.log(grid);
             console.log(this);
             grid.rebind({practitionerSpecialty : ''});//
            }
        );
    }

    function initsaveState() {
        $('#divAddProviderForm').hide();
        $('#divSpecifyProvider').hide();
    }

    function initEvents() {
        $('#chkNoneApply').click(handleNoneApplyCheck);
        $('#btnProviderSearch').click(handleProviderSearch);
        $('#btnProviderSearch').keyup(handleEnterKeyupEvent);
        $('#btnSave').click(handlePageSave);
    }


    function handlePageSave() {
        if ($('#chkNoneApply').attr('checked')) {
            saveProviderSuggestion();
            return;
        }

        if (saveState.saveLocation === saveState.UpdateExistingProvider) {
            if (saveState.GetSelectedProviderId() != 0) {
                saveExistingProvider();
            }
        }
    }


    function saveExistingProvider() {
        var AssignmentMap = GetAttributeUpdates();
        var providerId = saveState.GetSelectedProviderId();
        AssignmentMap['practitionerId'] = providerId;
        AssignmentMap['memberId'] = saveState.MemberId;

        $.ajax({
                    url: '@Url.RouteUrl(new { controller = "MemberProvider", action = "SpecifyNewProviderFromExisting" })',
                    data: AssignmentMap,
                    type: 'POST',
                    success: rebindPCPGrid
        });
    }


    function GetAttributeUpdates() {
        var providerName = $('#txtSpecifyProvider').val();
        var providerAttributes = {
            name: providerName
        }

        return providerAttributes;
    }

    function saveProviderSuggestion() {
        //gather form value
        var theFirstName = $('#txtFirstName').val();
        var theLastName = $('#txtLastName').val();
        var thePhone = $('#txtPhone').val();
        var theAddress1 = $('#txtAddress1').val();
        var theAddress2 = $('#txtAddress2').val();
        var theCity = $('#txtCity').val();
        var theState = $('#ddProviderState option:selected').val();

        @{
        <text>var memberId = </text> @Model.Member.MemberID;<text>;</text>
        }
        var args = {
            firstName: theFirstName,
            lastName: theLastName,
            phone: thePhone,
            address1: theAddress1,
            address2: theAddress2,
            city: theCity,
            stateCode: theState,
            memberId: memberId
        }

        $.ajax({
            url: '@Url.RouteUrl(new { controller = "MemberProvider", action = "SpecifyNewPCPCandidate" })',
            data: args,
            type: 'POST',
            success: rebindPCPGrid
        });
    }

    function rebindPCPGrid(data){
        $("#PCPGrid").data("tGrid").rebind(); 
    }

    function handleProviderSearch() {
        var practitionerGrid = $('#PractitionersGrid').data('tGrid');
        var theSearchTerm = $('#providerName').val();
        var theSpecialty = $('#ddlPractitionerSpecialties').val();
        var theStateCode = $('#ddlStates').val();
        practitionerGrid.rebind({ searchTerm: theSearchTerm, practitionerSpecialty: theSpecialty, stateCode: theStateCode });
    }


    function handleEnterKeyupEvent(event) {
        if (event.keyCode == 13) {
            $('#btnProviderSearch').click();
        }
    }

    function handleOnRowSelect(e) {
        //console.log('Row selected');
        //console.log(e);
    }

    function handleProviderSelected(selectedNode) {
        if (selectedNode.checked) {
            unselectPeerNodes(selectedNode);
            showElement('#divSpecifyProvider', 350);
            hideElement('#divAddProviderForm', 350);
            $('#chkNoneApply').attr("checked", false);
        }
        else {
            hideElement('#divSpecifyProvider', 350);
        }

        clearTextField('txtSpecifyProvider');
        saveState.saveLocation = saveState.UpdateExistingProvider;
        saveState.SetSelectedProviderId(selectedNode.value);
    }

    function handleNoneApplyCheck() {
        showHideAddProviderForm();
        clearPractitionerSelections();
        clearTextField('txtSpecifyProvider');
        $('#divSpecifyProvider').hide(350);
        saveState.saveLocation = saveState.NewProvider;
    }

    function showHideAddProviderForm() {
        if ($('#chkNoneApply').attr('checked') == true) {
            showElement('#divAddProviderForm', 350);
        } else {
            hideElement('#divAddProviderForm', 350);
        }
    }

    function clearCheckboxes(checkboxList) {
        checkboxList.each(
            function () {
                this.checked = false;
            }
        );
    }

    //Hides an element (elementId) at the specified velocity (speed)
    function hideElement(elementId, speed) {
        //Appending Hash will not work in IE7 or IE9 Compatability mode.
        //elementId = appendHashTagToElementId(elementId);
        $(elementId).hide(speed);
    }

    //shows an element (elementId) at the specified velocity (speed)
    function showElement(elementId, speed) {
        //Appending Hash will not work in IE7 or IE9 Compatability mode.
        //elementId = appendHashTagToElementId(elementId);
        $(elementId).show(speed);
    }

    //clears the value from a text field (elementId)
    function clearTextField(elementId) {
        var id = appendHashTagToElementId(elementId);
        $(id).attr("value", '');
    }

    //prepends a hashtag to an elementId if necessary
    function appendHashTagToElementId(elementId) {
        if (elementId[0] != '#') {
            elementId = '#' + elementId;
        }
        return elementId;
    }



    function unselectPeerNodes(selectedNode) {
        var selectedNodeValue = selectedNode["value"];
        var peerNodes = $('#PractitionersGrid :checkbox[value !=' + selectedNodeValue + ']');
        peerNodes.each(
            function () {
                this.checked = false;
            });
    }

    function clearPractitionerSelections() {
        $('#PractitionersGrid :checkbox').each(
                function () {
                    this.checked = false;
                }
            );
    }


    function PCPGRIDDatabinding(){
    }
</script>
