fullcalendar.js 175 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099
  1. /*!
  2. * FullCalendar v2.0.3
  3. * Docs & License: http://arshaw.com/fullcalendar/
  4. * (c) 2013 Adam Shaw
  5. */
  6. (function(factory) {
  7. if (typeof define === 'function' && define.amd) {
  8. define([ 'jquery', 'moment' ], factory);
  9. }
  10. else {
  11. factory(jQuery, moment);
  12. }
  13. })(function($, moment) {
  14. ;;
  15. var defaults = {
  16. lang: 'en',
  17. defaultTimedEventDuration: '02:00:00',
  18. defaultAllDayEventDuration: { days: 1 },
  19. forceEventDuration: false,
  20. nextDayThreshold: '09:00:00', // 9am
  21. // display
  22. defaultView: 'month',
  23. aspectRatio: 1.35,
  24. header: {
  25. left: 'title',
  26. center: '',
  27. right: 'today prev,next'
  28. },
  29. weekends: true,
  30. weekNumbers: false,
  31. weekNumberTitle: 'W',
  32. weekNumberCalculation: 'local',
  33. //editable: false,
  34. // event ajax
  35. lazyFetching: true,
  36. startParam: 'start',
  37. endParam: 'end',
  38. timezoneParam: 'timezone',
  39. timezone: false,
  40. //allDayDefault: undefined,
  41. // time formats
  42. titleFormat: {
  43. month: 'MMMM YYYY', // like "September 1986". each language will override this
  44. week: 'll', // like "Sep 4 1986"
  45. day: 'LL' // like "September 4 1986"
  46. },
  47. columnFormat: {
  48. month: 'ddd', // like "Sat"
  49. week: generateWeekColumnFormat,
  50. day: 'dddd' // like "Saturday"
  51. },
  52. timeFormat: { // for event elements
  53. 'default': generateShortTimeFormat
  54. },
  55. displayEventEnd: {
  56. month: false,
  57. basicWeek: false,
  58. 'default': true
  59. },
  60. // locale
  61. isRTL: false,
  62. defaultButtonText: {
  63. prev: "prev",
  64. next: "next",
  65. prevYear: "prev year",
  66. nextYear: "next year",
  67. today: 'today',
  68. month: 'month',
  69. week: 'week',
  70. day: 'day'
  71. },
  72. buttonIcons: {
  73. prev: 'left-single-arrow',
  74. next: 'right-single-arrow',
  75. prevYear: 'left-double-arrow',
  76. nextYear: 'right-double-arrow'
  77. },
  78. // jquery-ui theming
  79. theme: false,
  80. themeButtonIcons: {
  81. prev: 'circle-triangle-w',
  82. next: 'circle-triangle-e',
  83. prevYear: 'seek-prev',
  84. nextYear: 'seek-next'
  85. },
  86. //selectable: false,
  87. unselectAuto: true,
  88. dropAccept: '*',
  89. handleWindowResize: true,
  90. windowResizeDelay: 200 // milliseconds before a rerender happens
  91. };
  92. function generateShortTimeFormat(options, langData) {
  93. return langData.longDateFormat('LT')
  94. .replace(':mm', '(:mm)')
  95. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs
  96. .replace(/\s*a$/i, 't'); // convert to AM/PM/am/pm to lowercase one-letter. remove any spaces beforehand
  97. }
  98. function generateWeekColumnFormat(options, langData) {
  99. var format = langData.longDateFormat('L'); // for the format like "MM/DD/YYYY"
  100. format = format.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g, ''); // strip the year off the edge, as well as other misc non-whitespace chars
  101. if (options.isRTL) {
  102. format += ' ddd'; // for RTL, add day-of-week to end
  103. }
  104. else {
  105. format = 'ddd ' + format; // for LTR, add day-of-week to beginning
  106. }
  107. return format;
  108. }
  109. var langOptionHash = {
  110. en: {
  111. columnFormat: {
  112. week: 'ddd M/D' // override for english. different from the generated default, which is MM/DD
  113. }
  114. }
  115. };
  116. // right-to-left defaults
  117. var rtlDefaults = {
  118. header: {
  119. left: 'next,prev today',
  120. center: '',
  121. right: 'title'
  122. },
  123. buttonIcons: {
  124. prev: 'right-single-arrow',
  125. next: 'left-single-arrow',
  126. prevYear: 'right-double-arrow',
  127. nextYear: 'left-double-arrow'
  128. },
  129. themeButtonIcons: {
  130. prev: 'circle-triangle-e',
  131. next: 'circle-triangle-w',
  132. nextYear: 'seek-prev',
  133. prevYear: 'seek-next'
  134. }
  135. };
  136. ;;
  137. var fc = $.fullCalendar = { version: "2.0.3" };
  138. var fcViews = fc.views = {};
  139. $.fn.fullCalendar = function(options) {
  140. var args = Array.prototype.slice.call(arguments, 1); // for a possible method call
  141. var res = this; // what this function will return (this jQuery object by default)
  142. this.each(function(i, _element) { // loop each DOM element involved
  143. var element = $(_element);
  144. var calendar = element.data('fullCalendar'); // get the existing calendar object (if any)
  145. var singleRes; // the returned value of this single method call
  146. // a method call
  147. if (typeof options === 'string') {
  148. if (calendar && $.isFunction(calendar[options])) {
  149. singleRes = calendar[options].apply(calendar, args);
  150. if (!i) {
  151. res = singleRes; // record the first method call result
  152. }
  153. if (options === 'destroy') { // for the destroy method, must remove Calendar object data
  154. element.removeData('fullCalendar');
  155. }
  156. }
  157. }
  158. // a new calendar initialization
  159. else if (!calendar) { // don't initialize twice
  160. calendar = new Calendar(element, options);
  161. element.data('fullCalendar', calendar);
  162. calendar.render();
  163. }
  164. });
  165. return res;
  166. };
  167. // function for adding/overriding defaults
  168. function setDefaults(d) {
  169. mergeOptions(defaults, d);
  170. }
  171. // Recursively combines option hash-objects.
  172. // Better than `$.extend(true, ...)` because arrays are not traversed/copied.
  173. //
  174. // called like:
  175. // mergeOptions(target, obj1, obj2, ...)
  176. //
  177. function mergeOptions(target) {
  178. function mergeIntoTarget(name, value) {
  179. if ($.isPlainObject(value) && $.isPlainObject(target[name]) && !isForcedAtomicOption(name)) {
  180. // merge into a new object to avoid destruction
  181. target[name] = mergeOptions({}, target[name], value); // combine. `value` object takes precedence
  182. }
  183. else if (value !== undefined) { // only use values that are set and not undefined
  184. target[name] = value;
  185. }
  186. }
  187. for (var i=1; i<arguments.length; i++) {
  188. $.each(arguments[i], mergeIntoTarget);
  189. }
  190. return target;
  191. }
  192. // overcome sucky view-option-hash and option-merging behavior messing with options it shouldn't
  193. function isForcedAtomicOption(name) {
  194. // Any option that ends in "Time" or "Duration" is probably a Duration,
  195. // and these will commonly be specified as plain objects, which we don't want to mess up.
  196. return /(Time|Duration)$/.test(name);
  197. }
  198. // FIX: find a different solution for view-option-hashes and have a whitelist
  199. // for options that can be recursively merged.
  200. ;;
  201. //var langOptionHash = {}; // initialized in defaults.js
  202. fc.langs = langOptionHash; // expose
  203. // Initialize jQuery UI Datepicker translations while using some of the translations
  204. // for our own purposes. Will set this as the default language for datepicker.
  205. // Called from a translation file.
  206. fc.datepickerLang = function(langCode, datepickerLangCode, options) {
  207. var langOptions = langOptionHash[langCode];
  208. // initialize FullCalendar's lang hash for this language
  209. if (!langOptions) {
  210. langOptions = langOptionHash[langCode] = {};
  211. }
  212. // merge certain Datepicker options into FullCalendar's options
  213. mergeOptions(langOptions, {
  214. isRTL: options.isRTL,
  215. weekNumberTitle: options.weekHeader,
  216. titleFormat: {
  217. month: options.showMonthAfterYear ?
  218. 'YYYY[' + options.yearSuffix + '] MMMM' :
  219. 'MMMM YYYY[' + options.yearSuffix + ']'
  220. },
  221. defaultButtonText: {
  222. // the translations sometimes wrongly contain HTML entities
  223. prev: stripHTMLEntities(options.prevText),
  224. next: stripHTMLEntities(options.nextText),
  225. today: stripHTMLEntities(options.currentText)
  226. }
  227. });
  228. // is jQuery UI Datepicker is on the page?
  229. if ($.datepicker) {
  230. // Register the language data.
  231. // FullCalendar and MomentJS use language codes like "pt-br" but Datepicker
  232. // does it like "pt-BR" or if it doesn't have the language, maybe just "pt".
  233. // Make an alias so the language can be referenced either way.
  234. $.datepicker.regional[datepickerLangCode] =
  235. $.datepicker.regional[langCode] = // alias
  236. options;
  237. // Alias 'en' to the default language data. Do this every time.
  238. $.datepicker.regional.en = $.datepicker.regional[''];
  239. // Set as Datepicker's global defaults.
  240. $.datepicker.setDefaults(options);
  241. }
  242. };
  243. // Sets FullCalendar-specific translations. Also sets the language as the global default.
  244. // Called from a translation file.
  245. fc.lang = function(langCode, options) {
  246. var langOptions;
  247. if (options) {
  248. langOptions = langOptionHash[langCode];
  249. // initialize the hash for this language
  250. if (!langOptions) {
  251. langOptions = langOptionHash[langCode] = {};
  252. }
  253. mergeOptions(langOptions, options || {});
  254. }
  255. // set it as the default language for FullCalendar
  256. defaults.lang = langCode;
  257. };
  258. ;;
  259. function Calendar(element, instanceOptions) {
  260. var t = this;
  261. // Build options object
  262. // -----------------------------------------------------------------------------------
  263. // Precedence (lowest to highest): defaults, rtlDefaults, langOptions, instanceOptions
  264. instanceOptions = instanceOptions || {};
  265. var options = mergeOptions({}, defaults, instanceOptions);
  266. var langOptions;
  267. // determine language options
  268. if (options.lang in langOptionHash) {
  269. langOptions = langOptionHash[options.lang];
  270. }
  271. else {
  272. langOptions = langOptionHash[defaults.lang];
  273. }
  274. if (langOptions) { // if language options exist, rebuild...
  275. options = mergeOptions({}, defaults, langOptions, instanceOptions);
  276. }
  277. if (options.isRTL) { // is isRTL, rebuild...
  278. options = mergeOptions({}, defaults, rtlDefaults, langOptions || {}, instanceOptions);
  279. }
  280. // Exports
  281. // -----------------------------------------------------------------------------------
  282. t.options = options;
  283. t.render = render;
  284. t.destroy = destroy;
  285. t.refetchEvents = refetchEvents;
  286. t.reportEvents = reportEvents;
  287. t.reportEventChange = reportEventChange;
  288. t.rerenderEvents = rerenderEvents;
  289. t.changeView = changeView;
  290. t.select = select;
  291. t.unselect = unselect;
  292. t.prev = prev;
  293. t.next = next;
  294. t.prevYear = prevYear;
  295. t.nextYear = nextYear;
  296. t.today = today;
  297. t.gotoDate = gotoDate;
  298. t.incrementDate = incrementDate;
  299. t.getDate = getDate;
  300. t.getCalendar = getCalendar;
  301. t.getView = getView;
  302. t.option = option;
  303. t.trigger = trigger;
  304. // Language-data Internals
  305. // -----------------------------------------------------------------------------------
  306. // Apply overrides to the current language's data
  307. // Returns moment's internal locale data. If doesn't exist, returns English.
  308. // Works with moment-pre-2.8
  309. function getLocaleData(langCode) {
  310. var f = moment.localeData || moment.langData;
  311. return f.call(moment, langCode) ||
  312. f.call(moment, 'en'); // the newer localData could return null, so fall back to en
  313. }
  314. var localeData = createObject(getLocaleData(options.lang)); // make a cheap copy
  315. if (options.monthNames) {
  316. localeData._months = options.monthNames;
  317. }
  318. if (options.monthNamesShort) {
  319. localeData._monthsShort = options.monthNamesShort;
  320. }
  321. if (options.dayNames) {
  322. localeData._weekdays = options.dayNames;
  323. }
  324. if (options.dayNamesShort) {
  325. localeData._weekdaysShort = options.dayNamesShort;
  326. }
  327. if (options.firstDay != null) {
  328. var _week = createObject(localeData._week); // _week: { dow: # }
  329. _week.dow = options.firstDay;
  330. localeData._week = _week;
  331. }
  332. // Calendar-specific Date Utilities
  333. // -----------------------------------------------------------------------------------
  334. t.defaultAllDayEventDuration = moment.duration(options.defaultAllDayEventDuration);
  335. t.defaultTimedEventDuration = moment.duration(options.defaultTimedEventDuration);
  336. // Builds a moment using the settings of the current calendar: timezone and language.
  337. // Accepts anything the vanilla moment() constructor accepts.
  338. t.moment = function() {
  339. var mom;
  340. if (options.timezone === 'local') {
  341. mom = fc.moment.apply(null, arguments);
  342. // Force the moment to be local, because fc.moment doesn't guarantee it.
  343. if (mom.hasTime()) { // don't give ambiguously-timed moments a local zone
  344. mom.local();
  345. }
  346. }
  347. else if (options.timezone === 'UTC') {
  348. mom = fc.moment.utc.apply(null, arguments); // process as UTC
  349. }
  350. else {
  351. mom = fc.moment.parseZone.apply(null, arguments); // let the input decide the zone
  352. }
  353. if ('_locale' in mom) { // moment 2.8 and above
  354. mom._locale = localeData;
  355. }
  356. else { // pre-moment-2.8
  357. mom._lang = localeData;
  358. }
  359. return mom;
  360. };
  361. // Returns a boolean about whether or not the calendar knows how to calculate
  362. // the timezone offset of arbitrary dates in the current timezone.
  363. t.getIsAmbigTimezone = function() {
  364. return options.timezone !== 'local' && options.timezone !== 'UTC';
  365. };
  366. // Returns a copy of the given date in the current timezone of it is ambiguously zoned.
  367. // This will also give the date an unambiguous time.
  368. t.rezoneDate = function(date) {
  369. return t.moment(date.toArray());
  370. };
  371. // Returns a moment for the current date, as defined by the client's computer,
  372. // or overridden by the `now` option.
  373. t.getNow = function() {
  374. var now = options.now;
  375. if (typeof now === 'function') {
  376. now = now();
  377. }
  378. return t.moment(now);
  379. };
  380. // Calculates the week number for a moment according to the calendar's
  381. // `weekNumberCalculation` setting.
  382. t.calculateWeekNumber = function(mom) {
  383. var calc = options.weekNumberCalculation;
  384. if (typeof calc === 'function') {
  385. return calc(mom);
  386. }
  387. else if (calc === 'local') {
  388. return mom.week();
  389. }
  390. else if (calc.toUpperCase() === 'ISO') {
  391. return mom.isoWeek();
  392. }
  393. };
  394. // Get an event's normalized end date. If not present, calculate it from the defaults.
  395. t.getEventEnd = function(event) {
  396. if (event.end) {
  397. return event.end.clone();
  398. }
  399. else {
  400. return t.getDefaultEventEnd(event.allDay, event.start);
  401. }
  402. };
  403. // Given an event's allDay status and start date, return swhat its fallback end date should be.
  404. t.getDefaultEventEnd = function(allDay, start) { // TODO: rename to computeDefaultEventEnd
  405. var end = start.clone();
  406. if (allDay) {
  407. end.stripTime().add(t.defaultAllDayEventDuration);
  408. }
  409. else {
  410. end.add(t.defaultTimedEventDuration);
  411. }
  412. if (t.getIsAmbigTimezone()) {
  413. end.stripZone(); // we don't know what the tzo should be
  414. }
  415. return end;
  416. };
  417. // Date-formatting Utilities
  418. // -----------------------------------------------------------------------------------
  419. // Like the vanilla formatRange, but with calendar-specific settings applied.
  420. t.formatRange = function(m1, m2, formatStr) {
  421. // a function that returns a formatStr // TODO: in future, precompute this
  422. if (typeof formatStr === 'function') {
  423. formatStr = formatStr.call(t, options, localeData);
  424. }
  425. return formatRange(m1, m2, formatStr, null, options.isRTL);
  426. };
  427. // Like the vanilla formatDate, but with calendar-specific settings applied.
  428. t.formatDate = function(mom, formatStr) {
  429. // a function that returns a formatStr // TODO: in future, precompute this
  430. if (typeof formatStr === 'function') {
  431. formatStr = formatStr.call(t, options, localeData);
  432. }
  433. return formatDate(mom, formatStr);
  434. };
  435. // Imports
  436. // -----------------------------------------------------------------------------------
  437. EventManager.call(t, options);
  438. var isFetchNeeded = t.isFetchNeeded;
  439. var fetchEvents = t.fetchEvents;
  440. // Locals
  441. // -----------------------------------------------------------------------------------
  442. var _element = element[0];
  443. var header;
  444. var headerElement;
  445. var content;
  446. var tm; // for making theme classes
  447. var currentView;
  448. var elementOuterWidth;
  449. var suggestedViewHeight;
  450. var resizeUID = 0;
  451. var ignoreWindowResize = 0;
  452. var date;
  453. var events = [];
  454. var _dragElement;
  455. // Main Rendering
  456. // -----------------------------------------------------------------------------------
  457. if (options.defaultDate != null) {
  458. date = t.moment(options.defaultDate);
  459. }
  460. else {
  461. date = t.getNow();
  462. }
  463. function render(inc) {
  464. if (!content) {
  465. initialRender();
  466. }
  467. else if (elementVisible()) {
  468. // mainly for the public API
  469. calcSize();
  470. _renderView(inc);
  471. }
  472. }
  473. function initialRender() {
  474. tm = options.theme ? 'ui' : 'fc';
  475. element.addClass('fc');
  476. if (options.isRTL) {
  477. element.addClass('fc-rtl');
  478. }
  479. else {
  480. element.addClass('fc-ltr');
  481. }
  482. if (options.theme) {
  483. element.addClass('ui-widget');
  484. }
  485. content = $("<div class='fc-content' />")
  486. .prependTo(element);
  487. header = new Header(t, options);
  488. headerElement = header.render();
  489. if (headerElement) {
  490. element.prepend(headerElement);
  491. }
  492. changeView(options.defaultView);
  493. if (options.handleWindowResize) {
  494. $(window).resize(windowResize);
  495. }
  496. // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize
  497. if (!bodyVisible()) {
  498. lateRender();
  499. }
  500. }
  501. // called when we know the calendar couldn't be rendered when it was initialized,
  502. // but we think it's ready now
  503. function lateRender() {
  504. setTimeout(function() { // IE7 needs this so dimensions are calculated correctly
  505. if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once
  506. renderView();
  507. }
  508. },0);
  509. }
  510. function destroy() {
  511. if (currentView) {
  512. trigger('viewDestroy', currentView, currentView, currentView.element);
  513. currentView.triggerEventDestroy();
  514. }
  515. $(window).unbind('resize', windowResize);
  516. if (options.droppable) {
  517. $(document)
  518. .off('dragstart', droppableDragStart)
  519. .off('dragstop', droppableDragStop);
  520. }
  521. if (currentView.selectionManagerDestroy) {
  522. currentView.selectionManagerDestroy();
  523. }
  524. header.destroy();
  525. content.remove();
  526. element.removeClass('fc fc-ltr fc-rtl ui-widget');
  527. }
  528. function elementVisible() {
  529. return element.is(':visible');
  530. }
  531. function bodyVisible() {
  532. return $('body').is(':visible');
  533. }
  534. // View Rendering
  535. // -----------------------------------------------------------------------------------
  536. function changeView(newViewName) {
  537. if (!currentView || newViewName != currentView.name) {
  538. _changeView(newViewName);
  539. }
  540. }
  541. function _changeView(newViewName) {
  542. ignoreWindowResize++;
  543. if (currentView) {
  544. trigger('viewDestroy', currentView, currentView, currentView.element);
  545. unselect();
  546. currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event
  547. freezeContentHeight();
  548. currentView.element.remove();
  549. header.deactivateButton(currentView.name);
  550. }
  551. header.activateButton(newViewName);
  552. currentView = new fcViews[newViewName](
  553. $("<div class='fc-view fc-view-" + newViewName + "' />")
  554. .appendTo(content),
  555. t // the calendar object
  556. );
  557. renderView();
  558. unfreezeContentHeight();
  559. ignoreWindowResize--;
  560. }
  561. function renderView(inc) {
  562. if (
  563. !currentView.start || // never rendered before
  564. inc || // explicit date window change
  565. !date.isWithin(currentView.intervalStart, currentView.intervalEnd) // implicit date window change
  566. ) {
  567. if (elementVisible()) {
  568. _renderView(inc);
  569. }
  570. }
  571. }
  572. function _renderView(inc) { // assumes elementVisible
  573. ignoreWindowResize++;
  574. if (currentView.start) { // already been rendered?
  575. trigger('viewDestroy', currentView, currentView, currentView.element);
  576. unselect();
  577. clearEvents();
  578. }
  579. freezeContentHeight();
  580. if (inc) {
  581. date = currentView.incrementDate(date, inc);
  582. }
  583. currentView.render(date.clone()); // the view's render method ONLY renders the skeleton, nothing else
  584. setSize();
  585. unfreezeContentHeight();
  586. (currentView.afterRender || noop)();
  587. updateTitle();
  588. updateTodayButton();
  589. trigger('viewRender', currentView, currentView, currentView.element);
  590. ignoreWindowResize--;
  591. getAndRenderEvents();
  592. }
  593. // Resizing
  594. // -----------------------------------------------------------------------------------
  595. function updateSize() {
  596. if (elementVisible()) {
  597. unselect();
  598. clearEvents();
  599. calcSize();
  600. setSize();
  601. renderEvents();
  602. }
  603. }
  604. function calcSize() { // assumes elementVisible
  605. if (options.contentHeight) {
  606. suggestedViewHeight = options.contentHeight;
  607. }
  608. else if (options.height) {
  609. suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content);
  610. }
  611. else {
  612. suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
  613. }
  614. }
  615. function setSize() { // assumes elementVisible
  616. if (suggestedViewHeight === undefined) {
  617. calcSize(); // for first time
  618. // NOTE: we don't want to recalculate on every renderView because
  619. // it could result in oscillating heights due to scrollbars.
  620. }
  621. ignoreWindowResize++;
  622. currentView.setHeight(suggestedViewHeight);
  623. currentView.setWidth(content.width());
  624. ignoreWindowResize--;
  625. elementOuterWidth = element.outerWidth();
  626. }
  627. function windowResize(ev) {
  628. if (
  629. !ignoreWindowResize &&
  630. ev.target === window // so we don't process jqui "resize" events that have bubbled up
  631. ) {
  632. if (currentView.start) { // view has already been rendered
  633. var uid = ++resizeUID;
  634. setTimeout(function() { // add a delay
  635. if (uid == resizeUID && !ignoreWindowResize && elementVisible()) {
  636. if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) {
  637. ignoreWindowResize++; // in case the windowResize callback changes the height
  638. updateSize();
  639. currentView.trigger('windowResize', _element);
  640. ignoreWindowResize--;
  641. }
  642. }
  643. }, options.windowResizeDelay);
  644. }else{
  645. // calendar must have been initialized in a 0x0 iframe that has just been resized
  646. lateRender();
  647. }
  648. }
  649. }
  650. /* Event Fetching/Rendering
  651. -----------------------------------------------------------------------------*/
  652. // TODO: going forward, most of this stuff should be directly handled by the view
  653. function refetchEvents() { // can be called as an API method
  654. clearEvents();
  655. fetchAndRenderEvents();
  656. }
  657. function rerenderEvents(modifiedEventID) { // can be called as an API method
  658. clearEvents();
  659. renderEvents(modifiedEventID);
  660. }
  661. function renderEvents(modifiedEventID) { // TODO: remove modifiedEventID hack
  662. if (elementVisible()) {
  663. currentView.renderEvents(events, modifiedEventID); // actually render the DOM elements
  664. currentView.trigger('eventAfterAllRender');
  665. }
  666. }
  667. function clearEvents() {
  668. currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event
  669. currentView.clearEvents(); // actually remove the DOM elements
  670. currentView.clearEventData(); // for View.js, TODO: unify with clearEvents
  671. }
  672. function getAndRenderEvents() {
  673. if (!options.lazyFetching || isFetchNeeded(currentView.start, currentView.end)) {
  674. fetchAndRenderEvents();
  675. }
  676. else {
  677. renderEvents();
  678. }
  679. }
  680. function fetchAndRenderEvents() {
  681. fetchEvents(currentView.start, currentView.end);
  682. // ... will call reportEvents
  683. // ... which will call renderEvents
  684. }
  685. // called when event data arrives
  686. function reportEvents(_events) {
  687. events = _events;
  688. renderEvents();
  689. }
  690. // called when a single event's data has been changed
  691. function reportEventChange(eventID) {
  692. rerenderEvents(eventID);
  693. }
  694. /* Header Updating
  695. -----------------------------------------------------------------------------*/
  696. function updateTitle() {
  697. header.updateTitle(currentView.title);
  698. }
  699. function updateTodayButton() {
  700. var now = t.getNow();
  701. if (now.isWithin(currentView.intervalStart, currentView.intervalEnd)) {
  702. header.disableButton('today');
  703. }
  704. else {
  705. header.enableButton('today');
  706. }
  707. }
  708. /* Selection
  709. -----------------------------------------------------------------------------*/
  710. function select(start, end) {
  711. currentView.select(start, end);
  712. }
  713. function unselect() { // safe to be called before renderView
  714. if (currentView) {
  715. currentView.unselect();
  716. }
  717. }
  718. /* Date
  719. -----------------------------------------------------------------------------*/
  720. function prev() {
  721. renderView(-1);
  722. }
  723. function next() {
  724. renderView(1);
  725. }
  726. function prevYear() {
  727. date.add(-1, 'years');
  728. renderView();
  729. }
  730. function nextYear() {
  731. date.add(1, 'years');
  732. renderView();
  733. }
  734. function today() {
  735. date = t.getNow();
  736. renderView();
  737. }
  738. function gotoDate(dateInput) {
  739. date = t.moment(dateInput);
  740. renderView();
  741. }
  742. function incrementDate(delta) {
  743. date.add(moment.duration(delta));
  744. renderView();
  745. }
  746. function getDate() {
  747. return date.clone();
  748. }
  749. /* Height "Freezing"
  750. -----------------------------------------------------------------------------*/
  751. function freezeContentHeight() {
  752. content.css({
  753. width: '100%',
  754. height: content.height(),
  755. overflow: 'hidden'
  756. });
  757. }
  758. function unfreezeContentHeight() {
  759. content.css({
  760. width: '',
  761. height: '',
  762. overflow: ''
  763. });
  764. }
  765. /* Misc
  766. -----------------------------------------------------------------------------*/
  767. function getCalendar() {
  768. return t;
  769. }
  770. function getView() {
  771. return currentView;
  772. }
  773. function option(name, value) {
  774. if (value === undefined) {
  775. return options[name];
  776. }
  777. if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
  778. options[name] = value;
  779. updateSize();
  780. }
  781. }
  782. function trigger(name, thisObj) {
  783. if (options[name]) {
  784. return options[name].apply(
  785. thisObj || _element,
  786. Array.prototype.slice.call(arguments, 2)
  787. );
  788. }
  789. }
  790. /* External Dragging
  791. ------------------------------------------------------------------------*/
  792. if (options.droppable) {
  793. // TODO: unbind on destroy
  794. $(document)
  795. .on('dragstart', droppableDragStart)
  796. .on('dragstop', droppableDragStop);
  797. // this is undone in destroy
  798. }
  799. function droppableDragStart(ev, ui) {
  800. var _e = ev.target;
  801. var e = $(_e);
  802. if (!e.parents('.fc').length) { // not already inside a calendar
  803. var accept = options.dropAccept;
  804. if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) {
  805. _dragElement = _e;
  806. currentView.dragStart(_dragElement, ev, ui);
  807. }
  808. }
  809. }
  810. function droppableDragStop(ev, ui) {
  811. if (_dragElement) {
  812. currentView.dragStop(_dragElement, ev, ui);
  813. _dragElement = null;
  814. }
  815. }
  816. }
  817. ;;
  818. function Header(calendar, options) {
  819. var t = this;
  820. // exports
  821. t.render = render;
  822. t.destroy = destroy;
  823. t.updateTitle = updateTitle;
  824. t.activateButton = activateButton;
  825. t.deactivateButton = deactivateButton;
  826. t.disableButton = disableButton;
  827. t.enableButton = enableButton;
  828. // locals
  829. var element = $([]);
  830. var tm;
  831. function render() {
  832. tm = options.theme ? 'ui' : 'fc';
  833. var sections = options.header;
  834. if (sections) {
  835. element = $("<table class='fc-header' style='width:100%'/>")
  836. .append(
  837. $("<tr/>")
  838. .append(renderSection('left'))
  839. .append(renderSection('center'))
  840. .append(renderSection('right'))
  841. );
  842. return element;
  843. }
  844. }
  845. function destroy() {
  846. element.remove();
  847. }
  848. function renderSection(position) {
  849. var e = $("<td class='fc-header-" + position + "'/>");
  850. var buttonStr = options.header[position];
  851. if (buttonStr) {
  852. $.each(buttonStr.split(' '), function(i) {
  853. if (i > 0) {
  854. e.append("<span class='fc-header-space'/>");
  855. }
  856. var prevButton;
  857. $.each(this.split(','), function(j, buttonName) {
  858. if (buttonName == 'title') {
  859. e.append("<span class='fc-header-title'><h2>&nbsp;</h2></span>");
  860. if (prevButton) {
  861. prevButton.addClass(tm + '-corner-right');
  862. }
  863. prevButton = null;
  864. }else{
  865. var buttonClick;
  866. if (calendar[buttonName]) {
  867. buttonClick = calendar[buttonName]; // calendar method
  868. }
  869. else if (fcViews[buttonName]) {
  870. buttonClick = function() {
  871. button.removeClass(tm + '-state-hover'); // forget why
  872. calendar.changeView(buttonName);
  873. };
  874. }
  875. if (buttonClick) {
  876. // smartProperty allows different text per view button (ex: "Agenda Week" vs "Basic Week")
  877. var themeIcon = smartProperty(options.themeButtonIcons, buttonName);
  878. var normalIcon = smartProperty(options.buttonIcons, buttonName);
  879. var defaultText = smartProperty(options.defaultButtonText, buttonName);
  880. var customText = smartProperty(options.buttonText, buttonName);
  881. var html;
  882. if (customText) {
  883. html = htmlEscape(customText);
  884. }
  885. else if (themeIcon && options.theme) {
  886. html = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>";
  887. }
  888. else if (normalIcon && !options.theme) {
  889. html = "<span class='fc-icon fc-icon-" + normalIcon + "'></span>";
  890. }
  891. else {
  892. html = htmlEscape(defaultText || buttonName);
  893. }
  894. var button = $(
  895. "<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" +
  896. html +
  897. "</span>"
  898. )
  899. .click(function() {
  900. if (!button.hasClass(tm + '-state-disabled')) {
  901. buttonClick();
  902. }
  903. })
  904. .mousedown(function() {
  905. button
  906. .not('.' + tm + '-state-active')
  907. .not('.' + tm + '-state-disabled')
  908. .addClass(tm + '-state-down');
  909. })
  910. .mouseup(function() {
  911. button.removeClass(tm + '-state-down');
  912. })
  913. .hover(
  914. function() {
  915. button
  916. .not('.' + tm + '-state-active')
  917. .not('.' + tm + '-state-disabled')
  918. .addClass(tm + '-state-hover');
  919. },
  920. function() {
  921. button
  922. .removeClass(tm + '-state-hover')
  923. .removeClass(tm + '-state-down');
  924. }
  925. )
  926. .appendTo(e);
  927. disableTextSelection(button);
  928. if (!prevButton) {
  929. button.addClass(tm + '-corner-left');
  930. }
  931. prevButton = button;
  932. }
  933. }
  934. });
  935. if (prevButton) {
  936. prevButton.addClass(tm + '-corner-right');
  937. }
  938. });
  939. }
  940. return e;
  941. }
  942. function updateTitle(html) {
  943. element.find('h2')
  944. .html(html);
  945. }
  946. function activateButton(buttonName) {
  947. element.find('span.fc-button-' + buttonName)
  948. .addClass(tm + '-state-active');
  949. }
  950. function deactivateButton(buttonName) {
  951. element.find('span.fc-button-' + buttonName)
  952. .removeClass(tm + '-state-active');
  953. }
  954. function disableButton(buttonName) {
  955. element.find('span.fc-button-' + buttonName)
  956. .addClass(tm + '-state-disabled');
  957. }
  958. function enableButton(buttonName) {
  959. element.find('span.fc-button-' + buttonName)
  960. .removeClass(tm + '-state-disabled');
  961. }
  962. }
  963. ;;
  964. fc.sourceNormalizers = [];
  965. fc.sourceFetchers = [];
  966. var ajaxDefaults = {
  967. dataType: 'json',
  968. cache: false
  969. };
  970. var eventGUID = 1;
  971. function EventManager(options) { // assumed to be a calendar
  972. var t = this;
  973. // exports
  974. t.isFetchNeeded = isFetchNeeded;
  975. t.fetchEvents = fetchEvents;
  976. t.addEventSource = addEventSource;
  977. t.removeEventSource = removeEventSource;
  978. t.updateEvent = updateEvent;
  979. t.renderEvent = renderEvent;
  980. t.removeEvents = removeEvents;
  981. t.clientEvents = clientEvents;
  982. t.mutateEvent = mutateEvent;
  983. // imports
  984. var trigger = t.trigger;
  985. var getView = t.getView;
  986. var reportEvents = t.reportEvents;
  987. var getEventEnd = t.getEventEnd;
  988. // locals
  989. var stickySource = { events: [] };
  990. var sources = [ stickySource ];
  991. var rangeStart, rangeEnd;
  992. var currentFetchID = 0;
  993. var pendingSourceCnt = 0;
  994. var loadingLevel = 0;
  995. var cache = [];
  996. $.each(
  997. (options.events ? [ options.events ] : []).concat(options.eventSources || []),
  998. function(i, sourceInput) {
  999. var source = buildEventSource(sourceInput);
  1000. if (source) {
  1001. sources.push(source);
  1002. }
  1003. }
  1004. );
  1005. /* Fetching
  1006. -----------------------------------------------------------------------------*/
  1007. function isFetchNeeded(start, end) {
  1008. return !rangeStart || // nothing has been fetched yet?
  1009. // or, a part of the new range is outside of the old range? (after normalizing)
  1010. start.clone().stripZone() < rangeStart.clone().stripZone() ||
  1011. end.clone().stripZone() > rangeEnd.clone().stripZone();
  1012. }
  1013. function fetchEvents(start, end) {
  1014. rangeStart = start;
  1015. rangeEnd = end;
  1016. cache = [];
  1017. var fetchID = ++currentFetchID;
  1018. var len = sources.length;
  1019. pendingSourceCnt = len;
  1020. for (var i=0; i<len; i++) {
  1021. fetchEventSource(sources[i], fetchID);
  1022. }
  1023. }
  1024. function fetchEventSource(source, fetchID) {
  1025. _fetchEventSource(source, function(events) {
  1026. var isArraySource = $.isArray(source.events);
  1027. var i;
  1028. var event;
  1029. if (fetchID == currentFetchID) {
  1030. if (events) {
  1031. for (i=0; i<events.length; i++) {
  1032. event = events[i];
  1033. // event array sources have already been convert to Event Objects
  1034. if (!isArraySource) {
  1035. event = buildEvent(event, source);
  1036. }
  1037. if (event) {
  1038. cache.push(event);
  1039. }
  1040. }
  1041. }
  1042. pendingSourceCnt--;
  1043. if (!pendingSourceCnt) {
  1044. reportEvents(cache);
  1045. }
  1046. }
  1047. });
  1048. }
  1049. function _fetchEventSource(source, callback) {
  1050. var i;
  1051. var fetchers = fc.sourceFetchers;
  1052. var res;
  1053. for (i=0; i<fetchers.length; i++) {
  1054. res = fetchers[i].call(
  1055. t, // this, the Calendar object
  1056. source,
  1057. rangeStart.clone(),
  1058. rangeEnd.clone(),
  1059. options.timezone,
  1060. callback
  1061. );
  1062. if (res === true) {
  1063. // the fetcher is in charge. made its own async request
  1064. return;
  1065. }
  1066. else if (typeof res == 'object') {
  1067. // the fetcher returned a new source. process it
  1068. _fetchEventSource(res, callback);
  1069. return;
  1070. }
  1071. }
  1072. var events = source.events;
  1073. if (events) {
  1074. if ($.isFunction(events)) {
  1075. pushLoading();
  1076. events.call(
  1077. t, // this, the Calendar object
  1078. rangeStart.clone(),
  1079. rangeEnd.clone(),
  1080. options.timezone,
  1081. function(events) {
  1082. callback(events);
  1083. popLoading();
  1084. }
  1085. );
  1086. }
  1087. else if ($.isArray(events)) {
  1088. callback(events);
  1089. }
  1090. else {
  1091. callback();
  1092. }
  1093. }else{
  1094. var url = source.url;
  1095. if (url) {
  1096. var success = source.success;
  1097. var error = source.error;
  1098. var complete = source.complete;
  1099. // retrieve any outbound GET/POST $.ajax data from the options
  1100. var customData;
  1101. if ($.isFunction(source.data)) {
  1102. // supplied as a function that returns a key/value object
  1103. customData = source.data();
  1104. }
  1105. else {
  1106. // supplied as a straight key/value object
  1107. customData = source.data;
  1108. }
  1109. // use a copy of the custom data so we can modify the parameters
  1110. // and not affect the passed-in object.
  1111. var data = $.extend({}, customData || {});
  1112. var startParam = firstDefined(source.startParam, options.startParam);
  1113. var endParam = firstDefined(source.endParam, options.endParam);
  1114. var timezoneParam = firstDefined(source.timezoneParam, options.timezoneParam);
  1115. if (startParam) {
  1116. data[startParam] = rangeStart.format();
  1117. }
  1118. if (endParam) {
  1119. data[endParam] = rangeEnd.format();
  1120. }
  1121. if (options.timezone && options.timezone != 'local') {
  1122. data[timezoneParam] = options.timezone;
  1123. }
  1124. pushLoading();
  1125. $.ajax($.extend({}, ajaxDefaults, source, {
  1126. data: data,
  1127. success: function(events) {
  1128. events = events || [];
  1129. var res = applyAll(success, this, arguments);
  1130. if ($.isArray(res)) {
  1131. events = res;
  1132. }
  1133. callback(events);
  1134. },
  1135. error: function() {
  1136. applyAll(error, this, arguments);
  1137. callback();
  1138. },
  1139. complete: function() {
  1140. applyAll(complete, this, arguments);
  1141. popLoading();
  1142. }
  1143. }));
  1144. }else{
  1145. callback();
  1146. }
  1147. }
  1148. }
  1149. /* Sources
  1150. -----------------------------------------------------------------------------*/
  1151. function addEventSource(sourceInput) {
  1152. var source = buildEventSource(sourceInput);
  1153. if (source) {
  1154. sources.push(source);
  1155. pendingSourceCnt++;
  1156. fetchEventSource(source, currentFetchID); // will eventually call reportEvents
  1157. }
  1158. }
  1159. function buildEventSource(sourceInput) { // will return undefined if invalid source
  1160. var normalizers = fc.sourceNormalizers;
  1161. var source;
  1162. var i;
  1163. if ($.isFunction(sourceInput) || $.isArray(sourceInput)) {
  1164. source = { events: sourceInput };
  1165. }
  1166. else if (typeof sourceInput === 'string') {
  1167. source = { url: sourceInput };
  1168. }
  1169. else if (typeof sourceInput === 'object') {
  1170. source = $.extend({}, sourceInput); // shallow copy
  1171. if (typeof source.className === 'string') {
  1172. // TODO: repeat code, same code for event classNames
  1173. source.className = source.className.split(/\s+/);
  1174. }
  1175. }
  1176. if (source) {
  1177. // for array sources, we convert to standard Event Objects up front
  1178. if ($.isArray(source.events)) {
  1179. source.events = $.map(source.events, function(eventInput) {
  1180. return buildEvent(eventInput, source);
  1181. });
  1182. }
  1183. for (i=0; i<normalizers.length; i++) {
  1184. normalizers[i].call(t, source);
  1185. }
  1186. return source;
  1187. }
  1188. }
  1189. function removeEventSource(source) {
  1190. sources = $.grep(sources, function(src) {
  1191. return !isSourcesEqual(src, source);
  1192. });
  1193. // remove all client events from that source
  1194. cache = $.grep(cache, function(e) {
  1195. return !isSourcesEqual(e.source, source);
  1196. });
  1197. reportEvents(cache);
  1198. }
  1199. function isSourcesEqual(source1, source2) {
  1200. return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
  1201. }
  1202. function getSourcePrimitive(source) {
  1203. return ((typeof source == 'object') ? (source.events || source.url) : '') || source;
  1204. }
  1205. /* Manipulation
  1206. -----------------------------------------------------------------------------*/
  1207. function updateEvent(event) {
  1208. event.start = t.moment(event.start);
  1209. if (event.end) {
  1210. event.end = t.moment(event.end);
  1211. }
  1212. mutateEvent(event);
  1213. propagateMiscProperties(event);
  1214. reportEvents(cache); // reports event modifications (so we can redraw)
  1215. }
  1216. var miscCopyableProps = [
  1217. 'title',
  1218. 'url',
  1219. 'allDay',
  1220. 'className',
  1221. 'editable',
  1222. 'color',
  1223. 'backgroundColor',
  1224. 'borderColor',
  1225. 'textColor'
  1226. ];
  1227. function propagateMiscProperties(event) {
  1228. var i;
  1229. var cachedEvent;
  1230. var j;
  1231. var prop;
  1232. for (i=0; i<cache.length; i++) {
  1233. cachedEvent = cache[i];
  1234. if (cachedEvent._id == event._id && cachedEvent !== event) {
  1235. for (j=0; j<miscCopyableProps.length; j++) {
  1236. prop = miscCopyableProps[j];
  1237. if (event[prop] !== undefined) {
  1238. cachedEvent[prop] = event[prop];
  1239. }
  1240. }
  1241. }
  1242. }
  1243. }
  1244. function renderEvent(eventData, stick) {
  1245. var event = buildEvent(eventData);
  1246. if (event) {
  1247. if (!event.source) {
  1248. if (stick) {
  1249. stickySource.events.push(event);
  1250. event.source = stickySource;
  1251. }
  1252. cache.push(event);
  1253. }
  1254. reportEvents(cache);
  1255. }
  1256. }
  1257. function removeEvents(filter) {
  1258. var eventID;
  1259. var i;
  1260. if (filter == null) { // null or undefined. remove all events
  1261. filter = function() { return true; }; // will always match
  1262. }
  1263. else if (!$.isFunction(filter)) { // an event ID
  1264. eventID = filter + '';
  1265. filter = function(event) {
  1266. return event._id == eventID;
  1267. };
  1268. }
  1269. // Purge event(s) from our local cache
  1270. cache = $.grep(cache, filter, true); // inverse=true
  1271. // Remove events from array sources.
  1272. // This works because they have been converted to official Event Objects up front.
  1273. // (and as a result, event._id has been calculated).
  1274. for (i=0; i<sources.length; i++) {
  1275. if ($.isArray(sources[i].events)) {
  1276. sources[i].events = $.grep(sources[i].events, filter, true);
  1277. }
  1278. }
  1279. reportEvents(cache);
  1280. }
  1281. function clientEvents(filter) {
  1282. if ($.isFunction(filter)) {
  1283. return $.grep(cache, filter);
  1284. }
  1285. else if (filter != null) { // not null, not undefined. an event ID
  1286. filter += '';
  1287. return $.grep(cache, function(e) {
  1288. return e._id == filter;
  1289. });
  1290. }
  1291. return cache; // else, return all
  1292. }
  1293. /* Loading State
  1294. -----------------------------------------------------------------------------*/
  1295. function pushLoading() {
  1296. if (!(loadingLevel++)) {
  1297. trigger('loading', null, true, getView());
  1298. }
  1299. }
  1300. function popLoading() {
  1301. if (!(--loadingLevel)) {
  1302. trigger('loading', null, false, getView());
  1303. }
  1304. }
  1305. /* Event Normalization
  1306. -----------------------------------------------------------------------------*/
  1307. function buildEvent(data, source) { // source may be undefined!
  1308. var out = {};
  1309. var start;
  1310. var end;
  1311. var allDay;
  1312. var allDayDefault;
  1313. if (options.eventDataTransform) {
  1314. data = options.eventDataTransform(data);
  1315. }
  1316. if (source && source.eventDataTransform) {
  1317. data = source.eventDataTransform(data);
  1318. }
  1319. start = t.moment(data.start || data.date); // "date" is an alias for "start"
  1320. if (!start.isValid()) {
  1321. return;
  1322. }
  1323. end = null;
  1324. if (data.end) {
  1325. end = t.moment(data.end);
  1326. if (!end.isValid()) {
  1327. return;
  1328. }
  1329. }
  1330. allDay = data.allDay;
  1331. if (allDay === undefined) {
  1332. allDayDefault = firstDefined(
  1333. source ? source.allDayDefault : undefined,
  1334. options.allDayDefault
  1335. );
  1336. if (allDayDefault !== undefined) {
  1337. // use the default
  1338. allDay = allDayDefault;
  1339. }
  1340. else {
  1341. // all dates need to have ambig time for the event to be considered allDay
  1342. allDay = !start.hasTime() && (!end || !end.hasTime());
  1343. }
  1344. }
  1345. // normalize the date based on allDay
  1346. if (allDay) {
  1347. // neither date should have a time
  1348. if (start.hasTime()) {
  1349. start.stripTime();
  1350. }
  1351. if (end && end.hasTime()) {
  1352. end.stripTime();
  1353. }
  1354. }
  1355. else {
  1356. // force a time/zone up the dates
  1357. if (!start.hasTime()) {
  1358. start = t.rezoneDate(start);
  1359. }
  1360. if (end && !end.hasTime()) {
  1361. end = t.rezoneDate(end);
  1362. }
  1363. }
  1364. // Copy all properties over to the resulting object.
  1365. // The special-case properties will be copied over afterwards.
  1366. $.extend(out, data);
  1367. if (source) {
  1368. out.source = source;
  1369. }
  1370. out._id = data._id || (data.id === undefined ? '_fc' + eventGUID++ : data.id + '');
  1371. if (data.className) {
  1372. if (typeof data.className == 'string') {
  1373. out.className = data.className.split(/\s+/);
  1374. }
  1375. else { // assumed to be an array
  1376. out.className = data.className;
  1377. }
  1378. }
  1379. else {
  1380. out.className = [];
  1381. }
  1382. out.allDay = allDay;
  1383. out.start = start;
  1384. out.end = end;
  1385. if (options.forceEventDuration && !out.end) {
  1386. out.end = getEventEnd(out);
  1387. }
  1388. backupEventDates(out);
  1389. return out;
  1390. }
  1391. /* Event Modification Math
  1392. -----------------------------------------------------------------------------------------*/
  1393. // Modify the date(s) of an event and make this change propagate to all other events with
  1394. // the same ID (related repeating events).
  1395. //
  1396. // If `newStart`/`newEnd` are not specified, the "new" dates are assumed to be `event.start` and `event.end`.
  1397. // The "old" dates to be compare against are always `event._start` and `event._end` (set by EventManager).
  1398. //
  1399. // Returns an object with delta information and a function to undo all operations.
  1400. //
  1401. function mutateEvent(event, newStart, newEnd) {
  1402. var oldAllDay = event._allDay;
  1403. var oldStart = event._start;
  1404. var oldEnd = event._end;
  1405. var clearEnd = false;
  1406. var newAllDay;
  1407. var dateDelta;
  1408. var durationDelta;
  1409. var undoFunc;
  1410. // if no new dates were passed in, compare against the event's existing dates
  1411. if (!newStart && !newEnd) {
  1412. newStart = event.start;
  1413. newEnd = event.end;
  1414. }
  1415. // NOTE: throughout this function, the initial values of `newStart` and `newEnd` are
  1416. // preserved. These values may be undefined.
  1417. // detect new allDay
  1418. if (event.allDay != oldAllDay) { // if value has changed, use it
  1419. newAllDay = event.allDay;
  1420. }
  1421. else { // otherwise, see if any of the new dates are allDay
  1422. newAllDay = !(newStart || newEnd).hasTime();
  1423. }
  1424. // normalize the new dates based on allDay
  1425. if (newAllDay) {
  1426. if (newStart) {
  1427. newStart = newStart.clone().stripTime();
  1428. }
  1429. if (newEnd) {
  1430. newEnd = newEnd.clone().stripTime();
  1431. }
  1432. }
  1433. // compute dateDelta
  1434. if (newStart) {
  1435. if (newAllDay) {
  1436. dateDelta = dayishDiff(newStart, oldStart.clone().stripTime()); // treat oldStart as allDay
  1437. }
  1438. else {
  1439. dateDelta = dayishDiff(newStart, oldStart);
  1440. }
  1441. }
  1442. if (newAllDay != oldAllDay) {
  1443. // if allDay has changed, always throw away the end
  1444. clearEnd = true;
  1445. }
  1446. else if (newEnd) {
  1447. durationDelta = dayishDiff(
  1448. // new duration
  1449. newEnd || t.getDefaultEventEnd(newAllDay, newStart || oldStart),
  1450. newStart || oldStart
  1451. ).subtract(dayishDiff(
  1452. // subtract old duration
  1453. oldEnd || t.getDefaultEventEnd(oldAllDay, oldStart),
  1454. oldStart
  1455. ));
  1456. }
  1457. undoFunc = mutateEvents(
  1458. clientEvents(event._id), // get events with this ID
  1459. clearEnd,
  1460. newAllDay,
  1461. dateDelta,
  1462. durationDelta
  1463. );
  1464. return {
  1465. dateDelta: dateDelta,
  1466. durationDelta: durationDelta,
  1467. undo: undoFunc
  1468. };
  1469. }
  1470. // Modifies an array of events in the following ways (operations are in order):
  1471. // - clear the event's `end`
  1472. // - convert the event to allDay
  1473. // - add `dateDelta` to the start and end
  1474. // - add `durationDelta` to the event's duration
  1475. //
  1476. // Returns a function that can be called to undo all the operations.
  1477. //
  1478. function mutateEvents(events, clearEnd, forceAllDay, dateDelta, durationDelta) {
  1479. var isAmbigTimezone = t.getIsAmbigTimezone();
  1480. var undoFunctions = [];
  1481. $.each(events, function(i, event) {
  1482. var oldAllDay = event._allDay;
  1483. var oldStart = event._start;
  1484. var oldEnd = event._end;
  1485. var newAllDay = forceAllDay != null ? forceAllDay : oldAllDay;
  1486. var newStart = oldStart.clone();
  1487. var newEnd = (!clearEnd && oldEnd) ? oldEnd.clone() : null;
  1488. // NOTE: this function is responsible for transforming `newStart` and `newEnd`,
  1489. // which were initialized to the OLD values first. `newEnd` may be null.
  1490. // normlize newStart/newEnd to be consistent with newAllDay
  1491. if (newAllDay) {
  1492. newStart.stripTime();
  1493. if (newEnd) {
  1494. newEnd.stripTime();
  1495. }
  1496. }
  1497. else {
  1498. if (!newStart.hasTime()) {
  1499. newStart = t.rezoneDate(newStart);
  1500. }
  1501. if (newEnd && !newEnd.hasTime()) {
  1502. newEnd = t.rezoneDate(newEnd);
  1503. }
  1504. }
  1505. // ensure we have an end date if necessary
  1506. if (!newEnd && (options.forceEventDuration || +durationDelta)) {
  1507. newEnd = t.getDefaultEventEnd(newAllDay, newStart);
  1508. }
  1509. // translate the dates
  1510. newStart.add(dateDelta);
  1511. if (newEnd) {
  1512. newEnd.add(dateDelta).add(durationDelta);
  1513. }
  1514. // if the dates have changed, and we know it is impossible to recompute the
  1515. // timezone offsets, strip the zone.
  1516. if (isAmbigTimezone) {
  1517. if (+dateDelta || +durationDelta) {
  1518. newStart.stripZone();
  1519. if (newEnd) {
  1520. newEnd.stripZone();
  1521. }
  1522. }
  1523. }
  1524. event.allDay = newAllDay;
  1525. event.start = newStart;
  1526. event.end = newEnd;
  1527. backupEventDates(event);
  1528. undoFunctions.push(function() {
  1529. event.allDay = oldAllDay;
  1530. event.start = oldStart;
  1531. event.end = oldEnd;
  1532. backupEventDates(event);
  1533. });
  1534. });
  1535. return function() {
  1536. for (var i=0; i<undoFunctions.length; i++) {
  1537. undoFunctions[i]();
  1538. }
  1539. };
  1540. }
  1541. }
  1542. // updates the "backup" properties, which are preserved in order to compute diffs later on.
  1543. function backupEventDates(event) {
  1544. event._allDay = event.allDay;
  1545. event._start = event.start.clone();
  1546. event._end = event.end ? event.end.clone() : null;
  1547. }
  1548. ;;
  1549. fc.applyAll = applyAll;
  1550. // Create an object that has the given prototype.
  1551. // Just like Object.create
  1552. function createObject(proto) {
  1553. var f = function() {};
  1554. f.prototype = proto;
  1555. return new f();
  1556. }
  1557. // Copies specifically-owned (non-protoype) properties of `b` onto `a`.
  1558. // FYI, $.extend would copy *all* properties of `b` onto `a`.
  1559. function extend(a, b) {
  1560. for (var i in b) {
  1561. if (b.hasOwnProperty(i)) {
  1562. a[i] = b[i];
  1563. }
  1564. }
  1565. }
  1566. /* Date
  1567. -----------------------------------------------------------------------------*/
  1568. var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
  1569. // diffs the two moments into a Duration where full-days are recorded first,
  1570. // then the remaining time.
  1571. function dayishDiff(d1, d0) {
  1572. return moment.duration({
  1573. days: d1.clone().stripTime().diff(d0.clone().stripTime(), 'days'),
  1574. ms: d1.time() - d0.time()
  1575. });
  1576. }
  1577. function isNativeDate(input) {
  1578. return Object.prototype.toString.call(input) === '[object Date]' ||
  1579. input instanceof Date;
  1580. }
  1581. /* Event Element Binding
  1582. -----------------------------------------------------------------------------*/
  1583. function lazySegBind(container, segs, bindHandlers) {
  1584. container.unbind('mouseover').mouseover(function(ev) {
  1585. var parent=ev.target, e,
  1586. i, seg;
  1587. while (parent != this) {
  1588. e = parent;
  1589. parent = parent.parentNode;
  1590. }
  1591. if ((i = e._fci) !== undefined) {
  1592. e._fci = undefined;
  1593. seg = segs[i];
  1594. bindHandlers(seg.event, seg.element, seg);
  1595. $(ev.target).trigger(ev);
  1596. }
  1597. ev.stopPropagation();
  1598. });
  1599. }
  1600. /* Element Dimensions
  1601. -----------------------------------------------------------------------------*/
  1602. function setOuterWidth(element, width, includeMargins) {
  1603. for (var i=0, e; i<element.length; i++) {
  1604. e = $(element[i]);
  1605. e.width(Math.max(0, width - hsides(e, includeMargins)));
  1606. }
  1607. }
  1608. function setOuterHeight(element, height, includeMargins) {
  1609. for (var i=0, e; i<element.length; i++) {
  1610. e = $(element[i]);
  1611. e.height(Math.max(0, height - vsides(e, includeMargins)));
  1612. }
  1613. }
  1614. function hsides(element, includeMargins) {
  1615. return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0);
  1616. }
  1617. function hpadding(element) {
  1618. return (parseFloat($.css(element[0], 'paddingLeft', true)) || 0) +
  1619. (parseFloat($.css(element[0], 'paddingRight', true)) || 0);
  1620. }
  1621. function hmargins(element) {
  1622. return (parseFloat($.css(element[0], 'marginLeft', true)) || 0) +
  1623. (parseFloat($.css(element[0], 'marginRight', true)) || 0);
  1624. }
  1625. function hborders(element) {
  1626. return (parseFloat($.css(element[0], 'borderLeftWidth', true)) || 0) +
  1627. (parseFloat($.css(element[0], 'borderRightWidth', true)) || 0);
  1628. }
  1629. function vsides(element, includeMargins) {
  1630. return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0);
  1631. }
  1632. function vpadding(element) {
  1633. return (parseFloat($.css(element[0], 'paddingTop', true)) || 0) +
  1634. (parseFloat($.css(element[0], 'paddingBottom', true)) || 0);
  1635. }
  1636. function vmargins(element) {
  1637. return (parseFloat($.css(element[0], 'marginTop', true)) || 0) +
  1638. (parseFloat($.css(element[0], 'marginBottom', true)) || 0);
  1639. }
  1640. function vborders(element) {
  1641. return (parseFloat($.css(element[0], 'borderTopWidth', true)) || 0) +
  1642. (parseFloat($.css(element[0], 'borderBottomWidth', true)) || 0);
  1643. }
  1644. /* Misc Utils
  1645. -----------------------------------------------------------------------------*/
  1646. //TODO: arraySlice
  1647. //TODO: isFunction, grep ?
  1648. function noop() { }
  1649. function dateCompare(a, b) { // works with moments too
  1650. return a - b;
  1651. }
  1652. function arrayMax(a) {
  1653. return Math.max.apply(Math, a);
  1654. }
  1655. function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object
  1656. obj = obj || {};
  1657. if (obj[name] !== undefined) {
  1658. return obj[name];
  1659. }
  1660. var parts = name.split(/(?=[A-Z])/),
  1661. i=parts.length-1, res;
  1662. for (; i>=0; i--) {
  1663. res = obj[parts[i].toLowerCase()];
  1664. if (res !== undefined) {
  1665. return res;
  1666. }
  1667. }
  1668. return obj['default'];
  1669. }
  1670. function htmlEscape(s) {
  1671. return (s + '').replace(/&/g, '&amp;')
  1672. .replace(/</g, '&lt;')
  1673. .replace(/>/g, '&gt;')
  1674. .replace(/'/g, '&#039;')
  1675. .replace(/"/g, '&quot;')
  1676. .replace(/\n/g, '<br />');
  1677. }
  1678. function stripHTMLEntities(text) {
  1679. return text.replace(/&.*?;/g, '');
  1680. }
  1681. function disableTextSelection(element) {
  1682. element
  1683. .attr('unselectable', 'on')
  1684. .css('MozUserSelect', 'none')
  1685. .bind('selectstart.ui', function() { return false; });
  1686. }
  1687. /*
  1688. function enableTextSelection(element) {
  1689. element
  1690. .attr('unselectable', 'off')
  1691. .css('MozUserSelect', '')
  1692. .unbind('selectstart.ui');
  1693. }
  1694. */
  1695. function markFirstLast(e) { // TODO: use CSS selectors instead
  1696. e.children()
  1697. .removeClass('fc-first fc-last')
  1698. .filter(':first-child')
  1699. .addClass('fc-first')
  1700. .end()
  1701. .filter(':last-child')
  1702. .addClass('fc-last');
  1703. }
  1704. function getSkinCss(event, opt) {
  1705. var source = event.source || {};
  1706. var eventColor = event.color;
  1707. var sourceColor = source.color;
  1708. var optionColor = opt('eventColor');
  1709. var backgroundColor =
  1710. event.backgroundColor ||
  1711. eventColor ||
  1712. source.backgroundColor ||
  1713. sourceColor ||
  1714. opt('eventBackgroundColor') ||
  1715. optionColor;
  1716. var borderColor =
  1717. event.borderColor ||
  1718. eventColor ||
  1719. source.borderColor ||
  1720. sourceColor ||
  1721. opt('eventBorderColor') ||
  1722. optionColor;
  1723. var textColor =
  1724. event.textColor ||
  1725. source.textColor ||
  1726. opt('eventTextColor');
  1727. var statements = [];
  1728. if (backgroundColor) {
  1729. statements.push('background-color:' + backgroundColor);
  1730. }
  1731. if (borderColor) {
  1732. statements.push('border-color:' + borderColor);
  1733. }
  1734. if (textColor) {
  1735. statements.push('color:' + textColor);
  1736. }
  1737. return statements.join(';');
  1738. }
  1739. function applyAll(functions, thisObj, args) {
  1740. if ($.isFunction(functions)) {
  1741. functions = [ functions ];
  1742. }
  1743. if (functions) {
  1744. var i;
  1745. var ret;
  1746. for (i=0; i<functions.length; i++) {
  1747. ret = functions[i].apply(thisObj, args) || ret;
  1748. }
  1749. return ret;
  1750. }
  1751. }
  1752. function firstDefined() {
  1753. for (var i=0; i<arguments.length; i++) {
  1754. if (arguments[i] !== undefined) {
  1755. return arguments[i];
  1756. }
  1757. }
  1758. }
  1759. ;;
  1760. var ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/;
  1761. var ambigTimeOrZoneRegex = /^\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+)?)?)?)?)?$/;
  1762. // Creating
  1763. // -------------------------------------------------------------------------------------------------
  1764. // Creates a new moment, similar to the vanilla moment(...) constructor, but with
  1765. // extra features (ambiguous time, enhanced formatting). When gived an existing moment,
  1766. // it will function as a clone (and retain the zone of the moment). Anything else will
  1767. // result in a moment in the local zone.
  1768. fc.moment = function() {
  1769. return makeMoment(arguments);
  1770. };
  1771. // Sames as fc.moment, but forces the resulting moment to be in the UTC timezone.
  1772. fc.moment.utc = function() {
  1773. var mom = makeMoment(arguments, true);
  1774. // Force it into UTC because makeMoment doesn't guarantee it.
  1775. if (mom.hasTime()) { // don't give ambiguously-timed moments a UTC zone
  1776. mom.utc();
  1777. }
  1778. return mom;
  1779. };
  1780. // Same as fc.moment, but when given an ISO8601 string, the timezone offset is preserved.
  1781. // ISO8601 strings with no timezone offset will become ambiguously zoned.
  1782. fc.moment.parseZone = function() {
  1783. return makeMoment(arguments, true, true);
  1784. };
  1785. // Builds an FCMoment from args. When given an existing moment, it clones. When given a native
  1786. // Date, or called with no arguments (the current time), the resulting moment will be local.
  1787. // Anything else needs to be "parsed" (a string or an array), and will be affected by:
  1788. // parseAsUTC - if there is no zone information, should we parse the input in UTC?
  1789. // parseZone - if there is zone information, should we force the zone of the moment?
  1790. function makeMoment(args, parseAsUTC, parseZone) {
  1791. var input = args[0];
  1792. var isSingleString = args.length == 1 && typeof input === 'string';
  1793. var isAmbigTime;
  1794. var isAmbigZone;
  1795. var ambigMatch;
  1796. var output; // an object with fields for the new FCMoment object
  1797. if (moment.isMoment(input)) {
  1798. output = moment.apply(null, args); // clone it
  1799. // the ambig properties have not been preserved in the clone, so reassign them
  1800. if (input._ambigTime) {
  1801. output._ambigTime = true;
  1802. }
  1803. if (input._ambigZone) {
  1804. output._ambigZone = true;
  1805. }
  1806. }
  1807. else if (isNativeDate(input) || input === undefined) {
  1808. output = moment.apply(null, args); // will be local
  1809. }
  1810. else { // "parsing" is required
  1811. isAmbigTime = false;
  1812. isAmbigZone = false;
  1813. if (isSingleString) {
  1814. if (ambigDateOfMonthRegex.test(input)) {
  1815. // accept strings like '2014-05', but convert to the first of the month
  1816. input += '-01';
  1817. args = [ input ]; // for when we pass it on to moment's constructor
  1818. isAmbigTime = true;
  1819. isAmbigZone = true;
  1820. }
  1821. else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) {
  1822. isAmbigTime = !ambigMatch[5]; // no time part?
  1823. isAmbigZone = true;
  1824. }
  1825. }
  1826. else if ($.isArray(input)) {
  1827. // arrays have no timezone information, so assume ambiguous zone
  1828. isAmbigZone = true;
  1829. }
  1830. // otherwise, probably a string with a format
  1831. if (parseAsUTC) {
  1832. output = moment.utc.apply(moment, args);
  1833. }
  1834. else {
  1835. output = moment.apply(null, args);
  1836. }
  1837. if (isAmbigTime) {
  1838. output._ambigTime = true;
  1839. output._ambigZone = true; // ambiguous time always means ambiguous zone
  1840. }
  1841. else if (parseZone) { // let's record the inputted zone somehow
  1842. if (isAmbigZone) {
  1843. output._ambigZone = true;
  1844. }
  1845. else if (isSingleString) {
  1846. output.zone(input); // if not a valid zone, will assign UTC
  1847. }
  1848. }
  1849. }
  1850. return new FCMoment(output);
  1851. }
  1852. // Our subclass of Moment.
  1853. // Accepts an object with the internal Moment properties that should be copied over to
  1854. // `this` object (most likely another Moment object). The values in this data must not
  1855. // be referenced by anything else (two moments sharing a Date object for example).
  1856. function FCMoment(internalData) {
  1857. extend(this, internalData);
  1858. }
  1859. // Chain the prototype to Moment's
  1860. FCMoment.prototype = createObject(moment.fn);
  1861. // We need this because Moment's implementation won't create an FCMoment,
  1862. // nor will it copy over the ambig flags.
  1863. FCMoment.prototype.clone = function() {
  1864. return makeMoment([ this ]);
  1865. };
  1866. // Time-of-day
  1867. // -------------------------------------------------------------------------------------------------
  1868. // GETTER
  1869. // Returns a Duration with the hours/minutes/seconds/ms values of the moment.
  1870. // If the moment has an ambiguous time, a duration of 00:00 will be returned.
  1871. //
  1872. // SETTER
  1873. // You can supply a Duration, a Moment, or a Duration-like argument.
  1874. // When setting the time, and the moment has an ambiguous time, it then becomes unambiguous.
  1875. FCMoment.prototype.time = function(time) {
  1876. if (time == null) { // getter
  1877. return moment.duration({
  1878. hours: this.hours(),
  1879. minutes: this.minutes(),
  1880. seconds: this.seconds(),
  1881. milliseconds: this.milliseconds()
  1882. });
  1883. }
  1884. else { // setter
  1885. delete this._ambigTime; // mark that the moment now has a time
  1886. if (!moment.isDuration(time) && !moment.isMoment(time)) {
  1887. time = moment.duration(time);
  1888. }
  1889. // The day value should cause overflow (so 24 hours becomes 00:00:00 of next day).
  1890. // Only for Duration times, not Moment times.
  1891. var dayHours = 0;
  1892. if (moment.isDuration(time)) {
  1893. dayHours = Math.floor(time.asDays()) * 24;
  1894. }
  1895. // We need to set the individual fields.
  1896. // Can't use startOf('day') then add duration. In case of DST at start of day.
  1897. return this.hours(dayHours + time.hours())
  1898. .minutes(time.minutes())
  1899. .seconds(time.seconds())
  1900. .milliseconds(time.milliseconds());
  1901. }
  1902. };
  1903. // Converts the moment to UTC, stripping out its time-of-day and timezone offset,
  1904. // but preserving its YMD. A moment with a stripped time will display no time
  1905. // nor timezone offset when .format() is called.
  1906. FCMoment.prototype.stripTime = function() {
  1907. var a = this.toArray(); // year,month,date,hours,minutes,seconds as an array
  1908. // set the internal UTC flag
  1909. moment.fn.utc.call(this); // call the original method, because we don't want to affect _ambigZone
  1910. this.year(a[0]) // TODO: find a way to do this in one shot
  1911. .month(a[1])
  1912. .date(a[2])
  1913. .hours(0)
  1914. .minutes(0)
  1915. .seconds(0)
  1916. .milliseconds(0);
  1917. // Mark the time as ambiguous. This needs to happen after the .utc() call, which calls .zone(), which
  1918. // clears all ambig flags. Same concept with the .year/month/date calls in the case of moment-timezone.
  1919. this._ambigTime = true;
  1920. this._ambigZone = true; // if ambiguous time, also ambiguous timezone offset
  1921. return this; // for chaining
  1922. };
  1923. // Returns if the moment has a non-ambiguous time (boolean)
  1924. FCMoment.prototype.hasTime = function() {
  1925. return !this._ambigTime;
  1926. };
  1927. // Timezone
  1928. // -------------------------------------------------------------------------------------------------
  1929. // Converts the moment to UTC, stripping out its timezone offset, but preserving its
  1930. // YMD and time-of-day. A moment with a stripped timezone offset will display no
  1931. // timezone offset when .format() is called.
  1932. FCMoment.prototype.stripZone = function() {
  1933. var a = this.toArray(); // year,month,date,hours,minutes,seconds as an array
  1934. var wasAmbigTime = this._ambigTime;
  1935. moment.fn.utc.call(this); // set the internal UTC flag
  1936. this.year(a[0]) // TODO: find a way to do this in one shot
  1937. .month(a[1])
  1938. .date(a[2])
  1939. .hours(a[3])
  1940. .minutes(a[4])
  1941. .seconds(a[5])
  1942. .milliseconds(a[6]);
  1943. if (wasAmbigTime) {
  1944. // the above call to .utc()/.zone() unfortunately clears the ambig flags, so reassign
  1945. this._ambigTime = true;
  1946. }
  1947. // Mark the zone as ambiguous. This needs to happen after the .utc() call, which calls .zone(), which
  1948. // clears all ambig flags. Same concept with the .year/month/date calls in the case of moment-timezone.
  1949. this._ambigZone = true;
  1950. return this; // for chaining
  1951. };
  1952. // Returns of the moment has a non-ambiguous timezone offset (boolean)
  1953. FCMoment.prototype.hasZone = function() {
  1954. return !this._ambigZone;
  1955. };
  1956. // this method implicitly marks a zone
  1957. FCMoment.prototype.zone = function(tzo) {
  1958. if (tzo != null) {
  1959. // FYI, the delete statements need to be before the .zone() call or else chaos ensues
  1960. // for reasons I don't understand.
  1961. delete this._ambigTime;
  1962. delete this._ambigZone;
  1963. }
  1964. return moment.fn.zone.apply(this, arguments);
  1965. };
  1966. // this method implicitly marks a zone
  1967. FCMoment.prototype.local = function() {
  1968. var a = this.toArray(); // year,month,date,hours,minutes,seconds as an array
  1969. var wasAmbigZone = this._ambigZone;
  1970. // will happen anyway via .local()/.zone(), but don't want to rely on internal implementation
  1971. delete this._ambigTime;
  1972. delete this._ambigZone;
  1973. moment.fn.local.apply(this, arguments);
  1974. if (wasAmbigZone) {
  1975. // If the moment was ambiguously zoned, the date fields were stored as UTC.
  1976. // We want to preserve these, but in local time.
  1977. this.year(a[0]) // TODO: find a way to do this in one shot
  1978. .month(a[1])
  1979. .date(a[2])
  1980. .hours(a[3])
  1981. .minutes(a[4])
  1982. .seconds(a[5])
  1983. .milliseconds(a[6]);
  1984. }
  1985. return this; // for chaining
  1986. };
  1987. // this method implicitly marks a zone
  1988. FCMoment.prototype.utc = function() {
  1989. // will happen anyway via .local()/.zone(), but don't want to rely on internal implementation
  1990. delete this._ambigTime;
  1991. delete this._ambigZone;
  1992. return moment.fn.utc.apply(this, arguments);
  1993. };
  1994. // Formatting
  1995. // -------------------------------------------------------------------------------------------------
  1996. FCMoment.prototype.format = function() {
  1997. if (arguments[0]) {
  1998. return formatDate(this, arguments[0]); // our extended formatting
  1999. }
  2000. if (this._ambigTime) {
  2001. return momentFormat(this, 'YYYY-MM-DD');
  2002. }
  2003. if (this._ambigZone) {
  2004. return momentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  2005. }
  2006. return momentFormat(this); // default moment original formatting
  2007. };
  2008. FCMoment.prototype.toISOString = function() {
  2009. if (this._ambigTime) {
  2010. return momentFormat(this, 'YYYY-MM-DD');
  2011. }
  2012. if (this._ambigZone) {
  2013. return momentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
  2014. }
  2015. return moment.fn.toISOString.apply(this, arguments);
  2016. };
  2017. // Querying
  2018. // -------------------------------------------------------------------------------------------------
  2019. // Is the moment within the specified range? `end` is exclusive.
  2020. FCMoment.prototype.isWithin = function(start, end) {
  2021. var a = commonlyAmbiguate([ this, start, end ]);
  2022. return a[0] >= a[1] && a[0] < a[2];
  2023. };
  2024. // Make these query methods work with ambiguous moments
  2025. $.each([
  2026. 'isBefore',
  2027. 'isAfter',
  2028. 'isSame'
  2029. ], function(i, methodName) {
  2030. FCMoment.prototype[methodName] = function(input, units) {
  2031. var a = commonlyAmbiguate([ this, input ]);
  2032. return moment.fn[methodName].call(a[0], a[1], units);
  2033. };
  2034. });
  2035. // Misc Internals
  2036. // -------------------------------------------------------------------------------------------------
  2037. // given an array of moment-like inputs, return a parallel array w/ moments similarly ambiguated.
  2038. // for example, of one moment has ambig time, but not others, all moments will have their time stripped.
  2039. function commonlyAmbiguate(inputs) {
  2040. var outputs = [];
  2041. var anyAmbigTime = false;
  2042. var anyAmbigZone = false;
  2043. var i;
  2044. for (i=0; i<inputs.length; i++) {
  2045. outputs.push(fc.moment(inputs[i]));
  2046. anyAmbigTime = anyAmbigTime || outputs[i]._ambigTime;
  2047. anyAmbigZone = anyAmbigZone || outputs[i]._ambigZone;
  2048. }
  2049. for (i=0; i<outputs.length; i++) {
  2050. if (anyAmbigTime) {
  2051. outputs[i].stripTime();
  2052. }
  2053. else if (anyAmbigZone) {
  2054. outputs[i].stripZone();
  2055. }
  2056. }
  2057. return outputs;
  2058. }
  2059. ;;
  2060. // Single Date Formatting
  2061. // -------------------------------------------------------------------------------------------------
  2062. // call this if you want Moment's original format method to be used
  2063. function momentFormat(mom, formatStr) {
  2064. return moment.fn.format.call(mom, formatStr);
  2065. }
  2066. // Formats `date` with a Moment formatting string, but allow our non-zero areas and
  2067. // additional token.
  2068. function formatDate(date, formatStr) {
  2069. return formatDateWithChunks(date, getFormatStringChunks(formatStr));
  2070. }
  2071. function formatDateWithChunks(date, chunks) {
  2072. var s = '';
  2073. var i;
  2074. for (i=0; i<chunks.length; i++) {
  2075. s += formatDateWithChunk(date, chunks[i]);
  2076. }
  2077. return s;
  2078. }
  2079. // addition formatting tokens we want recognized
  2080. var tokenOverrides = {
  2081. t: function(date) { // "a" or "p"
  2082. return momentFormat(date, 'a').charAt(0);
  2083. },
  2084. T: function(date) { // "A" or "P"
  2085. return momentFormat(date, 'A').charAt(0);
  2086. }
  2087. };
  2088. function formatDateWithChunk(date, chunk) {
  2089. var token;
  2090. var maybeStr;
  2091. if (typeof chunk === 'string') { // a literal string
  2092. return chunk;
  2093. }
  2094. else if ((token = chunk.token)) { // a token, like "YYYY"
  2095. if (tokenOverrides[token]) {
  2096. return tokenOverrides[token](date); // use our custom token
  2097. }
  2098. return momentFormat(date, token);
  2099. }
  2100. else if (chunk.maybe) { // a grouping of other chunks that must be non-zero
  2101. maybeStr = formatDateWithChunks(date, chunk.maybe);
  2102. if (maybeStr.match(/[1-9]/)) {
  2103. return maybeStr;
  2104. }
  2105. }
  2106. return '';
  2107. }
  2108. // Date Range Formatting
  2109. // -------------------------------------------------------------------------------------------------
  2110. // TODO: make it work with timezone offset
  2111. // Using a formatting string meant for a single date, generate a range string, like
  2112. // "Sep 2 - 9 2013", that intelligently inserts a separator where the dates differ.
  2113. // If the dates are the same as far as the format string is concerned, just return a single
  2114. // rendering of one date, without any separator.
  2115. function formatRange(date1, date2, formatStr, separator, isRTL) {
  2116. var localeData;
  2117. date1 = fc.moment.parseZone(date1);
  2118. date2 = fc.moment.parseZone(date2);
  2119. localeData = (date1.localeData || date1.lang).call(date1); // works with moment-pre-2.8
  2120. // Expand localized format strings, like "LL" -> "MMMM D YYYY"
  2121. formatStr = localeData.longDateFormat(formatStr) || formatStr;
  2122. // BTW, this is not important for `formatDate` because it is impossible to put custom tokens
  2123. // or non-zero areas in Moment's localized format strings.
  2124. separator = separator || ' - ';
  2125. return formatRangeWithChunks(
  2126. date1,
  2127. date2,
  2128. getFormatStringChunks(formatStr),
  2129. separator,
  2130. isRTL
  2131. );
  2132. }
  2133. fc.formatRange = formatRange; // expose
  2134. function formatRangeWithChunks(date1, date2, chunks, separator, isRTL) {
  2135. var chunkStr; // the rendering of the chunk
  2136. var leftI;
  2137. var leftStr = '';
  2138. var rightI;
  2139. var rightStr = '';
  2140. var middleI;
  2141. var middleStr1 = '';
  2142. var middleStr2 = '';
  2143. var middleStr = '';
  2144. // Start at the leftmost side of the formatting string and continue until you hit a token
  2145. // that is not the same between dates.
  2146. for (leftI=0; leftI<chunks.length; leftI++) {
  2147. chunkStr = formatSimilarChunk(date1, date2, chunks[leftI]);
  2148. if (chunkStr === false) {
  2149. break;
  2150. }
  2151. leftStr += chunkStr;
  2152. }
  2153. // Similarly, start at the rightmost side of the formatting string and move left
  2154. for (rightI=chunks.length-1; rightI>leftI; rightI--) {
  2155. chunkStr = formatSimilarChunk(date1, date2, chunks[rightI]);
  2156. if (chunkStr === false) {
  2157. break;
  2158. }
  2159. rightStr = chunkStr + rightStr;
  2160. }
  2161. // The area in the middle is different for both of the dates.
  2162. // Collect them distinctly so we can jam them together later.
  2163. for (middleI=leftI; middleI<=rightI; middleI++) {
  2164. middleStr1 += formatDateWithChunk(date1, chunks[middleI]);
  2165. middleStr2 += formatDateWithChunk(date2, chunks[middleI]);
  2166. }
  2167. if (middleStr1 || middleStr2) {
  2168. if (isRTL) {
  2169. middleStr = middleStr2 + separator + middleStr1;
  2170. }
  2171. else {
  2172. middleStr = middleStr1 + separator + middleStr2;
  2173. }
  2174. }
  2175. return leftStr + middleStr + rightStr;
  2176. }
  2177. var similarUnitMap = {
  2178. Y: 'year',
  2179. M: 'month',
  2180. D: 'day', // day of month
  2181. d: 'day', // day of week
  2182. // prevents a separator between anything time-related...
  2183. A: 'second', // AM/PM
  2184. a: 'second', // am/pm
  2185. T: 'second', // A/P
  2186. t: 'second', // a/p
  2187. H: 'second', // hour (24)
  2188. h: 'second', // hour (12)
  2189. m: 'second', // minute
  2190. s: 'second' // second
  2191. };
  2192. // TODO: week maybe?
  2193. // Given a formatting chunk, and given that both dates are similar in the regard the
  2194. // formatting chunk is concerned, format date1 against `chunk`. Otherwise, return `false`.
  2195. function formatSimilarChunk(date1, date2, chunk) {
  2196. var token;
  2197. var unit;
  2198. if (typeof chunk === 'string') { // a literal string
  2199. return chunk;
  2200. }
  2201. else if ((token = chunk.token)) {
  2202. unit = similarUnitMap[token.charAt(0)];
  2203. // are the dates the same for this unit of measurement?
  2204. if (unit && date1.isSame(date2, unit)) {
  2205. return momentFormat(date1, token); // would be the same if we used `date2`
  2206. // BTW, don't support custom tokens
  2207. }
  2208. }
  2209. return false; // the chunk is NOT the same for the two dates
  2210. // BTW, don't support splitting on non-zero areas
  2211. }
  2212. // Chunking Utils
  2213. // -------------------------------------------------------------------------------------------------
  2214. var formatStringChunkCache = {};
  2215. function getFormatStringChunks(formatStr) {
  2216. if (formatStr in formatStringChunkCache) {
  2217. return formatStringChunkCache[formatStr];
  2218. }
  2219. return (formatStringChunkCache[formatStr] = chunkFormatString(formatStr));
  2220. }
  2221. // Break the formatting string into an array of chunks
  2222. function chunkFormatString(formatStr) {
  2223. var chunks = [];
  2224. var chunker = /\[([^\]]*)\]|\(([^\)]*)\)|(LT|(\w)\4*o?)|([^\w\[\(]+)/g; // TODO: more descrimination
  2225. var match;
  2226. while ((match = chunker.exec(formatStr))) {
  2227. if (match[1]) { // a literal string inside [ ... ]
  2228. chunks.push(match[1]);
  2229. }
  2230. else if (match[2]) { // non-zero formatting inside ( ... )
  2231. chunks.push({ maybe: chunkFormatString(match[2]) });
  2232. }
  2233. else if (match[3]) { // a formatting token
  2234. chunks.push({ token: match[3] });
  2235. }
  2236. else if (match[5]) { // an unenclosed literal string
  2237. chunks.push(match[5]);
  2238. }
  2239. }
  2240. return chunks;
  2241. }
  2242. ;;
  2243. fcViews.month = MonthView;
  2244. function MonthView(element, calendar) {
  2245. var t = this;
  2246. // exports
  2247. t.incrementDate = incrementDate;
  2248. t.render = render;
  2249. // imports
  2250. BasicView.call(t, element, calendar, 'month');
  2251. function incrementDate(date, delta) {
  2252. return date.clone().stripTime().add(delta, 'months').startOf('month');
  2253. }
  2254. function render(date) {
  2255. t.intervalStart = date.clone().stripTime().startOf('month');
  2256. t.intervalEnd = t.intervalStart.clone().add(1, 'months');
  2257. t.start = t.intervalStart.clone();
  2258. t.start = t.skipHiddenDays(t.start); // move past the first week if no visible days
  2259. t.start.startOf('week');
  2260. t.start = t.skipHiddenDays(t.start); // move past the first invisible days of the week
  2261. t.end = t.intervalEnd.clone();
  2262. t.end = t.skipHiddenDays(t.end, -1, true); // move in from the last week if no visible days
  2263. t.end.add((7 - t.end.weekday()) % 7, 'days'); // move to end of week if not already
  2264. t.end = t.skipHiddenDays(t.end, -1, true); // move in from the last invisible days of the week
  2265. var rowCnt = Math.ceil( // need to ceil in case there are hidden days
  2266. t.end.diff(t.start, 'weeks', true) // returnfloat=true
  2267. );
  2268. if (t.opt('weekMode') == 'fixed') {
  2269. t.end.add(6 - rowCnt, 'weeks');
  2270. rowCnt = 6;
  2271. }
  2272. t.title = calendar.formatDate(t.intervalStart, t.opt('titleFormat'));
  2273. t.renderBasic(rowCnt, t.getCellsPerWeek(), true);
  2274. }
  2275. }
  2276. ;;
  2277. fcViews.basicWeek = BasicWeekView;
  2278. function BasicWeekView(element, calendar) { // TODO: do a WeekView mixin
  2279. var t = this;
  2280. // exports
  2281. t.incrementDate = incrementDate;
  2282. t.render = render;
  2283. // imports
  2284. BasicView.call(t, element, calendar, 'basicWeek');
  2285. function incrementDate(date, delta) {
  2286. return date.clone().stripTime().add(delta, 'weeks').startOf('week');
  2287. }
  2288. function render(date) {
  2289. t.intervalStart = date.clone().stripTime().startOf('week');
  2290. t.intervalEnd = t.intervalStart.clone().add(1, 'weeks');
  2291. t.start = t.skipHiddenDays(t.intervalStart);
  2292. t.end = t.skipHiddenDays(t.intervalEnd, -1, true);
  2293. t.title = calendar.formatRange(
  2294. t.start,
  2295. t.end.clone().subtract(1), // make inclusive by subtracting 1 ms
  2296. t.opt('titleFormat'),
  2297. ' \u2014 ' // emphasized dash
  2298. );
  2299. t.renderBasic(1, t.getCellsPerWeek(), false);
  2300. }
  2301. }
  2302. ;;
  2303. fcViews.basicDay = BasicDayView;
  2304. function BasicDayView(element, calendar) { // TODO: make a DayView mixin
  2305. var t = this;
  2306. // exports
  2307. t.incrementDate = incrementDate;
  2308. t.render = render;
  2309. // imports
  2310. BasicView.call(t, element, calendar, 'basicDay');
  2311. function incrementDate(date, delta) {
  2312. var out = date.clone().stripTime().add(delta, 'days');
  2313. out = t.skipHiddenDays(out, delta < 0 ? -1 : 1);
  2314. return out;
  2315. }
  2316. function render(date) {
  2317. t.start = t.intervalStart = date.clone().stripTime();
  2318. t.end = t.intervalEnd = t.start.clone().add(1, 'days');
  2319. t.title = calendar.formatDate(t.start, t.opt('titleFormat'));
  2320. t.renderBasic(1, 1, false);
  2321. }
  2322. }
  2323. ;;
  2324. setDefaults({
  2325. weekMode: 'fixed'
  2326. });
  2327. function BasicView(element, calendar, viewName) {
  2328. var t = this;
  2329. // exports
  2330. t.renderBasic = renderBasic;
  2331. t.setHeight = setHeight;
  2332. t.setWidth = setWidth;
  2333. t.renderDayOverlay = renderDayOverlay;
  2334. t.defaultSelectionEnd = defaultSelectionEnd;
  2335. t.renderSelection = renderSelection;
  2336. t.clearSelection = clearSelection;
  2337. t.reportDayClick = reportDayClick; // for selection (kinda hacky)
  2338. t.dragStart = dragStart;
  2339. t.dragStop = dragStop;
  2340. t.getHoverListener = function() { return hoverListener; };
  2341. t.colLeft = colLeft;
  2342. t.colRight = colRight;
  2343. t.colContentLeft = colContentLeft;
  2344. t.colContentRight = colContentRight;
  2345. t.getIsCellAllDay = function() { return true; };
  2346. t.allDayRow = allDayRow;
  2347. t.getRowCnt = function() { return rowCnt; };
  2348. t.getColCnt = function() { return colCnt; };
  2349. t.getColWidth = function() { return colWidth; };
  2350. t.getDaySegmentContainer = function() { return daySegmentContainer; };
  2351. // imports
  2352. View.call(t, element, calendar, viewName);
  2353. OverlayManager.call(t);
  2354. SelectionManager.call(t);
  2355. BasicEventRenderer.call(t);
  2356. var opt = t.opt;
  2357. var trigger = t.trigger;
  2358. var renderOverlay = t.renderOverlay;
  2359. var clearOverlays = t.clearOverlays;
  2360. var daySelectionMousedown = t.daySelectionMousedown;
  2361. var cellToDate = t.cellToDate;
  2362. var dateToCell = t.dateToCell;
  2363. var rangeToSegments = t.rangeToSegments;
  2364. var formatDate = calendar.formatDate;
  2365. var calculateWeekNumber = calendar.calculateWeekNumber;
  2366. // locals
  2367. var table;
  2368. var head;
  2369. var headCells;
  2370. var body;
  2371. var bodyRows;
  2372. var bodyCells;
  2373. var bodyFirstCells;
  2374. var firstRowCellInners;
  2375. var firstRowCellContentInners;
  2376. var daySegmentContainer;
  2377. var viewWidth;
  2378. var viewHeight;
  2379. var colWidth;
  2380. var weekNumberWidth;
  2381. var rowCnt, colCnt;
  2382. var showNumbers;
  2383. var coordinateGrid;
  2384. var hoverListener;
  2385. var colPositions;
  2386. var colContentPositions;
  2387. var tm;
  2388. var colFormat;
  2389. var showWeekNumbers;
  2390. /* Rendering
  2391. ------------------------------------------------------------*/
  2392. disableTextSelection(element.addClass('fc-grid'));
  2393. function renderBasic(_rowCnt, _colCnt, _showNumbers) {
  2394. rowCnt = _rowCnt;
  2395. colCnt = _colCnt;
  2396. showNumbers = _showNumbers;
  2397. updateOptions();
  2398. if (!body) {
  2399. buildEventContainer();
  2400. }
  2401. buildTable();
  2402. }
  2403. function updateOptions() {
  2404. tm = opt('theme') ? 'ui' : 'fc';
  2405. colFormat = opt('columnFormat');
  2406. showWeekNumbers = opt('weekNumbers');
  2407. }
  2408. function buildEventContainer() {
  2409. daySegmentContainer =
  2410. $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
  2411. .appendTo(element);
  2412. }
  2413. function buildTable() {
  2414. var html = buildTableHTML();
  2415. if (table) {
  2416. table.remove();
  2417. }
  2418. table = $(html).appendTo(element);
  2419. head = table.find('thead');
  2420. headCells = head.find('.fc-day-header');
  2421. body = table.find('tbody');
  2422. bodyRows = body.find('tr');
  2423. bodyCells = body.find('.fc-day');
  2424. bodyFirstCells = bodyRows.find('td:first-child');
  2425. firstRowCellInners = bodyRows.eq(0).find('.fc-day > div');
  2426. firstRowCellContentInners = bodyRows.eq(0).find('.fc-day-content > div');
  2427. markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's
  2428. markFirstLast(bodyRows); // marks first+last td's
  2429. bodyRows.eq(0).addClass('fc-first');
  2430. bodyRows.filter(':last').addClass('fc-last');
  2431. bodyCells.each(function(i, _cell) {
  2432. var date = cellToDate(
  2433. Math.floor(i / colCnt),
  2434. i % colCnt
  2435. );
  2436. trigger('dayRender', t, date, $(_cell));
  2437. });
  2438. dayBind(bodyCells);
  2439. }
  2440. /* HTML Building
  2441. -----------------------------------------------------------*/
  2442. function buildTableHTML() {
  2443. var html =
  2444. "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" +
  2445. buildHeadHTML() +
  2446. buildBodyHTML() +
  2447. "</table>";
  2448. return html;
  2449. }
  2450. function buildHeadHTML() {
  2451. var headerClass = tm + "-widget-header";
  2452. var html = '';
  2453. var col;
  2454. var date;
  2455. html += "<thead><tr>";
  2456. if (showWeekNumbers) {
  2457. html +=
  2458. "<th class='fc-week-number " + headerClass + "'>" +
  2459. htmlEscape(opt('weekNumberTitle')) +
  2460. "</th>";
  2461. }
  2462. for (col=0; col<colCnt; col++) {
  2463. date = cellToDate(0, col);
  2464. html +=
  2465. "<th class='fc-day-header fc-" + dayIDs[date.day()] + " " + headerClass + "'>" +
  2466. htmlEscape(formatDate(date, colFormat)) +
  2467. "</th>";
  2468. }
  2469. html += "</tr></thead>";
  2470. return html;
  2471. }
  2472. function buildBodyHTML() {
  2473. var contentClass = tm + "-widget-content";
  2474. var html = '';
  2475. var row;
  2476. var col;
  2477. var date;
  2478. html += "<tbody>";
  2479. for (row=0; row<rowCnt; row++) {
  2480. html += "<tr class='fc-week'>";
  2481. if (showWeekNumbers) {
  2482. date = cellToDate(row, 0);
  2483. html +=
  2484. "<td class='fc-week-number " + contentClass + "'>" +
  2485. "<div>" +
  2486. htmlEscape(calculateWeekNumber(date)) +
  2487. "</div>" +
  2488. "</td>";
  2489. }
  2490. for (col=0; col<colCnt; col++) {
  2491. date = cellToDate(row, col);
  2492. html += buildCellHTML(date);
  2493. }
  2494. html += "</tr>";
  2495. }
  2496. html += "</tbody>";
  2497. return html;
  2498. }
  2499. function buildCellHTML(date) { // date assumed to have stripped time
  2500. var month = t.intervalStart.month();
  2501. var today = calendar.getNow().stripTime();
  2502. var html = '';
  2503. var contentClass = tm + "-widget-content";
  2504. var classNames = [
  2505. 'fc-day',
  2506. 'fc-' + dayIDs[date.day()],
  2507. contentClass
  2508. ];
  2509. if (date.month() != month) {
  2510. classNames.push('fc-other-month');
  2511. }
  2512. if (date.isSame(today, 'day')) {
  2513. classNames.push(
  2514. 'fc-today',
  2515. tm + '-state-highlight'
  2516. );
  2517. }
  2518. else if (date < today) {
  2519. classNames.push('fc-past');
  2520. }
  2521. else {
  2522. classNames.push('fc-future');
  2523. }
  2524. html +=
  2525. "<td" +
  2526. " class='" + classNames.join(' ') + "'" +
  2527. " data-date='" + date.format() + "'" +
  2528. ">" +
  2529. "<div>";
  2530. if (showNumbers) {
  2531. html += "<div class='fc-day-number'>" + date.date() + "</div>";
  2532. }
  2533. html +=
  2534. "<div class='fc-day-content'>" +
  2535. "<div style='position:relative'>&nbsp;</div>" +
  2536. "</div>" +
  2537. "</div>" +
  2538. "</td>";
  2539. return html;
  2540. }
  2541. /* Dimensions
  2542. -----------------------------------------------------------*/
  2543. function setHeight(height) {
  2544. viewHeight = height;
  2545. var bodyHeight = Math.max(viewHeight - head.height(), 0);
  2546. var rowHeight;
  2547. var rowHeightLast;
  2548. var cell;
  2549. if (opt('weekMode') == 'variable') {
  2550. rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6));
  2551. }else{
  2552. rowHeight = Math.floor(bodyHeight / rowCnt);
  2553. rowHeightLast = bodyHeight - rowHeight * (rowCnt-1);
  2554. }
  2555. bodyFirstCells.each(function(i, _cell) {
  2556. if (i < rowCnt) {
  2557. cell = $(_cell);
  2558. cell.find('> div').css(
  2559. 'min-height',
  2560. (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell)
  2561. );
  2562. }
  2563. });
  2564. }
  2565. function setWidth(width) {
  2566. viewWidth = width;
  2567. colPositions.clear();
  2568. colContentPositions.clear();
  2569. weekNumberWidth = 0;
  2570. if (showWeekNumbers) {
  2571. weekNumberWidth = head.find('th.fc-week-number').outerWidth();
  2572. }
  2573. colWidth = Math.floor((viewWidth - weekNumberWidth) / colCnt);
  2574. setOuterWidth(headCells.slice(0, -1), colWidth);
  2575. }
  2576. /* Day clicking and binding
  2577. -----------------------------------------------------------*/
  2578. function dayBind(days) {
  2579. days.click(dayClick)
  2580. .mousedown(daySelectionMousedown);
  2581. }
  2582. function dayClick(ev) {
  2583. if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
  2584. var date = calendar.moment($(this).data('date'));
  2585. trigger('dayClick', this, date, ev);
  2586. }
  2587. }
  2588. /* Semi-transparent Overlay Helpers
  2589. ------------------------------------------------------*/
  2590. // TODO: should be consolidated with AgendaView's methods
  2591. function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
  2592. if (refreshCoordinateGrid) {
  2593. coordinateGrid.build();
  2594. }
  2595. var segments = rangeToSegments(overlayStart, overlayEnd);
  2596. for (var i=0; i<segments.length; i++) {
  2597. var segment = segments[i];
  2598. dayBind(
  2599. renderCellOverlay(
  2600. segment.row,
  2601. segment.leftCol,
  2602. segment.row,
  2603. segment.rightCol
  2604. )
  2605. );
  2606. }
  2607. }
  2608. function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive
  2609. var rect = coordinateGrid.rect(row0, col0, row1, col1, element);
  2610. return renderOverlay(rect, element);
  2611. }
  2612. /* Selection
  2613. -----------------------------------------------------------------------*/
  2614. function defaultSelectionEnd(start) {
  2615. return start.clone().stripTime().add(1, 'days');
  2616. }
  2617. function renderSelection(start, end) { // end is exclusive
  2618. renderDayOverlay(start, end, true); // true = rebuild every time
  2619. }
  2620. function clearSelection() {
  2621. clearOverlays();
  2622. }
  2623. function reportDayClick(date, ev) {
  2624. var cell = dateToCell(date);
  2625. var _element = bodyCells[cell.row*colCnt + cell.col];
  2626. trigger('dayClick', _element, date, ev);
  2627. }
  2628. /* External Dragging
  2629. -----------------------------------------------------------------------*/
  2630. function dragStart(_dragElement, ev, ui) {
  2631. hoverListener.start(function(cell) {
  2632. clearOverlays();
  2633. if (cell) {
  2634. var d1 = cellToDate(cell);
  2635. var d2 = d1.clone().add(calendar.defaultAllDayEventDuration);
  2636. renderDayOverlay(d1, d2);
  2637. }
  2638. }, ev);
  2639. }
  2640. function dragStop(_dragElement, ev, ui) {
  2641. var cell = hoverListener.stop();
  2642. clearOverlays();
  2643. if (cell) {
  2644. trigger(
  2645. 'drop',
  2646. _dragElement,
  2647. cellToDate(cell),
  2648. ev,
  2649. ui
  2650. );
  2651. }
  2652. }
  2653. /* Utilities
  2654. --------------------------------------------------------*/
  2655. coordinateGrid = new CoordinateGrid(function(rows, cols) {
  2656. var e, n, p;
  2657. headCells.each(function(i, _e) {
  2658. e = $(_e);
  2659. n = e.offset().left;
  2660. if (i) {
  2661. p[1] = n;
  2662. }
  2663. p = [n];
  2664. cols[i] = p;
  2665. });
  2666. p[1] = n + e.outerWidth();
  2667. bodyRows.each(function(i, _e) {
  2668. if (i < rowCnt) {
  2669. e = $(_e);
  2670. n = e.offset().top;
  2671. if (i) {
  2672. p[1] = n;
  2673. }
  2674. p = [n];
  2675. rows[i] = p;
  2676. }
  2677. });
  2678. p[1] = n + e.outerHeight();
  2679. });
  2680. hoverListener = new HoverListener(coordinateGrid);
  2681. colPositions = new HorizontalPositionCache(function(col) {
  2682. return firstRowCellInners.eq(col);
  2683. });
  2684. colContentPositions = new HorizontalPositionCache(function(col) {
  2685. return firstRowCellContentInners.eq(col);
  2686. });
  2687. function colLeft(col) {
  2688. return colPositions.left(col);
  2689. }
  2690. function colRight(col) {
  2691. return colPositions.right(col);
  2692. }
  2693. function colContentLeft(col) {
  2694. return colContentPositions.left(col);
  2695. }
  2696. function colContentRight(col) {
  2697. return colContentPositions.right(col);
  2698. }
  2699. function allDayRow(i) {
  2700. return bodyRows.eq(i);
  2701. }
  2702. }
  2703. ;;
  2704. function BasicEventRenderer() {
  2705. var t = this;
  2706. // exports
  2707. t.renderEvents = renderEvents;
  2708. t.clearEvents = clearEvents;
  2709. // imports
  2710. DayEventRenderer.call(t);
  2711. function renderEvents(events, modifiedEventId) {
  2712. t.renderDayEvents(events, modifiedEventId);
  2713. }
  2714. function clearEvents() {
  2715. t.getDaySegmentContainer().empty();
  2716. }
  2717. // TODO: have this class (and AgendaEventRenderer) be responsible for creating the event container div
  2718. }
  2719. ;;
  2720. fcViews.agendaWeek = AgendaWeekView;
  2721. function AgendaWeekView(element, calendar) { // TODO: do a WeekView mixin
  2722. var t = this;
  2723. // exports
  2724. t.incrementDate = incrementDate;
  2725. t.render = render;
  2726. // imports
  2727. AgendaView.call(t, element, calendar, 'agendaWeek');
  2728. function incrementDate(date, delta) {
  2729. return date.clone().stripTime().add(delta, 'weeks').startOf('week');
  2730. }
  2731. function render(date) {
  2732. t.intervalStart = date.clone().stripTime().startOf('week');
  2733. t.intervalEnd = t.intervalStart.clone().add(1, 'weeks');
  2734. t.start = t.skipHiddenDays(t.intervalStart);
  2735. t.end = t.skipHiddenDays(t.intervalEnd, -1, true);
  2736. t.title = calendar.formatRange(
  2737. t.start,
  2738. t.end.clone().subtract(1), // make inclusive by subtracting 1 ms
  2739. t.opt('titleFormat'),
  2740. ' \u2014 ' // emphasized dash
  2741. );
  2742. t.renderAgenda(t.getCellsPerWeek());
  2743. }
  2744. }
  2745. ;;
  2746. fcViews.agendaDay = AgendaDayView;
  2747. function AgendaDayView(element, calendar) { // TODO: make a DayView mixin
  2748. var t = this;
  2749. // exports
  2750. t.incrementDate = incrementDate;
  2751. t.render = render;
  2752. // imports
  2753. AgendaView.call(t, element, calendar, 'agendaDay');
  2754. function incrementDate(date, delta) {
  2755. var out = date.clone().stripTime().add(delta, 'days');
  2756. out = t.skipHiddenDays(out, delta < 0 ? -1 : 1);
  2757. return out;
  2758. }
  2759. function render(date) {
  2760. t.start = t.intervalStart = date.clone().stripTime();
  2761. t.end = t.intervalEnd = t.start.clone().add(1, 'days');
  2762. t.title = calendar.formatDate(t.start, t.opt('titleFormat'));
  2763. t.renderAgenda(1);
  2764. }
  2765. }
  2766. ;;
  2767. setDefaults({
  2768. allDaySlot: true,
  2769. allDayText: 'all-day',
  2770. scrollTime: '06:00:00',
  2771. slotDuration: '00:30:00',
  2772. axisFormat: generateAgendaAxisFormat,
  2773. timeFormat: {
  2774. agenda: generateAgendaTimeFormat
  2775. },
  2776. dragOpacity: {
  2777. agenda: .5
  2778. },
  2779. minTime: '00:00:00',
  2780. maxTime: '24:00:00',
  2781. slotEventOverlap: true
  2782. });
  2783. function generateAgendaAxisFormat(options, langData) {
  2784. return langData.longDateFormat('LT')
  2785. .replace(':mm', '(:mm)')
  2786. .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs
  2787. .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
  2788. }
  2789. function generateAgendaTimeFormat(options, langData) {
  2790. return langData.longDateFormat('LT')
  2791. .replace(/\s*a$/i, ''); // remove trailing AM/PM
  2792. }
  2793. // TODO: make it work in quirks mode (event corners, all-day height)
  2794. // TODO: test liquid width, especially in IE6
  2795. function AgendaView(element, calendar, viewName) {
  2796. var t = this;
  2797. // exports
  2798. t.renderAgenda = renderAgenda;
  2799. t.setWidth = setWidth;
  2800. t.setHeight = setHeight;
  2801. t.afterRender = afterRender;
  2802. t.computeDateTop = computeDateTop;
  2803. t.getIsCellAllDay = getIsCellAllDay;
  2804. t.allDayRow = function() { return allDayRow; }; // badly named
  2805. t.getCoordinateGrid = function() { return coordinateGrid; }; // specifically for AgendaEventRenderer
  2806. t.getHoverListener = function() { return hoverListener; };
  2807. t.colLeft = colLeft;
  2808. t.colRight = colRight;
  2809. t.colContentLeft = colContentLeft;
  2810. t.colContentRight = colContentRight;
  2811. t.getDaySegmentContainer = function() { return daySegmentContainer; };
  2812. t.getSlotSegmentContainer = function() { return slotSegmentContainer; };
  2813. t.getSlotContainer = function() { return slotContainer; };
  2814. t.getRowCnt = function() { return 1; };
  2815. t.getColCnt = function() { return colCnt; };
  2816. t.getColWidth = function() { return colWidth; };
  2817. t.getSnapHeight = function() { return snapHeight; };
  2818. t.getSnapDuration = function() { return snapDuration; };
  2819. t.getSlotHeight = function() { return slotHeight; };
  2820. t.getSlotDuration = function() { return slotDuration; };
  2821. t.getMinTime = function() { return minTime; };
  2822. t.getMaxTime = function() { return maxTime; };
  2823. t.defaultSelectionEnd = defaultSelectionEnd;
  2824. t.renderDayOverlay = renderDayOverlay;
  2825. t.renderSelection = renderSelection;
  2826. t.clearSelection = clearSelection;
  2827. t.reportDayClick = reportDayClick; // selection mousedown hack
  2828. t.dragStart = dragStart;
  2829. t.dragStop = dragStop;
  2830. // imports
  2831. View.call(t, element, calendar, viewName);
  2832. OverlayManager.call(t);
  2833. SelectionManager.call(t);
  2834. AgendaEventRenderer.call(t);
  2835. var opt = t.opt;
  2836. var trigger = t.trigger;
  2837. var renderOverlay = t.renderOverlay;
  2838. var clearOverlays = t.clearOverlays;
  2839. var reportSelection = t.reportSelection;
  2840. var unselect = t.unselect;
  2841. var daySelectionMousedown = t.daySelectionMousedown;
  2842. var slotSegHtml = t.slotSegHtml;
  2843. var cellToDate = t.cellToDate;
  2844. var dateToCell = t.dateToCell;
  2845. var rangeToSegments = t.rangeToSegments;
  2846. var formatDate = calendar.formatDate;
  2847. var calculateWeekNumber = calendar.calculateWeekNumber;
  2848. // locals
  2849. var dayTable;
  2850. var dayHead;
  2851. var dayHeadCells;
  2852. var dayBody;
  2853. var dayBodyCells;
  2854. var dayBodyCellInners;
  2855. var dayBodyCellContentInners;
  2856. var dayBodyFirstCell;
  2857. var dayBodyFirstCellStretcher;
  2858. var slotLayer;
  2859. var daySegmentContainer;
  2860. var allDayTable;
  2861. var allDayRow;
  2862. var slotScroller;
  2863. var slotContainer;
  2864. var slotSegmentContainer;
  2865. var slotTable;
  2866. var selectionHelper;
  2867. var viewWidth;
  2868. var viewHeight;
  2869. var axisWidth;
  2870. var colWidth;
  2871. var gutterWidth;
  2872. var slotDuration;
  2873. var slotHeight; // TODO: what if slotHeight changes? (see issue 650)
  2874. var snapDuration;
  2875. var snapRatio; // ratio of number of "selection" slots to normal slots. (ex: 1, 2, 4)
  2876. var snapHeight; // holds the pixel hight of a "selection" slot
  2877. var colCnt;
  2878. var slotCnt;
  2879. var coordinateGrid;
  2880. var hoverListener;
  2881. var colPositions;
  2882. var colContentPositions;
  2883. var slotTopCache = {};
  2884. var tm;
  2885. var rtl;
  2886. var minTime;
  2887. var maxTime;
  2888. var colFormat;
  2889. /* Rendering
  2890. -----------------------------------------------------------------------------*/
  2891. disableTextSelection(element.addClass('fc-agenda'));
  2892. function renderAgenda(c) {
  2893. colCnt = c;
  2894. updateOptions();
  2895. if (!dayTable) { // first time rendering?
  2896. buildSkeleton(); // builds day table, slot area, events containers
  2897. }
  2898. else {
  2899. buildDayTable(); // rebuilds day table
  2900. }
  2901. }
  2902. function updateOptions() {
  2903. tm = opt('theme') ? 'ui' : 'fc';
  2904. rtl = opt('isRTL');
  2905. colFormat = opt('columnFormat');
  2906. minTime = moment.duration(opt('minTime'));
  2907. maxTime = moment.duration(opt('maxTime'));
  2908. slotDuration = moment.duration(opt('slotDuration'));
  2909. snapDuration = opt('snapDuration');
  2910. snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration;
  2911. }
  2912. /* Build DOM
  2913. -----------------------------------------------------------------------*/
  2914. function buildSkeleton() {
  2915. var s;
  2916. var headerClass = tm + "-widget-header";
  2917. var contentClass = tm + "-widget-content";
  2918. var slotTime;
  2919. var slotDate;
  2920. var minutes;
  2921. var slotNormal = slotDuration.asMinutes() % 15 === 0;
  2922. buildDayTable();
  2923. slotLayer =
  2924. $("<div style='position:absolute;z-index:2;left:0;width:100%'/>")
  2925. .appendTo(element);
  2926. if (opt('allDaySlot')) {
  2927. daySegmentContainer =
  2928. $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
  2929. .appendTo(slotLayer);
  2930. s =
  2931. "<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" +
  2932. "<tr>" +
  2933. "<th class='" + headerClass + " fc-agenda-axis'>" +
  2934. (
  2935. opt('allDayHTML') ||
  2936. htmlEscape(opt('allDayText'))
  2937. ) +
  2938. "</th>" +
  2939. "<td>" +
  2940. "<div class='fc-day-content'><div style='position:relative'/></div>" +
  2941. "</td>" +
  2942. "<th class='" + headerClass + " fc-agenda-gutter'>&nbsp;</th>" +
  2943. "</tr>" +
  2944. "</table>";
  2945. allDayTable = $(s).appendTo(slotLayer);
  2946. allDayRow = allDayTable.find('tr');
  2947. dayBind(allDayRow.find('td'));
  2948. slotLayer.append(
  2949. "<div class='fc-agenda-divider " + headerClass + "'>" +
  2950. "<div class='fc-agenda-divider-inner'/>" +
  2951. "</div>"
  2952. );
  2953. }else{
  2954. daySegmentContainer = $([]); // in jQuery 1.4, we can just do $()
  2955. }
  2956. slotScroller =
  2957. $("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>")
  2958. .appendTo(slotLayer);
  2959. slotContainer =
  2960. $("<div style='position:relative;width:100%;overflow:hidden'/>")
  2961. .appendTo(slotScroller);
  2962. slotSegmentContainer =
  2963. $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
  2964. .appendTo(slotContainer);
  2965. s =
  2966. "<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" +
  2967. "<tbody>";
  2968. slotTime = moment.duration(+minTime); // i wish there was .clone() for durations
  2969. slotCnt = 0;
  2970. while (slotTime < maxTime) {
  2971. slotDate = t.start.clone().time(slotTime); // will be in UTC but that's good. to avoid DST issues
  2972. minutes = slotDate.minutes();
  2973. s +=
  2974. "<tr class='fc-slot" + slotCnt + ' ' + (!minutes ? '' : 'fc-minor') + "'>" +
  2975. "<th class='fc-agenda-axis " + headerClass + "'>" +
  2976. ((!slotNormal || !minutes) ?
  2977. htmlEscape(formatDate(slotDate, opt('axisFormat'))) :
  2978. '&nbsp;'
  2979. ) +
  2980. "</th>" +
  2981. "<td class='" + contentClass + "'>" +
  2982. "<div style='position:relative'>&nbsp;</div>" +
  2983. "</td>" +
  2984. "</tr>";
  2985. slotTime.add(slotDuration);
  2986. slotCnt++;
  2987. }
  2988. s +=
  2989. "</tbody>" +
  2990. "</table>";
  2991. slotTable = $(s).appendTo(slotContainer);
  2992. slotBind(slotTable.find('td'));
  2993. }
  2994. /* Build Day Table
  2995. -----------------------------------------------------------------------*/
  2996. function buildDayTable() {
  2997. var html = buildDayTableHTML();
  2998. if (dayTable) {
  2999. dayTable.remove();
  3000. }
  3001. dayTable = $(html).appendTo(element);
  3002. dayHead = dayTable.find('thead');
  3003. dayHeadCells = dayHead.find('th').slice(1, -1); // exclude gutter
  3004. dayBody = dayTable.find('tbody');
  3005. dayBodyCells = dayBody.find('td').slice(0, -1); // exclude gutter
  3006. dayBodyCellInners = dayBodyCells.find('> div');
  3007. dayBodyCellContentInners = dayBodyCells.find('.fc-day-content > div');
  3008. dayBodyFirstCell = dayBodyCells.eq(0);
  3009. dayBodyFirstCellStretcher = dayBodyCellInners.eq(0);
  3010. markFirstLast(dayHead.add(dayHead.find('tr')));
  3011. markFirstLast(dayBody.add(dayBody.find('tr')));
  3012. // TODO: now that we rebuild the cells every time, we should call dayRender
  3013. }
  3014. function buildDayTableHTML() {
  3015. var html =
  3016. "<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" +
  3017. buildDayTableHeadHTML() +
  3018. buildDayTableBodyHTML() +
  3019. "</table>";
  3020. return html;
  3021. }
  3022. function buildDayTableHeadHTML() {
  3023. var headerClass = tm + "-widget-header";
  3024. var date;
  3025. var html = '';
  3026. var weekText;
  3027. var col;
  3028. html +=
  3029. "<thead>" +
  3030. "<tr>";
  3031. if (opt('weekNumbers')) {
  3032. date = cellToDate(0, 0);
  3033. weekText = calculateWeekNumber(date);
  3034. if (rtl) {
  3035. weekText += opt('weekNumberTitle');
  3036. }
  3037. else {
  3038. weekText = opt('weekNumberTitle') + weekText;
  3039. }
  3040. html +=
  3041. "<th class='fc-agenda-axis fc-week-number " + headerClass + "'>" +
  3042. htmlEscape(weekText) +
  3043. "</th>";
  3044. }
  3045. else {
  3046. html += "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>";
  3047. }
  3048. for (col=0; col<colCnt; col++) {
  3049. date = cellToDate(0, col);
  3050. html +=
  3051. "<th class='fc-" + dayIDs[date.day()] + " fc-col" + col + ' ' + headerClass + "'>" +
  3052. htmlEscape(formatDate(date, colFormat)) +
  3053. "</th>";
  3054. }
  3055. html +=
  3056. "<th class='fc-agenda-gutter " + headerClass + "'>&nbsp;</th>" +
  3057. "</tr>" +
  3058. "</thead>";
  3059. return html;
  3060. }
  3061. function buildDayTableBodyHTML() {
  3062. var headerClass = tm + "-widget-header"; // TODO: make these when updateOptions() called
  3063. var contentClass = tm + "-widget-content";
  3064. var date;
  3065. var today = calendar.getNow().stripTime();
  3066. var col;
  3067. var cellsHTML;
  3068. var cellHTML;
  3069. var classNames;
  3070. var html = '';
  3071. html +=
  3072. "<tbody>" +
  3073. "<tr>" +
  3074. "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>";
  3075. cellsHTML = '';
  3076. for (col=0; col<colCnt; col++) {
  3077. date = cellToDate(0, col);
  3078. classNames = [
  3079. 'fc-col' + col,
  3080. 'fc-' + dayIDs[date.day()],
  3081. contentClass
  3082. ];
  3083. if (date.isSame(today, 'day')) {
  3084. classNames.push(
  3085. tm + '-state-highlight',
  3086. 'fc-today'
  3087. );
  3088. }
  3089. else if (date < today) {
  3090. classNames.push('fc-past');
  3091. }
  3092. else {
  3093. classNames.push('fc-future');
  3094. }
  3095. cellHTML =
  3096. "<td class='" + classNames.join(' ') + "'>" +
  3097. "<div>" +
  3098. "<div class='fc-day-content'>" +
  3099. "<div style='position:relative'>&nbsp;</div>" +
  3100. "</div>" +
  3101. "</div>" +
  3102. "</td>";
  3103. cellsHTML += cellHTML;
  3104. }
  3105. html += cellsHTML;
  3106. html +=
  3107. "<td class='fc-agenda-gutter " + contentClass + "'>&nbsp;</td>" +
  3108. "</tr>" +
  3109. "</tbody>";
  3110. return html;
  3111. }
  3112. // TODO: data-date on the cells
  3113. /* Dimensions
  3114. -----------------------------------------------------------------------*/
  3115. function setHeight(height) {
  3116. if (height === undefined) {
  3117. height = viewHeight;
  3118. }
  3119. viewHeight = height;
  3120. slotTopCache = {};
  3121. var headHeight = dayBody.position().top;
  3122. var allDayHeight = slotScroller.position().top; // including divider
  3123. var bodyHeight = Math.min( // total body height, including borders
  3124. height - headHeight, // when scrollbars
  3125. slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border
  3126. );
  3127. dayBodyFirstCellStretcher
  3128. .height(bodyHeight - vsides(dayBodyFirstCell));
  3129. slotLayer.css('top', headHeight);
  3130. slotScroller.height(bodyHeight - allDayHeight - 1);
  3131. // the stylesheet guarantees that the first row has no border.
  3132. // this allows .height() to work well cross-browser.
  3133. var slotHeight0 = slotTable.find('tr:first').height() + 1; // +1 for bottom border
  3134. var slotHeight1 = slotTable.find('tr:eq(1)').height();
  3135. // HACK: i forget why we do this, but i think a cross-browser issue
  3136. slotHeight = (slotHeight0 + slotHeight1) / 2;
  3137. snapRatio = slotDuration / snapDuration;
  3138. snapHeight = slotHeight / snapRatio;
  3139. }
  3140. function setWidth(width) {
  3141. viewWidth = width;
  3142. colPositions.clear();
  3143. colContentPositions.clear();
  3144. var axisFirstCells = dayHead.find('th:first');
  3145. if (allDayTable) {
  3146. axisFirstCells = axisFirstCells.add(allDayTable.find('th:first'));
  3147. }
  3148. axisFirstCells = axisFirstCells.add(slotTable.find('th:first'));
  3149. axisWidth = 0;
  3150. setOuterWidth(
  3151. axisFirstCells
  3152. .width('')
  3153. .each(function(i, _cell) {
  3154. axisWidth = Math.max(axisWidth, $(_cell).outerWidth());
  3155. }),
  3156. axisWidth
  3157. );
  3158. var gutterCells = dayTable.find('.fc-agenda-gutter');
  3159. if (allDayTable) {
  3160. gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter'));
  3161. }
  3162. var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7)
  3163. gutterWidth = slotScroller.width() - slotTableWidth;
  3164. if (gutterWidth) {
  3165. setOuterWidth(gutterCells, gutterWidth);
  3166. gutterCells
  3167. .show()
  3168. .prev()
  3169. .removeClass('fc-last');
  3170. }else{
  3171. gutterCells
  3172. .hide()
  3173. .prev()
  3174. .addClass('fc-last');
  3175. }
  3176. colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt);
  3177. setOuterWidth(dayHeadCells.slice(0, -1), colWidth);
  3178. }
  3179. /* Scrolling
  3180. -----------------------------------------------------------------------*/
  3181. function resetScroll() {
  3182. var top = computeTimeTop(
  3183. moment.duration(opt('scrollTime'))
  3184. ) + 1; // +1 for the border
  3185. function scroll() {
  3186. slotScroller.scrollTop(top);
  3187. }
  3188. scroll();
  3189. setTimeout(scroll, 0); // overrides any previous scroll state made by the browser
  3190. }
  3191. function afterRender() { // after the view has been freshly rendered and sized
  3192. resetScroll();
  3193. }
  3194. /* Slot/Day clicking and binding
  3195. -----------------------------------------------------------------------*/
  3196. function dayBind(cells) {
  3197. cells.click(slotClick)
  3198. .mousedown(daySelectionMousedown);
  3199. }
  3200. function slotBind(cells) {
  3201. cells.click(slotClick)
  3202. .mousedown(slotSelectionMousedown);
  3203. }
  3204. function slotClick(ev) {
  3205. if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
  3206. var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth));
  3207. var date = cellToDate(0, col);
  3208. var match = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data
  3209. if (match) {
  3210. var slotIndex = parseInt(match[1], 10);
  3211. date.add(minTime + slotIndex * slotDuration);
  3212. date = calendar.rezoneDate(date);
  3213. trigger(
  3214. 'dayClick',
  3215. dayBodyCells[col],
  3216. date,
  3217. ev
  3218. );
  3219. }else{
  3220. trigger(
  3221. 'dayClick',
  3222. dayBodyCells[col],
  3223. date,
  3224. ev
  3225. );
  3226. }
  3227. }
  3228. }
  3229. /* Semi-transparent Overlay Helpers
  3230. -----------------------------------------------------*/
  3231. // TODO: should be consolidated with BasicView's methods
  3232. function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
  3233. if (refreshCoordinateGrid) {
  3234. coordinateGrid.build();
  3235. }
  3236. var segments = rangeToSegments(overlayStart, overlayEnd);
  3237. for (var i=0; i<segments.length; i++) {
  3238. var segment = segments[i];
  3239. dayBind(
  3240. renderCellOverlay(
  3241. segment.row,
  3242. segment.leftCol,
  3243. segment.row,
  3244. segment.rightCol
  3245. )
  3246. );
  3247. }
  3248. }
  3249. function renderCellOverlay(row0, col0, row1, col1) { // only for all-day?
  3250. var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer);
  3251. return renderOverlay(rect, slotLayer);
  3252. }
  3253. function renderSlotOverlay(overlayStart, overlayEnd) {
  3254. // normalize, because dayStart/dayEnd have stripped time+zone
  3255. overlayStart = overlayStart.clone().stripZone();
  3256. overlayEnd = overlayEnd.clone().stripZone();
  3257. for (var i=0; i<colCnt; i++) { // loop through the day columns
  3258. var dayStart = cellToDate(0, i);
  3259. var dayEnd = dayStart.clone().add(1, 'days');
  3260. var stretchStart = dayStart < overlayStart ? overlayStart : dayStart; // the max of the two
  3261. var stretchEnd = dayEnd < overlayEnd ? dayEnd : overlayEnd; // the min of the two
  3262. if (stretchStart < stretchEnd) {
  3263. var rect = coordinateGrid.rect(0, i, 0, i, slotContainer); // only use it for horizontal coords
  3264. var top = computeDateTop(stretchStart, dayStart);
  3265. var bottom = computeDateTop(stretchEnd, dayStart);
  3266. rect.top = top;
  3267. rect.height = bottom - top;
  3268. slotBind(
  3269. renderOverlay(rect, slotContainer)
  3270. );
  3271. }
  3272. }
  3273. }
  3274. /* Coordinate Utilities
  3275. -----------------------------------------------------------------------------*/
  3276. coordinateGrid = new CoordinateGrid(function(rows, cols) {
  3277. var e, n, p;
  3278. dayHeadCells.each(function(i, _e) {
  3279. e = $(_e);
  3280. n = e.offset().left;
  3281. if (i) {
  3282. p[1] = n;
  3283. }
  3284. p = [n];
  3285. cols[i] = p;
  3286. });
  3287. p[1] = n + e.outerWidth();
  3288. if (opt('allDaySlot')) {
  3289. e = allDayRow;
  3290. n = e.offset().top;
  3291. rows[0] = [n, n+e.outerHeight()];
  3292. }
  3293. var slotTableTop = slotContainer.offset().top;
  3294. var slotScrollerTop = slotScroller.offset().top;
  3295. var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight();
  3296. function constrain(n) {
  3297. return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n));
  3298. }
  3299. for (var i=0; i<slotCnt*snapRatio; i++) { // adapt slot count to increased/decreased selection slot count
  3300. rows.push([
  3301. constrain(slotTableTop + snapHeight*i),
  3302. constrain(slotTableTop + snapHeight*(i+1))
  3303. ]);
  3304. }
  3305. });
  3306. hoverListener = new HoverListener(coordinateGrid);
  3307. colPositions = new HorizontalPositionCache(function(col) {
  3308. return dayBodyCellInners.eq(col);
  3309. });
  3310. colContentPositions = new HorizontalPositionCache(function(col) {
  3311. return dayBodyCellContentInners.eq(col);
  3312. });
  3313. function colLeft(col) {
  3314. return colPositions.left(col);
  3315. }
  3316. function colContentLeft(col) {
  3317. return colContentPositions.left(col);
  3318. }
  3319. function colRight(col) {
  3320. return colPositions.right(col);
  3321. }
  3322. function colContentRight(col) {
  3323. return colContentPositions.right(col);
  3324. }
  3325. // NOTE: the row index of these "cells" doesn't correspond to the slot index, but rather the "snap" index
  3326. function getIsCellAllDay(cell) { // TODO: remove because mom.hasTime() from realCellToDate() is better
  3327. return opt('allDaySlot') && !cell.row;
  3328. }
  3329. function realCellToDate(cell) { // ugh "real" ... but blame it on our abuse of the "cell" system
  3330. var date = cellToDate(0, cell.col);
  3331. var snapIndex = cell.row;
  3332. if (opt('allDaySlot')) {
  3333. snapIndex--;
  3334. }
  3335. if (snapIndex >= 0) {
  3336. date.time(moment.duration(minTime + snapIndex * snapDuration));
  3337. date = calendar.rezoneDate(date);
  3338. }
  3339. return date;
  3340. }
  3341. function computeDateTop(date, startOfDayDate) {
  3342. return computeTimeTop(
  3343. moment.duration(
  3344. date.clone().stripZone() - startOfDayDate.clone().stripTime()
  3345. )
  3346. );
  3347. }
  3348. function computeTimeTop(time) { // time is a duration
  3349. if (time < minTime) {
  3350. return 0;
  3351. }
  3352. if (time >= maxTime) {
  3353. return slotTable.height();
  3354. }
  3355. var slots = (time - minTime) / slotDuration;
  3356. var slotIndex = Math.floor(slots);
  3357. var slotPartial = slots - slotIndex;
  3358. var slotTop = slotTopCache[slotIndex];
  3359. // find the position of the corresponding <tr>
  3360. // need to use this tecnhique because not all rows are rendered at same height sometimes.
  3361. if (slotTop === undefined) {
  3362. slotTop = slotTopCache[slotIndex] =
  3363. slotTable.find('tr').eq(slotIndex).find('td div')[0].offsetTop;
  3364. // .eq() is faster than ":eq()" selector
  3365. // [0].offsetTop is faster than .position().top (do we really need this optimization?)
  3366. // a better optimization would be to cache all these divs
  3367. }
  3368. var top =
  3369. slotTop - 1 + // because first row doesn't have a top border
  3370. slotPartial * slotHeight; // part-way through the row
  3371. top = Math.max(top, 0);
  3372. return top;
  3373. }
  3374. /* Selection
  3375. ---------------------------------------------------------------------------------*/
  3376. function defaultSelectionEnd(start) {
  3377. if (start.hasTime()) {
  3378. return start.clone().add(slotDuration);
  3379. }
  3380. else {
  3381. return start.clone().add(1, 'days');
  3382. }
  3383. }
  3384. function renderSelection(start, end) {
  3385. if (start.hasTime() || end.hasTime()) {
  3386. renderSlotSelection(start, end);
  3387. }
  3388. else if (opt('allDaySlot')) {
  3389. renderDayOverlay(start, end, true); // true for refreshing coordinate grid
  3390. }
  3391. }
  3392. function renderSlotSelection(startDate, endDate) {
  3393. var helperOption = opt('selectHelper');
  3394. coordinateGrid.build();
  3395. if (helperOption) {
  3396. var col = dateToCell(startDate).col;
  3397. if (col >= 0 && col < colCnt) { // only works when times are on same day
  3398. var rect = coordinateGrid.rect(0, col, 0, col, slotContainer); // only for horizontal coords
  3399. var top = computeDateTop(startDate, startDate);
  3400. var bottom = computeDateTop(endDate, startDate);
  3401. if (bottom > top) { // protect against selections that are entirely before or after visible range
  3402. rect.top = top;
  3403. rect.height = bottom - top;
  3404. rect.left += 2;
  3405. rect.width -= 5;
  3406. if ($.isFunction(helperOption)) {
  3407. var helperRes = helperOption(startDate, endDate);
  3408. if (helperRes) {
  3409. rect.position = 'absolute';
  3410. selectionHelper = $(helperRes)
  3411. .css(rect)
  3412. .appendTo(slotContainer);
  3413. }
  3414. }else{
  3415. rect.isStart = true; // conside rect a "seg" now
  3416. rect.isEnd = true; //
  3417. selectionHelper = $(slotSegHtml(
  3418. {
  3419. title: '',
  3420. start: startDate,
  3421. end: endDate,
  3422. className: ['fc-select-helper'],
  3423. editable: false
  3424. },
  3425. rect
  3426. ));
  3427. selectionHelper.css('opacity', opt('dragOpacity'));
  3428. }
  3429. if (selectionHelper) {
  3430. slotBind(selectionHelper);
  3431. slotContainer.append(selectionHelper);
  3432. setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended
  3433. setOuterHeight(selectionHelper, rect.height, true);
  3434. }
  3435. }
  3436. }
  3437. }else{
  3438. renderSlotOverlay(startDate, endDate);
  3439. }
  3440. }
  3441. function clearSelection() {
  3442. clearOverlays();
  3443. if (selectionHelper) {
  3444. selectionHelper.remove();
  3445. selectionHelper = null;
  3446. }
  3447. }
  3448. function slotSelectionMousedown(ev) {
  3449. if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button
  3450. unselect(ev);
  3451. var dates;
  3452. hoverListener.start(function(cell, origCell) {
  3453. clearSelection();
  3454. if (cell && cell.col == origCell.col && !getIsCellAllDay(cell)) {
  3455. var d1 = realCellToDate(origCell);
  3456. var d2 = realCellToDate(cell);
  3457. dates = [
  3458. d1,
  3459. d1.clone().add(snapDuration), // calculate minutes depending on selection slot minutes
  3460. d2,
  3461. d2.clone().add(snapDuration)
  3462. ].sort(dateCompare);
  3463. renderSlotSelection(dates[0], dates[3]);
  3464. }else{
  3465. dates = null;
  3466. }
  3467. }, ev);
  3468. $(document).one('mouseup', function(ev) {
  3469. hoverListener.stop();
  3470. if (dates) {
  3471. if (+dates[0] == +dates[1]) {
  3472. reportDayClick(dates[0], ev);
  3473. }
  3474. reportSelection(dates[0], dates[3], ev);
  3475. }
  3476. });
  3477. }
  3478. }
  3479. function reportDayClick(date, ev) {
  3480. trigger('dayClick', dayBodyCells[dateToCell(date).col], date, ev);
  3481. }
  3482. /* External Dragging
  3483. --------------------------------------------------------------------------------*/
  3484. function dragStart(_dragElement, ev, ui) {
  3485. hoverListener.start(function(cell) {
  3486. clearOverlays();
  3487. if (cell) {
  3488. var d1 = realCellToDate(cell);
  3489. var d2 = d1.clone();
  3490. if (d1.hasTime()) {
  3491. d2.add(calendar.defaultTimedEventDuration);
  3492. renderSlotOverlay(d1, d2);
  3493. }
  3494. else {
  3495. d2.add(calendar.defaultAllDayEventDuration);
  3496. renderDayOverlay(d1, d2);
  3497. }
  3498. }
  3499. }, ev);
  3500. }
  3501. function dragStop(_dragElement, ev, ui) {
  3502. var cell = hoverListener.stop();
  3503. clearOverlays();
  3504. if (cell) {
  3505. trigger(
  3506. 'drop',
  3507. _dragElement,
  3508. realCellToDate(cell),
  3509. ev,
  3510. ui
  3511. );
  3512. }
  3513. }
  3514. }
  3515. ;;
  3516. function AgendaEventRenderer() {
  3517. var t = this;
  3518. // exports
  3519. t.renderEvents = renderEvents;
  3520. t.clearEvents = clearEvents;
  3521. t.slotSegHtml = slotSegHtml;
  3522. // imports
  3523. DayEventRenderer.call(t);
  3524. var opt = t.opt;
  3525. var trigger = t.trigger;
  3526. var isEventDraggable = t.isEventDraggable;
  3527. var isEventResizable = t.isEventResizable;
  3528. var eventElementHandlers = t.eventElementHandlers;
  3529. var setHeight = t.setHeight;
  3530. var getDaySegmentContainer = t.getDaySegmentContainer;
  3531. var getSlotSegmentContainer = t.getSlotSegmentContainer;
  3532. var getHoverListener = t.getHoverListener;
  3533. var computeDateTop = t.computeDateTop;
  3534. var getIsCellAllDay = t.getIsCellAllDay;
  3535. var colContentLeft = t.colContentLeft;
  3536. var colContentRight = t.colContentRight;
  3537. var cellToDate = t.cellToDate;
  3538. var getColCnt = t.getColCnt;
  3539. var getColWidth = t.getColWidth;
  3540. var getSnapHeight = t.getSnapHeight;
  3541. var getSnapDuration = t.getSnapDuration;
  3542. var getSlotHeight = t.getSlotHeight;
  3543. var getSlotDuration = t.getSlotDuration;
  3544. var getSlotContainer = t.getSlotContainer;
  3545. var reportEventElement = t.reportEventElement;
  3546. var showEvents = t.showEvents;
  3547. var hideEvents = t.hideEvents;
  3548. var eventDrop = t.eventDrop;
  3549. var eventResize = t.eventResize;
  3550. var renderDayOverlay = t.renderDayOverlay;
  3551. var clearOverlays = t.clearOverlays;
  3552. var renderDayEvents = t.renderDayEvents;
  3553. var getMinTime = t.getMinTime;
  3554. var getMaxTime = t.getMaxTime;
  3555. var calendar = t.calendar;
  3556. var formatDate = calendar.formatDate;
  3557. var getEventEnd = calendar.getEventEnd;
  3558. // overrides
  3559. t.draggableDayEvent = draggableDayEvent;
  3560. /* Rendering
  3561. ----------------------------------------------------------------------------*/
  3562. function renderEvents(events, modifiedEventId) {
  3563. var i, len=events.length,
  3564. dayEvents=[],
  3565. slotEvents=[];
  3566. for (i=0; i<len; i++) {
  3567. if (events[i].allDay) {
  3568. dayEvents.push(events[i]);
  3569. }else{
  3570. slotEvents.push(events[i]);
  3571. }
  3572. }
  3573. if (opt('allDaySlot')) {
  3574. renderDayEvents(dayEvents, modifiedEventId);
  3575. setHeight(); // no params means set to viewHeight
  3576. }
  3577. renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId);
  3578. }
  3579. function clearEvents() {
  3580. getDaySegmentContainer().empty();
  3581. getSlotSegmentContainer().empty();
  3582. }
  3583. function compileSlotSegs(events) {
  3584. var colCnt = getColCnt(),
  3585. minTime = getMinTime(),
  3586. maxTime = getMaxTime(),
  3587. cellDate,
  3588. i,
  3589. j, seg,
  3590. colSegs,
  3591. segs = [];
  3592. for (i=0; i<colCnt; i++) {
  3593. cellDate = cellToDate(0, i);
  3594. colSegs = sliceSegs(
  3595. events,
  3596. cellDate.clone().time(minTime),
  3597. cellDate.clone().time(maxTime)
  3598. );
  3599. colSegs = placeSlotSegs(colSegs); // returns a new order
  3600. for (j=0; j<colSegs.length; j++) {
  3601. seg = colSegs[j];
  3602. seg.col = i;
  3603. segs.push(seg);
  3604. }
  3605. }
  3606. return segs;
  3607. }
  3608. function sliceSegs(events, rangeStart, rangeEnd) {
  3609. // normalize, because all dates will be compared w/o zones
  3610. rangeStart = rangeStart.clone().stripZone();
  3611. rangeEnd = rangeEnd.clone().stripZone();
  3612. var segs = [],
  3613. i, len=events.length, event,
  3614. eventStart, eventEnd,
  3615. segStart, segEnd,
  3616. isStart, isEnd;
  3617. for (i=0; i<len; i++) {
  3618. event = events[i];
  3619. // get dates, make copies, then strip zone to normalize
  3620. eventStart = event.start.clone().stripZone();
  3621. eventEnd = getEventEnd(event).stripZone();
  3622. if (eventEnd > rangeStart && eventStart < rangeEnd) {
  3623. if (eventStart < rangeStart) {
  3624. segStart = rangeStart.clone();
  3625. isStart = false;
  3626. }
  3627. else {
  3628. segStart = eventStart;
  3629. isStart = true;
  3630. }
  3631. if (eventEnd > rangeEnd) {
  3632. segEnd = rangeEnd.clone();
  3633. isEnd = false;
  3634. }
  3635. else {
  3636. segEnd = eventEnd;
  3637. isEnd = true;
  3638. }
  3639. segs.push({
  3640. event: event,
  3641. start: segStart,
  3642. end: segEnd,
  3643. isStart: isStart,
  3644. isEnd: isEnd
  3645. });
  3646. }
  3647. }
  3648. return segs.sort(compareSlotSegs);
  3649. }
  3650. // renders events in the 'time slots' at the bottom
  3651. // TODO: when we refactor this, when user returns `false` eventRender, don't have empty space
  3652. // TODO: refactor will include using pixels to detect collisions instead of dates (handy for seg cmp)
  3653. function renderSlotSegs(segs, modifiedEventId) {
  3654. var i, segCnt=segs.length, seg,
  3655. event,
  3656. top,
  3657. bottom,
  3658. columnLeft,
  3659. columnRight,
  3660. columnWidth,
  3661. width,
  3662. left,
  3663. right,
  3664. html = '',
  3665. eventElements,
  3666. eventElement,
  3667. triggerRes,
  3668. titleElement,
  3669. height,
  3670. slotSegmentContainer = getSlotSegmentContainer(),
  3671. isRTL = opt('isRTL');
  3672. // calculate position/dimensions, create html
  3673. for (i=0; i<segCnt; i++) {
  3674. seg = segs[i];
  3675. event = seg.event;
  3676. top = computeDateTop(seg.start, seg.start);
  3677. bottom = computeDateTop(seg.end, seg.start);
  3678. columnLeft = colContentLeft(seg.col);
  3679. columnRight = colContentRight(seg.col);
  3680. columnWidth = columnRight - columnLeft;
  3681. // shave off space on right near scrollbars (2.5%)
  3682. // TODO: move this to CSS somehow
  3683. columnRight -= columnWidth * .025;
  3684. columnWidth = columnRight - columnLeft;
  3685. width = columnWidth * (seg.forwardCoord - seg.backwardCoord);
  3686. if (opt('slotEventOverlap')) {
  3687. // double the width while making sure resize handle is visible
  3688. // (assumed to be 20px wide)
  3689. width = Math.max(
  3690. (width - (20/2)) * 2,
  3691. width // narrow columns will want to make the segment smaller than
  3692. // the natural width. don't allow it
  3693. );
  3694. }
  3695. if (isRTL) {
  3696. right = columnRight - seg.backwardCoord * columnWidth;
  3697. left = right - width;
  3698. }
  3699. else {
  3700. left = columnLeft + seg.backwardCoord * columnWidth;
  3701. right = left + width;
  3702. }
  3703. // make sure horizontal coordinates are in bounds
  3704. left = Math.max(left, columnLeft);
  3705. right = Math.min(right, columnRight);
  3706. width = right - left;
  3707. seg.top = top;
  3708. seg.left = left;
  3709. seg.outerWidth = width;
  3710. seg.outerHeight = bottom - top;
  3711. html += slotSegHtml(event, seg);
  3712. }
  3713. slotSegmentContainer[0].innerHTML = html; // faster than html()
  3714. eventElements = slotSegmentContainer.children();
  3715. // retrieve elements, run through eventRender callback, bind event handlers
  3716. for (i=0; i<segCnt; i++) {
  3717. seg = segs[i];
  3718. event = seg.event;
  3719. eventElement = $(eventElements[i]); // faster than eq()
  3720. triggerRes = trigger('eventRender', event, event, eventElement);
  3721. if (triggerRes === false) {
  3722. eventElement.remove();
  3723. }else{
  3724. if (triggerRes && triggerRes !== true) {
  3725. eventElement.remove();
  3726. eventElement = $(triggerRes)
  3727. .css({
  3728. position: 'absolute',
  3729. top: seg.top,
  3730. left: seg.left
  3731. })
  3732. .appendTo(slotSegmentContainer);
  3733. }
  3734. seg.element = eventElement;
  3735. if (event._id === modifiedEventId) {
  3736. bindSlotSeg(event, eventElement, seg);
  3737. }else{
  3738. eventElement[0]._fci = i; // for lazySegBind
  3739. }
  3740. reportEventElement(event, eventElement);
  3741. }
  3742. }
  3743. lazySegBind(slotSegmentContainer, segs, bindSlotSeg);
  3744. // record event sides and title positions
  3745. for (i=0; i<segCnt; i++) {
  3746. seg = segs[i];
  3747. if ((eventElement = seg.element)) {
  3748. seg.vsides = vsides(eventElement, true);
  3749. seg.hsides = hsides(eventElement, true);
  3750. titleElement = eventElement.find('.fc-event-title');
  3751. if (titleElement.length) {
  3752. seg.contentTop = titleElement[0].offsetTop;
  3753. }
  3754. }
  3755. }
  3756. // set all positions/dimensions at once
  3757. for (i=0; i<segCnt; i++) {
  3758. seg = segs[i];
  3759. if ((eventElement = seg.element)) {
  3760. eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px';
  3761. height = Math.max(0, seg.outerHeight - seg.vsides);
  3762. eventElement[0].style.height = height + 'px';
  3763. event = seg.event;
  3764. if (seg.contentTop !== undefined && height - seg.contentTop < 10) {
  3765. // not enough room for title, put it in the time (TODO: maybe make both display:inline instead)
  3766. eventElement.find('div.fc-event-time')
  3767. .text(
  3768. formatDate(event.start, opt('timeFormat')) + ' - ' + event.title
  3769. );
  3770. eventElement.find('div.fc-event-title')
  3771. .remove();
  3772. }
  3773. trigger('eventAfterRender', event, event, eventElement);
  3774. }
  3775. }
  3776. }
  3777. function slotSegHtml(event, seg) {
  3778. var html = "<";
  3779. var url = event.url;
  3780. var skinCss = getSkinCss(event, opt);
  3781. var classes = ['fc-event', 'fc-event-vert'];
  3782. if (isEventDraggable(event)) {
  3783. classes.push('fc-event-draggable');
  3784. }
  3785. if (seg.isStart) {
  3786. classes.push('fc-event-start');
  3787. }
  3788. if (seg.isEnd) {
  3789. classes.push('fc-event-end');
  3790. }
  3791. classes = classes.concat(event.className);
  3792. if (event.source) {
  3793. classes = classes.concat(event.source.className || []);
  3794. }
  3795. if (url) {
  3796. html += "a href='" + htmlEscape(event.url) + "'";
  3797. }else{
  3798. html += "div";
  3799. }
  3800. html +=
  3801. " class='" + classes.join(' ') + "'" +
  3802. " style=" +
  3803. "'" +
  3804. "position:absolute;" +
  3805. "top:" + seg.top + "px;" +
  3806. "left:" + seg.left + "px;" +
  3807. skinCss +
  3808. "'" +
  3809. ">" +
  3810. "<div class='fc-event-inner'>" +
  3811. "<div class='fc-event-time'>" +
  3812. htmlEscape(t.getEventTimeText(event)) +
  3813. "</div>" +
  3814. "<div class='fc-event-title'>" +
  3815. htmlEscape(event.title || '') +
  3816. "</div>" +
  3817. "</div>" +
  3818. "<div class='fc-event-bg'></div>";
  3819. if (seg.isEnd && isEventResizable(event)) {
  3820. html +=
  3821. "<div class='ui-resizable-handle ui-resizable-s'>=</div>";
  3822. }
  3823. html +=
  3824. "</" + (url ? "a" : "div") + ">";
  3825. return html;
  3826. }
  3827. function bindSlotSeg(event, eventElement, seg) {
  3828. var timeElement = eventElement.find('div.fc-event-time');
  3829. if (isEventDraggable(event)) {
  3830. draggableSlotEvent(event, eventElement, timeElement);
  3831. }
  3832. if (seg.isEnd && isEventResizable(event)) {
  3833. resizableSlotEvent(event, eventElement, timeElement);
  3834. }
  3835. eventElementHandlers(event, eventElement);
  3836. }
  3837. /* Dragging
  3838. -----------------------------------------------------------------------------------*/
  3839. // when event starts out FULL-DAY
  3840. // overrides DayEventRenderer's version because it needs to account for dragging elements
  3841. // to and from the slot area.
  3842. function draggableDayEvent(event, eventElement, seg) {
  3843. var isStart = seg.isStart;
  3844. var origWidth;
  3845. var revert;
  3846. var allDay = true;
  3847. var dayDelta;
  3848. var hoverListener = getHoverListener();
  3849. var colWidth = getColWidth();
  3850. var minTime = getMinTime();
  3851. var slotDuration = getSlotDuration();
  3852. var slotHeight = getSlotHeight();
  3853. var snapDuration = getSnapDuration();
  3854. var snapHeight = getSnapHeight();
  3855. eventElement.draggable({
  3856. opacity: opt('dragOpacity', 'month'), // use whatever the month view was using
  3857. revertDuration: opt('dragRevertDuration'),
  3858. start: function(ev, ui) {
  3859. trigger('eventDragStart', eventElement[0], event, ev, ui);
  3860. hideEvents(event, eventElement);
  3861. origWidth = eventElement.width();
  3862. hoverListener.start(function(cell, origCell) {
  3863. clearOverlays();
  3864. if (cell) {
  3865. revert = false;
  3866. var origDate = cellToDate(0, origCell.col);
  3867. var date = cellToDate(0, cell.col);
  3868. dayDelta = date.diff(origDate, 'days');
  3869. if (!cell.row) { // on full-days
  3870. renderDayOverlay(
  3871. event.start.clone().add(dayDelta, 'days'),
  3872. getEventEnd(event).add(dayDelta, 'days')
  3873. );
  3874. resetElement();
  3875. }
  3876. else { // mouse is over bottom slots
  3877. if (isStart) {
  3878. if (allDay) {
  3879. // convert event to temporary slot-event
  3880. eventElement.width(colWidth - 10); // don't use entire width
  3881. setOuterHeight(eventElement, calendar.defaultTimedEventDuration / slotDuration * slotHeight); // the default height
  3882. eventElement.draggable('option', 'grid', [ colWidth, 1 ]);
  3883. allDay = false;
  3884. }
  3885. }
  3886. else {
  3887. revert = true;
  3888. }
  3889. }
  3890. revert = revert || (allDay && !dayDelta);
  3891. }
  3892. else {
  3893. resetElement();
  3894. revert = true;
  3895. }
  3896. eventElement.draggable('option', 'revert', revert);
  3897. }, ev, 'drag');
  3898. },
  3899. stop: function(ev, ui) {
  3900. hoverListener.stop();
  3901. clearOverlays();
  3902. trigger('eventDragStop', eventElement[0], event, ev, ui);
  3903. if (revert) { // hasn't moved or is out of bounds (draggable has already reverted)
  3904. resetElement();
  3905. eventElement.css('filter', ''); // clear IE opacity side-effects
  3906. showEvents(event, eventElement);
  3907. }
  3908. else { // changed!
  3909. var eventStart = event.start.clone().add(dayDelta, 'days'); // already assumed to have a stripped time
  3910. var snapTime;
  3911. var snapIndex;
  3912. if (!allDay) {
  3913. snapIndex = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight); // why not use ui.offset.top?
  3914. snapTime = moment.duration(minTime + snapIndex * snapDuration);
  3915. eventStart = calendar.rezoneDate(eventStart.clone().time(snapTime));
  3916. }
  3917. eventDrop(
  3918. eventElement[0],
  3919. event,
  3920. eventStart,
  3921. ev,
  3922. ui
  3923. );
  3924. }
  3925. }
  3926. });
  3927. function resetElement() {
  3928. if (!allDay) {
  3929. eventElement
  3930. .width(origWidth)
  3931. .height('')
  3932. .draggable('option', 'grid', null);
  3933. allDay = true;
  3934. }
  3935. }
  3936. }
  3937. // when event starts out IN TIMESLOTS
  3938. function draggableSlotEvent(event, eventElement, timeElement) {
  3939. var coordinateGrid = t.getCoordinateGrid();
  3940. var colCnt = getColCnt();
  3941. var colWidth = getColWidth();
  3942. var snapHeight = getSnapHeight();
  3943. var snapDuration = getSnapDuration();
  3944. // states
  3945. var origPosition; // original position of the element, not the mouse
  3946. var origCell;
  3947. var isInBounds, prevIsInBounds;
  3948. var isAllDay, prevIsAllDay;
  3949. var colDelta, prevColDelta;
  3950. var dayDelta; // derived from colDelta
  3951. var snapDelta, prevSnapDelta; // the number of snaps away from the original position
  3952. // newly computed
  3953. var eventStart, eventEnd;
  3954. eventElement.draggable({
  3955. scroll: false,
  3956. grid: [ colWidth, snapHeight ],
  3957. axis: colCnt==1 ? 'y' : false,
  3958. opacity: opt('dragOpacity'),
  3959. revertDuration: opt('dragRevertDuration'),
  3960. start: function(ev, ui) {
  3961. trigger('eventDragStart', eventElement[0], event, ev, ui);
  3962. hideEvents(event, eventElement);
  3963. coordinateGrid.build();
  3964. // initialize states
  3965. origPosition = eventElement.position();
  3966. origCell = coordinateGrid.cell(ev.pageX, ev.pageY);
  3967. isInBounds = prevIsInBounds = true;
  3968. isAllDay = prevIsAllDay = getIsCellAllDay(origCell);
  3969. colDelta = prevColDelta = 0;
  3970. dayDelta = 0;
  3971. snapDelta = prevSnapDelta = 0;
  3972. eventStart = null;
  3973. eventEnd = null;
  3974. },
  3975. drag: function(ev, ui) {
  3976. // NOTE: this `cell` value is only useful for determining in-bounds and all-day.
  3977. // Bad for anything else due to the discrepancy between the mouse position and the
  3978. // element position while snapping. (problem revealed in PR #55)
  3979. //
  3980. // PS- the problem exists for draggableDayEvent() when dragging an all-day event to a slot event.
  3981. // We should overhaul the dragging system and stop relying on jQuery UI.
  3982. var cell = coordinateGrid.cell(ev.pageX, ev.pageY);
  3983. // update states
  3984. isInBounds = !!cell;
  3985. if (isInBounds) {
  3986. isAllDay = getIsCellAllDay(cell);
  3987. // calculate column delta
  3988. colDelta = Math.round((ui.position.left - origPosition.left) / colWidth);
  3989. if (colDelta != prevColDelta) {
  3990. // calculate the day delta based off of the original clicked column and the column delta
  3991. var origDate = cellToDate(0, origCell.col);
  3992. var col = origCell.col + colDelta;
  3993. col = Math.max(0, col);
  3994. col = Math.min(colCnt-1, col);
  3995. var date = cellToDate(0, col);
  3996. dayDelta = date.diff(origDate, 'days');
  3997. }
  3998. // calculate minute delta (only if over slots)
  3999. if (!isAllDay) {
  4000. snapDelta = Math.round((ui.position.top - origPosition.top) / snapHeight);
  4001. }
  4002. }
  4003. // any state changes?
  4004. if (
  4005. isInBounds != prevIsInBounds ||
  4006. isAllDay != prevIsAllDay ||
  4007. colDelta != prevColDelta ||
  4008. snapDelta != prevSnapDelta
  4009. ) {
  4010. // compute new dates
  4011. if (isAllDay) {
  4012. eventStart = event.start.clone().stripTime().add(dayDelta, 'days');
  4013. eventEnd = eventStart.clone().add(calendar.defaultAllDayEventDuration);
  4014. }
  4015. else {
  4016. eventStart = event.start.clone().add(snapDelta * snapDuration).add(dayDelta, 'days');
  4017. eventEnd = getEventEnd(event).add(snapDelta * snapDuration).add(dayDelta, 'days');
  4018. }
  4019. updateUI();
  4020. // update previous states for next time
  4021. prevIsInBounds = isInBounds;
  4022. prevIsAllDay = isAllDay;
  4023. prevColDelta = colDelta;
  4024. prevSnapDelta = snapDelta;
  4025. }
  4026. // if out-of-bounds, revert when done, and vice versa.
  4027. eventElement.draggable('option', 'revert', !isInBounds);
  4028. },
  4029. stop: function(ev, ui) {
  4030. clearOverlays();
  4031. trigger('eventDragStop', eventElement[0], event, ev, ui);
  4032. if (isInBounds && (isAllDay || dayDelta || snapDelta)) { // changed!
  4033. eventDrop(
  4034. eventElement[0],
  4035. event,
  4036. eventStart,
  4037. ev,
  4038. ui
  4039. );
  4040. }
  4041. else { // either no change or out-of-bounds (draggable has already reverted)
  4042. // reset states for next time, and for updateUI()
  4043. isInBounds = true;
  4044. isAllDay = false;
  4045. colDelta = 0;
  4046. dayDelta = 0;
  4047. snapDelta = 0;
  4048. updateUI();
  4049. eventElement.css('filter', ''); // clear IE opacity side-effects
  4050. // sometimes fast drags make event revert to wrong position, so reset.
  4051. // also, if we dragged the element out of the area because of snapping,
  4052. // but the *mouse* is still in bounds, we need to reset the position.
  4053. eventElement.css(origPosition);
  4054. showEvents(event, eventElement);
  4055. }
  4056. }
  4057. });
  4058. function updateUI() {
  4059. clearOverlays();
  4060. if (isInBounds) {
  4061. if (isAllDay) {
  4062. timeElement.hide();
  4063. eventElement.draggable('option', 'grid', null); // disable grid snapping
  4064. renderDayOverlay(eventStart, eventEnd);
  4065. }
  4066. else {
  4067. updateTimeText();
  4068. timeElement.css('display', ''); // show() was causing display=inline
  4069. eventElement.draggable('option', 'grid', [colWidth, snapHeight]); // re-enable grid snapping
  4070. }
  4071. }
  4072. }
  4073. function updateTimeText() {
  4074. if (eventStart) { // must of had a state change
  4075. timeElement.text(
  4076. t.getEventTimeText(eventStart, event.end ? eventEnd : null)
  4077. // ^
  4078. // only display the new end if there was an old end
  4079. );
  4080. }
  4081. }
  4082. }
  4083. /* Resizing
  4084. --------------------------------------------------------------------------------------*/
  4085. function resizableSlotEvent(event, eventElement, timeElement) {
  4086. var snapDelta, prevSnapDelta;
  4087. var snapHeight = getSnapHeight();
  4088. var snapDuration = getSnapDuration();
  4089. var eventEnd;
  4090. eventElement.resizable({
  4091. handles: {
  4092. s: '.ui-resizable-handle'
  4093. },
  4094. grid: snapHeight,
  4095. start: function(ev, ui) {
  4096. snapDelta = prevSnapDelta = 0;
  4097. hideEvents(event, eventElement);
  4098. trigger('eventResizeStart', eventElement[0], event, ev, ui);
  4099. },
  4100. resize: function(ev, ui) {
  4101. // don't rely on ui.size.height, doesn't take grid into account
  4102. snapDelta = Math.round((Math.max(snapHeight, eventElement.height()) - ui.originalSize.height) / snapHeight);
  4103. if (snapDelta != prevSnapDelta) {
  4104. eventEnd = getEventEnd(event).add(snapDuration * snapDelta);
  4105. var text;
  4106. if (snapDelta) { // has there been a change?
  4107. text = t.getEventTimeText(event.start, eventEnd);
  4108. }
  4109. else {
  4110. text = t.getEventTimeText(event); // the original time text
  4111. }
  4112. timeElement.text(text);
  4113. prevSnapDelta = snapDelta;
  4114. }
  4115. },
  4116. stop: function(ev, ui) {
  4117. trigger('eventResizeStop', eventElement[0], event, ev, ui);
  4118. if (snapDelta) {
  4119. eventResize(
  4120. eventElement[0],
  4121. event,
  4122. eventEnd,
  4123. ev,
  4124. ui
  4125. );
  4126. }
  4127. else {
  4128. showEvents(event, eventElement);
  4129. // BUG: if event was really short, need to put title back in span
  4130. }
  4131. }
  4132. });
  4133. }
  4134. }
  4135. /* Agenda Event Segment Utilities
  4136. -----------------------------------------------------------------------------*/
  4137. // Sets the seg.backwardCoord and seg.forwardCoord on each segment and returns a new
  4138. // list in the order they should be placed into the DOM (an implicit z-index).
  4139. function placeSlotSegs(segs) {
  4140. var levels = buildSlotSegLevels(segs);
  4141. var level0 = levels[0];
  4142. var i;
  4143. computeForwardSlotSegs(levels);
  4144. if (level0) {
  4145. for (i=0; i<level0.length; i++) {
  4146. computeSlotSegPressures(level0[i]);
  4147. }
  4148. for (i=0; i<level0.length; i++) {
  4149. computeSlotSegCoords(level0[i], 0, 0);
  4150. }
  4151. }
  4152. return flattenSlotSegLevels(levels);
  4153. }
  4154. // Builds an array of segments "levels". The first level will be the leftmost tier of segments
  4155. // if the calendar is left-to-right, or the rightmost if the calendar is right-to-left.
  4156. function buildSlotSegLevels(segs) {
  4157. var levels = [];
  4158. var i, seg;
  4159. var j;
  4160. for (i=0; i<segs.length; i++) {
  4161. seg = segs[i];
  4162. // go through all the levels and stop on the first level where there are no collisions
  4163. for (j=0; j<levels.length; j++) {
  4164. if (!computeSlotSegCollisions(seg, levels[j]).length) {
  4165. break;
  4166. }
  4167. }
  4168. (levels[j] || (levels[j] = [])).push(seg);
  4169. }
  4170. return levels;
  4171. }
  4172. // For every segment, figure out the other segments that are in subsequent
  4173. // levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
  4174. function computeForwardSlotSegs(levels) {
  4175. var i, level;
  4176. var j, seg;
  4177. var k;
  4178. for (i=0; i<levels.length; i++) {
  4179. level = levels[i];
  4180. for (j=0; j<level.length; j++) {
  4181. seg = level[j];
  4182. seg.forwardSegs = [];
  4183. for (k=i+1; k<levels.length; k++) {
  4184. computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
  4185. }
  4186. }
  4187. }
  4188. }
  4189. // Figure out which path forward (via seg.forwardSegs) results in the longest path until
  4190. // the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
  4191. function computeSlotSegPressures(seg) {
  4192. var forwardSegs = seg.forwardSegs;
  4193. var forwardPressure = 0;
  4194. var i, forwardSeg;
  4195. if (seg.forwardPressure === undefined) { // not already computed
  4196. for (i=0; i<forwardSegs.length; i++) {
  4197. forwardSeg = forwardSegs[i];
  4198. // figure out the child's maximum forward path
  4199. computeSlotSegPressures(forwardSeg);
  4200. // either use the existing maximum, or use the child's forward pressure
  4201. // plus one (for the forwardSeg itself)
  4202. forwardPressure = Math.max(
  4203. forwardPressure,
  4204. 1 + forwardSeg.forwardPressure
  4205. );
  4206. }
  4207. seg.forwardPressure = forwardPressure;
  4208. }
  4209. }
  4210. // Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
  4211. // from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
  4212. // seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
  4213. //
  4214. // The segment might be part of a "series", which means consecutive segments with the same pressure
  4215. // who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
  4216. // segments behind this one in the current series, and `seriesBackwardCoord` is the starting
  4217. // coordinate of the first segment in the series.
  4218. function computeSlotSegCoords(seg, seriesBackwardPressure, seriesBackwardCoord) {
  4219. var forwardSegs = seg.forwardSegs;
  4220. var i;
  4221. if (seg.forwardCoord === undefined) { // not already computed
  4222. if (!forwardSegs.length) {
  4223. // if there are no forward segments, this segment should butt up against the edge
  4224. seg.forwardCoord = 1;
  4225. }
  4226. else {
  4227. // sort highest pressure first
  4228. forwardSegs.sort(compareForwardSlotSegs);
  4229. // this segment's forwardCoord will be calculated from the backwardCoord of the
  4230. // highest-pressure forward segment.
  4231. computeSlotSegCoords(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
  4232. seg.forwardCoord = forwardSegs[0].backwardCoord;
  4233. }
  4234. // calculate the backwardCoord from the forwardCoord. consider the series
  4235. seg.backwardCoord = seg.forwardCoord -
  4236. (seg.forwardCoord - seriesBackwardCoord) / // available width for series
  4237. (seriesBackwardPressure + 1); // # of segments in the series
  4238. // use this segment's coordinates to computed the coordinates of the less-pressurized
  4239. // forward segments
  4240. for (i=0; i<forwardSegs.length; i++) {
  4241. computeSlotSegCoords(forwardSegs[i], 0, seg.forwardCoord);
  4242. }
  4243. }
  4244. }
  4245. // Outputs a flat array of segments, from lowest to highest level
  4246. function flattenSlotSegLevels(levels) {
  4247. var segs = [];
  4248. var i, level;
  4249. var j;
  4250. for (i=0; i<levels.length; i++) {
  4251. level = levels[i];
  4252. for (j=0; j<level.length; j++) {
  4253. segs.push(level[j]);
  4254. }
  4255. }
  4256. return segs;
  4257. }
  4258. // Find all the segments in `otherSegs` that vertically collide with `seg`.
  4259. // Append into an optionally-supplied `results` array and return.
  4260. function computeSlotSegCollisions(seg, otherSegs, results) {
  4261. results = results || [];
  4262. for (var i=0; i<otherSegs.length; i++) {
  4263. if (isSlotSegCollision(seg, otherSegs[i])) {
  4264. results.push(otherSegs[i]);
  4265. }
  4266. }
  4267. return results;
  4268. }
  4269. // Do these segments occupy the same vertical space?
  4270. function isSlotSegCollision(seg1, seg2) {
  4271. return seg1.end > seg2.start && seg1.start < seg2.end;
  4272. }
  4273. // A cmp function for determining which forward segment to rely on more when computing coordinates.
  4274. function compareForwardSlotSegs(seg1, seg2) {
  4275. // put higher-pressure first
  4276. return seg2.forwardPressure - seg1.forwardPressure ||
  4277. // put segments that are closer to initial edge first (and favor ones with no coords yet)
  4278. (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
  4279. // do normal sorting...
  4280. compareSlotSegs(seg1, seg2);
  4281. }
  4282. // A cmp function for determining which segment should be closer to the initial edge
  4283. // (the left edge on a left-to-right calendar).
  4284. function compareSlotSegs(seg1, seg2) {
  4285. return seg1.start - seg2.start || // earlier start time goes first
  4286. (seg2.end - seg2.start) - (seg1.end - seg1.start) || // tie? longer-duration goes first
  4287. (seg1.event.title || '').localeCompare(seg2.event.title); // tie? alphabetically by title
  4288. }
  4289. ;;
  4290. function View(element, calendar, viewName) {
  4291. var t = this;
  4292. // exports
  4293. t.element = element;
  4294. t.calendar = calendar;
  4295. t.name = viewName;
  4296. t.opt = opt;
  4297. t.trigger = trigger;
  4298. t.isEventDraggable = isEventDraggable;
  4299. t.isEventResizable = isEventResizable;
  4300. t.clearEventData = clearEventData;
  4301. t.reportEventElement = reportEventElement;
  4302. t.triggerEventDestroy = triggerEventDestroy;
  4303. t.eventElementHandlers = eventElementHandlers;
  4304. t.showEvents = showEvents;
  4305. t.hideEvents = hideEvents;
  4306. t.eventDrop = eventDrop;
  4307. t.eventResize = eventResize;
  4308. // t.start, t.end // moments with ambiguous-time
  4309. // t.intervalStart, t.intervalEnd // moments with ambiguous-time
  4310. // imports
  4311. var reportEventChange = calendar.reportEventChange;
  4312. // locals
  4313. var eventElementsByID = {}; // eventID mapped to array of jQuery elements
  4314. var eventElementCouples = []; // array of objects, { event, element } // TODO: unify with segment system
  4315. var options = calendar.options;
  4316. var nextDayThreshold = moment.duration(options.nextDayThreshold);
  4317. function opt(name, viewNameOverride) {
  4318. var v = options[name];
  4319. if ($.isPlainObject(v) && !isForcedAtomicOption(name)) {
  4320. return smartProperty(v, viewNameOverride || viewName);
  4321. }
  4322. return v;
  4323. }
  4324. function trigger(name, thisObj) {
  4325. return calendar.trigger.apply(
  4326. calendar,
  4327. [name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t])
  4328. );
  4329. }
  4330. /* Event Editable Boolean Calculations
  4331. ------------------------------------------------------------------------------*/
  4332. function isEventDraggable(event) {
  4333. var source = event.source || {};
  4334. return firstDefined(
  4335. event.startEditable,
  4336. source.startEditable,
  4337. opt('eventStartEditable'),
  4338. event.editable,
  4339. source.editable,
  4340. opt('editable')
  4341. );
  4342. }
  4343. function isEventResizable(event) { // but also need to make sure the seg.isEnd == true
  4344. var source = event.source || {};
  4345. return firstDefined(
  4346. event.durationEditable,
  4347. source.durationEditable,
  4348. opt('eventDurationEditable'),
  4349. event.editable,
  4350. source.editable,
  4351. opt('editable')
  4352. );
  4353. }
  4354. /* Event Data
  4355. ------------------------------------------------------------------------------*/
  4356. function clearEventData() {
  4357. eventElementsByID = {};
  4358. eventElementCouples = [];
  4359. }
  4360. /* Event Elements
  4361. ------------------------------------------------------------------------------*/
  4362. // report when view creates an element for an event
  4363. function reportEventElement(event, element) {
  4364. eventElementCouples.push({ event: event, element: element });
  4365. if (eventElementsByID[event._id]) {
  4366. eventElementsByID[event._id].push(element);
  4367. }else{
  4368. eventElementsByID[event._id] = [element];
  4369. }
  4370. }
  4371. function triggerEventDestroy() {
  4372. $.each(eventElementCouples, function(i, couple) {
  4373. t.trigger('eventDestroy', couple.event, couple.event, couple.element);
  4374. });
  4375. }
  4376. // attaches eventClick, eventMouseover, eventMouseout
  4377. function eventElementHandlers(event, eventElement) {
  4378. eventElement
  4379. .click(function(ev) {
  4380. if (!eventElement.hasClass('ui-draggable-dragging') &&
  4381. !eventElement.hasClass('ui-resizable-resizing')) {
  4382. return trigger('eventClick', this, event, ev);
  4383. }
  4384. })
  4385. .hover(
  4386. function(ev) {
  4387. trigger('eventMouseover', this, event, ev);
  4388. },
  4389. function(ev) {
  4390. trigger('eventMouseout', this, event, ev);
  4391. }
  4392. );
  4393. // TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
  4394. // TODO: same for resizing
  4395. }
  4396. function showEvents(event, exceptElement) {
  4397. eachEventElement(event, exceptElement, 'show');
  4398. }
  4399. function hideEvents(event, exceptElement) {
  4400. eachEventElement(event, exceptElement, 'hide');
  4401. }
  4402. function eachEventElement(event, exceptElement, funcName) {
  4403. // NOTE: there may be multiple events per ID (repeating events)
  4404. // and multiple segments per event
  4405. var elements = eventElementsByID[event._id],
  4406. i, len = elements.length;
  4407. for (i=0; i<len; i++) {
  4408. if (!exceptElement || elements[i][0] != exceptElement[0]) {
  4409. elements[i][funcName]();
  4410. }
  4411. }
  4412. }
  4413. // Compute the text that should be displayed on an event's element.
  4414. // Based off the settings of the view.
  4415. // Given either an event object or two arguments: a start and end date (which can be null)
  4416. t.getEventTimeText = function(event) {
  4417. var start;
  4418. var end;
  4419. if (arguments.length === 2) {
  4420. start = arguments[0];
  4421. end = arguments[1];
  4422. }
  4423. else {
  4424. start = event.start;
  4425. end = event.end;
  4426. }
  4427. if (end && opt('displayEventEnd')) {
  4428. return calendar.formatRange(start, end, opt('timeFormat'));
  4429. }
  4430. else {
  4431. return calendar.formatDate(start, opt('timeFormat'));
  4432. }
  4433. };
  4434. /* Event Modification Reporting
  4435. ---------------------------------------------------------------------------------*/
  4436. function eventDrop(el, event, newStart, ev, ui) {
  4437. var mutateResult = calendar.mutateEvent(event, newStart, null);
  4438. trigger(
  4439. 'eventDrop',
  4440. el,
  4441. event,
  4442. mutateResult.dateDelta,
  4443. function() {
  4444. mutateResult.undo();
  4445. reportEventChange(event._id);
  4446. },
  4447. ev,
  4448. ui
  4449. );
  4450. reportEventChange(event._id);
  4451. }
  4452. function eventResize(el, event, newEnd, ev, ui) {
  4453. var mutateResult = calendar.mutateEvent(event, null, newEnd);
  4454. trigger(
  4455. 'eventResize',
  4456. el,
  4457. event,
  4458. mutateResult.durationDelta,
  4459. function() {
  4460. mutateResult.undo();
  4461. reportEventChange(event._id);
  4462. },
  4463. ev,
  4464. ui
  4465. );
  4466. reportEventChange(event._id);
  4467. }
  4468. // ====================================================================================================
  4469. // Utilities for day "cells"
  4470. // ====================================================================================================
  4471. // The "basic" views are completely made up of day cells.
  4472. // The "agenda" views have day cells at the top "all day" slot.
  4473. // This was the obvious common place to put these utilities, but they should be abstracted out into
  4474. // a more meaningful class (like DayEventRenderer).
  4475. // ====================================================================================================
  4476. // For determining how a given "cell" translates into a "date":
  4477. //
  4478. // 1. Convert the "cell" (row and column) into a "cell offset" (the # of the cell, cronologically from the first).
  4479. // Keep in mind that column indices are inverted with isRTL. This is taken into account.
  4480. //
  4481. // 2. Convert the "cell offset" to a "day offset" (the # of days since the first visible day in the view).
  4482. //
  4483. // 3. Convert the "day offset" into a "date" (a Moment).
  4484. //
  4485. // The reverse transformation happens when transforming a date into a cell.
  4486. // exports
  4487. t.isHiddenDay = isHiddenDay;
  4488. t.skipHiddenDays = skipHiddenDays;
  4489. t.getCellsPerWeek = getCellsPerWeek;
  4490. t.dateToCell = dateToCell;
  4491. t.dateToDayOffset = dateToDayOffset;
  4492. t.dayOffsetToCellOffset = dayOffsetToCellOffset;
  4493. t.cellOffsetToCell = cellOffsetToCell;
  4494. t.cellToDate = cellToDate;
  4495. t.cellToCellOffset = cellToCellOffset;
  4496. t.cellOffsetToDayOffset = cellOffsetToDayOffset;
  4497. t.dayOffsetToDate = dayOffsetToDate;
  4498. t.rangeToSegments = rangeToSegments;
  4499. // internals
  4500. var hiddenDays = opt('hiddenDays') || []; // array of day-of-week indices that are hidden
  4501. var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
  4502. var cellsPerWeek;
  4503. var dayToCellMap = []; // hash from dayIndex -> cellIndex, for one week
  4504. var cellToDayMap = []; // hash from cellIndex -> dayIndex, for one week
  4505. var isRTL = opt('isRTL');
  4506. // initialize important internal variables
  4507. (function() {
  4508. if (opt('weekends') === false) {
  4509. hiddenDays.push(0, 6); // 0=sunday, 6=saturday
  4510. }
  4511. // Loop through a hypothetical week and determine which
  4512. // days-of-week are hidden. Record in both hashes (one is the reverse of the other).
  4513. for (var dayIndex=0, cellIndex=0; dayIndex<7; dayIndex++) {
  4514. dayToCellMap[dayIndex] = cellIndex;
  4515. isHiddenDayHash[dayIndex] = $.inArray(dayIndex, hiddenDays) != -1;
  4516. if (!isHiddenDayHash[dayIndex]) {
  4517. cellToDayMap[cellIndex] = dayIndex;
  4518. cellIndex++;
  4519. }
  4520. }
  4521. cellsPerWeek = cellIndex;
  4522. if (!cellsPerWeek) {
  4523. throw 'invalid hiddenDays'; // all days were hidden? bad.
  4524. }
  4525. })();
  4526. // Is the current day hidden?
  4527. // `day` is a day-of-week index (0-6), or a Moment
  4528. function isHiddenDay(day) {
  4529. if (moment.isMoment(day)) {
  4530. day = day.day();
  4531. }
  4532. return isHiddenDayHash[day];
  4533. }
  4534. function getCellsPerWeek() {
  4535. return cellsPerWeek;
  4536. }
  4537. // Incrementing the current day until it is no longer a hidden day, returning a copy.
  4538. // If the initial value of `date` is not a hidden day, don't do anything.
  4539. // Pass `isExclusive` as `true` if you are dealing with an end date.
  4540. // `inc` defaults to `1` (increment one day forward each time)
  4541. function skipHiddenDays(date, inc, isExclusive) {
  4542. var out = date.clone();
  4543. inc = inc || 1;
  4544. while (
  4545. isHiddenDayHash[(out.day() + (isExclusive ? inc : 0) + 7) % 7]
  4546. ) {
  4547. out.add(inc, 'days');
  4548. }
  4549. return out;
  4550. }
  4551. //
  4552. // TRANSFORMATIONS: cell -> cell offset -> day offset -> date
  4553. //
  4554. // cell -> date (combines all transformations)
  4555. // Possible arguments:
  4556. // - row, col
  4557. // - { row:#, col: # }
  4558. function cellToDate() {
  4559. var cellOffset = cellToCellOffset.apply(null, arguments);
  4560. var dayOffset = cellOffsetToDayOffset(cellOffset);
  4561. var date = dayOffsetToDate(dayOffset);
  4562. return date;
  4563. }
  4564. // cell -> cell offset
  4565. // Possible arguments:
  4566. // - row, col
  4567. // - { row:#, col:# }
  4568. function cellToCellOffset(row, col) {
  4569. var colCnt = t.getColCnt();
  4570. // rtl variables. wish we could pre-populate these. but where?
  4571. var dis = isRTL ? -1 : 1;
  4572. var dit = isRTL ? colCnt - 1 : 0;
  4573. if (typeof row == 'object') {
  4574. col = row.col;
  4575. row = row.row;
  4576. }
  4577. var cellOffset = row * colCnt + (col * dis + dit); // column, adjusted for RTL (dis & dit)
  4578. return cellOffset;
  4579. }
  4580. // cell offset -> day offset
  4581. function cellOffsetToDayOffset(cellOffset) {
  4582. var day0 = t.start.day(); // first date's day of week
  4583. cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-week
  4584. return Math.floor(cellOffset / cellsPerWeek) * 7 + // # of days from full weeks
  4585. cellToDayMap[ // # of days from partial last week
  4586. (cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets
  4587. ] -
  4588. day0; // adjustment for beginning-of-week normalization
  4589. }
  4590. // day offset -> date
  4591. function dayOffsetToDate(dayOffset) {
  4592. return t.start.clone().add(dayOffset, 'days');
  4593. }
  4594. //
  4595. // TRANSFORMATIONS: date -> day offset -> cell offset -> cell
  4596. //
  4597. // date -> cell (combines all transformations)
  4598. function dateToCell(date) {
  4599. var dayOffset = dateToDayOffset(date);
  4600. var cellOffset = dayOffsetToCellOffset(dayOffset);
  4601. var cell = cellOffsetToCell(cellOffset);
  4602. return cell;
  4603. }
  4604. // date -> day offset
  4605. function dateToDayOffset(date) {
  4606. return date.clone().stripTime().diff(t.start, 'days');
  4607. }
  4608. // day offset -> cell offset
  4609. function dayOffsetToCellOffset(dayOffset) {
  4610. var day0 = t.start.day(); // first date's day of week
  4611. dayOffset += day0; // normalize dayOffset to beginning-of-week
  4612. return Math.floor(dayOffset / 7) * cellsPerWeek + // # of cells from full weeks
  4613. dayToCellMap[ // # of cells from partial last week
  4614. (dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets
  4615. ] -
  4616. dayToCellMap[day0]; // adjustment for beginning-of-week normalization
  4617. }
  4618. // cell offset -> cell (object with row & col keys)
  4619. function cellOffsetToCell(cellOffset) {
  4620. var colCnt = t.getColCnt();
  4621. // rtl variables. wish we could pre-populate these. but where?
  4622. var dis = isRTL ? -1 : 1;
  4623. var dit = isRTL ? colCnt - 1 : 0;
  4624. var row = Math.floor(cellOffset / colCnt);
  4625. var col = ((cellOffset % colCnt + colCnt) % colCnt) * dis + dit; // column, adjusted for RTL (dis & dit)
  4626. return {
  4627. row: row,
  4628. col: col
  4629. };
  4630. }
  4631. //
  4632. // Converts a date range into an array of segment objects.
  4633. // "Segments" are horizontal stretches of time, sliced up by row.
  4634. // A segment object has the following properties:
  4635. // - row
  4636. // - cols
  4637. // - isStart
  4638. // - isEnd
  4639. //
  4640. function rangeToSegments(start, end) {
  4641. var rowCnt = t.getRowCnt();
  4642. var colCnt = t.getColCnt();
  4643. var segments = []; // array of segments to return
  4644. // day offset for given date range
  4645. var rangeDayOffsetStart = dateToDayOffset(start);
  4646. var rangeDayOffsetEnd = dateToDayOffset(end); // an exclusive value
  4647. var endTimeMS = +end.time();
  4648. if (endTimeMS && endTimeMS >= nextDayThreshold) {
  4649. rangeDayOffsetEnd++;
  4650. }
  4651. rangeDayOffsetEnd = Math.max(rangeDayOffsetEnd, rangeDayOffsetStart + 1);
  4652. // first and last cell offset for the given date range
  4653. // "last" implies inclusivity
  4654. var rangeCellOffsetFirst = dayOffsetToCellOffset(rangeDayOffsetStart);
  4655. var rangeCellOffsetLast = dayOffsetToCellOffset(rangeDayOffsetEnd) - 1;
  4656. // loop through all the rows in the view
  4657. for (var row=0; row<rowCnt; row++) {
  4658. // first and last cell offset for the row
  4659. var rowCellOffsetFirst = row * colCnt;
  4660. var rowCellOffsetLast = rowCellOffsetFirst + colCnt - 1;
  4661. // get the segment's cell offsets by constraining the range's cell offsets to the bounds of the row
  4662. var segmentCellOffsetFirst = Math.max(rangeCellOffsetFirst, rowCellOffsetFirst);
  4663. var segmentCellOffsetLast = Math.min(rangeCellOffsetLast, rowCellOffsetLast);
  4664. // make sure segment's offsets are valid and in view
  4665. if (segmentCellOffsetFirst <= segmentCellOffsetLast) {
  4666. // translate to cells
  4667. var segmentCellFirst = cellOffsetToCell(segmentCellOffsetFirst);
  4668. var segmentCellLast = cellOffsetToCell(segmentCellOffsetLast);
  4669. // view might be RTL, so order by leftmost column
  4670. var cols = [ segmentCellFirst.col, segmentCellLast.col ].sort();
  4671. // Determine if segment's first/last cell is the beginning/end of the date range.
  4672. // We need to compare "day offset" because "cell offsets" are often ambiguous and
  4673. // can translate to multiple days, and an edge case reveals itself when we the
  4674. // range's first cell is hidden (we don't want isStart to be true).
  4675. var isStart = cellOffsetToDayOffset(segmentCellOffsetFirst) == rangeDayOffsetStart;
  4676. var isEnd = cellOffsetToDayOffset(segmentCellOffsetLast) + 1 == rangeDayOffsetEnd; // +1 for comparing exclusively
  4677. segments.push({
  4678. row: row,
  4679. leftCol: cols[0],
  4680. rightCol: cols[1],
  4681. isStart: isStart,
  4682. isEnd: isEnd
  4683. });
  4684. }
  4685. }
  4686. return segments;
  4687. }
  4688. }
  4689. ;;
  4690. function DayEventRenderer() {
  4691. var t = this;
  4692. // exports
  4693. t.renderDayEvents = renderDayEvents;
  4694. t.draggableDayEvent = draggableDayEvent; // made public so that subclasses can override
  4695. t.resizableDayEvent = resizableDayEvent; // "
  4696. // imports
  4697. var opt = t.opt;
  4698. var trigger = t.trigger;
  4699. var isEventDraggable = t.isEventDraggable;
  4700. var isEventResizable = t.isEventResizable;
  4701. var reportEventElement = t.reportEventElement;
  4702. var eventElementHandlers = t.eventElementHandlers;
  4703. var showEvents = t.showEvents;
  4704. var hideEvents = t.hideEvents;
  4705. var eventDrop = t.eventDrop;
  4706. var eventResize = t.eventResize;
  4707. var getRowCnt = t.getRowCnt;
  4708. var getColCnt = t.getColCnt;
  4709. var allDayRow = t.allDayRow; // TODO: rename
  4710. var colLeft = t.colLeft;
  4711. var colRight = t.colRight;
  4712. var colContentLeft = t.colContentLeft;
  4713. var colContentRight = t.colContentRight;
  4714. var getDaySegmentContainer = t.getDaySegmentContainer;
  4715. var renderDayOverlay = t.renderDayOverlay;
  4716. var clearOverlays = t.clearOverlays;
  4717. var clearSelection = t.clearSelection;
  4718. var getHoverListener = t.getHoverListener;
  4719. var rangeToSegments = t.rangeToSegments;
  4720. var cellToDate = t.cellToDate;
  4721. var cellToCellOffset = t.cellToCellOffset;
  4722. var cellOffsetToDayOffset = t.cellOffsetToDayOffset;
  4723. var dateToDayOffset = t.dateToDayOffset;
  4724. var dayOffsetToCellOffset = t.dayOffsetToCellOffset;
  4725. var calendar = t.calendar;
  4726. var getEventEnd = calendar.getEventEnd;
  4727. // Render `events` onto the calendar, attach mouse event handlers, and call the `eventAfterRender` callback for each.
  4728. // Mouse event will be lazily applied, except if the event has an ID of `modifiedEventId`.
  4729. // Can only be called when the event container is empty (because it wipes out all innerHTML).
  4730. function renderDayEvents(events, modifiedEventId) {
  4731. // do the actual rendering. Receive the intermediate "segment" data structures.
  4732. var segments = _renderDayEvents(
  4733. events,
  4734. false, // don't append event elements
  4735. true // set the heights of the rows
  4736. );
  4737. // report the elements to the View, for general drag/resize utilities
  4738. segmentElementEach(segments, function(segment, element) {
  4739. reportEventElement(segment.event, element);
  4740. });
  4741. // attach mouse handlers
  4742. attachHandlers(segments, modifiedEventId);
  4743. // call `eventAfterRender` callback for each event
  4744. segmentElementEach(segments, function(segment, element) {
  4745. trigger('eventAfterRender', segment.event, segment.event, element);
  4746. });
  4747. }
  4748. // Render an event on the calendar, but don't report them anywhere, and don't attach mouse handlers.
  4749. // Append this event element to the event container, which might already be populated with events.
  4750. // If an event's segment will have row equal to `adjustRow`, then explicitly set its top coordinate to `adjustTop`.
  4751. // This hack is used to maintain continuity when user is manually resizing an event.
  4752. // Returns an array of DOM elements for the event.
  4753. function renderTempDayEvent(event, adjustRow, adjustTop) {
  4754. // actually render the event. `true` for appending element to container.
  4755. // Recieve the intermediate "segment" data structures.
  4756. var segments = _renderDayEvents(
  4757. [ event ],
  4758. true, // append event elements
  4759. false // don't set the heights of the rows
  4760. );
  4761. var elements = [];
  4762. // Adjust certain elements' top coordinates
  4763. segmentElementEach(segments, function(segment, element) {
  4764. if (segment.row === adjustRow) {
  4765. element.css('top', adjustTop);
  4766. }
  4767. elements.push(element[0]); // accumulate DOM nodes
  4768. });
  4769. return elements;
  4770. }
  4771. // Render events onto the calendar. Only responsible for the VISUAL aspect.
  4772. // Not responsible for attaching handlers or calling callbacks.
  4773. // Set `doAppend` to `true` for rendering elements without clearing the existing container.
  4774. // Set `doRowHeights` to allow setting the height of each row, to compensate for vertical event overflow.
  4775. function _renderDayEvents(events, doAppend, doRowHeights) {
  4776. // where the DOM nodes will eventually end up
  4777. var finalContainer = getDaySegmentContainer();
  4778. // the container where the initial HTML will be rendered.
  4779. // If `doAppend`==true, uses a temporary container.
  4780. var renderContainer = doAppend ? $("<div/>") : finalContainer;
  4781. var segments = buildSegments(events);
  4782. var html;
  4783. var elements;
  4784. // calculate the desired `left` and `width` properties on each segment object
  4785. calculateHorizontals(segments);
  4786. // build the HTML string. relies on `left` property
  4787. html = buildHTML(segments);
  4788. // render the HTML. innerHTML is considerably faster than jQuery's .html()
  4789. renderContainer[0].innerHTML = html;
  4790. // retrieve the individual elements
  4791. elements = renderContainer.children();
  4792. // if we were appending, and thus using a temporary container,
  4793. // re-attach elements to the real container.
  4794. if (doAppend) {
  4795. finalContainer.append(elements);
  4796. }
  4797. // assigns each element to `segment.event`, after filtering them through user callbacks
  4798. resolveElements(segments, elements);
  4799. // Calculate the left and right padding+margin for each element.
  4800. // We need this for setting each element's desired outer width, because of the W3C box model.
  4801. // It's important we do this in a separate pass from acually setting the width on the DOM elements
  4802. // because alternating reading/writing dimensions causes reflow for every iteration.
  4803. segmentElementEach(segments, function(segment, element) {
  4804. segment.hsides = hsides(element, true); // include margins = `true`
  4805. });
  4806. // Set the width of each element
  4807. segmentElementEach(segments, function(segment, element) {
  4808. element.width(
  4809. Math.max(0, segment.outerWidth - segment.hsides)
  4810. );
  4811. });
  4812. // Grab each element's outerHeight (setVerticals uses this).
  4813. // To get an accurate reading, it's important to have each element's width explicitly set already.
  4814. segmentElementEach(segments, function(segment, element) {
  4815. segment.outerHeight = element.outerHeight(true); // include margins = `true`
  4816. });
  4817. // Set the top coordinate on each element (requires segment.outerHeight)
  4818. setVerticals(segments, doRowHeights);
  4819. return segments;
  4820. }
  4821. // Generate an array of "segments" for all events.
  4822. function buildSegments(events) {
  4823. var segments = [];
  4824. for (var i=0; i<events.length; i++) {
  4825. var eventSegments = buildSegmentsForEvent(events[i]);
  4826. segments.push.apply(segments, eventSegments); // append an array to an array
  4827. }
  4828. return segments;
  4829. }
  4830. // Generate an array of segments for a single event.
  4831. // A "segment" is the same data structure that View.rangeToSegments produces,
  4832. // with the addition of the `event` property being set to reference the original event.
  4833. function buildSegmentsForEvent(event) {
  4834. var segments = rangeToSegments(event.start, getEventEnd(event));
  4835. for (var i=0; i<segments.length; i++) {
  4836. segments[i].event = event;
  4837. }
  4838. return segments;
  4839. }
  4840. // Sets the `left` and `outerWidth` property of each segment.
  4841. // These values are the desired dimensions for the eventual DOM elements.
  4842. function calculateHorizontals(segments) {
  4843. var isRTL = opt('isRTL');
  4844. for (var i=0; i<segments.length; i++) {
  4845. var segment = segments[i];
  4846. // Determine functions used for calulating the elements left/right coordinates,
  4847. // depending on whether the view is RTL or not.
  4848. // NOTE:
  4849. // colLeft/colRight returns the coordinate butting up the edge of the cell.
  4850. // colContentLeft/colContentRight is indented a little bit from the edge.
  4851. var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft;
  4852. var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight;
  4853. var left = leftFunc(segment.leftCol);
  4854. var right = rightFunc(segment.rightCol);
  4855. segment.left = left;
  4856. segment.outerWidth = right - left;
  4857. }
  4858. }
  4859. // Build a concatenated HTML string for an array of segments
  4860. function buildHTML(segments) {
  4861. var html = '';
  4862. for (var i=0; i<segments.length; i++) {
  4863. html += buildHTMLForSegment(segments[i]);
  4864. }
  4865. return html;
  4866. }
  4867. // Build an HTML string for a single segment.
  4868. // Relies on the following properties:
  4869. // - `segment.event` (from `buildSegmentsForEvent`)
  4870. // - `segment.left` (from `calculateHorizontals`)
  4871. function buildHTMLForSegment(segment) {
  4872. var html = '';
  4873. var isRTL = opt('isRTL');
  4874. var event = segment.event;
  4875. var url = event.url;
  4876. // generate the list of CSS classNames
  4877. var classNames = [ 'fc-event', 'fc-event-hori' ];
  4878. if (isEventDraggable(event)) {
  4879. classNames.push('fc-event-draggable');
  4880. }
  4881. if (segment.isStart) {
  4882. classNames.push('fc-event-start');
  4883. }
  4884. if (segment.isEnd) {
  4885. classNames.push('fc-event-end');
  4886. }
  4887. // use the event's configured classNames
  4888. // guaranteed to be an array via `buildEvent`
  4889. classNames = classNames.concat(event.className);
  4890. if (event.source) {
  4891. // use the event's source's classNames, if specified
  4892. classNames = classNames.concat(event.source.className || []);
  4893. }
  4894. // generate a semicolon delimited CSS string for any of the "skin" properties
  4895. // of the event object (`backgroundColor`, `borderColor` and such)
  4896. var skinCss = getSkinCss(event, opt);
  4897. if (url) {
  4898. html += "<a href='" + htmlEscape(url) + "'";
  4899. }else{
  4900. html += "<div";
  4901. }
  4902. html +=
  4903. " class='" + classNames.join(' ') + "'" +
  4904. " style=" +
  4905. "'" +
  4906. "position:absolute;" +
  4907. "left:" + segment.left + "px;" +
  4908. skinCss +
  4909. "'" +
  4910. ">" +
  4911. "<div class='fc-event-inner'>";
  4912. if (!event.allDay && segment.isStart) {
  4913. html +=
  4914. "<span class='fc-event-time'>" +
  4915. htmlEscape(t.getEventTimeText(event)) +
  4916. "</span>";
  4917. }
  4918. html +=
  4919. "<span class='fc-event-title'>" +
  4920. htmlEscape(event.title || '') +
  4921. "</span>" +
  4922. "</div>";
  4923. if (event.allDay && segment.isEnd && isEventResizable(event)) {
  4924. html +=
  4925. "<div class='ui-resizable-handle ui-resizable-" + (isRTL ? 'w' : 'e') + "'>" +
  4926. "&nbsp;&nbsp;&nbsp;" + // makes hit area a lot better for IE6/7
  4927. "</div>";
  4928. }
  4929. html += "</" + (url ? "a" : "div") + ">";
  4930. // TODO:
  4931. // When these elements are initially rendered, they will be briefly visibile on the screen,
  4932. // even though their widths/heights are not set.
  4933. // SOLUTION: initially set them as visibility:hidden ?
  4934. return html;
  4935. }
  4936. // Associate each segment (an object) with an element (a jQuery object),
  4937. // by setting each `segment.element`.
  4938. // Run each element through the `eventRender` filter, which allows developers to
  4939. // modify an existing element, supply a new one, or cancel rendering.
  4940. function resolveElements(segments, elements) {
  4941. for (var i=0; i<segments.length; i++) {
  4942. var segment = segments[i];
  4943. var event = segment.event;
  4944. var element = elements.eq(i);
  4945. // call the trigger with the original element
  4946. var triggerRes = trigger('eventRender', event, event, element);
  4947. if (triggerRes === false) {
  4948. // if `false`, remove the event from the DOM and don't assign it to `segment.event`
  4949. element.remove();
  4950. }
  4951. else {
  4952. if (triggerRes && triggerRes !== true) {
  4953. // the trigger returned a new element, but not `true` (which means keep the existing element)
  4954. // re-assign the important CSS dimension properties that were already assigned in `buildHTMLForSegment`
  4955. triggerRes = $(triggerRes)
  4956. .css({
  4957. position: 'absolute',
  4958. left: segment.left
  4959. });
  4960. element.replaceWith(triggerRes);
  4961. element = triggerRes;
  4962. }
  4963. segment.element = element;
  4964. }
  4965. }
  4966. }
  4967. /* Top-coordinate Methods
  4968. -------------------------------------------------------------------------------------------------*/
  4969. // Sets the "top" CSS property for each element.
  4970. // If `doRowHeights` is `true`, also sets each row's first cell to an explicit height,
  4971. // so that if elements vertically overflow, the cell expands vertically to compensate.
  4972. function setVerticals(segments, doRowHeights) {
  4973. var rowContentHeights = calculateVerticals(segments); // also sets segment.top
  4974. var rowContentElements = getRowContentElements(); // returns 1 inner div per row
  4975. var rowContentTops = [];
  4976. var i;
  4977. // Set each row's height by setting height of first inner div
  4978. if (doRowHeights) {
  4979. for (i=0; i<rowContentElements.length; i++) {
  4980. rowContentElements[i].height(rowContentHeights[i]);
  4981. }
  4982. }
  4983. // Get each row's top, relative to the views's origin.
  4984. // Important to do this after setting each row's height.
  4985. for (i=0; i<rowContentElements.length; i++) {
  4986. rowContentTops.push(
  4987. rowContentElements[i].position().top
  4988. );
  4989. }
  4990. // Set each segment element's CSS "top" property.
  4991. // Each segment object has a "top" property, which is relative to the row's top, but...
  4992. segmentElementEach(segments, function(segment, element) {
  4993. element.css(
  4994. 'top',
  4995. rowContentTops[segment.row] + segment.top // ...now, relative to views's origin
  4996. );
  4997. });
  4998. }
  4999. // Calculate the "top" coordinate for each segment, relative to the "top" of the row.
  5000. // Also, return an array that contains the "content" height for each row
  5001. // (the height displaced by the vertically stacked events in the row).
  5002. // Requires segments to have their `outerHeight` property already set.
  5003. function calculateVerticals(segments) {
  5004. var rowCnt = getRowCnt();
  5005. var colCnt = getColCnt();
  5006. var rowContentHeights = []; // content height for each row
  5007. var segmentRows = buildSegmentRows(segments); // an array of segment arrays, one for each row
  5008. var colI;
  5009. for (var rowI=0; rowI<rowCnt; rowI++) {
  5010. var segmentRow = segmentRows[rowI];
  5011. // an array of running total heights for each column.
  5012. // initialize with all zeros.
  5013. var colHeights = [];
  5014. for (colI=0; colI<colCnt; colI++) {
  5015. colHeights.push(0);
  5016. }
  5017. // loop through every segment
  5018. for (var segmentI=0; segmentI<segmentRow.length; segmentI++) {
  5019. var segment = segmentRow[segmentI];
  5020. // find the segment's top coordinate by looking at the max height
  5021. // of all the columns the segment will be in.
  5022. segment.top = arrayMax(
  5023. colHeights.slice(
  5024. segment.leftCol,
  5025. segment.rightCol + 1 // make exclusive for slice
  5026. )
  5027. );
  5028. // adjust the columns to account for the segment's height
  5029. for (colI=segment.leftCol; colI<=segment.rightCol; colI++) {
  5030. colHeights[colI] = segment.top + segment.outerHeight;
  5031. }
  5032. }
  5033. // the tallest column in the row should be the "content height"
  5034. rowContentHeights.push(arrayMax(colHeights));
  5035. }
  5036. return rowContentHeights;
  5037. }
  5038. // Build an array of segment arrays, each representing the segments that will
  5039. // be in a row of the grid, sorted by which event should be closest to the top.
  5040. function buildSegmentRows(segments) {
  5041. var rowCnt = getRowCnt();
  5042. var segmentRows = [];
  5043. var segmentI;
  5044. var segment;
  5045. var rowI;
  5046. // group segments by row
  5047. for (segmentI=0; segmentI<segments.length; segmentI++) {
  5048. segment = segments[segmentI];
  5049. rowI = segment.row;
  5050. if (segment.element) { // was rendered?
  5051. if (segmentRows[rowI]) {
  5052. // already other segments. append to array
  5053. segmentRows[rowI].push(segment);
  5054. }
  5055. else {
  5056. // first segment in row. create new array
  5057. segmentRows[rowI] = [ segment ];
  5058. }
  5059. }
  5060. }
  5061. // sort each row
  5062. for (rowI=0; rowI<rowCnt; rowI++) {
  5063. segmentRows[rowI] = sortSegmentRow(
  5064. segmentRows[rowI] || [] // guarantee an array, even if no segments
  5065. );
  5066. }
  5067. return segmentRows;
  5068. }
  5069. // Sort an array of segments according to which segment should appear closest to the top
  5070. function sortSegmentRow(segments) {
  5071. var sortedSegments = [];
  5072. // build the subrow array
  5073. var subrows = buildSegmentSubrows(segments);
  5074. // flatten it
  5075. for (var i=0; i<subrows.length; i++) {
  5076. sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array
  5077. }
  5078. return sortedSegments;
  5079. }
  5080. // Take an array of segments, which are all assumed to be in the same row,
  5081. // and sort into subrows.
  5082. function buildSegmentSubrows(segments) {
  5083. // Give preference to elements with certain criteria, so they have
  5084. // a chance to be closer to the top.
  5085. segments.sort(compareDaySegments);
  5086. var subrows = [];
  5087. for (var i=0; i<segments.length; i++) {
  5088. var segment = segments[i];
  5089. // loop through subrows, starting with the topmost, until the segment
  5090. // doesn't collide with other segments.
  5091. for (var j=0; j<subrows.length; j++) {
  5092. if (!isDaySegmentCollision(segment, subrows[j])) {
  5093. break;
  5094. }
  5095. }
  5096. // `j` now holds the desired subrow index
  5097. if (subrows[j]) {
  5098. subrows[j].push(segment);
  5099. }
  5100. else {
  5101. subrows[j] = [ segment ];
  5102. }
  5103. }
  5104. return subrows;
  5105. }
  5106. // Return an array of jQuery objects for the placeholder content containers of each row.
  5107. // The content containers don't actually contain anything, but their dimensions should match
  5108. // the events that are overlaid on top.
  5109. function getRowContentElements() {
  5110. var i;
  5111. var rowCnt = getRowCnt();
  5112. var rowDivs = [];
  5113. for (i=0; i<rowCnt; i++) {
  5114. rowDivs[i] = allDayRow(i)
  5115. .find('div.fc-day-content > div');
  5116. }
  5117. return rowDivs;
  5118. }
  5119. /* Mouse Handlers
  5120. ---------------------------------------------------------------------------------------------------*/
  5121. // TODO: better documentation!
  5122. function attachHandlers(segments, modifiedEventId) {
  5123. var segmentContainer = getDaySegmentContainer();
  5124. segmentElementEach(segments, function(segment, element, i) {
  5125. var event = segment.event;
  5126. if (event._id === modifiedEventId) {
  5127. bindDaySeg(event, element, segment);
  5128. }else{
  5129. element[0]._fci = i; // for lazySegBind
  5130. }
  5131. });
  5132. lazySegBind(segmentContainer, segments, bindDaySeg);
  5133. }
  5134. function bindDaySeg(event, eventElement, segment) {
  5135. if (isEventDraggable(event)) {
  5136. t.draggableDayEvent(event, eventElement, segment); // use `t` so subclasses can override
  5137. }
  5138. if (
  5139. event.allDay &&
  5140. segment.isEnd && // only allow resizing on the final segment for an event
  5141. isEventResizable(event)
  5142. ) {
  5143. t.resizableDayEvent(event, eventElement, segment); // use `t` so subclasses can override
  5144. }
  5145. // attach all other handlers.
  5146. // needs to be after, because resizableDayEvent might stopImmediatePropagation on click
  5147. eventElementHandlers(event, eventElement);
  5148. }
  5149. function draggableDayEvent(event, eventElement) {
  5150. var hoverListener = getHoverListener();
  5151. var dayDelta;
  5152. var eventStart;
  5153. eventElement.draggable({
  5154. delay: 50,
  5155. opacity: opt('dragOpacity'),
  5156. revertDuration: opt('dragRevertDuration'),
  5157. start: function(ev, ui) {
  5158. trigger('eventDragStart', eventElement[0], event, ev, ui);
  5159. hideEvents(event, eventElement);
  5160. hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
  5161. eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta);
  5162. clearOverlays();
  5163. if (cell) {
  5164. var origCellDate = cellToDate(origCell);
  5165. var cellDate = cellToDate(cell);
  5166. dayDelta = cellDate.diff(origCellDate, 'days');
  5167. eventStart = event.start.clone().add(dayDelta, 'days');
  5168. renderDayOverlay(
  5169. eventStart,
  5170. getEventEnd(event).add(dayDelta, 'days')
  5171. );
  5172. }
  5173. else {
  5174. dayDelta = 0;
  5175. }
  5176. }, ev, 'drag');
  5177. },
  5178. stop: function(ev, ui) {
  5179. hoverListener.stop();
  5180. clearOverlays();
  5181. trigger('eventDragStop', eventElement[0], event, ev, ui);
  5182. if (dayDelta) {
  5183. eventDrop(
  5184. eventElement[0],
  5185. event,
  5186. eventStart,
  5187. ev,
  5188. ui
  5189. );
  5190. }
  5191. else {
  5192. eventElement.css('filter', ''); // clear IE opacity side-effects
  5193. showEvents(event, eventElement);
  5194. }
  5195. }
  5196. });
  5197. }
  5198. function resizableDayEvent(event, element, segment) {
  5199. var isRTL = opt('isRTL');
  5200. var direction = isRTL ? 'w' : 'e';
  5201. var handle = element.find('.ui-resizable-' + direction); // TODO: stop using this class because we aren't using jqui for this
  5202. var isResizing = false;
  5203. // TODO: look into using jquery-ui mouse widget for this stuff
  5204. disableTextSelection(element); // prevent native <a> selection for IE
  5205. element
  5206. .mousedown(function(ev) { // prevent native <a> selection for others
  5207. ev.preventDefault();
  5208. })
  5209. .click(function(ev) {
  5210. if (isResizing) {
  5211. ev.preventDefault(); // prevent link from being visited (only method that worked in IE6)
  5212. ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called
  5213. // (eventElementHandlers needs to be bound after resizableDayEvent)
  5214. }
  5215. });
  5216. handle.mousedown(function(ev) {
  5217. if (ev.which != 1) {
  5218. return; // needs to be left mouse button
  5219. }
  5220. isResizing = true;
  5221. var hoverListener = getHoverListener();
  5222. var elementTop = element.css('top');
  5223. var dayDelta;
  5224. var eventEnd;
  5225. var helpers;
  5226. var eventCopy = $.extend({}, event);
  5227. var minCellOffset = dayOffsetToCellOffset(dateToDayOffset(event.start));
  5228. clearSelection();
  5229. $('body')
  5230. .css('cursor', direction + '-resize')
  5231. .one('mouseup', mouseup);
  5232. trigger('eventResizeStart', element[0], event, ev, {}); // {} is dummy jqui event
  5233. hoverListener.start(function(cell, origCell) {
  5234. if (cell) {
  5235. var origCellOffset = cellToCellOffset(origCell);
  5236. var cellOffset = cellToCellOffset(cell);
  5237. // don't let resizing move earlier than start date cell
  5238. cellOffset = Math.max(cellOffset, minCellOffset);
  5239. dayDelta =
  5240. cellOffsetToDayOffset(cellOffset) -
  5241. cellOffsetToDayOffset(origCellOffset);
  5242. eventEnd = getEventEnd(event).add(dayDelta, 'days'); // assumed to already have a stripped time
  5243. if (dayDelta) {
  5244. eventCopy.end = eventEnd;
  5245. var oldHelpers = helpers;
  5246. helpers = renderTempDayEvent(eventCopy, segment.row, elementTop);
  5247. helpers = $(helpers); // turn array into a jQuery object
  5248. helpers.find('*').css('cursor', direction + '-resize');
  5249. if (oldHelpers) {
  5250. oldHelpers.remove();
  5251. }
  5252. hideEvents(event);
  5253. }
  5254. else {
  5255. if (helpers) {
  5256. showEvents(event);
  5257. helpers.remove();
  5258. helpers = null;
  5259. }
  5260. }
  5261. clearOverlays();
  5262. renderDayOverlay( // coordinate grid already rebuilt with hoverListener.start()
  5263. event.start,
  5264. eventEnd
  5265. // TODO: instead of calling renderDayOverlay() with dates,
  5266. // call _renderDayOverlay (or whatever) with cell offsets.
  5267. );
  5268. }
  5269. }, ev);
  5270. function mouseup(ev) {
  5271. trigger('eventResizeStop', element[0], event, ev, {}); // {} is dummy jqui event
  5272. $('body').css('cursor', '');
  5273. hoverListener.stop();
  5274. clearOverlays();
  5275. if (dayDelta) {
  5276. eventResize(
  5277. element[0],
  5278. event,
  5279. eventEnd,
  5280. ev,
  5281. {} // dummy jqui event
  5282. );
  5283. // event redraw will clear helpers
  5284. }
  5285. // otherwise, the drag handler already restored the old events
  5286. setTimeout(function() { // make this happen after the element's click event
  5287. isResizing = false;
  5288. },0);
  5289. }
  5290. });
  5291. }
  5292. }
  5293. /* Generalized Segment Utilities
  5294. -------------------------------------------------------------------------------------------------*/
  5295. function isDaySegmentCollision(segment, otherSegments) {
  5296. for (var i=0; i<otherSegments.length; i++) {
  5297. var otherSegment = otherSegments[i];
  5298. if (
  5299. otherSegment.leftCol <= segment.rightCol &&
  5300. otherSegment.rightCol >= segment.leftCol
  5301. ) {
  5302. return true;
  5303. }
  5304. }
  5305. return false;
  5306. }
  5307. function segmentElementEach(segments, callback) { // TODO: use in AgendaView?
  5308. for (var i=0; i<segments.length; i++) {
  5309. var segment = segments[i];
  5310. var element = segment.element;
  5311. if (element) {
  5312. callback(segment, element, i);
  5313. }
  5314. }
  5315. }
  5316. // A cmp function for determining which segments should appear higher up
  5317. function compareDaySegments(a, b) {
  5318. return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first
  5319. b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1)
  5320. a.event.start - b.event.start || // if a tie, sort by event start date
  5321. (a.event.title || '').localeCompare(b.event.title); // if a tie, sort by event title
  5322. }
  5323. ;;
  5324. //BUG: unselect needs to be triggered when events are dragged+dropped
  5325. function SelectionManager() {
  5326. var t = this;
  5327. // exports
  5328. t.select = select;
  5329. t.unselect = unselect;
  5330. t.reportSelection = reportSelection;
  5331. t.daySelectionMousedown = daySelectionMousedown;
  5332. t.selectionManagerDestroy = destroy;
  5333. // imports
  5334. var calendar = t.calendar;
  5335. var opt = t.opt;
  5336. var trigger = t.trigger;
  5337. var defaultSelectionEnd = t.defaultSelectionEnd;
  5338. var renderSelection = t.renderSelection;
  5339. var clearSelection = t.clearSelection;
  5340. // locals
  5341. var selected = false;
  5342. // unselectAuto
  5343. if (opt('selectable') && opt('unselectAuto')) {
  5344. $(document).on('mousedown', documentMousedown);
  5345. }
  5346. function documentMousedown(ev) {
  5347. var ignore = opt('unselectCancel');
  5348. if (ignore) {
  5349. if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match
  5350. return;
  5351. }
  5352. }
  5353. unselect(ev);
  5354. }
  5355. function select(start, end) {
  5356. unselect();
  5357. start = calendar.moment(start);
  5358. if (end) {
  5359. end = calendar.moment(end);
  5360. }
  5361. else {
  5362. end = defaultSelectionEnd(start);
  5363. }
  5364. renderSelection(start, end);
  5365. reportSelection(start, end);
  5366. }
  5367. // TODO: better date normalization. see notes in automated test
  5368. function unselect(ev) {
  5369. if (selected) {
  5370. selected = false;
  5371. clearSelection();
  5372. trigger('unselect', null, ev);
  5373. }
  5374. }
  5375. function reportSelection(start, end, ev) {
  5376. selected = true;
  5377. trigger('select', null, start, end, ev);
  5378. }
  5379. function daySelectionMousedown(ev) { // not really a generic manager method, oh well
  5380. var cellToDate = t.cellToDate;
  5381. var getIsCellAllDay = t.getIsCellAllDay;
  5382. var hoverListener = t.getHoverListener();
  5383. var reportDayClick = t.reportDayClick; // this is hacky and sort of weird
  5384. if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button
  5385. unselect(ev);
  5386. var dates;
  5387. hoverListener.start(function(cell, origCell) { // TODO: maybe put cellToDate/getIsCellAllDay info in cell
  5388. clearSelection();
  5389. if (cell && getIsCellAllDay(cell)) {
  5390. dates = [ cellToDate(origCell), cellToDate(cell) ].sort(dateCompare);
  5391. renderSelection(
  5392. dates[0],
  5393. dates[1].clone().add(1, 'days') // make exclusive
  5394. );
  5395. }else{
  5396. dates = null;
  5397. }
  5398. }, ev);
  5399. $(document).one('mouseup', function(ev) {
  5400. hoverListener.stop();
  5401. if (dates) {
  5402. if (+dates[0] == +dates[1]) {
  5403. reportDayClick(dates[0], ev);
  5404. }
  5405. reportSelection(
  5406. dates[0],
  5407. dates[1].clone().add(1, 'days'), // make exclusive
  5408. ev
  5409. );
  5410. }
  5411. });
  5412. }
  5413. }
  5414. function destroy() {
  5415. $(document).off('mousedown', documentMousedown);
  5416. }
  5417. }
  5418. ;;
  5419. function OverlayManager() {
  5420. var t = this;
  5421. // exports
  5422. t.renderOverlay = renderOverlay;
  5423. t.clearOverlays = clearOverlays;
  5424. // locals
  5425. var usedOverlays = [];
  5426. var unusedOverlays = [];
  5427. function renderOverlay(rect, parent) {
  5428. var e = unusedOverlays.shift();
  5429. if (!e) {
  5430. e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>");
  5431. }
  5432. if (e[0].parentNode != parent[0]) {
  5433. e.appendTo(parent);
  5434. }
  5435. usedOverlays.push(e.css(rect).show());
  5436. return e;
  5437. }
  5438. function clearOverlays() {
  5439. var e;
  5440. while ((e = usedOverlays.shift())) {
  5441. unusedOverlays.push(e.hide().unbind());
  5442. }
  5443. }
  5444. }
  5445. ;;
  5446. function CoordinateGrid(buildFunc) {
  5447. var t = this;
  5448. var rows;
  5449. var cols;
  5450. t.build = function() {
  5451. rows = [];
  5452. cols = [];
  5453. buildFunc(rows, cols);
  5454. };
  5455. t.cell = function(x, y) {
  5456. var rowCnt = rows.length;
  5457. var colCnt = cols.length;
  5458. var i, r=-1, c=-1;
  5459. for (i=0; i<rowCnt; i++) {
  5460. if (y >= rows[i][0] && y < rows[i][1]) {
  5461. r = i;
  5462. break;
  5463. }
  5464. }
  5465. for (i=0; i<colCnt; i++) {
  5466. if (x >= cols[i][0] && x < cols[i][1]) {
  5467. c = i;
  5468. break;
  5469. }
  5470. }
  5471. return (r>=0 && c>=0) ? { row: r, col: c } : null;
  5472. };
  5473. t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive
  5474. var origin = originElement.offset();
  5475. return {
  5476. top: rows[row0][0] - origin.top,
  5477. left: cols[col0][0] - origin.left,
  5478. width: cols[col1][1] - cols[col0][0],
  5479. height: rows[row1][1] - rows[row0][0]
  5480. };
  5481. };
  5482. }
  5483. ;;
  5484. function HoverListener(coordinateGrid) {
  5485. var t = this;
  5486. var bindType;
  5487. var change;
  5488. var firstCell;
  5489. var cell;
  5490. t.start = function(_change, ev, _bindType) {
  5491. change = _change;
  5492. firstCell = cell = null;
  5493. coordinateGrid.build();
  5494. mouse(ev);
  5495. bindType = _bindType || 'mousemove';
  5496. $(document).bind(bindType, mouse);
  5497. };
  5498. function mouse(ev) {
  5499. _fixUIEvent(ev); // see below
  5500. var newCell = coordinateGrid.cell(ev.pageX, ev.pageY);
  5501. if (
  5502. Boolean(newCell) !== Boolean(cell) ||
  5503. newCell && (newCell.row != cell.row || newCell.col != cell.col)
  5504. ) {
  5505. if (newCell) {
  5506. if (!firstCell) {
  5507. firstCell = newCell;
  5508. }
  5509. change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col);
  5510. }else{
  5511. change(newCell, firstCell);
  5512. }
  5513. cell = newCell;
  5514. }
  5515. }
  5516. t.stop = function() {
  5517. $(document).unbind(bindType, mouse);
  5518. return cell;
  5519. };
  5520. }
  5521. // this fix was only necessary for jQuery UI 1.8.16 (and jQuery 1.7 or 1.7.1)
  5522. // upgrading to jQuery UI 1.8.17 (and using either jQuery 1.7 or 1.7.1) fixed the problem
  5523. // but keep this in here for 1.8.16 users
  5524. // and maybe remove it down the line
  5525. function _fixUIEvent(event) { // for issue 1168
  5526. if (event.pageX === undefined) {
  5527. event.pageX = event.originalEvent.pageX;
  5528. event.pageY = event.originalEvent.pageY;
  5529. }
  5530. }
  5531. ;;
  5532. function HorizontalPositionCache(getElement) {
  5533. var t = this,
  5534. elements = {},
  5535. lefts = {},
  5536. rights = {};
  5537. function e(i) {
  5538. return (elements[i] = (elements[i] || getElement(i)));
  5539. }
  5540. t.left = function(i) {
  5541. return (lefts[i] = (lefts[i] === undefined ? e(i).position().left : lefts[i]));
  5542. };
  5543. t.right = function(i) {
  5544. return (rights[i] = (rights[i] === undefined ? t.left(i) + e(i).width() : rights[i]));
  5545. };
  5546. t.clear = function() {
  5547. elements = {};
  5548. lefts = {};
  5549. rights = {};
  5550. };
  5551. }
  5552. ;;
  5553. });