13 lines
404 KiB
JavaScript
13 lines
404 KiB
JavaScript
"use strict";var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},function(){var hostUrl=localStorage.getItem("host")?"https://"+localStorage.getItem("host"):"",rootDir=localStorage.getItem("rootDir")||"",RESTWS=hostUrl+"/openmrs/ws/rest",RESTWS_V1=hostUrl+"/openmrs/ws/rest/v1",BAHMNI_CORE=RESTWS_V1+"/bahmnicore",EMRAPI=RESTWS+"/emrapi",BACTERIOLOGY=RESTWS_V1,BASE_URL=hostUrl+"/bahmni_config/openmrs/apps/",CUSTOM_URL=hostUrl+"/implementation_config/openmrs/apps/",IE_APPS_API=RESTWS_V1+"/bahmniie",serverErrorMessages=[{serverMessage:"Cannot have more than one active order for the same orderable and care setting at same time",clientMessage:"One or more drugs you are trying to order are already active. Please change the start date of the conflicting drug or remove them from the new prescription."},{serverMessage:"[Order.cannot.have.more.than.one]",clientMessage:"One or more drugs you are trying to order are already active. Please change the start date of the conflicting drug or remove them from the new prescription."}],representation="custom:(uuid,name,names,conceptClass,setMembers:(uuid,name,names,conceptClass,setMembers:(uuid,name,names,conceptClass,setMembers:(uuid,name,names,conceptClass))))",unAuthenticatedReferenceDataMap={"/openmrs/ws/rest/v1/location?tags=Login+Location&s=byTags&v=default":"LoginLocations","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=locale.allowed.list":"LocaleList"},authenticatedReferenceDataMap={"/openmrs/ws/rest/v1/idgen/identifiertype":"IdentifierTypes","/openmrs/module/addresshierarchy/ajax/getOrderedAddressHierarchyLevels.form":"AddressHierarchyLevels","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=mrs.genders":"Genders","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=bahmni.encountersession.duration":"encounterSessionDuration","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=bahmni.relationshipTypeMap":"RelationshipTypeMap","/openmrs/ws/rest/v1/bahmnicore/config/bahmniencounter?callerContext=REGISTRATION_CONCEPTS":"RegistrationConcepts","/openmrs/ws/rest/v1/relationshiptype?v=custom:(aIsToB,bIsToA,uuid)":"RelationshipType","/openmrs/ws/rest/v1/personattributetype?v=custom:(uuid,name,sortWeight,description,format,concept)":"PersonAttributeType","/openmrs/ws/rest/v1/entitymapping?mappingType=loginlocation_visittype&s=byEntityAndMappingType":"LoginLocationToVisitTypeMapping","/openmrs/ws/rest/v1/bahmnicore/config/patient":"PatientConfig","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Consultation+Note&v=custom:(uuid,name,answers)":"ConsultationNote","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Lab+Order+Notes&v=custom:(uuid,name)":"LabOrderNotes","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Impression&v=custom:(uuid,name)":"RadiologyImpressionConfig","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=All_Tests_and_Panels&v=custom:(uuid,name:(uuid,name),setMembers:(uuid,name:(uuid,name)))":"AllTestsAndPanelsConcept","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Dosage+Frequency&v=custom:(uuid,name,answers)":"DosageFrequencyConfig","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Dosage+Instructions&v=custom:(uuid,name,answers)":"DosageInstructionConfig","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=bahmni.encounterType.default":"DefaultEncounterType","/openmrs/ws/rest/v1/concept?s=byFullySpecifiedName&name=Stopped+Order+Reason&v=custom:(uuid,name,answers)":"StoppedOrderReasonConfig","/openmrs/ws/rest/v1/ordertype":"OrderType","/openmrs/ws/rest/v1/bahmnicore/config/drugOrders":"DrugOrderConfig","/openmrs/ws/rest/v1/bahmnicore/sql/globalproperty?property=drugOrder.drugOther":"NonCodedDrugConcept"};authenticatedReferenceDataMap["/openmrs/ws/rest/v1/entitymapping?mappingType=location_encountertype&s=byEntityAndMappingType&entityUuid="+(localStorage.getItem("LoginInformation")?JSON.parse(localStorage.getItem("LoginInformation")).currentLocation.uuid:"")]="LoginLocationToEncounterTypeMapping",Bahmni.Common.Constants={hostURL:hostUrl,dateFormat:"dd/mm/yyyy",dateDisplayFormat:"DD-MMM-YYYY",timeDisplayFormat:"hh:mm",emrapiDiagnosisUrl:EMRAPI+"/diagnosis",bahmniDiagnosisUrl:BAHMNI_CORE+"/diagnosis/search",bahmniDeleteDiagnosisUrl:BAHMNI_CORE+"/diagnosis/delete",diseaseTemplateUrl:BAHMNI_CORE+"/diseaseTemplates",AllDiseaseTemplateUrl:BAHMNI_CORE+"/diseaseTemplate",emrapiConceptUrl:EMRAPI+"/concept",encounterConfigurationUrl:BAHMNI_CORE+"/config/bahmniencounter",patientConfigurationUrl:BAHMNI_CORE+"/config/patient",drugOrderConfigurationUrl:BAHMNI_CORE+"/config/drugOrders",emrEncounterUrl:EMRAPI+"/encounter",encounterUrl:RESTWS_V1+"/encounter",locationUrl:RESTWS_V1+"/location",bahmniVisitLocationUrl:BAHMNI_CORE+"/visitLocation",bahmniOrderUrl:BAHMNI_CORE+"/orders",bahmniDrugOrderUrl:BAHMNI_CORE+"/drugOrders",bahmniDispositionByVisitUrl:BAHMNI_CORE+"/disposition/visitWithLocale",bahmniDispositionByPatientUrl:BAHMNI_CORE+"/disposition/patientWithLocale",bahmniSearchUrl:BAHMNI_CORE+"/search",bahmniLabOrderResultsUrl:BAHMNI_CORE+"/labOrderResults",bahmniEncounterUrl:BAHMNI_CORE+"/bahmniencounter",conceptUrl:RESTWS_V1+"/concept",bahmniConceptAnswerUrl:RESTWS_V1+"/bahmniconceptanswer",conceptSearchByFullNameUrl:RESTWS_V1+"/concept?s=byFullySpecifiedName",visitUrl:RESTWS_V1+"/visit",endVisitUrl:BAHMNI_CORE+"/visit/endVisit",endVisitAndCreateEncounterUrl:BAHMNI_CORE+"/visit/endVisitAndCreateEncounter",visitTypeUrl:RESTWS_V1+"/visittype",patientImageUrlByPatientUuid:RESTWS_V1+"/patientImage?patientUuid=",labResultUploadedFileNameUrl:"/uploaded_results/",visitSummaryUrl:BAHMNI_CORE+"/visit/summary",encounterModifierUrl:BAHMNI_CORE+"/bahmniencountermodifier",openmrsUrl:hostUrl+"/openmrs",loggingUrl:hostUrl+"/log/",idgenConfigurationURL:RESTWS_V1+"/idgen/identifiertype",bahmniRESTBaseURL:BAHMNI_CORE+"",observationsUrl:BAHMNI_CORE+"/observations",obsRelationshipUrl:BAHMNI_CORE+"/obsrelationships",encounterImportUrl:BAHMNI_CORE+"/admin/upload/encounter",programImportUrl:BAHMNI_CORE+"/admin/upload/program",conceptImportUrl:BAHMNI_CORE+"/admin/upload/concept",conceptSetImportUrl:BAHMNI_CORE+"/admin/upload/conceptset",drugImportUrl:BAHMNI_CORE+"/admin/upload/drug",labResultsImportUrl:BAHMNI_CORE+"/admin/upload/labResults",referenceTermsImportUrl:BAHMNI_CORE+"/admin/upload/referenceterms",updateReferenceTermsImportUrl:BAHMNI_CORE+"/admin/upload/referenceterms/new",relationshipImportUrl:BAHMNI_CORE+"/admin/upload/relationship",conceptSetExportUrl:BAHMNI_CORE+"/admin/export/conceptset?conceptName=:conceptName",patientImportUrl:BAHMNI_CORE+"/admin/upload/patient",adminImportStatusUrl:BAHMNI_CORE+"/admin/upload/status",programUrl:RESTWS_V1+"/program",programEnrollPatientUrl:RESTWS_V1+"/bahmniprogramenrollment",programStateDeletionUrl:RESTWS_V1+"/programenrollment",programEnrollmentDefaultInformation:"default",programEnrollmentFullInformation:"full",programAttributeTypes:RESTWS_V1+"/programattributetype",relationshipTypesUrl:RESTWS_V1+"/relationshiptype",personAttributeTypeUrl:RESTWS_V1+"/personattributetype",diseaseSummaryPivotUrl:BAHMNI_CORE+"/diseaseSummaryData",allTestsAndPanelsConceptName:"All_Tests_and_Panels",dosageFrequencyConceptName:"Dosage Frequency",dosageInstructionConceptName:"Dosage Instructions",stoppedOrderReasonConceptName:"Stopped Order Reason",consultationNoteConceptName:"Consultation Note",diagnosisConceptSet:"Diagnosis Concept Set",radiologyOrderType:"Radiology Order",radiologyResultConceptName:"Radiology Result",investigationEncounterType:"INVESTIGATION",validationNotesEncounterType:"VALIDATION NOTES",labOrderNotesConcept:"Lab Order Notes",impressionConcept:"Impression",qualifiedByRelationshipType:"qualified-by",dispositionConcept:"Disposition",dispositionGroupConcept:"Disposition Set",dispositionNoteConcept:"Disposition Note",ruledOutDiagnosisConceptName:"Ruled Out Diagnosis",emrapiConceptMappingSource:"org.openmrs.module.emrapi",abbreviationConceptMappingSource:"Abbreviation",includeAllObservations:!1,openmrsObsUrl:RESTWS_V1+"/obs",openmrsObsRepresentation:"custom:(uuid,obsDatetime,value:(uuid,name:(uuid,name)))",admissionCode:"ADMIT",dischargeCode:"DISCHARGE",transferCode:"TRANSFER",undoDischargeCode:"UNDO_DISCHARGE",vitalsConceptName:"Vitals",heightConceptName:"HEIGHT",weightConceptName:"WEIGHT",bmiConceptName:"BMI",bmiStatusConceptName:"BMI STATUS",abnormalObservationConceptName:"IS_ABNORMAL",documentsPath:"/document_images",documentsConceptName:"Document",miscConceptClassName:"Misc",abnormalConceptClassName:"Abnormal",unknownConceptClassName:"Unknown",durationConceptClassName:"Duration",conceptDetailsClassName:"Concept Details",admissionEncounterTypeName:"ADMISSION",dischargeEncounterTypeName:"DISCHARGE",imageClassName:"Image",videoClassName:"Video",locationCookieName:"bahmni.user.location",retrospectiveEntryEncounterDateCookieName:"bahmni.clinical.retrospectiveEncounterDate",JSESSIONID:"JSESSIONID",rootScopeRetrospectiveEntry:"retrospectiveEntry.encounterDate",patientFileConceptName:"Patient file",serverErrorMessages:serverErrorMessages,currentUser:"bahmni.user",retrospectivePrivilege:"app:clinical:retrospective",locationPickerPrivilege:"app:clinical:locationpicker",onBehalfOfPrivilege:"app:clinical:onbehalf",nutritionalConceptName:"Nutritional Values",messageForNoObservation:"NO_OBSERVATIONS_CAPTURED",messageForNoDisposition:"NO_DISPOSTIONS_AVAILABLE_MESSAGE_KEY",messageForNoFulfillment:"NO_FULFILMENT_MESSAGE",reportsUrl:"/bahmnireports",uploadReportTemplateUrl:"/bahmnireports/upload",ruledOutdiagnosisStatus:"Ruled Out Diagnosis",registartionConsultationPrivilege:"app:common:registration_consultation_link",manageIdentifierSequencePrivilege:"Manage Identifier Sequence",closeVisitPrivilege:"app:common:closeVisit",deleteDiagnosisPrivilege:"app:clinical:deleteDiagnosis",viewPatientsPrivilege:"View Patients",editPatientsPrivilege:"Edit Patients",addVisitsPrivilege:"Add Visits",deleteVisitsPrivilege:"Delete Visits",grantProviderAccess:"app:clinical:grantProviderAccess",grantProviderAccessDataCookieName:"app.clinical.grantProviderAccessData",globalPropertyUrl:BAHMNI_CORE+"/sql/globalproperty",passwordPolicyUrl:BAHMNI_CORE+"/globalProperty/passwordPolicyProperties",fulfillmentConfiguration:"fulfillment",fulfillmentFormSuffix:" Fulfillment Form",noNavigationLinksMessage:"NO_NAVIGATION_LINKS_AVAILABLE_MESSAGE",conceptSetRepresentationForOrderFulfillmentConfig:representation,entityMappingUrl:RESTWS_V1+"/entitymapping",encounterTypeUrl:RESTWS_V1+"/encountertype",defaultExtensionName:"default",orderSetMemberAttributeTypeUrl:RESTWS_V1+"/ordersetmemberattributetype",orderSetUrl:RESTWS_V1+"/bahmniorderset",primaryOrderSetMemberAttributeTypeName:"Primary",bahmniBacteriologyResultsUrl:BACTERIOLOGY+"/specimen",bedFromVisit:RESTWS_V1+"/beds",ordersUrl:RESTWS_V1+"/order",formDataUrl:RESTWS_V1+"/obs",providerUrl:RESTWS_V1+"/provider",drugUrl:RESTWS_V1+"/drug",orderTypeUrl:RESTWS_V1+"/ordertype",userUrl:RESTWS_V1+"/user",passwordUrl:RESTWS_V1+"/password",formUrl:RESTWS_V1+"/form",allFormsUrl:RESTWS_V1+"/bahmniie/form/allForms",latestPublishedForms:RESTWS_V1+"/bahmniie/form/latestPublishedForms",formTranslationsUrl:RESTWS_V1+"/bahmniie/form/translations",sqlUrl:BAHMNI_CORE+"/sql",patientAttributeDateFieldFormat:"org.openmrs.util.AttributableDate",platform:"user.platform",RESTWS_V1:RESTWS_V1,baseUrl:BASE_URL,customUrl:CUSTOM_URL,faviconUrl:hostUrl+"/bahmni/favicon.ico",platformType:{other:"other"},numericDataType:"Numeric",encryptionType:{SHA3:"SHA3"},LoginInformation:"LoginInformation",ServerDateTimeFormat:"YYYY-MM-DDTHH:mm:ssZZ",calculateDose:BAHMNI_CORE+"/calculateDose",unAuthenticatedReferenceDataMap:unAuthenticatedReferenceDataMap,authenticatedReferenceDataMap:authenticatedReferenceDataMap,rootDir:rootDir,dischargeUrl:BAHMNI_CORE+"/discharge",uuidRegex:"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",eventlogFilterUrl:hostUrl+"/openmrs/ws/rest/v1/eventlog/filter",bahmniConnectMetaDataDb:"metaData",serverDateTimeUrl:"/cgi-bin/systemdate",loginText:"/bahmni_config/openmrs/apps/home/whiteLabel.json",auditLogUrl:RESTWS_V1+"/auditlog",appointmentServiceUrl:RESTWS_V1+"/appointmentService",conditionUrl:EMRAPI+"/condition",conditionHistoryUrl:EMRAPI+"/conditionhistory",followUpConditionConcept:"Follow-up Condition",localeLangs:"/bahmni_config/openmrs/apps/home/locale_languages.json",privilegeRequiredErrorMessage:"PRIVILEGE_REQUIRED",patientFormsUrl:BAHMNI_CORE+"/patient/{patientUuid}/forms",defaultPossibleRelativeSearchLimit:10,formBuilderDisplayControlType:"formsV2",formBuilderType:"v2",formBuilderTranslationApi:IE_APPS_API+"/form/translate",disposition:"DISPOSITION",registration:"REGISTRATION",clinical:"CLINICAL",diagnosis:"DIAGNOSIS",ot:"OT",patientAttribute:"PATIENT_ATTRIBUTE",program:"PROGRAM",visitType:"VISIT_TYPE",bedmanagement:"BEDMANAGEMENT",bedmanagementDisposition:"BEDMANAGEMENT_DISPOSITION",loginConfig:"/bahmni_config/openmrs/apps/home/login_config.json",visit:"VISIT"}}(),angular.module("bahmni.common.routeErrorHandler",["ui.router"]).run(["$rootScope",function($rootScope){$rootScope.$on("$stateChangeError",function(event){event.preventDefault()})}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.Util=Bahmni.Common.Util||{},angular.module("bahmni.common.util",[]).provider("$bahmniCookieStore",[function(){var self=this;self.defaultOptions={};var fixedEncodeURIComponent=function(str){return encodeURIComponent(str).replace(/[!'()*]/g,function(c){return"%"+c.charCodeAt(0).toString(16)})};self.setDefaultOptions=function(options){self.defaultOptions=options},self.$get=function(){return{get:function(name){var jsonCookie=$.cookie(name);return jsonCookie?angular.fromJson(decodeURIComponent(jsonCookie)):null},put:function(name,value,options){options=$.extend({},self.defaultOptions,options),$.cookie.raw=!0,$.cookie(name,fixedEncodeURIComponent(angular.toJson(value)),options)},remove:function(name,options){options=$.extend({},self.defaultOptions,options),$.removeCookie(name,options)}}}}]),Bahmni.Common.Util.DateUtil={diffInDays:function(dateFrom,dateTo){return Math.floor((this.parse(dateTo)-this.parse(dateFrom))/864e5)},diffInMinutes:function(dateFrom,dateTo){return moment(dateTo).diff(moment(dateFrom),"minutes")},diffInSeconds:function(dateFrom,dateTo){return moment(dateFrom).diff(moment(dateTo),"seconds")},isInvalid:function(date){return"Invalid Date"==date},diffInDaysRegardlessOfTime:function(dateFrom,dateTo){var from=new Date(dateFrom),to=new Date(dateTo);return from.setHours(0,0,0,0),to.setHours(0,0,0,0),Math.floor((to-from)/864e5)},addSeconds:function(date,seconds){return moment(date).add(seconds,"seconds").toDate()},addMinutes:function(date,minutes){return this.addSeconds(date,60*minutes)},addDays:function(date,days){return moment(date).add(days,"day").toDate()},addMonths:function(date,months){return moment(date).add(months,"month").toDate()},addYears:function(date,years){return moment(date).add(years,"year").toDate()},subtractSeconds:function(date,seconds){return moment(date).subtract(seconds,"seconds").toDate()},subtractDays:function(date,days){return this.addDays(date,-1*days)},subtractISOWeekDays:function(date,days){return null==days?moment(date).isoWeekday():moment(date).isoWeekday()>=days?moment(date).isoWeekday()-days:7+moment(date).isoWeekday()-days},subtractMonths:function(date,months){return this.addMonths(date,-1*months)},subtractYears:function(date,years){return this.addYears(date,-1*years)},createDays:function(startDate,endDate){for(var startDate=this.getDate(startDate),endDate=this.getDate(endDate),numberOfDays=this.diffInDays(startDate,endDate),days=[],i=0;i<=numberOfDays;i++)days.push({dayNumber:i+1,date:this.addDays(startDate,i)});return days},getDayNumber:function(referenceDate,date){return this.diffInDays(this.getDate(referenceDate),this.getDate(date))+1},getDateWithoutTime:function(datetime){return datetime?moment(datetime).format("YYYY-MM-DD"):null},getDateInMonthsAndYears:function(date,format){var format=format||"MMM YY",dateRepresentation=isNaN(Number(date))?date:Number(date);return moment(dateRepresentation).isValid()?dateRepresentation?moment(dateRepresentation).format(format):null:date},formatDateWithTime:function(datetime){var dateRepresentation=isNaN(Number(datetime))?datetime:Number(datetime);return moment(dateRepresentation).isValid()?dateRepresentation?moment(dateRepresentation).format("DD MMM YY h:mm a"):null:datetime},formatDateWithoutTime:function(date){var dateRepresentation=isNaN(Number(date))?date:Number(date);return moment(dateRepresentation).isValid()?dateRepresentation?moment(dateRepresentation).format("DD MMM YY"):null:date},formatDateInStrictMode:function(date){var dateRepresentation=isNaN(Number(date))?date:Number(date);return moment(dateRepresentation,"YYYY-MM-DD",!0).isValid()?moment(dateRepresentation).format("DD MMM YY"):moment(dateRepresentation,"YYYY-MM-DDTHH:mm:ss.SSSZZ",!0).isValid()?moment(dateRepresentation).format("DD MMM YY"):date},formatTime:function(date){var dateRepresentation=isNaN(Number(date))?date:Number(date);return moment(dateRepresentation).isValid()?dateRepresentation?moment(dateRepresentation).format("h:mm a"):null:date},getDate:function(dateTime){return moment(this.parse(dateTime)).startOf("day").toDate()},parse:function(dateString){return dateString?moment(dateString).toDate():null},parseDatetime:function(dateTimeString){return dateTimeString?moment(dateTimeString):null},now:function(){return new Date},today:function(){return this.getDate(this.now())},endOfToday:function(){return moment(this.parse(this.now())).endOf("day").toDate()},getDateWithoutHours:function(dateString){return moment(dateString).toDate().setHours(0,0,0,0)},getDateTimeWithoutSeconds:function(dateString){return moment(dateString).toDate().setSeconds(0,0)},isSameDateTime:function(date1,date2){if(null==date1||null==date2)return!1;var dateOne=this.parse(date1),dateTwo=this.parse(date2);return dateOne.getTime()==dateTwo.getTime()},isBeforeDate:function(date1,date2){return moment(date1).isBefore(moment(date2))},isSameDate:function(date1,date2){if(null==date1||null==date2)return!1;var dateOne=this.parse(date1),dateTwo=this.parse(date2);return dateOne.getFullYear()===dateTwo.getFullYear()&&dateOne.getMonth()===dateTwo.getMonth()&&dateOne.getDate()===dateTwo.getDate()},diffInYearsMonthsDays:function(dateFrom,dateTo){dateFrom=this.parse(dateFrom),dateTo=this.parse(dateTo);var from={d:dateFrom.getDate(),m:dateFrom.getMonth(),y:dateFrom.getFullYear()},to={d:dateTo.getDate(),m:dateTo.getMonth(),y:dateTo.getFullYear()},age={d:0,m:0,y:0},daysFebruary=to.y%4!=0||to.y%100==0&&to.y%400!=0?28:29,daysInMonths=[31,daysFebruary,31,30,31,30,31,31,30,31,30,31];return age.y=to.y-from.y,age.m=to.m-from.m,from.m>to.m&&(age.y=age.y-1,age.m=to.m-from.m+12),age.d=to.d-from.d,from.d>to.d&&(age.m=age.m-1,from.m==to.m&&(age.y=age.y-1,age.m=age.m+12),age.d=to.d-from.d+daysInMonths[parseInt(from.m)]),{days:age.d,months:age.m,years:age.y}},convertToUnits:function(minutes){var allUnits={Years:525600,Months:43200,Weeks:10080,Days:1440,Hours:60,Minutes:1},durationRepresentation=function(value,unitName,unitValueInMinutes){return{value:value,unitName:unitName,unitValueInMinutes:unitValueInMinutes,allUnits:allUnits}};for(var unitName in allUnits){var unitValueInMinutes=allUnits[unitName];if((minutes||0!==minutes)&&minutes>=unitValueInMinutes&&minutes%unitValueInMinutes===0)return durationRepresentation(minutes/unitValueInMinutes,unitName,unitValueInMinutes)}return durationRepresentation(void 0,void 0,void 0)},getEndDateFromDuration:function(dateFrom,value,unit){dateFrom=this.parse(dateFrom);var from={h:dateFrom.getHours(),d:dateFrom.getDate(),m:dateFrom.getMonth(),y:dateFrom.getFullYear()},to=new Date(from.y,from.m,from.d,from.h);return"Months"===unit?to.setMonth(from.m+value):"Weeks"===unit?to.setDate(from.d+7*value):"Days"===unit?to.setDate(from.d+value):"Hours"===unit&&to.setHours(from.h+value),to},parseLongDateToServerFormat:function(longDate){return longDate?moment(longDate).format("YYYY-MM-DDTHH:mm:ss.SSS"):null},parseServerDateToDate:function(longDate){return longDate?moment(longDate,"YYYY-MM-DDTHH:mm:ss.SSSZZ").toDate():null},getDateTimeInSpecifiedFormat:function(date,format){return date?moment(date).format(format):null},getISOString:function(date){return date?moment(date).toDate().toISOString():null},isBeforeTime:function(time,otherTime){return moment(time,"hh:mm a").format("YYYY-MM-DD")},getWeekStartDate:function(date,startOfWeek){var daysToBeSubtracted=this.subtractISOWeekDays(date,startOfWeek);return moment(date).subtract(daysToBeSubtracted,"days").toDate()},getWeekEndDate:function(weekStartDate){return moment(weekStartDate).add(6,"days").toDate()}},Bahmni.Common.Util.ArrayUtil={chunk:function(array,chunkSize){for(var chunks=[],i=0;i<array.length;i+=chunkSize)chunks.push(array.slice(i,i+chunkSize));return chunks},groupByPreservingOrder:function(records,groupingFunction,keyName,valueName){var groups=[];return records.forEach(function(record){var recordKey=groupingFunction(record),existingGroup=_.find(groups,function(group){return group[keyName]===recordKey});if(existingGroup)existingGroup[valueName].push(record);else{var newGroup={};newGroup[keyName]=recordKey,newGroup[valueName]=[record],groups.push(newGroup)}}),groups}},angular.module("httpErrorInterceptor",[]).config(["$httpProvider",function($httpProvider){var interceptor=["$rootScope","$q",function($rootScope,$q){function stringAfter(value,searchString){var indexOfFirstColon=value.indexOf(searchString);return value.substr(indexOfFirstColon+1).trim()}function getServerError(message){return stringAfter(message,":")}function success(response){return response}function shouldRedirectToLogin(response){var errorMessage=response.data.error?response.data.error.message:response.data;if(errorMessage.search("HTTP Status 403 - Session timed out")>0)return!0}function error(response){var data=response.data,unexpectedError="There was an unexpected issue on the server. Please try again";if(500===response.status){var errorMessage=data.error&&data.error.message?getServerError(data.error.message):unexpectedError;showError(errorMessage)}else if(409===response.status){var errorMessage=data.error&&data.error.message?getServerError(data.error.message):"Duplicate entry error";showError(errorMessage)}else if(0===response.status)showError("Could not connect to the server. Please check your connection and try again");else if(405===response.status)showError(unexpectedError);else if(400===response.status){var errorMessage=data.error&&data.error.message?data.error.message:data.localizedMessage||"Could not connect to the server. Please check your connection and try again";showError(errorMessage)}else if(403===response.status){var errorMessage=data.error&&data.error.message?data.error.message:unexpectedError;shouldRedirectToLogin(response)?$rootScope.$broadcast("event:auth-loginRequired"):showError(errorMessage)}else 404===response.status&&(_.includes(response.config.url,"implementation_config")||_.includes(response.config.url,"locale_")||_.includes(response.config.url,"offlineMetadata")||showError("The requested information does not exist"));return $q.reject(response)}var serverErrorMessages=Bahmni.Common.Constants.serverErrorMessages,showError=function(errorMessage){var result=_.find(serverErrorMessages,function(listItem){return listItem.serverMessage===errorMessage});_.isEmpty(result)&&$rootScope.$broadcast("event:serverError",errorMessage)};return{response:success,responseError:error}}];$httpProvider.interceptors.push(interceptor)}]),Modernizr.addTest("ios",function(){return!!navigator.userAgent.match(/(iPad|iPhone|iPod)/i)}),Modernizr.addTest("windowOS",function(){return navigator.appVersion.indexOf("Win")!=-1}),$(function(){Modernizr.ios&&$(document).on("click","label[for]",function(){var $inputElement=$("input#"+$(this).attr("for")),elementType=$inputElement.attr("type");"radio"===elementType?$inputElement.prop("checked",!0):"checkbox"===elementType?$inputElement.prop("checked",!$inputElement.prop("checked")):$inputElement.focus()})}),Bahmni.Common.Util.DateTimeFormatter={getDateWithoutTime:function(datetime){return datetime?moment(datetime).format("YYYY-MM-DD"):null}};var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.Models=Bahmni.Common.Models||{},angular.module("bahmni.common.models",[]);var Bahmni=Bahmni||{};Bahmni.Auth=Bahmni.Auth||{},angular.module("authentication",["ui.router"]),Bahmni.Auth.User=function(user){angular.extend(this,user),this.userProperties=user.userProperties||{},this.favouriteObsTemplates=this.userProperties.favouriteObsTemplates?this.userProperties.favouriteObsTemplates.split("###"):[],this.favouriteWards=this.userProperties.favouriteWards?this.userProperties.favouriteWards.split("###"):[],this.recentlyViewedPatients=this.userProperties.recentlyViewedPatients?JSON.parse(this.userProperties.recentlyViewedPatients):[],this.toContract=function(){var user=angular.copy(this);return user.userProperties.favouriteObsTemplates=this.favouriteObsTemplates.join("###"),user.userProperties.favouriteWards=this.favouriteWards.join("###"),user.userProperties.recentlyViewedPatients=JSON.stringify(this.recentlyViewedPatients),delete user.favouriteObsTemplates,delete user.favouriteWards,delete user.recentlyViewedPatients,user},this.addDefaultLocale=function(locale){this.userProperties.defaultLocale=locale},this.addToRecentlyViewed=function(patient,maxPatients){_.some(this.recentlyViewedPatients,{uuid:patient.uuid})||(this.recentlyViewedPatients.unshift({uuid:patient.uuid,name:patient.name,identifier:patient.identifier}),_.size(this.recentlyViewedPatients)>=maxPatients&&(this.recentlyViewedPatients=_.take(this.recentlyViewedPatients,maxPatients)))},this.isFavouriteObsTemplate=function(conceptName){return _.includes(this.favouriteObsTemplates,conceptName)},this.toggleFavoriteObsTemplate=function(conceptName){this.isFavouriteObsTemplate(conceptName)?this.favouriteObsTemplates=_.without(this.favouriteObsTemplates,conceptName):this.favouriteObsTemplates.push(conceptName)},this.isFavouriteWard=function(wardName){return _.includes(this.favouriteWards,wardName)},this.toggleFavoriteWard=function(wardName){this.isFavouriteWard(wardName)?this.favouriteWards=_.without(this.favouriteWards,wardName):this.favouriteWards.push(wardName)}},angular.module("authentication").service("userService",["$rootScope","$http","$q",function($rootScope,$http,$q){var getUserFromServer=function(userName){return $http.get(Bahmni.Common.Constants.userUrl,{method:"GET",params:{username:userName,v:"custom:(username,uuid,person:(uuid,),privileges:(name,retired),userProperties)"},cache:!1})};this.getUser=function(userName){var deferrable=$q.defer();return getUserFromServer(userName).success(function(data){deferrable.resolve(data)}).error(function(){deferrable.reject("Unable to get user data")}),deferrable.promise},this.savePreferences=function(){var deferrable=$q.defer(),user=$rootScope.currentUser.toContract();return $http.post(Bahmni.Common.Constants.userUrl+"/"+user.uuid,{uuid:user.uuid,userProperties:user.userProperties},{withCredentials:!0}).then(function(response){$rootScope.currentUser.userProperties=response.data.userProperties,deferrable.resolve()}),deferrable.promise};var getProviderFromServer=function(uuid){return $http.get(Bahmni.Common.Constants.providerUrl,{method:"GET",params:{user:uuid},cache:!1})};this.getProviderForUser=function(uuid){var deferrable=$q.defer();return getProviderFromServer(uuid).success(function(data){if(data.results.length>0){var providerName=data.results[0].display.split("-")[1];data.results[0].name=providerName?providerName.trim():providerName,deferrable.resolve(data)}else deferrable.reject("UNABLE_TO_GET_PROVIDER_DATA")}).error(function(){deferrable.reject("UNABLE_TO_GET_PROVIDER_DATA")}),deferrable.promise},this.getPasswordPolicies=function(){return $http.get(Bahmni.Common.Constants.passwordPolicyUrl,{method:"GET",withCredentials:!0})},this.allowedDomains=function(redirectUrl){var deferrable=$q.defer();return $http.get(Bahmni.Common.Constants.loginConfig,{method:"GET",cache:!0}).success(function(data){deferrable.resolve(data.whiteListedDomains)}).error(function(){deferrable.resolve([])}),deferrable.promise}}]),angular.module("authentication").config(["$httpProvider",function($httpProvider){var interceptor=["$rootScope","$q",function($rootScope,$q){function success(response){return response}function error(response){return 401===response.status&&$rootScope.$broadcast("event:auth-loginRequired"),$q.reject(response)}return{response:success,responseError:error}}];$httpProvider.interceptors.push(interceptor)}]).run(["$rootScope","$window","$timeout",function($rootScope,$window,$timeout){$rootScope.$on("event:auth-loginRequired",function(){$timeout(function(){$window.location="../home/index.html#/login"})})}]).service("sessionService",["$rootScope","$http","$q","$bahmniCookieStore","userService",function($rootScope,$http,$q,$bahmniCookieStore,userService){var sessionResourcePath=Bahmni.Common.Constants.RESTWS_V1+"/session?v=custom:(uuid)",getAuthFromServer=function(username,password,otp){var btoa=otp?username+":"+password+":"+otp:username+":"+password;return $http.get(sessionResourcePath,{headers:{Authorization:"Basic "+window.btoa(btoa)},cache:!1})};this.resendOTP=function(username,password){var btoa=username+":"+password;return $http.get(sessionResourcePath+"&resendOTP=true",{headers:{Authorization:"Basic "+window.btoa(btoa)},cache:!1})};var createSession=function(username,password,otp){var deferrable=$q.defer();return destroySessionFromServer().success(function(){getAuthFromServer(username,password,otp).then(function(response){204==response.status&&deferrable.resolve({firstFactAuthorization:!0}),deferrable.resolve(response.data)},function(response){401==response.status?deferrable.reject("LOGIN_LABEL_WRONG_OTP_MESSAGE_KEY"):410==response.status?deferrable.reject("LOGIN_LABEL_OTP_EXPIRED"):429==response.status&&deferrable.reject("LOGIN_LABEL_MAX_FAILED_ATTEMPTS"),deferrable.reject("LOGIN_LABEL_LOGIN_ERROR_MESSAGE_KEY")})}).error(function(){deferrable.reject("LOGIN_LABEL_LOGIN_ERROR_MESSAGE_KEY")}),deferrable.promise},hasAnyActiveProvider=function(providers){return _.filter(providers,function(provider){return void 0==provider.retired||"false"==provider.retired}).length>0},self=this,destroySessionFromServer=function(){return $http.delete(sessionResourcePath)},sessionCleanup=function(){delete $.cookie(Bahmni.Common.Constants.currentUser,null,{path:"/"}),delete $.cookie(Bahmni.Common.Constants.currentUser,null,{path:"/"}),delete $.cookie(Bahmni.Common.Constants.retrospectiveEntryEncounterDateCookieName,null,{path:"/"}),delete $.cookie(Bahmni.Common.Constants.grantProviderAccessDataCookieName,null,{path:"/"}),$rootScope.currentUser=void 0};this.destroy=function(){var deferrable=$q.defer();return destroySessionFromServer().then(function(){sessionCleanup(),deferrable.resolve()}),deferrable.promise},this.loginUser=function(username,password,location,otp){var deferrable=$q.defer();return createSession(username,password,otp).then(function(data){data.authenticated?($bahmniCookieStore.put(Bahmni.Common.Constants.currentUser,username,{path:"/",expires:7}),void 0!=location&&($bahmniCookieStore.remove(Bahmni.Common.Constants.locationCookieName),$bahmniCookieStore.put(Bahmni.Common.Constants.locationCookieName,{name:location.display,uuid:location.uuid},{path:"/",expires:7})),deferrable.resolve(data)):data.firstFactAuthorization?deferrable.resolve(data):deferrable.reject("LOGIN_LABEL_LOGIN_ERROR_MESSAGE_KEY")},function(errorInfo){deferrable.reject(errorInfo)}),deferrable.promise},this.get=function(){return $http.get(sessionResourcePath,{cache:!1})},this.loadCredentials=function(){var deferrable=$q.defer(),currentUser=$bahmniCookieStore.get(Bahmni.Common.Constants.currentUser);return currentUser?(userService.getUser(currentUser).then(function(data){userService.getProviderForUser(data.results[0].uuid).then(function(providers){
|
|
!_.isEmpty(providers.results)&&hasAnyActiveProvider(providers.results)?($rootScope.currentUser=new Bahmni.Auth.User(data.results[0]),$rootScope.currentUser.currentLocation=$bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName).name,$rootScope.$broadcast("event:user-credentialsLoaded",data.results[0]),deferrable.resolve(data.results[0])):(self.destroy(),deferrable.reject("YOU_HAVE_NOT_BEEN_SETUP_PROVIDER"))},function(){self.destroy(),deferrable.reject("COULD_NOT_GET_PROVIDER")})},function(){self.destroy(),deferrable.reject("Could not get roles for the current user.")}),deferrable.promise):(this.destroy().finally(function(){$rootScope.$broadcast("event:auth-loginRequired"),deferrable.reject("No User in session. Please login again.")}),deferrable.promise)},this.getLoginLocationUuid=function(){return $bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName)?$bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName).uuid:null},this.changePassword=function(currentUserUuid,oldPassword,newPassword){return $http({method:"POST",url:Bahmni.Common.Constants.passwordUrl,data:{oldPassword:oldPassword,newPassword:newPassword},headers:{"Content-Type":"application/json"}})},this.loadProviders=function(userInfo){return $http.get(Bahmni.Common.Constants.providerUrl,{method:"GET",params:{user:userInfo.uuid},cache:!1}).success(function(data){var providerUuid=data.results.length>0?data.results[0].uuid:void 0;$rootScope.currentProvider={uuid:providerUuid}})}}]).factory("authenticator",["$rootScope","$q","$window","sessionService",function($rootScope,$q,$window,sessionService){var authenticateUser=function(){var defer=$q.defer(),sessionDetails=sessionService.get();return sessionDetails.then(function(response){response.data.authenticated?defer.resolve():(defer.reject("User not authenticated"),$rootScope.$broadcast("event:auth-loginRequired"))}),defer.promise};return{authenticateUser:authenticateUser}}]).directive("logOut",["sessionService","$window","configurationService","auditLogService",function(sessionService,$window,configurationService,auditLogService){return{link:function(scope,element){element.bind("click",function(){scope.$apply(function(){auditLogService.log(void 0,"USER_LOGOUT_SUCCESS",void 0,"MODULE_LABEL_LOGOUT_KEY").then(function(){sessionService.destroy().then(function(){$window.location="../home/index.html#/login"})})})})}}}]).directive("btnUserInfo",[function(){return{restrict:"CA",link:function(scope,elem){elem.bind("click",function(event){$(this).next().toggleClass("active"),event.stopPropagation()}),$(document).find("body").bind("click",function(){$(elem).next().removeClass("active")})}}}]),angular.module("bahmni.common.appFramework",["authentication"]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.AppFramework=Bahmni.Common.AppFramework||{},angular.module("bahmni.common.appFramework").config(["$compileProvider",function($compileProvider){$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|file):/)}]).service("appService",["$http","$q","sessionService","$rootScope","mergeService","loadConfigService","messagingService","$translate",function($http,$q,sessionService,$rootScope,mergeService,loadConfigService,messagingService,$translate){var currentUser=null,baseUrl=Bahmni.Common.Constants.baseUrl,customUrl=Bahmni.Common.Constants.customUrl,appDescriptor=null;$rootScope.meetId=null;var loadConfig=function(url){return loadConfigService.loadConfig(url,appDescriptor.contextPath)},loadTemplate=function(appDescriptor){var deferrable=$q.defer();return loadConfig(baseUrl+appDescriptor.contextPath+"/appTemplate.json").then(function(result){_.keys(result.data).length>0&&appDescriptor.setTemplate(result.data),deferrable.resolve(appDescriptor)},function(error){404!==error.status?deferrable.reject(error):deferrable.resolve(appDescriptor)}),deferrable.promise},setDefinition=function(baseResultData,customResultData){customResultData&&(_.keys(baseResultData).length>0||_.keys(customResultData.length>0))?appDescriptor.setDefinition(baseResultData,customResultData):_.keys(baseResultData).length>0&&appDescriptor.setDefinition(baseResultData)},loadDefinition=function(appDescriptor){var deferrable=$q.defer();return loadConfig(baseUrl+appDescriptor.contextPath+"/app.json").then(function(baseResult){baseResult.data.shouldOverRideConfig?loadConfig(customUrl+appDescriptor.contextPath+"/app.json").then(function(customResult){setDefinition(baseResult.data,customResult.data),deferrable.resolve(appDescriptor)},function(){setDefinition(baseResult.data),deferrable.resolve(appDescriptor)}):(setDefinition(baseResult.data),deferrable.resolve(appDescriptor))},function(error){404!==error.status?deferrable.reject(error):deferrable.resolve(appDescriptor)}),deferrable.promise},setExtensions=function(baseResultData,customResultData){customResultData?appDescriptor.setExtensions(baseResultData,customResultData):appDescriptor.setExtensions(baseResultData)},loadExtensions=function(appDescriptor,extensionFileName){var deferrable=$q.defer();return loadConfig(baseUrl+appDescriptor.extensionPath+extensionFileName).then(function(baseResult){baseResult.data.shouldOverRideConfig?loadConfig(customUrl+appDescriptor.extensionPath+extensionFileName).then(function(customResult){setExtensions(baseResult.data,customResult.data),deferrable.resolve(appDescriptor)},function(){setExtensions(baseResult.data),deferrable.resolve(appDescriptor)}):(setExtensions(baseResult.data),deferrable.resolve(appDescriptor))},function(error){404!==error.status?deferrable.reject(error):deferrable.resolve(appDescriptor)}),deferrable.promise},setDefaultPageConfig=function(pageName,baseResultData,customResultData){customResultData&&(_.keys(customResultData).length>0||_.keys(baseResultData).length>0)?appDescriptor.addConfigForPage(pageName,baseResultData,customResultData):_.keys(baseResultData).length>0&&appDescriptor.addConfigForPage(pageName,baseResultData)},hasPrivilegeOf=function(privilegeName){return _.some(currentUser.privileges,{name:privilegeName})},loadPageConfig=function(pageName,appDescriptor){var deferrable=$q.defer();return loadConfig(baseUrl+appDescriptor.contextPath+"/"+pageName+".json").then(function(baseResult){baseResult.data.shouldOverRideConfig?loadConfig(customUrl+appDescriptor.contextPath+"/"+pageName+".json").then(function(customResult){setDefaultPageConfig(pageName,baseResult.data,customResult.data),deferrable.resolve(appDescriptor)},function(){setDefaultPageConfig(pageName,baseResult.data),deferrable.resolve(appDescriptor)}):(setDefaultPageConfig(pageName,baseResult.data),deferrable.resolve(appDescriptor))},function(error){404!==error.status?(messagingService.showMessage("error",$translate.instance("INCORRECT_CONFIGURATION_MESSAGE",{error:error.message})),deferrable.reject(error)):deferrable.resolve(appDescriptor)}),deferrable.promise};this.getAppDescriptor=function(){return appDescriptor},this.configBaseUrl=function(){return baseUrl},this.loadCsvFileFromConfig=function(name){return loadConfig(baseUrl+appDescriptor.contextPath+"/"+name)},this.loadConfig=function(name,shouldMerge){return loadConfig(baseUrl+appDescriptor.contextPath+"/"+name).then(function(baseResponse){return baseResponse.data.shouldOverRideConfig?loadConfig(customUrl+appDescriptor.contextPath+"/"+name).then(function(customResponse){return shouldMerge||void 0===shouldMerge?mergeService.merge(baseResponse.data,customResponse.data):[baseResponse.data,customResponse.data]},function(){return baseResponse.data}):baseResponse.data})},this.loadMandatoryConfig=function(path){return $http.get(path)},this.getAppName=function(){return this.appName},this.checkPrivilege=function(privilegeName){return hasPrivilegeOf(privilegeName)?$q.when(!0):(messagingService.showMessage("error",$translate.instant(Bahmni.Common.Constants.privilegeRequiredErrorMessage)+" [Privileges required: "+privilegeName+"]"),$q.reject())},this.initApp=function(appName,options,extensionFileSuffix,configPages){this.appName=appName;var appLoader=$q.defer(),extensionFileName=extensionFileSuffix&&"default"!==extensionFileSuffix.toLowerCase()?"/extension-"+extensionFileSuffix+".json":"/extension.json",promises=[],opts=options||{app:!0,extension:!0},inheritAppContext=!opts.inherit||opts.inherit;appDescriptor=new Bahmni.Common.AppFramework.AppDescriptor(appName,inheritAppContext,function(){return currentUser},mergeService);var loadCredentialsPromise=sessionService.loadCredentials(),loadProviderPromise=loadCredentialsPromise.then(sessionService.loadProviders);return promises.push(loadCredentialsPromise),promises.push(loadProviderPromise),opts.extension&&promises.push(loadExtensions(appDescriptor,extensionFileName)),opts.template&&promises.push(loadTemplate(appDescriptor)),opts.app&&promises.push(loadDefinition(appDescriptor)),_.isEmpty(configPages)||configPages.forEach(function(configPage){promises.push(loadPageConfig(configPage,appDescriptor))}),$q.all(promises).then(function(results){currentUser=results[0],appLoader.resolve(appDescriptor),$rootScope.$broadcast("event:appExtensions-loaded")},function(errors){appLoader.reject(errors)}),appLoader.promise}}]),angular.module("bahmni.common.appFramework").service("mergeService",[function(){this.merge=function(base,custom){var mergeResult=$.extend(!0,{},base,custom);return deleteNullValuedKeys(mergeResult)};var deleteNullValuedKeys=function(currentObject){return _.forOwn(currentObject,function(value,key){(_.isUndefined(value)||_.isNull(value)||_.isNaN(value)||_.isObject(value)&&_.isNull(deleteNullValuedKeys(value)))&&delete currentObject[key]}),currentObject}}]),angular.module("bahmni.common.appFramework").directive("appExtensionList",["appService",function(appService){var appDescriptor=appService.getAppDescriptor();return{restrict:"EA",template:'<ul><li ng-repeat="appExtn in appExtensions"><a href="{{formatUrl(appExtn.url, extnParams)}}" class="{{appExtn.icon}}" onclick="return false;" title="{{appExtn.label}}" ng-click="extnLinkClick(appExtn, extnParams)"> <span ng-show="showLabel">{{appExtn.label}}</span></a></li></ul>',scope:{extnPointId:"@",showLabel:"@",onExtensionClick:"&",contextModel:"&"},compile:function(cElement,cAttrs){var extnList=appDescriptor.getExtensions(cAttrs.extnPointId);return function(scope){scope.appExtensions=extnList;var model=scope.contextModel();scope.extnParams=model||{}}},controller:function($scope,$location){$scope.formatUrl=appDescriptor.formatUrl,$scope.extnLinkClick=function(extn,params){var proceedWithDefault=!0,clickHandler=$scope.onExtensionClick(),target=appDescriptor.formatUrl(extn.url,params);if(clickHandler){var event={src:extn,target:target,params:params,preventDefault:function(){proceedWithDefault=!1}};clickHandler(event)}proceedWithDefault&&$location.url(target)}}}}]),Bahmni.Common.AppFramework.AppDescriptor=function(context,inheritContext,retrieveUserCallback,mergeService){this.id=null,this.instanceOf=null,this.description=null,this.contextModel=null,this.baseExtensionPoints=[],this.customExtensionPoints=[],this.baseExtensions={},this.customExtensions={},this.customConfigs={},this.baseConfigs={},this.extensionPath=context,this.contextPath=inheritContext?context.split("/")[0]:context;var self=this,setExtensionPointsFromExtensions=function(currentExtensions,currentExtensionPoints){_.values(currentExtensions).forEach(function(extn){if(extn){var existing=self[currentExtensionPoints].filter(function(ep){return ep.id===extn.extensionPointId});0===existing.length&&self[currentExtensionPoints].push({id:extn.extensionPointId,description:extn.description})}})};this.setExtensions=function(baseExtensions,customExtensions){customExtensions&&(setExtensionPointsFromExtensions(customExtensions,"customExtensionPoints"),self.customExtensions=customExtensions),self.baseExtensions=baseExtensions,setExtensionPointsFromExtensions(baseExtensions,"baseExtensionPoints")},this.setTemplate=function(template){self.instanceOf=template.id,self.description=self.description||template.description,self.contextModel=self.contextModel||template.contextModel,template.configOptions&&_.values(template.configOptions).forEach(function(opt){var existing=self.configs.filter(function(cfg){return cfg.name===opt.name});existing.length>0?existing[0].description=opt.description:self.configs.push({name:opt.name,description:opt.description,value:opt.defaultValue})})};var setConfig=function(instance,currentConfig){for(var configName in instance.config){var existingConfig=getConfig(self[currentConfig],configName);existingConfig?existingConfig.value=instance.config[configName]:self[currentConfig][configName]={name:configName,value:instance.config[configName]}}},setDefinitionExtensionPoints=function(extensionPoints,currentExtensionPoints){extensionPoints&&extensionPoints.forEach(function(iep){if(iep){var existing=self[currentExtensionPoints].filter(function(ep){return ep.id===iep.id});0===existing.length&&self[currentExtensionPoints].push(iep)}})};this.setDefinition=function(baseInstance,customInstance){self.instanceOf=customInstance&&customInstance.instanceOf?customInstance.instanceOf:baseInstance.instanceOf,self.id=customInstance&&customInstance.id?customInstance.id:baseInstance.id,self.description=customInstance&&customInstance.description?customInstance.description:baseInstance.description,self.contextModel=customInstance&&customInstance.contextModel?customInstance.contextModel:baseInstance.contextModel,setDefinitionExtensionPoints(baseInstance.extensionPoints,"baseExtensionPoints"),setConfig(baseInstance,"baseConfigs"),customInstance&&(setDefinitionExtensionPoints(customInstance.extensionPoints,"customExtensionPoints"),setConfig(customInstance,"customConfigs"))};var getExtensions=function(extPointId,type,extensions){var currentUser=retrieveUserCallback(),currentExtensions=_.values(extensions);if(currentUser&¤tExtensions){var extnType=type||"all",userPrivileges=currentUser.privileges.map(function(priv){return priv.retired?"":priv.name}),appsExtns=currentExtensions.filter(function(extn){return("all"===extnType||extn.type===extnType)&&extn.extensionPointId===extPointId&&(!extn.requiredPrivilege||userPrivileges.indexOf(extn.requiredPrivilege)>=0)});return appsExtns.sort(function(extn1,extn2){return extn1.order-extn2.order}),appsExtns}};this.getExtensions=function(extPointId,type,shouldMerge){if(shouldMerge||void 0===shouldMerge){var mergedExtensions=mergeService.merge(self.baseExtensions,self.customExtensions);return getExtensions(extPointId,type,mergedExtensions)}return[getExtensions(extPointId,type,self.baseExtensions),getExtensions(extPointId,type,self.customExtensions)]},this.getExtensionById=function(id,shouldMerge){if(shouldMerge||void 0===shouldMerge){var mergedExtensions=_.values(mergeService.merge(self.baseExtensions,self.customExtensions));return mergedExtensions.filter(function(extn){return extn.id===id})[0]}return[self.baseExtensions.filter(function(extn){return extn.id===id})[0],self.customExtensions.filter(function(extn){return extn.id===id})[0]]};var getConfig=function(config,configName){var cfgList=_.values(config).filter(function(cfg){return cfg.name===configName});return cfgList.length>0?cfgList[0]:null};this.getConfig=function(configName,shouldMerge){return shouldMerge||void 0===shouldMerge?getConfig(mergeService.merge(self.baseConfigs,self.customConfigs),configName):[getConfig(self.baseConfigs,configName),getConfig(self.customConfigs,configName)]},this.getConfigValue=function(configName,shouldMerge){var config=this.getConfig(configName,shouldMerge);return shouldMerge||void 0===shouldMerge?config?config.value:null:config},this.formatUrl=function(url,options,useQueryParams){var pattern=/{{([^}]*)}}/g,matches=url.match(pattern),replacedString=url,checkQueryParams=useQueryParams||!1,queryParameters=this.parseQueryParams();return matches&&matches.forEach(function(el){var key=el.replace("{{","").replace("}}",""),value=options[key];value||checkQueryParams!==!0||(value=queryParameters[key]||null),replacedString=replacedString.replace(el,value)}),replacedString.trim()},this.parseQueryParams=function(locationSearchString){var urlParams,match,pl=/\+/g,search=/([^&=]+)=?([^&]*)/g,decode=function(s){return decodeURIComponent(s.replace(pl," "))},queryString=locationSearchString||window.location.search.substring(1);for(urlParams={};match=search.exec(queryString);)urlParams[decode(match[1])]=decode(match[2]);return urlParams},this.addConfigForPage=function(pageName,baseConfig,customConfig){self.basePageConfigs=self.basePageConfigs||{},self.basePageConfigs[pageName]=baseConfig,self.customPageConfigs=self.customPageConfigs||{},self.customPageConfigs[pageName]=customConfig},this.getConfigForPage=function(pageName,shouldMerge){return shouldMerge||void 0===shouldMerge?mergeService.merge(self.basePageConfigs[pageName],self.customPageConfigs[pageName]):[_.values(self.basePageConfigs[pageName]),_.values(self.customPageConfigs[pageName])]}},angular.module("bahmni.common.appFramework").service("loadConfigService",["$http",function($http){this.loadConfig=function(url){return $http.get(url,{withCredentials:!0})}}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.DisplayControl=Bahmni.Common.DisplayControl||{},Bahmni.Common.DisplayControl.PatientProfile=Bahmni.Common.DisplayControl.PatientProfile||{},angular.module("bahmni.common.displaycontrol.patientprofile",[]),angular.module("bahmni.common.displaycontrol.patientprofile").filter("titleCase",function(){return function(input){return input=input||"",input.replace(/\w\S*/g,function(txt){return txt.charAt(0).toUpperCase()+txt.substr(1).toLowerCase()})}}),angular.module("bahmni.common.config",[]),angular.module("bahmni.common.config").service("configurations",["configurationService",function(configurationService){this.configs={},this.load=function(configNames){var self=this;return configurationService.getConfigurations(_.difference(configNames,Object.keys(this.configs))).then(function(configurations){angular.extend(self.configs,configurations)})},this.dosageInstructionConfig=function(){return this.configs.dosageInstructionConfig||[]},this.stoppedOrderReasonConfig=function(){return this.configs.stoppedOrderReasonConfig||[]},this.dosageFrequencyConfig=function(){return this.configs.dosageFrequencyConfig||[]},this.allTestsAndPanelsConcept=function(){return this.configs.allTestsAndPanelsConcept.results[0]||[]},this.impressionConcept=function(){return this.configs.radiologyImpressionConfig.results[0]||[]},this.labOrderNotesConcept=function(){return this.configs.labOrderNotesConfig.results[0]||[]},this.consultationNoteConcept=function(){return this.configs.consultationNoteConfig.results[0]||[]},this.patientConfig=function(){return this.configs.patientConfig||{}},this.encounterConfig=function(){return angular.extend(new EncounterConfig,this.configs.encounterConfig||[])},this.patientAttributesConfig=function(){return this.configs.patientAttributesConfig.results},this.identifierTypesConfig=function(){return this.configs.identifierTypesConfig},this.genderMap=function(){return this.configs.genderMap},this.addressLevels=function(){return this.configs.addressLevels},this.relationshipTypes=function(){return this.configs.relationshipTypeConfig.results||[]},this.relationshipTypeMap=function(){return this.configs.relationshipTypeMap||{}},this.loginLocationToVisitTypeMapping=function(){return this.configs.loginLocationToVisitTypeMapping||{}},this.defaultEncounterType=function(){return this.configs.defaultEncounterType}}]),angular.module("bahmni.common.config").directive("showIfPrivilege",["$rootScope",function($rootScope){return{scope:{showIfPrivilege:"@"},link:function(scope,element){var privileges=scope.showIfPrivilege.split(","),requiredPrivilege=!1;if($rootScope.currentUser){var allTypesPrivileges=_.map($rootScope.currentUser.privileges,_.property("name")),intersect=_.intersectionWith(allTypesPrivileges,privileges,_.isEqual);requiredPrivilege=intersect.length>0}requiredPrivilege||element.hide()}}}]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.Domain=Bahmni.Common.Domain||{},Bahmni.Common.Domain.Helper=Bahmni.Common.Domain.Helper||{},angular.module("bahmni.common.domain",[]),angular.module("bahmni.common.domain").factory("locationService",["$http","$bahmniCookieStore",function($http,$bahmniCookieStore){var getAllByTag=function(tags,operator){return $http.get(Bahmni.Common.Constants.locationUrl,{params:{s:"byTags",tags:tags||"",v:"default",operator:operator||"ALL"},cache:!0})},getByUuid=function(locationUuid){return $http.get(Bahmni.Common.Constants.locationUrl+"/"+locationUuid,{cache:!0}).then(function(response){return response.data})},getLoggedInLocation=function(){var cookie=$bahmniCookieStore.get(Bahmni.Common.Constants.locationCookieName);return getByUuid(cookie.uuid)},getVisitLocation=function(locationUuid){return $http.get(Bahmni.Common.Constants.bahmniVisitLocationUrl+"/"+locationUuid,{headers:{Accept:"application/json"}})};return{getAllByTag:getAllByTag,getLoggedInLocation:getLoggedInLocation,getByUuid:getByUuid,getVisitLocation:getVisitLocation}}]),angular.module("bahmni.common.domain").factory("configurationService",["$http","$q",function($http,$q){var configurationFunctions={};configurationFunctions.encounterConfig=function(){return $http.get(Bahmni.Common.Constants.encounterConfigurationUrl,{params:{callerContext:"REGISTRATION_CONCEPTS"},withCredentials:!0})},configurationFunctions.patientConfig=function(){var patientConfig=$http.get(Bahmni.Common.Constants.patientConfigurationUrl,{withCredentials:!0});return patientConfig},configurationFunctions.patientAttributesConfig=function(){return $http.get(Bahmni.Common.Constants.personAttributeTypeUrl,{params:{v:"custom:(uuid,name,sortWeight,description,format,concept)"},withCredentials:!0})},configurationFunctions.dosageFrequencyConfig=function(){var dosageFrequencyConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name,answers)",name:Bahmni.Common.Constants.dosageFrequencyConceptName},withCredentials:!0});return dosageFrequencyConfig},configurationFunctions.dosageInstructionConfig=function(){var dosageInstructionConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name,answers)",name:Bahmni.Common.Constants.dosageInstructionConceptName},withCredentials:!0});return dosageInstructionConfig},configurationFunctions.stoppedOrderReasonConfig=function(){var stoppedOrderReasonConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name,answers)",name:Bahmni.Common.Constants.stoppedOrderReasonConceptName},withCredentials:!0});return stoppedOrderReasonConfig},configurationFunctions.consultationNoteConfig=function(){var consultationNoteConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name,answers)",name:Bahmni.Common.Constants.consultationNoteConceptName},withCredentials:!0});return consultationNoteConfig},configurationFunctions.radiologyObservationConfig=function(){var radiologyObservationConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name)",name:Bahmni.Common.Constants.radiologyResultConceptName},withCredentials:!0});return radiologyObservationConfig},configurationFunctions.labOrderNotesConfig=function(){var labOrderNotesConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name)",name:Bahmni.Common.Constants.labOrderNotesConcept},withCredentials:!0});return labOrderNotesConfig},configurationFunctions.defaultEncounterType=function(){return $http.get(Bahmni.Common.Constants.globalPropertyUrl,{params:{property:"bahmni.encounterType.default"},withCredentials:!0,transformResponse:[function(data){return data}]})},configurationFunctions.radiologyImpressionConfig=function(){var radiologyImpressionConfig=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name)",name:Bahmni.Common.Constants.impressionConcept},withCredentials:!0});return radiologyImpressionConfig},configurationFunctions.addressLevels=function(){return $http.get(Bahmni.Common.Constants.openmrsUrl+"/module/addresshierarchy/ajax/getOrderedAddressHierarchyLevels.form",{withCredentials:!0})},configurationFunctions.allTestsAndPanelsConcept=function(){var allTestsAndPanelsConcept=$http.get(Bahmni.Common.Constants.conceptSearchByFullNameUrl,{method:"GET",params:{v:"custom:(uuid,name:(uuid,name),setMembers:(uuid,name:(uuid,name)))",name:Bahmni.Common.Constants.allTestsAndPanelsConceptName},withCredentials:!0});return allTestsAndPanelsConcept},configurationFunctions.identifierTypesConfig=function(){return $http.get(Bahmni.Common.Constants.idgenConfigurationURL,{withCredentials:!0})},configurationFunctions.genderMap=function(){return $http.get(Bahmni.Common.Constants.globalPropertyUrl,{method:"GET",params:{property:"mrs.genders"},withCredentials:!0})},configurationFunctions.relationshipTypeMap=function(){return $http.get(Bahmni.Common.Constants.globalPropertyUrl,{method:"GET",params:{property:"bahmni.relationshipTypeMap"},withCredentials:!0})},configurationFunctions.relationshipTypeConfig=function(){return $http.get(Bahmni.Common.Constants.relationshipTypesUrl,{withCredentials:!0,params:{v:"custom:(aIsToB,bIsToA,uuid)"}})},configurationFunctions.loginLocationToVisitTypeMapping=function(){var url=Bahmni.Common.Constants.entityMappingUrl;return $http.get(url,{params:{mappingType:"loginlocation_visittype",s:"byEntityAndMappingType"}})},configurationFunctions.enableAuditLog=function(){return $http.get(Bahmni.Common.Constants.globalPropertyUrl,{method:"GET",params:{property:"bahmni.enableAuditLog"},withCredentials:!0})};var existingPromises={},configurations={},getConfigurations=function(configurationNames){var configurationsPromiseDefer=$q.defer(),promises=[];return configurationNames.forEach(function(configurationName){existingPromises[configurationName]||(existingPromises[configurationName]=configurationFunctions[configurationName]().then(function(response){configurations[configurationName]=response.data}),promises.push(existingPromises[configurationName]))}),$q.all(promises).then(function(){configurationsPromiseDefer.resolve(configurations)}),configurationsPromiseDefer.promise};return{getConfigurations:getConfigurations}}]),angular.module("bahmni.common.domain").factory("providerService",["$http",function($http){var search=function(fieldValue){return $http.get(Bahmni.Common.Constants.providerUrl,{method:"GET",params:{q:fieldValue,v:"full"},withCredentials:!0})},searchByUuid=function(uuid){return $http.get(Bahmni.Common.Constants.providerUrl,{method:"GET",params:{user:uuid},cache:!1})},list=function(params){return $http.get(Bahmni.Common.Constants.providerUrl,{method:"GET",cache:!1,params:params})};return{search:search,searchByUuid:searchByUuid,list:list}}]),angular.module("bahmni.common.uiHelper",["ngClipboard"]),angular.module("bahmni.common.uiHelper").factory("spinner",["messagingService","$timeout",function(messagingService,$timeout){var tokens=[],topLevelDiv=function(element){return $(element).find("div").eq(0)},showSpinnerForElement=function(element){return 0===$(element).find(".dashboard-section-loader").length&&topLevelDiv(element).addClass("spinnable").append('<div class="dashboard-section-loader"></div>'),{element:$(element).find(".dashboard-section-loader")}},showSpinnerForOverlay=function(){var token=Math.random();tokens.push(token),0===$("#overlay").length&&$("body").prepend('<div id="overlay"><div></div></div>');var spinnerElement=$("#overlay");return spinnerElement.stop().show(),{element:spinnerElement,token:token}},show=function(element){return void 0!==element?showSpinnerForElement(element):showSpinnerForOverlay()},hide=function(spinner,parentElement){var spinnerElement=spinner.element;spinner.token?(_.pull(tokens,spinner.token),0===tokens.length&&spinnerElement.fadeOut(300)):(topLevelDiv(parentElement).removeClass("spinnable"),spinnerElement&&spinnerElement.remove())},forPromise=function(promise,element){return $timeout(function(){var spinner=show(element);return promise.finally(function(){hide(spinner,element)}),promise})},forAjaxPromise=function(promise,element){var spinner=show(element);return promise.always(function(){hide(spinner,element)}),promise};return{forPromise:forPromise,forAjaxPromise:forAjaxPromise,show:show,hide:hide}}]),angular.module("bahmni.common.uiHelper").factory("printer",["$rootScope","$compile","$http","$timeout","$q","spinner",function($rootScope,$compile,$http,$timeout,$q,spinner){var printHtml=function(html){var deferred=$q.defer(),hiddenFrame=$('<iframe style="visibility: hidden"></iframe>').appendTo("body")[0];hiddenFrame.contentWindow.printAndRemove=function(){hiddenFrame.contentWindow.print(),$(hiddenFrame).remove(),deferred.resolve()};var htmlContent='<!doctype html><html><body onload="printAndRemove();">'+html+"</body></html>",doc=hiddenFrame.contentWindow.document.open("text/html","replace");return doc.write(htmlContent),doc.close(),deferred.promise},print=function(templateUrl,data){$rootScope.isBeingPrinted=!0,$http.get(templateUrl).then(function(templateData){var template=templateData.data,printScope=$rootScope.$new();angular.extend(printScope,data);var element=$compile($("<div>"+template+"</div>"))(printScope),renderAndPrintPromise=$q.defer(),waitForRenderAndPrint=function(){return printScope.$$phase||$http.pendingRequests.length?$timeout(waitForRenderAndPrint,1e3):(printHtml(element.html()).then(function(){$rootScope.isBeingPrinted=!1,renderAndPrintPromise.resolve()}),printScope.$destroy()),renderAndPrintPromise.promise};spinner.forPromise(waitForRenderAndPrint())})},printFromScope=function(templateUrl,scope,afterPrint){$rootScope.isBeingPrinted=!0,$http.get(templateUrl).then(function(response){var template=response.data,printScope=scope,element=$compile($("<div>"+template+"</div>"))(printScope),renderAndPrintPromise=$q.defer(),waitForRenderAndPrint=function(){return printScope.$$phase||$http.pendingRequests.length?$timeout(waitForRenderAndPrint):printHtml(element.html()).then(function(){$rootScope.isBeingPrinted=!1,afterPrint&&afterPrint(),renderAndPrintPromise.resolve()}),renderAndPrintPromise.promise};spinner.forPromise(waitForRenderAndPrint())})};return{print:print,printFromScope:printFromScope}}]),angular.module("bahmni.common.uiHelper").service("backlinkService",["$window",function($window){var self=this,urls=[];self.reset=function(){urls=[]},self.setUrls=function(backLinks){self.reset(),angular.forEach(backLinks,function(backLink){self.addUrl(backLink)})},self.addUrl=function(backLink){urls.push(backLink)},self.addBackUrl=function(label){var backLabel=label||"Back";urls.push({label:backLabel,action:$window.history.back})},self.getUrlByLabel=function(label){return urls.filter(function(url){return url.label===label})},self.getAllUrls=function(){return urls}}]),angular.module("bahmni.common.uiHelper").service("stateChangeSpinner",["$rootScope","spinner",function($rootScope,spinner){var showSpinner=function(event,toState){toState.spinnerToken=spinner.show()},hideSpinner=function(event,toState){spinner.hide(toState.spinnerToken)};this.activate=function(){$rootScope.$on("$stateChangeStart",showSpinner),$rootScope.$on("$stateChangeSuccess",hideSpinner),$rootScope.$on("$stateChangeError",hideSpinner)}}]),angular.module("bahmni.common.uiHelper").directive("bmBackLinks",function(){return{template:'<ul><li ng-repeat="backLink in backLinks"><a class="back-btn" ng-if="backLink.action" accesskey="{{backLink.accessKey}}" ng-click="closeAllDialogs();backLink.action()" id="{{backLink.id}}"> <span ng-bind-html="backLink.label"></span> </a><a class="back-btn" ng-class="{\'dashboard-link\':backLink.image}" ng-if="backLink.url" accesskey="{{backLink.accessKey}}" ng-href="{{backLink.url}}" ng-click="closeAllDialogs()" id="{{backLink.id}}" title="{{backLink.title}}"> <img ng-if="backLink.image" ng-src="{{backLink.image}}" onerror="this.onerror=null; this.src=\'../images/blank-user.gif\'"/><i ng-if="backLink.icon && !backLink.image" class="fa {{backLink.icon}}"></i></a><a class="back-btn" ng-if="backLink.state && !backLink.text" accesskey="{{backLink.accessKey}}" ui-sref="{{backLink.state}}" ng-click="displayConfirmationDialog($event);closeAllDialogs()" id="{{backLink.id}}"><i ng-if="backLink.icon" class="fa {{backLink.icon}}"></i></a><a ng-if="backLink.text && backLink.requiredPrivilege" show-if-privilege="{{backLink.requiredPrivilege}}" accesskey="{{backLink.accessKey}}" ui-sref="{{backLink.state}}" id="{{backLink.id}}" class="back-btn-noIcon" ui-sref-active="active"><span>{{backLink.text | translate}}</span> </a><a ng-if="backLink.text && !backLink.requiredPrivilege" accesskey="{{backLink.accessKey}}" ui-sref="{{backLink.state}}" id="{{backLink.id}}" class="back-btn-noIcon" ui-sref-active="active"><span>{{backLink.text | translate}}</span> </a></li></ul>',
|
|
controller:function($scope,backlinkService){$scope.backLinks=backlinkService.getAllUrls(),$scope.$on("$stateChangeSuccess",function(event,state){state.data&&state.data.backLinks&&(backlinkService.setUrls(state.data.backLinks),$scope.backLinks=backlinkService.getAllUrls())}),$scope.$on("$destroy",function(){window.onbeforeunload=void 0})},restrict:"E"}}),angular.module("bahmni.common.uiHelper").controller("MessageController",["$scope","messagingService",function($scope,messagingService){$scope.messages=messagingService.messages,$scope.getMessageText=function(level){var string="";return $scope.messages[level].forEach(function(message){string=string.concat(message.value)}),string},$scope.hideMessage=function(level){messagingService.hideMessages(level)},$scope.isErrorMessagePresent=function(){return $scope.messages.error.length>0},$scope.isInfoMessagePresent=function(){return $scope.messages.info.length>0}}]),angular.module("bahmni.common.uiHelper").service("messagingService",["$rootScope","$timeout",function($rootScope,$timeout){this.messages={error:[],info:[]};var self=this;$rootScope.$on("event:serverError",function(event,errorMessage){self.showMessage("error",errorMessage,"serverError")}),this.showMessage=function(level,message,errorEvent){var messageObject={value:"",isServerError:!1};messageObject.value=message,errorEvent?messageObject.isServerError=!0:"info"==level&&this.createTimeout("info",4e3);var index=_.findIndex(this.messages[level],function(msg){return msg.value==messageObject.value});index>=0&&this.messages[level].splice(index,1),this.messages[level].push(messageObject)},this.createTimeout=function(level,time){$timeout(function(){self.messages[level]=[]},time,!0)},this.hideMessages=function(level){self.messages[level].length=0},this.clearAll=function(){self.messages.error=[],self.messages.info=[]}}]),angular.module("bahmni.common.uiHelper").service("confirmBox",["$rootScope","ngDialog",function($rootScope,ngDialog){var dialog,confirmBox=function(config){var confirmBoxScope=$rootScope.$new();confirmBoxScope.close=function(){ngDialog.close(dialog.id),confirmBoxScope.$destroy()},confirmBoxScope.scope=config.scope,confirmBoxScope.actions=config.actions,dialog=ngDialog.open({template:"../common/ui-helper/views/confirmBox.html",scope:confirmBoxScope,className:config.className||"ngdialog-theme-default"})};return confirmBox}]),angular.module("bahmni.common.uiHelper").directive("bahmniAutocomplete",["$translate",function($translate){var link=function(scope,element,attrs,ngModelCtrl){var source=scope.source(),responseMap=scope.responseMap&&scope.responseMap(),onSelect=scope.onSelect(),onEdit=scope.onEdit&&scope.onEdit(),minLength=scope.minLength||2,formElement=element[0],validationMessage=scope.validationMessage||$translate.instant("SELECT_VALUE_FROM_AUTOCOMPLETE_DEFAULT_MESSAGE"),validateIfNeeded=function(value){scope.strictSelect&&(scope.isInvalid=value!==scope.selectedValue,_.isEmpty(value)&&(scope.isInvalid=!1))};scope.$watch("initialValue",function(){scope.initialValue&&(scope.selectedValue=scope.initialValue,scope.isInvalid=!1)}),element.autocomplete({autofocus:!0,minLength:minLength,source:function(request,response){source({elementId:attrs.id,term:request.term,elementType:attrs.type}).then(function(data){var results=responseMap?responseMap(data):data;response(results)})},select:function(event,ui){return scope.selectedValue=ui.item.value,ngModelCtrl.$setViewValue(ui.item.value),null!=onSelect&&onSelect(ui.item),validateIfNeeded(ui.item.value),scope.blurOnSelect&&element.blur(),scope.$apply(),scope.$eval(attrs.ngDisabled),scope.$apply(),!0},search:function(event,ui){null!=onEdit&&onEdit(ui.item);var searchTerm=$.trim(element.val());validateIfNeeded(searchTerm),searchTerm.length<minLength&&event.preventDefault()}});var changeHanlder=function(e){validateIfNeeded(element.val())},keyUpHandler=function(e){validateIfNeeded(element.val()),scope.$apply()};element.on("change",changeHanlder),element.on("keyup",keyUpHandler),scope.$watch("isInvalid",function(){ngModelCtrl.$setValidity("selection",!scope.isInvalid),formElement.setCustomValidity(scope.isInvalid?validationMessage:"")}),scope.$on("$destroy",function(){element.off("change",changeHanlder),element.off("keyup",keyUpHandler)})};return{link:link,require:"ngModel",scope:{source:"&",responseMap:"&?",onSelect:"&",onEdit:"&?",minLength:"=?",blurOnSelect:"=?",strictSelect:"=?",validationMessage:"@",isInvalid:"=?",initialValue:"=?"}}}]),angular.module("bahmni.common.uiHelper").filter("days",function(){return function(startDate,endDate){return Bahmni.Common.Util.DateUtil.diffInDays(startDate,endDate)}}).filter("bahmniDateTime",function(){return function(date){return Bahmni.Common.Util.DateUtil.formatDateWithTime(date)}}).filter("bahmniDate",function(){return function(date){return Bahmni.Common.Util.DateUtil.formatDateWithoutTime(date)}}).filter("bahmniTime",function(){return function(date){return Bahmni.Common.Util.DateUtil.formatTime(date)}}).filter("bahmniDateInStrictMode",function(){return function(date){return Bahmni.Common.Util.DateUtil.formatDateInStrictMode(date)}}).filter("bahmniDateTimeWithFormat",function(){return function(date,format){return Bahmni.Common.Util.DateUtil.getDateTimeInSpecifiedFormat(date,format)}}).filter("addDays",function(){return function(date,numberOfDays){return Bahmni.Common.Util.DateUtil.addDays(date,numberOfDays)}}),angular.module("bahmni.common.patient",[]),Bahmni.PatientMapper=function(patientConfig,$rootScope,$translate){this.patientConfig=patientConfig,this.map=function(openmrsPatient){var patient=this.mapBasic(openmrsPatient);return this.mapAttributes(patient,openmrsPatient.person.attributes),patient},this.mapBasic=function(openmrsPatient){var patient={};if(patient.uuid=openmrsPatient.uuid,patient.givenName=openmrsPatient.person.preferredName.givenName,patient.familyName=null===openmrsPatient.person.preferredName.familyName?"":openmrsPatient.person.preferredName.familyName,patient.name=patient.givenName+" "+patient.familyName,patient.age=openmrsPatient.person.age,patient.ageText=calculateAge(Bahmni.Common.Util.DateUtil.parseServerDateToDate(openmrsPatient.person.birthdate)),patient.gender=openmrsPatient.person.gender,patient.genderText=mapGenderText(patient.gender),patient.address=mapAddress(openmrsPatient.person.preferredAddress),patient.birthdateEstimated=openmrsPatient.person.birthdateEstimated,patient.birthtime=Bahmni.Common.Util.DateUtil.parseServerDateToDate(openmrsPatient.person.birthtime),patient.bloodGroupText=getPatientBloodGroupText(openmrsPatient),openmrsPatient.identifiers){var primaryIdentifier=openmrsPatient.identifiers[0].primaryIdentifier;patient.identifier=primaryIdentifier?primaryIdentifier:openmrsPatient.identifiers[0].identifier}return openmrsPatient.person.birthdate&&(patient.birthdate=parseDate(openmrsPatient.person.birthdate)),openmrsPatient.person.personDateCreated&&(patient.registrationDate=parseDate(openmrsPatient.person.personDateCreated)),patient.image=Bahmni.Common.Constants.patientImageUrlByPatientUuid+openmrsPatient.uuid,patient},this.getPatientConfigByUuid=function(patientConfig,attributeUuid){return this.patientConfig.personAttributeTypes?patientConfig.personAttributeTypes.filter(function(item){return item.uuid===attributeUuid})[0]:{}},this.mapAttributes=function(patient,attributes){var self=this;this.patientConfig&&attributes.forEach(function(attribute){var x=self.getPatientConfigByUuid(patientConfig,attribute.attributeType.uuid);patient[x.name]={label:x.description,value:attribute.value,isDateField:checkIfDateField(x)}})};var calculateAge=function(birthDate){var DateUtil=Bahmni.Common.Util.DateUtil,age=DateUtil.diffInYearsMonthsDays(birthDate,DateUtil.now()),ageInString="";return age.years&&(ageInString+=age.years+" <span> "+$translate.instant("CLINICAL_YEARS_TRANSLATION_KEY")+" </span>"),age.months&&(ageInString+=age.months+"<span> "+$translate.instant("CLINICAL_MONTHS_TRANSLATION_KEY")+" </span>"),age.days&&(ageInString+=age.days+"<span> "+$translate.instant("CLINICAL_DAYS_TRANSLATION_KEY")+" </span>"),ageInString},mapAddress=function(preferredAddress){return preferredAddress?{address1:preferredAddress.address1,address2:preferredAddress.address2,address3:preferredAddress.address3,cityVillage:preferredAddress.cityVillage,countyDistrict:null===preferredAddress.countyDistrict?"":preferredAddress.countyDistrict,stateProvince:preferredAddress.stateProvince}:{}},parseDate=function(dateStr){return dateStr?Bahmni.Common.Util.DateUtil.parse(dateStr.substr(0,10)):dateStr},mapGenderText=function(genderChar){return null==genderChar?null:"<span>"+$rootScope.genderMap[angular.uppercase(genderChar)]+"</span>"},getPatientBloodGroupText=function(openmrsPatient){if(openmrsPatient.person.bloodGroup)return"<span>"+openmrsPatient.person.bloodGroup+"</span>";if(openmrsPatient.person.attributes&&openmrsPatient.person.attributes.length>0){var bloodGroup;if(_.forEach(openmrsPatient.person.attributes,function(attribute){"bloodGroup"==attribute.attributeType.display&&(bloodGroup=attribute.display)}),bloodGroup)return"<span>"+bloodGroup+"</span>"}},checkIfDateField=function(x){return x.format===Bahmni.Common.Constants.patientAttributeDateFieldFormat}},angular.module("bahmni.common.patient").service("patientService",["$http","sessionService",function($http,sessionService){this.getPatient=function(uuid,rep){rep||(rep="full");var patient=$http.get(Bahmni.Common.Constants.openmrsUrl+"/ws/rest/v1/patient/"+uuid,{method:"GET",params:{v:rep},withCredentials:!0});return patient},this.getRelationships=function(patientUuid){return $http.get(Bahmni.Common.Constants.openmrsUrl+"/ws/rest/v1/relationship",{method:"GET",params:{person:patientUuid,v:"full"},withCredentials:!0})},this.findPatients=function(params){return $http.get(Bahmni.Common.Constants.sqlUrl,{method:"GET",params:params,withCredentials:!0})},this.search=function(query,offset,identifier){return offset=offset||0,$http.get(Bahmni.Common.Constants.bahmniSearchUrl+"/patient",{method:"GET",params:{q:query,startIndex:offset,identifier:identifier,loginLocationUuid:sessionService.getLoginLocationUuid()},withCredentials:!0})},this.getPatientContext=function(patientUuid,programUuid,personAttributes,programAttributes,patientIdentifiers){return $http.get("/openmrs/ws/rest/v1/bahmnicore/patientcontext",{params:{patientUuid:patientUuid,programUuid:programUuid,personAttributes:personAttributes,programAttributes:programAttributes,patientIdentifiers:patientIdentifiers},withCredentials:!0})}}]),angular.module("bahmni.common.patient").filter("gender",["$rootScope",function($rootScope){return function(genderChar){return null==genderChar?"Unknown":$rootScope.genderMap[angular.uppercase(genderChar)]}}]);var Bahmni=Bahmni||{};Bahmni.ConceptSet=Bahmni.ConceptSet||{},Bahmni.ConceptSet.FormConditions=Bahmni.ConceptSet.FormConditions||{},angular.module("bahmni.common.conceptSet",["bahmni.common.uiHelper","ui.select2","pasvaz.bindonce","ngSanitize","ngTagsInput"]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.PatientSearch=Bahmni.Common.PatientSearch||{},Bahmni.Common.PatientSearch.Constants={searchExtensionTileViewType:"tile",searchExtensionTabularViewType:"tabular",tabularViewIgnoreHeadingsList:["display","uuid","image","$$hashKey","activeVisitUuid","hasBeenAdmitted","forwardUrl","programUuid","enrollment"],identifierHeading:["ID","Id","id","identifier","DQ_COLUMN_TITLE_ACTION"],nameHeading:["NAME","Name","name"],patientTileHeight:100,patientTileWidth:100,printIgnoreHeadingsList:["DQ_COLUMN_TITLE_ACTION"],tileLoadRatio:.5},Bahmni.Common.PatientSearch.Search=function(searchTypes){function mapPatient(patient){return(patient.name||patient.givenName||patient.familyName)&&(patient.name=patient.name||patient.givenName+(patient.familyName?" "+patient.familyName:"")),patient.display=_.map(self.searchColumns,function(column){return patient[column]}).join(" - "),patient.image=Bahmni.Common.Constants.patientImageUrlByPatientUuid+patient.uuid,patient}var self=this;self.searchTypes=searchTypes||[],self.searchType=this.searchTypes[0],self.searchParameter="",self.noResultsMessage=null,self.searchResults=[],self.activePatients=[],self.navigated=!1,self.links=self.searchType&&self.searchType.links?self.searchType.links:[],self.searchColumns=self.searchType&&self.searchType.searchColumns?self.searchType.searchColumns:["identifier","name"],angular.forEach(searchTypes,function(searchType){searchType.patientCount="..."}),self.switchSearchType=function(searchType){self.noResultsMessage=null,self.isSelectedSearch(searchType)||(self.searchParameter="",self.navigated=!0,self.searchType=searchType,self.activePatients=[],self.searchResults=[],self.links=self.searchType&&self.searchType.links?self.searchType.links:[],self.searchColumns=self.searchType&&self.searchType.searchColumns?self.searchType.searchColumns:["identifier","name"]),self.markPatientEntry()},self.markPatientEntry=function(){self.startPatientSearch=!0,window.setTimeout(function(){self.startPatientSearch=!1})},self.patientsCount=function(){return self.activePatients.length},self.updatePatientList=function(patientList){self.activePatients=patientList.map(mapPatient),self.searchResults=self.activePatients},self.updateSearchResults=function(patientList){self.updatePatientList(patientList),0===self.activePatients.length&&""!=self.searchParameter?self.noResultsMessage="NO_RESULTS_FOUND":self.noResultsMessage=null},self.hasSingleActivePatient=function(){return 1===self.activePatients.length},self.filterPatients=function(matchingCriteria){matchingCriteria=matchingCriteria?matchingCriteria:matchesNameOrId,self.searchResults=self.searchParameter?self.activePatients.filter(matchingCriteria):self.activePatients},self.filterPatientsByIdentifier=function(){self.filterPatients(matchesId)},self.isSelectedSearch=function(searchType){return self.searchType&&self.searchType.id==searchType.id},self.isCurrentSearchLookUp=function(){return self.searchType&&self.searchType.handler},self.isTileView=function(){return self.searchType&&self.searchType.view===Bahmni.Common.PatientSearch.Constants.searchExtensionTileViewType},self.isTabularView=function(){return self.searchType&&self.searchType.view===Bahmni.Common.PatientSearch.Constants.searchExtensionTabularViewType},self.showPatientCountOnSearchParameter=function(searchType){return showPatientCount(searchType)&&self.searchParameter};var matchesNameOrId=function(patient){return patient.display.toLowerCase().indexOf(self.searchParameter.toLowerCase())!==-1},matchesId=function(patient){return patient.identifier.toLowerCase().indexOf(self.searchParameter.toLowerCase())!==-1},showPatientCount=function(searchType){return self.isSelectedSearch(searchType)&&self.isCurrentSearchLookUp()}},angular.module("bahmni.common.patientSearch",["bahmni.common.patient","infinite-scroll"]);var Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.I18n=Bahmni.Common.I18n||{},angular.module("bahmni.common.i18n",[]),angular.module("bahmni.common.i18n",["pascalprecht.translate"]).provider("$bahmniTranslate",["$translateProvider",function($translateProvider){this.init=function(options){var preferredLanguage=window.localStorage.NG_TRANSLATE_LANG_KEY||"en";$translateProvider.useLoader("mergeLocaleFilesService",options),$translateProvider.useSanitizeValueStrategy("escaped"),$translateProvider.preferredLanguage(preferredLanguage),$translateProvider.useLocalStorage()},this.$get=[function(){return $translateProvider}]}]).filter("titleTranslate",["$translate",function($translate){return function(input){return input?input.translationKey?$translate.instant(input.translationKey):input.dashboardName?input.dashboardName:input.title?input.title:input.label?input.label:input.display?input.display:$translate.instant(input):input}}]),angular.module("bahmni.common.i18n").service("mergeLocaleFilesService",["$http","$q","mergeService",function($http,$q,mergeService){return function(options){var baseLocaleUrl="../i18n/",customLocaleUrl=Bahmni.Common.Constants.rootDir+"/bahmni_config/openmrs/i18n/",loadFile=function(url){return $http.get(url,{withCredentials:!0})},mergeLocaleFile=function(options){var fileURL=options.app+"/locale_"+options.key+".json",loadBahmniTranslations=function(){return loadFile(baseLocaleUrl+fileURL).then(function(result){return result},function(){})},loadCustomTranslations=function(){return loadFile(customLocaleUrl+fileURL).then(function(result){return result},function(){})},mergeTranslations=function(result){var baseFileData=result[0]?result[0].data:void 0,customFileData=result[1]?result[1].data:void 0;return options.shouldMerge||void 0===options.shouldMerge?mergeService.merge(baseFileData,customFileData):[baseFileData,customFileData]};return $q.all([loadBahmniTranslations(),loadCustomTranslations()]).then(mergeTranslations)};return mergeLocaleFile(options)}}]);var debugUiRouter=function($rootScope){$rootScope.$on("$stateChangeStart",function(event,toState,toParams){console.log("$stateChangeStart to "+toState.to+"- fired when the transition begins. toState,toParams : \n",toState,toParams)}),$rootScope.$on("$stateChangeError",function(){console.log("$stateChangeError - fired when an error occurs during transition."),console.log(arguments)}),$rootScope.$on("$stateChangeSuccess",function(event,toState){console.log("$stateChangeSuccess to "+toState.name+"- fired once the state transition is complete.")}),$rootScope.$on("$viewContentLoaded",function(event){console.log("$viewContentLoaded - fired after dom rendered",event)}),$rootScope.$on("$stateNotFound",function(event,unfoundState,fromState,fromParams){console.log("$stateNotFound "+unfoundState.to+" - fired when a state cannot be found by its name."),console.log(unfoundState,fromState,fromParams)})},Bahmni=Bahmni||{};Bahmni.Common=Bahmni.Common||{},Bahmni.Common.Logging=Bahmni.Common.Logging||{},angular.module("bahmni.common.logging",[]),angular.module("bahmni.common.logging").config(["$provide",function($provide){$provide.decorator("$exceptionHandler",function($delegate,$injector,$window,$log){var logError=function(exception,cause){try{var messagingService=$injector.get("messagingService"),loggingService=$injector.get("loggingService"),errorMessage=exception.toString(),stackTrace=printStackTrace({e:exception}),errorDetails={timestamp:new Date,browser:$window.navigator.userAgent,errorUrl:$window.location.href,errorMessage:errorMessage,stackTrace:stackTrace,cause:cause||""};loggingService.log(errorDetails),messagingService.showMessage("error",errorMessage),exposeException(errorDetails)}catch(loggingError){$log.warn("Error logging failed"),$log.log(loggingError)}},exposeException=function(exceptionDetails){window.angular_exception=window.angular_exception||[],window.angular_exception.push(exceptionDetails)};return function(exception,cause){$delegate(exception,cause),logError(exception,cause)}})}]),angular.module("bahmni.common.logging").service("loggingService",function(){var log=function(errorDetails){$.ajax({type:"POST",url:"/log",contentType:"application/json",data:angular.toJson(errorDetails)})};return{log:log}}),angular.module("ui.calendar",[]).constant("uiCalendarConfig",{calendars:{}}).controller("uiCalendarCtrl",["$scope","$locale",function($scope,$locale){var sources=$scope.eventSources,extraEventSignature=$scope.calendarWatchEvent?$scope.calendarWatchEvent:angular.noop,wrapFunctionWithScopeApply=function(functionToWrap){return function(){if($scope.$root.$$phase)return functionToWrap.apply(this,arguments);var args=arguments,that=this;return $scope.$root.$apply(function(){return functionToWrap.apply(that,args)})}},eventSerialId=1;this.eventFingerprint=function(e){e._id||(e._id=eventSerialId++);var extraSignature=extraEventSignature({event:e})||"",start=moment.isMoment(e.start)?e.start.unix():e.start?moment(e.start).unix():"",end=moment.isMoment(e.end)?e.end.unix():e.end?moment(e.end).unix():"";return[e._id,e.id||"",e.title||"",e.url||"",start,end,e.allDay||"",e.className||"",extraSignature].join("")};var sourceSerialId=1,sourceEventsSerialId=1;this.sourceFingerprint=function(source){var fp=""+(source.__id||(source.__id=sourceSerialId++)),events=angular.isObject(source)&&source.events;return events&&(fp=fp+"-"+(events.__id||(events.__id=sourceEventsSerialId++))),fp},this.allEvents=function(){return Array.prototype.concat.apply([],(sources||[]).reduce(function(previous,source){if(angular.isArray(source))previous.push(source);else if(angular.isObject(source)&&angular.isArray(source.events)){var extEvent=Object.keys(source).filter(function(key){return"_id"!==key&&"events"!==key});source.events.forEach(function(event){angular.extend(event,extEvent)}),previous.push(source.events)}return previous},[]))},this.changeWatcher=function(arraySource,tokenFn){var self,getTokens=function(){return((angular.isFunction(arraySource)?arraySource():arraySource)||[]).reduce(function(rslt,el){var token=tokenFn(el);return map[token]=el,rslt.push(token),rslt},[])},subtractAsSets=function(a,b){var obj=(b||[]).reduce(function(rslt,val){return rslt[val]=!0,rslt},Object.create(null));return(a||[]).filter(function(val){return!obj[val]})},map={},applyChanges=function(newTokens,oldTokens){var i,token,replacedTokens={},removedTokens=subtractAsSets(oldTokens,newTokens);for(i=0;i<removedTokens.length;i++){var removedToken=removedTokens[i],el=map[removedToken];delete map[removedToken];var newToken=tokenFn(el);newToken===removedToken?self.onRemoved(el):(replacedTokens[newToken]=removedToken,self.onChanged(el))}var addedTokens=subtractAsSets(newTokens,oldTokens);for(i=0;i<addedTokens.length;i++)token=addedTokens[i],replacedTokens[token]||self.onAdded(map[token])};return self={subscribe:function(scope,onArrayChanged){scope.$watch(getTokens,function(newTokens,oldTokens){var notify=!(onArrayChanged&&onArrayChanged(newTokens,oldTokens)===!1);notify&&applyChanges(newTokens,oldTokens)},!0)},onAdded:angular.noop,onChanged:angular.noop,onRemoved:angular.noop}},this.getFullCalendarConfig=function(calendarSettings,uiCalendarConfig){var config={};return angular.extend(config,uiCalendarConfig),angular.extend(config,calendarSettings),angular.forEach(config,function(value,key){"function"==typeof value&&(config[key]=wrapFunctionWithScopeApply(config[key]))}),config},this.getLocaleConfig=function(fullCalendarConfig){if(!fullCalendarConfig.lang||fullCalendarConfig.useNgLocale){var tValues=function(data){return(Object.keys(data)||[]).reduce(function(rslt,el){return rslt.push(data[el]),rslt},[])},dtf=$locale.DATETIME_FORMATS;return{monthNames:tValues(dtf.MONTH),monthNamesShort:tValues(dtf.SHORTMONTH),dayNames:tValues(dtf.DAY),dayNamesShort:tValues(dtf.SHORTDAY)}}return{}}}]).directive("uiCalendar",["uiCalendarConfig",function(uiCalendarConfig){return{restrict:"A",scope:{eventSources:"=ngModel",calendarWatchEvent:"&"},controller:"uiCalendarCtrl",link:function(scope,elm,attrs,controller){function getOptions(){var calendarSettings=attrs.uiCalendar?scope.$parent.$eval(attrs.uiCalendar):{},fullCalendarConfig=controller.getFullCalendarConfig(calendarSettings,uiCalendarConfig),localeFullCalendarConfig=controller.getLocaleConfig(fullCalendarConfig);angular.extend(localeFullCalendarConfig,fullCalendarConfig),options={eventSources:sources},angular.extend(options,localeFullCalendarConfig),options.calendars=null;var options2={};for(var o in options)"eventSources"!==o&&(options2[o]=options[o]);return JSON.stringify(options2)}var calendar,sources=scope.eventSources,sourcesChanged=!1,eventSourcesWatcher=controller.changeWatcher(sources,controller.sourceFingerprint),eventsWatcher=controller.changeWatcher(controller.allEvents,controller.eventFingerprint),options=null;scope.destroyCalendar=function(){calendar&&calendar.fullCalendar&&calendar.fullCalendar("destroy"),calendar=attrs.calendar?uiCalendarConfig.calendars[attrs.calendar]=angular.element(elm).html(""):angular.element(elm).html("")},scope.initCalendar=function(){calendar||(calendar=angular.element(elm).html("")),calendar.fullCalendar(options),attrs.calendar&&(uiCalendarConfig.calendars[attrs.calendar]=calendar)},scope.$on("$destroy",function(){scope.destroyCalendar()}),eventSourcesWatcher.onAdded=function(source){calendar&&calendar.fullCalendar&&(calendar.fullCalendar(options),attrs.calendar&&(uiCalendarConfig.calendars[attrs.calendar]=calendar),calendar.fullCalendar("addEventSource",source),sourcesChanged=!0)},eventSourcesWatcher.onRemoved=function(source){calendar&&calendar.fullCalendar&&(calendar.fullCalendar("removeEventSource",source),sourcesChanged=!0)},eventSourcesWatcher.onChanged=function(){calendar&&calendar.fullCalendar&&(calendar.fullCalendar("refetchEvents"),sourcesChanged=!0)},eventsWatcher.onAdded=function(event){calendar&&calendar.fullCalendar&&calendar.fullCalendar("renderEvent",event,!!event.stick)},eventsWatcher.onRemoved=function(event){calendar&&calendar.fullCalendar&&calendar.fullCalendar("removeEvents",event._id)},eventsWatcher.onChanged=function(event){if(calendar&&calendar.fullCalendar)for(var clientEvents=calendar.fullCalendar("clientEvents",event._id),i=0;i<clientEvents.length;i++){var clientEvent=clientEvents[i];clientEvent=angular.extend(clientEvent,event),calendar.fullCalendar("updateEvent",clientEvent)}},eventSourcesWatcher.subscribe(scope),eventsWatcher.subscribe(scope,function(){if(sourcesChanged===!0)return sourcesChanged=!1,!1}),scope.$watch(getOptions,function(newValue,oldValue){newValue!==oldValue?(scope.destroyCalendar(),scope.initCalendar()):newValue&&angular.isUndefined(calendar)&&scope.initCalendar()})}}}]),!function(a){"function"==typeof define&&define.amd?define(["jquery","moment"],a):"object"==typeof exports?module.exports=a(require("jquery"),require("moment")):a(jQuery,moment)}(function(a,b){function c(a){return W(a,Xa)}function d(b){var c,d={views:b.views||{}};return a.each(b,function(b,e){"views"!=b&&(a.isPlainObject(e)&&!/(time|duration|interval)$/i.test(b)&&-1==a.inArray(b,Xa)?(c=null,a.each(e,function(a,e){/^(month|week|day|default|basic(Week|Day)?|agenda(Week|Day)?)$/.test(a)?(d.views[a]||(d.views[a]={}),d.views[a][b]=e):(c||(c={}),c[a]=e)}),c&&(d[b]=c)):d[b]=e)}),d}function e(a,b){b.left&&a.css({"border-left-width":1,"margin-left":b.left-1}),b.right&&a.css({"border-right-width":1,"margin-right":b.right-1})}function f(a){a.css({"margin-left":"","margin-right":"","border-left-width":"","border-right-width":""})}function g(){a("body").addClass("fc-not-allowed")}function h(){a("body").removeClass("fc-not-allowed")}function i(b,c,d){var e=Math.floor(c/b.length),f=Math.floor(c-e*(b.length-1)),g=[],h=[],i=[],k=0;j(b),b.each(function(c,d){var j=c===b.length-1?f:e,l=a(d).outerHeight(!0);j>l?(g.push(d),h.push(l),i.push(a(d).height())):k+=l}),d&&(c-=k,e=Math.floor(c/g.length),f=Math.floor(c-e*(g.length-1))),a(g).each(function(b,c){var d=b===g.length-1?f:e,j=h[b],k=i[b],l=d-(j-k);d>j&&a(c).height(l)})}function j(a){a.height("")}function k(b){var c=0;return b.find("> span").each(function(b,d){var e=a(d).outerWidth();e>c&&(c=e)}),c++,b.width(c),c}function l(a,b){var c,d=a.add(b);return d.css({position:"relative",left:-1}),c=a.outerHeight()-b.outerHeight(),d.css({position:"",left:""}),c}function m(b){var c=b.css("position"),d=b.parents().filter(function(){var b=a(this);return/(auto|scroll)/.test(b.css("overflow")+b.css("overflow-y")+b.css("overflow-x"))}).eq(0);return"fixed"!==c&&d.length?d:a(b[0].ownerDocument||document)}function n(a,b){var c=a.offset(),d=c.left-(b?b.left:0),e=c.top-(b?b.top:0);return{left:d,right:d+a.outerWidth(),top:e,bottom:e+a.outerHeight()}}function o(a,b){var c=a.offset(),d=q(a),e=c.left+t(a,"border-left-width")+d.left-(b?b.left:0),f=c.top+t(a,"border-top-width")+d.top-(b?b.top:0);return{left:e,right:e+a[0].clientWidth,top:f,bottom:f+a[0].clientHeight}}function p(a,b){var c=a.offset(),d=c.left+t(a,"border-left-width")+t(a,"padding-left")-(b?b.left:0),e=c.top+t(a,"border-top-width")+t(a,"padding-top")-(b?b.top:0);return{left:d,right:d+a.width(),top:e,bottom:e+a.height()}}function q(a){var b=a.innerWidth()-a[0].clientWidth,c={left:0,right:0,top:0,bottom:a.innerHeight()-a[0].clientHeight};return r()&&"rtl"==a.css("direction")?c.left=b:c.right=b,c}function r(){return null===Ya&&(Ya=s()),Ya}function s(){var b=a("<div><div/></div>").css({position:"absolute",top:-1e3,left:0,border:0,padding:0,overflow:"scroll",direction:"rtl"}).appendTo("body"),c=b.children(),d=c.offset().left>b.offset().left;return b.remove(),d}function t(a,b){return parseFloat(a.css(b))||0}function u(a){return 1==a.which&&!a.ctrlKey}function v(a){if(void 0!==a.pageX)return a.pageX;var b=a.originalEvent.touches;return b?b[0].pageX:void 0}function w(a){if(void 0!==a.pageY)return a.pageY;var b=a.originalEvent.touches;return b?b[0].pageY:void 0}function x(a){return/^touch/.test(a.type)}function y(a){a.addClass("fc-unselectable").on("selectstart",z)}function z(a){a.preventDefault()}function A(a){return!!window.addEventListener&&(window.addEventListener("scroll",a,!0),!0)}function B(a){return!!window.removeEventListener&&(window.removeEventListener("scroll",a,!0),!0)}function C(a,b){var c={left:Math.max(a.left,b.left),right:Math.min(a.right,b.right),top:Math.max(a.top,b.top),bottom:Math.min(a.bottom,b.bottom)};return c.left<c.right&&c.top<c.bottom&&c}function D(a,b){return{left:Math.min(Math.max(a.left,b.left),b.right),top:Math.min(Math.max(a.top,b.top),b.bottom)}}function E(a){return{left:(a.left+a.right)/2,top:(a.top+a.bottom)/2}}function F(a,b){return{left:a.left-b.left,top:a.top-b.top}}function G(b){var c,d,e=[],f=[];for("string"==typeof b?f=b.split(/\s*,\s*/):"function"==typeof b?f=[b]:a.isArray(b)&&(f=b),c=0;c<f.length;c++)d=f[c],"string"==typeof d?e.push("-"==d.charAt(0)?{field:d.substring(1),order:-1}:{field:d,order:1}):"function"==typeof d&&e.push({func:d});return e}function H(a,b,c){var d,e;for(d=0;d<c.length;d++)if(e=I(a,b,c[d]))return e;return 0}function I(a,b,c){return c.func?c.func(a,b):J(a[c.field],b[c.field])*(c.order||1)}function J(b,c){return b||c?null==c?-1:null==b?1:"string"===a.type(b)||"string"===a.type(c)?String(b).localeCompare(String(c)):b-c:0}function K(a,b){var c,d,e,f,g=a.start,h=a.end,i=b.start,j=b.end;return h>i&&j>g?(g>=i?(c=g.clone(),e=!0):(c=i.clone(),e=!1),j>=h?(d=h.clone(),f=!0):(d=j.clone(),f=!1),{start:c,end:d,isStart:e,isEnd:f}):void 0}function L(a,c){return b.duration({days:a.clone().stripTime().diff(c.clone().stripTime(),"days"),ms:a.time()-c.time()})}function M(a,c){return b.duration({days:a.clone().stripTime().diff(c.clone().stripTime(),"days")})}function N(a,c,d){return b.duration(Math.round(a.diff(c,d,!0)),d)}function O(a,b){var c,d,e;for(c=0;c<$a.length&&(d=$a[c],e=P(d,a,b),!(e>=1&&ha(e)));c++);return d}function P(a,c,d){return null!=d?d.diff(c,a,!0):b.isDuration(c)?c.as(a):c.end.diff(c.start,a,!0)}function Q(a,b,c){var d;return T(c)?(b-a)/c:(d=c.asMonths(),Math.abs(d)>=1&&ha(d)?b.diff(a,"months",!0)/d:b.diff(a,"days",!0)/c.asDays())}function R(a,b){var c,d;return T(a)||T(b)?a/b:(c=a.asMonths(),d=b.asMonths(),Math.abs(c)>=1&&ha(c)&&Math.abs(d)>=1&&ha(d)?c/d:a.asDays()/b.asDays())}function S(a,c){var d;return T(a)?b.duration(a*c):(d=a.asMonths(),Math.abs(d)>=1&&ha(d)?b.duration({months:d*c}):b.duration({days:a.asDays()*c}))}function T(a){return Boolean(a.hours()||a.minutes()||a.seconds()||a.milliseconds())}function U(a){return"[object Date]"===Object.prototype.toString.call(a)||a instanceof Date}function V(a){return/^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(a)}function W(a,b){var c,d,e,f,g,h,i={};if(b)for(c=0;c<b.length;c++){for(d=b[c],e=[],f=a.length-1;f>=0;f--)if(g=a[f][d],"object"==typeof g)e.unshift(g);else if(void 0!==g){i[d]=g;break}e.length&&(i[d]=W(e))}for(c=a.length-1;c>=0;c--){h=a[c];for(d in h)d in i||(i[d]=h[d])}return i}function X(a){var b=function(){};return b.prototype=a,new b}function Y(a,b){for(var c in a)$(a,c)&&(b[c]=a[c])}function Z(a,b){var c,d,e=["constructor","toString","valueOf"];for(c=0;c<e.length;c++)d=e[c],a[d]!==Object.prototype[d]&&(b[d]=a[d])}function $(a,b){return cb.call(a,b);
|
|
}function _(b){return/undefined|null|boolean|number|string/.test(a.type(b))}function aa(b,c,d){if(a.isFunction(b)&&(b=[b]),b){var e,f;for(e=0;e<b.length;e++)f=b[e].apply(c,d)||f;return f}}function ba(){for(var a=0;a<arguments.length;a++)if(void 0!==arguments[a])return arguments[a]}function ca(a){return(a+"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,"'").replace(/"/g,""").replace(/\n/g,"<br />")}function da(a){return a.replace(/&.*?;/g,"")}function ea(b){var c=[];return a.each(b,function(a,b){null!=b&&c.push(a+":"+b)}),c.join(";")}function fa(a){return a.charAt(0).toUpperCase()+a.slice(1)}function ga(a,b){return a-b}function ha(a){return a%1===0}function ia(a,b){var c=a[b];return function(){return c.apply(a,arguments)}}function ja(a,b,c){var d,e,f,g,h,i=function(){var j=+new Date-g;b>j?d=setTimeout(i,b-j):(d=null,c||(h=a.apply(f,e),f=e=null))};return function(){f=this,e=arguments,g=+new Date;var j=c&&!d;return d||(d=setTimeout(i,b)),j&&(h=a.apply(f,e),f=e=null),h}}function ka(c,d,e){var f,g,h,i,j=c[0],k=1==c.length&&"string"==typeof j;return b.isMoment(j)?(i=b.apply(null,c),ma(j,i)):U(j)||void 0===j?i=b.apply(null,c):(f=!1,g=!1,k?db.test(j)?(j+="-01",c=[j],f=!0,g=!0):(h=eb.exec(j))&&(f=!h[5],g=!0):a.isArray(j)&&(g=!0),i=d||f?b.utc.apply(b,c):b.apply(null,c),f?(i._ambigTime=!0,i._ambigZone=!0):e&&(g?i._ambigZone=!0:k&&(i.utcOffset?i.utcOffset(j):i.zone(j)))),i._fullCalendar=!0,i}function la(a,c){var d,e,f=!1,g=!1,h=a.length,i=[];for(d=0;h>d;d++)e=a[d],b.isMoment(e)||(e=Va.moment.parseZone(e)),f=f||e._ambigTime,g=g||e._ambigZone,i.push(e);for(d=0;h>d;d++)e=i[d],c||!f||e._ambigTime?g&&!e._ambigZone&&(i[d]=e.clone().stripZone()):i[d]=e.clone().stripTime();return i}function ma(a,b){a._ambigTime?b._ambigTime=!0:b._ambigTime&&(b._ambigTime=!1),a._ambigZone?b._ambigZone=!0:b._ambigZone&&(b._ambigZone=!1)}function na(a,b){a.year(b[0]||0).month(b[1]||0).date(b[2]||0).hours(b[3]||0).minutes(b[4]||0).seconds(b[5]||0).milliseconds(b[6]||0)}function oa(a,b){return gb.format.call(a,b)}function pa(a,b){return qa(a,va(b))}function qa(a,b){var c,d="";for(c=0;c<b.length;c++)d+=ra(a,b[c]);return d}function ra(a,b){var c,d;return"string"==typeof b?b:(c=b.token)?hb[c]?hb[c](a):oa(a,c):b.maybe&&(d=qa(a,b.maybe),d.match(/[1-9]/))?d:""}function sa(a,b,c,d,e){var f;return a=Va.moment.parseZone(a),b=Va.moment.parseZone(b),f=(a.localeData||a.lang).call(a),c=f.longDateFormat(c)||c,d=d||" - ",ta(a,b,va(c),d,e)}function ta(a,b,c,d,e){var f,g,h,i,j=a.clone().stripZone(),k=b.clone().stripZone(),l="",m="",n="",o="",p="";for(g=0;g<c.length&&(f=ua(a,b,j,k,c[g]),f!==!1);g++)l+=f;for(h=c.length-1;h>g&&(f=ua(a,b,j,k,c[h]),f!==!1);h--)m=f+m;for(i=g;h>=i;i++)n+=ra(a,c[i]),o+=ra(b,c[i]);return(n||o)&&(p=e?o+d+n:n+d+o),l+p+m}function ua(a,b,c,d,e){var f,g;return"string"==typeof e?e:!!((f=e.token)&&(g=ib[f.charAt(0)],g&&c.isSame(d,g)))&&oa(a,f)}function va(a){return a in jb?jb[a]:jb[a]=wa(a)}function wa(a){for(var b,c=[],d=/\[([^\]]*)\]|\(([^\)]*)\)|(LTS|LT|(\w)\4*o?)|([^\w\[\(]+)/g;b=d.exec(a);)b[1]?c.push(b[1]):b[2]?c.push({maybe:wa(b[2])}):b[3]?c.push({token:b[3]}):b[5]&&c.push(b[5]);return c}function xa(){}function ya(a,b){var c;return $(b,"constructor")&&(c=b.constructor),"function"!=typeof c&&(c=b.constructor=function(){a.apply(this,arguments)}),c.prototype=X(a.prototype),Y(b,c.prototype),Z(b,c.prototype),Y(a,c),c}function za(a,b){Y(b,a.prototype)}function Aa(a,b){return!a&&!b||!(!a||!b)&&(a.component===b.component&&Ba(a,b)&&Ba(b,a))}function Ba(a,b){for(var c in a)if(!/^(component|left|right|top|bottom)$/.test(c)&&a[c]!==b[c])return!1;return!0}function Ca(a){var b=Ea(a);return"background"===b||"inverse-background"===b}function Da(a){return"inverse-background"===Ea(a)}function Ea(a){return ba((a.source||{}).rendering,a.rendering)}function Fa(a){var b,c,d={};for(b=0;b<a.length;b++)c=a[b],(d[c._id]||(d[c._id]=[])).push(c);return d}function Ga(a,b){return a.start-b.start}function Ha(c){var d,e,f,g,h=Va.dataAttrPrefix;return h&&(h+="-"),d=c.data(h+"event")||null,d&&(d="object"==typeof d?a.extend({},d):{},e=d.start,null==e&&(e=d.time),f=d.duration,g=d.stick,delete d.start,delete d.time,delete d.duration,delete d.stick),null==e&&(e=c.data(h+"start")),null==e&&(e=c.data(h+"time")),null==f&&(f=c.data(h+"duration")),null==g&&(g=c.data(h+"stick")),e=null!=e?b.duration(e):null,f=null!=f?b.duration(f):null,g=Boolean(g),{eventProps:d,startTime:e,duration:f,stick:g}}function Ia(a,b){var c,d;for(c=0;c<b.length;c++)if(d=b[c],d.leftCol<=a.rightCol&&d.rightCol>=a.leftCol)return!0;return!1}function Ja(a,b){return a.leftCol-b.leftCol}function Ka(a){var b,c,d,e=[];for(b=0;b<a.length;b++){for(c=a[b],d=0;d<e.length&&Na(c,e[d]).length;d++);c.level=d,(e[d]||(e[d]=[])).push(c)}return e}function La(a){var b,c,d,e,f;for(b=0;b<a.length;b++)for(c=a[b],d=0;d<c.length;d++)for(e=c[d],e.forwardSegs=[],f=b+1;f<a.length;f++)Na(e,a[f],e.forwardSegs)}function Ma(a){var b,c,d=a.forwardSegs,e=0;if(void 0===a.forwardPressure){for(b=0;b<d.length;b++)c=d[b],Ma(c),e=Math.max(e,1+c.forwardPressure);a.forwardPressure=e}}function Na(a,b,c){c=c||[];for(var d=0;d<b.length;d++)Oa(a,b[d])&&c.push(b[d]);return c}function Oa(a,b){return a.bottom>b.top&&a.top<b.bottom}function Pa(c,d){function e(){T?h()&&(k(),i()):f()}function f(){U=O.theme?"ui":"fc",c.addClass("fc"),O.isRTL?c.addClass("fc-rtl"):c.addClass("fc-ltr"),O.theme?c.addClass("ui-widget"):c.addClass("fc-unthemed"),T=a("<div class='fc-view-container'/>").prependTo(c),R=N.header=new Sa(N,O),S=R.render(),S&&c.prepend(S),i(O.defaultView),O.handleWindowResize&&(Y=ja(m,O.windowResizeDelay),a(window).resize(Y))}function g(){V&&V.removeElement(),R.removeElement(),T.remove(),c.removeClass("fc fc-ltr fc-rtl fc-unthemed ui-widget"),Y&&a(window).unbind("resize",Y)}function h(){return c.is(":visible")}function i(b){ca++,V&&b&&V.type!==b&&(R.deactivateButton(V.type),H(),V.removeElement(),V=N.view=null),!V&&b&&(V=N.view=ba[b]||(ba[b]=N.instantiateView(b)),V.setElement(a("<div class='fc-view fc-"+b+"-view' />").appendTo(T)),R.activateButton(b)),V&&(Z=V.massageCurrentDate(Z),V.displaying&&Z.isWithin(V.intervalStart,V.intervalEnd)||h()&&(V.display(Z),I(),u(),v(),q())),I(),ca--}function j(a){return h()?(a&&l(),ca++,V.updateSize(!0),ca--,!0):void 0}function k(){h()&&l()}function l(){W="number"==typeof O.contentHeight?O.contentHeight:"number"==typeof O.height?O.height-(S?S.outerHeight(!0):0):Math.round(T.width()/Math.max(O.aspectRatio,.5))}function m(a){!ca&&a.target===window&&V.start&&j(!0)&&V.trigger("windowResize",aa)}function n(){p(),r()}function o(){h()&&(H(),V.displayEvents(da),I())}function p(){H(),V.clearEvents(),I()}function q(){!O.lazyFetching||$(V.start,V.end)?r():o()}function r(){_(V.start,V.end)}function s(a){da=a,o()}function t(){o()}function u(){R.updateTitle(V.title)}function v(){var a=N.getNow();a.isWithin(V.intervalStart,V.intervalEnd)?R.disableButton("today"):R.enableButton("today")}function w(a,b){V.select(N.buildSelectSpan.apply(N,arguments))}function x(){V&&V.unselect()}function y(){Z=V.computePrevDate(Z),i()}function z(){Z=V.computeNextDate(Z),i()}function A(){Z.add(-1,"years"),i()}function B(){Z.add(1,"years"),i()}function C(){Z=N.getNow(),i()}function D(a){Z=N.moment(a).stripZone(),i()}function E(a){Z.add(b.duration(a)),i()}function F(a,b){var c;b=b||"day",c=N.getViewSpec(b)||N.getUnitViewSpec(b),Z=a.clone(),i(c?c.type:null)}function G(){return N.applyTimezone(Z)}function H(){T.css({width:"100%",height:T.height(),overflow:"hidden"})}function I(){T.css({width:"",height:"",overflow:""})}function J(){return N}function K(){return V}function L(a,b){return void 0===b?O[a]:void("height"!=a&&"contentHeight"!=a&&"aspectRatio"!=a||(O[a]=b,j(!0)))}function M(a,b){var c=Array.prototype.slice.call(arguments,2);return b=b||aa,this.triggerWith(a,b,c),O[a]?O[a].apply(b,c):void 0}var N=this;N.initOptions(d||{});var O=this.options;N.render=e,N.destroy=g,N.refetchEvents=n,N.reportEvents=s,N.reportEventChange=t,N.rerenderEvents=o,N.changeView=i,N.select=w,N.unselect=x,N.prev=y,N.next=z,N.prevYear=A,N.nextYear=B,N.today=C,N.gotoDate=D,N.incrementDate=E,N.zoomTo=F,N.getDate=G,N.getCalendar=J,N.getView=K,N.option=L,N.trigger=M;var P=X(Ra(O.lang));if(O.monthNames&&(P._months=O.monthNames),O.monthNamesShort&&(P._monthsShort=O.monthNamesShort),O.dayNames&&(P._weekdays=O.dayNames),O.dayNamesShort&&(P._weekdaysShort=O.dayNamesShort),null!=O.firstDay){var Q=X(P._week);Q.dow=O.firstDay,P._week=Q}P._fullCalendar_weekCalc=function(a){return"function"==typeof a?a:"local"===a?a:"iso"===a||"ISO"===a?"ISO":void 0}(O.weekNumberCalculation),N.defaultAllDayEventDuration=b.duration(O.defaultAllDayEventDuration),N.defaultTimedEventDuration=b.duration(O.defaultTimedEventDuration),N.moment=function(){var a;return"local"===O.timezone?(a=Va.moment.apply(null,arguments),a.hasTime()&&a.local()):a="UTC"===O.timezone?Va.moment.utc.apply(null,arguments):Va.moment.parseZone.apply(null,arguments),"_locale"in a?a._locale=P:a._lang=P,a},N.getIsAmbigTimezone=function(){return"local"!==O.timezone&&"UTC"!==O.timezone},N.applyTimezone=function(a){if(!a.hasTime())return a.clone();var b,c=N.moment(a.toArray()),d=a.time()-c.time();return d&&(b=c.clone().add(d),a.time()-b.time()===0&&(c=b)),c},N.getNow=function(){var a=O.now;return"function"==typeof a&&(a=a()),N.moment(a).stripZone()},N.getEventEnd=function(a){return a.end?a.end.clone():N.getDefaultEventEnd(a.allDay,a.start)},N.getDefaultEventEnd=function(a,b){var c=b.clone();return a?c.stripTime().add(N.defaultAllDayEventDuration):c.add(N.defaultTimedEventDuration),N.getIsAmbigTimezone()&&c.stripZone(),c},N.humanizeDuration=function(a){return(a.locale||a.lang).call(a,O.lang).humanize()},Ta.call(N,O);var R,S,T,U,V,W,Y,Z,$=N.isFetchNeeded,_=N.fetchEvents,aa=c[0],ba={},ca=0,da=[];Z=null!=O.defaultDate?N.moment(O.defaultDate).stripZone():N.getNow(),N.getSuggestedViewHeight=function(){return void 0===W&&k(),W},N.isHeightAuto=function(){return"auto"===O.contentHeight||"auto"===O.height},N.freezeContentHeight=H,N.unfreezeContentHeight=I,N.initialize()}function Qa(b){a.each(Cb,function(a,c){null==b[a]&&(b[a]=c(b))})}function Ra(a){var c=b.localeData||b.langData;return c.call(b,a)||c.call(b,"en")}function Sa(b,c){function d(){var b=c.header;return n=c.theme?"ui":"fc",b?o=a("<div class='fc-toolbar'/>").append(f("left")).append(f("right")).append(f("center")).append('<div class="fc-clear"/>'):void 0}function e(){o.remove(),o=a()}function f(d){var e=a('<div class="fc-'+d+'"/>'),f=c.header[d];return f&&a.each(f.split(" "),function(d){var f,g=a(),h=!0;a.each(this.split(","),function(d,e){var f,i,j,k,l,m,o,q,r,s;"title"==e?(g=g.add(a("<h2> </h2>")),h=!1):((f=(b.options.customButtons||{})[e])?(j=function(a){f.click&&f.click.call(s[0],a)},k="",l=f.text):(i=b.getViewSpec(e))?(j=function(){b.changeView(e)},p.push(e),k=i.buttonTextOverride,l=i.buttonTextDefault):b[e]&&(j=function(){b[e]()},k=(b.overrides.buttonText||{})[e],l=c.buttonText[e]),j&&(m=f?f.themeIcon:c.themeButtonIcons[e],o=f?f.icon:c.buttonIcons[e],q=k?ca(k):m&&c.theme?"<span class='ui-icon ui-icon-"+m+"'></span>":o&&!c.theme?"<span class='fc-icon fc-icon-"+o+"'></span>":ca(l),r=["fc-"+e+"-button",n+"-button",n+"-state-default"],s=a('<button type="button" class="'+r.join(" ")+'">'+q+"</button>").click(function(a){s.hasClass(n+"-state-disabled")||(j(a),(s.hasClass(n+"-state-active")||s.hasClass(n+"-state-disabled"))&&s.removeClass(n+"-state-hover"))}).mousedown(function(){s.not("."+n+"-state-active").not("."+n+"-state-disabled").addClass(n+"-state-down")}).mouseup(function(){s.removeClass(n+"-state-down")}).hover(function(){s.not("."+n+"-state-active").not("."+n+"-state-disabled").addClass(n+"-state-hover")},function(){s.removeClass(n+"-state-hover").removeClass(n+"-state-down")}),g=g.add(s)))}),h&&g.first().addClass(n+"-corner-left").end().last().addClass(n+"-corner-right").end(),g.length>1?(f=a("<div/>"),h&&f.addClass("fc-button-group"),f.append(g),e.append(f)):e.append(g)}),e}function g(a){o.find("h2").text(a)}function h(a){o.find(".fc-"+a+"-button").addClass(n+"-state-active")}function i(a){o.find(".fc-"+a+"-button").removeClass(n+"-state-active")}function j(a){o.find(".fc-"+a+"-button").attr("disabled","disabled").addClass(n+"-state-disabled")}function k(a){o.find(".fc-"+a+"-button").removeAttr("disabled").removeClass(n+"-state-disabled")}function l(){return p}var m=this;m.render=d,m.removeElement=e,m.updateTitle=g,m.activateButton=h,m.deactivateButton=i,m.disableButton=j,m.enableButton=k,m.getViewsWithButtons=l;var n,o=a(),p=[]}function Ta(c){function d(a,b){return!I||I>a||b>J}function e(a,b){I=a,J=b,S=[];var c=++Q,d=P.length;R=d;for(var e=0;d>e;e++)f(P[e],c)}function f(b,c){g(b,function(d){var e,f,g,h=a.isArray(b.events);if(c==Q){if(d)for(e=0;e<d.length;e++)f=d[e],g=h?f:s(f,b),g&&S.push.apply(S,w(g));R--,R||K(S)}})}function g(b,d){var e,f,h=Va.sourceFetchers;for(e=0;e<h.length;e++){if(f=h[e].call(H,b,I.clone(),J.clone(),c.timezone,d),f===!0)return;if("object"==typeof f)return void g(f,d)}var i=b.events;if(i)a.isFunction(i)?(H.pushLoading(),i.call(H,I.clone(),J.clone(),c.timezone,function(a){d(a),H.popLoading()})):a.isArray(i)?d(i):d();else{var j=b.url;if(j){var k,l=b.success,m=b.error,n=b.complete;k=a.isFunction(b.data)?b.data():b.data;var o=a.extend({},k||{}),p=ba(b.startParam,c.startParam),q=ba(b.endParam,c.endParam),r=ba(b.timezoneParam,c.timezoneParam);p&&(o[p]=I.format()),q&&(o[q]=J.format()),c.timezone&&"local"!=c.timezone&&(o[r]=c.timezone),H.pushLoading(),a.ajax(a.extend({},Db,b,{data:o,success:function(b){b=b||[];var c=aa(l,this,arguments);a.isArray(c)&&(b=c),d(b)},error:function(){aa(m,this,arguments),d()},complete:function(){aa(n,this,arguments),H.popLoading()}}))}else d()}}function h(a){var b=i(a);b&&(P.push(b),R++,f(b,Q))}function i(b){var c,d,e=Va.sourceNormalizers;if(a.isFunction(b)||a.isArray(b)?c={events:b}:"string"==typeof b?c={url:b}:"object"==typeof b&&(c=a.extend({},b)),c){for(c.className?"string"==typeof c.className&&(c.className=c.className.split(/\s+/)):c.className=[],a.isArray(c.events)&&(c.origArray=c.events,c.events=a.map(c.events,function(a){return s(a,c)})),d=0;d<e.length;d++)e[d].call(H,c);return c}}function j(b){P=a.grep(P,function(a){return!k(a,b)}),S=a.grep(S,function(a){return!k(a.source,b)}),K(S)}function k(a,b){return a&&b&&l(a)==l(b)}function l(a){return("object"==typeof a?a.origArray||a.googleCalendarId||a.url||a.events:null)||a}function m(a){a.start=H.moment(a.start),a.end?a.end=H.moment(a.end):a.end=null,x(a,n(a)),K(S)}function n(b){var c={};return a.each(b,function(a,b){o(a)&&void 0!==b&&_(b)&&(c[a]=b)}),c}function o(a){return!/^_|^(id|allDay|start|end)$/.test(a)}function p(a,b){var c,d,e,f=s(a);if(f){for(c=w(f),d=0;d<c.length;d++)e=c[d],e.source||(b&&(O.events.push(e),e.source=O),S.push(e));return K(S),c}return[]}function q(b){var c,d;for(null==b?b=function(){return!0}:a.isFunction(b)||(c=b+"",b=function(a){return a._id==c}),S=a.grep(S,b,!0),d=0;d<P.length;d++)a.isArray(P[d].events)&&(P[d].events=a.grep(P[d].events,b,!0));K(S)}function r(b){return a.isFunction(b)?a.grep(S,b):null!=b?(b+="",a.grep(S,function(a){return a._id==b})):S}function s(d,e){var f,g,h,i={};if(c.eventDataTransform&&(d=c.eventDataTransform(d)),e&&e.eventDataTransform&&(d=e.eventDataTransform(d)),a.extend(i,d),e&&(i.source=e),i._id=d._id||(void 0===d.id?"_fc"+Eb++:d.id+""),d.className?"string"==typeof d.className?i.className=d.className.split(/\s+/):i.className=d.className:i.className=[],f=d.start||d.date,g=d.end,V(f)&&(f=b.duration(f)),V(g)&&(g=b.duration(g)),d.dow||b.isDuration(f)||b.isDuration(g))i.start=f?b.duration(f):null,i.end=g?b.duration(g):null,i._recurring=!0;else{if(f&&(f=H.moment(f),!f.isValid()))return!1;g&&(g=H.moment(g),g.isValid()||(g=null)),h=d.allDay,void 0===h&&(h=ba(e?e.allDayDefault:void 0,c.allDayDefault)),t(f,g,h,i)}return H.normalizeEvent(i),i}function t(a,b,c,d){d.start=a,d.end=b,d.allDay=c,u(d),Ua(d)}function u(a){v(a),a.end&&!a.end.isAfter(a.start)&&(a.end=null),a.end||(c.forceEventDuration?a.end=H.getDefaultEventEnd(a.allDay,a.start):a.end=null)}function v(a){null==a.allDay&&(a.allDay=!(a.start.hasTime()||a.end&&a.end.hasTime())),a.allDay?(a.start.stripTime(),a.end&&a.end.stripTime()):(a.start.hasTime()||(a.start=H.applyTimezone(a.start.time(0))),a.end&&!a.end.hasTime()&&(a.end=H.applyTimezone(a.end.time(0))))}function w(b,c,d){var e,f,g,h,i,j,k,l,m,n=[];if(c=c||I,d=d||J,b)if(b._recurring){if(f=b.dow)for(e={},g=0;g<f.length;g++)e[f[g]]=!0;for(h=c.clone().stripTime();h.isBefore(d);)e&&!e[h.day()]||(i=b.start,j=b.end,k=h.clone(),l=null,i&&(k=k.time(i)),j&&(l=h.clone().time(j)),m=a.extend({},b),t(k,l,!i&&!j,m),n.push(m)),h.add(1,"days")}else n.push(b);return n}function x(b,c,d){function e(a,b){return d?N(a,b,d):c.allDay?M(a,b):L(a,b)}var f,g,h,i,j,k,l={};return c=c||{},c.start||(c.start=b.start.clone()),void 0===c.end&&(c.end=b.end?b.end.clone():null),null==c.allDay&&(c.allDay=b.allDay),u(c),f={start:b._start.clone(),end:b._end?b._end.clone():H.getDefaultEventEnd(b._allDay,b._start),allDay:c.allDay},u(f),g=null!==b._end&&null===c.end,h=e(c.start,f.start),c.end?(i=e(c.end,f.end),j=i.subtract(h)):j=null,a.each(c,function(a,b){o(a)&&void 0!==b&&(l[a]=b)}),k=y(r(b._id),g,c.allDay,h,j,l),{dateDelta:h,durationDelta:j,undo:k}}function y(b,c,d,e,f,g){var h=H.getIsAmbigTimezone(),i=[];return e&&!e.valueOf()&&(e=null),f&&!f.valueOf()&&(f=null),a.each(b,function(b,j){var k,l;k={start:j.start.clone(),end:j.end?j.end.clone():null,allDay:j.allDay},a.each(g,function(a){k[a]=j[a]}),l={start:j._start,end:j._end,allDay:d},u(l),c?l.end=null:f&&!l.end&&(l.end=H.getDefaultEventEnd(l.allDay,l.start)),e&&(l.start.add(e),l.end&&l.end.add(e)),f&&l.end.add(f),h&&!l.allDay&&(e||f)&&(l.start.stripZone(),l.end&&l.end.stripZone()),a.extend(j,g,l),Ua(j),i.push(function(){a.extend(j,k),Ua(j)})}),function(){for(var a=0;a<i.length;a++)i[a]()}}function z(b){var d,e=c.businessHours,f={className:"fc-nonbusiness",start:"09:00",end:"17:00",dow:[1,2,3,4,5],rendering:"inverse-background"},g=H.getView();return e&&(d=a.extend({},f,"object"==typeof e?e:{})),d?(b&&(d.start=null,d.end=null),w(s(d),g.start,g.end)):[]}function A(a,b){var d=b.source||{},e=ba(b.constraint,d.constraint,c.eventConstraint),f=ba(b.overlap,d.overlap,c.eventOverlap);return D(a,e,f,b)}function B(b,c,d){var e,f;return d&&(e=a.extend({},d,c),f=w(s(e))[0]),f?A(b,f):C(b)}function C(a){return D(a,c.selectConstraint,c.selectOverlap)}function D(a,b,c,d){var e,f,g,h,i,j;if(null!=b){for(e=E(b),f=!1,h=0;h<e.length;h++)if(F(e[h],a)){f=!0;break}if(!f)return!1}for(g=H.getPeerEvents(a,d),h=0;h<g.length;h++)if(i=g[h],G(i,a)){if(c===!1)return!1;if("function"==typeof c&&!c(i,d))return!1;if(d){if(j=ba(i.overlap,(i.source||{}).overlap),j===!1)return!1;if("function"==typeof j&&!j(d,i))return!1}}return!0}function E(a){return"businessHours"===a?z():"object"==typeof a?w(s(a)):r(a)}function F(a,b){var c=a.start.clone().stripZone(),d=H.getEventEnd(a).stripZone();return b.start>=c&&b.end<=d}function G(a,b){var c=a.start.clone().stripZone(),d=H.getEventEnd(a).stripZone();return b.start<d&&b.end>c}var H=this;H.isFetchNeeded=d,H.fetchEvents=e,H.addEventSource=h,H.removeEventSource=j,H.updateEvent=m,H.renderEvent=p,H.removeEvents=q,H.clientEvents=r,H.mutateEvent=x,H.normalizeEventDates=u,H.normalizeEventTimes=v;var I,J,K=H.reportEvents,O={events:[]},P=[O],Q=0,R=0,S=[];a.each((c.events?[c.events]:[]).concat(c.eventSources||[]),function(a,b){var c=i(b);c&&P.push(c)}),H.getBusinessHoursEvents=z,H.isEventSpanAllowed=A,H.isExternalSpanAllowed=B,H.isSelectionSpanAllowed=C,H.getEventCache=function(){return S}}function Ua(a){a._allDay=a.allDay,a._start=a.start.clone(),a._end=a.end?a.end.clone():null}var Va=a.fullCalendar={version:"2.7.3",internalApiVersion:4},Wa=Va.views={};a.fn.fullCalendar=function(b){var c=Array.prototype.slice.call(arguments,1),d=this;return this.each(function(e,f){var g,h=a(f),i=h.data("fullCalendar");"string"==typeof b?i&&a.isFunction(i[b])&&(g=i[b].apply(i,c),e||(d=g),"destroy"===b&&h.removeData("fullCalendar")):i||(i=new yb(h,b),h.data("fullCalendar",i),i.render())}),d};var Xa=["header","buttonText","buttonIcons","themeButtonIcons"];Va.intersectRanges=K,Va.applyAll=aa,Va.debounce=ja,Va.isInt=ha,Va.htmlEscape=ca,Va.cssToStr=ea,Va.proxy=ia,Va.capitaliseFirstLetter=fa,Va.getOuterRect=n,Va.getClientRect=o,Va.getContentRect=p,Va.getScrollbarWidths=q;var Ya=null;Va.preventDefault=z,Va.intersectRects=C,Va.parseFieldSpecs=G,Va.compareByFieldSpecs=H,Va.compareByFieldSpec=I,Va.flexibleCompare=J,Va.computeIntervalUnit=O,Va.divideRangeByDuration=Q,Va.divideDurationByDuration=R,Va.multiplyDuration=S,Va.durationHasTime=T;var Za=["sun","mon","tue","wed","thu","fri","sat"],$a=["year","month","week","day","hour","minute","second","millisecond"];Va.log=function(){var a=window.console;return a&&a.log?a.log.apply(a,arguments):void 0},Va.warn=function(){var a=window.console;return a&&a.warn?a.warn.apply(a,arguments):Va.log.apply(Va,arguments)};var _a,ab,bb,cb={}.hasOwnProperty,db=/^\s*\d{4}-\d\d$/,eb=/^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?)?$/,fb=b.fn,gb=a.extend({},fb);Va.moment=function(){return ka(arguments)},Va.moment.utc=function(){var a=ka(arguments,!0);return a.hasTime()&&a.utc(),a},Va.moment.parseZone=function(){return ka(arguments,!0,!0)},fb.clone=function(){var a=gb.clone.apply(this,arguments);return ma(this,a),this._fullCalendar&&(a._fullCalendar=!0),a},fb.week=fb.weeks=function(a){var b=(this._locale||this._lang)._fullCalendar_weekCalc;return null==a&&"function"==typeof b?b(this):"ISO"===b?gb.isoWeek.apply(this,arguments):gb.week.apply(this,arguments)},fb.time=function(a){if(!this._fullCalendar)return gb.time.apply(this,arguments);if(null==a)return b.duration({hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds()});this._ambigTime=!1,b.isDuration(a)||b.isMoment(a)||(a=b.duration(a));var c=0;return b.isDuration(a)&&(c=24*Math.floor(a.asDays())),this.hours(c+a.hours()).minutes(a.minutes()).seconds(a.seconds()).milliseconds(a.milliseconds())},fb.stripTime=function(){var a;return this._ambigTime||(a=this.toArray(),this.utc(),ab(this,a.slice(0,3)),this._ambigTime=!0,this._ambigZone=!0),this},fb.hasTime=function(){return!this._ambigTime},fb.stripZone=function(){var a,b;return this._ambigZone||(a=this.toArray(),b=this._ambigTime,this.utc(),ab(this,a),this._ambigTime=b||!1,this._ambigZone=!0),this},fb.hasZone=function(){return!this._ambigZone},fb.local=function(){var a=this.toArray(),b=this._ambigZone;return gb.local.apply(this,arguments),this._ambigTime=!1,this._ambigZone=!1,b&&bb(this,a),this},fb.utc=function(){return gb.utc.apply(this,arguments),this._ambigTime=!1,this._ambigZone=!1,this},a.each(["zone","utcOffset"],function(a,b){gb[b]&&(fb[b]=function(a){return null!=a&&(this._ambigTime=!1,this._ambigZone=!1),gb[b].apply(this,arguments)})}),fb.format=function(){return this._fullCalendar&&arguments[0]?pa(this,arguments[0]):this._ambigTime?oa(this,"YYYY-MM-DD"):this._ambigZone?oa(this,"YYYY-MM-DD[T]HH:mm:ss"):gb.format.apply(this,arguments)},fb.toISOString=function(){return this._ambigTime?oa(this,"YYYY-MM-DD"):this._ambigZone?oa(this,"YYYY-MM-DD[T]HH:mm:ss"):gb.toISOString.apply(this,arguments)},fb.isWithin=function(a,b){var c=la([this,a,b]);return c[0]>=c[1]&&c[0]<c[2]},fb.isSame=function(a,b){var c;return this._fullCalendar?b?(c=la([this,a],!0),gb.isSame.call(c[0],c[1],b)):(a=Va.moment.parseZone(a),gb.isSame.call(this,a)&&Boolean(this._ambigTime)===Boolean(a._ambigTime)&&Boolean(this._ambigZone)===Boolean(a._ambigZone)):gb.isSame.apply(this,arguments)},a.each(["isBefore","isAfter"],function(a,b){fb[b]=function(a,c){var d;return this._fullCalendar?(d=la([this,a]),gb[b].call(d[0],d[1],c)):gb[b].apply(this,arguments)}}),_a="_d"in b()&&"updateOffset"in b,ab=_a?function(a,c){a._d.setTime(Date.UTC.apply(Date,c)),b.updateOffset(a,!1)}:na,bb=_a?function(a,c){a._d.setTime(+new Date(c[0]||0,c[1]||0,c[2]||0,c[3]||0,c[4]||0,c[5]||0,c[6]||0)),b.updateOffset(a,!1)}:na;var hb={t:function(a){return oa(a,"a").charAt(0)},T:function(a){return oa(a,"A").charAt(0)}};Va.formatRange=sa;var ib={Y:"year",M:"month",D:"day",d:"day",A:"second",a:"second",T:"second",t:"second",H:"second",h:"second",m:"second",s:"second"},jb={};Va.Class=xa,xa.extend=function(){var a,b,c=arguments.length;for(a=0;c>a;a++)b=arguments[a],c-1>a&&za(this,b);return ya(this,b||{})},xa.mixin=function(a){za(this,a)};var kb=Va.EmitterMixin={on:function(b,c){var d=function(a,b){return c.apply(b.context||this,b.args||[])};return c.guid||(c.guid=a.guid++),d.guid=c.guid,a(this).on(b,d),this},off:function(b,c){return a(this).off(b,c),this},trigger:function(b){var c=Array.prototype.slice.call(arguments,1);return a(this).triggerHandler(b,{args:c}),this},triggerWith:function(b,c,d){return a(this).triggerHandler(b,{context:c,args:d}),this}},lb=Va.ListenerMixin=function(){var b=0,c={listenerId:null,listenTo:function(b,c,d){if("object"==typeof c)for(var e in c)c.hasOwnProperty(e)&&this.listenTo(b,e,c[e]);else"string"==typeof c&&b.on(c+"."+this.getListenerNamespace(),a.proxy(d,this))},stopListeningTo:function(a,b){a.off((b||"")+"."+this.getListenerNamespace())},getListenerNamespace:function(){return null==this.listenerId&&(this.listenerId=b++),"_listener"+this.listenerId}};return c}(),mb={isIgnoringMouse:!1,delayUnignoreMouse:null,initMouseIgnoring:function(a){this.delayUnignoreMouse=ja(ia(this,"unignoreMouse"),a||1e3)},tempIgnoreMouse:function(){this.isIgnoringMouse=!0,this.delayUnignoreMouse()},unignoreMouse:function(){this.isIgnoringMouse=!1}},nb=xa.extend(lb,{isHidden:!0,options:null,el:null,margin:10,constructor:function(a){this.options=a||{}},show:function(){this.isHidden&&(this.el||this.render(),this.el.show(),this.position(),this.isHidden=!1,this.trigger("show"))},hide:function(){this.isHidden||(this.el.hide(),this.isHidden=!0,this.trigger("hide"))},render:function(){var b=this,c=this.options;this.el=a('<div class="fc-popover"/>').addClass(c.className||"").css({top:0,left:0}).append(c.content).appendTo(c.parentEl),this.el.on("click",".fc-close",function(){b.hide()}),c.autoHide&&this.listenTo(a(document),"mousedown",this.documentMousedown)},documentMousedown:function(b){this.el&&!a(b.target).closest(this.el).length&&this.hide()},removeElement:function(){this.hide(),this.el&&(this.el.remove(),this.el=null),this.stopListeningTo(a(document),"mousedown")},position:function(){var b,c,d,e,f,g=this.options,h=this.el.offsetParent().offset(),i=this.el.outerWidth(),j=this.el.outerHeight(),k=a(window),l=m(this.el);e=g.top||0,f=void 0!==g.left?g.left:void 0!==g.right?g.right-i:0,l.is(window)||l.is(document)?(l=k,b=0,c=0):(d=l.offset(),b=d.top,c=d.left),b+=k.scrollTop(),c+=k.scrollLeft(),g.viewportConstrain!==!1&&(e=Math.min(e,b+l.outerHeight()-j-this.margin),e=Math.max(e,b+this.margin),f=Math.min(f,c+l.outerWidth()-i-this.margin),f=Math.max(f,c+this.margin)),this.el.css({top:e-h.top,left:f-h.left})},trigger:function(a){this.options[a]&&this.options[a].apply(this,Array.prototype.slice.call(arguments,1))}}),ob=Va.CoordCache=xa.extend({els:null,forcedOffsetParentEl:null,origin:null,boundingRect:null,isHorizontal:!1,isVertical:!1,lefts:null,rights:null,tops:null,bottoms:null,constructor:function(b){this.els=a(b.els),this.isHorizontal=b.isHorizontal,this.isVertical=b.isVertical,this.forcedOffsetParentEl=b.offsetParent?a(b.offsetParent):null},build:function(){var a=this.forcedOffsetParentEl||this.els.eq(0).offsetParent();this.origin=a.offset(),this.boundingRect=this.queryBoundingRect(),this.isHorizontal&&this.buildElHorizontals(),this.isVertical&&this.buildElVerticals()},clear:function(){this.origin=null,this.boundingRect=null,this.lefts=null,this.rights=null,this.tops=null,this.bottoms=null},ensureBuilt:function(){this.origin||this.build()},queryBoundingRect:function(){var a=m(this.els.eq(0));return a.is(document)?void 0:o(a)},buildElHorizontals:function(){var b=[],c=[];this.els.each(function(d,e){var f=a(e),g=f.offset().left,h=f.outerWidth();b.push(g),c.push(g+h)}),this.lefts=b,this.rights=c},buildElVerticals:function(){var b=[],c=[];this.els.each(function(d,e){var f=a(e),g=f.offset().top,h=f.outerHeight();b.push(g),c.push(g+h)}),this.tops=b,this.bottoms=c},getHorizontalIndex:function(a){this.ensureBuilt();var b,c=this.boundingRect,d=this.lefts,e=this.rights,f=d.length;if(!c||a>=c.left&&a<c.right)for(b=0;f>b;b++)if(a>=d[b]&&a<e[b])return b},getVerticalIndex:function(a){this.ensureBuilt();var b,c=this.boundingRect,d=this.tops,e=this.bottoms,f=d.length;if(!c||a>=c.top&&a<c.bottom)for(b=0;f>b;b++)if(a>=d[b]&&a<e[b])return b},getLeftOffset:function(a){return this.ensureBuilt(),this.lefts[a]},getLeftPosition:function(a){return this.ensureBuilt(),this.lefts[a]-this.origin.left},getRightOffset:function(a){return this.ensureBuilt(),this.rights[a]},getRightPosition:function(a){return this.ensureBuilt(),this.rights[a]-this.origin.left},getWidth:function(a){return this.ensureBuilt(),this.rights[a]-this.lefts[a]},getTopOffset:function(a){return this.ensureBuilt(),this.tops[a]},getTopPosition:function(a){return this.ensureBuilt(),this.tops[a]-this.origin.top},getBottomOffset:function(a){return this.ensureBuilt(),this.bottoms[a]},getBottomPosition:function(a){return this.ensureBuilt(),this.bottoms[a]-this.origin.top},getHeight:function(a){return this.ensureBuilt(),this.bottoms[a]-this.tops[a]}}),pb=Va.DragListener=xa.extend(lb,mb,{options:null,subjectEl:null,subjectHref:null,originX:null,originY:null,scrollEl:null,isInteracting:!1,isDistanceSurpassed:!1,isDelayEnded:!1,isDragging:!1,isTouch:!1,delay:null,delayTimeoutId:null,minDistance:null,handleTouchScrollProxy:null,constructor:function(a){this.options=a||{},this.handleTouchScrollProxy=ia(this,"handleTouchScroll"),this.initMouseIgnoring(500)},startInteraction:function(b,c){var d=x(b);if("mousedown"===b.type){if(this.isIgnoringMouse)return;if(!u(b))return;b.preventDefault()}this.isInteracting||(c=c||{},this.delay=ba(c.delay,this.options.delay,0),this.minDistance=ba(c.distance,this.options.distance,0),this.subjectEl=this.options.subjectEl,this.isInteracting=!0,this.isTouch=d,this.isDelayEnded=!1,this.isDistanceSurpassed=!1,this.originX=v(b),this.originY=w(b),this.scrollEl=m(a(b.target)),this.bindHandlers(),this.initAutoScroll(),this.handleInteractionStart(b),this.startDelay(b),this.minDistance||this.handleDistanceSurpassed(b))},handleInteractionStart:function(a){this.trigger("interactionStart",a)},endInteraction:function(a,b){this.isInteracting&&(this.endDrag(a),this.delayTimeoutId&&(clearTimeout(this.delayTimeoutId),this.delayTimeoutId=null),this.destroyAutoScroll(),this.unbindHandlers(),this.isInteracting=!1,this.handleInteractionEnd(a,b),this.isTouch&&this.tempIgnoreMouse())},handleInteractionEnd:function(a,b){this.trigger("interactionEnd",a,b||!1)},bindHandlers:function(){var b=this,c=1;this.isTouch?(this.listenTo(a(document),{touchmove:this.handleTouchMove,touchend:this.endInteraction,touchcancel:this.endInteraction,touchstart:function(a){c?c--:b.endInteraction(a,!0)}}),!A(this.handleTouchScrollProxy)&&this.scrollEl&&this.listenTo(this.scrollEl,"scroll",this.handleTouchScroll)):this.listenTo(a(document),{mousemove:this.handleMouseMove,mouseup:this.endInteraction}),this.listenTo(a(document),{selectstart:z,contextmenu:z})},unbindHandlers:function(){this.stopListeningTo(a(document)),B(this.handleTouchScrollProxy),this.scrollEl&&this.stopListeningTo(this.scrollEl,"scroll")},startDrag:function(a,b){this.startInteraction(a,b),this.isDragging||(this.isDragging=!0,this.handleDragStart(a))},handleDragStart:function(a){this.trigger("dragStart",a),this.initHrefHack()},handleMove:function(a){var b,c=v(a)-this.originX,d=w(a)-this.originY,e=this.minDistance;this.isDistanceSurpassed||(b=c*c+d*d,b>=e*e&&this.handleDistanceSurpassed(a)),this.isDragging&&this.handleDrag(c,d,a)},handleDrag:function(a,b,c){this.trigger("drag",a,b,c),this.updateAutoScroll(c)},endDrag:function(a){this.isDragging&&(this.isDragging=!1,this.handleDragEnd(a))},handleDragEnd:function(a){
|
|
this.trigger("dragEnd",a),this.destroyHrefHack()},startDelay:function(a){var b=this;this.delay?this.delayTimeoutId=setTimeout(function(){b.handleDelayEnd(a)},this.delay):this.handleDelayEnd(a)},handleDelayEnd:function(a){this.isDelayEnded=!0,this.isDistanceSurpassed&&this.startDrag(a)},handleDistanceSurpassed:function(a){this.isDistanceSurpassed=!0,this.isDelayEnded&&this.startDrag(a)},handleTouchMove:function(a){this.isDragging&&a.preventDefault(),this.handleMove(a)},handleMouseMove:function(a){this.handleMove(a)},handleTouchScroll:function(a){this.isDragging||this.endInteraction(a,!0)},initHrefHack:function(){var a=this.subjectEl;(this.subjectHref=a?a.attr("href"):null)&&a.removeAttr("href")},destroyHrefHack:function(){var a=this.subjectEl,b=this.subjectHref;setTimeout(function(){b&&a.attr("href",b)},0)},trigger:function(a){this.options[a]&&this.options[a].apply(this,Array.prototype.slice.call(arguments,1)),this["_"+a]&&this["_"+a].apply(this,Array.prototype.slice.call(arguments,1))}});pb.mixin({isAutoScroll:!1,scrollBounds:null,scrollTopVel:null,scrollLeftVel:null,scrollIntervalId:null,scrollSensitivity:30,scrollSpeed:200,scrollIntervalMs:50,initAutoScroll:function(){var a=this.scrollEl;this.isAutoScroll=this.options.scroll&&a&&!a.is(window)&&!a.is(document),this.isAutoScroll&&this.listenTo(a,"scroll",ja(this.handleDebouncedScroll,100))},destroyAutoScroll:function(){this.endAutoScroll(),this.isAutoScroll&&this.stopListeningTo(this.scrollEl,"scroll")},computeScrollBounds:function(){this.isAutoScroll&&(this.scrollBounds=n(this.scrollEl))},updateAutoScroll:function(a){var b,c,d,e,f=this.scrollSensitivity,g=this.scrollBounds,h=0,i=0;g&&(b=(f-(w(a)-g.top))/f,c=(f-(g.bottom-w(a)))/f,d=(f-(v(a)-g.left))/f,e=(f-(g.right-v(a)))/f,b>=0&&1>=b?h=b*this.scrollSpeed*-1:c>=0&&1>=c&&(h=c*this.scrollSpeed),d>=0&&1>=d?i=d*this.scrollSpeed*-1:e>=0&&1>=e&&(i=e*this.scrollSpeed)),this.setScrollVel(h,i)},setScrollVel:function(a,b){this.scrollTopVel=a,this.scrollLeftVel=b,this.constrainScrollVel(),!this.scrollTopVel&&!this.scrollLeftVel||this.scrollIntervalId||(this.scrollIntervalId=setInterval(ia(this,"scrollIntervalFunc"),this.scrollIntervalMs))},constrainScrollVel:function(){var a=this.scrollEl;this.scrollTopVel<0?a.scrollTop()<=0&&(this.scrollTopVel=0):this.scrollTopVel>0&&a.scrollTop()+a[0].clientHeight>=a[0].scrollHeight&&(this.scrollTopVel=0),this.scrollLeftVel<0?a.scrollLeft()<=0&&(this.scrollLeftVel=0):this.scrollLeftVel>0&&a.scrollLeft()+a[0].clientWidth>=a[0].scrollWidth&&(this.scrollLeftVel=0)},scrollIntervalFunc:function(){var a=this.scrollEl,b=this.scrollIntervalMs/1e3;this.scrollTopVel&&a.scrollTop(a.scrollTop()+this.scrollTopVel*b),this.scrollLeftVel&&a.scrollLeft(a.scrollLeft()+this.scrollLeftVel*b),this.constrainScrollVel(),this.scrollTopVel||this.scrollLeftVel||this.endAutoScroll()},endAutoScroll:function(){this.scrollIntervalId&&(clearInterval(this.scrollIntervalId),this.scrollIntervalId=null,this.handleScrollEnd())},handleDebouncedScroll:function(){this.scrollIntervalId||this.handleScrollEnd()},handleScrollEnd:function(){}});var qb=pb.extend({component:null,origHit:null,hit:null,coordAdjust:null,constructor:function(a,b){pb.call(this,b),this.component=a},handleInteractionStart:function(a){var b,c,d,e=this.subjectEl;this.computeCoords(),a?(c={left:v(a),top:w(a)},d=c,e&&(b=n(e),d=D(d,b)),this.origHit=this.queryHit(d.left,d.top),e&&this.options.subjectCenter&&(this.origHit&&(b=C(this.origHit,b)||b),d=E(b)),this.coordAdjust=F(d,c)):(this.origHit=null,this.coordAdjust=null),pb.prototype.handleInteractionStart.apply(this,arguments)},computeCoords:function(){this.component.prepareHits(),this.computeScrollBounds()},handleDragStart:function(a){var b;pb.prototype.handleDragStart.apply(this,arguments),b=this.queryHit(v(a),w(a)),b&&this.handleHitOver(b)},handleDrag:function(a,b,c){var d;pb.prototype.handleDrag.apply(this,arguments),d=this.queryHit(v(c),w(c)),Aa(d,this.hit)||(this.hit&&this.handleHitOut(),d&&this.handleHitOver(d))},handleDragEnd:function(){this.handleHitDone(),pb.prototype.handleDragEnd.apply(this,arguments)},handleHitOver:function(a){var b=Aa(a,this.origHit);this.hit=a,this.trigger("hitOver",this.hit,b,this.origHit)},handleHitOut:function(){this.hit&&(this.trigger("hitOut",this.hit),this.handleHitDone(),this.hit=null)},handleHitDone:function(){this.hit&&this.trigger("hitDone",this.hit)},handleInteractionEnd:function(){pb.prototype.handleInteractionEnd.apply(this,arguments),this.origHit=null,this.hit=null,this.component.releaseHits()},handleScrollEnd:function(){pb.prototype.handleScrollEnd.apply(this,arguments),this.computeCoords()},queryHit:function(a,b){return this.coordAdjust&&(a+=this.coordAdjust.left,b+=this.coordAdjust.top),this.component.queryHit(a,b)}}),rb=xa.extend(lb,{options:null,sourceEl:null,el:null,parentEl:null,top0:null,left0:null,y0:null,x0:null,topDelta:null,leftDelta:null,isFollowing:!1,isHidden:!1,isAnimating:!1,constructor:function(b,c){this.options=c=c||{},this.sourceEl=b,this.parentEl=c.parentEl?a(c.parentEl):b.parent()},start:function(b){this.isFollowing||(this.isFollowing=!0,this.y0=w(b),this.x0=v(b),this.topDelta=0,this.leftDelta=0,this.isHidden||this.updatePosition(),x(b)?this.listenTo(a(document),"touchmove",this.handleMove):this.listenTo(a(document),"mousemove",this.handleMove))},stop:function(b,c){function d(){this.isAnimating=!1,e.removeElement(),this.top0=this.left0=null,c&&c()}var e=this,f=this.options.revertDuration;this.isFollowing&&!this.isAnimating&&(this.isFollowing=!1,this.stopListeningTo(a(document)),b&&f&&!this.isHidden?(this.isAnimating=!0,this.el.animate({top:this.top0,left:this.left0},{duration:f,complete:d})):d())},getEl:function(){var a=this.el;return a||(this.sourceEl.width(),a=this.el=this.sourceEl.clone().addClass(this.options.additionalClass||"").css({position:"absolute",visibility:"",display:this.isHidden?"none":"",margin:0,right:"auto",bottom:"auto",width:this.sourceEl.width(),height:this.sourceEl.height(),opacity:this.options.opacity||"",zIndex:this.options.zIndex}),a.addClass("fc-unselectable"),a.appendTo(this.parentEl)),a},removeElement:function(){this.el&&(this.el.remove(),this.el=null)},updatePosition:function(){var a,b;this.getEl(),null===this.top0&&(this.sourceEl.width(),a=this.sourceEl.offset(),b=this.el.offsetParent().offset(),this.top0=a.top-b.top,this.left0=a.left-b.left),this.el.css({top:this.top0+this.topDelta,left:this.left0+this.leftDelta})},handleMove:function(a){this.topDelta=w(a)-this.y0,this.leftDelta=v(a)-this.x0,this.isHidden||this.updatePosition()},hide:function(){this.isHidden||(this.isHidden=!0,this.el&&this.el.hide())},show:function(){this.isHidden&&(this.isHidden=!1,this.updatePosition(),this.getEl().show())}}),sb=Va.Grid=xa.extend(lb,mb,{view:null,isRTL:null,start:null,end:null,el:null,elsByFill:null,eventTimeFormat:null,displayEventTime:null,displayEventEnd:null,minResizeDuration:null,largeUnit:null,dayDragListener:null,segDragListener:null,segResizeListener:null,externalDragListener:null,constructor:function(a){this.view=a,this.isRTL=a.opt("isRTL"),this.elsByFill={},this.dayDragListener=this.buildDayDragListener(),this.initMouseIgnoring()},computeEventTimeFormat:function(){return this.view.opt("smallTimeFormat")},computeDisplayEventTime:function(){return!0},computeDisplayEventEnd:function(){return!0},setRange:function(a){this.start=a.start.clone(),this.end=a.end.clone(),this.rangeUpdated(),this.processRangeOptions()},rangeUpdated:function(){},processRangeOptions:function(){var a,b,c=this.view;this.eventTimeFormat=c.opt("eventTimeFormat")||c.opt("timeFormat")||this.computeEventTimeFormat(),a=c.opt("displayEventTime"),null==a&&(a=this.computeDisplayEventTime()),b=c.opt("displayEventEnd"),null==b&&(b=this.computeDisplayEventEnd()),this.displayEventTime=a,this.displayEventEnd=b},spanToSegs:function(a){},diffDates:function(a,b){return this.largeUnit?N(a,b,this.largeUnit):L(a,b)},prepareHits:function(){},releaseHits:function(){},queryHit:function(a,b){},getHitSpan:function(a){},getHitEl:function(a){},setElement:function(a){this.el=a,y(a),this.bindDayHandler("touchstart",this.dayTouchStart),this.bindDayHandler("mousedown",this.dayMousedown),this.bindSegHandlers(),this.bindGlobalHandlers()},bindDayHandler:function(b,c){var d=this;this.el.on(b,function(b){return a(b.target).is(".fc-event-container *, .fc-more")||a(b.target).closest(".fc-popover").length?void 0:c.call(d,b)})},removeElement:function(){this.unbindGlobalHandlers(),this.clearDragListeners(),this.el.remove()},renderSkeleton:function(){},renderDates:function(){},unrenderDates:function(){},bindGlobalHandlers:function(){this.listenTo(a(document),{dragstart:this.externalDragStart,sortstart:this.externalDragStart})},unbindGlobalHandlers:function(){this.stopListeningTo(a(document))},dayMousedown:function(a){this.isIgnoringMouse||this.dayDragListener.startInteraction(a,{})},dayTouchStart:function(a){var b=this.view;(b.isSelected||b.selectedEvent)&&this.tempIgnoreMouse(),this.dayDragListener.startInteraction(a,{delay:this.view.opt("longPressDelay")})},buildDayDragListener:function(){var a,b,c=this,d=this.view,e=d.opt("selectable"),f=new qb(this,{scroll:d.opt("dragScroll"),interactionStart:function(){a=f.origHit},dragStart:function(){d.unselect()},hitOver:function(d,f,h){h&&(f||(a=null),e&&(b=c.computeSelection(c.getHitSpan(h),c.getHitSpan(d)),b?c.renderSelection(b):b===!1&&g()))},hitOut:function(){a=null,b=null,c.unrenderSelection(),h()},interactionEnd:function(e,f){f||(a&&!c.isIgnoringMouse&&d.triggerDayClick(c.getHitSpan(a),c.getHitEl(a),e),b&&d.reportSelection(b,e),h())}});return f},clearDragListeners:function(){this.dayDragListener.endInteraction(),this.segDragListener&&this.segDragListener.endInteraction(),this.segResizeListener&&this.segResizeListener.endInteraction(),this.externalDragListener&&this.externalDragListener.endInteraction()},renderEventLocationHelper:function(a,b){var c=this.fabricateHelperEvent(a,b);return this.renderHelper(c,b)},fabricateHelperEvent:function(a,b){var c=b?X(b.event):{};return c.start=a.start.clone(),c.end=a.end?a.end.clone():null,c.allDay=null,this.view.calendar.normalizeEventDates(c),c.className=(c.className||[]).concat("fc-helper"),b||(c.editable=!1),c},renderHelper:function(a,b){},unrenderHelper:function(){},renderSelection:function(a){this.renderHighlight(a)},unrenderSelection:function(){this.unrenderHighlight()},computeSelection:function(a,b){var c=this.computeSelectionSpan(a,b);return!(c&&!this.view.calendar.isSelectionSpanAllowed(c))&&c},computeSelectionSpan:function(a,b){var c=[a.start,a.end,b.start,b.end];return c.sort(ga),{start:c[0].clone(),end:c[3].clone()}},renderHighlight:function(a){this.renderFill("highlight",this.spanToSegs(a))},unrenderHighlight:function(){this.unrenderFill("highlight")},highlightSegClasses:function(){return["fc-highlight"]},renderBusinessHours:function(){},unrenderBusinessHours:function(){},getNowIndicatorUnit:function(){},renderNowIndicator:function(a){},unrenderNowIndicator:function(){},renderFill:function(a,b){},unrenderFill:function(a){var b=this.elsByFill[a];b&&(b.remove(),delete this.elsByFill[a])},renderFillSegEls:function(b,c){var d,e=this,f=this[b+"SegEl"],g="",h=[];if(c.length){for(d=0;d<c.length;d++)g+=this.fillSegHtml(b,c[d]);a(g).each(function(b,d){var g=c[b],i=a(d);f&&(i=f.call(e,g,i)),i&&(i=a(i),i.is(e.fillSegTag)&&(g.el=i,h.push(g)))})}return h},fillSegTag:"div",fillSegHtml:function(a,b){var c=this[a+"SegClasses"],d=this[a+"SegCss"],e=c?c.call(this,b):[],f=ea(d?d.call(this,b):{});return"<"+this.fillSegTag+(e.length?' class="'+e.join(" ")+'"':"")+(f?' style="'+f+'"':"")+" />"},getDayClasses:function(a){var b=this.view,c=b.calendar.getNow(),d=["fc-"+Za[a.day()]];return 1==b.intervalDuration.as("months")&&a.month()!=b.intervalStart.month()&&d.push("fc-other-month"),a.isSame(c,"day")?d.push("fc-today",b.highlightStateClass):c>a?d.push("fc-past"):d.push("fc-future"),d}});sb.mixin({mousedOverSeg:null,isDraggingSeg:!1,isResizingSeg:!1,isDraggingExternal:!1,segs:null,renderEvents:function(a){var b,c=[],d=[];for(b=0;b<a.length;b++)(Ca(a[b])?c:d).push(a[b]);this.segs=[].concat(this.renderBgEvents(c),this.renderFgEvents(d))},renderBgEvents:function(a){var b=this.eventsToSegs(a);return this.renderBgSegs(b)||b},renderFgEvents:function(a){var b=this.eventsToSegs(a);return this.renderFgSegs(b)||b},unrenderEvents:function(){this.handleSegMouseout(),this.clearDragListeners(),this.unrenderFgSegs(),this.unrenderBgSegs(),this.segs=null},getEventSegs:function(){return this.segs||[]},renderFgSegs:function(a){},unrenderFgSegs:function(){},renderFgSegEls:function(b,c){var d,e=this.view,f="",g=[];if(b.length){for(d=0;d<b.length;d++)f+=this.fgSegHtml(b[d],c);a(f).each(function(c,d){var f=b[c],h=e.resolveEventEl(f.event,a(d));h&&(h.data("fc-seg",f),f.el=h,g.push(f))})}return g},fgSegHtml:function(a,b){},renderBgSegs:function(a){return this.renderFill("bgEvent",a)},unrenderBgSegs:function(){this.unrenderFill("bgEvent")},bgEventSegEl:function(a,b){return this.view.resolveEventEl(a.event,b)},bgEventSegClasses:function(a){var b=a.event,c=b.source||{};return["fc-bgevent"].concat(b.className,c.className||[])},bgEventSegCss:function(a){return{"background-color":this.getSegSkinCss(a)["background-color"]}},businessHoursSegClasses:function(a){return["fc-nonbusiness","fc-bgevent"]},bindSegHandlers:function(){this.bindSegHandler("touchstart",this.handleSegTouchStart),this.bindSegHandler("touchend",this.handleSegTouchEnd),this.bindSegHandler("mouseenter",this.handleSegMouseover),this.bindSegHandler("mouseleave",this.handleSegMouseout),this.bindSegHandler("mousedown",this.handleSegMousedown),this.bindSegHandler("click",this.handleSegClick)},bindSegHandler:function(b,c){var d=this;this.el.on(b,".fc-event-container > *",function(b){var e=a(this).data("fc-seg");return!e||d.isDraggingSeg||d.isResizingSeg?void 0:c.call(d,e,b)})},handleSegClick:function(a,b){return this.view.trigger("eventClick",a.el[0],a.event,b)},handleSegMouseover:function(a,b){this.isIgnoringMouse||this.mousedOverSeg||(this.mousedOverSeg=a,a.el.addClass("fc-allow-mouse-resize"),this.view.trigger("eventMouseover",a.el[0],a.event,b))},handleSegMouseout:function(a,b){b=b||{},this.mousedOverSeg&&(a=a||this.mousedOverSeg,this.mousedOverSeg=null,a.el.removeClass("fc-allow-mouse-resize"),this.view.trigger("eventMouseout",a.el[0],a.event,b))},handleSegMousedown:function(a,b){var c=this.startSegResize(a,b,{distance:5});!c&&this.view.isEventDraggable(a.event)&&this.buildSegDragListener(a).startInteraction(b,{distance:5})},handleSegTouchStart:function(a,b){var c,d=this.view,e=a.event,f=d.isEventSelected(e),g=d.isEventDraggable(e),h=d.isEventResizable(e),i=!1;f&&h&&(i=this.startSegResize(a,b)),i||!g&&!h||(c=g?this.buildSegDragListener(a):this.buildSegSelectListener(a),c.startInteraction(b,{delay:f?0:this.view.opt("longPressDelay")})),this.tempIgnoreMouse()},handleSegTouchEnd:function(a,b){this.tempIgnoreMouse()},startSegResize:function(b,c,d){return!!a(c.target).is(".fc-resizer")&&(this.buildSegResizeListener(b,a(c.target).is(".fc-start-resizer")).startInteraction(c,d),!0)},buildSegDragListener:function(a){var b,c,d,e=this,f=this.view,i=f.calendar,j=a.el,k=a.event;if(this.segDragListener)return this.segDragListener;var l=this.segDragListener=new qb(f,{scroll:f.opt("dragScroll"),subjectEl:j,subjectCenter:!0,interactionStart:function(d){b=!1,c=new rb(a.el,{additionalClass:"fc-dragging",parentEl:f.el,opacity:l.isTouch?null:f.opt("dragOpacity"),revertDuration:f.opt("dragRevertDuration"),zIndex:2}),c.hide(),c.start(d)},dragStart:function(c){l.isTouch&&!f.isEventSelected(k)&&f.selectEvent(k),b=!0,e.handleSegMouseout(a,c),e.segDragStart(a,c),f.hideEvent(k)},hitOver:function(b,h,j){var m;a.hit&&(j=a.hit),d=e.computeEventDrop(j.component.getHitSpan(j),b.component.getHitSpan(b),k),d&&!i.isEventSpanAllowed(e.eventToSpan(d),k)&&(g(),d=null),d&&(m=f.renderDrag(d,a))?(m.addClass("fc-dragging"),l.isTouch||e.applyDragOpacity(m),c.hide()):c.show(),h&&(d=null)},hitOut:function(){f.unrenderDrag(),c.show(),d=null},hitDone:function(){h()},interactionEnd:function(g){c.stop(!d,function(){b&&(f.unrenderDrag(),f.showEvent(k),e.segDragStop(a,g)),d&&f.reportEventDrop(k,d,this.largeUnit,j,g)}),e.segDragListener=null}});return l},buildSegSelectListener:function(a){var b=this,c=this.view,d=a.event;if(this.segDragListener)return this.segDragListener;var e=this.segDragListener=new pb({dragStart:function(a){e.isTouch&&!c.isEventSelected(d)&&c.selectEvent(d)},interactionEnd:function(a){b.segDragListener=null}});return e},segDragStart:function(a,b){this.isDraggingSeg=!0,this.view.trigger("eventDragStart",a.el[0],a.event,b,{})},segDragStop:function(a,b){this.isDraggingSeg=!1,this.view.trigger("eventDragStop",a.el[0],a.event,b,{})},computeEventDrop:function(a,b,c){var d,e,f=this.view.calendar,g=a.start,h=b.start;return g.hasTime()===h.hasTime()?(d=this.diffDates(h,g),c.allDay&&T(d)?(e={start:c.start.clone(),end:f.getEventEnd(c),allDay:!1},f.normalizeEventTimes(e)):e={start:c.start.clone(),end:c.end?c.end.clone():null,allDay:c.allDay},e.start.add(d),e.end&&e.end.add(d)):e={start:h.clone(),end:null,allDay:!h.hasTime()},e},applyDragOpacity:function(a){var b=this.view.opt("dragOpacity");null!=b&&a.each(function(a,c){c.style.opacity=b})},externalDragStart:function(b,c){var d,e,f=this.view;f.opt("droppable")&&(d=a((c?c.item:null)||b.target),e=f.opt("dropAccept"),(a.isFunction(e)?e.call(d[0],d):d.is(e))&&(this.isDraggingExternal||this.listenToExternalDrag(d,b,c)))},listenToExternalDrag:function(a,b,c){var d,e=this,f=this.view.calendar,i=Ha(a),j=e.externalDragListener=new qb(this,{interactionStart:function(){e.isDraggingExternal=!0},hitOver:function(a){d=e.computeExternalDrop(a.component.getHitSpan(a),i),d&&!f.isExternalSpanAllowed(e.eventToSpan(d),d,i.eventProps)&&(g(),d=null),d&&e.renderDrag(d)},hitOut:function(){d=null},hitDone:function(){h(),e.unrenderDrag()},interactionEnd:function(b){d&&e.view.reportExternalDrop(i,d,a,b,c),e.isDraggingExternal=!1,e.externalDragListener=null}});j.startDrag(b)},computeExternalDrop:function(a,b){var c=this.view.calendar,d={start:c.applyTimezone(a.start),end:null};return b.startTime&&!d.start.hasTime()&&d.start.time(b.startTime),b.duration&&(d.end=d.start.clone().add(b.duration)),d},renderDrag:function(a,b){},unrenderDrag:function(){},buildSegResizeListener:function(a,b){var c,d,e=this,f=this.view,i=f.calendar,j=a.el,k=a.event,l=i.getEventEnd(k),m=this.segResizeListener=new qb(this,{scroll:f.opt("dragScroll"),subjectEl:j,interactionStart:function(){c=!1},dragStart:function(b){c=!0,e.handleSegMouseout(a,b),e.segResizeStart(a,b)},hitOver:function(c,h,j){var m=e.getHitSpan(j),n=e.getHitSpan(c);d=b?e.computeEventStartResize(m,n,k):e.computeEventEndResize(m,n,k),d&&(i.isEventSpanAllowed(e.eventToSpan(d),k)?d.start.isSame(k.start)&&d.end.isSame(l)&&(d=null):(g(),d=null)),d&&(f.hideEvent(k),e.renderEventResize(d,a))},hitOut:function(){d=null},hitDone:function(){e.unrenderEventResize(),f.showEvent(k),h()},interactionEnd:function(b){c&&e.segResizeStop(a,b),d&&f.reportEventResize(k,d,this.largeUnit,j,b),e.segResizeListener=null}});return m},segResizeStart:function(a,b){this.isResizingSeg=!0,this.view.trigger("eventResizeStart",a.el[0],a.event,b,{})},segResizeStop:function(a,b){this.isResizingSeg=!1,this.view.trigger("eventResizeStop",a.el[0],a.event,b,{})},computeEventStartResize:function(a,b,c){return this.computeEventResize("start",a,b,c)},computeEventEndResize:function(a,b,c){return this.computeEventResize("end",a,b,c)},computeEventResize:function(a,b,c,d){var e,f,g=this.view.calendar,h=this.diffDates(c[a],b[a]);return e={start:d.start.clone(),end:g.getEventEnd(d),allDay:d.allDay},e.allDay&&T(h)&&(e.allDay=!1,g.normalizeEventTimes(e)),e[a].add(h),e.start.isBefore(e.end)||(f=this.minResizeDuration||(d.allDay?g.defaultAllDayEventDuration:g.defaultTimedEventDuration),"start"==a?e.start=e.end.clone().subtract(f):e.end=e.start.clone().add(f)),e},renderEventResize:function(a,b){},unrenderEventResize:function(){},getEventTimeText:function(a,b,c){return null==b&&(b=this.eventTimeFormat),null==c&&(c=this.displayEventEnd),this.displayEventTime&&a.start.hasTime()?c&&a.end?this.view.formatRange(a,b):a.start.format(b):""},getSegClasses:function(a,b,c){var d=this.view,e=a.event,f=["fc-event",a.isStart?"fc-start":"fc-not-start",a.isEnd?"fc-end":"fc-not-end"].concat(e.className,e.source?e.source.className:[]);return b&&f.push("fc-draggable"),c&&f.push("fc-resizable"),d.isEventSelected(e)&&f.push("fc-selected"),f},getSegSkinCss:function(a){var b=a.event,c=this.view,d=b.source||{},e=b.color,f=d.color,g=c.opt("eventColor");return{"background-color":b.backgroundColor||e||d.backgroundColor||f||c.opt("eventBackgroundColor")||g,"border-color":b.borderColor||e||d.borderColor||f||c.opt("eventBorderColor")||g,color:b.textColor||d.textColor||c.opt("eventTextColor")}},eventToSegs:function(a){return this.eventsToSegs([a])},eventToSpan:function(a){return this.eventToSpans(a)[0]},eventToSpans:function(a){var b=this.eventToRange(a);return this.eventRangeToSpans(b,a)},eventsToSegs:function(b,c){var d=this,e=Fa(b),f=[];return a.each(e,function(a,b){var e,g=[];for(e=0;e<b.length;e++)g.push(d.eventToRange(b[e]));if(Da(b[0]))for(g=d.invertRanges(g),e=0;e<g.length;e++)f.push.apply(f,d.eventRangeToSegs(g[e],b[0],c));else for(e=0;e<g.length;e++)f.push.apply(f,d.eventRangeToSegs(g[e],b[e],c))}),f},eventToRange:function(a){return{start:a.start.clone().stripZone(),end:(a.end?a.end.clone():this.view.calendar.getDefaultEventEnd(null!=a.allDay?a.allDay:!a.start.hasTime(),a.start)).stripZone()}},eventRangeToSegs:function(a,b,c){var d,e=this.eventRangeToSpans(a,b),f=[];for(d=0;d<e.length;d++)f.push.apply(f,this.eventSpanToSegs(e[d],b,c));return f},eventRangeToSpans:function(b,c){return[a.extend({},b)]},eventSpanToSegs:function(a,b,c){var d,e,f=c?c(a):this.spanToSegs(a);for(d=0;d<f.length;d++)e=f[d],e.event=b,e.eventStartMS=+a.start,e.eventDurationMS=a.end-a.start;return f},invertRanges:function(a){var b,c,d=this.view,e=d.start.clone(),f=d.end.clone(),g=[],h=e;for(a.sort(Ga),b=0;b<a.length;b++)c=a[b],c.start>h&&g.push({start:h,end:c.start}),h=c.end;return f>h&&g.push({start:h,end:f}),g},sortEventSegs:function(a){a.sort(ia(this,"compareEventSegs"))},compareEventSegs:function(a,b){return a.eventStartMS-b.eventStartMS||b.eventDurationMS-a.eventDurationMS||b.event.allDay-a.event.allDay||H(a.event,b.event,this.view.eventOrderSpecs)}}),Va.isBgEvent=Ca,Va.dataAttrPrefix="";var tb=Va.DayTableMixin={breakOnWeeks:!1,dayDates:null,dayIndices:null,daysPerRow:null,rowCnt:null,colCnt:null,colHeadFormat:null,updateDayTable:function(){for(var a,b,c,d=this.view,e=this.start.clone(),f=-1,g=[],h=[];e.isBefore(this.end);)d.isHiddenDay(e)?g.push(f+.5):(f++,g.push(f),h.push(e.clone())),e.add(1,"days");if(this.breakOnWeeks){for(b=h[0].day(),a=1;a<h.length&&h[a].day()!=b;a++);c=Math.ceil(h.length/a)}else c=1,a=h.length;this.dayDates=h,this.dayIndices=g,this.daysPerRow=a,this.rowCnt=c,this.updateDayTableCols()},updateDayTableCols:function(){this.colCnt=this.computeColCnt(),this.colHeadFormat=this.view.opt("columnFormat")||this.computeColHeadFormat()},computeColCnt:function(){return this.daysPerRow},getCellDate:function(a,b){return this.dayDates[this.getCellDayIndex(a,b)].clone()},getCellRange:function(a,b){var c=this.getCellDate(a,b),d=c.clone().add(1,"days");return{start:c,end:d}},getCellDayIndex:function(a,b){return a*this.daysPerRow+this.getColDayIndex(b)},getColDayIndex:function(a){return this.isRTL?this.colCnt-1-a:a},getDateDayIndex:function(a){var b=this.dayIndices,c=a.diff(this.start,"days");return 0>c?b[0]-1:c>=b.length?b[b.length-1]+1:b[c]},computeColHeadFormat:function(){return this.rowCnt>1||this.colCnt>10?"ddd":this.colCnt>1?this.view.opt("dayOfMonthFormat"):"dddd"},sliceRangeByRow:function(a){var b,c,d,e,f,g=this.daysPerRow,h=this.view.computeDayRange(a),i=this.getDateDayIndex(h.start),j=this.getDateDayIndex(h.end.clone().subtract(1,"days")),k=[];for(b=0;b<this.rowCnt;b++)c=b*g,d=c+g-1,e=Math.max(i,c),f=Math.min(j,d),e=Math.ceil(e),f=Math.floor(f),f>=e&&k.push({row:b,firstRowDayIndex:e-c,lastRowDayIndex:f-c,isStart:e===i,isEnd:f===j});return k},sliceRangeByDay:function(a){var b,c,d,e,f,g,h=this.daysPerRow,i=this.view.computeDayRange(a),j=this.getDateDayIndex(i.start),k=this.getDateDayIndex(i.end.clone().subtract(1,"days")),l=[];for(b=0;b<this.rowCnt;b++)for(c=b*h,d=c+h-1,e=c;d>=e;e++)f=Math.max(j,e),g=Math.min(k,e),f=Math.ceil(f),g=Math.floor(g),g>=f&&l.push({row:b,firstRowDayIndex:f-c,lastRowDayIndex:g-c,isStart:f===j,isEnd:g===k});return l},renderHeadHtml:function(){var a=this.view;return'<div class="fc-row '+a.widgetHeaderClass+'"><table><thead>'+this.renderHeadTrHtml()+"</thead></table></div>"},renderHeadIntroHtml:function(){return this.renderIntroHtml()},renderHeadTrHtml:function(){return"<tr>"+(this.isRTL?"":this.renderHeadIntroHtml())+this.renderHeadDateCellsHtml()+(this.isRTL?this.renderHeadIntroHtml():"")+"</tr>"},renderHeadDateCellsHtml:function(){var a,b,c=[];for(a=0;a<this.colCnt;a++)b=this.getCellDate(0,a),c.push(this.renderHeadDateCellHtml(b));return c.join("")},renderHeadDateCellHtml:function(a,b,c){var d=this.view;return'<th class="fc-day-header '+d.widgetHeaderClass+" fc-"+Za[a.day()]+'"'+(1==this.rowCnt?' data-date="'+a.format("YYYY-MM-DD")+'"':"")+(b>1?' colspan="'+b+'"':"")+(c?" "+c:"")+">"+ca(a.format(this.colHeadFormat))+"</th>"},renderBgTrHtml:function(a){return"<tr>"+(this.isRTL?"":this.renderBgIntroHtml(a))+this.renderBgCellsHtml(a)+(this.isRTL?this.renderBgIntroHtml(a):"")+"</tr>"},renderBgIntroHtml:function(a){return this.renderIntroHtml()},renderBgCellsHtml:function(a){var b,c,d=[];for(b=0;b<this.colCnt;b++)c=this.getCellDate(a,b),d.push(this.renderBgCellHtml(c));return d.join("")},renderBgCellHtml:function(a,b){var c=this.view,d=this.getDayClasses(a);return d.unshift("fc-day",c.widgetContentClass),'<td class="'+d.join(" ")+'" data-date="'+a.format("YYYY-MM-DD")+'"'+(b?" "+b:"")+"></td>"},renderIntroHtml:function(){},bookendCells:function(a){var b=this.renderIntroHtml();b&&(this.isRTL?a.append(b):a.prepend(b))}},ub=Va.DayGrid=sb.extend(tb,{numbersVisible:!1,bottomCoordPadding:0,rowEls:null,cellEls:null,helperEls:null,rowCoordCache:null,colCoordCache:null,renderDates:function(a){var b,c,d=this.view,e=this.rowCnt,f=this.colCnt,g="";for(b=0;e>b;b++)g+=this.renderDayRowHtml(b,a);for(this.el.html(g),this.rowEls=this.el.find(".fc-row"),this.cellEls=this.el.find(".fc-day"),this.rowCoordCache=new ob({els:this.rowEls,isVertical:!0}),this.colCoordCache=new ob({els:this.cellEls.slice(0,this.colCnt),isHorizontal:!0}),b=0;e>b;b++)for(c=0;f>c;c++)d.trigger("dayRender",null,this.getCellDate(b,c),this.getCellEl(b,c))},unrenderDates:function(){this.removeSegPopover()},renderBusinessHours:function(){var a=this.view.calendar.getBusinessHoursEvents(!0),b=this.eventsToSegs(a);this.renderFill("businessHours",b,"bgevent")},renderDayRowHtml:function(a,b){var c=this.view,d=["fc-row","fc-week",c.widgetContentClass];return b&&d.push("fc-rigid"),'<div class="'+d.join(" ")+'"><div class="fc-bg"><table>'+this.renderBgTrHtml(a)+'</table></div><div class="fc-content-skeleton"><table>'+(this.numbersVisible?"<thead>"+this.renderNumberTrHtml(a)+"</thead>":"")+"</table></div></div>"},renderNumberTrHtml:function(a){return"<tr>"+(this.isRTL?"":this.renderNumberIntroHtml(a))+this.renderNumberCellsHtml(a)+(this.isRTL?this.renderNumberIntroHtml(a):"")+"</tr>"},renderNumberIntroHtml:function(a){return this.renderIntroHtml()},renderNumberCellsHtml:function(a){var b,c,d=[];for(b=0;b<this.colCnt;b++)c=this.getCellDate(a,b),d.push(this.renderNumberCellHtml(c));return d.join("")},renderNumberCellHtml:function(a){var b;return this.view.dayNumbersVisible?(b=this.getDayClasses(a),b.unshift("fc-day-number"),'<td class="'+b.join(" ")+'" data-date="'+a.format()+'">'+a.date()+"</td>"):"<td/>"},computeEventTimeFormat:function(){return this.view.opt("extraSmallTimeFormat")},computeDisplayEventEnd:function(){return 1==this.colCnt},rangeUpdated:function(){this.updateDayTable()},spanToSegs:function(a){var b,c,d=this.sliceRangeByRow(a);for(b=0;b<d.length;b++)c=d[b],this.isRTL?(c.leftCol=this.daysPerRow-1-c.lastRowDayIndex,c.rightCol=this.daysPerRow-1-c.firstRowDayIndex):(c.leftCol=c.firstRowDayIndex,c.rightCol=c.lastRowDayIndex);return d},prepareHits:function(){this.colCoordCache.build(),this.rowCoordCache.build(),this.rowCoordCache.bottoms[this.rowCnt-1]+=this.bottomCoordPadding},releaseHits:function(){this.colCoordCache.clear(),this.rowCoordCache.clear()},queryHit:function(a,b){var c=this.colCoordCache.getHorizontalIndex(a),d=this.rowCoordCache.getVerticalIndex(b);return null!=d&&null!=c?this.getCellHit(d,c):void 0},getHitSpan:function(a){return this.getCellRange(a.row,a.col)},getHitEl:function(a){return this.getCellEl(a.row,a.col)},getCellHit:function(a,b){return{row:a,col:b,component:this,left:this.colCoordCache.getLeftOffset(b),right:this.colCoordCache.getRightOffset(b),top:this.rowCoordCache.getTopOffset(a),bottom:this.rowCoordCache.getBottomOffset(a)}},getCellEl:function(a,b){return this.cellEls.eq(a*this.colCnt+b)},renderDrag:function(a,b){return this.renderHighlight(this.eventToSpan(a)),b&&!b.el.closest(this.el).length?this.renderEventLocationHelper(a,b):void 0},unrenderDrag:function(){this.unrenderHighlight(),this.unrenderHelper()},renderEventResize:function(a,b){return this.renderHighlight(this.eventToSpan(a)),this.renderEventLocationHelper(a,b)},unrenderEventResize:function(){this.unrenderHighlight(),this.unrenderHelper()},renderHelper:function(b,c){var d,e=[],f=this.eventToSegs(b);return f=this.renderFgSegEls(f),d=this.renderSegRows(f),this.rowEls.each(function(b,f){var g,h=a(f),i=a('<div class="fc-helper-skeleton"><table/></div>');g=c&&c.row===b?c.el.position().top:h.find(".fc-content-skeleton tbody").position().top,i.css("top",g).find("table").append(d[b].tbodyEl),h.append(i),e.push(i[0])}),this.helperEls=a(e)},unrenderHelper:function(){this.helperEls&&(this.helperEls.remove(),this.helperEls=null)},fillSegTag:"td",renderFill:function(b,c,d){var e,f,g,h=[];for(c=this.renderFillSegEls(b,c),e=0;e<c.length;e++)f=c[e],g=this.renderFillRow(b,f,d),this.rowEls.eq(f.row).append(g),h.push(g[0]);return this.elsByFill[b]=a(h),c},renderFillRow:function(b,c,d){var e,f,g=this.colCnt,h=c.leftCol,i=c.rightCol+1;return d=d||b.toLowerCase(),e=a('<div class="fc-'+d+'-skeleton"><table><tr/></table></div>'),f=e.find("tr"),h>0&&f.append('<td colspan="'+h+'"/>'),f.append(c.el.attr("colspan",i-h)),g>i&&f.append('<td colspan="'+(g-i)+'"/>'),this.bookendCells(f),e}});ub.mixin({rowStructs:null,unrenderEvents:function(){this.removeSegPopover(),sb.prototype.unrenderEvents.apply(this,arguments)},getEventSegs:function(){return sb.prototype.getEventSegs.call(this).concat(this.popoverSegs||[])},renderBgSegs:function(b){var c=a.grep(b,function(a){return a.event.allDay});return sb.prototype.renderBgSegs.call(this,c)},renderFgSegs:function(b){var c;return b=this.renderFgSegEls(b),c=this.rowStructs=this.renderSegRows(b),this.rowEls.each(function(b,d){a(d).find(".fc-content-skeleton > table").append(c[b].tbodyEl)}),b},unrenderFgSegs:function(){for(var a,b=this.rowStructs||[];a=b.pop();)a.tbodyEl.remove();this.rowStructs=null},renderSegRows:function(a){var b,c,d=[];for(b=this.groupSegRows(a),c=0;c<b.length;c++)d.push(this.renderSegRow(c,b[c]));return d},fgSegHtml:function(a,b){var c,d,e=this.view,f=a.event,g=e.isEventDraggable(f),h=!b&&f.allDay&&a.isStart&&e.isEventResizableFromStart(f),i=!b&&f.allDay&&a.isEnd&&e.isEventResizableFromEnd(f),j=this.getSegClasses(a,g,h||i),k=ea(this.getSegSkinCss(a)),l="";return j.unshift("fc-day-grid-event","fc-h-event"),a.isStart&&(c=this.getEventTimeText(f),c&&(l='<span class="fc-time">'+ca(c)+"</span>")),d='<span class="fc-title">'+(ca(f.title||"")||" ")+"</span>",'<a class="'+j.join(" ")+'"'+(f.url?' href="'+ca(f.url)+'"':"")+(k?' style="'+k+'"':"")+'><div class="fc-content">'+(this.isRTL?d+" "+l:l+" "+d)+"</div>"+(h?'<div class="fc-resizer fc-start-resizer" />':"")+(i?'<div class="fc-resizer fc-end-resizer" />':"")+"</a>";
|
|
},renderSegRow:function(b,c){function d(b){for(;b>g;)k=(r[e-1]||[])[g],k?k.attr("rowspan",parseInt(k.attr("rowspan")||1,10)+1):(k=a("<td/>"),h.append(k)),q[e][g]=k,r[e][g]=k,g++}var e,f,g,h,i,j,k,l=this.colCnt,m=this.buildSegLevels(c),n=Math.max(1,m.length),o=a("<tbody/>"),p=[],q=[],r=[];for(e=0;n>e;e++){if(f=m[e],g=0,h=a("<tr/>"),p.push([]),q.push([]),r.push([]),f)for(i=0;i<f.length;i++){for(j=f[i],d(j.leftCol),k=a('<td class="fc-event-container"/>').append(j.el),j.leftCol!=j.rightCol?k.attr("colspan",j.rightCol-j.leftCol+1):r[e][g]=k;g<=j.rightCol;)q[e][g]=k,p[e][g]=j,g++;h.append(k)}d(l),this.bookendCells(h),o.append(h)}return{row:b,tbodyEl:o,cellMatrix:q,segMatrix:p,segLevels:m,segs:c}},buildSegLevels:function(a){var b,c,d,e=[];for(this.sortEventSegs(a),b=0;b<a.length;b++){for(c=a[b],d=0;d<e.length&&Ia(c,e[d]);d++);c.level=d,(e[d]||(e[d]=[])).push(c)}for(d=0;d<e.length;d++)e[d].sort(Ja);return e},groupSegRows:function(a){var b,c=[];for(b=0;b<this.rowCnt;b++)c.push([]);for(b=0;b<a.length;b++)c[a[b].row].push(a[b]);return c}}),ub.mixin({segPopover:null,popoverSegs:null,removeSegPopover:function(){this.segPopover&&this.segPopover.hide()},limitRows:function(a){var b,c,d=this.rowStructs||[];for(b=0;b<d.length;b++)this.unlimitRow(b),c=!!a&&("number"==typeof a?a:this.computeRowLevelLimit(b)),c!==!1&&this.limitRow(b,c)},computeRowLevelLimit:function(b){function c(b,c){f=Math.max(f,a(c).outerHeight())}var d,e,f,g=this.rowEls.eq(b),h=g.height(),i=this.rowStructs[b].tbodyEl.children();for(d=0;d<i.length;d++)if(e=i.eq(d).removeClass("fc-limited"),f=0,e.find("> td > :first-child").each(c),e.position().top+f>h)return d;return!1},limitRow:function(b,c){function d(d){for(;d>w;)j=t.getCellSegs(b,w,c),j.length&&(m=f[c-1][w],s=t.renderMoreLink(b,w,j),r=a("<div/>").append(s),m.append(r),v.push(r[0])),w++}var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t=this,u=this.rowStructs[b],v=[],w=0;if(c&&c<u.segLevels.length){for(e=u.segLevels[c-1],f=u.cellMatrix,g=u.tbodyEl.children().slice(c).addClass("fc-limited").get(),h=0;h<e.length;h++){for(i=e[h],d(i.leftCol),l=[],k=0;w<=i.rightCol;)j=this.getCellSegs(b,w,c),l.push(j),k+=j.length,w++;if(k){for(m=f[c-1][i.leftCol],n=m.attr("rowspan")||1,o=[],p=0;p<l.length;p++)q=a('<td class="fc-more-cell"/>').attr("rowspan",n),j=l[p],s=this.renderMoreLink(b,i.leftCol+p,[i].concat(j)),r=a("<div/>").append(s),q.append(r),o.push(q[0]),v.push(q[0]);m.addClass("fc-limited").after(a(o)),g.push(m[0])}}d(this.colCnt),u.moreEls=a(v),u.limitedEls=a(g)}},unlimitRow:function(a){var b=this.rowStructs[a];b.moreEls&&(b.moreEls.remove(),b.moreEls=null),b.limitedEls&&(b.limitedEls.removeClass("fc-limited"),b.limitedEls=null)},renderMoreLink:function(b,c,d){var e=this,f=this.view;return a('<a class="fc-more"/>').text(this.getMoreLinkText(d.length)).on("click",function(g){var h=f.opt("eventLimitClick"),i=e.getCellDate(b,c),j=a(this),k=e.getCellEl(b,c),l=e.getCellSegs(b,c),m=e.resliceDaySegs(l,i),n=e.resliceDaySegs(d,i);"function"==typeof h&&(h=f.trigger("eventLimitClick",null,{date:i,dayEl:k,moreEl:j,segs:m,hiddenSegs:n},g)),"popover"===h?e.showSegPopover(b,c,j,m):"string"==typeof h&&f.calendar.zoomTo(i,h)})},showSegPopover:function(a,b,c,d){var e,f,g=this,h=this.view,i=c.parent();e=1==this.rowCnt?h.el:this.rowEls.eq(a),f={className:"fc-more-popover",content:this.renderSegPopoverContent(a,b,d),parentEl:this.el,top:e.offset().top,autoHide:!0,viewportConstrain:h.opt("popoverViewportConstrain"),hide:function(){g.segPopover.removeElement(),g.segPopover=null,g.popoverSegs=null}},this.isRTL?f.right=i.offset().left+i.outerWidth()+1:f.left=i.offset().left-1,this.segPopover=new nb(f),this.segPopover.show()},renderSegPopoverContent:function(b,c,d){var e,f=this.view,g=f.opt("theme"),h=this.getCellDate(b,c).format(f.opt("dayPopoverFormat")),i=a('<div class="fc-header '+f.widgetHeaderClass+'"><span class="fc-close '+(g?"ui-icon ui-icon-closethick":"fc-icon fc-icon-x")+'"></span><span class="fc-title">'+ca(h)+'</span><div class="fc-clear"/></div><div class="fc-body '+f.widgetContentClass+'"><div class="fc-event-container"></div></div>'),j=i.find(".fc-event-container");for(d=this.renderFgSegEls(d,!0),this.popoverSegs=d,e=0;e<d.length;e++)this.prepareHits(),d[e].hit=this.getCellHit(b,c),this.releaseHits(),j.append(d[e].el);return i},resliceDaySegs:function(b,c){var d=a.map(b,function(a){return a.event}),e=c.clone(),f=e.clone().add(1,"days"),g={start:e,end:f};return b=this.eventsToSegs(d,function(a){var b=K(a,g);return b?[b]:[]}),this.sortEventSegs(b),b},getMoreLinkText:function(a){var b=this.view.opt("eventLimitText");return"function"==typeof b?b(a):"+"+a+" "+b},getCellSegs:function(a,b,c){for(var d,e=this.rowStructs[a].segMatrix,f=c||0,g=[];f<e.length;)d=e[f][b],d&&g.push(d),f++;return g}});var vb=Va.TimeGrid=sb.extend(tb,{slotDuration:null,snapDuration:null,snapsPerSlot:null,minTime:null,maxTime:null,labelFormat:null,labelInterval:null,colEls:null,slatContainerEl:null,slatEls:null,nowIndicatorEls:null,colCoordCache:null,slatCoordCache:null,constructor:function(){sb.apply(this,arguments),this.processOptions()},renderDates:function(){this.el.html(this.renderHtml()),this.colEls=this.el.find(".fc-day"),this.slatContainerEl=this.el.find(".fc-slats"),this.slatEls=this.slatContainerEl.find("tr"),this.colCoordCache=new ob({els:this.colEls,isHorizontal:!0}),this.slatCoordCache=new ob({els:this.slatEls,isVertical:!0}),this.renderContentSkeleton()},renderHtml:function(){return'<div class="fc-bg"><table>'+this.renderBgTrHtml(0)+'</table></div><div class="fc-slats"><table>'+this.renderSlatRowHtml()+"</table></div>"},renderSlatRowHtml:function(){for(var a,c,d,e=this.view,f=this.isRTL,g="",h=b.duration(+this.minTime);h<this.maxTime;)a=this.start.clone().time(h),c=ha(R(h,this.labelInterval)),d='<td class="fc-axis fc-time '+e.widgetContentClass+'" '+e.axisStyleAttr()+">"+(c?"<span>"+ca(a.format(this.labelFormat))+"</span>":"")+"</td>",g+='<tr data-time="'+a.format("HH:mm:ss")+'"'+(c?"":' class="fc-minor"')+">"+(f?"":d)+'<td class="'+e.widgetContentClass+'"/>'+(f?d:"")+"</tr>",h.add(this.slotDuration);return g},processOptions:function(){var c,d=this.view,e=d.opt("slotDuration"),f=d.opt("snapDuration");e=b.duration(e),f=f?b.duration(f):e,this.slotDuration=e,this.snapDuration=f,this.snapsPerSlot=e/f,this.minResizeDuration=f,this.minTime=b.duration(d.opt("minTime")),this.maxTime=b.duration(d.opt("maxTime")),c=d.opt("slotLabelFormat"),a.isArray(c)&&(c=c[c.length-1]),this.labelFormat=c||d.opt("axisFormat")||d.opt("smallTimeFormat"),c=d.opt("slotLabelInterval"),this.labelInterval=c?b.duration(c):this.computeLabelInterval(e)},computeLabelInterval:function(a){var c,d,e;for(c=Mb.length-1;c>=0;c--)if(d=b.duration(Mb[c]),e=R(d,a),ha(e)&&e>1)return d;return b.duration(a)},computeEventTimeFormat:function(){return this.view.opt("noMeridiemTimeFormat")},computeDisplayEventEnd:function(){return!0},prepareHits:function(){this.colCoordCache.build(),this.slatCoordCache.build()},releaseHits:function(){this.colCoordCache.clear()},queryHit:function(a,b){var c=this.snapsPerSlot,d=this.colCoordCache,e=this.slatCoordCache,f=d.getHorizontalIndex(a),g=e.getVerticalIndex(b);if(null!=f&&null!=g){var h=e.getTopOffset(g),i=e.getHeight(g),j=(b-h)/i,k=Math.floor(j*c),l=g*c+k,m=h+k/c*i,n=h+(k+1)/c*i;return{col:f,snap:l,component:this,left:d.getLeftOffset(f),right:d.getRightOffset(f),top:m,bottom:n}}},getHitSpan:function(a){var b,c=this.getCellDate(0,a.col),d=this.computeSnapTime(a.snap);return c.time(d),b=c.clone().add(this.snapDuration),{start:c,end:b}},getHitEl:function(a){return this.colEls.eq(a.col)},rangeUpdated:function(){this.updateDayTable()},computeSnapTime:function(a){return b.duration(this.minTime+this.snapDuration*a)},spanToSegs:function(a){var b,c=this.sliceRangeByTimes(a);for(b=0;b<c.length;b++)this.isRTL?c[b].col=this.daysPerRow-1-c[b].dayIndex:c[b].col=c[b].dayIndex;return c},sliceRangeByTimes:function(a){var b,c,d,e,f=[];for(c=0;c<this.daysPerRow;c++)d=this.dayDates[c].clone(),e={start:d.clone().time(this.minTime),end:d.clone().time(this.maxTime)},b=K(a,e),b&&(b.dayIndex=c,f.push(b));return f},updateSize:function(a){this.slatCoordCache.build(),a&&this.updateSegVerticals([].concat(this.fgSegs||[],this.bgSegs||[],this.businessSegs||[]))},getTotalSlatHeight:function(){return this.slatContainerEl.outerHeight()},computeDateTop:function(a,c){return this.computeTimeTop(b.duration(a-c.clone().stripTime()))},computeTimeTop:function(a){var b,c,d=this.slatEls.length,e=(a-this.minTime)/this.slotDuration;return e=Math.max(0,e),e=Math.min(d,e),b=Math.floor(e),b=Math.min(b,d-1),c=e-b,this.slatCoordCache.getTopPosition(b)+this.slatCoordCache.getHeight(b)*c},renderDrag:function(a,b){return b?this.renderEventLocationHelper(a,b):void this.renderHighlight(this.eventToSpan(a))},unrenderDrag:function(){this.unrenderHelper(),this.unrenderHighlight()},renderEventResize:function(a,b){return this.renderEventLocationHelper(a,b)},unrenderEventResize:function(){this.unrenderHelper()},renderHelper:function(a,b){return this.renderHelperSegs(this.eventToSegs(a),b)},unrenderHelper:function(){this.unrenderHelperSegs()},renderBusinessHours:function(){var a=this.view.calendar.getBusinessHoursEvents(),b=this.eventsToSegs(a);this.renderBusinessSegs(b)},unrenderBusinessHours:function(){this.unrenderBusinessSegs()},getNowIndicatorUnit:function(){return"minute"},renderNowIndicator:function(b){var c,d=this.spanToSegs({start:b,end:b}),e=this.computeDateTop(b,b),f=[];for(c=0;c<d.length;c++)f.push(a('<div class="fc-now-indicator fc-now-indicator-line"></div>').css("top",e).appendTo(this.colContainerEls.eq(d[c].col))[0]);d.length>0&&f.push(a('<div class="fc-now-indicator fc-now-indicator-arrow"></div>').css("top",e).appendTo(this.el.find(".fc-content-skeleton"))[0]),this.nowIndicatorEls=a(f)},unrenderNowIndicator:function(){this.nowIndicatorEls&&(this.nowIndicatorEls.remove(),this.nowIndicatorEls=null)},renderSelection:function(a){this.view.opt("selectHelper")?this.renderEventLocationHelper(a):this.renderHighlight(a)},unrenderSelection:function(){this.unrenderHelper(),this.unrenderHighlight()},renderHighlight:function(a){this.renderHighlightSegs(this.spanToSegs(a))},unrenderHighlight:function(){this.unrenderHighlightSegs()}});vb.mixin({colContainerEls:null,fgContainerEls:null,bgContainerEls:null,helperContainerEls:null,highlightContainerEls:null,businessContainerEls:null,fgSegs:null,bgSegs:null,helperSegs:null,highlightSegs:null,businessSegs:null,renderContentSkeleton:function(){var b,c,d="";for(b=0;b<this.colCnt;b++)d+='<td><div class="fc-content-col"><div class="fc-event-container fc-helper-container"></div><div class="fc-event-container"></div><div class="fc-highlight-container"></div><div class="fc-bgevent-container"></div><div class="fc-business-container"></div></div></td>';c=a('<div class="fc-content-skeleton"><table><tr>'+d+"</tr></table></div>"),this.colContainerEls=c.find(".fc-content-col"),this.helperContainerEls=c.find(".fc-helper-container"),this.fgContainerEls=c.find(".fc-event-container:not(.fc-helper-container)"),this.bgContainerEls=c.find(".fc-bgevent-container"),this.highlightContainerEls=c.find(".fc-highlight-container"),this.businessContainerEls=c.find(".fc-business-container"),this.bookendCells(c.find("tr")),this.el.append(c)},renderFgSegs:function(a){return a=this.renderFgSegsIntoContainers(a,this.fgContainerEls),this.fgSegs=a,a},unrenderFgSegs:function(){this.unrenderNamedSegs("fgSegs")},renderHelperSegs:function(b,c){var d,e,f,g=[];for(b=this.renderFgSegsIntoContainers(b,this.helperContainerEls),d=0;d<b.length;d++)e=b[d],c&&c.col===e.col&&(f=c.el,e.el.css({left:f.css("left"),right:f.css("right"),"margin-left":f.css("margin-left"),"margin-right":f.css("margin-right")})),g.push(e.el[0]);return this.helperSegs=b,a(g)},unrenderHelperSegs:function(){this.unrenderNamedSegs("helperSegs")},renderBgSegs:function(a){return a=this.renderFillSegEls("bgEvent",a),this.updateSegVerticals(a),this.attachSegsByCol(this.groupSegsByCol(a),this.bgContainerEls),this.bgSegs=a,a},unrenderBgSegs:function(){this.unrenderNamedSegs("bgSegs")},renderHighlightSegs:function(a){a=this.renderFillSegEls("highlight",a),this.updateSegVerticals(a),this.attachSegsByCol(this.groupSegsByCol(a),this.highlightContainerEls),this.highlightSegs=a},unrenderHighlightSegs:function(){this.unrenderNamedSegs("highlightSegs")},renderBusinessSegs:function(a){a=this.renderFillSegEls("businessHours",a),this.updateSegVerticals(a),this.attachSegsByCol(this.groupSegsByCol(a),this.businessContainerEls),this.businessSegs=a},unrenderBusinessSegs:function(){this.unrenderNamedSegs("businessSegs")},groupSegsByCol:function(a){var b,c=[];for(b=0;b<this.colCnt;b++)c.push([]);for(b=0;b<a.length;b++)c[a[b].col].push(a[b]);return c},attachSegsByCol:function(a,b){var c,d,e;for(c=0;c<this.colCnt;c++)for(d=a[c],e=0;e<d.length;e++)b.eq(c).append(d[e].el)},unrenderNamedSegs:function(a){var b,c=this[a];if(c){for(b=0;b<c.length;b++)c[b].el.remove();this[a]=null}},renderFgSegsIntoContainers:function(a,b){var c,d;for(a=this.renderFgSegEls(a),c=this.groupSegsByCol(a),d=0;d<this.colCnt;d++)this.updateFgSegCoords(c[d]);return this.attachSegsByCol(c,b),a},fgSegHtml:function(a,b){var c,d,e,f=this.view,g=a.event,h=f.isEventDraggable(g),i=!b&&a.isStart&&f.isEventResizableFromStart(g),j=!b&&a.isEnd&&f.isEventResizableFromEnd(g),k=this.getSegClasses(a,h,i||j),l=ea(this.getSegSkinCss(a));return k.unshift("fc-time-grid-event","fc-v-event"),f.isMultiDayEvent(g)?(a.isStart||a.isEnd)&&(c=this.getEventTimeText(a),d=this.getEventTimeText(a,"LT"),e=this.getEventTimeText(a,null,!1)):(c=this.getEventTimeText(g),d=this.getEventTimeText(g,"LT"),e=this.getEventTimeText(g,null,!1)),'<a class="'+k.join(" ")+'"'+(g.url?' href="'+ca(g.url)+'"':"")+(l?' style="'+l+'"':"")+'><div class="fc-content">'+(c?'<div class="fc-time" data-start="'+ca(e)+'" data-full="'+ca(d)+'"><span>'+ca(c)+"</span></div>":"")+(g.title?'<div class="fc-title">'+ca(g.title)+"</div>":"")+'</div><div class="fc-bg"/>'+(j?'<div class="fc-resizer fc-end-resizer" />':"")+"</a>"},updateSegVerticals:function(a){this.computeSegVerticals(a),this.assignSegVerticals(a)},computeSegVerticals:function(a){var b,c;for(b=0;b<a.length;b++)c=a[b],c.top=this.computeDateTop(c.start,c.start),c.bottom=this.computeDateTop(c.end,c.start)},assignSegVerticals:function(a){var b,c;for(b=0;b<a.length;b++)c=a[b],c.el.css(this.generateSegVerticalCss(c))},generateSegVerticalCss:function(a){return{top:a.top,bottom:-a.bottom}},updateFgSegCoords:function(a){this.computeSegVerticals(a),this.computeFgSegHorizontals(a),this.assignSegVerticals(a),this.assignFgSegHorizontals(a)},computeFgSegHorizontals:function(a){var b,c,d;if(this.sortEventSegs(a),b=Ka(a),La(b),c=b[0]){for(d=0;d<c.length;d++)Ma(c[d]);for(d=0;d<c.length;d++)this.computeFgSegForwardBack(c[d],0,0)}},computeFgSegForwardBack:function(a,b,c){var d,e=a.forwardSegs;if(void 0===a.forwardCoord)for(e.length?(this.sortForwardSegs(e),this.computeFgSegForwardBack(e[0],b+1,c),a.forwardCoord=e[0].backwardCoord):a.forwardCoord=1,a.backwardCoord=a.forwardCoord-(a.forwardCoord-c)/(b+1),d=0;d<e.length;d++)this.computeFgSegForwardBack(e[d],0,a.forwardCoord)},sortForwardSegs:function(a){a.sort(ia(this,"compareForwardSegs"))},compareForwardSegs:function(a,b){return b.forwardPressure-a.forwardPressure||(a.backwardCoord||0)-(b.backwardCoord||0)||this.compareEventSegs(a,b)},assignFgSegHorizontals:function(a){var b,c;for(b=0;b<a.length;b++)c=a[b],c.el.css(this.generateFgSegHorizontalCss(c)),c.bottom-c.top<30&&c.el.addClass("fc-short")},generateFgSegHorizontalCss:function(a){var b,c,d=this.view.opt("slotEventOverlap"),e=a.backwardCoord,f=a.forwardCoord,g=this.generateSegVerticalCss(a);return d&&(f=Math.min(1,e+2*(f-e))),this.isRTL?(b=1-f,c=e):(b=e,c=1-f),g.zIndex=a.level+1,g.left=100*b+"%",g.right=100*c+"%",d&&a.forwardPressure&&(g[this.isRTL?"marginLeft":"marginRight"]=20),g}});var wb=Va.View=xa.extend(kb,lb,{type:null,name:null,title:null,calendar:null,options:null,el:null,displaying:null,isSkeletonRendered:!1,isEventsRendered:!1,start:null,end:null,intervalStart:null,intervalEnd:null,intervalDuration:null,intervalUnit:null,isRTL:!1,isSelected:!1,selectedEvent:null,eventOrderSpecs:null,widgetHeaderClass:null,widgetContentClass:null,highlightStateClass:null,nextDayThreshold:null,isHiddenDayHash:null,isNowIndicatorRendered:null,initialNowDate:null,initialNowQueriedMs:null,nowIndicatorTimeoutID:null,nowIndicatorIntervalID:null,constructor:function(a,c,d,e){this.calendar=a,this.type=this.name=c,this.options=d,this.intervalDuration=e||b.duration(1,"day"),this.nextDayThreshold=b.duration(this.opt("nextDayThreshold")),this.initThemingProps(),this.initHiddenDays(),this.isRTL=this.opt("isRTL"),this.eventOrderSpecs=G(this.opt("eventOrder")),this.initialize()},initialize:function(){},opt:function(a){return this.options[a]},trigger:function(a,b){var c=this.calendar;return c.trigger.apply(c,[a,b||this].concat(Array.prototype.slice.call(arguments,2),[this]))},setDate:function(a){this.setRange(this.computeRange(a))},setRange:function(b){a.extend(this,b),this.updateTitle()},computeRange:function(a){var b,c,d=O(this.intervalDuration),e=a.clone().startOf(d),f=e.clone().add(this.intervalDuration);return/year|month|week|day/.test(d)?(e.stripTime(),f.stripTime()):(e.hasTime()||(e=this.calendar.time(0)),f.hasTime()||(f=this.calendar.time(0))),b=e.clone(),b=this.skipHiddenDays(b),c=f.clone(),c=this.skipHiddenDays(c,-1,!0),{intervalUnit:d,intervalStart:e,intervalEnd:f,start:b,end:c}},computePrevDate:function(a){return this.massageCurrentDate(a.clone().startOf(this.intervalUnit).subtract(this.intervalDuration),-1)},computeNextDate:function(a){return this.massageCurrentDate(a.clone().startOf(this.intervalUnit).add(this.intervalDuration))},massageCurrentDate:function(a,b){return this.intervalDuration.as("days")<=1&&this.isHiddenDay(a)&&(a=this.skipHiddenDays(a,b),a.startOf("day")),a},updateTitle:function(){this.title=this.computeTitle()},computeTitle:function(){return this.formatRange({start:this.calendar.applyTimezone(this.intervalStart),end:this.calendar.applyTimezone(this.intervalEnd)},this.opt("titleFormat")||this.computeTitleFormat(),this.opt("titleRangeSeparator"))},computeTitleFormat:function(){return"year"==this.intervalUnit?"YYYY":"month"==this.intervalUnit?this.opt("monthYearFormat"):this.intervalDuration.as("days")>1?"ll":"LL"},formatRange:function(a,b,c){var d=a.end;return d.hasTime()||(d=d.clone().subtract(1)),sa(a.start,d,b,c,this.opt("isRTL"))},setElement:function(a){this.el=a,this.bindGlobalHandlers()},removeElement:function(){this.clear(),this.isSkeletonRendered&&(this.unrenderSkeleton(),this.isSkeletonRendered=!1),this.unbindGlobalHandlers(),this.el.remove()},display:function(b){var c=this,d=null;return this.displaying&&(d=this.queryScroll()),this.calendar.freezeContentHeight(),this.clear().then(function(){return c.displaying=a.when(c.displayView(b)).then(function(){c.forceScroll(c.computeInitialScroll(d)),c.calendar.unfreezeContentHeight(),c.triggerRender()})})},clear:function(){var b=this,c=this.displaying;return c?c.then(function(){return b.displaying=null,b.clearEvents(),b.clearView()}):a.when()},displayView:function(a){this.isSkeletonRendered||(this.renderSkeleton(),this.isSkeletonRendered=!0),a&&this.setDate(a),this.render&&this.render(),this.renderDates(),this.updateSize(),this.renderBusinessHours(),this.startNowIndicator()},clearView:function(){this.unselect(),this.stopNowIndicator(),this.triggerUnrender(),this.unrenderBusinessHours(),this.unrenderDates(),this.destroy&&this.destroy()},renderSkeleton:function(){},unrenderSkeleton:function(){},renderDates:function(){},unrenderDates:function(){},triggerRender:function(){this.trigger("viewRender",this,this,this.el)},triggerUnrender:function(){this.trigger("viewDestroy",this,this,this.el)},bindGlobalHandlers:function(){this.listenTo(a(document),"mousedown",this.handleDocumentMousedown),this.listenTo(a(document),"touchstart",this.processUnselect)},unbindGlobalHandlers:function(){this.stopListeningTo(a(document))},initThemingProps:function(){var a=this.opt("theme")?"ui":"fc";this.widgetHeaderClass=a+"-widget-header",this.widgetContentClass=a+"-widget-content",this.highlightStateClass=a+"-state-highlight"},renderBusinessHours:function(){},unrenderBusinessHours:function(){},startNowIndicator:function(){var a,c,d,e=this;this.opt("nowIndicator")&&(a=this.getNowIndicatorUnit(),a&&(c=ia(this,"updateNowIndicator"),this.initialNowDate=this.calendar.getNow(),this.initialNowQueriedMs=+new Date,this.renderNowIndicator(this.initialNowDate),this.isNowIndicatorRendered=!0,d=this.initialNowDate.clone().startOf(a).add(1,a)-this.initialNowDate,this.nowIndicatorTimeoutID=setTimeout(function(){e.nowIndicatorTimeoutID=null,c(),d=+b.duration(1,a),d=Math.max(100,d),e.nowIndicatorIntervalID=setInterval(c,d)},d)))},updateNowIndicator:function(){this.isNowIndicatorRendered&&(this.unrenderNowIndicator(),this.renderNowIndicator(this.initialNowDate.clone().add(new Date-this.initialNowQueriedMs)))},stopNowIndicator:function(){this.isNowIndicatorRendered&&(this.nowIndicatorTimeoutID&&(clearTimeout(this.nowIndicatorTimeoutID),this.nowIndicatorTimeoutID=null),this.nowIndicatorIntervalID&&(clearTimeout(this.nowIndicatorIntervalID),this.nowIndicatorIntervalID=null),this.unrenderNowIndicator(),this.isNowIndicatorRendered=!1)},getNowIndicatorUnit:function(){},renderNowIndicator:function(a){},unrenderNowIndicator:function(){},updateSize:function(a){var b;a&&(b=this.queryScroll()),this.updateHeight(a),this.updateWidth(a),this.updateNowIndicator(),a&&this.setScroll(b)},updateWidth:function(a){},updateHeight:function(a){var b=this.calendar;this.setHeight(b.getSuggestedViewHeight(),b.isHeightAuto())},setHeight:function(a,b){},computeInitialScroll:function(a){return 0},queryScroll:function(){},setScroll:function(a){},forceScroll:function(a){var b=this;this.setScroll(a),setTimeout(function(){b.setScroll(a)},0)},displayEvents:function(a){var b=this.queryScroll();this.clearEvents(),this.renderEvents(a),this.isEventsRendered=!0,this.setScroll(b),this.triggerEventRender()},clearEvents:function(){var a;this.isEventsRendered&&(a=this.queryScroll(),this.triggerEventUnrender(),this.destroyEvents&&this.destroyEvents(),this.unrenderEvents(),this.setScroll(a),this.isEventsRendered=!1)},renderEvents:function(a){},unrenderEvents:function(){},triggerEventRender:function(){this.renderedEventSegEach(function(a){this.trigger("eventAfterRender",a.event,a.event,a.el)}),this.trigger("eventAfterAllRender")},triggerEventUnrender:function(){this.renderedEventSegEach(function(a){this.trigger("eventDestroy",a.event,a.event,a.el)})},resolveEventEl:function(b,c){var d=this.trigger("eventRender",b,b,c);return d===!1?c=null:d&&d!==!0&&(c=a(d)),c},showEvent:function(a){this.renderedEventSegEach(function(a){a.el.css("visibility","")},a)},hideEvent:function(a){this.renderedEventSegEach(function(a){a.el.css("visibility","hidden")},a)},renderedEventSegEach:function(a,b){var c,d=this.getEventSegs();for(c=0;c<d.length;c++)b&&d[c].event._id!==b._id||d[c].el&&a.call(this,d[c])},getEventSegs:function(){return[]},isEventDraggable:function(a){var b=a.source||{};return ba(a.startEditable,b.startEditable,this.opt("eventStartEditable"),a.editable,b.editable,this.opt("editable"))},reportEventDrop:function(a,b,c,d,e){var f=this.calendar,g=f.mutateEvent(a,b,c),h=function(){g.undo(),f.reportEventChange()};this.triggerEventDrop(a,g.dateDelta,h,d,e),f.reportEventChange()},triggerEventDrop:function(a,b,c,d,e){this.trigger("eventDrop",d[0],a,b,c,e,{})},reportExternalDrop:function(b,c,d,e,f){var g,h,i=b.eventProps;i&&(g=a.extend({},i,c),h=this.calendar.renderEvent(g,b.stick)[0]),this.triggerExternalDrop(h,c,d,e,f)},triggerExternalDrop:function(a,b,c,d,e){this.trigger("drop",c[0],b.start,d,e),a&&this.trigger("eventReceive",null,a)},renderDrag:function(a,b){},unrenderDrag:function(){},isEventResizableFromStart:function(a){return this.opt("eventResizableFromStart")&&this.isEventResizable(a)},isEventResizableFromEnd:function(a){return this.isEventResizable(a)},isEventResizable:function(a){var b=a.source||{};return ba(a.durationEditable,b.durationEditable,this.opt("eventDurationEditable"),a.editable,b.editable,this.opt("editable"))},reportEventResize:function(a,b,c,d,e){var f=this.calendar,g=f.mutateEvent(a,b,c),h=function(){g.undo(),f.reportEventChange()};this.triggerEventResize(a,g.durationDelta,h,d,e),f.reportEventChange()},triggerEventResize:function(a,b,c,d,e){this.trigger("eventResize",d[0],a,b,c,e,{})},select:function(a,b){this.unselect(b),this.renderSelection(a),this.reportSelection(a,b)},renderSelection:function(a){},reportSelection:function(a,b){this.isSelected=!0,this.triggerSelect(a,b)},triggerSelect:function(a,b){this.trigger("select",null,this.calendar.applyTimezone(a.start),this.calendar.applyTimezone(a.end),b)},unselect:function(a){this.isSelected&&(this.isSelected=!1,this.destroySelection&&this.destroySelection(),this.unrenderSelection(),this.trigger("unselect",null,a))},unrenderSelection:function(){},selectEvent:function(a){this.selectedEvent&&this.selectedEvent===a||(this.unselectEvent(),this.renderedEventSegEach(function(a){a.el.addClass("fc-selected")},a),this.selectedEvent=a)},unselectEvent:function(){this.selectedEvent&&(this.renderedEventSegEach(function(a){a.el.removeClass("fc-selected")},this.selectedEvent),this.selectedEvent=null)},isEventSelected:function(a){return this.selectedEvent&&this.selectedEvent._id===a._id},handleDocumentMousedown:function(a){u(a)&&this.processUnselect(a)},processUnselect:function(a){this.processRangeUnselect(a),this.processEventUnselect(a)},processRangeUnselect:function(b){var c;this.isSelected&&this.opt("unselectAuto")&&(c=this.opt("unselectCancel"),c&&a(b.target).closest(c).length||this.unselect(b))},processEventUnselect:function(b){this.selectedEvent&&(a(b.target).closest(".fc-selected").length||this.unselectEvent())},triggerDayClick:function(a,b,c){this.trigger("dayClick",b,this.calendar.applyTimezone(a.start),c)},initHiddenDays:function(){var b,c=this.opt("hiddenDays")||[],d=[],e=0;for(this.opt("weekends")===!1&&c.push(0,6),b=0;7>b;b++)(d[b]=-1!==a.inArray(b,c))||e++;if(!e)throw"invalid hiddenDays";this.isHiddenDayHash=d},isHiddenDay:function(a){return b.isMoment(a)&&(a=a.day()),this.isHiddenDayHash[a]},skipHiddenDays:function(a,b,c){var d=a.clone();for(b=b||1;this.isHiddenDayHash[(d.day()+(c?b:0)+7)%7];)d.add(b,"days");return d},computeDayRange:function(a){var b,c=a.start.clone().stripTime(),d=a.end,e=null;return d&&(e=d.clone().stripTime(),b=+d.time(),b&&b>=this.nextDayThreshold&&e.add(1,"days")),(!d||c>=e)&&(e=c.clone().add(1,"days")),{start:c,end:e}},isMultiDayEvent:function(a){var b=this.computeDayRange(a);return b.end.diff(b.start,"days")>1}}),xb=Va.Scroller=xa.extend({el:null,scrollEl:null,overflowX:null,overflowY:null,constructor:function(a){a=a||{},this.overflowX=a.overflowX||a.overflow||"auto",this.overflowY=a.overflowY||a.overflow||"auto"},render:function(){this.el=this.renderEl(),this.applyOverflow()},renderEl:function(){return this.scrollEl=a('<div class="fc-scroller"></div>')},clear:function(){this.setHeight("auto"),this.applyOverflow()},destroy:function(){this.el.remove()},applyOverflow:function(){this.scrollEl.css({"overflow-x":this.overflowX,"overflow-y":this.overflowY})},lockOverflow:function(a){var b=this.overflowX,c=this.overflowY;a=a||this.getScrollbarWidths(),"auto"===b&&(b=a.top||a.bottom||this.scrollEl[0].scrollWidth-1>this.scrollEl[0].clientWidth?"scroll":"hidden"),"auto"===c&&(c=a.left||a.right||this.scrollEl[0].scrollHeight-1>this.scrollEl[0].clientHeight?"scroll":"hidden"),this.scrollEl.css({"overflow-x":b,"overflow-y":c})},setHeight:function(a){this.scrollEl.height(a)},getScrollTop:function(){return this.scrollEl.scrollTop()},setScrollTop:function(a){this.scrollEl.scrollTop(a)},getClientWidth:function(){return this.scrollEl[0].clientWidth},getClientHeight:function(){return this.scrollEl[0].clientHeight},getScrollbarWidths:function(){return q(this.scrollEl)}}),yb=Va.Calendar=xa.extend({dirDefaults:null,langDefaults:null,overrides:null,options:null,viewSpecCache:null,view:null,header:null,loadingLevel:0,constructor:Pa,initialize:function(){},initOptions:function(a){var b,e,f,g;a=d(a),b=a.lang,e=zb[b],e||(b=yb.defaults.lang,e=zb[b]||{}),f=ba(a.isRTL,e.isRTL,yb.defaults.isRTL),g=f?yb.rtlDefaults:{},this.dirDefaults=g,this.langDefaults=e,this.overrides=a,this.options=c([yb.defaults,g,e,a]),Qa(this.options),this.viewSpecCache={}},getViewSpec:function(a){var b=this.viewSpecCache;return b[a]||(b[a]=this.buildViewSpec(a))},getUnitViewSpec:function(b){var c,d,e;if(-1!=a.inArray(b,$a))for(c=this.header.getViewsWithButtons(),a.each(Va.views,function(a){c.push(a)}),d=0;d<c.length;d++)if(e=this.getViewSpec(c[d]),e&&e.singleUnit==b)return e},buildViewSpec:function(a){for(var d,e,f,g,h=this.overrides.views||{},i=[],j=[],k=[],l=a;l;)d=Wa[l],e=h[l],l=null,"function"==typeof d&&(d={class:d}),d&&(i.unshift(d),j.unshift(d.defaults||{}),f=f||d.duration,l=l||d.type),e&&(k.unshift(e),f=f||e.duration,l=l||e.type);return d=W(i),d.type=a,!!d.class&&(f&&(f=b.duration(f),f.valueOf()&&(d.duration=f,g=O(f),1===f.as(g)&&(d.singleUnit=g,k.unshift(h[g]||{})))),d.defaults=c(j),d.overrides=c(k),this.buildViewSpecOptions(d),this.buildViewSpecButtonText(d,a),d)},buildViewSpecOptions:function(a){a.options=c([yb.defaults,a.defaults,this.dirDefaults,this.langDefaults,this.overrides,a.overrides]),Qa(a.options)},buildViewSpecButtonText:function(a,b){function c(c){var d=c.buttonText||{};return d[b]||(a.singleUnit?d[a.singleUnit]:null)}a.buttonTextOverride=c(this.overrides)||a.overrides.buttonText,a.buttonTextDefault=c(this.langDefaults)||c(this.dirDefaults)||a.defaults.buttonText||c(yb.defaults)||(a.duration?this.humanizeDuration(a.duration):null)||b},instantiateView:function(a){var b=this.getViewSpec(a);return new b.class(this,a,b.options,b.duration)},isValidViewType:function(a){return Boolean(this.getViewSpec(a))},pushLoading:function(){this.loadingLevel++||this.trigger("loading",null,!0,this.view)},popLoading:function(){--this.loadingLevel||this.trigger("loading",null,!1,this.view)},buildSelectSpan:function(a,b){var c,d=this.moment(a).stripZone();return c=b?this.moment(b).stripZone():d.hasTime()?d.clone().add(this.defaultTimedEventDuration):d.clone().add(this.defaultAllDayEventDuration),{start:d,end:c}}});yb.mixin(kb),yb.defaults={titleRangeSeparator:" — ",monthYearFormat:"MMMM YYYY",defaultTimedEventDuration:"02:00:00",defaultAllDayEventDuration:{days:1},forceEventDuration:!1,nextDayThreshold:"09:00:00",defaultView:"month",aspectRatio:1.35,header:{left:"title",center:"",right:"today prev,next"},weekends:!0,weekNumbers:!1,weekNumberTitle:"W",weekNumberCalculation:"local",scrollTime:"06:00:00",lazyFetching:!0,startParam:"start",endParam:"end",timezoneParam:"timezone",timezone:!1,isRTL:!1,buttonText:{prev:"prev",next:"next",prevYear:"prev year",nextYear:"next year",year:"year",today:"today",month:"month",week:"week",day:"day"},buttonIcons:{prev:"left-single-arrow",next:"right-single-arrow",prevYear:"left-double-arrow",nextYear:"right-double-arrow"},theme:!1,themeButtonIcons:{prev:"circle-triangle-w",next:"circle-triangle-e",prevYear:"seek-prev",nextYear:"seek-next"},dragOpacity:.75,dragRevertDuration:500,dragScroll:!0,unselectAuto:!0,dropAccept:"*",eventOrder:"title",eventLimit:!1,eventLimitText:"more",eventLimitClick:"popover",dayPopoverFormat:"LL",handleWindowResize:!0,windowResizeDelay:200,longPressDelay:1e3},yb.englishDefaults={dayPopoverFormat:"dddd, MMMM D"},yb.rtlDefaults={header:{left:"next,prev today",center:"",right:"title"},buttonIcons:{prev:"right-single-arrow",next:"left-single-arrow",prevYear:"right-double-arrow",nextYear:"left-double-arrow"},themeButtonIcons:{prev:"circle-triangle-e",next:"circle-triangle-w",nextYear:"seek-prev",prevYear:"seek-next"}};var zb=Va.langs={};Va.datepickerLang=function(b,c,d){var e=zb[b]||(zb[b]={});e.isRTL=d.isRTL,e.weekNumberTitle=d.weekHeader,a.each(Ab,function(a,b){
|
|
e[a]=b(d)}),a.datepicker&&(a.datepicker.regional[c]=a.datepicker.regional[b]=d,a.datepicker.regional.en=a.datepicker.regional[""],a.datepicker.setDefaults(d))},Va.lang=function(b,d){var e,f;e=zb[b]||(zb[b]={}),d&&(e=zb[b]=c([e,d])),f=Ra(b),a.each(Bb,function(a,b){null==e[a]&&(e[a]=b(f,e))}),yb.defaults.lang=b};var Ab={buttonText:function(a){return{prev:da(a.prevText),next:da(a.nextText),today:da(a.currentText)}},monthYearFormat:function(a){return a.showMonthAfterYear?"YYYY["+a.yearSuffix+"] MMMM":"MMMM YYYY["+a.yearSuffix+"]"}},Bb={dayOfMonthFormat:function(a,b){var c=a.longDateFormat("l");return c=c.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g,""),b.isRTL?c+=" ddd":c="ddd "+c,c},mediumTimeFormat:function(a){return a.longDateFormat("LT").replace(/\s*a$/i,"a")},smallTimeFormat:function(a){return a.longDateFormat("LT").replace(":mm","(:mm)").replace(/(\Wmm)$/,"($1)").replace(/\s*a$/i,"a")},extraSmallTimeFormat:function(a){return a.longDateFormat("LT").replace(":mm","(:mm)").replace(/(\Wmm)$/,"($1)").replace(/\s*a$/i,"t")},hourFormat:function(a){return a.longDateFormat("LT").replace(":mm","").replace(/(\Wmm)$/,"").replace(/\s*a$/i,"a")},noMeridiemTimeFormat:function(a){return a.longDateFormat("LT").replace(/\s*a$/i,"")}},Cb={smallDayDateFormat:function(a){return a.isRTL?"D dd":"dd D"},weekFormat:function(a){return a.isRTL?"w[ "+a.weekNumberTitle+"]":"["+a.weekNumberTitle+" ]w"},smallWeekFormat:function(a){return a.isRTL?"w["+a.weekNumberTitle+"]":"["+a.weekNumberTitle+"]w"}};Va.lang("en",yb.englishDefaults),Va.sourceNormalizers=[],Va.sourceFetchers=[];var Db={dataType:"json",cache:!1},Eb=1;yb.prototype.normalizeEvent=function(a){},yb.prototype.getPeerEvents=function(a,b){var c,d,e=this.getEventCache(),f=[];for(c=0;c<e.length;c++)d=e[c],b&&b._id===d._id||f.push(d);return f};var Fb=Va.BasicView=wb.extend({scroller:null,dayGridClass:ub,dayGrid:null,dayNumbersVisible:!1,weekNumbersVisible:!1,weekNumberWidth:null,headContainerEl:null,headRowEl:null,initialize:function(){this.dayGrid=this.instantiateDayGrid(),this.scroller=new xb({overflowX:"hidden",overflowY:"auto"})},instantiateDayGrid:function(){var a=this.dayGridClass.extend(Gb);return new a(this)},setRange:function(a){wb.prototype.setRange.call(this,a),this.dayGrid.breakOnWeeks=/year|month|week/.test(this.intervalUnit),this.dayGrid.setRange(a)},computeRange:function(a){var b=wb.prototype.computeRange.call(this,a);return/year|month/.test(b.intervalUnit)&&(b.start.startOf("week"),b.start=this.skipHiddenDays(b.start),b.end.weekday()&&(b.end.add(1,"week").startOf("week"),b.end=this.skipHiddenDays(b.end,-1,!0))),b},renderDates:function(){this.dayNumbersVisible=this.dayGrid.rowCnt>1,this.weekNumbersVisible=this.opt("weekNumbers"),this.dayGrid.numbersVisible=this.dayNumbersVisible||this.weekNumbersVisible,this.el.addClass("fc-basic-view").html(this.renderSkeletonHtml()),this.renderHead(),this.scroller.render();var b=this.scroller.el.addClass("fc-day-grid-container"),c=a('<div class="fc-day-grid" />').appendTo(b);this.el.find(".fc-body > tr > td").append(b),this.dayGrid.setElement(c),this.dayGrid.renderDates(this.hasRigidRows())},renderHead:function(){this.headContainerEl=this.el.find(".fc-head-container").html(this.dayGrid.renderHeadHtml()),this.headRowEl=this.headContainerEl.find(".fc-row")},unrenderDates:function(){this.dayGrid.unrenderDates(),this.dayGrid.removeElement(),this.scroller.destroy()},renderBusinessHours:function(){this.dayGrid.renderBusinessHours()},renderSkeletonHtml:function(){return'<table><thead class="fc-head"><tr><td class="fc-head-container '+this.widgetHeaderClass+'"></td></tr></thead><tbody class="fc-body"><tr><td class="'+this.widgetContentClass+'"></td></tr></tbody></table>'},weekNumberStyleAttr:function(){return null!==this.weekNumberWidth?'style="width:'+this.weekNumberWidth+'px"':""},hasRigidRows:function(){var a=this.opt("eventLimit");return a&&"number"!=typeof a},updateWidth:function(){this.weekNumbersVisible&&(this.weekNumberWidth=k(this.el.find(".fc-week-number")))},setHeight:function(a,b){var c,d,g=this.opt("eventLimit");this.scroller.clear(),f(this.headRowEl),this.dayGrid.removeSegPopover(),g&&"number"==typeof g&&this.dayGrid.limitRows(g),c=this.computeScrollerHeight(a),this.setGridHeight(c,b),g&&"number"!=typeof g&&this.dayGrid.limitRows(g),b||(this.scroller.setHeight(c),d=this.scroller.getScrollbarWidths(),(d.left||d.right)&&(e(this.headRowEl,d),c=this.computeScrollerHeight(a),this.scroller.setHeight(c)),this.scroller.lockOverflow(d))},computeScrollerHeight:function(a){return a-l(this.el,this.scroller.el)},setGridHeight:function(a,b){b?j(this.dayGrid.rowEls):i(this.dayGrid.rowEls,a,!0)},queryScroll:function(){return this.scroller.getScrollTop()},setScroll:function(a){this.scroller.setScrollTop(a)},prepareHits:function(){this.dayGrid.prepareHits()},releaseHits:function(){this.dayGrid.releaseHits()},queryHit:function(a,b){return this.dayGrid.queryHit(a,b)},getHitSpan:function(a){return this.dayGrid.getHitSpan(a)},getHitEl:function(a){return this.dayGrid.getHitEl(a)},renderEvents:function(a){this.dayGrid.renderEvents(a),this.updateHeight()},getEventSegs:function(){return this.dayGrid.getEventSegs()},unrenderEvents:function(){this.dayGrid.unrenderEvents()},renderDrag:function(a,b){return this.dayGrid.renderDrag(a,b)},unrenderDrag:function(){this.dayGrid.unrenderDrag()},renderSelection:function(a){this.dayGrid.renderSelection(a)},unrenderSelection:function(){this.dayGrid.unrenderSelection()}}),Gb={renderHeadIntroHtml:function(){var a=this.view;return a.weekNumbersVisible?'<th class="fc-week-number '+a.widgetHeaderClass+'" '+a.weekNumberStyleAttr()+"><span>"+ca(a.opt("weekNumberTitle"))+"</span></th>":""},renderNumberIntroHtml:function(a){var b=this.view;return b.weekNumbersVisible?'<td class="fc-week-number" '+b.weekNumberStyleAttr()+"><span>"+this.getCellDate(a,0).format("w")+"</span></td>":""},renderBgIntroHtml:function(){var a=this.view;return a.weekNumbersVisible?'<td class="fc-week-number '+a.widgetContentClass+'" '+a.weekNumberStyleAttr()+"></td>":""},renderIntroHtml:function(){var a=this.view;return a.weekNumbersVisible?'<td class="fc-week-number" '+a.weekNumberStyleAttr()+"></td>":""}},Hb=Va.MonthView=Fb.extend({computeRange:function(a){var b,c=Fb.prototype.computeRange.call(this,a);return this.isFixedWeeks()&&(b=Math.ceil(c.end.diff(c.start,"weeks",!0)),c.end.add(6-b,"weeks")),c},setGridHeight:function(a,b){b=b||"variable"===this.opt("weekMode"),b&&(a*=this.rowCnt/6),i(this.dayGrid.rowEls,a,!b)},isFixedWeeks:function(){var a=this.opt("weekMode");return a?"fixed"===a:this.opt("fixedWeekCount")}});Wa.basic={class:Fb},Wa.basicDay={type:"basic",duration:{days:1}},Wa.basicWeek={type:"basic",duration:{weeks:1}},Wa.month={class:Hb,duration:{months:1},defaults:{fixedWeekCount:!0}};var Ib=Va.AgendaView=wb.extend({scroller:null,timeGridClass:vb,timeGrid:null,dayGridClass:ub,dayGrid:null,axisWidth:null,headContainerEl:null,noScrollRowEls:null,bottomRuleEl:null,initialize:function(){this.timeGrid=this.instantiateTimeGrid(),this.opt("allDaySlot")&&(this.dayGrid=this.instantiateDayGrid()),this.scroller=new xb({overflowX:"hidden",overflowY:"auto"})},instantiateTimeGrid:function(){var a=this.timeGridClass.extend(Jb);return new a(this)},instantiateDayGrid:function(){var a=this.dayGridClass.extend(Kb);return new a(this)},setRange:function(a){wb.prototype.setRange.call(this,a),this.timeGrid.setRange(a),this.dayGrid&&this.dayGrid.setRange(a)},renderDates:function(){this.el.addClass("fc-agenda-view").html(this.renderSkeletonHtml()),this.renderHead(),this.scroller.render();var b=this.scroller.el.addClass("fc-time-grid-container"),c=a('<div class="fc-time-grid" />').appendTo(b);this.el.find(".fc-body > tr > td").append(b),this.timeGrid.setElement(c),this.timeGrid.renderDates(),this.bottomRuleEl=a('<hr class="fc-divider '+this.widgetHeaderClass+'"/>').appendTo(this.timeGrid.el),this.dayGrid&&(this.dayGrid.setElement(this.el.find(".fc-day-grid")),this.dayGrid.renderDates(),this.dayGrid.bottomCoordPadding=this.dayGrid.el.next("hr").outerHeight()),this.noScrollRowEls=this.el.find(".fc-row:not(.fc-scroller *)")},renderHead:function(){this.headContainerEl=this.el.find(".fc-head-container").html(this.timeGrid.renderHeadHtml())},unrenderDates:function(){this.timeGrid.unrenderDates(),this.timeGrid.removeElement(),this.dayGrid&&(this.dayGrid.unrenderDates(),this.dayGrid.removeElement()),this.scroller.destroy()},renderSkeletonHtml:function(){return'<table><thead class="fc-head"><tr><td class="fc-head-container '+this.widgetHeaderClass+'"></td></tr></thead><tbody class="fc-body"><tr><td class="'+this.widgetContentClass+'">'+(this.dayGrid?'<div class="fc-day-grid"/><hr class="fc-divider '+this.widgetHeaderClass+'"/>':"")+"</td></tr></tbody></table>"},axisStyleAttr:function(){return null!==this.axisWidth?'style="width:'+this.axisWidth+'px"':""},renderBusinessHours:function(){this.timeGrid.renderBusinessHours(),this.dayGrid&&this.dayGrid.renderBusinessHours()},unrenderBusinessHours:function(){this.timeGrid.unrenderBusinessHours(),this.dayGrid&&this.dayGrid.unrenderBusinessHours()},getNowIndicatorUnit:function(){return this.timeGrid.getNowIndicatorUnit()},renderNowIndicator:function(a){this.timeGrid.renderNowIndicator(a)},unrenderNowIndicator:function(){this.timeGrid.unrenderNowIndicator()},updateSize:function(a){this.timeGrid.updateSize(a),wb.prototype.updateSize.call(this,a)},updateWidth:function(){this.axisWidth=k(this.el.find(".fc-axis"))},setHeight:function(a,b){var c,d,g;this.bottomRuleEl.hide(),this.scroller.clear(),f(this.noScrollRowEls),this.dayGrid&&(this.dayGrid.removeSegPopover(),c=this.opt("eventLimit"),c&&"number"!=typeof c&&(c=Lb),c&&this.dayGrid.limitRows(c)),b||(d=this.computeScrollerHeight(a),this.scroller.setHeight(d),g=this.scroller.getScrollbarWidths(),(g.left||g.right)&&(e(this.noScrollRowEls,g),d=this.computeScrollerHeight(a),this.scroller.setHeight(d)),this.scroller.lockOverflow(g),this.timeGrid.getTotalSlatHeight()<d&&this.bottomRuleEl.show())},computeScrollerHeight:function(a){return a-l(this.el,this.scroller.el)},computeInitialScroll:function(){var a=b.duration(this.opt("scrollTime")),c=this.timeGrid.computeTimeTop(a);return c=Math.ceil(c),c&&c++,c},queryScroll:function(){return this.scroller.getScrollTop()},setScroll:function(a){this.scroller.setScrollTop(a)},prepareHits:function(){this.timeGrid.prepareHits(),this.dayGrid&&this.dayGrid.prepareHits()},releaseHits:function(){this.timeGrid.releaseHits(),this.dayGrid&&this.dayGrid.releaseHits()},queryHit:function(a,b){var c=this.timeGrid.queryHit(a,b);return!c&&this.dayGrid&&(c=this.dayGrid.queryHit(a,b)),c},getHitSpan:function(a){return a.component.getHitSpan(a)},getHitEl:function(a){return a.component.getHitEl(a)},renderEvents:function(a){var b,c,d=[],e=[],f=[];for(c=0;c<a.length;c++)a[c].allDay?d.push(a[c]):e.push(a[c]);b=this.timeGrid.renderEvents(e),this.dayGrid&&(f=this.dayGrid.renderEvents(d)),this.updateHeight()},getEventSegs:function(){return this.timeGrid.getEventSegs().concat(this.dayGrid?this.dayGrid.getEventSegs():[])},unrenderEvents:function(){this.timeGrid.unrenderEvents(),this.dayGrid&&this.dayGrid.unrenderEvents()},renderDrag:function(a,b){return a.start.hasTime()?this.timeGrid.renderDrag(a,b):this.dayGrid?this.dayGrid.renderDrag(a,b):void 0},unrenderDrag:function(){this.timeGrid.unrenderDrag(),this.dayGrid&&this.dayGrid.unrenderDrag()},renderSelection:function(a){a.start.hasTime()||a.end.hasTime()?this.timeGrid.renderSelection(a):this.dayGrid&&this.dayGrid.renderSelection(a)},unrenderSelection:function(){this.timeGrid.unrenderSelection(),this.dayGrid&&this.dayGrid.unrenderSelection()}}),Jb={renderHeadIntroHtml:function(){var a,b=this.view;return b.opt("weekNumbers")?(a=this.start.format(b.opt("smallWeekFormat")),'<th class="fc-axis fc-week-number '+b.widgetHeaderClass+'" '+b.axisStyleAttr()+"><span>"+ca(a)+"</span></th>"):'<th class="fc-axis '+b.widgetHeaderClass+'" '+b.axisStyleAttr()+"></th>"},renderBgIntroHtml:function(){var a=this.view;return'<td class="fc-axis '+a.widgetContentClass+'" '+a.axisStyleAttr()+"></td>"},renderIntroHtml:function(){var a=this.view;return'<td class="fc-axis" '+a.axisStyleAttr()+"></td>"}},Kb={renderBgIntroHtml:function(){var a=this.view;return'<td class="fc-axis '+a.widgetContentClass+'" '+a.axisStyleAttr()+"><span>"+(a.opt("allDayHtml")||ca(a.opt("allDayText")))+"</span></td>"},renderIntroHtml:function(){var a=this.view;return'<td class="fc-axis" '+a.axisStyleAttr()+"></td>"}},Lb=5,Mb=[{hours:1},{minutes:30},{minutes:15},{seconds:30},{seconds:15}];return Wa.agenda={class:Ib,defaults:{allDaySlot:!0,allDayText:"all-day",slotDuration:"00:30:00",minTime:"00:00:00",maxTime:"24:00:00",slotEventOverlap:!0}},Wa.agendaDay={type:"agenda",duration:{days:1}},Wa.agendaWeek={type:"agenda",duration:{weeks:1}},Va}),!function(t){"function"==typeof define&&define.amd?define(["jquery","moment","fullcalendar"],t):"object"==typeof exports?module.exports=t(require("jquery"),require("moment"),require("fullcalendar")):t(jQuery,moment)}(function(t,e){var r,o,i,n,s,l,h,u,a,c,p,d,f,g,y,v,w,m,R,S,b,C,E,T,H,_,I,D,x,F,G,M,W,L,B,z,k,V,P,A,O,q,N,j,Y,U,X,$,K,Q,J,Z,tt,et,rt,ot,it,nt,st,lt,ht,ut,at,ct,pt,dt,ft,gt,yt,vt,wt,mt,Rt,St,bt,Ct,Et,Tt,Ht,_t,It,Dt,xt,Ft,Gt,Mt,Wt,Lt,Bt,zt,kt=function(t,e){function r(){this.constructor=t}for(var o in e)Vt.call(e,o)&&(t[o]=e[o]);return r.prototype=e.prototype,t.prototype=new r,t.__super__=e.prototype,t},Vt={}.hasOwnProperty,Pt=[].slice;return d=t.fullCalendar,d.schedulerVersion="1.3.2",4!==d.internalApiVersion?void d.warn("v"+d.schedulerVersion+" of FullCalendar Scheduler is incompatible with v"+d.version+" of the core.\nPlease see http://fullcalendar.io/support/ for more information."):(o=d.Calendar,n=d.Class,X=d.View,f=d.Grid,vt=d.intersectRanges,ot=d.debounce,Rt=d.isInt,ft=d.getScrollbarWidths,u=d.DragListener,yt=d.htmlEscape,J=d.computeIntervalUnit,Ft=d.proxy,K=d.capitaliseFirstLetter,$=d.applyAll,a=d.EmitterMixin,v=d.ListenerMixin,lt=d.durationHasTime,st=d.divideRangeByDuration,nt=d.divideDurationByDuration,Ct=d.multiplyDuration,Dt=d.parseFieldSpecs,Q=d.compareByFieldSpecs,ht=d.flexibleCompare,wt=d.intersectRects,l=d.CoordCache,ut=d.getContentRect,at=d.getOuterRect,ct=function(t){return t.find("> td").filter(function(t,e){return e.rowSpan<=1})},c=function(e){function r(){r.__super__.constructor.apply(this,arguments),this.requestMovingEnd=ot(this.reportMovingEnd,500)}var o,i;return kt(r,e),r.mixin(a),r.mixin(v),r.prototype.canvas=null,r.prototype.isScrolling=!1,r.prototype.isTouching=!1,r.prototype.isMoving=!1,r.prototype.isTouchScrollEnabled=!0,r.prototype.preventTouchScrollHandler=null,r.prototype.render=function(){return r.__super__.render.apply(this,arguments),this.canvas&&(this.canvas.render(),this.canvas.el.appendTo(this.scrollEl)),this.bindHandlers()},r.prototype.destroy=function(){return r.__super__.destroy.apply(this,arguments),this.unbindHandlers()},r.prototype.disableTouchScroll=function(){return this.isTouchScrollEnabled=!1,this.bindPreventTouchScroll()},r.prototype.enableTouchScroll=function(){return this.isTouchScrollEnabled=!0,this.isTouching?void 0:this.unbindPreventTouchScroll()},r.prototype.bindPreventTouchScroll=function(){return this.preventTouchScrollHandler?void 0:this.scrollEl.on("touchmove",this.preventTouchScrollHandler=d.preventDefault)},r.prototype.unbindPreventTouchScroll=function(){return this.preventTouchScrollHandler?(this.scrollEl.off("touchmove",this.preventTouchScrollHandler),this.preventTouchScrollHandler=null):void 0},r.prototype.bindHandlers=function(){return this.listenTo(this.scrollEl,{scroll:this.reportScroll,touchstart:this.reportTouchStart,touchend:this.reportTouchEnd})},r.prototype.unbindHandlers=function(){return this.stopListeningTo(this.scrollEl)},r.prototype.reportScroll=function(){return this.isScrolling||this.reportScrollStart(),this.trigger("scroll"),this.isMoving=!0,this.requestMovingEnd()},r.prototype.reportScrollStart=function(){return this.isScrolling?void 0:(this.isScrolling=!0,this.trigger("scrollStart",this.isTouching))},r.prototype.requestMovingEnd=null,r.prototype.reportMovingEnd=function(){return this.isMoving=!1,this.isTouching?void 0:this.reportScrollEnd()},r.prototype.reportScrollEnd=function(){return this.isScrolling?(this.trigger("scrollEnd"),this.isScrolling=!1):void 0},r.prototype.reportTouchStart=function(){return this.isTouching=!0},r.prototype.reportTouchEnd=function(){return this.isTouching&&(this.isTouching=!1,this.isTouchScrollEnabled&&this.unbindPreventTouchScroll(),!this.isMoving)?this.reportScrollEnd():void 0},r.prototype.getScrollLeft=function(){var t,e,r;if(t=this.scrollEl.css("direction"),e=this.scrollEl[0],r=e.scrollLeft,"rtl"===t)switch(i){case"positive":r=r+e.clientWidth-e.scrollWidth;break;case"reverse":r=-r}return r},r.prototype.setScrollLeft=function(t){var e,r;if(e=this.scrollEl.css("direction"),r=this.scrollEl[0],"rtl"===e)switch(i){case"positive":t=t-r.clientWidth+r.scrollWidth;break;case"reverse":t=-t}return r.scrollLeft=t},r.prototype.getScrollFromLeft=function(){var t,e,r;if(t=this.scrollEl.css("direction"),e=this.scrollEl[0],r=e.scrollLeft,"rtl"===t)switch(i){case"negative":r=r-e.clientWidth+e.scrollWidth;break;case"reverse":r=-r-e.clientWidth+e.scrollWidth}return r},r.prototype.getNativeScrollLeft=function(){return this.scrollEl[0].scrollLeft},r.prototype.setNativeScrollLeft=function(t){return this.scrollEl[0].scrollLeft=t},i=null,o=function(){var e,r,o;return e=t('<div style=" position: absolute top: -1000px; width: 1px; height: 1px; overflow: scroll; direction: rtl; font-size: 14px; ">A</div>').appendTo("body"),r=e[0],o=r.scrollLeft>0?"positive":(r.scrollLeft=1,e.scrollLeft>0?"reverse":"negative"),e.remove(),o},t(function(){return i=o()}),r}(d.Scroller),s=function(e){function r(){r.__super__.constructor.apply(this,arguments),"clipped-scroll"===this.overflowX&&(this.overflowX="scroll",this.isHScrollbarsClipped=!0),"clipped-scroll"===this.overflowY&&(this.overflowY="scroll",this.isVScrollbarsClipped=!0)}return kt(r,e),r.prototype.isHScrollbarsClipped=!1,r.prototype.isVScrollbarsClipped=!1,r.prototype.renderEl=function(){var e;return e=r.__super__.renderEl.apply(this,arguments),t('<div class="fc-scroller-clip" />').append(e)},r.prototype.updateSize=function(){var t,e,r;return e=this.scrollEl,r=ft(e),t={marginLeft:0,marginRight:0,marginTop:0,marginBottom:0},this.isHScrollbarsClipped&&(t.marginTop=-r.top,t.marginBottom=-r.bottom),this.isVScrollbarsClipped&&(t.marginLeft=-r.left,t.marginRight=-r.right),e.css(t),e.toggleClass("fc-no-scrollbars",(this.isHScrollbarsClipped||"hidden"===this.overflowX)&&(this.isVScrollbarsClipped||"hidden"===this.overflowY)&&!(r.top||r.bottom||r.left||r.right))},r.prototype.getScrollbarWidths=function(){var t;return t=ft(this.scrollEl),this.isHScrollbarsClipped&&(t.top=0,t.bottom=0),this.isVScrollbarsClipped&&(t.left=0,t.right=0),t},r}(c),O=function(){function e(){this.gutters={}}return e.prototype.el=null,e.prototype.contentEl=null,e.prototype.bgEl=null,e.prototype.gutters=null,e.prototype.width=null,e.prototype.minWidth=null,e.prototype.render=function(){return this.el=t('<div class="fc-scroller-canvas"> <div class="fc-content"></div> <div class="fc-bg"></div> </div>'),this.contentEl=this.el.find(".fc-content"),this.bgEl=this.el.find(".fc-bg")},e.prototype.setGutters=function(e){return e?t.extend(this.gutters,e):this.gutters={},this.updateSize()},e.prototype.setWidth=function(t){return this.width=t,this.updateSize()},e.prototype.setMinWidth=function(t){return this.minWidth=t,this.updateSize()},e.prototype.clearWidth=function(){return this.width=null,this.minWidth=null,this.updateSize()},e.prototype.updateSize=function(){var t;return t=this.gutters,this.el.toggleClass("fc-gutter-left",Boolean(t.left)).toggleClass("fc-gutter-right",Boolean(t.right)).toggleClass("fc-gutter-top",Boolean(t.top)).toggleClass("fc-gutter-bottom",Boolean(t.bottom)).css({paddingLeft:t.left||"",paddingRight:t.right||"",paddingTop:t.top||"",paddingBottom:t.bottom||"",width:null!=this.width?this.width+(t.left||0)+(t.right||0):"",minWidth:null!=this.minWidth?this.minWidth+(t.left||0)+(t.right||0):""}),this.bgEl.css({left:t.left||"",right:t.right||"",top:t.top||"",bottom:t.bottom||""})},e}(),A=function(){function t(t,e){var r,o,i,n;for(this.axis=t,this.scrollers=e,i=this.scrollers,r=0,o=i.length;o>r;r++)n=i[r],this.initScroller(n)}return t.prototype.axis=null,t.prototype.scrollers=null,t.prototype.masterScroller=null,t.prototype.initScroller=function(t){return t.scrollEl.on("wheel mousewheel DomMouseScroll MozMousePixelScroll",function(e){return function(){e.assignMasterScroller(t)}}(this)),t.on("scrollStart",function(e){return function(){return e.masterScroller?void 0:e.assignMasterScroller(t)}}(this)).on("scroll",function(e){return function(){var r,o,i,n,s;if(t===e.masterScroller){for(n=e.scrollers,s=[],r=0,o=n.length;o>r;r++)if(i=n[r],i!==t)switch(e.axis){case"horizontal":s.push(i.setNativeScrollLeft(t.getNativeScrollLeft()));break;case"vertical":s.push(i.setScrollTop(t.getScrollTop()));break;default:s.push(void 0)}else s.push(void 0);return s}}}(this)).on("scrollEnd",function(e){return function(){return t===e.masterScroller?e.unassignMasterScroller():void 0}}(this))},t.prototype.assignMasterScroller=function(t){var e,r,o,i;for(this.unassignMasterScroller(),this.masterScroller=t,i=this.scrollers,e=0,r=i.length;r>e;e++)o=i[e],o!==t&&o.disableTouchScroll()},t.prototype.unassignMasterScroller=function(){var t,e,r,o;if(this.masterScroller){for(o=this.scrollers,t=0,e=o.length;e>t;t++)r=o[t],r.enableTouchScroll();this.masterScroller=null}},t.prototype.update=function(){var t,e,r,o,i,n,s,l,h,u,a,c,p;for(t=function(){var t,e,r,o;for(r=this.scrollers,o=[],t=0,e=r.length;e>t;t++)c=r[t],o.push(c.getScrollbarWidths());return o}.call(this),l=h=u=s=0,r=0,i=t.length;i>r;r++)p=t[r],l=Math.max(l,p.left),h=Math.max(h,p.right),u=Math.max(u,p.top),s=Math.max(s,p.bottom);for(a=this.scrollers,e=o=0,n=a.length;n>o;e=++o)c=a[e],p=t[e],c.canvas.setGutters("horizontal"===this.axis?{left:l-p.left,right:h-p.right}:{top:u-p.top,bottom:s-p.bottom})},t}(),V=function(){function e(t,e){this.isTouch=e,this.scroller=t,this.sprites=[],this.isTouch&&(this.isForcedRelative=!0),t.on(this.isTouch?"scrollEnd":"scroll",function(t){return function(){return t.handleScroll()}}(this))}return e.prototype.scroller=null,e.prototype.scrollbarWidths=null,e.prototype.sprites=null,e.prototype.viewportRect=null,e.prototype.contentOffset=null,e.prototype.isHFollowing=!0,e.prototype.isVFollowing=!1,e.prototype.containOnNaturalLeft=!1,e.prototype.containOnNaturalRight=!1,e.prototype.minTravel=0,e.prototype.isTouch=!1,e.prototype.isForcedRelative=!1,e.prototype.setSprites=function(e){var r,o,i;if(this.clearSprites(),e instanceof t)return this.sprites=function(){var r,o,n;for(n=[],r=0,o=e.length;o>r;r++)i=e[r],n.push(new P(t(i),this));return n}.call(this);for(r=0,o=e.length;o>r;r++)i=e[r],i.follower=this;return this.sprites=e},e.prototype.clearSprites=function(){var t,e,r,o;for(r=this.sprites,t=0,e=r.length;e>t;t++)o=r[t],o.clear();return this.sprites=[]},e.prototype.handleScroll=function(){return this.updateViewport(),this.updatePositions()},e.prototype.cacheDimensions=function(){var t,e,r,o;for(this.updateViewport(),this.scrollbarWidths=this.scroller.getScrollbarWidths(),this.contentOffset=this.scroller.canvas.el.offset(),r=this.sprites,t=0,e=r.length;e>t;t++)o=r[t],o.cacheDimensions()},e.prototype.updateViewport=function(){var t,e,r;return e=this.scroller,t=e.getScrollFromLeft(),r=e.getScrollTop(),this.viewportRect={left:t,right:t+e.getClientWidth(),top:r,bottom:r+e.getClientHeight()}},e.prototype.forceRelative=function(){var t,e,r,o,i;if(!this.isForcedRelative){for(this.isForcedRelative=!0,r=this.sprites,o=[],t=0,e=r.length;e>t;t++)i=r[t],i.doAbsolute?o.push(i.assignPosition()):o.push(void 0);return o}},e.prototype.clearForce=function(){var t,e,r,o,i;if(this.isForcedRelative&&!this.isTouch){for(this.isForcedRelative=!1,r=this.sprites,o=[],t=0,e=r.length;e>t;t++)i=r[t],o.push(i.assignPosition());return o}},e.prototype.update=function(){return this.cacheDimensions(),this.updatePositions()},e.prototype.updatePositions=function(){var t,e,r,o;for(r=this.sprites,t=0,e=r.length;e>t;t++)o=r[t],o.updatePosition()},e.prototype.getContentRect=function(t){return ut(t,this.contentOffset)},e.prototype.getBoundingRect=function(t){return at(t,this.contentOffset)},e}(),P=function(){function t(t,e){this.el=t,this.follower=null!=e?e:null,this.isBlock="block"===this.el.css("display"),this.el.css("position","relative")}return t.prototype.follower=null,t.prototype.el=null,t.prototype.absoluteEl=null,t.prototype.naturalRect=null,t.prototype.parentRect=null,t.prototype.containerRect=null,t.prototype.isEnabled=!0,t.prototype.isHFollowing=!1,t.prototype.isVFollowing=!1,t.prototype.doAbsolute=!1,t.prototype.isAbsolute=!1,t.prototype.isCentered=!1,t.prototype.rect=null,t.prototype.isBlock=!1,t.prototype.naturalWidth=null,t.prototype.disable=function(){return this.isEnabled?(this.isEnabled=!1,this.resetPosition(),this.unabsolutize()):void 0},t.prototype.enable=function(){return this.isEnabled?void 0:(this.isEnabled=!0,this.assignPosition())},t.prototype.clear=function(){return this.disable(),this.follower=null,this.absoluteEl=null},t.prototype.cacheDimensions=function(){var t,e,r,o,i,n,s,l;return o=!1,i=!1,r=!1,this.naturalWidth=this.el.width(),this.resetPosition(),e=this.follower,s=this.naturalRect=e.getBoundingRect(this.el),l=this.el.parent(),this.parentRect=e.getBoundingRect(l),t=this.containerRect=bt(e.getContentRect(l),s),n=e.minTravel,e.containOnNaturalLeft&&(t.left=s.left),e.containOnNaturalRight&&(t.right=s.right),e.isHFollowing&&dt(t)-dt(s)>=n&&(r="center"===this.el.css("text-align"),o=!0),e.isVFollowing&&pt(t)-pt(s)>=n&&(i=!0),this.isHFollowing=o,this.isVFollowing=i,this.isCentered=r},t.prototype.updatePosition=function(){return this.computePosition(),this.assignPosition()},t.prototype.resetPosition=function(){return this.el.css({top:"",left:""})},t.prototype.computePosition=function(){var t,e,r,o,i,n,s,l;return s=this.follower.viewportRect,r=this.parentRect,t=this.containerRect,l=wt(s,r),o=null,e=!1,l&&(o=et(this.naturalRect),n=wt(o,r),(this.isCentered&&!Mt(s,r)||n&&!Mt(s,n))&&(e=!0,this.isHFollowing&&(this.isCentered?(i=dt(o),o.left=(l.left+l.right)/2-i/2,o.right=o.left+i):gt(o,s)||(e=!1),gt(o,t)&&(e=!1)),this.isVFollowing&&(zt(o,s)||(e=!1),zt(o,t)&&(e=!1)),Mt(s,o)||(e=!1))),this.rect=o,this.doAbsolute=e},t.prototype.assignPosition=function(){var t,e;return this.isEnabled?this.rect?this.doAbsolute&&!this.follower.isForcedRelative?(this.absolutize(),this.absoluteEl.css({top:this.rect.top-this.follower.viewportRect.top+this.follower.scrollbarWidths.top,left:this.rect.left-this.follower.viewportRect.left+this.follower.scrollbarWidths.left,width:this.isBlock?this.naturalWidth:""})):(e=this.rect.top-this.naturalRect.top,t=this.rect.left-this.naturalRect.left,this.unabsolutize(),this.el.toggleClass("fc-following",Boolean(e||t)).css({top:e,left:t})):this.unabsolutize():void 0},t.prototype.absolutize=function(){return this.isAbsolute?void 0:(this.absoluteEl||(this.absoluteEl=this.buildAbsoluteEl()),this.absoluteEl.appendTo(this.follower.scroller.el),this.el.css("visibility","hidden"),this.isAbsolute=!0)},t.prototype.unabsolutize=function(){return this.isAbsolute?(this.absoluteEl.detach(),this.el.css("visibility",""),this.isAbsolute=!1):void 0},t.prototype.buildAbsoluteEl=function(){return this.el.clone().addClass("fc-following").css({position:"absolute","z-index":1e3,"font-weight":this.el.css("font-weight"),"font-size":this.el.css("font-size"),"font-family":this.el.css("font-family"),color:this.el.css("color"),"padding-top":this.el.css("padding-top"),"padding-bottom":this.el.css("padding-bottom"),"padding-left":this.el.css("padding-left"),"padding-right":this.el.css("padding-right"),"pointer-events":"none"})},t}(),et=function(t){return{left:t.left,right:t.right,top:t.top,bottom:t.bottom}},dt=function(t){return t.right-t.left},pt=function(t){return t.bottom-t.top},Mt=function(t,e){return Wt(t,e)&&Lt(t,e)},Wt=function(t,e){return e.left>=t.left&&e.right<=t.right},Lt=function(t,e){return e.top>=t.top&&e.bottom<=t.bottom},gt=function(t,e){return t.left<e.left?(t.right=e.left+dt(t),t.left=e.left,!0):t.right>e.right&&(t.left=e.right-dt(t),t.right=e.right,!0)},zt=function(t,e){return t.top<e.top?(t.bottom=e.top+pt(t),t.top=e.top,!0):t.bottom>e.bottom&&(t.top=e.bottom-pt(t),t.bottom=e.bottom,!0)},bt=function(t,e){return{left:Math.min(t.left,e.left),right:Math.max(t.right,e.right),top:Math.min(t.top,e.top),bottom:Math.max(t.bottom,e.bottom)}},i=function(e){function r(){return r.__super__.constructor.apply(this,arguments)}return kt(r,e),r.prototype.resourceManager=null,r.prototype.initialize=function(){return this.resourceManager=new D(this)},r.prototype.instantiateView=function(t){var e,r;return e=this.getViewSpec(t),r=e.class,this.options.resources&&e.options.resources!==!1&&(e.queryResourceClass?r=e.queryResourceClass(e)||r:e.resourceClass&&(r=e.resourceClass)),new r(this,t,e.options,e.duration)},r.prototype.getResources=function(){return Array.prototype.slice.call(this.resourceManager.topLevelResources)},r.prototype.addResource=function(t,e){var r;null==e&&(e=!1),r=this.resourceManager.addResource(t),e&&this.view.scrollToResource&&r.done(function(t){return function(e){return t.view.scrollToResource(e)}}(this))},r.prototype.removeResource=function(t){return this.resourceManager.removeResource(t)},r.prototype.refetchResources=function(){this.resourceManager.fetchResources()},r.prototype.rerenderResources=function(){this.resourceManager.resetResources()},r.prototype.getPeerEvents=function(t,e){var o,i,n,s,l,h,u,a,c,p,d,f,g,y;for(f=r.__super__.getPeerEvents.apply(this,arguments),p=t.resourceId?[t.resourceId]:e?this.getEventResourceIds(e):[],o=[],n=0,h=f.length;h>n;n++){if(d=f[n],i=!1,y=this.getEventResourceIds(d),y.length&&p.length){for(s=0,u=y.length;u>s;s++)for(g=y[s],l=0,a=p.length;a>l;l++)if(c=p[l],c===g){i=!0;break}}else i=!0;i&&o.push(d)}return o},r.prototype.buildSelectSpan=function(t,e,o){var i;return i=r.__super__.buildSelectSpan.apply(this,arguments),o&&(i.resourceId=o),i},r.prototype.getResourceById=function(t){return this.resourceManager.getResourceById(t)},r.prototype.normalizeEvent=function(t){return r.__super__.normalizeEvent.apply(this,arguments),null==t.resourceId&&(t.resourceId=null),null!=t.resourceIds?t.resourceIds:t.resourceIds=null},r.prototype.getEventResourceId=function(t){return this.getEventResourceIds(t)[0]},r.prototype.getEventResourceIds=function(t){var e,r,o,i,n,s,l,h;if(h=String(null!=(n=null!=(s=t[this.getEventResourceField()])?s:t.resourceId)?n:""))return[h];if(t.resourceIds){for(i=[],l=t.resourceIds,e=0,r=l.length;r>e;e++)h=l[e],o=String(null!=h?h:""),o&&i.push(o);return i}return[]},r.prototype.setEventResourceId=function(t,e){return t[this.getEventResourceField()]=String(null!=e?e:"")},r.prototype.getEventResourceField=function(){return this.options.eventResourceField||"resourceId"},r.prototype.getResourceEvents=function(e){var r;return r="object"==typeof e?e:this.getResourceById(e),r?this.clientEvents(function(e){return function(o){return-1!==t.inArray(r.id,e.getEventResourceIds(o))}}(this)):[]},r.prototype.getEventResource=function(t){return this.getEventResources(t)[0]},r.prototype.getEventResources=function(t){var e,r,o,i,n,s,l;if(e="object"==typeof t?t:this.clientEvents(t)[0],l=[],e)for(i=this.getEventResourceIds(e),r=0,o=i.length;o>r;r++)s=i[r],n=this.getResourceById(s),n&&l.push(n);return l},r}(o),o.prototype=i.prototype,Tt=X.prototype.displayView,_t=X.prototype.renderSkeleton,It=X.prototype.unrenderSkeleton,Et=X.prototype.displayEvents,X.prototype.isResourcesBound=!1,X.prototype.settingResources=null,X.prototype.displayView=function(){return Tt.apply(this,arguments),xt(this.calendar.options.schedulerLicenseKey,this.el),this.bindResources(),this.whenResources()},X.prototype.unrenderSkeleton=function(){
|
|
return It.apply(this,arguments),this.unbindResources(!0)},X.prototype.displayEvents=function(t){return this.whenResources(function(e){return function(){return Et.call(e,t)}}(this))},X.prototype.bindResources=function(){var e;return this.isResourcesBound?void 0:(this.isResourcesBound=!0,this.settingResources=t.Deferred(),e=function(t){return function(e){return t.setResources(e),t.settingResources.resolve()}}(this),this.listenTo(this.calendar.resourceManager,{set:e,unset:this.unsetResources,reset:this.resetResources,add:this.addResource,remove:this.removeResource}),this.calendar.resourceManager.hasFetched()?e(this.calendar.resourceManager.topLevelResources):this.calendar.resourceManager.getResources())},X.prototype.unbindResources=function(t){return this.isResourcesBound?(this.stopListeningTo(this.calendar.resourceManager),"resolved"===this.settingResources.state()&&this.unsetResources(t),this.settingResources=null,this.isResourcesBound=!1):void 0},X.prototype.whenResources=function(e){return"resolved"===this.settingResources.state()?t.when(e?e():void 0):e?this.settingResources.then(e):this.settingResources.promise()},X.prototype.setResources=function(t){},X.prototype.unsetResources=function(){},X.prototype.resetResources=function(t){return this.calendar.rerenderEvents()},X.prototype.addResource=function(t){return this.resetResources(this.calendar.resourceManager.topLevelResources)},X.prototype.removeResource=function(t){return this.resetResources(this.calendar.resourceManager.topLevelResources)},Ht=f.prototype.getSegClasses,f.prototype.getSegClasses=function(t){var e,r,o,i,n;for(e=Ht.apply(this,arguments),i=this.getSegResources(t),r=0,o=i.length;o>r;r++)n=i[r],e=e.concat(n.eventClassName||[]);return e},f.prototype.getSegSkinCss=function(t){var e,r,o,i,n,s,l,h,u,a;return a=this.view,e=t.event,h=e.source||{},r=e.color,u=h.color,s=a.opt("eventColor"),l=this.getSegResources(t),o=function(){var t,e,r,o;for(o=null,e=0,r=l.length;r>e;e++)for(t=l[e];t&&!o;)o=t.eventBackgroundColor||t.eventColor,t=t._parent;return o},i=function(){var t,e,r,o;for(o=null,e=0,r=l.length;r>e;e++)for(t=l[e];t&&!o;)o=t.eventBorderColor||t.eventColor,t=t._parent;return o},n=function(){var t,e,r,o;for(o=null,e=0,r=l.length;r>e;e++)for(t=l[e];t&&!o;)o=t.eventTextColor,t=t._parent;return o},{"background-color":e.backgroundColor||r||o()||h.backgroundColor||u||a.opt("eventBackgroundColor")||s,"border-color":e.borderColor||r||i()||h.borderColor||u||a.opt("eventBorderColor")||s,color:e.textColor||n()||h.textColor||a.opt("eventTextColor")}},f.prototype.getSegResources=function(t){return t.resource?[t.resource]:this.view.calendar.getEventResources(t.event)},D=function(e){function r(t){this.calendar=t,this.initializeCache()}return kt(r,e),r.mixin(a),r.resourceGuid=1,r.ajaxDefaults={dataType:"json",cache:!1},r.prototype.calendar=null,r.prototype.topLevelResources=null,r.prototype.resourcesById=null,r.prototype.fetching=null,r.prototype.hasFetched=function(){return this.fetching&&"resolved"===this.fetching.state()},r.prototype.getResources=function(){var e;return this.fetching?t.Deferred().resolve(this.topLevelResources).promise():(e=t.Deferred(),this.fetchResources().done(function(t){return e.resolve(t)}).fail(function(){return e.resolve([])}),e)},r.prototype.fetchResources=function(){var e;return e=this.fetching,t.when(e).then(function(t){return function(){return t.fetching=t.fetchResourceInputs().then(function(r){return t.setResources(r,Boolean(e)),t.topLevelResources})}}(this))},r.prototype.fetchResourceInputs=function(){var e,o,i;switch(e=t.Deferred(),i=this.calendar.options.resources,"string"===t.type(i)&&(i={url:i}),t.type(i)){case"function":i(function(t){return function(t){return e.resolve(t)}}(this));break;case"object":o=t.ajax(t.extend({},r.ajaxDefaults,i));break;case"array":e.resolve(i);break;default:e.resolve([])}return o||(o=e.promise()),"pending"===!o.state()&&(this.calendar.pushLoading(),o.always(function(){return this.calendar.popLoading()})),o},r.prototype.resetResources=function(){return this.getResources().then(function(t){return function(){return t.trigger("reset",t.topLevelResources)}}(this))},r.prototype.getResourceById=function(t){return this.resourcesById[t]},r.prototype.initializeCache=function(){return this.topLevelResources=[],this.resourcesById={}},r.prototype.setResources=function(t,e){var r,o,i,n,s,l;for(this.initializeCache(),s=function(){var e,r,o;for(o=[],e=0,r=t.length;r>e;e++)n=t[e],o.push(this.buildResource(n));return o}.call(this),l=function(){var t,e,r;for(r=[],t=0,e=s.length;e>t;t++)i=s[t],this.addResourceToIndex(i)&&r.push(i);return r}.call(this),r=0,o=l.length;o>r;r++)i=l[r],this.addResourceToTree(i);return e?this.trigger("reset",this.topLevelResources):this.trigger("set",this.topLevelResources),this.calendar.trigger("resourcesSet",null,this.topLevelResources)},r.prototype.addResource=function(e){return t.when(this.fetching).then(function(t){return function(){var r;return r=t.buildResource(e),!!t.addResourceToIndex(r)&&(t.addResourceToTree(r),t.trigger("add",r),r)}}(this))},r.prototype.addResourceToIndex=function(t){var e,r,o,i;if(this.resourcesById[t.id])return!1;for(this.resourcesById[t.id]=t,i=t.children,r=0,o=i.length;o>r;r++)e=i[r],this.addResourceToIndex(e);return!0},r.prototype.addResourceToTree=function(t){var e,r,o,i;if(!t.parent){if(r=String(null!=(o=t.parentId)?o:"")){if(e=this.resourcesById[r],!e)return!1;t.parent=e,i=e.children}else i=this.topLevelResources;i.push(t)}return!0},r.prototype.removeResource=function(e){var r;return r="object"==typeof e?e.id:e,t.when(this.fetching).then(function(t){return function(){var e;return e=t.removeResourceFromIndex(r),e&&(t.removeResourceFromTree(e),t.trigger("remove",e)),e}}(this))},r.prototype.removeResourceFromIndex=function(t){var e,r,o,i,n;if(n=this.resourcesById[t]){for(delete this.resourcesById[t],i=n.children,r=0,o=i.length;o>r;r++)e=i[r],this.removeResourceFromIndex(e.id);return n}return!1},r.prototype.removeResourceFromTree=function(t,e){var r,o,i,n;for(null==e&&(e=this.topLevelResources),r=o=0,i=e.length;i>o;r=++o){if(n=e[r],n===t)return t.parent=null,e.splice(r,1),!0;if(this.removeResourceFromTree(t,n.children))return!0}return!1},r.prototype.buildResource=function(e){var o,i,n,s,l;return l=t.extend({},e),l.id=String(null!=(s=e.id)?s:"_fc"+r.resourceGuid++),n=e.eventClassName,l.eventClassName=function(){switch(t.type(n)){case"string":return n.split(/\s+/);case"array":return n;default:return[]}}(),l.children=function(){var t,r,n,s,h;for(s=null!=(n=e.children)?n:[],h=[],t=0,r=s.length;r>t;t++)i=s[t],o=this.buildResource(i),o.parent=l,h.push(o);return h}.call(this),l},r}(n),L={resourceTextFunc:null,unsetResources:function(){return this.clearEvents()},resetResources:function(t){var e;return e=this.queryScroll(),this.unsetResources(),this.setResources(t),this.setScroll(e),this.calendar.rerenderEvents()},getResourceText:function(t){return this.getResourceTextFunc()(t)},getResourceTextFunc:function(){var t;return this.resourceTextFunc?this.resourceTextFunc:(t=this.opt("resourceText"),"function"!=typeof t&&(t=function(t){return t.title||t.id}),this.resourceTextFunc=t)},triggerDayClick:function(t,e,r){var o;return o=this.calendar.resourceManager,this.trigger("dayClick",e,this.calendar.applyTimezone(t.start),r,this,o.getResourceById(t.resourceId))},triggerSelect:function(t,e){var r;return r=this.calendar.resourceManager,this.trigger("select",null,this.calendar.applyTimezone(t.start),this.calendar.applyTimezone(t.end),e,this,r.getResourceById(t.resourceId))},triggerExternalDrop:function(t,e,r,o,i){return this.trigger("drop",r[0],e.start,o,i,e.resourceId),t?this.trigger("eventReceive",null,t):void 0},reportEventDrop:function(){var t,e,r,o;return e=arguments[0],t=arguments[1],r=3<=arguments.length?Pt.call(arguments,2):[],t=this.normalizeDropLocation(t),t.resourceId&&e.resourceIds&&(t.resourceIds=null),(o=X.prototype.reportEventDrop).call.apply(o,[this,e,t].concat(Pt.call(r)))},reportExternalDrop:function(){var t,e,r,o;return e=arguments[0],t=arguments[1],r=3<=arguments.length?Pt.call(arguments,2):[],t=this.normalizeDropLocation(t),(o=X.prototype.reportExternalDrop).call.apply(o,[this,e,t].concat(Pt.call(r)))},normalizeDropLocation:function(e){var r;return r=t.extend({},e),delete r.resourceId,this.calendar.setEventResourceId(r,e.resourceId),r}},I={allowCrossResource:!0,eventRangeToSpans:function(e,r){var o,i,n,s,l;if(s=this.view.calendar.getEventResourceIds(r),s.length){for(l=[],o=0,i=s.length;i>o;o++)n=s[o],l.push(t.extend({},e,{resourceId:n}));return l}return d.isBgEvent(r)?f.prototype.eventRangeToSpans.apply(this,arguments):[]},fabricateHelperEvent:function(t,e){var r;return r=f.prototype.fabricateHelperEvent.apply(this,arguments),this.view.calendar.setEventResourceId(r,t.resourceId),r},computeEventDrop:function(t,e,r){var o,i;return o=!0,o||t.resourceId===e.resourceId?(i=f.prototype.computeEventDrop.apply(this,arguments),i&&(i.resourceId=e.resourceId),i):null},computeExternalDrop:function(t,e){var r;return r=f.prototype.computeExternalDrop.apply(this,arguments),r&&(r.resourceId=t.resourceId),r},computeEventResize:function(t,e,r,o){var i;if(this.allowCrossResource||e.resourceId===r.resourceId)return i=f.prototype.computeEventResize.apply(this,arguments),i&&(i.resourceId=e.resourceId),i},computeSelectionSpan:function(t,e){var r;if(this.allowCrossResource||t.resourceId===e.resourceId)return r=f.prototype.computeSelectionSpan.apply(this,arguments),r&&(r.resourceId=t.resourceId),r}},_={flattenedResources:null,resourceCnt:0,datesAboveResources:!1,allowCrossResource:!1,setResources:function(t){return this.flattenedResources=this.flattenResources(t),this.resourceCnt=this.flattenedResources.length,this.updateDayTableCols()},unsetResources:function(){return this.flattenedResources=null,this.resourceCnt=0,this.updateDayTableCols()},flattenResources:function(t){var e,r,o,i;return r=this.view.opt("resourceOrder"),r?(e=Dt(r),i=function(t,r){return Q(t,r,e)}):i=null,o=[],this.accumulateResources(t,i,o),o},accumulateResources:function(t,e,r){var o,i,n,s,l;for(e?(l=t.slice(0),l.sort(e)):l=t,s=[],o=0,i=l.length;i>o;o++)n=l[o],r.push(n),s.push(this.accumulateResources(n.children,e,r));return s},updateDayTableCols:function(){return this.datesAboveResources=this.view.opt("groupByDateAndResource"),d.DayTableMixin.updateDayTableCols.call(this)},computeColCnt:function(){return(this.resourceCnt||1)*this.daysPerRow},getColDayIndex:function(t){return this.isRTL&&(t=this.colCnt-1-t),this.datesAboveResources?Math.floor(t/(this.resourceCnt||1)):t%this.daysPerRow},getColResource:function(t){return this.flattenedResources[this.getColResourceIndex(t)]},getColResourceIndex:function(t){return this.isRTL&&(t=this.colCnt-1-t),this.datesAboveResources?t%(this.resourceCnt||1):Math.floor(t/this.daysPerRow)},indicesToCol:function(t,e){var r;return r=this.datesAboveResources?e*(this.resourceCnt||1)+t:t*this.daysPerRow+e,this.isRTL&&(r=this.colCnt-1-r),r},renderHeadTrHtml:function(){return this.resourceCnt?this.daysPerRow>1?this.datesAboveResources?this.renderHeadDateAndResourceHtml():this.renderHeadResourceAndDateHtml():this.renderHeadResourceHtml():d.DayTableMixin.renderHeadTrHtml.call(this)},renderHeadResourceHtml:function(){var t,e,r,o,i;for(i=[],r=this.flattenedResources,t=0,e=r.length;e>t;t++)o=r[t],i.push(this.renderHeadResourceCellHtml(o));return this.wrapTr(i,"renderHeadIntroHtml")},renderHeadResourceAndDateHtml:function(){var t,e,r,o,i,n,s,l,h,u;for(u=[],e=[],s=this.flattenedResources,o=0,n=s.length;n>o;o++)for(h=s[o],u.push(this.renderHeadResourceCellHtml(h,null,this.daysPerRow)),r=i=0,l=this.daysPerRow;l>i;r=i+=1)t=this.dayDates[r].clone(),e.push(this.renderHeadResourceDateCellHtml(t,h));return this.wrapTr(u,"renderHeadIntroHtml")+this.wrapTr(e,"renderHeadIntroHtml")},renderHeadDateAndResourceHtml:function(){var t,e,r,o,i,n,s,l,h,u;for(e=[],u=[],r=o=0,s=this.daysPerRow;s>o;r=o+=1)for(t=this.dayDates[r].clone(),e.push(this.renderHeadDateCellHtml(t,this.resourceCnt)),l=this.flattenedResources,i=0,n=l.length;n>i;i++)h=l[i],u.push(this.renderHeadResourceCellHtml(h,t));return this.wrapTr(e,"renderHeadIntroHtml")+this.wrapTr(u,"renderHeadIntroHtml")},renderHeadResourceCellHtml:function(t,e,r){return'<th class="fc-resource-cell" data-resource-id="'+t.id+'"'+(e?' data-date="'+e.format("YYYY-MM-DD")+'"':"")+(r>1?' colspan="'+r+'"':"")+">"+yt(this.view.getResourceText(t))+"</th>"},renderHeadResourceDateCellHtml:function(t,e,r){return this.renderHeadDateCellHtml(t,r,'data-resource-id="'+e.id+'"')},processHeadResourceEls:function(e){return e.find(".fc-resource-cell").each(function(e){return function(r,o){var i;return i=e.datesAboveResources?e.getColResource(r):e.flattenedResources[e.isRTL?e.flattenedResources.length-1-r:r],e.view.trigger("resourceRender",i,i,t(o),t())}}(this))},renderBgCellsHtml:function(t){var e,r,o,i,n,s;if(this.resourceCnt){for(o=[],e=i=0,n=this.colCnt;n>i;e=i+=1)r=this.getCellDate(t,e),s=this.getColResource(e),o.push(this.renderResourceBgCellHtml(r,s));return o.join("")}return d.DayTableMixin.renderBgCellsHtml.call(this,t)},renderResourceBgCellHtml:function(t,e){return this.renderBgCellHtml(t,'data-resource-id="'+e.id+'"')},wrapTr:function(t,e){return this.isRTL?(t.reverse(),"<tr>"+t.join("")+this[e]()+"</tr>"):"<tr>"+this[e]()+t.join("")+"</tr>"}},H=function(e){function r(){return r.__super__.constructor.apply(this,arguments)}return kt(r,e),r.mixin(I),r.mixin(_),r.prototype.getHitSpan=function(t){var e;return e=r.__super__.getHitSpan.apply(this,arguments),this.resourceCnt&&(e.resourceId=this.getColResource(t.col).id),e},r.prototype.spanToSegs=function(e){var r,o,i,n,s,l,h,u,a,c,p,d,f;if(a=this.resourceCnt,o=this.datesAboveResources?this.sliceRangeByDay(e):this.sliceRangeByRow(e),a){for(d=[],n=0,h=o.length;h>n;n++)for(f=o[n],c=s=0,u=a;u>s;c=s+=1)p=this.flattenedResources[c],e.resourceId&&e.resourceId!==p.id||(r=t.extend({},f),r.resource=p,this.isRTL?(r.leftCol=this.indicesToCol(c,f.lastRowDayIndex),r.rightCol=this.indicesToCol(c,f.firstRowDayIndex)):(r.leftCol=this.indicesToCol(c,f.firstRowDayIndex),r.rightCol=this.indicesToCol(c,f.lastRowDayIndex)),d.push(r));return d}for(i=0,l=o.length;l>i;i++)f=o[i],this.isRTL?(f.leftCol=f.lastRowDayIndex,f.rightCol=f.firstRowDayIndex):(f.leftCol=f.firstRowDayIndex,f.rightCol=f.lastRowDayIndex);return o},r}(d.DayGrid),G=function(e){function r(){return r.__super__.constructor.apply(this,arguments)}return kt(r,e),r.mixin(I),r.mixin(_),r.prototype.getHitSpan=function(t){var e;return e=r.__super__.getHitSpan.apply(this,arguments),this.resourceCnt&&(e.resourceId=this.getColResource(t.col).id),e},r.prototype.spanToSegs=function(e){var r,o,i,n,s,l,h,u,a,c,p,d,f;if(a=this.resourceCnt,o=this.sliceRangeByTimes(e),a){for(d=[],n=0,h=o.length;h>n;n++)for(f=o[n],c=s=0,u=a;u>s;c=s+=1)p=this.flattenedResources[c],e.resourceId&&e.resourceId!==p.id||(r=t.extend({},f),r.resource=p,r.col=this.indicesToCol(c,f.dayIndex),d.push(r));return d}for(i=0,l=o.length;l>i;i++)f=o[i],f.col=f.dayIndex;return o},r}(d.TimeGrid),j=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return kt(e,t),e.prototype.timeGrid=null,e.prototype.isScrolled=!1,e.prototype.initialize=function(){return this.timeGrid=this.instantiateGrid(),this.intervalDuration=this.timeGrid.duration},e.prototype.instantiateGrid=function(){return new N(this)},e.prototype.setRange=function(t){return e.__super__.setRange.apply(this,arguments),this.timeGrid.setRange(t)},e.prototype.renderSkeleton=function(){return this.el.addClass("fc-timeline"),this.opt("eventOverlap")===!1&&this.el.addClass("fc-no-overlap"),this.el.html(this.renderSkeletonHtml()),this.renderTimeGridSkeleton()},e.prototype.renderSkeletonHtml=function(){return'<table> <thead class="fc-head"> <tr> <td class="fc-time-area '+this.widgetHeaderClass+'"></td> </tr> </thead> <tbody class="fc-body"> <tr> <td class="fc-time-area '+this.widgetContentClass+'"></td> </tr> </tbody> </table>'},e.prototype.renderTimeGridSkeleton=function(){return this.timeGrid.setElement(this.el.find("tbody .fc-time-area")),this.timeGrid.headEl=this.el.find("thead .fc-time-area"),this.timeGrid.renderSkeleton(),this.isScrolled=!1,this.timeGrid.bodyScroller.on("scroll",Ft(this,"handleBodyScroll"))},e.prototype.handleBodyScroll=function(t,e){if(t){if(!this.isScrolled)return this.isScrolled=!0,this.el.addClass("fc-scrolled")}else if(this.isScrolled)return this.isScrolled=!1,this.el.removeClass("fc-scrolled")},e.prototype.unrenderSkeleton=function(){return this.timeGrid.removeElement(),this.handleBodyScroll(0),e.__super__.unrenderSkeleton.apply(this,arguments)},e.prototype.renderDates=function(){return this.timeGrid.renderDates()},e.prototype.unrenderDates=function(){return this.timeGrid.unrenderDates()},e.prototype.renderBusinessHours=function(){return this.timeGrid.renderBusinessHours()},e.prototype.unrenderBusinessHours=function(){return this.timeGrid.unrenderBusinessHours()},e.prototype.getNowIndicatorUnit=function(){return this.timeGrid.getNowIndicatorUnit()},e.prototype.renderNowIndicator=function(t){return this.timeGrid.renderNowIndicator(t)},e.prototype.unrenderNowIndicator=function(){return this.timeGrid.unrenderNowIndicator()},e.prototype.prepareHits=function(){return this.timeGrid.prepareHits()},e.prototype.releaseHits=function(){return this.timeGrid.releaseHits()},e.prototype.queryHit=function(t,e){return this.timeGrid.queryHit(t,e)},e.prototype.getHitSpan=function(t){return this.timeGrid.getHitSpan(t)},e.prototype.getHitEl=function(t){return this.timeGrid.getHitEl(t)},e.prototype.updateWidth=function(){return this.timeGrid.updateWidth()},e.prototype.setHeight=function(t,e){var r;return r=e?"auto":t-this.timeGrid.headHeight()-this.queryMiscHeight(),this.timeGrid.bodyScroller.setHeight(r)},e.prototype.queryMiscHeight=function(){return this.el.outerHeight()-this.timeGrid.headScroller.el.outerHeight()-this.timeGrid.bodyScroller.el.outerHeight()},e.prototype.computeInitialScroll=function(t){return this.timeGrid.computeInitialScroll(t)},e.prototype.queryScroll=function(){return this.timeGrid.queryScroll()},e.prototype.setScroll=function(t){return this.timeGrid.setScroll(t)},e.prototype.renderEvents=function(t){return this.timeGrid.renderEvents(t),this.updateWidth()},e.prototype.unrenderEvents=function(){return this.timeGrid.unrenderEvents(),this.updateWidth()},e.prototype.renderDrag=function(t,e){return this.timeGrid.renderDrag(t,e)},e.prototype.unrenderDrag=function(){return this.timeGrid.unrenderDrag()},e.prototype.getEventSegs=function(){return this.timeGrid.getEventSegs()},e.prototype.renderSelection=function(t){return this.timeGrid.renderSelection(t)},e.prototype.unrenderSelection=function(){return this.timeGrid.unrenderSelection()},e}(X),rt=d.cssToStr,N=function(r){function o(){var t;o.__super__.constructor.apply(this,arguments),this.initScaleProps(),this.minTime=e.duration(this.opt("minTime")||"00:00"),this.maxTime=e.duration(this.opt("maxTime")||"24:00"),this.timeWindowMs=this.maxTime-this.minTime,this.snapDuration=(t=this.opt("snapDuration"))?e.duration(t):this.slotDuration,this.minResizeDuration=this.snapDuration,this.snapsPerSlot=nt(this.slotDuration,this.snapDuration),this.slotWidth=this.opt("slotWidth")}return kt(o,r),o.prototype.slotDates=null,o.prototype.slotCnt=null,o.prototype.snapCnt=null,o.prototype.snapsPerSlot=null,o.prototype.snapDiffToIndex=null,o.prototype.snapIndexToDiff=null,o.prototype.headEl=null,o.prototype.slatContainerEl=null,o.prototype.slatEls=null,o.prototype.containerCoordCache=null,o.prototype.slatCoordCache=null,o.prototype.slatInnerCoordCache=null,o.prototype.headScroller=null,o.prototype.bodyScroller=null,o.prototype.joiner=null,o.prototype.follower=null,o.prototype.eventTitleFollower=null,o.prototype.minTime=null,o.prototype.maxTime=null,o.prototype.timeWindowMs=null,o.prototype.slotDuration=null,o.prototype.snapDuration=null,o.prototype.duration=null,o.prototype.labelInterval=null,o.prototype.headerFormats=null,o.prototype.isTimeScale=null,o.prototype.largeUnit=null,o.prototype.emphasizeWeeks=!1,o.prototype.titleFollower=null,o.prototype.segContainerEl=null,o.prototype.segContainerHeight=null,o.prototype.bgSegContainerEl=null,o.prototype.helperEls=null,o.prototype.innerEl=null,o.prototype.opt=function(t){return this.view.opt(t)},o.prototype.isValidDate=function(t){var e;return!this.view.isHiddenDay(t)&&(!this.isTimeScale||(e=t.time()-this.minTime,e=(e%864e5+864e5)%864e5,e<this.timeWindowMs))},o.prototype.computeDisplayEventTime=function(){return!this.isTimeScale},o.prototype.computeDisplayEventEnd=function(){return!1},o.prototype.computeEventTimeFormat=function(){return this.opt("extraSmallTimeFormat")},o.prototype.normalizeGridDate=function(t){var e;return this.isTimeScale?(e=t.clone(),e.hasTime()||e.time(0)):(e=t.clone().stripTime(),this.largeUnit&&e.startOf(this.largeUnit)),e},o.prototype.normalizeGridRange=function(t){var e,r;return this.isTimeScale?r={start:this.normalizeGridDate(t.start),end:this.normalizeGridDate(t.end)}:(r=this.view.computeDayRange(t),this.largeUnit&&(r.start.startOf(this.largeUnit),e=r.end.clone().startOf(this.largeUnit),e.isSame(r.end)&&e.isAfter(r.start)||e.add(this.slotDuration),r.end=e)),r},o.prototype.rangeUpdated=function(){var t,e;for(this.start=this.normalizeGridDate(this.start),this.end=this.normalizeGridDate(this.end),this.isTimeScale&&(this.start.add(this.minTime),this.end.subtract(1,"day").add(this.maxTime)),e=[],t=this.start.clone();t<this.end;)this.isValidDate(t)&&e.push(t.clone()),t.add(this.slotDuration);return this.slotDates=e,this.updateGridDates()},o.prototype.updateGridDates=function(){var t,e,r,o,i;for(o=-1,e=0,r=[],i=[],t=this.start.clone();t<this.end;)this.isValidDate(t)?(o++,r.push(o),i.push(e)):r.push(o+.5),t.add(this.snapDuration),e++;return this.snapDiffToIndex=r,this.snapIndexToDiff=i,this.snapCnt=o+1,this.slotCnt=this.snapCnt/this.snapsPerSlot},o.prototype.spanToSegs=function(t){var e,r;return e=this.normalizeGridRange(t),this.computeDateSnapCoverage(t.start)<this.computeDateSnapCoverage(t.end)&&(r=vt(e,this))?(r.isStart&&!this.isValidDate(r.start)&&(r.isStart=!1),r.isEnd&&r.end&&!this.isValidDate(r.end.clone().subtract(1))&&(r.isEnd=!1),[r]):[]},o.prototype.prepareHits=function(){return this.buildCoords()},o.prototype.queryHit=function(t,e){var r,o,i,n,s,l,h,u,a,c,p,d;return d=this.snapsPerSlot,n=this.slatCoordCache,r=this.containerCoordCache,null!=r.getVerticalIndex(e)&&(s=n.getHorizontalIndex(t),null!=s)?(u=n.getWidth(s),this.isRTL?(h=n.getRightOffset(s),i=(h-t)/u,o=Math.floor(i*d),a=s*d+o,p=h-o/d*u,c=p-(o+1)/d*u):(l=n.getLeftOffset(s),i=(t-l)/u,o=Math.floor(i*d),a=s*d+o,c=l+o/d*u,p=l+(o+1)/d*u),{snap:a,component:this,left:c,right:p,top:r.getTopOffset(0),bottom:r.getBottomOffset(0)}):void 0},o.prototype.getHitSpan=function(t){return this.getSnapRange(t.snap)},o.prototype.getHitEl=function(t){return this.getSnapEl(t.snap)},o.prototype.getSnapRange=function(t){var e,r;return r=this.start.clone(),r.add(Ct(this.snapDuration,this.snapIndexToDiff[t])),e=r.clone().add(this.snapDuration),{start:r,end:e}},o.prototype.getSnapEl=function(t){return this.slatEls.eq(Math.floor(t/this.snapsPerSlot))},o.prototype.renderSkeleton=function(){return this.headScroller=new s({overflowX:"clipped-scroll",overflowY:"hidden"}),this.headScroller.canvas=new O,this.headScroller.render(),this.headEl.append(this.headScroller.el),this.bodyScroller=new s,this.bodyScroller.canvas=new O,this.bodyScroller.render(),this.el.append(this.bodyScroller.el),this.innerEl=this.bodyScroller.canvas.contentEl,this.slatContainerEl=t('<div class="fc-slats"/>').appendTo(this.bodyScroller.canvas.bgEl),this.segContainerEl=t('<div class="fc-event-container"/>').appendTo(this.bodyScroller.canvas.contentEl),this.bgSegContainerEl=this.bodyScroller.canvas.bgEl,this.containerCoordCache=new l({els:this.bodyScroller.canvas.el,isHorizontal:!0,isVertical:!0}),this.joiner=new A("horizontal",[this.headScroller,this.bodyScroller]),this.follower=new V(this.headScroller,this.view.calendar.isTouch),this.eventTitleFollower=new V(this.bodyScroller,this.view.calendar.isTouch),this.eventTitleFollower.minTravel=50,this.isRTL?this.eventTitleFollower.containOnNaturalRight=!0:this.eventTitleFollower.containOnNaturalLeft=!0,o.__super__.renderSkeleton.apply(this,arguments)},o.prototype.headColEls=null,o.prototype.slatColEls=null,o.prototype.renderDates=function(){var t,e,r,o,i;for(this.headScroller.canvas.contentEl.html(this.renderHeadHtml()),this.headColEls=this.headScroller.canvas.contentEl.find("col"),this.slatContainerEl.html(this.renderSlatHtml()),this.slatColEls=this.slatContainerEl.find("col"),this.slatEls=this.slatContainerEl.find("td"),this.slatCoordCache=new l({els:this.slatEls,isHorizontal:!0}),this.slatInnerCoordCache=new l({els:this.slatEls.find("> div"),isHorizontal:!0,offsetParent:this.bodyScroller.canvas.el}),i=this.slotDates,e=r=0,o=i.length;o>r;e=++r)t=i[e],this.view.trigger("dayRender",null,t,this.slatEls.eq(e));return this.follower?this.follower.setSprites(this.headEl.find("tr:not(:last-child) span")):void 0},o.prototype.unrenderDates=function(){return this.follower&&this.follower.clearSprites(),this.headScroller.canvas.contentEl.empty(),this.slatContainerEl.empty(),this.headScroller.canvas.clearWidth(),this.bodyScroller.canvas.clearWidth()},o.prototype.renderHeadHtml=function(){var t,e,r,o,i,n,s,l,h,u,a,c,p,d,f,g,y,v,w,m,R,S,b,C,E,T,H,_,I,D,x,F,G,M,W,L,B;for(g=this.labelInterval,n=this.headerFormats,e=function(){var t,e,r;for(r=[],t=0,e=n.length;e>t;t++)i=n[t],r.push([]);return r}(),y=null,I=null,W=this.slotDates,M=[],p=0,v=W.length;v>p;p++){for(r=W[p],B=r.week(),c=this.emphasizeWeeks&&null!==I&&I!==B,x=d=0,w=n.length;w>d;x=++d)i=n[x],F=e[x],y=F[F.length-1],a=n.length>1&&x<n.length-1,H=null,a?(L=r.format(i),o=r.format(),y&&y.text===L?y.colspan+=1:H={text:L,dateData:o,colspan:1}):!y||Rt(st(this.start,r,g))?(L=r.format(i),o=r.format(),H={text:L,dateData:o,colspan:1}):y.colspan+=1,H&&(H.weekStart=c,F.push(H));M.push({weekStart:c}),I=B}for(h=g>this.slotDuration,s="<table>",s+="<colgroup>",f=0,m=W.length;m>f;f++)r=W[f],s+="<col/>";for(s+="</colgroup>",s+="<tbody>",l=E=0,R=e.length;R>E;l=++E){for(F=e[l],u=l===e.length-1,s+="<tr"+(h&&u?' class="fc-chrono"':"")+">",T=0,S=F.length;S>T;T++)t=F[T],s+='<th class="'+this.view.widgetHeaderClass+" "+(t.weekStart?"fc-em-cell":"")+'" data-date="'+t.dateData+'"'+(t.colspan>1?' colspan="'+t.colspan+'"':"")+'><div class="fc-cell-content"><span class="fc-cell-text">'+yt(t.text)+"</span></div></th>";s+="</tr>"}for(s+="</tbody></table>",G="<table>",G+="<colgroup>",_=0,b=M.length;b>_;_++)t=M[_],G+="<col/>";for(G+="</colgroup>",G+="<tbody><tr>",l=D=0,C=M.length;C>D;l=++D)t=M[l],r=W[l],G+=this.slatCellHtml(r,t.weekStart);return G+="</tr></tbody></table>",this._slatHtml=G,s},o.prototype.renderSlatHtml=function(){return this._slatHtml},o.prototype.slatCellHtml=function(t,e){var r;return this.isTimeScale?(r=[],r.push(Rt(st(this.start,t,this.labelInterval))?"fc-major":"fc-minor")):(r=this.getDayClasses(t),r.push("fc-day")),r.unshift(this.view.widgetContentClass),e&&r.push("fc-em-cell"),'<td class="'+r.join(" ")+'" data-date="'+t.format()+'"><div /></td>'},o.prototype.businessHourSegs=null,o.prototype.renderBusinessHours=function(){var t,e;return this.largeUnit?void 0:(t=this.view.calendar.getBusinessHoursEvents(!this.isTimeScale),e=this.businessHourSegs=this.eventsToSegs(t),this.renderFill("businessHours",e,"bgevent"))},o.prototype.unrenderBusinessHours=function(){return this.unrenderFill("businessHours")},o.prototype.nowIndicatorEls=null,o.prototype.getNowIndicatorUnit=function(){return this.isTimeScale?J(this.slotDuration):void 0},o.prototype.renderNowIndicator=function(e){var r,o,i;return i=[],e=this.normalizeGridDate(e),e>=this.start&&e<this.end&&(r=this.dateToCoord(e),o=this.isRTL?{right:-r}:{left:r},i.push(t("<div class='fc-now-indicator fc-now-indicator-arrow'></div>").css(o).appendTo(this.headScroller.canvas.el)[0]),i.push(t("<div class='fc-now-indicator fc-now-indicator-line'></div>").css(o).appendTo(this.bodyScroller.canvas.el)[0])),this.nowIndicatorEls=t(i)},o.prototype.unrenderNowIndicator=function(){return this.nowIndicatorEls?(this.nowIndicatorEls.remove(),this.nowIndicatorEls=null):void 0},o.prototype.explicitSlotWidth=null,o.prototype.defaultSlotWidth=null,o.prototype.updateWidth=function(){var t,e,r,o,i;return i=Math.round(this.slotWidth||(this.slotWidth=this.computeSlotWidth())),r=i*this.slotDates.length,e="",o=i,t=this.bodyScroller.getClientWidth(),t>r&&(e=t,r="",o=Math.floor(t/this.slotDates.length)),this.headScroller.canvas.setWidth(r),this.headScroller.canvas.setMinWidth(e),this.bodyScroller.canvas.setWidth(r),this.bodyScroller.canvas.setMinWidth(e),this.headColEls.slice(0,-1).add(this.slatColEls.slice(0,-1)).width(o),this.headScroller.updateSize(),this.bodyScroller.updateSize(),this.joiner.update(),this.buildCoords(),this.updateSegPositions(),this.view.updateNowIndicator(),this.follower&&this.follower.update(),this.eventTitleFollower?this.eventTitleFollower.update():void 0},o.prototype.computeSlotWidth=function(){var e,r,o,i,n,s;return o=0,r=this.headEl.find("tr:last-child th span"),r.each(function(e,r){var i;return i=t(r).outerWidth(),o=Math.max(o,i)}),e=o+1,s=nt(this.labelInterval,this.slotDuration),n=Math.ceil(e/s),i=this.headColEls.eq(0).css("min-width"),i&&(i=parseInt(i,10),i&&(n=Math.max(n,i))),n},o.prototype.buildCoords=function(){return this.containerCoordCache.build(),this.slatCoordCache.build(),this.slatInnerCoordCache.build()},o.prototype.computeDateSnapCoverage=function(t){var e,r,o;return r=st(this.start,t,this.snapDuration),0>r?0:r>=this.snapDiffToIndex.length?this.snapCnt:(o=Math.floor(r),e=this.snapDiffToIndex[o],Rt(e)?e+=r-o:e=Math.ceil(e),e)},o.prototype.dateToCoord=function(t){var e,r,o,i,n;return n=this.computeDateSnapCoverage(t),o=n/this.snapsPerSlot,i=Math.floor(o),i=Math.min(i,this.slotCnt-1),r=o-i,e=this.slatInnerCoordCache,this.isRTL?e.getRightPosition(i)-e.getWidth(i)*r-this.containerCoordCache.getWidth(0):e.getLeftPosition(i)+e.getWidth(i)*r},o.prototype.rangeToCoords=function(t){return this.isRTL?{right:this.dateToCoord(t.start),left:this.dateToCoord(t.end)}:{left:this.dateToCoord(t.start),right:this.dateToCoord(t.end)}},o.prototype.headHeight=function(){var t;return t=this.headScroller.canvas.contentEl.find("table"),t.height.apply(t,arguments)},o.prototype.updateSegPositions=function(){var t,e,r,o,i;for(i=(this.segs||[]).concat(this.businessHourSegs||[]),e=0,r=i.length;r>e;e++)o=i[e],t=this.rangeToCoords(o),o.el.css({left:o.left=t.left,right:-(o.right=t.right)})},o.prototype.computeInitialScroll=function(t){var r,o;return r=0,this.isTimeScale&&(o=this.opt("scrollTime"),o&&(o=e.duration(o),r=this.dateToCoord(this.start.clone().time(o)))),{left:r,top:0}},o.prototype.queryScroll=function(){return{left:this.bodyScroller.getScrollLeft(),top:this.bodyScroller.getScrollTop()}},o.prototype.setScroll=function(t){return this.headScroller.setScrollLeft(t.left),this.headScroller.setScrollLeft(t.left),this.bodyScroller.setScrollTop(t.top)},o.prototype.renderFgSegs=function(t){return t=this.renderFgSegEls(t),this.renderFgSegsInContainers([[this,t]]),this.updateSegFollowers(t),t},o.prototype.unrenderFgSegs=function(){return this.clearSegFollowers(),this.unrenderFgContainers([this])},o.prototype.renderFgSegsInContainers=function(t){var e,r,o,i,n,s,l,h,u,a,c,p,d,f,g,y,v,w,m,R,S,b,C,E,T;for(o=0,s=t.length;s>o;o++)for(m=t[o],e=m[0],T=m[1],i=0,l=T.length;l>i;i++)E=T[i],r=this.rangeToCoords(E),E.el.css({left:E.left=r.left,right:-(E.right=r.right)});for(n=0,h=t.length;h>n;n++)for(R=t[n],e=R[0],T=R[1],f=0,u=T.length;u>f;f++)E=T[f],E.el.appendTo(e.segContainerEl);for(g=0,a=t.length;a>g;g++){for(S=t[g],e=S[0],T=S[1],y=0,c=T.length;c>y;y++)E=T[y],E.height=E.el.outerHeight(!0);this.buildSegLevels(T),e.segContainerHeight=tt(T)}for(C=[],v=0,p=t.length;p>v;v++){for(b=t[v],e=b[0],T=b[1],w=0,d=T.length;d>w;w++)E=T[w],E.el.css("top",E.top);C.push(e.segContainerEl.height(e.segContainerHeight));
|
|
}return C},o.prototype.buildSegLevels=function(t){var e,r,o,i,n,s,l,h,u,a,c,p,d,f;for(d=[],this.sortEventSegs(t),o=0,s=t.length;s>o;o++){for(f=t[o],f.above=[],u=0;u<d.length;){for(r=!1,c=d[u],i=0,l=c.length;l>i;i++)a=c[i],Bt(f,a)&&(f.above.push(a),r=!0);if(!r)break;u+=1}for((d[u]||(d[u]=[])).push(f),u+=1;u<d.length;){for(p=d[u],n=0,h=p.length;h>n;n++)e=p[n],Bt(f,e)&&e.above.push(f);u+=1}}return d},o.prototype.unrenderFgContainers=function(t){var e,r,o,i;for(i=[],r=0,o=t.length;o>r;r++)e=t[r],e.segContainerEl.empty(),e.segContainerEl.height(""),i.push(e.segContainerHeight=null);return i},o.prototype.fgSegHtml=function(t,e){var r,o,i,n,s,l;return o=t.event,i=this.view.isEventDraggable(o),s=t.isStart&&this.view.isEventResizableFromStart(o),n=t.isEnd&&this.view.isEventResizableFromEnd(o),r=this.getSegClasses(t,i,s||n),r.unshift("fc-timeline-event","fc-h-event"),l=this.getEventTimeText(o),'<a class="'+r.join(" ")+'" style="'+rt(this.getSegSkinCss(t))+'"'+(o.url?' href="'+yt(o.url)+'"':"")+'><div class="fc-content">'+(l?'<span class="fc-time">'+yt(l)+"</span>":"")+'<span class="fc-title">'+(o.title?yt(o.title):" ")+'</span></div><div class="fc-bg" />'+(s?'<div class="fc-resizer fc-start-resizer"></div>':"")+(n?'<div class="fc-resizer fc-end-resizer"></div>':"")+"</a>"},o.prototype.updateSegFollowers=function(t){var e,r,o,i,n;if(this.eventTitleFollower){for(i=[],e=0,r=t.length;r>e;e++)o=t[e],n=o.el.find(".fc-title"),n.length&&i.push(new P(n));return this.eventTitleFollower.setSprites(i)}},o.prototype.clearSegFollowers=function(){return this.eventTitleFollower?this.eventTitleFollower.clearSprites():void 0},o.prototype.segDragStart=function(){return o.__super__.segDragStart.apply(this,arguments),this.eventTitleFollower?this.eventTitleFollower.forceRelative():void 0},o.prototype.segDragEnd=function(){return o.__super__.segDragEnd.apply(this,arguments),this.eventTitleFollower?this.eventTitleFollower.clearForce():void 0},o.prototype.segResizeStart=function(){return o.__super__.segResizeStart.apply(this,arguments),this.eventTitleFollower?this.eventTitleFollower.forceRelative():void 0},o.prototype.segResizeEnd=function(){return o.__super__.segResizeEnd.apply(this,arguments),this.eventTitleFollower?this.eventTitleFollower.clearForce():void 0},o.prototype.renderHelper=function(t,e){var r;return r=this.eventToSegs(t),r=this.renderFgSegEls(r),this.renderHelperSegsInContainers([[this,r]],e)},o.prototype.renderHelperSegsInContainers=function(e,r){var o,i,n,s,l,h,u,a,c,p,d,f,g,y,v,w,m,R;for(s=[],m=[],l=0,a=e.length;a>l;l++)for(g=e[l],o=g[0],R=g[1],h=0,c=R.length;c>h;h++)w=R[h],i=this.rangeToCoords(w),w.el.css({left:w.left=i.left,right:-(w.right=i.right)}),r&&r.resourceId===(null!=(y=o.resource)?y.id:void 0)?w.el.css("top",r.el.css("top")):w.el.css("top",0);for(u=0,p=e.length;p>u;u++)for(v=e[u],o=v[0],R=v[1],n=t('<div class="fc-event-container fc-helper-container"/>').appendTo(o.innerEl),s.push(n[0]),f=0,d=R.length;d>f;f++)w=R[f],n.append(w.el),m.push(w.el[0]);return this.helperEls?this.helperEls=this.helperEls.add(t(s)):this.helperEls=t(s),t(m)},o.prototype.unrenderHelper=function(){return this.helperEls?(this.helperEls.remove(),this.helperEls=null):void 0},o.prototype.renderEventResize=function(t,e){return this.renderHighlight(this.eventToSpan(t)),this.renderEventLocationHelper(t,e)},o.prototype.unrenderEventResize=function(){return this.unrenderHighlight(),this.unrenderHelper()},o.prototype.renderFill=function(t,e,r){return e=this.renderFillSegEls(t,e),this.renderFillInContainers(t,[[this,e]],r),e},o.prototype.renderFillInContainers=function(t,e,r){var o,i,n,s,l,h;for(l=[],i=0,n=e.length;n>i;i++)s=e[i],o=s[0],h=s[1],l.push(this.renderFillInContainer(t,o,h,r));return l},o.prototype.renderFillInContainer=function(e,r,o,i){var n,s,l,h,u;if(o.length){for(i||(i=e.toLowerCase()),n=t('<div class="fc-'+i+'-container" />').appendTo(r.bgSegContainerEl),l=0,h=o.length;h>l;l++)u=o[l],s=this.rangeToCoords(u),u.el.css({left:u.left=s.left,right:-(u.right=s.right)}),u.el.appendTo(n);return this.elsByFill[e]?this.elsByFill[e]=this.elsByFill[e].add(n):this.elsByFill[e]=n}},o.prototype.renderDrag=function(t,e){return e?this.renderEventLocationHelper(t,e):(this.renderHighlight(this.eventToSpan(t)),null)},o.prototype.unrenderDrag=function(){return this.unrenderHelper(),this.unrenderHighlight()},o}(f),tt=function(t){var e,r,o,i;for(o=0,e=0,r=t.length;r>e;e++)i=t[e],o=Math.max(o,Z(i));return o},Z=function(t){return null==t.top&&(t.top=tt(t.above)),t.top+t.height},Bt=function(t,e){return t.left<e.right&&t.right>e.left},S=18,m=6,w=200,R=1e3,h={months:1},k=[{years:1},{months:1},{days:1},{hours:1},{minutes:30},{minutes:15},{minutes:10},{minutes:5},{minutes:1},{seconds:30},{seconds:15},{seconds:10},{seconds:5},{seconds:1},{milliseconds:500},{milliseconds:100},{milliseconds:10},{milliseconds:1}],N.prototype.initScaleProps=function(){var e,r,o;return this.labelInterval=this.queryDurationOption("slotLabelInterval"),this.slotDuration=this.queryDurationOption("slotDuration"),this.ensureGridDuration(),this.validateLabelAndSlot(),this.ensureLabelInterval(),this.ensureSlotDuration(),e=this.opt("slotLabelFormat"),o=t.type(e),this.headerFormats="array"===o?e:"string"===o?[e]:this.computeHeaderFormats(),this.isTimeScale=lt(this.slotDuration),this.largeUnit=this.isTimeScale?void 0:(r=J(this.slotDuration),/year|month|week/.test(r)?r:void 0),this.emphasizeWeeks=1===this.slotDuration.as("days")&&this.duration.as("weeks")>=2&&!this.opt("businessHours")},N.prototype.queryDurationOption=function(t){var r,o;return o=this.opt(t),null!=o&&(r=e.duration(o),+r)?r:void 0},N.prototype.validateLabelAndSlot=function(){var t,e,r;return this.labelInterval&&(t=nt(this.duration,this.labelInterval),t>R&&(d.warn("slotLabelInterval results in too many cells"),this.labelInterval=null)),this.slotDuration&&(e=nt(this.duration,this.slotDuration),e>R&&(d.warn("slotDuration results in too many cells"),this.slotDuration=null)),this.labelInterval&&this.slotDuration&&(r=nt(this.labelInterval,this.slotDuration),!Rt(r)||1>r)?(d.warn("slotLabelInterval must be a multiple of slotDuration"),this.slotDuration=null):void 0},N.prototype.ensureGridDuration=function(){var t,r,o,i,n;if(t=this.duration,!t){if(t=this.view.intervalDuration,!t)if(this.labelInterval||this.slotDuration)for(n=this.ensureLabelInterval(),o=k.length-1;o>=0&&(r=k[o],t=e.duration(r),i=nt(t,n),!(i>=S));o+=-1);else t=e.duration(h);this.duration=t}return t},N.prototype.ensureLabelInterval=function(){var t,r,o,i,n,s,l,h,u;if(n=this.labelInterval,!n){if(this.duration||this.slotDuration||this.ensureGridDuration(),this.slotDuration){for(r=0,s=k.length;s>r;r++)if(t=k[r],u=e.duration(t),h=nt(u,this.slotDuration),Rt(h)&&m>=h){n=u;break}n||(n=this.slotDuration)}else for(o=0,l=k.length;l>o&&(t=k[o],n=e.duration(t),i=nt(this.duration,n),!(i>=S));o++);this.labelInterval=n}return n},N.prototype.ensureSlotDuration=function(){var t,r,o,i,n,s,l,h;if(s=this.slotDuration,!s){for(o=this.ensureLabelInterval(),r=0,i=k.length;i>r;r++)if(t=k[r],h=e.duration(t),l=nt(o,h),Rt(l)&&l>1&&m>=l){s=h;break}s&&this.duration&&(n=nt(this.duration,s),n>w&&(s=null)),s||(s=o),this.slotDuration=s}return s},N.prototype.computeHeaderFormats=function(){var t,e,r,o,i,n,s,l;switch(s=this.view,o=this.duration,i=this.labelInterval,n=J(i),l=this.opt("weekNumbers"),t=e=r=null,"week"!==n||l||(n="day"),n){case"year":t="YYYY";break;case"month":o.asYears()>1&&(t="YYYY"),e="MMM";break;case"week":o.asYears()>1&&(t="YYYY"),e=this.opt("shortWeekFormat");break;case"day":o.asYears()>1?t=this.opt("monthYearFormat"):o.asMonths()>1&&(t="MMMM"),l&&(e=this.opt("weekFormat")),r="dd D";break;case"hour":l&&(t=this.opt("weekFormat")),o.asDays()>1&&(e=this.opt("dayOfMonthFormat")),r=this.opt("smallTimeFormat");break;case"minute":i.asMinutes()/60>=m?(t=this.opt("hourFormat"),e="[:]mm"):t=this.opt("mediumTimeFormat");break;case"second":i.asSeconds()/60>=m?(t="LT",e="[:]ss"):t="LTS";break;case"millisecond":t="LTS",e="[.]SSS"}return[].concat(t||[],e||[],r||[])},d.views.timeline={class:j,defaults:{eventResizableFromStart:!0}},d.views.timelineDay={type:"timeline",duration:{days:1}},d.views.timelineWeek={type:"timeline",duration:{weeks:1}},d.views.timelineMonth={type:"timeline",duration:{months:1}},d.views.timelineYear={type:"timeline",duration:{years:1}},W=function(e){function r(){return r.__super__.constructor.apply(this,arguments)}return kt(r,e),r.mixin(L),r.prototype.resourceGrid=null,r.prototype.tbodyHash=null,r.prototype.joiner=null,r.prototype.dividerEls=null,r.prototype.superHeaderText=null,r.prototype.isVGrouping=null,r.prototype.isHGrouping=null,r.prototype.groupSpecs=null,r.prototype.colSpecs=null,r.prototype.orderSpecs=null,r.prototype.rowHierarchy=null,r.prototype.resourceRowHash=null,r.prototype.nestingCnt=0,r.prototype.isNesting=null,r.prototype.dividerWidth=null,r.prototype.initialize=function(){return r.__super__.initialize.apply(this,arguments),this.processResourceOptions(),this.resourceGrid=new q(this),this.rowHierarchy=new z(this),this.resourceRowHash={}},r.prototype.instantiateGrid=function(){return new M(this)},r.prototype.processResourceOptions=function(){var t,e,r,o,i,n,s,l,h,u,a,c,p,d,f,g,y,v,w,m,R,S;for(t=this.opt("resourceColumns")||[],f=this.opt("resourceLabelText"),o="Resources",S=null,t.length?S=f:t.push({labelText:f||o,text:this.getResourceTextFunc()}),m=[],i=[],s=[],a=!1,u=!1,c=0,g=t.length;g>c;c++)r=t[c],r.group?i.push(r):m.push(r);for(m[0].isMain=!0,i.length?(s=i,a=!0):(l=this.opt("resourceGroupField"),l&&(u=!0,s.push({field:l,text:this.opt("resourceGroupText"),render:this.opt("resourceGroupRender")}))),e=Dt(this.opt("resourceOrder")),R=[],p=0,y=e.length;y>p;p++){for(w=e[p],h=!1,d=0,v=s.length;v>d;d++)if(n=s[d],n.field===w.field){n.order=w.order,h=!0;break}h||R.push(w)}return this.superHeaderText=S,this.isVGrouping=a,this.isHGrouping=u,this.groupSpecs=s,this.colSpecs=i.concat(m),this.orderSpecs=R},r.prototype.renderSkeleton=function(){return r.__super__.renderSkeleton.apply(this,arguments),this.renderResourceGridSkeleton(),this.tbodyHash={spreadsheet:this.resourceGrid.tbodyEl,event:this.timeGrid.tbodyEl},this.joiner=new A("vertical",[this.resourceGrid.bodyScroller,this.timeGrid.bodyScroller]),this.initDividerMoving()},r.prototype.renderSkeletonHtml=function(){return'<table> <thead class="fc-head"> <tr> <td class="fc-resource-area '+this.widgetHeaderClass+'"></td> <td class="fc-divider fc-col-resizer '+this.widgetHeaderClass+'"></td> <td class="fc-time-area '+this.widgetHeaderClass+'"></td> </tr> </thead> <tbody class="fc-body"> <tr> <td class="fc-resource-area '+this.widgetContentClass+'"></td> <td class="fc-divider fc-col-resizer '+this.widgetHeaderClass+'"></td> <td class="fc-time-area '+this.widgetContentClass+'"></td> </tr> </tbody> </table>'},r.prototype.renderResourceGridSkeleton=function(){return this.resourceGrid.el=this.el.find("tbody .fc-resource-area"),this.resourceGrid.headEl=this.el.find("thead .fc-resource-area"),this.resourceGrid.renderSkeleton()},r.prototype.initDividerMoving=function(){var t;return this.dividerEls=this.el.find(".fc-divider"),this.dividerWidth=null!=(t=this.opt("resourceAreaWidth"))?t:this.resourceGrid.tableWidth,null!=this.dividerWidth&&this.positionDivider(this.dividerWidth),this.dividerEls.on("mousedown",function(t){return function(e){return t.dividerMousedown(e)}}(this))},r.prototype.dividerMousedown=function(t){var e,r,o,i,n;return r=this.opt("isRTL"),i=30,o=this.el.width()-30,n=this.getNaturalDividerWidth(),e=new u({dragStart:function(t){return function(){return t.dividerEls.addClass("fc-active")}}(this),drag:function(t){return function(e,s){var l;return l=r?n-e:n+e,l=Math.max(l,i),l=Math.min(l,o),t.dividerWidth=l,t.positionDivider(l),t.updateWidth()}}(this),dragEnd:function(t){return function(){return t.dividerEls.removeClass("fc-active")}}(this)}),e.startInteraction(t)},r.prototype.getNaturalDividerWidth=function(){return this.el.find(".fc-resource-area").width()},r.prototype.positionDivider=function(t){return this.el.find(".fc-resource-area").width(t)},r.prototype.renderEvents=function(t){return this.timeGrid.renderEvents(t),this.syncRowHeights(),this.updateWidth()},r.prototype.unrenderEvents=function(){return this.timeGrid.unrenderEvents(),this.syncRowHeights(),this.updateWidth()},r.prototype.updateWidth=function(){return r.__super__.updateWidth.apply(this,arguments),this.resourceGrid.updateWidth(),this.joiner.update(),this.cellFollower?this.cellFollower.update():void 0},r.prototype.updateHeight=function(t){return r.__super__.updateHeight.apply(this,arguments),t?this.syncRowHeights():void 0},r.prototype.setHeight=function(t,e){var r,o;return o=this.syncHeadHeights(),r=e?"auto":t-o-this.queryMiscHeight(),this.timeGrid.bodyScroller.setHeight(r),this.resourceGrid.bodyScroller.setHeight(r)},r.prototype.queryMiscHeight=function(){return this.el.outerHeight()-Math.max(this.resourceGrid.headScroller.el.outerHeight(),this.timeGrid.headScroller.el.outerHeight())-Math.max(this.resourceGrid.bodyScroller.el.outerHeight(),this.timeGrid.bodyScroller.el.outerHeight())},r.prototype.syncHeadHeights=function(){var t;return this.resourceGrid.headHeight("auto"),this.timeGrid.headHeight("auto"),t=Math.max(this.resourceGrid.headHeight(),this.timeGrid.headHeight()),this.resourceGrid.headHeight(t),this.timeGrid.headHeight(t),t},r.prototype.scrollToResource=function(t){return this.timeGrid.scrollToResource(t)},r.prototype.setResources=function(t){var e,r,o;for(this.batchRows(),e=0,r=t.length;r>e;e++)o=t[e],this.insertResource(o);return this.rowHierarchy.show(),this.unbatchRows(),this.reinitializeCellFollowers()},r.prototype.unsetResources=function(){return this.clearEvents(),this.batchRows(),this.rowHierarchy.removeChildren(),this.unbatchRows(),this.reinitializeCellFollowers()},r.prototype.addResource=function(t){return this.insertResource(t),this.reinitializeCellFollowers()},r.prototype.removeResource=function(t){var e;return e=this.getResourceRow(t.id),e?(this.batchRows(),e.remove(),this.unbatchRows(),this.reinitializeCellFollowers()):void 0},r.prototype.cellFollower=null,r.prototype.reinitializeCellFollowers=function(){var e,r,o,i,n,s;for(this.cellFollower&&this.cellFollower.clearSprites(),this.cellFollower=new V(this.resourceGrid.bodyScroller,this.calendar.isTouch),this.cellFollower.isHFollowing=!1,this.cellFollower.isVFollowing=!0,i=[],n=this.rowHierarchy.getNodes(),r=0,o=n.length;o>r;r++)s=n[r],s instanceof U&&s.groupTd&&(e=s.groupTd.find(".fc-cell-content"),e.length&&i.push(e[0]));return this.cellFollower.setSprites(t(i))},r.prototype.insertResource=function(t,e){var r,o,i,n,s,l,h;for(h=new F(this,t),null==e&&(n=t.parentId,n&&(e=this.getResourceRow(n))),e?this.insertRowAsChild(h,e):this.insertRow(h),s=t.children,l=[],o=0,i=s.length;i>o;o++)r=s[o],l.push(this.insertResource(r,h));return l},r.prototype.insertRow=function(t,e,r){var o;return null==e&&(e=this.rowHierarchy),null==r&&(r=this.groupSpecs),r.length?(o=this.ensureResourceGroup(t,e,r[0]),o instanceof g?this.insertRowAsChild(t,o):this.insertRow(t,o,r.slice(1))):this.insertRowAsChild(t,e)},r.prototype.insertRowAsChild=function(t,e){return e.addChild(t,this.computeChildRowPosition(t,e))},r.prototype.computeChildRowPosition=function(t,e){var r,o,i,n,s,l;if(this.orderSpecs.length)for(s=e.children,o=i=0,n=s.length;n>i;o=++i)if(l=s[o],r=this.compareResources(l.resource||{},t.resource||{}),r>0)return o;return null},r.prototype.compareResources=function(t,e){return Q(t,e,this.orderSpecs)},r.prototype.ensureResourceGroup=function(t,e,r){var o,i,n,s,l,h,u,a,c,p,d;if(n=(t.resource||{})[r.field],i=null,r.order)for(c=e.children,s=l=0,u=c.length;u>l;s=++l){if(d=c[s],o=ht(d.groupValue,n)*r.order,0===o){i=d;break}if(o>0)break}else for(p=e.children,s=h=0,a=p.length;a>h;s=++h)if(d=p[s],d.groupValue===n){i=d;break}return i||(i=this.isVGrouping?new U(this,r,n):new g(this,r,n),e.addChild(i,s)),i},r.prototype.pairSegsWithRows=function(t){var e,r,o,i,n,s,l,h;for(i=[],n={},e=0,r=t.length;r>e;e++)h=t[e],s=h.resourceId,s&&(l=this.getResourceRow(s),l&&(o=n[s],o||(o=[l,[]],i.push(o),n[s]=o),o[1].push(h)));return i},r.prototype.rowAdded=function(t){var e,r;return t instanceof F&&(this.resourceRowHash[t.resource.id]=t),r=this.isNesting,e=Boolean(this.nestingCnt+=t.depth?1:0),r!==e&&(this.el.toggleClass("fc-nested",e),this.el.toggleClass("fc-flat",!e)),this.isNesting=e},r.prototype.rowRemoved=function(t){var e,r;return t instanceof F&&delete this.resourceRowHash[t.resource.id],r=this.isNesting,e=Boolean(this.nestingCnt-=t.depth?1:0),r!==e&&(this.el.toggleClass("fc-nested",e),this.el.toggleClass("fc-flat",!e)),this.isNesting=e},r.prototype.batchRowDepth=0,r.prototype.shownRowBatch=null,r.prototype.hiddenRowBatch=null,r.prototype.batchRows=function(){return this.batchRowDepth++?void 0:(this.shownRowBatch=[],this.hiddenRowBatch=[])},r.prototype.unbatchRows=function(){return--this.batchRowDepth?void 0:(this.hiddenRowBatch.length&&this.rowsHidden(this.hiddenRowBatch),this.shownRowBatch.length&&this.rowsShown(this.shownRowBatch),this.hiddenRowBatch=null,this.shownRowBatch=null)},r.prototype.rowShown=function(t){return this.shownRowBatch?this.shownRowBatch.push(t):this.rowsShown([t])},r.prototype.rowHidden=function(t){return this.hiddenRowBatch?this.hiddenRowBatch.push(t):this.rowsHidden([t])},r.prototype.rowsShown=function(t){return this.syncRowHeights(t),this.updateWidth()},r.prototype.rowsHidden=function(t){return this.updateWidth()},r.prototype.syncRowHeights=function(t,e){var r,o,i,n,s,l,h,u,a,c;for(null==e&&(e=!1),null==t&&(t=this.getVisibleRows()),l=0,u=t.length;u>l;l++)c=t[l],c.setTrInnerHeight("");for(s=function(){var o,i,n;for(n=[],o=0,i=t.length;i>o;o++)c=t[o],r=c.getMaxTrInnerHeight(),e&&(r+=r%2),n.push(r);return n}(),n=h=0,a=t.length;a>h;n=++h)c=t[n],c.setTrInnerHeight(s[n]);return!e&&(o=this.resourceGrid.tbodyEl.height(),i=this.timeGrid.tbodyEl.height(),Math.abs(o-i)>1)?this.syncRowHeights(t,!0):void 0},r.prototype.getVisibleRows=function(){var t,e,r,o,i;for(r=this.rowHierarchy.getRows(),o=[],t=0,e=r.length;e>t;t++)i=r[t],i.isShown&&o.push(i);return o},r.prototype.getEventRows=function(){var t,e,r,o,i;for(r=this.rowHierarchy.getRows(),o=[],t=0,e=r.length;e>t;t++)i=r[t],i instanceof p&&o.push(i);return o},r.prototype.getResourceRow=function(t){return this.resourceRowHash[t]},r.prototype.setScroll=function(t){return r.__super__.setScroll.apply(this,arguments),this.resourceGrid.bodyScroller.setScrollTop(t.top)},r}(j),M=function(e){function r(){return r.__super__.constructor.apply(this,arguments)}return kt(r,e),r.mixin(I),r.prototype.eventRows=null,r.prototype.shownEventRows=null,r.prototype.tbodyEl=null,r.prototype.rowCoordCache=null,r.prototype.spanToSegs=function(t){var e,o,i,n,s,l;if(l=r.__super__.spanToSegs.apply(this,arguments),e=this.view.calendar,n=t.resourceId)for(o=0,i=l.length;i>o;o++)s=l[o],s.resource=e.getResourceById(n),s.resourceId=n;return l},r.prototype.prepareHits=function(){var t,e;return r.__super__.prepareHits.apply(this,arguments),this.eventRows=this.view.getEventRows(),this.shownEventRows=function(){var e,r,o,i;for(o=this.eventRows,i=[],e=0,r=o.length;r>e;e++)t=o[e],t.isShown&&i.push(t);return i}.call(this),e=function(){var e,r,o,i;for(o=this.shownEventRows,i=[],e=0,r=o.length;r>e;e++)t=o[e],i.push(t.getTr("event")[0]);return i}.call(this),this.rowCoordCache=new l({els:e,isVertical:!0}),this.rowCoordCache.build()},r.prototype.releaseHits=function(){return r.__super__.releaseHits.apply(this,arguments),this.eventRows=null,this.shownEventRows=null,this.rowCoordCache.clear()},r.prototype.queryHit=function(t,e){var o,i;return i=r.__super__.queryHit.apply(this,arguments),i&&(o=this.rowCoordCache.getVerticalIndex(e),null!=o)?{resourceId:this.shownEventRows[o].resource.id,snap:i.snap,component:this,left:i.left,right:i.right,top:this.rowCoordCache.getTopOffset(o),bottom:this.rowCoordCache.getBottomOffset(o)}:void 0},r.prototype.getHitSpan=function(t){var e;return e=this.getSnapRange(t.snap),e.resourceId=t.resourceId,e},r.prototype.getHitEl=function(t){return this.getSnapEl(t.snap)},r.prototype.renderSkeleton=function(){var e;return r.__super__.renderSkeleton.apply(this,arguments),this.segContainerEl.remove(),this.segContainerEl=null,e=t('<div class="fc-rows"><table><tbody/></table></div>').appendTo(this.bodyScroller.canvas.contentEl),this.tbodyEl=e.find("tbody")},r.prototype.renderFgSegs=function(t){var e,r,o,i,n,s,l;for(t=this.renderFgSegEls(t),s=this.view.pairSegsWithRows(t),l=[],o=0,i=s.length;i>o;o++)n=s[o],e=n[0],r=n[1],e.fgSegs=r,e.isShown&&(e.isSegsRendered=!0,l.push(n));return this.renderFgSegsInContainers(l),this.updateSegFollowers(t),t},r.prototype.unrenderFgSegs=function(){var t,e,r,o;for(this.clearSegFollowers(),e=this.view.getEventRows(),r=0,o=e.length;o>r;r++)t=e[r],t.fgSegs=null,t.isSegsRendered=!1;return this.unrenderFgContainers(e)},r.prototype.renderFill=function(t,e,r){var o,i,n,s,l,h,u,a,c,p,d,f;for(e=this.renderFillSegEls(t,e),a=[],l=[],o=0,n=e.length;n>o;o++)d=e[o],d.resourceId?a.push(d):l.push(d);for(u=this.view.pairSegsWithRows(a),f=[],i=0,s=u.length;s>i;i++)h=u[i],c=h[0],p=h[1],"bgEvent"===t&&(c.bgSegs=p),c.isShown&&f.push(h);return l.length&&f.unshift([this,l]),this.renderFillInContainers(t,f,r),e},r.prototype.renderHelper=function(t,e){var r,o;return o=this.eventToSegs(t),o=this.renderFgSegEls(o),r=this.view.pairSegsWithRows(o),this.renderHelperSegsInContainers(r,e)},r.prototype.computeInitialScroll=function(t){var e;return e=r.__super__.computeInitialScroll.apply(this,arguments),t&&(e.resourceId=t.resourceId,e.bottom=t.bottom),e},r.prototype.queryScroll=function(){var t,e,o,i,n,s,l,h;for(h=r.__super__.queryScroll.apply(this,arguments),l=this.bodyScroller.scrollEl.offset().top,n=this.view.getVisibleRows(),o=0,i=n.length;i>o;o++)if(s=n[o],s.resource&&(t=s.getTr("event"),e=t.offset().top+t.outerHeight(),e>l)){h.resourceId=s.resource.id,h.bottom=e-l;break}return h},r.prototype.setScroll=function(t){var e,o,i,n;return t.resourceId&&(n=this.view.getResourceRow(t.resourceId),n&&(e=n.getTr("event"),e&&(i=this.bodyScroller.canvas.el.offset().top,o=e.offset().top+e.outerHeight(),t.top=o-t.bottom-i))),r.__super__.setScroll.call(this,t)},r.prototype.scrollToResource=function(t){var e,r,o,i;return o=this.view.getResourceRow(t.id),o&&(e=o.getTr("event"))?(r=this.bodyScroller.canvas.el.offset().top,i=e.offset().top-r,this.bodyScroller.scrollEl.scrollTop(i)):void 0},r}(N),r=30,q=function(){function e(t){var e;this.view=t,this.isRTL=this.view.opt("isRTL"),this.givenColWidths=this.colWidths=function(){var t,r,o,i;for(o=this.view.colSpecs,i=[],t=0,r=o.length;r>t;t++)e=o[t],i.push(e.width);return i}.call(this)}return e.prototype.view=null,e.prototype.headEl=null,e.prototype.el=null,e.prototype.tbodyEl=null,e.prototype.headScroller=null,e.prototype.bodyScroller=null,e.prototype.joiner=null,e.prototype.colGroupHtml="",e.prototype.headTable=null,e.prototype.headColEls=null,e.prototype.headCellEls=null,e.prototype.bodyColEls=null,e.prototype.bodyTable=null,e.prototype.renderSkeleton=function(){return this.headScroller=new s({overflowX:"clipped-scroll",overflowY:"hidden"}),this.headScroller.canvas=new O,this.headScroller.render(),this.headScroller.canvas.contentEl.html(this.renderHeadHtml()),this.headEl.append(this.headScroller.el),this.bodyScroller=new s({overflowY:"clipped-scroll"}),this.bodyScroller.canvas=new O,this.bodyScroller.render(),this.bodyScroller.canvas.contentEl.html("<table>"+this.colGroupHtml+"<tbody/></table>"),this.tbodyEl=this.bodyScroller.canvas.contentEl.find("tbody"),this.el.append(this.bodyScroller.el),this.joiner=new A("horizontal",[this.headScroller,this.bodyScroller]),this.headTable=this.headEl.find("table"),this.headColEls=this.headEl.find("col"),this.headCellEls=this.headScroller.canvas.contentEl.find("tr:last-child th"),this.bodyColEls=this.el.find("col"),this.bodyTable=this.el.find("table"),this.colMinWidths=this.computeColMinWidths(),this.applyColWidths(),this.initColResizing()},e.prototype.renderHeadHtml=function(){var t,e,r,o,i,n,s,l,h,u,a;for(e=this.view.colSpecs,r="<table>",t="<colgroup>",s=0,h=e.length;h>s;s++)a=e[s],t+=a.isMain?'<col class="fc-main-col"/>':"<col/>";for(t+="</colgroup>",this.colGroupHtml=t,r+=t,r+="<tbody>",this.view.superHeaderText&&(r+='<tr class="fc-super"><th class="'+this.view.widgetHeaderClass+'" colspan="'+e.length+'"><div class="fc-cell-content"><span class="fc-cell-text">'+yt(this.view.superHeaderText)+"</span></div></th></tr>"),r+="<tr>",n=!0,o=l=0,u=e.length;u>l;o=++l)a=e[o],i=o===e.length-1,r+='<th class="'+this.view.widgetHeaderClass+'"><div><div class="fc-cell-content">'+(a.isMain?'<span class="fc-expander-space"><span class="fc-icon"></span></span>':"")+'<span class="fc-cell-text">'+yt(a.labelText||"")+"</span></div>"+(i?"":'<div class="fc-col-resizer"></div>')+"</div></th>";return r+="</tr>",r+="</tbody></table>"},e.prototype.givenColWidths=null,e.prototype.colWidths=null,e.prototype.colMinWidths=null,e.prototype.tableWidth=null,e.prototype.tableMinWidth=null,e.prototype.initColResizing=function(){return this.headEl.find("th .fc-col-resizer").each(function(e){return function(r,o){return o=t(o),o.on("mousedown",function(t){return e.colResizeMousedown(r,t,o)})}}(this))},e.prototype.colResizeMousedown=function(t,e,o){var i,n,s,l;return i=this.colWidths=this.queryColWidths(),i.pop(),i.push(null),l=i[t],s=Math.min(this.colMinWidths[t],r),n=new u({dragStart:function(t){return function(){return o.addClass("fc-active")}}(this),drag:function(e){return function(r,o){var n;return n=l+(e.isRTL?-r:r),n=Math.max(n,s),i[t]=n,e.applyColWidths()}}(this),dragEnd:function(t){return function(){return o.removeClass("fc-active")}}(this)}),n.startInteraction(e)},e.prototype.applyColWidths=function(){var t,e,r,o,i,n,s,l,h,u,a,c,p,d,f,g,y;for(r=this.colMinWidths,i=this.colWidths,t=!0,e=!1,y=0,u=0,p=i.length;p>u;u++)o=i[u],"number"==typeof o?y+=o:(t=!1,o&&(e=!0));for(l=e&&!this.view.isHGrouping?"auto":"",s=function(){var t,e,r;for(r=[],h=t=0,e=i.length;e>t;h=++t)o=i[h],r.push(null!=o?o:l);return r}(),g=0,h=a=0,d=s.length;d>a;h=++a)n=s[h],g+="number"==typeof n?n:r[h];for(h=c=0,f=s.length;f>c;h=++c)n=s[h],this.headColEls.eq(h).width(n),this.bodyColEls.eq(h).width(n);return this.headScroller.canvas.setMinWidth(g),this.bodyScroller.canvas.setMinWidth(g),this.tableMinWidth=g,this.tableWidth=t?y:void 0},e.prototype.computeColMinWidths=function(){var t,e,o,i,n,s;for(i=this.givenColWidths,n=[],t=e=0,o=i.length;o>e;t=++e)s=i[t],"number"==typeof s?n.push(s):n.push(parseInt(this.headColEls.eq(t).css("min-width"))||r);return n},e.prototype.queryColWidths=function(){var e,r,o,i,n;for(i=this.headCellEls,n=[],e=0,r=i.length;r>e;e++)o=i[e],n.push(t(o).outerWidth());return n},e.prototype.updateWidth=function(){return this.headScroller.updateSize(),this.bodyScroller.updateSize(),this.joiner.update(),this.follower?this.follower.update():void 0},e.prototype.headHeight=function(){var t;return t=this.headScroller.canvas.contentEl.find("table"),t.height.apply(t,arguments)},e}(),z=function(){function e(e){this.view=e,this.children=[],this.trHash={},this.trs=t()}return e.prototype.view=null,e.prototype.parent=null,e.prototype.prevSibling=null,e.prototype.children=null,e.prototype.depth=0,e.prototype.hasOwnRow=!1,e.prototype.trHash=null,e.prototype.trs=null,e.prototype.isRendered=!1,e.prototype.isExpanded=!0,e.prototype.isShown=!1,e.prototype.addChild=function(t,e){var r,o,i,n,s;for(t.remove(),r=this.children,null!=e?r.splice(e,0,t):(e=r.length,r.push(t)),t.prevSibling=e>0?r[e-1]:null,e<r.length-1&&(r[e+1].prevSibling=t),t.parent=this,t.depth=this.depth+(this.hasOwnRow?1:0),s=t.getNodes(),o=0,i=s.length;i>o;o++)n=s[o],n.added();return this.isShown&&this.isExpanded?t.show():void 0},e.prototype.removeChild=function(t){var e,r,o,i,n,s,l,h,u,a;for(e=this.children,o=!1,r=i=0,s=e.length;s>i;r=++i)if(a=e[r],a===t){o=!0;break}if(o){for(r<e.length-1&&(e[r+1].prevSibling=t.prevSibling),e.splice(r,1),t.recursivelyUnrender(),h=t.getNodes(),n=0,l=h.length;l>n;n++)u=h[n],u.removed();return t.parent=null,t.prevSibling=null,t}return!1},e.prototype.removeChildren=function(){var t,e,r,o,i,n,s;for(n=this.children,e=0,o=n.length;o>e;e++)t=n[e],t.recursivelyUnrender();for(s=this.getDescendants(),r=0,i=s.length;i>r;r++)t=s[r],t.removed();return this.children=[]},e.prototype.remove=function(){return this.parent?this.parent.removeChild(this):void 0},e.prototype.getLastChild=function(){var t;return t=this.children,t[t.length-1]},e.prototype.getPrevRow=function(){var t,e;for(e=this;e;){if(e.prevSibling)for(e=e.prevSibling;t=e.getLastChild();)e=t;else e=e.parent;if(e&&e.hasOwnRow&&e.isShown)return e}return null},e.prototype.getLeadingRow=function(){return this.hasOwnRow?this:this.isExpanded&&this.children.length?this.children[0].getLeadingRow():void 0},e.prototype.getRows=function(t){var e,r,o,i;for(null==t&&(t=[]),this.hasOwnRow&&t.push(this),i=this.children,r=0,o=i.length;o>r;r++)e=i[r],e.getRows(t);return t},e.prototype.getNodes=function(t){var e,r,o,i;for(null==t&&(t=[]),t.push(this),i=this.children,r=0,o=i.length;o>r;r++)e=i[r],e.getNodes(t);return t},e.prototype.getDescendants=function(){var t,e,r,o,i;for(t=[],i=this.children,r=0,o=i.length;o>r;r++)e=i[r],e.getNodes(t);return t},e.prototype.render=function(){var e,r,o,i,n,s,l;if(this.trHash={},s=[],this.hasOwnRow){e=this.getPrevRow(),r=this.view.tbodyHash;for(l in r)i=r[l],n=t("<tr/>"),this.trHash[l]=n,s.push(n[0]),o="render"+K(l)+"Content",this[o]&&this[o](n),e?e.trHash[l].after(n):i.prepend(n)}return this.trs=t(s).on("click",".fc-expander",Ft(this,"toggleExpanded")),this.isRendered=!0},e.prototype.unrender=function(){var e,r,o,i;if(this.isRendered){e=this.trHash;for(o in e)r=e[o],i="unrender"+K(o)+"Content",this[i]&&this[i](r);return this.trHash={},this.trs.remove(),this.trs=t(),this.isRendered=!1,this.isShown=!1,this.hidden()}},e.prototype.recursivelyUnrender=function(){var t,e,r,o,i;for(this.unrender(),o=this.children,i=[],e=0,r=o.length;r>e;e++)t=o[e],i.push(t.recursivelyUnrender());return i},e.prototype.getTr=function(t){return this.trHash[t]},e.prototype.show=function(){var t,e,r,o,i;if(!this.isShown&&(this.isRendered?this.trs.css("display",""):this.render(),this.ensureSegsRendered&&this.ensureSegsRendered(),this.isExpanded?this.indicateExpanded():this.indicateCollapsed(),this.isShown=!0,this.shown(),this.isExpanded)){for(o=this.children,i=[],e=0,r=o.length;r>e;e++)t=o[e],i.push(t.show());return i}},e.prototype.hide=function(){var t,e,r,o,i;if(this.isShown&&(this.isRendered&&this.trs.hide(),this.isShown=!1,this.hidden(),this.isExpanded)){for(o=this.children,i=[],e=0,r=o.length;r>e;e++)t=o[e],i.push(t.hide());return i}},e.prototype.expand=function(){var t,e,r,o;if(!this.isExpanded){for(this.isExpanded=!0,this.indicateExpanded(),this.view.batchRows(),o=this.children,e=0,r=o.length;r>e;e++)t=o[e],t.show();return this.view.unbatchRows(),this.animateExpand()}},e.prototype.collapse=function(){var t,e,r,o;if(this.isExpanded){for(this.isExpanded=!1,this.indicateCollapsed(),this.view.batchRows(),o=this.children,e=0,r=o.length;r>e;e++)t=o[e],t.hide();return this.view.unbatchRows()}},e.prototype.toggleExpanded=function(){return this.isExpanded?this.collapse():this.expand()},e.prototype.indicateExpanded=function(){return this.trs.find(".fc-expander .fc-icon").removeClass(this.getCollapsedIcon()).addClass(this.getExpandedIcon())},e.prototype.indicateCollapsed=function(){return this.trs.find(".fc-expander .fc-icon").removeClass(this.getExpandedIcon()).addClass(this.getCollapsedIcon())},e.prototype.enableExpanding=function(){return this.trs.find(".fc-expander-space").addClass("fc-expander")},e.prototype.disableExpanding=function(){return this.trs.find(".fc-expander-space").removeClass("fc-expander").find(".fc-icon").removeClass(this.getExpandedIcon()).removeClass(this.getCollapsedIcon())},e.prototype.getExpandedIcon=function(){return"fc-icon-down-triangle"},e.prototype.getCollapsedIcon=function(){var t;return t=this.view.isRTL?"left":"right",
|
|
"fc-icon-"+t+"-triangle"},e.prototype.animateExpand=function(){var t,e,r;return r=null!=(t=this.children[0])&&null!=(e=t.getLeadingRow())?e.trs:void 0,r?(r.addClass("fc-collapsed"),setTimeout(function(){return r.addClass("fc-transitioning"),r.removeClass("fc-collapsed")}),r.one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend",function(){return r.removeClass("fc-transitioning")})):void 0},e.prototype.getMaxTrInnerHeight=function(){var e;return e=0,t.each(this.trHash,function(t){return function(t,r){var o;return o=ct(r).find("> div:not(.fc-cell-content):first"),e=Math.max(o.height(),e)}}(this)),e},e.prototype.setTrInnerHeight=function(e){return t.each(this.trHash,function(t){return function(t,r){return ct(r).find("> div:not(.fc-cell-content):first").height(e)}}(this))},e.prototype.shown=function(){return this.hasOwnRow?this.rowShown(this):void 0},e.prototype.hidden=function(){return this.hasOwnRow?this.rowHidden(this):void 0},e.prototype.rowShown=function(t){return(this.parent||this.view).rowShown(t)},e.prototype.rowHidden=function(t){return(this.parent||this.view).rowHidden(t)},e.prototype.added=function(){return this.hasOwnRow?this.rowAdded(this):void 0},e.prototype.removed=function(){return this.hasOwnRow?this.rowRemoved(this):void 0},e.prototype.rowAdded=function(t){return(this.parent||this.view).rowAdded(t)},e.prototype.rowRemoved=function(t){return(this.parent||this.view).rowRemoved(t)},e}(),B=function(e){function r(t,e,o){this.groupSpec=e,this.groupValue=o,r.__super__.constructor.apply(this,arguments)}return kt(r,e),r.prototype.groupSpec=null,r.prototype.groupValue=null,r.prototype.rowRemoved=function(t){return r.__super__.rowRemoved.apply(this,arguments),t===this||this.children.length?void 0:this.remove()},r.prototype.renderGroupContentEl=function(){var e,r;return e=t('<div class="fc-cell-content" />').append(this.renderGroupTextEl()),r=this.groupSpec.render,"function"==typeof r&&(e=r(e,this.groupValue)||e),e},r.prototype.renderGroupTextEl=function(){var e,r;return r=this.groupValue||"",e=this.groupSpec.text,"function"==typeof e&&(r=e(r)||r),t('<span class="fc-cell-text" />').text(r)},r}(z),g=function(e){function r(){return r.__super__.constructor.apply(this,arguments)}return kt(r,e),r.prototype.hasOwnRow=!0,r.prototype.renderSpreadsheetContent=function(e){var r;return r=this.renderGroupContentEl(),r.prepend('<span class="fc-expander"><span class="fc-icon"></span></span>'),t('<td class="fc-divider" />').attr("colspan",this.view.colSpecs.length).append(t("<div/>").append(r)).appendTo(e)},r.prototype.renderEventContent=function(t){return t.append('<td class="fc-divider"> <div/> </td>')},r}(B),U=function(e){function r(){return r.__super__.constructor.apply(this,arguments)}return kt(r,e),r.prototype.rowspan=0,r.prototype.leadingTr=null,r.prototype.groupTd=null,r.prototype.rowShown=function(t){return this.rowspan+=1,this.renderRowspan(),r.__super__.rowShown.apply(this,arguments)},r.prototype.rowHidden=function(t){return this.rowspan-=1,this.renderRowspan(),r.__super__.rowHidden.apply(this,arguments)},r.prototype.renderRowspan=function(){var e;return this.rowspan?(this.groupTd||(this.groupTd=t('<td class="'+this.view.widgetContentClass+'"/>').append(this.renderGroupContentEl())),this.groupTd.attr("rowspan",this.rowspan),e=this.getLeadingRow().getTr("spreadsheet"),e!==this.leadingTr?(e&&e.prepend(this.groupTd),this.leadingTr=e):void 0):(this.groupTd&&(this.groupTd.remove(),this.groupTd=null),this.leadingTr=null)},r}(B),p=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return kt(e,t),e.prototype.hasOwnRow=!0,e.prototype.segContainerEl=null,e.prototype.segContainerHeight=null,e.prototype.innerEl=null,e.prototype.bgSegContainerEl=null,e.prototype.isSegsRendered=!1,e.prototype.bgSegs=null,e.prototype.fgSegs=null,e.prototype.renderEventContent=function(t){return t.html('<td class="'+this.view.widgetContentClass+'"> <div> <div class="fc-event-container" /> </div> </td>'),this.segContainerEl=t.find(".fc-event-container"),this.innerEl=this.bgSegContainerEl=t.find("td > div"),this.ensureSegsRendered()},e.prototype.ensureSegsRendered=function(){return this.isSegsRendered?void 0:(this.bgSegs&&this.view.timeGrid.renderFillInContainer("bgEvent",this,this.bgSegs),this.fgSegs&&this.view.timeGrid.renderFgSegsInContainers([[this,this.fgSegs]]),this.isSegsRendered=!0)},e.prototype.unrenderEventContent=function(){return this.bgSegs=null,this.fgSegs=null,this.isSegsRendered=!1},e}(z),F=function(e){function r(t,e){this.resource=e,r.__super__.constructor.apply(this,arguments)}return kt(r,e),r.prototype.resource=null,r.prototype.rowAdded=function(t){return r.__super__.rowAdded.apply(this,arguments),t!==this&&this.isRendered&&1===this.children.length?(this.enableExpanding(),this.isExpanded?this.indicateExpanded():this.indicateCollapsed()):void 0},r.prototype.rowRemoved=function(t){return r.__super__.rowRemoved.apply(this,arguments),t!==this&&this.isRendered&&!this.children.length?this.disableExpanding():void 0},r.prototype.render=function(){return r.__super__.render.apply(this,arguments),this.children.length>0?this.enableExpanding():this.disableExpanding(),this.view.trigger("resourceRender",this.resource,this.resource,this.getTr("spreadsheet").find("> td"),this.getTr("event").find("> td"))},r.prototype.renderEventContent=function(t){return r.__super__.renderEventContent.apply(this,arguments),t.attr("data-resource-id",this.resource.id)},r.prototype.renderSpreadsheetContent=function(e){var r,o,i,n,s,l,h,u,a;for(h=this.resource,l=this.view.colSpecs,n=0,s=l.length;s>n;n++)r=l[n],r.group||(i=r.field?h[r.field]||null:h,a="function"==typeof r.text?r.text(h,i):i,o=t('<div class="fc-cell-content">'+(r.isMain?this.renderGutterHtml():"")+'<span class="fc-cell-text">'+(a?yt(a):" ")+"</span></div>"),"function"==typeof r.render&&(o=r.render(h,o,i)||o),u=t('<td class="'+this.view.widgetContentClass+'"/>').append(o),r.isMain&&u.wrapInner("<div/>"),e.append(u));return e.attr("data-resource-id",h.id)},r.prototype.renderGutterHtml=function(){var t,e,r,o;for(t="",e=r=0,o=this.depth;o>r;e=r+=1)t+='<span class="fc-icon"/>';return t+='<span class="fc-expander-space"><span class="fc-icon"></span></span>'},r}(p),d.views.timeline.resourceClass=W,E=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return kt(e,t),e.mixin(L),e.prototype.timeGridClass=G,e.prototype.dayGridClass=H,e.prototype.renderHead=function(){return e.__super__.renderHead.apply(this,arguments),this.timeGrid.processHeadResourceEls(this.headContainerEl)},e.prototype.setResources=function(t){return this.timeGrid.setResources(t),this.dayGrid&&this.dayGrid.setResources(t),this.clearView(),this.displayView()},e.prototype.unsetResources=function(t){return this.clearEvents(),this.timeGrid.unsetResources(),this.dayGrid&&this.dayGrid.unsetResources(),t?void 0:(this.clearView(),this.displayView())},e}(d.AgendaView),d.views.agenda.queryResourceClass=function(t){var e;return(null!=(e=t.options.groupByResource||t.options.groupByDateAndResource)?e:1===t.duration.as("days"))?E:void 0},T=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return kt(e,t),e.mixin(L),e.prototype.dayGridClass=H,e.prototype.renderHead=function(){return e.__super__.renderHead.apply(this,arguments),this.dayGrid.processHeadResourceEls(this.headContainerEl)},e.prototype.setResources=function(t){return this.dayGrid.setResources(t),this.clearView(),this.displayView()},e.prototype.unsetResources=function(t){return this.clearEvents(),this.dayGrid.unsetResources(),t?void 0:(this.clearView(),this.displayView())},e}(d.BasicView),x=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return kt(e,t),e.mixin(L),e.prototype.dayGridClass=H,e.prototype.renderHead=function(){return e.__super__.renderHead.apply(this,arguments),this.dayGrid.processHeadResourceEls(this.headContainerEl)},e.prototype.setResources=function(t){return this.dayGrid.setResources(t),this.clearView(),this.displayView()},e.prototype.unsetResources=function(){return this.clearEvents(),this.dayGrid.unsetResources(),this.clearView(),this.displayView()},e}(d.MonthView),d.views.basic.queryResourceClass=function(t){var e;return(null!=(e=t.options.groupByResource||t.options.groupByDateAndResource)?e:1===t.duration.as("days"))?T:void 0},d.views.month.queryResourceClass=function(t){return t.options.groupByResource||t.options.groupByDateAndResource?x:void 0},C="2016-06-02",Y={years:1,weeks:1},y="http://fullcalendar.io/scheduler/license/",b=["GPL-My-Project-Is-Open-Source","CC-Attribution-NonCommercial-NoDerivatives"],xt=function(t,e){return mt(window.location.href)||St(t)||it(e)?void 0:Gt('Please use a valid license key. <a href="'+y+'">More Info</a>',e)},St=function(r){var o,i,n,s;return-1!==t.inArray(r,b)||(i=(r||"").match(/^(\d+)\-fcs\-(\d+)$/),!!(i&&10===i[1].length&&(n=e.utc(1e3*parseInt(i[2])),s=e.utc(d.mockSchedulerReleaseDate||C),s.isValid()&&(o=s.clone().subtract(Y),n.isAfter(o)))))},mt=function(t){return Boolean(t.match(/\w+\:\/\/fullcalendar\.io\/|\/demos\/[\w-]+\.html$/))},Gt=function(e,r){return r.append(t('<div class="fc-license-message" />').html(e))},void(it=function(t){return t.find(".fc-license-message").length>=1}))});var Bahmni=Bahmni||{};Bahmni.Appointments=Bahmni.Appointments||{},angular.module("bahmni.appointments",["ui.router","bahmni.common.config","bahmni.common.uiHelper","bahmni.common.i18n","bahmni.common.domain","bahmni.common.displaycontrol.patientprofile","authentication","bahmni.common.appFramework","bahmni.common.routeErrorHandler","httpErrorInterceptor","pasvaz.bindonce","infinite-scroll","bahmni.common.util","ngSanitize","pascalprecht.translate","ngCookies","bahmni.common.patient","bahmni.common.logging","ui.calendar","monospaced.elastic","ivh.treeview","ngTagsInput","ngDialog"]),angular.module("bahmni.appointments").config(["$urlRouterProvider","$stateProvider","$httpProvider","$bahmniTranslateProvider","$compileProvider",function($urlRouterProvider,$stateProvider,$httpProvider,$bahmniTranslateProvider,$compileProvider){$httpProvider.defaults.headers.common["Disable-WWW-Authenticate"]=!0,$urlRouterProvider.otherwise("/home/manage/summary"),$urlRouterProvider.when("/home/manage","/home/manage/summary"),$compileProvider.debugInfoEnabled(!1),$stateProvider.state("home",{url:"/home",abstract:!0,views:{"additional-header":{templateUrl:"views/appointmentsHeader.html",controller:"AppointmentsHeaderController"},mainContent:{template:'<div class="opd-wrapper appointments-page-wrapper"><div ui-view="content" class="opd-content-wrapper appointments-content-wrapper"></div></div>'}},data:{backLinks:[]},resolve:{initializeConfig:function(initialization,$stateParams){return initialization($stateParams.appName)}}}).state("home.manage",{url:"/manage",views:{content:{templateUrl:"views/manage/appointmentsManage.html",controller:"AppointmentsManageController"}}}).state("home.manage.summary",{url:"/summary",tabName:"summary",params:{viewDate:null},views:{"content@manage":{templateUrl:"views/manage/appointmentsSummary.html",controller:"AppointmentsSummaryController"}}}).state("home.manage.appointments",{url:"/appointments",params:{filterParams:{},isFilterOpen:!0,isSearchEnabled:!1},views:{filter:{templateUrl:"views/manage/appointmentFilter.html",controller:"AppointmentsFilterController"},"content@manage":{templateUrl:"views/manage/allAppointments.html",controller:"AllAppointmentsController"}}}).state("home.manage.appointments.calendar",{url:"/calendar",tabName:"calendar",params:{viewDate:null,doFetchAppointmentsData:!0,appointmentsData:null,weekView:!1},views:{"content@viewAppointments":{templateUrl:"views/manage/calendar/calendarView.html",controller:"AppointmentsCalendarViewController"}}}).state("home.manage.appointments.calendar.new",{url:"/new",params:{appointment:null},views:{"content@appointment":{templateUrl:"views/manage/newAppointment.html",controller:"AppointmentsCreateController"}},resolve:{appointmentContext:function(appointmentInitialization,$stateParams){return appointmentInitialization($stateParams)},appointmentCreateConfig:function(initializeConfig,appointmentConfigInitialization,appointmentContext){return appointmentConfigInitialization(appointmentContext)}}}).state("home.manage.appointments.calendar.edit",{url:"/:uuid",views:{"content@appointment":{templateUrl:"views/manage/newAppointment.html",controller:"AppointmentsCreateController"}},resolve:{appointmentContext:function(appointmentInitialization,$stateParams){return appointmentInitialization($stateParams)},appointmentCreateConfig:function(initializeConfig,appointmentConfigInitialization,appointmentContext){return appointmentConfigInitialization(appointmentContext)}}}).state("home.manage.appointments.list",{url:"/list",tabName:"list",params:{viewDate:null,patient:null,doFetchAppointmentsData:!0,appointmentsData:null},views:{"content@viewAppointments":{templateUrl:"views/manage/list/listView.html",controller:"AppointmentsListViewController"}}}).state("home.manage.appointments.list.new",{url:"/new",views:{"content@appointment":{templateUrl:"views/manage/newAppointment.html",controller:"AppointmentsCreateController"}},resolve:{appointmentContext:function(appointmentInitialization,$stateParams){return appointmentInitialization($stateParams)},appointmentCreateConfig:function(initializeConfig,appointmentConfigInitialization,appointmentContext){return appointmentConfigInitialization(appointmentContext)}}}).state("home.manage.appointments.list.edit",{url:"/:uuid",views:{"content@appointment":{templateUrl:"views/manage/newAppointment.html",controller:"AppointmentsCreateController"}},resolve:{appointmentContext:function(appointmentInitialization,$stateParams){return appointmentInitialization($stateParams)},appointmentCreateConfig:function(initializeConfig,appointmentConfigInitialization,appointmentContext){return appointmentConfigInitialization(appointmentContext)}}}).state("home.admin",{url:"/admin",abstract:!0,views:{content:{templateUrl:"views/admin/appointmentsAdmin.html"}}}).state("home.admin.service",{url:"/service",views:{"content@admin":{templateUrl:"views/admin/allAppointmentServices.html",controller:"AllAppointmentServicesController"}}}).state("home.admin.service.edit",{url:"/:uuid",views:{"content@admin":{templateUrl:"views/admin/appointmentService.html",controller:"AppointmentServiceController"}},resolve:{appointmentServiceContext:function(appointmentServiceInitialization,$stateParams){return appointmentServiceInitialization($stateParams.uuid)}}}),$bahmniTranslateProvider.init({app:"appointments",shouldMerge:!0})}]).run(["$window",function($window){moment.locale($window.localStorage.NG_TRANSLATE_LANG_KEY||"en")}]),angular.module("bahmni.appointments").factory("initialization",["authenticator","appService","spinner","configurations",function(authenticator,appService,spinner,configurations){return function(){var loadConfigPromise=function(){return configurations.load([])},initApp=function(){return appService.initApp("appointments",{app:!0,extension:!0})};return spinner.forPromise(authenticator.authenticateUser().then(initApp).then(loadConfigPromise))}}]),angular.module("bahmni.appointments").factory("appointmentServiceInitialization",["appointmentsServiceService",function(appointmentsServiceService){return function(serviceUuid){var getAppointmentService=function(){if("new"!==serviceUuid)return appointmentsServiceService.getService(serviceUuid).then(function(response){return{service:response.data}})};return getAppointmentService()}}]),angular.module("bahmni.appointments").factory("appointmentInitialization",["appointmentsService",function(appointmentsService){return function($stateParams){return $stateParams.appointment?{appointment:$stateParams.appointment}:$stateParams.uuid?appointmentsService.getAppointmentByUuid($stateParams.uuid).then(function(response){return{appointment:response.data}}):{}}}]),angular.module("bahmni.appointments").factory("appointmentConfigInitialization",["locationService","specialityService","appointmentsServiceService","providerService","appService","spinner","$q",function(locationService,specialityService,appointmentsServiceService,providerService,appService,spinner,$q){return function(appointmentContext){var init=function(){var promises=[],config={};promises.push(getAppointmentLocations(),getAllServices(),getAllProviders());var enableSpecialities=appService.getAppDescriptor().getConfigValue("enableSpecialities");return enableSpecialities&&promises.push(getAllSpecialities().then(function(response){config.specialities=response.data})),appointmentContext.appointment&&appointmentContext.appointment.service&&promises.push(getAppointmentService(appointmentContext.appointment.service.uuid).then(function(response){config.selectedService=response.data})),spinner.forPromise($q.all(promises).then(function(results){return config.locations=results[0].data.results,config.services=results[1].data,config.providers=results[2],config}))},getAppointmentLocations=function(){return locationService.getAllByTag("Appointment Location")},getAllSpecialities=function(){return specialityService.getAllSpecialities()},getAllServices=function(){return appointmentsServiceService.getAllServices()},getAllProviders=function(){var params={v:"custom:(display,person,uuid,retired,attributes:(attributeType:(display),value,voided))"};return providerService.list(params).then(function(response){return _.filter(response.data.results,function(provider){return _.find(provider.attributes,function(attribute){return!attribute.voided&&!provider.retired&&attribute.value&&attribute.attributeType.display===Bahmni.Appointments.Constants.availableForAppointments})})})},getAppointmentService=function(uuid){return appointmentsServiceService.getService(uuid)};return init()}}]);var Bahmni=Bahmni||{};Bahmni.Appointments=Bahmni.Appointments||{},Bahmni.Appointments.Constants=function(){var hostURL=Bahmni.Common.Constants.hostURL+Bahmni.Common.Constants.RESTWS_V1;return{createServiceUrl:hostURL+"/appointmentService",getServiceLoad:hostURL+"/appointmentService/load",getAllSpecialitiesUrl:hostURL+"/speciality/all",createAppointmentUrl:hostURL+"/appointment",getAppointmentsForServiceTypeUrl:hostURL+"/appointment/futureAppointmentsForServiceType/",changeAppointmentStatusUrl:hostURL+"/appointments/{{appointmentUuid}}/status-change",getAppointmentByUuid:hostURL+"/appointment/",getAllAppointmentsUrl:hostURL+"/appointment/all",searchAppointmentUrl:hostURL+"/appointment/search",searchAppointmentsUrl:hostURL+"/appointments/search",getAppointmentsSummaryUrl:hostURL+"/appointment/appointmentSummary",defaultServiceTypeDuration:15,defaultCalendarSlotLabelInterval:"01:00",defaultCalendarSlotDuration:"00:30",defaultCalendarStartTime:"08:00",defaultCalendarEndTime:"19:00",defaultExpandServiceFilter:-1,collapseServiceFilter:0,angularCalendarDaysOfWeek:[0,1,2,3,4,5,6],defaultWeekStartDayName:"Sunday",minDurationForAppointment:30,appointmentStatusList:["Scheduled","CheckedIn","Completed","Cancelled","Missed"],regexForTime:/^(?:(?:1[0-2]|0?[1-9]):[0-5]\d\s*[AaPp][Mm])?$/,privilegeManageAppointments:"app:appointments:manageAppointmentsTab",privilegeForAdmin:"app:appointments:adminTab",privilegeOwnAppointments:"Manage Own Appointments",privilegeResetAppointmentStatus:"Reset Appointment Status",availableForAppointments:"Available for appointments",weekDays:{Monday:1,Tuesday:2,Wednesday:3,Thursday:4,Friday:5,Saturday:6,Sunday:7},providerResponses:{ACCEPTED:"ACCEPTED",REJECTED:"REJECTED",TENTATIVE:"TENTATIVE",CANCELLED:"CANCELLED",AWAITING:"AWAITING"}}}(),Bahmni.Appointments.Appointment=function(){var Appointment=function(appointmentDetails){angular.extend(this,appointmentDetails)};return Appointment.create=function(appointmentDetails){var dateUtil=Bahmni.Common.Util.DateUtil,getDateTime=function(appointmentDate,givenTime){if(!appointmentDate&&!givenTime)return appointmentDate;var formattedTime=moment(givenTime,["hh:mm a"]).format("HH:mm");return dateUtil.parseServerDateToDate(dateUtil.getDateWithoutTime(appointmentDate)+" "+formattedTime)},getAppointmentProviders=function(providers){var providerList=[];return providers&&providers.forEach(function(p){void 0!=p.uuid&&providerList.push({uuid:p.uuid,response:p.response,comments:p.comments})}),providerList},appointment=new Appointment({uuid:appointmentDetails.uuid,patientUuid:appointmentDetails.patient.uuid,serviceUuid:appointmentDetails.service.uuid,serviceTypeUuid:appointmentDetails.serviceType&&appointmentDetails.serviceType.uuid,startDateTime:getDateTime(appointmentDetails.date,appointmentDetails.startTime),endDateTime:getDateTime(appointmentDetails.date,appointmentDetails.endTime),providerUuid:appointmentDetails.provider&&appointmentDetails.provider.uuid,providers:getAppointmentProviders(appointmentDetails.providers),locationUuid:appointmentDetails.location&&appointmentDetails.location.uuid,appointmentKind:appointmentDetails.appointmentKind,comments:appointmentDetails.comments});return appointment},Appointment}(),Bahmni.Appointments.AppointmentService=function(){var timeFormat="HH:mm:ss",Service=function(serviceDetails){angular.extend(this,serviceDetails)};return Service.createFromUIObject=function(serviceDetails){var dateUtil=Bahmni.Common.Util.DateUtil,getTime=function(dateTime){return dateTime?dateUtil.getDateTimeInSpecifiedFormat(dateTime,timeFormat):void 0},constructAvailabilityPerDay=function(result,availability){var selectedDays=availability.days.filter(function(day){return day.isSelected||day.uuid});return result=result.concat(selectedDays.map(function(day){return{dayOfWeek:day.dayOfWeek,uuid:day.uuid,startTime:getTime(availability.startTime),endTime:getTime(availability.endTime),maxAppointmentsLimit:availability.maxAppointmentsLimit,voided:!day.isSelected}}))},parse=function(availabilities){return availabilities?availabilities.reduce(constructAvailabilityPerDay,[]):[]},service=new Service({name:serviceDetails.name,uuid:serviceDetails.uuid,description:serviceDetails.description,durationMins:serviceDetails.durationMins,maxAppointmentsLimit:serviceDetails.maxAppointmentsLimit,color:serviceDetails.color,startTime:getTime(serviceDetails.startTime),endTime:getTime(serviceDetails.endTime),specialityUuid:serviceDetails.specialityUuid,locationUuid:serviceDetails.locationUuid,weeklyAvailability:parse(serviceDetails.weeklyAvailability),serviceTypes:serviceDetails.serviceTypes||[]});return service},Service}(),Bahmni.Appointments.AppointmentServiceViewModel=function(){var Service=function(serviceDetails){angular.extend(this,serviceDetails)},constDays=[{dayOfWeek:"SUNDAY",isSelected:!1},{dayOfWeek:"MONDAY",isSelected:!1},{dayOfWeek:"TUESDAY",isSelected:!1},{dayOfWeek:"WEDNESDAY",isSelected:!1},{dayOfWeek:"THURSDAY",isSelected:!1},{dayOfWeek:"FRIDAY",isSelected:!1},{dayOfWeek:"SATURDAY",isSelected:!1}];return Service.createFromResponse=function(serviceDetails){var getDateTime=function(time){return time?new Date("January 01, 1970 "+time):void 0},parseAvailability=function(avbsByDay){var groupedAvbs=_.groupBy(avbsByDay,function(avb){return avb.startTime+"#"+avb.endTime+"#"+avb.maxAppointmentsLimit});return Object.keys(groupedAvbs).map(function(key){var result={};result.startTime=getDateTime(groupedAvbs[key][0].startTime),result.endTime=getDateTime(groupedAvbs[key][0].endTime),result.maxAppointmentsLimit=groupedAvbs[key][0].maxAppointmentsLimit;var selectedDays=groupedAvbs[key],days=angular.copy(constDays);return selectedDays.map(function(day){var d=_.find(days,{dayOfWeek:day.dayOfWeek});d.uuid=day.uuid,d.isSelected=!0}),result.days=days,result})},service=new Service({name:serviceDetails.name,uuid:serviceDetails.uuid,description:serviceDetails.description,durationMins:serviceDetails.durationMins,maxAppointmentsLimit:serviceDetails.maxAppointmentsLimit,color:serviceDetails.color,startTime:getDateTime(serviceDetails.startTime),endTime:getDateTime(serviceDetails.endTime),specialityUuid:serviceDetails.speciality?serviceDetails.speciality.uuid:void 0,locationUuid:serviceDetails.location?serviceDetails.location.uuid:void 0,weeklyAvailability:parseAvailability(serviceDetails.weeklyAvailability)||[],serviceTypes:serviceDetails.serviceTypes||[]});return service},Service}(),Bahmni.Appointments.AppointmentViewModel=function(){var Appointment=function(appointmentDetails){angular.extend(this,appointmentDetails)};return Appointment.create=function(appointmentDetails,config){var getDateWithoutTime=function(dateTime){return dateTime?new Date(moment(dateTime)):void 0},getTimeWithoutDate=function(dateTime){return dateTime?moment(dateTime).format("hh:mm a"):void 0},parsePatient=function(patientInfo){var patient={};return patient.label=patientInfo.name+" ("+patientInfo.identifier+")",patient.uuid=patientInfo.uuid,patient},getSpecialityFromConfig=function(selectedSpeciality,config){var specialities=config.specialities;return _.find(specialities,function(speciality){return selectedSpeciality.uuid===speciality.uuid})},getLocationFromConfig=function(selectedLoc,config){var locations=config.locations;return _.find(locations,function(location){return location.uuid===selectedLoc.uuid})},getServiceFromConfig=function(selectedService,config){var services=config.services;return _.find(services,function(service){return selectedService.uuid===service.uuid})},getServiceTypeFromConfig=function(selectedServiceType,config){var serviceTypes=config.selectedService.serviceTypes;return _.find(serviceTypes,function(serviceType){return serviceType.uuid===selectedServiceType.uuid})},appointment=new Appointment({uuid:appointmentDetails.uuid,patient:appointmentDetails.patient&&parsePatient(appointmentDetails.patient),speciality:appointmentDetails.service&&getSpecialityFromConfig(appointmentDetails.service.speciality,config),service:appointmentDetails.service&&getServiceFromConfig(appointmentDetails.service,config),serviceType:appointmentDetails.serviceType&&getServiceTypeFromConfig(appointmentDetails.serviceType,config),providers:appointmentDetails.providers||[],location:appointmentDetails.location&&getLocationFromConfig(appointmentDetails.location,config),date:getDateWithoutTime(appointmentDetails.startDateTime),startTime:getTimeWithoutDate(appointmentDetails.startDateTime),endTime:getTimeWithoutDate(appointmentDetails.endDateTime),appointmentKind:appointmentDetails.appointmentKind,status:appointmentDetails.status,comments:appointmentDetails.comments});return appointment},Appointment}(),angular.module("bahmni.appointments").directive("timeValidator",function(){var DateUtil=Bahmni.Common.Util.DateUtil,isStartTimeBeforeEndTime=function(model){if(!model.startTime||!model.endTime)return!0;var timeFormat="THH:mm:ss",startTime=DateUtil.getDateTimeInSpecifiedFormat(model.startTime,timeFormat),endTime=DateUtil.getDateTimeInSpecifiedFormat(model.endTime,timeFormat);return startTime<endTime};return{restrict:"A",require:"ngModel",link:function(scope,element,attrs,ctrl){function validate(){ctrl.$setValidity("timeSequence",isStartTimeBeforeEndTime(ctrl.$viewValue))}scope.$watch(attrs.ngModel+".startTime",validate),scope.$watch(attrs.ngModel+".endTime",validate)}}}),angular.module("bahmni.appointments").directive("dayCalendar",[function(){return{restrict:"E",controller:"AppointmentsDayCalendarController",scope:{appointments:"=",date:"="},templateUrl:"../appointments/views/manage/calendar/dayCalendar.html"}}]),angular.module("bahmni.appointments").directive("weekCalendar",[function(){return{restrict:"E",controller:"AppointmentsWeekCalendarController",scope:{appointments:"=",date:"="},templateUrl:"../appointments/views/manage/calendar/weekCalendar.html"}}]),angular.module("bahmni.appointments").directive("weekdaySelector",function(){var constDays=[{dayOfWeek:"SUNDAY",isSelected:!1},{dayOfWeek:"MONDAY",isSelected:!1},{dayOfWeek:"TUESDAY",isSelected:!1},{dayOfWeek:"WEDNESDAY",isSelected:!1},{dayOfWeek:"THURSDAY",isSelected:!1},{dayOfWeek:"FRIDAY",isSelected:!1},{dayOfWeek:"SATURDAY",isSelected:!1}],template="<p class='service-ava-days' ng-class='{\"disabled\": ngDisabled===true}'><span id='day-0' ng-class='{\"is-selected\": ngModel[(0 + weekStartsIndex -1)%7].isSelected}' ng-click='onDayClicked((0 + weekStartsIndex -1)%7)'>{{constDays[(0 + weekStartsIndex -1)%7].dayOfWeek | translate}}</span><span id='day-1' ng-class='{\"is-selected\": ngModel[(1 + weekStartsIndex -1)%7].isSelected}' ng-click='onDayClicked((1 + weekStartsIndex -1)%7)'>{{constDays[(1 + weekStartsIndex -1)%7].dayOfWeek | translate}}</span><span id='day-2' ng-class='{\"is-selected\": ngModel[(2 + weekStartsIndex -1)%7].isSelected}' ng-click='onDayClicked((2 + weekStartsIndex -1)%7)'>{{constDays[(2 + weekStartsIndex -1)%7].dayOfWeek | translate}}</span><span id='day-3' ng-class='{\"is-selected\": ngModel[(3 + weekStartsIndex -1)%7].isSelected}' ng-click='onDayClicked((3 + weekStartsIndex -1)%7)'>{{constDays[(3 + weekStartsIndex -1)%7].dayOfWeek | translate}}</span><span id='day-4' ng-class='{\"is-selected\": ngModel[(4 + weekStartsIndex -1)%7].isSelected}' ng-click='onDayClicked((4 + weekStartsIndex -1)%7)'>{{constDays[(4 + weekStartsIndex -1)%7].dayOfWeek | translate}}</span><span id='day-5' ng-class='{\"is-selected\": ngModel[(5 + weekStartsIndex -1)%7].isSelected}' ng-click='onDayClicked((5 + weekStartsIndex -1)%7)'>{{constDays[(5 + weekStartsIndex -1)%7].dayOfWeek | translate}}</span><span id='day-6' ng-class='{\"is-selected\": ngModel[(6 + weekStartsIndex -1)%7].isSelected}' ng-click='onDayClicked((6 + weekStartsIndex -1)%7)'>{{constDays[(6 + weekStartsIndex -1)%7].dayOfWeek | translate}}</span></p>",link=function(scope){var init=function(){scope.constDays=constDays,scope.weekStartsIndex=scope.weekStartsIndex||1,initDays()},initDays=function(){scope.ngModel=scope.ngModel||angular.copy(scope.constDays)};scope.onDayClicked=function(dayIndex){initDays(),scope.ngDisabled||(scope.ngModel[dayIndex].isSelected=!scope.ngModel[dayIndex].isSelected,scope.ngChange&&scope.ngChange({newValue:{index:dayIndex,item:scope.ngModel[dayIndex]}}))},init()};return{restrict:"AE",scope:{ngModel:"=?",ngChange:"&",weekStartsIndex:"=",ngDisabled:"=?"},link:link,template:template}}),angular.module("bahmni.appointments").directive("serviceAvailability",["appService","confirmBox",function(appService,confirmBox){var states={NEW:0,EDIT:1,READONLY:2},constDays=[{dayOfWeek:"SUNDAY",isSelected:!1},{dayOfWeek:"MONDAY",isSelected:!1},{dayOfWeek:"TUESDAY",isSelected:!1},{dayOfWeek:"WEDNESDAY",isSelected:!1},{dayOfWeek:"THURSDAY",isSelected:!1},{dayOfWeek:"FRIDAY",isSelected:!1},{dayOfWeek:"SATURDAY",isSelected:!1}],link=function(scope){var init=function(){scope.availability=scope.availability||{},scope.startOfWeek=Bahmni.Appointments.Constants.weekDays[appService.getAppDescriptor().getConfigValue("startOfWeek")]+1||1};scope.add=function(){addOrUpdateToIndex(scope.availabilityList.length)&&(scope.availability={days:angular.copy(constDays)})},scope.clearValueIfInvalid=function(){scope.availability.maxAppointmentsLimit<0&&(scope.availability.maxAppointmentsLimit="")},scope.update=function(){var index=scope.availabilityList.indexOf(scope.backUpAvailability);addOrUpdateToIndex(index)&&(scope.state=states.READONLY)};var addOrUpdateToIndex=function(index){return scope.doesOverlap=overlapsWithExisting(index),scope.doesOverlap||(scope.availabilityList[index]=scope.availability),!scope.doesOverlap};scope.isValid=function(){var startTime=scope.availability.startTime,endTime=scope.availability.endTime;return startTime&&endTime&&startTime<endTime&&convertDaysToBinary(scope.availability.days)};var overlapsWithExisting=function(index){var avb=scope.availability;return!_.isEmpty(scope.availabilityList)&&_.some(scope.availabilityList,function(currAvb,currIndex){if(index!==currIndex)return hasCommonDays(avb,currAvb)&&hasOverlappingTimes(avb,currAvb)})},convertDaysToBinary=function(days){return parseInt(days.map(function(day){return day.isSelected?1:0}).reverse().join(""),2)},hasCommonDays=function(avb1,avb2){
|
|
var days1InBinary=convertDaysToBinary(avb1.days),days2InBinary=convertDaysToBinary(avb2.days);return 0!==(days1InBinary&days2InBinary)},hasOverlappingTimes=function(avb1,avb2){return avb1.startTime<avb2.endTime&&avb2.startTime<avb1.endTime};scope.confirmDelete=function(){var childScope={};childScope.message="CONFIRM_DELETE_AVAILABILITY",childScope.ok=deleteAvailability,childScope.cancel=cancelDelete,confirmBox({scope:childScope,actions:[{name:"cancel",display:"CANCEL_KEY"},{name:"ok",display:"OK_KEY"}],className:"ngdialog-theme-default delete-program-popup"})};var deleteAvailability=function(closeDialog){var index=scope.availabilityList.indexOf(scope.availability);scope.availabilityList.splice(index,1),closeDialog()},cancelDelete=function(closeDialog){closeDialog()};scope.cancel=function(){scope.availability=scope.backUpAvailability,scope.doesOverlap=!1,scope.state=states.READONLY},scope.enableEdit=function(){scope.backUpAvailability=scope.availability,scope.availability=angular.copy(scope.availability),scope.state=states.EDIT},scope.isNew=function(){return scope.state===states.NEW},scope.isEdit=function(){return scope.state===states.EDIT},scope.isReadOnly=function(){return scope.state===states.READONLY},init()};return{restrict:"AE",scope:{availability:"=?",availabilityList:"=",state:"=",disableMaxLoad:"="},link:link,templateUrl:"../appointments/views/admin/appointmentServiceAvailability.html"}}]),angular.module("bahmni.appointments").directive("serviceTypes",["ngDialog","messagingService","appointmentsService",function(ngDialog,messagingService,appointmentsService){var controller=function($scope){$scope.serviceType={},$scope.updateServiceTypeDuration=function(){_.isEmpty($scope.serviceType.name)?($scope.serviceType.duration=void 0,$scope.serviceTypesForm.serviceTypeName.$setValidity("uniqueServiceTypeName",!0)):$scope.serviceType.duration=$scope.serviceType.duration||Bahmni.Appointments.Constants.defaultServiceTypeDuration};var validateServiceType=function(serviceType){var nonVoidedServiceTypes=_.filter($scope.service.serviceTypes,function(serviceType){return!serviceType.voided});return!_.find(nonVoidedServiceTypes,serviceType)};$scope.addServiceType=function(serviceType){validateServiceType(serviceType)?($scope.service.serviceTypes.push({name:serviceType.name,duration:serviceType.duration?serviceType.duration:0}),$scope.serviceType={name:void 0,duration:void 0},$scope.serviceTypesForm.serviceTypeName.$setValidity("uniqueServiceTypeName",!0)):$scope.serviceTypesForm.serviceTypeName.$setValidity("uniqueServiceTypeName",!1)};var openConfirmationDialog=function(serviceType){ngDialog.openConfirm({template:"views/admin/serviceTypeDeleteConfirmation.html",scope:$scope,data:{serviceType:serviceType},closeByEscape:!0})};$scope.deleteServiceType=function(serviceType){_.isEmpty(serviceType.uuid)?openConfirmationDialog(serviceType):appointmentsService.getAppointmentsForServiceType(serviceType.uuid).then(function(response){response.data.length?messagingService.showMessage("error","APPOINTMENT_SERVICE_TYPE_DELETE_CONFIRMATION_DIALOG_MESSAGE_KEY"):openConfirmationDialog(serviceType)})},$scope.deleteServiceTypeOnConfirmation=function(serviceType){_.isEmpty(serviceType.uuid)?_.remove($scope.service.serviceTypes,serviceType):serviceType.voided=!0,ngDialog.close()},$scope.cancelTransition=function(){ngDialog.close()}};return{restrict:"E",scope:{service:"="},templateUrl:"../appointments/views/admin/serviceTypes.html",controller:controller}}]),angular.module("bahmni.appointments").directive("colorPicker",["$document",function($document){return{restrict:"E",scope:{colors:"=",selectedColor:"="},templateUrl:"../appointments/views/admin/colorPicker.html",link:function(scope){scope.showTheColorPicker=function(event){scope.showColorPicker=!scope.showColorPicker,event.stopPropagation()},scope.setColor=function(color,event){scope.selectedColor=color,scope.showColorPicker=!1,event.stopPropagation()},$document.bind("click",function(ev){scope.showColorPicker=!1,scope.$digest()})}}}]),angular.module("bahmni.appointments").directive("datePicker",function(){var controller=function($scope){var dateUtil=Bahmni.Common.Util.DateUtil,init=function(){$scope.viewDate||$scope.goToCurrent(),viewDateChange()},viewDateChange=function(){(!$scope.lastValidDate||$scope.lastValidDate&&$scope.viewDate&&$scope.lastValidDate.getTime()!==$scope.viewDate.getTime())&&($scope.lastValidDate=$scope.viewDate,$scope.onChange($scope.viewDate))};$scope.goToPrevious=function(){$scope.viewDate=$scope.viewDate&&dateUtil.subtractDays($scope.viewDate,1),viewDateChange()},$scope.goToCurrent=function(){$scope.viewDate=moment().startOf("day").toDate(),viewDateChange()},$scope.goToNext=function(){$scope.viewDate=$scope.viewDate&&dateUtil.addDays($scope.viewDate,1),viewDateChange()},$scope.keydownEvent=function(){var keyCode;event&&(keyCode=event.keyCode?event.keyCode:event.which),!keyCode||46!==keyCode&&8!==keyCode?keyCode&&13===keyCode&&viewDateChange():event.preventDefault()},$scope.dateChanged=function(){viewDateChange()},init()};return{restrict:"E",scope:{viewDate:"=",onChange:"=",lastValidDate:"=",showButtons:"="},templateUrl:"../appointments/views/manage/datePicker.html",controller:controller}}),angular.module("bahmni.appointments").directive("weekPicker",function(){var controller=function($scope){var dateUtil=Bahmni.Common.Util.DateUtil,init=function(){$scope.viewDate||$scope.setViewDateToToday()};$scope.goToPreviousWeek=function(){$scope.viewDate=$scope.viewDate&&dateUtil.subtractDays($scope.viewDate,7)},$scope.setViewDateToToday=function(){$scope.viewDate=moment().startOf("day").toDate()},$scope.goToNextWeek=function(){$scope.viewDate=$scope.viewDate&&dateUtil.addDays($scope.viewDate,7)};var setWeekStartDate=function(date){var daysToBeSubtracted=daysToSubtract(date,$scope.weekStart);$scope.weekStartDate=moment(date).subtract(daysToBeSubtracted,"days").toDate()},daysToSubtract=function(date,weekStart){return moment(date).isoWeekday()>=weekStart?moment(date).isoWeekday()-weekStart:7+moment(date).isoWeekday()-weekStart},setWeekEndDate=function(date){$scope.weekEndDate=moment($scope.weekStartDate).add(6,"days").endOf("day").toDate()};$scope.$watch("viewDate",function(viewDate){setWeekStartDate(viewDate),setWeekEndDate(viewDate),$scope.onChange($scope.weekStartDate,$scope.weekEndDate)}),init()};return{restrict:"E",scope:{viewDate:"=",onChange:"=",weekStart:"=?",showButtons:"="},templateUrl:"../appointments/views/manage/weekPicker.html",controller:controller}}),angular.module("bahmni.appointments").directive("multiSelectAutocomplete",[function(){var link=function($scope,element){$scope.focusOnTheTest=function(){var autoselectInput=$("input.input");autoselectInput[0].focus(),$scope.selectedValues=$scope.selectedValues||[]},$scope.addItem=function(item){item[item.name]=!0,$scope.selectedValues=_.union($scope.selectedValues,item,$scope.keyProperty)},$scope.removeItem=function(item){$scope.selectedValues=_.filter($scope.selectedValues,function(value){return value[$scope.keyProperty]!==item[$scope.keyProperty]})},$scope.search=function(query){var matchingAnswers=[],unselectedValues=_.xorBy($scope.inputItems,$scope.selectedValues,$scope.keyProperty);return _.forEach(unselectedValues,function(answer){"object"!=typeof answer.name&&answer.name.toLowerCase().indexOf(query.toLowerCase())!==-1&&matchingAnswers.push(answer)}),_.uniqBy(matchingAnswers,$scope.keyProperty)}};return{restrict:"E",link:link,scope:{inputItems:"=",selectedValues:"=",displayProperty:"=",keyProperty:"=",placeholder:"=",loadOnDownArrow:"=",autoCompleteMinLength:"="},templateUrl:"../appointments/views/manage/multiSelectAutocomplete.html"}}]),angular.module("bahmni.appointments").directive("patientSearch",["patientService","appointmentsService","spinner","$state",function(patientService,appointmentsService,spinner,$state){return{restrict:"E",scope:{onSearch:"="},templateUrl:"../appointments/views/manage/patientSearch.html",link:{pre:function($scope){$scope.search=function(){return spinner.forPromise(patientService.search($scope.patient).then(function(response){return response.data.pageOfResults}))},$scope.responseMap=function(data){return _.map(data,function(patientInfo){var familyName=patientInfo.familyName?" "+patientInfo.familyName:"";return patientInfo.label=patientInfo.givenName+familyName+" ("+patientInfo.identifier+")",patientInfo})},$scope.onSelectPatient=function(data){$state.params.patient=data,spinner.forPromise(appointmentsService.search({patientUuid:data.uuid}).then(function(oldAppointments){var appointmentInDESCOrderBasedOnStartDateTime=_.sortBy(oldAppointments.data,"startDateTime").reverse();$scope.onSearch(appointmentInDESCOrderBasedOnStartDateTime)}))},$state.params.isSearchEnabled&&$state.params.patient&&($scope.patient=$scope.responseMap([$state.params.patient])[0].label,$scope.onSelectPatient($state.params.patient)),$scope.$watch(function(){return $state.params.isSearchEnabled},function(isSearchEnabled){0==isSearchEnabled&&($scope.patient=null)},!0)}}}}]),angular.module("bahmni.appointments").service("appointmentsServiceService",["$http",function($http){this.save=function(service){return $http.post(Bahmni.Appointments.Constants.createServiceUrl,service,{withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.getAllServices=function(){return $http.get(Bahmni.Common.Constants.appointmentServiceUrl+"/all/default",{withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.getAllServicesWithServiceTypes=function(){return $http.get(Bahmni.Common.Constants.appointmentServiceUrl+"/all/full",{withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.getServiceLoad=function(serviceUuid,startDateTime,endDateTime){var params={uuid:serviceUuid,startDateTime:startDateTime,endDateTime:endDateTime};return $http.get(Bahmni.Appointments.Constants.getServiceLoad,{params:params,withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.getService=function(uuid){return $http.get(Bahmni.Common.Constants.appointmentServiceUrl+"?uuid="+uuid,{withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.deleteAppointmentService=function(serviceUuid){var params={uuid:serviceUuid};return $http.delete(Bahmni.Common.Constants.appointmentServiceUrl,{params:params,withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})}}]),angular.module("bahmni.appointments").service("specialityService",["$http",function($http){this.getAllSpecialities=function(){return $http.get(Bahmni.Appointments.Constants.getAllSpecialitiesUrl,{withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})}}]),angular.module("bahmni.appointments").service("appointmentsService",["$http","appService",function($http,appService){this.save=function(appointment){return $http.post(Bahmni.Appointments.Constants.createAppointmentUrl,appointment,{withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.search=function(appointment){return $http.post(Bahmni.Appointments.Constants.searchAppointmentUrl,appointment,{withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.getAppointmentsForServiceType=function(serviceTypeUuid){var params={appointmentServiceTypeUuid:serviceTypeUuid};return $http.get(Bahmni.Appointments.Constants.getAppointmentsForServiceTypeUrl,{params:params,withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.searchAppointments=function(data){return $http.post(Bahmni.Appointments.Constants.searchAppointmentsUrl,data,{withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.getAllAppointments=function(params){return $http.get(Bahmni.Appointments.Constants.getAllAppointmentsUrl,{params:params,withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.getAppointmentByUuid=function(appointmentUuid){var params={uuid:appointmentUuid};return $http.get(Bahmni.Appointments.Constants.getAppointmentByUuid,{params:params,withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.getAppointmentsSummary=function(params){return $http.get(Bahmni.Appointments.Constants.getAppointmentsSummaryUrl,{params:params,withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})},this.changeStatus=function(appointmentUuid,toStatus,onDate){var params={toStatus:toStatus,onDate:onDate},changeStatusUrl=appService.getAppDescriptor().formatUrl(Bahmni.Appointments.Constants.changeAppointmentStatusUrl,{appointmentUuid:appointmentUuid});return $http.post(changeStatusUrl,params,{withCredentials:!0,headers:{Accept:"application/json","Content-Type":"application/json"}})}}]),angular.module("bahmni.appointments").service("calendarViewPopUp",["$rootScope","ngDialog","$state","$translate","appointmentsService","confirmBox","checkinPopUp","appService","messagingService","appointmentCommonService",function($rootScope,ngDialog,$state,$translate,appointmentsService,confirmBox,checkinPopUp,appService,messagingService,appointmentCommonService){var calendarViewPopUp=function(config){var dialog,popUpScope=$rootScope.$new(),scope=config.scope,maxAppointmentProviders=appService.getAppDescriptor().getConfigValue("maxAppointmentProviders")||1,appointmentProviders=scope.appointments[0].providers,currentUserPrivileges=$rootScope.currentUser.privileges,currentProviderUuId=$rootScope.currentProvider.uuid;popUpScope.scope=scope,popUpScope.appointment=1===scope.appointments.length?scope.appointments[0]:void 0,popUpScope.manageAppointmentPrivilege=Bahmni.Appointments.Constants.privilegeManageAppointments,popUpScope.ownAppointmentPrivilege=Bahmni.Appointments.Constants.privilegeOwnAppointments,popUpScope.allowedActions=appService.getAppDescriptor().getConfigValue("allowedActions")||[],popUpScope.allowedActionsByStatus=appService.getAppDescriptor().getConfigValue("allowedActionsByStatus")||{},popUpScope.navigateTo=function(state,appointment){var params=$state.params;"edit"===state?(ngDialog.close(dialog.id,!1),params.uuid=appointment.uuid,$state.go("home.manage.appointments.calendar.edit",params,{reload:!1})):"new"===state?(ngDialog.close(dialog.id,!1),params.appointment={startDateTime:scope.appointments[0].startDateTime,endDateTime:scope.appointments[0].endDateTime,provider:scope.appointments[0].provider,appointmentKind:"Scheduled"},$state.go("home.manage.appointments.calendar.new",params,{reload:!1})):$state.go($state.current,params,{reload:!0}),popUpScope.$destroy()};var closeConfirmBox=function(closeConfirmBox){closeConfirmBox()};popUpScope.isUserAllowedToPerformEdit=function(){return appointmentCommonService.isUserAllowedToPerformEdit(appointmentProviders,currentUserPrivileges,currentProviderUuId)},popUpScope.isEditAllowed=function(){return maxAppointmentProviders>1||appointmentCommonService.isUserAllowedToPerformEdit(appointmentProviders,currentUserPrivileges,currentProviderUuId)};var changeStatus=function(appointment,toStatus,onDate,closeConfirmBox){var message=$translate.instant("APPOINTMENT_STATUS_CHANGE_SUCCESS_MESSAGE",{toStatus:toStatus});return appointmentsService.changeStatus(appointment.uuid,toStatus,onDate).then(function(){appointment.status=toStatus,closeConfirmBox(),messagingService.showMessage("info",message)})};popUpScope.checkinAppointment=function(patientAppointment){var scope=$rootScope.$new();scope.message=$translate.instant("APPOINTMENT_STATUS_CHANGE_CONFIRM_MESSAGE",{toStatus:"CheckedIn"}),scope.action=_.partial(changeStatus,patientAppointment,"CheckedIn",_),checkinPopUp({scope:scope,className:"ngdialog-theme-default app-dialog-container"})},popUpScope.confirmAction=function(appointment,toStatus){var scope={};scope.message=$translate.instant("APPOINTMENT_STATUS_CHANGE_CONFIRM_MESSAGE",{toStatus:toStatus}),scope.no=closeConfirmBox,scope.yes=_.partial(changeStatus,appointment,toStatus,void 0,_),confirmBox({scope:scope,actions:[{name:"yes",display:"YES_KEY"},{name:"no",display:"NO_KEY"}],className:"ngdialog-theme-default"})},popUpScope.isAllowedAction=function(action){return _.includes(popUpScope.allowedActions,action)},popUpScope.isValidActionAndIsUserAllowedToPerformEdit=function(appointment,action){return!!appointment&&(!!appointmentCommonService.isUserAllowedToPerformEdit(appointmentProviders,currentUserPrivileges,currentProviderUuId)&&isValidAction(appointment,action))};var isValidAction=function(appointment,action){var allowedActions=popUpScope.allowedActionsByStatus.hasOwnProperty(appointment.status)?popUpScope.allowedActionsByStatus[appointment.status]:[];return _.includes(allowedActions,action)};popUpScope.getAppointmentProviderNames=function(appointment){if(appointment.providers){var providerNames=appointment.providers.filter(function(p){return p.response!==Bahmni.Appointments.Constants.providerResponses.CANCELLED}).map(function(p){return p.name}).join(", ");return providerNames}return""},dialog=ngDialog.open({template:"../appointments/views/manage/calendar/popUp.html",scope:popUpScope,className:config.className||"ngdialog-theme-default"}),dialog.closePromise.then(function(data){data.value!==!1&&popUpScope.navigateTo("calendar")})};return calendarViewPopUp}]),angular.module("bahmni.appointments").service("appointmentCommonService",["$rootScope","ngDialog","$state","$translate","appointmentsService","confirmBox","checkinPopUp","appService","messagingService",function($rootScope,ngDialog,$state,$translate,appointmentsService,confirmBox,checkinPopUp,appService,messagingService){this.isCurrentUserHavingPrivilege=function(privilege,currentUserPrivileges){return!_.isUndefined(_.find(currentUserPrivileges,function(userPrivilege){return userPrivilege.name===privilege}))};var isOwnPrivilegedUserAllowedToPerformEdit=function(appointmentProviders,currentProviderUuId){return _.isEmpty(appointmentProviders)||!_.isUndefined(_.find(appointmentProviders,function(provider){return provider.uuid===currentProviderUuId&&"ACCEPTED"===provider.response}))||_.isUndefined(_.find(appointmentProviders,function(provider){return"ACCEPTED"==provider.response}))};this.isUserAllowedToPerformEdit=function(appointmentProviders,currentUserPrivileges,currentProviderUuId){return!!this.isCurrentUserHavingPrivilege(Bahmni.Appointments.Constants.privilegeManageAppointments,currentUserPrivileges)||!!this.isCurrentUserHavingPrivilege(Bahmni.Appointments.Constants.privilegeOwnAppointments,currentUserPrivileges)&&isOwnPrivilegedUserAllowedToPerformEdit(appointmentProviders,currentProviderUuId)}}]),angular.module("bahmni.common.uiHelper").service("checkinPopUp",["$rootScope","ngDialog",function($rootScope,ngDialog){var confirmBox=function(config){var dialog,scope=config.scope;scope.checkedInAppointment={time:moment().seconds(0).milliseconds(0).toDate()},scope.close=function(){ngDialog.close(dialog.id),scope.$destroy()},dialog=ngDialog.open({template:"../appointments/views/checkInPopUp.html",scope:scope,className:config.className||"ngdialog-theme-default"}),scope.performAction=function(){scope.action(scope.checkedInAppointment.time,scope.close)}};return confirmBox}]),angular.module("bahmni.appointments").controller("deleteAppointmentServiceController",["$scope","appointmentsServiceService","messagingService","ngDialog","$state",function($scope,appointmentsServiceService,messagingService,ngDialog,$state){$scope.service=$scope.ngDialogData.service,$scope.deleteServiceConfirmation=function(){return appointmentsServiceService.deleteAppointmentService($scope.service.uuid).then(function(){messagingService.showMessage("info","{{'APPOINTMENT_SERVICE_DELETE_SUCCESS_MESSAGE_KEY' | translate}}"),ngDialog.close(),$state.reload()},function(){ngDialog.close()})},$scope.cancelDeleteService=function(){ngDialog.close()}}]),angular.module("bahmni.appointments").controller("AppointmentsHeaderController",["$scope","$state","appService",function($scope,$state,appService){var setBackLinks=function(){var backLinks=[{label:"Home",url:"../home/",accessKey:"h",icon:"fa-home"}];backLinks.push({text:"APPOINTMENTS_MANAGE",state:"home.manage",accessKey:"M"});var enableAdminPage=appService.getAppDescriptor().getExtensionById("bahmni.appointments.admin",!0);enableAdminPage&&backLinks.push({text:"APPOINTMENTS_ADMIN",state:"home.admin.service",accessKey:"A",requiredPrivilege:Bahmni.Appointments.Constants.privilegeForAdmin}),$state.get("home").data.backLinks=backLinks},init=function(){setBackLinks()};return init()}]),angular.module("bahmni.appointments").controller("AppointmentsManageController",["$scope","$state","appService",function($scope,$state,appService){$scope.enableCalendarView=appService.getAppDescriptor().getConfigValue("enableCalendarView"),$scope.navigateTo=function(viewName){if(!isSameTab(viewName)){var stateName="home.manage."+("appointments"===viewName?getAppointmentsTab():viewName);$state.go(stateName,$state.params,{reload:!1})}};var isSameTab=function(viewName){var appointmentListTabs=["calendar","list"],isInAppointmentListTab=_.includes(appointmentListTabs,$scope.getCurrentTabName());return $scope.getCurrentTabName()===viewName||isInAppointmentListTab&&"appointments"===viewName},getAppointmentsTab=function(){return"appointments."+($scope.enableCalendarView?"calendar":"list")};$scope.getCurrentTabName=function(){return $state.current&&$state.current.tabName}}]),angular.module("bahmni.appointments").controller("AllAppointmentServicesController",["$scope","$state","$location","spinner","appointmentsServiceService","appService","ngDialog",function($scope,$state,$location,spinner,appointmentsServiceService,appService,ngDialog){$scope.enableSpecialities=appService.getAppDescriptor().getConfigValue("enableSpecialities"),$scope.createService=function(){$state.go("home.admin.service.edit",{uuid:"new"})},$scope.editService=function(uuid){$state.go("home.admin.service.edit",{uuid:uuid})},$scope.deleteAppointmentService=function(service){ngDialog.open({template:"views/admin/deleteAppointmentService.html",className:"ngdialog-theme-default",data:{service:service},controller:"deleteAppointmentServiceController"})};var init=function(){return appointmentsServiceService.getAllServices().then(function(response){$scope.appointmentServices=response.data})};return spinner.forPromise(init())}]),angular.module("bahmni.appointments").controller("AppointmentsCreateController",["$scope","$rootScope","$q","$window","$state","$translate","spinner","patientService","appointmentsService","appointmentsServiceService","messagingService","appointmentCommonService","ngDialog","appService","$stateParams","appointmentCreateConfig","appointmentContext","$http","sessionService",function($scope,$rootScope,$q,$window,$state,$translate,spinner,patientService,appointmentsService,appointmentsServiceService,messagingService,appointmentCommonService,ngDialog,appService,$stateParams,appointmentCreateConfig,appointmentContext,$http,sessionService){function setMinDuration(){$scope.minDuration=Bahmni.Appointments.Constants.minDurationForAppointment,$scope.minDuration=$scope.appointment.serviceType?$scope.appointment.serviceType.duration||$scope.minDuration:$scope.appointment.service?$scope.appointment.service.durationMins||$scope.minDuration:$scope.minDuration}$scope.isFilterOpen=$stateParams.isFilterOpen,$scope.showConfirmationPopUp=!0,$scope.enableSpecialities=appService.getAppDescriptor().getConfigValue("enableSpecialities"),$scope.enableServiceTypes=appService.getAppDescriptor().getConfigValue("enableServiceTypes"),$scope.today=Bahmni.Common.Util.DateUtil.getDateWithoutTime(Bahmni.Common.Util.DateUtil.now()),$scope.timeRegex=Bahmni.Appointments.Constants.regexForTime,$scope.warning={},$scope.minDuration=Bahmni.Appointments.Constants.minDurationForAppointment;var providerListForCurrentUser=function(providers){return appointmentCommonService.isCurrentUserHavingPrivilege(Bahmni.Appointments.Constants.privilegeManageAppointments,$rootScope.currentUser.privileges)?providers:appointmentCommonService.isCurrentUserHavingPrivilege(Bahmni.Appointments.Constants.privilegeOwnAppointments,$rootScope.currentUser.privileges)?_.filter(providers,function(provider){return provider.uuid===$rootScope.currentProvider.uuid}):providers};$scope.appointmentCreateConfig=appointmentCreateConfig,$scope.appointmentCreateConfig.providers=providerListForCurrentUser(appointmentCreateConfig.providers),$scope.enableEditService=appService.getAppDescriptor().getConfigValue("isServiceOnAppointmentEditable"),$scope.showStartTimes=[],$scope.showEndTimes=[];var patientSearchURL=appService.getAppDescriptor().getConfigValue("patientSearchUrl"),loginLocationUuid=sessionService.getLoginLocationUuid();$scope.minCharLengthToTriggerPatientSearch=appService.getAppDescriptor().getConfigValue("minCharLengthToTriggerPatientSearch")||3,$scope.maxAppointmentProviders=appService.getAppDescriptor().getConfigValue("maxAppointmentProviders")||1;var isProviderNotAvailableForAppointments=function(selectedProvider){var providers=appointmentCreateConfig.providers;return _.isUndefined(_.find(providers,function(provider){return selectedProvider.uuid===provider.uuid}))},init=function(){if(wireAutocompleteEvents(),!_.isEmpty(appointmentContext)&&!_.isEmpty(appointmentContext.appointment)&&!_.isEmpty(appointmentContext.appointment.provider)){var isProviderNotAvailable=isProviderNotAvailableForAppointments(appointmentContext.appointment.provider);isProviderNotAvailable&&(appointmentContext.appointment.provider.person={display:appointmentContext.appointment.provider.name},appointmentCreateConfig.providers.push(appointmentContext.appointment.provider))}$scope.appointment=Bahmni.Appointments.AppointmentViewModel.create(appointmentContext.appointment||{appointmentKind:"Scheduled"},appointmentCreateConfig),$scope.appointment.newProvider=null,$scope.selectedService=appointmentCreateConfig.selectedService,$scope.isPastAppointment=!!$scope.isEditMode()&&Bahmni.Common.Util.DateUtil.isBeforeDate($scope.appointment.date,moment().startOf("day")),$scope.appointment.patient&&$scope.onSelectPatient($scope.appointment.patient)};$scope.allowProviderAddition=function(){return void 0!=$scope.appointment.providers?$scope.appointment.providers.filter(function(p){return p.response!==Bahmni.Appointments.Constants.providerResponses.CANCELLED}).length<$scope.maxAppointmentProviders:$scope.maxAppointmentProviders>0},$scope.addNewProvider=function(){if(void 0==$scope.appointment.providers&&($scope.appointment.providers=[]),$scope.allowProviderAddition()){var pList=$scope.appointment.providers.filter(function(provider){return provider.uuid===$scope.appointment.newProvider.uuid});if(0===pList.length){var p={uuid:$scope.appointment.newProvider.uuid,response:Bahmni.Appointments.Constants.providerResponses.ACCEPTED,name:$scope.appointment.newProvider.name||$scope.appointment.newProvider.person.display,comments:null};$scope.appointment.providers.push(p)}1===pList.length&&(pList[0].response=Bahmni.Appointments.Constants.providerResponses.ACCEPTED)}$scope.appointment.newProvider=null},$scope.removeProviderFromAttendees=function(appProvider){var index=$scope.appointment.providers.indexOf(appProvider);index>-1&&$scope.appointment.providers.splice(index,1)},$scope.save=function(){var message;if($scope.createAppointmentForm.$invalid?message=$scope.createAppointmentForm.$error.pattern?"INVALID_TIME_ERROR_MESSAGE":"INVALID_SERVICE_FORM_ERROR_MESSAGE":moment($scope.appointment.startTime,"hh:mm a").isBefore(moment($scope.appointment.endTime,"hh:mm a"),"minutes")||(message="TIME_SEQUENCE_ERROR_MESSAGE"),message)return void messagingService.showMessage("error",message);$scope.validatedAppointment=Bahmni.Appointments.Appointment.create($scope.appointment);var conflictingAppointments=getConflictingAppointments($scope.validatedAppointment);return 0===conflictingAppointments.length?saveAppointment($scope.validatedAppointment):void $scope.displayConflictConfirmationDialog()},$scope.search=function(){var formattedUrl;if(patientSearchURL&&!_.isEmpty(patientSearchURL)){var params={loginLocationUuid:loginLocationUuid,searchValue:$scope.appointment.patient.label};formattedUrl=appService.getAppDescriptor().formatUrl(patientSearchURL,params)}return spinner.forPromise(formattedUrl?$http.get(Bahmni.Common.Constants.RESTWS_V1+formattedUrl):patientService.search($scope.appointment.patient.label)).then(function(response){return response.data.pageOfResults})},$scope.timeSource=function(){return $q(function(resolve){resolve($scope.showStartTimes)})},$scope.endTimeSlots=function(){return $q(function(resolve){resolve($scope.showEndTimes)})},$scope.onSelectPatient=function(data){return $scope.appointment.patient=data,spinner.forPromise(appointmentsService.search({patientUuid:data.uuid}).then(function(oldAppointments){$scope.patientAppointments=oldAppointments.data}))};var clearSlotsInfo=function(){delete $scope.currentLoad,delete $scope.maxAppointmentsLimit},getSlotsInfo=function(){var startDateTime,endDateTime,availabilityObject,daysOfWeek=["SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"],selectedService=$scope.selectedService,appointment=$scope.appointment;if(clearSlotsInfo(),_.isEmpty(selectedService.weeklyAvailability))moment(selectedService.startTime||"00:00","hh:mm a")<=moment(appointment.startTime,"hh:mm a")&&moment(appointment.endTime,"hh:mm a")<=moment(selectedService.endTime||"23:59","hh:mm a")&&(availabilityObject=selectedService);else{var availability=_.find(selectedService.weeklyAvailability,function(avb){return daysOfWeek[appointment.date.getDay()]===avb.dayOfWeek&&moment(avb.startTime,"hh:mm a")<=moment(appointment.startTime,"hh:mm a")&&moment(appointment.endTime,"hh:mm a")<=moment(avb.endTime,"hh:mm a")});availability&&(availabilityObject=availability,availabilityObject.durationMins=selectedService.durationMins||$scope.minDuration)}availabilityObject&&($scope.maxAppointmentsLimit=availabilityObject.maxAppointmentsLimit||calculateMaxLoadFromDuration(availabilityObject),startDateTime=getDateTime(appointment.date,availabilityObject.startTime||"00:00"),endDateTime=getDateTime(appointment.date,availabilityObject.endTime||"23:59"),appointmentsServiceService.getServiceLoad(selectedService.uuid,startDateTime,endDateTime).then(function(response){$scope.currentLoad=response.data}))},dateUtil=Bahmni.Common.Util.DateUtil,calculateMaxLoadFromDuration=function(avb){if(avb.durationMins&&avb.startTime&&avb.endTime){var startTime=moment(avb.startTime,["hh:mm a"]),endTime=moment(avb.endTime,["hh:mm a"]);return Math.round(dateUtil.diffInMinutes(startTime,endTime)/avb.durationMins)}},getDateTime=function(date,time){var formattedTime=moment(time,["hh:mm a"]).format("HH:mm");return dateUtil.parseServerDateToDate(dateUtil.getDateWithoutTime(date)+" "+formattedTime)},isAppointmentTimeWithinServiceAvailability=function(appointmentTime){return $scope.weeklyAvailabilityOnSelectedDate&&$scope.weeklyAvailabilityOnSelectedDate.length?_.find($scope.weeklyAvailabilityOnSelectedDate,function(availability){return!(moment(appointmentTime,"hh:mm a").isBefore(moment(availability.startTime,"hh:mm a"))||moment(availability.endTime,"hh:mm a").isBefore(moment(appointmentTime,"hh:mm a")))}):!$scope.allowedStartTime&&!$scope.allowedEndTime||!(moment(appointmentTime,"hh:mm a").isBefore(moment($scope.allowedStartTime,"hh:mm a"))||moment($scope.allowedEndTime,"hh:mm a").isBefore(moment(appointmentTime,"hh:mm a")))},isAppointmentStartTimeAndEndTimeWithinServiceAvailability=function(){var appointmentStartTime=$scope.appointment.startTime,appointmentEndTime=$scope.appointment.endTime;return!$scope.weeklyAvailabilityOnSelectedDate||!$scope.weeklyAvailabilityOnSelectedDate.length||_.find($scope.weeklyAvailabilityOnSelectedDate,function(availability){return moment(availability.startTime,"hh:mm a")<=moment(appointmentStartTime,"hh:mm a")&&moment(appointmentEndTime,"hh:mm a")<=moment(availability.endTime,"hh:mm a");
|
|
})},filterTimingsBasedOnInput=function(enteredNumber,allowedList){var showTimes=[];return _.each(allowedList,function(time){(time.startsWith(enteredNumber)||1===time.indexOf(enteredNumber)&&0===time.indexOf(0))&&showTimes.push(time)}),0===showTimes.length?allowedList:showTimes};$scope.onKeyDownOnStartTime=function(){$scope.showStartTimes=filterTimingsBasedOnInput($scope.appointment.startTime,$scope.startTimes)},$scope.onKeyDownOnEndTime=function(){$scope.showEndTimes=filterTimingsBasedOnInput($scope.appointment.endTime,$scope.endTimes)},$scope.onSelectStartTime=function(data){setMinDuration(),$scope.warning.startTime=!isAppointmentTimeWithinServiceAvailability($scope.appointment.startTime),moment($scope.appointment.startTime,"hh:mm a",!0).isValid()&&($scope.appointment.endTime=moment($scope.appointment.startTime,"hh:mm a").add($scope.minDuration,"m").format("hh:mm a"),$scope.onSelectEndTime())};var isSelectedSlotOutOfRange=function(){return!(!$scope.appointment.startTime||$scope.warning.appointmentDate||$scope.warning.startTime||$scope.warning.endTime)&&!isAppointmentStartTimeAndEndTimeWithinServiceAvailability()};$scope.onSelectEndTime=function(data){$scope.warning.endTime=!1,$scope.checkAvailability(),$scope.warning.endTime=!isAppointmentTimeWithinServiceAvailability($scope.appointment.endTime),$scope.warning.outOfRange=isSelectedSlotOutOfRange()};var triggerSlotCalculation=function(){$scope.appointment&&$scope.appointment.service&&$scope.appointment.date&&$scope.appointment.startTime&&$scope.appointment.endTime&&_.isEmpty($scope.selectedService.serviceTypes)&&getSlotsInfo()};$scope.responseMap=function(data){return _.map(data,function(patientInfo){return patientInfo.label=patientInfo.givenName+(patientInfo.familyName?" "+patientInfo.familyName:"")+" ("+patientInfo.identifier+")",patientInfo})};var clearAvailabilityInfo=function(){$scope.warning.appointmentDate=!1,$scope.warning.startTime=!1,$scope.warning.endTime=!1,$scope.warning.outOfRange=!1,clearSlotsInfo()};$scope.onSpecialityChange=function(){$scope.appointment.specialityUuid||delete $scope.appointment.specialityUuid,delete $scope.selectedService,delete $scope.appointment.service,delete $scope.appointment.serviceType,delete $scope.appointment.location,clearAvailabilityInfo()},$scope.onServiceChange=function(){clearAvailabilityInfo(),delete $scope.appointment.serviceType,delete $scope.weeklyAvailabilityOnSelectedDate,$scope.appointment.service&&setServiceDetails($scope.appointment.service).then(function(){$scope.onSelectStartTime()})},$scope.onServiceTypeChange=function(){$scope.appointment.serviceType&&(setMinDuration(),clearAvailabilityInfo(),$scope.onSelectStartTime())};var getWeeklyAvailabilityOnADate=function(date,weeklyAvailability){var dayOfWeek=moment(date).format("dddd").toUpperCase();return _.filter(weeklyAvailability,function(o){return o.dayOfWeek===dayOfWeek})},setServiceAvailableTimesForADate=function(date){$scope.allowedStartTime=$scope.selectedService.startTime||"12:00 am",$scope.allowedEndTime=$scope.selectedService.endTime||"11:59 pm",$scope.selectedService.weeklyAvailability&&$scope.selectedService.weeklyAvailability.length>0&&($scope.weeklyAvailabilityOnSelectedDate=getWeeklyAvailabilityOnADate(date,$scope.selectedService.weeklyAvailability),$scope.weeklyAvailabilityOnSelectedDate&&0===$scope.weeklyAvailabilityOnSelectedDate.length&&($scope.allowedStartTime=void 0,$scope.allowedEndTime=void 0))},isServiceAvailableOnWeekDate=function(dayOfWeek,weeklyAvailability){return _.find(weeklyAvailability,function(wA){return wA.dayOfWeek===dayOfWeek})};$scope.checkAvailability=function(){if($scope.warning.appointmentDate=!1,!$scope.isPastAppointment&&$scope.selectedService&&$scope.appointment.date){setServiceAvailableTimesForADate($scope.appointment.date);var allSlots,dayOfWeek=moment($scope.appointment.date).format("dddd").toUpperCase();_.isEmpty($scope.selectedService.weeklyAvailability)?allSlots=getAllSlots($scope.selectedService.startTime,$scope.selectedService.endTime,$scope.minDuration):(allSlots=getSlotsForWeeklyAvailability(dayOfWeek,$scope.selectedService.weeklyAvailability,$scope.minDuration),$scope.warning.appointmentDate=!isServiceAvailableOnWeekDate(dayOfWeek,$scope.selectedService.weeklyAvailability)),$scope.startTimes=allSlots.startTime,$scope.endTimes=allSlots.endTime,$scope.warning.endTime=!isAppointmentTimeWithinServiceAvailability($scope.appointment.endTime),$scope.warning.startTime=!isAppointmentTimeWithinServiceAvailability($scope.appointment.startTime),$scope.warning.outOfRange=isSelectedSlotOutOfRange(),triggerSlotCalculation()}};var setServiceDetails=function(service){return appointmentsServiceService.getService(service.uuid).then(function(response){$scope.selectedService=response.data,$scope.appointment.location=_.find(appointmentCreateConfig.locations,{uuid:$scope.selectedService.location.uuid}),$scope.minDuration=response.data.durationMins||Bahmni.Appointments.Constants.minDurationForAppointment})};$scope.continueWithoutSaving=function(){$scope.showConfirmationPopUp=!1,$state.go($scope.toStateConfig.toState,$scope.toStateConfig.toParams,{reload:!0}),ngDialog.close()},$scope.continueWithSaving=function(){saveAppointment($scope.validatedAppointment),ngDialog.close()},$scope.cancelTransition=function(){$scope.showConfirmationPopUp=!0,ngDialog.close()},$scope.displayConfirmationDialog=function(){ngDialog.openConfirm({template:"views/admin/appointmentServiceNavigationConfirmation.html",scope:$scope,closeByEscape:!0})},$scope.displayConflictConfirmationDialog=function(){ngDialog.openConfirm({template:"views/manage/appointmentConflictConfirmation.html",scope:$scope,closeByEscape:!0})},$scope.$on("$destroy",function(){cleanUpListenerStateChangeStart()});var getSlotsForWeeklyAvailability=function(dayOfWeek,weeklyAvailability,durationInMin){var slots={startTime:[],endTime:[]},dayAvailability=_.filter(weeklyAvailability,function(o){return o.dayOfWeek===dayOfWeek});return dayAvailability=_.sortBy(dayAvailability,"startTime"),_.each(dayAvailability,function(day){var allSlots=getAllSlots(day.startTime,day.endTime,durationInMin);slots.startTime=_.concat(slots.startTime,allSlots.startTime),slots.endTime=_.concat(slots.endTime,allSlots.endTime)}),slots},getAllSlots=function(startTimeString,endTimeString,durationInMin){startTimeString=_.isEmpty(startTimeString)?"00:00":startTimeString,endTimeString=_.isEmpty(endTimeString)?"23:59":endTimeString;for(var startTime=getFormattedTime(startTimeString),endTime=getFormattedTime(endTimeString),result=[],slots={startTime:[],endTime:[]},current=moment(startTime);current.valueOf()<=endTime.valueOf();)result.push(current.format("hh:mm a")),current.add(durationInMin,"minutes");return slots.startTime=_.slice(result,0,result.length-1),slots.endTime=_.slice(result,1),slots},getFormattedTime=function(time){return moment(time,"hh:mm a")},isFormFilled=function(){return!_.every(_.values($scope.appointment),function(value){return!value})},cleanUpListenerStateChangeStart=$scope.$on("$stateChangeStart",function(event,toState,toParams,fromState,fromParams){isFormFilled()&&$scope.showConfirmationPopUp&&(event.preventDefault(),ngDialog.close(),$scope.toStateConfig={toState:toState,toParams:toParams},$scope.displayConfirmationDialog())}),newAppointmentStartingEndingBeforeExistingAppointment=function(existingStart,newStart,newEnd){return newEnd<=existingStart},newAppointmentStartingEndingAfterExistingAppointment=function(newStart,existingStart,existingEnd){return newStart>=existingEnd},isNewAppointmentConflictingWithExistingAppointment=function(existingAppointment,newAppointment){var existingStart=moment(existingAppointment.startDateTime),existingEnd=moment(existingAppointment.endDateTime),newStart=moment(newAppointment.startDateTime),newEnd=moment(newAppointment.endDateTime);return!(newAppointmentStartingEndingBeforeExistingAppointment(existingStart,newStart,newEnd)||newAppointmentStartingEndingAfterExistingAppointment(newStart,existingStart,existingEnd))},checkForConflict=function(existingAppointment,newAppointment){var isOnSameDay=0===moment(existingAppointment.startDateTime).diff(moment(newAppointment.startDateTime),"days"),isAppointmentTimingConflicted=isNewAppointmentConflictingWithExistingAppointment(existingAppointment,newAppointment);return existingAppointment.uuid!==newAppointment.uuid&&"Cancelled"!==existingAppointment.status&&isOnSameDay&&isAppointmentTimingConflicted},getConflictingAppointments=function(appointment){return _.filter($scope.patientAppointments,function(bookedAppointment){return checkForConflict(bookedAppointment,appointment)})},saveAppointment=function(appointment){return spinner.forPromise(appointmentsService.save(appointment).then(function(){messagingService.showMessage("info","APPOINTMENT_SAVE_SUCCESS"),$scope.showConfirmationPopUp=!1;var params=$state.params;params.viewDate=moment($scope.appointment.date).startOf("day").toDate(),params.isFilterOpen=!0,params.isSearchEnabled=params.isSearchEnabled&&$scope.isEditMode(),$state.go("^",params,{reload:!0})}))},wireAutocompleteEvents=function(){$("#endTimeID").bind("focus",function(){$("#endTimeID").autocomplete("search")});var $startTimeID=$("#startTimeID");$startTimeID.bind("focus",function(){$("#startTimeID").autocomplete("search")}),$startTimeID.bind("focusout",function(){$scope.onSelectStartTime()})};$scope.isEditMode=function(){return $scope.appointment.uuid},$scope.isEditAllowed=function(){return!$scope.isPastAppointment&&("Scheduled"===$scope.appointment.status||"CheckedIn"===$scope.appointment.status)},$scope.navigateToPreviousState=function(){$state.go("^",$state.params,{reload:!0})},$scope.canManageOwnAppointmentOnly=function(){return appointmentCommonService.isCurrentUserHavingPrivilege(Bahmni.Appointments.Constants.privilegeOwnAppointments,$rootScope.currentUser.privileges)&&!appointmentCommonService.isCurrentUserHavingPrivilege(Bahmni.Appointments.Constants.privilegeManageAppointments,$rootScope.currentUser.privileges)},$scope.isUserAllowedToRemoveProvider=function(providerUuid){return(!$scope.canManageOwnAppointmentOnly()||$rootScope.currentProvider.uuid===providerUuid)&&$scope.isEditAllowed()},$scope.doesAppointmentHaveProvider=function(){return 0===$scope.appointment.providers.length||_.isUndefined(_.find($scope.appointment.providers,function(provider){return provider.response===Bahmni.Appointments.Constants.providerResponses.ACCEPTED}))};var isAppointmentWithSomeProviderButNotCurrentUser=function(){return _.isUndefined($scope.isCurrentProviderPartOfAppointment())&&!$scope.doesAppointmentHaveProvider()};$scope.isCurrentProviderPartOfAppointment=function(){return _.find($scope.appointment.providers,function(provider){return provider.uuid===$rootScope.currentProvider.uuid&&provider.response!=Bahmni.Appointments.Constants.providerResponses.CANCELLED})},$scope.isFieldEditNotAllowed=function(){return!(!$scope.canManageOwnAppointmentOnly()||!isAppointmentWithMultipleProvider()&&!isAppointmentWithSomeProviderButNotCurrentUser())||!$scope.isEditAllowed()};var isAppointmentWithMultipleProvider=function(){return $scope.appointment.providers.length>1};return init()}]),angular.module("bahmni.appointments").controller("AppointmentServiceController",["$scope","$q","spinner","$state","appointmentsServiceService","locationService","messagingService","specialityService","ngDialog","appService","appointmentServiceContext","confirmBox",function($scope,$q,spinner,$state,appointmentsServiceService,locationService,messagingService,specialityService,ngDialog,appService,appointmentServiceContext,confirmBox){$scope.showConfirmationPopUp=!0,$scope.enableSpecialities=appService.getAppDescriptor().getConfigValue("enableSpecialities"),$scope.enableServiceTypes=appService.getAppDescriptor().getConfigValue("enableServiceTypes"),$scope.enableCalendarView=appService.getAppDescriptor().getConfigValue("enableCalendarView"),$scope.colorsForAppointmentService=appService.getAppDescriptor().getConfigValue("colorsForAppointmentService");var serviceDetails=appointmentServiceContext?appointmentServiceContext.service:{};$scope.service=Bahmni.Appointments.AppointmentServiceViewModel.createFromResponse(serviceDetails),$scope.service.color=$scope.service.color||$scope.colorsForAppointmentService&&$scope.colorsForAppointmentService[0]||"#008000";var save=function(){if(clearValuesIfDisabledAndInvalid(),$scope.createServiceForm.$invalid)return void messagingService.showMessage("error","INVALID_SERVICE_FORM_ERROR_MESSAGE");var service=Bahmni.Appointments.AppointmentService.createFromUIObject($scope.service);appointmentsServiceService.save(service).then(function(){messagingService.showMessage("info","APPOINTMENT_SERVICE_SAVE_SUCCESS"),$scope.showConfirmationPopUp=!1,$state.go("home.admin.service")}),ngDialog.close()},clearValuesIfDisabledAndInvalid=function(){var form=$scope.createServiceForm;form.serviceTime.$invalid&&$scope.hasWeeklyAvailability()&&(delete $scope.service.startTime,delete $scope.service.endTime,form.serviceTime.$setValidity("timeSequence",!0)),form.serviceMaxLoad.$invalid&&($scope.hasWeeklyAvailability()||$scope.hasServiceTypes())&&(delete $scope.service.maxAppointmentsLimit,form.serviceMaxLoad.$setValidity("min",!0)),form.serviceMaxLoad.$invalid&&$scope.hasServiceTypes()&&(delete $scope.service.maxAppointmentsLimit,form.serviceMaxLoad.$setValidity("min",!0))};$scope.hasWeeklyAvailability=function(){return $scope.service.weeklyAvailability.length>0},$scope.hasServiceTypes=function(){return $scope.service.serviceTypes.length>0};var isNew=function(){return!$scope.service.uuid};$scope.confirmSave=function(){if(isNew())return void save();var childScope={};childScope.message="CONFIRM_EDIT_SERVICE_MESSAGE_KEY",childScope.cancel=cancelSave,childScope.ok=save,confirmBox({scope:childScope,actions:[{name:"cancel",display:"CANCEL_KEY"},{name:"ok",display:"OK_KEY"}],className:"ngdialog-theme-default delete-program-popup"})};var cancelSave=function(closeDialog){closeDialog()};$scope.validateServiceName=function(){$scope.createServiceForm.name.$setValidity("uniqueServiceName",isServiceNameUnique($scope.service))};var isServiceNameUnique=function(service){return!service.name||!$scope.services.some(function(existingService){var isConflictingName=existingService.name.toLowerCase()===service.name.toLowerCase();return service.uuid?isConflictingName&&service.uuid!==existingService.uuid:isConflictingName})},initAppointmentLocations=function(){return locationService.getAllByTag("Appointment Location").then(function(response){$scope.locations=response.data.results})},initSpecialities=function(){return specialityService.getAllSpecialities().then(function(response){$scope.specialities=response.data})},initServices=function(){return appointmentsServiceService.getAllServices().then(function(response){$scope.services=response.data})},init=function(){var promises=[];return promises.push(initAppointmentLocations()),promises.push(initServices()),$scope.enableSpecialities&&promises.push(initSpecialities()),spinner.forPromise($q.all(promises))};$scope.continueWithoutSaving=function(){$scope.showConfirmationPopUp=!1,$state.go($scope.toStateConfig.toState,$scope.toStateConfig.toParams),ngDialog.close()},$scope.cancelTransition=function(){$scope.showConfirmationPopUp=!0,ngDialog.close()},$scope.displayConfirmationDialog=function(){ngDialog.openConfirm({template:"views/admin/appointmentServiceNavigationConfirmation.html",scope:$scope,closeByEscape:!0})};var cleanUpListenerStateChangeStart=$scope.$on("$stateChangeStart",function(event,toState,toParams){$scope.showConfirmationPopUp&&(event.preventDefault(),ngDialog.close(),$scope.toStateConfig={toState:toState,toParams:toParams},$scope.displayConfirmationDialog())});return $scope.$on("$destroy",function(){cleanUpListenerStateChangeStart()}),init()}]),angular.module("bahmni.appointments").controller("AppointmentsDayCalendarController",["$scope","$rootScope","$state","uiCalendarConfig","appService","calendarViewPopUp","checkinPopUp",function($scope,$rootScope,$state,uiCalendarConfig,appService,calendarViewPopUp,checkinPopUp){$scope.eventSources=[];var init=function(){function isOwnAppointmentUserPrivilegedToCreateAppointment(privilege,provider){var NO_PROVIDER_UUID="no-provider-uuid";return privilege.name===Bahmni.Appointments.Constants.privilegeOwnAppointments&&(provider.uuid===NO_PROVIDER_UUID||provider.uuid===$rootScope.currentProvider.uuid)}$scope.events=$scope.appointments.events,$scope.alertOnEventClick=function(event,jsEvent,view){var checkinAppointment=function(patient,patientAppointment){checkinPopUp({scope:{patientAppointment:patientAppointment},className:"ngdialog-theme-default app-dialog-container"})};calendarViewPopUp({scope:{appointments:event.appointments,checkinAppointment:checkinAppointment,enableCreateAppointment:isSelectable()},className:"ngdialog-theme-default delete-program-popup app-dialog-container"})},$scope.alertOnDrop=function(event,delta,revertFunc,jsEvent,ui,view){$scope.alertMessage="Event Dropped to make dayDelta "+delta},$scope.alertOnResize=function(event,delta,revertFunc,jsEvent,ui,view){$scope.alertMessage="Event Resized to make dayDelta "+delta},$scope.addRemoveEventSource=function(sources,source){var canAdd=0;angular.forEach(sources,function(value,key){sources[key]===source&&(sources.splice(key,1),canAdd=1)}),0===canAdd&&sources.push(source)},$scope.remove=function(index){$scope.events.splice(index,1)},$scope.changeView=function(view,calendar){uiCalendarConfig.calendars[calendar].fullCalendar("changeView",view)};var isUserPrivilegedToCreateAppointment=function(provider){return _.find($rootScope.currentUser.privileges,function(privilege){return privilege.name===Bahmni.Appointments.Constants.privilegeManageAppointments||isOwnAppointmentUserPrivilegedToCreateAppointment(privilege,provider)})};$scope.createAppointment=function(start,end,jsEvent,view,resource){if(!resource||isUserPrivilegedToCreateAppointment(resource.provider)){var params=$state.params;params.appointment={startDateTime:start,endDateTime:end,appointmentKind:"Scheduled",provider:resource&&resource.provider},$state.go("home.manage.appointments.calendar.new",params,{reload:!1})}};var isSelectable=function(){return!Bahmni.Common.Util.DateUtil.isBeforeDate($scope.date,moment().startOf("day"))};$scope.uiConfig={calendar:{height:document.getElementsByClassName("app-calendar-container")[0].clientHeight,editable:!1,defaultDate:$scope.date,header:!1,timezone:"local",defaultView:"agendaDay",resources:$scope.appointments.resources,businessHours:{start:appService.getAppDescriptor().getConfigValue("startOfDay")||Bahmni.Appointments.Constants.defaultCalendarStartTime,end:appService.getAppDescriptor().getConfigValue("endOfDay")||Bahmni.Appointments.Constants.defaultCalendarEndTime},scrollTime:appService.getAppDescriptor().getConfigValue("startOfDay")||Bahmni.Appointments.Constants.defaultCalendarStartTime,groupByResource:!0,selectable:isSelectable(),select:$scope.createAppointment,slotLabelInterval:appService.getAppDescriptor().getConfigValue("calendarSlotLabelInterval")||Bahmni.Appointments.Constants.defaultCalendarSlotLabelInterval,slotDuration:appService.getAppDescriptor().getConfigValue("calendarSlotDuration")||Bahmni.Appointments.Constants.defaultCalendarSlotDuration,eventLimit:!0,allDaySlot:!1,allDayDefault:!1,eventClick:$scope.alertOnEventClick,eventDrop:$scope.alertOnDrop,eventResize:$scope.alertOnResize,eventRender:$scope.eventRender,schedulerLicenseKey:"GPL-My-Project-Is-Open-Source"}},$scope.eventSources=[$scope.events]},resetEvents=function(){_.isEmpty($scope.eventSources)||$scope.eventSources.splice(0,$scope.eventSources.length),_.isEmpty($scope.appointments.events)||$scope.eventSources.push($scope.appointments.events),$scope.uiConfig.calendar.resources=$scope.appointments.resources};$scope.$watch("appointments",function(newValue,oldValue){newValue!==oldValue&&resetEvents()}),init()}]),angular.module("bahmni.appointments").controller("AppointmentsWeekCalendarController",["$scope","$rootScope","$state","uiCalendarConfig","appService","calendarViewPopUp","checkinPopUp","spinner","appointmentsService","appointmentsFilter",function($scope,$rootScope,$state,uiCalendarConfig,appService,calendarViewPopUp,checkinPopUp,spinner,appointmentsService,appointmentsFilter){$scope.eventSources=[];var init=function(){function isOwnAppointmentUserPrivilegedToCreateAppointment(privilege,provider){const NO_PROVIDER_UUID="no-provider-uuid";return privilege.name===Bahmni.Appointments.Constants.privilegeOwnAppointments&&(provider.uuid===NO_PROVIDER_UUID||provider.uuid===$rootScope.currentProvider.uuid)}$scope.events=$scope.appointments.events,$scope.alertOnEventClick=function(event,jsEvent,view){var checkinAppointment=function(patient,patientAppointment){checkinPopUp({scope:{patientAppointment:patientAppointment},className:"ngdialog-theme-default app-dialog-container"})};calendarViewPopUp({scope:{appointments:event.appointments,checkinAppointment:checkinAppointment,enableCreateAppointment:!0},className:"ngdialog-theme-default delete-program-popup app-dialog-container"})},$scope.alertOnDrop=function(event,delta,revertFunc,jsEvent,ui,view){$scope.alertMessage="Event Dropped to make dayDelta "+delta},$scope.alertOnResize=function(event,delta,revertFunc,jsEvent,ui,view){$scope.alertMessage="Event Resized to make dayDelta "+delta},$scope.addRemoveEventSource=function(sources,source){var canAdd=0;angular.forEach(sources,function(value,key){sources[key]===source&&(sources.splice(key,1),canAdd=1)}),0===canAdd&&sources.push(source)},$scope.remove=function(index){$scope.events.splice(index,1)},$scope.changeView=function(view,calendar){uiCalendarConfig.calendars[calendar].fullCalendar("changeView",view)};var isUserPrivilegedToCreateAppointment=function(provider){return _.find($rootScope.currentUser.privileges,function(privilege){return privilege.name===Bahmni.Appointments.Constants.privilegeManageAppointments||isOwnAppointmentUserPrivilegedToCreateAppointment(privilege,provider)})};$scope.createAppointment=function(start,end,jsEvent,view,resource){if(!resource||isUserPrivilegedToCreateAppointment(resource.provider)){var params=$state.params;params.appointment={startDateTime:start,endDateTime:end,appointmentKind:"Scheduled",provider:resource&&resource.provider},$state.go("home.manage.appointments.calendar.new",params,{reload:!1})}},$scope.uiConfig={calendar:{height:document.getElementsByClassName("app-calendar-container")[0].clientHeight,editable:!1,defaultDate:$scope.date,header:!1,timezone:"local",defaultView:"agendaWeek",businessHours:{start:appService.getAppDescriptor().getConfigValue("startOfDay")||Bahmni.Appointments.Constants.defaultCalendarStartTime,end:appService.getAppDescriptor().getConfigValue("endOfDay")||Bahmni.Appointments.Constants.defaultCalendarEndTime,dow:Bahmni.Appointments.Constants.angularCalendarDaysOfWeek},scrollTime:appService.getAppDescriptor().getConfigValue("startOfDay")||Bahmni.Appointments.Constants.defaultCalendarStartTime,selectable:!0,selectConstraint:{start:moment().startOf("day"),end:moment().add(100,"year")},select:$scope.createAppointment,slotLabelInterval:appService.getAppDescriptor().getConfigValue("calendarSlotLabelInterval")||Bahmni.Appointments.Constants.defaultCalendarSlotLabelInterval,slotDuration:appService.getAppDescriptor().getConfigValue("calendarSlotDuration")||Bahmni.Appointments.Constants.defaultCalendarSlotDuration,eventLimit:!0,allDaySlot:!1,allDayDefault:!1,eventClick:$scope.alertOnEventClick,eventDrop:$scope.alertOnDrop,eventResize:$scope.alertOnResize,eventRender:$scope.eventRender,schedulerLicenseKey:"GPL-My-Project-Is-Open-Source",firstDay:Bahmni.Appointments.Constants.weekDays[appService.getAppDescriptor().getConfigValue("startOfWeek")]||Bahmni.Appointments.Constants.defaultWeekStartDayName}},$scope.eventSources=[$scope.events]},resetEvents=function(){_.isEmpty($scope.eventSources)||$scope.eventSources.splice(0,$scope.eventSources.length),_.isEmpty($scope.appointments.events)||$scope.eventSources.push($scope.appointments.events)};$scope.$watch("appointments",function(newValue,oldValue){newValue!==oldValue&&resetEvents()}),init()}]),angular.module("bahmni.appointments").controller("AllAppointmentsController",["$scope","$state","appService","$rootScope",function($scope,$state,appService,$rootScope){$scope.enableCalendarView=appService.getAppDescriptor().getConfigValue("enableCalendarView"),$scope.isSearchEnabled=!1,$scope.manageAppointmentPrivilege=Bahmni.Appointments.Constants.privilegeManageAppointments,$scope.ownAppointmentPrivilege=Bahmni.Appointments.Constants.privilegeOwnAppointments,$scope.navigateTo=function(viewName){$scope.currentTab=viewName;var path="home.manage.appointments."+viewName;$state.params.appointmentsData=$rootScope.appointmentsData,$state.go(path,$state.params,{reload:!1})},$scope.getCurrentAppointmentTabName=function(){return $state.current.tabName},$scope.$watch(function(){return $state.params.isSearchEnabled},function(isSearchEnabled){$scope.isSearchEnabled=isSearchEnabled},!0)}]),angular.module("bahmni.appointments").controller("AppointmentsCalendarViewController",["$scope","$state","$translate","spinner","appointmentsService","appointmentsFilter","$rootScope","$interval","appService",function($scope,$state,$translate,spinner,appointmentsService,appointmentsFilter,$rootScope,$interval,appService){var autoRefreshIntervalInSeconds=parseInt(appService.getAppDescriptor().getConfigValue("autoRefreshIntervalInSeconds")),enableAutoRefresh=!isNaN(autoRefreshIntervalInSeconds),autoRefreshStatus=!0;const SECONDS_TO_MILLISECONDS_FACTOR=1e3;var init=function(){$scope.weekView=$rootScope.weekView||$state.params.weekView,$state.params.viewDate=$state.params.viewDate||moment().startOf("day").toDate(),$scope.weekView&&($state.params.viewDate=getViewDate($state.params.viewDate)),$scope.startDate=$state.params.viewDate,$scope.$on("filterClosedOpen",function(event,args){$scope.isFilterOpen=args.filterViewStatus}),$scope.isFilterOpen=$state.params.isFilterOpen;var weekStartDay=appService.getAppDescriptor().getConfigValue("startOfWeek")||Bahmni.Appointments.Constants.defaultWeekStartDayName;$scope.weekStart=Bahmni.Appointments.Constants.weekDays[weekStartDay]},createProviderEventForAppointment=function(provider,appointment,eventList){var event={};event.resourceId=provider?provider.name:$translate.instant("NO_PROVIDER_COLUMN_KEY"),event.start=appointment.startDateTime,event.end=appointment.endDateTime,event.color=appointment.service.color,event.serviceName=appointment.service.name;var existingEvent=_.find(eventList,event),patientName=appointment.patient.name+" ("+appointment.patient.identifier+")",isBedAssigned=appointment.additionalInfo&&appointment.additionalInfo.BED_NUMBER_KEY;existingEvent?(existingEvent.title=[existingEvent.title,patientName].join(", "),existingEvent.className="appointmentIcons multiplePatients"+(isBedAssigned?" bed-accom":""),existingEvent.appointments.push(appointment)):(event.title=patientName,event.className="appointmentIcons "+appointment.status+(isBedAssigned?" bed-accom":""),event.appointments=[],event.appointments.push(appointment),eventList.push(event))};$scope.toggleWeekView=function(){$scope.weekView=!$scope.weekView,$rootScope.weekView=$scope.weekView,$state.params.weekView=$scope.weekView,fetchAppointmentsData()},$scope.getAppointmentsForDate=function(viewDate){if(!$scope.weekView){$state.params.viewDate=viewDate,$scope.shouldReload=!1;var params={forDate:viewDate};if($scope.$on("$stateChangeStart",function(event,toState,toParams){"list"!=toState.tabName||$scope.weekView||(toParams.doFetchAppointmentsData=!1)}),$state.params.doFetchAppointmentsData)return spinner.forPromise(setAppointments(params));var filteredAppointments=appointmentsFilter($state.params.appointmentsData,$state.params.filterParams);return $state.params.doFetchAppointmentsData=!0,parseAppointments(filteredAppointments,$state.params.filterParams)}},$scope.getAppointmentsForWeek=function(startDate,endDate){if($scope.weekView){$state.params.viewDate=$scope.startDate,$scope.shouldReload=!1;var data={startDate:startDate,endDate:endDate};return $state.params.doFetchAppointmentsData=!0,spinner.forPromise(setAppointments(data))}},$scope.$watch(function(){return $state.params.filterParams},function(newValue,oldValue){if(newValue!==oldValue){var filteredAppointments=appointmentsFilter($scope.allAppointmentsForDay||$state.params.appointmentsData,$state.params.filterParams);filteredAppointments&&parseAppointments(filteredAppointments,$state.params.filterParams)}},!0),$scope.hasNoAppointments=function(){return _.isEmpty($scope.providerAppointments)||_.isEmpty($scope.providerAppointments.events)};var fetchAppointmentsData=function(){var viewDate=$scope.startDate||moment().startOf("day").toDate();if($scope.weekView){var weekStartDate=getWeekStartDate(viewDate),weekEndDate=getWeekEndDate(weekStartDate);$scope.getAppointmentsForWeek(weekStartDate,weekEndDate)}else $scope.getAppointmentsForDate(viewDate)},getWeekStartDate=function(date){var daysToBeSubtracted=daysToSubtract(date,$scope.weekStart);return moment(date).subtract(daysToBeSubtracted,"days").toDate()},getWeekEndDate=function(date){return moment(date).add(6,"days").toDate()},getViewDate=function(date){var weekStartDate=getWeekStartDate(date),weekEndDate=getWeekEndDate(weekStartDate),isoWeekdayForToday=moment().isoWeekday(),weekStart=$scope.weekStart,daysBetweenTodayAndWeekStart=weekStart-isoWeekdayForToday;if(daysBetweenTodayAndWeekStart>0){var daysToSubtract=daysBetweenTodayAndWeekStart-1;return moment(weekEndDate).subtract(daysToSubtract,"days").toDate()}var daysToAdd=Math.abs(daysBetweenTodayAndWeekStart);return moment(weekStartDate).add(daysToAdd,"days").toDate()},parseAppointments=function(allAppointments,filterParams){if(allAppointments){var appointments=allAppointments.filter(function(appointment){return"Cancelled"!==appointment.status}),resources=_.chain(appointments).filter(function(appointment){return!_.isEmpty(appointment.providers)}).map(function(appointment){return appointment.providers.filter(function(p){return p.response!==Bahmni.Appointments.Constants.providerResponses.CANCELLED})}).reduce(function(list,p){return void 0!=p?list.concat(p.filter(function(pi){return!(filterParams&&!_.isEmpty(filterParams.providerUuids))||filterParams.providerUuids.find(function(uuid){return uuid===pi.uuid})})):list},[]).uniqBy("name").map(function(provider){return{id:provider.name,title:provider.name,provider:provider}}).sortBy(function(provider){return provider.id&&provider.id.toLowerCase()}).value(),hasAppointmentsWithNoProvidersSpecified=_.find(appointments,function(appointment){return _.every(appointment.providers,{response:Bahmni.Appointments.Constants.providerResponses.CANCELLED})||_.isEmpty(appointment.providers)});hasAppointmentsWithNoProvidersSpecified&&resources.push({id:$translate.instant("NO_PROVIDER_COLUMN_KEY"),title:$translate.instant("NO_PROVIDER_COLUMN_KEY"),provider:{name:$translate.instant("NO_PROVIDER_COLUMN_KEY"),display:$translate.instant("NO_PROVIDER_COLUMN_KEY"),uuid:"no-provider-uuid"}});var events=appointments.reduce(function(result,appointment){var appProviderList=appointment.providers&&!_.isEmpty(appointment.providers)?appointment.providers.filter(function(ap){return ap.response!=Bahmni.Appointments.Constants.providerResponses.CANCELLED}):[];return appProviderList.forEach(function(ap){filterParams&&!_.isEmpty(filterParams.providerUuids)?filterParams.providerUuids.find(function(uuid){return uuid===ap.uuid})&&createProviderEventForAppointment(ap,appointment,result):createProviderEventForAppointment(ap,appointment,result)}),0==appProviderList.length&&createProviderEventForAppointment(null,appointment,result),result},[]);$scope.providerAppointments={resources:resources,events:events},$scope.shouldReload=!0}},daysToSubtract=function(date,weekStart){return moment(date).isoWeekday()>=weekStart?moment(date).isoWeekday()-weekStart:7+moment(date).isoWeekday()-weekStart;
|
|
},setAppointments=function(params){return autoRefreshStatus=!1,$scope.weekView?appointmentsService.searchAppointments(params).then(resolveAppointmentsData):appointmentsService.getAllAppointments(params).then(resolveAppointmentsData)},resolveAppointmentsData=function(response){$scope.allAppointmentsForDay=response.data;var filteredAppointments=appointmentsFilter($scope.allAppointmentsForDay,$state.params.filterParams);return $rootScope.appointmentsData=filteredAppointments,autoRefreshStatus=!0,parseAppointments(filteredAppointments,$state.params.filterParams)},setAppointmentsInAutoRefresh=function(){if(autoRefreshStatus){var viewDate=$scope.startDate||moment().startOf("day").toDate(),params={forDate:viewDate};if($scope.weekView){var weekStartDate=getWeekStartDate(viewDate),weekEndDate=getWeekEndDate(weekStartDate);params={startDate:weekStartDate,endDate:weekEndDate}}setAppointments(params)}},autoRefresh=function(){if(enableAutoRefresh){var autoRefreshIntervalInMilliSeconds=autoRefreshIntervalInSeconds*SECONDS_TO_MILLISECONDS_FACTOR;return $interval(setAppointmentsInAutoRefresh,autoRefreshIntervalInMilliSeconds)}}();return $scope.$on("$destroy",function(){enableAutoRefresh&&$interval.cancel(autoRefresh)}),init()}]),angular.module("bahmni.appointments").controller("AppointmentsListViewController",["$scope","$state","$rootScope","$translate","$stateParams","spinner","appointmentsService","appService","appointmentsFilter","printer","checkinPopUp","confirmBox","ngDialog","messagingService","appointmentCommonService","$interval",function($scope,$state,$rootScope,$translate,$stateParams,spinner,appointmentsService,appService,appointmentsFilter,printer,checkinPopUp,confirmBox,ngDialog,messagingService,appointmentCommonService,$interval){$scope.enableSpecialities=appService.getAppDescriptor().getConfigValue("enableSpecialities"),$scope.enableServiceTypes=appService.getAppDescriptor().getConfigValue("enableServiceTypes"),$scope.allowedActions=appService.getAppDescriptor().getConfigValue("allowedActions")||[],$scope.allowedActionsByStatus=appService.getAppDescriptor().getConfigValue("allowedActionsByStatus")||{},$scope.colorsForListView=appService.getAppDescriptor().getConfigValue("colorsForListView")||{};var maxAppointmentProviders=appService.getAppDescriptor().getConfigValue("maxAppointmentProviders")||1;$scope.enableResetAppointmentStatuses=appService.getAppDescriptor().getConfigValue("enableResetAppointmentStatuses"),$scope.manageAppointmentPrivilege=Bahmni.Appointments.Constants.privilegeManageAppointments,$scope.ownAppointmentPrivilege=Bahmni.Appointments.Constants.privilegeOwnAppointments,$scope.resetAppointmentStatusPrivilege=Bahmni.Appointments.Constants.privilegeResetAppointmentStatus,$scope.searchedPatient=!1,$scope.additionalInfoColumns=appService.getAppDescriptor().getConfigValue("additionalInfoColumns")||{};var autoRefreshIntervalInSeconds=parseInt(appService.getAppDescriptor().getConfigValue("autoRefreshIntervalInSeconds")),enableAutoRefresh=!isNaN(autoRefreshIntervalInSeconds),autoRefreshStatus=!0;const SECONDS_TO_MILLISECONDS_FACTOR=1e3;var oldPatientData=[],currentUserPrivileges=$rootScope.currentUser.privileges,currentProviderUuId=$rootScope.currentProvider.uuid;$scope.$on("filterClosedOpen",function(event,args){$scope.isFilterOpen=args.filterViewStatus});var init=function(){$scope.searchedPatient=$stateParams.isSearchEnabled&&$stateParams.patient,$scope.startDate=$stateParams.viewDate||moment().startOf("day").toDate(),$scope.isFilterOpen=$stateParams.isFilterOpen},buildTableHeader=function(){$scope.tableInfo=[{heading:"APPOINTMENT_PATIENT_ID",sortInfo:"patient.identifier",enable:!0},{heading:"APPOINTMENT_PATIENT_NAME",sortInfo:"patient.name",class:!0,enable:!0},{heading:"APPOINTMENT_DATE",sortInfo:"date",enable:!0},{heading:"APPOINTMENT_START_TIME_KEY",sortInfo:"startDateTime",enable:!0},{heading:"APPOINTMENT_END_TIME_KEY",sortInfo:"endDateTime",enable:!0},{heading:"APPOINTMENT_PROVIDER",sortInfo:"provider.name",class:!0,enable:!0},{heading:"APPOINTMENT_SERVICE_SPECIALITY_KEY",sortInfo:"service.speciality.name",enable:$scope.enableSpecialities},{heading:"APPOINTMENT_SERVICE",sortInfo:"service.name",class:!0,enable:!0},{heading:"APPOINTMENT_SERVICE_TYPE_FULL",sortInfo:"serviceType.name",class:!0,enable:$scope.enableServiceTypes},{heading:"APPOINTMENT_STATUS",sortInfo:"status",enable:!0},{heading:"APPOINTMENT_WALK_IN",sortInfo:"appointmentKind",enable:!0},{heading:"APPOINTMENT_SERVICE_LOCATION_KEY",sortInfo:"location.name",class:!0,enable:!0},{heading:"APPOINTMENT_CREATE_NOTES",sortInfo:"comments",enable:!0}],$scope.additionalInfoColumns.length>0?$scope.tableInfo.splice($scope.tableInfo.length-1,0,{heading:"APPOINTMENT_ADDITIONAL_INFO",sortInfo:"additionalInfo",class:!0,enable:!0}):_.forEach($scope.additionalInfoColumns,function(key,value){var str=value.replace(/ +/g,"");$scope.tableInfo.splice($scope.tableInfo.length-1,0,{heading:"APPOINTMENT_ADDITIONAL_INFO_COLUMN_"+str.toUpperCase(),sortInfo:value,class:!0,enable:!0})})},setAppointments=function(params){return autoRefreshStatus=!1,appointmentsService.getAllAppointments(params).then(function(response){$scope.appointments=response.data,$scope.filteredAppointments=appointmentsFilter($scope.appointments,$stateParams.filterParams),$rootScope.appointmentsData=$scope.filteredAppointments,updateSelectedAppointment(),autoRefreshStatus=!0})},updateSelectedAppointment=function(){void 0!==$scope.selectedAppointment&&($scope.selectedAppointment=_.find($scope.filteredAppointments,function(appointment){return appointment.uuid===$scope.selectedAppointment.uuid}))},setAppointmentsInPatientSearch=function(patientUuid){appointmentsService.search({patientUuid:patientUuid}).then(function(response){var appointmentsInDESCOrderBasedOnStartDateTime=_.sortBy(response.data,"startDateTime").reverse();setFilteredAppointmentsInPatientSearch(appointmentsInDESCOrderBasedOnStartDateTime)})},setAppointmentsInAutoRefresh=function(){if(autoRefreshStatus)if($stateParams.isSearchEnabled)setAppointmentsInPatientSearch($stateParams.patient.uuid);else{var viewDate=$state.params.viewDate||moment().startOf("day").toDate();setAppointments({forDate:viewDate})}},autoRefresh=function(){if(enableAutoRefresh){var autoRefreshIntervalInMilliSeconds=autoRefreshIntervalInSeconds*SECONDS_TO_MILLISECONDS_FACTOR;return $interval(setAppointmentsInAutoRefresh,autoRefreshIntervalInMilliSeconds)}}();$scope.$on("$destroy",function(){enableAutoRefresh&&$interval.cancel(autoRefresh)}),$scope.getAppointmentsForDate=function(viewDate){$stateParams.viewDate=viewDate,$scope.selectedAppointment=void 0;var params={forDate:viewDate};$scope.$on("$stateChangeStart",function(event,toState,toParams){"calendar"==toState.tabName&&(toParams.doFetchAppointmentsData=!1)}),$state.params.doFetchAppointmentsData?spinner.forPromise(setAppointments(params)):($scope.filteredAppointments=appointmentsFilter($state.params.appointmentsData,$stateParams.filterParams),$state.params.doFetchAppointmentsData=!0)},$scope.getProviderNamesForAppointment=function(appointment){return void 0!=appointment.providers?appointment.providers.filter(function(p){return"CANCELLED"!=p.response}).map(function(p){return p.name}).join(","):""};var setFilteredAppointmentsInPatientSearch=function(appointments){$scope.filteredAppointments=appointments.map(function(appointmet){return appointmet.date=appointmet.startDateTime,appointmet})};$scope.displaySearchedPatient=function(appointments){oldPatientData=$scope.filteredAppointments,setFilteredAppointmentsInPatientSearch(appointments),$scope.searchedPatient=!0,$stateParams.isFilterOpen=!1,$scope.isFilterOpen=!1,$stateParams.isSearchEnabled=!0,$scope.selectedAppointment=void 0},$scope.hasNoAppointments=function(){return _.isEmpty($scope.filteredAppointments)},$scope.hasAdditionalInfoColumnsEntered=function(){return _.isEmpty($scope.additionalInfoColumns)},$scope.goBackToPreviousView=function(){$scope.searchedPatient=!1,$scope.filteredAppointments=oldPatientData,$stateParams.isFilterOpen=!0,$scope.isFilterOpen=!0,$stateParams.isSearchEnabled=!1},$scope.isSelected=function(appointment){return $scope.selectedAppointment===appointment},$scope.select=function(appointment){return $scope.isSelected(appointment)?void($scope.selectedAppointment=void 0):void($scope.selectedAppointment=appointment)},$scope.isWalkIn=function(appointmentType){return"WalkIn"===appointmentType?"Yes":"No"},$scope.editAppointment=function(){var params=$stateParams;params.uuid=$scope.selectedAppointment.uuid,$state.go("home.manage.appointments.list.edit",params)},$scope.checkinAppointment=function(){var scope=$rootScope.$new();scope.message=$translate.instant("APPOINTMENT_STATUS_CHANGE_CONFIRM_MESSAGE",{toStatus:"CheckedIn"}),scope.action=_.partial(changeStatus,"CheckedIn",_),checkinPopUp({scope:scope,className:"ngdialog-theme-default app-dialog-container"})},$scope.$watch(function(){return $stateParams.filterParams},function(newValue,oldValue){newValue!==oldValue&&($scope.filteredAppointments=appointmentsFilter($scope.appointments||$state.params.appointmentsData,$stateParams.filterParams))},!0),$scope.sortAppointmentsBy=function(sortColumn){"additionalInfo"===sortColumn&&($scope.filteredAppointments=$scope.filteredAppointments.map(function(appointment){return appointment.additionalInformation=$scope.display(_.get(appointment,sortColumn)),appointment}),sortColumn="additionalInformation");var emptyObjects=_.filter($scope.filteredAppointments,function(appointment){return!_.property(sortColumn)(appointment)});_.includes($scope.additionalInfoColumns,sortColumn)&&(emptyObjects=_.filter($scope.filteredAppointments,function(appointment){return!_.property(sortColumn)(appointment.additionalInfo)})),"provider.name"===sortColumn&&(emptyObjects=$scope.filteredAppointments.filter(function(fa){return _.every(fa.providers,{response:Bahmni.Appointments.Constants.providerResponses.CANCELLED})||_.isEmpty(fa.providers)}));var nonEmptyObjects=_.difference($scope.filteredAppointments,emptyObjects),sortedNonEmptyObjects=_.sortBy(nonEmptyObjects,function(appointment){if("provider.name"===sortColumn){var firstProvider=appointment.providers.find(function(p){return p.response!==Bahmni.Appointments.Constants.providerResponses.CANCELLED});return firstProvider.name.toLowerCase()}return angular.isNumber(_.get(appointment,sortColumn))?_.get(appointment,sortColumn):_.includes($scope.additionalInfoColumns,sortColumn)?_.get(appointment.additionalInfo,sortColumn).toLowerCase():_.get(appointment,sortColumn).toLowerCase()});$scope.reverseSort&&sortedNonEmptyObjects.reverse(),$scope.filteredAppointments=sortedNonEmptyObjects.concat(emptyObjects),$scope.sortColumn=sortColumn,$scope.reverseSort=!$scope.reverseSort},$scope.printPage=function(){var printTemplateUrl=appService.getAppDescriptor().getConfigValue("printListViewTemplateUrl")||"views/manage/list/defaultListPrint.html";printer.print(printTemplateUrl,{searchedPatient:$scope.searchedPatient,filteredAppointments:$scope.filteredAppointments,startDate:$stateParams.viewDate,enableServiceTypes:$scope.enableServiceTypes,enableSpecialities:$scope.enableSpecialities})},$scope.undoCheckIn=function(){var scope={};scope.message=$translate.instant("APPOINTMENT_UNDO_CHECKIN_CONFIRM_MESSAGE"),scope.yes=resetStatus,showPopUp(scope)};var resetStatus=function(closeConfirmBox){return appointmentsService.changeStatus($scope.selectedAppointment.uuid,"Scheduled",null).then(function(response){$scope.selectedAppointment.status=response.data.status;var message=$translate.instant("APPOINTMENT_STATUS_CHANGE_SUCCESS_MESSAGE",{toStatus:response.data.status});closeConfirmBox(),messagingService.showMessage("info",message)})};$scope.reset=function(){var scope={};scope.message=$translate.instant("APPOINTMENT_RESET_CONFIRM_MESSAGE"),scope.yes=resetStatus,showPopUp(scope)};var changeStatus=function(toStatus,onDate,closeConfirmBox){var message=$translate.instant("APPOINTMENT_STATUS_CHANGE_SUCCESS_MESSAGE",{toStatus:toStatus});return appointmentsService.changeStatus($scope.selectedAppointment.uuid,toStatus,onDate).then(function(response){ngDialog.close(),$scope.selectedAppointment.status=response.data.status,closeConfirmBox(),messagingService.showMessage("info",message)})};$scope.confirmAction=function(toStatus){var scope={};scope.message=$translate.instant("APPOINTMENT_STATUS_CHANGE_CONFIRM_MESSAGE",{toStatus:toStatus}),scope.yes=_.partial(changeStatus,toStatus,void 0,_),showPopUp(scope)},$scope.displayNewColumns=function(jsonObj,columnName){if(null!=jsonObj)return jsonObj[columnName]},$scope.display=function(jsonObj){if(jsonObj=_.mapKeys(jsonObj,function(value,key){return $translate.instant(key)}),_.isEmpty($scope.additionalInfoColumns)){var colList=[];return angular.forEach(jsonObj,function(value,key){_.includes($scope.additionalInfoColumns,key)||colList.push(jsonObj[value])}),Object.values(colList).join(", ")}return JSON.stringify(jsonObj||"").replace(/[{\"}]/g,"").replace(/[,]/g,",\t")};var showPopUp=function(popUpScope){popUpScope.no=function(closeConfirmBox){closeConfirmBox()},confirmBox({scope:popUpScope,actions:[{name:"yes",display:"YES_KEY"},{name:"no",display:"NO_KEY"}],className:"ngdialog-theme-default"})};$scope.isAllowedAction=function(action){return _.includes($scope.allowedActions,action)},$scope.isValidActionAndIsUserAllowedToPerformEdit=function(action){if(!_.isUndefined($scope.selectedAppointment)){var appointmentProvider=$scope.selectedAppointment.providers;return!!appointmentCommonService.isUserAllowedToPerformEdit(appointmentProvider,currentUserPrivileges,currentProviderUuId)&&isValidAction(action)}return!1};var isValidAction=function(action){var status=$scope.selectedAppointment.status,allowedActions=$scope.allowedActionsByStatus.hasOwnProperty(status)?$scope.allowedActionsByStatus[status]:[];return _.includes(allowedActions,action)},isCurrentUserHavePrivilege=function(privilege){return!_.isUndefined(_.find($rootScope.currentUser.privileges,function(userPrivilege){return userPrivilege.name===privilege}))};$scope.isUserAllowedToPerform=function(){return!!isCurrentUserHavePrivilege($scope.manageAppointmentPrivilege)||!(!isCurrentUserHavePrivilege($scope.ownAppointmentPrivilege)||!$scope.selectedAppointment)&&(_.isNull($scope.selectedAppointment.provider)||$scope.selectedAppointment.provider.uuid===$rootScope.currentProvider.uuid)},$scope.isUndoCheckInAllowed=function(){return $scope.isUserAllowedToPerform()&&isCurrentUserHavePrivilege($scope.resetAppointmentStatusPrivilege)&&$scope.selectedAppointment&&"CheckedIn"===$scope.selectedAppointment.status},$scope.isEditAllowed=function(){if(!_.isUndefined($scope.selectedAppointment)){var appointmentProvider=$scope.selectedAppointment.providers;return maxAppointmentProviders>1||appointmentCommonService.isUserAllowedToPerformEdit(appointmentProvider,currentUserPrivileges,currentProviderUuId)}return!1},$scope.isResetAppointmentStatusFeatureEnabled=function(){return!(_.isNull($scope.enableResetAppointmentStatuses)||_.isUndefined($scope.enableResetAppointmentStatuses))};var isSelectedAppointmentStatusAllowedToReset=function(){return _.isArray($scope.enableResetAppointmentStatuses)&&_.includes($scope.enableResetAppointmentStatuses,$scope.selectedAppointment.status)};$scope.isResetAppointmentStatusAllowed=function(){return $scope.isUserAllowedToPerform()&&isCurrentUserHavePrivilege($scope.resetAppointmentStatusPrivilege)&&$scope.selectedAppointment&&"Scheduled"!=$scope.selectedAppointment.status&&isSelectedAppointmentStatusAllowedToReset()},init(),buildTableHeader()}]),angular.module("bahmni.appointments").controller("AppointmentsSummaryController",["$scope","$state","$window","spinner","appointmentsService","appService",function($scope,$state,$window,spinner,appointmentsService,appService){var init=function(){$scope.viewDate=$state.params.viewDate||moment().startOf("day").toDate();var weekStartDay=appService.getAppDescriptor().getConfigValue("startOfWeek")||Bahmni.Appointments.Constants.defaultWeekStartDayName;$scope.weekStart=Bahmni.Appointments.Constants.weekDays[weekStartDay]};$scope.getAppointmentsSummaryForAWeek=function(startDate,endDate){$scope.weekStartDate=startDate,$scope.weekEndDate=endDate;var params={startDate:startDate,endDate:endDate};spinner.forPromise(appointmentsService.getAppointmentsSummary(params).then(function(response){$scope.appointments=response.data,setWeekDatesInfo()})),$state.params.viewDate=$scope.viewDate},$scope.goToListView=function(date,service){var params={viewDate:moment(date).toDate(),filterParams:{statusList:_.without(Bahmni.Appointments.Constants.appointmentStatusList,"Cancelled")}};_.isUndefined(service)||(params.filterParams.serviceUuids=[service.uuid]),$state.go("home.manage.appointments.list",params)},$scope.isCurrentDate=function(date){return moment(date).format("YYYY-MM-DD")===moment().format("YYYY-MM-DD")};var setWeekDatesInfo=function(){$scope.weekDatesInfo=[];for(var i=$scope.weekStartDate;Bahmni.Common.Util.DateUtil.isBeforeDate(i,$scope.weekEndDate);i=Bahmni.Common.Util.DateUtil.addDays(i,1)){var weekDate={date:moment(i).format("YYYY-MM-DD")};weekDate.total=_.reduce($scope.appointments,function(total,appointment){var appointmentCount=appointment.appointmentCountMap[weekDate.date];return appointmentCount?{all:appointmentCount.allAppointmentsCount+total.all,missed:appointmentCount.missedAppointmentsCount+total.missed}:total},{all:0,missed:0}),$scope.weekDatesInfo.push(weekDate)}};return init()}]),angular.module("bahmni.appointments").controller("AppointmentsFilterController",["$scope","$state","$rootScope","$q","$translate","appointmentsServiceService","spinner","ivhTreeviewMgr","providerService","appService",function($scope,$state,$rootScope,$q,$translate,appointmentsServiceService,spinner,ivhTreeviewMgr,providerService,appService){var init=function(){$scope.isSpecialityEnabled=appService.getAppDescriptor().getConfigValue("enableSpecialities"),$scope.isServiceTypeEnabled=appService.getAppDescriptor().getConfigValue("enableServiceTypes"),$scope.isFilterOpen=$state.params.isFilterOpen,$scope.expandToDepth=1==appService.getAppDescriptor().getConfigValue("collapseServiceFilter")?Bahmni.Appointments.Constants.collapseServiceFilter:Bahmni.Appointments.Constants.defaultExpandServiceFilter,$scope.isSearchEnabled=$state.params.isSearchEnabled,$scope.statusList=_.map(Bahmni.Appointments.Constants.appointmentStatusList,function(status){return{name:status,value:status}}),$scope.selectedStatusList=_.filter($scope.statusList,function(status){return _.includes($state.params.filterParams.statusList,status.value)}),"calendar"===$state.current.tabName&&($scope.statusList=_.filter($scope.statusList,function(status){return"Cancelled"!==status.name}));var params={v:"custom:(display,person,uuid,retired,attributes:(attributeType:(display),value,voided))"};$scope.$watch("selectedProviders",function(selectedProviders){_.isUndefined($scope.selectedSpecialities)||$scope.applyFilter()}),$scope.$watch("selectedStatusList",function(selectedStatusList){_.isUndefined($scope.selectedSpecialities)||$scope.applyFilter()}),spinner.forPromise($q.all([appointmentsServiceService.getAllServicesWithServiceTypes(),providerService.list(params)]).then(function(response){$scope.providers=_.filter(response[1].data.results,function(provider){return _.find(provider.attributes,function(attribute){return!attribute.voided&&!provider.retired&&attribute.value&&attribute.attributeType.display===Bahmni.Appointments.Constants.availableForAppointments})}).map(function(provider){return provider.name=provider.person.display,provider}),$scope.providers.push({name:$translate.instant("NO_PROVIDER_COLUMN_KEY"),display:$translate.instant("NO_PROVIDER_COLUMN_KEY"),uuid:"no-provider-uuid"}),$scope.isSpecialityEnabled?($scope.specialities=_.groupBy(response[0].data,function(service){return service.speciality.name||$translate.instant("NO_SPECIALITY_KEY")}),$scope.selectedSpecialities=_.map($scope.specialities,function(speciality,key){return{label:key,id:speciality[0].speciality.uuid||"",children:_.map(speciality,function(service){return{label:service.name,id:service.uuid,color:service.color,children:$scope.isServiceTypeEnabled?_.map(service.serviceTypes,function(serviceType){return{label:serviceType.name+" ["+serviceType.duration+" "+$translate.instant("PLACEHOLDER_SERVICE_TYPE_DURATION_MIN")+"]",id:serviceType.uuid}}):[]}})}})):$scope.selectedSpecialities=_.map(response[0].data,function(service){return{label:service.name,id:service.uuid,color:service.color,children:$scope.isServiceTypeEnabled?_.map(service.serviceTypes,function(serviceType){return{label:serviceType.name+" ["+serviceType.duration+" "+$translate.instant("PLACEHOLDER_SERVICE_TYPE_DURATION_MIN")+"]",id:serviceType.uuid}}):[]}}),$scope.selectedProviders=_.filter($scope.providers,function(provider){return _.includes($state.params.filterParams.providerUuids,provider.uuid)}),_.isEmpty($state.params.filterParams)||ivhTreeviewMgr.selectEach($scope.selectedSpecialities,$state.params.filterParams.serviceUuids)}))};$scope.$watch("searchText",function(){$scope.expandToDepth==Bahmni.Appointments.Constants.collapseServiceFilter&&expandCollapsedFilter()});var collapseExpandedFilter=function(){if(!_.isUndefined($scope.selectedSpecialities)){var collapsableNodes=$scope.selectedSpecialities.filter(function(selectedSpeciality){return _.isUndefined(selectedSpeciality.selected)});ivhTreeviewMgr.collapseRecursive($scope.selectedSpecialities,collapsableNodes)}},expandCollapsedFilter=function(){!_.isUndefined($scope.searchText)&&$scope.searchText.length>0?ivhTreeviewMgr.expandRecursive($scope.selectedSpecialities):collapseExpandedFilter()};$scope.filterSelected=function(){$scope.filterSelectedValues=$scope.showSelected?{selected:!0}:void 0},$scope.expandFilter=function(){$state.params.isFilterOpen=!0,$scope.isFilterOpen=$state.params.isFilterOpen,$rootScope.$broadcast("filterClosedOpen",{filterViewStatus:$scope.isFilterOpen})},$scope.minimizeFilter=function(){$state.params.isFilterOpen=!1,$scope.isFilterOpen=$state.params.isFilterOpen,$rootScope.$broadcast("filterClosedOpen",{filterViewStatus:$scope.isFilterOpen})};var resetFilterParams=function(){$state.params.filterParams={serviceUuids:[],serviceTypeUuids:[],providerUuids:[],statusList:[]}};$scope.setSelectedSpecialities=function(selectedSpecialities){$scope.selectedSpecialities=selectedSpecialities,$scope.applyFilter()},$scope.getCurrentAppointmentTabName=function(){return $state.current.tabName};var collapseExpandedFilterOnFilterReset=function(){$scope.expandToDepth==Bahmni.Appointments.Constants.collapseServiceFilter&&ivhTreeviewMgr.collapseRecursive($scope.selectedSpecialities,$scope.selectedSpecialities)};$scope.resetFilter=function(){$scope.selectedSpecialities&&(ivhTreeviewMgr.deselectAll($scope.selectedSpecialities,!1),collapseExpandedFilterOnFilterReset()),$scope.selectedProviders=[],$scope.selectedStatusList=[],$scope.showSelected=!1,$scope.filterSelectedValues=void 0,$scope.searchText=void 0,resetFilterParams()},$scope.resetSearchText=function(){$scope.searchText=void 0},$scope.applyFilter=function(){resetFilterParams(),$scope.isSpecialityEnabled?($state.params.filterParams.serviceUuids=_.reduce($scope.selectedSpecialities,function(accumulator,speciality){var serviceUuids=_.chain(speciality.children).filter(function(service){return service.selected}).map(function(service){return service.id}).value();return serviceUuids.concat(accumulator)},[]),$scope.isServiceTypeEnabled?$state.params.filterParams.serviceTypeUuids=_.reduce($scope.selectedSpecialities,function(accumulator,speciality){var selectedServiceTypes=_.reduce(speciality.children,function(accumulator,service){var serviceTypesForService=[];return service.selected||(serviceTypesForService=_.filter(service.children,function(serviceType){return serviceType.selected}).map(function(serviceType){return serviceType.id})),serviceTypesForService.concat(accumulator)},[]);return selectedServiceTypes.concat(accumulator)},[]):$state.params.filterParams.serviceTypeUuids=[]):($state.params.filterParams.serviceUuids=_.chain($scope.selectedSpecialities).filter(function(service){return service.selected}).map(function(service){return service.id}).value(),$scope.isServiceTypeEnabled?$state.params.filterParams.serviceTypeUuids=$scope.selectedSpecialities.filter(function(service){return!service.selected}).reduce(function(accumulator,service){return accumulator.concat(service.children)},[]).filter(function(serviceType){return serviceType.selected}).reduce(function(accumulator,serviceType){return accumulator.concat(serviceType.id)},[]):$state.params.filterParams.serviceTypeUuids=[]),$state.params.filterParams.providerUuids=_.map($scope.selectedProviders,function(provider){return provider.uuid}),$state.params.filterParams.statusList=_.map($scope.selectedStatusList,function(status){return status.value})},$scope.isFilterApplied=function(){return _.find($state.params.filterParams,function(filterParam){return!_.isEmpty(filterParam)})},$scope.$watch(function(){return $state.params.isFilterOpen},function(isFilterHidden){$scope.isFilterOpen=isFilterHidden,$scope.isSearchEnabled=isFilterHidden},!0),$scope.$watch(function(){return $state.params.isSearchEnabled},function(isSearchEnabled){$scope.isSearchEnabled=isSearchEnabled},!0),$scope.$watch(function(){return $state.current.tabName},function(newValue,oldValue){newValue!==oldValue&&("calendar"===newValue?($scope.statusList=_.filter($scope.statusList,function(status){return"Cancelled"!==status.name}),$scope.selectedStatusList=_.filter($scope.selectedStatusList,function(status){return"Cancelled"!==status.name})):$scope.statusList=_.map(Bahmni.Appointments.Constants.appointmentStatusList,function(status){return{name:status,value:status}}))},!0),init()}]),angular.module("bahmni.appointments").filter("appointments",[function(){var filterAppointmentsByService=function(appointments,serviceUuids){return _.filter(appointments,function(appointment){return appointment.service&&_.includes(serviceUuids,appointment.service.uuid)})},filterAppointmentsByServiceType=function(appointments,serviceTypeUuids){return _.filter(appointments,function(appointment){return appointment.serviceType&&_.includes(serviceTypeUuids,appointment.serviceType.uuid)})},filterAppointmentsByProviders=function(appointments,providerUuids){return _.isEmpty(providerUuids)?appointments:_.filter(appointments,function(appointment){if(void 0==appointment.providers||_.isEmpty(appointment.providers))return _.includes(providerUuids,"no-provider-uuid");var found=_.find(appointment.providers,function(p){return _.includes(providerUuids,p.uuid)});return found&&"CANCELLED"!==found.response})},filterAppointmentsByStatus=function(appointments,statusList){return _.isEmpty(statusList)?appointments:_.filter(appointments,function(appointment){return _.includes(statusList,appointment.status)})};return function(appointments,filters){if(_.isEmpty(filters))return appointments;if(_.isEmpty(filters.serviceUuids)&&_.isEmpty(filters.serviceTypeUuids)){var appointmentsFilteredByProviders=filterAppointmentsByProviders(appointments,filters.providerUuids);return filterAppointmentsByStatus(appointmentsFilteredByProviders,filters.statusList)}var appointmentsFilteredByService=filterAppointmentsByService(appointments,filters.serviceUuids),appointmentsFilteredByServiceType=filterAppointmentsByServiceType(appointments,filters.serviceTypeUuids),appointmentsFilteredBySpeciality=appointmentsFilteredByService.concat(appointmentsFilteredByServiceType),appointmentsFilteredByProviders=filterAppointmentsByProviders(appointmentsFilteredBySpeciality,filters.providerUuids);return filterAppointmentsByStatus(appointmentsFilteredByProviders,filters.statusList)}}]); |