fullcalendar.js 148 KB

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