aboutsummaryrefslogtreecommitdiff
path: root/js/document/mediators/template.js
blob: 015a50ff29ca1c37e284c55d00410c16c64544b6 (plain)
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
/* <copyright>
This file contains proprietary software owned by Motorola Mobility, Inc.<br/>
No rights, expressed or implied, whatsoever to this software are provided by Motorola Mobility, Inc. hereunder.<br/>
(c) Copyright 2011 Motorola Mobility, Inc.  All Rights Reserved.
</copyright> */

////////////////////////////////////////////////////////////////////////
//
var Montage = 			require("montage/core/core").Montage,
	Component = 		require("montage/ui/component").Component,
	TemplateCreator = 	require("node_modules/tools/template/template-creator").TemplateCreator,
	ClassUuid = 		require("js/components/core/class-uuid").ClassUuid;
////////////////////////////////////////////////////////////////////////
//	
exports.TemplateDocumentMediator = Montage.create(Component, {
	////////////////////////////////////////////////////////////////////
	//
	hasTemplate: {
        value: false
    },
    ////////////////////////////////////////////////////////////////////
    //
    getAppTemplatesUrlRegEx: {
        value: function () {
            var regex = new RegExp(chrome.extension.getURL(this.application.ninja.currentDocument.model.views.design.iframe.src.split(chrome.extension.getURL('/'))[1]).replace(/\//gi, '\\\/'), 'gi');
            return regex;
        }
    },
    ////////////////////////////////////////////////////////////////////
    //
    getDataDirectory: {
    	value: function (path) {
    		//TODO: Implement user overwrite
        	return this._getUserDirectory(path+'data/');
    	}
    },
    ////////////////////////////////////////////////////////////////////
    //
    getNinjaDirectory: {
    	value: function (path) {
    		//TODO: Implement user overwrite
    		return this._getUserDirectory(this.getDataDirectory(path)+'ninja/');
    	}
    },
    ////////////////////////////////////////////////////////////////////
    //
    getCanvasDirectory: {
    	value: function (path) {
    		//TODO: Implement user overwrite
    		return this._getUserDirectory(this.getNinjaDirectory(path)+'canvas/');
    	}
    },
    ////////////////////////////////////////////////////////////////////
    //
    _getUserDirectory: {
    	value: function (path) {
    		//Checking for data directory
            var check = this.application.ninja.coreIoApi.fileExists({uri: path}), directory;
            //Creating directory if doesn't exists
            switch (check.status) {
            	case 204: //Exists
            		directory = path;
            		break;
            	case 404: //Doesn't exists
            		directory = this.application.ninja.coreIoApi.createDirectory({uri: path});
            		//Checking for success
            		if (directory.status === 201) {
            			directory = path;
            		} else {
            			//Error
            			directory = null;
            		}
            		break;
            	default: //Error
            		directory = null;
            		break;
            }
            //Returning the path to the directory on disk (null for any error)
            return directory;
    	}
    },
    ////////////////////////////////////////////////////////////////////
    //
    parseHtmlToNinjaTemplate: {
        value: function (html) {
            //Creating temp object to mimic HTML
            var doc = window.document.implementation.createHTMLDocument(), template, docHtmlTag,
            	hackHtml = document.createElement('html'), hackTag;
            //Setting content to temp
            doc.getElementsByTagName('html')[0].innerHTML = html;
            //TODO: Improve this, very bad way of copying attributes (in a pinch to get it working)
            hackHtml.innerHTML = html.replace(/html/gi, 'ninjahtmlhack');
            hackTag = hackHtml.getElementsByTagName('ninjahtmlhack')[0];
            docHtmlTag = doc.getElementsByTagName('html')[0];
            //Looping through the attributes to copy them
            if (hackTag) {
	            for (var m in hackTag.attributes) {
					if (hackTag.attributes[m].value) {
						docHtmlTag.setAttribute(hackTag.attributes[m].name.replace(/ninjahtmlhack/gi, 'html'), hackTag.attributes[m].value.replace(/ninjahtmlhack/gi, 'html'));
					}
				}
			}
			//Garbage collection
            hackHtml = hackTag = null;
            //Creating return object
            return {head: doc.head.innerHTML, body: doc.body.innerHTML, document: doc};
        }
    },
    ////////////////////////////////////////////////////////////////////
    //TODO: Expand to allow more templates, clean up variables
    parseNinjaTemplateToHtml: {
        value: function (saveExternalData, template, ninjaWrapper, libCopyCallback) {
        	//TODO: Improve reference for rootUrl
            var regexRootUrl,
            	rootUrl = this.application.ninja.coreIoApi.rootUrl + escape((this.application.ninja.documentController.documentHackReference.root.split(this.application.ninja.coreIoApi.cloudData.root)[1])),
            	mjsCreator = template.mjsTemplateCreator.create(),
            	mJsSerialization,
            	toremovetags = [],
            	presentNodes,
            	montageTemplate;
            //Creating instance of template creator
            montageTemplate = mjsCreator.initWithDocument(template.document);
            //Setting up expression for parsing URLs
            regexRootUrl = new RegExp(rootUrl.replace(/\//gi, '\\\/'), 'gi');
            //Injecting head and body into old document
            if (montageTemplate._ownerSerialization.length > 0) {
            	template.file.content.document.head.innerHTML = montageTemplate._document.head.innerHTML.replace(regexRootUrl, '');
	            template.file.content.document.body.innerHTML = montageTemplate._document.body.innerHTML.replace(regexRootUrl, '');
	            //
	            mJsSerialization = montageTemplate._ownerSerialization;
            } else {
            	template.file.content.document.head.innerHTML = template.head.innerHTML.replace(regexRootUrl, '');
	            template.file.content.document.body.innerHTML = template.body.innerHTML.replace(regexRootUrl, '');
            }
            //Removes all attributes from node
            function wipeAttributes (node) {
	            for (var f in node.attributes) {
		            node.removeAttribute(node.attributes[f].name);
			    }
            }
            //Copying attributes to maintain same properties as the <body>
            wipeAttributes(template.file.content.document.body);
			for (var n in template.body.attributes) {
				if (template.body.attributes[n].value) {
					template.file.content.document.body.setAttribute(template.body.attributes[n].name, template.body.attributes[n].value);
				}				
			}
			//
            if(template.template) {
                //
                // TODO - Need to handle banner and animation templates.
                //Copying attributes to maintain same properties as <ninja-content>
                var ninjaContentTagMem = template.document.getElementsByTagName('ninja-content')[0], ninjaContentTagDoc = template.file.content.document.getElementsByTagName('ninja-content')[0];
                if (ninjaContentTagMem && ninjaContentTagMem.getAttribute('data-ninja-style') !== null) {
                    ninjaContentTagDoc.setAttribute('style', ninjaContentTagMem.getAttribute('data-ninja-style'));
                    ninjaContentTagDoc.removeAttribute('data-ninja-style');
                } else if (ninjaContentTagMem && ninjaContentTagMem.getAttribute('data-ninja-style') === null) {
                    ninjaContentTagDoc.removeAttribute('style');
                    ninjaContentTagDoc.removeAttribute('data-ninja-style');
                }
                // TODO - clean up into single method
                ninjaContentTagMem = template.document.getElementsByTagName('ninja-viewport')[0], ninjaContentTagDoc = template.file.content.document.getElementsByTagName('ninja-viewport')[0];
                if (ninjaContentTagMem && ninjaContentTagMem.getAttribute('data-ninja-style') !== null) {
                    ninjaContentTagDoc.setAttribute('style', ninjaContentTagMem.getAttribute('data-ninja-style'));
                    ninjaContentTagDoc.removeAttribute('data-ninja-style');
                } else if (ninjaContentTagMem && ninjaContentTagMem.getAttribute('data-ninja-style') === null) {
                    ninjaContentTagDoc.removeAttribute('style');
                    ninjaContentTagDoc.removeAttribute('data-ninja-style');
                }
            } else {
                if (template.body && template.body.getAttribute('data-ninja-style') !== null) {
                    template.file.content.document.body.setAttribute('style', template.body.getAttribute('data-ninja-style'));
                    template.file.content.document.body.removeAttribute('data-ninja-style');
                } else if (template.body && template.body.getAttribute('data-ninja-style') === null) {
                    template.file.content.document.body.removeAttribute('style');
                    template.file.content.document.body.removeAttribute('data-ninja-style');
                }
            }

			wipeAttributes(template.file.content.document.head);
            //Copying attributes to maintain same properties as the <head>
			for (var m in template.document.head.attributes) {
				if (template.document.head.attributes[m].value) {
					template.file.content.document.head.setAttribute(template.document.head.attributes[m].name, template.document.head.attributes[m].value);
				}
			}
            //Copying attributes to maintain same properties as the <html>
			var htmlTagMem = template.document.getElementsByTagName('html')[0], htmlTagDoc = template.file.content.document.getElementsByTagName('html')[0];
			wipeAttributes(htmlTagDoc);
			//
			for (var m in htmlTagMem.attributes) {
				if (htmlTagMem.attributes[m].value) {
					if (htmlTagMem.attributes[m].value.replace(/montage-app-bootstrapping/gi, '').length>0) {
						htmlTagDoc.setAttribute(htmlTagMem.attributes[m].name, htmlTagMem.attributes[m].value.replace(/ montage-app-bootstrapping/gi, ''));
					}
				}
			}
			//
			if (htmlTagMem && htmlTagMem.getAttribute('data-ninja-style') !== null) {
		    	htmlTagDoc.setAttribute('style', htmlTagMem.getAttribute('data-ninja-style'));
		   		htmlTagDoc.removeAttribute('data-ninja-style');
			} else if (htmlTagMem && htmlTagMem.getAttribute('data-ninja-style') === null) {
				htmlTagDoc.removeAttribute('style');
				htmlTagDoc.removeAttribute('data-ninja-style');
			}
            //Getting list of current nodes (Ninja DOM)
            presentNodes = template.file.content.document.getElementsByTagName('*');
            //Looping through nodes to determine origin and removing if not inserted by Ninja
            for (var n in presentNodes) {
	    		//
	    		if (presentNodes[n].getAttribute && presentNodes[n].getAttribute('data-ninja-node') === null) {
		    	 	toremovetags.push(presentNodes[n]);	
	    		} else if (presentNodes[n].getAttribute && presentNodes[n].getAttribute('data-ninja-node') !== null) {
	    			//Removing attribute
		    		presentNodes[n].removeAttribute('data-ninja-node');
	    		}
    		}
            //Getting all CSS (style or link) tags
            var styletags = template.file.content.document.getElementsByTagName('style'),
    			linktags = template.file.content.document.getElementsByTagName('link'),
    			njtemplatetags = template.file.content.document.querySelectorAll('[data-ninja-template]');
    		
    		//Adding to tags to be removed form template
    		for (var f in njtemplatetags) {
    			if (njtemplatetags[f].getAttribute) toremovetags.push(njtemplatetags[f]);
    		}
            //Getting styles tags to be removed from document
            if (styletags.length) {
                for (var j = 0; j < styletags.length; j++) {
                    if (styletags[j].getAttribute) {
                        if (styletags[j].getAttribute('data-ninja-uri') !== null && !styletags[j].getAttribute('data-ninja-template')) {
                            toremovetags.push(styletags[j]);
                        } else if (styletags[j].getAttribute('data-ninja-external-url')) {
                            toremovetags.push(styletags[j]);
                        }
                    }
                }
            }
            //Removing styles tags from document
            for (var h = 0; toremovetags[h]; h++) {
                try {
                    //Checking head first
                    template.file.content.document.head.removeChild(toremovetags[h]);
                } catch (e) {
                    
                }
                try {
                        //Checking body if not in head
                        template.file.content.document.body.removeChild(toremovetags[h]);
                    } catch (e) {
                        //Error, not found!
                    }
            }
            //Removing disabled tags from tags that were not originally disabled by user (Ninja enables all)
            for (var l in linktags) {
                if (linktags[l].getAttribute && linktags[l].getAttribute('disabled')) {//TODO: Use querySelectorAll
                    for (var p = 0; toremovetags[p]; p++) {
                        if (toremovetags[p].getAttribute('href') === linktags[l].getAttribute('href')) {
                            if (!toremovetags[p].getAttribute('data-ninja-disabled')) {
                                linktags[l].removeAttribute('disabled');
                            }
                        }
                    }
                }
            }
            
            
            
            
            
            
            
            
            
            
            
            
            
            //TODO: Make proper CSS method
            
            
            
            //Checking for type of save: styles = <style> only | css = <style> and <link> (all CSS)
            if (template.styles) {
                //Getting all style tags
                var styleCounter = 0,
    				docStyles = template.file.content.document.getElementsByTagName('style');
                //Looping through all style tags
                for (var i in template.styles) {
                    if (template.styles[i].ownerNode) {
                        if (template.styles[i].ownerNode.getAttribute) {
                            //Checking for node not to be loaded from file
                            if (template.styles[i].ownerNode.getAttribute('data-ninja-uri') === null && !template.styles[i].ownerNode.getAttribute('data-ninja-template') && !template.styles[i].ownerNode.getAttribute('data-ninja-external-url')) {
                                if (docStyles[styleCounter] && template.styles[i].ownerNode.getAttribute('data-ninja-node')) {
                                    //Inseting data from rules array into tag as string
                                    docStyles[styleCounter].innerHTML = this.getCssFromRules(template.styles[i].cssRules);
                                    //Syncing <style> tags count since it might be mixed with <link>
                                    styleCounter++;
                                }
                            }
                        }
                    }
                }
            } else if (template.css) {
                //Getting all style and link tags
                var styleCounter = 0,
    				docStyles = template.file.content.document.getElementsByTagName('style'),
    				docLinks = template.file.content.document.getElementsByTagName('link');
                //Removing Ninja Data Attributes
                for (var n in docLinks) {
                    if (docLinks[n].attributes) {
                        for (var m in docLinks[n].attributes) {
                            if (docLinks[n].attributes[m].name && docLinks[n].attributes[m].name.indexOf('data-ninja') !== -1) {
                                docLinks[n].removeAttribute(docLinks[n].attributes[m].name);
                            }
                        }
                    }
                }
                //
                for (var i in template.css) {
                    if (template.css[i].ownerNode) {
                        if (template.css[i].ownerNode.getAttribute) {
                            if (template.css[i].ownerNode.getAttribute('data-ninja-uri') === null && !template.css[i].ownerNode.getAttribute('data-ninja-template')) {//TODO: Use querySelectorAll
                                //Inseting data from rules array into <style> as string
                                if (docStyles[styleCounter] && !template.css[i].ownerNode.getAttribute('data-ninja-external-url') && template.css[i].ownerNode.getAttribute('data-ninja-node')) {
                                    docStyles[styleCounter].innerHTML = this.getCssFromRules(template.css[i].cssRules);
                                    styleCounter++;
                                }
                            } else if (!template.css[i].ownerNode.getAttribute('data-ninja-template')) {
                                //Checking for attributes to be added to tag upon saving
                                for (var k in docLinks) {
                                    if (docLinks[k].getAttribute) {
                                        if (docLinks[k].getAttribute('href') && ('/' + docLinks[k].getAttribute('href')) === template.css[i].ownerNode.getAttribute('data-ninja-file-url')) {
                                            for (var l in template.css[i].ownerNode.attributes) {
                                                if (template.css[i].ownerNode.attributes[l].value) {
                                                    if (template.css[i].ownerNode.attributes[l].name.indexOf('data-ninja') != -1) {
                                                        //Ninja attribute...
                                                    } else {
                                                        docLinks[k].setAttribute(template.css[i].ownerNode.attributes[l].name, template.css[i].ownerNode.attributes[l].value);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                ///////////////////////////////////////////////////////////////////////////////////////////
                                ///////////////////////////////////////////////////////////////////////////////////////////


                                var cleanedCss,
    								dirtyCss = this.getCssFromRules(template.css[i].cssRules),
    								fileUrl = template.css[i].ownerNode.getAttribute('data-ninja-file-url'),
    								fileRootUrl = this.application.ninja.coreIoApi.rootUrl + fileUrl.split(fileUrl.split('/')[fileUrl.split('/').length - 1])[0],
    								cleanedCss = dirtyCss.replace(/(\b(?:(?:https?|ftp|file|[A-Za-z]+):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$]))/gi, parseNinjaUrl.bind(this));

                                function parseNinjaUrl(url) {
                                    if (url.indexOf(this.application.ninja.coreIoApi.rootUrl) !== -1) {
                                        return this.getUrlfromNinjaUrl(url, fileRootUrl, fileUrl);
                                    } else {
                                        return url;
                                    }
                                }

                                ///////////////////////////////////////////////////////////////////////////////////////////
                                ///////////////////////////////////////////////////////////////////////////////////////////




                                //Saving data from rules array converted to string into <link> file
                                var save = this.application.ninja.ioMediator.fio.saveFile({ uri: template.css[i].ownerNode.getAttribute('data-ninja-uri'), contents: cleanedCss });
                                //TODO: Add error handling for saving files
                            }
                        }
                    }
                }
            }
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            //
            var webgltag, webgllibtag, webglrdgetag, mjstag, mjslibtag, matchingtags = [],
            	scripts = template.file.content.document.getElementsByTagName('script'),
            	libsobserver = {montage: false, canvas: false, montageCopied: null, canvasCopied: null, callback: libCopyCallback, dispatched: false};
            //TODO: Clean up, this is messy
            if (mJsSerialization) libsobserver.montage = true;
            if (template.webgl && template.webgl.length > 1) libsobserver.canvas = true;
            //
            for (var i in scripts) {
            	if (scripts[i].getAttribute) {
               		if (scripts[i].getAttribute('data-ninja-canvas') !== null) {//TODO: Use querySelectorAll
               			matchingtags.push(scripts[i]);
                    }
                    if (scripts[i].getAttribute('data-ninja-canvas-lib') !== null) {
                        webgllibtag = scripts[i]; // TODO: Add logic to delete unneccesary tags
                    }
                    if (scripts[i].getAttribute('data-ninja-canvas-rdge') !== null) {
               	        webglrdgetag = scripts[i]; // TODO: Add logic to delete unneccesary tags
                    }
                    if (scripts[i].getAttribute('type') === 'text/montage-serialization') {
                        mjstag = scripts[i]; // TODO: Add logic to delete unneccesary tags
                    }
                    if (scripts[i].getAttribute('data-mjs-lib') !== null) {
                     	mjslibtag = scripts[i]; // TODO: Add logic to delete unneccesary tags
                    }
                }
            }
            
            
            
            
            //TODO: Make proper webGL/Canvas method
            
            
            //Checking for webGL elements in document
            if (template.webgl && template.webgl.length > 1) {//TODO: Should be length 0, hack for a temp fix
                var rdgeDirName, rdgeVersion, cvsDataDir = this.getCanvasDirectory(template.file.root), fileCvsDir, fileCvsDirAppend, cvsDirCounter = 1, fileOrgDataSrc;
                //
                if (cvsDataDir && !matchingtags.length && !webgllibtag) {
                
                	if (template.libs.canvasId) {
	                	libsobserver.canvasId = template.libs.canvasId;
                	} else {
	                	libsobserver.canvasId = ClassUuid.generate();
                	}
                	
                	//Creating data directory, will include materials at a later time
                	fileCvsDir = cvsDataDir+template.file.name.split('.'+template.file.extension)[0]+'_'+libsobserver.canvasId;
                	
                	if (!this._getUserDirectory(fileCvsDir)) {
                		//TODO: create proper logic not to overwrite files
                		console.log('error');
                	}
                	
                	fileCvsDir += '/';
                } else if (webgllibtag && webgllibtag.getAttribute && webgllibtag.getAttribute('data-ninja-canvas-json') !== null) {
                	fileOrgDataSrc = template.file.root+webgllibtag.getAttribute('data-ninja-canvas-json');
                }
                //Copy webGL library if needed
                for (var i in this.application.ninja.coreIoApi.ninjaLibrary.libs) {
                    //Checking for RDGE library to be available
                    if (this.application.ninja.coreIoApi.ninjaLibrary.libs[i].name === 'RDGE') {
                        rdgeDirName = (this.application.ninja.coreIoApi.ninjaLibrary.libs[i].name + this.application.ninja.coreIoApi.ninjaLibrary.libs[i].version).toLowerCase();
                        rdgeVersion = this.application.ninja.coreIoApi.ninjaLibrary.libs[i].version;
                        this.application.ninja.coreIoApi.ninjaLibrary.copyLibToCloud(template.file.root, rdgeDirName, function(result) {libsobserver.canvasCopied = result; this.libCopied(libsobserver);}.bind(this));
                    } else {
                        //TODO: Error handle no available library to copy
                    }
                }
                //
                if (matchingtags.length) {
                    if (matchingtags.length === 1) {
                        webgltag = matchingtags[0];
                    } else {
                        //TODO: Add logic to handle multiple tags, perhaps combine to one
                        webgltag = matchingtags[matchingtags.length - 1]; //Saving all data to last one...
                    }
                }
                //TODO: Add check for file needed
                if (!webglrdgetag) {
                    webglrdgetag = template.file.content.document.createElement('script');
                    webglrdgetag.setAttribute('type', 'text/javascript');
                    webglrdgetag.setAttribute('src', rdgeDirName + '/rdge-compiled.js');
                    webglrdgetag.setAttribute('data-ninja-canvas-rdge', 'true');
                    if (ninjaWrapper) {
                    	template.file.content.document.body.getElementsByTagName('ninja-content')[0].appendChild(webglrdgetag);
                    } else {
                    	template.file.content.document.head.appendChild(webglrdgetag);
                    }
                }
                //
                if (!webgllibtag) {
                    webgllibtag = template.file.content.document.createElement('script');
                    webgllibtag.setAttribute('type', 'text/javascript');
                    webgllibtag.setAttribute('src', rdgeDirName + '/canvas-runtime.js');
                    webgllibtag.setAttribute('data-ninja-canvas-lib', 'true');
                    if (ninjaWrapper) {
                    	template.file.content.document.body.getElementsByTagName('ninja-content')[0].appendChild(webgllibtag);
                    } else {
                    	template.file.content.document.head.appendChild(webgllibtag);
                    }
                }
                //
                if (!webgltag && !fileCvsDir && !fileOrgDataSrc) {
                    webgltag = template.file.content.document.createElement('script');
                    webgltag.setAttribute('data-ninja-canvas', 'true');
                    if (ninjaWrapper) {
                    	template.file.content.document.body.getElementsByTagName('ninja-content')[0].appendChild(webgltag);
                    } else {
	                    template.file.content.document.head.appendChild(webgltag);
	                }
                }
                
                //TODO: Decide if this should be over-writter or only written on creation
                var rootElement = 'document.body'; //TODO: Set actual root element
                
                //TODO: This data should be saved to a JSON file eventually
                var json = '\n({\n\t"version": "' + rdgeVersion + '",\n\t"directory": "' + rdgeDirName + '/",\n\t"data": [';
                //Looping through data to create escaped array
                for (var j = 0; template.webgl[j]; j++) {
                    if (j === 0) {
                    	json += '\n\t\t\t"' + escape(template.webgl[j]) + '"';
                    } else {
                    	json += ',\n\t\t\t"' + escape(template.webgl[j]) + '"';
                    }
                }
                //Closing array (make-shift JSON string to validate data in <script> tag)
                json += '\n\t\t]\n})\n';
                //Setting string in tag
                if (fileCvsDir || fileOrgDataSrc) {
                	//
                	var cvsDataFilePath, cvsDataFileUrl, cvsDataFileCheck, cvsDataFileOperation;
                	//
                	if (fileOrgDataSrc) {
	                	cvsDataFilePath = fileOrgDataSrc;
                	} else {
	                	cvsDataFilePath = fileCvsDir+'data.json';
                	}
                	//
                	cvsDataFileUrl = this.getNinjaPropUrlRedirect(cvsDataFilePath.split(this.application.ninja.coreIoApi.cloudData.root+'/')[1]),
                	cvsDataFileCheck = this.application.ninja.coreIoApi.fileExists({uri: cvsDataFilePath}),
                	//Setting the local path to the JSON file
                	webgllibtag.setAttribute('data-ninja-canvas-json', this.application.ninja.coreIoApi.rootUrl+'/'+cvsDataFileUrl);
                	webgllibtag.setAttribute('data-ninja-canvas-libpath', rdgeDirName);
                	//
                	if (cvsDataFileCheck.status === 404 || cvsDataFileCheck.status === 204) {
                		//Saving file
                		cvsDataFileOperation = this.application.ninja.ioMediator.fio.saveFile({uri: cvsDataFilePath, contents: json});
                	} else {
                		//Error
                	}
                	
                	
                } else {
                	webgllibtag.setAttribute('data-ninja-canvas-libpath', rdgeDirName);
                	webgltag.innerHTML = json;
                }
            }
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            //TODO: Make proper Montage method
            
			//Checking for Montage
			if (mJsSerialization) {
				//Copy Montage library if needed
                for (var i in this.application.ninja.coreIoApi.ninjaLibrary.libs) {
                    //Checking for Montage library to be available
                    if (this.application.ninja.coreIoApi.ninjaLibrary.libs[i].name === 'Montage') {
                        mjsDirName = (this.application.ninja.coreIoApi.ninjaLibrary.libs[i].name + this.application.ninja.coreIoApi.ninjaLibrary.libs[i].version).toLowerCase();
                        mjsVersion = this.application.ninja.coreIoApi.ninjaLibrary.libs[i].version;
                        this.application.ninja.coreIoApi.ninjaLibrary.copyLibToCloud(template.file.root, mjsDirName, function(result) {libsobserver.montageCopied = result; this.libCopied(libsobserver);}.bind(this));
                        
                        
                        
                        //TODO: Fix to allow no overwrite and nested locations
                        var mjsCheck, mjsPath = template.file.root + 'package.json';
                        mjsCheck = this.application.ninja.coreIoApi.fileExists({uri: mjsPath});
                        //
                        if (!mjsCheck || mjsCheck.status !== 204) {
	                        var packjson = this.application.ninja.coreIoApi.createFile({ uri: mjsPath, contents: '{"mappings": {\n\t\t"montage": "' + mjsDirName + '/montage/",\n\t\t"montage-google": "' + mjsDirName + '/montage-google/"\n\t}\n}' });
                        } else {
                        	//Already exists
                        }
                        
                        
                        
                    } else {
                        //TODO: Error handle no available library to copy
                    }
                }
                //
                if (!mjslibtag) {
                    mjslibtag = template.file.content.document.createElement('script');
                    mjslibtag.setAttribute('type', 'text/javascript');
                    mjslibtag.setAttribute('src', mjsDirName + '/montage/montage.js');
                    mjslibtag.setAttribute('data-package', '.');
                    mjslibtag.setAttribute('data-mjs-lib', 'true');
                    if (ninjaWrapper) {
                    	template.file.content.document.body.getElementsByTagName('ninja-content')[0].appendChild(mjslibtag);
                    } else {
                    	template.file.content.document.head.appendChild(mjslibtag);
                    }
                    
                }
                //
                if (!mjstag) {
                    mjstag = template.file.content.document.createElement('script');
                    mjstag.setAttribute('type', 'text/montage-serialization');
                    if (ninjaWrapper) {
                    	template.file.content.document.body.getElementsByTagName('ninja-content')[0].appendChild(mjstag);
                    } else {
                    	template.file.content.document.head.appendChild(mjstag);
                    }
                    
                }
                //
                mjstag.innerHTML = mJsSerialization;
                mjsCreator = null;
			}