physicianPortalApp.controller('patientProfileController', ['$scope', '$window', '$location', '$rootScope', '$localStorage', '$sessionStorage', '$filter',
    'baseRxcServices', 'utils', 'config', 'validate', 'textConfig', 'loadingServices',
    function ($scope, $window, $location, $rootScope, $localStorage, $sessionStorage, $filter, baseRxcServices, utils, config, validate, textConfig, loadingServices) {

        $scope.patientId = utils.parseQueryString('PatientId');
        $scope.caseId = utils.parseQueryString('CaseId');
        $scope.showTab = utils.parseQueryString('showTab');
        $scope.phyId = utils.parseQueryString('NGPhyID');
        $scope.DateOfBirth = decodeURIComponent(utils.parseQueryString('DOB'));
        $scope.PatientProfileDataSpinner = true;
        $scope.benefiterrmsg = false;
        $scope.emptyRecordLabelShow = false;
        $scope.emptyRecordenrollment = false;
        $scope.emptyRecordprescption = false;
        $scope.emptyRecordinsurance = false;
        $scope.patientAlertsCount = 0;
        $scope.showbenefit = true;

        $scope.tabType = "Tabs";
        $scope.showTabType = "Tabs";
        $scope.showTabs = function (val) {
            $scope.showTabType = val;
            if (val == "Tabs")
                $("#enrollment").click();
        };
        $scope.showTabs("Tabs");
        $scope.loadPatientProfile = function () {
            $scope.CaseIds.push({
                CaseId: $scope.caseId
            });
            $scope.noBenifitsLabel = textConfig.PatProfile.noBenifits;
            $scope.noMedicationLabel = textConfig.PatProfile.noMedication;
            $scope.emptyRecordLabel = textConfig.PatProfile.emptyRecord;

            //$scope.getAllCaseIds();
            //loadingServices.ShowLoading();
            var reqData = { "PortalId": config.PortalId, "SiteUserId": config.SiteUserId, "PatientId": parseInt($scope.patientId), "CaseId": parseInt($scope.caseId), "ClinicId": utils.getCookie("ClinicId")};
            $scope.showNoRecFound = false;
            $scope.getPatientMilestone();

            baseRxcServices.PostQuery(config.Dashboard.GetPatientProfileByCaseId.API + config.Dashboard.GetPatientProfileByCaseId.URL, reqData)
                .success(function (data, status, headers, config) {
                    if (validate.isNullOrEmptyOrUndefined(data)) {
                        $scope.PatientProfileDataSpinner = false;
                        $scope.showNoRecFound = true;
                        return;
                    }

                    if (data.ErrorMessage) {
                        $scope.PatientProfileDataSpinner = false;
                        $scope.showNoRecFound = true;
                        return;
                    }
                    $scope.patientProfileData = data;

                    if (!validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientDemographics) && !validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientDemographics.PatientDemographics)) {
                        $scope.patientDetails = $scope.patientProfileData.PatientDemographics.PatientDemographics;
                    }
                    if (!validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientMilestones) && !validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientMilestones.PatientMilestones)) {
                        $scope.patientMilestonesCount = $scope.patientProfileData.PatientMilestones.PatientMilestones.length;
                        $scope.patientMilestones = [$scope.patientProfileData.PatientMilestones.PatientMilestones[0]];
                    }

                    $scope.getPrescriptionInfo();
                    $scope.getDocuments();
                    $scope.getInsurance();
                    $scope.getBenefit();
                    $scope.getEnrollmentData();

                    if ($scope.showTab == "shipment") {
                        $('#orders').addClass('active');
                        $('#orders').click();

                    } else if ($scope.showTab == "document") {
                        $('#Documents').addClass('active');
                        $('#Documents').click();

                    } else {
                        $('#enrollment').addClass('active');
                        $('#enrollment').click();
                    }
                    $scope.PatientProfileDataSpinner = false;
                }).error(function (data, status, headers, config) {
                    $scope.PatientProfileDataSpinner = false;
                });
            $scope.getAllCaseIds();
            $scope.getDocuments();
            $scope.getAlerts();
        }
        $scope.showPatientMilestonesNoActivity = false;
        $scope.getPatientMilestone = function () {
            var reqData = {
                "PortalId": config.PortalId,
                "SiteUserId": config.SiteUserId,
                "PatientId": parseInt($scope.patientId),
                "CaseId": parseInt($scope.caseId),
                "ClinicId": utils.getCookie("ClinicId")
            };

            baseRxcServices.PostQuery(config.PatientProfile.GetPatientProfileByCaseId.API + config.PatientProfile.GetPatientProfileByCaseId.URL, reqData)
                .success(function (data, status, headers, config) {
                    $scope.PatientMilestones = data.PatientMilestones.PatientMilestones;

                    $scope.showPatientMilestonesNoActivity = (!$scope.PatientMilestones || $scope.PatientMilestones.length == 0);

                    //$scope.PatientmilestoneDataSpinner = false;
                }).error(function (data, status, headers, config) {
                    //$scope.PatientmilestoneDataSpinner = false;
                });
        };

        $scope.Pagination = {};
        $scope.Pagination.PageNo = 1;
        $scope.Pagination.PageSize = 10;
        $scope.Pagination.SortExpr = '';
        $scope.Pagination.SortDir = '';

        page_num = 1;
        sortBy = 'ASC';
        sortColumn = 'PatientName';
        var items = $("enrollmentTable table tbody tr");

        $scope.RefreshDetails = function (caseId) {
            $scope.caseId = caseId;
            $scope.getDocuments();
            $scope.getPatientMilestone();
            $scope.getAlerts();
            var reqData = {
                "PortalId": config.PortalId,
                "SiteUserId": config.SiteUserId,
                "PatientId": parseInt($scope.patientId),
                "CaseId": parseInt($scope.caseId),
                "ClinicId": utils.getCookie("ClinicId")
            };
            $scope.demographic = true;
            baseRxcServices.PostQuery(config.PatientProfile.GetPatientProfileByCaseId.API + config.PatientProfile.GetPatientProfileByCaseId.URL, reqData)
                .success(function (data, status, headers, config) {
                    $scope.patientProfileData = data;

                    if (!validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientDemographics) && !validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientDemographics.PatientDemographics)) {
                        $scope.demographic = false;
                        $scope.patientDetails = $scope.patientProfileData.PatientDemographics.PatientDemographics;
                    }
                    if (!validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientMilestones) && !validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientMilestones.PatientMilestones)) {
                        $scope.demographic = false;
                        $scope.patientMilestonesCount = $scope.patientProfileData.PatientMilestones.PatientMilestones.length;
                        $scope.patientMilestones = [$scope.patientProfileData.PatientMilestones.PatientMilestones[0]];
                    }


                    $scope.getPrescriptionInfo();
                    //$scope.getDocuments();
                    $scope.getInsurance();
                    $scope.getBenefit();
                    $scope.getEnrollmentData();

                    setTimeout(function () {
                        $('#enrollment').click();
                    }, 200);

                    if ($scope.showTab == "shipment") {
                        $('#orders').addClass('active');
                        $('#orders').click();

                    } else if ($scope.showTab == "document") {
                        $('#Documents').addClass('active');
                        $('#Documents').click();

                    } else {
                        $('#enrollment').addClass('active');
                    }
                    $scope.demographic = false;
                }).error(function (data, status, headers, config) {
                    $scope.demographic = false;

                });

        };
        $scope.getAlerts = function () {
            var reqData = {
                "SiteUserid": config.SiteUserId,
                "PortalId": config.PortalId,
                "ClinicId": (utils.getCookie("ClinicId")) ? JSON.parse(utils.getCookie("ClinicId")) : 0
            };
            if ($scope.patientId)
                reqData.PatientId = $scope.patientId;
            if ($scope.caseId)
                reqData.CaseId = $scope.caseId;

            baseRxcServices.PostQuery(config.AlertNotifications.GetAlertsAndNotifications.API + config.AlertNotifications.GetAlertsAndNotifications.URL, reqData)
                .success(function (data, status, headers, configs) {

                    $scope.patientAlertsCount = data.Alerts ? data.Alerts.length : 0;
                }).error(function (data, status, headers, config) {
                });
        }
        $scope.getEnrollmentData = function () {    //(clickOnButton) now did
            if (!validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientEnrollments) && !validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientEnrollments.PatientEnrollments)) {
                $scope.getNgPatientEnrollment = $scope.patientProfileData.PatientEnrollments.PatientEnrollments;
                $scope.TotalRows = $scope.getNgPatientEnrollment.length;
            }
            else {
                $scope.emptyRecordenrollment = true;
                $scope.getNgPatientEnrollment = 0;
            }
            var numItems = items.length;
            if (numItems == 0) {
                var patientId = $('#patientId').val();
                var caseId = $('#caseId').val();
            }
        }

        $scope.getPrescriptionInfo = function (tab) {

            if (!validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientPrescriptions) && !validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientPrescriptions.PatientPrescriptions)) {
                $scope.getPrescriptionInfoByCaseId = $scope.patientProfileData.PatientPrescriptions.PatientPrescriptions;
                $scope.TotalRows = $scope.getPrescriptionInfoByCaseId.length;
            }
            else {
                $scope.emptyRecordprescption = true;
                $scope.TotalRows = 0;
            }

        }

        $scope.getInsurance = function (tab) {
            if (!validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientInsurance) && !validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientInsurance.PatientInsurance)) {
                $scope.getInsuranceInfo = $scope.patientProfileData.PatientInsurance.PatientInsurance;
                $scope.TotalRows = $scope.getInsuranceInfo.length;
            }
            else {
                $scope.emptyRecordinsurance = true;
                $scope.TotalRows = 0
            }

        }

        $scope.getDocuments = function (tab) {
            var reqData = {
                "PortalId": config.PortalId,
                "SiteUserId": config.SiteUserId,
                "PatientId": parseInt($scope.patientId),
                "CaseId": parseInt($scope.caseId),
                "ActivityMethod": "Web",
                "PageSearchCriteria": {}
            };

            baseRxcServices.PostQuery(config.PatientProfile.GetPatientUploadedDocumentsByCaseId.API + config.PatientProfile.GetPatientUploadedDocumentsByCaseId.URL, reqData)
                .success(function (data, status, headers, config) {
                    $scope.getDocumentsInfo = data.DocumentsResponse;
                    $scope.TotalRows = data.DocumentsResponse.length;
                    if ($scope.TotalRows == 0)
                        $scope.emptyRecordLabelShow = true;
                    if (tab)
                        activeProfileTab(tab);
                });
        };

        $scope.getBenefit = function (tab) {
            $scope.benefiterrmsg = false;
            if (!validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientBenefits) && !validate.isNullOrEmptyOrUndefined($scope.patientProfileData.PatientBenefits.PatientBenefits)) {
                $scope.getBenefitInfo = $scope.patientProfileData.PatientBenefits.PatientBenefits;
                $scope.TotalRows = $scope.getBenefitInfo.length
            } else {
                $scope.TotalRows = 0;
            }

            if ($scope.getBenefitInfo.length > 0) {
                if (($scope.getBenefitInfo[0].CaseReferralType == 'BenInvest' || $scope.getBenefitInfo[0].CaseReferralType == 'RenewalBI')) {
                    $scope.showbenefit = false;
                }
            }

            //$scope.TotalRows = $scope.getBenefitInfo ? $scope.getBenefitInfo.length : 0;

            if (validate.isNullOrEmptyOrUndefined($scope.getBenefitInfo)) {
                $scope.benefiterrmsg = true;
            } else {
                if ($scope.getBenefitInfo.length > 0) {
                    $scope.summaryBenefits = $scope.getBenefitInfo[0].SummaryBenefits;
                    if ($scope.summaryBenefits == null || $scope.summaryBenefits == 'undefined' || $scope.summaryBenefits == '') {
                        $scope.benefiterrmsg = true;
                    }
                    if (!validate.isNullOrEmptyOrUndefined($scope.getBenefitInfo[0].PayorName)) {
                        $scope.benefitName = $scope.getBenefitInfo[0].PayorName;
                        return true;
                    } else if (!validate.isNullOrEmptyOrUndefined($scope.getBenefitInfo[0].PBMName)) {
                        $scope.benefitName = $scope.getBenefitInfo[0].PBMName;
                        return true;
                    } else {
                        $scope.benefitName = '';
                    }
                } else {
                    $scope.benefitName = '';
                }
            }
        }

        $(".nav-tabs li a").click(function () {

            var tab = $(this).attr('id');
            if ("#" + tab === '#enrollment') {
                $('#requestHistory').removeClass('active');
                $('#prescription').removeClass(' active');
                $('#orders').removeClass(' active');
                $('#insurance').removeClass(' active');
                $('#nurseVisit').removeClass(' active');
                $('#Documents').removeClass(' active');
                $('#Benefits').removeClass(' active');
                $("#" + tab).addClass('active')
                activeProfileTab(tab);

            }
            else if ("#" + tab === '#insurance') {
                $('#enrollment').removeClass('active');
                $('#prescription').removeClass(' active');
                $('#requestHistory').removeClass('active');
                $('#orders').removeClass(' active');
                $('#nurseVisit').removeClass(' active');
                $('#Documents').removeClass(' active');
                $('#Benefits').removeClass(' active');
                $("#" + tab).addClass('active');

                activeProfileTab(tab);

            }
            else if ("#" + tab === '#prescription') {
                $('#enrollment').removeClass(' active');
                $('#requestHistory').removeClass(' active');
                $('#orders').removeClass(' active');
                $('#insurance').removeClass(' active');
                $('#nurseVisit').removeClass(' active');
                $('#Documents').removeClass(' active');
                $('#Benefits').removeClass(' active');
                $("#" + tab).addClass(' active');
                activeProfileTab(tab);

            }
            else if ("#" + tab === '#Documents') {
                $('#enrollment').removeClass(' active');
                $('#requestHistory').removeClass(' active');
                $('#orders').removeClass(' active');
                $('#insurance').removeClass(' active');
                $('#prescription').removeClass(' active');
                $('#nurseVisit').removeClass(' active');
                $('#Benefits').removeClass(' active');
                $("#" + tab).addClass(' active');
                activeProfileTab(tab);
            }
            else {
                $('#enrollment').removeClass(' active');
                $('#prescription').removeClass(' active');
                $('#requestHistory').removeClass(' active');
                $('#nurseVisit').removeClass(' active');
                $('#insurance').removeClass(' active');
                $('#orders').removeClass(' active');
                $('#Documents').removeClass(' active');
                $("#" + tab).addClass(' active');
                //$scope.getBenefit(tab);

                activeProfileTab(tab);
            }
        });

        $(".nav-tabs1 li a").click(function () {

            var tab = $(this).attr('id');
            if ("#" + tab === '#enrollment1') {
                $('#requestHistory1').removeClass('active');
                $('#prescription1').removeClass(' active');
                $('#orders1').removeClass(' active');
                $('#insurance1').removeClass(' active');
                $('#nurseVisit1').removeClass(' active');
                $('#Documents1').removeClass(' active');
                $('#Benefits1').removeClass(' active');
                $("#" + tab).addClass('active')
                activeProfileTab1(tab);

            }
            else if ("#" + tab === '#insurance1') {
                $('#enrollment1').removeClass('active');
                $('#prescription1').removeClass(' active');
                $('#requestHistory1').removeClass('active');
                $('#orders1').removeClass(' active');
                $('#nurseVisit1').removeClass(' active');
                $('#Documents1').removeClass(' active');
                $('#Benefits1').removeClass(' active');
                $("#" + tab).addClass('active');

                activeProfileTab1(tab);

            }
            else if ("#" + tab === '#prescription1') {
                $('#enrollment1').removeClass(' active');
                $('#requestHistory1').removeClass(' active');
                $('#orders1').removeClass(' active');
                $('#insurance1').removeClass(' active');
                $('#nurseVisit1').removeClass(' active');
                $('#Documents1').removeClass(' active');
                $('#Benefits1').removeClass(' active');
                $("#" + tab).addClass(' active');
                activeProfileTab1(tab);

            }
            else if ("#" + tab === '#Documents1') {
                $('#enrollment1').removeClass(' active');
                $('#requestHistory1').removeClass(' active');
                $('#orders1').removeClass(' active');
                $('#insurance1').removeClass(' active');
                $('#prescription1').removeClass(' active');
                $('#nurseVisit1').removeClass(' active');
                $('#Benefits1').removeClass(' active');
                $("#" + tab).addClass(' active');
                activeProfileTab1(tab);
            }
            else {
                $('#enrollment1').removeClass(' active');
                $('#prescription1').removeClass(' active');
                $('#requestHistory1').removeClass(' active');
                $('#nurseVisit1').removeClass(' active');
                $('#insurance1').removeClass(' active');
                $('#orders1').removeClass(' active');
                $('#Documents1').removeClass(' active');
                $("#" + tab).addClass(' active');
                //$scope.getBenefit(tab);

                activeProfileTab1(tab);
            }
        });
        pagecount = 0;
        isInitPageNo = 0;

        function activeProfileTab(tab) {

            var currentTab = "#" + tab + "Con";
            var currentTable = tab + "Table";
            if (currentTab === '#enrollmentCon') {
                $('#requestHistoryCon').removeClass('in active');
                $('#prescriptionCon').removeClass('in active');
                $('#ordersCon').removeClass('in active');
                $('#insuranceCon').removeClass('in active');
                $('#nurseVisitCon').removeClass('in active');
                $('#DocumentsCon').removeClass('in active');
                $('#BenefitsCon').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();


            }
            else if (currentTab === '#requestHistoryCon') {
                $('#enrollmentCon').removeClass('in active');
                $('#prescriptionCon').removeClass('in active');
                $('#ordersCon').removeClass('in active');
                $('#insuranceCon').removeClass('in active');
                $('#nurseVisitCon').removeClass('in active');
                $('#DocumentsCon').removeClass('in active');
                $('#BenefitsCon').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();

            }
            else if (currentTab === '#prescriptionCon') {
                $('#enrollmentCon').removeClass('in active');
                $('#requestHistoryCon').removeClass('in active');
                $('#ordersCon').removeClass('in active');
                $('#insuranceCon').removeClass('in active');
                $('#nurseVisitCon').removeClass('in active');
                $('#DocumentsCon').removeClass('in active');
                $('#BenefitsCon').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();
            }
            else if (currentTab === '#insuranceCon') {
                $('#enrollmentCon').removeClass('in active');
                $('#requestHistoryCon').removeClass('in active');
                $('#ordersCon').removeClass('in active');
                $('#prescriptionCon').removeClass('in active');
                $('#nurseVisitCon').removeClass('in active');
                $('#DocumentsCon').removeClass('in active');
                $('#BenefitsCon').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();
            }
            else if (currentTab === '#nurseVisitCon') {
                $('#enrollmentCon').removeClass('in active');
                $('#requestHistoryCon').removeClass('in active');
                $('#ordersCon').removeClass('in active');
                $('#insuranceCon').removeClass('in active');
                $('#prescriptionCon').removeClass('in active');
                $('#DocumentsCon').removeClass('in active');
                $('#BenefitsCon').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();
            }
            else if (currentTab === '#ordersCon') {
                $('#enrollmentCon').removeClass('in active');
                $('#prescriptionCon').removeClass('in active');
                $('#requestHistoryCon').removeClass('in active');
                $('#nurseVisitCon').removeClass('in active');
                $('#insuranceCon').removeClass('in active');
                $('#DocumentsCon').removeClass('in active');
                $('#BenefitsCon').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();
            }
            else if (currentTab === '#DocumentsCon') {
                $('#enrollmentCon').removeClass('in active');
                $('#prescriptionCon').removeClass('in active');
                $('#requestHistoryCon').removeClass('in active');
                $('#nurseVisitCon').removeClass('in active');
                $('#insuranceCon').removeClass('in active');
                $('#ordersCon').removeClass('in active');
                $('#BenefitsCon').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();
            }
            else {
                $('#enrollmentCon').removeClass('in active');
                $('#prescriptionCon').removeClass('in active');
                $('#requestHistoryCon').removeClass('in active');
                $('#nurseVisitCon').removeClass('in active');
                $('#insuranceCon').removeClass('in active');
                $('#ordersCon').removeClass('in active');
                $('#DocumentsCon').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();
            }

        }

        function activeProfileTab1(tab) {

            var currentTab = "#" + tab + "Con";
            var currentTable = tab + "Table";
            if (currentTab === '#enrollment1Con') {
                $('#requestHistory1Con').removeClass('in active');
                $('#prescription1Con').removeClass('in active');
                $('#orders1Con').removeClass('in active');
                $('#insurance1Con').removeClass('in active');
                $('#nurseVisit1Con').removeClass('in active');
                $('#Documents1Con').removeClass('in active');
                $('#Benefits1Con').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();


            }
            else if (currentTab === '#prescription1Con') {
                $('#enrollment1Con').removeClass('in active');
                $('#requestHistory1Con').removeClass('in active');
                $('#orders1Con').removeClass('in active');
                $('#insurance1Con').removeClass('in active');
                $('#nurseVisit1Con').removeClass('in active');
                $('#Documents1Con').removeClass('in active');
                $('#Benefits1Con').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();
            }
            else if (currentTab === '#insurance1Con') {
                $('#enrollment1Con').removeClass('in active');
                $('#requestHistoryCon').removeClass('in active');
                $('#orders1Con').removeClass('in active');
                $('#prescription1Con').removeClass('in active');
                $('#nurseVisit1Con').removeClass('in active');
                $('#Documents1Con').removeClass('in active');
                $('#Benefits1Con').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();
            }

            else if (currentTab === '#Documents1Con') {
                $('#enrollment1Con').removeClass('in active');
                $('#prescription1Con').removeClass('in active');
                $('#requestHistory1Con').removeClass('in active');
                $('#nurseVisit1Con').removeClass('in active');
                $('#insurance1Con').removeClass('in active');
                $('#orders1Con').removeClass('in active');
                $('#Benefits1Con').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();
            }
            else {
                $('#enrollment1Con').removeClass('in active');
                $('#prescription1Con').removeClass('in active');
                $('#requestHistory1Con').removeClass('in active');
                $('#nurseVisit1Con').removeClass('in active');
                $('#insurance1Con').removeClass('in active');
                $('#orders1Con').removeClass('in active');
                $('#Documents1Con').removeClass('in active');
                $(currentTab).addClass('in active');
                $(currentTab).show();
            }

        }
        function loadPatientTableGrid(id, searchString, patientId, caseId) {
            patientId = patientId;
            caseId = caseId;
            loadTableGrid(false, id, searchString);
        }
        var sortBy = 'ASC';
        var sortColumn = '';
        var page_num = 1;
        var pageSize = 10;
        var searchParam = '';
        visiblePages = 6;
        isArchive = false;
        function loadTableGrid(fromSort, id, searchString, physicianIdForAdmin) {
            searchVal = searchString;
            //id =  id.split("#")[1];

            isSorting = fromSort;
            table_id = id;
            if (physicianIdForAdmin != null)
                physicianIdForPatientGrid = physicianIdForAdmin;

            initPageNumbers(sortBy, sortColumn);

        }

        function initPageNumbers(sortBy, sortColumn) {
            //Get total rows number
            var pageNo = 0;
            var itemsPerPage = 10;
            var gridId = table_id;
            if (gridId == 'BenefitsTable') {
                var BenefitsData = $scope.getBenefitInfo;
                var docExists = $scope.getBenefitInfo[0].SummeryBenefits;
                if (docExists) {
                    $("#biMessage").hide();
                    $("#biDocDiv").show();
                } else {
                    $("#biDocDiv").hide();
                    $("#biMessage").show();
                }
                if (BenefitsData != null) {
                    if (BenefitsData[0].BenefitInvestigationDate == null) {
                        $('#biDate').text('');
                    } else {
                        $('#biDate').text(BenefitsData[0].BenefitInvestigationDate);
                    }
                    $('#payerName').text(BenefitsData[0].PayorName);
                    $('#planName').text(BenefitsData[0].PlanName);
                    $('#insuranceStatus').text(BenefitsData[0].InsuranceStatus);
                    $('#coverageStatus').text(BenefitsData[0].CoverageStatus);
                    $('#eligibility').text(BenefitsData[0].NordiSureEligiblity);
                }
                $('.norecordsrequest').removeClass('showDiv').addClass('hideDiv');
            }
            if (searchParam == '') {
                total_rows = parseInt($scope.TotalRows);

            } else {
                if (data.jsonresult.obj.gridData != null) {
                    total_rows = parseInt($scope.getNgPatientEnrollment.length);
                } else {
                    total_rows = 0;
                }

            }
            pagecount = Math.ceil(total_rows / itemsPerPage);
            $('#page-numbers').html('');
            var count = 1;
            if (gridId != 'BenefitsTable') {
                if (total_rows > 0) {
                    $('#page-numbers').append('<li class="inline pull-left"><a id="Prev" onclick="getPrevPage(' + pagecount + ')"> <i class="fa fa-angle-double-left fa-lg"></i> </a></li>');

                    for (var x = 0; x < total_rows; x += itemsPerPage) {
                        if (count <= visiblePages) {
                            $('#page-numbers').append('<li class="inline pull-left"><a id="' + count + '" onclick="getPage(' + count + ',' + pagecount + ')">' + count + '</a></li>');
                        }

                        count++;
                    }

                    $('#page-numbers').append('<li class="inline pull-left"><a id="Next" onclick="getNextPage(' + pagecount + ')"> <i class="fa fa-angle-double-right fa-lg"></i> </a></li>');
                    $('#pagination ul li:nth-child(2) a').addClass('paginate');
                    $('#pagination ul li:nth-child(1) a').removeClass('pagination').addClass('disabled');
                    page_num = 1;
                    $('.tablerequest').removeClass('hideDiv').addClass('showDiv');
                    $('.norecordsrequest').removeClass('showDiv').addClass('hideDiv');

                    //we already have the array of rows, just pass in that object so we can render the tables
                    getPage(page_num, pagecount);
                }
                else {
                    $('.norecordsrequest').removeClass('hideDiv').addClass('showDiv');
                    $('.tablerequest').removeClass('showDiv').addClass('hideDiv');
                }
            }

        }

        function getPage(page_number, pagecount) {
            //Clear the existing data view

            page_num = page_number;
            if (page_num == 1 && page_num != pagecount) {
                $('#pagination ul li:nth-child(1) a').removeClass('pagination').addClass('disabled');

            } else if (page_num != 1 && page_num == pagecount) {
                $('#pagination ul li:nth-child(' + (page_num + 2) + ') a').addClass('disabled').removeClass('pagination');
            } else if (page_num != 1 && page_num != pagecount) {
                $('#pagination ul li:nth-child(1) a').addClass('pagination').removeClass('disabled');
                $('#pagination ul li:nth-child(' + (pagecount + 2) + ') a').addClass('pagination').removeClass('disabled');
            } else if (page_num == 1 && page_num == pagecount) {
                $('#pagination ul li:nth-child(' + (pagecount + 2) + ') a').addClass('disabled').removeClass('pagination');
                $('#pagination ul li:nth-child(1) a').removeClass('pagination').addClass('disabled');

            }
            $('#pagination ul li a').removeClass('paginate');
            if (page_number <= visiblePages) {
                $('#pagination ul li:nth-child(' + (page_number + 1) + ') a').addClass('paginate');
            } else {
                $('#pagination ul li:nth-child(7) a').addClass('paginate');
            }

            //Get subset of data
            var grid = table_id;

            //Loop through each row and output the data

            if ($scope.TotalRows === 0) {
                $('#errorMessage').show();
            } else {
                $('#errorMessage').hide();

                //Loop through each row and output the data

                if (grid == 'enrollmentTable') {
                    var GridData = $scope.getNgPatientEnrollment;
                } else if (grid == 'prescriptionTable') {
                    var GridData = $scope.getPrescriptionInfoByCaseId;
                } else if (grid == 'insuranceTable') {
                    var GridData = $scope.getInsuranceInfo;
                } else if (grid == 'DocumentsTable') {
                    var GridData = $scope.getDocumentsInfo;
                } else {
                    var GridData = $scope.getBenefitInfo;
                }

                if (GridData != null && grid != 'BenefitsTable') {
                    drawTable(GridData, grid);
                } else {
                    if (grid != 'BenefitsTable') {
                        $('.norecordsrequest').removeClass('hideDiv').addClass('showDiv');
                    } else {
                        $('.norecordsrequest').removeClass('showDiv').addClass('hideDiv');
                    }
                }
            }
        }

        function drawTable(data, id) {


            id = "#" + id;
            if (!isSorting) {


                if (id == '#ordersTable' || id == '#patientTable' || id == '#enrollmentTable' || id == '#insuranceTable' || id == '#prescriptionTable' || id == '#DocumentsTable' || id == '#nurseVisitTable') {
                    $(id).html('');
                } else {
                    $(id + ' tbody').html('');
                }
                var row = $("<tr>");
                if (data.length > 0) {


                    $(id).append(row);

                    if (isArchive) {
                        something = 1;
                    } else {
                        something = 0;
                    }

                    if (id == '#DocumentsTable') {
                        row.append($("<th class='up' onclick='sort(this);'>File Name</th><th class='up' onclick='sort(this);'>File Description</th><th class='up' onclick='sort(this);'>Document Type</th><th class='up' onclick='sort(this);'>User</th><th class='up' onclick='sort(this);'>Date</th><th class='up' onclick='sort(this);'>Action</th>"));
                    }
                    if (id != '#PatientSummaryGrid' && id != '#DocumentsTable' && id != '#BenefitsTable') {
                        $.each(data[0], function (k, v) {
                            if (id == '#PatientRequestGrid' && something == 0 && isArchive == false) {
                                row.append($("<th class='myReqCheckbox' style='cursor:pointer;'></th>"));
                                something = 1;
                            } else if (id == '#PatientRequestGrid' && something == 1 && isArchive == true) {
                                $('table tr th:first-child ').hide();
                                something = 0;
                            }

                            else if (id == '#patientTable' && something == 0) {
                                if (k == "PatientDateofBirth") {
                                    k = "Patient Date of Birth";
                                    row.append($("<th class='up' id='PatientDateofBirth' onclick='sort(this);' style='cursor:pointer;'>" + k + "</th>"));
                                } else if (k == "CaseId") {
                                } else if (k == "PatientId") {
                                    k = "Patient ID";
                                    row.append($("<th class='up' id='PatientId' onclick='sort(this);' style='cursor:pointer;'>" + k + "</th>"));
                                } else if (k == "PatientName") {
                                    k = "Patient Name";
                                    row.append($("<th class='up' id='PatientName' onclick='sort(this);' style='cursor:pointer;'>" + k + "</th>"));
                                } else if (k == "ApplicationDate") {
                                    k = "Enrollment Date";
                                    row.append($("<th class='up' id='ApplicationDate' onclick='sort(this);' style='cursor:pointer;'>" + k + "</th>"));
                                } else if (k == "Status") {
                                    k = "Status";
                                    row.append($("<th class='up' id='Status' onclick='sort(this);' style='cursor:pointer;'>" + k + "</th><th>Select</th>"));
                                } else if (k == "PhysicianName" || k == "ProductName" || k == "IsMileStoneCreated") {

                                } else {
                                    row.append($("<th class='up' onclick='sort(this);' style='cursor:pointer;'>" + k + "</th>"));
                                }

                            } else {
                                var columnID = k;
                                if (id == '#enrollmentTable' && (k == 'EnrollmentDate' || k == 'LastReferralDate')) { }
                                else if ((id == '#prescriptionTable' || id == '#nurseVisitTable' || id == '#insuranceTable') && (k == 'ROWNUMBER')) { }
                                else {
                                    if (id == '#enrollmentTable' && k == 'startdate') {
                                        k = 'Program Start Date';
                                    }
                                    else if (id == '#enrollmentTable' && k == 'enddate') {
                                        k = 'Program End Date';
                                    }
                                    else if (id == '#enrollmentTable' && k == 'Product') {
                                        k = 'Product';
                                    }
                                    else if (id == '#prescriptionTable' && k == 'ProductDescription') {
                                        k = 'Product Description';
                                    }
                                    else if (id == '#prescriptionTable' && k == 'NumberofRefills') {
                                        k = 'Number of Refill';
                                    }
                                    else if (id == '#prescriptionTable' && k == 'PrescribingPhysician') {
                                        k = 'Prescribing Physician';
                                    }
                                    else if (id == '#nurseVisitTable' && k == 'InitiationDate') {
                                        k = 'Nurse Visit Initiation Date';

                                    }
                                    else if (id == '#nurseVisitTable' && k == 'CompleteDate') {
                                        k = 'Nurse Visit Complete Date';

                                    }
                                    else if (id == '#nurseVisitTable' && k == 'NurseStatus') {
                                        k = 'Status';

                                    }
                                    else if (id == '#insuranceTable' && k == 'PBMName') {
                                        k = 'PBM or Medical';
                                    } else if (id == '#insuranceTable' && k == 'PARequired') {
                                        k = 'Prior Authorization Required?';
                                    } else if (id == '#insuranceTable' && k == 'PAEndDate') {
                                        k = 'PA End Date';
                                    } else if (id == '#insuranceTable' && k == 'PayorName') {
                                        k = 'Payor Name';
                                    } else if (id == '#insuranceTable' && k == 'PolicyHolderName') {
                                        k = 'Policy Holder Name';
                                    } else if (id == '#insuranceTable' && k == 'PolicyHolderName') {
                                        k = 'Policy Holder Name';
                                    } else if (id == '#ordersTable' && k == 'DateFilledBySPP') {
                                        k = 'Date filled by SPP';
                                    } else if (id == '#ordersTable' && k == 'DateTraigedtoSPP') {
                                        k = 'Date triaged to SPP';
                                    }
                                    else if (id == '#ordersTable' && k == 'ProductDescription') {
                                        k = 'Product Description';
                                    }
                                    else {
                                        k = k.split(/(?=[A-Z])/).join(" ");
                                    }
                                    if (id == '#enrollmentTable') {
                                        if (k != "Case Id" && k != "Last Therapy Start Date") {
                                            row.append($("<th class='up' id=" + columnID + " onclick='sort(this);' style='cursor:pointer;'>" + k + "</th>"));
                                        }

                                    } else {

                                        row.append($("<th class='up' id=" + columnID + " onclick='sort(this);' style='cursor:pointer;'>" + k + "</th>"));
                                    }


                                }
                            }
                        });
                    }


                }
            } else {

                $(id + ' tbody').html('');
                var row = $("<tr>");
                $(id).append(row);
            }


            for (var i = 0; i < data.length; i++) {

                drawRow(data[i], id);

            }


            $('table').each(function () {
                var $this = $(this);

                $this.children('tbody').children().unwrap();
                $this.children('tr:has(th)').wrapAll('<thead>');
                $this.children('tr:has(td)').wrapAll('<tbody>');
            });

        }

        function drawRow(rowData, id) {
            var ApplicationDropDown = $('#ApplicationDropDown').val();
            var reqStarterKit = localStorage.getItem("selectedAppName");
            var row = $("<tr />");
            var rowArray = [];

            $(id).append(row);
            var mistoneExists = false;
            //this will append tr element to table... keep its reference for a while since we will add cels into it
            $.each(rowData, function (k, v) {
                if (id == "#patientTable" && k == "Status") {
                    rowArray.push(v);
                    rowArray.push('Select');
                } else {
                    if (v == "" || v == null) {
                        v = "";
                    }
                    if (id == "#patientTable" && (k == "PhysicianName" || k == "ProductName")) { }
                    else if ((id == "#PatientSummaryGrid" || id == "#patientTable") && (k == "IsMileStoneCreated")) {
                        mistoneExists = v;
                    } else if (id == '#enrollmentTable' && (k == 'EnrollmentDate' || k == 'LastReferralDate' || k == 'LastTherapyStartDate')) { }
                    else if (id == '#enrollmentTable' && (k == 'CaseId')) { }
                    else if ((id == '#prescriptionTable' || id == '#nurseVisitTable' || id == '#insuranceTable') && (k == 'ROWNUMBER')) {

                    }

                    else {
                        rowArray.push(v);
                    }

                }

            });

            for (var i = 0; i < rowArray.length; i++) {
                if (id == '#PatientSummaryGrid' && i == 0)
                    row.append($("<td><a style='color:#428bca !important;' href='/PatientSummary/PatientDemographics?patientId=" + rowArray[0] + "&caseId=" + rowArray[3] + "' >" + rowArray[1] + "</a></td>"));
                else if (id == '#PatientRequestGrid' && i == 0 && isArchive == false)
                    row.append($("<td><input type=\"checkbox\" class='myReqCheckbox' value='" + rowArray[3] + "'></td>"));

                else if (id == '#PatientRequestGrid' && i == 0 && isArchive == true) {
                    row.append($("<td ><input type=\"checkbox\" class='myReqCheckbox' value='" + rowArray[3] + "'></td>"));
                    $('table tr td:first-child ').hide();
                } else if (id == '#PatientRequestGrid' && i == 1)
                    row.append($("<td><a style='color:#428bca !important;' href='/PatientSummary/PatientDemographics?id=" + rowArray[0] + "' >" + rowArray[i] + "</a></td>"));
                else if (id == '#patientTable' && i == 6) {
                    row.append($("<td><a style='color:#428bca !important;' onclick='selectedExistingPatientLink(" + rowArray[0] + "," + rowArray[3] + "," + ApplicationDropDown + ",\"" + reqStarterKit + "\"," + true + ")' >" + rowArray[6] + "</a></td>"));
                }
                else {
                    if (id == '#DocumentsTable') {
                        if (i == 0)
                            row.append($("<td class='text-left'>" + rowArray[0] + "</td>"));
                        else if (i == 1)
                            row.append($("<td class='text-left'>" + rowArray[0] + "</td>"));
                        else if (i == 2)
                            row.append($("<td class='text-left'>" + rowArray[2] + "</td>"));
                        else if (i == 3)
                            row.append($("<td class='text-left'>" + rowArray[4] + "</td>"));
                        else if (i == 4)
                            row.append($("<td class='text-left'>" + rowArray[5] + "</td>"));
                        else if (i == 5)
                            row.append($("<td class='text-left'><img id='" + rowArray[3] + "' class='action' style='cursor:pointer;' src='../Images/download_icon.png'  /></td>"));

                    }
                    else if (id == '#PatientSummaryGrid') {
                        if (i == 1)
                            row.append($("<td class='text-left'>" + rowArray[3] + "</td>"));
                        else if (i == 2)
                            row.append($("<td class='text-left'>" + rowArray[0] + "</td>"));
                        else if (i == 3)
                            row.append($("<td class='text-left'>" + rowArray[6] + "</td>"));
                        else if (i == 4)
                            row.append($("<td class='text-left'>" + rowArray[2] + "</td>"));
                        else if (i == 5)
                            row.append($("<td class='text-left'>" + rowArray[4] + "</td>"));
                        else if (i == 6)
                            if (mistoneExists) {
                                row.append($("<td class='text-left'><a style='color:#428bca !important;' href='/PatientSummary/PatientMilestone?patientId=" + rowArray[0] + "&caseId=" + rowArray[3] + "'>" + rowArray[5] + "</a></td>"));
                            } else {
                                row.append($("<td class='text-left'>" + rowArray[5] + "</td>"));
                            }

                    } else {

                        row.append($("<td class='text-left'>" + rowArray[i] + "</td>"));
                    }

                }
            }

        }


        $scope.CaseIds = [];
        $scope.getAllCaseIds = function () {
            var reqData = {
                "PortalId": config.PortalId,
                "SiteUserId": config.SiteUserId,
                "PatientId": $scope.patientId
            };
            baseRxcServices.PostQuery(config.PatientProfile.GetPatientCasesByCaseId.API + config.PatientProfile.GetPatientCasesByCaseId.URL, reqData)
                .success(function (data, header, status, config) {
                    if (data.PatientCasesData) {
                        $scope.CaseIds = data.PatientCasesData
                    }
                }).error(function (data, status, headers, config) {
                    return false;
                });
        };

        $scope.downloadFiles = function (arg) {
            var nameindex = arg.lastIndexOf('\\');
            var filedetail = arg.substring(nameindex + 1);

            var extension = arg.lastIndexOf(".");
            arg = arg.substring(0, extension) + arg.substring(extension).toLowerCase();
            var extensionName = arg.substring(extension);

            var reqData = {
                "FilePath": encodeURI(arg)
            };
            baseRxcServices.DownloadQuery(config.GetFile.DownloadFile.API + config.GetFile.DownloadFile.URL, reqData)
                .success(function (data, status, headers, config) {
                    var octetStreamMime = 'application/octet-stream';
                    var success = false;
                    //$scope.verifyReportStatusSob();

                    // Get the headers
                    headers = headers();

                    // Get the filename from the x-filename header or default to "download.bin"
                    var filename = headers['content-disposition'] || filedetail;

                    // Determine the content type from the header or default to "application/octet-stream"
                    var contentType = headers['content-type'] || octetStreamMime;

                    try {
                        // Try using msSaveBlob if supported

                        var blob = new Blob([data], {
                            type: contentType
                        });
                        if (navigator.msSaveBlob)
                            navigator.msSaveBlob(blob, filename);
                        else {
                            // Try using other saveBlob implementations, if available
                            var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
                            if (saveBlob === undefined) throw "Not supported";
                            saveBlob(blob, filename);
                        }
                        success = true;

                    } catch (ex) { }

                    if (!success) {
                        // Get the blob url creator
                        var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
                        if (urlCreator) {
                            // Try to use a download link
                            var link = document.createElement('a');
                            if ('download' in link) {
                                // Try to simulate a click
                                try {
                                    // Prepare a blob URL
                                    var blob = new Blob([data], {
                                        type: contentType
                                    });
                                    var url = urlCreator.createObjectURL(blob);
                                    link.setAttribute('href', url);

                                    // Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
                                    link.setAttribute("download", filename);

                                    // Simulate clicking the download link
                                    var event = document.createEvent('MouseEvents');
                                    event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                                    link.dispatchEvent(event);
                                    success = true;

                                } catch (ex) { }
                            }

                            if (!success) {
                                // Fallback to window.location method
                                try {
                                    // Prepare a blob URL
                                    // Use application/octet-stream when using window.location to force download
                                    var applicationType;
                                    if (extensionName == '.pdf') {
                                        applicationType = 'application/pdf';
                                    } else if (extensionName == '.doc') {
                                        applicationType = 'application/msword';

                                    } else if (extensionName == '.docx') {
                                        applicationType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';

                                    } else if (extensionName == '.xls') {
                                        applicationType = 'application/vnd.ms-excel';

                                    } else if (extensionName == '.xlsx') {
                                        applicationType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

                                    } else if (extensionName == '.png') {
                                        applicationType = 'image/png';

                                    } else if (extensionName == '.txt') {
                                        applicationType = 'text/plain';

                                    } else if (extensionName == '.jpg') {
                                        applicationType = 'image/jpg';

                                    } else if (extensionName == '.gif') {
                                        applicationType = 'image/gif';

                                    } else if (extensionName == '.tif' || extensionName == '.tiff') {
                                        applicationType = 'image/tiff';

                                    } else if (extensionName == '.mp4') {
                                        applicationType = 'video/mp4';

                                    }
                                    var blob = new Blob([data], {
                                        type: applicationType
                                    });
                                    var url = urlCreator.createObjectURL(blob);
                                    window.location = url;
                                    success = true;
                                } catch (ex) { }
                            }

                        }
                    }

                    if (!success) {
                        // Fallback to window.open method
                        window.open(httpPath, '_blank', '');
                    }
                }).error(function (data, status, headers, config) {
                    return false;
                });

        }
        $scope.navigateToSecureMessageCompose = function () {
            $scope.patientName = $scope.patientDetails[0].FirstName + ' ' + $scope.patientDetails[0].LastName;

            $location.url('/SecureMsg').search('PatientId', $scope.patientId).search('CaseId', $scope.caseId).search('PatientName', $scope.patientName)
                .search('redirectedFrom', 'PatientProfile').search('sendView', 'Send');
        }

        $scope.navigateToSecureMessageInbox = function () {
            $scope.patientName = $scope.patientDetails[0].FirstName + ' ' + $scope.patientDetails[0].LastName;

            $location.url('/SecureMsg').search('PatientId', $scope.patientId).search('CaseId', $scope.caseId).search('PatientName', $scope.patientName)
                .search('redirectedFrom', 'PatientProfile').search('sendView', 'View');

        }

        $scope.navigateToMilestone = function () {
            $rootScope.milestoneNav = "PatientProfile";
            $location.url('/PatientMilestone').search('PatientId', $scope.patientId).search('CaseId', $scope.caseId).search('NGPhyID', $scope.phyId);
        };

        $scope.navigateToAlerts = function () {
            $location.url('/Alerts').search('PatientId', $scope.patientId).search('CaseId', $scope.caseId);
        }

        $scope.verifyReportStatusSob = function () {

            var object =
               [{
                   "FieldType": "PortalId",
                   "FieldValue": (config.PortalId),
                   "StatisticsId": 0,
                   "StatisticsPrimaryValue": 1,
                   "StatisticsType": "Number of times an SOB was downloaded"
               }
               ];



            baseRxcServices.PostQuery(config.Login.ReportVerification.API + config.Login.ReportVerification.URL, object, config.SiteUserId, config.PortalId, 0)
                  .success(function (data, status, headers, configs) {


                  }).error(function (data, status, headers, config) {
                  });
        }

        $scope.navigateToDashBoard = function () {
            $location.url('/DashBoard');
        }
        $scope.navBack = function () {
            var returnUrl = localStorage.getItem("returnUrl");
            if (returnUrl && returnUrl != 'null') {
                $location.url('/DashBoard');
            }
            else {
                window.history.back();
            }
        };
    }]);