forked from ndreckshage/roughdraft.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjquery.roughdraft.0.1.3.js
1520 lines (1340 loc) · 56.4 KB
/
jquery.roughdraft.0.1.3.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 RoughDraft.js Plugin * *
* * Version 0.1.3 * *
* * * *
* * Copyright Nick Dreckshage, licensed GPL & MIT * *
* * https://github.com/ndreckshage/roughdraft.js * *
* * * *
* ****************************************************** *
*********************************************************/
// semi-colon as safety net against concatenated scripts that are improperly closed
;(function($,window,document,undefined){
// undefined to protect against undefined, mutatable global in ECMAScript 3
// window and document as local variables to quicken resolution
/************************************************
* ********************************************* *
* * * *
* * CONSTRUCTOR * *
* * * *
* ********************************************* *
************************************************/
$.RedPen = function(options) {
// called first to create markup
this._create(options)
// then build default functionality
this._init();
}
/************************************************
* ********************************************* *
* * * *
* * DEFAULT SETTINGS * *
* * * *
* ********************************************* *
************************************************/
/**
*
* -- these can/should be overwritten when calling plugin
*
* EXAMPLE OF HOW WIDGET CAN BE CALLED WITH OPTIONS
*
* $(window).roughDraft({
* 'author' : 'baconipsum',
* 'illustrator' : 'placehold',
* });
*
*/
$.RedPen.settings = {
// the site to generate lorem ipsum from, for both jsonp + custom options
author : 'bacon',
// the site to generate placeholder images from
illustrator : 'placehold',
// array ['000', 'fff', 'eaeaea'] of colors the images should be in (will only work for image generators that allow colors)
paintColor : [],
// true if customIpsum library is preferred over jsonp api libraries
customIpsum : false,
// set timeout for JSONP requests
timeout: 5000,
// if customIpsum is true, relative url of library is necessary
customIpsumPath: '/roughdraft.thesaurus.json',
// calendar data formatting (default using PHP formatting)
calendar: {
dayNumber : 'j',
dayNumberZeros : 'd',
dayText : 'l',
dayTextThree : 'D',
monthNumber : 'n',
monthNumberZeros : 'm',
monthText : 'F',
monthTextThree : 'M',
yearNumber : 'Y',
yearNumberTwo : 'y'
},
ajaxType: 'GET'
}
/************************************************
* ********************************************* *
* * * *
* * FULL SCOPE VARIABLES * *
* * * *
* ********************************************* *
************************************************/
$.RedPen.scopeVar = {
dataTag : 'data-',
paragraphType : 'p',
sentenceType : 's',
wordType : 'w',
currencyType : '$',
inputSplit : '/',
rangeSplit : '-'
}
/***********************************************
* ******************************************** *
* * * *
* * PROTOTYPE * *
* * * *
* ******************************************** *
***********************************************/
$.RedPen.prototype = {
/***********************************************
* ******************************************** *
* * * *
* * CORE METHODS * *
* * * *
* ******************************************** *
***********************************************/
/**********************************************
*
* _create method
*
* -- builds markup and sets up the plugin
*
* @param options -- object -- configurations options passed in by constructor
*
**********************************************/
_create: function(options) {
var $draftRepeat = $('[data-draft-repeat]');
// to see an outline of everything, run 'new $.RedPen' in your chrome devtools console
// extends the options to allow them to be overwritten in other files
this.options = $.extend(true, {}, $.RedPen.settings, options);
// sets up the full scope variables
this.scopeVar = $.RedPen.scopeVar;
/**
* set up custom expression so we can filter data-draft-repeat
* and return parent matches only
*/
$.extend($.expr[':'], {
parentsFirst: function(a,i,m){
return $(a).parents(m[3]).length < 1;
}
});
// data-draft-repeat will act as a loop for the div and inner html/js events
// buils the markup, necessary to call this first, and repeat all necessary divs, prior to using other methods
if ($draftRepeat.length) {
this.scanner($draftRepeat);
}
},
/**********************************************
*
* _init method
*
* -- builds default functionality following create
*
**********************************************/
_init : function() {
var $draftText = $('[data-draft-text]'),
$draftImage = $('[data-draft-image]'),
$draftDate = $('[data-draft-date]'),
$draftNumber = $('[data-draft-number]'),
$draftUser = $('[data-draft-user]');
// data-draft-text taps into lorem ipsum library in roughdraft.thesaurus.json
if ($draftText.length) {
this.bookClub();
}
// data-draft-image taps into placeholder image library
if ($draftImage.length) {
this.doodler($draftImage);
}
// data-draft-date generates current/random date in various formats
if ($draftDate.length) {
this.scheduler($draftDate);
}
// data-draft-number generates random numbers
if ($draftNumber.length) {
this.lottery($draftNumber);
}
// data-draft-name generates a random name
if ($draftUser.length) {
this.socialNetwork($draftUser);
}
},
/**********************************************
*
* scanner method
*
* -- handles instances of data-draft-repeat. duplicates and appends them in dom.
* -- mimics server side loops/html duplication
* -- called by data-draft-repeat="3" etc
*
* @param draftRepeat -- object -- data selector passed in through _create
*
**********************************************/
scanner: function($draftRepeat) {
var $self,
$draftRepeatTree,
draftRepeatBare = 'draft-repeat',
repeatCount,
failSafe = 0;
/**
* to repeat the elements in fully recursive way, use a custom selector to grab all top level
* repeats first, and then traverse down the tree, repeating their children nodes
*
* for example --
* <div data-draft-repeat="3">
* <span data-draft-repeat="2">
* </div>
*/
// set the tree to the top level elements that we want to repeat
$draftRepeatTree = $draftRepeat.filter(':parentsFirst([data-draft-repeat])');
/**
* repeat the outer elements first, then remove their properties
* then the children nodes will be set as the new top tree
*/
while ($draftRepeatTree.length > 0) {
$self = $($draftRepeatTree[0]);
repeatCount = $self.data(draftRepeatBare);
/**
* remove the data-draft-repeat-tags from the dom
* NOTE -- this is now important to avoid infinte loops
*/
$self.removeAttr(this.scopeVar.dataTag + draftRepeatBare);
/**
* loop through the count of requested repeats
* -1 on the repeat count because the initial instance of the node still exists
*/
for (var x = 0; x < repeatCount - 1; x++) {
// clone true true (with all deep data + events) to maintain node's JS, and insert into dom
$self.clone(true, true).insertAfter($self);
}
// reset the variables with the data-repeat tags removed, and repeat loop until 0 instances
$draftRepeat = $('[data-draft-repeat]');
$draftRepeatTree = $draftRepeat.filter(':parentsFirst([data-draft-repeat])');
/**
* this is less than ideal, and shouldn't be hit.
* only hit if $self.removeAttr(this.scopeVar.dataTag + draftRepeatBare) not hit
* + $draftRepeat/$draftRepeatTree do no update on each pass
*/
if (failSafe >= 1000) {
console.log('There was an infinite loop error. Please check the loop if you are editing it, or report the' +
' error here -- https://github.com/ndreckshage/roughdraft.js/issues/new');
break;
}
failSafe++;
}
},
/**********************************************
*
* bookClub method
*
* -- handles instances of data-draft-text and inserts as text into calling node
* -- words/sentences/paragraphs can be called by data-draft-text="3p" etc
* -- this uses lorem ipsum apis or json through local library
* -- because of remote api, this is the only method which sends data down to be handled
* -- rather than calling functions to return within the top level method
*
**********************************************/
bookClub: function() {
var opt = this.options,
gps = new Array(),
type = 'json',
url;
/**
* switch on the author to attribute the correct api url
* set url to false if author name entered incorrectly/doesnt exist
* NOTE - bacon ipsum set as default
*/
switch (opt.author) {
case 'lorem':
url = 'http://www.randomtext.me/api/lorem/p-20/40-50';
gps = ['_fixJSON','_fixParagraphs'];
break;
case 'bacon':
url = 'https://baconipsum.com/api/?type=all-meat¶s=20&start-with-lorem=1';
type = 'jsonp';
gps = ['_fixParagraphs'];
break;
case 'hipster':
url = 'http://hipsterjesus.com/api?paras=20&type=hipster-centric&html=false';
gps = ['_fixJSON','_fixParagraphs'];
break;
default:
url = 'https://baconipsum.com/api/?type=all-meat¶s=20&start-with-lorem=1';
type = 'jsonp';
gps = ['_fixParagraphs'];
break;
}
/**
* determine whether the local lorem ipsum library, or jsonp
* send local library to bookstore method ('owning ipsum')
* and jsonp to library method ('borrowing ipsum')
*
* BUILT IN CUSTOM LIBRARY (with author permission)
* + 'lorem'
* + 'tunaipsum.com'
* + 'robotipsum.com'
* + 'lorizzle.nl'
*/
if (opt.customIpsum === true) {
// call the custom library/bookstore method
this._bookStore();
} else if (url && type && gps) {
// send the data to the library method to get json data
this._library(url, type, gps);
} else {
console.log('Please ensure that you have specified a correct remote (JSONP) / local' +
' (thesaurus.roughdraft.json) library, and have correctly set the "customIpsum" option.')
}
},
/**********************************************
*
* doodler method
*
* -- handles instances of data-draft-image and inserts image into calling node
* -- taps into 'lorem ipsum' image galleries
* -- images with width/height can be called by data-draft-image="500/1000" for a 500px wide by 1000px high image
*
* @param draftImage -- object -- data selector passed in through _init
*
**********************************************/
doodler: function($draftImage) {
var $self,
draftImageBare = 'draft-image',
imageData,
imageWidth,
imageHeight,
imageLink;
// this will loop through all dom elements that use the data-draft-image tag
for (var i = 0; i < $draftImage.length; i++) {
// set self to the current dom node being repeated
$self = $($draftImage[i]);
// access the value (ex. data-draft-image="300/500")
imageData = $self.data(draftImageBare);
// check that the value is in the correct format
if (typeof imageData === 'string') {
// split the image dimensions on the backslash making array ['300','500']
imageData = imageData.split('/');
// set the width to the first index and convert to number
imageWidth = parseInt(imageData[0]);
// set the height to the 2nd index and convert
imageHeight = parseInt(imageData[1]);
// if either index is not a number, something went wrong, and set both vars to false
if (isNaN(imageWidth) || isNaN(imageHeight)) {
imageWidth = false;
imageHeight = false;
}
// if all went well, sent the image to the _photoAlbum method to return an image
if (imageWidth && imageHeight) {
// pass in the width and height and it will return a link
imageLink = this._photoAlbum(imageWidth, imageHeight);
// set the link to the img src attribute, hard code the width + height, and remove the data-draft-image tag
$self.attr('src', imageLink)
.attr('width', imageWidth)
.attr('height', imageHeight)
.removeAttr(this.scopeVar.dataTag + draftImageBare);
} else{
// if imageWidth/imageHeight are false, log an error to the console
console.log("Please ensure that you specify Width/Height in the format 250/300 for 250px wide by 300px tall");
}
}
}
},
/**********************************************
*
* scheduler method
*
* -- handles instances of data-draft-date and inserts text into calling node
* -- uses js date engine + some randomization if requested
* -- currently using PHP date structure which can be changed on user preference in plugin options
* -- dates can be called with data-draft-date="M/j/Y" for Jan 23 2013 or "l-r/n-r/y-r" etc for random date (in 23 1 13 format)
* -- returned dates are currently separated with spaces
*
* @param draftDate -- object -- data selector passed in through _init
*
**********************************************/
scheduler: function($draftDate) {
var $self,
draftDateBare = 'draft-date',
dateData,
dateRequest,
formatDate = new String();
// this will loop through all dom elements that use the data-draft-date tag
for (var i = 0; i < $draftDate.length; i++){
// set self to the current dom node being repeated
$self = $($draftDate[i]);
// access the value (ex. data-draft-date="M")
dateData = $self.data(draftDateBare);
// check that the data is interpreted as string
if (typeof dateData === 'string') {
// split the dates on the backslash making array ['D','M-r','Y']
dateData = dateData.split('/');
// count the indexes
dateDataLength = dateData.length;
// loop on the indexes, sending each one to the datePicker method
// before loop, reset date to empty string
formatDate = '';
for (var x = 0; x < dateData.length; x++) {
// the method will return a string of the specific date index, build this into full string
formatDate += this._datePicker(dateData[x]);
// unless it is the last index, follow the date with a space
x != dateData.length - 1 ? formatDate += ' ' : '';
}
// remove the plugin instructions and set the text of the calling node equal to the fully formatted date
$self.removeAttr(this.scopeVar.dataTag + draftDateBare);
$self.text(formatDate);
}
}
},
/**********************************************
*
* lottery method
*
* -- handles instances of data-draft-number and inserts as number into calling node
* -- numbers can be formatted by data-draft-number="$/2-3/0" (ex: Format as money, range of two to three digits, no decimal: $26 or $113)
* -- format (separated by '/'):
* ---- optional. if first char is '$', dollar sign will be appended
* ---- required. include either a range of total digits or a single digit length: "2-3" will return a number of either 2 or 3 digits in length. "4" will return a 4-digit number.
* ---- optional. include the number of decimal places to include. single number: "2-3/4" will return a 2 or 3 digit number with 4 decimal places
*
* @param $draftNumber -- object -- data selector passed in through _init
*
**********************************************/
lottery: function($draftNumber) {
var $self,
draftNumberBare = 'draft-number',
numberData,
formatNumber = new String(),
naturalNumDigits,
naturalNumRange,
decimalNumRange;
// this will loop through all dom elements that use the data-draft-number tag
for (var i = 0; i < $draftNumber.length; i++) {
// set self to the current dom node setting number for
$self = $($draftNumber[i]);
// access the value (ex. data-draft-number="$/2-3/4")
numberData = $self.data(draftNumberBare);
// send the raw data to the parse number format method to return usable object
numberData = this._parseNumberFormat(numberData);
// reset format number string for every loop pass
formatNumber = '';
/**
* begin formatting the formatNumber string based on the numberData object
* if isCurrency is true, prepend number with dollar sign
*/
numberData.isCurrency && (formatNumber += '$');
/**
* if user specifies random range (2-4), send the min/max digits to be randomized
* this will ensure that (for example) a 2 digit, 3 digit and 4 digit will be equally weighted
* rather than a 4 digit number being returned with much higher weight. more likely to be use case intent
*/
naturalNumDigits = this._randomizer(numberData.digitMin, numberData.digitMax);
// send resulting number digit to rangefinder to return min/max object
naturalNumRange = this._rangeFinder(naturalNumDigits);
// the decimal numbers are specified, so skip the digit step, and sent to rangefinder
decimalNumRange = this._rangeFinder(numberData.decimalNumber);
/**
* add to the string with the resulting data from randomizer/rangefinder
* only include decimal if applicable
*/
formatNumber += this._randomizer(naturalNumRange.min, naturalNumRange.max);
numberData.decimalNumber && (formatNumber += '.' + this._randomizer(decimalNumRange.min, decimalNumRange.max));
// add the formatted numbers to the dom and clean up the plugin tags
$self.removeAttr(this.scopeVar.dataTag + draftNumberBare);
$self.text(formatNumber);
}
},
/**********************************************
*
* socialNetwork method
*
* -- handles instances of data-draft-user
* -- makes single request to roughdraftjs.com API
* -- different user data can be requested in format of data-draft-user="full"
* -- full, first, last, email, username, twitter, phone, address, city, state, zip, country
*
* @param $draftUser -- object -- data selector passed in through _init
*
**********************************************/
socialNetwork: function($draftUser) {
var self = this,
opt = this.options;
/**
* make jsonp ajax call to roughdraftjs.com api
* grab 25 records per request
* uses a php port of 'Faker', to generate random content
*/
$.ajax({
url: 'http://www.roughdraftjs.com/api/?number=25',
dataType: 'jsonp',
type: opt.ajaxType,
timeout: opt.timeout,
// if the call was successful, send the data to method to format
success: function(data) {
self._johnDoe(data, $draftUser);
},
error: function() {
console.log('There was an error reaching the JSONP API. Please reload as API is hosted in cloud (PAAS). If issue is persistent, please report on Github');
}
});
},
/***********************************************
* ******************************************** *
* * * *
* * BOOKCLUB PRIVATE METHODS * *
* * * *
* ******************************************** *
***********************************************/
/**********************************************
*
* _library method
*
* -- request to the url to return the api's json/jsonp
* -- initiates the chain of methods by passing the json data through the success function
*
* @param url -- string -- of the selected api
* @param type -- string -- type of data request
* @param gps -- array -- of the path the data needs to follow for formatting
*
**********************************************/
_library: function(url, type, gps) {
var self = this,
opt = this.options;
$.ajax({
url: url,
dataType: type,
type: opt.ajaxType,
timeout: opt.timeout,
// if the call was successful, send the data to method to format
success: function(data) {
if (gps.length > 0) {
self._deweyDecimal(data, gps);
} else {
self._speedReader(data);
}
},
error: function() {
console.log('There was an error reaching the lorem ipsum JSON API. Please confirm the link, or try' +
' a different service if they are down.');
}
});
},
/**********************************************
*
* _bookStore method
*
* -- makes the ajax json call to local custom lorem ipsum library
*
**********************************************/
_bookStore: function() {
var opt = this.options,
self = this;
/**
* make the ajax call based on the default/user option url
* async off since that conflicts with page load
*/
$.ajax({
url: opt.customIpsumPath,
dataType: 'json',
async: false,
type: opt.ajaxType,
success: function(data) {
// send to the speed reader method if ajax returned correctly + author library exists
if (data[opt.author]) {
self._speedReader(data[opt.author]);
} else {
console.log('Please ensure the requested author is in your custom library and is spelled + formatted correctly.');
}
},
error: function() {
console.log('The ajax requested could not be completed. Ensure the relative path to your custom library is accurate.');
}
});
},
/**********************************************
*
* _deweyDecimal method
*
* -- handles where to send the data to be organized correctly
*
* @param data -- object -- of the returned api
* @param gps -- array -- of the path the data needs to follow for formatting
*
**********************************************/
_deweyDecimal: function(data, gps) {
var turnAt = (gps.splice(0,1))[0];
// send to the first index, and send the remaining chain with it
if (turnAt == '_fixJSON') {
this._fixJSON(data, gps);
} else if (turnAt == '_fixParagraphs') {
this._fixParagraphs(data, gps);
}
},
_fixJSON: function(data, gps) {
var opt = this.options,
wrappedPTags = false,
method;
// clean up various json styles to match our format
switch(opt.author) {
case 'lorem':
data = data.text_out;
wrappedPTags = true;
break;
case 'hipster':
data = data.text;
default:
break;
}
/**
* stringify so we can get rid of line feed + carriage return characters
* this took me a while to figure out...charCodeAt returned 13 for enter key
* and couldnt detect it with "\n" or "\r"...
*/
data = JSON.stringify(data);
data = this._replaceWith(data, "\\r", "<BREAK>");
data = this._replaceWith(data, "\\n", "<BREAK>");
// split on the P tags
if (wrappedPTags) {
// opted for this dual approach rather than regex
data = this._replaceWith(data,"<p>","");
data = this._replaceWith(data,"</p>","");
}
// convert back to string
data = JSON.parse(data);
// split on the line breaks and remove any empty index to create actual list of paragraphs
data = data.split("<BREAK>");
data = this._removeEmptyIndexes(data);
// send back to format more or send to get the data processed
if (gps.length > 0) {
this._deweyDecimal(data, gps);
} else {
this._speedReader(data);
}
},
/**********************************************
*
* _fixParagraphs method
*
* -- formats jsonp api data into paragraphs that we can work with
* -- sends to the next method down the chain
*
* @param data -- object -- of jsonp data from callback
*
**********************************************/
_fixParagraphs: function(data, gps) {
var self = this,
paragraphsArray = new Array(),
paragraphArray,
paragraph;
for (var i = 0; i < data.length; i++) {
// set paragraph to the data index
paragraph = data[i];
// call function to take out ellipses so they don't conflict
paragraph = this._replaceWith(paragraph,"...","<ELLIPSES>");
// split returned string on periods to create array
paragraph = paragraph.split('.')
// take out empty indexes
paragraph = this._removeEmptyIndexes(paragraph);
// reformat the sentences for each in paragraph
paragraphArray = new Array();
$.each(paragraph, function(key, value) {
// put ellipses back in
value = self._replaceWith(value,"<ELLIPSES>","...");
// add ending period
value = value + ".";
// kill leading/trailing spaces
value = value.replace(/(^\s+|\s+$)/g, '');
// and add into array
paragraphArray.push(value);
});
// add the paragraph to array of paragraphs
paragraphsArray.push(paragraphArray);
}
// set data back to paragraphsArray for readability
data = paragraphsArray;
// send back to format more or send to get the data processed
if (gps.length > 0) {
this._deweyDecimal(data, gps);
} else {
this._speedReader(data);
}
},
/**********************************************
*
* _speedReader method
*
* -- reconnects the jsonp + custom/local json libraries
* -- determines what to do with each instance of data-draft-text in dom
* -- sends to next method down the chain
*
* @param data -- object -- of the json/jsonp data (full array of all paragraphs)
*
**********************************************/
_speedReader: function(data) {
var $self,
$draftText = $('[data-draft-text]'),
draftTextBare = 'draft-text',
scope = this.scopeVar,
textData,
textCount,
textType;
// this will loop through all dom elements that use the data-draft-text tag
for (var i = 0; i < $draftText.length; i++) {
// set self to the current dom node being repeated
$self = $($draftText[i]);
// access the value (ex. data-draft-text="4s")
textData = $self.data(draftTextBare);
// ensure that the value is correctly returned as string
if (typeof textData === 'string') {
// split the string at the backslash creating an array ['5','p']
textData = textData.split('/');
// take index 0 and convert it into a number. this is the number requested
textCount = parseInt(textData[0]);
// take index 1 and set it to var that will be the type of text requested (word/sentence/paragraphs)
textType = textData[1].toLowerCase();
// if either index is bad, set both vars to false
if (isNaN(textCount) || typeof textType !== 'string') {
textCount = false;
textType = false;
}
// if both indexes are good, then grab the text
if (textCount && textType) {
// remove the data tags from the dom
$self.removeAttr(scope.dataTag + draftTextBare);
// call the method to get lorem ipsum info, passing in the textcount and type
this._inceptionLevelOne($self, data, textCount, textType);
} else {
// if something went wrong, log the error
console.log("Please ensure that you specify Paragraph/Sentence/Word in the format 3/S, for 3 sentences");
}
}
}
},
/**********************************************
*
* _inceptionLevelOne method
*
* -- handles the data on the paragraph level
* -- outputs paragraph calls to the dom
* -- send sentence/words calls to the next method down the chain
*
* @param $self -- object -- current jquery object of requesting node
* @param data -- object -- of the properly formatted paragraphs
* @param textCount -- number -- of paragraphs/sentences/words to return
* @param textType -- string -- whether to return paragraphs/sentences/words
*
**********************************************/
_inceptionLevelOne: function($self, data, textCount, textType) {
var totalParagraphs = data.length,
combinedParagraphs = new Array(),
returnParagraph = new Array(),
lineBreak = new String(),
scope = this.scopeVar,
randomParagraphIndex,
currentParagraph,
lastSentence;
/**
* this method is called by all text types
* if paragraphs are requested, several may need to be returned
* if not called by a paragraph type, only 1 paragraphy needs to be returned
*/
if (textType == scope.paragraphType) {
// return a new random paragraph while the text count is > 0
while (textCount > 0) {
// randomize the paragraph index based on total paragraphs left
randomParagraphIndex = this._randomizer(totalParagraphs);
// pick a paragraph from the array
currentParagraph = data[randomParagraphIndex];
// add line breaks except for final paragraph
if (textCount > 1) {
// add line break to split the paragraphs
lineBreak = '<br/><br/>';
} else {
lineBreak = '';
}
// join the paragraph sentences
currentParagraph = currentParagraph.join(' ') + lineBreak;
// concatenate the current paragraph to the total list within the while loop
returnParagraph = returnParagraph.concat(currentParagraph);
// and decrease the text count for the requested number of paragraphs
textCount--;
}
// join the random together from array
returnParagraph = returnParagraph.join('');
// and insert into dom (use html instead of text for paragraphs to preserve line breaks)
$self.html(returnParagraph);
} else {
// loop through the paragraphs, and combine them into a 1st level array
for (i = 0; i < totalParagraphs; i++) {
currentParagraph = data[i];
combinedParagraphs = combinedParagraphs.concat(currentParagraph);
}
// go a level deeper into sentences + words
this._inceptionLevelTwo($self, combinedParagraphs, textCount, textType);
}
},
/**********************************************
*
* _inceptionLevelTwo method
*
* -- handles the data on the sentence/word level
* -- outputs the resulting data to the dom
*
* @param $self -- object -- current jquery object of requesting node
* @param data -- object -- of the properly formatted sentences (complete array, regardless of paragraph)
* @param textCount -- number -- of sentences/words to return
* @param textType -- string -- whether to return sentences/words
*
**********************************************/
_inceptionLevelTwo: function($self, data, textCount, textType) {
var scope = this.scopeVar,
dataLength = data.length,
randomIndex = this._randomizer(dataLength);
/**
* set up the data context (all sentences for paragraphs, and all words of random paragraph for words)
* and send to the same function to loop through the data
* to be returned to the dom
*/
if (textType == scope.sentenceType) {
var returnSentences;
// call function to turn the data (array of all sentences) into the requested number of sentences
returnSentences = this._inceptionLevelTwoKick(textCount, data, randomIndex);
// insert the sentences into the dom
$self.text(returnSentences);
} else if (textType = scope.wordType) {
var currentSentence = data[randomIndex].split(' '),
index = 0,
returnWords;
// turn the data (array of words from random paragraph) into requested number of words
returnWords = this._inceptionLevelTwoKick(textCount, currentSentence, index);
// insert words into the dom
$self.text(returnWords);
}
},
/**********************************************
*
* _inceptionLevelTwoKick method
*
* -- handles the while loop for sentences/words to format string
*
* @param textCount -- number -- of sentences/words to return
* @param data -- object -- of the properly formatted sentences (complete array, regardless of paragraph)
* @param index -- number -- of where in the array to begin formatting string from
*
* @return context -- string -- combined sentences/words to end up in dom
*
**********************************************/
_inceptionLevelTwoKick: function(textCount, data, index) {
var initialTextCount = textCount,
dataLength = data.length,
currentContext = new String,
context = new String();
/**
* loop through the total requested sentences/words, and
* form them into complete string
*/
while (textCount > 0) {
// except for the first word/sentence, increase index to set to following
if (textCount != initialTextCount) {
index++;
// reset to 0 if we eclipse length of array
if (index >= dataLength) {
index = 0;
}
}
// set the current word/sentence based on the index
currentContext = data[index];
// except for last in set, add a space to the string
if(textCount < dataLength) {
currentContext += ' ';
}
// add the current word/sentence to the total group from loop and decrease count
context += currentContext;
textCount--;
}
// kick the string of words/sentences back
return context;
},
/***********************************************
* ******************************************** *
* * * *
* * DOODLER PRIVATE METHODS * *
* * * *
* ******************************************** *
***********************************************/
/**********************************************
*
* _photoAlbum method
*
* -- handles the logic of where to get the placehold images from
*
* @param width -- number -- of the requested width
* @param height -- number -- of the requested height
*
* @return imageLink -- string -- of the formatted placeholder image link
*
**********************************************/
_photoAlbum: function(width, height) {
var photoAlbum = false,
illustrator = this.options.illustrator,
placeHold = 'placehold',