6839a166af47f195b71b006a028c61465bb0006c
[Plinn.git] / skins / ajax_scripts / fragment_importer.js
1 // (c) BenoƮt PIN 2006-2007
2 // http://plinn.org
3 // Licence GPL
4 //
5 //
6
7 var FragmentImporter;
8
9 (function(){
10
11 var isTextMime = /^text\/.+/i;
12
13 FragmentImporter = function(url, onAfterPopulate) {
14 var thisImporter = this;
15 this.url = url;
16 this.onAfterPopulate = (!onAfterPopulate) ? function(){return;} : onAfterPopulate;
17 };
18
19 FragmentImporter.prototype._load = function(url) {
20 var req = new XMLHttpRequest();
21 var thisImporter = this;
22 req.onreadystatechange = function() {
23 switch (req.readyState) {
24 case 1 :
25 showProgressImage();
26 break;
27 case 2 :
28 try {
29 if (! isTextMime.exec(req.getResponseHeader('Content-Type'))) {
30 req.onreadystatechange = null;
31 req.abort();
32 hideProgressImage();
33 window.location.href = thisImporter._fallBackUrl;
34 }
35 }
36 catch(e){}
37 break;
38 case 4 :
39 hideProgressImage();
40 if (req.status === 200) {
41 thisImporter.populateBaseElement(req); }
42 else {
43 alert('Error: ' + req.status); }
44 break;
45 }
46 };
47
48 req.open("GET", url, true);
49 req.send(null);
50 };
51
52 FragmentImporter.prototype.load = function(fallBackUrl) {
53 if (fallBackUrl) {
54 this._fallBackUrl = fallBackUrl; }
55 else {
56 this._fallBackUrl = this.url; }
57 this._load(this.url);
58 };
59
60 FragmentImporter.prototype.useMacro = function(template, macro, fragmentId, queryString) {
61 var url = this.url + "/use_macro?template=" + template + "&macro=" + macro + "&fragmentId=" + fragmentId;
62 if (queryString) {
63 url += '&' + queryString; }
64 this._load(url);
65 };
66
67
68 FragmentImporter.prototype.populateBaseElement = function(req) {
69 // :( IE : innerHTML is read-only for these tags:
70 // COL, COLGROUP, FRAMESET, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR
71 var contentType = req.getResponseHeader('Content-Type');
72 if (! isTextMime.exec(contentType)) {
73 window.location.href = this._fallBackUrl;
74 return;
75 }
76 if (contentType.indexOf('text/xml') !== -1) {
77 var fragments = req.responseXML.documentElement.childNodes;
78 var fragment, dest, scripts, i, j;
79 for (i=0 ; i < fragments.length ; i++) {
80 fragment = fragments[i];
81 if (fragment.nodeName === 'fragment') {
82 dest = document.getElementById(fragment.getAttribute('id'));
83 if(dest) {
84 dest.innerHTML = fragment.firstChild.nodeValue;
85 scripts = dest.getElementsByTagName('script');
86 for (j=0 ; j < scripts.length ; j++) {
87 globalScriptRegistry.loadScript(scripts[j]); }
88 }
89 }
90 }
91 }
92 this.onAfterPopulate();
93 };
94
95 }());