/* Minification failed. Returning unminified contents.
(637,17-28): run-time error JS1292: Strict-mode does not allow duplicate property names: orientation
 */
(function () {
    'use strict';

    window.app = angular
        .module('ZestApp', ['ngSanitize', 'ngStorage', 'ngAnimate', 'ui.bootstrap', 'ui.mask', 'ui.grid', 'ui.grid.pagination', 'ui.grid.autoResize', 'ng.deviceDetector', 'vcRecaptcha', 'toaster', 'naif.base64', 'ui.grid.edit', 'ui.toggle'])
        .constant('broadcast', '')
        .constant('moment', moment)        
        .config(['$httpProvider', function ($httpProvider) {

            $httpProvider.defaults.cache = false;
            if (!$httpProvider.defaults.headers.get) {
                $httpProvider.defaults.headers.get = {};
            }
            // disable IE ajax request caching
            $httpProvider.defaults.headers.get['If-Modified-Since'] = '0';

            $httpProvider.interceptors.push('httpInterceptor');
            $httpProvider.interceptors.push("antiForgeryInterceptor");
            $httpProvider.interceptors.push('documentSvc');
        }])
        .config(['uiMask.ConfigProvider', function (uiMaskConfigProvider) {
            uiMaskConfigProvider.clearOnBlur(false);
            uiMaskConfigProvider.allowInvalidValue(true);
        }]);

    window.app.run(['$window','$rootScope', 'httpService', '$timeout', 'documentSvc', function ($window, $rootScope, httpService, $timeout, documentSvc) {
        $rootScope.recaptcha = {
            siteKey: '6LfhQgwUAAAAAAp1_BWEmthg-MMknryXHfKKSe-R'
        };
        $rootScope.logOut = function () {
            httpService.post(url_logout, null)
                .then(function (response) {
                    $window.location.href = url_login;
                    //$rootScope.menus = [];
                });
        }

        //$rootScope.menus = [];
        //httpService.get(api_navApi).then(function (response2) {
        //    if (response2.data) {
        //        $rootScope.menus = response2.data;
        //    }
        //});

        // set timeout to execute on next digest
        $timeout(function () {
            documentSvc.recalculateHeight();            
        }, 0);
        angular.element($window).on('resize', function () {
            documentSvc.recalculateHeight();
        });

        // dummy method to swallow if not in page with recaptcha directive
        $window.vcRecaptchaApiLoaded = $window.vcRecaptchaApiLoaded || function () {
        };
    }]);

    app.filter("trustUrl", ['$sce', function ($sce) {
        return function (url) {
            return $sce.trustAsResourceUrl(url);
        };
    }]);
})();;
var url_forgotPassword = '/account/forgotpassword';
var url_login = '/account/login';
var url_logout = '/account/logout';
var url_resetPassword = '/account/resetpassword';

var url_userList = '/user/index';

var url_manageEventAttendees = '/admin/events/event/{eventId}/manage';

var api = '/api';
var api_navApi = api + '/navApi';
var api_navApi_helpingHands = api + '/navApi/helpinghands';

var api_lookup_byType = api + '/lookupApi/{0}';

var api_registerHcp = api + '/hcpApi/register';
var api_getHcp_by_userId = api + '/hcpApi/hcpDetailsByUserId/{userId}';
var api_hcp_getHcpDetailsCurrentUser = api + '/hcpApi/GetHcpDetailsCurrentUser';

var api_getMyProfile_byUserId = api + '/profileApi/myProfile/{userId}/{isCDE}';
var api_updateProfile = api + '/profileApi/updateProfile/{userId}';
var api_changeUserName = api + '/profileApi/changeUserName';
var api_changePassword = api + '/profileApi/changePassword';

var api_user_search = api + "/userApi/search/{pageSize}/{pageNo}/{sortFields}?browserTimeZone={0}&keyword={1}";
var api_getRoles = api + '/userApi/getRoles';
var api_getAllRoles = api + '/userApi/getAllRoles';
var api_addNovoUser = api + '/userApi/createUser';
var api_get_nonHCPUser = api + '/userApi/getUser/{id}';
var api_edit_nonHCPUser = api + '/userApi/editUser';
var api_delete_User = api + '/userApi/deleteUser';
var api_add_HCPUser = api + '/userApi/createHCPUser';
var api_user_getHcp = api + '/userApi/getHCPUser/{id}';
var api_user_editHcp = api + '/userApi/editHcpUser';

var api_addPatientDetail = api + '/patientApi/createPatient';
var api_invoices_export = api + '/helpingHandsApi/ExportInvoices';
var api_invoices_revert = api + '/helpingHandsApi/RevertInvoice/{id}';
var api_invoices_approveOrDecline = api + '/helpingHandsApi/ApproveOrDeclineInvoice/{id}/{approveInvoice}';
var api_hcp_getHcpPrograms = api + '/helpingHandsApi/getHcpProgramDetails';

var api_search_invoices = api + '/helpingHandsApi/searchByInvoice/{pageSize}/{pageNo}/{sort}?browserTimeZone={0}&keyword={1}';

var api_getPatientDetail = api + '/patientApi/getPatient/{id}';
var api_editPatientDetail = api + '/patientApi/editPatient';

var api_institution_search = api + '/institutionApi/getFilter?value={0}&exceptIds={1}';
var api_my_patient_search = api + "/patientApi/searchMyPatients/{pageSize}/{pageNo}/{sort}?browserTimeZone={0}&keyword={1}";

var api_helpingHands_registerCDE = api + '/helpingHandsApi/registerCDE';
var api_propertyType_search = api + '/helpingHandsApi/propertyTypeSearch/{value}';
var api_propertyType_values = api + '/helpingHandsApi/getObjectTypeProperty/{propertyType}/{objectId}';
var api_isCde_registered = api + '/helpingHandsApi/isCDERegistered/{userId}';

var api_propertyType_getValue = api + '/lookupApi/propertyValue{id}';
var api_propertyType_getProduct = api + '/programApi/getListProduct/{programId}';
var api_cde_search_byArea = api + '/hcpApi/searchCDEByArea/{pageSize}/{pageNo}/{sort}/{filterArea}';
var api_cde_search_byState = api + '/hcpApi/searchCDEByState/{pageSize}/{pageNo}/{sort}/{filterState}';


var api_property_values = api + '/propertyApi/values/{0}';
var api_doctor_search = api + '/hcpApi/getFilter';
var api_search_doctorByName = api + '/hcpApi/getDoctorByName';
var api_lookup_property = api + "/lookupApi/propertyValue";
var api_patient_add_diabete_program = api + '/patientApi/addDiabetesProgram';
var api_patient_edit_diabete_program = api + '/patientApi/editDiabetesProgram';
var api_product_get = api + "/programApi/getListProduct/{programId}";
var api_patient_add_obesity_program = api + '/patientApi/addObesityProgram';
var api_patient_programs_get = api + "/patientApi/getPrograms/{patientId}";


var api_propertyvalues_search = api + '/propertyApi/values/{propertyId:int?}/{keyword?}';

var api_patient_programs_getObesity = api + "/patientApi/getObesityProgram/{id}";
var api_patient_programs_editObesity = api + '/patientApi/editObesityProgram';
var api_patient_programs_getDiabetes = api + "/patientApi/getDiabetesProgram/{patientProgramId}";
var api_patient_program_visits_search = api + '/patientApi/searchVisits/{patientId}/{programId}/{pageSize}/{pageNo}/{sortFields}?browserTimeZone={0}&keyword={1}';

var api_patient_visit_addDiabetes = api + "/programVisitApi/createDiabetes";
var api_patient_visit_addObesity = api + "/programVisitApi/createObesity";
var api_patient_isCanAddDiabetesProgram = api + '/patientApi/isCanAddDiabetesProgram/{patientId}';
var api_patient_isCanAddObesityProgram = api + '/patientApi/isCanAddObesityProgram/{patientId}';

var api_patient_visit_getDiabetes = api + "/programVisitApi/getDiabetes/{patientProgramVisitId}";
var api_patient_visit_getObesity = api + "/programVisitApi/getObesity/{patientProgramVisitId}";

var api_patient_visit_editDiabetes = api + "/programVisitApi/editDiabetes";
var api_patient_visit_editObesity = api + "/programVisitApi/editObesity";
var api_patient_visit_deleteObesity = api + "/programVisitApi/deleteObesity";
var api_patient_visit_deleteDiabetes = api + "/programVisitApi/deleteDiabetes";

var api_invoice_search = api + '/invoiceApi/search';
var api_patient_visit_getRemainingHours = api + "/programVisitApi/getSupportTimeRemainHour/{patientProgramId}";
var api_patient_visit_getRemainingMinutes = api + "/programVisitApi/GetSupportTimeRemainMinute/{patientProgramId}";
var api_patient_visit_edit_getRemainingHours = api + "/programVisitApi/getSupportTimeRemainHour/{patientProgramId}/{patientProgramVisitId?}";
var api_patient_visit_edit_getRemainingMinutes = api + "/programVisitApi/GetSupportTimeRemainMinute/{patientProgramId}/{patientProgramVisitId?}";
var api_patient_visit_getSupportTimeUsageMinute = api + "/programVisitApi/getSupportTimeUsageMinute/{patientProgramId}"

var api_invoice_getVisits = api + '/invoiceApi/getVisitTable';
var api_invoice_confirmVisits = api + '/invoiceApi/confirmVisit';
var api_invoice_confirmPaymentDetails = api + '/invoiceApi/confirmPayment';
var api_invoice_finaliseBySystem = api + '/invoiceApi/finaliseBySystem?browserTimeZone={tz}';
var api_invoice_finaliseByUpload = api + '/invoiceApi/finaliseByUpload?browserTimeZone={tz}';
var api_invoice_getPaymentDetails = api + '/invoiceApi/getPayment';
var api_invoice_isCanCreateMonthlyInvoice = api + '/invoiceApi/isCanCreateMonthlyInvoice';

var api_hh_userAdministration_search = api + '/helpingHandsApi/searchUser/{pageSize}/{pageNo}/{sortFields}?keyword={keyword}&browserTimeZone={tz}';
var api_hh_userAdministration_approve = api + '/helpingHandsApi/approveHHUser/{hcpProgramId}';
var api_hh_userAdministration_declined = api + '/helpingHandsApi/declinedHHUser/{hcpProgramId}';
var api_hcp_deletehcpnonuser = api + '/hcpApi/DeleteHcpNonUser/{hcpId}'

var api_add_AddressBook = api + '/addressBookApi/createAddressBook';
var api_get_AddressBook = api + '/addressBookApi/getAddressBook/{id}';
var api_edit_AddressBook = api + '/addressBookApi/editAddressBook';
var api_edit_isAddressAssociatedToPlace = api + '/addressBookApi/isAddressAssociatedToPlace/{id}/{placeType}';

var api_hh_userAdministration_declined = api + '/helpingHandsApi/declinedHHUser/{hcpProgramId}';
var api_add_presenter = api + '/presenterApi/creatPresenter';
var api_get_presenter = api + '/presenterApi/getPresenter/{id}';
var api_edit_presenter = api + '/presenterApi/editPresenter';
var api_presenter_delete = api + '/presenterApi/Delete/{presenterId}';
var api_presenter_associatedToNonDeletedEvent = api + '/presenterApi/isPresenterAssociatedToNonDeletedEvent/{id}';

var api_addressBook_search = api + '/addressBookApi/search';
var api_presenter_search = api + '/presenterApi/search';

var api_event_getLastEventHcp = api + '/eventApi/GetLastEventHcp';
var api_event_getDetail = api + '/eventApi/HcpRegisterGetEventDetail/{eventId}';
var api_event_getEventHcpDetail = api + '/eventApi/GetEventHcpDetail/{eventHcpId}';
var api_event_unInviteHcp = api + '/eventApi/unInviteHcp/{eventHcpId}';

var api_event_getEventType = api + '/eventApi/getEventType';
var api_event_registerEventHcp = api + '/eventApi/RegisterEventHcp';
var api_event_presenter_search = api + '/presenterApi/getFilter?value={0}&exceptIds={1}';
var api_events_hcp = api + '/eventApi/getHCPEvents?id={0}&clientDate={1}';

var api_get_event_detail = api + '/eventApi/getDetail/{id}';
var api_delete_event = api + '/eventApi/delete/{id}';
var api_event_unPublish = api + '/eventApi/unPublish/{id}';
var api_event_publish = api + '/eventApi/publish/{id}/{mail}';
var api_event_publishEditMode = api + '/eventApi/publishEditMode/{id}/{mail}';
var api_addedit_event = api + '/eventApi/AddOrEdit';
var api_get_inviteHCp = api + '/eventApi/getEventInvite/{eventId}';

var api_get_eventVenue_detail = api + '/eventApi/getDateVenue/{eventId}';
var api_event_venue_search = api + '/venueApi/getFilter?value={0}&exceptIds={1}';
var api_addedit_eventVenue = api + '/eventApi/addOrEditDateVenue';

var api_get_eventFlight_detail = api + '/eventApi/getEventFlight/{eventId}';
var api_addedit_eventFlight = api + '/eventApi/addOrEditEventFlight/{eventId}';

var api_event_Accommodation_search = api + '/hotelApi/getFilter?value={0}&exceptIds={1}';
var api_get_eventAccommodation_detail = api + '/eventApi/getAccommodation/{eventId}';
var api_addedit_eventAccommodation = api + '/eventApi/addOrEditAccommodation/{eventId}';

var api_event_upload = api + '/eventApi/uploadDocument';
var api_event_downloadDocument = '/download/{fileKey}';


var api_get_eventDocument = api + '/eventApi/getEventDocument/{eventId}';
var api_addedit_eventDocument = api + '/eventApi/addOrEditEventDocument/{eventId}';
var api_add_event_inviteHCP = api + '/eventApi/addOrEditEventInvite/{eventId}';

var api_event_InviteHcp_search = api + '/eventApi/searchToInviteHcp?value={0}&type={1}&suburb={2}&exceptIds={3}&pageSize={pageSize}&pageNo={pageNo}&isExactKeyword={isExact}';
var api_event_InviteHcp_searchFilterValues = api + '/eventApi/searchToInviteHcpFilterValues?type={type}&value={value}&exceptIds={exceptIds}'

var api_event_searchEventHcp = api + '/eventApi/SearchEventHcp';
var api_event_updateAttendeeStatus = api + '/eventApi/UpdateAttendeeStatus/{eventHcpId}/{status}';
var api_event_searchAttendee = api + '/eventApi/SearchAttendee';
var api_event_searchEvent = api + '/eventApi/SearchEvent';
var api_event_searchEventHcpAccommodation = api + '/eventApi/SearchEventHcpAccommodation';

var api_place_delete = api + '/addressBookApi/deleteAddressBook/{id}';
var api_event_updateRoom = api + '/eventApi/UpdateRoom';
var api_event_updateBookingReference = api + '/eventApi/UpdateBookingReference';

var api_search_resource = api + '/resourceApi/searchResource/{pageSize}/{pageNo}/{sort}/{keyword?}';
var api_getAllLanguages = api + '/resourceApi/getAllLanguages'
var api_resource_add = api + '/resourceApi/addResource'
var api_resource_getResource = api + '/resourceApi/getResource/{id}'
var api_resource_deleteResource = api + '/resourceApi/deleteResource/{id}'
var api_resource_editResource = api + '/resourceApi/editResource'
var api_resource_getAllResources = api + '/resourceApi/getAllResources?resourceTypes={0}'
var api_lookupValue_getResourceLookupValues = api + '/lookupApi/GetResourceLookupValues/{isPublicFacing}'

var api_event_searchEventHcpFlight = api + '/eventApi/SearchEventHcpFlight';
var api_event_updateBookingReferenceFlight = api + '/eventApi/UpdateBookingReferenceFlight';
var api_event_checkEventHcpValid = api + '/eventApi/CheckEventHcpValid/{eventHcpId}';
var api_event_updateDateOfAttendee = api + '/eventApi/UpdateDateAttendee';
var api_event_sendMail_manageInvite = api + '/eventApi/sendMailManageInviteHcp/{id}';


var api_myEvent_getMyEvents = api + '/eventApi/getMyEvents/{pageSize}/{pageNo}/{sort}/{filterOption}/{keyword?}?browserDate={0}';
var api_myEvent_getMyEventTypes = api + '/eventApi/getMyEventTypes';

var api_hcp_updateIms = api + '/hcpApi/UpdateIms';


var api_events_getTopThreeUpcomingEvents = api + '/dashboardApi/getUpcomingEventsDashboard?clientBrowserDate={0}'
var api_events_getUpcomingEventForHCP = api + '/dashboardApi/getUpcomingEventsDashboardHCP/{userId}?clientBrowserDate={0}'
var api_events_getNextUpcomingEventForHCP = api + '/dashboardApi/getNextUpcomingEventsDashboardHCP/{userId}?clientBrowserDate={0}'
var api_events_getHcpEventInvitations = api + '/dashboardApi/getHcpEventInvitations/{userId}?clientBrowserDate={0}'
var api_events_getHcpCdeInvoiceDetails = api + '/dashboardApi/getHcpCdeLastInvoiceDetails/{userId}'
var api_events_getHcpTotalEventsAttended = api + '/dashboardApi/getHcpTotalEventsAttended/{userId}'


var api_dashboard_searchUpdateRegistration = api + '/dashboardApi/searchUpdateRegistration?browserDate={0}';
var api_dashboard_searchUpdateAccommodation = api + '/dashboardApi/searchUpdateAccommodation?browserDate={0}';
var api_dashboard_searchUpdateFlights = api + '/dashboardApi/searchUpdateFlights?browserDate={0}';
var api_dashboard_searchUpdateAttendance = api + '/dashboardApi/searchUpdateAttendance?browserDate={0}';
var api_dashboard_getTotalStatistics = api + '/dashboardApi/getTotalStatistics?browserDate={0}';

var api_dashboard_pendingChangingDiabetesRegistrationsCount = api + '/dashboardApi/getTotalPendingApprovalChangingDiabetesRegistrations';
var api_dashboard_pendingHelpingHandsRegistrationsCount = api + '/dashboardApi/getTotalHelpingHandsPendingRegistrations';
var api_dashboard_pendingInvoicesCount = api + '/dashboardApi/getTotalPendingInvoices';
var api_dashboard_approvedChangingDiabetesRegistrationsCount = api + '/dashboardApi/getTotalApprovedChangingDiabetesRegistrations';
var api_dashboard_approvedHelpingHandsDoctorsCount = api + '/dashboardApi/getTotalHelpingHandsDoctorsApproved';
var api_dashboard_approvedHelpingHandsCDECount = api + '/dashboardApi/getTotalHelpingHandsCDEApproved';

//CDE Training Details
var api_cdeTrainingDetails_cdesRequireTrainingAccess = api + '/cdeTrainingApi/getTrainingAccessRequiredCdes/{pageSize}/{pageNo}/{sort}';
var api_cdeTrainingDetails_grantTrainingAccessToCde = api + '/cdeTrainingApi/grantTrainingAccessToCde/{hcpId}';
var api_cdeTrainingDetails_getTrainingCourseImages = api + '/cdeTrainingApi/getTrainingCourseImages/{trainingType}';
var api_cdeTrainingDetails_getEvaluationResults = api + '/cdeTrainingApi/getEvaluationResults/{trainingType}/{hcpId}';
var api_cdeTrainingDetails_getCdeTrainingDetails = api + '/cdeTrainingApi/getCdeTrainingDetails/{pageSize}/{pageNo}/{sort}/{keyword?}?browserTimeZone={0}';
var api_cdeTrainingDetails_getLatestCdeTrainingDetails = api + '/cdeTrainingApi/getLatestCdeTrainingDetails';
var api_cdeTrainingDetails_getCdesToUnlockTraining = api + '/cdeTrainingApi/getTrainingToUnlockCdes/{pageSize}/{pageNo}/{sort}';
var api_cdeTrainingDetails_unlockCdeTraining = api + '/cdeTrainingApi/unlockCdeTraining/{cdeTrainingId}';
var api_cdeTrainingDetails_exportTrainingReport = api + '/cdeTrainingApi/downloadTrainingReport/{trainingId}?timeZone={0}';

//webinars
var api_webinar_video_complete = api + '/webinarApi/sendVideoCompleteEmailToHcp?videoTitle={0}';
var api_webinar_loadImages = api + '/webinarApi/getELearningModuleImages?imagePath={0}&imageListFileName={1}';

//pv-ae reporting
var api_PV_AE_Report_generatePVAEReport = api + '/reportApi/generatePVAEReport';
(function () {
    'use strict';

    window.app = angular
        .module('ZestApp', ['ngSanitize', 'ngStorage', 'ngAnimate', 'ui.bootstrap', 'ui.mask', 'ui.grid', 'ui.grid.pagination', 'ui.grid.autoResize', 'ng.deviceDetector', 'vcRecaptcha', 'toaster', 'naif.base64', 'ui.grid.edit', 'ui.toggle'])
        .constant('broadcast', '')
        .constant('moment', moment)        
        .config(['$httpProvider', function ($httpProvider) {

            $httpProvider.defaults.cache = false;
            if (!$httpProvider.defaults.headers.get) {
                $httpProvider.defaults.headers.get = {};
            }
            // disable IE ajax request caching
            $httpProvider.defaults.headers.get['If-Modified-Since'] = '0';

            $httpProvider.interceptors.push('httpInterceptor');
            $httpProvider.interceptors.push("antiForgeryInterceptor");
            $httpProvider.interceptors.push('documentSvc');
        }])
        .config(['uiMask.ConfigProvider', function (uiMaskConfigProvider) {
            uiMaskConfigProvider.clearOnBlur(false);
            uiMaskConfigProvider.allowInvalidValue(true);
        }]);

    window.app.run(['$window','$rootScope', 'httpService', '$timeout', 'documentSvc', function ($window, $rootScope, httpService, $timeout, documentSvc) {
        $rootScope.recaptcha = {
            siteKey: '6LfhQgwUAAAAAAp1_BWEmthg-MMknryXHfKKSe-R'
        };
        $rootScope.logOut = function () {
            httpService.post(url_logout, null)
                .then(function (response) {
                    $window.location.href = url_login;
                    //$rootScope.menus = [];
                });
        }

        //$rootScope.menus = [];
        //httpService.get(api_navApi).then(function (response2) {
        //    if (response2.data) {
        //        $rootScope.menus = response2.data;
        //    }
        //});

        // set timeout to execute on next digest
        $timeout(function () {
            documentSvc.recalculateHeight();            
        }, 0);
        angular.element($window).on('resize', function () {
            documentSvc.recalculateHeight();
        });

        // dummy method to swallow if not in page with recaptcha directive
        $window.vcRecaptchaApiLoaded = $window.vcRecaptchaApiLoaded || function () {
        };
    }]);

    app.filter("trustUrl", ['$sce', function ($sce) {
        return function (url) {
            return $sce.trustAsResourceUrl(url);
        };
    }]);
})();;
var url_forgotPassword = '/account/forgotpassword';
var url_login = '/account/login';
var url_logout = '/account/logout';
var url_resetPassword = '/account/resetpassword';

var url_userList = '/user/index';

var url_manageEventAttendees = '/admin/events/event/{eventId}/manage';

var api = '/api';
var api_navApi = api + '/navApi';
var api_navApi_helpingHands = api + '/navApi/helpinghands';

var api_lookup_byType = api + '/lookupApi/{0}';

var api_registerHcp = api + '/hcpApi/register';
var api_getHcp_by_userId = api + '/hcpApi/hcpDetailsByUserId/{userId}';
var api_hcp_getHcpDetailsCurrentUser = api + '/hcpApi/GetHcpDetailsCurrentUser';

var api_getMyProfile_byUserId = api + '/profileApi/myProfile/{userId}/{isCDE}';
var api_updateProfile = api + '/profileApi/updateProfile/{userId}';
var api_changeUserName = api + '/profileApi/changeUserName';
var api_changePassword = api + '/profileApi/changePassword';

var api_user_search = api + "/userApi/search/{pageSize}/{pageNo}/{sortFields}?browserTimeZone={0}&keyword={1}";
var api_getRoles = api + '/userApi/getRoles';
var api_getAllRoles = api + '/userApi/getAllRoles';
var api_addNovoUser = api + '/userApi/createUser';
var api_get_nonHCPUser = api + '/userApi/getUser/{id}';
var api_edit_nonHCPUser = api + '/userApi/editUser';
var api_delete_User = api + '/userApi/deleteUser';
var api_add_HCPUser = api + '/userApi/createHCPUser';
var api_user_getHcp = api + '/userApi/getHCPUser/{id}';
var api_user_editHcp = api + '/userApi/editHcpUser';

var api_addPatientDetail = api + '/patientApi/createPatient';
var api_invoices_export = api + '/helpingHandsApi/ExportInvoices';
var api_invoices_revert = api + '/helpingHandsApi/RevertInvoice/{id}';
var api_invoices_approveOrDecline = api + '/helpingHandsApi/ApproveOrDeclineInvoice/{id}/{approveInvoice}';
var api_hcp_getHcpPrograms = api + '/helpingHandsApi/getHcpProgramDetails';

var api_search_invoices = api + '/helpingHandsApi/searchByInvoice/{pageSize}/{pageNo}/{sort}?browserTimeZone={0}&keyword={1}';

var api_getPatientDetail = api + '/patientApi/getPatient/{id}';
var api_editPatientDetail = api + '/patientApi/editPatient';

var api_institution_search = api + '/institutionApi/getFilter?value={0}&exceptIds={1}';
var api_my_patient_search = api + "/patientApi/searchMyPatients/{pageSize}/{pageNo}/{sort}?browserTimeZone={0}&keyword={1}";

var api_helpingHands_registerCDE = api + '/helpingHandsApi/registerCDE';
var api_propertyType_search = api + '/helpingHandsApi/propertyTypeSearch/{value}';
var api_propertyType_values = api + '/helpingHandsApi/getObjectTypeProperty/{propertyType}/{objectId}';
var api_isCde_registered = api + '/helpingHandsApi/isCDERegistered/{userId}';

var api_propertyType_getValue = api + '/lookupApi/propertyValue{id}';
var api_propertyType_getProduct = api + '/programApi/getListProduct/{programId}';
var api_cde_search_byArea = api + '/hcpApi/searchCDEByArea/{pageSize}/{pageNo}/{sort}/{filterArea}';
var api_cde_search_byState = api + '/hcpApi/searchCDEByState/{pageSize}/{pageNo}/{sort}/{filterState}';


var api_property_values = api + '/propertyApi/values/{0}';
var api_doctor_search = api + '/hcpApi/getFilter';
var api_search_doctorByName = api + '/hcpApi/getDoctorByName';
var api_lookup_property = api + "/lookupApi/propertyValue";
var api_patient_add_diabete_program = api + '/patientApi/addDiabetesProgram';
var api_patient_edit_diabete_program = api + '/patientApi/editDiabetesProgram';
var api_product_get = api + "/programApi/getListProduct/{programId}";
var api_patient_add_obesity_program = api + '/patientApi/addObesityProgram';
var api_patient_programs_get = api + "/patientApi/getPrograms/{patientId}";


var api_propertyvalues_search = api + '/propertyApi/values/{propertyId:int?}/{keyword?}';

var api_patient_programs_getObesity = api + "/patientApi/getObesityProgram/{id}";
var api_patient_programs_editObesity = api + '/patientApi/editObesityProgram';
var api_patient_programs_getDiabetes = api + "/patientApi/getDiabetesProgram/{patientProgramId}";
var api_patient_program_visits_search = api + '/patientApi/searchVisits/{patientId}/{programId}/{pageSize}/{pageNo}/{sortFields}?browserTimeZone={0}&keyword={1}';

var api_patient_visit_addDiabetes = api + "/programVisitApi/createDiabetes";
var api_patient_visit_addObesity = api + "/programVisitApi/createObesity";
var api_patient_isCanAddDiabetesProgram = api + '/patientApi/isCanAddDiabetesProgram/{patientId}';
var api_patient_isCanAddObesityProgram = api + '/patientApi/isCanAddObesityProgram/{patientId}';

var api_patient_visit_getDiabetes = api + "/programVisitApi/getDiabetes/{patientProgramVisitId}";
var api_patient_visit_getObesity = api + "/programVisitApi/getObesity/{patientProgramVisitId}";

var api_patient_visit_editDiabetes = api + "/programVisitApi/editDiabetes";
var api_patient_visit_editObesity = api + "/programVisitApi/editObesity";
var api_patient_visit_deleteObesity = api + "/programVisitApi/deleteObesity";
var api_patient_visit_deleteDiabetes = api + "/programVisitApi/deleteDiabetes";

var api_invoice_search = api + '/invoiceApi/search';
var api_patient_visit_getRemainingHours = api + "/programVisitApi/getSupportTimeRemainHour/{patientProgramId}";
var api_patient_visit_getRemainingMinutes = api + "/programVisitApi/GetSupportTimeRemainMinute/{patientProgramId}";
var api_patient_visit_edit_getRemainingHours = api + "/programVisitApi/getSupportTimeRemainHour/{patientProgramId}/{patientProgramVisitId?}";
var api_patient_visit_edit_getRemainingMinutes = api + "/programVisitApi/GetSupportTimeRemainMinute/{patientProgramId}/{patientProgramVisitId?}";
var api_patient_visit_getSupportTimeUsageMinute = api + "/programVisitApi/getSupportTimeUsageMinute/{patientProgramId}"

var api_invoice_getVisits = api + '/invoiceApi/getVisitTable';
var api_invoice_confirmVisits = api + '/invoiceApi/confirmVisit';
var api_invoice_confirmPaymentDetails = api + '/invoiceApi/confirmPayment';
var api_invoice_finaliseBySystem = api + '/invoiceApi/finaliseBySystem?browserTimeZone={tz}';
var api_invoice_finaliseByUpload = api + '/invoiceApi/finaliseByUpload?browserTimeZone={tz}';
var api_invoice_getPaymentDetails = api + '/invoiceApi/getPayment';
var api_invoice_isCanCreateMonthlyInvoice = api + '/invoiceApi/isCanCreateMonthlyInvoice';

var api_hh_userAdministration_search = api + '/helpingHandsApi/searchUser/{pageSize}/{pageNo}/{sortFields}?keyword={keyword}&browserTimeZone={tz}';
var api_hh_userAdministration_approve = api + '/helpingHandsApi/approveHHUser/{hcpProgramId}';
var api_hh_userAdministration_declined = api + '/helpingHandsApi/declinedHHUser/{hcpProgramId}';
var api_hcp_deletehcpnonuser = api + '/hcpApi/DeleteHcpNonUser/{hcpId}'

var api_add_AddressBook = api + '/addressBookApi/createAddressBook';
var api_get_AddressBook = api + '/addressBookApi/getAddressBook/{id}';
var api_edit_AddressBook = api + '/addressBookApi/editAddressBook';
var api_edit_isAddressAssociatedToPlace = api + '/addressBookApi/isAddressAssociatedToPlace/{id}/{placeType}';

var api_hh_userAdministration_declined = api + '/helpingHandsApi/declinedHHUser/{hcpProgramId}';
var api_add_presenter = api + '/presenterApi/creatPresenter';
var api_get_presenter = api + '/presenterApi/getPresenter/{id}';
var api_edit_presenter = api + '/presenterApi/editPresenter';
var api_presenter_delete = api + '/presenterApi/Delete/{presenterId}';
var api_presenter_associatedToNonDeletedEvent = api + '/presenterApi/isPresenterAssociatedToNonDeletedEvent/{id}';

var api_addressBook_search = api + '/addressBookApi/search';
var api_presenter_search = api + '/presenterApi/search';

var api_event_getLastEventHcp = api + '/eventApi/GetLastEventHcp';
var api_event_getDetail = api + '/eventApi/HcpRegisterGetEventDetail/{eventId}';
var api_event_getEventHcpDetail = api + '/eventApi/GetEventHcpDetail/{eventHcpId}';
var api_event_unInviteHcp = api + '/eventApi/unInviteHcp/{eventHcpId}';

var api_event_getEventType = api + '/eventApi/getEventType';
var api_event_registerEventHcp = api + '/eventApi/RegisterEventHcp';
var api_event_presenter_search = api + '/presenterApi/getFilter?value={0}&exceptIds={1}';
var api_events_hcp = api + '/eventApi/getHCPEvents?id={0}&clientDate={1}';

var api_get_event_detail = api + '/eventApi/getDetail/{id}';
var api_delete_event = api + '/eventApi/delete/{id}';
var api_event_unPublish = api + '/eventApi/unPublish/{id}';
var api_event_publish = api + '/eventApi/publish/{id}/{mail}';
var api_event_publishEditMode = api + '/eventApi/publishEditMode/{id}/{mail}';
var api_addedit_event = api + '/eventApi/AddOrEdit';
var api_get_inviteHCp = api + '/eventApi/getEventInvite/{eventId}';

var api_get_eventVenue_detail = api + '/eventApi/getDateVenue/{eventId}';
var api_event_venue_search = api + '/venueApi/getFilter?value={0}&exceptIds={1}';
var api_addedit_eventVenue = api + '/eventApi/addOrEditDateVenue';

var api_get_eventFlight_detail = api + '/eventApi/getEventFlight/{eventId}';
var api_addedit_eventFlight = api + '/eventApi/addOrEditEventFlight/{eventId}';

var api_event_Accommodation_search = api + '/hotelApi/getFilter?value={0}&exceptIds={1}';
var api_get_eventAccommodation_detail = api + '/eventApi/getAccommodation/{eventId}';
var api_addedit_eventAccommodation = api + '/eventApi/addOrEditAccommodation/{eventId}';

var api_event_upload = api + '/eventApi/uploadDocument';
var api_event_downloadDocument = '/download/{fileKey}';


var api_get_eventDocument = api + '/eventApi/getEventDocument/{eventId}';
var api_addedit_eventDocument = api + '/eventApi/addOrEditEventDocument/{eventId}';
var api_add_event_inviteHCP = api + '/eventApi/addOrEditEventInvite/{eventId}';

var api_event_InviteHcp_search = api + '/eventApi/searchToInviteHcp?value={0}&type={1}&suburb={2}&exceptIds={3}&pageSize={pageSize}&pageNo={pageNo}&isExactKeyword={isExact}';
var api_event_InviteHcp_searchFilterValues = api + '/eventApi/searchToInviteHcpFilterValues?type={type}&value={value}&exceptIds={exceptIds}'

var api_event_searchEventHcp = api + '/eventApi/SearchEventHcp';
var api_event_updateAttendeeStatus = api + '/eventApi/UpdateAttendeeStatus/{eventHcpId}/{status}';
var api_event_searchAttendee = api + '/eventApi/SearchAttendee';
var api_event_searchEvent = api + '/eventApi/SearchEvent';
var api_event_searchEventHcpAccommodation = api + '/eventApi/SearchEventHcpAccommodation';

var api_place_delete = api + '/addressBookApi/deleteAddressBook/{id}';
var api_event_updateRoom = api + '/eventApi/UpdateRoom';
var api_event_updateBookingReference = api + '/eventApi/UpdateBookingReference';

var api_search_resource = api + '/resourceApi/searchResource/{pageSize}/{pageNo}/{sort}/{keyword?}';
var api_getAllLanguages = api + '/resourceApi/getAllLanguages'
var api_resource_add = api + '/resourceApi/addResource'
var api_resource_getResource = api + '/resourceApi/getResource/{id}'
var api_resource_deleteResource = api + '/resourceApi/deleteResource/{id}'
var api_resource_editResource = api + '/resourceApi/editResource'
var api_resource_getAllResources = api + '/resourceApi/getAllResources?resourceTypes={0}'
var api_lookupValue_getResourceLookupValues = api + '/lookupApi/GetResourceLookupValues/{isPublicFacing}'

var api_event_searchEventHcpFlight = api + '/eventApi/SearchEventHcpFlight';
var api_event_updateBookingReferenceFlight = api + '/eventApi/UpdateBookingReferenceFlight';
var api_event_checkEventHcpValid = api + '/eventApi/CheckEventHcpValid/{eventHcpId}';
var api_event_updateDateOfAttendee = api + '/eventApi/UpdateDateAttendee';
var api_event_sendMail_manageInvite = api + '/eventApi/sendMailManageInviteHcp/{id}';


var api_myEvent_getMyEvents = api + '/eventApi/getMyEvents/{pageSize}/{pageNo}/{sort}/{filterOption}/{keyword?}?browserDate={0}';
var api_myEvent_getMyEventTypes = api + '/eventApi/getMyEventTypes';

var api_hcp_updateIms = api + '/hcpApi/UpdateIms';


var api_events_getTopThreeUpcomingEvents = api + '/dashboardApi/getUpcomingEventsDashboard?clientBrowserDate={0}'
var api_events_getUpcomingEventForHCP = api + '/dashboardApi/getUpcomingEventsDashboardHCP/{userId}?clientBrowserDate={0}'
var api_events_getNextUpcomingEventForHCP = api + '/dashboardApi/getNextUpcomingEventsDashboardHCP/{userId}?clientBrowserDate={0}'
var api_events_getHcpEventInvitations = api + '/dashboardApi/getHcpEventInvitations/{userId}?clientBrowserDate={0}'
var api_events_getHcpCdeInvoiceDetails = api + '/dashboardApi/getHcpCdeLastInvoiceDetails/{userId}'
var api_events_getHcpTotalEventsAttended = api + '/dashboardApi/getHcpTotalEventsAttended/{userId}'


var api_dashboard_searchUpdateRegistration = api + '/dashboardApi/searchUpdateRegistration?browserDate={0}';
var api_dashboard_searchUpdateAccommodation = api + '/dashboardApi/searchUpdateAccommodation?browserDate={0}';
var api_dashboard_searchUpdateFlights = api + '/dashboardApi/searchUpdateFlights?browserDate={0}';
var api_dashboard_searchUpdateAttendance = api + '/dashboardApi/searchUpdateAttendance?browserDate={0}';
var api_dashboard_getTotalStatistics = api + '/dashboardApi/getTotalStatistics?browserDate={0}';

var api_dashboard_pendingChangingDiabetesRegistrationsCount = api + '/dashboardApi/getTotalPendingApprovalChangingDiabetesRegistrations';
var api_dashboard_pendingHelpingHandsRegistrationsCount = api + '/dashboardApi/getTotalHelpingHandsPendingRegistrations';
var api_dashboard_pendingInvoicesCount = api + '/dashboardApi/getTotalPendingInvoices';
var api_dashboard_approvedChangingDiabetesRegistrationsCount = api + '/dashboardApi/getTotalApprovedChangingDiabetesRegistrations';
var api_dashboard_approvedHelpingHandsDoctorsCount = api + '/dashboardApi/getTotalHelpingHandsDoctorsApproved';
var api_dashboard_approvedHelpingHandsCDECount = api + '/dashboardApi/getTotalHelpingHandsCDEApproved';

//CDE Training Details
var api_cdeTrainingDetails_cdesRequireTrainingAccess = api + '/cdeTrainingApi/getTrainingAccessRequiredCdes/{pageSize}/{pageNo}/{sort}';
var api_cdeTrainingDetails_grantTrainingAccessToCde = api + '/cdeTrainingApi/grantTrainingAccessToCde/{hcpId}';
var api_cdeTrainingDetails_getTrainingCourseImages = api + '/cdeTrainingApi/getTrainingCourseImages/{trainingType}';
var api_cdeTrainingDetails_getEvaluationResults = api + '/cdeTrainingApi/getEvaluationResults/{trainingType}/{hcpId}';
var api_cdeTrainingDetails_getCdeTrainingDetails = api + '/cdeTrainingApi/getCdeTrainingDetails/{pageSize}/{pageNo}/{sort}/{keyword?}?browserTimeZone={0}';
var api_cdeTrainingDetails_getLatestCdeTrainingDetails = api + '/cdeTrainingApi/getLatestCdeTrainingDetails';
var api_cdeTrainingDetails_getCdesToUnlockTraining = api + '/cdeTrainingApi/getTrainingToUnlockCdes/{pageSize}/{pageNo}/{sort}';
var api_cdeTrainingDetails_unlockCdeTraining = api + '/cdeTrainingApi/unlockCdeTraining/{cdeTrainingId}';
var api_cdeTrainingDetails_exportTrainingReport = api + '/cdeTrainingApi/downloadTrainingReport/{trainingId}?timeZone={0}';

//webinars
var api_webinar_video_complete = api + '/webinarApi/sendVideoCompleteEmailToHcp?videoTitle={0}';
var api_webinar_loadImages = api + '/webinarApi/getELearningModuleImages?imagePath={0}&imageListFileName={1}';

//pv-ae reporting
var api_PV_AE_Report_generatePVAEReport = api + '/reportApi/generatePVAEReport';
(function () {
    'use strict';

    window.app.controller('PvAeReportController', PvAeReportController);
    PvAeReportController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
       'moment', 'formConfig', 'toaster', '$rootScope'];

    function PvAeReportController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
       moment, formConfig, toaster, $rootScope) {
        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;
        vm.toggleNovoProductSelection = toggleNovoProductSelection;
        vm.toggleActionTakenSelection = toggleActionTakenSelection;
        vm.toggleProductAESelection = toggleProductAESelection;
        vm.toggleProductAESelectionDueToOtherProduct = toggleProductAESelectionDueToOtherProduct;
        vm.patientNotReceivedTreatment = patientNotReceivedTreatment;
        vm.severityOfAdverseEvent = severityOfAdverseEvent;
        vm.isPatientGrantPermissionToContactDoctor = isPatientGrantPermissionToContactDoctor;
        vm.isReporterConsentToDisclosePersonalInfo = isReporterConsentToDisclosePersonalInfo;
        vm.patientNotPartOfNovoPSP = patientNotPartOfNovoPSP;
        vm.typeOfReporter = typeOfReporter;
        vm.isReporterAgreeToContactThem = isReporterAgreeToContactThem;
        vm.submit = submit;
        vm.errors = [];

        function init() {

            vm.model.personNameWhoPreparedReport = formConfig.hcpName;
            vm.model.personContactDetailsWhoPreparedReport = formConfig.hcpEmail;
            vm.model.reporterProfession = formConfig.hcpProfession;

            $('.date-picker').datepicker({
                clearBtn: true,
                orientation: "left",
                autoclose: true,
                endDate: '+0d',
                format: "dd/M/yyyy",
                orientation: "bottom auto",
            }).on('changeDate', function (ev) {
                $(this).datepicker('hide');
            });

            loadInitData();
        }

        function toggleNovoProductSelection(novoProductName) {
            var idx = vm.model.selectedNovoProducts.indexOf(novoProductName);
            if (idx > -1)
                vm.model.selectedNovoProducts.splice(idx, 1);
            else
                vm.model.selectedNovoProducts.push(novoProductName);
        }

        function toggleActionTakenSelection(actionTaken) {
            var idx = vm.model.selectedActionsTaken.indexOf(actionTaken);
            if (idx > -1)
                vm.model.selectedActionsTaken.splice(idx, 1);
            else
                vm.model.selectedActionsTaken.push(actionTaken);
        }

        function toggleProductAESelection(advereEventSelected) {
            var idx = vm.model.selectedAdverseEventsCaused.indexOf(advereEventSelected);
            if (idx > -1)
                vm.model.selectedAdverseEventsCaused.splice(idx, 1);
            else
                vm.model.selectedAdverseEventsCaused.push(advereEventSelected);
        }

        function toggleProductAESelectionDueToOtherProduct(advereEventSelected) {
            var idx = vm.model.selectedAdverseEventsCausedDueToOtherProducts.indexOf(advereEventSelected);
            if (idx > -1)
                vm.model.selectedAdverseEventsCausedDueToOtherProducts.splice(idx, 1);
            else
                vm.model.selectedAdverseEventsCausedDueToOtherProducts.push(advereEventSelected);
        }

        function isDateInCorrectFormat() {

            var startDateOfAe = vm.model.startDateOfAdverseEvent;
            var startDate = vm.model.startDate;
            var stopDate = vm.model.stopDate;
            var dateOfReceipt = vm.model.dateOfReceiptOfAdverseEvent;

            var dateFormat = /^(([0-9])|([0-2][0-9])|([3][0-1]))\/((J|j)an|(F|f)eb|(M|m)ar|(A|a)pr|(M|m)ay|(J|j)un|(J|j)ul|(A|a)ug|(S|s)ep|(O|o)ct|(N|n)ov|(D|d)ec)\/\d{4}$/;

            if (startDateOfAe != null && startDateOfAe != undefined && startDateOfAe.trim() != "") {
                var match = startDateOfAe.match(dateFormat);
                if (match == null) {
                    vm.dateFormatError = true;
                    return false;
                }
            }

            if (startDate != null && startDate != undefined && startDate.trim() != "") {
                var match = startDate.match(dateFormat);
                if (match == null) {
                    vm.dateFormatError = true;
                    return false;
                }
            }

            if (stopDate != null && stopDate != undefined && stopDate.trim() != "") {
                var match = stopDate.match(dateFormat);
                if (match == null) {
                    vm.dateFormatError = true;
                    return false;
                }
            }

            if (dateOfReceipt != null && dateOfReceipt != undefined && dateOfReceipt.trim() != "") {
                var match = dateOfReceipt.match(dateFormat);
                if (match == null) {
                    vm.dateFormatError = true;
                    return false;
                }
            }

            return true;
        }

        function patientNotReceivedTreatment() {
            vm.model.treatmentReceivedForAdverseEvent = "";
        }

        function patientNotPartOfNovoPSP() {
            vm.model.patientProgramName = "";
        }

        function severityOfAdverseEvent() {
            if (vm.model.severityOfAdverseEvent != 'Other')
                vm.model.otherAdverseEvent = "";
        }

        function loadInitData() {
            vm.novoProducts = [
                { id: 1, name: 'Actrapid<span class="super-script"><span>&reg;</span></span>' },
                { id: 2, name: 'NovoFine<span class="super-script"><span>&reg;</span></span> needles' },
                { id: 3, name: 'Levemir<span class="super-script"><span>&reg;</span></span>' },
                { id: 4, name: 'NovoMix<span class="super-script"><span>&reg;</span></span> 30' },
                { id: 5, name: 'Mixtard<span class="super-script"><span>&reg;</span></span> 30/70' },
                { id: 6, name: 'NovoRapid<span class="super-script"><span>&reg;</span></span>' },
                { id: 7, name: 'Mixtard<span class="super-script"><span>&reg;</span></span> 50/50' },
                { id: 8, name: 'Protaphane<span class="super-script"><span>&reg;</span></span>' },
                { id: 9, name: 'NovoFine<span class="super-script"><span>&reg;</span></span> 4mm needles' },
                { id: 10, name: 'Saxenda<span class="super-script"><span>&reg;</span></span>' },
                { id: 11, name: 'NovoFine<span class="super-script"><span>&reg;</span></span> 6mm needles' },
                { id: 12, name: 'Victoza<span class="super-script"><span>&reg;</span></span>' }
            ];

            vm.actionsTaken = [
                { id: 1, name: 'Discontinued' },
                { id: 2, name: 'Dose increased' },
                { id: 3, name: 'Discontinued due to event' },
                { id: 4, name: 'No change' },
                { id: 5, name: 'Dose decreased' },
                { id: 6, name: 'Not reported' },
            ];

            vm.productCausingAE = [
                { id: 1, name: 'Yes (Possible)' },
                { id: 2, name: 'No (Unlikely)' },
                { id: 3, name: 'Unknown (Reporter does not know)' },
                { id: 4, name: 'Not reported/not requested from reporter' }
            ];

            vm.reporterTypes = [
                { id: 1, name: 'Doctor' },
                { id: 2, name: 'Nurse' },
                { id: 3, name: 'Pharmacist' },
                { id: 4, name: 'Patient' },
                { id: 5, name: 'Other' },
            ];

            vm.adverseEvents = [
                { id: 1, name: 'Mild - did not affect everyday activities' },
                { id: 2, name: 'Was admitted to hospital' },
                { id: 3, name: 'Other' }
            ];

            vm.outcomeOfAdverseEvents = [
                { id: 1, name: 'Recovered (no more symptoms)' },
                { id: 2, name: 'Not recovered (no change in symptoms)' },
                { id: 3, name: 'Recovering (getting better, but still symptoms)' },
                { id: 4, name: 'Died' },
                { id: 5, name: 'Unknown' },
            ];

            vm.ageGroups = [
                { id: 1, name: 'Infant' },
                { id: 2, name: 'Child' },
                { id: 3, name: 'Adolescent' },
                { id: 4, name: 'Adult' },
                { id: 5, name: 'Elderly' },
            ];

            vm.model.selectedNovoProducts = [];
            vm.model.selectedActionsTaken = [];
            vm.model.selectedAdverseEventsCaused = [];
            vm.model.selectedAdverseEventsCausedDueToOtherProducts = [];
        }

        function submit(form) {
            if (isValid(form)) {
                httpService.post(api_PV_AE_Report_generatePVAEReport, vm.model)
                .then(function (response) {
                    if (response.status == 200) {
                        $rootScope.$broadcast("loader_show");
                        toaster.pop({
                            type: 'success',
                            title: 'Success',
                            body: 'PV-AE form is submitted successfully',
                            timeout: 2000,
                            onHideCallback: function () {
                                $window.location.href = '/ae-reporting/pv';
                                $rootScope.$broadcast("loader_hide");
                            }
                        });
                    }
                    else {
                        toaster.pop({
                            type: 'error',
                            title: 'Fail',
                            body: 'Failed to submit PV-AE form',
                            timeout: 2000
                        });
                    }
                });
            }
            else {
                document.getElementById('page-wrapper').scrollIntoView();
            }
            utilitySvc.invalidateControlOnSubmission(form);
        }

        function isValid(formPvAeReport) {
            formPvAeReport.$setSubmitted();
            vm.errors = [];
            var valid = formPvAeReport.$valid;
            var isGender = isGenderValid();
            var isPatientPSP = isPatientPartOfNovoPSP();
            var isGrantToContactDoctor = isPermissionToContactDoctor();
            var isReporterAgreedToObtainAdditionalInfo = isObtainAdditionalInfo();
            var isDisclosePersonalInfo = isDisclosePersonalDetails();
            var isReporterType = isTypeOfReporter();
            var isNovoNordiskProduct = isNovoProduct();
            var isNovoProductContributedToAE = isProductContributedToAE();
            var isDateInValidFormat = isDateInCorrectFormat();
            var isAgreedToContactThem = isReporterAgreedToContactThem();

            var formValid = valid && isGender && isPatientPSP && isGrantToContactDoctor && isReporterAgreedToObtainAdditionalInfo
                && isDisclosePersonalInfo && isReporterType && isNovoNordiskProduct && isNovoProductContributedToAE && isAgreedToContactThem;

            if (!formValid) {
                vm.errors.push({ message: "All fields highlighted in red are mandatory" });
            }

            if (!isDateInValidFormat) {
                vm.errors.push({ message: "Please enter the date in valid format" });
            }

            return formValid && isDateInValidFormat;
        }

        function isGenderValid() {
            var gender = vm.model.gender;
            if (gender == null || gender == undefined || gender == "") {
                return false;
            }
            return true;
        }

        function isPatientPartOfNovoPSP() {
            var partOfPSP = vm.model.patientPartOfNovoPSP;
            if (partOfPSP == null || partOfPSP == undefined || partOfPSP == "") {
                return false;
            }
            return true;
        }

        function isPermissionToContactDoctor() {
            var ispatientGrantAcessToContactDoctor = vm.model.patientGrantAcessToContactDoctor;
            if (ispatientGrantAcessToContactDoctor == null || ispatientGrantAcessToContactDoctor == undefined || ispatientGrantAcessToContactDoctor == "") {
                return false;
            }
            return true;
        }

        function isObtainAdditionalInfo() {
            var isAdditionalInfo = vm.model.reporterAgreeSafetyDepartmentToContactThem;
            if (isAdditionalInfo == null || isAdditionalInfo == undefined || isAdditionalInfo == "") {
                return false;
            }
            return true;
        }

        function isDisclosePersonalDetails() {
            var additionalInfo = vm.model.reporterAgreeSafetyDepartmentToContactThem;
            var isReporterAgreeToDisclosePersonalInfo = vm.model.reporterAgreeToDisclosePersonalInfo;
            if (additionalInfo == 'Yes') {
                if (isReporterAgreeToDisclosePersonalInfo == null || isReporterAgreeToDisclosePersonalInfo == undefined || isReporterAgreeToDisclosePersonalInfo == "") {
                    return false;
                }
            }
            return true;
        }

        function isTypeOfReporter() {
            var reporterType = vm.model.reporterType;
            if (reporterType == null || reporterType == undefined || reporterType == "") {
                return false;
            }
            return true;
        }

        function isNovoProduct() {
            var novoProducts = vm.model.selectedNovoProducts;
            if (novoProducts == null || novoProducts == undefined || novoProducts.length <= 0) {
                return false;
            }
            return true;
        }

        function isProductContributedToAE() {
            var isProductToAe = vm.model.selectedAdverseEventsCaused;
            if (isProductToAe == null || isProductToAe == undefined || isProductToAe.length <= 0) {
                return false;
            }
            return true;
        }

        function isPatientGrantPermissionToContactDoctor(value) {
            if (value == 'No') {
                vm.model.reportedPersonName = null;
                vm.model.reportedPersonAddress = null;
                vm.model.reportedPersonContactDetails = null;
            }
        }

        function isReporterConsentToDisclosePersonalInfo(value) {
            if (value == 'No') {
                vm.model.reporterName = null;
                vm.model.reporterAddress = null;
                vm.model.reporterPreferredContactMethod = null;
                vm.model.reporterContactDetails = null;
                vm.model.reporterType = null;
                vm.model.otherReporterType = null;
            }
        }

        function typeOfReporter(value) {
            if (value != 'Other') {
                vm.model.otherReporterType = null;
            }
        }

        function isReporterAgreeToContactThem(value) {
            if (value == 'No') {
                vm.model.reporterAgreeToDisclosePersonalInfo = null;
                vm.model.reporterName = null;
                vm.model.reporterAddress = null;
                vm.model.reporterPreferredContactMethod = null;
                vm.model.reporterContactDetails = null;
            }
        }

        function isReporterAgreedToContactThem() {
            var agreedToContactThem = vm.model.youAgreeSafetyDepartmentToContactYou;
            if (agreedToContactThem == null || agreedToContactThem == undefined || agreedToContactThem.length <= 0) {
                return false;
            }
            return true;
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('ForgotPasswordController', ForgotPasswordController);

    ForgotPasswordController.$inject = ['$rootScope', '$scope', '$window', 'httpService',
        'modelStateErrorBuilder', 'vcRecaptchaService'];

    function ForgotPasswordController($rootScope, $scope, $window, httpService,
        modelStateErrorBuilder, vcRecaptchaService) {
        var vm = this;
        vm.model = {};
        vm.resetPassword = resetPassword;
        vm.setWidgetId = setWidgetId;

        function setWidgetId(widgetId) {
            vm.widgetId = widgetId;
        }

        function resetPassword(forgotPwd) {
            if (isValid(forgotPwd) == 1) {
                vm.model.Captcha = vm.recaptchaResponse;

                httpService.post(url_forgotPassword, vm.model)
                    .then(function (response) {
                        vm.errors = response.data.errors;

                        if (vm.errors.length > 0) {
                            modelStateErrorBuilder.build(vm.errors, vm.model);
                            vcRecaptchaService.reload(vm.widgetId);
                        } else {
                            vm.success = [];
                            vm.success.push({ message: "Please go to your email and follow the instructions to reset your passwod" });
                            modelStateErrorBuilder.build(vm.success, vm.model);
                            // $window.location.href = url_login;
                        }
                    });
            }
        }

        function isValid(forgotPwd) {
            var success = 1;
            vm.errors = [];
            vm.success = [];
            if (!forgotPwd.$valid) {
                if (forgotPwd.username.$error.required) {
                    vm.errors.push({
                        message: "Please enter email address"
                    });
                }
                else {
                    if (forgotPwd.username.$error.email) {
                        vm.errors.push({
                            message: "Invalid email address"
                        });
                    }
                }
                success = 0;
            }

            if (!vm.recaptchaResponse) {
                vm.errors.push({
                    message: "Please complete the CAPTCHA field"
                });
                success = 0;
            }

            return success;
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('LoginController', LoginController);

    LoginController.$inject = ['$window', 'httpService', 'modelStateErrorBuilder',
        '$sessionStorage', '$rootScope'];

    function LoginController($window, httpService, modelStateErrorBuilder,
        $sessionStorage, $rootScope) {
        var vm = this;

        setToDefault();

        vm.signin = signin;

        if (vm.login == undefined || vm.login == null) {
            vm.login = {};
        }
        var returnUrl = getQueryStringValue('returnurl');
        if (returnUrl) {
            vm.login.ReturnUrl = returnUrl;
        }

        function signin(loginForm) {
            setToDefault();

            if (isValid(loginForm) == 1) {
                httpService.post('/account/login', vm.login)
                .then(function (response) {
                    vm.errors = response.data.errors === undefined ? [] : response.data.errors;

                    if (vm.errors.length > 0)
                        modelStateErrorBuilder.build(vm.errors, vm.login);
                    else {
                        if (response.status === 200) {
                            if (response.data.type == "loginRedirectUrl") {
                                $window.location.href = response.data.message;
                            }
                        }
                    }
                });
            }
        }

        function isValid(loginForm) {
            var success = 1;
            vm.errors = [];
            if (!loginForm.$valid) {
                if (loginForm.username.$error.required) {
                    vm.errors.push({
                        message: "Please enter email address"
                    });
                }
                else {
                    if (loginForm.username.$error.email) {
                        vm.errors.push({
                            message: "Invalid email address"
                        });
                    }
                }
                if (loginForm.password.$error.required)
                    vm.errors.push({
                        message: "Please enter password"
                    });
                success = 0;
            }

            return success;
        }

        function setToDefault() {
            vm.errors = [];
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('ResetPasswordController', ResetPasswordController);

    ResetPasswordController.$inject = ['$rootScope', '$scope', '$window', 'httpService', 'model',
    'modelStateErrorBuilder', 'vcRecaptchaService', 'utilitySvc'];

    function ResetPasswordController($rootScope, $scope, $window, httpService, model,
    modelStateErrorBuilder, vcRecaptchaService, utilitySvc) {
        var vm = this;
        vm.model = model;
        vm.updatePassword = updatePassword;

        if (vm.model == undefined || vm.model == null)
            vm.model = {};

        function isFormValid(form) {
            var valid = form.$valid;
            return valid;
        }

        function updatePassword(form) {
            if (isFormValid(form)) {
                httpService.post(url_resetPassword, vm.model)
                    .then(function (response) {
                        vm.errors = response.data.errors;
                        if (vm.errors.length > 0) {
                            modelStateErrorBuilder.build(vm.errors, vm.model);
                        }
                        else {
                            $window.location.href = url_login;
                        }
                    });
            }
            utilitySvc.invalidateControlOnSubmission(form);
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('AddressBookController', AddressBookController);
    AddressBookController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', 'modalService'];

    function AddressBookController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout,modalService) {
        var vm = this;
        vm.submit = submit;
        vm.model = vm.model || {};
        vm.init = init;
        vm.submit = submit;
        vm.isEditMode = false;
        vm.deletePlace = deletePlace;
        function init() {
            initLookups();
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
                .success(function (data) {                    
                    vm.types = data.Place_Type;
                    vm.states = data.State;
                }).then(function(d) {
                    loadAddressBook();
                });
        }
 
        function loadAddressBook() {
            if (formConfig.addressBookId > 0) {
                httpService.get(api_get_AddressBook.replace('{id}', formConfig.addressBookId))
                    .success(function(response) {                        
                        vm.model = response;
                        IsAddressAssociatedToPlace();
                        vm.isEditMode = true;
                    });
            }
        }

        function IsAddressAssociatedToPlace() {
            var url = api_edit_isAddressAssociatedToPlace.replace('{id}', formConfig.addressBookId).replace('{placeType}', vm.model.type);
            httpService.get(url)
                    .success(function(response) {                        
                        vm.isAddressAssociatedToPlace = response.data;                        
                    });
        }

        function submit(form) {
            utilitySvc.invalidateControlOnSubmission(form);
            var url = api_add_AddressBook;
            if (vm.isEditMode) {
                vm.model.id = formConfig.addressBookId;
                url = api_edit_AddressBook;
            }
            if (isFormAddAddressBookValid(form)) {
                    console.log(vm.model);
                    httpService.post(url, vm.model)
                        .then(function (response) {
                            vm.errors = [];
                            vm.errors = response.data.errors;
                            if (response.data.errors.length > 0) {
                                modelStateErrorBuilder.build(vm.errors, vm.model);
                                scrollToTop();
                            } else {
                                redirectAddressBookList();
                            }
                        });
                } else {
                    scrollToTop();
                }
             
        }

        function deletePlace() {
            var modalOptions = {
                actionButtonText: 'Yes',
                bodyText: 'Are you sure you want to delete this address book?',
                closeButtonText: 'Cancel'
            };

            modalService.showModal({}, modalOptions)
                .then(function(result) {
                    httpService.post(api_place_delete
                            .replace('{id}', formConfig.addressBookId))
                        .then(function(response) {
                            if (response.data.success) {
                                redirectAddressBookList();
                            } else {
                                vm.errors = response.data.errors;
                            }
                        });
                });
        }

        function isFormAddAddressBookValid(form) {
            vm.errors = [];
            var isValid = true;
            var type = vm.model.type;
            var state = '';

            if (vm.model.address != undefined)
             state = vm.model.address.state;

            if (type === undefined || type == "" || type == null) {
                isValid = false;
            }
            if (state === undefined || state == "" || state == null) {
                isValid = false;
            }

            if (form.name.$error.required) {
                isValid = false;
            }
            if (form.addrLine1.$error.required) {
                isValid = false;
            }
            if (form.suburb.$error.required) {
                isValid = false;
            }
            if (form.postcode.$error.required) {
                isValid = false;
            }
            if (!isValid) {
                addError("All fields highlighted in red are mandatory");;
            }

            if (form.email.$error.email) {
                isValid = false;
                addError("Please specify a valid email");
            }

            if (form.fax.$error.phone) {
                isValid = false;
                addError("Please specify a valid fax number");
            }

            if (form.phone.$error.phone) {
                isValid = false;
                addError("Please specify a valid phone number");
            }

            var postCodeValid = isPostCode();
            if (!postCodeValid) {
                isValid = false;
            }
            return isValid;
        }


        function redirectAddressBookList() {
            window.location.href = formConfig.addressBookListUrl;
        }

        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }

        function addError(message) {
            var isExists = false;

            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists)
                vm.errors.push({
                    message: message
                });
        }

        function isPostCode() {
            var postCode = vm.model.address.postcode;
            if (postCode != null && postCode != undefined && postCode.length > 0) {
                if (postCode.length < 4) {
                    addError("Postcode must be 4 digits");
                    return false;
                }
            }
            return true;
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('AddressBookIndexController', AddressBookIndexController);
    AddressBookIndexController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService',
        'uiGridConstants', 'moment', 'utilitySvc', 'formConfig'];

    function AddressBookIndexController($rootScope, $scope, $window, filterFilter, httpService,
        uiGridConstants, moment, utilitySvc, formConfig) {
        var vm = this;
        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: 'id',
            keyword: ''
        };
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getDataGird);
        vm.gridOptions.paginationPageSizes = [25, 50, 75, 100];
        vm.gridOptions.columnDefs = [
            { name: 'name', displayName: 'Bussiness name' },
            { name: 'suburb', displayName: 'Suburb' },
            { name: 'stateName', displayName: 'State', maxWidth: 150 },
            { name: 'postcode', displayName: 'Postcode', maxWidth: 100 },
            { name: 'phone', displayName: 'Phone', maxWidth: 160 },
            { name: 'typeName', displayName: 'Type', maxWidth: 120 },
            {
                field: 'id',
                enableSorting: false,
                displayName: '',
                maxWidth: 100,
                enableCellEdit: false,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center""><a href="' + formConfig.addEditUrl + '/{{row.entity.id}}">edit</a></div>'
            }
        ];

        // This is to watch the filter value changed, and call the getUsers again!
        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getDataGird();
            }
        });

        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.gridOptions);
        }

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            getDataGird();
        };

        function getDataGird() {
            var url = api_addressBook_search;
            url += '?pageSize=' + vm.searchOption.pageSize;
            url += '&pageNo=' + vm.searchOption.pageNumber;
            url += '&sortFields=' + vm.searchOption.sort;
            url += '&keyword=' + vm.searchOption.keyword;

            return httpService.get(url).then(function (response) {
                if (response.data.success) {
                    console.log(response.data.data.result);
                    vm.gridOptions.data = response.data.data.result;
                    vm.gridOptions.totalItems = response.data.data.totalCount;
                } else {
                    vm.errors = response.data.errors;
                }
            });
        }

        
    }
})();;
(function () {
    'use strict';

    window.app.controller('CdeTrainingDetailsController', CdeTrainingDetailsController);
    CdeTrainingDetailsController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        '$timeout', 'toaster', '$rootScope', 'uiGridConstants', 'moment'];

    function CdeTrainingDetailsController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        $timeout, toaster, $rootScope, uiGridConstants, moment) {

        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;
        vm.grantTrainingAccessToCde = grantTrainingAccessToCde;
        vm.unlockCdeTraining = unlockCdeTraining;
        vm.exportTrainingReport = exportTrainingReport;

        //grid details
        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: '-trainingDueDate',
            keyword: ''
        };

        function init() {
            getCdesRequireTrainingAccess();
            getCdeTrainingDetails();
            getCdesToUnlockTraining();
        }

        function grantTrainingAccessToCde(event, hcpId) {
            var url = api_cdeTrainingDetails_grantTrainingAccessToCde.replace('{hcpId}', hcpId);
            httpService.post(url)
                .then(function (response) {
                    vm.errors = [];
                    vm.errors = response.data.errors;

                    if (response.data.errors.length > 0) {
                        modelStateErrorBuilder.build(vm.errors, vm.model);
                        document.getElementById('page-wrapper').scrollIntoView();
                    }
                    else {
                        $rootScope.$broadcast("loader_show");
                        toaster.pop({
                            type: 'success',
                            title: 'Success',
                            body: 'Training access granted successfully',
                            timeout: 2500,
                            onHideCallback: function () {
                                $rootScope.$broadcast("loader_hide");
                            }
                        });
                        getCdesRequireTrainingAccess();
                        getCdeTrainingDetails();
                    }
                });
        }

        function unlockCdeTraining(cdeTrainingId) {
            var url = api_cdeTrainingDetails_unlockCdeTraining.replace('{cdeTrainingId}', cdeTrainingId);
            httpService.post(url)
                .then(function (response) {
                    vm.errors = [];
                    vm.errors = response.data.errors;

                    if (response.data.errors.length > 0) {
                        modelStateErrorBuilder.build(vm.errors, vm.model);
                        document.getElementById('page-wrapper').scrollIntoView();
                    }
                    else {
                        $rootScope.$broadcast("loader_show");
                        toaster.pop({
                            type: 'success',
                            title: 'Success',
                            body: 'Training unlocked successfully',
                            timeout: 2500,
                            onHideCallback: function () {
                                $rootScope.$broadcast("loader_hide");
                            }
                        });
                        getCdesToUnlockTraining();
                        getCdeTrainingDetails();
                    }
                });
        }

        function exportTrainingReport(e)
        {
            var timeZone = moment.tz.guess();
            var trainingId = e.currentTarget.attributes.data.nodeValue;
            var url = api_cdeTrainingDetails_exportTrainingReport.replace('{trainingId}', trainingId).replace('{0}', timeZone);
            utilitySvc.downloadFileFromApi(url);
        }

        //cde training details
        function getCdeTrainingDetails() {
            var browserTimeZone = moment.tz.guess();
            var url = api_cdeTrainingDetails_getCdeTrainingDetails;
            url = url.replace('{pageSize}', vm.searchOption.pageSize);
            url = url.replace('{pageNo}', vm.searchOption.pageNumber);
            url = url.replace('{sort}', vm.searchOption.sort);
            url = url.replace('{keyword?}', vm.searchOption.keyword);
            url = url.replace('{0}', browserTimeZone);

            httpService.get(url)
            .success(function (response) {
                var data = response.data;
                vm.cdeTrainingDetailsGridOptions.data = data.result;
                vm.cdeTrainingDetailsGridOptions.totalItems = data.totalCount;

                angular.forEach(vm.cdeTrainingDetailsGridOptions.data, function (record) {
                    if (record.trainingDueDate) {
                        record.trainingDueDate = moment.utc(record.trainingDueDate).local().format("DD/MM/YYYY");
                    }
                    if (record.lastPassedDate) {
                        record.lastPassedDate = moment.utc(record.lastPassedDate).local().format("DD/MM/YYYY");
                    }
                });
            })
        }

        vm.cdeTrainingDetailsGridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getCdeTrainingDetails);
        vm.cdeTrainingDetailsGridOptions.paginationPageSizes = [1, 5, 10, 25, 50, 100];
        vm.cdeTrainingDetailsGridOptions.columnDefs = [];
        var restOfColTrainingRecordsDefs = [
            { name: 'trainingDueDate', displayName: 'Training due Date', maxWidth: 150 },
            { name: 'lastPassedDate', displayName: 'Last passed date', maxWidth: 200 },            
            { name: 'moduleName', displayName: 'Module name', maxWidth: 1000 },
            { name: 'version', displayName: 'Version', maxWidth: 150 },
            { name: 'cdeName', displayName: 'CDE name', maxWidth: 650 },
            { name: 'numberOfAttempts', displayName: 'Number of failed attempts since last passing', maxWidth: 200 },
            { name: 'evaluationMarks', displayName: 'Evaluation Mark', maxWidth: 200 },
        ];
        vm.cdeTrainingDetailsGridOptions.appScopeProvider = vm;
        vm.cdeTrainingDetailsGridOptions.columnDefs = vm.cdeTrainingDetailsGridOptions.columnDefs.concat(restOfColTrainingRecordsDefs);
        
        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getCdeTrainingDetails();
            }
        });
        //end - cde training details

        //training access required details
        function getCdesRequireTrainingAccess() {
            var url = api_cdeTrainingDetails_cdesRequireTrainingAccess;
            url = url.replace('{pageSize}', vm.searchOption.pageSize);
            url = url.replace('{pageNo}', vm.searchOption.pageNumber);
            url = url.replace('{sort}', vm.searchOption.sort);

            httpService.get(url)
            .success(function (response) {
                var data = response.data;
                vm.cdeTrainingRequiredGridOptions.data = data.result;
                vm.cdeTrainingRequiredGridOptions.totalItems = data.totalCount;

                angular.forEach(vm.cdeTrainingRequiredGridOptions.data, function (record) {
                    if (record.registrationDate) {
                        record.registrationDate = moment.utc(record.registrationDate).local().format("DD/MM/YYYY");
                    }
                });
            })
        }

        vm.cdeTrainingRequiredGridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getCdesRequireTrainingAccess);
        vm.cdeTrainingRequiredGridOptions.paginationPageSizes = [1, 5, 10, 25, 50, 100];
        vm.cdeTrainingRequiredGridOptions.columnDefs = [];
        var restOfColDefs = [
            { name: 'registrationDate', displayName: 'Registration Date', maxWidth: 300 },
            { name: 'name', displayName: 'Name', maxWidth: 650 },
            { name: 'email', displayName: 'Email Address', maxWidth: 650 },
            {
                field: 'hcpId',
                maxWidth: 430,
                enableSorting: false,
                displayName: '',
                enableCellEdit: false,
                cellTemplate: '<div class="grid-button ui-grid-cell"><button type="button" id="grantAccess_{{row.entity.hcpId}}" class="btn btn-primary" ng-click="grid.appScope.grantTrainingAccessToCde($event, row.entity.hcpId)">Grant access</button></div>'
            }
        ];
        vm.cdeTrainingRequiredGridOptions.appScopeProvider = vm;
        vm.cdeTrainingRequiredGridOptions.columnDefs = vm.cdeTrainingRequiredGridOptions.columnDefs.concat(restOfColDefs);
        //end - training access required details

        //training access required details
        function getCdesToUnlockTraining() {
            var url = api_cdeTrainingDetails_getCdesToUnlockTraining;
            url = url.replace('{pageSize}', vm.searchOption.pageSize);
            url = url.replace('{pageNo}', vm.searchOption.pageNumber);
            url = url.replace('{sort}', vm.searchOption.sort);

            httpService.get(url)
            .success(function (response) {
                var data = response.data;
                vm.cdeTrainingUnlockGridOptions.data = data.result;
                vm.cdeTrainingUnlockGridOptions.totalItems = data.totalCount;

                angular.forEach(vm.cdeTrainingUnlockGridOptions.data, function (record) {
                    if (record.trainingDueOn) {
                        record.trainingDueOn = moment.utc(record.trainingDueOn).local().format("DD/MM/YYYY");
                    }
                    if (record.dateOfLastAttempt) {
                        record.dateOfLastAttempt = moment.utc(record.dateOfLastAttempt).local().format("DD/MM/YYYY");
                    }
                });
            })
        }

        vm.cdeTrainingUnlockGridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getCdesToUnlockTraining);
        vm.cdeTrainingUnlockGridOptions.paginationPageSizes = [1, 5, 10, 25, 50, 100];
        vm.cdeTrainingUnlockGridOptions.columnDefs = [];
        var restOfTrainingUnlockColDefs = [
            { name: 'trainingDueOn', displayName: 'Training due date', maxWidth: 300 },
            { name: 'modulename', displayName: 'Module name', maxWidth: 650 },
            { name: 'version', displayName: 'Version', maxWidth: 650 },
            { name: 'cdeName', displayName: 'CDE name', maxWidth: 650 },
            { name: 'numberOfAttempts', displayName: 'Number of attempts', maxWidth: 650 },
            { name: 'dateOfLastAttempt', displayName: 'Date of last attempt', maxWidth: 650 },
            {
                field: 'cdeTrainingId',
                maxWidth: 430,
                enableSorting: false,
                displayName: '',
                enableCellEdit: false,
                cellTemplate: '<div class="grid-button ui-grid-cell"><button type="button" id="unlockTraining_{{row.entity.cdeTrainingId}}" class="btn btn-primary" ng-click="grid.appScope.unlockCdeTraining(row.entity.cdeTrainingId)">Unlock</button></div>'
            }
        ];
        vm.cdeTrainingUnlockGridOptions.appScopeProvider = vm;
        vm.cdeTrainingUnlockGridOptions.columnDefs = vm.cdeTrainingUnlockGridOptions.columnDefs.concat(restOfTrainingUnlockColDefs);
        //end - training access required details
    }

})();;
(function () {
    'use strict';

    window.app.controller('TrainingCourseContentController', TrainingCourseContentController);
    TrainingCourseContentController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', 'modalService'];

    function TrainingCourseContentController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, modalService) {

        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;

        function init() {
            $(".carousel").carousel();

            var url = api_cdeTrainingDetails_getTrainingCourseImages.replace('{trainingType}', formConfig.trainingType);
            httpService.get(url)
            .then(function (response) {
                var data = response.data;
                vm.model.imagesPath = data.data;
            });
        }        
    }
})();;
(function () {
    'use strict';

    window.app.controller('TrainingEvaluationController', TrainingEvaluationController);

    TrainingEvaluationController.$inject = ['$scope', '$window', 'httpService',
        '$sessionStorage', '$rootScope', 'formConfig'];

    function TrainingEvaluationController($scope, $window, httpService,
        $sessionStorage, $rootScope, formConfig) {
        var vm = this;
        var model = {};
        vm.submit = submit;
        vm.onTrainingPass = onTrainingPass;
        vm.errors = [];        
        vm.refreshPage = refreshPage

        function submit() {
            model.Answers = [];
            vm.errors = [];

            $(".questions .item").each(function (index) {
                var questionId = $(this).attr("data-id");
                var isMultiDopDown = $(this).hasClass("multi-answer-dropdown");

                if (isMultiDopDown) {
                    $("select[name='question-" + questionId + "']").each(function (index) {
                        var answer = {
                            QuestionId: questionId,
                            AnswerId: $(this).attr("data-val"),
                            Value: $(this).val() != "" && $(this).val() != undefined && $(this).val() != null ? $(this).val() : null
                        }
                        model.Answers.push(answer);
                    });
                }
                else {
                    var obj = $("input[name='question-" + questionId + "']:checked");
                    var answerId = "";

                    answerId = obj != null && obj !== undefined && obj.length > 0 ? obj.attr("data-val") : null;

                    var answer = {
                        QuestionId: questionId,
                        AnswerId: answerId,
                        Value: "selected"
                    }
                    model.Answers.push(answer);
                }
            });

            if (IsAnsweredForAllQuestions()) {
                var url = api_cdeTrainingDetails_getEvaluationResults.replace('{trainingType}', formConfig.trainingType).replace('{hcpId}', formConfig.hcpId);
                httpService.post(url, model.Answers).
                then(function (response) {
                    // Server-side validation
                    if (response.data.success) {
                        vm.results = response.data.data;                        
                        if (vm.results.isTrainingPassed)
                            showModal("Congratulations");
                        else if (!vm.results.isTrainingPassed && !vm.results.isEvaluationLocked)
                            showModal("PleaseReTry");
                        else if (!vm.results.isTrainingPassed && vm.results.isEvaluationLocked)
                            showModal("Locked");
                    }
                    else if (response.data.errors.length == 0) {
                        if (response.data.data != null) {
                            showFailResult(response);
                        }
                    }
                });
            }
            else {
                vm.errors.push({
                    message: "Please answer all the questions"
                });
                document.getElementById('wrapper').scrollIntoView();
            }
        }

        function IsAnsweredForAllQuestions() {
            for (var i = 0; i < model.Answers.length; i++) {
                if (model.Answers[i].AnswerId == null || model.Answers[i].AnswerId == undefined) {
                    return false;
                    break;
                }
            }
            return true;
        }

        function showFailResult(response) {
            $(".questions .item").each(function (index) {
                var titleDom = $(this).children(".title");

                //Initialize color
                titleDom.find("p[class^='question-status']").removeClass().addClass("question-status text-blue");

                var questionId = $(this).attr("data-id");
                titleDom.find("p[class^='question-status']").removeClass("text-blue").addClass("correct-question");

                for (var i in response.data.data) {
                    if (!response.data.data[i].isCorrect
                        && parseInt(questionId) == response.data.data[i].questionId) {
                        titleDom.find("p[class^='question-status']").removeClass("correct-question").addClass("wrong-question");
                        break;
                    }
                }
            });
            showModal("PleaseReTry");
        }

        function showSuccessResult() {
            //$(".questions .item").each(function (index) {
            //    var titleDom = $(this).children(".title");

            //    //Initialize color
            //    titleDom.find("p[class^='question-status']").removeClass().addClass("question-status text-blue");

            //    var questionId = $(this).attr("data-id");
            //    titleDom.find("p[class^='question-status']").removeClass("text-blue").addClass("correct-question");

            //});

            showModal("Congratulations");
        }

        function showModal(name) {
            var height = $(window).height();
            var heightModal = 205;
            $("#" + name + " " + ".modal-dialog").height(heightModal)
            var marginTop = (height - heightModal) / 2;
            $("#" + name + " " + ".modal-dialog").css("margin-top", marginTop - marginTop * 0.2);
            $("#" + name).modal("show");
        }

        function refreshPage() {
            $window.location.reload();
        }

        function onTrainingPass() {
            $window.location = "/dashboard";
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('HHTrainingController', HHTrainingController);
    HHTrainingController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', 'modalService'];

    function HHTrainingController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, modalService) {

        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;
        vm.nextTab = nextTab;
        vm.activeTabIndex = 0;
        vm.activeTabSelected = activeTabSelected;

        function init() {
            
        }

        function nextTab() {
            if (vm.activeTabIndex < 2) {
                vm.activeTabIndex = vm.activeTabIndex + 1;
            }
        }

        function activeTabSelected(a) {
            vm.activeTabIndex = a;
        }        
    }
})();;
(function () {
    'use strict';

    window.app.controller('PVTrainingController', PVTrainingController);
    PVTrainingController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', 'modalService'];

    function PVTrainingController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, modalService) {

        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;        
        vm.nextTab = nextTab;
        vm.activeTabIndex = 0;
        vm.activeTabSelected = activeTabSelected;

        function init() {
            
        }

        function nextTab() {
            if (vm.activeTabIndex < 2) {                
                vm.activeTabIndex = vm.activeTabIndex + 1;
            }
        }

        function activeTabSelected(a) {
            vm.activeTabIndex = a;
        }
    }

})();;
(function () {
    'use strict';

    window.app.controller('SaxendaTrainingController', SaxendaTrainingController);
    SaxendaTrainingController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', 'modalService'];

    function SaxendaTrainingController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, modalService) {

        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;
        vm.nextTab = nextTab;
        vm.activeTabIndex = 0;
        vm.activeTabSelected = activeTabSelected;

        function init() {
            
        }

        function nextTab() {
            if (vm.activeTabIndex < 2) {
                vm.activeTabIndex = vm.activeTabIndex + 1;
            }
        }

        function activeTabSelected(a) {
            vm.activeTabIndex = a;
        }
    }

})();;
//if (Function('/*@cc_on return document.documentMode===10@*/')()) {
//    window.oldIE = true;
//}
//if (/*@cc_on!@*/false) {
//    window.oldIE = true;
//}

function isValidBrowserInformation() {
    var browser = get_browser();
    var browserName = browser.name.toLowerCase();
    var version = parseInt(browser.version);

    if (browserName === 'msie' && version <= 8 //IE < 9
            || (browserName === 'chrome' && version < 50)
            || (browserName === 'safari' && version < 9)) {
        return false;
    }
    return true;
}

function get_browser() {
    var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return { name: 'IE', version: (tem[1] || '') };
    }
    if (M[1] === 'Chrome') {
        tem = ua.match(/\bOPR\/(\d+)/)
        if (tem != null) { return { name: 'Opera', version: tem[1] }; }
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) { M.splice(1, 1, tem[1]); }
    return {
        name: M[0],
        version: M[1]
    };
}

function getQueryString(name, url) {
    if (!url) {
        url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&](" + name + ")(=([^&#]*)|&|#|$)", "i"),
        results = regex.exec(url);
    if (!results) return null;

    var obj = {};
    if (!results[3]) {
        obj[results[1]] = '';
    }
    else {
        var val = decodeURIComponent(results[3].replace(/\+/g, " "));
        obj[results[1]] = val;
    }
    return obj;
}

function getQueryStringValue(name, url) {
    var obj = getQueryString(name, url);
    if (obj) {
        return Object.values(obj)[0];
    }
    else {
        return null;
    }
}

function redirect(path) {
    /// <summary>
    /// Redirect to path
    /// </summary>

    window.location.replace(path);
}

var common = {
    openLoading: function () {
        $("html").addClass("loading");
    },

    closeLoading: function () {
        $("html").removeClass("loading");
    },

    disableScreen: function () {
        // creates <div class="overlay"></div> and
        // adds it to the DOM
        var div = document.createElement("div");
        div.className += "overlay";
        document.body.appendChild(div);
    },

    activeScreen: function () {
        $("body .overlay").remove();
    },

    maskNumberOnly: function () {
        $(".mask-number-only").inputmask('9');
    },

    numberOnly: function () {
        $(".number-only").keydown(function (e) {
            // Allow: backspace, delete, tab, escape, enter and .
            if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
                // Allow: Ctrl+A, Command+A
                (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                // Allow: home, end, left, right, down, up
                (e.keyCode >= 35 && e.keyCode <= 40)) {
                // let it happen, don't do anything
                return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
        });
    },

    maskMobile: function ($element) {
        $element.inputmask('9999 999 999');
    },

    maskPhone: function ($element) {
        $element.inputmask('(99) 9999 9999');
    },

    maskDate: function ($element) {
        $element.inputmask('99/99/9999');
    },

    clickDatePicker: function () {
        // Date picker
        setTimeout(function () {
            $(document).on("click", ".datepicker", function () {
                $(this).datetimepicker({
                    pickTime: false,
                    format: "DD/MM/YYYY"
                }).on("change", function () {
                    angular.element($(this)).triggerHandler("input");
                }).focus();
            });
        }, 1);
    },

    validateDate: function () {
        $.validator.addMethod('date',
            function (value, element) {
                if (this.optional(element)) {
                    return true;
                }

                var ok = true;
                try {
                    $.datepicker.parseDate('dd/mm/yy', value);
                }
                catch (err) {
                    ok = false;
                }
                return ok;
            });
    }
}

var CONSTANTS = {
    get MOBILE_FORMAT() {
        return "9999 999 999";
    },
    get DATE_FORMAT() {
        return "99/99/9999";
    }
};
(function () {
    window.app.directive('addressDetails', function () {
        return {
            restrict: 'E',
            scope: {
                labelprepend: '@?',
                controlprepend: '@?',
                model: '=',
                form: '=',
                states: '=',
                ngDisabled: '=?',
                ngRequired: '=?'
            },
            link: function (scope, iElem, iAttrs) {
                scope.disabled = false;
                if (iAttrs.disabled || iAttrs.disabled === '') {
                    scope.disabled = true;
                }
                scope.required = false;
                if (iAttrs.required || iAttrs.required === '') {
                    scope.required = true;
                }

                scope.disableInputs = function () {
                    return scope.disabled || scope.ngDisabled;
                }
                scope.requireInputs = function () {
                    return scope.required || scope.ngRequired;
                }
            },
            templateUrl: '/templates/address.html'
        }
    });
})();;
(function () {
    'use strict';
    window.app.directive('advTypeAheadCtrl', advTypeAheadCtrl);

    advTypeAheadCtrl.$inject = ['$compile'];

    // NOTE: variable used: noResults, loadingItems

    function advTypeAheadCtrl($compile) {
        return {
            restrict: 'E',
            transclude: {
                'titleLabelTemplate': 'titleLabel',
                'controlItemsTemplate': '?controlItems',
                'loadingItemsTemplate': '?loadingItems',
                'noResultsTemplate': '?noResults'
            },
            scope: {
                typeaheadTemplateUrl: '@',
                typeaheadMinLength: '=?',
                getItems: '=?',
                selectItem: '=?',
                id: '@?',
                name: '@',
                placeholder: '@?',
                ngModel: '=',
                ngDisabled: '=?',
                ngRequired: '=?',
                ngSearchDisabled: '=?',
                inputTextClass: '=?',
                advancedGetItems: '&?',
                advancedSelectItem: '&?'
            },
            replace: true,
            template:
'<div class="form-group">\
    <label for="{{id}}" ng-transclude="titleLabelTemplate"></label>\
    <div window-resize ng-class="{\'input-group\' : (inputBtnExists && windowWidth >= 768)}">\
        <input autocomplete="off" type="text" class="form-control typeahead-input-text" id="{{id}}" name="{{name}}" ng-required="required || ngRequired" ng-disabled="disabled || ngDisabled"\
                uib-typeahead="item.typeahead_displayField for item in onGetItems($viewValue) | limitTo:limitTo" typeahead-template-url="{{typeaheadTemplateUrl}}"\
                typeahead-on-select="selectItem($item)" typeahead-no-results="noResults" typeahead-loading="loadingItems" aria-autocomplete="list" placeholder="{{placeholder}}"\
                ng-model="ngModel" typeahead-min-length="typeaheadMinLength" ng-class="inputTextClass" />\
        <span class="input-group-btn" ng-transclude="controlItemsTemplate"></span>\
    </div>\
    <div ng-if="!(ngSearchDisabled)">\
        <div ng-transclude="loadingItemsTemplate" ng-if="loadingItems"><i class="glyphicon glyphicon-refresh" style=""></i></div>\
        <div ng-transclude="noResultsTemplate" ng-if="ngModel && ngModel != \'\' && ngModel.length >= typeaheadMinLength && noResults"><i class="glyphicon glyphicon-remove"></i>No Results Found</div>\
    </div>\
</div>'
            ,
            compile: function compile(ele, attrs, transclude) {
                var eleHtml = ele.html();
                eleHtml = eleHtml.replace('typeahead_displayField', attrs.displayField);
                if (attrs.advancedGetItems) {
                    eleHtml = eleHtml.replace('onGetItems($viewValue)', attrs.advancedGetItems);
                }
                if (attrs.advancedSelectItem) {
                    eleHtml = eleHtml.replace('selectItem($item)', attrs.advancedSelectItem);
                }
                ele.html(eleHtml);

                //Convert camelCase to dash
                function toDash(str) {
                    return str.replace(/\W+/g, '-')
                              .replace(/([a-z\d])([A-Z])/g, '$1-$2');
                }

                for (var key in attrs) {
                    if (key[0] !== '$' && key !== 'class') {
                        //Remove all attribute to the top level element
                        ele.removeAttr(toDash(key));
                    }
                }

                return {
                    pre: function (scope, iElem, iAttrs) {
                        scope.inputBtnExists = false;
                        scope.typeaheadMinLength = scope.typeaheadMinLength || 3;

                        scope.disabled = false;
                        if (iAttrs.disabled || iAttrs.disabled === '') {
                            scope.disabled = true;
                        }

                        scope.required = false;
                        if (iAttrs.required || iAttrs.required === '') {
                            scope.required = true;
                        }

                        if (!scope.advancedGetItems) {
                            scope.onGetItems = function () {
                                if (!scope.ngSearchDisabled) {
                                    return scope.getItems(arguments[0]);
                                }
                            }
                        }
                    },
                    post: function (scope, iElem, iAttrs) {
                        var buttonTransclusionContents = iElem.find('span.input-group-btn').contents();
                        if (buttonTransclusionContents.length > 0) {
                            scope.inputBtnExists = true;
                        }
                    }
                }
            }
        };
    }
})();;
'use strict';
(function () {
    window.app.directive('compareTo', function () {
        return {
            scope: {
                targetModel: '=compareTo',
                compareOperator: '@?compareToOperator',
                transformFunc: '=?compareToTransformFunc'
            },
            require: 'ngModel',
            link: function postLink(scope, element, attrs, ctrl) {

                var compare = function () {

                    var e1 = element.val();
                    if (scope.transformFunc) {
                        e1 = scope.transformFunc(e1);
                    }

                    if (e1 === undefined || e1 === null || (typeof e1 === 'string' && e1.trim() === '')) {
                        return true;
                    }

                    var e2 = scope.targetModel;
                    if (scope.transformFunc) {
                        e2 = scope.transformFunc(e2);
                    }

                    if (e2 !== null) {
                        if (scope.compareOperator) {
                            switch (scope.compareOperator) {
                                case '==':
                                    return e1 == e2;
                                case '>':
                                    return e1 > e2;
                                case '<':
                                    return e1 < e2;
                                case '>=':
                                    return e1 >= e2;
                                case '<=':
                                    return e1 <= e2;
                                default:
                                    return e1 === e2;
                            }
                        }
                        else {
                            return e1 === e2;
                        }
                    }

                    return false;
                };

                scope.$watch(compare, function(newValue) {
                    ctrl.$setValidity('compare', newValue);
                });
            }
        };
    });
})();;
(function () {
    window.app.directive('dob', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, elem, attr, ctrl) {
                function checkDOB(value) {
                    var now = new Date();
                    var dobPlusOneYear = moment(value).add(1, 'year').toDate();
                    return dobPlusOneYear < now;
                }

                function validate(value) {
                    var valid = ctrl.$isEmpty(value);
                    if (!valid) {
                        valid = checkDOB(value);
                    }
                    ctrl.$setValidity('dob', valid);
                    return value;
                }

                ctrl.$parsers.push(validate);
            }
        }
    });

    window.app.directive('date',
        ['dateFilter', function (dateFilter) {
            return {
                require: 'ngModel',
                link: function (scope, elm, attrs, ctrl) {
                    var dateFormat = attrs['date'] || 'yyyy-MM-dd';

                    ctrl.$formatters.unshift(function (modelValue) {
                        return dateFilter(modelValue, dateFormat);
                    });
                }
            };
        }]);
})();;
(function () {
    window.app.directive('elearningModule', ['httpService', function (httpService) {
        return {
            restrict: 'E',
            scope: {
                elearningModule: '='
            },
            link: function (scope, iElem, iAttrs) {
                scope.sendVideoCompleteEmailToHcp = function () {
                    var url = api_webinar_video_complete.replace('{0}', scope.elearningModule.videoTitle);
                    httpService.post(url)
                    .success(function (response) {
                    });
                }

                scope.loadAndPlayVideo = function (videoId) {
                    var videoElement = $("#" + videoId);
                    videoElement.get(0).load();
                    videoElement.get(0).play();
                }
            },
            templateUrl: '/templates/elearningmodules.html'
        }
    }]);
})();;
(function () {
    window.app.directive('hcpAddressDetails', function () {
        return {
            restrict: 'E',
            scope: {
                labelprepend: '@?',
                controlprepend: '@?',
                model: '=',
                form: '=',
                states: '=',
                ngDisabled: '=?',
                ngRequired: '=?',
                isRequiredDisabled:'=?'
            },
            link: function (scope, iElem, iAttrs) {
                scope.disabled = false;
                scope.disabledAddress = false;
                scope.disabledSuburbStatePostcodeInputs = false;

                if (iAttrs.disabled || iAttrs.disabled === '') {
                    scope.disabled = true;
                    scope.disabledAddress = true;
                }
                scope.required = false;
                if (iAttrs.required || iAttrs.required === '') {
                    scope.required = true;
                }

                scope.requireInputs = function () {
                    return scope.required || scope.ngRequired;
                }

                scope.disableAddressInputs = function () {
                    return scope.disabledAddress || scope.ngDisabled;
                }

                scope.disabledSuburbStatePostcode = function () {
                    //if addrLine1 is null then the address is associated to profile else address is associated to institution
                    if (scope.model != undefined && scope.model.id != undefined && scope.model.id != null && scope.model.addrLine1 != null) {
                        scope.disabledSuburbStatePostcodeInputs = true;
                    }
                    else
                        scope.disabledSuburbStatePostcodeInputs = false;
                    return scope.disabledSuburbStatePostcodeInputs;
                }
            },
            templateUrl: '/templates/address.html'
        }
    });
})();;

(function () {
    window.app.directive('lightboxDirective', function () {
        return {
            restrict: 'E', // applied on 'element'
            transclude: true, // re-use the inner HTML of the directive
            template: '<section ng-transclude></section>', // need this so that inner HTML will be used
        }
    });
})();;
(function () {
    'use strict';

    window.app.directive('loader', loader);

    loader.$inject = ['$rootScope'];

    function loader($rootScope) {
        return function ($scope, element, attrs) {
            element.hide();

            $scope.$on("loader_show", function () {
                return element.show();
            });
            $scope.$on("loader_hide", function () {
                return element.hide();
            });
        };
    }
})();;
(function () {'use strict';
    window.app.directive('navigationCtrl', navigationCtrl);

    navigationCtrl.$inject = ['$window', 'userRoles'];

    function navigationCtrl($window) {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                menus: '=',
                roles: '=?'
            },
            template: '<ul>\
                        <li ng-class="{ \'active\': isSelected(menu) ,\'first\' : $first, \'dropdown\' : hasChild(menu) }"\
                            ng-repeat="menu in menus | filter: hasAccess | orderBy: \'sequence\'">\
                            <a ng-if="!hasChild(menu)" ng-href="{{menu.path}}">{{menu.name}}</a>\
                            <a ng-if="hasChild(menu)" href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{{menu.name}} <span class="caret"></span></a>\
                            <ul ng-if="hasChild(menu)" class="dropdown-menu">\
                                <li ng-repeat="menu2 in menu.childItems" ng-class="{ \'active\': isSelected(menu2) }"><a ng-href="{{menu2.path}}">{{menu2.name}}</a></li>\
                            </ul>\
                        </li>\
                    </ul>',
            link: function (scope, element, attrs) {
                scope.isSelected = isSelected;
                scope.hasAccess = hasAccess;
                scope.hasChild = hasChild;

                function isSelected(menu) {
                    if ($window.location.pathname.toLowerCase() == menu.path.toLowerCase()) {
                        return true;
                    }
                    return false;
                }

                function hasChild(menu) {
                    return (menu.childItems && menu.childItems.length > 0);
                }

                function hasAccess(nav) {
                    var isAuthorised = false;
                    if (scope.roles && nav.role && nav.role !== '') {
                        angular.forEach(scope.roles, function (userRole) {
                            console.log('navRole =', nav.role, ', userRole =', userRole);
                            if (userRole === nav.role) {
                                isAuthorised = true;
                                return;
                            }
                        });
                    }
                    else {
                        isAuthorised = true;
                    }

                    return isAuthorised;
                }
            }
        }
    }
})();;
(function () {
    window.app.directive('numberSelection', function () {
        return {
            restrict: 'E',
            scope: {
                selectedValue: '=',
                number: '='
            },
            link: function (scope) {
                scope.numberArray = new Array();
                for (var i = 1; i <= scope.number; i++) {
                    scope.numberArray.push(i);
                }

                scope.setSelectedValue = function (val) {
                    scope.selectedValue = val;
                }
            },
            template: '<div class="btn-group"><button ng-repeat="num in numberArray" type="button" class="btn" ng-click="setSelectedValue(num)" ng-class="{ \'btn-primary\': (num == selectedValue), \'btn-default\': (num != selectedValue) }">{{num}}</button></div>'
        }
    });
})();;
(function () {
    window.app.directive('patientDoctorAddressDetails', function () {
        return {
            restrict: 'E',
            scope: {
                labelprepend: '@?',
                controlprepend: '@?',
                model: '=',
                form: '=',
                states: '=',
                ngDisabled: '=?',
                ngRequired: '=?',
                isRequiredDisabled: '=?',
                isDiabetesSuburbDisabled: '=?',
                isDiabetesInstitutionAddressDisabled: '=?'
            },
            link: function (scope, iElem, iAttrs) {
                scope.disabled = false;
                scope.disabledAddress = false;
                //scope.disabledSuburbStatePostcodeInputs = true;

                if (iAttrs.disabled || iAttrs.disabled === '') {
                    scope.disabled = true;
                    scope.disabledAddress = true;
                }
                scope.required = false;
                if (iAttrs.required || iAttrs.required === '') {
                    scope.required = true;
                }

                scope.requireInputs = function () {
                    return scope.required || scope.ngRequired;
                }

                //scope.disableAddressInputs = function () {
                //    return scope.disabledAddress || scope.ngDisabled;
                //}

                scope.disableAddressInputs = function () {
                    return scope.isDiabetesInstitutionAddressDisabled;
                }

                scope.disabledSuburbStatePostcode = function () {                    
                    return scope.isDiabetesSuburbDisabled;
                }
            },
            templateUrl: '/templates/address.html'
        }
    });
})();;
(function () {
    window.app.directive('phone', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, elem, attr, ctrl) {
                function IsPhoneNumber(value) {
                    value = value === undefined || value === null ? "" : value;
                    var regex = /[0-9-()+]{3,20}/
                    var val = $.trim(value.replace(/\_/g, '').replace(/\ /g, '').replace(/\)/g, '').replace(/\(/g, ''));
                    return regex.test(val) && (val.length == 10 || val.length == 0);
                }

                function validate(value) {
                    var valid = ctrl.$isEmpty(value);
                    if (!valid) {
                        valid = IsPhoneNumber(value);
                    }
                    ctrl.$setValidity('phone', valid);
                    return value;
                }

                ctrl.$parsers.push(validate);
            }
        }
    });
})();;
(function () {
    window.app.directive('postcode', function () {
        return {
            restrict: 'A',
            require: 'ngModel',            
            link: function (scope, elem, attr, ctrl) {
                function IsPostCode(value) {
                    value = value === undefined ? "" : value;
                    var regex = /\d{3,4}/
                    var val = $.trim(value);
                    return regex.test(val) && val != "000" && val != "0000";
                }                

                function validate(value) {
                    var valid = ctrl.$isEmpty(value);
                    if (!valid) {
                        valid = IsPostCode(value);
                    }
                    ctrl.$setValidity('postcode', valid);
                    return value;
                }

                ctrl.$parsers.push(validate);
            }
        }
    });
})();;
(function () {
    window.app.directive('requireChecked', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, elm, attr, ctrl) {
                if (!ctrl) return;

                ctrl.$validators.requireChecked = function (modelValue, viewValue) {
                    return viewValue;
                };

                attr.$observe('requireChecked', function () {
                    ctrl.$validate();
                });
            }
        }
    });
})();;
(function () {
    'use strict';
    window.app.directive('strictEmail', strictEmail);

    strictEmail.$inject = ['$compile'];

    function strictEmail() {
        return {
            require : 'ngModel',
            link : function(scope, element, attrs, ngModel) {
                // /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/
                var regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
                var EMAIL_REGEX = new RegExp(regex, "i");

                ngModel.$validators["email"] = function (modelValue, viewValue) {
                    var value = modelValue || viewValue;
                    return ngModel.$isEmpty(value) || EMAIL_REGEX.test(value);
                };
            }
        }
    }
})();;
(function () {
    'use strict';
    window.app.directive('typeAheadCtrl', typeAheadCtrl);

    typeAheadCtrl.$inject = ['$compile', 'httpService'];

    function typeAheadCtrl($compile, httpService) {
        return {
            restrict: 'E',
            transclude: {
                'titleLabel': 'titleLabel'
            },
            scope: {
                controlId: '@',
                controlName: '@',
                inputText: '=?',
                displayField: '@',
                onGetItems: '=',
                form: '=',
                typeaheadTemplateUrl: '@',
                onSelectItem: '=',
                onCreateNew: '=',
                onClear: '=',
                isDisabled: '=',
                allowEditItem: '=?',
                initialItem: '=?',
                mode: '=?',
                ngDisabled: '=?',
                ngRequired: '=?',
                placeholder: '@?',
                editLabel: '@?',
                createLabel: '@?',
                clearLabel: '@?'
            },
            templateUrl: '/templates/typeAheadControl.html',
            compile: function compile(el, attrs, transclude) {
                var eleHtml = el.html();
                eleHtml = eleHtml.replace('typeahead_displayField', attrs.displayField);
                el.html(eleHtml);

                return {
                    pre: function (scope, iElem, iAttrs) {
                        scope.hasInitialItem = false;
                        scope.selectedItem = undefined;
                        scope.selectItem = selectItem;
                        scope.editItem = editItem;
                        scope.createNew = createNew;
                        scope.clear = clear;
                        scope.getItems = getItems;
                            
                        scope.disabled = false;
                        if (iAttrs.disabled || iAttrs.disabled === '') {
                            scope.disabled = true;
                        }
                        scope.required = false;
                        if (iAttrs.required || iAttrs.required === '') {
                            scope.required = true;
                        }

                        scope.$watch('initialItem', function (newValue, oldValue) {
                            if (!scope.hasInitialItem && newValue !== undefined) {
                                console.log('initialItem is initialised...');
                                scope.selectedItem = scope.initialItem;
                                scope.hasInitialItem = true;
                            }
                        });

                        scope.$watch('inputText', function (newValue, oldValue) {
                            scope.isDisabled = getDisableStatus();
                        });
                        scope.$watch('mode', function (newValue, oldValue) {
                            scope.isDisabled = getDisableStatus();
                        });

                        function getDisableStatus() {
                            return scope.disabled || scope.ngDisabled ||
                                scope.mode === undefined ||
                                (scope.mode === 'add' && (scope.inputText === undefined || scope.inputText === ''));
                        }

                        function selectItem(item) {
                            scope.selectedItem = item;
                            scope.onSelectItem(item);
                        }

                        function editItem() {
                            scope.mode = 'edit';
                        }

                        function createNew() {
                            scope.mode = 'add';
                            scope.selectedItem = undefined;
                            scope.onCreateNew();
                        }

                        function clear() {
                            scope.selectedItem = undefined;
                            scope.noResults = undefined;
                            scope.mode = undefined;
                            scope.inputText = undefined;
                            scope.onClear();
                        }

                        function getItems(value) {
                            if (scope.mode === undefined) {
                                return scope.onGetItems(value);
                            }
                            return [];
                        }
                    },
                    post: function (scope, iElem, iAttrs) {
                    }
                }
            }
        };
    }
})();;
(function () {
    'use strict';
    window.app.directive('typeAheadCtrlSearch', typeAheadCtrlSearch);

    typeAheadCtrlSearch.$inject = ['$compile', 'httpService'];

    function typeAheadCtrlSearch($compile, httpService) {
        return {
            restrict: 'E',
            transclude: {
                'titleLabel': 'titleLabel'
            },
            scope: {
                controlId: '@',
                controlName: '@',
                inputText: '=',
                displayField: '@',
                onGetItems: '=',
                form: '=',
                typeaheadTemplateUrl: '@',
                onSelectItem: '=',
                onCreateNew: '=',
                allowEditItem: '=?',
                initialItem: '=?',                
                mode: '=?',
                ngDisabled: '=?',
                ngRequired: '=?',
                placeHolder: '@?',
                editLabel: '@?',
                createLabel: '@?',
                clearLabel: '@?'
            },
            templateUrl: '/templates/typeAheadControlSearch.html',
            compile: function compile(el, attrs, transclude) {
                var eleHtml = el.html();
                eleHtml = eleHtml.replace('typeahead_displayField', attrs.displayField);
                el.html(eleHtml);

                return {
                    pre: function (scope, iElem, iAttrs) {
                        scope.hasInitialItem = false;
                        scope.selectedItem = undefined;
                        scope.selectItem = selectItem;
                        scope.createNew = createNew;
                        scope.getItems = getItems;

                        scope.disabled = true;
                        if (iAttrs.disabled || iAttrs.disabled === '') {
                            scope.disabled = true;
                        }
                        scope.required = false;
                        if (iAttrs.required || iAttrs.required === '') {
                            scope.required = true;
                        }

                        scope.$watch('initialItem', function (newValue, oldValue) {
                            if (!scope.hasInitialItem && newValue !== undefined) {
                                console.log('initialItem is initialised...');
                                scope.selectedItem = scope.initialItem;
                                scope.hasInitialItem = true;
                            }
                        });

                        scope.$watch('inputText', function (newValue, oldValue) {
                            scope.isDisabled = getDisableStatus();
                        });
                        scope.$watch('mode', function (newValue, oldValue) {
                            scope.isDisabled = getDisableStatus();
                        });

                        function getDisableStatus() {
                            return scope.disabled || scope.ngDisabled ||
                                scope.mode === undefined ||
                                (scope.mode === 'add' && (scope.inputText === undefined || scope.inputText === ''));
                        }

                        function selectItem(item) {
                            scope.selectedItem = item;
                            //scope.disabled = false;
                            scope.onSelectItem(item);
                        }

                        function createNew() {
                            //scope.mode = 'add';
                            scope.selectedItem = undefined;
                            //scope.disabled = true;
                            scope.onCreateNew();
                        }

                        function getItems(value) {
                            if (scope.mode === undefined) {
                                return scope.onGetItems(value);
                            }
                            return [];
                        }
                    },
                    post: function (scope, iElem, iAttrs) {
                    }
                }
            }
        };
    }
})();;
(function () {
    window.app.directive('uiGridEditDatepicker', ['$timeout', '$document', 'uiGridConstants', 'uiGridEditConstants', function ($timeout, $document, uiGridConstants, uiGridEditConstants) {
        return {
            template: function (element, attrs) {
                var html = '<div class="datepicker-wrapper" ><input type="text" uib-datepicker-popup="dd/MM/yyyy" datepicker-options="datepickerOptions" class="date-picker" datepicker-append-to-body="true" is-open="isOpen" ng-model="datePickerValue" ng-change="changeDate($event)"/></div>';
                return html;
            },
            require: ['?^uiGrid', '?^uiGridRenderContainer'],
            scope: true,
            compile: function () {
                return {
                    pre: function ($scope, $elm, $attrs) {
                        if ($attrs.datepickerOptions) {
                            if ($scope.col.grid.appScope[$attrs.datepickerOptions]) {
                                $scope.datepickerOptions = $scope.col.grid.appScope[$attrs.datepickerOptions];
                            }
                        }
                    },
                    post: function ($scope, $elm, $attrs, controllers) {
                        var setCorrectPosition = function () {
                            var gridElement = $('.ui-grid-viewport');
                            var gridPosition = {
                                width: gridElement.outerWidth(),
                                height: gridElement.outerHeight(),
                                offset: gridElement.offset()
                            };
                            debugger;
                            var cellElement = $($elm);
                            var cellPosition = {
                                width: cellElement.outerWidth(),
                                height: cellElement.outerHeight(),
                                offset: cellElement.offset()
                            };

                            var datepickerElement = $('div[uib-datepicker-popup-wrap]');
                            var datepickerPosition = {
                                width: datepickerElement.outerWidth(),
                                height: datepickerElement.outerHeight()
                            };

                            var setCorrectTopPositionInGrid = function () {
                                var topPosition;
                                var freePixelsOnBottom = gridPosition.height - (cellPosition.offset.top - gridPosition.offset.top) - cellPosition.height;
                                var freePixelsOnTop = gridPosition.height - freePixelsOnBottom - cellPosition.height;
                                var requiredPixels = (datepickerPosition.height - cellPosition.height) / 2;
                                if (freePixelsOnBottom >= requiredPixels && freePixelsOnTop >= requiredPixels) {
                                    topPosition = cellPosition.offset.top - requiredPixels + 10;
                                } else if (freePixelsOnBottom >= requiredPixels && freePixelsOnTop < requiredPixels) {
                                    topPosition = cellPosition.offset.top - freePixelsOnTop + 10;
                                } else {
                                    topPosition = gridPosition.height - datepickerPosition.height + gridPosition.offset.top - 20;
                                }
                                return topPosition;
                            };

                            var setCorrectTopPositionInWindow = function () {
                                var topPosition;
                                var windowHeight = window.innerHeight - 10;

                                var freePixelsOnBottom = windowHeight - cellPosition.offset.top;
                                var freePixelsOnTop = windowHeight - freePixelsOnBottom - cellPosition.height;
                                var requiredPixels = (datepickerPosition.height - cellPosition.height) / 2;
                                if (freePixelsOnBottom >= requiredPixels && freePixelsOnTop >= requiredPixels) {
                                    topPosition = cellPosition.offset.top - requiredPixels;
                                } else if (freePixelsOnBottom >= requiredPixels && freePixelsOnTop < requiredPixels) {
                                    topPosition = cellPosition.offset.top - freePixelsOnTop;
                                } else {
                                    topPosition = windowHeight - datepickerPosition.height - 10;
                                }
                                return topPosition;
                            };


                            var newOffsetValues = {};
                            var isFreeOnRight = (gridPosition.width - (cellPosition.offset.left - gridPosition.offset.left) - cellPosition.width) > datepickerPosition.width;
                            if (isFreeOnRight) {
                                newOffsetValues.left = cellPosition.offset.left + cellPosition.width;
                            } else {
                                newOffsetValues.left = cellPosition.offset.left;
                            }
                            
                            if (datepickerPosition.height < gridPosition.height) {
                                newOffsetValues.top = setCorrectTopPositionInGrid();
                            } else {
                                newOffsetValues.top = setCorrectTopPositionInWindow();
                            }

                            datepickerElement.offset(newOffsetValues);
                            datepickerElement.css("visibility", "visible");
                        };

                        $timeout(function () {
                            setCorrectPosition();
                        }, 0);
                        if ($scope.row.entity[$scope.col.field] == null) {
                            $scope.datePickerValue = null;//new Date();
                        } else {
                            try {
                                var parts = $scope.row.entity[$scope.col.field].match(/(\d+)/g);
                                var date = new Date(parts[2], parts[1] - 1, parts[0]);
                                $scope.datePickerValue = new Date(date);
                            } catch (e) {
                                $scope.datePickerValue = new Date($scope.row.entity[$scope.col.field]);
                            } 
                        }
                            
                        $scope.isOpen = true;
                        var uiGridCtrl = controllers[0];
                        var renderContainerCtrl = controllers[1];

                        var onWindowClick = function (evt) {
                            var classNamed = angular.element(evt.target).attr('class');
                            if (classNamed) {
                                var inDatepicker = (classNamed.indexOf('datepicker-calendar') > -1);
                                if (!inDatepicker && evt.target.nodeName !== "INPUT") {
                                    $scope.stopEdit(evt);
                                }
                            }
                            else {
                                $scope.stopEdit(evt);
                            }
                        };

                        var onCellClick = function (evt) {
                            angular.element(document.querySelectorAll('.ui-grid-cell-contents')).off('click', onCellClick);
                            $scope.stopEdit(evt);
                        };

                        $scope.changeDate = function (evt) {
                            $scope.row.entity[$scope.col.field] = $scope.datePickerValue ? $scope.datePickerValue : new Date();
                            $scope.stopEdit(evt);
                        };

                        $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () {
                            if (uiGridCtrl.grid.api.cellNav) {
                                uiGridCtrl.grid.api.cellNav.on.navigate($scope, function (newRowCol, oldRowCol) {
                                    $scope.stopEdit();
                                });
                            } else {
                                angular.element(document.querySelectorAll('.ui-grid-cell-contents')).on('click', onCellClick);
                            }
                            angular.element(window).on('click', onWindowClick);
                        });

                        $scope.$on('$destroy', function () {
                            angular.element(window).off('click', onWindowClick);
                            $('div[uib-datepicker-popup-wrap]').remove();
                        });

                        $scope.stopEdit = function (evt) {
                            $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
                        };

                        $elm.on('keydown', function (evt) {
                            switch (evt.keyCode) {
                                case uiGridConstants.keymap.ESC:
                                    evt.stopPropagation();
                                    $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
                                    break;
                            }
                            if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
                                evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId;
                                if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) {
                                    $scope.stopEdit(evt);
                                }
                            } else {
                                switch (evt.keyCode) {
                                    case uiGridConstants.keymap.ENTER:
                                    case uiGridConstants.keymap.TAB:
                                        evt.stopPropagation();
                                        evt.preventDefault();
                                        $scope.stopEdit(evt);
                                        break;
                                }
                            }
                            return true;
                        });
                    }
                };
            }
        };
    }]);
})();;
(function () {
    window.app.directive('validatePassword', ['utilitySvc', function (utilitySvc) {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: {
                label: '@?validatePasswordLabel',
                errorArray: '=?validatePasswordErrorArray'
            },
            link: function (scope, elem, attr, ctrl) {
                function validate(value) {
                    var valid = ctrl.$isEmpty(value);
                    if (!valid) {
                        scope.errorArray = [];
                        valid = utilitySvc.isPasswordValid(value, scope.errorArray, scope.label);
                    }
                    ctrl.$setValidity('password', valid);
                    return value;
                }

                ctrl.$parsers.push(validate);
            }
        }
    }]);
})();;
(function () {
    window.app.directive('webinarDetails', ['httpService', function (httpService) {
        return {
            restrict: 'E',
            scope: {
                pdfThumbnailUrl: '@',
                pdfUrl: '@',
                pdfTitle: '@',
                videoThumbnailUrl: '@',
                videoUrl: '@',
                videoTitle: '@',
                videoId: '@',
                bucketVideoUrl: '@'
            },
            link: function (scope, iElem, iAttrs) {
                scope.sendVideoCompleteEmailToHcp = function () {
                    var url = api_webinar_video_complete.replace('{0}', scope.videoTitle);
                    httpService.post(url)
                    .success(function (response) {
                    });
                }

                $(document).on('show.bs.modal', '#' + scope.videoId, function () {
                    scope.videoUrl = scope.bucketVideoUrl;
                    scope.$apply();
                    loadVideo();
                });

                $(document).on('hidden.bs.modal', '#' + scope.videoId, function () {
                    $("video").each(function () {
                        $(this).get(0).pause();
                    });
                });

                function loadVideo() {
                    var videoElement = $("#video" + scope.videoId);
                    videoElement.get(0).load();
                    videoElement.get(0).addEventListener("loadstart", function () {
                        videoElement.addClass('loading')
                    });
                    videoElement.get(0).addEventListener("canplay", function () {
                        videoElement.removeClass('loading')
                    });
                }
            },
            templateUrl: '/templates/webinar.html'
        }
    }]);
})();;
(function () {
    'use strict';
    window.app.directive('windowResize', ['$window', '$timeout', function ($window, $timeout) {
        return {
            link: function (scope, element, attr) {
                var w = angular.element($window);
                scope.$watch(function () {
                    return {
                        'h': w.height(),
                        'w': w.width()
                    };
                }, function (newValue, oldValue) {
                    scope.windowHeight = newValue.h;
                    scope.windowWidth = newValue.w;
                }, true);

                w.bind('resize', function () {
                    scope.$apply();
                });
            }
        }
    }]);
})();;
(function () {
    'use strict';

    window.app.controller('CreateEventController', CreateEventController);
    CreateEventController.$inject = ['$rootScope', '$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', 'toaster', 'moment', '$q'];

    function CreateEventController($rootScope, $scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, toaster, moment, $q) {
        var vm = this;
        vm.init = init;
        vm.getCancelUrl = getCancelUrl;
        vm.isCancelDisabled = function () {
            return false;
        }

        vm.model = {
            eventDetail: { presenter: {} },
            venueDetail: { venue: { address: {} } },
            flightDetail: {},
            accommodationDetail: {},
            documentDetail: {},
            inviteHCPDetail: {}
        };

        vm.parseInt = function (str) {
            return parseInt(str);
        }
        vm.convertTimeStrToDate = function (timeStr) {
            if (!timeStr) {
                return undefined;
            }

            return moment(timeStr, 'HH:mm a').toDate();
        }
        vm.getMatchedRegex = function (str, regex) {
            var match = new RegExp(regex).exec(str);
            if (match != null) {
                return match.length > 1 ? match[1] : match[0];
            } else {
                return null;
            }
        }

        vm.addFlights = addFlights;
        vm.deleteFlights = deleteFlights;
        vm.onCreatePresenter = onCreatePresenter;
        vm.cancelCreatePresenter = cancelCreatePresenter;
        vm.eventDetailFormSubmit = eventDetailFormSubmit;
        vm.flightsFormSubmit = flightsFormSubmit;
        vm.eventDocsFormSubmit = eventDocsFormSubmit;
        vm.removeInviteHCP = removeInviteHCP;
        vm.previousTab = previousTab;
        vm.model.flightDetail.listFlights = [];
        vm.model.flightDetail.listFlightResults = [];
        vm.model.documentDetail.listDocuments = [];
        vm.model.documentDetail.listDocumentResults = [];
        vm.model.inviteHCPDetail.listHCP = [];

        vm.listPresenterExist = [];
        vm.listInviteHcpExist = [];
        vm.isCreatePresenter = false;
        vm.isDisabled = true;
        vm.isContributorUser = false;
        vm.isEditMode = false;
        vm.dateFormat = 'dd/MM/yyyy';
        vm.eventId = formConfig.eventId;
        vm.eventVenueId = 0;
        vm.isErrorPresenter = false;
        vm.isPublishEdit = true;
        var existingError = "";

        function init() {
            $rootScope.$broadcast("loader_show");
            if (formConfig.userRole.toLowerCase() == 'contributor') {
                vm.isContributorUser = true;
            }
            if (formConfig.eventId <= 0) {
                addDays();
                addFlights();
                addAccommodations();
            }
            getEventDetail();
        }
        $(function () {
            $('body').on('focus', ".date-picker", function () {
                $(this).datepicker({
                    orientation: "left",
                    autoclose: true,
                    format: "dd/mm/yyyy"
                });
            });

            $('body').on('focus', ".time-picker", function () {
                $(this).timepicker({
                    showInputs: true,
                    showSeconds: false,
                    format: "HH:mm"
                });
            });

            initLookups();
        });

        function getCancelUrl() {
            if (vm.eventId > 0) {
                return formConfig.eventManageUrl.replace('eventId', vm.eventId);
            }
            else {
                return formConfig.eventListUrl;
            }
        }

        // Get detail event tabs
        function getEventDetail() {
            if (formConfig.eventId > 0) {
                httpService.get(api_get_event_detail.replace('{id}', formConfig.eventId))
                    .then(function (res) {
                        var response = res.data;
                        vm.isEditMode = true;
                        vm.eventId = formConfig.eventId;
                        vm.isPublishEdit = response.isPublish;
                        console.log('999');
                        console.log(response);
                        $('#btnEventDetailSubmit').html('Save');
                        vm.model.eventDetail = response;
                        if (vm.model.eventDetail.publishedDate) {
                            vm.model.eventDetail.publishedDate = vm.model.eventDetail.publishedDate + 'Z';
                        }
                        console.log(vm.model.eventDetail);
                        if (response.listPresenter != null) {
                            angular.forEach(response.listPresenter,
                                function (item) {
                                    vm.listPresenterExist.push(item.id);
                                });
                        }

                        getVenueDetail();
                        getFlightDetail();
                        getAccommodationDetail();
                        getEventDocument();
                    }, function (response) {
                        if (response.status == 404) {
                            location.href = formConfig.eventListUrl;
                        }
                    });
            }
        }

        function getFlightDetail() {
            if (formConfig.eventId > 0) {
                vm.model.flightDetail.listFlights = [];
                httpService.get(api_get_eventFlight_detail.replace('{eventId}', formConfig.eventId))
                    .success(function (response) {
                        $('#btnSubmitFlight').html('Save');
                        if (response != null && response != undefined) {
                            angular.forEach(response,
                                function (item) {
                                    vm.isEditMode = true;
                                    vm.model.flightDetail.returningTo = item.returningTo;
                                    var departDate = item.departingDate.split("/");
                                    item.departingDate = new Date(departDate[2], departDate[1] - 1, departDate[0]);
                                    var returnDate = item.returningDate.split("/");
                                    item.returningDate = new Date(returnDate[2], returnDate[1] - 1, returnDate[0]);
                                    item.departingTime = moment(item.departingTime, "HH:mm").format("HH:mm");
                                    item.departingArrivalTime = moment(item.departingArrivalTime, "HH:mm").format("HH:mm");
                                    var departingTime = convertAMPMformat(item.departingTime);
                                    var departingArrivalTime = convertAMPMformat(item.departingArrivalTime);

                                    item.returningTime = moment(item.returningTime, "HH:mm").format("HH:mm");
                                    item.returningArrivalTime = moment(item.returningArrivalTime, "HH:mm").format("HH:mm");
                                    var returningTime = convertAMPMformat(item.returningTime);
                                    var returningArrivalTime = convertAMPMformat(item.returningArrivalTime);
                                    vm.model.flightDetail.listFlights.push({
                                        id: item.id,
                                        eventId: vm.eventId,
                                        returningTo: item.returningTo,
                                        departingFrom: item.departingFrom,
                                        departingDate: item.departingDate,
                                        departingTime: departingTime,
                                        departingArrivalTime: departingArrivalTime,
                                        departingFlightNumber: item.departingFlightNumber,
                                        returningDate: item.returningDate,
                                        returningTime: returningTime,
                                        returningArrivalTime: returningArrivalTime,
                                        returningFlightNumber: item.returningFlightNumber,
                                        isNotAddOrUpdate: false
                                    });
                                }
                            );
                        }
                    }).error(function (d) {
                        addFlights();
                    });
            }
        }

        function getEventDocument() {
            if (vm.eventId > 0) {
                vm.model.documentDetail.listDocuments = [];
                httpService.get(api_get_eventDocument.replace('{eventId}', vm.eventId))
                    .success(function (response) {
                        if (vm.isEditMode)
                            $('#btnSubmitEventDocs').html('Save');
                        var i = 0;
                        if (response != null && response != undefined) {
                            angular.forEach(response,
                                function (item) {
                                    var extension = '';
                                    if (item.documentExtension == formConfig.fileJPG) {
                                        extension = '.jpg';
                                    }
                                    else if (item.documentExtension == formConfig.fileJPEG) {
                                        extension = '.jpeg';
                                    }
                                    else if (item.documentExtension == formConfig.filePDF) {
                                        extension = '.pdf';
                                    }
                                    else if (item.documentExtension == formConfig.fileXLSX) {
                                        extension = '.xlsx';
                                    }
                                    else if (item.documentExtension == formConfig.fileDocx) {
                                        extension = '.docx';
                                    }
                                    else if (item.documentExtension == formConfig.filePptx) {
                                        extension = '.pptx';
                                    }
                                    else if (item.documentExtension == formConfig.fileXLS) {
                                        extension = '.xls';
                                    }
                                    else if (item.documentExtension == formConfig.fileDoc) {
                                        extension = '.doc';
                                    }
                                    else if (item.documentExtension == formConfig.filePpt) {
                                        extension = '.ppt';
                                    }
                                    vm.model.documentDetail.listDocuments.push({
                                        id: item.id,
                                        eventId: item.eventId,
                                        documentId: item.documentId,
                                        documentType: item.documentType,
                                        documentExtension: item.documentExtension,
                                        documentName: item.documentName,
                                        fileName: item.documentName + extension,
                                        base64: "",
                                        documentLabel: item.documentLabel,
                                        location: item.location
                                    });

                                    i++;
                                }
                            );
                        }
                    }).error(function (d) {

                    });
            }
        }
        // End get detail

        function addFlights() {
            vm.model.flightDetail.listFlights.push({
                id: 0,
                eventId: 0,
                returningTo: 0,
                departingFrom: 0,
                departingDate: "",
                departingTime: "",
                departingArrivalTime: "",
                departingFlightNumber: "",
                returningDate: "",
                returningTime: "",
                returningArrivalTime: "",
                returningFlightNumber: "",
                isNotAddOrUpdate: false
            });
        }

        function deleteFlights(index) {
            if (vm.model.flightDetail.listFlights.length == 1) {
                vm.model.flightDetail.listFlights[index].departingFrom = "";
                vm.model.flightDetail.listFlights[index].departingDate = "";
                vm.model.flightDetail.listFlights[index].departingTime = "";
                vm.model.flightDetail.listFlights[index].departingArrivalTime = "";
                vm.model.flightDetail.listFlights[index].departingFlightNumber = "";
                vm.model.flightDetail.listFlights[index].returningDate = "";
                vm.model.flightDetail.listFlights[index].returningTime = "";
                vm.model.flightDetail.listFlights[index].returningArrivalTime = "";
                vm.model.flightDetail.listFlights[index].returningFlightNumber = "";
                vm.model.flightDetail.listFlights[index].isNotAddOrUpdate = false;
            } else {
                vm.model.flightDetail.listFlights.splice(index, 1);
            }
        }

        function removeInviteHCP(index, hcpIdToRemove) {
            vm.model.inviteHCPDetail.listHCP.splice(index, 1);

            var indexToRemove = -1;
            angular.forEach(vm.listInviteHcpExist, function (hcpId, idx) {
                if (hcpId == hcpIdToRemove) {
                    indexToRemove = idx;
                    return;
                }
            });
            if (indexToRemove >= 0) {
                vm.listInviteHcpExist.splice(indexToRemove, 1);
            }
        }
        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                vm.hcpProfessions = [];
                angular.forEach(data.Hcp_Profession, function (item) {
                    if (item.Value != formConfig.registrar && item.Value != formConfig.other)
                        vm.hcpProfessions.push(item);
                });
                vm.accreditations = data.HcpAccreditation_Type;
                vm.titles = data.Title;
                vm.states = data.State;
            }).then(function (d) {
                httpService.get(api_event_getEventType)
                        .success(function (response) {
                            angular.forEach(response,
                         function (item) {
                             if (item.type == formConfig.eventType) {
                                 vm.eventTypes = item.eventValues;
                             }
                             if (item.type == formConfig.educationEventType) {
                                 vm.educationEventTypes = item.eventValues;
                             }
                             if (item.type == formConfig.educationType) {
                                 vm.educationTypes = item.eventValues;
                             }
                             if (item.type == formConfig.flightplaceType) {
                                 vm.flightplaceTypes = item.eventValues;
                             }
                             if (item.type == formConfig.roomType) {
                                 vm.roomTypes = item.eventValues;
                             }
                             if (item.type == formConfig.documentType) {
                                 vm.documentTypes = item.eventValues;
                             }
                             if (item.type == formConfig.searchCriteriaHCP) {
                                 vm.searchCriteriaHCPs = item.eventValues;
                             }
                         });
                            console.log(response);
                        });
            });
        }

        //Tab Create Event Detail
        vm.getPresenters = getPresenters;
        vm.onSelectPresenterDetail = onSelectPresenterDetail;
        vm.getInstitutions = getInstitutions;
        vm.onSelectInstitution = onSelectInstitution;
        vm.onNewInstitution = onNewInstitution;
        vm.clearEditInstitution = clearEditInstitution;
        vm.onEventEditInstitution = onEventEditInstitution;
        vm.submitPresenter = submitPresenter;
        vm.removePresenter = removePresenter;
        vm.unPublish = unPublish;
        vm.deleteEvent = deleteEvent;
        vm.isInstitutionInputsDisabled = true;
        vm.IsShowNewInstitution = true;
        vm.isSearchEventInstitution = true;
        vm.model.eventDetail.listPresenter = [];
        vm.isEditInstitution = false;
        vm.isDetailInstitutionFormDisabled = true;
        vm.model.newPresenter = { institution: { address: {} } };
        vm.onEventTypeChanged = onEventTypeChanged;

        function onEventTypeChanged() {
            if (!isEducationProgramRequired()) {
                vm.model.eventDetail.educationProgram = undefined;
            }
        }

        function onCreatePresenter() {
            vm.isCreatePresenter = true;
        }
        function unPublish() {
            httpService.post(api_event_unPublish.replace('{id}', formConfig.eventId))
                     .then(function (response) {
                         vm.errors = [];
                         vm.errors = response.data.errors;
                         if (response.data.errors.length > 0) {
                             modelStateErrorBuilder.build(vm.errors, vm.model.eventDetail);
                             scrollToTop();
                         } else {
                             vm.isPublishEdit = false;
                             vm.model.eventDetail.isPublish = false;
                         }
                     });
        }

        function deleteEvent() {
            httpService.post(api_delete_event.replace('{id}', formConfig.eventId))
                    .then(function (response) {
                        vm.errors = [];
                        vm.errors = response.data.errors;
                        if (response.data.errors.length > 0) {
                            modelStateErrorBuilder.build(vm.errors, vm.model.eventDetail);
                            scrollToTop();
                        } else {
                            redirectEventAdministration();
                            vm.model.eventDetail.isPublish = false;
                            vm.model.eventDetail.isPublish = false;
                        }
                    });
        }

        function submitPresenter(form) {
            vm.isErrorPresenter = false;
            if (isFormAddPresenterValid(form)) {
                console.log(vm.model.newPresenter);
                vm.model.newPresenter.isEditInstitution = vm.isEditInstitution;
                httpService.post(api_add_presenter, vm.model.newPresenter)
                     .then(function (response) {
                         vm.errors = [];
                         vm.errors = response.data.errors;
                         if (response.data.errors.length > 0) {
                             modelStateErrorBuilder.build(vm.errors, vm.model.newPresenter);
                             // scrollToTop();
                             vm.isErrorPresenter = true;
                         } else {
                             console.log(response.data.data);
                             vm.listPresenterExist.push(response.data.data.id);
                             vm.model.eventDetail.listPresenter.push(response.data.data);
                             vm.model.newPresenter = { institution: { address: {} } };
                             vm.errors = [];
                             vm.isCreatePresenter = false;
                             vm.isDisablePresenterName = false;
                             vm.isDetailInstitutionFormDisabled = false;
                             if (formConfig.eventId > 0) {
                                 $('#btnEventDetailSubmit').html('Save');
                             }
                         }
                     });
            } else {
                // scrollToTop();
                vm.isErrorPresenter = true;
            }
            vm.isSearchEventInstitution = true;
        }
        function cancelCreatePresenter() {
            vm.isSearchEventInstitution = true;
            vm.isCreatePresenter = false;
            vm.errors = [];
        }

        function getPresenters(value) {
            var presenters = [];
            var lstExist = vm.listPresenterExist.join(",");

            return httpService.get(api_event_presenter_search.replace('{0}', value).replace('{1}', lstExist), { disable_loading: true })
                .then(function (response) {
                    response.data.forEach(function (item) {
                        presenters.push(item);
                    });
                    $timeout(function () {
                        $scope.$apply();
                    }, 0)
                    console.log(presenters);
                    return presenters;
                });
        }
        function onSelectPresenterDetail(item) {
            vm.listPresenterExist.push(item.id);
            vm.model.eventDetail.presenter = item;
            vm.model.eventDetail.listPresenter.push(item);
        }
        function removePresenter(index) {
            vm.model.eventDetail.listPresenter.splice(index, 1);
            vm.listPresenterExist.splice(index, 1);
        }
        function getInstitutions(value) {
            if (vm.isSearchEventInstitution) {
                var url = api_institution_search.replace('{0}', value);
                return getItems(url);
            }
        }

        vm.IsShowEventClearInstitution = true;
        vm.IsShowEventEditInstitution = false;
        function onSelectInstitution(item, form) {
            vm.model.newPresenter.institution = item;
            vm.isInstitutionInputsDisabled = true;
            $timeout(function () {
                $scope.$apply();
            }, 0);
            vm.IsShowEventEditInstitution = true;
            vm.IsShowEventClearInstitution = true;
            vm.isDetailInstitutionFormDisabled = true;
            vm.isDisablePresenterName = true;
        }

        function onNewInstitution() {
            var name = vm.model.newPresenter.institution ? vm.model.newPresenter.institution.name : undefined;
            vm.model.newPresenter.institution = {
            };
            $timeout(function () {
                vm.isInstitutionInputsDisabled = false;
            });
            vm.IsShowEventEditInstitution = false;
            vm.isDisablePresenterName = false;
            vm.isSearchEventInstitution = false;
            vm.isDetailInstitutionFormDisabled = false;
            vm.IsShowEventClearInstitution = true;
        }
        function onEventEditInstitution() {
            vm.isEditInstitution = true;
            vm.isDetailInstitutionFormDisabled = false;
            vm.isDisablePresenterName = false;
            vm.isSearchEventInstitution = false;
        }
        function clearEditInstitution() {
            vm.model.newPresenter.institution = undefined;
            $timeout(function () {
                vm.isInstitutionInputsDisabled = false;
            });
            vm.IsShowEventEditInstitution = false;
            vm.isDisablePresenterName = false;
            vm.isSearchEventInstitution = true;
            vm.isDetailInstitutionFormDisabled = true;
        }
        //End Create

        //////------ Date and Venue ------//////
        vm.model.venueDetail.listDays = [];
        vm.model.venueDetail.listDateVenue = [];
        vm.listVenueExist = [];
        vm.dateVenueFormSubmit = dateVenueFormSubmit;
        vm.addDays = addDays;
        vm.deletedays = deletedays;
        vm.getVenues = getVenues;
        vm.onSelectVenue = onSelectVenue;
        vm.onNewVenue = onNewVenue;
        vm.clearVenue = clearVenue;
        vm.onEditVenue = onEditVenue;

        // AJAX //
        function getVenueDetail() {
            if (formConfig.eventId > 0) {
                vm.model.venueDetail.listDays = [];
                httpService.get(api_get_eventVenue_detail.replace('{eventId}', formConfig.eventId))
                    .success(function (response) {
                        $('#btnSubmitVenue').html('Save');
                        var i = 0;
                        if (response != null && response != undefined) {
                            angular.forEach(response,
                                function (item) {
                                    vm.listVenueExist.push(item.venue.id);
                                    var dateParts = item.date.split("/");
                                    item.date = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
                                    vm.eventVenueId = item.id;
                                    item.startTime = moment(item.startTime, "HH:mm").format("HH:mm");
                                    item.endTime = moment(item.endTime, "HH:mm").format("HH:mm");
                                    var s = convertAMPMformat(item.startTime);
                                    var e = convertAMPMformat(item.endTime);
                                    vm.model.venueDetail.listDays.push({
                                        id: item.id,
                                        name: item.venue.name,
                                        venueId: item.venue.id,
                                        floorOrFunctionRoom: item.floorOrFunctionRoom,
                                        address: {
                                            addrLine1: item.venue.address.addrLine1,
                                            addrLine2: item.venue.address.addrLine2,
                                            postcode: item.venue.address.postcode,
                                            state: item.venue.address.state,
                                            suburb: item.venue.address.suburb
                                        },
                                        date: item.date,
                                        startTime: s,
                                        endTime: e,
                                        mode: 'select'
                                    });
                                    i++;
                                }
                            );
                        }
                    }).error(function (d) {
                        addDays();
                    });
            }
        }

        function dateVenueFormSubmit(event, form) {
            utilitySvc.invalidateControlOnSubmission(form);
            beforeSubmitVenue();
            if (isDateVenueFormValid(form)) {
                compareDateVenue();
                httpService.post(api_addedit_eventVenue, vm.model.venueDetail.listDateVenue)
                             .then(function (response) {
                                 vm.errors = [];
                                 vm.errors = response.data.errors;
                                 if (response.data.errors.length > 0) {
                                     modelStateErrorBuilder.build(vm.errors, vm.model.venueDetail.listDateVenue);
                                     scrollToTop();
                                 } else {
                                     if (formConfig.eventId > 0) {
                                         $rootScope.$broadcast("loader_show");
                                         toaster.pop({
                                             type: 'success',
                                             title: 'Success',
                                             body: 'Your changes have been successfully saved',
                                             timeout: 2500,
                                             onHideCallback: function () {
                                                 $rootScope.$broadcast("loader_hide");
                                             }
                                         });
                                     } else {
                                         console.log('----')
                                         console.log(response.data.data);
                                         var index = 0;
                                         angular.forEach(response.data.data,
                                             function (item) {
                                                 vm.model.venueDetail.listDays[index].id = item.id;
                                                 vm.model.venueDetail.listDays[index].venueId = item.venueId;
                                                 index++;
                                             });
                                         nextTab();
                                     }
                                 }
                             });
            } else {
                scrollToTop();
            }
        }

        function beforeSubmitVenue() {
            var i = 0;
            vm.model.venueDetail.listDateVenue = [];
            angular.forEach(vm.model.venueDetail.listDays,
                function (item) {
                    //var currTimestamp = Date.now(), //1482905176396
                    //utcDateString = (new Date(currTimestamp)).toUTCString();
                    //var localTime = new Date(currTimestamp).getTime();
                    //var utcTime = new Date(utcDateString).getTime();
                    //item.utcTimeOffset = localTime - utcTime;
                    //var formattedTime = getTimeOffSet(item.utcTimeOffset);

                    //item.date = $("#dateRevenue" + i).datepicker('getDate');
                    item.startTime = $("#startTimeVenue" + i).val();
                    item.endTime = $("#endTimeVenue" + i).val();
                    vm.model.venueDetail.listDateVenue.push({
                        id: item.id,
                        eventId: vm.eventId,
                        venue: {
                            id: item.venueId,
                            name: item.name,
                            address: item.address
                        },
                        //utcTimeOffset: formattedTime,
                        floorOrFunctionRoom: item.floorOrFunctionRoom,
                        // no timezone conversion necessary!!!
                        date: moment(item.date).format("YYYY-MM-DD"),
                        startTime: moment(item.startTime, "HH:mm").format("HH:mm"),
                        endTime: moment(item.endTime, "HH:mm").format("HH:mm"),
                        sequence: i
                    });
                    i++;
                });
        }

        function isDateVenueFormValid(form) {
            vm.errors = [];
            var isValid = true;
            var isPostcodeValid = true;
            var isTimeValid = true;
            var incre = 0;
            var i = 0;
            angular.forEach(vm.model.venueDetail.listDays,
                       function (item) {
                           if (incre == 0) {
                               if (item.name == '' || item.name == null || item.name == undefined) {
                                   incre++;
                               }
                               if (item.address.addrLine1 == '' || item.address.addrLine1 == null || item.address.addrLine1 == undefined) {
                                   incre++;
                               }
                               if (item.address.suburb == '' || item.address.suburb == null || item.address.suburb == undefined) {
                                   incre++;
                               }
                               if (item.address.postcode == '' || item.address.postcode == null || item.address.postcode == undefined) {
                                   incre++;
                               }
                               if (item.address.state == '' || item.address.state == null || item.address.state == undefined) {
                                   incre++;
                               }
                               if (item.date == '' || item.date == null || item.date == undefined) {
                                   incre++;
                               }
                               if (item.startTime == '' || item.startTime == null || item.startTime == undefined) {
                                   incre++;
                               }
                               if (item.endTime == '' || item.endTime == null || item.endTime == undefined) {
                                   incre++;
                               }

                               if (incre <= 0) {
                                   var startTime = $("#startTimeVenue" + i).val();
                                   var endTime = $("#endTimeVenue" + i).val();
                                   var postcodeValid = isPostCodeValid(item.address.postcode);
                                   var validTime = checkTime(startTime, endTime);
                                   if (!validTime) {
                                       isValid = false;
                                       isTimeValid = false;
                                   }
                                   if (!postcodeValid) {
                                       isValid = false;
                                       isPostcodeValid = false;
                                   }

                               }
                               i++;
                           }
                       });

            if (incre > 0) {
                isValid = false;
                addError("All fields highlighted in red are mandatory");
            } else {
                //if (!isTimeValid)
                //    addError("The start time must be before the end time");
                if (!isPostcodeValid)
                    addError("Postcode provided is invalid");
            }
            return isValid;
        }

        function compareDateVenue() {
            var i = 0;
            angular.forEach(vm.model.venueDetail.listDateVenue,
                function (item) {
                    //item.date = $("#dateRevenue" + i).datepicker('getDate');
                    item.startTime = $("#startTimeVenue" + i).val();
                    item.endTime = $("#endTimeVenue" + i).val();
                    item.startTime = convertTimeformat(item.startTime);
                    item.endTime = convertTimeformat(item.endTime);
                    //item.startTime = moment.utc(item.startTime, "HH:mm").format("HH:mm");
                    //item.endTime = moment.utc(item.endTime, "HH:mm").format("HH:mm");
                    i++;
                });
        }
        // END - AJAX //

        function newDay() {
            return {
                id: 0,
                venueId: 0,
                name: "",
                floorOrFunctionRoom: "",
                address: {
                    addrLine1: "",
                    addrLine2: "",
                    postcode: "",
                    state: "",
                    suburb: ""
                },
                date: "",
                startTime: "",
                endTime: "",
                mode: 'search'
            };
        }
        function addDays() {
            vm.model.venueDetail.listDays.push(newDay());
        }

        function deletedays(index) {
            var item = vm.model.venueDetail.listDays[index];
            removeVenueFromSearchExemption(item);
            if (vm.model.venueDetail.listDays.length > 1) {
                vm.model.venueDetail.listDays.splice(index, 1);
            }
            else {
                vm.model.venueDetail.listDays = [];
                addDays();
            }
        }

        function getVenues(model, value) {
            //vm.temp = [];
            //angular.forEach(vm.listVenueExist,
            //    function (item) {
            //        if (item != model.venueId)
            //            vm.temp.push(item);
            //    });
            //var exceptIds = vm.temp.join(',');
            var exceptIds = '';

            if (model.mode == 'search') {
                var venues = [];
                return httpService.get(api_event_venue_search.replace('{0}', value).replace('{1}', exceptIds), { disable_loading: true })
                    .then(function (response) {

                        response.data.forEach(function (item) {
                            venues.push(item);
                        });
                        console.log(venues);
                        return venues;
                    });
            }
        }

        function onSelectVenue(item, index) {
            vm.listVenueExist = [];

            item.mode = 'select';
            item.venueId = item.id;
            item.id = 0;
            vm.model.venueDetail.listDays[index] = item;
            console.log(item);
            angular.forEach(vm.model.venueDetail.listDays,
                function (data) {
                    vm.listVenueExist.push(data.venueId);
                });
        }

        function onNewVenue(item) {
            resetVenue(item);
            item.mode = 'add';
        }

        function onEditVenue(item) {
            item.mode = 'edit';
        }

        function clearVenue(item) {
            removeVenueFromSearchExemption(item);
            resetVenue(item);
            item.mode = 'search';
        }

        function resetVenue(item) {
            item.id = 0;
            item.venueId = 0;
            item.address = {};
            item.name = "";
        }

        function removeVenueFromSearchExemption(item) {
            if (item.venueId > 0) {
                var itemIdx = null;
                angular.forEach(vm.listVenueExist,
                    function (ele, idx) {
                        if (ele == item.venueId) {
                            itemIdx = idx;
                            return;
                        }
                    });
                if (itemIdx != null) {
                    vm.listVenueExist.splice(itemIdx, 1);
                }
            }
        }
        //////------ END - Date and Venue ------//////

        //////------ Accommodation ------//////
        vm.model.accommodationDetail.listAccommodation = [];
        vm.model.accommodationDetail.listAccommodationResults = [];
        vm.listHotelExist = [];
        vm.getHotels = getHotels;
        vm.onSelectHotel = onSelectHotel;
        vm.onNewHotel = onNewHotel;
        vm.clearHotel = clearHotel;
        vm.onEditHotel = onEditHotel;
        vm.deleteAccommodations = deleteAccommodations;
        vm.addAccommodations = addAccommodations;
        vm.accommodationFormSubmit = accommodationFormSubmit;

        // AJAX //
        function getAccommodationDetail() {
            if (formConfig.eventId > 0) {
                vm.model.accommodationDetail.listAccommodation = [];
                httpService.get(api_get_eventAccommodation_detail.replace('{eventId}', formConfig.eventId))
                    .success(function (response) {
                        $('#btnSubmitAccommodation').html('Save');
                        var i = 0;
                        if (response != null && response != undefined) {
                            angular.forEach(response,
                                function (item) {
                                    vm.listHotelExist.push(item.accommodation.id);
                                    item.checkInTime = moment(item.checkInTime, "HH:mm").format("HH:mm");
                                    item.checkOutTime = moment(item.checkOutTime, "HH:mm").format("HH:mm");
                                    var s = convertAMPMformat(item.checkInTime);
                                    var e = convertAMPMformat(item.checkOutTime);
                                    vm.model.accommodationDetail.listAccommodation.push({
                                        id: item.id,
                                        eventId: vm.eventId,
                                        accommodation: {
                                            id: item.accommodation.id,
                                            name: item.accommodation.name,
                                            isDisableAccommodationName: (item.accommodation.name != null && item.accommodation.name != undefined && item.accommodation.name.length > 0) ? true : false,
                                            address: item.accommodation.address,
                                            mode: 'select'
                                        },
                                        roomType: item.roomType,
                                        parkingOptions: item.parkingOptions,
                                        isBreakfastIncluded: item.isBreakfastIncluded,
                                        checkInTime: s,
                                        checkOutTime: e,
                                        sequence: i
                                    });
                                    i++;
                                }
                            );
                        }
                    }).error(function (d) {
                        addAccommodations();
                    });
            }
        }

        function accommodationFormSubmit(event, form) {
            if (isAccommodationOptionValid(form)) {
                beforeSubmitAccommodation();
                if (isAccmmodationFormValid(form)) {
                    compareDateAccommodation();
                    var a = utilitySvc.invalidateControlOnSubmission(form);
                    httpService.post(api_addedit_eventAccommodation.replace('{eventId}', vm.eventId), vm.model.accommodationDetail.listAccommodationResults)
                        .then(function (response) {
                            vm.errors = [];
                            vm.errors = response.data.errors;
                            if (response.data.errors.length > 0) {
                                modelStateErrorBuilder.build(vm.errors, vm.model);
                                scrollToTop();
                            } else {
                                if (formConfig.eventId > 0) {
                                    $rootScope.$broadcast("loader_show");
                                    toaster.pop({
                                        type: 'success',
                                        title: 'Success',
                                        body: 'Your changes have been successfully saved',
                                        timeout: 2500,
                                        onHideCallback: function () {
                                            $rootScope.$broadcast("loader_hide");
                                        }
                                    });
                                } else {
                                    var index = 0;
                                    angular.forEach(response.data.data,
                                        function (item) {
                                            vm.model.accommodationDetail.listAccommodation[index].id = item.id;
                                            vm.model.accommodationDetail.listAccommodation[index].accommodation.id = item.accommodationId;
                                            index++;
                                        });
                                    nextTab();
                                }
                            }
                        });
                } else {
                    scrollToTop();
                }
            }
        }

        function beforeSubmitAccommodation() {
            var i = 0;
            vm.model.accommodationDetail.listAccommodationResults = [];
            angular.forEach(vm.model.accommodationDetail.listAccommodation,
                function (item) {
                    if (item != null) {
                        if (!item.isNotAddOrUpdate) {
                            item.checkInTime = $("#checkInTime" + i).val();
                            item.checkOutTime = $("#checkOutTime" + i).val();
                            vm.model.accommodationDetail.listAccommodationResults.push({
                                id: item.id,
                                eventId: vm.eventId,
                                accommodation: {
                                    id: item.accommodation.id,
                                    name: item.accommodation.name,
                                    address: item.accommodation.address
                                },
                                roomType: item.roomType,
                                parkingOptions: item.parkingOptions,
                                isBreakfastIncluded: item.isBreakfastIncluded,
                                checkInTime: moment(item.checkInTime, "HH:mm").format("HH:mm"),
                                checkOutTime: moment(item.checkOutTime, "HH:mm").format("HH:mm"),
                                sequence: i
                            });
                            i++;
                        }
                    }
                });
        }

        function isAccommodationOptionValid(form) {
            if (vm.hotelName && vm.hotelName != null && vm.hotelName != '') {
                return true;
            }

            var isNotSaved = false;
            if (vm.model.accommodationDetail.listAccommodation.length == 1) {
                angular.forEach(vm.model.accommodationDetail.listAccommodation,
                    function (item) {
                        if (item == null) {
                            item.isNotAddOrUpdate = true;
                            isNotSaved = true;
                        }
                        else if (item != null) {
                            if ((item.accommodation.name != '' && item.accommodation.name != null && item.accommodation.name != 0)
                                || (item.accommodation.address.addrLine1 != '' && item.accommodation.address.addrLine1 != null && item.accommodation.address.addrLine1 != undefined)
                                || (item.accommodation.address.suburb != '' && item.accommodation.address.suburb != null && item.accommodation.address.suburb != undefined)
                                || (item.accommodation.address.postcode != '' && item.accommodation.address.postcode != null && item.accommodation.address.postcode != undefined)
                                || (item.accommodation.address.state != '' && item.accommodation.address.state != null && item.accommodation.address.state != undefined)
                                || (item.roomType != '' && item.roomType != null && item.roomType != undefined)
                                || (item.checkInTime != '' && item.checkInTime != null && item.checkInTime != undefined)
                                || (item.checkOutTime != '' && item.checkOutTime != null && item.checkOutTime != undefined)) {
                                isNotSaved = false;
                                item.isNotAddOrUpdate = false;
                            } else {
                                item.isNotAddOrUpdate = true;
                                isNotSaved = true;
                            }
                        }
                    });
            }
            if (isNotSaved && !vm.isEditMode && formConfig.eventId <= 0) {
                nextTab();
                return false;
            }
            return true;
        }

        function isAccmmodationFormValid(form) {
            vm.errors = [];
            var incre = 0;
            var isPostcodeValid = true;
            var isAccValid = true;
            var i = 0;
            utilitySvc.invalidateControlOnSubmission(form);
            angular.forEach(vm.model.accommodationDetail.listAccommodation,
                function (item) {
                    if (incre == 0) {
                        if (item.accommodation.name == '' || item.accommodation.name == null || item.accommodation.name == undefined) {
                            incre++;
                        }
                        if (item.accommodation.address.addrLine1 == '' || item.accommodation.address.addrLine1 == null || item.accommodation.address.addrLine1 == undefined) {
                            incre++;
                        }
                        if (item.accommodation.address.suburb == '' || item.accommodation.address.suburb == null || item.accommodation.address.suburb == undefined) {
                            incre++;
                        }
                        if (item.accommodation.address.postcode == '' || item.accommodation.address.postcode == null || item.accommodation.address.postcode == undefined) {
                            incre++;
                        }
                        if (item.accommodation.address.state == '' || item.accommodation.address.state == null || item.accommodation.address.state == undefined) {
                            incre++;
                        }
                        if (item.roomType == '' || item.roomType == null || item.roomType == undefined) {
                            incre++;
                        }
                        if (item.checkInTime == '' || item.checkInTime == null || item.checkInTime == undefined) {
                            incre++;
                        }
                        if (item.checkOutTime == '' || item.checkOutTime == null || item.checkOutTime == undefined) {
                            incre++;
                        }
                        if (incre <= 0) {
                            var checkInTime = $("#checkInTime" + i).val();
                            var checkOutTime = $("#checkOutTime" + i).val();
                            //if (checkInTime != '' && checkOutTime != '') {
                            //    var isTimeDepartingValid = checkTime(checkInTime, checkOutTime);
                            //    if (!isTimeDepartingValid) {
                            //        isValid = false;
                            //        $("#checkOutTime" + i).addClass("ng-invalid ng-dirty has-error");
                            //        $("#checkInTime" + i).addClass("ng-invalid ng-dirty has-error");
                            //    } else {
                            //        $("#checkOutTime" + i).removeClass("ng-invalid ng-dirty has-error");
                            //        $("#checkInTime" + i).removeClass("ng-invalid ng-dirty has-error");
                            //    }
                            //}
                            var postcodeValid = isPostCodeValid(item.accommodation.address.postcode);
                            if (!postcodeValid) {
                                isAccValid = false;
                                isPostcodeValid = false;
                            }
                        }
                        i++;
                    }
                });

            if (incre > 0) {
                isAccValid = false;
                addError("All fields highlighted in red are mandatory");
            } else {
                //if (!isValid) {
                //    addError("The checkin time must be before the checkout time");
                //}
                if (!isPostcodeValid)
                    addError("Postcode provided is invalid");
            }
            return isAccValid;
        }

        function compareDateAccommodation() {
            var i = 0;
            angular.forEach(vm.model.accommodationDetail.listAccommodationResults,
                function (item) {
                    item.checkInTime = $("#checkInTime" + i).val();
                    item.checkOutTime = $("#checkOutTime" + i).val();
                    if (item.checkInTime != '' && item.checkInTime != null && item.checkOutTime != '' && item.checkOutTime != null) {
                        item.checkInTime = convertTimeformat(item.checkInTime);
                        item.checkOutTime = convertTimeformat(item.checkOutTime);
                        item.checkInTime = moment(item.checkInTime, "HH:mm").format("HH:mm");
                        item.checkOutTime = moment(item.checkOutTime, "HH:mm").format("HH:mm");
                    }
                    i++;
                });
        }
        // END - AJAX //

        function newAccommodation() {
            return {
                id: 0,
                eventId: 0,
                roomType: "",
                parkingOptions: "",
                accommodation: {
                    id: 0,
                    name: "",
                    address: {
                        addrLine1: "",
                        addrLine2: "",
                        postcode: "",
                        state: "",
                        suburb: ""
                    },
                    mode: 'search'
                },
                IsBreakfastIncluded: false,
                checkInTime: "",
                checkOutTime: ""
            };
        }
        function addAccommodations() {
            vm.model.accommodationDetail.listAccommodation.push(newAccommodation());
        }

        function deleteAccommodations(index) {
            var item = vm.model.accommodationDetail.listAccommodation[index];
            removeHotelFromSearchExemption(item);
            if (vm.model.accommodationDetail.listAccommodation.length > 1) {
                vm.model.accommodationDetail.listAccommodation.splice(index, 1);
            }
            else {
                vm.model.accommodationDetail.listAccommodation = [];
                addAccommodations();
            }
        }

        function getHotels(model, value) {
            //vm.temp = [];
            //angular.forEach(vm.listHotelExist,
            //    function (item) {
            //        if (item != model.accommodation.id)
            //            vm.temp.push(item);
            //    });
            //var exceptIds = vm.temp.join(',');
            var exceptIds = '';

            if (model.accommodation.mode == 'search') {
                var accommodations = [];
                return httpService.get(api_event_Accommodation_search.replace('{0}', value).replace('{1}', exceptIds), { disable_loading: true })
                    .then(function (response) {

                        response.data.forEach(function (item) {
                            accommodations.push(item);
                        });
                        console.log(accommodations);
                        return accommodations;
                    });
            }
        }

        function onSelectHotel(item, index) {
            vm.listHotelExist = [];

            item.mode = 'select';
            vm.model.accommodationDetail.listAccommodation[index].accommodation = item;
            console.log(item);
            angular.forEach(vm.model.accommodationDetail.listAccommodation,
                function (data) {
                    vm.listHotelExist.push(data.accommodation.id);
                });
        }

        function onNewHotel(item) {
            resetHotel(item);
            item.accommodation.mode = 'add';
        }

        function onEditHotel(item) {
            item.accommodation.mode = 'edit';
        }

        function clearHotel(item) {
            removeHotelFromSearchExemption(item);
            resetHotel(item);
            item.accommodation.mode = 'search';
        }

        function resetHotel(item) {
            item.id = 0;
            item.accommodation = {
                id: 0,
                name: "",
                address: {}
            };
        }

        function removeHotelFromSearchExemption(item) {
            if (item.accommodation.id > 0) {
                var itemIdx = null;
                angular.forEach(vm.listHotelExist,
                    function (ele, idx) {
                        if (ele == item.accommodation.id) {
                            itemIdx = idx;
                            return;
                        }
                    });
                if (itemIdx != null) {
                    vm.listHotelExist.splice(itemIdx, 1);
                }
            }
        }
        //////------ Accommodation ------//////

        //Tab Event docs
        vm.removeDocument = removeDocument;
        vm.eventDocsFormSubmit = eventDocsFormSubmit;
        //vm.openDocument = openDocument;
        function removeDocument(index) {
            vm.model.documentDetail.listDocuments.splice(index, 1);
        }
        function openDocument(key) {
            if (key != '' && key != null) {
                httpService.get('home/download/{fileKey}'.replace('{fileKey}', key))
                    .success(function (response) {

                    }
                    );
            }
        }
        vm.files = [];
        function handleFileSelect(evt) {
            var files = evt.target.files; // FileList object
            console.log(files)
            $.each(files, function (i, file) {
                vm.files.push(file);
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function () {
                    vm.model.documentDetail.listDocuments.push({
                        id: 0,
                        documentId: 0,
                        fileName: file.name,
                        documentType: "",
                        documentLabel: "",
                        base64: reader.result.substring(reader.result.indexOf(",") + 1)
                    });
                    angular.element('#btnTrigger').triggerHandler('click');
                };
            });
        }
        $('#holder').on({
            'dragover dragenter': function (e) {
                e.preventDefault();
                e.stopPropagation();
            },
            'click': function (e) {
                $('#files').trigger('click');
                document.getElementById('files').addEventListener('change', handleFileSelect, false);

            },
            'drop': function (e) {
                var dataTransfer = e.originalEvent.dataTransfer;
                if (dataTransfer && dataTransfer.files.length) {
                    e.preventDefault();
                    e.stopPropagation();
                    $.each(dataTransfer.files, function (i, file) {
                        vm.files.push(file);
                        var reader = new FileReader();
                        reader.readAsDataURL(file);
                        reader.onload = function () {
                            vm.model.documentDetail.listDocuments.push({
                                id: 0,
                                documentId: 0,
                                fileName: file.name,
                                documentType: "",
                                documentLabel: "",
                                base64: reader.result.substring(reader.result.indexOf(",") + 1)
                            });
                            angular.element('#btnTrigger').triggerHandler('click');
                        };
                    });
                }
            }
        });
        //End Event docs

        //Tab Invite HCPs
        vm.getAttendees = getAttendees;
        vm.onSelectAttendee = onSelectAttendee;
        vm.getAttendeeFilterValues = getAttendeeFilterValues;
        vm.onSelectFilterValue = onSelectFilterValue;
        vm.inviteHCPForm = inviteHCPForm;
        vm.publishEvent = publishEvent;
        vm.publishEditEvent = publishEditEvent;
        vm.resetHcpList = resetHcpList;
        vm.changeHcpFilter = changeHcpFilter;
        vm.listInviteHcpExist = [];
        function resetHcpList(form) {
            vm.model.inviteHCPDetail.listHCP = [];
            vm.listInviteHcpExist = [];
        }
        function changeHcpFilter() {
            vm.model.inviteHCPDetail.name = '';
        }

        function publishEvent(form) {
            var eventId = 0;
            var mail = '';
            if (formConfig.eventId > 0)
                eventId = formConfig.eventId;
            else if (vm.eventId > 0)
                eventId = vm.eventId;
            if (vm.model.inviteHCPDetail.isSendMail)
                mail = 'true';
            else
                mail = 'false';
            httpService.post(api_event_publish.replace('{id}', eventId).replace('{mail}', mail), vm.model.inviteHCPDetail.listHCP)
                     .then(function (response) {
                         vm.errors = [];
                         vm.errors = response.data.errors;
                         if (response.data.errors.length > 0) {
                             modelStateErrorBuilder.build(vm.errors, vm.model.inviteHCPDetail);
                             scrollToTop();
                         } else {
                             redirectEventAdministration();
                         }
                     });
        }
        function publishEditEvent() {
            var mail = '';
            var eventId = vm.eventId;
            if (vm.model.eventDetail.isEditSendMail)
                mail = 'true';
            else
                mail = 'false';
            httpService.post(api_event_publishEditMode.replace('{id}', eventId).replace('{mail}', mail))
                     .then(function (response) {
                         vm.errors = [];
                         vm.errors = response.data.errors;
                         if (response.data.errors.length > 0) {
                             modelStateErrorBuilder.build(vm.errors, vm.model.inviteHCPDetail);
                             scrollToTop();
                         } else {
                             $rootScope.$broadcast("loader_show");
                             toaster.pop({
                                 type: 'success',
                                 title: 'Success',
                                 body: 'Event was published successfully!',
                                 timeout: 2500,
                                 onHideCallback: function () {
                                     $rootScope.$broadcast("loader_hide");

                                     var publishedDate = response.data.data;
                                     if (publishedDate && !publishedDate.endsWith('Z')) {
                                         publishedDate = publishedDate + 'Z';
                                     }
                                     vm.model.eventDetail.publishedDate = publishedDate;
                                     vm.model.eventDetail.isPublish = true;
                                     vm.isPublishEdit = true;
                                 }
                             });
                         }
                     });
        }
        function inviteHCPForm(form) {
            httpService.post(api_add_event_inviteHCP.replace('{eventId}', vm.eventId), vm.model.inviteHCPDetail.listHCP)
                     .then(function (response) {
                         vm.errors = [];
                         vm.errors = response.data.errors;
                         if (response.data.errors.length > 0) {
                             modelStateErrorBuilder.build(vm.errors, vm.model.inviteHCPDetail.listHCP);
                             scrollToTop();
                         } else {
                             redirectEventAdministration();
                             //$rootScope.$broadcast("loader_show");
                             //toaster.pop({
                             //    type: 'success',
                             //    title: 'Success',
                             //    body: 'Your changes have been successfully saved',
                             //    timeout: 2500,
                             //    onHideCallback: function () {
                             //        $rootScope.$broadcast("loader_hide");
                             //    }
                             //});
                         }
                     });
        }
        function searchAttendees(value, search, type, exceptIds, pageSize, pageNo, isExact) {
            return httpService.get(api_event_InviteHcp_search
                    .replace('{0}', value)
                    .replace('{1}', search)
                    .replace('{2}', type)
                    .replace('{3}', exceptIds)
                    .replace('{pageSize}', pageSize)
                    .replace('{pageNo}', pageNo)
                    .replace('{isExact}', isExact),
                    { disable_loading: true })
                    .then(function (response) {
                        return response.data;
                    });
        }
        function getAttendees(value) {
            var attendees = [];
            var type = vm.model.inviteHCPDetail.searchFilter;
            var search = '';
            vm.temp = [];
            var exceptIds = vm.listInviteHcpExist.join(',');

            if (type > 0) {
                if (type > 0 && type <= 8) {
                    search = 'suburb';
                } else if (type == 9) {
                    search = 'profession';
                } else if (type == 10) {
                    search = 'targetclass';
                } else if (type == 11) {
                    search = 'name';
                }

                var pageSize = type == 11 ? 10 : 100;
                var pageNo = 1;
                var isExact = type == 11 ? 'false' : 'true';

                return searchAttendees(value, search, type, exceptIds, pageSize, pageNo, isExact).then(function (data) {
                    if (data && data.result) {
                        data.result.forEach(function (item) {
                            attendees.push(item);
                        });

                        var paginationCount = (data.totalCount / pageSize) + 1;
                        if (paginationCount > 1) {
                            var prom = [];
                            pageNo++;
                            while (pageNo <= paginationCount) {
                                prom.push(searchAttendees(value, search, type, exceptIds, pageSize, pageNo, isExact).then(function (data) {
                                    if (data && data.result) {
                                        data.result.forEach(function (item) {
                                            attendees.push(item);
                                        });
                                    }
                                }));
                                pageNo++;
                            }
                            return $q.all(prom).then(function () {
                                return attendees;
                            });
                        }
                    }
                });
            }
        }
        function addTolistInviteHcpExist(item) {
            var isInArr = false;
            angular.forEach(vm.listInviteHcpExist, function (itemId) {
                if (itemId == item.id) {
                    isInArr = true;
                    return;
                }
            });
            if (!isInArr) {
                vm.listInviteHcpExist.push(item.id);
            }
        }
        function addToAttendeeList(item) {
            var iscontaint = false;
            angular.forEach(vm.model.inviteHCPDetail.listHCP, function (itemContaint) {
                if (item.id == itemContaint.hcpId) {
                    iscontaint = true;
                    return;
                }
            });
            if (!iscontaint) {
                vm.model.inviteHCPDetail.listHCP.push({
                    id: 0,
                    eventId: vm.eventId,
                    hcpId: item.id,
                    profile: item.profile,
                    isSendMail: false
                });
            }
        }
        function onSelectAttendee(item) {
            addTolistInviteHcpExist(item);
            addToAttendeeList(item);
            $timeout(function () {
                vm.model.inviteHCPDetail.name = '';
            }, 100);

        }
        function getAttendeeFilterValues(value) {
            var filterValues = [];
            var type = vm.model.inviteHCPDetail.searchFilter;
            vm.temp = [];
            var exceptIds = vm.listInviteHcpExist.join(',');
            if (type > 0) {
                return httpService.get(api_event_InviteHcp_searchFilterValues.replace('{value}', value).replace('{type}', type).replace('{exceptIds}', exceptIds), { disable_loading: true })
                    .then(function (response) {
                        if (response.data && response.data.result) {
                            filterValues = response.data.result;
                        }
                        return filterValues;
                    });
            }
        }
        function onSelectFilterValue(searchValue) {
            getAttendees(searchValue).then(function (result) {
                angular.forEach(result, function (hcp) {
                    addTolistInviteHcpExist(hcp);
                    addToAttendeeList(hcp);
                });
                $timeout(function () {
                    vm.model.inviteHCPDetail.name = '';
                }, 100);
            });
        }
        // Get detail event tabs
        function getInviteHcp() {
            if (formConfig.eventId > 0) {
                httpService.get(api_get_event_detail.replace('{id}', formConfig.eventId))
                    .success(function (response) {
                        vm.isEditMode = true;
                        vm.eventId = formConfig.eventId;
                        console.log(response);
                        $('#btnEventDetailSubmit').html('Save');
                        vm.model.eventDetail = response;
                        if (response.listPresenter != null) {
                            angular.forEach(response.listPresenter,
                                function (item) {
                                    vm.listPresenterExist.push(item.id);
                                });
                        }
                    }).then(function (data) {
                        getVenueDetail();
                        getFlightDetail();
                        getAccommodationDetail();
                        getEventDocument();
                    });
            }
        }
        //End Invite HCPs

        // Submit on Tab
        vm.eventDocumentId = 0;
        function eventDetailFormSubmit(event, form) {
            vm.isErrorPresenter = false;
            utilitySvc.invalidateControlOnSubmission(form);
            if (isEventDetailFormValid(form)) {
                console.log(vm.model.eventDetail);
                httpService.post(api_addedit_event, vm.model.eventDetail)
                     .then(function (response) {
                         vm.errors = [];
                         vm.errors = response.data.errors;
                         if (response.data.errors.length > 0) {
                             modelStateErrorBuilder.build(vm.errors, vm.model);
                             scrollToTop();
                         } else {
                             vm.eventId = response.data.data;
                             vm.model.eventDetail.id = vm.eventId;
                             console.log(vm.eventId);
                             if (formConfig.eventId > 0) {
                                 $rootScope.$broadcast("loader_show");
                                 toaster.pop({
                                     type: 'success',
                                     title: 'Success',
                                     body: 'Your changes have been successfully saved',
                                     timeout: 2500,
                                     onHideCallback: function () {
                                         $rootScope.$broadcast("loader_hide");
                                     }
                                 });
                             } else {
                                 nextTab();
                             }
                         }
                     });
            } else {
                scrollToTop();
            }
        }
        function flightsFormSubmit(event, form) {
            console.log('2222');
            console.log(vm.model.flightDetail.listFlights);
            if (isFlightOptionValid(form)) {
                if (isNotCheckFlight(form)) {
                    if (!vm.isEditMode && formConfig.eventId <= 0)
                        nextTab();
                } else {
                    utilitySvc.invalidateControlOnSubmission(form);
                    beforeSubmitFlights();
                    if (isFlightDetailFormValid(form)) {
                        compareDateFlight();
                        httpService.post(api_addedit_eventFlight.replace('{eventId}', vm.eventId), vm.model.flightDetail.listFlightResults)
                            .then(function (response) {
                                vm.errors = [];
                                vm.errors = response.data.errors;
                                if (response.data.errors.length > 0) {
                                    modelStateErrorBuilder.build(vm.errors, vm.model);
                                    scrollToTop();
                                } else {
                                    if (formConfig.eventId > 0) {
                                        $rootScope.$broadcast("loader_show");
                                        toaster.pop({
                                            type: 'success',
                                            title: 'Success',
                                            body: 'Your changes have been successfully saved',
                                            timeout: 2500,
                                            onHideCallback: function () {
                                                $rootScope.$broadcast("loader_hide");

                                                var i = 0;
                                                angular.forEach(response.data.data,
                                                    function (item) {
                                                        $("#departingDate" +i).removeClass("ng-invalid ng-dirty has-error");
                                                        $("#returningDate" + i).removeClass("ng-invalid ng-dirty has-error");
                                                        $("#departingTime" +i).removeClass("ng-invalid ng-dirty has-error");
                                                        $("#departingArrivalTime" +i).removeClass("ng-invalid ng-dirty has-error");
                                                        $("#returningTime" +i).removeClass("ng-invalid ng-dirty has-error");
                                                        $("#returningArrivalTime" +i).removeClass("ng-invalid ng-dirty has-error");
                                                        i++;
                                                    });
                                            }
                                        });
                                    } else {
                                        var index = 0;
                                        angular.forEach(response.data.data,
                                            function (item) {
                                                vm.model.flightDetail.listFlights[index].id = item.id;
                                                index++;
                                            });
                                        nextTab();
                                    }
                                }
                            });
                    } else {
                        scrollToTop();
                    }
                }
            }
        }

        vm.getDocWithError = function (idx) {
            var found = false;
            if (vm.docWithErrIdxArr) {
                angular.forEach(vm.docWithErrIdxArr, function (val) {
                    if (idx == val) {
                        found = true;
                        return;
                    }
                });
            }

            return found;
        }

        function eventDocsFormSubmit(event, form) {
            vm.docWithErrIdxArr = [];
            if (isEventDocumentValid(form)) {
                vm.loading = true;
                var i = 0;
                var totalSuccess = 0;
                vm.errors = [];
                vm.model.documentDetail.listDocumentResults = [];
                if ((vm.model.documentDetail.listDocuments == null || vm.model.documentDetail.listDocuments.length <= 0) && vm.eventId > 0) {
                    addUpdateDocument();
                } else {
                    angular.forEach(vm.model.documentDetail.listDocuments,
                        function (item, idx) {
                            httpService.post(api_event_upload, item)
                                .success(function (response) {
                                    if (response.errors.length <= 0) {
                                        item.documentId = response.data.id;
                                        console.log('Upload Successfull');
                                        i++;
                                        totalSuccess++;
                                        if (i == vm.model.documentDetail.listDocuments.length) {
                                            if (i === totalSuccess) {
                                                beforeSubmitEventDocument();
                                                addUpdateDocument();
                                            } else
                                                console.log('Error');
                                        }
                                    } else {
                                        vm.docWithErrIdxArr.push(idx);
                                        vm.errors = response.errors;
                                        modelStateErrorBuilder.build(vm.errors, vm.model.documentDetail.listDocumentResults);
                                        scrollToTop();
                                    }
                                }).error(function (res) {
                                    i++;
                                });
                        });
                }
            } else {
                scrollToTop();
            }
        }
        function beforeSubmitFlights() {
            var i = 0;
            vm.model.flightDetail.listFlightResults = [];
            angular.forEach(vm.model.flightDetail.listFlights,
                function (item) {
                    if (item != null) {
                        if (!item.isNotAddOrUpdate) {
                            //item.createdOn = moment.utc(item.createdOn).local().format("DD/MM/YYYY");
                            //item.departingDate = $("#departingDate" + i).datepicker('getDate');
                            item.departingTime = $("#departingTime" + i).val();
                            item.departingArrivalTime = $("#departingArrivalTime" + i).val();

                            //item.returningDate = $("#returningDate" + i).datepicker('getDate');
                            item.returningTime = $("#returningTime" + i).val();
                            item.returningArrivalTime = $("#returningArrivalTime" + i).val();
                            item.returningTo = vm.model.flightDetail.returningTo,

                                vm.model.flightDetail.listFlightResults.push({
                                    id: item.id,
                                    eventId: vm.eventId,

                                    departingFrom: item.departingFrom,
                                    departingDate: moment(item.departingDate).format("YYYY-MM-DD"),
                                    departingTime: moment(item.departingTime, "HH:mm").format("HH:mm"),
                                    departingArrivalTime: moment(item.departingArrivalTime, "HH:mm").format("HH:mm"),
                                    departingFlightNumber: item.departingFlightNumber,

                                    returningTo: vm.model.flightDetail.returningTo,
                                    returningDate: moment(item.returningDate).format("YYYY-MM-DD"),
                                    returningTime: moment(item.returningTime, "HH:mm").format("HH:mm"),
                                    returningArrivalTime: moment(item.returningArrivalTime, "HH:mm").format("HH:mm"),
                                    returningFlightNumber: item.returningFlightNumber,
                                    isNotAddOrUpdate: item.isNotAddOrUpdate,
                                    sequence: i
                                });
                            i++;
                        }
                    }
                });
        }
        function beforeSubmitEventDocument() {
            angular.forEach(vm.model.documentDetail.listDocuments,
                function (data) {
                    vm.model.documentDetail.listDocumentResults.push({
                        id: data.id,
                        eventId: vm.eventId,
                        documentId: data.documentId,
                        documentType: data.documentType
                    });
                });
        }
        function addUpdateDocument() {
            httpService.post(api_addedit_eventDocument.replace('{eventId}', vm.eventId), vm.model.documentDetail.listDocumentResults)
            .success(function (data) {
                vm.errors = [];
                console.log(data);
                vm.errors = data.errors;
                if (data.errors.length > 0) {
                    modelStateErrorBuilder.build(vm.errors, vm.model.documentDetail.listDocumentResults);
                    scrollToTop();
                } else {
                    if (vm.model.documentDetail.listDocuments.length > 0) {
                        angular.forEach(vm.model.documentDetail.listDocumentResults,
                            function (item) {
                                item.id = data.id;
                            });
                    }
                    console.log('Save document for event Successfull');
                    if (formConfig.eventId > 0) {
                        $rootScope.$broadcast("loader_show");
                        toaster.pop({
                            type: 'success',
                            title: 'Success',
                            body: 'Your changes have been successfully saved',
                            timeout: 2500,
                            onHideCallback: function () {
                                $rootScope.$broadcast("loader_hide");
                            }
                        });
                    } else {
                        nextTab();
                    }
                }
            }).then(function (res) {
                getEventDocument();
                vm.loading = false;
                console.log(vm.model.documentDetail.listDocuments);
            });
        }
        function isEventDocumentValid(form) {
            var incre = 0;
            vm.errors = [];
            angular.forEach(vm.model.documentDetail.listDocuments,
                function (item, idx) {
                    if (item.documentType == "" || item.documentType == null || item.documentType == undefined) {
                        incre++;
                        vm.docWithErrIdxArr.push(idx);
                    }
                });
            if (incre > 0) {
                addError("Please select a document type for all documents");
                return false;
            }
            return true;
        }
        function isEventDetailFormValid(form) {
            vm.errors = [];
            var isValid = true;
            var type = vm.model.eventDetail.type;
            var educationProgram = vm.model.eventDetail.educationProgram;

            if (type == "" || type == null || type === undefined) {
                isValid = false;
            }
            if (!isEducationProgramValid()) {
                isValid = false;
            }
            if (form.eventName.$error.required) {
                isValid = false;
            }
            if (form.primaryContactEmail.$error.required) {
                isValid = false;
            }

            if (!isValid) {
                addError("All fields highlighted in red are mandatory");
            }
            if (isValid) {
                var emailPrimaryValid = isEmailPrimaryValid(vm.model.eventDetail.primaryContactEmail);
                var emailSecondValid = isEmailSecondValid(vm.model.eventDetail.secondaryContactEmail);
                if (!emailPrimaryValid || !emailSecondValid) {
                    isValid = false;
                }
            }
            return isValid;
        }
        vm.isEducationProgramRequired = isEducationProgramRequired;
        function isEducationProgramRequired() {
            var type = vm.model.eventDetail.type;
            var isEducationEventType = false;
            angular.forEach(vm.educationEventTypes, function (val, key) {
                if (val.value === type) {
                    isEducationEventType = true;
                    return;
                }
            });
            return isEducationEventType;
        }
        function isEducationProgramValid() {
            var isValid = true;
            var educationProgram = vm.model.eventDetail.educationProgram;
            if (isEducationProgramRequired()) {
                if (educationProgram == "" || educationProgram == null || educationProgram === undefined) {
                    isValid = false;
                }
            }
            return isValid;
        }
        function isFlightOptionValid(form) {
            var isNotSaved = false;
            if (vm.model.flightDetail.listFlights.length == 1) {
                angular.forEach(vm.model.flightDetail.listFlights,
                    function (item) {
                        if (item == null) {
                            item.isNotAddOrUpdate = true;
                            isNotSaved = true;
                        }
                        else if (item != null) {
                            if ((item.departingFrom != '' && item.departingFrom != null && item.departingFrom != 0)
                                || (item.departingDate != '' && item.departingDate != null && item.departingDate != undefined)
                                || (item.departingTime != '' && item.departingTime != null && item.departingTime != undefined)
                                || (item.departingArrivalTime != '' && item.departingArrivalTime != null && item.departingArrivalTime != undefined)
                                || (item.returningDate != '' && item.returningDate != null && item.returningDate != undefined)
                                || (item.returningTime != '' && item.returningTime != null && item.returningTime != undefined)
                                || (item.returningArrivalTime != '' && item.returningArrivalTime != null && item.returningArrivalTime != undefined)) {
                                item.isNotAddOrUpdate = false;
                                isNotSaved = false;
                            } else {
                                item.isNotAddOrUpdate = true;
                                isNotSaved = true;
                            }
                        }
                    });
            }
            if (isNotSaved && !vm.isEditMode && formConfig.eventId <= 0) {
                nextTab();
                return false;
            }
            return true;
        }

        function isFlightDetailFormValid(form) {
            vm.errors = [];
            var isValid = true;
            var isTimeValid = true;
            var incre = 0;
            var isDateValid = true;
            var i = 0;
            var entered = 0;
            angular.forEach(vm.model.flightDetail.listFlights,
                       function (item) {
                           if (item != null) {
                               if (!item.isNotAddOrUpdate) {
                                   if (incre == 0) {
                                       if (item.departingFrom == '' || item.departingFrom == null || item.departingFrom == undefined) {
                                           incre++;
                                       }
                                       if (item.returningTo == '' || item.returningTo == null || item.returningTo == undefined) {
                                           incre++;
                                       }
                                       if (item.departingDate == '' || item.departingDate == null || item.departingDate == undefined) {
                                           incre++;
                                       }
                                       if (item.departingTime == '' || item.departingTime == null || item.departingTime == undefined) {
                                           incre++;
                                       }
                                       if (item.departingArrivalTime == '' || item.departingArrivalTime == null || item.departingArrivalTime == undefined) {
                                           incre++;
                                       }

                                       if (item.returningDate == '' || item.returningDate == null || item.returningDate == undefined) {
                                           incre++;
                                       }
                                       if (item.returningTime == '' || item.returningTime == null || item.returningTime == undefined) {
                                           incre++;
                                       }
                                       if (item.returningArrivalTime == '' || item.returningArrivalTime == null || item.returningArrivalTime == undefined) {
                                           incre++;
                                       }
                                       if ((item.departingFrom != '' && item.departingFrom != null && item.departingFrom != undefined)
                                           || (item.departingDate != '' && item.departingDate != null && item.departingDate != undefined)
                                           || (item.departingTime != '' && item.departingTime != null && item.departingTime != undefined)
                                           || (item.departingArrivalTime != '' && item.departingArrivalTime != null && item.departingArrivalTime != undefined)
                                           || (item.returningDate != '' && item.returningDate != null && item.returningDate != undefined)
                                           || (item.returningTime != '' && item.returningTime != null && item.returningTime != undefined)
                                           || (item.returningArrivalTime != '' && item.returningArrivalTime != null && item.returningArrivalTime != undefined)) {
                                           entered++;
                                           item.isNotAddOrUpdate = false;
                                       }
                                       if (incre <= 0) {
                                           var departingTime = $("#departingTime" + i).val();
                                           var departingArrivalTime = $("#departingArrivalTime" + i).val();
                                           var isTimeDepartingValid = checkTime(departingTime, departingArrivalTime);

                                           var returningTime = $("#returningTime" + i).val();
                                           var returningArrivalTime = $("#returningArrivalTime" + i).val();
                                           var isTimeReturningValid = checkTime(returningTime, returningArrivalTime);

                                           //item.departingDate = $("#departingDate" + i).datepicker('getDate');
                                           //item.returningDate = $("#returningDate" + i).datepicker('getDate');
                                           if (!isTimeDepartingValid || !isTimeReturningValid) {
                                               if (!isTimeDepartingValid) {
                                                   $("#departingTime" + i).addClass("ng-invalid ng-dirty has-error");
                                                   $("#departingArrivalTime" + i).addClass("ng-invalid ng-dirty has-error");
                                               } else {
                                                   $("#departingTime" + i).removeClass("ng-invalid ng-dirty has-error");
                                                   $("#departingArrivalTime" + i).removeClass("ng-invalid ng-dirty has-error");
                                               }
                                               if (!isTimeReturningValid) {
                                                   $("#returningTime" + i).addClass("ng-invalid ng-dirty has-error");
                                                   $("#returningArrivalTime" + i).addClass("ng-invalid ng-dirty has-error");
                                               } else {
                                                   $("#returningTime" + i).removeClass("ng-invalid ng-dirty has-error");
                                                   $("#returningArrivalTime" + i).removeClass("ng-invalid ng-dirty has-error");
                                               }

                                               isValid = false;
                                           } else {
                                               $("#returningTime" + i).addClass("ng-invalid ng-dirty has-error");
                                               $("#returningArrivalTime" + i).addClass("ng-invalid ng-dirty has-error");
                                               $("#returningTime" + i).removeClass("ng-invalid ng-dirty has-error");
                                               $("#returningArrivalTime" + i).removeClass("ng-invalid ng-dirty has-error");
                                           }
                                           if (item.departingDate > item.returningDate) {
                                               $("#departingArrivalTime" + i).removeClass("ng-invalid ng-dirty has-error");
                                               $("#returningTime" + i).removeClass("ng-invalid ng-dirty has-error");
                                               $("#departingDate" + i).addClass("ng-invalid ng-dirty has-error");
                                               $("#returningDate" + i).addClass("ng-invalid ng-dirty has-error");
                                               isDateValid = false;
                                           }
                                           else if (item.departingDate.getTime() == item.returningDate.getTime()
                                               && !IsDepartingArrivalTimeValid(item.departingArrivalTime, item.returningTime)) {
                                               $("#departingDate" + i).removeClass("ng-invalid ng-dirty has-error");
                                               $("#returningDate" + i).removeClass("ng-invalid ng-dirty has-error");
                                               $("#departingArrivalTime" + i).addClass("ng-invalid ng-dirty has-error");
                                               $("#returningTime" + i).addClass("ng-invalid ng-dirty has-error");
                                               isTimeValid = false;
                                           }
                                           else {
                                               $("#departingDate" +i).removeClass("ng-invalid ng-dirty has-error");
                                               $("#returningDate" +i).removeClass("ng-invalid ng-dirty has-error");
                                               $("#departingTime" +i).removeClass("ng-invalid ng-dirty has-error");
                                               $("#departingArrivalTime" +i).removeClass("ng-invalid ng-dirty has-error");
                                               $("#returningTime" +i).removeClass("ng-invalid ng-dirty has-error");
                                               $("#returningArrivalTime" +i).removeClass("ng-invalid ng-dirty has-error");
                                           }
                                       }
                                   }
                                   i++;
                               }
                           }
                       });
            if (entered > 0) {
                if (incre > 0) {
                    isValid = false;
                    addError("All fields highlighted in red are mandatory");
                } else {
                    if (!isValid)
                        addError("The departure time must be before the arrival time for all options");
                    if (!isDateValid) {
                        addError("Departing flight dates must be before the returning flight for all options");
                        isValid = false;
                    }
                    if (!isTimeValid) {
                        addError("Departing Arrival time must be before the returning departure time for all options");
                        isValid = false;
                    }
                }
            }

            return isValid;
        }
        function isNotCheckFlight(form) {
            var incre = 0;
            var i = 0;
            angular.forEach(vm.model.flightDetail.listFlights,
           function (item) {
               if (item != null) {
                   if ((item.departingFrom != '' && item.departingFrom != null && item.departingFrom != undefined)
                       || (item.departingDate != '' && item.departingDate != null && item.departingDate != undefined)
                       || (item.departingTime != '' && item.departingTime != null && item.departingTime != undefined)
                       || (item.departingArrivalTime != '' && item.departingArrivalTime != null && item.departingArrivalTime != undefined)
                       || (item.returningDate != '' && item.returningDate != null && item.returningDate != undefined)
                       || (item.returningTime != '' && item.returningTime != null && item.returningTime != undefined)
                       || (item.returningArrivalTime != '' && item.returningArrivalTime != null && item.returningArrivalTime != undefined)) {
                       incre++;
                   }
                   i++;
               }
           });

            if (incre == 0)
                return true;
            else
                return false;
        }
        function isFormAddPresenterValid(form) {
            vm.errors = [];
            var isValid = true;
            var profession = vm.model.newPresenter.professionId;
            var title = vm.model.newPresenter.title;
            var state = null;
            if (vm.model.newPresenter.institution == null || vm.model.newPresenter.institution == undefined) {
                state = null;
            } else {
                if (vm.model.newPresenter.institution.address == null || vm.model.newPresenter.institution.address == undefined)
                    state = null;
                else
                    state = vm.model.newPresenter.institution.address.state;
            }

            if (profession == "" || profession == null || profession === undefined) {
                isValid = false;
                $('#professionEvent').addClass("ng-invalid ng-dirty has-error");
            }
            if (title == "" || title == null || title === undefined) {
                $('#titleEvent').addClass("ng-invalid ng-dirty has-error");
                isValid = false;
            }
            if (state == "" || state == null || state === undefined) {
                $('#stateEvent').addClass("ng-invalid ng-dirty has-error");
                isValid = false;
            }
            if (form.eventInstitutionName.$error.required) {
                $('#eventInstitutionName').addClass("ng-invalid ng-dirty has-error");
                isValid = false;
            }
            if (form.firstNameEvent.$error.required) {
                $('#firstNameEvent').addClass("ng-invalid ng-dirty has-error");
                isValid = false;
            }
            if (form.lastNameEvent.$error.required) {
                $('#lastNameEvent').addClass("ng-invalid ng-dirty has-error");
                isValid = false;
            }
            if (form.emailEvent.$error.required) {
                $('#emailEvent').addClass("ng-invalid ng-dirty has-error");
                isValid = false;
            }
            if (form.addrLine1Event.$error.required) {
                $('#addrLine1Event').addClass("ng-invalid ng-dirty has-error");
                isValid = false;
            }
            if (form.suburbEvent.$error.required) {
                $('#suburbEvent').addClass("ng-invalid ng-dirty has-error");
                isValid = false;
            }
            if (form.postcodeEvent.$error.required) {
                $('#postcodeEvent').addClass("ng-invalid ng-dirty has-error");
                isValid = false;
            }
            if (!isValid) {
                addError("All fields highlighted in red are mandatory");;
            }
            if (isValid) {
                var emailValid = isEmailValid(vm.model.newPresenter.email);
                if (!emailValid) {
                    addError("Please specify a valid email");
                }
                var phoneValid = isPhoneValid(vm.model.newPresenter.phone);
                if (!phoneValid) {
                    addError("The phone number entered is invalid");
                }
                var mobileValid = isPhoneValid(vm.model.newPresenter.mobile);
                if (!mobileValid) {
                    addError("The mobile number entered is invalid");
                }
                var postcodeValid = isPostCodeValid(vm.model.newPresenter.institution.address.postcode);
                if (!postcodeValid) {
                    addError("Postcode provided is invalid");
                }
                if (!emailValid || !phoneValid || !mobileValid || !postcodeValid) {
                    isValid = false;
                }
            }
            return isValid;
        }

        // TAB FUNCTIONS
        vm.activeTabIndex = 1;

        function nextTab() {
            if (vm.activeTabIndex < 6) {
                vm.errors = [];
                vm.activeTabIndex = vm.activeTabIndex + 1;
            }
        }

        function previousTab() {
            if (vm.activeTabIndex > 1) {
                vm.errors = [];
                vm.activeTabIndex = vm.activeTabIndex - 1;
            }
            else {
                // redirect to previous page
            }
        }

        // COMMON FUNCTIONS
        function getItems(url) {
            var items = [];
            return httpService.get(url, { disable_loading: true })
                .then(function (response) {
                    response.data.forEach(function (item) {
                        items.push(item);
                    });
                    return items;
                });
        }
        function redirectEventAdministration() {
            window.location.href = formConfig.eventListUrl;
        }
        function checkTime(startTime, endTime) {
            var stt = new Date("Jan 01, 2016 " + startTime);
            stt = stt.getTime();
            var endt = new Date("Jan 01, 2016 " + endTime);
            endt = endt.getTime();
            if (stt >= endt) {
                return false;
            }
            return true;
        }

        function IsDepartingArrivalTimeValid(departingArrivalTime, returningDepartingTime) {
            var stt = new Date("Jan 01, 2016 " + departingArrivalTime);
            stt = stt.getTime();
            var endt = new Date("Jan 01, 2016 " + returningDepartingTime);
            endt = endt.getTime();
            if (stt >= endt) {
                return false;
            }
            return true;
        }

        function convertAMPMformat(time) {
            var hrs = Number(time.match(/^(\d+)/)[1]);
            var mnts = Number(time.match(/:(\d+)/)[1]);
            var hours = hrs == 0 ? "12" : hrs > 12 ? hrs - 12 : hrs;
            var minutes = (mnts < 10 ? "0" : "") + mnts;
            var ampm = hrs < 12 ? "AM" : "PM";
            var formattedTime = hours + ":" + minutes + " " + ampm;
            return formattedTime;
        }
        function convertTimeformat(time) {
            var hrs = Number(time.match(/^(\d+)/)[1]);
            var mnts = Number(time.match(/:(\d+)/)[1]);
            var format = time.match(/\s(.*)$/)[1];
            if (format == "PM" && hrs < 12) hrs = hrs + 12;
            if (format == "AM" && hrs == 12) hrs = hrs - 12;
            var hours = hrs.toString();
            var minutes = mnts.toString();
            if (hrs < 10) hours = "0" + hours;
            if (mnts < 10) minutes = "0" + minutes;
            return hours + ":" + minutes;
        }
        function compareDateFlight() {
            var i = 0;
            angular.forEach(vm.model.flightDetail.listFlightResults,
                function (item) {
                    //item.departingDate = $("#departingDate" + i).datepicker('getDate');
                    //item.returningDate = $("#returningDate" + i).datepicker('getDate');
                    item.departingTime = $("#departingTime" + i).val();
                    item.departingArrivalTime = $("#departingArrivalTime" + i).val();
                    item.returningTime = $("#returningTime" + i).val();
                    item.returningArrivalTime = $("#returningArrivalTime" + i).val();

                    item.departingTime = convertTimeformat(item.departingTime);
                    item.departingArrivalTime = convertTimeformat(item.departingArrivalTime);
                    item.returningTime = convertTimeformat(item.returningTime);
                    item.returningArrivalTime = convertTimeformat(item.returningArrivalTime);

                    item.departingTime = moment(item.departingTime, "HH:mm").format("HH:mm");
                    item.departingArrivalTime = moment(item.departingArrivalTime, "HH:mm").format("HH:mm");
                    item.returningTime = moment(item.returningTime, "HH:mm").format("HH:mm");
                    item.returningArrivalTime = moment(item.returningArrivalTime, "HH:mm").format("HH:mm");
                    i++;
                });
        }
        function getTimeOffSet(item) {
            // Create a new JavaScript Date object based on the timestamp
            // multiplied by 1000 so that the argument is in milliseconds, not seconds.
            var date = new Date(item * 1000);
            // Hours part from the timestamp
            var hours = date.getHours();
            // Minutes part from the timestamp
            var minutes = "0" + date.getMinutes();
            // Seconds part from the timestamp
            var seconds = "0" + date.getSeconds();

            // Will display time in 10:30:23 format
            return hours + ':' + minutes.substr(-2);
        }
        function utcDate(date) {
            date = new Date(date);
            //Local time converted to UTC
            console.log("Time: " + date);
            var localOffset = 1440 * 60000;
            var localTime = date.getTime();

            date = localTime + localOffset;
            date = new Date(date);

            return date;
        }
        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }

        function isPostCodeValid(postCode) {
            if (postCode != null && postCode != undefined && postCode.length > 0) {
                if (postCode.length < 4) {
                    return false;
                }
            }
            return true;
        }

        function isEmailValid(value) {
            var isValid = true;
            if (value != "" && value != undefined && !isEmail(value)) {
                isValid = false;
            }
            return isValid;
        }

        function isPhoneValid(value) {
            var isValid = true;
            if (value != null && value != undefined && value.length > 0) {
                if (value.length < 10) {
                    isValid = false;
                }
            }
            return isValid;
        }

        vm.onChangeEmail = onChangeEmail;
        vm.onChangeSecondEmail = onChangeSecondEmail;
        vm.onChangeEmailPresenter = onChangeEmailPresenter;
        function onChangeEmail($event) {
            vm.errors = [];
            vm.validate = 0;
            var val = $($event.target).val();
            showErrorEmail($event.target, val);
        }
        function onChangeSecondEmail($event) {
            vm.errors = [];
            vm.validate = 0;
            var val = $($event.target).val();
            showErrorEmail($event.target, val);
        }
        function onChangeEmailPresenter($event, form) {
            vm.errors = [];
            vm.validate = 0;
            var val = $($event.target).val();
            var incre = showErrorEmail($event.target, val);
            if (incre == 0)
                vm.isErrorPresenter = true;

            isFormAddPresenterValid(form);
        }
        function showErrorEmail(obj, val) {
            if ((val == "" && $(obj).attr("required") !== undefined) || (val != "" && !isEmail(val))) {
                $($(obj).parent()).addClass("ng-invalid ng-dirty has-error");
                if (val != "" && !isEmail(val)) {
                    addError("Please specify a valid email address");
                }
                return 0;
            }
            else {
                $($(obj).parent()).removeClass("ng-invalid ng-dirty has-error");
                $(obj).parent().find(".help-block").html("");
            }
            return 1;
        }
        function isEmailPrimaryValid(value) {
            var isValid = true;
            if (value != "" && value != undefined && !isEmail(value)) {
                addError("Please provide a valid primary email address");
                isValid = false;
                $('#primaryContactEmail').addClass("ng-invalid ng-dirty has-error");
            } else {
                isValid = true;
                $('#primaryContactEmail').removeClass("ng-invalid ng-dirty has-error");
            }
            return isValid;
        }

        function isEmailSecondValid(value) {
            var isValid = true;
            if (value != "" && value != undefined && !isEmail(value)) {
                addError("Please provide a valid second email address");
                isValid = false;
                $('#secondaryContactEmail').addClass("ng-invalid ng-dirty has-error");
            } else {
                isValid = true;
                $('#secondaryContactEmail').removeClass("ng-invalid ng-dirty has-error");
            }
            return isValid;
        }

        function isEmail(value) {
            value = value === undefined || value == null ? "" : value;
            var regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
            var val = $.trim(value);
            return regex.test(val);
        }

        function addError(message, key) {
            var isExists = false;
            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists) {
                var theError = {
                    message: message
                };

                if (key && key !== null) {
                    theError.key = key;
                }
                vm.errors.push(theError);
            }
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('EventAccommodationListController', EventAccommodationListController);
    EventAccommodationListController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService',
        'uiGridConstants', 'moment', 'utilitySvc', 'formConfig'];

    function EventAccommodationListController($rootScope, $scope, $window, filterFilter, httpService,
        uiGridConstants, moment, utilitySvc, formConfig) {
        var vm = this;
        vm.eventId = formConfig.eventId;
        vm.event = {};
        vm.errors = [];
        vm.rooms = [];
        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: 'id',
            keyword: ''
        };
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getDataGird);
        vm.gridOptions.paginationPageSizes = [25, 50, 75, 100];
        vm.gridOptions.columnDefs = [
            { name: 'hcpName', displayName: 'HCP name', enableCellEdit: false },
            { name: 'email', displayName: 'Email', enableCellEdit: false },
            { name: 'hotelName', displayName: 'Hotel', enableCellEdit: false },
             {
                 name: 'roomTypeName', displayName: 'Room', editableCellTemplate: 'ui-grid/dropdownEditor',
                 editDropdownIdLabel: 'roomTypeName',
                 editDropdownValueLabel: 'roomTypeName',
                 editDropdownRowEntityOptionsArrayPath: 'eventAccommodationRelates',
                 enableCellEdit: true
             },
             {
                 field: 'bookingReference',
                 enableSorting: true,
                 displayName: 'Booking reference',
                 enableCellEdit: true
             },
            {
                field: 'isBreakfastIncluded',
                enableSorting: true,
                displayName: 'Breakfast included',
                maxWidth: 100,
                enableCellEdit: false,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center""><input type="checkbox" ng-checked="row.entity.isBreakfastIncluded" disabled></div>'
            },
            {
                field: 'isParkingRequired',
                enableSorting: true,
                displayName: 'Parking required',
                maxWidth: 100,
                enableCellEdit: false,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center""><input type="checkbox" ng-checked="row.entity.isParkingRequired" disabled></div>'
            }
        ];

        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getDataGird();
            }
        });
        
        var defaultOnRegisterApi = vm.gridOptions.onRegisterApi;
        vm.gridOptions.onRegisterApi = function (gridApi) {
            $scope.gridApi = gridApi;
            gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
                console.log(rowEntity);
                if (colDef.name === 'roomTypeName' && oldValue !== newValue) {
                    updateRoom(rowEntity, oldValue,newValue);
                }

                if (colDef.name === 'bookingReference' && oldValue !== newValue) {
                    updateBookingReference(rowEntity, oldValue, newValue);
                }
            });

            defaultOnRegisterApi(gridApi);
        };


        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.gridOptions);
        }

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            //initLookups();
            getEventDetail();
            getDataGird();
        };
        
        function getEventDetail() {
            if (formConfig.eventId > 0) {
                httpService.get(api_get_event_detail.replace('{id}', formConfig.eventId))
                    .then(function (response) {
                        if (response.data != null) {
                            vm.event = response.data;
                        }
                    }, function (response) {
                        if (response.status == 404) {
                            location.href = formConfig.eventListUrl;
                        }
                    });
            }
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
                .success(function (data) {
                    vm.rooms = data.RoomType;
                    vm.gridOptions.columnDefs[3].editDropdownOptionsArray = vm.rooms;
                });
        }

        function getDataGird() {
            vm.errors = [];
            var url = api_event_searchEventHcpAccommodation;
            url += '?pageSize=' + vm.searchOption.pageSize;
            url += '&pageNo=' + vm.searchOption.pageNumber;
            url += '&sortFields=' + vm.searchOption.sort;
            url += '&keyword=' + vm.searchOption.keyword;
            url += '&eventId=' + vm.eventId;
            return httpService.get(url).then(function (response) {
                console.log(response);
                if (response.data.success) {
                    vm.gridOptions.data = response.data.data.result;
                    vm.gridOptions.totalItems = response.data.data.totalCount;

                } else {
                    vm.errors = response.data.errors;
                }
            });
        }

        function updateRoom(model, oldValue, newValue) {
            httpService.post(api_event_updateRoom, model).then(function(response) {
                if (response.data.success) {

                } else {
                    vm.errors = response.data.errors;
                }
            });
        }

        function updateBookingReference(model, oldValue, newValue) {
            httpService.post(api_event_updateBookingReference, model).then(function (response) {
                if (response.data.success) {

                } else {
                    vm.errors = response.data.errors;
                }
            });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('EventAttendeeListController', EventAttendeeListController);
    EventAttendeeListController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService',
        'uiGridConstants', 'moment', 'utilitySvc', 'formConfig', 'toaster'];

    function EventAttendeeListController($rootScope, $scope, $window, filterFilter, httpService,
        uiGridConstants, moment, utilitySvc, formConfig, toaster) {
        var vm = this;
        $scope.isContributorUser = formConfig.isContributorUser;
        vm.errors = [];
        vm.eventId = formConfig.eventId;
        vm.event = {};
        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: 'id',
            keyword: ''
        };
        $scope.updateAttendeeStatus = updateAttendeeStatus;
        $scope.editEventHcp = editEventHcp;
        $scope.unInviteHcp = unInviteHcp;
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getDataGird);
        vm.gridOptions.paginationPageSizes = [25, 50, 75, 100];
        vm.gridOptions.columnDefs = [
            { name: 'createdOn', displayName: 'Invited date', enableCellEdit: false, maxWidth: 120 },
            { name: 'registeredOn', displayName: 'Registered date', enableCellEdit: false, maxWidth: 120 },
            { name: 'nameOfAttendee', displayName: 'Name of HCP', enableCellEdit: false },
            { name: 'hcp.profile.email', displayName: 'Email', enableCellEdit: false },
            { name: 'mobile', displayName: 'Mobile', maxWidth: 160, enableCellEdit: false },
            {
                name: 'dateOfAttendance',
                displayName: 'Date of attendance', maxWidth: 120,
                editableCellTemplate: '<input placeholder="DD/MM/YYYY" type="text" id="dateOfBirth{{row.entity.id}}" name="dateOfBirth{{row.entity.id}}" ' +
                    'ng-model="row.entity.dateOfAttendance" ui-grid-edit-datepicker />',
                //type: 'date',
                cellFilter: "date : 'dd/MM/yyyy'",
                cellEditableCondition: function ($scope) {
                    return $scope.row.entity.registeredOn != null;
                }
            },
            {
                field: 'status',
                enableSorting: false,
                displayName: 'Status',
                minWidth: 300,
                enableCellEdit: false,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center" ng-if="row.entity.registeredOn !=null">' +
                        '<div class="switch-toggle">' +
                            '<input id="{{row.entity.id}}_statusPending" name="{{row.entity.id}}_statusPending" ng-value="1" ng-model="row.entity.status" type="radio" ng-click="grid.appScope.updateAttendeeStatus(row.entity, 1)">' +
                            '<label for="{{row.entity.id}}_statusPending">Pending</label>' +
                            '<input id="{{row.entity.id}}_statusApproved" name="{{row.entity.id}}_statusApproved" ng-value="2" ng-model="row.entity.status" type="radio" ng-click="grid.appScope.updateAttendeeStatus(row.entity, 2)">' +
                            '<label for="{{row.entity.id}}_statusApproved">Approved</label>' +
                            '<input id="{{row.entity.id}}_statusDeclined" name="{{row.entity.id}}_statusDeclined" ng-value="3" ng-model="row.entity.status" type="radio" ng-click="grid.appScope.updateAttendeeStatus(row.entity, 3)">' +
                            '<label for="{{row.entity.id}}_statusDeclined">Declined</label>' +
                            '<a class="btn btn-blue"></a>' +
                        '</div>' +
                    '</div>'
            },
            {
                field: 'id',
                enableSorting: false,
                displayName: '',
                maxWidth: 80,
                enableCellEdit: false,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center" ng-if="row.entity.registeredOn !=null"><a href="#" ng-click="grid.appScope.editEventHcp(row.entity.id)"><span ng-if="!grid.appScope.isContributorUser">edit</span><span ng-if="grid.appScope.isContributorUser">view</span></a></div>' +
                '<div class="ui-grid-cell-contents text-center" ng-if="row.entity.registeredOn ==null"><a href="#" ng-click="grid.appScope.unInviteHcp(row.entity.id, row.entity.hcp)">uninvite</a></div>'

            }
        ];

        var defaultOnRegisterApi = vm.gridOptions.onRegisterApi;
        vm.gridOptions.onRegisterApi = function (gridApi) {
            $scope.gridApi = gridApi;
            gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
                console.log(rowEntity);
                if (colDef.name === 'dateOfAttendance' && oldValue !== newValue) {
                    // call update api
                    updateDateAttendee(rowEntity, oldValue, newValue);
                }
            });

            defaultOnRegisterApi(gridApi);
        };

        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getDataGird();
            }
        });

        function updateDateAttendee(rowEntity, oldValue, newValue) {
            var isValidDate = newValue === null || newValue === undefined || (typeof (newValue) === "string" && newValue.trim() === "");

            if (!isValidDate) {
                if (!(newValue instanceof Date)) {
                    newValue = moment(newValue, 'DD/MM/YYYY', true).toDate();
                }

                isValidDate = newValue instanceof Date && !isNaN(newValue.getTime());
            }

            if (isValidDate) {
                rowEntity['dateOfAttendance'] = newValue;
                httpService.post(api_event_updateDateOfAttendee, rowEntity).then(function (response) {
                    if (response.data.success) {
                        getDataGird();
                    } else {
                        vm.errors = response.data.errors;
                    }
                });
            }
            else {
                toaster.pop({
                    type: 'error',
                    title: 'Invalid date',
                    body: 'Please enter a valid date with format DD/MM/YYYY',
                    timeout: 2500
                });
                rowEntity['dateOfAttendance'] = oldValue;
            }

            return isValidDate;
        }

        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.gridOptions);
        }

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            getEventDetail();
            getDataGird();
            console.log(formConfig.editEventHcpUrl);
        };

        function getEventDetail() {
            if (formConfig.eventId > 0) {
                httpService.get(api_get_event_detail.replace('{id}', formConfig.eventId))
                    .then(function (response) {
                        if (response.data != null) {
                            vm.event = response.data;
                        }
                    }, function (response) {
                        if (response.status == 404) {
                            location.href = formConfig.eventListUrl;
                        }
                    });
            }
        }

        function getDataGird() {
            var url = api_event_searchEventHcp;
            url += '?pageSize=' + vm.searchOption.pageSize;
            url += '&pageNo=' + vm.searchOption.pageNumber;
            url += '&sortFields=' + vm.searchOption.sort;
            url += '&eventId=' + vm.eventId;
            url += '&keyword=' + vm.searchOption.keyword;
            var browserTimeZone = moment.tz.guess();
            url += '&browserTimeZone=' + browserTimeZone;
            return httpService.get(url).then(function (response) {
                if (response.data.success) {
                    console.log(response.data.data.result);
                    vm.gridOptions.data = response.data.data.result;
                    vm.gridOptions.totalItems = response.data.data.totalCount;

                    angular.forEach(vm.gridOptions.data,
                       function (item) {
                           if (item.createdOn && item.createdOn != null) {
                               item.createdOn = moment.utc(item.createdOn).local().format("DD/MM/YYYY");
                           }
                           if (item.registeredOn && item.registeredOn != null) {
                               item.registeredOn = moment.utc(item.registeredOn).local().format("DD/MM/YYYY");
                           }
                           if (item.dateOfAttendance && item.dateOfAttendance != null) {
                               item.dateOfAttendance = moment.utc(item.dateOfAttendance).local().format("DD/MM/YYYY");
                           }
                           item.originalStatus = item.status;
                           item.originalStatusName = item.statusName;
                       });

                } else {
                    vm.errors = response.data.errors;
                }
            });
        }

        function updateAttendeeStatus(item, status) {
            httpService.post(api_event_updateAttendeeStatus.replace('{eventHcpId}', item.id).replace('{status}', status)).then(function (response) {
                if (response.data.success) {
                    updateGirdItem(response.data.data);
                } else {
                    item.status = item.originalStatus;
                    item.statusName = item.originalStatusName;
                    response.data.errors.forEach(function (error) {
                        addError(error);
                    });
                }
            });
        }

        function updateGirdItem(item) {
            $.each(vm.gridOptions.data,
                function (index, element) {
                    if (element.id === item.id) {
                        element.status = item.status;
                        element.statusName = item.statusName;
                        return;
                    }
                });
        }

        function addError(error) {
            var isExists = false;
            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i].message === error.message) {
                    isExists = true;
                    break;
                }
            }
            if (!isExists) vm.errors.push(error);
        }

        function editEventHcp(eventHcpId) {
            window.location.href = formConfig.editEventHcpUrl
                .replace('eventHcpIdTmp', eventHcpId)
                .replace('eventIdTmp', vm.eventId);
        }

        function unInviteHcp(eventHcpId, hcp) {
            if (confirm("Are you sure want to uninvite this user?")) {
                httpService.post(api_event_unInviteHcp.replace('{eventHcpId}', eventHcpId))
                .then(function (response) {
                    if (response.data.success) {
                        getDataGird();
                    } else {
                        item.status = item.originalStatus;
                        item.statusName = item.originalStatusName;
                        response.data.errors.forEach(function (error) {
                            addError(error);
                        });
                    }
                });
            }
        }

        $rootScope.$on('Event_Attendee_Invited', function () {
            getDataGird();
        });
    }

})();;
(function () {
    'use strict';

    window.app.controller('EventEditAttendeeController', EventEditAttendeeController);
    EventEditAttendeeController.$inject = ['$scope', '$window', 'utilitySvc', 'httpService',
        'formConfig', '$timeout'];

    function EventEditAttendeeController($scope, $window, utilitySvc, httpService,
        formConfig, $timeout) {
        var vm = this;
        vm.init = init;
        vm.eventHcpId = formConfig.eventHcpId;
        vm.eventId = 0;
        vm.hcpId = 0;
        vm.contactDetailsFormSubmit = contactDetailsFormSubmit;
        vm.flightsFormSubmit = flightsFormSubmit;
        vm.accommodationFormSubmit = accommodationFormSubmit;
        vm.specialRequestsFormSubmit = specialRequestsFormSubmit;
        vm.cancelRegistration = cancelRegistration;
        vm.isShowOtherFlight = true;
        vm.clickFlight = clickFlight;
        vm.clickAccommodation = clickAccommodation;
        vm.clearAccomodations = clearAccomodations;
        vm.isHcpInputsDisabled = true;
        vm.viewOnly = formConfig.viewOnly || false;
        vm.isHasAnyFlightSelected = isHasAnyFlightSelected;
        vm.checkFlightRequestText = checkFlightRequestText;
        vm.otherFlightRequestHasValue = false;

        vm.errors = [];
        vm.messages = [];
        vm.model = {
            contactDetails: {
                hcp: { mode: 'search' }
            },
            flights: {},
            accommodations: { enabled: false },
            specialRequests: {}
        };
        vm.event = {};
        function init() {
            initLookups();
            getEventHcpDetail();
        }

        function getEventHcpDetail() {
            httpService.get(api_event_getEventHcpDetail.replace('{eventHcpId}', vm.eventHcpId)).then(function (response) {
                console.log(response);
                if (response.data.success) {
                    vm.eventId = response.data.data.event.id;
                    vm.event = response.data.data.event;
                    vm.event.flights = $.grep(vm.event.flights, function (value) {
                        var isHcpSelected = false;
                        angular.forEach(response.data.data.flights, function (item, idx) {
                            if (item.flightId === value.id && !item.isDeleted && value.isDeleted) {
                                isHcpSelected = true;
                                return false;
                            }
                        });

                        return value.isDeleted === false || isHcpSelected;
                    });
                    vm.event.accommodations = $.grep(vm.event.accommodations, function (value) {
                        var isHcpSelected = false;
                        angular.forEach(response.data.data.accommodations, function (item, idx) {
                            if (item.eventAccommodationId === value.id && !item.isDeleted && value.isDeleted) {
                                isHcpSelected = true;
                                return false;
                            }
                        });

                        return value.isDeleted === false || isHcpSelected;
                    });
                    vm.event.venues = $.grep(vm.event.venues, function (value) {
                        return value.isDeleted === false;
                    });

                    // populate data
                    vm.model.contactDetails.hcp = response.data.data.hcp;
                    vm.hcpId = vm.model.contactDetails.hcp.id;
                    vm.model.flights.frequentName = response.data.data.frequentFlyerClubName;
                    vm.model.flights.frequentNumber = response.data.data.frequentFlyerMembershipNumber;
                    vm.model.flights.isAirportToHotel = response.data.data.isAirportToHotel;
                    vm.model.flights.isHotelToAirport = response.data.data.isHotelToAirport;
                    vm.model.flights.otherFlightRequest_DepartingFrom = response.data.data.otherFlightRequest_DepartingFrom;
                    vm.model.flights.otherFlightRequest_ReturningTo = response.data.data.otherFlightRequest_ReturningTo;
                    vm.model.specialRequests.specialMealRequirement = response.data.data.specialMealRequirement;
                    vm.model.specialRequests.medicalConditions = response.data.data.medicalConditions;

                    response.data.data.flights = $.grep(response.data.data.flights, function (value) {
                        return value.isDeleted === false;
                    });
                    response.data.data.accommodations = $.grep(response.data.data.accommodations, function (value) {
                        return value.isDeleted === false;
                    });
                    
                    if (vm.model.flights.otherFlightRequest_DepartingFrom || vm.model.flights.otherFlightRequest_ReturningTo) {
                        vm.otherFlightRequestHasValue = true;
                    }
                    else {
                        if (response.data.data.flights != null && response.data.data.flights.length > 0) {
                            $.each(vm.event.flights, function (index, element) {
                                var foundItem = isFlightExistInArray(response.data.data.flights, element);
                                if (foundItem != null) {
                                    element.isSelected = true;
                                    vm.isShowOtherFlight = false;
                                }
                            });
                        }
                    }
                    if (response.data.data.accommodations != null && response.data.data.accommodations.length > 0) {
                        $.each(vm.event.accommodations, function (index, element) {
                            var foundItem = isExistAccommodationInArray(response.data.data.accommodations, element);
                            if (foundItem != null) {
                                element.isSelected = true;
                                element.isParkingRequired = foundItem.isParkingRequired;
                                vm.model.accommodations.enabled = true;
                            }
                        });
                    }

                } else {
                    response.data.errors.forEach(function (error) {
                        addError(error.message);
                    });
                }
            });
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                vm.hcpProfessions = data.Hcp_Profession;
                vm.titles = data.Title;
                vm.states = data.State;
            });
        }

        function cancelRegistration() {
            window.location.href = formConfig.manageAttendeeUrl;
        }

        function contactDetailsFormSubmit(event, form) {
            if (isContactDetailsFormValid(form)) {
                nextTab();
            } else {
                scrollToTop();
            }
        }

        function flightsFormSubmit(event, form) {
            nextTab();
        }

        function accommodationFormSubmit(event, form) {
            nextTab();
        }

        function specialRequestsFormSubmit(event, form) {
            if (isSpecialRequestsFormValid(form)) {
                var registerEventHcpViewModel = {
                    id: vm.eventHcpId,
                    eventId: vm.eventId,
                    hcpId: vm.model.contactDetails.hcp.id,
                    title: vm.model.contactDetails.hcp.profile.title,
                    firstName: vm.model.contactDetails.hcp.profile.firstName,
                    lastName: vm.model.contactDetails.hcp.profile.lastName,
                    institution: vm.model.contactDetails.hcp.institution,
                    mobile: vm.model.contactDetails.mobile,
                    frequentName: vm.model.flights.frequentName,
                    frequentNumber: vm.model.flights.frequentNumber,
                    isAirportToHotel: vm.model.flights.isAirportToHotel,
                    isHotelToAirport: vm.model.flights.isHotelToAirport,
                    otherFlightRequest_DepartingFrom: vm.model.flights.otherFlightRequest_DepartingFrom,
                    otherFlightRequest_ReturningTo: vm.model.flights.otherFlightRequest_ReturningTo,
                    specialMealRequirement: vm.model.specialRequests.specialMealRequirement,
                    medicalConditions: vm.model.specialRequests.medicalConditions,
                    flights: [],
                    accommodations: []
                };

                if (!vm.isShowOtherFlight) {
                    $.each(vm.event.flights, function (index, item) {
                        if (item.isSelected) {
                            registerEventHcpViewModel.flights.push(item);
                        }
                    });
                    registerEventHcpViewModel.otherFlightRequest_DepartingFrom = null;
                    registerEventHcpViewModel.otherFlightRequest_ReturningTo = null;
                }

                if (vm.model.accommodations.enabled) {
                    $.each(vm.event.accommodations, function (index, item) {
                        if (item.isSelected) {
                            registerEventHcpViewModel.accommodations.push(item);
                        }
                    });
                }

                httpService.post(api_event_registerEventHcp, registerEventHcpViewModel).then(function (response) {
                    console.log(response);
                    if (response.data.success) {
                        window.location.href = formConfig.manageAttendeeUrl;
                    } else {
                        response.data.errors.forEach(function (error) {
                            addError(error.message);
                        });
                    }
                });

            } else {
                scrollToTop();
            }
        }

        function clickFlight(item) {
            if (!vm.viewOnly) {
                var prevSelectedElement = null;
                $.each(vm.event.flights, function (index, element) {
                    if (element.isSelected === true) {
                        prevSelectedElement = element;
                        if (element.id !== item.id) {
                            element.isSelected = false;
                        }
                    }
                });

                if (item.isSelected == undefined) item.isSelected = false;

                item.isSelected = !item.isSelected;
                checkVisibleOtherFlight();

                if ((prevSelectedElement == null && item.isSelected) || (prevSelectedElement != null && !item.isSelected)) {
                    resetGroundTransfer();
                }
            }
        }

        function checkFlightRequestText() {
            vm.otherFlightRequestHasValue = false;
            if (vm.model.flights.otherFlightRequest_DepartingFrom && vm.model.flights.otherFlightRequest_DepartingFrom.trim() != ''
            || vm.model.flights.otherFlightRequest_ReturningTo && vm.model.flights.otherFlightRequest_ReturningTo.trim() != '') {
                vm.otherFlightRequestHasValue = true;
            }

            if (!vm.otherFlightRequestHasValue) {
                resetGroundTransfer();
            }
        }

        function checkVisibleOtherFlight() {
            console.log(isHasAnyFlightSelected());
            if (isHasAnyFlightSelected()) {
                vm.isShowOtherFlight = false;
                vm.model.flights.otherFlightRequest_DepartingFrom = undefined;
                vm.model.flights.otherFlightRequest_ReturningTo = undefined;
                vm.otherFlightRequestHasValue = false;
            } else {
                vm.isShowOtherFlight = true;
            }
        }

        function resetGroundTransfer() {
            vm.model.flights.isAirportToHotel = undefined;
            vm.model.flights.isHotelToAirport = undefined;
        }

        function isHasAnyFlightSelected() {
            console.log(vm.event.flights);
            var result = false;
            $.each(vm.event.flights, function (index, item) {
                if (item.isSelected != undefined && item.isSelected) {
                    result = true;
                }
            });

            return result;
        }

        function clickAccommodation(item) {
            if (!vm.viewOnly) {
                if (vm.model.accommodations.enabled) {
                    $.each(vm.event.accommodations, function (index, element) {
                        if (element.isSelected === true && element.id !== item.id) {
                            element.isSelected = false;
                        }
                    });
                    if (item.isSelected == undefined) item.isSelected = false;
                    item.isSelected = !item.isSelected;
                }
            }
        }

        function clearAccomodations() {
            if (!vm.model.accommodations.enabled) {
                $.each(vm.event.accommodations, function (index, element) {
                    element.isSelected = false;
                });
            }
        }

        function isContactDetailsFormValid(form) {
            vm.errors = [];
            $($('#LastName').parent()).removeClass('has-error');
            var isValid = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                isValid = false;
            }

            if (!vm.model.contactDetails.hcp
                || vm.model.contactDetails.hcp.id == undefined
                || vm.model.contactDetails.hcp.id === 0) {
                addError("All fields highlighted in red are mandatory");
                $($('#LastName').parent()).addClass("has-error");
                isValid = false;
            }

            return isValid;
        }

        function isSpecialRequestsFormValid(form) {
            vm.errors = [];
            var isValid = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                isValid = false;
            }

            return isValid;
        }

        // TAB FUNCTIONS
        vm.activeTabIndex = 1;
        vm.previousTab = previousTab;

        function nextTab() {
            if (vm.activeTabIndex < 6) {
                vm.errors = [];
                vm.activeTabIndex = vm.activeTabIndex + 1;
            }
        }

        function previousTab() {
            if (vm.activeTabIndex > 1) {
                vm.errors = [];
                vm.activeTabIndex = vm.activeTabIndex - 1;
            }
        }

        // COMMON FUNCTIONS
        function addError(message) {
            var isExists = false;
            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }
            if (!isExists) vm.errors.push(message);
        }

        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }

        function isFlightExistInArray(array, item) {
            var result = null;
            $.each(array,
                function(index, element) {
                    if (element.flightId === item.id) {
                        result = element;
                    }
                });
            return result;
        }
        function isExistAccommodationInArray(array, item) {
            var result = null;
            $.each(array,
                function (index, element) {
                    if (element.eventAccommodationId === item.id) {
                        result = element;
                    }
                });
            return result;
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('EventFlightListController', EventFlightListController);
    EventFlightListController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService',
        'uiGridConstants', 'moment', 'utilitySvc', 'formConfig'];

    function EventFlightListController($rootScope, $scope, $window, filterFilter, httpService,
        uiGridConstants, moment, utilitySvc, formConfig) {
        var vm = this;
        vm.eventId = formConfig.eventId;
        vm.event = {};
        vm.errors = [];
        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: 'id',
            keyword: ''
        };
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getDataGird);
        vm.gridOptions.paginationPageSizes = [25, 50, 75, 100];
        vm.gridOptions.columnDefs = [
            { name: 'hcpName', displayName: 'HCP name', enableCellEdit: false,maxWidth:200 },
            { name: 'departingFrom', displayName: 'Departing from', enableCellEdit: false, enableSorting: true },
            {
                field: 'departing',
                enableSorting: false,
                displayName: 'Flight selected',
                enableCellEdit: false,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center"">{{row.entity.departing}} <br/> {{row.entity.returning}}</div>'
            },
             {
                 field: 'bookingReference',
                 enableSorting: true,
                 displayName: 'Booking reference',
                 enableCellEdit: true,
                  maxWidth: 200
             },
            {
                field: 'isAirportToHotel',
                enableSorting: true,
                displayName: 'Transfer from airport',
                maxWidth: 100,
                enableCellEdit: false,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center""><input type="checkbox" ng-checked="row.entity.isAirportToHotel" disabled></div>'
            },
            {
                field: 'isHotelToAirport',
                enableSorting: true,
                displayName: 'Transfer to airport',
                maxWidth: 100,
                enableCellEdit: false,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center""><input type="checkbox" ng-checked="row.entity.isHotelToAirport" disabled></div>'
            }
        ];

        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getDataGird();
            }
        });

        var defaultOnRegisterApi = vm.gridOptions.onRegisterApi;
        vm.gridOptions.onRegisterApi = function (gridApi) {
            $scope.gridApi = gridApi;
            gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
                console.log(rowEntity);
                if (colDef.name === 'bookingReference' && oldValue !== newValue) {
                    updateBookingReference(rowEntity, oldValue, newValue);
                }
            });

            defaultOnRegisterApi(gridApi);
        };


        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.gridOptions);
        }

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            getEventDetail();
            getDataGird();
        };
        
        function getEventDetail() {
            if (formConfig.eventId > 0) {
                httpService.get(api_get_event_detail.replace('{id}', formConfig.eventId))
                    .then(function (response) {
                        if (response.data != null) {
                            vm.event = response.data;
                        }
                    }, function (response) {
                        if (response.status == 404) {
                            location.href = formConfig.eventListUrl;
                        }
                    });
            }
        }

        function getDataGird() {
            vm.errors = [];
            var url = api_event_searchEventHcpFlight;
            url += '?pageSize=' + vm.searchOption.pageSize;
            url += '&pageNo=' + vm.searchOption.pageNumber;
            url += '&sortFields=' + vm.searchOption.sort;
            url += '&keyword=' + vm.searchOption.keyword;
            url += '&eventId=' + vm.eventId;
            return httpService.get(url).then(function (response) {
                console.log(response);
                if (response.data.success) {
                    vm.gridOptions.data = response.data.data.result;
                    vm.gridOptions.totalItems = response.data.data.totalCount;

                } else {
                    vm.errors = response.data.errors;
                }
            });
        }

        function updateBookingReference(model, oldValue, newValue) {
            httpService.post(api_event_updateBookingReferenceFlight, model).then(function (response) {
                if (response.data.success) {

                } else {
                    vm.errors = response.data.errors;
                }
            });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('EventHCPController', EventHCPController);
    EventHCPController.$inject = ['$rootScope', '$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', 'toaster', 'moment'];

    function EventHCPController($rootScope, $scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, toaster, moment) {

        var vm = this;
        vm.init = init;
        vm.model = vm.model || {};        

        function init() {
            getEvents();
        }

        function getEvents() {
            var currentClientDate = moment().format("DD/MM/YYYY");
            httpService.get(api_events_hcp.replace('{0}', formConfig.hcpUserId).replace('{1}', currentClientDate))
            .success(function (data) {
                vm.model.hcpEvents = data;
                angular.forEach(vm.model.hcpEvents, function (item) {
                    item.eventDay = moment.utc(item.eventDate).local().format("DD");
                    item.eventMonth = moment.utc(item.eventDate).local().format("MMM");
                });
        });
        }
    };
})();;
(function () {
    'use strict';

    window.app.controller('EventInviteAttendeeController', EventInviteAttendeeController);
    EventInviteAttendeeController.$inject = ['$rootScope', '$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', 'toaster', '$q'];

    function EventInviteAttendeeController($rootScope, $scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, toaster, $q) {
        var vm = this;
        vm.model = {};
        vm.init = init;
        vm.getAttendees = getAttendees;
        vm.onSelectAttendee = onSelectAttendee;
        vm.getAttendeeFilterValues = getAttendeeFilterValues;
        vm.onSelectFilterValue = onSelectFilterValue;
        vm.resetHcpList = resetHcpList;
        vm.removeInviteHCP = removeInviteHCP;
        vm.submitManageInviteHcp = submitManageInviteHcp;
        vm.changeHcpFilter = changeHcpFilter;
        vm.inviteEmail = inviteEmail;
        vm.model.listHCP = [];
        vm.errors = [];
        vm.listInviteHcpExist = [];
        vm.isShowSendEmail = false;
        function init() {
            initLookups();
            getEventDetail();
        }

         function getInviteHcp() {
             httpService.get(api_get_inviteHCp.replace('{eventId}', formConfig.eventId))
                 .success(function(response) {
                     console.log(response);
                     if (response != null) {
                         angular.forEach(response,
                             function(item) {
                                 vm.listInviteHcpExist.push(item.hcpId);
                             });
                     }
                 });
         }
         function getEventDetail() {
             if (formConfig.eventId > 0) {
                 httpService.get(api_get_event_detail.replace('{id}', formConfig.eventId))
                     .success(function (response) {
                         if (response != null) {
                             if (response.isPublish)
                                 vm.isShowSendEmail = true;
                         }
                     });
             }
         }

        function initLookups() {
                httpService.get(api_event_getEventType)
                        .success(function (response) {
                            angular.forEach(response,
                         function (item) {
                             if (item.type == formConfig.searchCriteriaHCP) {
                                 vm.searchCriteriaHCPs = item.eventValues;
                             }
                         });
                        });
        }
        function resetHcpList(form) {
            vm.model.listHCP = [];
            vm.listInviteHcpExist = [];
            getInviteHcp();
        }
        function clearAll() {
            vm.model.listHCP = [];
            vm.listInviteHcpExist = [];
            vm.model.searchFilter = 0;
            vm.model.name = '';
        }
        function removeInviteHCP(index, hcpIdToRemove) {
            vm.model.listHCP.splice(index, 1);

            var indexToRemove = -1;
            angular.forEach(vm.listInviteHcpExist, function (hcpId, idx) {
                if (hcpId == hcpIdToRemove) {
                    indexToRemove = idx;
                    return;
                }
            });
            if (indexToRemove >= 0) {
                vm.listInviteHcpExist.splice(indexToRemove, 1);
            }
        }
        function searchAttendees(value, search, type, exceptIds, pageSize, pageNo, isExact) {
            return httpService.get(api_event_InviteHcp_search
                    .replace('{0}', value)
                    .replace('{1}', search)
                    .replace('{2}', type)
                    .replace('{3}', exceptIds)
                    .replace('{pageSize}', pageSize)
                    .replace('{pageNo}', pageNo)
                    .replace('{isExact}', isExact),
                    { disable_loading: true })
                    .then(function (response) {
                        return response.data;
                    });
        }
        function getAttendees(value) {
            var attendees = [];
            var type = vm.model.searchFilter;
            var search = '';
            vm.temp = [];
            var exceptIds = vm.listInviteHcpExist.join(',');
            if (type > 0) {
                if (type > 0 && type <= 8) {
                    search = 'suburb';
                } else if (type == 9) {
                    search = 'profession';
                } else if (type == 10) {
                    search = 'targetclass';
                } else if (type == 11) {
                    search = 'name';
                }

                var pageSize = type == 11 ? 10 : 100;
                var pageNo = 1;
                var isExact = type == 11 ? 'false' : 'true';

                return searchAttendees(value, search, type, exceptIds, pageSize, pageNo, isExact).then(function (data) {
                    if (data && data.result) {
                        data.result.forEach(function (item) {
                            attendees.push(item);
                        });

                        var paginationCount = (data.totalCount / pageSize) + 1;
                        if (paginationCount > 1) {
                            var prom = [];
                            pageNo++;
                            while (pageNo <= paginationCount) {
                                prom.push(searchAttendees(value, search, type, exceptIds, pageSize, pageNo, isExact).then(function (data) {
                                    if (data && data.result) {
                                        data.result.forEach(function (item) {
                                            attendees.push(item);
                                        });
                                    }
                                }));
                                pageNo++;
                            }
                            return $q.all(prom).then(function () {
                                return attendees;
                            });
                        }
                    }
                });
            }
        }
        function addTolistInviteHcpExist(item) {
            var isInArr = false;
            angular.forEach(vm.listInviteHcpExist, function (itemId) {
                if (itemId == item.id) {
                    isInArr = true;
                    return;
                }
            });
            if (!isInArr) {
                vm.listInviteHcpExist.push(item.id);
            }
        }
        function addToAttendeeList(item) {
            var iscontaint = false;
            angular.forEach(vm.model.listHCP, function (itemContaint) {
                if (item.id == itemContaint.hcpId) {
                    iscontaint = true;
                    return;
                }
            });
            if (!iscontaint) {
                vm.model.listHCP.push({
                    id: 0,
                    eventId: formConfig.eventId,
                    hcpId: item.id,
                    profile: item.profile
                });
            }
        }
        function onSelectAttendee(item) {
            addTolistInviteHcpExist(item);
            addToAttendeeList(item);
            $timeout(function () {
                vm.model.name = '';
            }, 100);

        }
        function getAttendeeFilterValues(value) {
            var filterValues = [];
            var type = vm.model.searchFilter;
            vm.temp = [];
            var exceptIds = vm.listInviteHcpExist.join(',');
            if (type > 0) {
                return httpService.get(api_event_InviteHcp_searchFilterValues.replace('{value}', value).replace('{type}', type).replace('{exceptIds}', exceptIds), { disable_loading: true })
                    .then(function (response) {
                        if (response.data && response.data.result) {
                            filterValues = response.data.result;
                        }
                        return filterValues;
                    });
            }
        }
        function onSelectFilterValue(searchValue) {
            getAttendees(searchValue).then(function (result) {
                angular.forEach(result, function (hcp) {
                    addTolistInviteHcpExist(hcp);
                    addToAttendeeList(hcp);
                });
                $timeout(function () {
                    vm.model.name = '';
                }, 100);
            });
        }
        function submitManageInviteHcp(form) {
            httpService.post(api_add_event_inviteHCP.replace('{eventId}', formConfig.eventId), vm.model.listHCP)
                     .then(function (response) {
                         vm.errors = [];
                         vm.errors = response.data.errors;
                         if (response.data.errors.length > 0) {
                             modelStateErrorBuilder.build(vm.errors, vm.model.listHCP);
                             scrollToTop();
                             vm.model = {};
                         } else {
                             $rootScope.$emit('Event_Attendee_Invited');
                             $("#inviteAttendee").modal('hide');
                             clearAll();
                         }
                     });
        }
        function inviteEmail(form) {
            httpService.post(api_event_sendMail_manageInvite.replace('{id}', formConfig.eventId), vm.model.listHCP)
                     .then(function (response) {
                         vm.errors = [];
                         vm.errors = response.data.errors;
                         if (response.data.errors.length > 0) {
                             modelStateErrorBuilder.build(vm.errors, vm.model.inviteHCPDetail);
                             scrollToTop();
                         } else {
                             $rootScope.$emit('Event_Attendee_Invited');
                             $("#inviteAttendee").modal('hide');
                             clearAll();
                         }
                     });
        }
        function changeHcpFilter() {
            vm.model.name = '';
        }
        $("#inviteAttendee").on("shown.bs.modal", function () {
            resetHcpList();
        });
        // COMMON FUNCTIONS
        function addError(message) {
            var isExists = false;
            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }
            if (!isExists) vm.errors.push(message);
        }

        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }

        function isExist(array, id) {
            $.each(array, function (index, item) {
                if (item.id === id) {
                    return true;
                }
            });

            return false;
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('EventListController', EventListController);
    EventListController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService',
        'uiGridConstants', 'moment', 'utilitySvc', 'formConfig'];

    function EventListController($rootScope, $scope, $window, filterFilter, httpService,
        uiGridConstants, moment, utilitySvc, formConfig) {
        var vm = this;
        vm.errors = [];
        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: 'startDate',
            keyword: '',
            filterType: formConfig.currentEventFilter
        };
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getDataGird);
        vm.gridOptions.columnDefs = [
            { name: 'startDate', displayName: 'Start date', maxWidth: 100 },
            { name: 'name', displayName: 'Event name' },
            { name: 'eventSalesRep', displayName: 'Sale reps' },         
            { name: 'stateName', displayName: 'State', maxWidth: 80 },
            { name: 'totalRegistered', displayName: 'Total registered', maxWidth: 100 },
            { name: 'publishedDate', displayName: 'Published', maxWidth: 100 },
            {
                field: 'id',
                enableSorting: false,
                displayName: '',
                maxWidth: 100,
                enableCellEdit: false,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center""><a href="/admin/events/event/{{row.entity.id}}/manage">edit</a></div>'
            }
        ];

        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getDataGird();
            }
        });

        vm.changeFilterType = changeFilterType;

        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.gridOptions);
        }

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            getDataGird();
        };

        function changeFilterType() {
            getDataGird();
        }

        function getDataGird() {
            vm.errors = [];
            var browserTimeZone = moment.tz.guess();
            var browserDate = moment().format('DD/MM/YYYY');
            var url = api_event_searchEvent;
            url += '?browserDate=' + browserDate;
            url += '&pageSize=' + vm.searchOption.pageSize;
            url += '&pageNo=' + vm.searchOption.pageNumber;
            url += '&sortFields=' + vm.searchOption.sort;
            url += '&keyword=' + vm.searchOption.keyword;
            url += '&filterType=' + vm.searchOption.filterType;
            url += '&browserTimeZone=' + browserTimeZone;
            
            return httpService.get(url).then(function (response) {
                if (response.data.success) {
                    console.log(response.data.data.result);
                    vm.gridOptions.data = response.data.data.result;
                    vm.gridOptions.totalItems = response.data.data.totalCount;

                    angular.forEach(vm.gridOptions.data,
                       function (item) {
                           if (item.startDate && item.startDate != null) {
                               item.startDate = moment.utc(item.startDate).local().format("DD/MM/YYYY");
                           }
                           if (item.publishedDate && item.publishedDate != null) {
                               item.publishedDate = moment.utc(item.publishedDate).local().format("DD/MM/YYYY");
                           }
                       });

                } else {
                    vm.errors = response.data.errors;
                }
            });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('EventRegisterAttendeeController', EventRegisterAttendeeController);
    EventRegisterAttendeeController.$inject = ['$scope', '$window', 'utilitySvc', 'httpService',
        'formConfig', '$timeout'];

    function EventRegisterAttendeeController($scope, $window, utilitySvc, httpService,
        formConfig, $timeout) {
        var vm = this;
        vm.init = init;
        vm.eventId = formConfig.eventId;
        vm.contactDetailsFormSubmit = contactDetailsFormSubmit;
        vm.flightsFormSubmit = flightsFormSubmit;
        vm.accommodationFormSubmit = accommodationFormSubmit;
        vm.specialRequestsFormSubmit = specialRequestsFormSubmit;
        vm.cancelRegistration = cancelRegistration;
        vm.isShowOtherFlight = true;
        vm.clickFlight = clickFlight;
        vm.clickAccommodation = clickAccommodation;
        vm.clearAccomodations = clearAccomodations;
        vm.isHasAnyFlightSelected = isHasAnyFlightSelected;
        vm.checkFlightRequestText = checkFlightRequestText;
        vm.otherFlightRequestHasValue = false;
        
        vm.errors = [];
        vm.messages = [];
        vm.model = {
            contactDetails: {
                hcp: {mode:'search'}
            },
            flights: {},
            accommodations: { enabled: false },
            specialRequests: {}
        };
        vm.event = {};
        function init() {
            initLookups();
            getEventDetail();
        }

        function getHcpDetail() {
            httpService.get(api_hcp_getHcpDetailsCurrentUser).then(function (response) {
                if (response.data.success) {
                    if (response.data.data != null) {
                        vm.model.privacy.title = response.data.data.profile.title;
                        vm.model.privacy.firstName = response.data.data.profile.firstName;
                        vm.model.privacy.lastName = response.data.data.profile.lastName;
                    }
                } else {
                    response.data.errors.forEach(function (error) {
                        addError(error.message);
                    });
                }
            });
        }

        function getLastEventHcp() {
            var url = api_event_getLastEventHcp;
            if (vm.model.contactDetails.hcp) {
                url += '?userId=' + vm.model.contactDetails.hcp.userId;
                httpService.get(url).then(function (response) {
                    if (response.data.success) {
                        if (response.data.data != null) {
                            vm.model.flights.frequentName = response.data.data.frequentFlyerClubName;
                            vm.model.flights.frequentNumber = response.data.data.frequentFlyerMembershipNumber;
                        }
                    } else {
                        response.data.errors.forEach(function (error) {
                            addError(error.message);
                        });
                    }
                });
            }
        }

        function getEventDetail() {
            httpService.get(api_event_getDetail.replace('{eventId}', vm.eventId)).then(function (response) {
                console.log(response);
                if (response.data.success) {
                    vm.eventId = response.data.data.id;
                    vm.event = response.data.data;
                    vm.event.flights = $.grep(vm.event.flights, function (value) {
                        return value.isDeleted === false;
                    });
                    vm.event.accommodations = $.grep(vm.event.accommodations, function (value) {
                        return value.isDeleted === false;
                    });
                    vm.event.venues = $.grep(vm.event.venues, function (value) {
                        return value.isDeleted === false;
                    });

                } else {
                    response.data.errors.forEach(function (error) {
                        addError(error.message);
                    });
                }
            });
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                vm.hcpProfessions = data.Hcp_Profession;
                vm.titles = data.Title;
                vm.states = data.State;
            });
        }

        function cancelRegistration() {
            window.location.href = formConfig.manageAttendeeUrl;
        }

        function contactDetailsFormSubmit(event, form) {
            if (isContactDetailsFormValid(form)) {
                nextTab();
            } else {
                scrollToTop();
            }
        }

        function flightsFormSubmit(event, form) {
            nextTab();
        }

        function accommodationFormSubmit(event, form) {
            nextTab();
        }

        function specialRequestsFormSubmit(event, form) {
            if (isSpecialRequestsFormValid(form)) {
                var registerEventHcpViewModel = {
                    id: 0,
                    eventId: vm.eventId,
                    hcpId: vm.model.contactDetails.hcp.id,
                    title: vm.model.contactDetails.hcp.profile.title,
                    firstName: vm.model.contactDetails.hcp.profile.firstName,
                    lastName: vm.model.contactDetails.hcp.profile.lastName,
                    institution: vm.model.contactDetails.hcp.institution,
                    mobile: vm.model.contactDetails.mobile,
                    frequentName: vm.model.flights.frequentName,
                    frequentNumber: vm.model.flights.frequentNumber,
                    isAirportToHotel: vm.model.flights.isAirportToHotel,
                    isHotelToAirport: vm.model.flights.isHotelToAirport,
                    otherFlightRequest_DepartingFrom: vm.model.flights.otherFlightRequest_DepartingFrom,
                    otherFlightRequest_ReturningTo: vm.model.flights.otherFlightRequest_ReturningTo,
                    specialMealRequirement: vm.model.specialRequests.specialMealRequirement,
                    medicalConditions: vm.model.specialRequests.medicalConditions,
                    flights: [],
                    accommodations: []
                };

                if (!vm.isShowOtherFlight) {
                    $.each(vm.event.flights, function (index, item) {
                        if (item.isSelected) {
                            registerEventHcpViewModel.flights.push(item);
                        }
                    });
                }

                if (vm.model.accommodations.enabled) {
                    $.each(vm.event.accommodations, function (index, item) {
                        if (item.isSelected) {
                            registerEventHcpViewModel.accommodations.push(item);
                        }
                    });
                }

                httpService.post(api_event_registerEventHcp, registerEventHcpViewModel).then(function (response) {
                    console.log(response);
                    if (response.data.success) {
                        window.location.href = formConfig.manageAttendeeUrl;
                    } else {
                        response.data.errors.forEach(function (error) {
                            addError(error.message);
                        });
                    }
                });

            } else {
                scrollToTop();
            }
        }

        function clickFlight(item) {
            var prevSelectedElement = null;
            $.each(vm.event.flights, function (index, element) {
                if (element.isSelected === true) {
                    prevSelectedElement = element;
                    if (element.id !== item.id) {
                        element.isSelected = false;
                    }
                }
            });

            if (item.isSelected == undefined) item.isSelected = false;

            item.isSelected = !item.isSelected;
            checkVisibleOtherFlight();

            if ((prevSelectedElement == null && item.isSelected) || (prevSelectedElement != null && !item.isSelected)) {
                resetGroundTransfer();
            }
        }

        function checkFlightRequestText() {
            vm.otherFlightRequestHasValue = false;
            if (vm.model.flights.otherFlightRequest_DepartingFrom && vm.model.flights.otherFlightRequest_DepartingFrom.trim() != ''
            || vm.model.flights.otherFlightRequest_ReturningTo && vm.model.flights.otherFlightRequest_ReturningTo.trim() != '') {
                vm.otherFlightRequestHasValue = true;
            }

            if (!vm.otherFlightRequestHasValue) {
                resetGroundTransfer();
            }
        }

        function checkVisibleOtherFlight() {
            console.log(isHasAnyFlightSelected());
            if (isHasAnyFlightSelected()) {
                vm.isShowOtherFlight = false;
                vm.model.flights.otherFlightRequest_DepartingFrom = undefined;
                vm.model.flights.otherFlightRequest_ReturningTo = undefined;
                vm.otherFlightRequestHasValue = false;
            } else {
                vm.isShowOtherFlight = true;
            }
        }

        function resetGroundTransfer() {
            vm.model.flights.isAirportToHotel = undefined;
            vm.model.flights.isHotelToAirport = undefined;
        }

        function isHasAnyFlightSelected() {
            var result = false;
            $.each(vm.event.flights, function (index, item) {
                if (item.isSelected != undefined && item.isSelected) {
                    result = true;
                    return result;
                }
            });

            return result;
        }

        function clickAccommodation(item) {
            if (vm.model.accommodations.enabled) {
                $.each(vm.event.accommodations, function (index, element) {
                    if (element.isSelected === true && element.id !== item.id) {
                        element.isSelected = false;
                    }
                });
                if (item.isSelected == undefined) item.isSelected = false;
                item.isSelected = !item.isSelected;
            }
        }

        function clearAccomodations() {
            if (!vm.model.accommodations.enabled) {
                $.each(vm.event.accommodations, function (index, element) {
                    element.isSelected = false;
                });
            }
        }

        function isContactDetailsFormValid(form) {
            vm.errors = [];
            $($('#LastName').parent()).removeClass('has-error');
            var isValid = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                isValid = false;
            }

            if (!vm.model.contactDetails.hcp
                || vm.model.contactDetails.hcp.id == undefined
                || vm.model.contactDetails.hcp.id === 0) {
                addError("All fields highlighted in red are mandatory");
                $($('#LastName').parent()).addClass("has-error");
                isValid = false;
            }

            return isValid;
        }

        function isSpecialRequestsFormValid(form) {
            vm.errors = [];
            var isValid = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                isValid = false;
            }

            return isValid;
        }

        //////////////////////// SEACH ATTENDEE //////////////////////////
        vm.getHcp = getHcp;
        vm.onSelectHcp = onSelectHcp;
        vm.clearHcp = clearHcp;
        vm.isHcpInputsDisabled = true;

        function getItems(url) {
            var items = [];

            return httpService.get(url, { disable_loading: true })
                .then(function (response) {
                    if (response.data && response.data.result) {
                        response.data.result.forEach(function (item) {
                            items.push(item);
                        });
                    }
                    return items;
                });
        }

        function getHcp(value) {
            var url = api_event_searchAttendee;
            url += '?keyword=' + value;
            url += '&eventId=' + vm.eventId;
            return getItems(url);
        }

        function onSelectHcp(item, form) {
            console.log(item);
            vm.model.contactDetails.hcp = item;
            vm.model.contactDetails.hcp.mode = 'select';
            vm.isHcpInputsDisabled = true;
            $timeout(function () {
                $scope.$apply();
                getLastEventHcp();
                $($('#LastName').parent()).removeClass('has-error');
            }, 0);
        }

        function clearHcp() {
            vm.model.contactDetails.hcp = {mode:'search'};
            $timeout(function () {
                
            });
        }
        //////////////////////// SEACH ATTENDEE //////////////////////////

        // TAB FUNCTIONS
        vm.activeTabIndex = 1;
        vm.previousTab = previousTab;

        function nextTab() {
            if (vm.activeTabIndex < 6) {
                vm.errors = [];
                vm.activeTabIndex = vm.activeTabIndex + 1;
            }
        }

        function previousTab() {
            if (vm.activeTabIndex > 1) {
                vm.errors = [];
                vm.activeTabIndex = vm.activeTabIndex - 1;
            }
        }

        // COMMON FUNCTIONS
        function addError(message) {
            var isExists = false;
            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }
            if (!isExists) vm.errors.push(message);
        }

        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }

        function onBlurNumberOnly($event) {
            var val = $($event.target).val();
            showErrorNumberOnly($event.target, val);
        }

        function onBlurCharacterOnly($event) {
            var val = $($event.target).val();
            showErrorCharacterOnly($event.target, val);
        }

        function showErrorNumberOnly(obj, val) {
            if (isNaN(val)) {
                $($(obj).parent()).addClass("has-error");
            } else {
                $($(obj).parent()).removeClass("has-error");
            }
        }

        function showErrorCharacterOnly(obj, val) {
            var matches = val.match(/\d+/g);
            if (matches != null) {
                $($(obj).parent()).addClass("has-error");
            } else {
                $($(obj).parent()).removeClass("has-error");
            }
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('MyEventsController', MyEventsController);
    MyEventsController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService',
        'uiGridConstants', 'moment', 'utilitySvc'];

    function MyEventsController($rootScope, $scope, $window, filterFilter, httpService,
        uiGridConstants, moment, utilitySvc) {
        var vm = this;
        vm.filterOptionList = [];
        vm.filterOption = 0;
        vm.totalAttended = 0;
        vm.totalUpcoming = 0;
        vm.totalPending = 0;
        vm.filterMyEventsGrid = filterMyEventsGrid;

        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: 'eventName',
            filterOption: 1,
            keyword: ''
        };
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getMyEvents);
        vm.gridOptions.columnDefs = [
            //{ name: 'eventName', displayName: 'Event' },
            {
                name: 'eventName',
                displayName: 'Event',
                cellTemplate: '<div class="ui-grid-cell-contents"><a href="details/{{row.entity.eventHcpId}}">{{row.entity.eventName}}</a></div>'
            },
            { name: 'location', displayName: 'Location' },
            { name: 'eventDate', displayName: 'Event date' },
            { name: 'status', displayName: 'Status' }
        ];

        // This is to watch the filter value changed, and call the getUsers again!
        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getMyEvents();
            }
        });

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            getMyEventFilterOptions();
            getMyEvents();
        };

        function filterMyEventsGrid(selectedOption) {
            vm.searchOption.filterOption = selectedOption;
            getMyEvents();
        }

        function getMyEventFilterOptions() {
            var url = api_myEvent_getMyEventTypes;

            return httpService.get(url).then(function (response) {
                if (response.data.success) {
                    vm.filterOptionList = response.data.data;
                    vm.filterOption = 1;
                } else {
                    vm.errors = response.data.errors;
                }
            });
        }

        function getMyEvents() {
            var browserDate = moment().format('DD/MM/YYYY');
            var url = api_myEvent_getMyEvents;
            url = url.replace('{pageSize}', vm.searchOption.pageSize);
            url = url.replace('{pageNo}', vm.searchOption.pageNumber);
            url = url.replace('{sort}', vm.searchOption.sort);
            url = url.replace('{filterOption}', vm.searchOption.filterOption);
            url = url.replace('{keyword?}', vm.searchOption.keyword);
            url = url.replace('{0}', browserDate);

            return httpService.get(url).then(function (response) {
                if (response.data.success) {
                    vm.gridOptions.data = response.data.data.result;
                    vm.gridOptions.totalItems = response.data.data.totalCount;
                    vm.totalAttended = response.data.totalAttended;
                    vm.totalUpcoming = response.data.totalUpcoming;
                    vm.totalPending = response.data.totalPending;
                } else {
                    vm.errors = response.data.errors;
                }
            });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('CDEListController', CDEListController);
    CDEListController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService',
        'uiGridConstants', 'moment', 'utilitySvc', 'formConfig'];

    function CDEListController($rootScope, $scope, $window, filterFilter, httpService,
        uiGridConstants, moment, utilitySvc, formConfig) {
        var vm = this;

        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: 'fullName',
            filterState: ''
        };
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getCDEs, 'fullName');
        vm.gridOptions.columnDefs = [
            { name: 'fullName', displayName: 'CDE', maxWidth: 250},
            {
                name: 'mobile',
                maxWidth: 450,
                enableSorting: false,
                displayName: 'Contact',
                enableCellEdit: false,
                cellTemplate: '<div class="ui-grid-cell-contents text-center"><span ng-bind="row.entity.mobile"></span><br ng-if="row.entity.mobile"/><span ng-if="!row.entity.mobile" ng-bind="row.entity.phone"></span><br ng-if="!row.entity.mobile && row.entity.phone"/><span ng-bind="row.entity.email"></span></div>'
            },
            {
                name: 'areas',                
                enableSorting: false,
                displayName: 'Areas covered',
                enableCellEdit: false,
                cellTemplate: '<div class="ui-grid-cell-contents"><span ng-repeat="item in row.entity.areas track by item.id">{{item.value}}<span ng-if="!$last">, </span></span></div>'
            }
            //{
            //    name: 'languages',
            //    maxWidth: 200,
            //    enableSorting: false,
            //    displayName: 'Other languages spoken',
            //    enableCellEdit: false,
            //    cellTemplate: '<div class="ui-grid-cell-contents text-center"><span ng-repeat="item in row.entity.languages track by item.id">{{item.value}}<span ng-if="!$last">, </span></span></div>'
            //},
            //{
            //    name: 'willingToTravel',
            //    maxWidth: 100,
            //    enableSorting: false,
            //    displayName: 'Prepared to travel',
            //    enableCellEdit: false,
            //    cellTemplate: '<div class="ui-grid-cell-contents text-center"><span ng-if="row.entity.willingToTravel" class="glyphicon glyphicon-ok"></span><span ng-if="!row.entity.willingToTravel" class="glyphicon glyphicon-remove"></span></div>'
            //}
        ];

        // This is to watch the filter value changed, and call the getUsers again!
        $scope.$watch('vm.filterState', function (newValue, oldValue) {
            vm.searchOption.filterState = newValue;
            getCDEs();
        });

        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.gridOptions);
        }

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            //getCDEs();
            initLookups();
        };

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                vm.states = data.State;
            });
        }

        function getCDEs() {
            var url = api_cde_search_byState;
            url = url.replace('{pageSize}', vm.searchOption.pageSize);
            url = url.replace('{pageNo}', vm.searchOption.pageNumber);
            url = url.replace('{sort}', vm.searchOption.sort);
            url = url.replace('{filterState}', vm.searchOption.filterState ? vm.searchOption.filterState : '');

            return httpService.get(url).then(function (response) {
                if (response.data) {
                    vm.gridOptions.data = response.data.result;
                    vm.gridOptions.totalItems = response.data.totalCount;
                    angular.forEach(vm.gridOptions.data,
                        function (resultItem) {
                            if (resultItem.registeredOn && resultItem.registeredOn != null) {
                                resultItem.registeredOn = moment(resultItem.registeredOn).format("DD/MM/YYYY");
                            }
                        });
                }
            });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('HCPEditController', HCPEditController);
    HCPEditController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout'];

    function HCPEditController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout) {
        var vm = this;
        vm.errors = [];
        vm.submit = submit;
        vm.model = vm.model || {};
        vm.getInstitutions = getInstitutions;
        vm.onSelectInstitution = onSelectInstitution;
        vm.onNewInstitution = onNewInstitution;
        vm.onClearInstitution = onClearInstitution;
        vm.institutionId = -1;
        vm.addAccreditations = addAccreditations;
        vm.deleteAccreditations = deleteAccreditations;
        vm.model.listAccreditation = [];
        vm.init = init;
        vm.IsShowNewInstitution = true;
        vm.IsShowClearInstitution = true;
        vm.otherProfession = formConfig.otherProfession;
        vm.changeAccreditationType = changeAccreditationType;
       
        vm.viewOnly = formConfig.viewOnly;
        vm.isHcpCDE = false;
        vm.onChangeEmail = onChangeEmail;

        vm.removeAreas = removeAreas;
        vm.removeLanguages = removeLanguages;
        vm.getAreaType = getAreaType;
        vm.getLanguageType = getLanguageType;
        vm.onSelectLanguage = onSelectLanguage;
        vm.onSelectArea = onSelectArea;
        vm.onAddArea = onAddArea;
        vm.onAddLanguage = onAddLanguage;
        vm.areasCovered = [];
        vm.languagesSpoken = [];
        vm.currentUserStatus = 0;
        vm.deleteUser = deleteUser;
        vm.getCancelUrl = getCancelUrl;

        $scope.$watch('vm.model.status', function (newValue, oldValue) {
            if (vm.currentUserStatus == formConfig.userStatusApproved && newValue == formConfig.userStatusUnverified) {
                addError('The user status can not changed from approved to unverified');
                vm.model.status = oldValue;
            }

            if (vm.currentUserStatus == formConfig.userStatusDeclined && newValue == formConfig.userStatusUnverified) {
                addError('The user status can not changed from declined to unverified');
                vm.model.status = oldValue;
            }

            if (vm.currentUserStatus == formConfig.userStatusArchived && newValue == formConfig.userStatusUnverified) {
                addError('The user status can not changed from archived to unverified');
                vm.model.status = oldValue;
            }

        });

        function getCancelUrl() {
            if (document.referrer === undefined || document.referrer === null || document.referrer.trim() === '') {
                return formConfig.userListUrl;
            }
            return document.referrer;
        }

        function init() {
           
            initLookups();
            loadRoles();
            loadHcp();
        }

        function changeAccreditationType(item) {
            vm.errors = [];
            var count = 0;
            $.each(vm.model.listAccreditation,
                function (index, element) {
                    if (element.type === item.type) {
                        count++;
                    }
                });

            if (count > 1) {
                addError('Duplicate Accreditation type');
                item.type = 0;
                scrollToTop();
            }
        }

        function loadHcp() {
            httpService.get(api_user_getHcp.replace('{id}', formConfig.hcpId))
                .then(function (response) {
                    console.log(response);
                    if (response.status == 200) {
                        vm.model = response.data;
                        vm.currentUserStatus = vm.model.status;
                        // Convert utc server time to local brower time
                        if (vm.model.registerDate != null)
                        {
                            vm.model.registerDate += 'Z';
                        }
                        if (vm.model.lastLoggedIn != null) {
                            vm.model.lastLoggedIn += 'Z';
                        }
                        if (vm.model.hcpDiabetesProgramRegisterDate != null) {
                            vm.model.hcpDiabetesProgramRegisterDate += 'Z';
                        }

                        if (vm.model.address != null)
                        {
                            vm.model.institution.name = null;
                            vm.model.institution.id = null;
                            vm.model.institution.address = vm.model.address;
                        }

                        vm.model.isInstitutionFormDisabled = vm.model.hcpDiabetesProgramId > 0 ? true : false;
                        vm.institutionId = -1;
                        if (vm.model.institution == null) {
                            vm.model.institution = {};
                            vm.isFormAddressDisabled = true;
                        }
                       
                        if (vm.model.institution.id > 0) {
                            vm.model.isInstitutionFormDisabled = true;
                            vm.model.isInstitutionAddressFormDisabled = true;
                            vm.model.isInstitutionSuburbStatePostCodeFormDisabled = true;
                            vm.institutionId = vm.model.institution.id;

                            vm.isInstitutionFormDisabled = true;
                            vm.isFormAddressDisabled = true;
                            vm.isStateSuburbPostCodeInputsDisabled = true;
                            vm.model.existingInstitutionId = vm.model.institution.id;
                        }
                        vm.model.institution.mode = 'select';

                        // if has CDE
                        if (vm.model.cde != null) {
                            vm.isHcpCDE = true;
                            $.each(vm.model.cde.listLanguage,function(index, item) {
                                vm.languagesSpoken.push({ value: item });
                            });
                            $.each(vm.model.cde.listArea, function (index, item) {
                                vm.areasCovered.push({ value: item });
                            });
                        }
                    }
                }, function (error) {
                    if (jQuery.type(error.data) === 'string') {
                        addError(error.data);
                    } else {
                        addError(error.data.message);
                    }
                    scrollToTop();
                    vm.viewOnly = true;
                });
        }

        function loadRoles() {
            var url = api_getAllRoles;
            httpService.get(url)
                .success(function (response) {
                    vm.roles = response.data;
                });
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
                .success(function (data) {
                    vm.titles = data.Title;
                    vm.status = data.User_Status;
                    vm.states = data.State;
                    vm.professions = data.Hcp_Profession;
                    vm.accreditations = data.HcpAccreditation_Type;
                    vm.targets = data.Hcp_TargetClass;
                });
        }

        function addAccreditations() {
            vm.model.listAccreditation.push({
                type: 0,
                membershipNumber: ""
            });
        }

        function deleteAccreditations(index) {
            vm.model.listAccreditation.splice(index, 1);
        }


        function getInstitutions(value) {
            var institutions = [];            
            return httpService.get(api_institution_search.replace('{0}', value).replace('{1}', ''), { disable_loading: true })
                .then(function (response) {

                    response.data.forEach(function (item) {
                        institutions.push(item);
                    });

                    angular.forEach(vm.model.institutions, function (item, idx) {

                        if (idx != vm.model.institutionSelectedIndex) {
                            angular.forEach(institutions, function (item2, idx2) {
                                if (item.name == item2.name)
                                    institutions.splice(idx2, 1);
                            });
                        }
                    });
                    console.log(institutions);
                    return institutions;
                });
        }

        vm.isStateSuburbPostCodeInputsDisabled = false;
        vm.isFormAddressDisabled = true;

        vm.disableAddressInputs = function () {
            return vm.isFormAddressDisabled;
        }

        vm.isStateSuburbPostCodeDisabled = function () {
            return vm.isStateSuburbPostCodeInputsDisabled;
        }

        vm.requireInputs = function () {
            return !vm.isFormAddressDisabled;
        }

        function onSelectInstitution(item) {
            vm.model.institution = item;
            vm.institutionId = item.id;
            vm.model.institution.mode = 'select';
            vm.model.isInstitutionFormDisabled = true;            
            vm.model.isInstitutionAddressFormDisabled = true;
            vm.model.isInstitutionSuburbStatePostCodeFormDisabled = true;
            vm.IsShowClearInstitution = true;
            vm.IsShowNewInstitution = true;

            vm.isInstitutionNameRequired = false;
            vm.isInstitutionFormDisabled = true;
            vm.isFormAddressDisabled = true;
            vm.isStateSuburbPostCodeInputsDisabled = true;
        }

        function onNewInstitution() {
            vm.institutionId = 0;
            vm.model.institution = {}
            vm.model.institution.mode = 'add';
            vm.model.isInstitutionFormDisabled = false;            
            vm.model.isInstitutionAddressFormDisabled = false;
            vm.model.isInstitutionSuburbStatePostCodeFormDisabled = false;

            vm.isInstitutionNameRequired = true;
            vm.isInstitutionFormDisabled = false;
            vm.isFormAddressDisabled = false;
            vm.isStateSuburbPostCodeInputsDisabled = false;
            vm.insIsSearchDisabled = true;
        }

        function onClearInstitution(institution) {
            vm.institutionId = -1;
            vm.model.isInstitutionFormDisabled = vm.model.hcpDiabetesProgramId > 0 ? true : false;            
            vm.model.isInstitutionAddressFormDisabled = true;
            vm.model.isInstitutionSuburbStatePostCodeFormDisabled = false;
            
            vm.isInstitutionNameRequired = false;
            vm.isInstitutionFormDisabled = false;
            vm.isFormAddressDisabled = true;
            vm.isStateSuburbPostCodeInputsDisabled = false;
            vm.insIsSearchDisabled = false;

            if (institution) {
                vm.model.institution = {
                    name: undefined,
                    address: {
                    },
                    mode: 'add'
                };
            }
        }

        function submit(form) {
            console.log(vm.model);
            if (isFormAddHcpUserValid(form)) {
                if (vm.isHcpCDE) {
                    vm.model.cde.listLanguage = [];
                    vm.model.cde.listArea = [];
                    $.each(vm.languagesSpoken, function (index, item) {
                        vm.model.cde.listLanguage.push(item.value);
                    });
                    $.each(vm.areasCovered, function (index, item) {
                        vm.model.cde.listArea.push(item.value);
                    });
                }

                vm.model.listAccreditation = $.grep(vm.model.listAccreditation, function (value) {
                    return value.type != null && value.type !== 0;
                });

                vm.model.institution.id = vm.institutionId;
                if (vm.model.institution.id < 0
                    && vm.model.institution.name != null
                    && vm.model.institution.name != "")
                {
                    vm.model.institution.id = 0;
                }

                httpService.post(api_user_editHcp, vm.model)
                    .then(function (response) {
                        console.log(response);
                        if (response.data.success) {
                            redirectUserList();
                        } else {
                            $.each(response.data.errors, function(index, error) {
                                addError(error.message);
                            });
                            scrollToTop();
                        }
                    },function(error) {
                        if (jQuery.type(error.data) === 'string') {
                            addError(error.data);
                        } else {
                            addError(error.data.message);
                        }
                        scrollToTop();
                    });

            } else {
                scrollToTop();
            }
        }

        function isFormAddHcpUserValid(form) {
            vm.errors = [];
            var isValid = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");;
                isValid = false;
            }

            if (vm.model.email != "" && !isEmail(vm.model.email)) {
                addError("Please specify a valid Hcp email");
                isValid = false;
                showHighlightError('#email');
            } else {
                removeHighlightError('#email');
            }
            
            if (!isAddressValid() || !isOtherValid()) {
                isValid = false;
            }

            if (!isProviderNumberValid()) {
                showHighlightError('#providerNumber');
                isValid = false;
            } else {
                removeHighlightError('#providerNumber');
            }

            if (!isAhpraNumberValid()) {
                showHighlightError('#ahpraNumber');
                isValid = false;
            } else {
                removeHighlightError('#ahpraNumber');
            }

            if (vm.isHcpCDE) {
                if (vm.model.cde.contactEmail && vm.model.cde.contactEmail.length > 0 && !isEmail(vm.model.cde.contactEmail)) {
                    addError("Please specify a valid Contact email");
                    isValid = false;
                    showHighlightError('#contactEmail');
                } else {
                    removeHighlightError('#contactEmail');
                }

                if (form.cdeMobile.$error.phone) {
                    addError("Please specify a valid mobile number");
                    isValid = false;
                }

                if (form.cdePhone.$error.phone) {
                    addError("Please specify a valid phone number");
                    isValid = false;
                }

            } else {
                removeHighlightError('#contactEmail');
            }

            if (vm.model.isSendProgramSMS || vm.model.isSendEventSMS) {
                if (vm.model.mobile == undefined || vm.model.mobile == null || vm.model.mobile == '') {
                    addError("Mobile number is required when SMS notification is selected");
                    isValid = false;
                    showHighlightError('#mobile');
                } else {
                    removeHighlightError('#mobile');
                }
            } else {
                removeHighlightError('#mobile');
            }

            if (form.mobile.$error.phone) {
                addError("Please specify a valid mobile number");
                isValid = false;
            }

            if (form.phone.$error.phone) {
                addError("Please specify a valid phone number");
                isValid = false;
            }

            if (form.Fax.$error.phone) {
                addError("Please specify a valid fax number");
                isValid = false;
            }

            return isValid;
        }

        function deleteUser() {
            if (confirm("Are you sure want to delete this user?")) {
                httpService.post(api_delete_User, vm.model.userId)
                .then(function (response) {
                    if (response.data.success) {
                        redirectUserList();
                    } else {
                        response.data.errors.forEach(function (error) {
                            addError(error.message);
                        });
                    }
                });
            }
        }


        //////////////////////// AREA AND LANGUAGE //////////////////////////

        vm.isAddAreaButtonDisabled = true;
        vm.isAddLanguageButtonDisabled = true;

        vm.isAreaFieldDisabled = false;
        vm.isLanguageFieldDisabled = false;

        function getItems(url) {
            var items = [];

            return httpService.get(url, { disable_loading: true })
                .then(function (response) {
                    response.data.forEach(function (item) {
                        items.push(item);
                    });
                    return items;
                });
        }

        function getAreaType(value) {
            return getObjectType(value, formConfig.areaTypeId);
        }

        function getLanguageType(value) {
            return getObjectType(value, formConfig.languageTypeId);
        }

        function getObjectType(value, type) {
            var url = api_propertyvalues_search.replace('{propertyId:int?}', type).replace('{keyword?}', value);
            return getItems(url);
        }

        function onSelectLanguage(item) {
            vm.selectedLanguage = item;
            vm.isAddLanguageButtonDisabled = false;
            vm.isLanguageFieldDisabled = true;
        }

        function onSelectArea(item) {
            vm.selectedArea = item;
            vm.isAddAreaButtonDisabled = false;
            vm.isAreaFieldDisabled = true;
        }

        function onAddArea() {
            var item = vm.selectedArea;
            vm.isAddAreaButtonDisabled = true;
            vm.isAreaFieldDisabled = false;
            console.log(item);
            if (item.id == undefined) {
                vm.areasCovered.push({
                    propertyValueId: 0,
                    value: item.value,
                    propertyId: formConfig.areaTypeId
                });
            }
            else {
                if (!isExistProperty(item, vm.areasCovered)) {
                    vm.areasCovered.push({
                        propertyValueId: item.id,
                        value: item.value,
                        propertyId: formConfig.areaTypeId
                    });
                }
            }

            vm.selectedArea = null;
        }

        function isExistProperty(item, array) {
            var result = false;
            $.each(array, function (index, element) {
                if (item.value === element.value) {
                    result = true;
                }
            });
            return result;
        }

        function onAddLanguage() {
            var item = vm.selectedLanguage;
            vm.isAddLanguageButtonDisabled = true;
            vm.isLanguageFieldDisabled = false;
            console.log(item);
            if (item.id == undefined) {
                vm.languagesSpoken.push({
                    propertyValueId: 0,
                    value: item.value,
                    propertyId: formConfig.languageTypeId
                });
            }
            else {
                if (!isExistProperty(item, vm.languagesSpoken)) {
                    vm.languagesSpoken.push({
                        propertyValueId: item.id,
                        value: item.value,
                        propertyId: formConfig.languageTypeId
                    });
                }
            }

            vm.selectedLanguage = null;
        }

        function removeAreas(index) {
            if (vm.viewOnly) return false;

            if (vm.areasCovered != null) {
                vm.areasCovered.splice(index, 1);
            }
            console.log(vm.areasCovered);
        }

        function removeLanguages(index) {
            if (vm.viewOnly) return false;
            
            if (vm.languagesSpoken != null) {
                vm.languagesSpoken.splice(index, 1);
            }
        }
        //////////////////////// AREA AND LANGUAGE //////////////////////////

        // COMMON FUNCTIONS
        function isAddressValid() {
            if (vm.model.institution == undefined || vm.model.institution.address == undefined) {
                return false;
            }
            if ((vm.model.institution.address.addrLine1 == '' || vm.model.institution.address.addrLine1 == undefined) && vm.model.institution.name != '' && vm.model.institution.name != undefined) {
                addError("Address line 1 is required if the primary place of work is provided");
                return false;
            }
            return true;
        }

        function isOtherValid() {
            var profession = vm.model.profession;
            if (profession == formConfig.otherProfession && (vm.model.otherProfession == '' || vm.model.otherProfession == undefined)) {
                addError("Other value must be provided when 'other' profession is selected");
                return false;
            }
            return true;
        }

        function isAhpraNumberValid() {
            var ahpraNumber = vm.model.ahpraNumber;
            var profession = vm.model.profession;
            var regexAhpraNumberFormat = /^[a-zA-Z]{3,}\d{10}$/;
            var isValid = true;
            if (ahpraNumber != undefined && ahpraNumber != null && ahpraNumber.length > 0) {
                if (!regexAhpraNumberFormat.test(ahpraNumber)) {
                    addError("AHPRA number should start with three letters and ends with 10 digits");
                    isValid = false;
                }
                //general physician or specialist or general practioner
                if (profession == 2 || profession == 8 || profession == 3) {
                    if (ahpraNumber.substr(0, 3).toUpperCase() != "MED") {
                        addError("AHPRA number should start with MED");
                        isValid = false;
                    }
                }
                    //nurse practioner or registered nurse
                else if (profession == 4 || profession == 6) {
                    if (ahpraNumber.substr(0, 3).toUpperCase() != "NMW") {
                        addError("AHPRA number should start with NMW");
                        isValid = false;
                    }
                }
                    //pharmacist
                else if (profession == 5) {
                    if (ahpraNumber.substr(0, 3).toUpperCase() != "PHA") {
                        addError("AHPRA number should start with PHA");
                        isValid = false;
                    }
                }
            }
            return isValid;
        }

        function isProviderNumberValid() {
            var providerNumber = vm.model.prescriberNumber;
            var regexStartsWithSixDigits = /^\d{6,}/;
            var regexSeventhCharacter = /(I|O|S|Z)/;
            var regexEigthCharacter = /(A|B|F|H|J|K|L|T|W|X|Y)/;

            if (providerNumber != null && providerNumber != undefined && providerNumber.length > 0) {
                if (providerNumber.length != 8) {
                    vm.errors.push("Provider number must be 8 characters");
                    return false;
                }
                else if (!regexStartsWithSixDigits.test(providerNumber)) {
                    vm.errors.push("Provider number must start with 6 digits");
                    return false;
                }
                else if (regexSeventhCharacter.test(providerNumber.substr(6, 1))) {
                    vm.errors.push("Provider number: The 7th character must be a digit or alpha character that is NOT I, O, S or Z");
                    return false;
                }
                else if (!regexEigthCharacter.test(providerNumber.substr(7, 1))) {
                    vm.errors.push("Provider number: The 8th character must be one of the following alpha characters A, B, F, H, J, K, L, T, W, X, Y");
                    return false;
                }
            }
            return true;
        }
      

        function redirectUserList() {
            window.location.href = getCancelUrl();
        }

        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }

        function isEmail(value) {
            value = value === undefined || value == null ? "" : value;
            var regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
            var val = $.trim(value);
            return regex.test(val);
        }

        function addError(message) {
            var isExists = false;

            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists)
                vm.errors.push(message);
        }

        function onChangeEmail($event) {
            vm.validate = 0
            var val = $($event.target).val();
            showErrorEmail($event.target, val);
        }

        function showErrorEmail(obj, val) {
            if ((val == "" && $(obj).attr("required") !== undefined) || (val != "" && !isEmail(val))) {
                $($(obj).parent()).addClass("has-error");
                if (val != "" && !isEmail(val)) {
                    addError("Please specify a valid email address");
                }
                return 0;
            }
            else {
                $($(obj).parent()).removeClass("has-error");
                $(obj).parent().find(".help-block").html("");
            }
            return 1;
        }

        function showHighlightError(obj) {
            $($(obj).parent()).addClass("has-error");
        }

        function removeHighlightError(obj) {
            $($(obj).parent()).removeClass("has-error");
        }

        function resetHighlightError() {
            $('.has-error')
                .each(function() {
                    $(this).removeClass('has-error');
                });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('HCPRegisterController', HCPRegisterController);
    HCPRegisterController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout'];

    function HCPRegisterController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout) {
        var vm = this;
        vm.submit = submit;
        vm.cancel = cancel;
        vm.model = vm.model || {};
        vm.init = init;
        vm.addAccreditations = addAccreditations;
        vm.deleteAccreditations = deleteAccreditations;
        vm.model.accreditations = [];
        vm.model.accreditationsInForm = [];
        vm.isInstitutionFieldRequired = false;
        vm.checkErrorExists = function (arr, key) {
            var errorExists = false;
            angular.forEach(arr, function (ele) {
                if (ele.key == key) {
                    errorExists = true;
                    return;
                }
            });
            return errorExists;
        }
        $scope.$watch('vm.model.professionId', function (newValue, oldValue) {
            if (newValue != 9) {
                vm.model.otherProfession = null;
            }
        });

        function init() {
            initLookups();
            addAccreditations();
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                vm.hcpProfessions = data.Hcp_Profession;
                vm.accreditations = data.HcpAccreditation_Type;
                vm.titles = data.Title;
                vm.states = data.State;
            });
        }

        function cancel() {
            $window.location.href = '/account/login';
        }

        function submit(form) {
            if (isValid(form)) {
                removeEmptyAccreditations();
                clearSubmitErrorClassValues();
                var url = api_registerHcp;
                httpService.post(url, vm.model)
                .then(function (response) {
                    vm.errors = [];
                    vm.errors = response.data.errors;

                    if (response.data.errors.length > 0) {
                        modelStateErrorBuilder.build(vm.errors, vm.model);
                        document.getElementById('page-wrapper').scrollIntoView();
                    } else if (response.status === 200) {
                        if (response.data.data != null && response.data.data.type == "loginRedirectUrl") {
                            $window.location.href = response.data.data.message;
                        }
                        else {
                            $window.location.href = '/account/thankyou';
                        }
                    }
                });
            }
            else {
                document.getElementById('page-wrapper').scrollIntoView();
            }
            utilitySvc.invalidateControlOnSubmission(form);
        }

        function clearSubmitErrorClassValues() {
            if (vm.model.ahpranumber_error && vm.model.ahpranumber_error != null)
                vm.model.ahpranumber_error = undefined;
            if (vm.model.prescribernumber_error && vm.model.prescribernumber_error != null)
                vm.model.prescribernumber_error = undefined;
        }

        function addAccreditations() {
            vm.model.accreditations.push({
                type: 0,
                membershipNumber: ""
            });
        }

        function deleteAccreditations(index) {
            vm.model.accreditations.splice(index, 1);
        }

        function removeEmptyAccreditations() {
            for (var i = 0; i < vm.model.accreditations.length; i++) {
                if (vm.model.accreditations[i].type == undefined || vm.model.accreditations[i].type == null) {
                    if (vm.model.accreditations.length != 1) {
                        vm.model.accreditations.splice(vm.model.accreditations[i], 1);
                    }
                }
            }
        }

        function isValid(formRegisterHcp) {
            vm.errors = [];
            var valid = formRegisterHcp.$valid;
            return valid;
        }

        function isEmailAndConfirmEmailMatching() {
            var email = vm.model.email;
            var confirmEmail = vm.model.confirmEmail;

            if (email != confirmEmail) {
                vm.errors.push({
                    key: 'ConfirmEmail_NotMatched',
                    message: "Confirm email doesn't match with entered email"
                });
                return false;
            }
            return true;
        }

        //////////////////////// INSTITUTION //////////////////////////
        vm.isStateSuburbPostCodeInputsDisabled = false;
        vm.isFormAddressDisabled = true;

        vm.disableAddressInputs = function () {
            return vm.isFormAddressDisabled;
        }

        vm.isStateSuburbPostCodeDisabled = function () {
            return vm.isStateSuburbPostCodeInputsDisabled;
        }

        vm.requireInputs = function () {
            return !vm.isFormAddressDisabled;
        }

        function getItems(url) {
            var items = [];

            return httpService.get(url, { disable_loading: true })
                .then(function (response) {
                    response.data.forEach(function (item) {
                        items.push(item);
                    });
                    return items;
                });
        }

        function clearInstitution() {
            if (vm.model.institution) {
                vm.model.institution.address = {};
            }
            vm.isStateSuburbPostCodeInputsDisabled = false;
            vm.isInstitutionFieldRequired = false;
            vm.insIsSearchDisabled = false;
        }

        vm.getInstitutions = getInstitutions;
        vm.onSelectInstitution = onSelectInstitution;
        vm.onNewInstitution = onNewInstitution;
        vm.onClearInstitution = onClearInstitution;

        function getInstitutions(value) {
            var url = api_institution_search.replace('{0}', value);
            return getItems(url);
        }

        function onSelectInstitution(item, form) {
            vm.model.institution = item;
            vm.model.address = vm.model.institution.address;
            vm.isFormAddressDisabled = true;
            vm.isInstitutionFormDisabled = true;
            vm.isStateSuburbPostCodeInputsDisabled = true;
            $timeout(function () {
                $scope.$apply();
            }, 0);
        }

        function clearAddress() {
            if (vm.model.address) {
                vm.model.address = {};
            }
            vm.isFormAddressDisabled = true;
            vm.isStateSuburbPostCodeInputsDisabled = false;
        }

        function onNewInstitution() {
            vm.model.NewInstitution = true;
            vm.isInstitutionFieldRequired = true;
            vm.insIsSearchDisabled = true;
            var name = vm.model.institution ? vm.model.institution.name : undefined;
            vm.model.institution = {
                name: ""
            }
            clearAddress();
            $timeout(function () {
                vm.isFormAddressDisabled = false;
                vm.isInstitutionFormDisabled = false;
                vm.isStateSuburbPostCodeInputsDisabled = false;
            });
        }

        function onClearInstitution() {
            vm.model.institution = undefined;
            clearAddress();
            $timeout(function () {
                vm.isFormAddressDisabled = true;
                vm.isInstitutionFormDisabled = false;
                vm.isStateSuburbPostCodeInputsDisabled = false;
                vm.isInstitutionFieldRequired = false;
                vm.insIsSearchDisabled = false;
            });
        }
        //////////////////////// INSTITUTION //////////////////////////
    }
})();;
(function () {
    'use strict';

    window.app.controller('HcpRegisterEventController', HcpRegisterEventController);
    HcpRegisterEventController.$inject = ['$scope', '$window', 'utilitySvc', 'httpService',
        'formConfig', '$timeout'];

    function HcpRegisterEventController($scope, $window, utilitySvc, httpService,
        formConfig, $timeout) {
        var vm = this;
        vm.init = init;
        vm.eventId = 0;
        vm.hcpId = 0;
        vm.eventHcpId = formConfig.eventHcpId;
        vm.privacyFormSubmit = privacyFormSubmit;
        vm.contactDetailsFormSubmit = contactDetailsFormSubmit;
        vm.flightsFormSubmit = flightsFormSubmit;
        vm.accommodationFormSubmit = accommodationFormSubmit;
        vm.specialRequestsFormSubmit = specialRequestsFormSubmit;
        vm.consentFormSubmit = consentFormSubmit;
        vm.cancelRegistration = cancelRegistration;
        vm.isShowOtherFlight = true;
        vm.clickFlight = clickFlight;
        vm.clickAccommodation = clickAccommodation;
        vm.clearAccomodations = clearAccomodations;
        vm.isHasAnyFlightSelected = isHasAnyFlightSelected;
        vm.checkFlightRequestText = checkFlightRequestText;
        vm.otherFlightRequestHasValue = false;

        vm.errors = [];
        vm.messages = [];
        vm.model = {
            privacy: {},
            contactDetails: {
                NewInstitution: false
            },
            flights: {},
            accommodations: { enabled: false },
            specialRequests: {},
            consent: {}
        };
        vm.event = {};
        function init() {
            initLookups();
            checkEventHcpValid();
            getHcpDetail();
            getLastEventHcp();
            getEventHcpDetail();
        }

        function checkEventHcpValid() {
            httpService.get(api_event_checkEventHcpValid.replace('{eventHcpId}', vm.eventHcpId))
                .then(function (response) {
                    if (response.data.success) {

                    } else {
                        redirectToMyEvents();
                    }
                });
        }

        function redirectToMyEvents() {
            window.location.href = "/events/myevents";
        }

        function getHcpDetail() {
            httpService.get(api_hcp_getHcpDetailsCurrentUser).then(function (response) {
                if (response.data.success) {
                    if (response.data.data != null) {
                        vm.model.privacy.title = response.data.data.profile.title;
                        vm.model.privacy.firstName = response.data.data.profile.firstName;
                        vm.model.privacy.lastName = response.data.data.profile.lastName;
                        vm.model.privacy.mobile = response.data.data.profile.mobile;
                        vm.model.contactDetails.institution = response.data.data.institution;
                        if (vm.model.contactDetails.institution != null && vm.model.contactDetails.institution.name != null && vm.model.contactDetails.institution.name.length > 0)
                            disablingInstitutionAddressFields(true, true, true);
                        console.log('333');
                        console.log(response.data.data.institution);
                        console.log(vm.model.contactDetails.institution);
                    }
                } else {
                    response.data.errors.forEach(function (error) {
                        addError(error.message);
                    });
                }
            });
        }

        function getLastEventHcp() {
            httpService.get(api_event_getLastEventHcp).then(function (response) {
                if (response.data.success) {
                    if (response.data.data != null) {
                        vm.model.flights.frequentName = response.data.data.frequentFlyerClubName;
                        vm.model.flights.frequentNumber = response.data.data.frequentFlyerMembershipNumber;
                    }
                } else {
                    response.data.errors.forEach(function (error) {
                        addError(error.message);
                    });
                }
            });
        }

        function getEventHcpDetail() {
            httpService.get(api_event_getEventHcpDetail.replace('{eventHcpId}', vm.eventHcpId)).then(function (response) {
                console.log(response);
                if (response.data.success) {
                    vm.hcpId = response.data.data.hcpId;
                    vm.eventId = response.data.data.eventId;
                    vm.event = response.data.data.event;
                    vm.event.flights = $.grep(vm.event.flights, function (value) {
                        return value.isDeleted === false;
                    });
                    vm.event.accommodations = $.grep(vm.event.accommodations, function (value) {
                        return value.isDeleted === false;
                    });
                    vm.event.venues = $.grep(vm.event.venues, function (value) {
                        return value.isDeleted === false;
                    });

                } else {
                    response.data.errors.forEach(function (error) {
                        addError(error.message);
                    });
                }
            });
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                vm.hcpProfessions = data.Hcp_Profession;
                vm.titles = data.Title;
                vm.states = data.State;
            });
        }

        function cancelRegistration() {
            window.location.href = getCancelUrl();
        }

        function getCancelUrl() {
            if (document.referrer === undefined || document.referrer === null || document.referrer.trim() === '') {
                return formConfig.eventsUrl;
            }
            return document.referrer;
        }

        function privacyFormSubmit(event, form) {
            if (isPrivacyFormValid(form)) {
                nextTab();
            } else {
                scrollToTop();
            }
        }

        function contactDetailsFormSubmit(event, form) {
            if (isContactDetailsFormValid(form)) {
                nextTab();
            } else {
                scrollToTop();
            }
        }

        function flightsFormSubmit(event, form) {
            nextTab();
        }

        function accommodationFormSubmit(event, form) {
            if (isAccommodationFormValid(form))
                nextTab();
            else
                scrollToTop();
        }

        function specialRequestsFormSubmit(event, form) {
            nextTab();
        }

        function consentFormSubmit(event, form) {
            if (isConsentFormValid(form)) {
                var registerEventHcpViewModel = {
                    id: vm.eventHcpId,
                    eventId: vm.eventId,
                    hcpId: vm.hcpId,
                    title: vm.model.privacy.title,
                    firstName: vm.model.privacy.firstName,
                    lastName: vm.model.privacy.lastName,
                    institution: vm.model.contactDetails.institution,
                    //mobile: vm.model.contactDetails.mobile,
                    mobile: vm.model.privacy.mobile,
                    frequentName: vm.model.flights.frequentName,
                    frequentNumber: vm.model.flights.frequentNumber,
                    isAirportToHotel: vm.model.flights.isAirportToHotel,
                    isHotelToAirport: vm.model.flights.isHotelToAirport,
                    otherFlightRequest_DepartingFrom: vm.model.flights.otherFlightRequest_DepartingFrom,
                    otherFlightRequest_ReturningTo: vm.model.flights.otherFlightRequest_ReturningTo,
                    specialMealRequirement: vm.model.specialRequests.specialMealRequirement,
                    medicalConditions: vm.model.specialRequests.medicalConditions,
                    flights: [],
                    accommodations: []
                };

                if (!vm.isShowOtherFlight) {
                    $.each(vm.event.flights, function (index, item) {
                        if (item.isSelected) {
                            registerEventHcpViewModel.flights.push(item);
                        }
                    });
                }

                if (vm.model.accommodations.enabled) {
                    $.each(vm.event.accommodations, function (index, item) {
                        if (item.isSelected) {
                            registerEventHcpViewModel.accommodations.push(item);
                        }
                    });
                }

                httpService.post(api_event_registerEventHcp, registerEventHcpViewModel).then(function (response) {
                    console.log(response);
                    if (response.data.success) {
                        window.location.href = '/events/myevents';
                    } else {
                        response.data.errors.forEach(function (error) {
                            addError(error.message);
                        });
                    }
                });

            } else {
                scrollToTop();
            }
        }

        function clickFlight(item) {
            var prevSelectedElement = null;
            $.each(vm.event.flights, function (index, element) {
                if (element.isSelected === true) {
                    prevSelectedElement = element;
                    if (element.id !== item.id) {
                        element.isSelected = false;
                    }
                }
            });

            if (item.isSelected == undefined) item.isSelected = false;

            item.isSelected = !item.isSelected;
            checkVisibleOtherFlight();

            if ((prevSelectedElement == null && item.isSelected) || (prevSelectedElement != null && !item.isSelected)) {
                resetGroundTransfer();
            }
        }

        function checkFlightRequestText() {
            vm.otherFlightRequestHasValue = false;
            if (vm.model.flights.otherFlightRequest_DepartingFrom && vm.model.flights.otherFlightRequest_DepartingFrom.trim() != ''
            || vm.model.flights.otherFlightRequest_ReturningTo && vm.model.flights.otherFlightRequest_ReturningTo.trim() != '') {
                vm.otherFlightRequestHasValue = true;
            }

            if (!vm.otherFlightRequestHasValue) {
                resetGroundTransfer();
            }
        }

        function checkVisibleOtherFlight() {
            console.log(isHasAnyFlightSelected());
            if (isHasAnyFlightSelected()) {
                vm.isShowOtherFlight = false;
                vm.model.flights.otherFlightRequest_DepartingFrom = undefined;
                vm.model.flights.otherFlightRequest_ReturningTo = undefined;
                vm.otherFlightRequestHasValue = false;
            } else {
                vm.isShowOtherFlight = true;
            }
        }

        function resetGroundTransfer() {
            vm.model.flights.isAirportToHotel = undefined;
            vm.model.flights.isHotelToAirport = undefined;
        }

        function isHasAnyFlightSelected() {
            var result = false;
            $.each(vm.event.flights, function (index, item) {
                if (item.isSelected != undefined && item.isSelected) {
                    result = true;
                }
            });

            return result;
        }

        function clickAccommodation(item) {
            if (vm.model.accommodations.enabled) {
                $.each(vm.event.accommodations, function (index, element) {
                    if (element.isSelected === true && element.id !== item.id) {
                        element.isSelected = false;
                    }
                });
                if (item.isSelected == undefined) item.isSelected = false;
                item.isSelected = !item.isSelected;
            }
        }

        function clearAccomodations() {
            if (!vm.model.accommodations.enabled) {
                $.each(vm.event.accommodations, function (index, element) {
                    element.isSelected = false;
                });
            }
        }

        function isPrivacyFormValid(form) {
            vm.errors = [];
            var isValid = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                isValid = false;
            }

            return isValid;
        }

        function isAccommodationFormValid(form) {
            vm.errors = [];
            var isValid = true;
            var incre = 0;
            if (vm.model.accommodations.enabled && vm.event.accommodations.length > 0) {
                angular.forEach(vm.event.accommodations, function (item) {
                    if (item.isSelected) {
                        incre++;
                    }
                });
                $timeout(function () {
                }, 100);
                if (incre == 0) {
                    addError("Please select an accommodation option");
                    isValid = false;
                } else if (incre > 1) {
                    addError("Only one option can be selected");
                    isValid = false;
                }
            }
            return isValid;
        }

        function isContactDetailsFormValid(form) {
            vm.errors = [];
            $($('#InstitutionName').parent()).removeClass('has-error');
            var isValid = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                isValid = false;
            }

            if (form.mobile.$error.phone) {
                addError("Please specify a valid mobile number");
                isValid = false;
            }

            if (form.phone.$error.phone) {
                addError("Please specify a valid phone number");
                isValid = false;
            }

            if (form.fax.$error.phone) {
                addError("Please specify a valid fax number");
                isValid = false;
            }

            if (!vm.model.contactDetails.NewInstitution
                && (vm.model.contactDetails.institution == undefined || vm.model.contactDetails.institution == null
                || vm.model.contactDetails.institution.id == undefined
                || vm.model.contactDetails.institution.id === 0)) {
                addError("All fields highlighted in red are mandatory");
                $($('#InstitutionName').parent()).addClass("has-error");
                isValid = false;
            }

            return isValid;
        }

        function isConsentFormValid(form) {
            vm.errors = [];
            var isValid = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                isValid = false;
            }

            return isValid;
        }

        //////////////////////// INSTITUTION //////////////////////////
        vm.getInstitutions = getInstitutions;
        vm.onSelectInstitution = onSelectInstitution;
        vm.onNewInstitution = onNewInstitution;
        vm.onClearInstitution = onClearInstitution;
        vm.disablingInstitutionAddressFields = disablingInstitutionAddressFields;
        vm.isInstitutionInputsDisabled = true;

        function getItems(url) {
            var items = [];

            return httpService.get(url, { disable_loading: true })
                .then(function (response) {
                    response.data.forEach(function (item) {
                        items.push(item);
                    });
                    return items;
                });
        }

        function getInstitutions(value) {
            var url = api_institution_search.replace('{0}', value);
            return getItems(url);
        }

        function onSelectInstitution(item, form) {
            vm.model.contactDetails.institution = item;
            vm.isInstitutionInputsDisabled = true;
            disablingInstitutionAddressFields(true, true, true);
            $timeout(function () {
                $scope.$apply();
            }, 0);
        }

        function onNewInstitution() {
            vm.model.contactDetails.NewInstitution = true;
            var name = vm.model.contactDetails.institution ? vm.model.contactDetails.institution.name : undefined;
            vm.model.contactDetails.institution = {
                name: ''
            }
            $timeout(function () {
                vm.isInstitutionInputsDisabled = false;
                disablingInstitutionAddressFields(false, false, false);
            });
        }

        function onClearInstitution() {
            vm.model.contactDetails.NewInstitution = false;
            vm.model.contactDetails.institution = undefined;
            $timeout(function () {
                vm.isInstitutionInputsDisabled = false;
                disablingInstitutionAddressFields(false, true, false);
            });
        }

        function disablingInstitutionAddressFields(isInstituteDisabled, isAddressDisabled, isSuburbStatePostcodeDisabled) {
            vm.isInstitutionFormDisabled = isInstituteDisabled;
            vm.isAddressFormDisabled = isAddressDisabled;
            vm.isSuburbStatePostcodeFormDisabled = isSuburbStatePostcodeDisabled;
        }
        //////////////////////// INSTITUTION //////////////////////////

        // TAB FUNCTIONS
        vm.activeTabIndex = 1;
        vm.previousTab = previousTab;

        function nextTab() {
            if (vm.activeTabIndex < 6) {
                vm.errors = [];
                vm.activeTabIndex = vm.activeTabIndex + 1;
            }
        }

        function previousTab() {
            if (vm.activeTabIndex > 1) {
                vm.errors = [];
                vm.activeTabIndex = vm.activeTabIndex - 1;
            }
        }

        // COMMON FUNCTIONS
        function addError(message) {
            var isExists = false;
            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }
            if (!isExists) vm.errors.push(message);
        }

        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }

        function onBlurNumberOnly($event) {
            var val = $($event.target).val();
            showErrorNumberOnly($event.target, val);
        }

        function onBlurCharacterOnly($event) {
            var val = $($event.target).val();
            showErrorCharacterOnly($event.target, val);
        }

        function showErrorNumberOnly(obj, val) {
            if (isNaN(val)) {
                $($(obj).parent()).addClass("has-error");
            } else {
                $($(obj).parent()).removeClass("has-error");
            }
        }

        function showErrorCharacterOnly(obj, val) {
            var matches = val.match(/\d+/g);
            if (matches != null) {
                $($(obj).parent()).addClass("has-error");
            } else {
                $($(obj).parent()).removeClass("has-error");
            }
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('CDERegisterController', CDERegisterController);
    CDERegisterController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', 'toaster', '$rootScope'];

    function CDERegisterController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, toaster, $rootScope) {
        var vm = this;
        vm.submit = submit;
        vm.back = back;
        vm.model = vm.model || {};
        vm.init = init;
        vm.removeAreas = removeAreas;
        vm.removeLanguages = removeLanguages;
        vm.getAreaType = getAreaType;
        vm.getLanguageType = getLanguageType;
        vm.onSelectLanguage = onSelectLanguage;
        vm.onSelectArea = onSelectArea;
        vm.onAddArea = onAddArea;
        vm.onAddLanguage = onAddLanguage;
        vm.showAreaLanguage = showAreaLanguage;
        vm.areasCovered = [];
        vm.languagesSpoken = [];

        function init() {
            isCDERegistered();
            initLookups();
            showAreaLanguage();
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                vm.hcpProfessions = data.Hcp_Profession;
                vm.states = data.State;
                getHcpDetails();
            });
        }

        function isCDERegistered() {
            httpService.get(api_isCde_registered.replace('{userId}', formConfig.userId))
            .success(function (response) {
                vm.model.isRegisteredToCDE = response.data;
            });
        }

        $scope.$watch('vm.model.professionId', function (newValue, oldValue) {
            if (newValue != undefined && newValue != formConfig.otherProfession) {
                vm.model.otherProfession = null;
            }
            showAreaLanguage();
        });

        function getObjectPropertyValuesForAreaAndLanguage(propertyType) {
            var objectId = 0;
            if (vm.model.hcp.hcpPrograms != null)
                objectId = vm.model.hcp.hcpPrograms[0].id;
            httpService.get(api_propertyType_values.replace('{propertyType}', propertyType).replace('{objectId}', objectId))
           .success(function (response) {
               if (propertyType == formConfig.areaTypeId)
                   vm.areasCovered = response.data;
               else if (propertyType == formConfig.languageTypeId)
                   vm.languagesSpoken = response.data;
           });
        }

        function getHcpDetails() {
            httpService.get(api_getHcp_by_userId.replace('{userId}', formConfig.userId))
           .success(function (response) {
               vm.model.hcp = response.data;
               vm.model.id = response.data.id;
               vm.model.professionId = response.data.professionId;
               vm.model.otherProfession = response.data.otherProfession;
               vm.model.user = response.data.user;
               vm.model.willingToTravel = false;
               vm.isInstitutionAddressFormDisabled = true;

               //institution details
               if (vm.model.hcp.hcpInstitutions[0] != null && vm.model.hcp.hcpInstitutions[0] != undefined) {
                   vm.model.institution = vm.model.hcp.hcpInstitutions[0].institution;
                   vm.model.address = vm.model.hcp.hcpInstitutions[0].institution.address;
                   vm.isInstitutionFormDisabled = true;                   
               }
               else {
                   //vm.model.address = vm.model.hcp.user.address;
                   vm.model.address = vm.model.hcp.profile.address;
                   vm.isInstitutionFormDisabled = false;
                   vm.isFormAddressDisabled = true;                   
                   vm.isStateSuburbPostCodeInputsDisabled = false;
                   vm.insIsSearchDisabled = false;                   
               }

               //profile details
               if (vm.model.hcp.profile != null) {
                   vm.model.profile = vm.model.hcp.profile;
               }
               else if (vm.model.user.profile != null) {
                   vm.model.profile = vm.model.user.profile;
               }

               if (vm.model.isRegisteredToCDE) {
                   $window.location.href = '/helpinghands';
               }
           });
        }

        function showAreaLanguage() {
            if (vm.model.professionId != formConfig.generalPhysician && vm.model.professionId != formConfig.generalPractitioner && vm.model.professionId != formConfig.specialist) {
                return true;
            }
            else {
                return false;
            }
        }

        function removeAreas(index) {
            if (vm.areasCovered != null) {
                vm.areasCovered.splice(index, 1);
            }
        }

        function removeLanguages(index) {
            if (vm.languagesSpoken != null) {
                vm.languagesSpoken.splice(index, 1);
            }
        }

        function back() {
            $window.location.href = '/helpinghands/index'
        }


        function submit(form) {
            var message = "Registered successfully";
            if (isValid(form)) {
                pushDetailsToObjectProperties();
                if (vm.model.professionId != formConfig.generalPhysician && vm.model.professionId != formConfig.generalPractitioner && vm.model.professionId != formConfig.specialist) {
                    message = "Registered successfully, please complete training";
                }
                var url = api_helpingHands_registerCDE;
                httpService.post(url, vm.model)
                .then(function (response) {
                    vm.errors = [];
                    vm.errors = response.data.errors;

                    if (response.data.errors.length > 0) {
                        modelStateErrorBuilder.build(vm.errors, vm.model);
                        document.getElementById('page-wrapper').scrollIntoView();

                    } else {
                        $rootScope.$broadcast("loader_show");
                        toaster.pop({
                            type: 'success',
                            title: 'Success',
                            body: message,
                            timeout: 6000,
                            onHideCallback: function () {
                                $window.location.href = '/helpinghands';
                                $rootScope.$broadcast("loader_hide");
                            }
                        });
                    }
                });
            }
            else {
                document.getElementById('page-wrapper').scrollIntoView();
            }
            utilitySvc.invalidateControlOnSubmission(form);
        }

        function isValid(formRegisterCde) {
            vm.errors = [];

            var valid = formRegisterCde.$valid;
            return valid;
        }


        function pushDetailsToObjectProperties() {
            vm.model.objectProperties = [];
            for (var i = 0; i < vm.areasCovered.length; i++) {
                vm.model.objectProperties.push({
                    propertyValueId: vm.areasCovered[i].propertyValueId,
                    value: vm.areasCovered[i].value,
                    propertyId: vm.areasCovered[i].propertyId
                });
            }

            for (var i = 0; i < vm.languagesSpoken.length; i++) {
                vm.model.objectProperties.push({
                    propertyValueId: vm.languagesSpoken[i].propertyValueId,
                    value: vm.languagesSpoken[i].value,
                    propertyId: vm.languagesSpoken[i].propertyId
                });
            }

            vm.model.objectProperties.push({
                propertyValueId: null,
                value: vm.model.cdeEmail == undefined ? null : vm.model.cdeEmail,
                propertyId: formConfig.cdeEmailTypeId
            });

            vm.model.objectProperties.push({
                propertyValueId: null,
                value: vm.model.cdeMobile == undefined ? null : vm.model.cdeMobile,
                propertyId: formConfig.cdeMobileTypeId
            });

            vm.model.objectProperties.push({
                propertyValueId: null,
                value: vm.model.cdePhone == undefined ? null : vm.model.cdePhone,
                propertyId: formConfig.cdePhoneTypeId
            });

            if (vm.model.willingToTravel != undefined && vm.model.willingToTravel != null) {
                vm.model.objectProperties.push({
                    propertyValueId: null,
                    value: vm.model.willingToTravel,
                    propertyId: formConfig.cdeWillingToTravelTypeId
                });
            }
        }
        //////////////////////// AREA AND LANGUAGE //////////////////////////

        vm.isAddAreaButtonDisabled = true;
        vm.isAddLanguageButtonDisabled = true;
        vm.isAreaFieldDisabled = false;
        vm.isLanguageFieldDisabled = false;

        function getItems(url) {
            var items = [];

            return httpService.get(url, { disable_loading: true })
                .then(function (response) {
                    response.data.forEach(function (item) {
                        items.push(item);
                    });
                    return items;
                });
        }

        function getAreaType(value) {
            return getObjectType(value, formConfig.areaTypeId);
        }

        function getLanguageType(value) {
            return getObjectType(value, formConfig.languageTypeId);
        }

        function getObjectType(value, type) {
            var url = api_propertyvalues_search.replace('{propertyId:int?}', type).replace('{keyword?}', value);
            return getItems(url);
        }

        function onSelectLanguage(item) {
            //vm.model.value = item;
            vm.model.languagePropertyValue = item;
            vm.isAddLanguageButtonDisabled = false;
            vm.isLanguageFieldDisabled = true;
        }

        function onSelectArea(item) {
            //vm.objectProperties = item;
            vm.model.areaPropertyValue = item;
            vm.isAddAreaButtonDisabled = false;
            vm.isAreaFieldDisabled = true;
        }

        function onAddArea() {
            var item = vm.model.areaPropertyValue;
            vm.isAddAreaButtonDisabled = true;
            vm.isAreaFieldDisabled = false;
            //if new area added
            if (item != undefined && item != null && item.value.length > 0) {
                if (item.id == undefined) {
                    if (!isAreaOrLanguageExists(vm.areasCovered, item)) {
                        vm.areasCovered.push({
                            propertyValueId: 0,
                            value: item,
                            propertyId: formConfig.areaTypeId
                        });
                        
                    }
                }
                else {
                    if (!isAreaOrLanguageExists(vm.areasCovered, item.value)) {
                        vm.areasCovered.push({
                            propertyValueId: item.id,
                            value: item.value,
                            propertyId: formConfig.areaTypeId
                        });                       
                    }
                }
                vm.model.areaPropertyValue = null;
            }
        }

        function onAddLanguage() {
            var item = vm.model.languagePropertyValue;
            vm.isLanguageFieldDisabled = false;
            vm.isAddLanguageButtonDisabled = true;
            if (item != undefined && item != null && item.value.length > 0) {
                if (item.id == undefined) {
                    if (!isAreaOrLanguageExists(vm.languagesSpoken, item)) {
                        vm.languagesSpoken.push({
                            propertyValueId: 0,
                            value: item,
                            propertyId: formConfig.languageTypeId
                        });
                    }
                }
                else {
                    if (!isAreaOrLanguageExists(vm.languagesSpoken, item.value)) {
                        vm.languagesSpoken.push({
                            propertyValueId: item.id,
                            value: item.value,
                            propertyId: formConfig.languageTypeId
                        });
                    }
                }
                vm.model.languagePropertyValue = null;
            }
        }

        function isAreaOrLanguageExists(areaOrLanguageArray, areaOrLanguageValue) {
            var arrayLength = areaOrLanguageArray.length;
            for (var i = 0; i < arrayLength; i++) {
                if (areaOrLanguageArray[i].value.toLowerCase() == areaOrLanguageValue.toLowerCase()) {
                    return true;
                }
            }
            return false;
        }
        //////////////////////// AREA AND LANGUAGE //////////////////////////

        //////////////////////// INSTITUTION //////////////////////////
        vm.isStateSuburbPostCodeInputsDisabled = false;
        vm.isFormAddressDisabled = true;        

        vm.disableAddressInputs = function () {
            return vm.isFormAddressDisabled;
        }

        vm.isStateSuburbPostCodeDisabled = function () {
            return vm.isStateSuburbPostCodeInputsDisabled;
        }

        vm.requireInputs = function () {
            return !vm.isFormAddressDisabled;
        }

        function getItems(url) {
            var items = [];

            return httpService.get(url, { disable_loading: true })
                .then(function (response) {
                    response.data.forEach(function (item) {
                        items.push(item);
                    });
                    return items;
                });
        }

        function clearInstitution() {
            if (vm.model.institution) {
                vm.model.institution.address = {};
            }
            vm.isStateSuburbPostCodeInputsDisabled = false;
            vm.isInstitutionFormDisabled = true;
        }

        vm.getInstitutions = getInstitutions;
        vm.onSelectInstitution = onSelectInstitution;
        vm.onNewInstitution = onNewInstitution;
        vm.onClearInstitution = onClearInstitution;

        function getInstitutions(value) {
            var url = api_institution_search.replace('{0}', value);
            return getItems(url);
        }

        function onSelectInstitution(item) {
            vm.model.institution = item;
            vm.model.address = vm.model.institution.address;
            vm.isInstitutionAddressFormDisabled = true;
            vm.isInstitutionFormDisabled = true;
            vm.isStateSuburbPostCodeInputsDisabled = true;            
        }

        function clearAddress() {
            if (vm.model.address) {
                vm.model.address = {};
            }
            vm.isInstitutionAddressFormDisabled = true;
            vm.isStateSuburbPostCodeInputsDisabled = false;
        }

        function onNewInstitution() {
            vm.model.NewInstitution = true;
            var name = vm.model.institution ? vm.model.institution.name : undefined;
            vm.model.institution = {
                name: ''
            }
            clearAddress();
            $timeout(function () {
                vm.isInstitutionAddressFormDisabled = false;
                vm.isInstitutionFormDisabled = false;
                vm.isStateSuburbPostCodeInputsDisabled = false;
                vm.isInstitutionFieldRequired = true;
                vm.insIsSearchDisabled = true;
            });
        }

        function onClearInstitution() {
            vm.model.institution = undefined;
            clearAddress();
            $timeout(function () {
                vm.isInstitutionAddressFormDisabled = true;
                vm.isInstitutionFormDisabled = false;
                vm.isStateSuburbPostCodeInputsDisabled = false;
                vm.isInstitutionFieldRequired = false;
                vm.insIsSearchDisabled = false;
            });
        }
        //////////////////////// INSTITUTION //////////////////////////
    }
})();;
(function () {
    'use strict';

    window.app.controller('CreateInvoiceController', CreateInvoiceController);
    CreateInvoiceController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', 'moment'];

    function CreateInvoiceController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, moment) {
        var vm = this;
        vm.init = init;
        vm.visits = [];
        vm.errors = [];
        vm.model = {};
        vm.dateOfLastInvoice = null;
        vm.currentDate = new Date();
        vm.confirmVisit = confirmVisit;
        vm.confirmPaymentDetails = confirmPaymentDetails;
        vm.finaliseAndGenerateSystemInvoice = finaliseInvoice;
        vm.onBlurNumberOnly = onBlurNumberOnly;
        vm.onBlurCharacterOnly = onBlurCharacterOnly;

        vm.activeTabIndex = 1;
        vm.setActiveTab = setActiveTab;
        vm.nextTab = nextTab;
        vm.previousTab = previousTab;
        var acceptTypes = ['image/jpeg', 'image/jpg', 'application/pdf'];
        vm.totalAmount = 0;

        function init() {
            getVisits();
            getPaymentDetails();
        }

        $scope.$watch('vm.document', function (newValue, oldValue) {
            if (newValue !== null && newValue != undefined) {
                finaliseAndUploadInvoice();
            }
        });

        function getVisits() {
            httpService.get(api_invoice_getVisits).then(function (response) {
                if (response.status == 200) {
                    vm.totalAmount = 0;
                    vm.visits = response.data.listVisit;
                    angular.forEach(vm.visits,
                        function (item) {
                            item.patientDOB = moment.utc(item.patientDOB).local().format("DD/MM/YYYY");
                            item.enteredDate = moment.utc(item.enteredDate).local().format("DD/MM/YYYY");
                            item.visitedOn = moment.utc(item.visitedOn).local().format("DD/MM/YYYY");

                            item.amount = item.interactionLength / 60 * 80;
                            vm.totalAmount += item.amount;
                        });
                    vm.dateOfLastInvoice = response.data.dateOfLastInvoice;
                }
            });
        }

        function getPaymentDetails() {
            httpService.get(api_invoice_getPaymentDetails).then(function (response) {
                if (response.status == 200) {
                    vm.model.abn = parseInt(response.data.abn);
                    vm.model.accountNumber = parseInt(response.data.accountNumber);
                    vm.model.accountBranchNumber = parseInt(response.data.accountBranchNumber);
                    vm.model.accountName = response.data.accountName;
                    vm.model.isRememberMyAccountDetail = response.data.isRememberMyAccountDetail;
                    vm.model.isGSTApplied = response.data.isGSTApplied;
                }
            });
        }

        function redirectMonthlyInvoicesPage() {
            window.location.href = '/helpinghands/invoices';
        }

        function confirmVisit(form) {
            httpService.post(api_invoice_confirmVisits)
                .then(function (response) {
                    if (response.data.success) {
                        nextTab();
                    } else {
                        response.data.errors.forEach(function (error) {
                            addError(error.message);
                        });
                        scrollToTop();
                    }
                },
                    function (error) {
                        if (jQuery.type(error.data) === 'string') {
                            addError(error.data);
                        } else {
                            addError(error.data.message);
                        }
                    });
        }

        function isValidFormPaymentDetails(form) {
            vm.errors = [];
            var isValid = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addRequireError("All fields highlighted in red are mandatory");;
                isValid = false;
            }

            return isValid;
        }

        function confirmPaymentDetails(form) {
            if (isValidFormPaymentDetails(form)) {
                httpService.post(api_invoice_confirmPaymentDetails, vm.model)
                    .then(function (response) {
                        if (response.data.success) {
                            nextTab();
                        } else {
                            response.data.errors.forEach(function (error) {
                                addError(error.message);
                            });
                            scrollToTop();
                        }
                    });
            } else {
                scrollToTop();
            }
        }

        function finaliseInvoice() {
            callInvoiceApi(api_invoice_finaliseBySystem);
        }

        function finaliseAndUploadInvoice() {
            callInvoiceApi(api_invoice_finaliseByUpload);
        }

        function callInvoiceApi(api_url) {
            var browserTimeZone = moment.tz.guess();
            api_url = api_url.replace('{tz}', browserTimeZone);

            var model = {
                document: vm.document,
                abn: vm.model.abn,
                accountName: vm.model.accountName,
                accountBranchNumber: vm.model.accountBranchNumber,
                accountNumber: vm.model.accountNumber
            };
            httpService.post(api_url, model)
              .then(function (response) {
                  if (response.data.success) {
                      redirectMonthlyInvoicesPage();
                  } else {
                      response.data.errors.forEach(function (error) {
                          addError(error.message);
                      });
                      scrollToTop();
                  }
              },
                  function (error) {
                      addError(error.data.exceptionMessage);
                      scrollToTop();
                  });
        }

        // TAB FUNCTIONS
        function setActiveTab(tabIndex) {
            switch (vm.activeTabIndex) {
                case 1:
                    confirmVisit(vm.ConfirmVisitForm);
                    break;
                case 2:
                    confirmPaymentDetails(vm.ConfirmPaymentDetailForm);
                    break;
            }
            vm.activeTabIndex = tabIndex;
        }

        function nextTab() {
            if (vm.activeTabIndex < 3) {
                vm.errors = [];
                vm.activeTabIndex = vm.activeTabIndex + 1;
            }
        }

        function previousTab() {
            if (vm.activeTabIndex > 1) {
                vm.errors = [];
                vm.activeTabIndex = vm.activeTabIndex - 1;
            }
            else {
                redirectMonthlyInvoicesPage();
            }
        }
        // COMMON FUNCTIONS
        function addError(message) {
            var isExists = false;
            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }
            if (!isExists) vm.errors.push(message);
        }

        function addRequireError(message) {
            var isExists = false;

            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists)
                vm.errors.push(message);
        }

        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }

        function onBlurNumberOnly($event) {
            var val = $($event.target).val();
            showErrorNumberOnly($event.target, val);
        }

        function onBlurCharacterOnly($event) {
            var val = $($event.target).val();
            showErrorCharacterOnly($event.target, val);
        }

        function showErrorNumberOnly(obj, val) {
            if (isNaN(val)) {
                $($(obj).parent()).addClass("has-error");
            } else {
                $($(obj).parent()).removeClass("has-error");
            }
        }

        function showErrorCharacterOnly(obj, val) {
            var matches = val.match(/\d+/g);
            if (matches != null) {
                $($(obj).parent()).addClass("has-error");
            } else {
                $($(obj).parent()).removeClass("has-error");
            }
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('HhMonthlyInvoiceController', HhMonthlyInvoiceController);
    HhMonthlyInvoiceController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService',
        'uiGridConstants', 'moment', 'utilitySvc', 'formConfig'];

    function HhMonthlyInvoiceController($rootScope, $scope, $window, filterFilter, httpService,
        uiGridConstants, moment, utilitySvc, formConfig) {
        var vm = this;
        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: '-invoiceDate',
            keyword: ''
        };
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getDataGird);
        vm.gridOptions.columnDefs = [
            { name: 'id', displayName: 'System invoice #', maxWidth: 140 },
            { name: 'invoiceDate', displayName: 'Invoiced date', maxWidth: 120 },
            { name: 'periodStart', displayName: 'Start invoice period', maxWidth: 160 },
            { name: 'periodEnd', displayName: 'End invoice period', maxWidth: 150 },
            { name: 'statusName', displayName: 'Invoice status', maxWidth: 120 },
            {
                field: 'id',
                enableSorting: false,
                displayName: 'System generated invoice',
                enableCellEdit: false,
                maxWidth: 200,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center""><a target="__blank" ng-if="row.entity.systemGenerateInvoice !=null" href="{{row.entity.systemGenerateInvoice}}">download</a></div>'
            },
            {
                field: 'id',
                enableSorting: false,
                displayName: 'Your uploaded invoices (optional)',
                enableCellEdit: false,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center"><a target="__blank" ng-if="row.entity.yourUploadedInvoice !=null" href="{{row.entity.yourUploadedInvoice}}">download</a></div>'
            }
        ];
        vm.isCanCreateMonthlyInvoice = false;

        // This is to watch the filter value changed, and call the getUsers again!
        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getDataGird();
            }
        });

        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.gridOptions);
        }

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            getDataGird();
            checkVisableBtnCreateMonthlyInvoice();
        };

        function getDataGird() {
            var url = api_invoice_search;
            url += '?pageSize=' + vm.searchOption.pageSize;
            url += '&pageNo=' + vm.searchOption.pageNumber;
            url += '&sortFields=' + vm.searchOption.sort;
            url += '&keyword=' + vm.searchOption.keyword;
            var browserTimeZone = moment.tz.guess();
            url += '&browserTimeZone=' + browserTimeZone;

            return httpService.get(url).then(function (response) {
                if (response.data.success) {
                    console.log(response.data.data.result);
                    vm.gridOptions.data = response.data.data.result;
                    vm.gridOptions.totalItems = response.data.data.totalCount;
                    angular.forEach(vm.gridOptions.data,
                        function (item) {
                            if (item.invoiceDate && item.invoiceDate != null) {
                                //item.invoiceDate = moment(item.invoiceDate).format("DD/MM/YYYY");
                                item.invoiceDate = moment.utc(item.invoiceDate).local().format("DD/MM/YYYY");
                            }
                            if (item.periodStart && item.periodStart != null) {
                               //item.periodStart = moment(item.periodStart).format("DD/MM/YYYY");
                                item.periodStart = moment.utc(item.periodStart).local().format("DD/MM/YYYY");
                            }
                            if (item.periodEnd && item.periodEnd != null) {
                               // item.periodEnd = moment(item.periodEnd).format("DD/MM/YYYY");
                                item.periodEnd = moment.utc(item.periodEnd).local().format("DD/MM/YYYY");
                            }
                        });
                } else {
                    vm.errors = response.data.errors;
                }
            });
        }

        function checkVisableBtnCreateMonthlyInvoice() {
            httpService.get(api_invoice_isCanCreateMonthlyInvoice).then(function(response) {
                if (response.data.success) {
                    vm.isCanCreateMonthlyInvoice = response.data.data;
                } else {
                    vm.errors = response.data.errors;
                }
            });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('HHNavigationController', HHNavigationController);
    HHNavigationController.$inject = ['$scope', 'httpService'];

    function HHNavigationController($scope, httpService) {
        var vm = this;
        vm.init = init;
        vm.menus = [];

        function init() {
            httpService.get(api_navApi_helpingHands).then(function (response) {
                if (response.data) {
                    vm.menus = response.data;
                }
            });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('HHResourceController', HHResourceController);
    HHResourceController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
       '$timeout', 'formConfig', '$sce'];

    function HHResourceController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
       $timeout, formConfig, $sce) {
        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;
        vm.errors = [];
        vm.resourceTypes = [];
        vm.setRedirectAction = setRedirectAction;
        vm.countResouceForEachResourceType = countResouceForEachResourceType;

        function init() {            
            getResources();
            getResourceTypes();         

        }

        function getResources() {
            
            return httpService.get(api_resource_getAllResources.replace('{0}', formConfig.helpingHandsResource)).success(function (response) {
                vm.model.resources = response;
                assignResourceUrlToTrustedUrl(response);
            });
        };

        function getResourceTypes() {            
            return httpService.get(api_lookupValue_getResourceLookupValues.replace('{isPublicFacing}', 'false'))
                .success(function (response) {
                    vm.model.resourceTypes = response;
                });
        }

        function assignResourceUrlToTrustedUrl(response) {
            angular.forEach(response,
                function (item) {
                    item.videoUrl = $sce.trustAsResourceUrl(item.url);
                });
        }

        function countResouceForEachResourceType(resourceTypeId) {
            if (vm.model.resources) {
                for (var i = 0; i < vm.model.resources.length; i++) {
                    if (vm.model.resources[i].type == resourceTypeId)
                        return true;
                }
            }
            return false;
        }

        //pause the video when modal is closed
        $('body').on('hidden.bs.modal', '.modal', function () {
            $('video').trigger('pause');
        });
    }
})();;
(function () {
    'use strict';


    window.app.controller('InvoiceAdministrationController', InvoiceAdministrationController);

    InvoiceAdministrationController.$inject = ['$scope', 'httpService', 'modelStateErrorBuilder',
        'uiGridConstants', 'moment', 'utilitySvc', '$window', '$rootScope', 'toaster'];

    function InvoiceAdministrationController($scope, httpService, modelStateErrorBuilder,
        uiGridConstants, moment, utilitySvc, $window, $rootScope, toaster) {
        var vm = this;
        vm.init = init;
        vm.model = vm.model || {};
        vm.dateFormat = 'dd/MM/yyyy';
        vm.revertInvoice = revertInvoice;
        vm.approveOrDeclineInvoice = approveOrDeclineInvoice;
        vm.exportInvoices = exportInvoices;
        var table = null;
        vm.errors = [];

        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: 'invoiceDate',
            keyword: ''
        };

        vm.validateDateInput = function () {
            if (vm.fromDate != null
                && vm.toDate != null
                && !isDatesRangeValid()) {
                vm.errors.push({
                    key: 'InvalidDateRange',
                    message: "The from date can not be after the to date"
                });
            }
            else {
                vm.errors = vm.errors.filter(function (el) {
                    return el.key !== "InvalidDateRange";
                });
            }
        }

        function exportInvoices() {
            if (vm.errors)
                vm.errors.splice(0);

            var url = api_invoices_export;
            var browserTimeZone = moment.tz.guess();
            url = url + '?browserTimeZone=' + browserTimeZone;
            if (vm.fromDate) {
                url = url + '&fromDate=' + moment.utc(vm.fromDate).local().format("YYYY/MM/DD");
            }
            if (vm.toDate) {
                url = url + '&toDate=' + moment.utc(vm.toDate).local().format("YYYY/MM/DD");
            }
            if (isDatesRangeValid())
                utilitySvc.downloadFileFromApi(url);
            else {
                vm.errors.push({
                    key: 'InvalidDateRange',
                    message: "The from date can not be after the to date"
                });
            }
        }

        function isDatesRangeValid() {
            var fromDate = moment(vm.fromDate, "DD/MM/YYYY");
            var toDate = moment(vm.toDate, "DD/MM/YYYY");
            if (fromDate != null && toDate != null) {
                if (fromDate > toDate) {
                    return false;
                }
            }
            return true;
        }

        function getInvoices() {
            var browserTimeZone = moment.tz.guess();
            var url = api_search_invoices;
            if (vm.searchOption.sort.toLowerCase() == "invoiceperiod")
                vm.searchOption.sort = "PeriodStart";
            else if (vm.searchOption.sort.toLowerCase() == "-invoiceperiod")
                vm.searchOption.sort = "-PeriodStart";

            url = url.replace('{pageSize}', vm.searchOption.pageSize);
            url = url.replace('{pageNo}', vm.searchOption.pageNumber);
            url = url.replace('{sort}', vm.searchOption.sort);
            url = url.replace('{1}', vm.searchOption.keyword);
            url = url.replace('{0}', browserTimeZone);

            if (vm.fromDate) {
                url = url + '&fromDate=' + moment.utc(vm.fromDate).local().format("YYYY/MM/DD");
            }
            if (vm.toDate) {
                url = url + '&toDate=' + moment.utc(vm.toDate).local().format("YYYY/MM/DD");
            }

            return httpService.get(url).success(function (data) {
                vm.invoiceGridOptions.data = data.result;
                vm.invoiceGridOptions.totalItems = data.totalCount;

                angular.forEach(vm.invoiceGridOptions.data, function (record) {
                    if (record.invoiceDate) {
                        record.invoiceDate = moment.utc(record.invoiceDate).local().format("DD/MM/YYYY");
                    }
                    if (record.periodStart) {
                        record.periodStart = moment.utc(record.periodStart).local().format("DD/MM/YYYY");
                    }
                    if (record.periodEnd) {
                        record.periodEnd = moment.utc(record.periodEnd).local().format("DD/MM/YYYY");
                    }

                    record.invoicePeriod = record.periodStart + " - " + record.periodEnd;
                });
            });
        }

        function init() {
            $('.date-picker').datepicker({
                orientation: "left",
                autoclose: true,
                format: "dd/mm/yyyy"
            });

            getInvoices();
        }

        function revertInvoice(id) {
            var url = api_invoices_revert;
            url = url.replace('{id}', id);

            httpService.post(url)
                .then(function (response) {
                    vm.errors = [];
                    vm.errors = response.data.errors;

                    if (response.data.errors.length > 0) {
                        modelStateErrorBuilder.build(vm.errors, vm.model);
                        document.getElementById('page-wrapper').scrollIntoView();
                    }
                    else {
                        $rootScope.$broadcast("loader_show");
                        toaster.pop({
                            type: 'success',
                            title: 'Success',
                            body: 'Invoice reverted successfully',
                            timeout: 2500,
                            onHideCallback: function () {
                                $rootScope.$broadcast("loader_hide");
                            }
                        });
                        getInvoices();
                    }
                });
        }

        function approveOrDeclineInvoice(e, id) {

            var message = "";
            if (e.target.value == 'true') {
                vm.model.approveInvoice = true;
                message = "Invoice Approved successfully";
            }
            else {
                vm.model.approveInvoice = false;
                message = "Invoice Declined";
            }

            var url = api_invoices_approveOrDecline;
            url = url.replace('{id}', id).replace('{approveInvoice}', vm.model.approveInvoice);

            httpService.post(url)
                .then(function (response) {
                    vm.errors = [];
                    vm.errors = response.data.errors;

                    if (response.data.errors.length > 0) {
                        modelStateErrorBuilder.build(vm.errors, vm.model);
                        document.getElementById('page-wrapper').scrollIntoView();
                    }
                    else {
                        $rootScope.$broadcast("loader_show");
                        toaster.pop({
                            type: 'success',
                            title: 'Success',
                            body: message,
                            timeout: 2500,
                            onHideCallback: function () {
                                $rootScope.$broadcast("loader_hide");
                            }
                        });
                        getInvoices();
                    }
                });
        }

        // This is to watch the filter value changed, and call the getUsers again!
        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getInvoices();
            }
        });

        function checkAndDoDateFilter(newValue, oldValue) {
            if (newValue === undefined || newValue === null) {
                getInvoices();
            }
            else {
                var dateEntered = moment.utc(newValue).local().format("DD/MM/YYYY");
                if (isDateEnteredValid(dateEntered)) {
                    getInvoices();
                }
            }
        }

        $scope.$watch('vm.fromDate', function (newValue, oldValue) {
            checkAndDoDateFilter(newValue, oldValue);
        });

        $scope.$watch('vm.toDate', function (newValue, oldValue) {
            checkAndDoDateFilter(newValue, oldValue);
        });

        function isDateEnteredValid(dateEntered) {
            var regexDateFormat = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}/;
            if (regexDateFormat.test(dateEntered))
                return true;
            else
                return false;
        }

        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.invoiceGridOptions);
        }



        ////////////////////////////// Invoices List ///////////////////////////


        vm.invoiceGridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getInvoices);
        vm.invoiceGridOptions.paginationPageSizes = [1, 5, 10, 25, 50, 100];
        vm.invoiceGridOptions.columnDefs = [];
        var restOfColDefs = [
            { name: 'id', displayName: 'Invoice ID', maxWidth: 100 },
            { name: 'invoiceDate', displayName: 'Report submitted', maxWidth: 180 },
            { name: 'fullName', displayName: 'CDE', maxWidth: 200 },
            { name: 'amount', displayName: 'Invoice total', maxWidth: 180 },
            { name: 'invoicePeriod', displayName: 'Invoiced Period', maxWidth: 250 },
            {
                field: 'id',
                maxWidth: 130,
                enableSorting: true,
                displayName: 'System invoice',
                enableCellEdit: false,
                cellTemplate: '<div class="ui-grid-cell-contents text-center""><a target="__blank" ng-if="row.entity.systemGenerateInvoice !=null" href="{{row.entity.systemGenerateInvoice}}">download</a></div>'
            },
            {
                field: 'id',
                maxWidth: 250,
                enableSorting: false,
                displayName: 'Uploaded invoice',
                enableCellEdit: false,
                cellTemplate: '<div class="ui-grid-cell-contents text-center""><a target="__blank" ng-if="row.entity.yourUploadedInvoice !=null" href="{{row.entity.yourUploadedInvoice}}">download</a></div>'
            },
            {
                field: 'approvalPending',
                maxWidth: 250,
                enableSorting: false,
                displayName: 'Approval pending',
                enableCellEdit: false,
                cellTemplate: '<div ng-if="row.entity.approvalPending"><div class="inside-grid ui-grid-cell"><div class="switch-toggle">' +
                            '<input id="rdYes_{{row.entity.id}}" name="view" ng-value="true" ng-model="vm.model.approveInvoice" type="radio" ng-click="grid.appScope.approveOrDeclineInvoice($event, row.entity.id)" checked>' +
                            '<label for="rdYes_{{row.entity.id}}" onclick="">Yes</label>' +
                            '<input id="rdNo_{{row.entity.id}}" name="view" ng-value="false" ng-model="vm.model.approveInvoice" type="radio" ng-click="grid.appScope.approveOrDeclineInvoice($event, row.entity.id)">' +
                            '<label for="rdNo_{{row.entity.id}}" onclick="">No</label>' +
                            '<a class="btn btn-blue"></a></div></div></div>'
            },
            { name: 'statusName', displayName: 'Status', maxWidth: 130 },
            {
                field: 'revert',
                maxWidth: 280,
                enableSorting: false,
                displayName: '',
                enableCellEdit: false,
                cellTemplate: '<div class="inside-grid ui-grid-cell"><div ng-if="row.entity.revert"><a id="btn-revert-invoice_{{row.entity.id}}" ng-click="grid.appScope.revertInvoice(row.entity.id)" type="submit" class="btn btn-revert">revert</a></div></div>'
            }
        ];
        vm.invoiceGridOptions.appScopeProvider = vm;
        vm.invoiceGridOptions.columnDefs = vm.invoiceGridOptions.columnDefs.concat(restOfColDefs);
    }
})();

;
(function () {
    'use strict';

    window.app.controller('UserAdministrationController', UserAdministrationController);
    UserAdministrationController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService', 'modelStateErrorBuilder',
        'uiGridConstants', 'moment', 'utilitySvc', 'formConfig', 'toaster'];

    function UserAdministrationController($rootScope, $scope, $window, filterFilter, httpService, modelStateErrorBuilder,
        uiGridConstants, moment, utilitySvc, formConfig, toaster) {
        var vm = this;
        vm.approveOrDeclineUser = approveOrDeclineUser;
         
        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: '-registeredDate',
            keyword: ''
        };
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getHelpingHandsUserList);
        vm.gridOptions.columnDefs = [
            { name: 'registeredDate', displayName: 'Registered date', maxWidth: 100 },
            { name: 'fullName', displayName: 'Name' },
            { name: 'professionName', displayName: 'Profession', maxWidth: 120 },
            { name: 'email', displayName: 'Email', maxWidth: 320 },
            { name: 'registrationType', displayName: 'Registration type', maxWidth: 140 },
            {
                field: 'id',
                maxWidth: 80,
                enableSorting: false,
                displayName: '',
                enableCellEdit: false,
                cellTemplate: '<div class="ui-grid-cell-contents text-center"><a ng-if="row.entity.isUser" ng-href="{{grid.appScope.getEditHcpUrl(row.entity.id)}}">edit</a><a ng-if="!row.entity.isUser" href="#" ng-click="grid.appScope.deleteHcp(row.entity)">delete</a></div>'
            },
            {
                field: 'diabetesHCPProgramStatusName',
                maxWidth: 100,
                enableSorting: true,
                displayName: 'Diabetes program status',
                enableCellEdit: false
            }
        ];
        vm.gridOptions.appScopeProvider = vm;
        // This is to watch the filter value changed, and call the getUsers again!
        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getHelpingHandsUserList();
            }
        });

        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.gridOptions);
        }

        vm.getEditHcpUrl = function(id) {
            return formConfig.editHcpUrl.replace('hcpId', id);
        }
        vm.deleteHcp = function (hcp) {
            var url = api_hcp_deletehcpnonuser;
            url = url.replace('{hcpId}', hcp.id);
            return httpService.get(url).then(function (response) {
                //vm.errors = [];
                //vm.errors = response.data.errors;

                if (response.data.errors.length > 0) {
                    //modelStateErrorBuilder.build(vm.errors, vm.model);
                    //document.getElementById('page-wrapper').scrollIntoView();
                    $rootScope.$broadcast("loader_show");
                    toaster.pop({
                        type: 'error',
                        title: 'Delete error',
                        body: response.data.errors[0].message,
                        onHideCallback: function () {
                            $rootScope.$broadcast("loader_hide");
                        }
                    });
                }
                else {
                    $rootScope.$broadcast("loader_show");
                    toaster.pop({
                        type: 'success',
                        title: 'Success',
                        body: 'HCP \'' + hcp.fullName + '\' has been deleted successfully',
                        timeout: 2500,
                        onHideCallback: function () {
                            $rootScope.$broadcast("loader_hide");
                            getHelpingHandsUserList();
                        }
                    });
                }
            });
        }

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            getHelpingHandsUserList();
        };

        function getHelpingHandsUserList() {
            var url = api_hh_userAdministration_search;
            url = url.replace('{pageSize}', vm.searchOption.pageSize);
            url = url.replace('{pageNo}', vm.searchOption.pageNumber);
            url = url.replace('{sortFields}', vm.searchOption.sort);
            url = url.replace('{keyword}', vm.searchOption.keyword);
            var browserTimeZone = moment.tz.guess();
            url = url.replace('{tz}', browserTimeZone);

            return httpService.get(url).then(function (response) {
                if (response.data.success) {
                    console.log(response.data.data.result);
                    vm.gridOptions.data = response.data.data.result;
                    vm.gridOptions.totalItems = response.data.data.totalCount;
                    angular.forEach(vm.gridOptions.data,
                        function (item) {
                            if (item.registeredDate && item.registeredDate != null) {
                                //item.registeredDate = moment(item.registeredDate).format("DD/MM/YYYY");
                                item.registeredDate = moment.utc(item.registeredDate).local().format("DD/MM/YYYY");
                            }
                        });
                } else {
                    vm.errors = response.data.errors;
                }
            });
        }

        function approveOrDeclineUser(e, hcpProgramId) {
            var message = "";
            var url = "";
            if (e.target.value == 'true') {
               // vm.model.registrationStatus = true;
                url = api_hh_userAdministration_approve;
                message = "User was approved successfully";
            }
            else {
              //  vm.model.registrationStatus = false;
                url = api_hh_userAdministration_declined;
                message = "User was declined successfully";
            }

            url = url.replace('{hcpProgramId}', hcpProgramId);

            httpService.post(url)
                .then(function (response) {
                    vm.errors = [];
                    vm.errors = response.data.errors;

                    if (response.data.errors.length > 0) {
                        modelStateErrorBuilder.build(vm.errors, vm.model);
                        document.getElementById('page-wrapper').scrollIntoView();
                    }
                    else {
                        $rootScope.$broadcast("loader_show");
                        toaster.pop({
                            type: 'success',
                            title: 'Success',
                            body: message,
                            timeout: 2500,
                            onHideCallback: function () {
                                $rootScope.$broadcast("loader_hide");
                                getHelpingHandsUserList();
                            }
                        });
                    }
                });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('DummyTypeAheadExamplesController', DummyTypeAheadExamplesController);
    DummyTypeAheadExamplesController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService', '$timeout'];

    function DummyTypeAheadExamplesController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService, $timeout) {
        var vm = this;

        vm.states = [
        {
            Value: 1,
            Name: 'ACT'
        },
        {
            Value: 2,
            Name: 'NSW'
        }];

        resetIns();
        vm.insIsDisabled = false;
        vm.insIsAddressDisabled = true;
        vm.insIsSearchDisabled = false;
        vm.insClear = function() {
            console.log('clear is called!');
            vm.insIsSearchDisabled = false;
            vm.insIsDisabled = false;
            vm.insIsAddressDisabled = true;

            resetIns();
        };
        vm.insSelect = function (item) {
            console.log('select is called!');
            vm.insIsDisabled = true;

            vm.ins = item;
        }
        vm.insEdit = function (item) {
            console.log('edit is called!');
            vm.insIsDisabled = false;
            vm.insIsSearchDisabled = true;
            vm.insIsAddressDisabled = false;
        }
        vm.insNew = function (item) {
            console.log('new is called!');
            vm.insIsDisabled = false;
            vm.insIsSearchDisabled = true;
            vm.insIsAddressDisabled = false;

            resetIns();
        }
        function resetIns() {
            vm.ins = {
                name: null
            };
        }
        vm.insAddressDisable = function () {
            return vm.insIsDisabled || vm.insIsAddressDisabled;
        }

        vm.getInstitutions = function(value) {
            var url = api_institution_search.replace('{0}', value);
            return getItems(url);
        }

        function getItems(url) {
            var items = [];

            return httpService.get(url, { disable_loading: true })
                .then(function (response) {
                    response.data.forEach(function (item) {
                        items.push(item);
                    });
                    return items;
                });
        }


        // LANGUAGE
        vm.langAddBtnDisabled = true;
        vm.langSelectedItem = null;
        vm.langItems = [];
        vm.langSelect = function langSelect(item) {
            vm.langSelectedItem = item;
            vm.langAddBtnDisabled = false;
        }
        vm.langAdd = function langAdd() {
            vm.langItems.push(vm.langSelectedItem);
            vm.langAddBtnDisabled = true;
            vm.langSelectedItem = null;
        }
        vm.langRemove = function langRemove(index) {
            vm.langItems.splice(index, 1);
        }
        vm.getLanguageType = function getLanguageType(value) {
            return getObjectType(value, 8);
        }
        function getObjectType(value, type) {
            var url = api_propertyvalues_search.replace('{propertyId:int?}', type).replace('{keyword?}', value);
            return getItems(url);
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('ELearningModuleController', ELearningModuleController);
    ELearningModuleController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
       '$timeout', 'formConfig'];

    function ELearningModuleController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
       $timeout, formConfig) {
        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;

        function init() {
            //type 1 diabetes
            type1DiabeticPregnency();
            type1TreatingDiabetes();
            type1ManagingDiabetes();
            type1OptimisingManagementDiabetes();

            //type 2 diabetes
            type2UpdateOnTreatmentOptions();
            type2AnsweringFAQ();
            type2IntensifyingInsulinTherapy();
            type2PracticalGuidanceInsulinTherapy();
            type2ChronicKidneyDisease();
            type2OptimisingTreatment();

            $timeout(function () {
                $('.carousel').carousel();                
            }, 0);
        }

        function type1DiabeticPregnency() {
            var imagePath = formConfig.s3BucketUrl + '/webinars/Type 1 Diabetes/Diabetic pregnancy -before during and after/Carousel/';
            loadCarouselImages(imagePath).then(function (result) {
                vm.model.type1DiabeticPregnency = {};
                vm.model.type1DiabeticPregnency.images = result.data;
                vm.model.type1DiabeticPregnency.carouselId = 't1m3';
                vm.model.type1DiabeticPregnency.pdfTitle = 'Diabetic pregnency-before during and after - Accompanying PDF';
                vm.model.type1DiabeticPregnency.videoUrl = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 1 Diabetes/Diabetic pregnancy -before during and after/T1M3_Ward6_FinalEdit.mp4';
                vm.model.type1DiabeticPregnency.videoPoster = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 1 Diabetes/Diabetic pregnancy -before during and after/T1M3_poster.jpg';
                vm.model.type1DiabeticPregnency.videoTitle = 'Diabetic pregnency-before during and after';
                vm.model.type1DiabeticPregnency.videoId = 'video_t1m3';
            });
        }

        function type1TreatingDiabetes() {
            var imagePath = formConfig.s3BucketUrl + '/webinars/Type 1 Diabetes/Diagnosing and treating type 1 diabetes/Carousel/';
            loadCarouselImages(imagePath).then(function (result) {
                vm.model.type1TreatingDiabetes = {};
                vm.model.type1TreatingDiabetes.images = result.data;
                vm.model.type1TreatingDiabetes.carouselId = 't1m2';
                vm.model.type1TreatingDiabetes.pdfTitle = 'Diagnosing and treating type 1 diabetes - Accompanying PDF';
                vm.model.type1TreatingDiabetes.videoUrl = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 1 Diabetes/Diagnosing and treating type 1 diabetes/T1M2_FINAL VID FROM VIOCORP Ward6_top-tailed.mp4';
                vm.model.type1TreatingDiabetes.videoPoster = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 1 Diabetes/Diagnosing and treating type 1 diabetes/T1M2_poster.jpg';
                vm.model.type1TreatingDiabetes.videoTitle = 'Diagnosing and treating type 1 diabetes';
                vm.model.type1TreatingDiabetes.videoId = 'video_t1m2';
            });
        }

        function type1ManagingDiabetes() {
            var imagePath = formConfig.s3BucketUrl + '/webinars/Type 1 Diabetes/Managing type 1 diabetes in adolescents/Carousel/';
            loadCarouselImages(imagePath).then(function (result) {
                vm.model.type1ManagingDiabetes = {};
                vm.model.type1ManagingDiabetes.images = result.data;
                vm.model.type1ManagingDiabetes.carouselId = 't1m4';
                vm.model.type1ManagingDiabetes.pdfTitle = 'Managing type 1 diabetes in adolescents - Accompanying PDF';
                vm.model.type1ManagingDiabetes.videoUrl = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 1 Diabetes/Managing type 1 diabetes in adolescents/T1M4_ward6novowebinar20160505odv1-960x540-1-6-mbps.mp4';
                vm.model.type1ManagingDiabetes.videoPoster = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 1 Diabetes/Managing type 1 diabetes in adolescents/T1M4_poster.jpg';
                vm.model.type1ManagingDiabetes.videoTitle = 'Managing type 1 diabetes in adolescents';
                vm.model.type1ManagingDiabetes.videoId = 'video_t1m4';
            });
        }

        function type1OptimisingManagementDiabetes() {
            var imagePath = formConfig.s3BucketUrl + '/webinars/Type 1 Diabetes/Optimising management and relationships with type 1 diabetes patients and HCPs/Carousel/';
            loadCarouselImages(imagePath).then(function (result) {
                vm.model.type1OptimisingDiabetes = {};
                vm.model.type1OptimisingDiabetes.images = result.data;
                vm.model.type1OptimisingDiabetes.carouselId = 't1m1';
                vm.model.type1OptimisingDiabetes.pdfTitle = 'Optimising management and relationships with type 1 diabetes patients and HCPs - Accompanying PDF';
                vm.model.type1OptimisingDiabetes.videoUrl = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 1 Diabetes/Optimising management and relationships with type 1 diabetes patients and HCPs/T1M1_20130514_WARD6_isky-edit.mp4';
                vm.model.type1OptimisingDiabetes.videoPoster = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 1 Diabetes/Optimising management and relationships with type 1 diabetes patients and HCPs/T1M1_poster.jpg';
                vm.model.type1OptimisingDiabetes.videoTitle = 'Optimising management and relationships with type 1 diabetes patients and HCPs';
                vm.model.type1OptimisingDiabetes.videoId = 'video_t1m1';
            });
        }

        function type2UpdateOnTreatmentOptions() {
            var imagePath = formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/An update on treatment options for type 2 diabetes/Carousel/';
            loadCarouselImages(imagePath).then(function (result) {
                vm.model.type2TreatmentOptionsUpdate = {};
                vm.model.type2TreatmentOptionsUpdate.images = result.data;
                vm.model.type2TreatmentOptionsUpdate.carouselId = 't2m1';
                vm.model.type2TreatmentOptionsUpdate.pdfTitle = 'An update on treatment options for type 2 diabetes - Accompanying PDF';
                vm.model.type2TreatmentOptionsUpdate.videoUrl = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/An update on treatment options for type 2 diabetes/T2M1_1959_128267_55391_mp4med.mp4';
                vm.model.type2TreatmentOptionsUpdate.videoPoster = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/An update on treatment options for type 2 diabetes/T2M1_poster.jpg';
                vm.model.type2TreatmentOptionsUpdate.videoTitle = 'An update on treatment options for type 2 diabetes';
                vm.model.type2TreatmentOptionsUpdate.videoId = 'video_t2m1';
            });
        }

        function type2AnsweringFAQ() {
            var imagePath = formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Answering your frequently asked questions in type 2 diabetes/Carousel/';
            loadCarouselImages(imagePath).then(function (result) {
                vm.model.type2AnsweringFAQModel = {};
                vm.model.type2AnsweringFAQModel.images = result.data;
                vm.model.type2AnsweringFAQModel.carouselId = 't2m4';
                vm.model.type2AnsweringFAQModel.pdfTitle = 'Answering your frequently asked questions in type 2 diabetes - Accompanying PDF';
                vm.model.type2AnsweringFAQModel.videoUrl = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Answering your frequently asked questions in type 2 diabetes/T2M4_1959_155511_39578_MP4HIGH.mp4';
                vm.model.type2AnsweringFAQModel.videoPoster = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Answering your frequently asked questions in type 2 diabetes/T2M4_poster.jpg';
                vm.model.type2AnsweringFAQModel.videoTitle = 'Answering your frequently asked questions in type 2 diabetes';
                vm.model.type2AnsweringFAQModel.videoId = 'video_t2m4';
            });
        }

        function type2IntensifyingInsulinTherapy() {
            var imagePath = formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Initiating and intensifying insulin therapy/Carousel/';
            loadCarouselImages(imagePath).then(function (result) {
                vm.model.type2IntensifyingInsulinTherapyModel = {};
                vm.model.type2IntensifyingInsulinTherapyModel.images = result.data;
                vm.model.type2IntensifyingInsulinTherapyModel.carouselId = 't2m2';
                vm.model.type2IntensifyingInsulinTherapyModel.pdfTitle = 'Initiating and intensifying insulin therapy - Accompanying PDF';
                vm.model.type2IntensifyingInsulinTherapyModel.videoUrl = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Initiating and intensifying insulin therapy/T2M2_1959_130263_65211_mp4med.mp4';
                vm.model.type2IntensifyingInsulinTherapyModel.videoPoster = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Initiating and intensifying insulin therapy/T2M2_poster.jpg';
                vm.model.type2IntensifyingInsulinTherapyModel.videoTitle = 'Initiating and intensifying insulin therapy';
                vm.model.type2IntensifyingInsulinTherapyModel.videoId = 'video_t2m2';
            });
        }

        function type2PracticalGuidanceInsulinTherapy() {
            var imagePath = formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Introducing Insulin - practical guidance for initiating insulin therapy/Carousel/';
            loadCarouselImages(imagePath).then(function (result) {
                vm.model.type2PracticalGuidanceInsulinTherapyModel = {};
                vm.model.type2PracticalGuidanceInsulinTherapyModel.images = result.data;
                vm.model.type2PracticalGuidanceInsulinTherapyModel.carouselId = 't2m5';
                vm.model.type2PracticalGuidanceInsulinTherapyModel.pdfTitle = 'Introducing Insulin - practical guidance for initiating insulin therapy - Accompanying PDF';
                vm.model.type2PracticalGuidanceInsulinTherapyModel.videoUrl = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Introducing Insulin - practical guidance for initiating insulin therapy/T2M5_novo-nordisk-changing-diabetes.mp4';
                vm.model.type2PracticalGuidanceInsulinTherapyModel.videoPoster = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Introducing Insulin - practical guidance for initiating insulin therapy/T2M5_poster.jpg';
                vm.model.type2PracticalGuidanceInsulinTherapyModel.videoTitle = 'Introducing Insulin - practical guidance for initiating insulin therapy';
                vm.model.type2PracticalGuidanceInsulinTherapyModel.videoId = 'video_t2m5';
            });
        }

        function type2ChronicKidneyDisease() {
            var imagePath = formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Management of chronic kidney disease in diabetes/Carousel/';
            loadCarouselImages(imagePath).then(function (result) {
                vm.model.type2ChronicKidneyDiseaseModel = {};
                vm.model.type2ChronicKidneyDiseaseModel.images = result.data;
                vm.model.type2ChronicKidneyDiseaseModel.carouselId = 't2m3';
                vm.model.type2ChronicKidneyDiseaseModel.pdfTitle = 'Management of chronic kidney disease in diabetes - Accompanying PDF';
                vm.model.type2ChronicKidneyDiseaseModel.videoUrl = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Management of chronic kidney disease in diabetes/T2M3_1959_132768_49913_mp4med.mp4';
                vm.model.type2ChronicKidneyDiseaseModel.videoPoster = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Management of chronic kidney disease in diabetes/T2M3_poster.jpg';
                vm.model.type2ChronicKidneyDiseaseModel.videoTitle = 'Management of chronic kidney disease in diabetes';
                vm.model.type2ChronicKidneyDiseaseModel.videoId = 'video_t2m3';
            });
        }

        function type2OptimisingTreatment() {
            var imagePath = formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Premix in practice Optimising treatment in type 2 diabetes/Carousel/';
            loadCarouselImages(imagePath).then(function (result) {
                vm.model.type2OptimisingTreatmentModel = {};
                vm.model.type2OptimisingTreatmentModel.images = result.data;
                vm.model.type2OptimisingTreatmentModel.carouselId = 't2m6';
                vm.model.type2OptimisingTreatmentModel.pdfTitle = 'Premix in practice Optimising treatment in type 2 diabetes - Accompanying PDF';
                vm.model.type2OptimisingTreatmentModel.videoUrl = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Premix in practice Optimising treatment in type 2 diabetes/T2M6_Video for archive NODA11249.mp4';
                vm.model.type2OptimisingTreatmentModel.videoPoster = 'https://' + formConfig.s3BucketUrl + '/webinars/Type 2 Diabetes/Premix in practice Optimising treatment in type 2 diabetes/T2M6_poster.jpg';
                vm.model.type2OptimisingTreatmentModel.videoTitle = 'Premix in practice Optimising treatment in type 2 diabetes';
                vm.model.type2OptimisingTreatmentModel.videoId = 'video_t2m6';
            });
        }

        function loadCarouselImages(imagePath) {
            var imageListFileName = 'imgList.txt';
            var url = api_webinar_loadImages.replace('{0}', imagePath).replace('{1}', imageListFileName);
            return httpService.get(url)
            .then(function (response) {
                return response.data;
            });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('ResourceController', ResourceController);
    ResourceController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
       '$timeout', 'formConfig', '$sce'];

    function ResourceController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
       $timeout, formConfig, $sce) {
        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;
        vm.errors = [];
        var resourceTypes = [];
        vm.setRedirectAction = setRedirectAction;
        vm.countResouceForEachResourceType = countResouceForEachResourceType;

        function init() {
            getResources();
            getResourceTypes();
        }

        function getResources() {
            var resourceTypes = "";
            if (formConfig.isHCPUser.toLowerCase() == "true") {
                resourceTypes = formConfig.hcpResourceTypes;
            }
            else {
                resourceTypes = formConfig.adminResourceTypes;
            }

            return httpService.get(api_resource_getAllResources.replace('{0}', resourceTypes)).success(function (response) {
                vm.model.resources = response;
                assignResourceUrlToTrustedUrl(response);
            });
        };

        function getResourceTypes() {
            return httpService.get(api_lookupValue_getResourceLookupValues.replace('{isPublicFacing}', 'true'))
                .success(function (response) {
                    vm.model.resourceTypes = response;
                    if (formConfig.isHCPUser.toLowerCase() == 'true') {
                        for (var i = 0; i < vm.model.resourceTypes.length; i++) {
                            if (vm.model.resourceTypes[i].value == formConfig.novoNordiskStaff) {
                                vm.model.resourceTypes.splice(i, 1);
                            }
                        }
                    }
                });
        }

        function assignResourceUrlToTrustedUrl(response) {
            angular.forEach(response,
                function (item) {
                    item.videoUrl = $sce.trustAsResourceUrl(item.url);
                });
        }

        function countResouceForEachResourceType(resourceTypeId) {
            if (vm.model.resources) {
                for (var i = 0; i < vm.model.resources.length; i++) {
                    if (vm.model.resources[i].type == resourceTypeId)
                        return true;
                }
            }
            return false;
        }

        //pause the video when modal is closed
        $('body').on('hidden.bs.modal', '.modal', function () {
            $('video').trigger('pause');
        });
    }
})();;
(function () {
    'use strict';

    window.app.controller('DashboardHCPController', DashboardHCPController);
    DashboardHCPController.$inject = ['$scope', '$rootScope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService', 'moment', 'formConfig'];

    function DashboardHCPController($scope, $rootScope, $window, modelStateErrorBuilder, utilitySvc, httpService, moment, formConfig) {
        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;

        function init() {
            upComingEventHCP();
            getHcpEventInvitations();
            getHcpTotalEventsAttended();
            if (formConfig.isHcpCdeDiabetesRegistrationApproved)
                getHcpCdeLastInvoiceDetails();
            if (formConfig.isCde.toLowerCase() == 'true')
                getLatestCdeTrainingDetails();
        }

        function upComingEventHCP() {
            var url = api_events_getNextUpcomingEventForHCP.replace('{userId}', formConfig.userId);
            var clientBrowserDate = moment().format('DD/MM/YYYY');
            url = url.replace('{0}', clientBrowserDate);

            httpService.get(url)
		    .success(function (response) {
		        vm.model.hcpUpcomingEvent = response;
		        if (vm.model.hcpUpcomingEvent != null && vm.model.hcpUpcomingEvent.eventDate != null)
		            vm.model.hcpUpcomingEvent.eventDate = moment(vm.model.hcpUpcomingEvent.eventDate).format('DD MMMM YYYY');
		    });
        }

        function getHcpEventInvitations() {
            var url = api_events_getHcpEventInvitations.replace('{userId}', formConfig.userId);
            var clientBrowserDate = moment().format('DD/MM/YYYY');
            url = url.replace('{0}', clientBrowserDate);

            httpService.get(url)
		    .success(function (response) {
		        vm.model.hcpEventInvite = response;

		        if (vm.model != null) {
		            angular.forEach(vm.model.hcpEventInvite, function (item) {
		                if (item.eventDate != null)
		                    item.eventDate = moment(item.eventDate).format('DD MMMM YYYY');
		            });
		        }
		    });
        }

        function getHcpCdeLastInvoiceDetails() {
            var url = api_events_getHcpCdeInvoiceDetails.replace('{userId}', formConfig.userId);

            httpService.get(url)
		    .success(function (response) {
		        vm.model.cdeLastInvoiceDetails = response;

		        if (vm.model != null) {
		            if (vm.model.cdeLastInvoiceDetails != null)
		                vm.model.cdeLastInvoiceDetails.invoiceSubmittedDate = moment.utc(vm.model.cdeLastInvoiceDetails.invoiceSubmittedDate).local().format('DD MMMM YYYY');
		        }
		    });
        }

        function getHcpTotalEventsAttended() {
            var url = api_events_getHcpTotalEventsAttended.replace('{userId}', formConfig.userId);

            httpService.get(url)
		    .success(function (response) {
		        vm.model.hcpTotalEventsAttended = response;
		    });
        }

        function getLatestCdeTrainingDetails() {
            httpService.get(api_cdeTrainingDetails_getLatestCdeTrainingDetails)
            .then(function (response) {
                if (response.data.success) {
                    vm.trainingDetails = response.data.data;                    
                    displayTrainingDetails(vm.trainingDetails);
                }
            });
        }

        function displayTrainingDetails(trainingDetails) {
            var today = moment();
            vm.isPVTrainingExist = false;
            vm.isHHTrainingExist = false;
            vm.isSaxendaTrainingExist = false;
            angular.forEach(trainingDetails, function (item) {
                var isTrainingDueOnLessthanTwoMonths = (today >= moment.utc(item.trainingDueOn).local().subtract(2, 'months')) ? true : false;
                if (item.trainingId == formConfig.pvTrainingId) {
                    vm.isPVTrainingExist = true;
                    if (isTrainingDueOnLessthanTwoMonths || item.trainingCompletedOn == null) {
                        vm.pvDate = moment(item.trainingDueOn).format('DD/MM/YYYY');
                        vm.displayPVDueDate = true;
                    }
                    else if (item.trainingCompletedOn != null) {
                        vm.pvDate = moment(item.trainingCompletedOn).format('DD/MM/YYYY');
                        vm.displayPVDueDate = false;
                    }
                }
                else if (item.trainingId == formConfig.hhTrainingId) {
                    vm.isHHTrainingExist = true;
                    if (isTrainingDueOnLessthanTwoMonths || item.trainingCompletedOn == null) {
                        vm.hhDate = moment(item.trainingDueOn).format('DD/MM/YYYY');
                        vm.displayhhDueDate = true;
                    }
                    else if (item.trainingCompletedOn != null) {
                        vm.hhDate = moment(item.trainingCompletedOn).format('DD/MM/YYYY');
                        vm.displayhhDueDate = false;
                    }
                }
                else if (item.trainingId == formConfig.saxendaTrainingId) {
                    vm.isSaxendaTrainingExist = true;
                    if (isTrainingDueOnLessthanTwoMonths || item.trainingCompletedOn == null) {
                        vm.saxendaDate = moment(item.trainingDueOn).format('DD/MM/YYYY');
                        vm.displaySaxendaDueDate = true;
                    }
                    else if (item.trainingCompletedOn != null) {
                        vm.saxendaDate = moment(item.trainingCompletedOn).format('DD/MM/YYYY');
                        vm.displaySaxendaDueDate = false;
                    }
                }
            });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('DashboardSuperUserController', DashboardSuperUserController);
    DashboardSuperUserController.$inject = ['$scope', '$rootScope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService', 'moment', 'formConfig'];

    function DashboardSuperUserController($scope, $rootScope, $window, modelStateErrorBuilder, utilitySvc, httpService, moment, formConfig) {
        var vm = this;
        vm.model = vm.model || {};
        vm.model.updateRegistrations = null;
        vm.model.updateAccommodations = null;
        vm.model.updateFlights = null;
        vm.model.updateAttendances = null;
        vm.model.total = null;
        var browserDate = moment().format('DD/MM/YYYY');

        vm.init = function () {
            httpService.get(api_dashboard_searchUpdateRegistration.replace('{0}', browserDate))
             .success(function (data) {
                 if (data.data.length > 0) {
                     vm.model.updateRegistrations = data.data;
                     angular.forEach(vm.model.updateRegistrations, function (item) {
                         if (item.firstDate != null)
                             item.firstDate = moment(item.firstDate).format('DD MMMM YYYY');
                     });
                 }
             });

            httpService.get(api_dashboard_searchUpdateAccommodation.replace('{0}', browserDate))
            .success(function (data) {
                if (data.data.length > 0) {
                    vm.model.updateAccommodations = data.data;
                    angular.forEach(vm.model.updateAccommodations, function (item) {
                        if (item.firstDate != null)
                            item.firstDate = moment(item.firstDate).format('DD MMMM YYYY');
                    });
                }
            });

            httpService.get(api_dashboard_searchUpdateFlights.replace('{0}', browserDate))
            .success(function (data) {
                if (data.data.length > 0) {
                    vm.model.updateFlights = data.data;
                    angular.forEach(vm.model.updateFlights, function (item) {
                        if (item.firstDate != null)
                            item.firstDate = moment(item.firstDate).format('DD MMMM YYYY');
                    });
                }
            });

            httpService.get(api_dashboard_searchUpdateAttendance.replace('{0}', browserDate))
            .success(function (data) {
                if (data.data.length > 0) {
                    vm.model.updateAttendances = data.data;
                    angular.forEach(vm.model.updateAttendances, function (item) {
                        if (item.firstDate != null)
                            item.firstDate = moment(item.firstDate).format('DD MMMM YYYY');
                    });
                }
            });

            httpService.get(api_dashboard_getTotalStatistics.replace('{0}', browserDate))
            .success(function (data) {
                if (data.data != null) {
                    vm.model.total = data.data;
                }
            });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('DashboardSystemAdminController', DashboardSystemAdminController);
    DashboardSystemAdminController.$inject = ['$scope', '$rootScope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService', 'moment', 'formConfig'];

    function DashboardSystemAdminController($scope, $rootScope, $window, modelStateErrorBuilder, utilitySvc, httpService, moment, formConfig) {
        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;

        function init() {
            getPendingChangingDiabetesRegistrationsCount();
            getPendingHelpingHandsRegistrationsCount();
            getPendingInvoicesCount();
            getApprovedChangingDiabetesRegistrationsCount();
            getApprovedHelpingHandsDoctorsCount();
            getApprovedHelpingHandsCDECount();            
        }

        function getPendingChangingDiabetesRegistrationsCount() {
            httpService.get(api_dashboard_pendingChangingDiabetesRegistrationsCount)
		    .success(function (response) {
		        vm.model.pendingChangingDiabetesRegistrationsCount = response;
		    });
        }

        function getPendingHelpingHandsRegistrationsCount() {
            httpService.get(api_dashboard_pendingHelpingHandsRegistrationsCount)
		    .success(function (response) {
		        vm.model.pendingHelpingHandsRegistrationsCount = response;
		    });
        }

        function getPendingInvoicesCount() {
            httpService.get(api_dashboard_pendingInvoicesCount)
		    .success(function (response) {
		        vm.model.pendingInvoicesCount = response;
		    });
        }

        function getApprovedChangingDiabetesRegistrationsCount() {
            httpService.get(api_dashboard_approvedChangingDiabetesRegistrationsCount)
		    .success(function (response) {
		        vm.model.approvedChangingDiabetesRegistrationsCount = response;
		    });
        }

        function getApprovedHelpingHandsDoctorsCount() {
            httpService.get(api_dashboard_approvedHelpingHandsDoctorsCount)
		    .success(function (response) {
		        vm.model.approvedHelpingHandsDoctorsCount = response;
		    });
        }

        function getApprovedHelpingHandsCDECount() {
            httpService.get(api_dashboard_approvedHelpingHandsCDECount)
		    .success(function (response) {
		        vm.model.approvedHelpingHandsCDECount = response;
		    });
        }
    }
})();
;
(function () {
    'use strict';

    window.app.controller('LeftHandUpcomingEventsController', LeftHandUpcomingEventsController);
    LeftHandUpcomingEventsController.$inject = ['$scope', '$rootScope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService', 'moment', 'formConfig'];


    function LeftHandUpcomingEventsController($scope, $rootScope, $window, modelStateErrorBuilder, utilitySvc, httpService, moment, formConfig) {
        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;

        function init() {            
            getTopUpcomingEvents();                    
        }

        function getTopUpcomingEvents() {
            var url = '';
            if (formConfig.userRole.toLowerCase() == 'systemadmin' || formConfig.userRole.toLowerCase() == 'superuser')
                url = api_events_getTopThreeUpcomingEvents;
            else if (formConfig.userRole.toLowerCase() == 'hcp')
                url = api_events_getUpcomingEventForHCP.replace('{userId}', formConfig.userId);

            var clientBrowserDate = moment().format('DD/MM/YYYY');
            url = url.replace('{0}', clientBrowserDate);

            httpService.get(url)
		    .success(function (response) {
		        vm.model = response;
		        
		        if (vm.model != null) {
		            angular.forEach(vm.model, function (item) {
		                if (item.eventDate != null)
		                    item.eventDate = moment(item.eventDate).format('DD MMMM YYYY');
		            });
		        }

		        if (vm.model != null) {
		            if (vm.model.length >= 1) {
		                vm.model.eventVenue1 = vm.model[0];
		            }
		            if (vm.model.length >= 2) {
		                vm.model.eventVenue2 = vm.model[1];
		            }
		            if (vm.model.length >= 3) {
		                vm.model.eventVenue3 = vm.model[2];
		            }
		        }
		    });
        }
    }
    })();;
(function () {
    'use strict';

    window.app.controller('PatientAddController', PatientAddController);
    PatientAddController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout'];

    function PatientAddController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout) {
        var vm = this;
        vm.isValidSaxenda = true;
        vm.activeTabIndex = 0;
        vm.submit = submit;
        vm.addProgram = addProgram;
        vm.chooseAnswers = chooseAnswers;
        vm.getTab = getTab;
        vm.patientId = 0;
        vm.patientProgramId = 0;
        vm.backToPatientDetail = backToPatientDetail;
        vm.redirectPatientVisitPage = redirectPatientVisitPage;
        vm.onChangeEmailAddPatient = onChangeEmail;
        vm.model = vm.model || {};
        vm.init = init;
        vm.errors = [];
        vm.model.email = '';
        vm.remainingMinutes = 0;
        vm.isCaculate = false;
        vm.isFromPatientVisit = false;
        vm.isEditProgram = false;
        vm.material = true;
        vm.dateFormat = 'dd/MM/yyyy';
        vm.diabetesProgramId = 0;
        vm.obesityProgramId = 0;
        vm.tabPrimaryId = true;
        vm.tabSecondId = false;
        vm.tabThirdId = false;
        vm.doctorId = 0;
        vm.institutionId = 0;
        vm.isSearchInstitution = true;
        vm.isSearchDoctor = true;
        //Variables for institution, doctor - Diabetes
        vm.doctorDiabetesIsSearchDisabled = false;
        vm.isDoctorDiabetesFormDisabled = false;
        vm.diabetesInstitutionIsSearchDisabled = false;
        vm.diabetesInstitutionFormDisabled = true;
        vm.diabetesInstitutionAddressFormDisabled = true;
        vm.diabetesInstitutionAddressRequired = false;
        vm.diabetesInstitutionButtonsDisabled = true;
        vm.diabetesSuburbStatePostcodeDisabled = true;

        var dobRegex = /^\d{2}\/\d{2}\/\d{4}/;
        //End
        var acceptTypes = ['image/jpeg', 'image/jpg', 'application/pdf'];
        function init() {

            vm.model.hasLearningDifficulties = false;
            vm.model.hasMentalHealthDifficulties = false;
            vm.model.hasElderlyDifficulties = false;
            vm.model.hasLanguageBarrier = false;
            vm.model.hasDisability = false;
            vm.materialProvided = true;

            $('.date-picker').datepicker({
                orientation: "left",
                autoclose: true,
                endDate: '+0d',
                format: "dd/mm/yyyy"
            });
            initLookups();
            $('#toggle-hasMentalHealthDifficulties').change(function () {
                vm.model.hasMentalHealthDifficulties = $(this).prop('checked');
            });
            $('#toggle-hasElderlyDifficulties').change(function () {
                vm.model.hasElderlyDifficulties = $(this).prop('checked');
            });
            $('#toggle-hasLanguageBarrier').change(function () {
                vm.model.hasLanguageBarrier = $(this).prop('checked');
            });
            $('#toggle-hasDisability').change(function () {
                vm.model.hasDisability = $(this).prop('checked');
            });

            // For Add program Diabetes
            $('#toggle-isFlexPen').change(function () {
                vm.addDiabetes.isFlexPen = $(this).prop('checked');
            });
            $('#toggle-isNovoPen4').change(function () {
                vm.addDiabetes.isNovoPen4 = $(this).prop('checked');
            });
            $('#toggle-isNovoPenEcho').change(function () {
                vm.addDiabetes.isNovoPenEcho = $(this).prop('checked');
            });
            $('#toggle-notRequired').change(function () {
                vm.addDiabetes.isDeviceNotRequired = $(this).prop('checked');
            });

            // For Add Visit Diabetes
            $('#toggle-isDeviceEducation').change(function () {
                vm.educationDeviceProvided = $(this).prop('checked');
            });
            $('#toggle-isPhysicianCustom').change(function () {
                vm.educationPhysicianPlanProvided = $(this).prop('checked');
            });
            $('#toggle-isNovoMix30').change(function () {
                vm.educationPatientLedTitrationProvided = $(this).prop('checked');
            });
            $('#toggle-isSickDay').change(function () {
                vm.educationSickDayAdviceProvided = $(this).prop('checked');
            });
        }
        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                console.log(data);
                var typeInt = data.PatientProgramVisit_InteractionType;
                var lengthInt = data.PatientProgramVisit_InteractionLength;
                //vm.titles = data.Title;
                vm.titles = formConfig.titlesToPopulate;
                vm.states = data.State;
                vm.typeInteractions = typeInt;
                vm.lengthInteractions = lengthInt;
                vm.interactionType = vm.typeInteractions[0].Value;
                vm.interactionLength = vm.lengthInteractions[0].Value;
                for (var i = 0; i < typeInt.length; i++) {
                    if (typeInt[i].Name == 'In person') {
                        vm.typePerson = typeInt[i];
                    }
                }
                for (var i = 0; i < lengthInt.length; i++) {
                    if (lengthInt[i].Name == '60') {
                        vm.lengthInt = lengthInt[i];
                    }
                }
            });
            initialLookupAddProgram();
            initialProductProgram();
        }
        function chooseAnswers(e) {
            if (e.target.value == 'true') {
                vm.model.hasLearningDifficulties = true;
                $('#answerFields').removeClass('hidden');
            } else {
                vm.model.hasLearningDifficulties = false;
                $('#answerFields').addClass('hidden');
            }
        }
        function submit(form) {
            vm.model.dateOfBirth_error = false;
            BeforeSubmit();
            clearSatusSubmitTab();
            vm.tabPrimaryId = true;
            var url = api_addPatientDetail;
            if (vm.patientId > 0) {
                url = api_editPatientDetail;
                vm.model.patientId = vm.patientId;
            }
            if (isFormAddPatientValid(form)) {
                httpService.post(url, vm.model)
                    .then(function (response) {
                        vm.errors = [];
                        vm.errors = response.data.errors;
                        if (response.data.errors.length > 0) {
                            $("#dateOfBirth").datepicker("setDate", moment(vm.model.dateOfBirth).format('DD/MM/YYYY'));
                            modelStateErrorBuilder.build(vm.errors, vm.model);
                        } else {
                            $("#dateOfBirth").datepicker("setDate", moment(vm.model.dateOfBirth).format('DD/MM/YYYY'));
                            vm.patientId = response.data.data;
                            //if (vm.patientId > 0) {
                            //    getCurrentTab();
                            //}
                            redirectMyPatientPage();
                        }
                        scrollToTop();
                    });
            } else {
                $timeout(function () {
                    if (vm.model.dateOfBirth != null && vm.model.dateOfBirth != "" && vm.model.dateOfBirth != "Invalid date") {
                        if (dobRegex.test(moment(vm.model.dateOfBirth).format('DD/MM/YYYY')))
                            $("#dateOfBirth").datepicker("setDate", moment(vm.model.dateOfBirth).format('DD/MM/YYYY'));
                    }
                }, 0);
                scrollToTop();
            }
        }

        function clearSatusSubmitTab() {
            vm.tabPrimaryId = false;
            vm.tabSecondId = false;
            vm.tabThirdId = false;
        }
        function addProgram(form) {
            vm.model.dateOfBirth_error = false;
            BeforeSubmit();
            clearSatusSubmitTab();
            vm.tabPrimaryId = true;

            var url = api_addPatientDetail;
            if (vm.patientId > 0) {
                url = api_editPatientDetail;
                vm.model.patientId = vm.patientId;
            }
            if (isFormAddPatientValid(form)) {
                httpService.post(url, vm.model)
                    .then(function (response) {
                        vm.errors = [];
                        vm.errors = response.data.errors;
                        if (response.data.errors.length > 0) {
                            $("#dateOfBirth").datepicker("setDate", moment(vm.model.dateOfBirth).format('DD/MM/YYYY'));
                            modelStateErrorBuilder.build(vm.errors, vm.model);
                        } else {
                            vm.errors = [];
                            $("#dateOfBirth").datepicker("setDate", moment(vm.model.dateOfBirth).format('DD/MM/YYYY'));
                            if (vm.patientId <= 0) {
                                vm.patientId = response.data.data;
                            }
                            form.$invalid = false;
                            getCurrentTab();
                        }
                        scrollToTop();
                    });
            } else {
                $timeout(function () {
                    if (vm.model.dateOfBirth != null && vm.model.dateOfBirth != "" && vm.model.dateOfBirth != "Invalid date") {
                        if (dobRegex.test(moment(vm.model.dateOfBirth).format('DD/MM/YYYY')))
                            $("#dateOfBirth").datepicker("setDate", moment(vm.model.dateOfBirth).format('DD/MM/YYYY'));
                    }
                }, 0);
                scrollToTop();
            }
        }

        function isFormAddPatientValid(form) {
            vm.errors = [];
            var isValid = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addRequireError("All fields highlighted in red are mandatory");;
                isValid = false;
            }

            if (vm.model.email != "" && !isEmail(vm.model.email)) {
                addRequireError("Please specify a valid email");
                isValid = false;
            }

            if (vm.model.hasLearningDifficulties === true && vm.model.hasMentalHealthDifficulties === false &&
             vm.model.hasElderlyDifficulties === false && vm.model.hasLanguageBarrier === false && vm.model.hasDisability === false) {
                addRequireError("At least 1 learning difficulty must be selected");
                isValid = false;
            }

            var dob = $("#dateOfBirth").val();
            if (dob != null && dob.length > 0) {
                if (!dobRegex.test(dob)) {
                    vm.errors.push({
                        key: 'Invalid_Dob',
                        message: "Please supply valid format for date of birth (dd/mm/yyyy)"
                    });
                    vm.model.dateOfBirth_error = true;
                    isValid = false;
                }
            }

            //var birthDay = new Date(vm.model.dateOfBirth);
            //if (birthDay < new Date(1800, 1, 1)) {
            //    addRequireError("You must choose a valid birthday");
            //    isValid = false;
            //}
            return isValid;
        }

        function getTab(idx) {
            vm.activeTabIndex = idx;
            //$(".nav-tabs > li > a").css("background-color", "gray");
            //$('#' + e + '').css("color", "#FFFFFF");
            //$('#' + e + '').css("background-color", "rgba(44, 86, 151, 1)");

        };
        function backToPatientDetail() {
            //$(".nav-tabs > li > a").css("background-color", "gray");
            //$('.nav-tabs a[href="#primary"]').css("color", "#FFFFFF");
            //$('.nav-tabs a[href="#primary"]').css("background-color", "rgba(44, 86, 151, 1)");
            $('#btnSavePatient').html('Save patient');
            $('.nav-tabs a[href="#primary"]').tab('show');

            if (vm.model.dateOfBirth != null && vm.model.dateOfBirth != "" && vm.model.dateOfBirth != "Invalid date") {
                $("#dateOfBirth").datepicker("setDate", moment(vm.model.dateOfBirth).format('DD/MM/YYYY'));
            }

        }
        function BeforeSubmit() {
            var dob = $("#dateOfBirth").val();
            if (dobRegex.test(dob))
                vm.model.dateOfBirth = vm.model.dateOfBirth != null && vm.model.dateOfBirth != "" ? moment($("#dateOfBirth").datepicker('getDate')).format('YYYY-MM-DD') : "";

            if (vm.model.hasLearningDifficulties == false) {
                vm.model.hasMentalHealthDifficulties = false;
                vm.model.hasElderlyDifficulties = false;
                vm.model.hasLanguageBarrier = false;
                vm.model.hasDisability = false;
            }
            if (vm.model.suburb === undefined || vm.model.suburb === null)
                vm.model.suburb = '';
        }

        function getCurrentTab() {
            //$(".nav-tabs > li > a").css("background-color", "gray");
            //$('.nav-tabs a[href="#second"]').css("background-color", "rgba(44, 86, 151, 1)");
            $('.nav-tabs a[href="#second"]').tab('show');
            vm.activeTabIndex = 1;
        }

        /*ADD PROGRAM DIABETES -->*/
        vm.showDiabeteProgram = function () {
            vm.isShowDiabeteProgram = true;
            vm.errors = [];
            vm.addDiabetes.dmTypeId = "3"; // set the default when showing diabetes program
            scrollToTop();
        }
        vm.addDiabetes = { doctor: {}, diabetesProgramId: 0 };
        vm.addDiabetes.doctor.profile = {};
        vm.addDiabetes.doctor.institutionSelectedIndex = 0;

        vm.addDiabetes.isFlexPen = false;
        vm.addDiabetes.isNovoPen4 = false;
        vm.addDiabetes.isNovoPenEcho = false;
        vm.addDiabetes.isDeviceNotRequired = false;
        vm.addDiabetes.doctor.isInstitutionFormDisabled = true;
        vm.isShowDiabeteProgram = false;
        vm.showDiabetesVisit = showDiabetesVisit;
        vm.isShowDiabeteVisit = false;
        vm.getInstitutions = getInstitutions;
        vm.onSelectInstitution = onSelectInstitution;
        vm.onNewInstitution = onNewInstitution;
        vm.clearInstitution = clearInstitution;
        vm.clearDoctor = clearDoctor;
        vm.onSelectDoctor = onSelectDoctor;
        vm.getDoctorsDiabetes = getDoctorsDiabetes;
        vm.getDoctorsObesity = getDoctorsObesity;
        vm.newDoctor = newDoctor;
        vm.addProgramDiabetes = addProgramDiabetes;
        vm.onChangeEmail = onChangeEmail;
        vm.getDMTType = getDMTType;
        vm.getStatus = getStatus;
        vm.addDiabetes.doctor.disableInstitutionInputs = function () {
            return vm.addDiabetes.doctor.isInstitutionFormDisabled;
        }
        vm.addDiabetes.doctor.requireInstitutionInputs = function () {
            return !vm.addDiabetes.doctor.isInstitutionFormDisabled;
        }
        vm.cancelAddProgramDiabetes = cancelAddProgramDiabetes;
        vm.backAddProgramDiabetes = backAddProgramDiabetes;

        vm.isProgramViewOnly = function () {
            return false;
        }

        vm.IsShowClearDoctor = false;
        vm.IsShowNewDoctor = true;
        vm.IsShowClearInstitution = false;
        vm.IsShowNewInstitution = false;

        function initialLookupAddProgram() {
            httpService.get(api_propertyType_getValue.replace('{id}', formConfig.propertyTye))
          .success(function (data) {
              vm.dmttype = data.DMType.ListOption;
              vm.insulinStatus = data.InsulinStatus.ListOption;
              vm.deviceTrainingRequired = data.DeviceTrainingRequired.ListOption;

              vm.addDiabetes.dmTypeId = data.DMType.ListOption[0].Id;
              vm.addDiabetes.insulinStatusId = data.InsulinStatus.ListOption[0].Id;
          });
        }
        function initialProductProgram() {
            httpService.get(api_propertyType_getProduct.replace('{programId}', formConfig.programHH_PSP_CDE_DiabetesId))
         .success(function (data) {
             angular.forEach(data, function (prod) {
                 prod.isSelected = false;
             });
             vm.products = data;

             vm.addDiabetes.selectedProducts = [];
             angular.copy(data, vm.addDiabetes.selectedProducts);
             vm.addDiabetes.selectedProducts[0].isSelected = true;
         });
        }
        function getInstitutions(value) {
            if (vm.isSearchInstitution) {
                var institutions = [];
                return httpService.get(api_institution_search.replace('{0}', value).replace('{1}', ''), { disable_loading: true })
                    .then(function (response) {
                        response.data.forEach(function (item) {
                            institutions.push(item);
                        });

                        angular.forEach(vm.addDiabetes.institutions, function (item, idx) {
                            if (idx != vm.addDiabetes.doctor.institutionSelectedIndex) {
                                angular.forEach(institutions, function (item2, idx2) {
                                    if (item.name == item2.name)
                                        institutions.splice(idx2, 1);
                                });
                            }
                        });
                        return institutions;
                    });
            }
        }

        vm.disabledSuburbStatePostcode = function () {
            return vm.diabetesSuburbStatePostcodeDisabled;
        }

        vm.disableInputs = function () {
            return vm.diabetesInstitutionAddressFormDisabled;
        }

        vm.requireInputs = function () {
            return vm.diabetesInstitutionAddressRequired;
            //return vm.diabetesInstitutionAddressRequired;
        }


        function onSelectInstitution(item) {
            vm.addDiabetes.doctor.institution = item;
            vm.addDiabetes.doctor.institution.mode = 'select';
            vm.addDiabetes.doctor.isInstitutionFormDisabled = true;
            vm.institutionId = item.id;
            vm.IsShowClearInstitution = true;
            vm.IsShowNewInstitution = true;

            vm.diabetesInstitutionIsSearchDisabled = false;
            vm.diabetesInstitutionFormDisabled = true;
            vm.diabetesInstitutionAddressFormDisabled = true;
            vm.diabetesSuburbStatePostcodeDisabled = true;
            vm.diabetesInstitutionAddressRequired = false;

            //assigning institution address to doctor address
            vm.addDiabetes.doctor.address = item.address;
            vm.addDiabetes.doctor.institution.address = {};
        }

        function onNewInstitution() {
            //if (vm.addDiabetes.doctor.institution != undefined) {
            //    vm.addDiabetes.doctor.institution = { name: "" };
            //    vm.addDiabetes.doctor.institution.mode = 'add';
            //    if (vm.addDiabetes.doctor.institution.address != null) {
            //        vm.addDiabetes.doctor.institution.address = {};
            //    }
            //}

            if (vm.addDiabetes.doctor.institution != null)
                vm.addDiabetes.doctor.institution = null;

            vm.institutionId = 0;
            vm.addDiabetes.doctor.isInstitutionFormDisabled = false;
            vm.isSearchInstitution = false;
            vm.IsShowClearInstitution = true;

            vm.diabetesInstitutionIsSearchDisabled = true;
            vm.diabetesInstitutionFormDisabled = false;
            vm.diabetesInstitutionAddressFormDisabled = false;
            vm.diabetesSuburbStatePostcodeDisabled = false;
            vm.diabetesInstitutionAddressRequired = true;

            vm.addDiabetes.doctor.address = {};
        }
        function clearInstitution(institution) {
            if (institution) {
                vm.addDiabetes.doctor.institution = null;
                //vm.addDiabetes.doctor.institution = {                    
                //    address: {
                //    },
                //    mode: 'add'
                //};
            }
            vm.isSearchInstitution = true;

            vm.addDiabetes.doctor.isInstitutionFormDisabled = true;
            vm.diabetesInstitutionIsSearchDisabled = false;
            vm.diabetesInstitutionFormDisabled = false;
            vm.diabetesInstitutionAddressFormDisabled = true;
            vm.diabetesInstitutionButtonsDisabled = false;
            vm.diabetesSuburbStatePostcodeDisabled = false;
            vm.diabetesInstitutionAddressRequired = false;

            if (vm.addDiabetes.doctor.address != null) {
                vm.addDiabetes.doctor.address = {};
            }
        }

        function getDMTType(e) {
            vm.addDiabetes.dmTypeId = e.target.value;
        }

        function getStatus(e) {
            vm.addDiabetes.InsulinStatusId = e.target.value;
        }

        function newDoctor() {
            vm.addDiabetes.doctor = { lastName: "" };
            vm.addDiabetes.doctor.isInstitutionFormDisabled = false;
            vm.addDiabetes.doctor.mode = 'add';

            vm.IsShowClearDoctor = true;
            vm.IsShowNewDoctor = true;
            vm.IsShowClearInstitution = false;
            vm.IsShowNewInstitution = true;
            vm.doctorId = 0;
            vm.isSearchDoctor = false;

            vm.doctorDiabetesIsSearchDisabled = true;
            vm.isDoctorDiabetesFormDisabled = false;
            vm.diabetesInstitutionIsSearchDisabled = false;
            vm.diabetesInstitutionFormDisabled = false;
            vm.diabetesInstitutionAddressFormDisabled = true;
            vm.diabetesInstitutionButtonsDisabled = false;
            vm.diabetesSuburbStatePostcodeDisabled = false;
            vm.diabetesInstitutionAddressRequired = false;
        }

        function getDoctors(programId, lastName, stateOrSuburb) {
            if (vm.isSearchDoctor == true) {
                var doctors = [];
                var url = api_doctor_search;
                url += '?programId=' + programId;
                url += '&stateOrSuburb=' + stateOrSuburb;
                url += '&lastName=' + lastName;
                return httpService.get(url, { disable_loading: true })
                    .then(function (response) {
                        response.data.forEach(function (item) {
                            doctors.push(item);
                        });
                        return doctors;
                    });
            }
        }

        function getDoctorsByLastName(programId, lastName, stateOrSuburb) {
            if (vm.isSearchDoctor == true) {
                var doctors = [];
                var url = api_search_doctorByName;
                url += '?programId=' + programId;
                url += '&stateOrSuburb=' + stateOrSuburb;
                url += '&lastName=' + lastName;
                return httpService.get(url, { disable_loading: true })
                    .then(function (response) {
                        response.data.forEach(function (item) {
                            doctors.push(item);
                        });
                        return doctors;
                    });
            }
        }

        function getDoctorsDiabetes(lastName) {
            if (vm.addDiabetes.doctor.searchKey == undefined)
                vm.addDiabetes.doctor.searchKey = '';

            return getDoctorsByLastName(formConfig.programHH_PSP_DiabetesId, lastName, vm.addDiabetes.doctor.searchKey);
            //return getDoctors(formConfig.programHH_PSP_DiabetesId, lastName, vm.addDiabetes.doctor.searchKey);
        }

        function getDoctorsObesity(lastName) {
            if (vm.addDiabetes.doctor.searchKey == undefined)
                vm.addDiabetes.doctor.searchKey = '';

            return getDoctorsByLastName(formConfig.programHH_PSP_ObesityId, lastName, vm.addDiabetes.doctor.searchKey);
            //return getDoctors(formConfig.programHH_PSP_ObesityId, lastName, vm.addDiabetes.doctor.searchKey);
        }

        function onSelectDoctor(item) {
            vm.addDiabetes.doctor = item;

            vm.addDiabetes.doctor.mode = 'select';
            vm.addDiabetes.doctor.isInstitutionFormDisabled = true;
            vm.doctorId = item.id;
            vm.IsShowClearDoctor = true;
            vm.IsShowNewDoctor = true;
            vm.IsShowClearInstitution = false;
            vm.IsShowNewInstitution = false;

            vm.isDoctorDiabetesFormDisabled = true;
            vm.diabetesInstitutionFormDisabled = true;
            vm.diabetesInstitutionAddressFormDisabled = true;
            vm.diabetesInstitutionButtonsDisabled = true;
            vm.diabetesSuburbStatePostcodeDisabled = true;
            vm.diabetesInstitutionAddressRequired = false;
        }

        function clearDoctor() {
            vm.addDiabetes.doctor = {};
            vm.addDiabetes.doctor.mode = 'select';
            vm.addDiabetes.doctor.isInstitutionFormDisabled = true;
            vm.isSearchDoctor = true;

            vm.doctorDiabetesIsSearchDisabled = false;
            vm.isDoctorDiabetesFormDisabled = false;
            vm.diabetesInstitutionFormDisabled = true;
            vm.diabetesInstitutionAddressFormDisabled = true;
            vm.diabetesInstitutionButtonsDisabled = true;
            vm.diabetesSuburbStatePostcodeDisabled = true;
            vm.diabetesInstitutionAddressRequired = false;
        }

        function addProgramDiabetes(form) {
            clearSatusSubmitTab();
            vm.tabSecondId = true;
            vm.isSearchInstitution = true;
            vm.isSearchDoctor = true;
            vm.errors = [];
            var diabetesProgramViewModel = {
                patientId: vm.patientId,
                doctor: vm.addDiabetes.doctor,
                dmTypeId: vm.addDiabetes.dmTypeId,
                insulinStatusId: vm.addDiabetes.insulinStatusId,
                isFlexPen: vm.addDiabetes.isFlexPen,
                isNovoPen4: vm.addDiabetes.isNovoPen4,
                isNovoPenEcho: vm.addDiabetes.isNovoPenEcho,
                isDeviceNotRequired: vm.addDiabetes.isDeviceNotRequired,
                document: vm.addDiabetes.document,
                isConserted: vm.addDiabetes.isConserted,
                selectedProducts: vm.addDiabetes.selectedProducts
            };
            var url = api_patient_add_diabete_program;
            if (vm.diabetesProgramId > 0) {
                url = api_patient_edit_diabete_program;
                diabetesProgramViewModel.diabetesProgramId = vm.diabetesProgramId;
            }
            console.log(diabetesProgramViewModel);
            if (isFormAddProgramValid(form, diabetesProgramViewModel)) {
                httpService.post(url, diabetesProgramViewModel)
                    .then(function (response) {
                        if (response.data.success) {
                            redirectMyPatientPage();
                        } else {
                            response.data.errors.forEach(function (error) {
                                addError(error.message);
                            });
                        }
                        vm.activeTabIndex = 2;
                        scrollToTop();
                    });
            } else {
                scrollToTop();
            }
        }
        function showDiabetesVisit(form) {
            clearSatusSubmitTab();
            vm.tabSecondId = true;
            vm.isSearchInstitution = true;
            vm.isSearchDoctor = true;
            vm.errors = [];
            var diabetesProgramViewModel = {
                patientId: vm.patientId,
                doctor: vm.addDiabetes.doctor,
                dmTypeId: vm.addDiabetes.dmTypeId,
                insulinStatusId: vm.addDiabetes.insulinStatusId,
                isFlexPen: vm.addDiabetes.isFlexPen,
                isNovoPen4: vm.addDiabetes.isNovoPen4,
                isNovoPenEcho: vm.addDiabetes.isNovoPenEcho,
                isDeviceNotRequired: vm.addDiabetes.isDeviceNotRequired,
                document: vm.addDiabetes.document,
                isConserted: vm.addDiabetes.isConserted,
                selectedProducts: vm.addDiabetes.selectedProducts
            };

            var url = api_patient_add_diabete_program;
            if (vm.diabetesProgramId > 0) {
                url = api_patient_edit_diabete_program;
                diabetesProgramViewModel.diabetesProgramId = vm.diabetesProgramId;
                diabetesProgramViewModel.doctor.id = vm.doctorId;
                diabetesProgramViewModel.doctor.institution.id = vm.institutionId;
            }
            console.log(diabetesProgramViewModel);
            if (isFormAddProgramValid(form, diabetesProgramViewModel)) {
                httpService.post(url, diabetesProgramViewModel)
                    .then(function (response) {
                        console.log(response);
                        if (response.data.success) {
                            console.log(response.data.data);
                            if (vm.diabetesProgramId <= 0) {
                                vm.patientProgramId = response.data.data.patientProgramId;
                                vm.diabetesProgramId = response.data.data.patientProgramId;
                                vm.doctorId = response.data.data.doctorId;
                                vm.institutionId = response.data.data.institutionId;
                            }
                            if (vm.doctorId <= 0) {
                                vm.doctorId = response.data.data.doctorId;
                                vm.institutionId = response.data.data.institutionId;
                            }
                            $('.nav-tabs a[href="#third"]').tab('show');
                            vm.isShowDiabeteVisit = true;
                        } else {
                            response.data.errors.forEach(function (error) {
                                addError(error.message);
                            });
                        }
                        scrollToTop();
                        vm.activeTabIndex = 2;
                    });
            } else {
                scrollToTop();
            }
        }

        function backAddProgramDiabetes() {
            // return patient details
            $('#primaryTab').tab('show');
            history.pushState(null, null, $('#primaryTab').attr("href"));
            scrollToTop();
            vm.activeTabIndex = 0;
        }

        function cancelAddProgramDiabetes() {
            redirectMyPatientPage();
        }

        function redirectMyPatientPage() {
            window.location.href = "/helpinghands";
        }

        function isAnyProductSelected(viewModel) {
            if (viewModel.selectedProducts == undefined || viewModel.selectedProducts == null) {
                return false;
            }
            var isAnySelected = false;
            angular.forEach(viewModel.selectedProducts, function (prod) {
                if (prod.isSelected) {
                    isAnySelected = true;
                    return;
                }
            });
            return isAnySelected;
        }

        function isFormAddProgramValid(form, viewModel) {
            var result = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                result = false;
            }

            if (viewModel.patientId == 0) {
                addError("Please save patient before add diabetes program");
                result = false;
            }

            if (!viewModel.doctor || viewModel.doctor == null) {
                addError("Please choose a doctor");
                result = false;
            }

            if (viewModel.dmTypeId == 0) {
                addError("Please select the DM type");
                result = false;
            }

            if (!isAnyProductSelected(viewModel)) {
                addError("Please select one or more of the prescribed product");
                result = false;
            }

            if (viewModel.insulinStatusId == 0) {
                addError("Please select the insulin status");
                result = false;
            }

            if (!viewModel.isDeviceNotRequired && !viewModel.isFlexPen && !viewModel.isNovoPen4 && !viewModel.isNovoPenEcho) {
                addError("Please select at least 1 device training");
                result = false;
            }

            if (viewModel.isDeviceNotRequired &&
            (viewModel.isFlexPen || viewModel.isNovoPen4 || viewModel.isNovoPenEcho)) {
                addError("You can't select 'Not required' option and another option for device training");
                result = false;
            }

            if (form.$error.requireChecked !== undefined) {
                for (var i = 0; i < form.$error.requireChecked.length; i++) {
                    form.$error.requireChecked[i].$setDirty();
                }
                addError("Please check that you have obtained patient consent (including disclosure of payments to HCP)");
                result = false;
            }

            if (viewModel.document == undefined || viewModel.document == null) {
                addError("You must upload a patient registration form");
                result = false;
            }

            if (viewModel.document != undefined && acceptTypes.indexOf(viewModel.document.filetype) < 0) {
                addError("Enrolment form can only be a pdf or jpeg/jpg file");
                result = false;
            }

            if (form.patientFile.$error.maxsize) {
                addError("The file upload must not exceed 10 MB");
                result = false;
            }
            var postCodeValid = isPostCode();
            var phoneValid = isPhone();
            if (!postCodeValid || !phoneValid) {
                result = false;
            }
            return result;
        }

        /*<--End add program diabetes*/

        /*ADD PROGRAM OBESITY -->*/
        vm.backAddProgram = backAddProgram;
        vm.addProgramObesity = addProgramObesity;
        vm.onChangeEmailObesity = onChangeEmail;
        vm.showObesityVisit = showObesityVisit;
        vm.isShowObesityVisit = false;
        vm.isShowObesityProgram = false;
        vm.addDiabetes.obesityProgramId = 0;
        vm.showObesityProgram = function () {
            vm.isShowObesityProgram = true;
            vm.errors = [];
            scrollToTop();
        }

        function addProgramObesity(form) {
            clearSatusSubmitTab();
            vm.tabSecondId = true;
            vm.isSearchInstitution = true;
            vm.isSearchDoctor = true;
            vm.errors = [];
            vm.isValidSaxenda = true;
            var obesityProgramViewModel = {
                saxendaCareNumber: vm.saxendaCareNumber,
                patientId: vm.patientId,
                doctor: vm.addDiabetes.doctor
            };
            var url = api_patient_add_obesity_program;
            if (vm.obesityProgramId > 0) {
                url = api_patient_programs_editObesity;
                obesityProgramViewModel.obesityProgramId = vm.obesityProgramId;
            }
            if (isFormValid(form, obesityProgramViewModel)) {
                httpService.post(url, obesityProgramViewModel)
                    .then(function (response) {
                        if (response.data.success) {
                            redirectMyPatientPage();
                        } else {
                            response.data.errors.forEach(function (error) {
                                addError(error.message);
                                if (error.key && error.key.toLowerCase().indexOf("saxendacarenumber") >= 0) {
                                    vm.isValidSaxenda = false;
                                }
                            });
                        }
                        scrollToTop();
                        vm.activeTabIndex = 2;
                    });
            } else {
                scrollToTop();
            }
        }
        function showObesityVisit(form) {
            clearSatusSubmitTab();
            vm.tabSecondId = true;
            vm.isSearchInstitution = true;
            vm.isSearchDoctor = true;
            vm.errors = [];
            vm.isValidSaxenda = true;
            var obesityProgramViewModel = {
                saxendaCareNumber: vm.saxendaCareNumber,
                patientId: vm.patientId,
                doctor: vm.addDiabetes.doctor
            };

            var url = api_patient_add_obesity_program;
            if (vm.obesityProgramId > 0) {
                url = api_patient_programs_editObesity;
                obesityProgramViewModel.obesityProgramId = vm.obesityProgramId;
                obesityProgramViewModel.doctor.id = vm.doctorId;
                obesityProgramViewModel.doctor.institution.id = vm.institutionId;
            }

            if (isFormValid(form, obesityProgramViewModel)) {
                httpService.post(url, obesityProgramViewModel)
                    .then(function (response) {
                        if (response.data.success) {
                            if (vm.obesityProgramId <= 0) {
                                vm.obesityProgramId = response.data.data.patientProgramId;
                                vm.patientProgramId = response.data.data.patientProgramId;
                                vm.doctorId = response.data.data.doctorId;
                                vm.institutionId = response.data.data.institutionId;
                            }
                            if (vm.doctorId <= 0) {
                                vm.doctorId = response.data.data.doctorId;
                                vm.institutionId = response.data.data.institutionId;
                            }
                            vm.isShowObesityVisit = true;
                            $('.nav-tabs a[href="#third"]').tab('show');
                            $('#rdTypeI-toggle').bootstrapToggle('on');
                            $('#rdLength-toggle').bootstrapToggle('on');
                        } else {
                            response.data.errors.forEach(function (error) {
                                addError(error.message);
                                if (error.key && error.key.toLowerCase().indexOf("saxendacarenumber") >= 0) {
                                    vm.isValidSaxenda = false;
                                }
                            });
                        }
                        scrollToTop();
                        vm.activeTabIndex = 2;
                    });
            } else {
                scrollToTop();
            }
        }
        function backAddProgram(form) {
            $('#primaryTab').tab('show');
            history.pushState(null, null, $('#primaryTab').attr("href"));
            scrollToTop();
            vm.activeTabIndex = 0;
        }

        function isFormValid(form, viewModel) {
            var result = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                result = false;
            }
            if (form.$error.email !== undefined) {
                addError("Please specify a valid email");
                result = false;
            }
            if (viewModel.patientId == 0) {
                addError("Please save patient before add obesity program");
                result = false;
            }

            if (!viewModel.doctor || viewModel.doctor == null) {
                addError("Please choose a doctor");
                result = false;
            }

            if (form.$error.requireChecked !== undefined) {
                for (var i = 0; i < form.$error.requireChecked.length; i++) {
                    form.$error.requireChecked[i].$setDirty();
                }
                addError("Please check that you have read and agree with the payment to a HCP");
                result = false;
            }

            var postCodeValid = isPostCode();
            var phoneValid = isPhone();
            if (!postCodeValid || !phoneValid) {
                result = false;
            }

            return result;
        }
        /*<--End add program diabetes*/

        /*  ADD Visit Diabetes*/
        vm.backAddVisitDiabetes = backAddVisitDiabetes;
        vm.addVisitDiabetes = addVisitDiabetes;
        vm.getTypeInteraction = getTypeInteraction;
        vm.getLengthInteraction = getLengthInteraction;
        vm.chooseYesMaterials = chooseYesMaterials;
        vm.educationDeviceProvided = false;
        vm.educationPhysicianPlanProvided = false;
        vm.educationPatientLedTitrationProvided = false;
        vm.educationSickDayAdviceProvided = false;
        // vm.material = vm.materialProvided;
        vm.diabetesProgramVisitId = 0;
        function addVisitDiabetes(form) {
            vm.errors = [];
            vm.visitedOn = $("#visitedOn").datepicker('getDate');
            clearSatusSubmitTab();
            vm.tabThirdId = true;
            var diabetesAddVisitViewModel = {
                patientId: vm.patientId,
                patientProgramId: vm.patientProgramId,
                visitedOn: vm.visitedOn,
                interactionType: vm.interactionType,
                interactionLength: vm.interactionLength,
                educationDeviceProvided: vm.educationDeviceProvided,
                educationPhysicianPlanProvided: vm.educationPhysicianPlanProvided,
                educationPatientLedTitrationProvided: vm.educationPatientLedTitrationProvided,
                educationSickDayAdviceProvided: vm.educationSickDayAdviceProvided,
                materialProvided: vm.material
            };
            console.log(diabetesAddVisitViewModel);
            if (isFormAddVisitDiabete(form, diabetesAddVisitViewModel)) {
                httpService.post(api_patient_visit_addDiabetes, diabetesAddVisitViewModel)
                    .then(function (response) {
                        if (response.data.success) {
                            redirectPatientVisitPage();
                        } else {
                            response.data.errors.forEach(function (error) {
                                addError(error.message);
                            });
                        }
                        scrollToTop();
                    });
            } else {
                scrollToTop();
            }
        }

        function getTypeInteraction(e) {

            vm.interactionType = e.target.value;
        }

        function getLengthInteraction(e) {
            vm.interactionLength = e.target.value;
        }

        function chooseYesMaterials(event) {
            vm.material = event.target.value;
        }

        function isFormAddVisitDiabete(form, viewModel) {
            var result = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                result = false;
            }

            if (viewModel.patientId == 0) {
                addError("Please save patient before add diabetes program");
                result = false;
            }
            if (vm.educationDeviceProvided == false && vm.educationPhysicianPlanProvided == false && vm.educationPatientLedTitrationProvided == false && vm.educationSickDayAdviceProvided == false) {
                addError("At least one education provided must be chosen");
                result = false;
            }
            return result;
        }

        function backAddVisitDiabetes() {
            // return patient details
            $('#secondTab').tab('show');
            $('#btnAddProgramDiabetes').html('Confirm Changes');
            history.pushState(null, null, $('#secondTab').attr("href"));
            scrollToTop();
            vm.activeTabIndex = 1;
        }
        /*<--End add visit diabetes*/

        /*  ADD Visit Obesity*/
        vm.backAddVisitObesity = backAddVisitObesity;
        vm.addVisitObesity = addVisitObesity;
        vm.interactionType = 0;
        vm.interactionLength = 0;
        vm.obesityProgramVisitId = 0;

        function addVisitObesity(form) {
            clearSatusSubmitTab();
            vm.tabThirdId = true;
            vm.errors = [];
            vm.visitedOnObesity = $("#visitedOnObesity").datepicker('getDate');

            checkInteration();
            var obesityAddVisitViewModel = {
                patientId: vm.patientId,
                patientProgramId: vm.patientProgramId,
                visitedOn: vm.visitedOnObesity,
                interactionType: vm.interactionType,
                interactionLength: vm.interactionLength
            };
            console.log(obesityAddVisitViewModel);
            if (isFormAddVisitObesity(form, obesityAddVisitViewModel)) {
                httpService.post(api_patient_visit_addObesity, obesityAddVisitViewModel)
                    .then(function (response) {
                        if (response.data.success) {
                            redirectPatientVisitPage();
                        } else {
                            response.data.errors.forEach(function (error) {
                                addError(error.message);
                            });
                        }
                        scrollToTop();
                    });
            } else {
                scrollToTop();
            }
        }

        function isFormAddVisitObesity(form, viewModel) {
            var result = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                result = false;
            }

            if (vm.interactionType == 0) {
                addError("Please choose type of interaction");
                result = false;
            }

            if (vm.interactionLength == 0) {
                addError("Please choose length of interaction");
                result = false;
            }

            if (viewModel.patientId == 0) {
                addError("Please save patient before add diabetes program");
                result = false;
            }
            return result;
        }

        function backAddVisitObesity() {
            // return patient details
            $('#secondTab').tab('show');
            $('#btnAddProgramObesity').html('Confirm Changes');
            history.pushState(null, null, $('#secondTab').attr("href"));
            scrollToTop();
            vm.activeTabIndex = 1;
        }

        function checkInteration() {
            if ($('#rdTypeI-toggle').prop('checked')) {
                vm.interactionType = vm.typePerson.Value;
            } else {
                vm.interactionType = 0;
            }

            if ($('#rdLength-toggle').prop('checked')) {
                vm.interactionLength = vm.lengthInt.Value;
            } else {
                vm.interactionLength = 0;
            }
        }
        function redirectPatientVisitPage() {
            window.location.href = "/patient/visits?patientId=" + vm.patientId;
        }
        /*<--End add visit Obesity*/

        //COMMON METHODS 
        function addError(message) {
            var isExists = false;
            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists) vm.errors.push(message);
        }

        function addRequireError(message) {
            var isExists = false;

            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists)
                vm.errors.push({
                    message: message
                });
        }
        function onChangeEmail($event) {
            vm.validate = 0
            var val = $($event.target).val();
            showErrorEmail($event.target, val);
        }

        function showErrorEmail(obj, val) {
            if ((val == "" && $(obj).attr("required") !== undefined) || (val != "" && !isEmail(val))) {
                $($(obj).parent()).addClass("has-error");
                if (val != "" && !isEmail(val)) {
                    addError("Please specify a valid email address");
                }
                return 0;
            }
            else {
                $($(obj).parent()).removeClass("has-error");
                $(obj).parent().find(".help-block").html("");
            }
            return 1;
        }

        function isEmail(value) {
            value = value === undefined || value == null ? "" : value;
            var regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
            var val = $.trim(value);
            return regex.test(val);
        }
        function isPostCode() {
            //if (vm.addDiabetes.doctor && vm.addDiabetes.doctor.institution) {
            if (vm.addDiabetes.doctor.institution != null && vm.addDiabetes.doctor.institution.address != null &&
                vm.addDiabetes.doctor.institution.address.postcode != null) {
                var postCode = vm.addDiabetes.doctor.institution.address.postcode;
                if (postCode != null && postCode != undefined && postCode.length > 0) {
                    if (postCode.length < 4) {
                        addError("Postcode must be 4 digits");
                        return false;
                    }
                }
            }
            //} else {
            //    return false;
            //}
            return true;
        }

        function isPhone() {
            if (vm.addDiabetes.doctor && vm.addDiabetes.doctor.institution) {
                var phone = vm.addDiabetes.doctor.institution.phone;
                //var regex = /@"^[0-9]*$"/;
                if (phone != null && phone != undefined && phone.length > 0) {
                    if (phone.length < 10) {
                        addError("Phone must be 10 digits");
                        return false;
                    }
                }
            }
            return true;
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('PatientDiabetesVisitController', PatientDiabetesVisitController);
    PatientDiabetesVisitController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout'];

    function PatientDiabetesVisitController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout) {
        var vm = this;
        vm.init = init;
        vm.errors = [];
        vm.dateFormat = 'dd/MM/yyyy';
        vm.typeInteractions = [];
        vm.lengthInteractions = [];
        vm.getTypeInteraction = getTypeInteraction;
        vm.redirectPatientVisitPage = redirectPatientVisitPage;
        vm.getLengthInteraction = getLengthInteraction;
        vm.chooseYesMaterials = chooseYesMaterials;
        vm.diabetesProgramVisitId = 0;
        vm.remainingHours = 0;
        vm.remainingMinutes = 0;
        vm.isCaculate = true;
        vm.patientName = formConfig.patientName;
        vm.patientId = formConfig.patientId;
        vm.educationDeviceProvided = false;
        vm.educationPhysicianPlanProvided = false;
        vm.educationPatientLedTitrationProvided = false;
        vm.educationSickDayAdviceProvided = false;
        vm.isAllowToEdit = true;
        vm.material = true;
        vm.tabThirdId = true;
        var date = new Date();
        var minDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 180);
        function init() {
            initLookups();
            $('.date-picker').datepicker({
                startDate: minDate,
                orientation: "left",
                autoclose: true,
                format: "dd/mm/yyyy"
            });
            $('#toggle-isDeviceEducation').change(function () {
                vm.educationDeviceProvided = $(this).prop('checked');
            });
            $('#toggle-isPhysicianCustom').change(function () {
                vm.educationPhysicianPlanProvided = $(this).prop('checked');
            });
            $('#toggle-isNovoMix30').change(function () {
                vm.educationPatientLedTitrationProvided = $(this).prop('checked');
            });
            $('#toggle-isSickDay').change(function () {
                vm.educationSickDayAdviceProvided = $(this).prop('checked');
            });
        }
        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
                .success(function(data) {
                    var typeInt = data.PatientProgramVisit_InteractionType;
                    var lengthInt = data.PatientProgramVisit_InteractionLength;
                    vm.typeInteractions = typeInt;
                    vm.lengthInteractions = lengthInt;
                    vm.interactionType = vm.typeInteractions[0].Value;
                    vm.interactionLength = vm.lengthInteractions[0].Value;
                }).then(function() {
                    loadProgramVisitDiabetes();
                }).finally(function () {
                    getSupportTimeRemainHour();
                    getSupportTimeRemainMinutes();
            });
        }
        function getSupportTimeRemainHour() {
            var url = api_patient_visit_getRemainingHours;
            if (formConfig.patientProgramVisitId > 0) {
                url = api_patient_visit_edit_getRemainingHours.replace('{patientProgramVisitId?}', formConfig.patientProgramVisitId);
            }
            httpService.get(url.replace('{patientProgramId}', formConfig.patientProgramId))
                .success(function (data) {
                    console.log(data);
                    vm.remainingHours = data * 60;
                });
        }
        function getSupportTimeRemainMinutes() {
            var url = api_patient_visit_getRemainingMinutes;
            if (formConfig.patientProgramVisitId > 0) {
                url = api_patient_visit_edit_getRemainingMinutes.replace('{patientProgramVisitId?}', formConfig.patientProgramVisitId);
            }
            httpService.get(url.replace('{patientProgramId}', formConfig.patientProgramId))
                .success(function (data) {
                    console.log(data);
                    vm.remainingMinutes = data;
                });
        }
        function loadProgramVisitDiabetes() {
            if (formConfig.patientProgramVisitId > 0) {
                httpService.get(api_patient_visit_getDiabetes.replace('{patientProgramVisitId}', formConfig.patientProgramVisitId))
                    .success(function(response) {
                        console.log(response);
                        vm.isAllowToEdit = response.isAllowToEdit;
                        vm.patientName = response.patientName;
                        vm.visitedOn = response.visitedOn;
                        vm.diabetesProgramVisitId = response.diabetesProgramVisitId;
                        vm.patientProgramId = response.patientProgramId;
                        vm.educationDeviceProvided = response.educationDeviceProvided;
                        vm.educationPhysicianPlanProvided = response.educationPhysicianPlanProvided;
                        vm.educationPatientLedTitrationProvided = response.educationPatientLedTitrationProvided;
                        vm.educationSickDayAdviceProvided = response.educationSickDayAdviceProvided;
                        vm.materialProvided = response.materialProvided;
                        vm.interactionType = response.interactionType;
                        vm.interactionLength = response.interactionLength;
                        vm.material = vm.materialProvided;

                        $("#visitedOn").datepicker("setDate", new Date(moment.utc(vm.visitedOn).local()));
                        if (vm.educationDeviceProvided == true)
                            $('input:checkbox[id^="toggle-isDeviceEducation"]').bootstrapToggle('on');
                        if (vm.educationPhysicianPlanProvided == true)
                            $('input:checkbox[id^="toggle-isPhysicianCustom"]').bootstrapToggle('on');
                        if (vm.educationPatientLedTitrationProvided == true)
                            $('input:checkbox[id^="toggle-isNovoMix30"]').bootstrapToggle('on');
                        if (vm.educationSickDayAdviceProvided == true)
                            $('input:checkbox[id^="toggle-isSickDay"]').bootstrapToggle('on');

                        if (vm.materialProvided == true)
                            $('#rdNo1').prop('checked', true);
                        else
                            $('#rdYes2').prop('checked', true);

                        $('#visitrdType' + response.interactionType).prop('checked', true);
                        $('#visitrdLenghth' + response.interactionLength).prop('checked', true);

                        //[NORSYLRN-346] disabling diabetes visit form if the Invoice is either submitted or approved
                        if (vm.diabetesProgramVisitId > 0 && !vm.isAllowToEdit) {
                            $('.toggle-group label').addClass('disabled');
                        }

                    }).error(function (response) {
                    console.log(response);
                });
            }
        }

        /*ADD Visit Diabetes*/
        vm.backAddVisitDiabetes = backAddVisitDiabetes;
        vm.addVisitDiabetes = addVisitDiabetes;
        
        function getTypeInteraction(e) {
            vm.interactionType = e.target.value;
        }

        function getLengthInteraction(e) {
            vm.interactionLength = e.target.value;
        }

        function chooseYesMaterials(event) {
            vm.material = event.target.value;
        }

        function addVisitDiabetes(form) {
            vm.errors = [];
            vm.visitedOn = $("#visitedOn").datepicker('getDate');

            var diabetesAddVisitViewModel = {
                patientProgramId: formConfig.patientProgramId,
                visitedOn: vm.visitedOn,
                interactionType: vm.interactionType,
                interactionLength: vm.interactionLength,
                educationDeviceProvided: vm.educationDeviceProvided,
                educationPhysicianPlanProvided: vm.educationPhysicianPlanProvided,
                educationPatientLedTitrationProvided: vm.educationPatientLedTitrationProvided,
                educationSickDayAdviceProvided: vm.educationSickDayAdviceProvided,
                materialProvided: vm.material
            };
            console.log(diabetesAddVisitViewModel);
            if (isFormAddVisitDiabete(form, diabetesAddVisitViewModel)) {
                httpService.post(api_patient_visit_addDiabetes, diabetesAddVisitViewModel)
                    .then(function(response) {
                        if (response.data.success) {
                            redirectPatientVisitPage();
                        } else {
                            response.data.errors.forEach(function(error) {
                                addError(error.message);
                            });
                            scrollToTop();
                        }
                    });
            } else {
                scrollToTop();
            }
        }

        function backAddVisitDiabetes() {
            redirectPatientVisitPage();
        }
        /*<--End add visit Diabetes*/

        /*  Edit Visit Diabetes*/
        vm.backEditVisitDiabetes = backEditVisitDiabetes;
        vm.updateVisitDiabetes = updateVisitDiabetes;
        vm.deleteVisitDiabetes = deleteVisitDiabetes;

        function updateVisitDiabetes(form) {
            vm.errors = [];
            vm.visitedOn = $("#visitedOn").datepicker('getDate');

            var diabetesEditVisitViewModel = {
                diabetesProgramVisitId: vm.diabetesProgramVisitId,
                patientProgramId: formConfig.patientProgramId,
                visitedOn: vm.visitedOn,
                interactionType: vm.interactionType,
                interactionLength: vm.interactionLength,
                educationDeviceProvided: vm.educationDeviceProvided,
                educationPhysicianPlanProvided: vm.educationPhysicianPlanProvided,
                educationPatientLedTitrationProvided: vm.educationPatientLedTitrationProvided,
                educationSickDayAdviceProvided: vm.educationSickDayAdviceProvided,
                materialProvided: vm.material
            };
            console.log(diabetesEditVisitViewModel);
            if (isFormAddVisitDiabete(form, diabetesEditVisitViewModel)) {
                httpService.post(api_patient_visit_editDiabetes, diabetesEditVisitViewModel)
                    .then(function(response) {
                        if (response.data.success) {
                            redirectPatientVisitPage();
                        } else {
                            response.data.errors.forEach(function(error) {
                                addError(error.message);
                            });
                            scrollToTop();
                        }
                    });
            } else {
                scrollToTop();
            }
        }
        function deleteVisitDiabetes(form) {
            httpService.post(api_patient_visit_deleteDiabetes, vm.diabetesProgramVisitId)
                   .then(function (response) {
                       if (response.data.success) {
                           redirectPatientVisitPage();
                       } else {
                           response.data.errors.forEach(function (error) {
                               addError(error.message);
                           });
                       }
                   });
        }
        function backEditVisitDiabetes() {
            redirectPatientVisitPage();
        }

        function isFormAddVisitDiabete(form, viewModel) {
            var result = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                result = false;
            }

            if (vm.educationDeviceProvided == false && vm.educationPhysicianPlanProvided == false && vm.educationPatientLedTitrationProvided == false && vm.educationSickDayAdviceProvided == false) {
                addError("At least one education provided must be chosen");
                result = false;
            }
            return result;
        }

        /*<--End edit visit Diabetes*/

        //COMMON METHODS 
        function redirectPatientVisitPage() {
            window.location.href = "/patient/visits?patientId=" + vm.patientId;
        }
        function addError(message) {
            var isExists = false;
            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists) vm.errors.push(message);
        }

        function addRequireError(message) {
            var isExists = false;

            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists)
                vm.errors.push({
                    message: message
                });
        }
        function onChangeEmail($event) {
            vm.validate = 0
            var val = $($event.target).val();
            showErrorEmail($event.target, val);
        }

        function showErrorEmail(obj, val) {
            if ((val == "" && $(obj).attr("required") !== undefined) || (val != "" && !isEmail(val))) {
                $($(obj).parent()).addClass("has-error");
                if (val != "" && !isEmail(val)) {
                    addError("Please specify a valid email address");
                }
                return 0;
            }
            else {
                $($(obj).parent()).removeClass("has-error");
                $(obj).parent().find(".help-block").html("");
            }
            return 1;
        }

        function isEmail(value) {
            value = value === undefined || value == null ? "" : value;
            var regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
            var val = $.trim(value);
            return regex.test(val);
        }
          function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('PatientEditController', PatientEditController);
    PatientEditController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout'];

    function PatientEditController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout) {
        var vm = this;
        vm.isValidSaxenda = true;
        vm.submit = submit;
        vm.chooseAnswers = chooseAnswers;
        vm.patientId = formConfig.patientId;
        vm.getTab = getTab;
        vm.init = init;
        vm.errors = [];
        vm.model = vm.model || {};
        vm.dateFormat = 'dd/MM/yyyy';
        vm.editPatientProgram = editPatientProgram;
        vm.updateProgramDiabetes = updateProgramDiabetes;
        vm.editProgramObesity = editProgramObesity;
        vm.isEdit = false;
        vm.IsShowBtnEnrolDiabetesProgram = false;
        vm.IsShowBtnEnrolObesityProgram = false;
        vm.isEditProgram = true;
        vm.isSearchInstitution = true;
        vm.isSearchDoctor = true;
        vm.doctorId = 0;
        vm.institutionId = 0;
        vm.activeTabIndex = 0;
        vm.setActiveTab = setActiveTab;
        //Variables for institution, doctor - Diabetes
        vm.doctorDiabetesIsSearchDisabled = false;
        vm.isDoctorDiabetesFormDisabled = false;
        vm.diabetesInstitutionIsSearchDisabled = false;
        vm.diabetesInstitutionFormDisabled = true;
        vm.diabetesInstitutionAddressFormDisabled = true;
        vm.diabetesInstitutionAddressRequired = false;
        vm.diabetesInstitutionButtonsDisabled = true;
        vm.diabetesSuburbStatePostcodeDisabled = true;
        vm.dobValidation = "";
        vm.activeDiabetesProgramSupportTimeUsageMinutes = 0;

        //End
        var acceptTypes = ['image/jpeg', 'image/jpg', 'application/pdf'];

        $scope.$watch('vm.addDiabetes.document', function (newValue, oldValue) {
            if (oldValue && oldValue.location)
                vm.addDiabetes.document.location = oldValue.location;
        });

        function setActiveTab(idx) {
            vm.activeTabIndex = idx;
        }

        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }
        function init() {
            initLookups();
            getPatientProfile(vm.patientId);
            loadPatientPrograms();
            initialLookupAddProgram();
            initialProductProgram();
            setVisiableBtnEnrolPatientProgram(vm.patientId);
            $('.date-picker').datepicker({
                orientation: "left",
                autoclose: true,
                endDate: '+0d',
                format: "dd/mm/yyyy"
            });
            $('#toggle-hasMentalHealthDifficulties').change(function () {
                vm.model.hasMentalHealthDifficulties = $(this).prop('checked');
            });
            $('#toggle-hasElderlyDifficulties').change(function () {
                vm.model.hasElderlyDifficulties = $(this).prop('checked');
            });
            $('#toggle-hasLanguageBarrier').change(function () {
                vm.model.hasLanguageBarrier = $(this).prop('checked');
            });
            $('#toggle-hasDisability').change(function () {
                vm.model.hasDisability = $(this).prop('checked');
            });

            $('#toggle-isFlexPen').change(function () {
                vm.addDiabetes.isFlexPen = $(this).prop('checked');
            });
            $('#toggle-isNovoPen4').change(function () {
                vm.addDiabetes.isNovoPen4 = $(this).prop('checked');
            });
            $('#toggle-isNovoPenEcho').change(function () {
                vm.addDiabetes.isNovoPenEcho = $(this).prop('checked');
            });
            $('#toggle-notRequired').change(function () {
                vm.addDiabetes.isDeviceNotRequired = $(this).prop('checked');
            });
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                console.log(data);
                //vm.titles = data.Title;
                vm.titles = formConfig.titlesToPopulate;
                vm.states = data.State;
            });
        }

        function getPatientProfile(id) {
            httpService.get(api_getPatientDetail.replace('{id}', id))
                .success(function (response) {
                    vm.model = response;
                    if (vm.model.state == 0) {
                        vm.model.state = undefined;
                    }

                    $("#dateOfBirth").datepicker("setDate", moment(vm.model.dateOfBirth).format('DD/MM/YYYY'));
                    if (vm.model.hasElderlyDifficulties == true)
                        $('input:checkbox[id^="toggle-hasElderlyDifficulties"]').bootstrapToggle('on');
                    if (vm.model.hasDisability == true)
                        $('input:checkbox[id^="toggle-hasDisability"]').bootstrapToggle('on');
                    if (vm.model.hasLanguageBarrier == true)
                        $('input:checkbox[id^="toggle-hasLanguageBarrier"]').bootstrapToggle('on');
                    if (vm.model.hasMentalHealthDifficulties == true)
                        $('input:checkbox[id^="toggle-hasMentalHealthDifficulties"]').bootstrapToggle('on');
                });
        }

        function chooseAnswers(e) {
            if (e.target.value == 'true') {
                vm.model.hasLearningDifficulties = true;
                $('#answerFields').removeClass('hidden');
            } else {
                vm.model.hasLearningDifficulties = false;
                $('#answerFields').addClass('hidden');
            }
        }
        function submit(form) {
            vm.tabPrimaryId = true;
            vm.tabSecondId = false;
            BeforeSubmit();
            if (isFormAddPatientValid(form)) {
                httpService.post(api_editPatientDetail, vm.model)
                    .then(function (response) {
                        vm.errors = [];
                        vm.errors = response.data.errors;
                        if (response.data.errors.length > 0) {
                            $("#dateOfBirth").datepicker("setDate", moment(vm.model.dateOfBirth).format('DD/MM/YYYY'));
                            modelStateErrorBuilder.build(vm.errors, vm.model);
                            scrollToTop();
                        } else {
                            $window.location.href = '/helpinghands';
                        }
                    });
            } else {
                $timeout(function () {
                    if (vm.model.dateOfBirth != null && vm.model.dateOfBirth != "Invalid date")
                        $("#dateOfBirth").datepicker("setDate", moment(vm.model.dateOfBirth).format('DD/MM/YYYY'));
                }, 0);
                scrollToTop();
            }
        }
        function isFormAddPatientValid(form) {
            vm.errors = [];
            var isValid = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addRequireError("All fields highlighted in red are mandatory");;
                isValid = false;
            }

            if (vm.model.email != "" && !isEmail(vm.model.email)) {
                addRequireError("Please specify a valid email");
                isValid = false;
            }

            if (vm.model.hasLearningDifficulties == true && vm.model.hasMentalHealthDifficulties == false &&
             vm.model.hasElderlyDifficulties == false && vm.model.hasLanguageBarrier == false && vm.model.hasDisability == false) {
                addRequireError("At least 1 learning difficulty must be selected");
                isValid = false;
            }

            var dobValidation = $("#dateOfBirth").val();
            if (dobValidation != null && dobValidation.length > 0) {
                var dobRegex = /^\d{2}\/\d{2}\/\d{4}/;
                if (!dobRegex.test(dobValidation)) {
                    vm.errors.push({
                        key: 'Invalid_Dob',
                        message: "Please supply valid format for date of birth (dd/mm/yyyy)"
                    });
                    vm.model.dateOfBirth_error = true;
                    isValid = false;
                }
            }

            //var birthDay = new Date(vm.model.dateOfBirth);
            //if (birthDay < new Date(1800, 1, 1)) {
            //    addRequireError("You must choose a valid birthday");
            //    isValid = false;
            //}

            return isValid;
        }
        function addRequireError(message) {
            var isExists = false;
            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists) vm.errors.push({
                message: message
            });
        }
        function getTab(e) {
            //$(".nav-tabs > li > a").css("background-color", "gray");
            //$('#' + e + '').css("color", "#FFFFFF");
            //$('#' + e + '').css("background-color", "rgba(44, 86, 151, 1)");
        };

        function BeforeSubmit() {
            vm.model.dateOfBirth = moment($("#dateOfBirth").datepicker('getDate')).format('YYYY-MM-DD');

            if (vm.model.hasLearningDifficulties == false) {
                vm.model.hasMentalHealthDifficulties = false;
                vm.model.hasElderlyDifficulties = false;
                vm.model.hasLanguageBarrier = false;
                vm.model.hasDisability = false;
            }
            if (vm.model.suburb === undefined || vm.model.suburb === null)
                vm.model.suburb = '';
        }

        function loadPatientPrograms() {
            httpService.get(api_patient_programs_get.replace('{patientId}', vm.patientId))
                .then(function (response) {
                    vm.patientPrograms = response.data;
                    getActiveDiabetesProgramSupportTimeUsageMinute();
                });
        }

        function editPatientProgram(patientProgramViewModel) {
            vm.isEdit = true;
            vm.tabSecondId = true;
            vm.tabPrimaryId = false;
            if (patientProgramViewModel.programId == formConfig.programHH_PSP_ObesityId) {
                showObesityProgram();
                getObesityProgram(patientProgramViewModel.id);
            } else if (patientProgramViewModel.programId == formConfig.programHH_PSP_DiabetesId) {
                showDiabeteProgram();
                loadProgramDiabetes(patientProgramViewModel.id);
            }
        }
        function convertExtension(c) {
            if (c == formConfig.fileJPG) {
                return '.jpg';
            }
            if (c == formConfig.fileJPEG) {
                return '.jpeg';
            }
            if (c == formConfig.filePDF) {
                return '.pdf';
            }
        }
        function loadProgramDiabetes(patientProgramId) {
            httpService.get(api_patient_programs_getDiabetes.replace('{patientProgramId}', patientProgramId))
                .then(function (response) {
                    console.log(response);
                    if (response.status == 200) {
                        vm.addDiabetes = response.data;
                        vm.addDiabetes.document.fileName = response.data.document.fileName + convertExtension(response.data.document.extension);
                        if (vm.addDiabetes.doctor.institution != null && vm.addDiabetes.doctor.institution.id > 0) {
                            vm.addDiabetes.doctor.address = vm.addDiabetes.doctor.institution.address;
                            //vm.addDiabetes.doctor.isInstitutionFormDisabled = true;
                        }
                        if (vm.addDiabetes.isFlexPen)
                            $('#toggle-isFlexPen').bootstrapToggle('on');
                        if (vm.addDiabetes.isNovoPen4)
                            $('#toggle-isNovoPen4').bootstrapToggle('on');
                        if (vm.addDiabetes.isNovoPenEcho)
                            $('#toggle-isNovoPenEcho').bootstrapToggle('on');
                        if (vm.addDiabetes.isDeviceNotRequired)
                            $('#toggle-notRequired').bootstrapToggle('on');

                        vm.addDiabetes.enrolmentStatus = response.data.enrolmentStatus;

                        if (vm.isProgramViewOnly()) {
                            $('#toggle-isFlexPen').bootstrapToggle('disable');
                            $('#toggle-isNovoPen4').bootstrapToggle('disable');
                            $('#toggle-isNovoPenEcho').bootstrapToggle('disable');
                            $('#toggle-notRequired').bootstrapToggle('disable');
                        }
                        else {
                            $('#toggle-isFlexPen').bootstrapToggle('enable');
                            $('#toggle-isNovoPen4').bootstrapToggle('enable');
                            $('#toggle-isNovoPenEcho').bootstrapToggle('enable');
                            $('#toggle-notRequired').bootstrapToggle('enable');
                        }

                        if (vm.addDiabetes.selectedProducts) {
                            var tempSelProducts = [];
                            angular.copy(vm.products, tempSelProducts);
                            angular.forEach(tempSelProducts, function (prod) {
                                angular.forEach(vm.addDiabetes.selectedProducts, function (dProd) {
                                    if (prod.id == dProd.id) {
                                        prod.isSelected = dProd.isSelected;
                                        return;
                                    }
                                });
                            });
                            vm.addDiabetes.selectedProducts = tempSelProducts;
                        }
                    }
                });
        }

        function updateProgramDiabetes(form) {
            vm.tabSecondId = true;
            vm.tabPrimaryId = false;
            vm.isSearchDoctor = true;
            vm.isSearchInstitution = true;
            vm.errors = [];
            console.log(vm.addDiabetes.document);
            console.log(vm.addDiabetes);
            if (isFormUpdateProgramDiabetesValid(form, vm.addDiabetes)) {
                httpService.post(api_patient_edit_diabete_program, vm.addDiabetes)
                    .then(function (response) {
                        if (response.data.success) {
                            redirectMyPatientPage();
                        } else {
                            response.data.errors.forEach(function (error) {
                                addError(error.message);
                            });
                            scrollToTop();
                        }
                    });

            } else {
                scrollToTop();
            }
        }

        function isFormUpdateProgramDiabetesValid(form, viewModel) {
            var result = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                result = false;
            }

            if (viewModel.patientId == 0) {
                addError("Please save patient before add diabetes program");
                result = false;
            }

            if (!viewModel.doctor || viewModel.doctor == null) {
                addError("Please choose a doctor");
                result = false;
            }

            if (!viewModel.isDeviceNotRequired && !viewModel.isFlexPen && !viewModel.isNovoPen4 && !viewModel.isNovoPenEcho) {
                addError("Please select at least 1 device training");
                result = false;
            }

            if (viewModel.dmTypeId == 0) {
                addError("Please select the DM type");
                result = false;
            }

            if (!isAnyProductSelected(viewModel)) {
                addError("Please select one or more of the prescribed product");
                result = false;
            }

            if (viewModel.insulinStatusId == 0) {
                addError("Please select the insulin status");
                result = false;
            }

            if (viewModel.isDeviceNotRequired &&
            (viewModel.isFlexPen || viewModel.isNovoPen4 || viewModel.isNovoPenEcho)) {
                addError("You can't select 'Not required' option and another option for device training");
                result = false;
            }

            if (viewModel.document != undefined) {
                if (viewModel.document.id == null || viewModel.document.id == undefined || viewModel.document.id <= 0) {
                    if (viewModel.document != undefined && acceptTypes.indexOf(viewModel.document.filetype) < 0) {
                        addError("Enrolment form can only be a pdf or jpeg/jpg file");
                        result = false;
                    }
                }
            }

            if (form.patientFile.$error.maxsize) {
                addError("The file upload must not exceed 10 MB");
                result = false;
            }

            var postCodeValid = isPostCode();
            var phoneValid = isPhone();
            if (!postCodeValid || !phoneValid) {
                result = false;
            }
            return result;
        }

        function setVisiableBtnEnrolPatientProgram(patientId) {
            httpService.get(api_patient_isCanAddDiabetesProgram.replace('{patientId}', patientId))
                .then(function (response) {
                    if (response.status == 200) {
                        vm.IsShowBtnEnrolDiabetesProgram = response.data;
                    }
                });
            httpService.get(api_patient_isCanAddObesityProgram.replace('{patientId}', patientId))
                .then(function (response) {
                    if (response.status == 200) {
                        vm.IsShowBtnEnrolObesityProgram = response.data;
                    }
                });
        }

        /*ADD PROGRAM DIABETES -->*/
        vm.showDiabeteProgram = showDiabeteProgram;
        vm.addDiabetes = { doctor: {} };
        vm.addDiabetes.doctor.profile = {};
        vm.addDiabetes.doctor.institutionSelectedIndex = 0;
        vm.diabetesProgramVisitId = 0;

        vm.addDiabetes.isFlexPen = false;
        vm.addDiabetes.isNovoPen4 = false;
        vm.addDiabetes.isNovoPenEcho = false;
        vm.addDiabetes.isDeviceNotRequired = false;
        vm.addDiabetes.doctor.isInstitutionFormDisabled = true;
        vm.isShowDiabeteProgram = false;
        vm.addDiabetes.diabetesProgramId = 0;
        vm.getInstitutions = getInstitutions;
        vm.onSelectInstitution = onSelectInstitution;
        vm.onNewInstitution = onNewInstitution;
        vm.clearInstitution = clearInstitution;
        vm.clearDoctor = clearDoctor;
        vm.onSelectDoctor = onSelectDoctor;
        vm.getDoctorsDiabetes = getDoctorsDiabetes;
        vm.getDoctorsObesity = getDoctorsObesity;
        vm.newDoctor = newDoctor;
        vm.addProgramDiabetes = addProgramDiabetes;
        vm.onChangeEmail = onChangeEmail;
        vm.getDMTType = getDMTType;
        vm.getStatus = getStatus;
        vm.addDiabetes.doctor.disableInstitutionInputs = function () {
            return vm.addDiabetes.doctor.isInstitutionFormDisabled;
        }
        vm.addDiabetes.doctor.requireInstitutionInputs = function () {
            return !vm.addDiabetes.doctor.isInstitutionFormDisabled;
        }
        vm.cancelAddProgramDiabetes = cancelAddProgramDiabetes;
        vm.backAddProgramDiabetes = backAddProgramDiabetes;

        vm.isProgramViewOnly = function () {
            if (vm.isShowDiabeteProgram) {
                return vm.addDiabetes.diabetesProgramId > 0 && vm.addDiabetes.enrolmentStatus !== 1;
            } else if (vm.isShowObesityProgram) {
                return vm.addDiabetes.obesityProgramId > 0 && vm.addDiabetes.enrolmentStatus !== 1;
            }

            return false;
        }

        vm.IsShowClearDoctor = false;
        vm.IsShowNewDoctor = true;
        vm.IsShowClearInstitution = false;
        vm.IsShowNewInstitution = false;

        function showDiabeteProgram() {
            vm.isShowDiabeteProgram = true;
            vm.tabPrimaryId = false;
            vm.tabSecondId = true;
            vm.errors = [];
            vm.addDiabetes.dmTypeId = "3"; // set the default when showing diabetes program
        }
        function initialLookupAddProgram() {
            httpService.get(api_propertyType_getValue.replace('{id}', formConfig.propertyTye))
          .success(function (data) {
              vm.dmttype = data.DMType.ListOption;
              vm.insulinStatus = data.InsulinStatus.ListOption;
              vm.deviceTrainingRequired = data.DeviceTrainingRequired.ListOption;

              vm.addDiabetes.dmTypeId = data.DMType.ListOption[0].Id;
              vm.addDiabetes.insulinStatusId = data.InsulinStatus.ListOption[0].Id;
          });
        }
        function initialProductProgram() {
            httpService.get(api_propertyType_getProduct.replace('{programId}', formConfig.programHH_PSP_CDE_DiabetesId))
         .success(function (data) {
             angular.forEach(data, function (prod) {
                 prod.isSelected = false;
             });
             vm.products = data;

             vm.addDiabetes.selectedProducts = [];
             angular.copy(data, vm.addDiabetes.selectedProducts);
             vm.addDiabetes.selectedProducts[0].isSelected = true;
         });
        }
        function getInstitutions(value) {
            if (vm.isSearchInstitution == true) {
                var institutions = [];

                return httpService.get(api_institution_search.replace('{0}', value).replace('{1}', ''), { disable_loading: true })
                    .then(function (response) {
                        response.data.forEach(function (item) {
                            institutions.push(item);
                        });

                        angular.forEach(vm.addDiabetes.institutions, function (item, idx) {
                            if (idx != vm.addDiabetes.doctor.institutionSelectedIndex) {
                                angular.forEach(institutions, function (item2, idx2) {
                                    if (item.name == item2.name)
                                        institutions.splice(idx2, 1);
                                });
                            }
                        });
                        return institutions;
                    });
            }
        }

        vm.disableInputs = function () {
            return vm.diabetesInstitutionAddressFormDisabled;
        }

        vm.requireInputs = function () {
            return vm.diabetesInstitutionAddressRequired;
        }

        function onSelectInstitution(item) {
            vm.addDiabetes.doctor.institution = item;
            vm.addDiabetes.doctor.institution.mode = 'select';
            vm.addDiabetes.doctor.isInstitutionFormDisabled = true;
            vm.institutionId = item.id;
            vm.IsShowClearInstitution = true;
            vm.IsShowNewInstitution = true;

            vm.diabetesInstitutionIsSearchDisabled = false;
            vm.diabetesInstitutionFormDisabled = true;
            vm.diabetesInstitutionAddressFormDisabled = true;

            if (vm.addDiabetes.doctor.institution != null && vm.addDiabetes.doctor.institution.address != null) {
                vm.addDiabetes.doctor.address = vm.addDiabetes.doctor.institution.address;
            }
        }

        function onNewInstitution() {
            //if (vm.addDiabetes.doctor.institution != undefined) {
            //    vm.addDiabetes.doctor.institution = { name: "" };
            //    vm.addDiabetes.doctor.institution.mode = 'add';
            //}
            if (vm.addDiabetes.doctor.institution != null)
                vm.addDiabetes.doctor.institution = null;

            vm.institutionId = 0;
            vm.addDiabetes.doctor.isInstitutionFormDisabled = false;
            vm.isSearchInstitution = false;
            vm.IsShowClearInstitution = true;

            vm.diabetesInstitutionIsSearchDisabled = true;
            vm.diabetesInstitutionFormDisabled = false;
            vm.diabetesInstitutionAddressFormDisabled = false;
            vm.diabetesSuburbStatePostcodeDisabled = false;
            vm.diabetesInstitutionAddressRequired = true;

            vm.addDiabetes.doctor.address = {};
        }

        function clearInstitution(institution) {
            if (institution) {
                vm.addDiabetes.doctor.institution = null;
                //vm.addDiabetes.doctor.institution = {
                //    name: undefined,
                //    address: {
                //    },
                //    mode: 'add'
                //};
            }
            vm.isSearchInstitution = true;

            vm.diabetesInstitutionIsSearchDisabled = false;
            vm.diabetesInstitutionFormDisabled = false;
            vm.diabetesInstitutionAddressFormDisabled = true;
            vm.diabetesInstitutionButtonsDisabled = false;
            vm.diabetesSuburbStatePostcodeDisabled = false;
            vm.diabetesInstitutionAddressRequired = false;

            if (vm.addDiabetes.doctor.address != null) {
                vm.addDiabetes.doctor.address = {};
            }
        }

        function getDMTType(e) {
            vm.addDiabetes.dmTypeId = e.target.value;
        }

        function getStatus(e) {
            vm.addDiabetes.InsulinStatusId = e.target.value;
        }

        function newDoctor() {
            vm.addDiabetes.doctor = { lastName: "" };
            vm.addDiabetes.doctor.isInstitutionFormDisabled = false;
            vm.addDiabetes.doctor.mode = 'add';
            vm.doctorId = 0;
            vm.IsShowClearDoctor = true;
            vm.IsShowNewDoctor = true;
            vm.IsShowClearInstitution = false;
            vm.IsShowNewInstitution = true;
            vm.isSearchDoctor = false;

            vm.doctorDiabetesIsSearchDisabled = true;
            vm.isDoctorDiabetesFormDisabled = false;
            vm.diabetesInstitutionIsSearchDisabled = false;
            vm.diabetesInstitutionFormDisabled = false;
            vm.diabetesInstitutionAddressFormDisabled = true;
            vm.diabetesInstitutionButtonsDisabled = false;
            vm.diabetesSuburbStatePostcodeDisabled = false;
            vm.diabetesInstitutionAddressRequired = false;
        }

        function getDoctors(programId, lastName, stateOrSuburb) {
            if (vm.isSearchDoctor == true) {
                var doctors = [];
                var url = api_doctor_search;
                url += '?programId=' + programId;
                url += '&stateOrSuburb=' + stateOrSuburb;
                url += '&lastName=' + lastName;
                return httpService.get(url, { disable_loading: true })
                    .then(function (response) {
                        response.data.forEach(function (item) {
                            doctors.push(item);
                        });
                        return doctors;
                    });
            }
        }

        function getDoctorsByLastName(programId, lastName, stateOrSuburb) {
            if (vm.isSearchDoctor == true) {
                var doctors = [];
                var url = api_search_doctorByName;
                url += '?programId=' + programId;
                url += '&stateOrSuburb=' + stateOrSuburb;
                url += '&lastName=' + lastName;
                return httpService.get(url, { disable_loading: true })
                    .then(function (response) {
                        response.data.forEach(function (item) {
                            doctors.push(item);
                        });
                        return doctors;
                    });
            }
        }

        function getDoctorsDiabetes(lastName) {
            if (vm.addDiabetes.doctor.searchKey == undefined)
                vm.addDiabetes.doctor.searchKey = '';

            return getDoctorsByLastName(formConfig.programHH_PSP_DiabetesId, lastName, vm.addDiabetes.doctor.searchKey);
            //return getDoctors(formConfig.programHH_PSP_DiabetesId, lastName, vm.addDiabetes.doctor.searchKey);
        }

        function getDoctorsObesity(lastName) {
            if (vm.addDiabetes.doctor.searchKey == undefined)
                vm.addDiabetes.doctor.searchKey = '';

            return getDoctorsByLastName(formConfig.programHH_PSP_ObesityId, lastName, vm.addDiabetes.doctor.searchKey);
            //return getDoctors(formConfig.programHH_PSP_ObesityId, lastName, vm.addDiabetes.doctor.searchKey);
        }

        function onSelectDoctor(item) {
            vm.addDiabetes.doctor = item;
            vm.addDiabetes.doctor.mode = 'select';
            vm.addDiabetes.doctor.isInstitutionFormDisabled = true;
            vm.doctorId = item.id;
            vm.IsShowClearDoctor = true;
            vm.IsShowNewDoctor = true;
            vm.IsShowClearInstitution = false;
            vm.IsShowNewInstitution = false;

            vm.isDoctorDiabetesFormDisabled = true;
            vm.diabetesInstitutionFormDisabled = true;
            vm.diabetesInstitutionAddressFormDisabled = true;
            vm.diabetesInstitutionButtonsDisabled = true;
        }

        function clearDoctor() {
            vm.addDiabetes.doctor = {};
            vm.addDiabetes.doctor.email = '';
            vm.addDiabetes.doctor.mode = 'select';
            vm.addDiabetes.doctor.isInstitutionFormDisabled = true;
            vm.isSearchDoctor = true;

            vm.doctorDiabetesIsSearchDisabled = false;
            vm.isDoctorDiabetesFormDisabled = false;
            vm.diabetesInstitutionFormDisabled = true;
            vm.diabetesInstitutionAddressFormDisabled = true;
            vm.diabetesInstitutionButtonsDisabled = true;
            vm.diabetesSuburbStatePostcodeDisabled = true;
            vm.diabetesInstitutionAddressRequired = false;
        }


        function addProgramDiabetes(form) {
            vm.errors = [];
            vm.isSearchDoctor = true;
            vm.isSearchInstitution = true;
            var diabetesProgramViewModel = {
                patientId: vm.patientId,
                doctor: vm.addDiabetes.doctor,
                dmTypeId: vm.addDiabetes.dmTypeId,
                insulinStatusId: vm.addDiabetes.insulinStatusId,
                isFlexPen: vm.addDiabetes.isFlexPen,
                isNovoPen4: vm.addDiabetes.isNovoPen4,
                isNovoPenEcho: vm.addDiabetes.isNovoPenEcho,
                isDeviceNotRequired: vm.addDiabetes.isDeviceNotRequired,
                document: vm.addDiabetes.document,
                isConserted: vm.addDiabetes.isConserted,
                selectedProducts: vm.addDiabetes.selectedProducts
            };

            console.log(diabetesProgramViewModel);
            if (isFormAddProgramValid(form, diabetesProgramViewModel)) {
                httpService.post(api_patient_add_diabete_program, diabetesProgramViewModel)
                    .then(function (response) {
                        if (response.data.success) {
                            redirectMyPatientPage();
                        } else {
                            response.data.errors.forEach(function (error) {
                                addError(error.message);
                            });
                            scrollToTop();
                        }
                    });
            } else {
                scrollToTop();
            }
        }

        function backToProgramList() {
            vm.isShowDiabeteProgram = false;
            vm.isShowObesityProgram = false;
            vm.isEdit = false;
            vm.addDiabetes = {};
            vm.saxendaCareNumber = '';
            vm.addDiabetes.diabetesProgramId = 0;
            vm.addDiabetes.obesityProgramId = 0;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").removeClass("ng-invalid ng-dirty has-error");
                }
            }

            $('.nav-tabs a[href="#second"]').tab('show');
        }

        function backAddProgramDiabetes() {
            //// return patient details
            //$('#primaryTab').tab('show');
            //history.pushState(null, null, $('#primaryTab').attr("href"));
            backToProgramList();
        }

        function cancelAddProgramDiabetes() {
            redirectMyPatientPage();
        }

        function redirectMyPatientPage() {
            window.location.href = "/helpinghands";
        }

        function isAnyProductSelected(viewModel) {
            if (viewModel.selectedProducts == undefined || viewModel.selectedProducts == null) {
                return false;
            }
            var isAnySelected = false;
            angular.forEach(viewModel.selectedProducts, function (prod) {
                if (prod.isSelected) {
                    isAnySelected = true;
                    return;
                }
            });
            return isAnySelected;
        }

        function isFormAddProgramValid(form, viewModel) {
            var result = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                result = false;
            }

            if (viewModel.patientId == 0) {
                addError("Please save patient before add diabetes program");
                result = false;
            }

            if (!viewModel.doctor || viewModel.doctor == null) {
                addError("Please choose a doctor");
                result = false;
            }

            if (!viewModel.isDeviceNotRequired && !viewModel.isFlexPen && !viewModel.isNovoPen4 && !viewModel.isNovoPenEcho) {
                addError("Please select at least 1 device training");
                result = false;
            }

            if (viewModel.dmTypeId == 0) {
                addError("Please select the DM type");
                result = false;
            }

            if (!isAnyProductSelected(viewModel)) {
                addError("Please select one or more of the prescribed product");
                result = false;
            }

            if (viewModel.insulinStatusId == 0) {
                addError("Please select the insulin status");
                result = false;
            }

            if (viewModel.isDeviceNotRequired &&
            (viewModel.isFlexPen || viewModel.isNovoPen4 || viewModel.isNovoPenEcho)) {
                addError("You can't select Not Required and another option same time");
                result = false;
            }

            if (viewModel.document == undefined || viewModel.document == null) {
                addError("You must upload a patient registration form");
                result = false;
            }


            if (viewModel.document != undefined && acceptTypes.indexOf(viewModel.document.filetype) < 0) {
                addError("Enrolment form can only be a pdf or jpeg/jpg file");
                result = false;
            }

            if (form.patientFile.$error.maxsize) {
                addError("The file upload must not exceed 10 MB");
                result = false;
            }

            var postCodeValid = isPostCode();
            var phoneValid = isPhone();
            if (!postCodeValid || !phoneValid) {
                result = false;
            }
            return result;
        }


        /*<--End add program diabetes*/

        /* Add PROGRAM OBESITY*/
        vm.addProgramObesity = addProgramObesity;
        function addProgramObesity(form) {
            vm.errors = [];
            vm.isValidSaxenda = true;
            vm.isSearchDoctor = true;
            vm.isSearchInstitution = true;
            var obesityProgramViewModel = {
                saxendaCareNumber: vm.saxendaCareNumber,
                patientId: vm.patientId,
                doctor: vm.addDiabetes.doctor
            };

            if (isFormValid(form, obesityProgramViewModel)) {
                httpService.post(api_patient_add_obesity_program, obesityProgramViewModel)
                    .then(function (response) {
                        if (response.data.success) {
                            redirectMyPatientPage();
                        } else {
                            response.data.errors.forEach(function (error) {
                                addError(error.message);
                                if (error.key && error.key.toLowerCase().indexOf("saxendacarenumber") >= 0) {
                                    vm.isValidSaxenda = false;
                                }
                            });
                            scrollToTop();
                        }
                    });
            } else {
                scrollToTop();
            }
        }

        /*EDIT PROGRAM OBESITY -->*/
        vm.showObesityProgram = showObesityProgram;
        vm.isShowObesityProgram = false;
        vm.obesityProgramVisitId = 0;
        vm.backAddProgram = backAddProgram;



        function showObesityProgram() {
            vm.addDiabetes.obesityProgramId = 0;
            vm.isShowObesityProgram = true;
            vm.tabPrimaryId = false;
            vm.tabSecondId = true;
            vm.errors = [];
        }

        function editProgramObesity(form) {
            vm.errors = [];
            vm.isValidSaxenda = true;
            vm.isEdit = false;
            vm.isSearchDoctor = true;
            vm.isSearchInstitution = true;
            var obesityEditProgramViewModel = {
                saxendaCareNumber: vm.saxendaCareNumber,
                patientId: vm.addDiabetes.patientId,
                doctor: vm.addDiabetes.doctor,
                obesityProgramId: vm.addDiabetes.obesityProgramId
            };

            if (isFormValid(form, obesityEditProgramViewModel)) {
                httpService.post(api_patient_programs_editObesity, obesityEditProgramViewModel)
                    .then(function (response) {
                        if (response.data.success) {
                            redirectMyPatientPage();
                        } else {
                            response.data.errors.forEach(function (error) {
                                addError(error.message);
                                if (error.key && error.key.toLowerCase().indexOf("saxendacarenumber") >= 0) {
                                    vm.isValidSaxenda = false;
                                }
                            });
                            scrollToTop();
                        }
                    });
            } else {
                scrollToTop();
            }
        }

        function getObesityProgram(patientProgramId) {
            if (vm.isEdit == true) {
                return httpService.get(api_patient_programs_getObesity.replace('{id}', patientProgramId))
                    .then(function (response) {
                        console.log(response.data);
                        vm.addDiabetes.doctor = response.data.doctor;
                        vm.addDiabetes.patientId = response.data.patientId;
                        vm.addDiabetes.obesityProgramId = response.data.obesityProgramId;
                        vm.addDiabetes.enrolmentStatus = response.data.enrolmentStatus;
                        vm.saxendaCareNumber = response.data.saxendaCareNumber;
                        if (vm.addDiabetes.doctor.institution != null && vm.addDiabetes.doctor.institution.id > 0) {
                            vm.addDiabetes.doctor.address = vm.addDiabetes.doctor.institution.address;
                            //vm.addDiabetes.doctor.isInstitutionFormDisabled = true;
                        }
                    });
            }
        }
        function backAddProgram(form) {
            backToProgramList();
        }

        function isFormValid(form, viewModel) {
            var result = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                result = false;
            }
            if (form.$error.email !== undefined) {
                addError("Please specify a valid email");
                result = false;
            }
            if (vm.model.email != "" && !isEmail(vm.model.email)) {
                addRequireError("Please specify a valid email");
                result = false;
            }

            if (viewModel.patientId == 0) {
                addError("Please save patient before add obesity program");
                result = false;
            }

            if (!viewModel.doctor || viewModel.doctor == null) {
                addError("Please choose a doctor");
                result = false;
            }

            if (vm.addDiabetes.obesityProgramId == 0) {
                if (form.$error.requireChecked !== undefined) {
                    for (var i = 0; i < form.$error.requireChecked.length; i++) {
                        form.$error.requireChecked[i].$setDirty();
                    }
                    addError("Please check that you have obtained patient consent (including disclosure of payments to HCP)");
                    result = false;
                }
            }

            var postCodeValid = isPostCode();
            var phoneValid = isPhone();
            if (!postCodeValid || !phoneValid) {
                result = false;
            }
            return result;
        }
        /*<--End add program diabetes*/

        //COMMON METHODS 
        function addError(message) {
            var isExists = false;
            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists) vm.errors.push(message);
        }

        function onChangeEmail($event) {
            vm.validate = 0
            var val = $($event.target).val();
            showErrorEmail($event.target, val);
        }

        function showErrorEmail(obj, val) {
            if ((val == "" && $(obj).attr("required") !== undefined) || (val != "" && !isEmail(val))) {
                $($(obj).parent()).addClass("has-error");
                if (val != "" && !isEmail(val)) {
                    addError("Please specify a valid email address");
                }
                return 0;
            }
            else {
                $($(obj).parent()).removeClass("has-error");
                $(obj).parent().find(".help-block").html("");
            }
            return 1;
        }

        function isEmail(value) {
            value = value === undefined || value == null ? "" : value;
            var regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
            var val = $.trim(value);
            return regex.test(val);
        }

        function isPostCode() {
            //if (vm.addDiabetes.doctor.institution && vm.addDiabetes.doctor.institution) {
            //    var postCode = vm.addDiabetes.doctor.institution.address.postcode;
            //    if (postCode != null && postCode != undefined && postCode.length > 0) {
            //        if (postCode.length < 4) {
            //            addError("Postcode must be 4 digits");
            //            return false;
            //        }
            //    }
            //}
            //return true;
            if (vm.addDiabetes.doctor.address) {
                var postCode = vm.addDiabetes.doctor.address.postcode;
                if (postCode != null && postCode != undefined && postCode.length > 0) {
                    if (postCode.length < 4) {
                        addError("Postcode must be 4 digits");
                        return false;
                    }
                }
            }
            return true;
        }

        function isPhone() {
            if (vm.addDiabetes.doctor && vm.addDiabetes.doctor.institution) {
                var phone = vm.addDiabetes.doctor.institution.phone;
                //var regex = /@"^[0-9]*$"/;
                if (phone != null && phone != undefined && phone.length > 0) {
                    if (phone.length < 10) {
                        addError("Phone must be 10 digits");
                        return false;
                    }
                }
            }
            return true;
        }


        function getActiveDiabetesProgramSupportTimeUsageMinute() {
            vm.activeDiabetesProgramSupportTimeUsageMinutes = 0;
            var activeDiabetesProgram = undefined;
            angular.forEach(vm.patientPrograms, function (patientProg) {
                if (patientProg.enrolmentStatus == 1) {
                    activeDiabetesProgram = patientProg;
                    return;
                }
            });

            if (activeDiabetesProgram) {
                var url = api_patient_visit_getSupportTimeUsageMinute;
                httpService.get(url.replace('{patientProgramId}', activeDiabetesProgram.id))
                    .success(function (data) {
                        console.log(data);
                        vm.activeDiabetesProgramSupportTimeUsageMinutes = data;
                    });
            }
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('PatientListController', PatientListController);
    PatientListController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService',
        'uiGridConstants', 'moment', 'utilitySvc'];

    function PatientListController($rootScope, $scope, $window, filterFilter, httpService,
        uiGridConstants, moment, utilitySvc) {
        var vm = this;

        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: 'Profile.LastName',
            keyword: ''
        };
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getPatients);
        vm.gridOptions.columnDefs = [
            { name: 'id', displayName: 'Patient ID', maxWidth: 100 },
            { name: 'fullName', displayName: 'Patient name', maxWidth: 200 },
            { name: 'dateOfBirth', displayName: 'DOB', maxWidth: 120 },
            { name: 'doctor', displayName: 'Doctor', maxWidth: 120 },
            { name: 'phone', displayName: 'Phone' },
            {
                field: 'id',
                maxWidth: 50,
                enableSorting: false,
                displayName: '',
                enableCellEdit: false,
                cellTemplate: '<div class="ui-grid-cell-contents text-center"><a ng-href="/patient/edit/{{COL_FIELD}}">edit</a></div>'
            },
            {
                field: 'id',
                enableSorting: false,
                displayName: '',
                enableCellEdit: false,
                cellTemplate: '<div class="ui-grid-cell-contents text-center"><a ng-href="/patient/visits?patientId={{COL_FIELD}}">add/view visits</a></div>'
            }
        ];

        // This is to watch the filter value changed, and call the getUsers again!
        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getPatients();
            }
        });

        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.gridOptions);
        }

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            getPatients();
        };

        function getPatients() {
            var browserTimeZone = moment.tz.guess();
            var url = api_my_patient_search;
            url = url.replace('{pageSize}', vm.searchOption.pageSize);
            url = url.replace('{pageNo}', vm.searchOption.pageNumber);
            url = url.replace('{sort}', vm.searchOption.sort);
            url = url.replace('{0}', browserTimeZone);
            url = url.replace('{1}', vm.searchOption.keyword);

            return httpService.get(url).then(function (response) {
                if (response.data.success) {
                    vm.gridOptions.data = response.data.data.result;
                    vm.gridOptions.totalItems = response.data.data.totalCount;
                    angular.forEach(vm.gridOptions.data,
                        function (patient) {
                            if (patient.dateOfBirth && patient.dateOfBirth != null) {
                                patient.dateOfBirth = moment.utc(patient.dateOfBirth).local().format("DD/MM/YYYY");
                            }
                        });
                } else {
                    vm.errors = response.data.errors;
                }
            });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('PatientObesityVisitController', PatientObesityVisitController);
    PatientObesityVisitController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout'];

    function PatientObesityVisitController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout) {
        var vm = this;
        vm.init = init;
        vm.errors = [];

        vm.dateFormat = 'dd/MM/yyyy';
        vm.updateVisitObesity = updateVisitObesity;
        vm.redirectPatientVisitPage = redirectPatientVisitPage;

        vm.obesityProgramVisitId = 0;
        vm.interactionType = 0;
        vm.interactionLength = 0;
        vm.isFromPatientVisit = true;
        vm.patientName = formConfig.patientName;
        vm.patientId = formConfig.patientId;
        vm.isAllowToEdit = true;
        vm.tabThirdId = true;
        function init() {
            initLookups();
            loadProgramVisitObesity();
            $('.date-picker').datepicker({
                orientation: "left",
                autoclose: true,
                format: "dd/mm/yyyy"
            });
        }
        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                var typeInt = data.PatientProgramVisit_InteractionType;
                var lengthInt = data.PatientProgramVisit_InteractionLength;
                for (var i = 0; i < typeInt.length; i++) {
                    if (typeInt[i].Name == 'In person') {
                        vm.interactionTypePerson = typeInt[i].Value;
                    }
                }
                for (var i = 0; i < lengthInt.length; i++) {
                    if (lengthInt[i].Name == '60') {
                        vm.interactionLengthPerson = lengthInt[i].Value;
                    }
                }
            });
        }
        function loadProgramVisitObesity() {
            if (formConfig.patientProgramVisitId > 0) {
                httpService.get(api_patient_visit_getObesity.replace('{patientProgramVisitId}', formConfig.patientProgramVisitId))
                    .success(function (response) {
                        console.log(response);
                        vm.isAllowToEdit = response.isAllowToEdit;
                        vm.patientName = response.patientName;
                        vm.visitedOnObesity = response.visitedOn;
                        vm.interactionTypePerson = response.interactionType;
                        vm.interactionLengthPerson = response.interactionLength;
                        vm.obesityProgramVisitId = response.obesityProgramVisitId;
                        vm.patientProgramId = response.patientProgramId;
                        $("#visitedOnObesity").datepicker("setDate", new Date(moment.utc(response.visitedOn).local()));
                        $('#rdTypeI-toggle').bootstrapToggle('on');
                        $('#rdLength-toggle').bootstrapToggle('on');

                        //[NORSYLRN-346] disabling obesity visit form if the Invoice is either submitted or approved
                        if (vm.obesityProgramVisitId > 0 && !vm.isAllowToEdit) {
                            $('.toggle-group label').addClass('disabled');
                        }

                        console.log(vm);
                    }).error(function (response) {
                        console.log(response);
                    });
            }
            else {
                $('#rdTypeI-toggle').bootstrapToggle('on');
                $('#rdLength-toggle').bootstrapToggle('on');
            }
        }

        /*ADD Visit Obesity*/
        vm.backAddVisitObesity = backAddVisitObesity;
        vm.addVisitObesity = addVisitObesity;

        function addVisitObesity(form) {
            vm.errors = [];
            vm.visitedOnObesity = $("#visitedOnObesity").datepicker('getDate');

            checkInteration();
            var obesityAddVisitViewModel = {
                patientId: vm.patientId,
                patientProgramId: formConfig.patientProgramId,
                visitedOn: vm.visitedOnObesity,
                interactionType: vm.interactionType,
                interactionLength: vm.interactionLength
            };
            console.log(obesityAddVisitViewModel);
            if (isFormAddVisitObesity(form, obesityAddVisitViewModel)) {
                httpService.post(api_patient_visit_addObesity, obesityAddVisitViewModel)
                    .then(function(response) {
                        if (response.data.success) {
                            redirectPatientVisitPage();
                        } else {
                            response.data.errors.forEach(function(error) {
                                addError(error.message);
                            });
                        }
                    });
            } else {
                scrollToTop();
            }
        }
        function backAddVisitObesity() {
            redirectPatientVisitPage();
        }
        /*<--End add visit Obesity*/

        /*  Edit Visit Obesity*/
        vm.backEditVisitObesity = backEditVisitObesity;
        vm.updateVisitObesity = updateVisitObesity;
        vm.deleteVisitObesity = deleteVisitObesity;

        function updateVisitObesity(form) {
            vm.errors = [];
            vm.visitedOnObesity = $("#visitedOnObesity").datepicker('getDate');

            checkInteration();
            var obesityEditVisitViewModel = {
                obesityProgramVisitId: vm.obesityProgramVisitId,
                patientProgramId: vm.patientProgramId,
                visitedOn: vm.visitedOnObesity,
                interactionType: vm.interactionType,
                interactionLength: vm.interactionLength
            };
            console.log(obesityEditVisitViewModel);
            if (isFormAddVisitObesity(form, obesityEditVisitViewModel)) {
                httpService.post(api_patient_visit_editObesity, obesityEditVisitViewModel)
                    .then(function(response) {
                        if (response.data.success) {
                            redirectPatientVisitPage();
                        } else {
                            response.data.errors.forEach(function(error) {
                                addError(error.message);
                            });
                        }
                    });
            } else {
                scrollToTop();
            }
        }
        function deleteVisitObesity(form) {
            httpService.post(api_patient_visit_deleteObesity, vm.obesityProgramVisitId)
                   .then(function (response) {
                       if (response.data.success) {
                           redirectPatientVisitPage();
                       } else {
                           response.data.errors.forEach(function (error) {
                               addError(error.message);
                           });
                       }
                   });
        }
        function backEditVisitObesity() {
            redirectPatientVisitPage();
        }

        function checkInteration() {
            if ($('#rdTypeI-toggle').prop('checked')) {
                vm.interactionType = vm.interactionTypePerson;
            } else {
                vm.interactionType = 0;
            }

            if ($('#rdLength-toggle').prop('checked')) {
                vm.interactionLength = vm.interactionLengthPerson;
            } else {
                vm.interactionLength = 0;
            }
        }

        function isFormAddVisitObesity(form, viewModel) {
            var result = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                result = false;
            }

            if (vm.interactionType == 0) {
                addError("Please choose type of interaction");
                result = false;
            }

            if (vm.interactionLength == 0) {
                addError("Please choose length of interaction");
                result = false;
            }

            if (viewModel.patientId == 0) {
                addError("Please save patient before add diabetes program");
                result = false;
            }
            return result;
        }
        /*<--End edit visit Obesity*/

        //COMMON METHODS 
        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }
        function redirectPatientVisitPage() {
            window.location.href = "/patient/visits?patientId=" + vm.patientId;
        }
        function addError(message) {
            var isExists = false;
            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists) vm.errors.push(message);
        }

        function addRequireError(message) {
            var isExists = false;

            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists)
                vm.errors.push({
                    message: message
                });
        }
        function onChangeEmail($event) {
            vm.validate = 0
            var val = $($event.target).val();
            showErrorEmail($event.target, val);
        }

        function showErrorEmail(obj, val) {
            if ((val == "" && $(obj).attr("required") !== undefined) || (val != "" && !isEmail(val))) {
                $($(obj).parent()).addClass("has-error");
                if (val != "" && !isEmail(val)) {
                    addError("Please specify a valid email address");
                }
                return 0;
            }
            else {
                $($(obj).parent()).removeClass("has-error");
                $(obj).parent().find(".help-block").html("");
            }
            return 1;
        }

        function isEmail(value) {
            value = value === undefined || value == null ? "" : value;
            var regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
            var val = $.trim(value);
            return regex.test(val);
        }

    }
})();;
(function () {
    'use strict';

    window.app.controller('PatientVisitListController', PatientVisitListController);
    PatientVisitListController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService',
        'uiGridConstants', 'moment', 'utilitySvc','formConfig'];

    function PatientVisitListController($rootScope, $scope, $window, filterFilter, httpService,
        uiGridConstants, moment, utilitySvc,formConfig) {
        var vm = this;
        vm.programHH_PSP_Diabetes = formConfig.programHH_PSP_Diabetes;
        vm.programHH_PSP_Obesity = formConfig.programHH_PSP_Obesity;
        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: 'id',
            keyword: '',
            programId: "0",
            patientId: formConfig.patientId
        };
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getVisits);
        vm.gridOptions.columnDefs = [
            { name: 'patientProgramId', displayName: 'Program enrolment ID', maxWidth: 200 },
            { name: 'enrolledOn', displayName: 'Enrolment date', maxWidth: 200 },
            { name: 'programName', displayName: 'Program name', maxWidth: 200 },
            { name: 'visitedOn', displayName: 'Visit date' },
            { name: 'hcpName', displayName: 'Referring HCP' },
            { name: 'enrolmentStatusName', displayName: 'Enrolment status' },
            {
                field: 'id',
                maxWidth: 80,
                enableSorting: false,
                displayName: '',
                enableCellEdit: false,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center">' +
                        '<a ng-if="row.entity.programId == ' + vm.programHH_PSP_Diabetes + '" ng-href="/patient/DiabetesVisit?patientProgramId={{row.entity.patientProgramId}}&patientProgramVisitId={{COL_FIELD}}">view/edit</a>' +
                        '<a ng-if="row.entity.programId == ' + vm.programHH_PSP_Obesity + '" ng-href="/patient/ObesityVisit?patientProgramId={{row.entity.patientProgramId}}&patientProgramVisitId={{COL_FIELD}}">view/edit</a>' +
                        '</div>'
            }
        ];

        // This is to watch the filter value changed, and call the getUsers again!
        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getVisits();
            }
        });

        $scope.$watch('vm.searchOption.programId', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.programId = newValue;
                getVisits();
            }
        });

        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.gridOptions);
        }

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            getVisits();
        };

        function getVisits() {
            var browserTimeZone = moment.tz.guess();
            var url = api_patient_program_visits_search;
            url = url.replace('{pageSize}', vm.searchOption.pageSize);
            url = url.replace('{pageNo}', vm.searchOption.pageNumber);
            url = url.replace('{sortFields}', vm.searchOption.sort);
            url = url.replace('{1}', vm.searchOption.keyword);
            url = url.replace('{0}', browserTimeZone);
            url = url.replace('{programId}', vm.searchOption.programId);
            url = url.replace('{patientId}', vm.searchOption.patientId);

            return httpService.get(url).then(function (response) {
                if (response.data.success) {
                    console.log('kol');
                    console.log(response.data.data);
                    vm.gridOptions.data = response.data.data.result;
                    vm.gridOptions.totalItems = response.data.data.totalCount;
                    angular.forEach(vm.gridOptions.data,
                        function (item) {
                            if (item.patientProgram.enrolledOn && item.patientProgram.enrolledOn != null) {
                                item.enrolledOn = moment.utc(item.patientProgram.enrolledOn).local().format("DD/MM/YYYY");
                            }
                            if (item.visitedOn && item.visitedOn != null) {
                                item.visitedOn = moment.utc(item.visitedOn).local().format("DD/MM/YYYY");
                            }
                        });
                } else {
                    vm.errors = response.data.errors;
                }
            });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('PresenterController', PresenterController);
    PresenterController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', 'modalService'];

    function PresenterController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, modalService) {
        var vm = this;
        vm.submit = submit;
        vm.model = { institution: { address: {} } };
        vm.init = init;
        vm.isEditMode = false;
        vm.isEditInstitution = false;
        vm.modeLabel = 'Create presenter';
        vm.deletePresenter = deletePresenter;
        function init() {
            initLookups();
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
                .success(function (data) {
                    console.log(data);
                    vm.professions = data.Hcp_Profession;
                    vm.professions = $.grep(vm.professions,
                        function (item) {
                            return item.Value !== formConfig.otherProfessionValue
                                && item.Value !== formConfig.registrarProfessionValue;
                        });
                    vm.titles = data.Title;
                    vm.states = data.State;
                }).then(function (d) {
                    loadPresenter();
                });
        }

        /******************************  Institution  *****************************/
        resetIns();
        vm.insIsDisabled = false;
        vm.insIsAddressDisabled = true;
        vm.insIsSearchDisabled = false;
        vm.isInstitutionSelected = false;
        vm.isNewInstitutionClicked = false;

        vm.insClear = function () {
            vm.isInstitutionSelected = false;
            vm.isNewInstitutionClicked = false;
            console.log('clear is called!');
            vm.insIsSearchDisabled = false;
            vm.insIsDisabled = false;
            vm.insIsAddressDisabled = true;

            resetIns();
        };
        vm.insSelect = function (item) {
            vm.isInstitutionSelected = true;
            //console.log('select is called!');
            vm.insIsDisabled = true;
            vm.model.institution = item;
        }
        vm.insEdit = function (item) {
            vm.isEditInstitution = true;
            //console.log('edit is called!');
            vm.insIsDisabled = false;
            vm.insIsSearchDisabled = true;
            vm.insIsAddressDisabled = false;
        }
        vm.insNew = function (item) {
            vm.isInstitutionSelected = false;
            vm.isNewInstitutionClicked = true;
            //console.log('new is called!');
            vm.insIsDisabled = false;
            vm.insIsSearchDisabled = true;
            vm.insIsAddressDisabled = false;

            resetIns();
        }
        function resetIns() {
            vm.model.institution = null;
        };

        vm.insAddressDisable = function () {
            return vm.insIsDisabled || vm.insIsAddressDisabled;
        }

        vm.getInstitutions = function (value) {
            var url = api_institution_search.replace('{0}', value);
            return getItems(url);
        }

        function getItems(url) {
            var items = [];

            return httpService.get(url, { disable_loading: true })
                .then(function (response) {
                    response.data.forEach(function (item) {
                        items.push(item);
                    });
                    return items;
                });
        }

        function loadPresenter() {
            if (formConfig.presenterId > 0) {
                isPresenterAssociatedToNonDeletedEvent();
                httpService.get(api_get_presenter.replace('{id}', formConfig.presenterId))
                    .success(function (response) {
                        console.log(response);
                        vm.model = response;
                        vm.isEditMode = true;
                        if (vm.model.institution != null) {
                            vm.isInstitutionSelected = true;
                            vm.insIsDisabled = true;
                        }
                    });
                vm.modeLabel = 'Edit presenter';
            }
        }

        function isPresenterAssociatedToNonDeletedEvent() {
            httpService.get(api_presenter_associatedToNonDeletedEvent.replace('{id}', formConfig.presenterId))
            .success(function (response) {
                vm.isPresenterAssociatedToNonDeletedEvent = response.data;
            });
        }

        function submit(form) {
            utilitySvc.invalidateControlOnSubmission(form);
            var url = api_add_presenter;
            vm.model.isEditInstitution = vm.isEditInstitution;
            if (vm.isEditMode) {
                vm.model.id = formConfig.presenterId;
                url = api_edit_presenter;
            }
            if (vm.isNewInstitutionClicked && vm.model.institution != null) {
                vm.model.institution.id = 0;
            }

            if (isFormAddPresenterValid(form)) {
                console.log(vm.model);

                httpService.post(url, vm.model)
                    .then(function (response) {
                        vm.errors = [];
                        vm.errors = response.data.errors;
                        if (response.data.errors.length > 0) {
                            modelStateErrorBuilder.build(vm.errors, vm.model);
                            scrollToTop();
                        } else {
                            redirectPresenterList();
                        }
                    });
            } else {
                scrollToTop();
            }

        }

        function deletePresenter() {
            var modalOptions = {
                actionButtonText: 'Yes',
                bodyText: 'Are you sure you want to delete this presenter?',
                closeButtonText: 'Cancel'
            };

            modalService.showModal({}, modalOptions)
                .then(function (result) {
                    httpService.post(api_presenter_delete.replace('{presenterId}', formConfig.presenterId))
                   .then(function (response) {
                       if (response.data.success) {
                           redirectPresenterList();
                       } else {
                           console.log(response.data.errors);
                           vm.errors = response.data.errors;
                           scrollToTop();
                       }
                   });
                });
        }

        function isFormAddPresenterValid(form) {
            vm.errors = [];
            var isValid = true;
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    $("[name='" + $(form.$error.required[i])[0].$name + "']").addClass("ng-invalid ng-dirty has-error");
                }
                addError("All fields highlighted in red are mandatory");
                isValid = false;
            }

            if (form.email.$error.email !== undefined) {
                addError("Please specify a valid email");
                isValid = false;
            }
            if (form.phone.$error.phone !== undefined) {
                addError("Please specify a valid phone number");
                isValid = false;
            }
            if (form.mobile.$error.phone !== undefined) {
                addError("Please specify a valid mobile number");
                isValid = false;
            }

            if (isValid) {
                var emailValid = isEmailValid(vm.model.email);
                var phoneValid = isPhone();
                var postcodeValid = isPostCode();
                if (!emailValid || !phoneValid || !postcodeValid) {
                    isValid = false;
                }
            }
            return isValid;
        }


        function redirectPresenterList() {
            window.location.href = formConfig.presenterListUrl;
        }

        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }

        function isPostCode() {
            if (vm.model.institution != null) {
                var postCode = vm.model.institution.address.postcode;
                if (postCode != null && postCode != undefined && postCode.length > 0) {
                    if (postCode.length < 4) {
                        addError("Postcode provided is invalid");
                        return false;
                    }
                }
            }
            return true;
        }

        function isPhone() {
            var phone = vm.model.phone;
            var mobile = vm.model.mobile;
            var inValid = true;
            if (phone != null && phone != undefined && phone.length > 0) {
                if (phone.length < 10) {
                    addError("The phone number entered is invalid");
                    inValid = false;
                }
            }
            if (mobile != null && mobile != undefined && mobile.length > 0) {
                if (mobile.length < 10) {
                    addError("The mobile number entered is invalid");
                    inValid = false;
                }
            }
            return inValid;
        }

        function isEmailValid(value) {
            var isValid = true;
            if (value != "" && !isEmail(value)) {
                addError("Please specify a valid email");
                isValid = false;
            }
            return isValid;
        }

        function isEmail(value) {
            value = value === undefined || value == null ? "" : value;
            var regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
            var val = $.trim(value);
            return regex.test(val);
        }

        function addError(message) {
            var isExists = false;

            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists)
                vm.errors.push({
                    message: message
                });
        }

    }
})();;
(function () {
    'use strict';

    window.app.controller('PresenterListController', PresenterListController);
    PresenterListController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService',
        'uiGridConstants', 'moment', 'utilitySvc', 'formConfig'];

    function PresenterListController($rootScope, $scope, $window, filterFilter, httpService,
        uiGridConstants, moment, utilitySvc, formConfig) {
        var vm = this;
        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: 'id',
            keyword: ''
        };
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getDataGird);
        vm.gridOptions.paginationPageSizes = [25, 50, 75, 100];
        vm.gridOptions.columnDefs = [
            { name: 'name', displayName: 'Name' },
            { name: 'professionName', displayName: 'Profession' },
            { name: 'suburb', displayName: 'Suburb', maxWidth: 150 },
            { name: 'stateName', displayName: 'State', maxWidth: 100 },
            { name: 'phone', displayName: 'Phone', maxWidth: 160 },
            {
                field: 'id',
                enableSorting: false,
                displayName: '',
                maxWidth: 100,
                enableCellEdit: false,
                cellTemplate:
                    '<div class="ui-grid-cell-contents text-center""><a href="' + formConfig.addEditUrl + '/{{row.entity.id}}">edit</a></div>'
            }
        ];

        // This is to watch the filter value changed, and call the getUsers again!
        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getDataGird();
            }
        });

        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.gridOptions);
        }

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            getDataGird();
        };

        function getDataGird() {
            var url = api_presenter_search;
            url += '?pageSize=' + vm.searchOption.pageSize;
            url += '&pageNo=' + vm.searchOption.pageNumber;
            url += '&sortFields=' + vm.searchOption.sort;
            url += '&keyword=' + vm.searchOption.keyword;

            return httpService.get(url).then(function (response) {
                if (response.data.success) {
                    console.log(response.data.data.result);
                    vm.gridOptions.data = response.data.data.result;
                    vm.gridOptions.totalItems = response.data.data.totalCount;
                } else {
                    vm.errors = response.data.errors;
                }
            });
        }


    }
})();;
(function () {
    'use strict';

    window.app.controller('ReportsListController', ReportsListController);
    ReportsListController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
       'moment'];

    function ReportsListController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
       moment) {
        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;
        vm.errors = [];

        function init() {
            vm.model.browserTimezone = moment.tz.guess();
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('ResourceAddController', ResourceAddController);
    ResourceAddController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', '$rootScope', 'toaster'];

    function ResourceAddController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, $rootScope, toaster) {
        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;
        vm.errors = [];
        vm.submit = submit;
        var thumbnailAcceptTypes = ['image/jpeg', 'image/jpg', 'image/png'];
        var resourceAcceptTypes = ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf', 'application/ppt', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/pptx', 'video/mp4'];
        var resourceImageAcceptTypes = ['image/jpeg', 'image/jpg', 'image/png'];
        var resourceDocumentAcceptTypes = ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf', 'application/ppt', 'application/pptx', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'];
        var resourceVideoAcceptTypes = ['video/mp4'];

        function init() {
            getResourceTypes();
            getLanguages();
        };

        function getResourceTypes() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                vm.resourceTypes = data.Resource_Type;
                vm.resourceMediaTypes = data.Resource_MediaType;
            });
        }

        function getLanguages() {
            var url = api_propertyvalues_search
            url = url.replace('{propertyId:int?}', formConfig.languagePropertyId);
            url = url.replace('{keyword?}', "");
            httpService.get(url)
            .success(function (data) {
                vm.resourceLanguages = data;
                vm.model.languageId = formConfig.englishLanguageId;
            });
        }

        function submit(form) {
            if (isValid(form)) {

                //if url is entered then avoid sending the resource file to server
                if (vm.model.url != undefined && vm.model.url != null && vm.model.url.length > 0) {
                    if (vm.model.fileData != undefined && vm.model.fileData != null)
                        vm.model.fileData = null;
                }

                var url = api_resource_add;
                httpService.post(url, vm.model)
                .then(function (response) {
                    vm.errors = [];
                    vm.errors = response.data.errors;
                    if (response.data.errors.length > 0) {
                        modelStateErrorBuilder.build(vm.errors, vm.model);
                        document.getElementById('page-wrapper').scrollIntoView();

                    } else {
                        $rootScope.$broadcast("loader_show");
                        toaster.pop({
                            type: 'success',
                            title: 'Success',
                            body: 'Resource added successfully',
                            timeout: 2500,
                            onHideCallback: function () {
                                $window.location.href = '/admin/resources';
                                $rootScope.$broadcast("loader_hide");
                            }
                        });
                    }
                });
            }
            else {
                document.getElementById('page-wrapper').scrollIntoView();
            }
            utilitySvc.invalidateControlOnSubmission(form);
        }

        function isValid(formAddResources) {
            vm.errors = [];

            var valid = formAddResources.$valid;
            var validResourceFileType = validateResourceFileType();
            var validThumbnailFileType = validateThumbnailFileType();
            var validUrl = isUrlValid();
            //var validFileSize = isFileSizeValid();

            valid = valid && validResourceFileType && validThumbnailFileType && validUrl;// && validFileSize;
            return valid;
        }

        function validateResourceFileType() {
            if (vm.model.mediaType == formConfig.pageMediaType) {
                if (vm.model.url == null || vm.model.url == undefined || vm.model.url.length <= 0) {
                    vm.errors.push({
                        key: 'ResourceFileInvalid',
                        message: "Please provide url for the resource file"
                    });
                    return false;
                }
                return true;
            }
            if (vm.model.fileData != null && vm.model.fileData != undefined) {
                if (vm.model.mediaType == formConfig.imageMediaType) {
                    if (resourceImageAcceptTypes.indexOf(vm.model.fileData.filetype.toLowerCase()) < 0) {
                        vm.errors.push({
                            key: 'ResourceFileInvalid',
                            message: "Only jpg, jpeg, png files are allowed for resource file"
                        });
                        return false;
                    }
                }
                if (vm.model.mediaType == formConfig.documentMediaType) {
                    if (resourceDocumentAcceptTypes.indexOf(vm.model.fileData.filetype.toLowerCase()) < 0) {
                        vm.errors.push({
                            key: 'ResourceFileInvalid',
                            message: "Only pdf, ppt, pptx, doc, docx files are allowed for resource file"
                        });
                        return false;
                    }
                }
                if (vm.model.mediaType == formConfig.videoMediaType) {
                    if (resourceVideoAcceptTypes.indexOf(vm.model.fileData.filetype.toLowerCase()) < 0) {
                        vm.errors.push({
                            key: 'ResourceFileInvalid',
                            message: "Only mp4 files are allowed for resource file"
                        });
                        return false;
                    }
                }
            }
            if (vm.model.mediaType != formConfig.pageMediaType && (vm.model.fileData == null || vm.model.fileData == undefined) && (vm.model.url == null || vm.model.url == undefined || vm.model.url.length <= 0)) {
                vm.errors.push({
                    key: 'ResourceFileInvalid',
                    message: "Please upload resource file or provide url for the resource"
                });
                return false;
            }
            return true;
        }

        function validateThumbnailFileType() {
            if (vm.model.thumbnailFileData != null && vm.model.thumbnailFileData != undefined) {
                if (thumbnailAcceptTypes.indexOf(vm.model.thumbnailFileData.filetype.toLowerCase()) < 0) {
                    vm.errors.push({
                        key: 'ThumbnailFileInvalid',
                        message: "Only jpg, jpeg, png files are allowed for thumbnail resource"
                    });
                    return false;
                }
            }
            else {
                vm.errors.push({
                    key: 'ThumbnailFileInvalid',
                    message: "Please upload resource for thumbnail"
                });
                return false;
            }
            return true;
        }

        function isUrlValid() {
            var url = vm.model.resourceUrl;
            if (url != null && url.length > 0) {
                //check if the url starts with http
                if (url.substr(0, 4).toUpperCase() != "HTTP") {
                    vm.errors.push({
                        key: 'InvalidUrl',
                        message: "Resource url must start with http"
                    });
                    return false;
                }
                //check if the url has space
                if (url.indexOf(' ') >= 0) {
                    vm.errors.push({
                        key: 'InvalidUrl',
                        message: "Resource url cannot contain space"
                    });
                    return false;
                }
            }
            return true;
        }

        function isFileSizeValid() {
            var thumbnailImage = vm.model.thumbnailFileData;
            if (thumbnailImage != undefined && thumbnailImage != null) {
                if (thumbnailImage.filesize / 1024 > formConfig.thumbnailFileMaxSize) {
                    vm.errors.push({
                        key: 'InvalidFileSize',
                        message: "Thumbnail file should cannot be greater than 200kb"
                    });
                    return false;
                }
            }
            return true;
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('ResourceEditController', ResourceEditController);
    ResourceEditController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', '$rootScope', 'toaster'];

    function ResourceEditController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, $rootScope, toaster) {
        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;
        vm.errors = [];
        vm.submit = submit;
        vm.deleteResource = deleteResource;
        var thumbnailAcceptTypes = ['image/jpeg', 'image/jpg', 'image/png'];
        var resourceAcceptTypes = ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf', 'application/ppt', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/pptx', 'video/mp4'];
        var resourceImageAcceptTypes = ['image/jpeg', 'image/jpg', 'image/png'];
        var resourceDocumentAcceptTypes = ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf', 'application/ppt', 'application/pptx', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'];
        var resourceVideoAcceptTypes = ['video/mp4'];

        var ImageTypes = ['jpeg', 'jpg', 'png'];
        var DocumentTypes = ['pdf', 'ppt', 'pptx','doc','docx'];
        var VideoTypes = ['mp4'];

        function init() {
            getResourceTypes();
            getLanguages();
            getResoureRecord();
        };

        function getResourceTypes() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                vm.resourceTypes = data.Resource_Type;
                vm.resourceMediaTypes = data.Resource_MediaType;
            });
        }

        function getLanguages() {
            var url = api_propertyvalues_search;
            url = url.replace('{propertyId:int?}', formConfig.languagePropertyId);
            url = url.replace('{keyword?}', "");
            httpService.get(url)
            .success(function (data) {
                vm.resourceLanguages = data;
            });
        }

        function getResoureRecord() {
            var url = api_resource_getResource.replace('{id}', formConfig.resourceId);
            httpService.get(url)
            .success(function (response) {
                vm.model = response;
                vm.model.existingUrl = response.url;
                vm.model.existingThumbnailUrl = response.thumbnailUrl;

                if (!vm.model.isExternalResource) {
                    vm.model.url = "";
                }
                else if (vm.model.isExternalResource) {
                    vm.model.existingUrl = "";
                }
            });
        }

        function submit(form) {
            if (isValid(form)) {

                //if url is entered then avoid sending the resource file to server
                //if (vm.model.url != undefined && vm.model.url != null && vm.model.url.length > 0) {
                //    if (vm.model.fileData != undefined && vm.model.fileData != null)
                //        vm.model.fileData = null;
                //}

                var url = api_resource_editResource;
                httpService.post(url, vm.model)
                .then(function (response) {
                    vm.errors = [];
                    vm.errors = response.data.errors;
                    if (response.data.errors.length > 0) {
                        modelStateErrorBuilder.build(vm.errors, vm.model);
                        document.getElementById('page-wrapper').scrollIntoView();

                    } else {
                        $rootScope.$broadcast("loader_show");
                        toaster.pop({
                            type: 'success',
                            title: 'Success',
                            body: 'Resource updated successfully',
                            timeout: 2500,
                            onHideCallback: function () {
                                $window.location.href = '/admin/resources';
                                $rootScope.$broadcast("loader_hide");
                            }
                        });
                    }
                });
            }
            else {
                document.getElementById('page-wrapper').scrollIntoView();
            }
            utilitySvc.invalidateControlOnSubmission(form);
        }

        function deleteResource() {
            var url = api_resource_deleteResource.replace('{id}', formConfig.resourceId);
            httpService.post(url)
            .then(function (response) {
                vm.errors = [];
                vm.errors = response.data.errors;
                if (response.data.errors.length > 0) {
                    modelStateErrorBuilder.build(vm.errors, vm.model);
                    document.getElementById('page-wrapper').scrollIntoView();

                } else {
                    $rootScope.$broadcast("loader_show");
                    toaster.pop({
                        type: 'success',
                        title: 'Success',
                        body: 'Resource deleted successfully',
                        timeout: 2500,
                        onHideCallback: function () {
                            $window.location.href = '/admin/resources';
                            $rootScope.$broadcast("loader_hide");
                        }
                    });
                }
            });
        }

        function isValid(formEditResources) {
            vm.errors = [];

            var valid = formEditResources.$valid;
            var validResourceFileType = validateResourceFileType();
            var validThumbnailFileType = validateThumbnailFileType();
            var validUrl = isUrlValid();
            var validFileSize = isFileSizeValid();

            valid = valid && validResourceFileType && validThumbnailFileType && validUrl && validFileSize;
            return valid;
        }

        function validateResourceFileType() {
            if ((vm.model.fileData == null || vm.model.fileData == undefined) && vm.model.existingUrl == "" && vm.model.url == "") {
                vm.errors.push({
                    key: 'ResourceFileInvalid',
                    message: "Please supply either url or upload the resource file"
                });
                return false;
            }
            if (vm.model.mediaType == formConfig.pageMediaType) {
                if (vm.model.url == null || vm.model.url == undefined || vm.model.url.length <= 0) {
                    vm.errors.push({
                        key: 'ResourceFileInvalid',
                        message: "Please provide url for the resource file"
                    });
                    return false;
                }
                return true;
            }
            if (vm.model.fileData != null && vm.model.fileData != undefined) {
                if (vm.model.mediaType == formConfig.imageMediaType) {
                    if (resourceImageAcceptTypes.indexOf(vm.model.fileData.filetype.toLowerCase()) < 0) {
                        vm.errors.push({
                            key: 'ResourceFileInvalid',
                            message: "Only jpg, jpeg, png files are allowed for resource file"
                        });
                        return false;
                    }
                }
                if (vm.model.mediaType == formConfig.documentMediaType) {
                    if (resourceDocumentAcceptTypes.indexOf(vm.model.fileData.filetype.toLowerCase()) < 0) {
                        vm.errors.push({
                            key: 'ResourceFileInvalid',
                            message: "Only pdf, ppt, pptx, doc, docx files are allowed for resource file"
                        });
                        return false;
                    }
                }
                if (vm.model.mediaType == formConfig.videoMediaType) {
                    if (resourceVideoAcceptTypes.indexOf(vm.model.fileData.filetype.toLowerCase()) < 0) {
                        vm.errors.push({
                            key: 'ResourceFileInvalid',
                            message: "Only mp4 files are allowed for resource file"
                        });
                        return false;
                    }
                }
            }
            else if (vm.model.existingUrl == "" && vm.model.url == "") {
                if (vm.model.mediaType == formConfig.imageMediaType) {
                    for (var index in ImageTypes) {
                        if (vm.model.existingUrl.toLowerCase().indexOf(ImageTypes[index]) >= 0) {
                            return true;
                        }
                    }
                    vm.errors.push({
                        key: 'ResourceFileInvalid',
                        message: "Image type is used for jpg, jpeg, png files"
                    });
                    return false;
                }
                if (vm.model.mediaType == formConfig.documentMediaType) {
                    for (var index in DocumentTypes) {
                        if (vm.model.existingUrl.toLowerCase().indexOf(DocumentTypes[index]) >= 0) {
                            return true;
                        }
                    }
                    vm.errors.push({
                        key: 'ResourceFileInvalid',
                        message: "Document type is used for pdf, ppt, pptx, doc, docx files"
                    });
                    return false;
                }
                if (vm.model.mediaType == formConfig.videoMediaType) {
                    for (var index in VideoTypes) {
                        if (vm.model.existingUrl.toLowerCase().indexOf(VideoTypes[index]) >= 0) {
                            return true;
                        }
                    }
                    vm.errors.push({
                        key: 'ResourceFileInvalid',
                        message: "Video type is used for mp4 files"
                    });
                    return false;
                }
            }

            return true;
        }

        function validateThumbnailFileType() {
            if (vm.model.thumbnailUrl == null || vm.model.thumbnailUrl == undefined) {
                if (vm.model.thumbnailFileData != null && vm.model.thumbnailFileData != undefined) {
                    if (thumbnailAcceptTypes.indexOf(vm.model.thumbnailFileData.filetype.toLowerCase()) < 0) {
                        vm.errors.push({
                            key: 'ThumbnailFileInvalid',
                            message: "Only jpg, jpeg, png files are allowed"
                        });
                        return false;
                    }
                }
                else {
                    vm.errors.push({
                        key: 'ThumbnailFileInvalid',
                        message: "Please upload resource for thumbnail"
                    });
                    return false;
                }
            }
            return true;
        }

        function isUrlValid() {
            var url = vm.model.resourceUrl;
            if (url != null && url.length > 0) {
                //check if the url starts with http
                if (url.substr(0, 4).toUpperCase() != "HTTP") {
                    vm.errors.push({
                        key: 'InvalidUrl',
                        message: "Resource url must start with http"
                    });
                    return false;
                }
                //check if the url has space
                if (url.indexOf(' ') >= 0) {
                    vm.errors.push({
                        key: 'InvalidUrl',
                        message: "Resource url cannot contain space"
                    });
                    return false;
                }
            }
            return true;
        }

        function isFileSizeValid() {
            var thumbnailImage = vm.model.thumbnailFileData;
            if (thumbnailImage != undefined && thumbnailImage != null) {
                if (thumbnailImage.filesize / 1024 > formConfig.thumbnailFileMaxSize) {
                    vm.errors.push({
                        key: 'InvalidFileSize',
                        message: "Thumbnail file should cannot be greater than 200kb"
                    });
                    return false;
                }
            }
            return true;
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('ResourceListController', ResourceListController);
    ResourceListController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
       'uiGridConstants', '$timeout'];

    function ResourceListController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
       uiGridConstants, $timeout) {
        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;
        vm.errors = [];

        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: 'typeName',
            keyword: ''
        };

        function init(){
            getResources();
        }

        function getResources() {
            var url = api_search_resource;
            url = url.replace('{pageSize}', vm.searchOption.pageSize);
            url = url.replace('{pageNo}', vm.searchOption.pageNumber);
            url = url.replace('{sort}', vm.searchOption.sort);
            url = url.replace('{keyword?}', vm.searchOption.keyword);

            return httpService.get(url).success(function (data) {
                vm.resourceGridOptions.data = data.result;
                vm.resourceGridOptions.totalItems = data.totalCount;
            });
        };

        // This is to watch the filter value changed, and call the getResources again!
        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getResources();
            }
        });

        ////////////////////////////// Resources List ///////////////////////////

        vm.resourceGridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getResources);
        vm.resourceGridOptions.paginationPageSizes = [1, 5, 10, 25, 50, 100];
        vm.resourceGridOptions.columnDefs = [];
        var restOfColDefs = [
            { name: 'typeName', displayName: 'Type', maxWidth: 180 },
            { name: 'language', displayName: 'Language', maxWidth: 200 },
            { name: 'title', displayName: 'Title'},            
            {
                field: 'id',
                enableSorting: false,
                displayName: '',
                enableCellEdit: false,
                cellTemplate: '<div class="ui-grid-cell-contents text-center"><a ng-href="/admin/resources/edit/{{COL_FIELD}}">edit</a></div>',
                maxWidth: 180
            }
        ];
        vm.resourceGridOptions.appScopeProvider = vm;
        vm.resourceGridOptions.columnDefs = vm.resourceGridOptions.columnDefs.concat(restOfColDefs);
    }
})();;
(function(window, undefined) {

  'use strict';

  /* istanbul ignore next */
  window._arrayBufferToBase64 = function(buffer) { //http://stackoverflow.com/questions/9267899/arraybuffer-to-base64-encoded-string
    var binary = '';
    var bytes = new Uint8Array(buffer);
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
  };


  var mod = window.angular.module('naif.base64', []);

  mod.directive('baseSixtyFourInput', [
    '$window',
    '$q',
    function($window, $q) {

      var isolateScope = {
        onChange: '&',
        onAfterValidate: '&',
        parser: '&'
      };

      var FILE_READER_EVENTS = ['onabort', 'onerror', 'onloadstart', 'onloadend', 'onprogress', 'onload'];
      for (var i = FILE_READER_EVENTS.length - 1; i >= 0; i--) {
        var e = FILE_READER_EVENTS[i];
        isolateScope[e] = '&';
      }

      return {
        restrict: 'A',
        require: 'ngModel',
        scope: isolateScope,
        link: function(scope, elem, attrs, ngModel) {

          /* istanbul ignore if */
          if (!ngModel) {
            return;
          }

          var rawFiles = [];
          var fileObjects = [];

          elem.on('change', function(e) {

            if (!e.target.files.length) {
              return;
            }

            fileObjects = [];
            fileObjects = angular.copy(fileObjects);
            rawFiles = e.target.files; // use event target so we can mock the files from test
            _readFiles();
            _onChange(e);
            _onAfterValidate(e);
          });

          function _readFiles() {
            var promises = [];
            var i;
            for (i = rawFiles.length - 1; i >= 0; i--) {
              // append file a new promise, that waits until resolved
              rawFiles[i].deferredObj = $q.defer();
              promises.push(rawFiles[i].deferredObj.promise);
              // TODO: Make sure all promises are resolved even during file reader error, otherwise view value wont be updated
            }

            // set view value once all files are read
            $q.all(promises).then(_setViewValue);

            for (i = rawFiles.length - 1; i >= 0; i--) {
              var reader = new $window.FileReader();
              var file = rawFiles[i];
              var fileObject = {};

              fileObject.filetype = file.type;
              fileObject.filename = file.name;
              fileObject.filesize = file.size;
              
              _attachEventHandlers(reader, file, fileObject);
              reader.readAsArrayBuffer(file);
            }
          }

          function _onChange(e) {
            if (attrs.onChange) {
                if (scope.onChange && typeof scope.onChange() === "function") {
                    scope.onChange()(e, rawFiles);
                }
                else {
                    scope.onChange(e, rawFiles);
              }
            }
          }

          function _onAfterValidate(e) {
            if (attrs.onAfterValidate) {
                // wait for all promises, in rawFiles,
                //   then call onAfterValidate
                var promises = [];
                for (var i = rawFiles.length - 1; i >= 0; i--) {
                    promises.push(rawFiles[i].deferredObj.promise);
                }
                $q.all(promises).then(function () {
                  if (scope.onAfterValidate && typeof scope.onAfterValidate() === "function"){
                      scope.onAfterValidate()(e, fileObjects, rawFiles);
                  }
                  else{
                      scope.onAfterValidate(e, fileObjects, rawFiles);
                  }
                });
            }
          }

          function _attachEventHandlers(fReader, file, fileObject) {

            for (var i = FILE_READER_EVENTS.length - 1; i >= 0; i--) {
              var e = FILE_READER_EVENTS[i];
              if (attrs[e] && e !== 'onload') { // don't attach handler to onload yet
                _attachHandlerForEvent(e, scope[e], fReader, file, fileObject);
              }
            }

            fReader.onload = _readerOnLoad(fReader, file, fileObject);
          }

          function _attachHandlerForEvent(eventName, handler, fReader, file, fileObject) {
            fReader[eventName] = function(e) {
              handler()(e, fReader, file, rawFiles, fileObjects, fileObject);
            };
          }

          function _readerOnLoad(fReader, file, fileObject) {

            return function(e) {

              var buffer = e.target.result;
              var promise;

              // do not convert the image to base64 if it exceeds the maximum
              // size to prevent the browser from freezing
              var exceedsMaxSize = attrs.maxsize && file.size > attrs.maxsize * 1024;
              if (attrs.doNotParseIfOversize !== undefined && exceedsMaxSize) {
                fileObject.base64 = null;
              } else {
                fileObject.base64 = $window._arrayBufferToBase64(buffer);
              }

              if (attrs.parser) {
                promise = $q.when(scope.parser()(file, fileObject));
              } else {
                promise = $q.when(fileObject);
              }

              promise.then(function(fileObj) {
                fileObjects.push(fileObj);
                // fulfill the promise here.
                file.deferredObj.resolve();
              });

              if (attrs.onload) {
                if (scope.onload && typeof scope.onload() === "function"){
                    scope.onload()(e, fReader, file, rawFiles, fileObjects, fileObject);
                }
                else{
                    scope.onload(e, rawFiles);
                }
              }

            };

          }

          function _setViewValue() {
            var newVal = attrs.multiple ? fileObjects : fileObjects[0];
            ngModel.$setViewValue(newVal);
            _maxsize(newVal);
            _minsize(newVal);
            _maxnum(newVal);
            _minnum(newVal);
            _accept(newVal);
          }

          ngModel.$isEmpty = function(val) {
            return !val || (angular.isArray(val) ? val.length === 0 : !val.base64);
          };

          // http://stackoverflow.com/questions/1703228/how-can-i-clear-an-html-file-input-with-javascript
          scope._clearInput = function() {
            elem[0].value = '';
          };

          scope.$watch(function() {
            return ngModel.$viewValue;
          }, function(val) {
            if (ngModel.$isEmpty(val)) {
              scope._clearInput();
            }
          });

          // VALIDATIONS =========================================================

          function _maxnum(val) {
            if (attrs.maxnum && attrs.multiple && val) {
              var valid = val.length <= parseInt(attrs.maxnum);
              ngModel.$setValidity('maxnum', valid);
            }
            return val;
          }

          function _minnum(val) {
            if (attrs.minnum && attrs.multiple && val) {
              var valid = val.length >= parseInt(attrs.minnum);
              ngModel.$setValidity('minnum', valid);
            }
            return val;
          }

          function _maxsize(val) {
            var valid = true;

            if (attrs.maxsize && val) {
              var max = parseFloat(attrs.maxsize) * 1000;

              if (attrs.multiple) {
                for (var i = 0; i < val.length; i++) {
                  var file = val[i];
                  if (file.filesize > max) {
                    valid = false;
                    break;
                  }
                }
              } else {
                valid = val.filesize <= max;
              }
              ngModel.$setValidity('maxsize', valid);
            }

            return val;
          }

          function _minsize(val) {
            var valid = true;
            var min = parseFloat(attrs.minsize) * 1000;

            if (attrs.minsize && val) {
              if (attrs.multiple) {
                for (var i = 0; i < val.length; i++) {
                  var file = val[i];
                  if (file.filesize < min) {
                    valid = false;
                    break;
                  }
                }
              } else {
                valid = val.filesize >= min;
              }
              ngModel.$setValidity('minsize', valid);
            }

            return val;
          }

          function _accept(val) {
            var valid = true;
            var regExp, exp, fileExt;
            if (attrs.accept) {
              exp = attrs.accept.trim().replace(/[,\s]+/gi, "|").replace(/\./g, "\\.").replace(/\/\*/g, "/.*");
              regExp = new RegExp(exp, 'i');
            }

            if (attrs.accept && val) {
              if (attrs.multiple) {
                for (var i = 0; i < val.length; i++) {
                  var file = val[i];
                  fileExt = "." + file.filename.split('.').pop();
                  valid = regExp.test(file.filetype) || regExp.test(fileExt);

                  if (!valid) {
                    break; }
                }
              } else {
                fileExt = "." + val.filename.split('.').pop();
                valid = regExp.test(val.filetype) || regExp.test(fileExt);
              }
              ngModel.$setValidity('accept', valid);
            }

            return val;
          }

        }
      };

    }
  ]);

})(window);
;
(function () {
    window.app.factory('antiForgeryInterceptor', antiForgeryInterceptor);

    antiForgeryInterceptor.$inject = ["$location", "$q"];
    function antiForgeryInterceptor($location, $q) {
        return {
            request: function (config) {
                var token = $("input:hidden[name=\"__RequestVerificationToken\"]").val();

                if (!!token && token.length > 0) {
                    if (!config.headers)
                        config.headers = { __RequestVerificationToken: token };
                    else
                        config.headers.__RequestVerificationToken = token;
                }

                return config;
            },
            responseError: function (rejection) {
                if (rejection.status === 403) {
                    //$location.path("/error/accessdenied");
                    if (rejection.data && typeof rejection.data === "string") {
                        alert(rejection.data + "\n" + "Please refresh your browser and try again.");
                    }
                }
                return $q.reject(rejection);
            }
        };
    }
})();;
(function () {
    window.app.factory('documentSvc', documentSvc);
    documentSvc.$inject = ['$window', '$filter', '$timeout', '$q'];
    function documentSvc($window, $filter, $timeout) {
        return {
            recalculateHeight: recalculateHeight,
            response: onHttpResponse
        };

        function recalculateHeight() {
            //console.log("recalculateHeight CALLED");
            //var windowHeight = angular.element($window).height();
            //var headerHeight = angular.element('.header').outerHeight();
            //var footerHeight = angular.element('.footer').outerHeight()
            //var calcHeight = windowHeight - (headerHeight + footerHeight);
            //var wrapperHeight = angular.element('#wrapper').height();

            //if (wrapperHeight < calcHeight) {
            //    angular.element('#wrapper').height(calcHeight);
            //}
            //else {
            //    var childrenHeight = 0;
            //    angular.element('#wrapper').children().each(function (idx, ele) {
            //        childrenHeight += angular.element(ele).outerHeight();
            //    });
            //    var totalContentHeight = childrenHeight + headerHeight + footerHeight;
            //    if (totalContentHeight > windowHeight) {
            //        angular.element('#wrapper').height('auto');
            //    }
            //}
        }

        function onHttpResponse(resp) {
            // NOTE: recalculate height as grid size might changed!
            // timeout to execute in the next digest
            $timeout(function () {
                recalculateHeight();
            }, 0);
            return resp || $q.when(resp);
        }
    }
})();;
(function () {
    'use strict';

    window.app.factory('httpService', ['$http', function ($http) {
        var HOST = "";
        return {
            get: function (url, data) {
                var req = {
                    method: 'GET',
                    cache: false,
                    url: url,
                    headers: {
                        'Content-Type': undefined
                    },
                    data: data
                }
                var http = $http(req);
                http.error(function (error, status) {
                    //location.href = location.href;
                });
                return http;
            },
            download: function (url) {
                var req = {
                    method: 'GET',
                    cache: false,
                    url: url,
                    headers: {
                        'Content-Type': 'application/json; charset=utf-8'
                    },
                    responseType: 'arraybuffer'
                }
                var http = $http(req);
                http.error(function (error, status) {
                    //location.href = location.href;
                });
                return http;
            },
            post: function (url, data) {
                var req = {
                    method: 'POST',
                    url: url,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    data: data
                }
                var http = $http(req);
                http.error(function (error, status) {
                    switch (status) {
                    }
                });
                return http;
            },
            putFile: function (url, data, authorization) {
                var fd = new FormData();
                fd.append('file', file);

                var http = $http({
                    method: 'PUT',
                    url: url,
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': 'Bearer ' + authorization
                    },
                    data: data,
                    transformRequest: function (data, headersGetter) {
                        var formData = new FormData();
                        angular.forEach(data, function (value, key) {
                            formData.append(key, value);
                        });

                        var headers = headersGetter();
                        delete headers['Content-Type'];

                        return formData;
                    }
                });

                http.error(function (error, status) {
                    switch (status) {
                        case 500:
                            NotificationService.ShowError("Internal server error")
                            break;
                        default:
                            NotificationService.ShowError("an error occurred while processing your request. Please try again...")
                            break;
                    }
                });
                return http;
            },
            put: function (url, data) {
                var req = {
                    method: 'PUT',
                    url: url,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    data: data
                }
                var http = $http(req);
                http.error(function (error, status) {
                    location.href = location.href;
                });
                return http;
            },
            delete: function (url, data) {
                var req = {
                    method: 'DELETE',
                    url: url,
                    headers: {
                        'Content-Type': undefined
                    },
                    data: data
                }
                var http = $http(req);
                http.error(function (error, status) {
                    location.href = location.href;
                });
                return http;
            },
            upload: function (url, method, data, token) {
                var http = Upload.upload({
                    method: method,
                    url: url,
                    data: data,
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': 'Bearer ' + token
                    },
                });

                return http;
            },
            exportFile: function (url, data) {
            var req = {
                method: 'POST',
                url: url,
                headers: {
                    'Content-Type': 'application/json'
                },
                data: data,
                responseType: 'blob'
            }
            var http = $http(req);
            http.error(function (error, status) {
                return $q.reject(response.data);
            });
            return http;
        }
        };
    }]);
})();;
(function () {
    window.app.factory('httpInterceptor', httpInterceptor);

    httpInterceptor.$inject = ['$rootScope', '$q', 'deviceDetector', 'moment'];

    function httpInterceptor($rootScope, $q, deviceDetector, moment) {
        var numLoadings = 0;

        var service = {
            request: requestTranslator,
            requestError: requestErrorTranslator,
            responseError: responseErrorTranslator,
            response: responseTranslator
        };

        return service;

        function requestTranslator(config) {
            numLoadings++;

            if (config.url.indexOf('typeahead') < 0 && config.url.indexOf('institution') < 0)
                $rootScope.$broadcast("loader_show");

            if (deviceDetector) {
                var device = deviceDetector.device == 'unknown' ? 'desktop' : deviceDetector.device;
                var userAgent = deviceDetector.raw.userAgent;
                if (!config.headers) {
                    config.headers = {
                        AuditDevice: device,
                        AuditBrowser: userAgent,
                        UserTimeOffset: moment().utcOffset(),
                        'X-Requested-With': 'XMLHttpRequest'
                    };
                }
                else {
                    config.headers.AuditDevice = device;
                    config.headers.AuditBrowser = userAgent;
                    config.headers.UserTimeOffset = moment().utcOffset();
                    config.headers['X-Requested-With'] = 'XMLHttpRequest';
                }
            }

            return config || $q.when(config);
        }

        function responseTranslator(response) {
            if ((--numLoadings) === 0)
                $rootScope.$broadcast("loader_hide");

            return response || $q.when(response);
        }

        function requestErrorTranslator(request) {
            $rootScope.$broadcast("loader_hide");
            return $q.reject(response);
        }

        function responseErrorTranslator(response) {
            if (!(--numLoadings))
                $rootScope.$broadcast("loader_hide");

            if (response.status == 401) {
                //location.href = '/Account/Login?ReturnUrl=' + encodeURIComponent(location.pathname);
                location.href = '/Error/AccessDenied?ReturnUrl=' + encodeURIComponent(location.pathname) + '&Url=' + encodeURIComponent(response.config.url);
            }

            return $q.reject(response);
        }
    }
})();;
(function () {
    'use strict';

    window.app.service('modalService', ['$uibModal', function ($uibModal) {
        var modalDefaults = {
            backdrop: true,
            keyboard: true,
            modalFade: true,
            templateUrl: 'reusableModal.html',
            windowClass: 'reusableModal'
        };

        var modalOptions = {
            closeButtonText: 'Close',
            actionButtonText: 'OK',
            headerText: 'Proceed?',
            bodyText: 'Perform this action?',
            showCloseButton: true
        };

        this.showModal = function (customModalDefaults, customModalOptions) {
            if (!customModalDefaults) customModalDefaults = {};
            customModalDefaults.backdrop = 'static';
            return this.show(customModalDefaults, customModalOptions);
        };

        this.show = function (customModalDefaults, customModalOptions) {
            //Create temp objects to work with since we're in a singleton service
            var tempModalDefaults = {};
            var tempModalOptions = {};

            //Map angular-ui modal custom defaults to modal defaults defined in service
            angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);

            //Map modal.html $scope custom properties to defaults defined in service
            angular.extend(tempModalOptions, modalOptions, customModalOptions);

            if (!tempModalDefaults.controller) {
                tempModalDefaults.controller = ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {
                    $scope.modalOptions = tempModalOptions;
                    $scope.modalOptions.ok = function (result) {
                        $uibModalInstance.close(result);
                    };
                    $scope.modalOptions.close = function (result) {
                        $uibModalInstance.dismiss('cancel');
                    };
                }]
            }

            return $uibModal.open(tempModalDefaults).result;
        };
    }]);
})();;
(function () {
    window.app.factory('modelStateErrorBuilder', modelStateErrorBuilder);

    function modelStateErrorBuilder() {
        var numLoadings = 0;

        var service = {
            build: build
        };

        return service;

        function build(errors, model) {
            angular.forEach(errors, function (error) {
                var key = error.key == undefined ? (error.Key == undefined ? '' : error.Key) : error.key;

                if (key != '') {
                    if (model[key.toLowerCase() + '_error'] === undefined)
                        model[key.toLowerCase().replace('.', '_') + '_error'] = true;
                }
            });
        }
    }
})();;
(function () {
    window.app.factory('utilitySvc', utilitySvc);

    utilitySvc.$inject = ['$window', 'httpService', '$filter'];

    function utilitySvc($window, httpService, $filter) {
        var service = {
            getParameterByName: getParameterByName,
            convertISODateToDDMMYYYY: convertISODateToDDMMYYYY,
            convertDDMMYYYYToISODate: convertDDMMYYYYToISODate,
            uiGrid: {
                createDefaultUIGridOptions: createDefaultUIGridOptions,
                getTableHeightStyle: getTableHeightStyle
            },
            downloadFileFromApi: downloadFileFromApi,
            invalidateControlOnSubmission: invalidateControlOnSubmission,
            isPasswordValid: isPasswordValid
        };

        return service;

        function getParameterByName(name, url) {
            if (!url) url = $window.location.href;

            name = name.replace(/[\[\]]/g, "\\$&");

            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);

            if (!results) return null;
            if (!results[2]) return '';

            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }

        function convertISODateToDDMMYYYY(date) {
            if (!date) return;

            var d = new Date(date),
                month = '' + (d.getMonth() + 1),
                day = '' + d.getDate(),
                year = d.getFullYear();

            if (month.length < 2) month = '0' + month;
            if (day.length < 2) day = '0' + day;

            return [day, month, year].join('/');
        }

        function convertDDMMYYYYToISODate(text) {
            if (!text) return;

            var dates = text.split('/');

            return new Date(parseInt(dates[2]), parseInt(dates[1]) - 1, parseInt(dates[0])).toISOString();
        }

        function createDefaultUIGridOptions(uiGridConstants, searchOption, apiFunctionDelegate, defaultSortColumn) {
            // NOTE: columnDefs need to be defined separately later on!
            return {
                rowHeight: 30,
                enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER,
                useExternalPagination: true,
                useExternalSorting: true,
                useExternalFiltering: true,
                gridMenuShowHideColumns: false,
                enableColumnMenus: false,
                paginationPageSizes: [1, 5, 10, 25, 50, 100],
                paginationPageSize: searchOption.pageSize,
                onRegisterApi: function (gridApi) {
                    gridApi.core.on.sortChanged(null, function (grid, sortColumns) {
                        if (sortColumns.length == 0) {
                            searchOption.sort = defaultSortColumn ? defaultSortColumn : 'id';
                        } else {
                            var sortedFields = $filter('orderBy')(sortColumns, 'sort.priority');
                            var sortArr = [];
                            angular.forEach(sortedFields, function (gridCol, idx) {
                                var sortField = gridCol.name;
                                if (gridCol.sort.direction == 'desc') {
                                    sortField = '-' + sortField;
                                }
                                sortArr.push(sortField);
                            });
                            searchOption.sort = sortArr.join(',');
                        }
                        apiFunctionDelegate();
                    });
                    gridApi.pagination.on.paginationChanged(null, function (newPage, pageSize) {
                        searchOption.pageNumber = newPage;
                        searchOption.pageSize = pageSize;
                        apiFunctionDelegate();
                    });
                }
            };
        }

        function getTableHeightStyle(gridOptions) {
            var rowHeight = 30; // your row height
            var headerHeight = 32; // your header height
            var paginationHeight = 32;

            var noOfRecords = gridOptions.data ? gridOptions.data.length : 0;
            var maxRows = gridOptions.paginationPageSize;
            var fittedRows = noOfRecords == 0 ? 1 : (noOfRecords < maxRows ? noOfRecords : maxRows);
            return {
                height: (fittedRows * rowHeight + headerHeight + paginationHeight) + "px"
            };
        };

        function downloadFileFromApi(apiDownloadUrl) {
            return httpService.download(apiDownloadUrl)
                .then(function (response) {
                    var success = false;
                    var contentType = response.headers('Content-Type');
                    var disposition = response.headers('Content-Disposition');
                    var defaultFileName = '';

                    if (disposition) {
                        var match = disposition.match(/.*filename=\"?([^;\"]+)\"?.*/);
                        if (match[1])
                            defaultFileName = match[1];
                    }
                    defaultFileName = defaultFileName.replace(/[<>:"\/\\|?*]+/g, '_');

                    try {
                        var blob = new Blob([response.data], { type: contentType });

                        if (navigator.msSaveBlob)
                            navigator.msSaveBlob(blob, defaultFileName);
                        else {
                            var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
                            if (saveBlob === undefined) throw "Not supported";
                            saveBlob(blob, defaultFileName);
                        }

                        console.log("saveBlob succeeded");
                        success = true;
                    } catch (ex) {
                        console.log("saveBlob method failed with the following exception:");
                        console.log(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
                                    console.log("Trying download link method with simulated click ...");
                                    var blob = new Blob([response.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", defaultFileName);

                                    // 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);
                                    console.log("Download link method with simulated click succeeded");
                                    success = true;
                                } catch (ex) {
                                    console.log("Download link method with simulated click failed with the following exception:");
                                    console.log(ex);
                                }
                            }

                            if (!success) {
                                // Fallback to window.location method
                                try {
                                    // Prepare a blob URL
                                    // Use application/octet-stream when using window.location to force download
                                    console.log("Trying download link method with window.location ...");
                                    var blob = new Blob([response.data], { type: octetStreamMime });
                                    var url = urlCreator.createObjectURL(blob);
                                    window.location = url;
                                    console.log("Download link method with window.location succeeded");
                                    success = true;
                                } catch (ex) {
                                    console.log("Download link method with window.location failed with the following exception:");
                                    console.log(ex);
                                }
                            }
                        }
                    }

                    if (!success) {
                        // Fallback to window.open method
                        console.log("No methods worked for saving the arraybuffer, using last resort window.open");
                        window.open(httpPath, '_blank', '');
                    }
                });
        }

        function invalidateControlOnSubmission(form) {
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    form.$error.required[i].$setDirty();
                }
            }
            if (form.$error.requireChecked !== undefined) {
                for (var i = 0; i < form.$error.requireChecked.length; i++) {
                    form.$error.requireChecked[i].$setDirty();
                }
            }
        }

        function isPasswordValid(password) {
            var regexSpace = /^\S+$/;
            var regexLetter = /^(?=.*[a-zA-Z]).+$/;
            var regexNumeric = /^(?=.*[0-9]).+$/; // /^(?=.*[0-9_\W]).+$/;
            var regexCapitalLetter = /^(?=.*[A-Z]).+$/;

            var errorArr = [];
            if (arguments.length > 1 && arguments[1]) {
                errorArr = arguments[1];
            }
            var label = 'Password';
            if (arguments.length > 2 && arguments[2]) {
                label = arguments[2];
            }

            if (password !== undefined && password !== null) {
                if (password.length < 8) {
                    errorArr.push({
                        message: label + " must have a minimum of 8 characters"
                    });
                    return false;
                }
                if (!regexNumeric.test(password)) {
                    errorArr.push({
                        message: label + " must contain at least one numeric character"
                    });
                    return false;
                }
                if (!regexLetter.test(password)) {
                    errorArr.push({
                        message: label + " must contain at least 1 letter"
                    });
                    return false;
                }
                if (!regexSpace.test(password)) {
                    errorArr.push({
                        message: label + " must not contain spaces"
                    });
                    return false;
                }
                if (!regexCapitalLetter.test(password)) {
                    errorArr.push({
                        message: label + " must contain at least 1 capital letter"
                    });
                    return false;
                }
            }
            return true;
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('MyProfileController', MyProfileController);
    MyProfileController.$inject = ['$scope', '$rootScope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout', 'toaster'];

    function MyProfileController($scope, $rootScope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout, toaster) {
        var vm = this;
        vm.model = vm.model || {};
        vm.init = init;
        vm.addAccreditations = addAccreditations;
        vm.deleteAccreditations = deleteAccreditations;
        vm.submitMyProfile = submitMyProfile;
        vm.findPrimaryInstitution = findPrimaryInstitution;
        vm.hcpInstitution = {};
        vm.isSelectedAddress = false;

        vm.submitMyUserName = submitMyUserName;
        vm.model.newUserName = "";
        vm.model.confirmUserName = "";
        vm.model.confirmPassword = "";

        vm.submitMyPassword = submitMyPassword;
        vm.model.newPassword = "";
        vm.model.confirmNewPassword = "";
        vm.model.oldPassword = "";

        vm.chooseProfession = function () {
            if (vm.model.hcp.professionId != 9
                && vm.model.hcp.otherProfession != null
                && vm.model.hcp.otherProfession != "")
            {
                vm.model.hcp.otherProfession = null;
            }
        }

        var originalModel = {};

        function init() {
            initLookups();
            loadMyProfileData();
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                vm.hcpProfessions = data.Hcp_Profession;
                vm.accreditations = data.HcpAccreditation_Type;
                vm.titles = data.Title;
                vm.states = data.State;
            });
        }

        function loadMyProfileData() {
            var isCDE = formConfig.isCDE == 1 ? true : false;
            httpService.get(api_getMyProfile_byUserId.replace('{userId}', formConfig.userId).replace('{isCDE}', isCDE))
           .success(function (response) {
               var data = response.data;
               vm.model = data.profile;
               vm.model.newUserName = vm.model.hcp.user.username;

               if (!vm.model.hcp.accreditations
                    || vm.model.hcp.accreditations.length == 0) {
                   vm.model.hcp.accreditations = [];
                   addAccreditations();
               }
               vm.model.mainInsName = findPrimaryInstitution(vm.model.hcp.hcpInstitutions) != null ? findPrimaryInstitution(vm.model.hcp.hcpInstitutions).institution.name : "";

               if (vm.model.mainInsName != "") {
                   vm.isInstitutionFormDisabled = true;
                   vm.isStateSuburbPostCodeInputsDisabled = true;
                   vm.isSelectedAddress = true;
               }
               vm.model.address = findPrimaryInstitution(vm.model.hcp.hcpInstitutions) != null ? findPrimaryInstitution(vm.model.hcp.hcpInstitutions).institution.address : data.profile.address != null && !data.profile.address.isDeleted ? data.profile.address : {
               };

               if (data.cdeInfo && data.cdeInfo != null) {
                   loadCDEInfo(data.cdeInfo);
               }

               vm.UserNameForm.$setPristine();
               angular.copy(vm.model, originalModel);
           });
        }

        function loadCDEInfo(data) {
            vm.model.languagesSpoken = [];
            vm.model.areasCovered = [];
            vm.model.CDEMobile = {};
            vm.model.CDEPhone = {};
            vm.model.CDEEmail = {};

            for (var pos in data) {
                switch (data[pos].propertyId) {
                    case formConfig.mobilePropertyId:
                        vm.model.CDEMobile = generateObjectProperty(data[pos]);
                        break;
                    case formConfig.phonePropertyId:
                        vm.model.CDEPhone = generateObjectProperty(data[pos]);
                        break;
                    case formConfig.emailPropertyId:
                        vm.model.CDEEmail = generateObjectProperty(data[pos]);
                        break;
                    case formConfig.areaPropertyId:
                        vm.model.areasCovered.push(
                            generateObjectProperty(data[pos])
                        );
                        break;
                    case formConfig.languagePropertyId:
                        vm.model.languagesSpoken.push(
                           generateObjectProperty(data[pos])
                        );
                        break;
                    case formConfig.isWillingToTravelPropertyId:
                        vm.model.willingToTravel = generateObjectProperty(data[pos]);
                        if(vm.model.willingToTravel.value != null){
                            vm.model.willingToTravel.value = vm.model.willingToTravel.value.toLowerCase();
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        function submitMyProfile(form) {
            if (form.$valid) {
                if (vm.model.mainInsName != null && vm.model.mainInsName != "" && !isPrimaryInstitutionExist()) {// When manually adding status
                    addManualInstitution();
                }
                removeAllEmptyAccList();
                clearSubmitErrorClassValues();
                httpService.post(api_updateProfile.replace('{userId}', formConfig.userId), vm.model)
                  .then(function (response) {
                      vm.errors = [];
                      vm.errors = response.data.errors;
                      // Server-side validation
                      if (response.data.errors.length > 0) {
                          modelStateErrorBuilder.build(vm.errors, vm.model);
                          document.getElementById('page-wrapper').scrollIntoView();
                      }
                      else {
                          $rootScope.$broadcast("loader_show");
                          toaster.pop({
                              type: 'success',
                              title: 'Success',
                              body: 'Your profile have been successfully updated',
                              timeout: 2500,
                              onHideCallback: function () {
                                  $rootScope.$broadcast("loader_hide");

                                  if (originalModel.firstName) {
                                      if (originalModel.title !== vm.model.title || originalModel.firstName !== vm.model.firstName || originalModel.lastName !== vm.model.lastName) {
                                        location.reload();
                                      }
                                  }
                              }
                          });
                      }
                  });
            }
            else {// Client-side validation
                vm.errors = [];// Clear out the client errors first
                document.getElementById('page-wrapper').scrollIntoView();
            }
            utilitySvc.invalidateControlOnSubmission(form);
        }

        function clearSubmitErrorClassValues() {
            if (vm.model.ahpranumber_error && vm.model.ahpranumber_error != null)
                vm.model.ahpranumber_error = undefined;
            if (vm.model.prescribernumber_error && vm.model.prescribernumber_error != null)
                vm.model.prescribernumber_error = undefined;
        }

        /************Accreditation****************************/
        function addAccreditations() {
            vm.model.hcp.accreditations.push({
                id: 0,
                type: 0,
                membershipNumber: "",
                hcpId: vm.model.hcp.id,
                isDeleted: false
            });
        }

        function deleteAccreditations(index) {
            vm.model.hcp.accreditations.splice(index, 1);
            if (vm.model.hcp.accreditations.length == 0) {
                addAccreditations();
            }
        }

        function removeAllEmptyAccList() {
            for (var pos in vm.model.hcp.accreditations) {
                if (vm.model.hcp.accreditations[pos].id == 0
                    && vm.model.hcp.accreditations[pos].type == 0) {
                    vm.model.hcp.accreditations.splice(pos, 1);
                }
            }
            if (vm.model.hcp.accreditations.length == 0) {
                addAccreditations();
            }
        }
        /*****************End of Acc**************************/

        var objectIdVal = 0;
        function generateObjectProperty(obj) {
            objectIdVal = objectIdVal == 0 ? obj.objectId : objectIdVal;

            return {
                id: obj.id,
                propertyValueId: obj.propertyValueId,
                value: obj.value,
                propertyId: obj.propertyId,
                objectId: obj.objectId
            }
        }

        function findPrimaryInstitution(hcpInstitutionList) {
            for (var pos in hcpInstitutionList) {
                if (hcpInstitutionList[pos].isPrimaryInstitution) {
                    return hcpInstitutionList[pos];
                }
            }
            return null;
        }

        function getItems(url) {
            var items = [];

            return httpService.get(url, { disable_loading: true })
                .then(function (response) {
                    response.data.forEach(function (item) {
                        items.push(item);
                    });
                    return items;
                });
        }

        function isDuplicatedOption(id, optionList) {
            for (var pos in optionList) {
                if (id == optionList[pos].propertyValueId) {
                    if (!optionList[pos].isDeleted) {
                        return true;
                    }
                }
            }
            return false;
        }

        ////////////////////////// INSTITUTION //////////////////////////
        function cancelPrimaryInstition() {
            for (var pos in vm.model.hcp.hcpInstitutions) {
                if (vm.model.hcp.hcpInstitutions[pos].isPrimaryInstitution) {
                    vm.model.hcp.hcpInstitutions[pos].isPrimaryInstitution = false;
                    return;
                }
            }
        }

        vm.isFormAddressDisabled = true;
        vm.isStateSuburbPostCodeInputsDisabled = false;

        vm.disableAddressInputs = function () {
            return vm.isFormAddressDisabled;
        }

        vm.requireInputs = function () {
            return !vm.isFormAddressDisabled;
        }

        vm.isStateSuburbPostCodeDisabled = function () {
            return vm.isStateSuburbPostCodeInputsDisabled;
        }

        vm.getInstitutions = getInstitutions;
        vm.onSelectInstitution = onSelectInstitution;
        vm.onNewInstitution = onNewInstitution;
        vm.onClearInstitution = onClearInstitution;

        function getInstitutions(value) {
            var url = api_institution_search.replace('{0}', value);
            return getItems(url);
        }

        function addManualInstitution() {
            var address = {
                id: 0,
                addrLine1: vm.model.address.addrLine1,
                addrLine2: vm.model.address.addrLine2,
                postcode: vm.model.address.postcode,
                state: vm.model.address.state,
                stateName: vm.states[vm.model.address.state].Name,// options is not correct, need to check with others
                suburb: vm.model.address.suburb
            };

            var institution = {
                id: 0,
                address: address,
                email: "",
                fax: "",
                isDeleted: false,
                name: vm.model.mainInsName,
                phone: ""
            };

            cancelPrimaryInstition();
            vm.model.hcp.hcpInstitutions.push({
                id: 0,
                institution: institution,
                hcpId: vm.model.hcp.id,
                institutionId: 0
            });
            vm.model.hcp.hcpInstitutions[vm.model.hcp.hcpInstitutions.length - 1].isPrimaryInstitution = true;
        }

        function onNewInstitution() {
            vm.model.hcp.hcpInstitutions = [];
            vm.isFormAddressDisabled = false;
            clearAddress();
            if (vm.model.mainInsName != null && vm.model.mainInsName != "") {
                vm.model.mainInsName = null;                
                cancelPrimaryInstition();
            }
            vm.isSelectedAddress = false;
            vm.isInstitutionFormDisabled = false;
            vm.isStateSuburbPostCodeInputsDisabled = false;
            vm.insIsSearchDisabled = true;
            vm.isInstitutionNameRequired = true;
        }

        function onSelectInstitution(item) {
            vm.model.hcp.hcpInstitutions = [];
            cancelPrimaryInstition();
            vm.model.hcp.hcpInstitutions.push({
                id: item.id,
                institution: item,
                hcpId: vm.model.hcp.id,
                institutionId: item.id
            });
            vm.model.hcp.hcpInstitutions[0].isPrimaryInstitution = true;

            vm.model.mainInsName = item.name;
            vm.model.address = item.address;
            vm.isFormAddressDisabled = true;
            vm.isSelectedAddress = true;
            vm.isInstitutionNameRequired = false;

            vm.isInstitutionFormDisabled = true;
            vm.isStateSuburbPostCodeInputsDisabled = true;
            $timeout(function () {
                $scope.$apply();
            }, 0);
        }

        function isPrimaryInstitutionExist() {
            for (var pos in vm.model.hcp.hcpInstitutions) {
                if (vm.model.hcp.hcpInstitutions[pos].isPrimaryInstitution) {
                    return true;
                }
            }
            return false;
        }

        function clearAddress() {
            if (vm.model.address) {
                vm.model.address = {};
            }
        }

        function onClearInstitution() { // you can only clear the institution data 
            vm.isFormAddressDisabled = true;
            clearAddress();
            if (vm.model.mainInsName != null && vm.model.mainInsName != "") {                
                vm.model.mainInsName = null;
                cancelPrimaryInstition();
            }
            vm.isInstitutionNameRequired = false;
            vm.isInstitutionFormDisabled = false;
            vm.isFormAddressDisabled = true;
            vm.isStateSuburbPostCodeInputsDisabled = false;
            vm.isSelectedAddress = true;
            vm.insIsSearchDisabled = false;
            $timeout(function () {
                $scope.$apply();
            }, 0);
        }
        //////////////////////// INSTITUTION //////////////////////////

        /**************************** Area ***************************/

        vm.getAreaType = getAreaType;
        vm.removeAreas = removeAreas;
        vm.onSelectArea = onSelectArea;
        vm.onAddArea = onAddArea;
        vm.isAddAreaButtonDisabled = true;
        vm.isAreaFieldDisabled = false;


        function removeAreas(index) {
            if (vm.model.areasCovered[index] != null) {
                vm.model.areasCovered[index].isDeleted = true;
            }
        }

        function getAreaType(value) {
            return getObjectType(value, formConfig.areaPropertyId);
        }

        function getObjectType(value, type) {
            var url = api_propertyvalues_search.replace('{propertyId:int?}', type).replace('{keyword?}', value);
            return getItems(url);
        }

        function onSelectArea(item) {
            //vm.objectProperties = item;
            vm.model.areaPropertyValue = item;
            vm.isAddAreaButtonDisabled = false;
            vm.isAreaFieldDisabled = true;
        }

        function onAddArea() {
            var item = vm.model.areaPropertyValue;
            vm.isAreaFieldDisabled = false;
            if (item && item.id != undefined) {
                if (isDuplicatedOption(item.id, vm.model.areasCovered)) return;
                vm.model.areasCovered.push({
                    propertyValueId: item.id,
                    value: item.value,
                    propertyId: 7,
                    objectId: objectIdVal,
                    isDeleted: false
                });
            }
            vm.model.areaPropertyValue = null;
            vm.isAddAreaButtonDisabled = true;
        }

        /**************************** End of Area ********************/

        /*************************** Language ********************************/
        vm.removeLanguages = removeLanguages;
        vm.getLanguageType = getLanguageType;
        vm.onSelectLanguage = onSelectLanguage;
        vm.onAddLanguage = onAddLanguage;
        vm.isAddLanguageButtonDisabled = true;
        vm.isLanguageFieldDisabled = false;

        function getLanguageType(value) {
            return getObjectType(value, formConfig.languagePropertyId);
        }

        function onSelectLanguage(item) {
            //vm.model.value = item;
            vm.model.languagePropertyValue = item;
            vm.isAddLanguageButtonDisabled = false;
            vm.isLanguageFieldDisabled = true;
        }

        function onAddLanguage() {
            var item = vm.model.languagePropertyValue;
            vm.isLanguageFieldDisabled = false;
            if (item && item.id != undefined) {
                if (isDuplicatedOption(item.id, vm.model.languagesSpoken)) return;
                vm.model.languagesSpoken.push({
                    propertyValueId: item.id,
                    value: item.value,
                    propertyId: 8,
                    objectId: objectIdVal,
                    isDeleted: false
                });
            }
            vm.model.languagePropertyValue = null;
            vm.isAddLanguageButtonDisabled = true;
        }

        function removeLanguages(index) {
            if (vm.model.languagesSpoken[index] != null) {
                vm.model.languagesSpoken[index].isDeleted = true;
            }
        }

        /*******************************End of Language*****************************/

        /******************************Change UserInfo********************************/

        function submitMyUserName(form, isInputDiff) {
            if (form.$valid && !isInputDiff) {
                httpService.post(api_changeUserName, vm.model)
                .then(function (response) {
                    vm.changeUserNameErrors = [];
                    vm.changeUserNameErrors = response.data.errors;
                    //Server-side validation
                    if (response.data.errors.length > 0) {
                        modelStateErrorBuilder.build(vm.changeUserNameErrors, vm.model);
                        document.getElementById('userNameChangeError').scrollIntoView();
                    }
                    else {
                        $rootScope.logOut();
                    }
                });
            }
            else {// Client-side validation
                document.getElementById('userNameChangeError').scrollIntoView();
            }
            utilitySvc.invalidateControlOnSubmission(form);
        }

        function submitMyPassword(form) {
            if (form.$valid) {
                httpService.post(api_changePassword, vm.model)
               .then(function (response) {
                   vm.changePasswordErrors = [];
                   vm.changePasswordErrors = response.data.errors;
                   //Server-side validation
                   if (response.data.errors.length > 0) {
                       modelStateErrorBuilder.build(vm.changePasswordErrors, vm.model);
                       document.getElementById('passwordChangeError').scrollIntoView();
                   }
                   else {
                       $rootScope.logOut();
                   }
               });
            }
            else {// Client-side validation
                document.getElementById('passwordChangeError').scrollIntoView();
            }
            utilitySvc.invalidateControlOnSubmission(form);
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('NavController', NavController);
   
    function NavController() {
        var vm = this;
        vm.init = init;
       
        function init(menus) {
            vm.menus = [];
            vm.menus = menus;
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('UserAddController', UserAddController);
    UserAddController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout'];

    function UserAddController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout) {
        var vm = this;
        vm.errors = [];
        vm.submit = submit;
        vm.changeRole = changeRole;
        vm.model = vm.model || {};
        vm.getInstitutions = getInstitutions;
        vm.onSelectInstitution = onSelectInstitution;
        vm.onNewInstitution = onNewInstitution;
        vm.clearInstitution = clearInstitution;
        vm.addAccreditations = addAccreditations;
        vm.deleteAccreditations = deleteAccreditations;
        vm.model.listAccreditation = [];
        vm.hcp = { institution: { address: {} } };
        vm.init = init;
        vm.isCreateNonHCP = true;
        vm.IsShowNewInstitution = true;
        vm.IsShowClearInstitution = true;
        vm.isAddressDisabled = true;
        vm.isSuburbStatePostcodeDisabled = false;
        vm.isInstitutionAndAddr1Required = false;
        vm.institutionId = -1;
        vm.isSearchInstitution = true;
        vm.otherProfession = formConfig.otherProfession;
        vm.changeAccreditationType = changeAccreditationType;
        function init() {
            var url = api_getRoles;
            httpService.get(url)
                .success(function (response) {
                    vm.roles = response.data;
                    console.log(vm.roles);
                });
            initLookups();
            addAccreditations();
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
                .success(function (data) {
                    console.log(data);
                    vm.titles = data.Title;
                    vm.status = data.User_Status;
                    vm.states = data.State;
                    vm.professions = data.Hcp_Profession;
                    vm.accreditations = data.HcpAccreditation_Type;
                    vm.targets = data.Hcp_TargetClass;
                });
        }

        function addAccreditations() {
            vm.model.listAccreditation.push({
                type: 0,
                membershipNumber: ""
            });
        }

        function deleteAccreditations(index) {
            vm.model.listAccreditation.splice(index, 1);
        }

        function changeAccreditationType(item) {
            vm.errors = [];
            var count = 0;
            $.each(vm.model.listAccreditation,
                function(index, element) {
                    if (element.type === item.type) {
                        count++;
                    }
                });

            if (count > 1) {
                addError('Duplicate Accreditation type');
                item.type = 0;
                scrollToTop();
            }
        }

        function changeRole() {
            console.log(vm.model.role);
            if (vm.model.role == formConfig.hcpRole) {
                vm.isCreateNonHCP = false;
            } else {
                vm.isCreateNonHCP = true;
            }
        }

        function getInstitutions(value) {
            if (vm.isSearchInstitution == true) {
                var institutions = [];
                return httpService.get(api_institution_search.replace('{0}', value).replace('{1}', ''), { disable_loading: true })
                    .then(function(response) {

                        response.data.forEach(function(item) {
                            institutions.push(item);
                        });

                        angular.forEach(vm.hcp.institutions, function(item, idx) {

                            if (idx != vm.hcp.institutionSelectedIndex) {
                                angular.forEach(institutions, function(item2, idx2) {
                                    if (item.name == item2.name)
                                        institutions.splice(idx2, 1);
                                });
                            }
                        });
                        console.log(institutions);
                        return institutions;
                    });
            }
        }

        function onSelectInstitution(item) {
            vm.hcp.institution = item;
            vm.hcp.institution.mode = 'select';
            vm.hcp.isInstitutionFormDisabled = true;
            vm.institutionId = item.id;
            vm.IsShowClearInstitution = true;
            vm.IsShowNewInstitution = true;
            vm.isAddressDisabled = true;
            vm.isSuburbStatePostcodeDisabled = true;
            vm.isInstitutionAndAddr1Required = false;
        }

        function onNewInstitution() {
            //vm.hcp.institution = { name: vm.hcp.institution.name };
            vm.hcp.institution = {}
            vm.hcp.institution.mode = 'add';
            vm.institutionId = 0;
            vm.hcp.isInstitutionFormDisabled = false;
            $('#addressLine1').prop('disabled', false);
            $('#addressLine2').prop('disabled', false);
            vm.isSearchInstitution = false;
            vm.isAddressDisabled = false;
            vm.isSuburbStatePostcodeDisabled = false;
            vm.isInstitutionAndAddr1Required = true;
        }

        function clearInstitution(institution) {
            vm.institutionId = -1;
            if (institution) {
                vm.hcp.institution = {
                    name: undefined,
                    address: {
                    },
                    mode: 'add'
                };
                $('#addressLine1').prop('disabled', true);
                $('#addressLine2').prop('disabled', true);
            }
            vm.isSearchInstitution = true;
            vm.isAddressDisabled = true;
            vm.isSuburbStatePostcodeDisabled = false;
            vm.isInstitutionAndAddr1Required = false;
        }

        function submit(form) {
            utilitySvc.invalidateControlOnSubmission(form);
            if (vm.model.listAccreditation && vm.model.listAccreditation != null) {
                vm.model.listAccreditation = $.grep(vm.model.listAccreditation, function (value) {
                    return value.type != null && value.type !== 0;
                });
            }

            vm.isSearchInstitution = true;
            if (vm.isCreateNonHCP) {
                if (isFormAddUserValid(form)) {
                    httpService.post(api_addNovoUser, vm.model)
                        .then(function (response) {
                            vm.errors = [];
                            vm.errors = response.data.errors;
                            if (response.data.errors.length > 0) {
                                modelStateErrorBuilder.build(vm.errors, vm.model);
                                scrollToTop();
                            } else {
                                redirectUserList();
                            }
                        });
                } else {
                    scrollToTop();
                }
            } else {
                if (isFormAddHcpUserValid(form)) {
                    vm.model.institution = vm.hcp.institution;
                    vm.model.institution.id = vm.institutionId;
                    console.log(vm.model);
                    httpService.post(api_add_HCPUser, vm.model)
                        .then(function (response) {
                            vm.errors = [];
                            vm.errors = response.data.errors;
                            console.log(response);
                            if (response.data.errors.length > 0) {
                                modelStateErrorBuilder.build(vm.errors, vm.model);
                                scrollToTop();
                            } else {
                                redirectUserList();
                            }
                        });
                } else {
                    scrollToTop();
                }
            }
        }

        function isFormAddUserValid(form) {
            vm.errors = [];
            var isValid = true;
            var roles = vm.model.role;
            var status = vm.model.status;

            if (roles == "" || roles == null || roles === undefined) {
                isValid = false;
            }
            if (status == "" || status == null || status === undefined) {
                isValid = false;
            }
            if (form.email.$error.required) {
                isValid = false;
            }
            if (form.confirmEmail.$error.required) {
                isValid = false;
            }
            if (form.firstName.$error.required) {
                isValid = false;
            }
            if (form.lastName.$error.required) {
                isValid = false;
            }

            if (!isValid) {
                addError("All fields highlighted in red are mandatory");;
            }
            if (form.mobile.$error.phone) {
                isValid = false;
                addError("Please specify a valid mobile number");
            }

            if (form.phone.$error.phone) {
                isValid = false;
                addError("Please specify a valid phone number");
            }

            if (isValid) {
                var emailValid = isValidEmail(vm.model.email, vm.model.confirmEmail);
                if (!emailValid) {
                    isValid = false;
                } 
            }
            return isValid;
        }
        function isFormAddHcpUserValid(form) {
            vm.errors = [];
            var isValid = true;
            var roles = vm.model.role;
            var status = vm.model.status;
            var states = vm.hcp.institution.address.state;

            if (roles == "" || roles == null || roles === undefined) {
                isValid = false;
            }
            if (status == "" || status == null || status === undefined) {
                isValid = false;
            }
            if (states == "" || states == null || states === undefined) {
                isValid = false;
            }
            if (form.email.$error.required) {
                isValid = false;
            }
            if (form.confirmEmail.$error.required) {
                isValid = false;
            }
            if (form.firstName.$error.required) {
                isValid = false;
            }
            if (form.lastName.$error.required) {
                isValid = false;
            }
            if (form.suburb.$error.required) {
                isValid = false;
            }

            if (form.profession.$error.required) {
                isValid = false;
            }
            if (!isValid) {
                addError("All fields highlighted in red are mandatory");
            }

            if (form.mobile.$error.phone) {
                isValid = false;
                addError("Please specify a valid mobile number");
            }

            if (form.phone.$error.phone) {
                isValid = false;
                addError("Please specify a valid phone number");
            }

            if (form.Fax.$error.phone) {
                isValid = false;
                addError("Please specify a valid fax number");
            }

            if (isValid) {
               var emailValid = isValidEmail(vm.model.email, vm.model.confirmEmail);
                var addressValid = isAddressValid();
                var ahpraNumberValid = isAhpraNumberValid();
                var providerNumberValid = isProviderNumberValid();
                var otherFieldValid = isOtherValid();
                var postCodeValid = isPostCode();
                var accrediationMembershipValid = isAccrediationMembershipValid();
                var duplicateMemberShipValid = isDuplicateMemberShipValie();
                if (!emailValid || !addressValid || !ahpraNumberValid || !providerNumberValid || !otherFieldValid || !accrediationMembershipValid || !duplicateMemberShipValid  || !postCodeValid) {
                    isValid = false;
                }
            }

            return isValid;
        }

        function isAddressValid() {
            if (vm.institutionId >= 0) {
                if ((vm.hcp.institution.address.addrLine1 == '' || vm.hcp.institution.address.addrLine1 == undefined) && vm.hcp.institution.name != '' && vm.hcp.institution.name != undefined) {
                    addError("Address line 1 is required if the primary place of work is provided");
                    return false;
                }
            }
            return true;
        }
        function isOtherValid() {
            var profession = vm.model.profession;
            if (profession == formConfig.otherProfession && (vm.model.otherProfession == '' || vm.model.otherProfession == undefined)) {
                addError("Other value must be provided when 'other' profession is selected");
                return false;
            }
            return true;
        }

        function isAccrediationMembershipValid() {
            //var incre = 0;
            //angular.forEach(vm.model.listAccreditation,
            //           function (item) {
            //               if (incre == 0) {
            //                   if (item.membershipNumber == '' || item.membershipNumber == null || item.membershipNumber == undefined) {
            //                       addError("Please enter Membership Number");
            //                       incre++;
            //                   }
            //               }
            //           });
            //if(incre > 0)
            //    return false;
            //else 
            //    return true;
            return true;
        }

        function isDuplicateMemberShipValie() {
            var finalSort = vm.model.listAccreditation;
            finalSort.sort(function(a, b) { return b.type > a.type });
            for (var i = 0; i < finalSort.length - 1; i++) {
                if (finalSort[i + 1].type == finalSort[i].type) {
                    if (finalSort[i + 1].membershipNumber == finalSort[i].membershipNumber) {
                        addError("Membership number is unique in each accreditation type");
                        return false;
                    }
                }
            }
            return true;
        }

        function isAhpraNumberValid() {
            var ahpraNumber = vm.model.ahpraNumber;
            var profession = vm.model.profession;
            var regexAhpraNumberFormat = /^[a-zA-Z]{3,}\d{10}$/;
            var isValid = true;
            if (ahpraNumber != undefined && ahpraNumber != null && ahpraNumber.length > 0) {
                if (!regexAhpraNumberFormat.test(ahpraNumber)) {
                    addError("AHPRA number should start with three letters and ends with 10 digits");
                    isValid = false;
                }
                //general physician or specialist or general practioner
                if (profession == 2 || profession == 8 || profession == 3) {
                    if (ahpraNumber.substr(0, 3).toUpperCase() != "MED") {
                        addError("AHPRA number should start with MED");
                        isValid = false;
                    }
                }
                    //nurse practioner or registered nurse
                else if (profession == 4 || profession == 6) {
                    if (ahpraNumber.substr(0, 3).toUpperCase() != "NMW") {
                        addError("AHPRA number should start with NMW");
                        isValid = false;
                    }
                }
                    //pharmacist
                else if (profession == 5) {
                    if (ahpraNumber.substr(0, 3).toUpperCase() != "PHA") {
                        addError("AHPRA number should start with PHA");
                        isValid = false;
                    }
                }
            }
            return isValid;
        }

        function isProviderNumberValid() {
            var providerNumber = vm.model.prescriberNumber;
            var regexStartsWithSixDigits = /^\d{6,}/;
            var regexSeventhCharacter = /(I|O|S|Z)/;
            var regexEigthCharacter = /(A|B|F|H|J|K|L|T|W|X|Y)/;

            if (providerNumber != null && providerNumber != undefined && providerNumber.length > 0) {
                if (providerNumber.length != 8) {
                    vm.errors.push({
                        message: "Provider number must have 8 characters"
                    });
                    return false;
                }
                else if (!regexStartsWithSixDigits.test(providerNumber)) {
                    vm.errors.push({
                        message: "Provider number must start with 6 digits"
                    });
                    return false;
                }
                else if (regexSeventhCharacter.test(providerNumber.substr(6, 1))) {
                    vm.errors.push({
                        message: "Provider number seventh character must be a digit or alpha character that is NOT I, O, S or Z"
                });
                    return false;
                }
                else if (!regexEigthCharacter.test(providerNumber.substr(7, 1))) {
                    vm.errors.push({
                        message: "Provider number eigth character must be one of the following alpha characters A, B, F, H, J, K, L, T, W, X, Y"
                    });
                    return false;
                }
            }
            return true;
        }

        function isValidEmail(val1, val2) {
            var isValid = true;
            if (val1 != "" && !isEmail(val1)) {
                addError("Please specify a valid email");
                isValid = false;
            }
            if (val2 != "" && !isEmail(val2)) {
                addError("Please specify a valid confirm email");
                isValid = false;
            }
            if (isValid) {
                if (val1 != val2) {
                    addError("'Confirm email' and email does not match");
                }
            }
            return isValid;
        }

        function redirectUserList() {
            window.location.href = formConfig.userListUrl;
        }

        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }
        function isEmail(value) {
            value = value === undefined || value == null ? "" : value;
            var regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
            var val = $.trim(value);
            return regex.test(val);
        }
        function addError(message) {
            var isExists = false;

            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists)
                vm.errors.push({
                    message: message
                });
        }

        function isPostCode() {
            var postCode = vm.hcp.institution.address.postcode;
            if (postCode != null && postCode != undefined && postCode.length > 0) {
                if (postCode.length < 4) {
                    addError("Postcode must be 4 digits");
                    return false;
                }
            }
            return true;
        }

        function isPhone() {
            var phone = vm.model.phone;
            var mobile = vm.model.mobile;
            var fax = vm.model.fax;
            //var regex = /@"^[0-9]*$"/;
            var inValid = true;
            if (phone != null && phone != undefined && phone.length > 0) {
                if (phone.length < 10) {
                    addError("Phone must be 10 digits");
                    inValid = false;
                }
            }
            if (mobile != null && mobile != undefined && mobile.length > 0) {
                if (mobile.length < 10) {
                    addError("Mobile must be 10 digits");
                    inValid = false;
                }
            }
            if (fax != null && fax != undefined && fax.length > 0) {
                if (fax.length < 10) {
                    addError("Fax must be 10 digits");
                    inValid = false;
                }
            }
            return inValid;
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('UserEditController', UserEditController);
    UserEditController.$inject = ['$scope', '$window', 'modelStateErrorBuilder', 'utilitySvc', 'httpService',
        'formConfig', '$timeout'];

    function UserEditController($scope, $window, modelStateErrorBuilder, utilitySvc, httpService,
        formConfig, $timeout) {
        var vm = this;
        vm.submit = submit;
        vm.changeRole = changeRole;
        vm.model = vm.model || {};
        vm.getInstitutions = getInstitutions;
        vm.onSelectInstitution = onSelectInstitution;
        vm.onNewInstitution = onNewInstitution;
        vm.clearInstitution = clearInstitution;
        vm.deleteUser = deleteUser;
        vm.userRole = formConfig.userRole;
        vm.viewOnly = formConfig.viewOnly;

        vm.init = init;
        function init() {
            var url = api_getRoles;
            httpService.get(url)
                .success(function (response) {
                    vm.roles = response.data;
                    vm.roles = $.grep(vm.roles, function (element) {
                        return element.value != formConfig.hcpRole;
                    });
                });
            $('#chkInSendNotification').change(function () {
                vm.model.isSendNotification = $(this).prop('checked');
            });
            initLookups();
            if (formConfig.userRole.toLowerCase() == 'systemadmin')
                vm.loginRole = 'System Admin';
            else if (formConfig.userRole.toLowerCase() == 'superuser')
                vm.loginRole = 'Super User';
        }

        function initLookups() {
            httpService.get(api_lookup_byType.replace('{0}', formConfig.lookupType))
            .success(function (data) {
                console.log(data);
                vm.titles = data.Title;
                vm.status = data.User_Status;
                vm.states = data.State;
            }).then(function (data) {
                getUserNonHCP();
            });
        }

        function getUserNonHCP() {
            httpService.get(api_get_nonHCPUser.replace('{id}', formConfig.userId))
            .success(function (response) {
                console.log(response);
                vm.model = response;
            });
        }

        function changeRole() {
            if (vm.model.role == formConfig.hcpRole) {
                $('#hcpFields1').removeClass('hidden');
                $('#hcpFields2').removeClass('hidden');
            } else {
                $('#hcpFields1').addClass('hidden');
                $('#hcpFields2').addClass('hidden');
            }
        }

        function getInstitutions(value) {
            var institutions = [];
            return httpService.get(api_institution_search.replace('{0}', value).replace('{1}', ''), { disable_loading: true })
                .then(function (response) {

                    response.data.forEach(function (item) {
                        institutions.push(item);
                    });

                    angular.forEach(vm.hcp.institutions, function (item, idx) {

                        if (idx != vm.hcp.institutionSelectedIndex) {
                            angular.forEach(institutions, function (item2, idx2) {
                                if (item.name == item2.name)
                                    institutions.splice(idx2, 1);
                            });
                        }
                    });
                    console.log(institutions);
                    return institutions;
                });
        }

        function onSelectInstitution(item) {
            vm.hcp.institution = item;
            vm.hcp.institution.mode = 'select';
            vm.hcp.isInstitutionFormDisabled = true;

            vm.IsShowClearInstitution = true;
            vm.IsShowNewInstitution = true;
        }

        function onNewInstitution() {
            vm.hcp.institution = { name: "" };
            vm.hcp.institution.mode = 'add';
            vm.hcp.isInstitutionFormDisabled = false;
        }

        function clearInstitution(institution) {
            if (institution) {
                vm.hcp.institution = {
                    name: undefined,
                    address: {
                    },
                    mode: 'add'
                };
            }
        }
        function isFormAddUserValid(form) {
            vm.errors = [];
            var isValid = true;

            var roles = vm.model.role;
            var status = vm.model.status;

            if (roles == "" || roles == null || roles === undefined) {
                isValid = false;
            }
            if (status == "" || status == null || status === undefined) {
                isValid = false;
            }
            if (form.email.$error.required) {
                isValid = false;
            }
            if (form.firstName.$error.required) {
                isValid = false;
            }
            if (form.lastName.$error.required) {
                isValid = false;
            }
            if (!isValid) {
                addError("All fields highlighted in red are mandatory");;
            }

            if (form.mobile.$error.phone) {
                addError("Please specify a valid mobile number");
                isValid = false;
            }

            if (form.phone.$error.phone) {
                addError("Please specify a valid phone number");
                isValid = false;
            }

            if (isValid) {
                return isValidEmail(vm.model.email);
            }
            return isValid;
        }
        function isValidEmail(val1) {
            var isValid = true;
            if (val1 != "" && !isEmail(val1)) {
                addError("Please specify a valid email");
                isValid = false;
            }
            return isValid;
        }
        function submit(form) {
            utilitySvc.invalidateControlOnSubmission(form);
            if (isFormAddUserValid(form)) {
                clearSubmitErrorClassValues();
                vm.model.isSendNotification = vm.model.isSendNotification;
                console.log(vm.model);
                httpService.post(api_edit_nonHCPUser, vm.model)
                    .then(function (response) {
                        vm.errors = [];
                        vm.errors = response.data.errors;
                        if (response.data.errors.length > 0) {
                            modelStateErrorBuilder.build(vm.errors, vm.model);
                        } else {
                            redirectUserList();
                        }
                    });
            }
            else {
                scrollToTop();
            }
        }
        function clearSubmitErrorClassValues() {
            if (vm.model.ahpranumber_error && vm.model.ahpranumber_error != null)
                vm.model.ahpranumber_error = undefined;
            if (vm.model.ahpranumber_error && vm.model.ahpranumber_error != null)
                vm.model.ahpranumber_error = undefined;
        }
        function deleteUser() {
            httpService.post(api_delete_User, formConfig.userId)
                 .then(function (response) {
                     if (response.data.success) {
                         redirectUserList();
                     } else {
                         response.data.errors.forEach(function (error) {
                             addError(error.message);
                         });
                     }
                 });
        }
        function redirectUserList() {
            document.location.href = "/admin/users";
        }
        function isValid(form) {
            if (form.$error.required !== undefined) {
                for (var i = 0; i < form.$error.required.length; i++) {
                    form.$error.required[i].$setDirty();
                }
            }
            if (form.$error.requireChecked !== undefined) {
                for (var i = 0; i < form.$error.requireChecked.length; i++) {
                    form.$error.requireChecked[i].$setDirty();
                }
            }
        }

        function isEmailAndConfirmEmailMatching() {
            var email = vm.model.email;
            var confirmEmail = vm.model.confirmEmail;

            if (email != confirmEmail) {
                vm.errors.push({
                    message: "Confirm email doesn't match with entered email"
                });
                return false;
            }
            return true;
        }

        function scrollToTop() {
            document.getElementById('wrapper').scrollIntoView();
        }
        function isEmail(value) {
            value = value === undefined || value == null ? "" : value;
            var regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
            var val = $.trim(value);
            return regex.test(val);
        }
        function addError(message) {
            var isExists = false;

            for (var i = 0; i < vm.errors.length; i++) {
                if (vm.errors[i] == message) {
                    isExists = true;
                    break;
                }
            }

            if (!isExists)
                vm.errors.push({
                    message: message
                });
        }
    }
})();;
(function () {
    'use strict';

    window.app.controller('UserListController', UserListController);
    UserListController.$inject = ['$rootScope', '$scope', '$window', 'filterFilter', 'httpService',
        'uiGridConstants', 'moment', 'utilitySvc', 'formConfig'];

    function UserListController($rootScope, $scope, $window, filterFilter, httpService,
        uiGridConstants, moment, utilitySvc,formConfig) {
        var vm = this;

        vm.searchOption = {
            pageNumber: 1,
            pageSize: 25,
            sort: '-createdOn',
            keyword: ''
        };
        vm.roleHcp = formConfig.roleHcp;
        vm.gridOptions = utilitySvc.uiGrid.createDefaultUIGridOptions(uiGridConstants, vm.searchOption, getUsers);
        //vm.gridOptions.excessRows = 100;
        vm.gridOptions.columnDefs = [
            { name: 'createdOn', displayName: 'Registered date', maxWidth: 120, enableCellEdit: false },
            { name: 'fullName', displayName: 'User', enableCellEdit: false },
            { name: 'role', displayName: 'Role', maxWidth: 180, enableCellEdit: false },
            { name: 'email', displayName: 'Email', maxWidth: 300, enableCellEdit: false },
            { name: 'statusName', displayName: 'Status', maxWidth: 150, enableCellEdit: false },
            {
                name: 'ims', displayName: 'IMS', maxWidth: 150, enableCellEdit: true,
                cellEditableCondition: function ($scope) {
                    return $scope.row.entity.hcpId != null && $scope.row.entity.hcpId > 0;
                }
            },
            {
                field: 'id',
                maxWidth: 50,
                enableSorting: false,
                displayName: '',
                enableCellEdit: false,
                cellTemplate: '<div class="ui-grid-cell-contents text-center">' +
                    '<a ng-if="row.entity.roleId != ' + vm.roleHcp + '" ng-href="/admin/users/edit/{{COL_FIELD}}">edit</a>' +
                    '<a ng-if="row.entity.roleId == ' + vm.roleHcp + '" ng-href="/admin/users/hcp/edit/{{row.entity.hcpId}}">edit</a>' +
                    '</div>'
            }
        ];

        var defaultOnRegisterApi = vm.gridOptions.onRegisterApi;
        vm.gridOptions.onRegisterApi = function (gridApi) {
            //$scope.gridApi = gridApi;
            gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
                if (colDef.name === 'ims' && oldValue !== newValue) {
                    updateIms(rowEntity, newValue, oldValue);
                }
            });

            defaultOnRegisterApi(gridApi);
        };

        function updateIms(rowEntity, newValue, oldValue) {
            vm.errors = [];
            var url = api_hcp_updateIms;
            url += '?hcpId=' + rowEntity.hcpId;
            url += '&imsNumber=' + rowEntity.ims;
            httpService.post(url)
                .then(function(response) {
                    getUsers();
                    if (!response.data.success) {
                        vm.errors = response.data.errors;
                    }
                });
        }

        // This is to watch the filter value changed, and call the getUsers again!
        $scope.$watch('vm.filterValue', function (newValue, oldValue) {
            if (newValue !== undefined) {
                vm.searchOption.keyword = newValue;
                getUsers();
            }
        });

        // this is to resize the table height of ui-grid
        vm.getTableHeightStyle = function () {
            return utilitySvc.uiGrid.getTableHeightStyle(vm.gridOptions);
        }

        vm.init = function () {
            $rootScope.$broadcast("loader_show");
            getUsers();
        };

        function getUsers() {
            var url = api_user_search;
            var browserTimeZone = moment.tz.guess();
            url = url.replace('{pageSize}', vm.searchOption.pageSize);
            url = url.replace('{pageNo}', vm.searchOption.pageNumber);
            url = url.replace('{sortFields}', vm.searchOption.sort);
            url = url.replace('{1}', vm.searchOption.keyword);
            url = url.replace('{0}', browserTimeZone);

            return httpService.get(url).then(function (response) {
                if (response.data.success) {
                    vm.gridOptions.totalItems = response.data.data.totalCount;

                    angular.forEach(response.data.data.result,
                        function(user) {
                            user.createdOn = moment.utc(user.createdOn).local().format("DD/MM/YYYY");
                        });

                    vm.gridOptions.data = response.data.data.result;
                } else {
                    vm.errors = response.data.errors;
                }
            });
        }
    }
})();;
