timeline.js 169 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256
  1. /**
  2. * @file timeline.js
  3. *
  4. * @brief
  5. * The Timeline is an interactive visualization chart to visualize events in
  6. * time, having a start and end date.
  7. * You can freely move and zoom in the timeline by dragging
  8. * and scrolling in the Timeline. Items are optionally dragable. The time
  9. * scale on the axis is adjusted automatically, and supports scales ranging
  10. * from milliseconds to years.
  11. *
  12. * Timeline is part of the CHAP Links library.
  13. *
  14. * Timeline is tested on Firefox 3.6, Safari 5.0, Chrome 6.0, Opera 10.6, and
  15. * Internet Explorer 6+.
  16. *
  17. * @license
  18. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  19. * use this file except in compliance with the License. You may obtain a copy
  20. * of the License at
  21. *
  22. * http://www.apache.org/licenses/LICENSE-2.0
  23. *
  24. * Unless required by applicable law or agreed to in writing, software
  25. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  26. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  27. * License for the specific language governing permissions and limitations under
  28. * the License.
  29. *
  30. * Copyright (c) 2011-2012 Almende B.V.
  31. *
  32. * @author Jos de Jong, <jos@almende.org>
  33. * @date 2012-06-15
  34. * @version 2.1.2
  35. */
  36. /*
  37. * TODO
  38. *
  39. * Add zooming with pinching on Android
  40. *
  41. * Bug: when an item contains a javascript onclick or a link, this does not work
  42. * when the item is not selected (when the item is being selected,
  43. * it is redrawn, which cancels any onclick or link action)
  44. * Bug: when an item contains an image without size, or a css max-width, it is not sized correctly
  45. * Bug: neglect items when they have no valid start/end, instead of throwing an error
  46. * Bug: Pinching on ipad does not work very well, sometimes the page will zoom when pinching vertically
  47. * Bug: cannot set max width for an item, like div.timeline-event-content {white-space: normal; max-width: 100px;}
  48. * Bug on IE in Quirks mode. When you have groups, and delete an item, the groups become invisible
  49. */
  50. /**
  51. * Declare a unique namespace for CHAP's Common Hybrid Visualisation Library,
  52. * "links"
  53. */
  54. if (typeof links === 'undefined') {
  55. links = {};
  56. // important: do not use var, as "var links = {};" will overwrite
  57. // the existing links variable value with undefined in IE8, IE7.
  58. }
  59. /**
  60. * Ensure the variable google exists
  61. */
  62. if (typeof google === 'undefined') {
  63. google = undefined;
  64. // important: do not use var, as "var google = undefined;" will overwrite
  65. // the existing google variable value with undefined in IE8, IE7.
  66. }
  67. /**
  68. * @constructor links.Timeline
  69. * The timeline is a visualization chart to visualize events in time.
  70. *
  71. * The timeline is developed in javascript as a Google Visualization Chart.
  72. *
  73. * @param {Element} container The DOM element in which the Timeline will
  74. * be created. Normally a div element.
  75. */
  76. links.Timeline = function(container) {
  77. // create variables and set default values
  78. this.dom = {};
  79. this.conversion = {};
  80. this.eventParams = {}; // stores parameters for mouse events
  81. this.groups = [];
  82. this.groupIndexes = {};
  83. this.items = [];
  84. this.visibleItems = 0;
  85. this.selection = undefined; // stores index and item which is currently selected
  86. this.listeners = {}; // event listener callbacks
  87. // Initialize sizes.
  88. // Needed for IE (which gives an error when you try to set an undefined
  89. // value in a style)
  90. this.size = {
  91. 'actualHeight': 0,
  92. 'axis': {
  93. 'characterMajorHeight': 0,
  94. 'characterMajorWidth': 0,
  95. 'characterMinorHeight': 0,
  96. 'characterMinorWidth': 0,
  97. 'height': 0,
  98. 'labelMajorTop': 0,
  99. 'labelMinorTop': 0,
  100. 'line': 0,
  101. 'lineMajorWidth': 0,
  102. 'lineMinorHeight': 0,
  103. 'lineMinorTop': 0,
  104. 'lineMinorWidth': 0,
  105. 'top': 0
  106. },
  107. 'contentHeight': 0,
  108. 'contentLeft': 0,
  109. 'contentWidth': 0,
  110. 'dataChanged': false,
  111. 'frameHeight': 0,
  112. 'frameWidth': 0,
  113. 'groupsLeft': 0,
  114. 'groupsWidth': 0,
  115. 'items': {
  116. 'top': 0
  117. }
  118. };
  119. this.dom.container = container;
  120. this.options = {
  121. 'width': "100%",
  122. 'height': "auto",
  123. 'minHeight': 0, // minimal height in pixels
  124. 'autoHeight': true,
  125. 'eventMargin': 10, // minimal margin between events
  126. 'eventMarginAxis': 20, // minimal margin beteen events and the axis
  127. 'dragAreaWidth': 10, // pixels
  128. 'min': undefined,
  129. 'max': undefined,
  130. 'intervalMin': 10, // milliseconds
  131. 'intervalMax': 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  132. 'moveable': true,
  133. 'zoomable': true,
  134. 'selectable': true,
  135. 'editable': false,
  136. 'snapEvents': true,
  137. 'groupChangeable': true,
  138. 'mousewheel': "zoom",
  139. 'dblclick':"edit",
  140. 'showCurrentTime': true, // show a red bar displaying the current time
  141. 'showCustomTime': false, // show a blue, draggable bar displaying a custom time
  142. 'showMajorLabels': true,
  143. 'showNavigation': false,
  144. 'showButtonAdd': true,
  145. 'groupsOnRight': false,
  146. 'axisOnTop': false,
  147. 'stackEvents': true,
  148. 'animate': true,
  149. 'animateZoom': true,
  150. 'style': 'box',
  151. 'language':'en'
  152. };
  153. this.clientTimeOffset = 0; // difference between client time and the time
  154. // set via Timeline.setCurrentTime()
  155. var dom = this.dom;
  156. // remove all elements from the container element.
  157. while (dom.container.hasChildNodes()) {
  158. dom.container.removeChild(dom.container.firstChild);
  159. }
  160. // create a step for drawing the axis
  161. this.step = new links.Timeline.StepDate();
  162. // initialize data
  163. this.data = [];
  164. this.firstDraw = true;
  165. // date interval must be initialized
  166. this.setVisibleChartRange(undefined, undefined, false);
  167. // create all DOM elements
  168. this.redrawFrame();
  169. // Internet Explorer does not support Array.indexof,
  170. // so we define it here in that case
  171. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  172. if(!Array.prototype.indexOf) {
  173. Array.prototype.indexOf = function(obj){
  174. for(var i = 0; i < this.length; i++){
  175. if(this[i] == obj){
  176. return i;
  177. }
  178. }
  179. return -1;
  180. }
  181. }
  182. // fire the ready event
  183. this.trigger('ready');
  184. };
  185. /**
  186. * Main drawing logic. This is the function that needs to be called
  187. * in the html page, to draw the timeline.
  188. *
  189. * A data table with the events must be provided, and an options table.
  190. *
  191. * @param {google.visualization.DataTable} data
  192. * The data containing the events for the timeline.
  193. * Object DataTable is defined in
  194. * google.visualization.DataTable
  195. * @param {Object} options A name/value map containing settings for the
  196. * timeline. Optional.
  197. */
  198. links.Timeline.prototype.draw = function(data, options) {
  199. this.setOptions(options);
  200. // read the data
  201. this.setData(data);
  202. // set timer range. this will also redraw the timeline
  203. if (options && options.start && options.end) {
  204. this.setVisibleChartRange(options.start, options.end);
  205. }
  206. else if (this.firstDraw) {
  207. this.setVisibleChartRangeAuto();
  208. }
  209. this.firstDraw = false;
  210. };
  211. /**
  212. * Set options for the timeline.
  213. * Timeline must be redrawn afterwards
  214. * @param {Object} options A name/value map containing settings for the
  215. * timeline. Optional.
  216. */
  217. links.Timeline.prototype.setOptions = function(options) {
  218. if (options) {
  219. // retrieve parameter values
  220. for (var i in options) {
  221. if (options.hasOwnProperty(i)) {
  222. this.options[i] = options[i];
  223. }
  224. }
  225. }
  226. // validate options
  227. this.options.autoHeight = (this.options.height === "auto");
  228. };
  229. links.Timeline.prototype.getOptions = function(){
  230. return this.options;
  231. };
  232. /**
  233. * Set data for the timeline
  234. * @param {google.visualization.DataTable | array} data
  235. */
  236. links.Timeline.prototype.setData = function(data) {
  237. // unselect any previously selected item
  238. this.unselectItem();
  239. if (!data) {
  240. data = [];
  241. }
  242. this.items = [];
  243. this.data = data;
  244. var items = this.items;
  245. var options = this.options;
  246. // create groups from the data
  247. this.setGroups(data);
  248. if (google && google.visualization &&
  249. data instanceof google.visualization.DataTable) {
  250. // read DataTable
  251. var hasGroups = (data.getNumberOfColumns() > 3);
  252. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  253. items.push(this.createItem({
  254. 'start': data.getValue(row, 0),
  255. 'end': data.getValue(row, 1),
  256. 'content': data.getValue(row, 2),
  257. 'group': (hasGroups ? data.getValue(row, 3) : undefined)
  258. }));
  259. }
  260. }
  261. else if (links.Timeline.isArray(data)) {
  262. // read JSON array
  263. for (var row = 0, rows = data.length; row < rows; row++) {
  264. var itemData = data[row]
  265. var item = this.createItem(itemData);
  266. items.push(item);
  267. }
  268. }
  269. else {
  270. throw "Unknown data type. DataTable or Array expected.";
  271. }
  272. // set a flag to force the recalcSize method to recalculate the
  273. // heights and widths of the events
  274. this.size.dataChanged = true;
  275. this.redrawFrame(); // create the items for the new data
  276. this.recalcSize(); // position the items
  277. this.repositionItems();
  278. this.stackEvents(false);
  279. this.redrawFrame(); // redraw the items on the final positions
  280. this.size.dataChanged = false;
  281. };
  282. /**
  283. * Set the groups available in the given dataset
  284. * @param {google.visualization.DataTable | array} data
  285. */
  286. links.Timeline.prototype.setGroups = function (data) {
  287. this.deleteGroups();
  288. var groups = this.groups;
  289. var groupIndexes = this.groupIndexes;
  290. if (google && google.visualization &&
  291. data instanceof google.visualization.DataTable) {
  292. // get groups from DataTable
  293. var hasGroups = (data.getNumberOfColumns() > 3);
  294. if (hasGroups) {
  295. var groupNames = data.getDistinctValues(3);
  296. for (var i = 0, iMax = groupNames.length; i < iMax; i++) {
  297. this.addGroup(groupNames[i]);
  298. }
  299. }
  300. }
  301. else if (links.Timeline.isArray(data)){
  302. // get groups from JSON Array
  303. for (var i = 0, iMax = data.length; i < iMax; i++) {
  304. var row = data[i],
  305. group = row.group;
  306. if (group) {
  307. this.addGroup(group);
  308. }
  309. }
  310. }
  311. else {
  312. throw 'Unknown data type. DataTable or Array expected.';
  313. }
  314. };
  315. /**
  316. * Return the original data table.
  317. * @return {google.visualization.DataTable | Array} data
  318. */
  319. links.Timeline.prototype.getData = function () {
  320. return this.data;
  321. };
  322. /**
  323. * Update the original data with changed start, end or group.
  324. *
  325. * @param {Number} index
  326. * @param {Object} values An object containing some of the following parameters:
  327. * {Date} start,
  328. * {Date} end,
  329. * {String} content,
  330. * {String} group
  331. */
  332. links.Timeline.prototype.updateData = function (index, values) {
  333. var data = this.data;
  334. if (google && google.visualization &&
  335. data instanceof google.visualization.DataTable) {
  336. // update the original google DataTable
  337. var missingRows = (index + 1) - data.getNumberOfRows();
  338. if (missingRows > 0) {
  339. data.addRows(missingRows);
  340. }
  341. if (values.start) {
  342. data.setValue(index, 0, values.start);
  343. }
  344. if (values.end) {
  345. data.setValue(index, 1, values.end);
  346. }
  347. if (values.content) {
  348. data.setValue(index, 2, values.content);
  349. }
  350. if (values.group && data.getNumberOfColumns() > 3) {
  351. // TODO: append a column when needed?
  352. data.setValue(index, 3, values.group);
  353. }
  354. }
  355. else if (links.Timeline.isArray(data)) {
  356. // update the original JSON table
  357. var row = data[index];
  358. if (row == undefined) {
  359. row = {};
  360. data[index] = row;
  361. }
  362. if (values.start) {
  363. row.start = values.start;
  364. }
  365. if (values.end) {
  366. row.end = values.end;
  367. }
  368. if (values.content) {
  369. row.content = values.content;
  370. }
  371. if (values.group) {
  372. row.group = values.group;
  373. }
  374. }
  375. else {
  376. throw "Cannot update data, unknown type of data";
  377. }
  378. };
  379. /**
  380. * Find the item index from a given HTML element
  381. * If no item index is found, undefined is returned
  382. * @param {Element} element
  383. * @return {Number} index
  384. */
  385. links.Timeline.prototype.getItemIndex = function(element) {
  386. var e = element,
  387. dom = this.dom,
  388. items = this.items,
  389. index = undefined;
  390. // try to find the frame where the items are located in
  391. while (e.parentNode && e.parentNode !== dom.items.frame) {
  392. e = e.parentNode;
  393. }
  394. if (e.parentNode === dom.items.frame) {
  395. // yes! we have found the parent element of all items
  396. // retrieve its id from the array with items
  397. for (var i = 0, iMax = items.length; i < iMax; i++) {
  398. if (items[i].dom === e) {
  399. index = i;
  400. break;
  401. }
  402. }
  403. }
  404. return index;
  405. };
  406. /**
  407. * Set a new size for the timeline
  408. * @param {string} width Width in pixels or percentage (for example "800px"
  409. * or "50%")
  410. * @param {string} height Height in pixels or percentage (for example "400px"
  411. * or "30%")
  412. */
  413. links.Timeline.prototype.setSize = function(width, height) {
  414. if (width) {
  415. this.options.width = width;
  416. this.dom.frame.style.width = width;
  417. }
  418. if (height) {
  419. this.options.height = height;
  420. this.options.autoHeight = (this.options.height === "auto");
  421. if (height !== "auto" ) {
  422. this.dom.frame.style.height = height;
  423. }
  424. }
  425. this.recalcSize();
  426. this.repositionItems();
  427. this.stackEvents(false);
  428. this.redrawFrame();
  429. };
  430. /**
  431. * Set a new value for the visible range int the timeline.
  432. * Set start to null to include everything from the earliest date to end.
  433. * Set end to null to include everything from start to the last date.
  434. * Example usage:
  435. * myTimeline.setVisibleChartRange(new Date("2010-08-22"),
  436. * new Date("2010-09-13"));
  437. * @param {Date} start The start date for the timeline. optional
  438. * @param {Date} end The end date for the timeline. optional
  439. * @param {boolean} redraw Optional. If true (default) the Timeline is
  440. * directly redrawn
  441. */
  442. links.Timeline.prototype.setVisibleChartRange = function(start, end, redraw) {
  443. if (start == undefined) {
  444. // default of 3 days ago
  445. start = new Date();
  446. start.setDate(start.getDate() - 3);
  447. }
  448. if (end == undefined) {
  449. // default of 4 days ahead
  450. end = new Date();
  451. end.setDate(start.getDate() + 4);
  452. }
  453. // prevent start Date <= end Date
  454. if (end.valueOf() <= start.valueOf()) {
  455. end = new Date(start);
  456. end.setDate(end.getDate() + 7);
  457. }
  458. // limit to the allowed range (dont let this do by applyRange,
  459. // because that method will try to maintain the interval (end-start)
  460. var min = this.options.min ? this.options.min.valueOf() : undefined;
  461. if (min && start.valueOf() < min) {
  462. start = new Date(min);
  463. }
  464. var max = this.options.max ? this.options.max.valueOf() : undefined;
  465. if (max && end.valueOf() > max) {
  466. end = new Date(max);
  467. }
  468. this.applyRange(start, end);
  469. if (redraw == undefined || redraw == true) {
  470. this.recalcSize();
  471. this.repositionItems();
  472. this.stackEvents(false);
  473. this.redrawFrame();
  474. }
  475. else {
  476. this.recalcConversion();
  477. }
  478. };
  479. /**
  480. * Change the visible chart range such that all items become visible
  481. */
  482. links.Timeline.prototype.setVisibleChartRangeAuto = function() {
  483. var items = this.items,
  484. startMin = undefined, // long value of a data
  485. endMax = undefined; // long value of a data
  486. // find earliest start date from the data
  487. for (var i = 0, iMax = items.length; i < iMax; i++) {
  488. var item = items[i],
  489. start = item.start ? item.start.valueOf() : undefined,
  490. end = item.end ? item.end.valueOf() : start;
  491. if (startMin !== undefined && start !== undefined) {
  492. startMin = Math.min(startMin, start);
  493. }
  494. else {
  495. startMin = start;
  496. }
  497. if (endMax !== undefined && end !== undefined) {
  498. endMax = Math.max(endMax, end);
  499. }
  500. else {
  501. endMax = end;
  502. }
  503. }
  504. if (startMin !== undefined && endMax !== undefined) {
  505. // zoom out 5% such that you have a little white space on the left and right
  506. var center = (endMax + startMin) / 2,
  507. diff = (endMax - startMin);
  508. startMin = startMin - diff * 0.05;
  509. endMax = endMax + diff * 0.05;
  510. // adjust the start and end date
  511. this.setVisibleChartRange(new Date(startMin), new Date(endMax));
  512. }
  513. else {
  514. this.setVisibleChartRange(undefined, undefined);
  515. }
  516. };
  517. /**
  518. * Adjust the visible range such that the current time is located in the center
  519. * of the timeline
  520. */
  521. links.Timeline.prototype.setVisibleChartRangeNow = function() {
  522. var now = new Date();
  523. var diff = (this.end.getTime() - this.start.getTime());
  524. var startNew = new Date(now.getTime() - diff/2);
  525. var endNew = new Date(startNew.getTime() + diff);
  526. this.setVisibleChartRange(startNew, endNew);
  527. };
  528. /**
  529. * Retrieve the current visible range in the timeline.
  530. * @return {Object} An object with start and end properties
  531. */
  532. links.Timeline.prototype.getVisibleChartRange = function() {
  533. var range = {
  534. 'start': new Date(this.start),
  535. 'end': new Date(this.end)
  536. };
  537. return range;
  538. };
  539. /**
  540. * Redraw the timeline. This needs to be executed after the start and/or
  541. * end time are changed, or when data is added or removed dynamically.
  542. */
  543. links.Timeline.prototype.redrawFrame = function() {
  544. var dom = this.dom,
  545. options = this.options,
  546. size = this.size;
  547. if (!dom.frame) {
  548. // the surrounding main frame
  549. dom.frame = document.createElement("DIV");
  550. dom.frame.className = "timeline-frame";
  551. dom.frame.style.position = "relative";
  552. dom.frame.style.overflow = "hidden";
  553. dom.container.appendChild(dom.frame);
  554. }
  555. if (options.autoHeight) {
  556. dom.frame.style.height = size.frameHeight + "px";
  557. }
  558. else {
  559. dom.frame.style.height = options.height || "100%";
  560. }
  561. dom.frame.style.width = options.width || "100%";
  562. this.redrawContent();
  563. this.redrawGroups();
  564. this.redrawCurrentTime();
  565. this.redrawCustomTime();
  566. this.redrawNavigation();
  567. };
  568. /**
  569. * Redraw the content of the timeline: the axis and the items
  570. */
  571. links.Timeline.prototype.redrawContent = function() {
  572. var dom = this.dom,
  573. size = this.size;
  574. if (!dom.content) {
  575. // create content box where the axis and canvas will
  576. dom.content = document.createElement("DIV");
  577. //this.frame.className = "timeline-frame";
  578. dom.content.style.position = "relative";
  579. dom.content.style.overflow = "hidden";
  580. dom.frame.appendChild(dom.content);
  581. var timelines = document.createElement("DIV");
  582. timelines.style.position = "absolute";
  583. timelines.style.left = "0px";
  584. timelines.style.top = "0px";
  585. timelines.style.height = "100%";
  586. timelines.style.width = "0px";
  587. dom.content.appendChild(timelines);
  588. dom.contentTimelines = timelines;
  589. var params = this.eventParams,
  590. me = this;
  591. if (!params.onMouseDown) {
  592. params.onMouseDown = function (event) {me.onMouseDown(event);};
  593. links.Timeline.addEventListener(dom.content, "mousedown", params.onMouseDown);
  594. }
  595. if (!params.onTouchStart) {
  596. params.onTouchStart = function (event) {me.onTouchStart(event);};
  597. links.Timeline.addEventListener(dom.content, "touchstart", params.onTouchStart);
  598. }
  599. if (!params.onMouseWheel) {
  600. params.onMouseWheel = function (event) {me.onMouseWheel(event);};
  601. links.Timeline.addEventListener(dom.content, "mousewheel", params.onMouseWheel);
  602. }
  603. if (!params.onDblClick) {
  604. params.onDblClick = function (event) {me.onDblClick(event);};
  605. links.Timeline.addEventListener(dom.content, "dblclick", params.onDblClick);
  606. }
  607. }
  608. dom.content.style.left = size.contentLeft + "px";
  609. dom.content.style.top = "0px";
  610. dom.content.style.width = size.contentWidth + "px";
  611. dom.content.style.height = size.frameHeight + "px";
  612. this.redrawAxis();
  613. this.redrawItems();
  614. this.redrawDeleteButton();
  615. this.redrawDragAreas();
  616. };
  617. /**
  618. * Redraw the timeline axis with minor and major labels
  619. */
  620. links.Timeline.prototype.redrawAxis = function() {
  621. var dom = this.dom,
  622. options = this.options,
  623. size = this.size,
  624. step = this.step;
  625. var axis = dom.axis;
  626. if (!axis) {
  627. axis = {};
  628. dom.axis = axis;
  629. }
  630. if (size.axis.properties === undefined) {
  631. size.axis.properties = {};
  632. }
  633. if (axis.minorTexts === undefined) {
  634. axis.minorTexts = [];
  635. }
  636. if (axis.minorLines === undefined) {
  637. axis.minorLines = [];
  638. }
  639. if (axis.majorTexts === undefined) {
  640. axis.majorTexts = [];
  641. }
  642. if (axis.majorLines === undefined) {
  643. axis.majorLines = [];
  644. }
  645. if (!axis.frame) {
  646. axis.frame = document.createElement("DIV");
  647. axis.frame.style.position = "absolute";
  648. axis.frame.style.left = "0px";
  649. axis.frame.style.top = "0px";
  650. axis.frame.className = "axis";
  651. dom.content.appendChild(axis.frame);
  652. }
  653. // take axis offline
  654. dom.content.removeChild(axis.frame);
  655. axis.frame.style.width = (size.contentWidth) + "px";
  656. axis.frame.style.height = (size.axis.height) + "px";
  657. // the drawn axis is more wide than the actual visual part, such that
  658. // the axis can be dragged without having to redraw it each time again.
  659. var start = this.screenToTime(0);
  660. var end = this.screenToTime(size.contentWidth);
  661. var width = size.contentWidth;
  662. // calculate minimum step (in milliseconds) based on character size
  663. this.minimumStep = this.screenToTime(size.axis.characterMinorWidth * 6).valueOf() -
  664. this.screenToTime(0).valueOf();
  665. step.setRange(start, end, this.minimumStep);
  666. this.redrawAxisCharacters();
  667. this.redrawAxisStartOverwriting();
  668. step.start();
  669. var xFirstMajorLabel = undefined;
  670. while (!step.end()) {
  671. var cur = step.getCurrent(),
  672. x = this.timeToScreen(cur),
  673. isMajor = step.isMajor();
  674. this.redrawAxisMinorText(x, step.getLabelMinor(undefined, options.language));
  675. if (isMajor && options.showMajorLabels) {
  676. if (x > 0) {
  677. if (xFirstMajorLabel === undefined) {
  678. xFirstMajorLabel = x;
  679. }
  680. this.redrawAxisMajorText(x, step.getLabelMajor(undefined, options.language));
  681. }
  682. this.redrawAxisMajorLine(x);
  683. }
  684. else {
  685. this.redrawAxisMinorLine(x);
  686. }
  687. step.next();
  688. }
  689. // create a major label on the left when needed
  690. if (options.showMajorLabels) {
  691. var leftTime = this.screenToTime(0),
  692. leftText = this.step.getLabelMajor(leftTime, options.language),
  693. width = leftText.length * size.axis.characterMajorWidth + 10;// estimation
  694. if (xFirstMajorLabel === undefined || width < xFirstMajorLabel) {
  695. this.redrawAxisMajorText(0, leftText, leftTime);
  696. }
  697. }
  698. this.redrawAxisHorizontal();
  699. // cleanup left over labels
  700. this.redrawAxisEndOverwriting();
  701. // put axis online
  702. dom.content.insertBefore(axis.frame, dom.content.firstChild);
  703. };
  704. /**
  705. * Create characters used to determine the size of text on the axis
  706. */
  707. links.Timeline.prototype.redrawAxisCharacters = function () {
  708. // calculate the width and height of a single character
  709. // this is used to calculate the step size, and also the positioning of the
  710. // axis
  711. var dom = this.dom,
  712. axis = dom.axis;
  713. if (!axis.characterMinor) {
  714. var text = document.createTextNode("0");
  715. var characterMinor = document.createElement("DIV");
  716. characterMinor.className = "timeline-axis-text timeline-axis-text-minor";
  717. characterMinor.appendChild(text);
  718. characterMinor.style.position = "absolute";
  719. characterMinor.style.visibility = "hidden";
  720. characterMinor.style.paddingLeft = "0px";
  721. characterMinor.style.paddingRight = "0px";
  722. axis.frame.appendChild(characterMinor);
  723. axis.characterMinor = characterMinor;
  724. }
  725. if (!axis.characterMajor) {
  726. var text = document.createTextNode("0");
  727. var characterMajor = document.createElement("DIV");
  728. characterMajor.className = "timeline-axis-text timeline-axis-text-major";
  729. characterMajor.appendChild(text);
  730. characterMajor.style.position = "absolute";
  731. characterMajor.style.visibility = "hidden";
  732. characterMajor.style.paddingLeft = "0px";
  733. characterMajor.style.paddingRight = "0px";
  734. axis.frame.appendChild(characterMajor);
  735. axis.characterMajor = characterMajor;
  736. }
  737. };
  738. /**
  739. * Initialize redraw of the axis. All existing labels and lines will be
  740. * overwritten and reused.
  741. */
  742. links.Timeline.prototype.redrawAxisStartOverwriting = function () {
  743. var properties = this.size.axis.properties;
  744. properties.minorTextNum = 0;
  745. properties.minorLineNum = 0;
  746. properties.majorTextNum = 0;
  747. properties.majorLineNum = 0;
  748. };
  749. /**
  750. * End of overwriting HTML DOM elements of the axis.
  751. * remaining elements will be removed
  752. */
  753. links.Timeline.prototype.redrawAxisEndOverwriting = function () {
  754. var dom = this.dom,
  755. props = this.size.axis.properties,
  756. frame = this.dom.axis.frame;
  757. // remove leftovers
  758. var minorTexts = dom.axis.minorTexts,
  759. num = props.minorTextNum;
  760. while (minorTexts.length > num) {
  761. var minorText = minorTexts[num];
  762. frame.removeChild(minorText);
  763. minorTexts.splice(num, 1);
  764. }
  765. var minorLines = dom.axis.minorLines,
  766. num = props.minorLineNum;
  767. while (minorLines.length > num) {
  768. var minorLine = minorLines[num];
  769. frame.removeChild(minorLine);
  770. minorLines.splice(num, 1);
  771. }
  772. var majorTexts = dom.axis.majorTexts,
  773. num = props.majorTextNum;
  774. while (majorTexts.length > num) {
  775. var majorText = majorTexts[num];
  776. frame.removeChild(majorText);
  777. majorTexts.splice(num, 1);
  778. }
  779. var majorLines = dom.axis.majorLines,
  780. num = props.majorLineNum;
  781. while (majorLines.length > num) {
  782. var majorLine = majorLines[num];
  783. frame.removeChild(majorLine);
  784. majorLines.splice(num, 1);
  785. }
  786. };
  787. /**
  788. * Redraw the horizontal line and background of the axis
  789. */
  790. links.Timeline.prototype.redrawAxisHorizontal = function() {
  791. var axis = this.dom.axis,
  792. size = this.size;
  793. if (!axis.backgroundLine) {
  794. // create the axis line background (for a background color or so)
  795. var backgroundLine = document.createElement("DIV");
  796. backgroundLine.className = "timeline-axis";
  797. backgroundLine.style.position = "absolute";
  798. backgroundLine.style.left = "0px";
  799. backgroundLine.style.width = "100%";
  800. backgroundLine.style.border = "none";
  801. axis.frame.insertBefore(backgroundLine, axis.frame.firstChild);
  802. axis.backgroundLine = backgroundLine;
  803. }
  804. axis.backgroundLine.style.top = size.axis.top + "px";
  805. axis.backgroundLine.style.height = size.axis.height + "px";
  806. if (axis.line) {
  807. // put this line at the end of all childs
  808. var line = axis.frame.removeChild(axis.line);
  809. axis.frame.appendChild(line);
  810. }
  811. else {
  812. // make the axis line
  813. var line = document.createElement("DIV");
  814. line.className = "timeline-axis";
  815. line.style.position = "absolute";
  816. line.style.left = "0px";
  817. line.style.width = "100%";
  818. line.style.height = "0px";
  819. axis.frame.appendChild(line);
  820. axis.line = line;
  821. }
  822. axis.line.style.top = size.axis.line + "px";
  823. };
  824. /**
  825. * Create a minor label for the axis at position x
  826. * @param {Number} x
  827. * @param {String} text
  828. */
  829. links.Timeline.prototype.redrawAxisMinorText = function (x, text) {
  830. var size = this.size,
  831. dom = this.dom,
  832. props = size.axis.properties,
  833. frame = dom.axis.frame,
  834. minorTexts = dom.axis.minorTexts,
  835. index = props.minorTextNum,
  836. label;
  837. if (index < minorTexts.length) {
  838. label = minorTexts[index]
  839. }
  840. else {
  841. // create new label
  842. var content = document.createTextNode(""),
  843. label = document.createElement("DIV");
  844. label.appendChild(content);
  845. label.className = "timeline-axis-text timeline-axis-text-minor";
  846. label.style.position = "absolute";
  847. frame.appendChild(label);
  848. minorTexts.push(label);
  849. }
  850. label.childNodes[0].nodeValue = text;
  851. label.style.left = x + "px";
  852. label.style.top = size.axis.labelMinorTop + "px";
  853. //label.title = title; // TODO: this is a heavy operation
  854. props.minorTextNum++;
  855. };
  856. /**
  857. * Create a minor line for the axis at position x
  858. * @param {Number} x
  859. */
  860. links.Timeline.prototype.redrawAxisMinorLine = function (x) {
  861. var axis = this.size.axis,
  862. dom = this.dom,
  863. props = axis.properties,
  864. frame = dom.axis.frame,
  865. minorLines = dom.axis.minorLines,
  866. index = props.minorLineNum,
  867. line;
  868. if (index < minorLines.length) {
  869. line = minorLines[index];
  870. }
  871. else {
  872. // create vertical line
  873. line = document.createElement("DIV");
  874. line.className = "timeline-axis-grid timeline-axis-grid-minor";
  875. line.style.position = "absolute";
  876. line.style.width = "0px";
  877. frame.appendChild(line);
  878. minorLines.push(line);
  879. }
  880. line.style.top = axis.lineMinorTop + "px";
  881. line.style.height = axis.lineMinorHeight + "px";
  882. line.style.left = (x - axis.lineMinorWidth/2) + "px";
  883. props.minorLineNum++;
  884. };
  885. /**
  886. * Create a Major label for the axis at position x
  887. * @param {Number} x
  888. * @param {String} text
  889. */
  890. links.Timeline.prototype.redrawAxisMajorText = function (x, text) {
  891. var size = this.size,
  892. props = size.axis.properties,
  893. frame = this.dom.axis.frame,
  894. majorTexts = this.dom.axis.majorTexts,
  895. index = props.majorTextNum,
  896. label;
  897. if (index < majorTexts.length) {
  898. label = majorTexts[index];
  899. }
  900. else {
  901. // create label
  902. var content = document.createTextNode(text);
  903. label = document.createElement("DIV");
  904. label.className = "timeline-axis-text timeline-axis-text-major";
  905. label.appendChild(content);
  906. label.style.position = "absolute";
  907. label.style.top = "0px";
  908. frame.appendChild(label);
  909. majorTexts.push(label);
  910. }
  911. label.childNodes[0].nodeValue = text;
  912. label.style.top = size.axis.labelMajorTop + "px";
  913. label.style.left = x + "px";
  914. //label.title = title; // TODO: this is a heavy operation
  915. props.majorTextNum ++;
  916. };
  917. /**
  918. * Create a Major line for the axis at position x
  919. * @param {Number} x
  920. */
  921. links.Timeline.prototype.redrawAxisMajorLine = function (x) {
  922. var size = this.size,
  923. props = size.axis.properties,
  924. axis = this.size.axis,
  925. frame = this.dom.axis.frame,
  926. majorLines = this.dom.axis.majorLines,
  927. index = props.majorLineNum,
  928. line;
  929. if (index < majorLines.length) {
  930. var line = majorLines[index];
  931. }
  932. else {
  933. // create vertical line
  934. line = document.createElement("DIV");
  935. line.className = "timeline-axis-grid timeline-axis-grid-major";
  936. line.style.position = "absolute";
  937. line.style.top = "0px";
  938. line.style.width = "0px";
  939. frame.appendChild(line);
  940. majorLines.push(line);
  941. }
  942. line.style.left = (x - axis.lineMajorWidth/2) + "px";
  943. line.style.height = size.frameHeight + "px";
  944. props.majorLineNum ++;
  945. };
  946. /**
  947. * Redraw all items
  948. */
  949. links.Timeline.prototype.redrawItems = function() {
  950. var dom = this.dom,
  951. options = this.options,
  952. boxAlign = (options.box && options.box.align) ? options.box.align : undefined,
  953. size = this.size,
  954. contentWidth = size.contentWidth,
  955. items = this.items,
  956. visibleItems = [];
  957. // console.log("redrawItems");
  958. if (!dom.items) {
  959. dom.items = {};
  960. }
  961. // draw the frame containing the items
  962. var frame = dom.items.frame;
  963. if (!frame) {
  964. frame = document.createElement("DIV");
  965. frame.style.position = "relative";
  966. dom.content.appendChild(frame);
  967. dom.items.frame = frame;
  968. }
  969. frame.style.left = "0px";
  970. //frame.style.width = "0px";
  971. frame.style.top = size.items.top + "px";
  972. frame.style.height = (size.frameHeight - size.axis.height) + "px";
  973. // initialize arrarys for storing the items
  974. var ranges = dom.items.ranges;
  975. if (!ranges) {
  976. ranges = [];
  977. dom.items.ranges = ranges;
  978. }
  979. var boxes = dom.items.boxes;
  980. if (!boxes) {
  981. boxes = [];
  982. dom.items.boxes = boxes;
  983. }
  984. var dots = dom.items.dots;
  985. if (!dots) {
  986. dots = [];
  987. dom.items.dots = dots;
  988. }
  989. // Take frame offline
  990. dom.content.removeChild(frame);
  991. if (size.dataChanged) {
  992. // create the items
  993. var rangesCreated = ranges.length,
  994. boxesCreated = boxes.length,
  995. dotsCreated = dots.length,
  996. rangesUsed = 0,
  997. boxesUsed = 0,
  998. dotsUsed = 0,
  999. itemsLength = items.length;
  1000. for (var i = 0, iMax = items.length; i < iMax; i++) {
  1001. var item = items[i];
  1002. switch (item.type) {
  1003. case 'range':
  1004. if (rangesUsed < rangesCreated) {
  1005. // reuse existing range
  1006. var domItem = ranges[rangesUsed];
  1007. domItem.firstChild.innerHTML = item.content;
  1008. domItem.style.display = '';
  1009. item.dom = domItem;
  1010. rangesUsed++;
  1011. }
  1012. else {
  1013. // create a new range
  1014. var domItem = this.createEventRange(item.content);
  1015. ranges[rangesUsed] = domItem;
  1016. frame.appendChild(domItem);
  1017. item.dom = domItem;
  1018. rangesUsed++;
  1019. rangesCreated++;
  1020. }
  1021. break;
  1022. case 'box':
  1023. if (boxesUsed < boxesCreated) {
  1024. // reuse existing box
  1025. var domItem = boxes[boxesUsed];
  1026. domItem.firstChild.innerHTML = item.content;
  1027. domItem.style.display = '';
  1028. item.dom = domItem;
  1029. boxesUsed++;
  1030. }
  1031. else {
  1032. // create a new box
  1033. var domItem = this.createEventBox(item.content);
  1034. boxes[boxesUsed] = domItem;
  1035. frame.appendChild(domItem);
  1036. frame.insertBefore(domItem.line, frame.firstChild);
  1037. // Note: line must be added in front of the items,
  1038. // such that it stays below all items
  1039. frame.appendChild(domItem.dot);
  1040. item.dom = domItem;
  1041. boxesUsed++;
  1042. boxesCreated++;
  1043. }
  1044. break;
  1045. case 'dot':
  1046. if (dotsUsed < dotsCreated) {
  1047. // reuse existing box
  1048. var domItem = dots[dotsUsed];
  1049. domItem.firstChild.innerHTML = item.content;
  1050. domItem.style.display = '';
  1051. item.dom = domItem;
  1052. dotsUsed++;
  1053. }
  1054. else {
  1055. // create a new box
  1056. var domItem = this.createEventDot(item.content);
  1057. dots[dotsUsed] = domItem;
  1058. frame.appendChild(domItem);
  1059. item.dom = domItem;
  1060. dotsUsed++;
  1061. dotsCreated++;
  1062. }
  1063. break;
  1064. default:
  1065. // do nothing
  1066. break;
  1067. }
  1068. }
  1069. // remove redundant items when needed
  1070. for (var i = rangesUsed; i < rangesCreated; i++) {
  1071. frame.removeChild(ranges[i]);
  1072. }
  1073. ranges.splice(rangesUsed, rangesCreated - rangesUsed);
  1074. for (var i = boxesUsed; i < boxesCreated; i++) {
  1075. var box = boxes[i];
  1076. frame.removeChild(box.line);
  1077. frame.removeChild(box.dot);
  1078. frame.removeChild(box);
  1079. }
  1080. boxes.splice(boxesUsed, boxesCreated - boxesUsed);
  1081. for (var i = dotsUsed; i < dotsCreated; i++) {
  1082. frame.removeChild(dots[i]);
  1083. }
  1084. dots.splice(dotsUsed, dotsCreated - dotsUsed);
  1085. }
  1086. for (var i = 0, iMax = this.items.length; i < iMax; i++) {
  1087. item = this.items[i];
  1088. domItem = item.dom;
  1089. switch (item.type) {
  1090. case 'range':
  1091. domItem.style.top = item.top + "px";
  1092. domItem.style.left = item.left + "px";
  1093. //domItem.style.width = Math.max(right - left - 2 * item.borderWidth, 1) + "px"; // TODO: borderWidth
  1094. domItem.style.width = Math.max(item.right - item.left, 1) + "px";
  1095. break;
  1096. case 'box':
  1097. var axisOnTop = options.axisOnTop,
  1098. axisHeight = size.axis.height,
  1099. axisTop = size.axis.top;
  1100. domItem.style.top = item.top + "px";
  1101. if (boxAlign == 'right') {
  1102. domItem.style.left = (item.left - item.width) + "px";
  1103. }
  1104. else if (boxAlign == 'left') {
  1105. domItem.style.left = (item.left) + "px";
  1106. }
  1107. else { // default or 'center'
  1108. domItem.style.left = (item.left - item.width/2) + "px";
  1109. }
  1110. var line = domItem.line;
  1111. line.style.left = (item.left - item.lineWidth/2) + "px";
  1112. if (axisOnTop) {
  1113. line.style.top = "0px";
  1114. line.style.height = Math.max(item.top, 0) + "px";
  1115. }
  1116. else {
  1117. line.style.top = (item.top + item.height) + "px";
  1118. line.style.height = Math.max(axisTop - item.top - item.height, 0) + "px";
  1119. }
  1120. var dot = domItem.dot;
  1121. dot.style.left = (item.left - item.dotWidth/2) + "px";
  1122. dot.style.top = (axisTop - item.dotHeight/2) + "px";
  1123. break;
  1124. case 'dot':
  1125. domItem.style.top = item.top + "px";
  1126. domItem.style.left = (item.left - item.dotWidth / 2) + "px";
  1127. domItem.content.style.marginLeft = (1.5 * item.dotWidth) + "px";
  1128. //domItem.content.style.marginRight = (0.5 * item.dotWidth) + "px"; // TODO
  1129. domItem.dot.style.top = ((item.height - item.dotHeight) / 2) + "px";
  1130. break;
  1131. default:
  1132. // do nothing
  1133. break;
  1134. }
  1135. };
  1136. // ! ! ! ! here there was the all items repositionig ! ! ! !
  1137. // move selected item to the end, to ensure that it is always on top
  1138. if (this.selection) {
  1139. var item = this.selection.item;
  1140. frame.removeChild(item);
  1141. frame.appendChild(item);
  1142. }
  1143. // put frame online again
  1144. dom.content.appendChild(frame);
  1145. /* TODO
  1146. // retrieve all image sources from the items, and set a callback once
  1147. // all images are retrieved
  1148. var urls = [];
  1149. var timeline = this;
  1150. links.Timeline.filterImageUrls(frame, urls);
  1151. if (urls.length) {
  1152. for (var i = 0; i < urls.length; i++) {
  1153. var url = urls[i];
  1154. var callback = function (url) {
  1155. timeline.redraw();
  1156. };
  1157. var sendCallbackWhenAlreadyLoaded = false;
  1158. links.imageloader.load(url, callback, sendCallbackWhenAlreadyLoaded);
  1159. }
  1160. }
  1161. */
  1162. };
  1163. /**
  1164. * Create an event in the timeline, with (optional) formatting: inside a box
  1165. * with rounded corners, and a vertical line+dot to the axis.
  1166. * @param {string} content The content for the event. This can be plain text
  1167. * or HTML code.
  1168. */
  1169. links.Timeline.prototype.createEventBox = function(content) {
  1170. // background box
  1171. var divBox = document.createElement("DIV");
  1172. divBox.style.position = "absolute";
  1173. divBox.style.left = "0px";
  1174. divBox.style.top = "0px";
  1175. divBox.className = "timeline-event timeline-event-box";
  1176. // contents box (inside the background box). used for making margins
  1177. var divContent = document.createElement("DIV");
  1178. divContent.className = "timeline-event-content";
  1179. divContent.innerHTML = content;
  1180. divBox.appendChild(divContent);
  1181. // line to axis
  1182. var divLine = document.createElement("DIV");
  1183. divLine.style.position = "absolute";
  1184. divLine.style.width = "0px";
  1185. divLine.className = "timeline-event timeline-event-line";
  1186. // important: the vertical line is added at the front of the list of elements,
  1187. // so it will be drawn behind all boxes and ranges
  1188. divBox.line = divLine;
  1189. // dot on axis
  1190. var divDot = document.createElement("DIV");
  1191. divDot.style.position = "absolute";
  1192. divDot.style.width = "0px";
  1193. divDot.style.height = "0px";
  1194. divDot.className = "timeline-event timeline-event-dot";
  1195. divBox.dot = divDot;
  1196. return divBox;
  1197. };
  1198. /**
  1199. * Create an event in the timeline: a dot, followed by the content.
  1200. * @param {string} content The content for the event. This can be plain text
  1201. * or HTML code.
  1202. */
  1203. links.Timeline.prototype.createEventDot = function(content) {
  1204. // background box
  1205. var divBox = document.createElement("DIV");
  1206. divBox.style.position = "absolute";
  1207. // contents box, right from the dot
  1208. var divContent = document.createElement("DIV");
  1209. divContent.className = "timeline-event-content";
  1210. divContent.innerHTML = content;
  1211. divBox.appendChild(divContent);
  1212. // dot at start
  1213. var divDot = document.createElement("DIV");
  1214. divDot.style.position = "absolute";
  1215. divDot.className = "timeline-event timeline-event-dot";
  1216. divDot.style.width = "0px";
  1217. divDot.style.height = "0px";
  1218. divBox.appendChild(divDot);
  1219. divBox.content = divContent;
  1220. divBox.dot = divDot;
  1221. return divBox;
  1222. };
  1223. /**
  1224. * Create an event range as a beam in the timeline.
  1225. * @param {string} content The content for the event. This can be plain text
  1226. * or HTML code.
  1227. */
  1228. links.Timeline.prototype.createEventRange = function(content) {
  1229. // background box
  1230. var divBox = document.createElement("DIV");
  1231. divBox.style.position = "absolute";
  1232. divBox.className = "timeline-event timeline-event-range";
  1233. // contents box
  1234. var divContent = document.createElement("DIV");
  1235. divContent.className = "timeline-event-content";
  1236. divContent.innerHTML = content;
  1237. divBox.appendChild(divContent);
  1238. return divBox;
  1239. };
  1240. /**
  1241. * Redraw the group labels
  1242. */
  1243. links.Timeline.prototype.redrawGroups = function() {
  1244. var dom = this.dom,
  1245. options = this.options,
  1246. size = this.size,
  1247. groups = this.groups;
  1248. if (dom.groups === undefined) {
  1249. dom.groups = {};
  1250. }
  1251. var labels = dom.groups.labels;
  1252. if (!labels) {
  1253. labels = [];
  1254. dom.groups.labels = labels;
  1255. }
  1256. var labelLines = dom.groups.labelLines;
  1257. if (!labelLines) {
  1258. labelLines = [];
  1259. dom.groups.labelLines = labelLines;
  1260. }
  1261. var itemLines = dom.groups.itemLines;
  1262. if (!itemLines) {
  1263. itemLines = [];
  1264. dom.groups.itemLines = itemLines;
  1265. }
  1266. // create the frame for holding the groups
  1267. var frame = dom.groups.frame;
  1268. if (!frame) {
  1269. frame = document.createElement("DIV");
  1270. frame.className = "timeline-groups-axis";
  1271. frame.style.position = "absolute";
  1272. frame.style.overflow = "hidden";
  1273. frame.style.top = "0px";
  1274. frame.style.height = "100%";
  1275. dom.frame.appendChild(frame);
  1276. dom.groups.frame = frame;
  1277. }
  1278. frame.style.left = size.groupsLeft + "px";
  1279. frame.style.width = (options.groupsWidth !== undefined) ?
  1280. options.groupsWidth :
  1281. size.groupsWidth + "px";
  1282. // hide groups axis when there are no groups
  1283. if (groups.length == 0) {
  1284. frame.style.display = 'none';
  1285. }
  1286. else {
  1287. frame.style.display = '';
  1288. }
  1289. if (size.dataChanged) {
  1290. // create the items
  1291. var current = labels.length,
  1292. needed = groups.length;
  1293. // overwrite existing items
  1294. for (var i = 0, iMax = Math.min(current, needed); i < iMax; i++) {
  1295. var group = groups[i];
  1296. var label = labels[i];
  1297. label.innerHTML = group.content;
  1298. label.style.display = '';
  1299. }
  1300. // append new items when needed
  1301. for (var i = current; i < needed; i++) {
  1302. var group = groups[i];
  1303. // create text label
  1304. var label = document.createElement("DIV");
  1305. label.className = "timeline-groups-text";
  1306. label.style.position = "absolute";
  1307. if (options.groupsWidth === undefined) {
  1308. label.style.whiteSpace = "nowrap";
  1309. }
  1310. label.innerHTML = group.content;
  1311. frame.appendChild(label);
  1312. labels[i] = label;
  1313. // create the grid line between the group labels
  1314. var labelLine = document.createElement("DIV");
  1315. labelLine.className = "timeline-axis-grid timeline-axis-grid-minor";
  1316. labelLine.style.position = "absolute";
  1317. labelLine.style.left = "0px";
  1318. labelLine.style.width = "100%";
  1319. labelLine.style.height = "0px";
  1320. labelLine.style.borderTopStyle = "solid";
  1321. frame.appendChild(labelLine);
  1322. labelLines[i] = labelLine;
  1323. // create the grid line between the items
  1324. var itemLine = document.createElement("DIV");
  1325. itemLine.className = "timeline-axis-grid timeline-axis-grid-minor";
  1326. itemLine.style.position = "absolute";
  1327. itemLine.style.left = "0px";
  1328. itemLine.style.width = "100%";
  1329. itemLine.style.height = "0px";
  1330. itemLine.style.borderTopStyle = "solid";
  1331. dom.content.insertBefore(itemLine, dom.content.firstChild);
  1332. itemLines[i] = itemLine;
  1333. }
  1334. // remove redundant items from the DOM when needed
  1335. for (var i = needed; i < current; i++) {
  1336. var label = labels[i],
  1337. labelLine = labelLines[i],
  1338. itemLine = itemLines[i];
  1339. frame.removeChild(label);
  1340. frame.removeChild(labelLine);
  1341. dom.content.removeChild(itemLine);
  1342. }
  1343. labels.splice(needed, current - needed);
  1344. labelLines.splice(needed, current - needed);
  1345. itemLines.splice(needed, current - needed);
  1346. frame.style.borderStyle = options.groupsOnRight ?
  1347. "none none none solid" :
  1348. "none solid none none";
  1349. }
  1350. // position the groups
  1351. for (var i = 0, iMax = groups.length; i < iMax; i++) {
  1352. var group = groups[i],
  1353. label = labels[i],
  1354. labelLine = labelLines[i],
  1355. itemLine = itemLines[i];
  1356. label.style.top = group.labelTop + "px";
  1357. labelLine.style.top = group.lineTop + "px";
  1358. itemLine.style.top = group.lineTop + "px";
  1359. itemLine.style.width = size.contentWidth + "px";
  1360. }
  1361. if (!dom.groups.background) {
  1362. // create the axis grid line background
  1363. var background = document.createElement("DIV");
  1364. background.className = "timeline-axis";
  1365. background.style.position = "absolute";
  1366. background.style.left = "0px";
  1367. background.style.width = "100%";
  1368. background.style.border = "none";
  1369. frame.appendChild(background);
  1370. dom.groups.background = background;
  1371. }
  1372. dom.groups.background.style.top = size.axis.top + 'px';
  1373. dom.groups.background.style.height = size.axis.height + 'px';
  1374. if (!dom.groups.line) {
  1375. // create the axis grid line
  1376. var line = document.createElement("DIV");
  1377. line.className = "timeline-axis";
  1378. line.style.position = "absolute";
  1379. line.style.left = "0px";
  1380. line.style.width = "100%";
  1381. line.style.height = "0px";
  1382. frame.appendChild(line);
  1383. dom.groups.line = line;
  1384. }
  1385. dom.groups.line.style.top = size.axis.line + 'px';
  1386. };
  1387. /**
  1388. * Redraw the current time bar
  1389. */
  1390. links.Timeline.prototype.redrawCurrentTime = function() {
  1391. var options = this.options,
  1392. dom = this.dom,
  1393. size = this.size;
  1394. if (!options.showCurrentTime) {
  1395. if (dom.currentTime) {
  1396. dom.contentTimelines.removeChild(dom.currentTime);
  1397. delete dom.currentTime;
  1398. }
  1399. return;
  1400. }
  1401. if (!dom.currentTime) {
  1402. // create the current time bar
  1403. var currentTime = document.createElement("DIV");
  1404. currentTime.className = "timeline-currenttime";
  1405. currentTime.style.position = "absolute";
  1406. currentTime.style.top = "0px";
  1407. currentTime.style.height = "100%";
  1408. dom.contentTimelines.appendChild(currentTime);
  1409. dom.currentTime = currentTime;
  1410. }
  1411. var now = new Date();
  1412. var nowOffset = new Date(now.getTime() + this.clientTimeOffset);
  1413. var x = this.timeToScreen(nowOffset);
  1414. var visible = (x > -size.contentWidth && x < 2 * size.contentWidth);
  1415. dom.currentTime.style.display = visible ? '' : 'none';
  1416. dom.currentTime.style.left = x + "px";
  1417. dom.currentTime.title = "Current time: " + nowOffset;
  1418. // start a timer to adjust for the new time
  1419. if (this.currentTimeTimer != undefined) {
  1420. clearTimeout(this.currentTimeTimer);
  1421. delete this.currentTimeTimer;
  1422. }
  1423. var timeline = this;
  1424. var onTimeout = function() {
  1425. timeline.redrawCurrentTime();
  1426. };
  1427. // the time equal to the width of one pixel, divided by 2 for more smoothness
  1428. var interval = 1 / this.conversion.factor / 2;
  1429. if (interval < 30) interval = 30;
  1430. this.currentTimeTimer = setTimeout(onTimeout, interval);
  1431. };
  1432. /**
  1433. * Redraw the custom time bar
  1434. */
  1435. links.Timeline.prototype.redrawCustomTime = function() {
  1436. var options = this.options,
  1437. dom = this.dom,
  1438. size = this.size;
  1439. if (!options.showCustomTime) {
  1440. if (dom.customTime) {
  1441. dom.contentTimelines.removeChild(dom.customTime);
  1442. delete dom.customTime;
  1443. }
  1444. return;
  1445. }
  1446. if (!dom.customTime) {
  1447. var customTime = document.createElement("DIV");
  1448. customTime.className = "timeline-customtime";
  1449. customTime.style.position = "absolute";
  1450. customTime.style.top = "0px";
  1451. customTime.style.height = "100%";
  1452. var drag = document.createElement("DIV");
  1453. drag.style.position = "relative";
  1454. drag.style.top = "0px";
  1455. drag.style.left = "-10px";
  1456. drag.style.height = "100%";
  1457. drag.style.width = "20px";
  1458. customTime.appendChild(drag);
  1459. dom.contentTimelines.appendChild(customTime);
  1460. dom.customTime = customTime;
  1461. // initialize parameter
  1462. this.customTime = new Date();
  1463. }
  1464. var x = this.timeToScreen(this.customTime),
  1465. visible = (x > -size.contentWidth && x < 2 * size.contentWidth);
  1466. dom.customTime.style.display = visible ? '' : 'none';
  1467. dom.customTime.style.left = x + "px";
  1468. dom.customTime.title = "Time: " + this.customTime;
  1469. };
  1470. /**
  1471. * Redraw the delete button, on the top right of the currently selected item
  1472. * if there is no item selected, the button is hidden.
  1473. */
  1474. links.Timeline.prototype.redrawDeleteButton = function () {
  1475. var timeline = this,
  1476. options = this.options,
  1477. dom = this.dom,
  1478. size = this.size,
  1479. frame = dom.items.frame;
  1480. if (!options.editable) {
  1481. return;
  1482. }
  1483. var deleteButton = dom.items.deleteButton;
  1484. if (!deleteButton) {
  1485. // create a delete button
  1486. deleteButton = document.createElement("DIV");
  1487. deleteButton.className = "timeline-navigation-delete";
  1488. deleteButton.style.position = "absolute";
  1489. frame.appendChild(deleteButton);
  1490. dom.items.deleteButton = deleteButton;
  1491. }
  1492. if (this.selection) {
  1493. var index = this.selection.index,
  1494. item = this.items[index],
  1495. domItem = this.selection.item,
  1496. right,
  1497. top = item.top;
  1498. switch (item.type) {
  1499. case 'range':
  1500. right = this.timeToScreen(item.end);
  1501. break;
  1502. case 'box':
  1503. //right = this.timeToScreen(item.start) + item.width / 2 + item.borderWidth; // TODO: borderWidth
  1504. right = this.timeToScreen(item.start) + item.width / 2;
  1505. break;
  1506. case 'dot':
  1507. right = this.timeToScreen(item.start) + item.width;
  1508. break;
  1509. }
  1510. // limit the position
  1511. if (right < -size.contentWidth) {
  1512. right = -size.contentWidth;
  1513. }
  1514. if (right > 2 * size.contentWidth) {
  1515. right = 2 * size.contentWidth;
  1516. }
  1517. deleteButton.style.left = right + 'px';
  1518. deleteButton.style.top = top + 'px';
  1519. deleteButton.style.display = '';
  1520. frame.removeChild(deleteButton);
  1521. frame.appendChild(deleteButton);
  1522. }
  1523. else {
  1524. deleteButton.style.display = 'none';
  1525. }
  1526. };
  1527. /**
  1528. * Redraw the drag areas. When an item (ranges only) is selected,
  1529. * it gets a drag area on the left and right side, to change its width
  1530. */
  1531. links.Timeline.prototype.redrawDragAreas = function () {
  1532. var timeline = this,
  1533. options = this.options,
  1534. dom = this.dom,
  1535. size = this.size,
  1536. frame = this.dom.items.frame;
  1537. if (!options.editable) {
  1538. return;
  1539. }
  1540. // create left drag area
  1541. var dragLeft = dom.items.dragLeft;
  1542. if (!dragLeft) {
  1543. dragLeft = document.createElement("DIV");
  1544. dragLeft.className="timeline-event-range-drag-left";
  1545. dragLeft.style.width = options.dragAreaWidth + "px";
  1546. dragLeft.style.position = "absolute";
  1547. frame.appendChild(dragLeft);
  1548. dom.items.dragLeft = dragLeft;
  1549. }
  1550. // create right drag area
  1551. var dragRight = dom.items.dragRight;
  1552. if (!dragRight) {
  1553. dragRight = document.createElement("DIV");
  1554. dragRight.className="timeline-event-range-drag-right";
  1555. dragRight.style.width = options.dragAreaWidth + "px";
  1556. dragRight.style.position = "absolute";
  1557. frame.appendChild(dragRight);
  1558. dom.items.dragRight = dragRight;
  1559. }
  1560. // reposition left and right drag area
  1561. if (this.selection) {
  1562. var index = this.selection.index,
  1563. item = this.items[index];
  1564. if (item.type == 'range') {
  1565. var domItem = item.dom,
  1566. left = this.timeToScreen(item.start),
  1567. right = this.timeToScreen(item.end),
  1568. top = item.top,
  1569. height = item.height;
  1570. dragLeft.style.left = left + 'px';
  1571. dragLeft.style.top = top + 'px';
  1572. dragLeft.style.height = height + 'px';
  1573. dragLeft.style.display = '';
  1574. frame.removeChild(dragLeft);
  1575. frame.appendChild(dragLeft);
  1576. dragRight.style.left = (right - options.dragAreaWidth) + 'px';
  1577. dragRight.style.top = top + 'px';
  1578. dragRight.style.height = height + 'px';
  1579. dragRight.style.display = '';
  1580. frame.removeChild(dragRight);
  1581. frame.appendChild(dragRight);
  1582. }
  1583. }
  1584. else {
  1585. dragLeft.style.display = 'none';
  1586. dragRight.style.display = 'none';
  1587. }
  1588. };
  1589. /**
  1590. * Create the navigation buttons for zooming and moving
  1591. */
  1592. links.Timeline.prototype.redrawNavigation = function () {
  1593. var timeline = this,
  1594. options = this.options,
  1595. dom = this.dom,
  1596. frame = dom.frame,
  1597. navBar = dom.navBar;
  1598. if (!navBar) {
  1599. if (options.editable || options.showNavigation) {
  1600. // create a navigation bar containing the navigation buttons
  1601. navBar = document.createElement("DIV");
  1602. navBar.style.position = "absolute";
  1603. navBar.className = "timeline-navigation";
  1604. if (options.groupsOnRight) {
  1605. navBar.style.left = '10px';
  1606. }
  1607. else {
  1608. navBar.style.right = '10px';
  1609. }
  1610. if (options.axisOnTop) {
  1611. navBar.style.bottom = '10px';
  1612. }
  1613. else {
  1614. navBar.style.top = '10px';
  1615. }
  1616. dom.navBar = navBar;
  1617. frame.appendChild(navBar);
  1618. }
  1619. if (options.editable && options.showButtonAdd) {
  1620. // create a new in button
  1621. navBar.addButton = document.createElement("DIV");
  1622. navBar.addButton.className = "timeline-navigation-new";
  1623. navBar.addButton.title = "Create new event";
  1624. var onAdd = function(event) {
  1625. links.Timeline.preventDefault(event);
  1626. links.Timeline.stopPropagation(event);
  1627. // create a new event at the center of the frame
  1628. var w = timeline.size.contentWidth;
  1629. var x = w / 2;
  1630. var xstart = timeline.screenToTime(x - w / 10); // subtract 10% of timeline width
  1631. var xend = timeline.screenToTime(x + w / 10); // add 10% of timeline width
  1632. if (options.snapEvents) {
  1633. timeline.step.snap(xstart);
  1634. timeline.step.snap(xend);
  1635. }
  1636. var content = "New";
  1637. var group = timeline.groups.length ? timeline.groups[0].content : undefined;
  1638. timeline.addItem({
  1639. 'start': xstart,
  1640. 'end': xend,
  1641. 'content': content,
  1642. 'group': group
  1643. });
  1644. var index = (timeline.items.length - 1);
  1645. timeline.selectItem(index);
  1646. timeline.applyAdd = true;
  1647. // fire an add event.
  1648. // Note that the change can be canceled from within an event listener if
  1649. // this listener calls the method cancelAdd().
  1650. timeline.trigger('add');
  1651. if (!timeline.applyAdd) {
  1652. // undo an add
  1653. timeline.deleteItem(index);
  1654. }
  1655. timeline.redrawDeleteButton();
  1656. timeline.redrawDragAreas();
  1657. };
  1658. links.Timeline.addEventListener(navBar.addButton, "mousedown", onAdd);
  1659. navBar.appendChild(navBar.addButton);
  1660. }
  1661. if (options.editable && options.showButtonAdd && options.showNavigation) {
  1662. // create a separator line
  1663. navBar.addButton.style.borderRightWidth = "1px";
  1664. navBar.addButton.style.borderRightStyle = "solid";
  1665. }
  1666. if (options.showNavigation) {
  1667. // create a zoom out button
  1668. navBar.zoomOutButton = document.createElement("DIV");
  1669. navBar.zoomOutButton.className = "timeline-navigation-zoom-out";
  1670. navBar.zoomOutButton.title = "Zoom out";
  1671. var onZoomOut = function(event) {
  1672. links.Timeline.preventDefault(event);
  1673. links.Timeline.stopPropagation(event);
  1674. timeline.zoom(-0.7);
  1675. timeline.trigger("rangechange");
  1676. timeline.trigger("rangechanged");
  1677. };
  1678. links.Timeline.addEventListener(navBar.zoomOutButton, "mousedown", onZoomOut);
  1679. navBar.appendChild(navBar.zoomOutButton);
  1680. // create a zoom in button
  1681. navBar.zoomInButton = document.createElement("DIV");
  1682. navBar.zoomInButton.className = "timeline-navigation-zoom-in";
  1683. navBar.zoomInButton.title = "Zoom in";
  1684. var onZoomIn = function(event) {
  1685. links.Timeline.preventDefault(event);
  1686. links.Timeline.stopPropagation(event);
  1687. timeline.zoom(0.7);
  1688. timeline.trigger("rangechange");
  1689. timeline.trigger("rangechanged");
  1690. };
  1691. links.Timeline.addEventListener(navBar.zoomInButton, "mousedown", onZoomIn);
  1692. navBar.appendChild(navBar.zoomInButton);
  1693. // create a move left button
  1694. navBar.moveLeftButton = document.createElement("DIV");
  1695. navBar.moveLeftButton.className = "timeline-navigation-move-left";
  1696. navBar.moveLeftButton.title = "Move left";
  1697. var onMoveLeft = function(event) {
  1698. links.Timeline.preventDefault(event);
  1699. links.Timeline.stopPropagation(event);
  1700. timeline.move(-0.2);
  1701. timeline.trigger("rangechange");
  1702. timeline.trigger("rangechanged");
  1703. };
  1704. links.Timeline.addEventListener(navBar.moveLeftButton, "mousedown", onMoveLeft);
  1705. navBar.appendChild(navBar.moveLeftButton);
  1706. // create a move right button
  1707. navBar.moveRightButton = document.createElement("DIV");
  1708. navBar.moveRightButton.className = "timeline-navigation-move-right";
  1709. navBar.moveRightButton.title = "Move right";
  1710. var onMoveRight = function(event) {
  1711. links.Timeline.preventDefault(event);
  1712. links.Timeline.stopPropagation(event);
  1713. timeline.move(0.2);
  1714. timeline.trigger("rangechange");
  1715. timeline.trigger("rangechanged");
  1716. };
  1717. links.Timeline.addEventListener(navBar.moveRightButton, "mousedown", onMoveRight);
  1718. navBar.appendChild(navBar.moveRightButton);
  1719. }
  1720. }
  1721. };
  1722. /**
  1723. * Set current time. This function can be used to set the time in the client
  1724. * timeline equal with the time on a server.
  1725. * @param {Date} time
  1726. */
  1727. links.Timeline.prototype.setCurrentTime = function(time) {
  1728. var now = new Date();
  1729. this.clientTimeOffset = time.getTime() - now.getTime();
  1730. this.redrawCurrentTime();
  1731. };
  1732. /**
  1733. * Get current time. The time can have an offset from the real time, when
  1734. * the current time has been changed via the method setCurrentTime.
  1735. * @return {Date} time
  1736. */
  1737. links.Timeline.prototype.getCurrentTime = function() {
  1738. var now = new Date();
  1739. return new Date(now.getTime() + this.clientTimeOffset);
  1740. };
  1741. /**
  1742. * Set custom time.
  1743. * The custom time bar can be used to display events in past or future.
  1744. * @param {Date} time
  1745. */
  1746. links.Timeline.prototype.setCustomTime = function(time) {
  1747. this.customTime = new Date(time);
  1748. this.redrawCustomTime();
  1749. };
  1750. /**
  1751. * Retrieve the current custom time.
  1752. * @return {Date} customTime
  1753. */
  1754. links.Timeline.prototype.getCustomTime = function() {
  1755. return new Date(this.customTime);
  1756. };
  1757. /**
  1758. * Set a custom scale. Autoscaling will be disabled.
  1759. * For example setScale(SCALE.MINUTES, 5) will result
  1760. * in minor steps of 5 minutes, and major steps of an hour.
  1761. *
  1762. * @param {links.Timeline.StepDate.SCALE} scale
  1763. * A scale. Choose from SCALE.MILLISECOND,
  1764. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  1765. * SCALE.DAY, SCALE.MONTH, SCALE.YEAR.
  1766. * @param {int} step A step size, by default 1. Choose for
  1767. * example 1, 2, 5, or 10.
  1768. */
  1769. links.Timeline.prototype.setScale = function(scale, step) {
  1770. this.step.setScale(scale, step);
  1771. this.redrawFrame();
  1772. };
  1773. /**
  1774. * Enable or disable autoscaling
  1775. * @param {boolean} enable If true or not defined, autoscaling is enabled.
  1776. * If false, autoscaling is disabled.
  1777. */
  1778. links.Timeline.prototype.setAutoScale = function(enable) {
  1779. this.step.setAutoScale(enable);
  1780. this.redrawFrame();
  1781. };
  1782. /**
  1783. * Redraw the timeline
  1784. * Reloads the (linked) data table and redraws the timeline when resized.
  1785. * See also the method checkResize
  1786. */
  1787. links.Timeline.prototype.redraw = function() {
  1788. this.setData(this.data);
  1789. };
  1790. /**
  1791. * Check if the timeline is resized, and if so, redraw the timeline.
  1792. * Useful when the webpage is resized.
  1793. */
  1794. links.Timeline.prototype.checkResize = function() {
  1795. var resized = this.recalcSize();
  1796. resized = this.repositionItems();
  1797. if (resized) {
  1798. this.redrawFrame();
  1799. }
  1800. };
  1801. /**
  1802. * Recursively retrieve all image urls from the images located inside a given
  1803. * HTML element
  1804. * @param {HTMLElement} elem
  1805. * @param {String[]} urls Urls will be added here (no duplicates)
  1806. */
  1807. links.Timeline.filterImageUrls = function(elem, urls) {
  1808. var child = elem.firstChild;
  1809. while (child) {
  1810. if (child.tagName == 'IMG') {
  1811. var url = child.src;
  1812. if (urls.indexOf(url) == -1) {
  1813. urls.push(url);
  1814. }
  1815. }
  1816. links.Timeline.filterImageUrls(child, urls);
  1817. child = child.nextSibling;
  1818. }
  1819. };
  1820. /**
  1821. * Recalculate the sizes of all frames, groups, items, axis
  1822. * After recalcSize() is executed, the Timeline should be redrawn normally
  1823. *
  1824. * @return {boolean} resized Returns true when the timeline has been resized
  1825. */
  1826. links.Timeline.prototype.recalcSize = function() {
  1827. var resized = false;
  1828. var timeline = this,
  1829. size = this.size,
  1830. options = this.options,
  1831. axisOnTop = options.axisOnTop,
  1832. dom = this.dom,
  1833. axis = dom.axis,
  1834. groups = this.groups,
  1835. labels = dom.groups.labels,
  1836. items = this.items;
  1837. var groupsWidth = size.groupsWidth,
  1838. characterMinorWidth = axis.characterMinor ? axis.characterMinor.clientWidth : 0,
  1839. characterMinorHeight = axis.characterMinor ? axis.characterMinor.clientHeight : 0,
  1840. characterMajorWidth = axis.characterMajor ? axis.characterMajor.clientWidth : 0,
  1841. characterMajorHeight = axis.characterMajor ? axis.characterMajor.clientHeight : 0,
  1842. axisHeight = characterMinorHeight + (options.showMajorLabels ? characterMajorHeight : 0),
  1843. actualHeight = size.actualHeight || axisHeight;
  1844. // TODO: move checking for loaded items when creating the dom
  1845. if (size.dataChanged) {
  1846. // retrieve all image sources from the items, and set a callback once
  1847. // all images are retrieved
  1848. var urls = [];
  1849. for (var i = 0, iMax = items.length; i < iMax; i++) {
  1850. var item = items[i],
  1851. domItem = item.dom;
  1852. if (domItem) {
  1853. links.Timeline.filterImageUrls(domItem, urls);
  1854. }
  1855. }
  1856. if (urls.length) {
  1857. for (var i = 0; i < urls.length; i++) {
  1858. var url = urls[i];
  1859. var callback = function (url) {
  1860. timeline.redraw();
  1861. };
  1862. var sendCallbackWhenAlreadyLoaded = false;
  1863. links.imageloader.load(url, callback, sendCallbackWhenAlreadyLoaded);
  1864. }
  1865. }
  1866. }
  1867. // check sizes of the items and groups (width and height) when the data is changed
  1868. if (size.dataChanged) { // TODO: always calculate the size of an item?
  1869. //if (true) {
  1870. groupsWidth = 0;
  1871. // loop through all groups to get the maximum width and the heights
  1872. for (var i = 0, iMax = labels.length; i < iMax; i++) {
  1873. var group = groups[i];
  1874. group.width = labels[i].clientWidth;
  1875. group.height = labels[i].clientHeight;
  1876. group.labelHeight = group.height;
  1877. groupsWidth = Math.max(groupsWidth, group.width);
  1878. }
  1879. var resized = this.recalcSizeItems();
  1880. // calculate the actual height of the timeline (needed for auto sizing
  1881. // the timeline)
  1882. actualHeight = axisHeight + 2 * options.eventMarginAxis;
  1883. for (var i = 0, iMax = groups.length; i < iMax; i++) {
  1884. actualHeight += groups[i].height + options.eventMargin;
  1885. }
  1886. }
  1887. // calculate actual height of the timeline when there are no groups
  1888. // but stacked items
  1889. if (groups.length == 0 && options.autoHeight) {
  1890. var min = 0,
  1891. max = 0;
  1892. if (this.animation && this.animation.finalItems) {
  1893. // adjust the offset of all finalItems when the actualHeight has been changed
  1894. var finalItems = this.animation.finalItems,
  1895. finalItem = finalItems[0];
  1896. if (finalItem && finalItem.top) {
  1897. min = finalItem.top,
  1898. max = finalItem.top + finalItem.height;
  1899. }
  1900. for (var i = 1, iMax = finalItems.length; i < iMax; i++) {
  1901. finalItem = finalItems[i];
  1902. min = Math.min(min, finalItem.top);
  1903. max = Math.max(max, finalItem.top + finalItem.height);
  1904. }
  1905. }
  1906. else {
  1907. var item = items[0];
  1908. if (item && item.top) {
  1909. min = item.top,
  1910. max = item.top + item.height;
  1911. }
  1912. for (var i = 1, iMax = items.length; i < iMax; i++) {
  1913. var item = items[i];
  1914. if (item.top) {
  1915. min = Math.min(min, item.top);
  1916. max = Math.max(max, (item.top + item.height));
  1917. }
  1918. }
  1919. }
  1920. actualHeight = (max - min) + 2 * options.eventMarginAxis + axisHeight;
  1921. if (size.actualHeight != actualHeight && options.autoHeight && !options.axisOnTop) {
  1922. // adjust the offset of all items when the actualHeight has been changed
  1923. var diff = actualHeight - size.actualHeight;
  1924. if (this.animation && this.animation.finalItems) {
  1925. var finalItems = this.animation.finalItems;
  1926. for (var i = 0, iMax = finalItems.length; i < iMax; i++) {
  1927. finalItems[i].top += diff;
  1928. finalItems[i].item.top += diff;
  1929. }
  1930. }
  1931. else {
  1932. for (var i = 0, iMax = items.length; i < iMax; i++) {
  1933. items[i].top += diff;
  1934. }
  1935. }
  1936. }
  1937. }
  1938. // now the heights of the elements are known, we can calculate the the
  1939. // width and height of frame and axis and content
  1940. // Note: IE7 has issues with giving frame.clientWidth, therefore I use offsetWidth instead
  1941. var frameWidth = dom.frame ? dom.frame.offsetWidth : 0,
  1942. frameHeight = Math.max(options.autoHeight ?
  1943. actualHeight : (dom.frame ? dom.frame.clientHeight : 0),
  1944. options.minHeight),
  1945. axisTop = axisOnTop ? 0 : frameHeight - axisHeight,
  1946. axisLine = axisOnTop ? axisHeight : axisTop,
  1947. itemsTop = axisOnTop ? axisHeight : 0,
  1948. contentHeight = Math.max(frameHeight - axisHeight, 0);
  1949. if (options.groupsWidth !== undefined) {
  1950. groupsWidth = dom.groups.frame ? dom.groups.frame.clientWidth : 0;
  1951. }
  1952. var groupsLeft = options.groupsOnRight ? frameWidth - groupsWidth : 0;
  1953. if (size.dataChanged) {
  1954. // calculate top positions of the group labels and lines
  1955. var eventMargin = options.eventMargin,
  1956. top = axisOnTop ?
  1957. options.eventMarginAxis + eventMargin/2 :
  1958. contentHeight - options.eventMarginAxis + eventMargin/2;
  1959. for (var i = 0, iMax = groups.length; i < iMax; i++) {
  1960. var group = groups[i];
  1961. if (axisOnTop) {
  1962. group.top = top;
  1963. group.labelTop = top + axisHeight + (group.height - group.labelHeight) / 2;
  1964. group.lineTop = top + axisHeight + group.height + eventMargin/2;
  1965. top += group.height + eventMargin;
  1966. }
  1967. else {
  1968. top -= group.height + eventMargin;
  1969. group.top = top;
  1970. group.labelTop = top + (group.height - group.labelHeight) / 2;
  1971. group.lineTop = top - eventMargin/2;
  1972. }
  1973. }
  1974. // calculate top position of the items
  1975. for (var i = 0, iMax = items.length; i < iMax; i++) {
  1976. var item = items[i],
  1977. group = item.group;
  1978. if (group) {
  1979. item.top = group.top;
  1980. }
  1981. }
  1982. resized = true;
  1983. }
  1984. resized = resized || (size.groupsWidth !== groupsWidth);
  1985. resized = resized || (size.groupsLeft !== groupsLeft);
  1986. resized = resized || (size.actualHeight !== actualHeight);
  1987. size.groupsWidth = groupsWidth;
  1988. size.groupsLeft = groupsLeft;
  1989. size.actualHeight = actualHeight;
  1990. resized = resized || (size.frameWidth !== frameWidth);
  1991. resized = resized || (size.frameHeight !== frameHeight);
  1992. size.frameWidth = frameWidth;
  1993. size.frameHeight = frameHeight;
  1994. resized = resized || (size.groupsWidth !== groupsWidth);
  1995. size.groupsWidth = groupsWidth;
  1996. size.contentLeft = options.groupsOnRight ? 0 : groupsWidth;
  1997. size.contentWidth = Math.max(frameWidth - groupsWidth, 0);
  1998. size.contentHeight = contentHeight;
  1999. resized = resized || (size.axis.top !== axisTop);
  2000. resized = resized || (size.axis.line !== axisLine);
  2001. resized = resized || (size.axis.height !== axisHeight);
  2002. resized = resized || (size.items.top !== itemsTop);
  2003. size.axis.top = axisTop;
  2004. size.axis.line = axisLine;
  2005. size.axis.height = axisHeight;
  2006. size.axis.labelMajorTop = options.axisOnTop ? 0 : axisLine + characterMinorHeight;
  2007. size.axis.labelMinorTop = options.axisOnTop ?
  2008. (options.showMajorLabels ? characterMajorHeight : 0) :
  2009. axisLine;
  2010. size.axis.lineMinorTop = options.axisOnTop ? size.axis.labelMinorTop : 0;
  2011. size.axis.lineMinorHeight = options.showMajorLabels ?
  2012. frameHeight - characterMajorHeight:
  2013. frameHeight;
  2014. size.axis.lineMinorWidth = dom.axis.minorLines.length ?
  2015. dom.axis.minorLines[0].offsetWidth : 1;
  2016. size.axis.lineMajorWidth = dom.axis.majorLines.length ?
  2017. dom.axis.majorLines[0].offsetWidth : 1;
  2018. size.items.top = itemsTop;
  2019. resized = resized || (size.axis.characterMinorWidth !== characterMinorWidth);
  2020. resized = resized || (size.axis.characterMinorHeight !== characterMinorHeight);
  2021. resized = resized || (size.axis.characterMajorWidth !== characterMajorWidth);
  2022. resized = resized || (size.axis.characterMajorHeight !== characterMajorHeight);
  2023. size.axis.characterMinorWidth = characterMinorWidth;
  2024. size.axis.characterMinorHeight = characterMinorHeight;
  2025. size.axis.characterMajorWidth = characterMajorWidth;
  2026. size.axis.characterMajorHeight = characterMajorHeight;
  2027. // conversion factors can be changed when width of the Timeline is changed,
  2028. // and when start or end are changed
  2029. this.recalcConversion();
  2030. return resized;
  2031. };
  2032. /**
  2033. *
  2034. *
  2035. */
  2036. links.Timeline.prototype.recalcSizeItems = function(resized) {
  2037. // loop through the width and height of all items
  2038. resized = resized || false;
  2039. for (var i = 0, iMax = this.items.length; i < iMax; i++) {
  2040. var item = this.items[i],
  2041. domItem = item.dom,
  2042. group = item.group;
  2043. var width = domItem ? domItem.clientWidth : 0;
  2044. var height = domItem ? domItem.clientHeight : 0;
  2045. resized = resized || (item.width != width);
  2046. resized = resized || (item.height != height);
  2047. item.width = width;
  2048. item.height = height;
  2049. //item.borderWidth = (domItem.offsetWidth - domItem.clientWidth - 2) / 2; // TODO: borderWidth
  2050. switch (item.type) {
  2051. case 'range':
  2052. break;
  2053. case 'box':
  2054. item.dotHeight = domItem.dot.offsetHeight;
  2055. item.dotWidth = domItem.dot.offsetWidth;
  2056. item.lineWidth = domItem.line.offsetWidth;
  2057. break;
  2058. case 'dot':
  2059. item.dotHeight = domItem.dot.offsetHeight;
  2060. item.dotWidth = domItem.dot.offsetWidth;
  2061. item.contentHeight = domItem.content.offsetHeight;
  2062. break;
  2063. }
  2064. if (group) {
  2065. group.height = group.height ? Math.max(group.height, item.height) : item.height;
  2066. }
  2067. }
  2068. return resized;
  2069. }
  2070. /**
  2071. * Calculate the factor and offset to convert a position on screen to the
  2072. * corresponding date and vice versa.
  2073. * After the method calcConversionFactor is executed once, the methods screenToTime and
  2074. * timeToScreen can be used.
  2075. */
  2076. links.Timeline.prototype.recalcConversion = function() {
  2077. this.conversion.offset = parseFloat(this.start.valueOf());
  2078. this.conversion.factor = parseFloat(this.size.contentWidth) /
  2079. parseFloat(this.end.valueOf() - this.start.valueOf());
  2080. };
  2081. /**
  2082. * Convert a position on screen (pixels) to a datetime
  2083. * Before this method can be used, the method calcConversionFactor must be
  2084. * executed once.
  2085. * @param {int} x Position on the screen in pixels
  2086. * @return {Date} time The datetime the corresponds with given position x
  2087. */
  2088. links.Timeline.prototype.screenToTime = function(x) {
  2089. var conversion = this.conversion,
  2090. time = new Date(parseFloat(x) / conversion.factor + conversion.offset);
  2091. return time;
  2092. };
  2093. /**
  2094. * Convert a datetime (Date object) into a position on the screen
  2095. * Before this method can be used, the method calcConversionFactor must be
  2096. * executed once.
  2097. * @param {Date} time A date
  2098. * @return {int} x The position on the screen in pixels which corresponds
  2099. * with the given date.
  2100. */
  2101. links.Timeline.prototype.timeToScreen = function(time) {
  2102. var conversion = this.conversion;
  2103. var x = (time.valueOf() - conversion.offset) * conversion.factor;
  2104. return x;
  2105. };
  2106. /**
  2107. * Event handler for touchstart event on mobile devices
  2108. */
  2109. links.Timeline.prototype.onTouchStart = function(event) {
  2110. var params = this.eventParams,
  2111. dom = this.dom,
  2112. me = this;
  2113. if (params.touchDown) {
  2114. // if already moving, return
  2115. return;
  2116. }
  2117. params.touchDown = true;
  2118. params.zoomed = false;
  2119. this.onMouseDown(event);
  2120. if (!params.onTouchMove) {
  2121. params.onTouchMove = function (event) {me.onTouchMove(event);};
  2122. links.Timeline.addEventListener(document, "touchmove", params.onTouchMove);
  2123. }
  2124. if (!params.onTouchEnd) {
  2125. params.onTouchEnd = function (event) {me.onTouchEnd(event);};
  2126. links.Timeline.addEventListener(document, "touchend", params.onTouchEnd);
  2127. }
  2128. };
  2129. /**
  2130. * Event handler for touchmove event on mobile devices
  2131. */
  2132. links.Timeline.prototype.onTouchMove = function(event) {
  2133. var params = this.eventParams;
  2134. if (event.scale && event.scale !== 1) {
  2135. params.zoomed = true;
  2136. }
  2137. if (!params.zoomed) {
  2138. // move
  2139. this.onMouseMove(event);
  2140. }
  2141. else {
  2142. if (this.options.zoomable) {
  2143. // pinch
  2144. // TODO: pinch only supported on iPhone/iPad. Create something manually for Android?
  2145. params.zoomed = true;
  2146. var scale = event.scale,
  2147. oldWidth = (params.end.valueOf() - params.start.valueOf()),
  2148. newWidth = oldWidth / scale,
  2149. diff = newWidth - oldWidth,
  2150. start = new Date(parseInt(params.start.valueOf() - diff/2)),
  2151. end = new Date(parseInt(params.end.valueOf() + diff/2));
  2152. // TODO: determine zoom-around-date from touch positions?
  2153. this.setVisibleChartRange(start, end);
  2154. timeline.trigger("rangechange");
  2155. links.Timeline.preventDefault(event);
  2156. }
  2157. }
  2158. };
  2159. /**
  2160. * Event handler for touchend event on mobile devices
  2161. */
  2162. links.Timeline.prototype.onTouchEnd = function(event) {
  2163. var params = this.eventParams;
  2164. params.touchDown = false;
  2165. if (params.zoomed) {
  2166. timeline.trigger("rangechanged");
  2167. }
  2168. if (params.onTouchMove) {
  2169. links.Timeline.removeEventListener(document, "touchmove", params.onTouchMove);
  2170. delete params.onTouchMove;
  2171. }
  2172. if (params.onTouchEnd) {
  2173. links.Timeline.removeEventListener(document, "touchend", params.onTouchEnd);
  2174. delete params.onTouchEnd;
  2175. }
  2176. this.onMouseUp(event);
  2177. };
  2178. /**
  2179. * Start a moving operation inside the provided parent element
  2180. * @param {event} event The event that occurred (required for
  2181. * retrieving the mouse position)
  2182. */
  2183. links.Timeline.prototype.onMouseDown = function(event) {
  2184. event = event || window.event;
  2185. var params = this.eventParams,
  2186. options = this.options,
  2187. dom = this.dom;
  2188. // only react on left mouse button down
  2189. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  2190. if (!leftButtonDown && !params.touchDown) {
  2191. return;
  2192. }
  2193. // check if frame is not resized (causing a mismatch with the end Date)
  2194. this.recalcSize();
  2195. // get mouse position
  2196. if (!params.touchDown) {
  2197. params.mouseX = event.clientX;
  2198. params.mouseY = event.clientY;
  2199. }
  2200. else {
  2201. params.mouseX = event.targetTouches[0].clientX;
  2202. params.mouseY = event.targetTouches[0].clientY;
  2203. }
  2204. if (params.mouseX === undefined) {params.mouseX = 0;}
  2205. if (params.mouseY === undefined) {params.mouseY = 0;}
  2206. params.frameLeft = links.Timeline.getAbsoluteLeft(this.dom.content);
  2207. params.frameTop = links.Timeline.getAbsoluteTop(this.dom.content);
  2208. params.previousLeft = 0;
  2209. params.previousOffset = 0;
  2210. params.moved = false;
  2211. params.start = new Date(this.start);
  2212. params.end = new Date(this.end);
  2213. params.target = links.Timeline.getTarget(event);
  2214. params.itemDragLeft = (params.target === this.dom.items.dragLeft);
  2215. params.itemDragRight = (params.target === this.dom.items.dragRight);
  2216. if (params.itemDragLeft || params.itemDragRight) {
  2217. params.itemIndex = this.selection ? this.selection.index : undefined;
  2218. }
  2219. else {
  2220. params.itemIndex = this.getItemIndex(params.target);
  2221. }
  2222. params.customTime = (params.target === dom.customTime ||
  2223. params.target.parentNode === dom.customTime) ?
  2224. this.customTime :
  2225. undefined;
  2226. params.addItem = (options.editable && event.ctrlKey);
  2227. if (params.addItem) {
  2228. // create a new event at the current mouse position
  2229. var x = params.mouseX - params.frameLeft;
  2230. var y = params.mouseY - params.frameTop;
  2231. var xstart = this.screenToTime(x);
  2232. if (options.snapEvents) {
  2233. this.step.snap(xstart);
  2234. }
  2235. var xend = new Date(xstart);
  2236. var content = "New";
  2237. var group = this.getGroupFromHeight(y);
  2238. this.addItem({
  2239. 'start': xstart,
  2240. 'end': xend,
  2241. 'content': content,
  2242. 'group': group.content
  2243. });
  2244. params.itemIndex = (this.items.length - 1);
  2245. this.selectItem(params.itemIndex);
  2246. params.itemDragRight = true;
  2247. }
  2248. params.editItem = options.editable ? this.isSelected(params.itemIndex) : undefined;
  2249. if (params.editItem) {
  2250. var item = this.items[params.itemIndex];
  2251. params.itemStart = item.start;
  2252. params.itemEnd = item.end;
  2253. params.itemType = item.type;
  2254. if (params.itemType == 'range') {
  2255. params.itemLeft = this.timeToScreen(item.start);
  2256. params.itemRight = this.timeToScreen(item.end);
  2257. }
  2258. else {
  2259. params.itemLeft = this.timeToScreen(item.start);
  2260. }
  2261. }
  2262. else {
  2263. this.dom.frame.style.cursor = 'move';
  2264. }
  2265. if (!params.touchDown) {
  2266. // add event listeners to handle moving the contents
  2267. // we store the function onmousemove and onmouseup in the timeline, so we can
  2268. // remove the eventlisteners lateron in the function mouseUp()
  2269. var me = this;
  2270. if (!params.onMouseMove) {
  2271. params.onMouseMove = function (event) {me.onMouseMove(event);};
  2272. links.Timeline.addEventListener(document, "mousemove", params.onMouseMove);
  2273. }
  2274. if (!params.onMouseUp) {
  2275. params.onMouseUp = function (event) {me.onMouseUp(event);};
  2276. links.Timeline.addEventListener(document, "mouseup", params.onMouseUp);
  2277. }
  2278. links.Timeline.preventDefault(event);
  2279. }
  2280. };
  2281. /**
  2282. * Perform moving operating.
  2283. * This function activated from within the funcion links.Timeline.onMouseDown().
  2284. * @param {event} event Well, eehh, the event
  2285. */
  2286. links.Timeline.prototype.onMouseMove = function (event) {
  2287. event = event || window.event;
  2288. var params = this.eventParams,
  2289. size = this.size,
  2290. dom = this.dom,
  2291. options = this.options;
  2292. // calculate change in mouse position
  2293. var mouseX, mouseY;
  2294. if (!params.touchDown) {
  2295. mouseX = event.clientX;
  2296. mouseY = event.clientY;
  2297. }
  2298. else {
  2299. mouseX = event.targetTouches[0].clientX;
  2300. mouseY = event.targetTouches[0].clientY;
  2301. }
  2302. if (mouseX === undefined) {mouseX = 0;}
  2303. if (mouseY === undefined) {mouseY = 0;}
  2304. if (params.mouseX === undefined) {
  2305. params.mouseX = mouseX;
  2306. }
  2307. if (params.mouseY === undefined) {
  2308. params.mouseY = mouseY;
  2309. }
  2310. var diffX = parseFloat(mouseX) - params.mouseX;
  2311. var diffY = parseFloat(mouseY) - params.mouseY;
  2312. params.moved = true;
  2313. if (params.customTime) {
  2314. var x = this.timeToScreen(params.customTime);
  2315. var xnew = x + diffX;
  2316. this.customTime = this.screenToTime(xnew);
  2317. this.redrawCustomTime();
  2318. // fire a timechange event
  2319. this.trigger('timechange');
  2320. }
  2321. else if (params.editItem) {
  2322. var item = this.items[params.itemIndex],
  2323. domItem = item.dom,
  2324. left,
  2325. right;
  2326. if (params.itemDragLeft) {
  2327. // move the start of the item
  2328. left = params.itemLeft + diffX;
  2329. right = params.itemRight;
  2330. item.start = this.screenToTime(left);
  2331. if (options.snapEvents) {
  2332. this.step.snap(item.start);
  2333. left = this.timeToScreen(item.start);
  2334. }
  2335. if (left > right) {
  2336. left = right;
  2337. item.start = this.screenToTime(left);
  2338. }
  2339. }
  2340. else if (params.itemDragRight) {
  2341. // move the end of the item
  2342. left = params.itemLeft;
  2343. right = params.itemRight + diffX;
  2344. item.end = this.screenToTime(right);
  2345. if (options.snapEvents) {
  2346. this.step.snap(item.end);
  2347. right = this.timeToScreen(item.end);
  2348. }
  2349. if (right < left) {
  2350. right = left;
  2351. item.end = this.screenToTime(right);
  2352. }
  2353. }
  2354. else {
  2355. // move the item
  2356. left = params.itemLeft + diffX;
  2357. item.start = this.screenToTime(left);
  2358. if (options.snapEvents) {
  2359. this.step.snap(item.start);
  2360. left = this.timeToScreen(item.start);
  2361. }
  2362. if (item.end) {
  2363. right = left + (params.itemRight - params.itemLeft);
  2364. item.end = this.screenToTime(right);
  2365. }
  2366. }
  2367. this.repositionItem(item, left, right);
  2368. if (this.groups.length == 0) {
  2369. // TODO: does not work well in FF, forces redraw with every mouse move it seems
  2370. this.stackEvents(options.animate);
  2371. if (!options.animate) {
  2372. this.redrawFrame();
  2373. }
  2374. // Note: when animate==true, no redraw is needed here, its done by stackEvents animation
  2375. }
  2376. else {
  2377. // move item from one group to another when needed
  2378. if (options.groupsChangeable) {
  2379. var y = mouseY - params.frameTop;
  2380. var group = this.getGroupFromHeight(y);
  2381. if (item.group !== group) {
  2382. // move item to the other group
  2383. //item.group = group;
  2384. var index = this.items.indexOf(item);
  2385. this.changeItem(index, {'group': group.content});
  2386. item.top = group.top;
  2387. this.repositionItem(item);
  2388. }
  2389. }
  2390. }
  2391. this.redrawDeleteButton();
  2392. this.redrawDragAreas();
  2393. }
  2394. else if (options.moveable) {
  2395. this.moveFrame(diffX);
  2396. }
  2397. links.Timeline.preventDefault(event);
  2398. };
  2399. links.Timeline.prototype.moveFrame = function(diffX){
  2400. var params = this.eventParams,
  2401. size = this.size,
  2402. dom = this.dom,
  2403. options = this.options;
  2404. var interval = (params.end.valueOf() - params.start.valueOf());
  2405. var diffMillisecs = Math.round(parseFloat(-diffX) / size.contentWidth * interval);
  2406. var newStart = new Date(params.start.valueOf() + diffMillisecs);
  2407. var newEnd = new Date(params.end.valueOf() + diffMillisecs);
  2408. this.applyRange(newStart, newEnd);
  2409. // console.log('interval = '+interval+'\ndiffMillisecs = '+diffMillisecs);//+'\nnewStart = '+newStart+'\nnewEnd = '+newEnd)
  2410. // if the applied range is moved due to a fixed min or max,
  2411. // change the diffMillisecs accordingly
  2412. var appliedDiff = (this.start.valueOf() - newStart.valueOf());
  2413. if (appliedDiff) {
  2414. diffMillisecs += appliedDiff;
  2415. }
  2416. this.recalcConversion();
  2417. // move the items by changing the left position of their frame.
  2418. // this is much faster than repositioning all elements individually via the
  2419. // redrawFrame() function (which is done once at mouseup)
  2420. // note that we round diffX to prevent wrong positioning on millisecond scale
  2421. var previousLeft = params.previousLeft || 0;
  2422. var currentLeft = parseFloat(dom.items.frame.style.left) || 0;
  2423. var previousOffset = params.previousOffset || 0;
  2424. var frameOffset = previousOffset + (currentLeft - previousLeft);
  2425. var frameLeft = Math.round(-diffMillisecs / interval * size.contentWidth + frameOffset);
  2426. params.previousOffset = frameOffset;
  2427. params.previousLeft = frameLeft;
  2428. // console.log('previousLeft = '+previousLeft+' \ncurrentLeft = '+currentLeft+'\npreviousOffset = '+previousOffset+'\nframeOffset = '+frameOffset+'\nframeLeft = '+frameLeft);
  2429. dom.items.frame.style.left = (frameLeft) + "px";
  2430. this.redrawCurrentTime();
  2431. this.redrawCustomTime();
  2432. this.redrawAxis();
  2433. // fire a rangechange event
  2434. this.trigger('rangechange');
  2435. // console.log('dom.items.frame.style.left = '+dom.items.frame.style.left);
  2436. }
  2437. /**
  2438. * Stop moving operating.
  2439. * This function activated from within the funcion links.Timeline.onMouseDown().
  2440. * @param {event} event The event
  2441. */
  2442. links.Timeline.prototype.onMouseUp = function (event) {
  2443. var params = this.eventParams,
  2444. options = this.options;
  2445. event = event || window.event;
  2446. this.dom.frame.style.cursor = 'auto';
  2447. // remove event listeners here, important for Safari
  2448. if (params.onMouseMove) {
  2449. links.Timeline.removeEventListener(document, "mousemove", params.onMouseMove);
  2450. delete params.onMouseMove;
  2451. }
  2452. if (params.onMouseUp) {
  2453. links.Timeline.removeEventListener(document, "mouseup", params.onMouseUp);
  2454. delete params.onMouseUp;
  2455. }
  2456. //links.Timeline.preventDefault(event);
  2457. if (params.customTime) {
  2458. // fire a timechanged event
  2459. this.trigger('timechanged');
  2460. }
  2461. else if (params.editItem) {
  2462. var item = this.items[params.itemIndex];
  2463. if (params.moved || params.addItem) {
  2464. this.applyChange = true;
  2465. this.applyAdd = true;
  2466. this.updateData(params.itemIndex, {
  2467. 'start': item.start,
  2468. 'end': item.end
  2469. });
  2470. // fire an add or change event.
  2471. // Note that the change can be canceled from within an event listener if
  2472. // this listener calls the method cancelChange().
  2473. this.trigger(params.addItem ? 'add' : 'change');
  2474. if (params.addItem) {
  2475. if (this.applyAdd) {
  2476. this.updateData(params.itemIndex, {
  2477. 'start': item.start,
  2478. 'end': item.end,
  2479. 'content': item.content,
  2480. 'group': item.group ? item.group.content : undefined
  2481. });
  2482. }
  2483. else {
  2484. // undo an add
  2485. this.deleteItem(params.itemIndex);
  2486. }
  2487. }
  2488. else {
  2489. if (this.applyChange) {
  2490. this.updateData(params.itemIndex, {
  2491. 'start': item.start,
  2492. 'end': item.end
  2493. });
  2494. }
  2495. else {
  2496. // undo a change
  2497. delete this.applyChange;
  2498. delete this.applyAdd;
  2499. var item = this.items[params.itemIndex],
  2500. domItem = item.dom;
  2501. item.start = params.itemStart;
  2502. item.end = params.itemEnd;
  2503. this.repositionItem(item, params.itemLeft, params.itemRight);
  2504. }
  2505. }
  2506. this.recalcSize();
  2507. this.repositionItems();
  2508. this.stackEvents(options.animate);
  2509. if (!options.animate) {
  2510. this.redrawFrame();
  2511. }
  2512. this.redrawDeleteButton();
  2513. this.redrawDragAreas();
  2514. }
  2515. }
  2516. else {
  2517. this.endMoveFrame();
  2518. // mouse did not move -> user has selected an item
  2519. }
  2520. };
  2521. links.Timeline.prototype.endMoveFrame = function(){
  2522. //console.log('endMoveFrame');
  2523. var params = this.eventParams,
  2524. options = this.options;
  2525. if (!params.moved && !params.zoomed) {
  2526. // mouse did not move -> user has selected an item
  2527. if (options.editable && (params.target === this.dom.items.deleteButton)) {
  2528. // delete item
  2529. if (this.selection) {
  2530. this.confirmDeleteItem(this.selection.index);
  2531. }
  2532. this.redrawFrame();
  2533. }
  2534. else if (options.selectable) {
  2535. // select/unselect item
  2536. if (params.itemIndex !== undefined) {
  2537. if (!this.isSelected(params.itemIndex)) {
  2538. this.selectItem(params.itemIndex);
  2539. this.redrawDeleteButton();
  2540. this.redrawDragAreas();
  2541. this.trigger('select');
  2542. }
  2543. }
  2544. else {
  2545. this.unselectItem();
  2546. this.redrawDeleteButton();
  2547. this.redrawDragAreas();
  2548. }
  2549. }
  2550. }
  2551. else {
  2552. // timeline is moved
  2553. this.repositionItems();
  2554. this.stackEvents(options.animate);
  2555. if (!options.animate) {
  2556. this.redrawFrame();
  2557. }
  2558. if ((params.moved && options.moveable) || (params.zoomed && options.zoomable) ) {
  2559. // fire a rangechanged event
  2560. this.trigger('rangechanged');
  2561. }
  2562. }
  2563. };
  2564. /**
  2565. * Double click event occurred for an item
  2566. * @param {event} event
  2567. */
  2568. links.Timeline.prototype.onDblClick = function (event) {
  2569. var params = this.eventParams,
  2570. options = this.options,
  2571. dom = this.dom,
  2572. size = this.size;
  2573. event = event || window.event;
  2574. if (!options.editable && !options.zoomable) {
  2575. return;
  2576. }
  2577. /*
  2578. TODO WRONG here
  2579. detect dblclick on editable element or on timeline background
  2580. */
  2581. switch(options.dblclick){
  2582. case "edit":
  2583. if(!options.editable)
  2584. return;
  2585. if (params.itemIndex !== undefined) {
  2586. // fire the edit event
  2587. this.trigger('edit');
  2588. } else {
  2589. // create a new item
  2590. var x = event.clientX - links.Timeline.getAbsoluteLeft(dom.content);
  2591. var y = event.clientY - links.Timeline.getAbsoluteTop(dom.content);
  2592. // create a new event at the current mouse position
  2593. var xstart = this.screenToTime(x);
  2594. var xend = this.screenToTime(x + size.frameWidth / 10); // add 10% of timeline width
  2595. if (options.snapEvents) {
  2596. this.step.snap(xstart);
  2597. this.step.snap(xend);
  2598. }
  2599. var content = "New";
  2600. var group = this.getGroupFromHeight(y); // (group may be undefined)
  2601. this.addItem({
  2602. 'start': xstart,
  2603. 'end': xend,
  2604. 'content': content,
  2605. 'group': group.content
  2606. });
  2607. params.itemIndex = (this.items.length - 1);
  2608. this.selectItem(params.itemIndex);
  2609. this.applyAdd = true;
  2610. // fire an add event.
  2611. // Note that the change can be canceled from within an event listener if
  2612. // this listener calls the method cancelAdd().
  2613. this.trigger('add');
  2614. if (!this.applyAdd) {
  2615. // undo an add
  2616. this.deleteItem(params.itemIndex);
  2617. }
  2618. this.redrawDeleteButton();
  2619. this.redrawDragAreas();
  2620. }
  2621. break;
  2622. case "zoom":
  2623. if(!options.zoomable)
  2624. return;
  2625. // this.zoom(0.7);
  2626. var x = event.clientX - links.Timeline.getAbsoluteLeft(dom.content),
  2627. range = size.frameWidth / 5,
  2628. xstart = this.screenToTime(x - range),
  2629. xend = this.screenToTime(x + range);
  2630. this.setVisibleChartRange(xstart, xend);
  2631. break;
  2632. }
  2633. links.Timeline.preventDefault(event);
  2634. };
  2635. /**
  2636. * Event handler for mouse wheel event
  2637. * @param {event} event The event
  2638. */
  2639. links.Timeline.prototype.onMouseWheel = function(event) {
  2640. if (!this.options.zoomable && !this.options.moveable)
  2641. return;
  2642. if (!event) { /* For IE. */
  2643. event = window.event;
  2644. }
  2645. // retrieve delta
  2646. var delta = 0;
  2647. if (event.wheelDelta) { /* IE/Opera. */
  2648. delta = event.wheelDelta/120;
  2649. } else if (event.detail) { /* Mozilla case. */
  2650. // In Mozilla, sign of delta is different than in IE.
  2651. // Also, delta is multiple of 3.
  2652. delta = -event.detail/3;
  2653. }
  2654. // If delta is nonzero, handle it.
  2655. // Basically, delta is now positive if wheel was scrolled up,
  2656. // and negative, if wheel was scrolled down.
  2657. if (delta) {
  2658. switch(this.options.mousewheel){
  2659. case 'zoom':
  2660. this.onMouseWheelZoom(event, delta);
  2661. break;
  2662. case 'move':
  2663. this.onMouseWheelMove(event, delta);
  2664. break;
  2665. default:
  2666. break;
  2667. }
  2668. }
  2669. // Prevent default actions caused by mouse wheel.
  2670. // That might be ugly, but we handle scrolls somehow
  2671. // anyway, so don't bother here...
  2672. links.Timeline.preventDefault(event);
  2673. }
  2674. /**
  2675. * Event handler for mouse wheel event, used to zoom the timeline
  2676. * Code from http://adomas.org/javascript-mouse-wheel/
  2677. * @param {event} event The event
  2678. */
  2679. links.Timeline.prototype.onMouseWheelZoom = function(event, delta) {
  2680. if (!this.options.zoomable)
  2681. return;
  2682. // TODO: on FireFox, the window is not redrawn within repeated scroll-events
  2683. // -> use a delayed redraw? Make a zoom queue?
  2684. var timeline = this;
  2685. var zoom = function () {
  2686. // check if frame is not resized (causing a mismatch with the end date)
  2687. timeline.recalcSize();
  2688. // perform the zoom action. Delta is normally 1 or -1
  2689. var zoomFactor = delta / 5.0;
  2690. var frameLeft = links.Timeline.getAbsoluteLeft(timeline.dom.content);
  2691. var zoomAroundDate =
  2692. (event.clientX != undefined && frameLeft != undefined) ?
  2693. timeline.screenToTime(event.clientX - frameLeft) :
  2694. undefined;
  2695. timeline.zoom(zoomFactor, zoomAroundDate);
  2696. // fire a rangechange and a rangechanged event
  2697. timeline.trigger("rangechange");
  2698. timeline.trigger("rangechanged");
  2699. /* TODO: smooth scrolling on FF
  2700. timeline.zooming = false;
  2701. if (timeline.zoomingQueue) {
  2702. setTimeout(timeline.zoomingQueue, 100);
  2703. timeline.zoomingQueue = undefined;
  2704. }
  2705. timeline.zoomCount = (timeline.zoomCount || 0) + 1;
  2706. //console.log('zoomCount', timeline.zoomCount)
  2707. */
  2708. };
  2709. zoom();
  2710. /* TODO: smooth scrolling on FF
  2711. if (!timeline.zooming || true) {
  2712. timeline.zooming = true;
  2713. setTimeout(zoom, 100);
  2714. }
  2715. else {
  2716. timeline.zoomingQueue = zoom;
  2717. }
  2718. //*/
  2719. };
  2720. /**
  2721. * Event handler for mouse wheel event, used to move the timeline
  2722. * Code from http://adomas.org/javascript-mouse-wheel/
  2723. * @param {event} event The event
  2724. */
  2725. links.Timeline.prototype.onMouseWheelMove = function(event, delta) {
  2726. if (!this.options.moveable)
  2727. return;
  2728. var params = this.eventParams;
  2729. if(params.scrolled === undefined || !params.scrolled){
  2730. params.start = new Date(this.start);
  2731. params.end = new Date(this.end);
  2732. params.scrolled = true;
  2733. params.wheelScrolledX = 0;
  2734. params.previousLeft = 0;
  2735. params.previousOffset = 0;
  2736. params.dif
  2737. }
  2738. params.wheelScrolledX += Math.round(delta*11);
  2739. this.moveFrame(params.wheelScrolledX);
  2740. /* SET TIME OUT FOR END SCROLLING EVENT */
  2741. if(this.eventParams.wheelEnderTimer !== undefined)
  2742. clearTimeout(this.eventParams.wheelEnderTimer);
  2743. /*
  2744. var me = this;
  2745. function endScorlling(){
  2746. me.repositionItems();
  2747. me.stackEvents(me.options.animate);
  2748. if (!me.options.animate) {
  2749. me.redrawFrame();
  2750. }
  2751. if (params.scrolled && me.options.moveable) {
  2752. params.scrolled = false;
  2753. // fire a rangechanged event
  2754. me.trigger('rangechanged');
  2755. }
  2756. };
  2757. */
  2758. var me = this;
  2759. this.eventParams.wheelEnderTimer = setTimeout(function(){
  2760. params.scrolled = false;
  2761. me.endMoveFrame();
  2762. }, 100);
  2763. };
  2764. /**
  2765. * Zoom the timeline the given zoomfactor in or out. Start and end date will
  2766. * be adjusted, and the timeline will be redrawn. You can optionally give a
  2767. * date around which to zoom.
  2768. * For example, try zoomfactor = 0.1 or -0.1
  2769. * @param {Number} zoomFactor Zooming amount. Positive value will zoom in,
  2770. * negative value will zoom out
  2771. * @param {Date} zoomAroundDate Date around which will be zoomed. Optional
  2772. */
  2773. links.Timeline.prototype.zoom = function(zoomFactor, zoomAroundDate) {
  2774. // if zoomAroundDate is not provided, take it half between start Date and end Date
  2775. if (zoomAroundDate == undefined) {
  2776. zoomAroundDate = new Date((this.start.valueOf() + this.end.valueOf()) / 2);
  2777. }
  2778. // prevent zoom factor larger than 1 or smaller than -1 (larger than 1 will
  2779. // result in a start>=end )
  2780. if (zoomFactor >= 1) {
  2781. zoomFactor = 0.9;
  2782. }
  2783. if (zoomFactor <= -1) {
  2784. zoomFactor = -0.9;
  2785. }
  2786. // adjust a negative factor such that zooming in with 0.1 equals zooming
  2787. // out with a factor -0.1
  2788. if (zoomFactor < 0) {
  2789. zoomFactor = zoomFactor / (1 + zoomFactor);
  2790. }
  2791. // zoom start Date and end Date relative to the zoomAroundDate
  2792. var startDiff = parseFloat(this.start.valueOf() - zoomAroundDate.valueOf());
  2793. var endDiff = parseFloat(this.end.valueOf() - zoomAroundDate.valueOf());
  2794. // calculate new dates
  2795. var newStart = new Date(this.start.valueOf() - startDiff * zoomFactor);
  2796. var newEnd = new Date(this.end.valueOf() - endDiff * zoomFactor);
  2797. this.applyRange(newStart, newEnd, zoomAroundDate);
  2798. this.recalcSize();
  2799. var animate = this.options.animate ? this.options.animateZoom : false;
  2800. this.repositionItems();
  2801. this.stackEvents(animate);
  2802. if (!animate || this.groups.length > 0) {
  2803. this.redrawFrame();
  2804. }
  2805. /* TODO
  2806. else {
  2807. this.redrawFrame();
  2808. this.recalcSize();
  2809. this.stackEvents(animate);
  2810. this.redrawFrame();
  2811. }*/
  2812. };
  2813. /**
  2814. * Move the timeline the given movefactor to the left or right. Start and end
  2815. * date will be adjusted, and the timeline will be redrawn.
  2816. * For example, try moveFactor = 0.1 or -0.1
  2817. * @param {Number} moveFactor Moving amount. Positive value will move right,
  2818. * negative value will move left
  2819. */
  2820. links.Timeline.prototype.move = function(moveFactor) {
  2821. // zoom start Date and end Date relative to the zoomAroundDate
  2822. var diff = parseFloat(this.end.valueOf() - this.start.valueOf());
  2823. // apply new dates
  2824. var newStart = new Date(this.start.valueOf() + diff * moveFactor);
  2825. var newEnd = new Date(this.end.valueOf() + diff * moveFactor);
  2826. this.applyRange(newStart, newEnd);
  2827. this.recalcConversion();
  2828. this.repositionItems();
  2829. this.stackEvents(this.options.animate);
  2830. if (!this.options.animate) {
  2831. this.redrawFrame();
  2832. }
  2833. };
  2834. /**
  2835. * Reposition given item
  2836. * @param {Object} item
  2837. * @param {Number} left
  2838. * @param {Number} right
  2839. */
  2840. links.Timeline.prototype.repositionItem = function (item, left, right) {
  2841. var domItem = item.dom;
  2842. switch(item.type) {
  2843. case 'range':
  2844. domItem.style.left = left + "px";
  2845. //domItem.style.width = Math.max(right - left - 2 * item.borderWidth, 1) + "px"; // TODO: borderwidth
  2846. domItem.style.width = Math.max(right - left, 1) + "px";
  2847. break;
  2848. case 'box':
  2849. domItem.style.left = (left - item.width / 2) + "px";
  2850. domItem.line.style.left = (left - item.lineWidth / 2) + "px";
  2851. domItem.dot.style.left = (left - item.dotWidth / 2) + "px";
  2852. break;
  2853. case 'dot':
  2854. domItem.style.left = (left - item.dotWidth / 2) + "px";
  2855. break;
  2856. }
  2857. if (this.groups.length > 0) {
  2858. domItem.style.top = item.top + 'px';
  2859. }
  2860. };
  2861. /**
  2862. * Apply a visible range. The range is limited to feasible maximum and minimum
  2863. * range.
  2864. * @param {Date} start
  2865. * @param {Date} end
  2866. * @param {Date} zoomAroundDate Optional. Date around which will be zoomed.
  2867. */
  2868. links.Timeline.prototype.applyRange = function (start, end, zoomAroundDate) {
  2869. // calculate new start and end value
  2870. var startValue = start.valueOf();
  2871. var endValue = end.valueOf();
  2872. var interval = (endValue - startValue);
  2873. // determine maximum and minimum interval
  2874. var options = this.options;
  2875. var year = 1000 * 60 * 60 * 24 * 365;
  2876. var intervalMin = Number(options.intervalMin) || 10;
  2877. if (intervalMin < 10) {
  2878. intervalMin = 10;
  2879. }
  2880. var intervalMax = Number(options.intervalMax) || 10000 * year;
  2881. if (intervalMax > 10000 * year) {
  2882. intervalMax = 10000 * year;
  2883. }
  2884. if (intervalMax < intervalMin) {
  2885. intervalMax = intervalMin;
  2886. }
  2887. // determine min and max date value
  2888. var min = options.min ? options.min.valueOf() : undefined;
  2889. var max = options.max ? options.max.valueOf() : undefined;
  2890. if (min && max) {
  2891. if (min >= max) {
  2892. // empty range
  2893. var day = 1000 * 60 * 60 * 24;
  2894. max = min + day;
  2895. }
  2896. if (intervalMax > (max - min)) {
  2897. intervalMax = (max - min);
  2898. }
  2899. if (intervalMin > (max - min)) {
  2900. intervalMin = (max - min);
  2901. }
  2902. }
  2903. // prevent empty interval
  2904. if (startValue >= endValue) {
  2905. endValue += 1000 * 60 * 60 * 24;
  2906. }
  2907. // prevent too small scale
  2908. // TODO: IE has problems with milliseconds
  2909. if (interval < intervalMin) {
  2910. var diff = (intervalMin - interval);
  2911. var f = zoomAroundDate ? (zoomAroundDate.valueOf() - startValue) / interval : 0.5;
  2912. startValue -= Math.round(diff * f);
  2913. endValue += Math.round(diff * (1 - f));
  2914. }
  2915. // prevent too large scale
  2916. if (interval > intervalMax) {
  2917. var diff = (interval - intervalMax);
  2918. var f = zoomAroundDate ? (zoomAroundDate.valueOf() - startValue) / interval : 0.5;
  2919. startValue += Math.round(diff * f);
  2920. endValue -= Math.round(diff * (1 - f));
  2921. }
  2922. // prevent to small start date
  2923. if (min) {
  2924. var diff = (startValue - min);
  2925. if (diff < 0) {
  2926. startValue -= diff;
  2927. endValue -= diff;
  2928. }
  2929. }
  2930. // prevent to large end date
  2931. if (max) {
  2932. var diff = (max - endValue);
  2933. if (diff < 0) {
  2934. startValue += diff;
  2935. endValue += diff;
  2936. }
  2937. }
  2938. // apply new dates
  2939. this.start = new Date(startValue);
  2940. this.end = new Date(endValue);
  2941. };
  2942. /**
  2943. * Delete an item after a confirmation.
  2944. * The deletion can be cancelled by executing .cancelDelete() during the
  2945. * triggered event 'delete'.
  2946. * @param {int} index Index of the item to be deleted
  2947. */
  2948. links.Timeline.prototype.confirmDeleteItem = function(index) {
  2949. this.applyDelete = true;
  2950. // select the event to be deleted
  2951. if (!this.isSelected(index)) {
  2952. this.selectItem(index);
  2953. }
  2954. // fire a delete event trigger.
  2955. // Note that the delete event can be canceled from within an event listener if
  2956. // this listener calls the method cancelChange().
  2957. this.trigger('delete');
  2958. if (this.applyDelete) {
  2959. this.deleteItem(index);
  2960. }
  2961. delete this.applyDelete;
  2962. };
  2963. /**
  2964. * Delete an item
  2965. * @param {int} index Index of the item to be deleted
  2966. */
  2967. links.Timeline.prototype.deleteItem = function(index) {
  2968. if (index >= this.items.length) {
  2969. throw "Cannot delete row, index out of range";
  2970. }
  2971. this.unselectItem();
  2972. // actually delete the item
  2973. this.items.splice(index, 1);
  2974. // delete the row in the original data table
  2975. if (this.data) {
  2976. if (google && google.visualization &&
  2977. this.data instanceof google.visualization.DataTable) {
  2978. this.data.removeRow(index);
  2979. }
  2980. else if (links.Timeline.isArray(this.data)) {
  2981. this.data.splice(index, 1);
  2982. }
  2983. else {
  2984. throw "Cannot delete row from data, unknown data type";
  2985. }
  2986. }
  2987. this.size.dataChanged = true;
  2988. this.redrawFrame();
  2989. this.recalcSize();
  2990. this.repositionItems();
  2991. this.stackEvents(this.options.animate);
  2992. if (!this.options.animate) {
  2993. this.redrawFrame();
  2994. }
  2995. this.size.dataChanged = false;
  2996. };
  2997. /**
  2998. * Delete all items
  2999. */
  3000. links.Timeline.prototype.deleteAllItems = function() {
  3001. this.unselectItem();
  3002. // delete the loaded data
  3003. this.items = [];
  3004. // delete the groups
  3005. this.deleteGroups();
  3006. // empty original data table
  3007. if (this.data) {
  3008. if (google && google.visualization &&
  3009. this.data instanceof google.visualization.DataTable) {
  3010. this.data.removeRows(0, this.data.getNumberOfRows());
  3011. }
  3012. else if (links.Timeline.isArray(this.data)) {
  3013. this.data.splice(0, this.data.length);
  3014. }
  3015. else {
  3016. throw "Cannot delete row from data, unknown data type";
  3017. }
  3018. }
  3019. this.size.dataChanged = true;
  3020. this.redrawFrame();
  3021. this.recalcSize();
  3022. this.repositionItems();
  3023. this.stackEvents(this.options.animate);
  3024. if (!this.options.animate) {
  3025. this.redrawFrame();
  3026. }
  3027. this.size.dataChanged = false;
  3028. };
  3029. /**
  3030. * Find the group from a given height in the timeline
  3031. * @param {Number} height Height in the timeline
  3032. * @param {boolean}
  3033. * @return {Object} group The group object, or undefined if out of range
  3034. */
  3035. links.Timeline.prototype.getGroupFromHeight = function(height) {
  3036. var groups = this.groups,
  3037. options = this.options,
  3038. size = this.size,
  3039. y = height - (options.axisOnTop ? size.axis.height : 0);
  3040. if (groups) {
  3041. var group;
  3042. /* TODO: cleanup
  3043. for (var i = 0, iMax = groups.length; i < iMax; i++) {
  3044. group = groups[i];
  3045. if (y > group.top && y < group.top + group.height) {
  3046. return group;
  3047. }
  3048. }*/
  3049. for (var i = groups.length - 1; i >= 0; i--) {
  3050. group = groups[i];
  3051. if (y > group.top) {
  3052. return group;
  3053. }
  3054. }
  3055. return group; // return the last group
  3056. }
  3057. return undefined;
  3058. };
  3059. /**
  3060. * Retrieve the properties of an item.
  3061. * @param {Number} index
  3062. * @return {Object} properties Object containing item properties:<br>
  3063. * {Date} start (required),
  3064. * {Date} end (optional),
  3065. * {String} content (required),
  3066. * {String} group (optional)
  3067. */
  3068. links.Timeline.prototype.getItem = function (index) {
  3069. if (index >= this.items.length) {
  3070. throw "Cannot get item, index out of range";
  3071. }
  3072. var item = this.items[index];
  3073. var properties = {};
  3074. properties.start = new Date(item.start);
  3075. if (item.end) {
  3076. properties.end = new Date(item.end);
  3077. }
  3078. properties.content = item.content;
  3079. if (item.group) {
  3080. properties.group = item.group.content;
  3081. }
  3082. return properties;
  3083. };
  3084. /**
  3085. * Add a new item.
  3086. * @param {Object} itemData Object containing item properties:<br>
  3087. * {Date} start (required),
  3088. * {Date} end (optional),
  3089. * {String} content (required),
  3090. * {String} group (optional)
  3091. */
  3092. links.Timeline.prototype.addItem = function (itemData) {
  3093. var items = [
  3094. itemData
  3095. ];
  3096. this.addItems(items);
  3097. };
  3098. /**
  3099. * Add new items.
  3100. * @param {Array} items An array containing Objects.
  3101. * The objects must have the following parameters:
  3102. * {Date} start,
  3103. * {Date} end,
  3104. * {String} content with text or HTML code,
  3105. * {String} group
  3106. */
  3107. links.Timeline.prototype.addItems = function (items) {
  3108. var newItems = items,
  3109. curItems = this.items;
  3110. // append the items
  3111. for (var i = 0, iMax = newItems.length; i < iMax; i++) {
  3112. var itemData = items[i];
  3113. this.addGroup(itemData.group);
  3114. curItems.push(this.createItem(itemData));
  3115. var index = curItems.length - 1;
  3116. this.updateData(index, itemData);
  3117. }
  3118. // redraw timeline
  3119. this.size.dataChanged = true;
  3120. this.redrawFrame();
  3121. this.recalcSize();
  3122. this.repositionItems();
  3123. this.stackEvents(false);
  3124. this.redrawFrame();
  3125. this.size.dataChanged = false;
  3126. };
  3127. /**
  3128. * Create an item object, containing all needed parameters
  3129. * @param {Object} itemData Object containing parameters start, end
  3130. * content, group.
  3131. * @return {Object} item
  3132. */
  3133. links.Timeline.prototype.createItem = function(itemData) {
  3134. var item = {
  3135. 'start': itemData.start,
  3136. 'end': itemData.end,
  3137. 'content': itemData.content,
  3138. 'type': itemData.end ? 'range' : this.options.style,
  3139. 'group': this.findGroup(itemData.group),
  3140. 'top': 0,
  3141. 'left': 0,
  3142. 'width': 0,
  3143. 'height': 0,
  3144. 'lineWidth' : 0,
  3145. 'dotWidth': 0,
  3146. 'dotHeight': 0
  3147. };
  3148. return item;
  3149. };
  3150. /**
  3151. * Edit an item
  3152. * @param {Number} index
  3153. * @param {Object} itemData Object containing item properties:<br>
  3154. * {Date} start (required),
  3155. * {Date} end (optional),
  3156. * {String} content (required),
  3157. * {String} group (optional)
  3158. */
  3159. links.Timeline.prototype.changeItem = function (index, itemData) {
  3160. if (index >= this.items.length) {
  3161. throw "Cannot change item, index out of range";
  3162. }
  3163. var style = this.options.style;
  3164. var item = this.items[index];
  3165. // edit the item
  3166. if (itemData.start) {
  3167. item.start = itemData.start;
  3168. }
  3169. if (itemData.end) {
  3170. item.end = itemData.end;
  3171. }
  3172. if (itemData.content) {
  3173. item.content = itemData.content;
  3174. }
  3175. if (itemData.group) {
  3176. item.group = this.addGroup(itemData.group);
  3177. }
  3178. // update the original data table
  3179. this.updateData(index, itemData);
  3180. // redraw timeline
  3181. this.size.dataChanged = true;
  3182. this.redrawFrame();
  3183. this.recalcSize();
  3184. this.repositionItems();
  3185. this.stackEvents(false);
  3186. this.redrawFrame();
  3187. this.size.dataChanged = false;
  3188. };
  3189. /**
  3190. * Find a group by its name.
  3191. * @param {String} group
  3192. * @return {Object} a group object or undefined when group is not found
  3193. */
  3194. links.Timeline.prototype.findGroup = function (group) {
  3195. var index = this.groupIndexes[group];
  3196. return (index != undefined) ? this.groups[index] : undefined;
  3197. };
  3198. /**
  3199. * Delete all groups
  3200. */
  3201. links.Timeline.prototype.deleteGroups = function () {
  3202. this.groups = [];
  3203. this.groupIndexes = {};
  3204. };
  3205. /**
  3206. * Add a group. When the group already exists, no new group is created
  3207. * but the existing group is returned.
  3208. * @param {String} groupName the name of the group
  3209. * @return {Object} groupObject
  3210. */
  3211. links.Timeline.prototype.addGroup = function (groupName) {
  3212. var groups = this.groups,
  3213. groupIndexes = this.groupIndexes,
  3214. groupObj = undefined;
  3215. var groupIndex = groupIndexes[groupName];
  3216. if (groupIndex === undefined && groupName !== undefined) {
  3217. groupObj = {
  3218. 'content': groupName,
  3219. 'labelTop': 0,
  3220. 'lineTop': 0
  3221. // note: this object will lateron get addition information,
  3222. // such as height and width of the group
  3223. };
  3224. groups.push(groupObj);
  3225. // sort the groups
  3226. groups = groups.sort(function (a, b) {
  3227. if (a.content > b.content) {
  3228. return 1;
  3229. }
  3230. if (a.content < b.content) {
  3231. return -1;
  3232. }
  3233. return 0;
  3234. });
  3235. // rebuilt the groupIndexes
  3236. for (var i = 0, iMax = groups.length; i < iMax; i++) {
  3237. groupIndexes[groups[i].content] = i;
  3238. }
  3239. }
  3240. else {
  3241. groupObj = groups[groupIndex];
  3242. }
  3243. return groupObj;
  3244. };
  3245. /**
  3246. * Cancel a change item
  3247. * This method can be called insed an event listener which catches the "change"
  3248. * event. The changed event position will be undone.
  3249. */
  3250. links.Timeline.prototype.cancelChange = function () {
  3251. this.applyChange = false;
  3252. };
  3253. /**
  3254. * Cancel deletion of an item
  3255. * This method can be called insed an event listener which catches the "delete"
  3256. * event. Deletion of the event will be undone.
  3257. */
  3258. links.Timeline.prototype.cancelDelete = function () {
  3259. this.applyDelete = false;
  3260. };
  3261. /**
  3262. * Cancel creation of a new item
  3263. * This method can be called insed an event listener which catches the "new"
  3264. * event. Creation of the new the event will be undone.
  3265. */
  3266. links.Timeline.prototype.cancelAdd = function () {
  3267. this.applyAdd = false;
  3268. };
  3269. /**
  3270. * Select an event. The visible chart range will be moved such that the selected
  3271. * event is placed in the middle.
  3272. * For example selection = [{row: 5}];
  3273. * @param {Array} selection An array with a column row, containing the row
  3274. * number (the id) of the event to be selected.
  3275. * @return {boolean} true if selection is succesfully set, else false.
  3276. */
  3277. links.Timeline.prototype.setSelection = function(selection) {
  3278. if (selection != undefined && selection.length > 0) {
  3279. if (selection[0].row != undefined) {
  3280. var index = selection[0].row;
  3281. if (this.items[index]) {
  3282. var item = this.items[index];
  3283. this.selectItem(index);
  3284. // move the visible chart range to the selected event.
  3285. var start = item.start;
  3286. var end = item.end;
  3287. var middle;
  3288. if (end != undefined) {
  3289. middle = new Date((end.valueOf() + start.valueOf()) / 2);
  3290. } else {
  3291. middle = new Date(start);
  3292. }
  3293. var diff = (this.end.valueOf() - this.start.valueOf()),
  3294. newStart = new Date(middle.valueOf() - diff/2),
  3295. newEnd = new Date(middle.valueOf() + diff/2);
  3296. this.setVisibleChartRange(newStart, newEnd);
  3297. return true;
  3298. }
  3299. }
  3300. }
  3301. else {
  3302. // unselect current selection
  3303. this.unselectItem();
  3304. }
  3305. return false;
  3306. };
  3307. /**
  3308. * Retrieve the currently selected event
  3309. * @return {Array} sel An array with a column row, containing the row number
  3310. * of the selected event. If there is no selection, an
  3311. * empty array is returned.
  3312. */
  3313. links.Timeline.prototype.getSelection = function() {
  3314. var sel = [];
  3315. if (this.selection) {
  3316. sel.push({"row": this.selection.index});
  3317. }
  3318. return sel;
  3319. };
  3320. /**
  3321. * Select an item by its index
  3322. * @param {Number} index
  3323. */
  3324. links.Timeline.prototype.selectItem = function(index) {
  3325. this.unselectItem();
  3326. this.selection = undefined;
  3327. if (this.items[index] !== undefined) {
  3328. var item = this.items[index],
  3329. domItem = item.dom;
  3330. this.selection = {
  3331. 'index': index,
  3332. 'item': domItem
  3333. };
  3334. if (this.options.editable) {
  3335. domItem.style.cursor = 'move';
  3336. }
  3337. switch (item.type) {
  3338. case 'range':
  3339. domItem.className = "timeline-event timeline-event-selected timeline-event-range";
  3340. break;
  3341. case 'box':
  3342. domItem.className = "timeline-event timeline-event-selected timeline-event-box";
  3343. domItem.line.className = "timeline-event timeline-event-selected timeline-event-line";
  3344. domItem.dot.className = "timeline-event timeline-event-selected timeline-event-dot";
  3345. break;
  3346. case 'dot':
  3347. domItem.className = "timeline-event timeline-event-selected";
  3348. domItem.dot.className = "timeline-event timeline-event-selected timeline-event-dot";
  3349. break;
  3350. }
  3351. /* TODO: cleanup this cannot work as this breaks any javscript action inside the item
  3352. // move the item to the end, such that it will be displayed on top of the other items
  3353. var parent = domItem.parentNode;
  3354. if (parent) {
  3355. parent.removeChild(domItem);
  3356. parent.appendChild(domItem);
  3357. }
  3358. */
  3359. }
  3360. };
  3361. /**
  3362. * Check if an item is currently selected
  3363. * @param {Number} index
  3364. * @return {boolean} true if row is selected, else false
  3365. */
  3366. links.Timeline.prototype.isSelected = function (index) {
  3367. return (this.selection && this.selection.index === index);
  3368. };
  3369. /**
  3370. * Unselect the currently selected event (if any)
  3371. */
  3372. links.Timeline.prototype.unselectItem = function() {
  3373. if (this.selection) {
  3374. var item = this.items[this.selection.index];
  3375. if (item && item.dom) {
  3376. var domItem = item.dom;
  3377. domItem.style.cursor = '';
  3378. switch (item.type) {
  3379. case 'range':
  3380. domItem.className = "timeline-event timeline-event-range";
  3381. break;
  3382. case 'box':
  3383. domItem.className = "timeline-event timeline-event-box";
  3384. domItem.line.className = "timeline-event timeline-event-line";
  3385. domItem.dot.className = "timeline-event timeline-event-dot";
  3386. break;
  3387. case 'dot':
  3388. domItem.className = "";
  3389. domItem.dot.className = "timeline-event timeline-event-dot";
  3390. break;
  3391. }
  3392. }
  3393. }
  3394. this.selection = undefined;
  3395. };
  3396. /**
  3397. *
  3398. *
  3399. *
  3400. */
  3401. links.Timeline.prototype.repositionItems = function(){
  3402. var size = this.size,
  3403. contentWidth = size.contentWidth,
  3404. item, domItem,
  3405. visibleItems = [];
  3406. // reposition all items
  3407. for (var i = 0, iMax = this.items.length; i < iMax; i++) {
  3408. item = this.items[i];
  3409. domItem = item.dom;
  3410. switch (item.type) {
  3411. case 'range':
  3412. item.left = this.timeToScreen(item.start);
  3413. item.right = this.timeToScreen(item.end);
  3414. // limit the width of the item, as browsers cannot draw very wide divs
  3415. if (item.left < -contentWidth) {
  3416. item.left = -contentWidth;
  3417. }
  3418. if (item.right > 2 * contentWidth) {
  3419. item.right = 2 * contentWidth;
  3420. }
  3421. var visible = item.right > -contentWidth && item.left < 2 * contentWidth;
  3422. if (visible || size.dataChanged) {
  3423. // when data is changed, all items must be kept visible, as their heights must be measured
  3424. if (item.hidden) {
  3425. item.hidden = false;
  3426. domItem.style.display = '';
  3427. }
  3428. }
  3429. else {
  3430. // hide when outside of the current window
  3431. if (!item.hidden) {
  3432. domItem.style.display = 'none';
  3433. item.hidden = true;
  3434. }
  3435. }
  3436. break;
  3437. case 'box':
  3438. item.left = this.timeToScreen(item.start);
  3439. var visible = ((item.left + item.width/2 > -contentWidth) &&
  3440. (item.left - item.width/2 < 2 * contentWidth));
  3441. if (visible || size.dataChanged) {
  3442. //when data is changed, all items must be kept visible, as their heights must be measured
  3443. if (item.hidden) {
  3444. item.hidden = false;
  3445. domItem.style.display = '';
  3446. domItem.line.style.display = '';
  3447. domItem.dot.style.display = '';
  3448. }
  3449. }
  3450. else {
  3451. // hide when outside of the current window
  3452. if (!item.hidden) {
  3453. domItem.style.display = 'none';
  3454. domItem.line.style.display = 'none';
  3455. domItem.dot.style.display = 'none';
  3456. item.hidden = true;
  3457. }
  3458. }
  3459. break;
  3460. case 'dot':
  3461. item.left = this.timeToScreen(item.start);
  3462. var visible = (item.left + item.width > -contentWidth) && (item.left < 2 * contentWidth);
  3463. if (visible || size.dataChanged) {
  3464. // when data is changed, all items must be kept visible, as their heights must be measured
  3465. if (item.hidden) {
  3466. item.hidden = false;
  3467. domItem.style.display = '';
  3468. }
  3469. }
  3470. else {
  3471. // hide when outside of the current window
  3472. if (!item.hidden) {
  3473. domItem.style.display = 'none';
  3474. item.hidden = true;
  3475. }
  3476. }
  3477. break;
  3478. default:
  3479. // do nothing
  3480. break;
  3481. }
  3482. if(!item.hidden)
  3483. visibleItems.push(item);
  3484. this.items[i] = item;
  3485. }
  3486. if(this.visibleItems.length != visibleItems.length){
  3487. this.visibleItemsChanged = true;
  3488. }else{
  3489. this.visibleItemsChanged = false;
  3490. }
  3491. this.visibleItems = visibleItems;
  3492. this.itemsSizeChanged = false;
  3493. }
  3494. /**
  3495. * Stack the items such that they don't overlap. The items will have a minimal
  3496. * distance equal to options.eventMargin.
  3497. * @param {boolean} animate if animate is true, the items are moved to
  3498. * their new position animated
  3499. */
  3500. links.Timeline.prototype.stackEvents = function(animate) {
  3501. this.trigger('on-before-stack-events');
  3502. if(this.itemsSizeChanged)
  3503. this.recalcSizeItems();
  3504. if (this.groups.length > 0) {
  3505. // under this conditions we refuse to stack the events
  3506. return;
  3507. }
  3508. if (animate == undefined) {
  3509. animate = false;
  3510. }
  3511. var sortedItems = this.stackOrder(this.items);
  3512. var finalItems = this.stackCalculateFinal(sortedItems, animate);
  3513. if (animate) {
  3514. // move animated to the final positions
  3515. var animation = this.animation;
  3516. if (!animation) {
  3517. animation = {};
  3518. this.animation = animation;
  3519. }
  3520. animation.finalItems = finalItems;
  3521. var timeline = this;
  3522. var step = function () {
  3523. var arrived = timeline.stackMoveOneStep(sortedItems, animation.finalItems);
  3524. timeline.recalcSize();
  3525. timeline.repositionItems();
  3526. timeline.redrawFrame();
  3527. if (!arrived) {
  3528. animation.timer = setTimeout(step, 30);
  3529. }
  3530. else {
  3531. delete animation.finalItems;
  3532. delete animation.timer;
  3533. }
  3534. };
  3535. if (!animation.timer) {
  3536. animation.timer = setTimeout(step, 30);
  3537. }
  3538. }
  3539. else {
  3540. this.stackMoveToFinal(sortedItems, finalItems);
  3541. this.recalcSize();
  3542. }
  3543. };
  3544. /**
  3545. * Order the items in the array this.items. The order is determined via:
  3546. * - Ranges go before boxes and dots.
  3547. * - The item with the left most location goes first
  3548. * @param {Array} items Array with items
  3549. * @return {Array} sortedItems Array with sorted items
  3550. */
  3551. links.Timeline.prototype.stackOrder = function(items) {
  3552. // TODO: store the sorted items, to have less work later on
  3553. var sortedItems = items.concat([]);
  3554. var f = function (a, b) {
  3555. if (a.type == 'range' && b.type != 'range') {
  3556. return -1;
  3557. }
  3558. if (a.type != 'range' && b.type == 'range') {
  3559. return 1;
  3560. }
  3561. return (a.left - b.left);
  3562. };
  3563. sortedItems.sort(f);
  3564. return sortedItems;
  3565. };
  3566. /**
  3567. * Adjust vertical positions of the events such that they don't overlap each
  3568. * other.
  3569. */
  3570. links.Timeline.prototype.stackCalculateFinal = function(items) {
  3571. var size = this.size,
  3572. axisTop = size.axis.top,
  3573. options = this.options,
  3574. axisOnTop = options.axisOnTop,
  3575. eventMargin = options.eventMargin,
  3576. eventMarginAxis = options.eventMarginAxis,
  3577. finalItems = [];
  3578. // initialize final positions
  3579. for (var i = 0, iMax = items.length; i < iMax; i++) {
  3580. var item = items[i],
  3581. top,
  3582. left,
  3583. right,
  3584. bottom,
  3585. height = item.height,
  3586. width = item.width;
  3587. if (axisOnTop) {
  3588. top = axisTop + eventMarginAxis + eventMargin / 2;
  3589. }
  3590. else {
  3591. top = axisTop - height - eventMarginAxis - eventMargin / 2;
  3592. }
  3593. bottom = top + height;
  3594. switch (item.type) {
  3595. case 'range':
  3596. case 'dot':
  3597. left = this.timeToScreen(item.start);
  3598. right = item.end ? this.timeToScreen(item.end) : left + width;
  3599. break;
  3600. case 'box':
  3601. left = this.timeToScreen(item.start) - width / 2;
  3602. right = left + width;
  3603. break;
  3604. }
  3605. finalItems[i] = {
  3606. 'left': left,
  3607. 'top': top,
  3608. 'right': right,
  3609. 'bottom': bottom,
  3610. 'height': height,
  3611. 'item': item
  3612. };
  3613. }
  3614. if (this.options.stackEvents) {
  3615. // calculate new, non-overlapping positions
  3616. //var items = sortedItems;
  3617. for (var i = 0, iMax = finalItems.length; i < iMax; i++) {
  3618. //for (var i = finalItems.length - 1; i >= 0; i--) {
  3619. var finalItem = finalItems[i];
  3620. var collidingItem = null;
  3621. do {
  3622. // TODO: optimize checking for overlap. when there is a gap without items,
  3623. // you only need to check for items from the next item on, not from zero
  3624. collidingItem = this.stackEventsCheckOverlap(finalItems, i, 0, i-1);
  3625. if (collidingItem != null) {
  3626. // There is a collision. Reposition the event above the colliding element
  3627. if (axisOnTop) {
  3628. finalItem.top = collidingItem.top + collidingItem.height + eventMargin;
  3629. }
  3630. else {
  3631. finalItem.top = collidingItem.top - finalItem.height - eventMargin;
  3632. }
  3633. finalItem.bottom = finalItem.top + finalItem.height;
  3634. }
  3635. } while (collidingItem);
  3636. }
  3637. }
  3638. return finalItems;
  3639. };
  3640. /**
  3641. * Move the events one step in the direction of their final positions
  3642. * @param {Array} currentItems Array with the real items and their current
  3643. * positions
  3644. * @param {Array} finalItems Array with objects containing the final
  3645. * positions of the items
  3646. * @return {boolean} arrived True if all items have reached their final
  3647. * location, else false
  3648. */
  3649. links.Timeline.prototype.stackMoveOneStep = function(currentItems, finalItems) {
  3650. var arrived = true;
  3651. // apply new positions animated
  3652. for (i = 0, iMax = currentItems.length; i < iMax; i++) {
  3653. var finalItem = finalItems[i],
  3654. item = finalItem.item;
  3655. var topNow = parseInt(item.top);
  3656. var topFinal = parseInt(finalItem.top);
  3657. var diff = (topFinal - topNow);
  3658. if (diff) {
  3659. var step = (topFinal == topNow) ? 0 : ((topFinal > topNow) ? 1 : -1);
  3660. if (Math.abs(diff) > 4) step = diff / 4;
  3661. var topNew = parseInt(topNow + step);
  3662. if (topNew != topFinal) {
  3663. arrived = false;
  3664. }
  3665. item.top = topNew;
  3666. item.bottom = item.top + item.height;
  3667. }
  3668. else {
  3669. item.top = finalItem.top;
  3670. item.bottom = finalItem.bottom;
  3671. }
  3672. item.left = finalItem.left;
  3673. item.right = finalItem.right;
  3674. }
  3675. return arrived;
  3676. };
  3677. /**
  3678. * Move the events from their current position to the final position
  3679. * @param {Array} currentItems Array with the real items and their current
  3680. * positions
  3681. * @param {Array} finalItems Array with objects containing the final
  3682. * positions of the items
  3683. */
  3684. links.Timeline.prototype.stackMoveToFinal = function(currentItems, finalItems) {
  3685. // Put the events directly at there final position
  3686. for (i = 0, iMax = currentItems.length; i < iMax; i++) {
  3687. var current = currentItems[i],
  3688. finalItem = finalItems[i];
  3689. current.left = finalItem.left;
  3690. current.top = finalItem.top;
  3691. current.right = finalItem.right;
  3692. current.bottom = finalItem.bottom;
  3693. }
  3694. };
  3695. /**
  3696. * Check if the destiny position of given item overlaps with any
  3697. * of the other items from index itemStart to itemEnd.
  3698. * @param {Array} items Array with items
  3699. * @param {int} itemIndex Number of the item to be checked for overlap
  3700. * @param {int} itemStart First item to be checked.
  3701. * @param {int} itemEnd Last item to be checked.
  3702. * @return {Object} colliding item, or undefined when no collisions
  3703. */
  3704. links.Timeline.prototype.stackEventsCheckOverlap = function(items, itemIndex,
  3705. itemStart, itemEnd) {
  3706. var eventMargin = this.options.eventMargin,
  3707. collision = this.collision;
  3708. // we loop from end to start, as we suppose that the chance of a
  3709. // collision is larger for items at the end, so check these first.
  3710. var item1 = items[itemIndex];
  3711. for (var i = itemEnd; i >= itemStart; i--) {
  3712. var item2 = items[i];
  3713. if (collision(item1, item2, eventMargin)) {
  3714. if (i != itemIndex) {
  3715. return item2;
  3716. }
  3717. }
  3718. }
  3719. return undefined;
  3720. };
  3721. /**
  3722. * Test if the two provided items collide
  3723. * The items must have parameters left, right, top, and bottom.
  3724. * @param {Element} item1 The first item
  3725. * @param {Element} item2 The second item
  3726. * @param {Number} margin A minimum required margin. Optional.
  3727. * If margin is provided, the two items will be
  3728. * marked colliding when they overlap or
  3729. * when the margin between the two is smaller than
  3730. * the requested margin.
  3731. * @return {boolean} true if item1 and item2 collide, else false
  3732. */
  3733. links.Timeline.prototype.collision = function(item1, item2, margin) {
  3734. // set margin if not specified
  3735. if (margin == undefined) {
  3736. margin = 0;
  3737. }
  3738. // calculate if there is overlap (collision)
  3739. return (item1.left - margin < item2.right &&
  3740. item1.right + margin > item2.left &&
  3741. item1.top - margin < item2.bottom &&
  3742. item1.bottom + margin > item2.top);
  3743. };
  3744. /**
  3745. * fire an event
  3746. * @param {String} event The name of an event, for example "rangechange" or "edit"
  3747. */
  3748. links.Timeline.prototype.trigger = function (event) {
  3749. // built up properties
  3750. var properties = null;
  3751. switch (event) {
  3752. case 'rangechange':
  3753. case 'rangechanged':
  3754. properties = {
  3755. 'start': new Date(this.start),
  3756. 'end': new Date(this.end)
  3757. };
  3758. break;
  3759. case 'timechange':
  3760. case 'timechanged':
  3761. properties = {
  3762. 'time': new Date(this.customTime)
  3763. };
  3764. break;
  3765. }
  3766. // trigger the links event bus
  3767. links.events.trigger(this, event, properties);
  3768. // trigger the google event bus
  3769. if (google && google.visualization) {
  3770. google.visualization.events.trigger(this, event, properties);
  3771. }
  3772. };
  3773. /** ------------------------------------------------------------------------ **/
  3774. /**
  3775. * Event listener (singleton)
  3776. */
  3777. links.events = links.events || {
  3778. 'listeners': [],
  3779. /**
  3780. * Find a single listener by its object
  3781. * @param {Object} object
  3782. * @return {Number} index -1 when not found
  3783. */
  3784. 'indexOf': function (object) {
  3785. var listeners = this.listeners;
  3786. for (var i = 0, iMax = this.listeners.length; i < iMax; i++) {
  3787. var listener = listeners[i];
  3788. if (listener && listener.object == object) {
  3789. return i;
  3790. }
  3791. }
  3792. return -1;
  3793. },
  3794. /**
  3795. * Add an event listener
  3796. * @param {Object} object
  3797. * @param {String} event The name of an event, for example 'select'
  3798. * @param {function} callback The callback method, called when the
  3799. * event takes place
  3800. */
  3801. 'addListener': function (object, event, callback) {
  3802. var index = this.indexOf(object);
  3803. var listener = this.listeners[index];
  3804. if (!listener) {
  3805. listener = {
  3806. 'object': object,
  3807. 'events': {}
  3808. };
  3809. this.listeners.push(listener);
  3810. }
  3811. var callbacks = listener.events[event];
  3812. if (!callbacks) {
  3813. callbacks = [];
  3814. listener.events[event] = callbacks;
  3815. }
  3816. // add the callback if it does not yet exist
  3817. if (callbacks.indexOf(callback) == -1) {
  3818. callbacks.push(callback);
  3819. }
  3820. },
  3821. /**
  3822. * Remove an event listener
  3823. * @param {Object} object
  3824. * @param {String} event The name of an event, for example 'select'
  3825. * @param {function} callback The registered callback method
  3826. */
  3827. 'removeListener': function (object, event, callback) {
  3828. var index = this.indexOf(object);
  3829. var listener = this.listeners[index];
  3830. if (listener) {
  3831. var callbacks = listener.events[event];
  3832. if (callbacks) {
  3833. var index = callbacks.indexOf(callback);
  3834. if (index != -1) {
  3835. callbacks.splice(index, 1);
  3836. }
  3837. // remove the array when empty
  3838. if (callbacks.length == 0) {
  3839. delete listener.events[event];
  3840. }
  3841. }
  3842. // count the number of registered events. remove listener when empty
  3843. var count = 0;
  3844. var events = listener.events;
  3845. for (var e in events) {
  3846. if (events.hasOwnProperty(e)) {
  3847. count++;
  3848. }
  3849. }
  3850. if (count == 0) {
  3851. delete this.listeners[index];
  3852. }
  3853. }
  3854. },
  3855. /**
  3856. * Remove all registered event listeners
  3857. */
  3858. 'removeAllListeners': function () {
  3859. this.listeners = [];
  3860. },
  3861. /**
  3862. * Trigger an event. All registered event handlers will be called
  3863. * @param {Object} object
  3864. * @param {String} event
  3865. * @param {Object} properties (optional)
  3866. */
  3867. 'trigger': function (object, event, properties) {
  3868. var index = this.indexOf(object);
  3869. var listener = this.listeners[index];
  3870. if (listener) {
  3871. var callbacks = listener.events[event];
  3872. if (callbacks) {
  3873. for (var i = 0, iMax = callbacks.length; i < iMax; i++) {
  3874. callbacks[i](properties);
  3875. }
  3876. }
  3877. }
  3878. }
  3879. };
  3880. /** ------------------------------------------------------------------------ **/
  3881. /**
  3882. * @constructor links.Timeline.StepDate
  3883. * The class StepDate is an iterator for dates. You provide a start date and an
  3884. * end date. The class itself determines the best scale (step size) based on the
  3885. * provided start Date, end Date, and minimumStep.
  3886. *
  3887. * If minimumStep is provided, the step size is chosen as close as possible
  3888. * to the minimumStep but larger than minimumStep. If minimumStep is not
  3889. * provided, the scale is set to 1 DAY.
  3890. * The minimumStep should correspond with the onscreen size of about 6 characters
  3891. *
  3892. * Alternatively, you can set a scale by hand.
  3893. * After creation, you can initialize the class by executing start(). Then you
  3894. * can iterate from the start date to the end date via next(). You can check if
  3895. * the end date is reached with the function end(). After each step, you can
  3896. * retrieve the current date via get().
  3897. * The class step has scales ranging from milliseconds, seconds, minutes, hours,
  3898. * days, to years.
  3899. *
  3900. * Version: 1.0
  3901. *
  3902. * @param {Date} start The start date, for example new Date(2010, 9, 21)
  3903. * or new Date(2010, 9,21,23,45,00)
  3904. * @param {Date} end The end date
  3905. * @param {int} minimumStep Optional. Minimum step size in milliseconds
  3906. */
  3907. links.Timeline.StepDate = function(start, end, minimumStep) {
  3908. // variables
  3909. this.current = new Date();
  3910. this._start = new Date();
  3911. this._end = new Date();
  3912. this.autoScale = true;
  3913. this.scale = links.Timeline.StepDate.SCALE.DAY;
  3914. this.step = 1;
  3915. // initialize the range
  3916. this.setRange(start, end, minimumStep);
  3917. };
  3918. /// enum scale
  3919. links.Timeline.StepDate.SCALE = { MILLISECOND : 1,
  3920. SECOND : 2,
  3921. MINUTE : 3,
  3922. HOUR : 4,
  3923. DAY : 5,
  3924. MONTH : 6,
  3925. YEAR : 7};
  3926. /**
  3927. * Set a new range
  3928. * If minimumStep is provided, the step size is chosen as close as possible
  3929. * to the minimumStep but larger than minimumStep. If minimumStep is not
  3930. * provided, the scale is set to 1 DAY.
  3931. * The minimumStep should correspond with the onscreen size of about 6 characters
  3932. * @param {Date} start The start date and time.
  3933. * @param {Date} end The end date and time.
  3934. * @param {int} minimumStep Optional. Minimum step size in milliseconds
  3935. */
  3936. links.Timeline.StepDate.prototype.setRange = function(start, end, minimumStep) {
  3937. if (isNaN(start) || isNaN(end)) {
  3938. //throw "No legal start or end date in method setRange";
  3939. return;
  3940. }
  3941. this._start = (start != undefined) ? new Date(start) : new Date();
  3942. this._end = (end != undefined) ? new Date(end) : new Date();
  3943. if (this.autoScale) {
  3944. this.setMinimumStep(minimumStep);
  3945. }
  3946. };
  3947. /**
  3948. * Set the step iterator to the start date.
  3949. */
  3950. links.Timeline.StepDate.prototype.start = function() {
  3951. this.current = new Date(this._start);
  3952. this.roundToMinor();
  3953. };
  3954. /**
  3955. * Round the current date to the first minor date value
  3956. * This must be executed once when the current date is set to start Date
  3957. */
  3958. links.Timeline.StepDate.prototype.roundToMinor = function() {
  3959. // round to floor
  3960. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  3961. switch (this.scale) {
  3962. case links.Timeline.StepDate.SCALE.YEAR:
  3963. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  3964. this.current.setMonth(0);
  3965. case links.Timeline.StepDate.SCALE.MONTH: this.current.setDate(1);
  3966. case links.Timeline.StepDate.SCALE.DAY: this.current.setHours(0);
  3967. case links.Timeline.StepDate.SCALE.HOUR: this.current.setMinutes(0);
  3968. case links.Timeline.StepDate.SCALE.MINUTE: this.current.setSeconds(0);
  3969. case links.Timeline.StepDate.SCALE.SECOND: this.current.setMilliseconds(0);
  3970. //case links.Timeline.StepDate.SCALE.MILLISECOND: // nothing to do for milliseconds
  3971. }
  3972. if (this.step != 1) {
  3973. // round down to the first minor value that is a multiple of the current step size
  3974. switch (this.scale) {
  3975. case links.Timeline.StepDate.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  3976. case links.Timeline.StepDate.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  3977. case links.Timeline.StepDate.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  3978. case links.Timeline.StepDate.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  3979. case links.Timeline.StepDate.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  3980. case links.Timeline.StepDate.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  3981. case links.Timeline.StepDate.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  3982. default: break;
  3983. }
  3984. }
  3985. };
  3986. /**
  3987. * Check if the end date is reached
  3988. * @return {boolean} true if the current date has passed the end date
  3989. */
  3990. links.Timeline.StepDate.prototype.end = function () {
  3991. return (this.current.getTime() > this._end.getTime());
  3992. };
  3993. /**
  3994. * Do the next step
  3995. */
  3996. links.Timeline.StepDate.prototype.next = function() {
  3997. var prev = this.current.getTime();
  3998. // Two cases, needed to prevent issues with switching daylight savings
  3999. // (end of March and end of October)
  4000. if (this.current.getMonth() < 6) {
  4001. switch (this.scale)
  4002. {
  4003. case links.Timeline.StepDate.SCALE.MILLISECOND:
  4004. this.current = new Date(this.current.getTime() + this.step); break;
  4005. case links.Timeline.StepDate.SCALE.SECOND: this.current = new Date(this.current.getTime() + this.step * 1000); break;
  4006. case links.Timeline.StepDate.SCALE.MINUTE: this.current = new Date(this.current.getTime() + this.step * 1000 * 60); break;
  4007. case links.Timeline.StepDate.SCALE.HOUR:
  4008. this.current = new Date(this.current.getTime() + this.step * 1000 * 60 * 60);
  4009. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  4010. var h = this.current.getHours();
  4011. this.current.setHours(h - (h % this.step));
  4012. break;
  4013. case links.Timeline.StepDate.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  4014. case links.Timeline.StepDate.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  4015. case links.Timeline.StepDate.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  4016. default: break;
  4017. }
  4018. }
  4019. else {
  4020. switch (this.scale)
  4021. {
  4022. case links.Timeline.StepDate.SCALE.MILLISECOND:
  4023. this.current = new Date(this.current.getTime() + this.step); break;
  4024. case links.Timeline.StepDate.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  4025. case links.Timeline.StepDate.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  4026. case links.Timeline.StepDate.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  4027. case links.Timeline.StepDate.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  4028. case links.Timeline.StepDate.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  4029. case links.Timeline.StepDate.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  4030. default: break;
  4031. }
  4032. }
  4033. if (this.step != 1) {
  4034. // round down to the correct major value
  4035. switch (this.scale) {
  4036. case links.Timeline.StepDate.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  4037. case links.Timeline.StepDate.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  4038. case links.Timeline.StepDate.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  4039. case links.Timeline.StepDate.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  4040. case links.Timeline.StepDate.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  4041. case links.Timeline.StepDate.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  4042. case links.Timeline.StepDate.SCALE.YEAR: break; // nothing to do for year
  4043. default: break;
  4044. }
  4045. }
  4046. // safety mechanism: if current time is still unchanged, move to the end
  4047. if (this.current.getTime() == prev) {
  4048. this.current = new Date(this._end);
  4049. }
  4050. };
  4051. /**
  4052. * Get the current datetime
  4053. * @return {Date} current The current date
  4054. */
  4055. links.Timeline.StepDate.prototype.getCurrent = function() {
  4056. return this.current;
  4057. };
  4058. /**
  4059. * Set a custom scale. Autoscaling will be disabled.
  4060. * For example setScale(SCALE.MINUTES, 5) will result
  4061. * in minor steps of 5 minutes, and major steps of an hour.
  4062. *
  4063. * @param {links.Timeline.StepDate.SCALE} newScale
  4064. * A scale. Choose from SCALE.MILLISECOND,
  4065. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  4066. * SCALE.DAY, SCALE.MONTH, SCALE.YEAR.
  4067. * @param {int} newStep A step size, by default 1. Choose for
  4068. * example 1, 2, 5, or 10.
  4069. */
  4070. links.Timeline.StepDate.prototype.setScale = function(newScale, newStep) {
  4071. this.scale = newScale;
  4072. if (newStep > 0)
  4073. this.step = newStep;
  4074. this.autoScale = false;
  4075. };
  4076. /**
  4077. * Enable or disable autoscaling
  4078. * @param {boolean} enable If true, autoascaling is set true
  4079. */
  4080. links.Timeline.StepDate.prototype.setAutoScale = function (enable) {
  4081. this.autoScale = enable;
  4082. };
  4083. /**
  4084. * Automatically determine the scale that bests fits the provided minimum step
  4085. * @param {int} minimumStep The minimum step size in milliseconds
  4086. */
  4087. links.Timeline.StepDate.prototype.setMinimumStep = function(minimumStep) {
  4088. if (minimumStep == undefined)
  4089. return;
  4090. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  4091. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  4092. var stepDay = (1000 * 60 * 60 * 24);
  4093. var stepHour = (1000 * 60 * 60);
  4094. var stepMinute = (1000 * 60);
  4095. var stepSecond = (1000);
  4096. var stepMillisecond= (1);
  4097. // find the smallest step that is larger than the provided minimumStep
  4098. if (stepYear*1000 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 1000;}
  4099. if (stepYear*500 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 500;}
  4100. if (stepYear*100 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 100;}
  4101. if (stepYear*50 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 50;}
  4102. if (stepYear*10 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 10;}
  4103. if (stepYear*5 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 5;}
  4104. if (stepYear > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.YEAR; this.step = 1;}
  4105. if (stepMonth*3 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MONTH; this.step = 3;}
  4106. if (stepMonth > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MONTH; this.step = 1;}
  4107. if (stepDay*5 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.DAY; this.step = 5;}
  4108. if (stepDay*2 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.DAY; this.step = 2;}
  4109. if (stepDay > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.DAY; this.step = 1;}
  4110. if (stepHour*4 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.HOUR; this.step = 4;}
  4111. if (stepHour > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.HOUR; this.step = 1;}
  4112. if (stepMinute*15 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MINUTE; this.step = 15;}
  4113. if (stepMinute*10 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MINUTE; this.step = 10;}
  4114. if (stepMinute*5 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MINUTE; this.step = 5;}
  4115. if (stepMinute > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MINUTE; this.step = 1;}
  4116. if (stepSecond*15 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.SECOND; this.step = 15;}
  4117. if (stepSecond*10 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.SECOND; this.step = 10;}
  4118. if (stepSecond*5 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.SECOND; this.step = 5;}
  4119. if (stepSecond > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.SECOND; this.step = 1;}
  4120. if (stepMillisecond*200 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MILLISECOND; this.step = 200;}
  4121. if (stepMillisecond*100 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MILLISECOND; this.step = 100;}
  4122. if (stepMillisecond*50 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MILLISECOND; this.step = 50;}
  4123. if (stepMillisecond*10 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MILLISECOND; this.step = 10;}
  4124. if (stepMillisecond*5 > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MILLISECOND; this.step = 5;}
  4125. if (stepMillisecond > minimumStep) {this.scale = links.Timeline.StepDate.SCALE.MILLISECOND; this.step = 1;}
  4126. };
  4127. /**
  4128. * Snap a date to a rounded value. The snap intervals are dependent on the
  4129. * current scale and step.
  4130. * @param {Date} date the date to be snapped
  4131. */
  4132. links.Timeline.StepDate.prototype.snap = function(date) {
  4133. if (this.scale == links.Timeline.StepDate.SCALE.YEAR) {
  4134. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  4135. date.setFullYear(Math.round(year / this.step) * this.step);
  4136. date.setMonth(0);
  4137. date.setDate(0);
  4138. date.setHours(0);
  4139. date.setMinutes(0);
  4140. date.setSeconds(0);
  4141. date.setMilliseconds(0);
  4142. }
  4143. else if (this.scale == links.Timeline.StepDate.SCALE.MONTH) {
  4144. if (date.getDate() > 15) {
  4145. date.setDate(1);
  4146. date.setMonth(date.getMonth() + 1);
  4147. // important: first set Date to 1, after that change the month.
  4148. }
  4149. else {
  4150. date.setDate(1);
  4151. }
  4152. date.setHours(0);
  4153. date.setMinutes(0);
  4154. date.setSeconds(0);
  4155. date.setMilliseconds(0);
  4156. }
  4157. else if (this.scale == links.Timeline.StepDate.SCALE.DAY) {
  4158. switch (this.step) {
  4159. case 5:
  4160. case 2:
  4161. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  4162. default:
  4163. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  4164. }
  4165. date.setMinutes(0);
  4166. date.setSeconds(0);
  4167. date.setMilliseconds(0);
  4168. }
  4169. else if (this.scale == links.Timeline.StepDate.SCALE.HOUR) {
  4170. switch (this.step) {
  4171. case 4:
  4172. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  4173. default:
  4174. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  4175. }
  4176. date.setSeconds(0);
  4177. date.setMilliseconds(0);
  4178. } else if (this.scale == links.Timeline.StepDate.SCALE.MINUTE) {
  4179. switch (this.step) {
  4180. case 15:
  4181. case 10:
  4182. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  4183. date.setSeconds(0);
  4184. break;
  4185. case 5:
  4186. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  4187. default:
  4188. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  4189. }
  4190. date.setMilliseconds(0);
  4191. }
  4192. else if (this.scale == links.Timeline.StepDate.SCALE.SECOND) {
  4193. switch (this.step) {
  4194. case 15:
  4195. case 10:
  4196. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  4197. date.setMilliseconds(0);
  4198. break;
  4199. case 5:
  4200. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  4201. default:
  4202. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  4203. }
  4204. }
  4205. else if (this.scale == links.Timeline.StepDate.SCALE.MILLISECOND) {
  4206. var step = this.step > 5 ? this.step / 2 : 1;
  4207. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  4208. }
  4209. };
  4210. /**
  4211. * Check if the current step is a major step (for example when the step
  4212. * is DAY, a major step is each first day of the MONTH)
  4213. * @return true if current date is major, else false.
  4214. */
  4215. links.Timeline.StepDate.prototype.isMajor = function() {
  4216. switch (this.scale)
  4217. {
  4218. case links.Timeline.StepDate.SCALE.MILLISECOND:
  4219. return (this.current.getMilliseconds() == 0);
  4220. case links.Timeline.StepDate.SCALE.SECOND:
  4221. return (this.current.getSeconds() == 0);
  4222. case links.Timeline.StepDate.SCALE.MINUTE:
  4223. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  4224. // Note: this is no bug. Major label is equal for both minute and hour scale
  4225. case links.Timeline.StepDate.SCALE.HOUR:
  4226. return (this.current.getHours() == 0);
  4227. case links.Timeline.StepDate.SCALE.DAY:
  4228. return (this.current.getDate() == 1);
  4229. case links.Timeline.StepDate.SCALE.MONTH:
  4230. return (this.current.getMonth() == 0);
  4231. case links.Timeline.StepDate.SCALE.YEAR:
  4232. return false;
  4233. default:
  4234. return false;
  4235. }
  4236. };
  4237. /**
  4238. * Returns formatted text for the minor axislabel, depending on the current
  4239. * date and the scale. For example when scale is MINUTE, the current time is
  4240. * formatted as "hh:mm".
  4241. * @param {Date} [date] custom date. if not provided, current date is taken
  4242. * @return {string} minor axislabel
  4243. */
  4244. links.Timeline.StepDate.prototype.getLabelMinor = function(date, language) {
  4245. // console.log('getLabelMinor', language);
  4246. switch(language){
  4247. case 'fr':
  4248. var MONTHS_SHORT = new Array("Jan", "Fev", "Mar", "Avr", "Mai", "Juin", "Juil", "Aout", "Sep", "Oct", "Nov", "Dec");
  4249. break;
  4250. case 'en':
  4251. default:
  4252. var MONTHS_SHORT = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
  4253. break;
  4254. }
  4255. if (date == undefined) {
  4256. date = this.current;
  4257. }
  4258. switch (this.scale)
  4259. {
  4260. case links.Timeline.StepDate.SCALE.MILLISECOND: return String(date.getMilliseconds());
  4261. case links.Timeline.StepDate.SCALE.SECOND: return String(date.getSeconds());
  4262. case links.Timeline.StepDate.SCALE.MINUTE: return this.addZeros(date.getHours(), 2) + ":" +
  4263. this.addZeros(date.getMinutes(), 2);
  4264. case links.Timeline.StepDate.SCALE.HOUR: return this.addZeros(date.getHours(), 2) + ":" +
  4265. this.addZeros(date.getMinutes(), 2);
  4266. case links.Timeline.StepDate.SCALE.DAY: return String(date.getDate());
  4267. case links.Timeline.StepDate.SCALE.MONTH: return MONTHS_SHORT[date.getMonth()]; // month is zero based
  4268. case links.Timeline.StepDate.SCALE.YEAR: return String(date.getFullYear());
  4269. default: return "";
  4270. }
  4271. };
  4272. /**
  4273. * Returns formatted text for the major axislabel, depending on the current
  4274. * date and the scale. For example when scale is MINUTE, the major scale is
  4275. * hours, and the hour will be formatted as "hh".
  4276. * @param {Date} [date] custom date. if not provided, current date is taken
  4277. * @return {string} major axislabel
  4278. */
  4279. links.Timeline.StepDate.prototype.getLabelMajor = function(date, language) {
  4280. // console.log('getLabelMajor',language);
  4281. switch(language){
  4282. case 'fr':
  4283. var MONTHS = new Array("Janvier", "Février", "Mars","Avril", "Mai", "Juin","Juillet", "Aout", "Septembre","Octobre", "Novembre", "Decembre");
  4284. var DAYS = new Array("Dimanche", "Lundi", "Mardi","mercredi", "Jeudi", "Vendredi", "Samedi");
  4285. break;
  4286. case 'en':
  4287. default:
  4288. var MONTHS = new Array("January", "February", "March","April", "May", "June","July", "August", "September","October", "November", "December");
  4289. var DAYS = new Array("Sunday", "Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday");
  4290. break;
  4291. }
  4292. if (date == undefined) {
  4293. date = this.current;
  4294. }
  4295. switch (this.scale) {
  4296. case links.Timeline.StepDate.SCALE.MILLISECOND:
  4297. return this.addZeros(date.getHours(), 2) + ":" +
  4298. this.addZeros(date.getMinutes(), 2) + ":" +
  4299. this.addZeros(date.getSeconds(), 2);
  4300. case links.Timeline.StepDate.SCALE.SECOND:
  4301. return date.getDate() + " " +
  4302. MONTHS[date.getMonth()] + " " +
  4303. this.addZeros(date.getHours(), 2) + ":" +
  4304. this.addZeros(date.getMinutes(), 2);
  4305. case links.Timeline.StepDate.SCALE.MINUTE:
  4306. return DAYS[date.getDay()] + " " +
  4307. date.getDate() + " " +
  4308. MONTHS[date.getMonth()] + " " +
  4309. date.getFullYear();
  4310. case links.Timeline.StepDate.SCALE.HOUR:
  4311. return DAYS[date.getDay()] + " " +
  4312. date.getDate() + " " +
  4313. MONTHS[date.getMonth()] + " " +
  4314. date.getFullYear();
  4315. case links.Timeline.StepDate.SCALE.DAY:
  4316. return MONTHS[date.getMonth()] + " " +
  4317. date.getFullYear();
  4318. case links.Timeline.StepDate.SCALE.MONTH:
  4319. return String(date.getFullYear());
  4320. default:
  4321. return "";
  4322. }
  4323. };
  4324. /**
  4325. * Add leading zeros to the given value to match the desired length.
  4326. * For example addZeros(123, 5) returns "00123"
  4327. * @param {int} value A value
  4328. * @param {int} len Desired final length
  4329. * @return {string} value with leading zeros
  4330. */
  4331. links.Timeline.StepDate.prototype.addZeros = function(value, len) {
  4332. var str = "" + value;
  4333. while (str.length < len) {
  4334. str = "0" + str;
  4335. }
  4336. return str;
  4337. };
  4338. /** ------------------------------------------------------------------------ **/
  4339. /**
  4340. * Image Loader service.
  4341. * can be used to get a callback when a certain image is loaded
  4342. *
  4343. */
  4344. links.imageloader = (function () {
  4345. var urls = {}; // the loaded urls
  4346. var callbacks = {}; // the urls currently being loaded. Each key contains
  4347. // an array with callbacks
  4348. /**
  4349. * Check if an image url is loaded
  4350. * @param {String} url
  4351. * @return {boolean} loaded True when loaded, false when not loaded
  4352. * or when being loaded
  4353. */
  4354. function isLoaded (url) {
  4355. if (urls[url] == true) {
  4356. return true;
  4357. }
  4358. var image = new Image();
  4359. image.src = url;
  4360. if (image.complete) {
  4361. return true;
  4362. }
  4363. return false;
  4364. }
  4365. /**
  4366. * Check if an image url is being loaded
  4367. * @param {String} url
  4368. * @return {boolean} loading True when being loaded, false when not loading
  4369. * or when already loaded
  4370. */
  4371. function isLoading (url) {
  4372. return (callbacks[url] != undefined);
  4373. }
  4374. /**
  4375. * Load given image url
  4376. * @param {String} url
  4377. * @param {function} callback
  4378. * @param {boolean} sendCallbackWhenAlreadyLoaded optional
  4379. */
  4380. function load (url, callback, sendCallbackWhenAlreadyLoaded) {
  4381. if (sendCallbackWhenAlreadyLoaded == undefined) {
  4382. sendCallbackWhenAlreadyLoaded = true;
  4383. }
  4384. if (isLoaded(url)) {
  4385. if (sendCallbackWhenAlreadyLoaded) {
  4386. callback(url);
  4387. }
  4388. return;
  4389. }
  4390. if (isLoading(url) && !sendCallbackWhenAlreadyLoaded) {
  4391. return;
  4392. }
  4393. var c = callbacks[url];
  4394. if (!c) {
  4395. var image = new Image();
  4396. image.src = url;
  4397. c = [];
  4398. callbacks[url] = c;
  4399. image.onload = function (event) {
  4400. urls[url] = true;
  4401. delete callbacks[url];
  4402. for (var i = 0; i < c.length; i++) {
  4403. c[i](url);
  4404. }
  4405. }
  4406. }
  4407. if (c.indexOf(callback) == -1) {
  4408. c.push(callback);
  4409. }
  4410. }
  4411. return {
  4412. 'isLoaded': isLoaded,
  4413. 'isLoading': isLoading,
  4414. 'load': load
  4415. };
  4416. })();
  4417. /** ------------------------------------------------------------------------ **/
  4418. /**
  4419. * Add and event listener. Works for all browsers
  4420. * @param {Element} element An html element
  4421. * @param {string} action The action, for example "click",
  4422. * without the prefix "on"
  4423. * @param {function} listener The callback function to be executed
  4424. * @param {boolean} useCapture
  4425. */
  4426. links.Timeline.addEventListener = function (element, action, listener, useCapture) {
  4427. if (element.addEventListener) {
  4428. if (useCapture === undefined)
  4429. useCapture = false;
  4430. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  4431. action = "DOMMouseScroll"; // For Firefox
  4432. }
  4433. element.addEventListener(action, listener, useCapture);
  4434. } else {
  4435. element.attachEvent("on" + action, listener); // IE browsers
  4436. }
  4437. };
  4438. /**
  4439. * Remove an event listener from an element
  4440. * @param {Element} element An html dom element
  4441. * @param {string} action The name of the event, for example "mousedown"
  4442. * @param {function} listener The listener function
  4443. * @param {boolean} useCapture
  4444. */
  4445. links.Timeline.removeEventListener = function(element, action, listener, useCapture) {
  4446. if (element.removeEventListener) {
  4447. // non-IE browsers
  4448. if (useCapture === undefined)
  4449. useCapture = false;
  4450. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  4451. action = "DOMMouseScroll"; // For Firefox
  4452. }
  4453. element.removeEventListener(action, listener, useCapture);
  4454. } else {
  4455. // IE browsers
  4456. element.detachEvent("on" + action, listener);
  4457. }
  4458. };
  4459. /**
  4460. * Get HTML element which is the target of the event
  4461. * @param {MouseEvent} event
  4462. * @return {Element} target element
  4463. */
  4464. links.Timeline.getTarget = function (event) {
  4465. // code from http://www.quirksmode.org/js/events_properties.html
  4466. if (!event) {
  4467. event = window.event;
  4468. }
  4469. var target;
  4470. if (event.target) {
  4471. target = event.target;
  4472. }
  4473. else if (event.srcElement) {
  4474. target = event.srcElement;
  4475. }
  4476. if (target.nodeType !== undefined && target.nodeType == 3) {
  4477. // defeat Safari bug
  4478. target = target.parentNode;
  4479. }
  4480. return target;
  4481. };
  4482. /**
  4483. * Stop event propagation
  4484. */
  4485. links.Timeline.stopPropagation = function (event) {
  4486. if (!event)
  4487. event = window.event;
  4488. if (event.stopPropagation) {
  4489. event.stopPropagation(); // non-IE browsers
  4490. }
  4491. else {
  4492. event.cancelBubble = true; // IE browsers
  4493. }
  4494. };
  4495. /**
  4496. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  4497. */
  4498. links.Timeline.preventDefault = function (event) {
  4499. if (!event)
  4500. event = window.event;
  4501. if (event.preventDefault) {
  4502. event.preventDefault(); // non-IE browsers
  4503. }
  4504. else {
  4505. event.returnValue = false; // IE browsers
  4506. }
  4507. };
  4508. /**
  4509. * Retrieve the absolute left value of a DOM element
  4510. * @param {Element} elem A dom element, for example a div
  4511. * @return {number} left The absolute left position of this element
  4512. * in the browser page.
  4513. */
  4514. links.Timeline.getAbsoluteLeft = function(elem) {
  4515. var left = 0;
  4516. while( elem != null ) {
  4517. left += elem.offsetLeft;
  4518. left -= elem.scrollLeft;
  4519. elem = elem.offsetParent;
  4520. }
  4521. if (!document.body.scrollLeft && window.pageXOffset) {
  4522. // FF
  4523. left -= window.pageXOffset;
  4524. }
  4525. return left;
  4526. };
  4527. /**
  4528. * Retrieve the absolute top value of a DOM element
  4529. * @param {Element} elem A dom element, for example a div
  4530. * @return {number} top The absolute top position of this element
  4531. * in the browser page.
  4532. */
  4533. links.Timeline.getAbsoluteTop = function(elem) {
  4534. var top = 0;
  4535. while( elem != null ) {
  4536. top += elem.offsetTop;
  4537. top -= elem.scrollTop;
  4538. elem = elem.offsetParent;
  4539. }
  4540. if (!document.body.scrollTop && window.pageYOffset) {
  4541. // FF
  4542. top -= window.pageYOffset;
  4543. }
  4544. return top;
  4545. };
  4546. /**
  4547. * Check if given object is a Javascript Array
  4548. * @param {*} obj
  4549. * @return {Boolean} isArray true if the given object is an array
  4550. */
  4551. // See http://stackoverflow.com/questions/2943805/javascript-instanceof-typeof-in-gwt-jsni
  4552. links.Timeline.isArray = function (obj) {
  4553. if (obj instanceof Array) {
  4554. return true;
  4555. }
  4556. return (Object.prototype.toString.call(obj) === '[object Array]');
  4557. };