forked from customd/jquery-calendar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.calendar.js
3641 lines (2976 loc) · 130 KB
/
jquery.calendar.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* jQuery calendar plug-in 1.1.0
* Copyright 2012, Digital Fusion
* Licensed under the MIT license.
* http://opensource.teamdf.com/license/
*
* @author Sam Sehnert | [email protected]
* @docs http://opensource.teamdf.com/calendar/docs/
*
* Implement an extremely flexible calendar interface with minimal up front development.
*/
(function($){
"use strict";
// The name of your plugin. This is used to namespace your
// plugin methods, object data, and registerd events.
var plugin_name = 'cal';
var plugin_version = '1.1.0';
var const_month = 'month';
var const_week = 'week';
// Set up the plugin defaults.
// These will be stored in $this.data(plugin_name).settings,
// and can be overwritten by having 'options' passed through
// as the parameter to the init method.
var defaults = {
// Start date and days to display.
startdate : null, // Defaults to new Date() if none of start month/year/monthstodisplay are defined.
daystodisplay : null, // Defaults to 7 if none of start month/year/monthstodisplay are defined.
// Start month,year and months to display.
startmonth : null, // Defaults to (new Date()).getMonth()+1 if monthstodisplay or startyear are defined (we use 1-12, not 0-11).
startyear : null, // Defaults to (new Date()).getFullYear() if monthstodisplay or startmonth are defined.
monthstodisplay : null, // Defaults to 1 if either of startmonth or startyear are defined. TODO: Support more than one month???
// Default colors
defaultcolor : '#255BA1',
invalidcolor : '#888888',
// Date Masks
maskmonthlabel : 'l',
maskeventlabel : 'g:i A',
maskeventlabeldelimiter : '', // –
maskeventlabelend : '', // g:i A
maskdatelabel : 'D, jS',
masktimelabel : {
'00' : 'g:i <\\sp\\a\\n>A<\/\\sp\\a\\n>',
'noon' : '\\N\\O\\O\\N'
},
// Either false, or an array of resources.
resources : false,
// Default height and widths.
minwidth : 130,
minheight : null,
overlapoffset : 15,
// Start and end times for the days
daytimestart : '00:00:00',
daytimeend : '24:00:00',
// Which day the week starts on 1-7, 1 being Sunday, 7 being Saturday.
weekstart : 1,
// Other options...
dragincrement : '15 mins',
gridincrement : '15 mins',
creationsize : '15 mins',
// Global appointment permissions
allowcreation : 'both', // Options, 'both', 'click', 'drag', 'none', false.
allowmove : false, // Enable or disable appointment dragging/moving.
allowresize : false, // Enable or disable appointment resizing.
allowselect : false, // Enable or disable appointment selection.
allowremove : false, // Enable or disable appointment deletion.
allowoverlap : false, // Enable or disable appointment overlaps.
allownotesedit : false, // Enable or disable inline notes editing.
allowhtml : false, // Whether or not to allow users to embed html to appointment data
// Easing effects
easing : {
eventupdate : 'linear',
eventremove : 'linear',
eventeditin : 'linear',
eventeditout : 'linear',
datechange : 'linear'
},
// appointment events.
eventcreate : $.noop,
eventnotesedit : $.noop,
eventremove : $.noop,
eventselect : $.noop,
eventmove : $.noop,
eventresize : $.noop,
// day events
dayclick : $.noop,
daydblclick : $.noop,
// Other events.
onload : $.noop
};
var _private = {
/**
* Attached to several elements to prevent default actions.
*
* @param object e : An object representing the event that triggered this method.
*
* @return void
*/
prevent : function(e){ e.preventDefault(); },
/**
* Get the scrollbar width so we know how much space to allocate.
*
* @return int : Returns the width of the scrollbars in pixels.
*/
scrollbarSize : function() {
// Use the cached version if exists.
if (!_private._scrollbarSize) {
var $doc = $(document.body),
// Set the overflow to hidden, scroll and measure difference.
w =$doc.css({overflow:'hidden'}).width();
w-=$doc.css({overflow:'scroll'}).width();
// Add support for IE in Standards mode.
if(!w) w=$doc.width()-$doc[0].clientWidth;
// Restore the overflow setting.
$doc.css({overflow:''});
// Cache the scrollbar width.
_private._scrollbarSize = w;
}
// Return the width.
return _private._scrollbarSize;
},
// Cache the scrollbar size here.
_scrollbarSize : false,
/**
* Called with a jquery collection of textareas and/or input boxes as 'this'.
* Allows setting a selecting text easily cross browser.
*
* @param int start : The start index in the string that we should select from.
* @param int end : The end index in the string that we should select to.
*
* @return object : Returns the jquery collection that was passed as 'this'.
*/
selectrange : function(start, end) {
return this.each(function() {
if(this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if(this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
},
/**
* Called when the scroll container elment is scrolled. Attached to the onscroll event.
*
* @param object e : An object representing the event that triggered this method.
*
* @return void
*/
onscroll : function(e){
// Called on scroll on the container element.
// Init the variables we'll need.
var $this = $(this),
$parent = $this.parent('.ui-'+plugin_name+'-container'),
scrollX = $this.scrollLeft(),
scrollY = $this.scrollTop(),
data = $parent.data(plugin_name);
if( data ){
// Position the date and timeline at the correct scroll position.
$parent.find('.ui-'+plugin_name+'-timeline').scrollTop(scrollY);
$parent.find('.ui-'+plugin_name+'-dateline').scrollLeft(scrollX);
$parent.find('.ui-'+plugin_name+'-resourceline').scrollLeft(scrollX);
}
},
/**
* Check to see if a number or date is between start and end.
*
* @param mixed item : The item we want to compare with start and end.
* @param mixed start : The beginning of the range we want to check item against.
* @param mixed end : The end of the range we want to check item against.
*
* @return bool : Returns true if item falls between the range start - end.
*/
between : function( item, start, end ){
// If we're dealing with a date.
if( item instanceof Date ){
var timestamp = item.getTime();
return ( timestamp >= start.getTime() && timestamp <= end.getTime() );
// If we're dealing with a number.
} else if( !isNaN( Number( item ) ) ){
return ( item >= start && item <= end );
}
return false;
},
/**
* Check to see if a date range overlaps any part of a second range.
*
* @param date partStart :
* @param date partEnd :
* @param date inStart :
* @param date inEnd :
*
* @return bool : in range, or not.
*/
inrange : function( partStart, partEnd, inStart, inEnd )
{
return !( partEnd.getTime() < inStart.getTime() || partStart.getTime() > inEnd.getTime() );
},
/**
* Called to get a resource at a given index from the settings object.
*
* @param int index : A number representing the index position of the resouce data we want.
* @param object data : Am object containing the plugin data (which we'll use to get the resources).
*
* @return object : The resource object at the given index.
*/
resource : function( index, data ){
var iterator = 0;
if( data.settings.resources !== false ){
for( var i in data.settings.resources ){
if( data.settings.resources.hasOwnProperty( i ) ){
if( iterator == index ){
return { 'id' : i, 'name' : data.settings.resources[i] };
}
iterator++;
}
}
}
return { 'id' : null, 'name' : null };
},
/**
* Called to get the index of a given resource item in the settings object.
*
* @param mixed id : A string or number type which represents the resource key of the resource index we want returned.
* @param object data : An object containing the plugin data (which we'll use to get the resources).
*
* @return int : Returns the index position of the passed resource in the settings object.
*/
resourceIndex : function( id, data ){
var index = 0;
if( data.settings.resources !== false ){
// If we've been given a straight array of keys, then
// we only check against the value.
if( $.isArray( data.settings.resources ) ){
for( var i in data.settings.resources ){
if( data.settings.resources[i] == id ){
return index;
}
index++;
}
} else {
for( var i in data.settings.resources ){
if( data.settings.resources.hasOwnProperty( i ) ){
if( i == id ){
return index;
}
index++;
}
}
}
}
return false;
},
/**
* Get dates for given repetition rules, limited by begin and end dates.
*
* @param object data : The calendar data object.
* @param object event : The event we're generating repetitions for.
*
* @return array : An array of dates which the repetitions fall on.
*/
repetitions : function( data, event )
{
var repeat = [];
console.log( 'Parsing repetitions: ', arguments );
if( 'freq' in event.rules )
{
switch( event.rules.freq )
{
case 'daily' :
case 'weekly' :
case 'yearly' :
break;
}
}
return repeat;
},
/**
* Parse event overlaps for the given event.
*
* @param date begin : The beginning of the range that we want to check for overlaps.
* @param date end : The end of the range that we want to check for overlaps.
* @param object resource : A resource id / label object if we want to check for overlaps on resources too.
*
* @return void;
*/
overlaps : function( begin, end, resource ){
// Get variables that we'll use later.
var $this = $(this),
data = $this.data(plugin_name),
check = [];
// If the calendar has been implemented on this object.
if( data ){
// Store shortcut to events array.
var events = data.cache.events;
// Loop through the cached event data.
for( var uid in events ){
if( // Part of the event falls into the date range that we're checking.
events.hasOwnProperty(uid) &&
(
events[uid].begins < end &&
events[uid].ends > begin &&
events[uid].resource === resource
)
){
// Initialise the overlap object.
events[uid].overlap = {
partial : true,
inset : 0,
count : 0,
items : {},
uid : uid
};
check.push(events[uid]);
}
}
// We only need to check if there is more than one appointment in this time span.
if( check.length > 1 ){
// Sort by start date.
check.sort(function(a,b){ return a.begins.getTime()-b.begins.getTime(); });
// Loop through each of the events that in the date range,
// and build up the overlap settings.
for( var uid1 in check ){
// Make sure this property exists on the object (not a prototyped property).
if( check.hasOwnProperty(uid1) ){
// Loop through each of the events and compare.
for( var uid2 in check ){
// Skip this... we don't need to compare the same object.
if( uid1 === uid2 ) continue;
if( // These object overlap AND they haven't already been flagged as overlapping.
check.hasOwnProperty(uid2) &&
!( check[uid1].overlap.uid in check[uid2].overlap.items ) &&
!( check[uid2].overlap.uid in check[uid1].overlap.items ) &&
(
check[uid1].begins < check[uid2].ends &&
check[uid1].ends > check[uid2].begins &&
check[uid1].resource === check[uid2].resource
)
){
// Store a reference to the overlapped object.
check[uid1].overlap.items[check[uid2].overlap.uid] = check[uid2];
check[uid2].overlap.items[check[uid1].overlap.uid] = check[uid1];
check[uid1].overlap.count++;
check[uid2].overlap.count++;
if( // The begin times are exactly the same...
check[uid1].begins.getTime() == check[uid2].begins.getTime()
){
// Set these up as non-partial overlaps.
check[uid1].overlap.partial = false;
check[uid2].overlap.partial = false;
// Set the new inset for non-partial overlaps.
check[uid2].overlap.inset = check[uid1].overlap.inset+1;
} else if( // The begins time is less than the ends time.
check[uid1].begins.getTime() < check[uid2].begins.getTime()
){
// Increment the inset if this is a partial overlap.
if( check[uid1].overlap.partial ) check[uid2].overlap.inset++;
} else {
// Increment the first appointments inset if this is a partial overlap.
if( check[uid2].overlap.partial ) check[uid1].overlap.inset++;
}
// Update the cache.
data.cache.events[check[uid1].overlap.uid] = check[uid1];
data.cache.events[check[uid2].overlap.uid] = check[uid2];
}
}
}
}
// Update each of the overlap items data.
for( var uid in check ) check[uid].elems.data(plugin_name,check[uid]);
}
// Update the plugin data.
$this.data(plugin_name,data);
}
},
// Error objects used by the calendar
errors : {
eventParse : function( message, event ){
// Create a new error object
var error = new Error( message );
error.type = 'EventParse';
error.event = event;
// Return the error object (usually to throw).
return error;
},
icsParse : function( message, line, value ){
// Create a new error object
var error = new Error( message );
error.type = 'ICSParse';
error.line = line;
error.value = value;
// Return the error object (usually to throw).
return error;
}
},
// Holds the event parser methods.
parse : {
// Patterns for parsing ICS files.
_icalendar : {
// Folded lines: start with a whitespace character */
folds : /^\s(.*)$/,
// Individual entry: name:value */
entry : /^([A-Za-z0-9-]+)((?:;[A-Za-z0-9-]+=(?:"[^"]+"|[^";:,]+)(?:,(?:"[^"]+"|[^";:,]+))*)*):(.*)$/,
// Individual parameter: name=value[,value] */
param : /;([A-Za-z0-9-]+)=((?:"[^"]+"|[^";:,]+)(?:,(?:"[^"]+"|[^";:,]+))*)/g,
// Individual parameter value: value | "value" */
value : /,?("[^"]+"|[^";:,]+)/g,
// Date only field: yyyymmdd */
date : /^(\d{4})(\d\d)(\d\d)$/,
// Date/time field: yyyymmddThhmmss[Z] */
time : /^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)(Z?)$/,
// Date/time range field: yyyymmddThhmmss[Z]/yyyymmddThhmmss[Z] */
range : /^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)(Z?)\/(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)(Z?)$/,
// Timezone offset field: +hhmm */
offset : /^([+-])(\d\d)(\d\d)$/,
// Duration: [+-]PnnW or [+-]PnnDTnnHnnMnnS */
duration : /^([+-])?P(\d+W)?(\d+D)?(T)?(\d+H)?(\d+M)?(\d+S)?$/,
/**
* Parses iCalendar (RFC 2445) RRULE property.
*
* @param string rule : The rule to parse.
*
* @return object : An object describing the repetition rules.
*/
_rrule : function( rule )
{
var parts = rule.split(';'),
props,
rules = {};
// Loop over each rule set.
for( var i in parts )
{
props = parts[i].split('=');
rules[props[0].toLowerCase()] = props[1].toLowerCase();
}
// Return this rule set.
return rules;
}
},
/**
* Parses iCalendar (RFC 2445) into a javascript object.
* @docs http://www.ietf.org/rfc/rfc2445.txt
*
* @param string ics : An iCalendar formatted string.
*
* @return object : Returns a javascript object representing the passed iCalendar format.
*/
icalendar : function( ics )
{
var err = _private.errors.icsParse,
parse = _private.parse._icalendar,
parsing = 'cal_begin',
calendars = [],
lines = ics.replace(/\r\n/g,'\n').split('\n'),
event = null,
calendar = null;
for( var i=lines.length-1; i>0; i-- ){
var matches = parse.folds.exec(lines[i]);
if( matches ){
lines[i-1] += matches[1];
lines[i] = '';
}
}
$.each(lines,function(i,line){
// Skip blank lines.
if( !line ) return;
switch( parsing ){
//case 'done' : If we decide to support more than one calendar in the same ics.
case 'cal_begin' :
// Check for calendar begin.
if( line.indexOf('BEGIN:VCALENDAR')==-1 ) throw new err( 'Expecting BEGIN:VCALENDAR but found \''+line+'\' instead.', i, line );
// Initialise the calendar object.
calendar = {events:[]};
parsing = 'cal_info';
break;
case 'cal_info' :
// Check for a change in parsing mode.
if( line.indexOf('BEGIN:VEVENT')==0 ){ event = { repeat : [], except : [] }; parsing = 'cal_event' };
if( line.indexOf('END:VCALENDAR')==0 ){ calendars.push(calendar); parsing = 'done' };
// If parsing mode has changed, continue with next line.
if( parsing !== 'cal_info' ) return;
break;
case 'cal_event' :
// Check for a change in parsing mode.
if( line.indexOf('END:VEVENT')==0 ){ calendar.events.push(event); parsing = 'cal_info' };
// If parsing mode has changed, continue with next line.
if( parsing !== 'cal_event' ) return;
// Match an entry line.
var matches = parse.entry.exec(line);
if (!matches) {
throw new err( 'Missing entry name.', i, line );
}
// Parse the different date values.
switch( matches[1].toLowerCase() ){
//
// Standard / Basic values.
//
case 'uid' : event.uid = matches[3]; break;
case 'dtstart' : event.begins = $[plugin_name].date(matches[3]); break;
case 'dtend' : event.ends = $[plugin_name].date(matches[3]); break;
case 'summary' : event.notes = matches[3]; break;
//
// Repetition rules.
// TODO: This doesn't conform to the standard, in that we're only parsing one instance of this, and thus missing potential repetitions.
//
case 'rrule' : event.repeats = parse._rrule(matches[3]); break;
case 'exrule' : event.excepts = parse._rrule(matches[3]); break;
//
// Repetition dates.
// TODO: This doesn't confirm to the standard. It assumes each rdate is on it's own row, where the standard allows multiple separated by semi-colon.
//
case 'rdate' : event.repeat.push($[plugin_name].date(matches[3])); break;
case 'exdate' : event.except.push($[plugin_name].date(matches[3])); break;
}
break;
}
});
// Throw an error if we didn't find group end.
if( parsing !== 'done' ) throw new err( 'Unexpected end of file. Expecting END:VCALENDAR.', lines.length, '' );
// Return the parsed calendars.
return calendars.length > 0 ? calendars.pop() : false;
}
},
// Pseudo events used by the calendar.
event : {
/**
* Returns the number of elements required to draw the event.
*
* @param obj values : Should be a fully validated values object, with minimum of begins, ends timestamps.
*
* @return int : The number of elements that should be drawn (the number of days that this element spans, visually).
*/
calculateElementCount : function( values ){
// Return the number of elements that should be drawn for this object.
return Math.ceil( values.cache.begins.getDaysBetween( values.cache.ends, true ) )+1;
},
/**
* Positions an event object on the screen according to its data object.
*
* @param mixed speed : (opt) If int is number of milleseconds for animation, or string 'fast', 'slow'. If undefined, no animation.
* @param string ease : (opt) The easing method to use. See jQuery easing documentation for details.
*
* @return void
*/
update : function( bData, speed, ease ){
// Clone the event element, and set up the values.
var $event = $(this),
values = $event.data(plugin_name),
data = values && values.calendar ? values.calendar.data(plugin_name) : false ;
// Make sure we've got values.
if( data && values ){
// Get each of the event elements.
var $events = values.elems;
// Set the new values.
if( 'begins' in bData ) values.begins = $[plugin_name].date( bData.begins );
if( 'ends' in bData ) values.ends = $[plugin_name].date( bData.ends );
if( 'color' in bData ) values.colors = bData.color ? $[plugin_name].colors.generate( bData.color ) : data.settings.defaultcolor;
if( 'title' in bData ) values.title = bData.title || null;
if( 'notes' in bData ) values.notes = bData.notes || '';
// Exit if there's no need to draw anything.
if( values.ends < data.settings.startdate || values.begins > data.cache.enddate ) return false;
// Work out the cached end date.
values.cache.ends = ( data.cache.enddate < values.ends ? data.cache.enddate.addSeconds(-1) : values.ends );
values.cache.begins = ( data.settings.startdate > values.begins ? data.settings.startdate.copy() : values.begins );
var content_setter = data.settings.allowhtml ? 'html' : 'text' ;
// Set the new value into the event data.
$events.find('pre.details')[content_setter]( values.notes );
$events.find('p.title')[content_setter](
values.title || ( values.begins.format(data.settings.maskeventlabel) +
(
data.settings.maskeventlabelend !== '' ? data.settings.maskeventlabeldelimiter + values.ends.format( data.settings.maskeventlabelend ) : ''
)
)
);
// Save the new values to the element.
$events.data(plugin_name,values);
data.cache.events[values.uid] = values;
values.calendar.data(plugin_name,data);
// Call the positioning code.
_private.draw[data.type].position.apply($events,[speed,ease]);
return true;
}
return false;
},
/**
* Creates an inline edit area for an appointment's description.
*
* @param object e : An object representing the event that triggered this method.
*
* @return void
*/
edit : function( e ){
var $event = e && !$(this).is('div.ui-'+plugin_name+'-event') ? $(this).parents('div.ui-'+plugin_name+'-event') : $(this),
values = $event.data(plugin_name),
data = values && values.calendar ? values.calendar.data(plugin_name) : false ;
if( data && values ){
// Exit now if we don't allow selection.
if( !data.settings.allownotesedit ) return;
// Set the notes base height.
var $notes = $event.find('pre.details'),
noteHeight = $notes.height();
var content_setter = data.settings.allowhtml ? 'html' : 'text' ;
// Now append the textarea.
var $textarea = $('<textarea class="details" />')[content_setter](values.notes||'').css({
boxShadow : 'inset 0px 0px 6px '+values.colors.mainShadow
}).on('mousedown.'+plugin_name,function(e){e.stopPropagation()}).appendTo($event);
if( $event.height() <= 30 ){
// Work out the margin to use.
var marginSide = $event.height() <= 15 ? 4 : 1 ,
marginTop = $event.height() <= 15 ? -1 : 0 ;
// Unbind the double click handler while we're showing the dropdown.
// Also, stop (and complete) the animations on the parent, otherwise
// it can cause some weird animation issues.
$event.unbind('dblclick.'+plugin_name).stop(true,true);
$textarea.css({
marginTop : marginTop,
left : marginSide,
right : marginSide,
height : noteHeight,
border : '1px solid '+values.colors.mainSelected,
borderTop : 'none',
borderTopLeftRadius : 0,
borderTopRightRadius : 0,
opacity : 0,
overflow : 'hidden',
zIndex : 1
}).animate({ height: 45, opacity: 1 },'fast',data.settings.easing.eventeditin,function(){
// Make sure the body is scrollable.
$(this).css('overflow', 'scroll');
// Detatch the PRE element from the DOM.
$notes.detach();
// Trigger the selection now that we've done our animation.
_private.selectrange.apply($textarea,[values.notes.length||0,values.notes.length||0]);
});
} else {
// Detatch the PRE element from the DOM.
$notes.detach();
// Trigger the text selection
_private.selectrange.apply($textarea,[values.notes.length||0,values.notes.length||0]);
}
// Add the blur handler which will set the value when done.
$textarea.blur(function(){
// Store if we've changed the notes or not.
var hasChanged = values.notes != $(this).val(),
$events = values.elems;
// Get the new value, and re-apply it to the event.
values.notes = $(this).val();
// Add the tittle.
$events.attr('title',values.notes||'')
if( $event.height() <= 30 ){
$(this).css('overflow', 'hidden');
$(this).animate({ height: noteHeight, opacity: 0 },125,data.settings.easing.eventeditout,function(){
$(this).remove();
});
} else {
$(this).remove();
}
// Add the original notes back in.
$events.append($notes[content_setter](values.notes||''));
$event.bind('dblclick.'+plugin_name,_private.event.edit);
// Only bother with the callback if the notes have actually changed.
if( hasChanged ){
// Store the new value against the object.
$events.data(plugin_name,values);
data.cache.events[values.uid] = values;
values.calendar.data(plugin_name,data);
// Run the user function with the new notes.
data.settings.eventnotesedit.apply(values.calendar,[values.uid,values,$events]);
};
});
}
// Prevent default if we were given an event.
if( e ){
e.preventDefault();
e.stopPropagation();
}
},
/**
* Triggered when an appointment is clicked for selection, or manually selected via the.
*
* @param mixed speed : (opt) If int is number of milleseconds for animation, or string 'fast', 'slow'. If undefined, defaults to fast.
* @param string ease : (opt) The easing method to use. See jQuery easing documentation for details.
*
* @return void
*/
select : function( speed, ease ){
var $event = $(this),
values = $event.data(plugin_name),
data = values && values.calendar ? values.calendar.data(plugin_name) : false ;
if( data && values ){
// Exit now if we don't allow selection.
if( !data.settings.allowselect ) return;
// Set the default speed if its not already defined.
if( speed === undefined ) speed = 'fast';
// Get the previously seleted element.
var $old = values.calendar.find('div.ui-'+plugin_name+'-event.selected'),
oldvalues = $old.data(plugin_name);
// Were trying to select the same element.
if( oldvalues && ( oldvalues.uid === values.uid ) ) return;
// Run the on select handler, if the user has defined one for this instance.
var veto = data.settings.eventselect.apply(values.calendar,[values.uid,values,$event]);
// Check whether the eventselect handler overrode the selection.
if( veto === undefined || veto ){
// Get each of the elements for this event.
var $events = values.elems;
// Remove the currently selected appointment.
// Add the selected class to the appointment.
$old.removeClass('selected');
$events.addClass('selected');
// The position method will also apply any color changes.
_private.draw[data.type].position.apply($events,[speed, ease]);
_private.draw[data.type].position.apply($old,[speed, ease]);
}
}
},
/**
* Removes an event from the internal data array, and clears it off the calendar layout.
*
* @param object e : An object representing the event that triggered this method.
* @param mixed speed : (opt) If int is number of milleseconds for animation, or string 'fast', 'slow'. If undefined, defaults to fast.
* @param string ease : (opt) The easing method to use. See jQuery easing documentation for details.
*
* @return void
*/
remove : function( e, speed, ease ){
// This method can be called from an event handler OR direct invocation. Get the correct
// element depending on the calling method.
var $event = e ? $(this).closest('div.ui-'+plugin_name+'-event') : $(this),
values = $event.data(plugin_name),
data = values && values.calendar ? values.calendar.data(plugin_name) : false ;
// Make sure we've got valid data and values for the calendar.
if( data && values ){
// Set the default speed if its not already defined.
if( speed === undefined ) speed = 'fast';
if( !ease ) ease = data.settings.easing.eventremove;
// Get the events, check for a user veto, and define the animation end handler.
var $events = values.elems,
veto = data.settings.eventremove.apply(values.calendar,[values.uid,values,$events,e]),
removeEvent = function(){
// Remove the event from the DOM.
// This method also cleans up all data assigned to this event.
$(this).remove();
};
// Check whether the eventremove handler overrode the deletion.
if( veto === undefined || veto ){
// Animate the elements removal.
// Set the base animation properties.
var animation = {
width : 0,
height : 0,
fontSize : '0em',
opacity : .1
};
// Assume that the events will be removed, and remove
// them from the calendars event cache.
delete data.cache.events[values.uid];
values.calendar.data(plugin_name,data);
// Animate slightly differently depending on the
// number of elements that we're displaying.
switch( $events.length ){
// Animating just the one element.
case 1 :
// Set the animation properties.
animation.left = '+='+( $event.width()/2 );
animation.top = '+='+( $event.height()/2 );
// Run the animation.
$event.animate( animation, speed, ease, removeEvent );
break;
// Animating two elements
case 2 :
// Get animation details first.
var $e1 = $events.eq(0),
$e2 = $events.eq(1),
anim1 = $.extend({},animation),
anim2 = $.extend({},animation);
// Set the animation properties.
anim1.left = '+='+( $events.eq(0).width() );
anim1.top = data.cache.dayHeight;
anim2.top = 0;
// Run the animations. Delay the first animation to give time
// for the second one to start (so they animate at the same time).
// TODO: This might be different for other browsers, in which case
// we might just need to ignore the difference in animation time??
$e1.delay(375).animate( anim1, speed, ease, removeEvent );
$e2.animate( anim2, speed, ease, removeEvent );
break;
// Animating three or more elements.
default :
var eventLeft = 0;
// Find the left position to animate to.
$events.each(function(){ eventLeft += $(this).width(); });
// Set the absolute left position (no relative positions for the multiple days.
animation.left = $event.position().left + data.elements.container.scrollLeft() + ( eventLeft/2 );
animation.top = data.cache.dayHeight / 2;
// Animate each of the events.
// Again, the first animation seems to happen before the rest...
// this delay hack ensures they all run together...
// TODO: This might be different for other browsers, in which case
// we might just need to ignore the difference in animation time??
$events.first().delay(375).animate( animation, speed, ease, removeEvent );
$events.filter(':not(:first)').animate( animation, speed, ease, removeEvent );
break;
}
}