Solr optionnel.
[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 element, dest, scripts, i, j;
79 for (i=0 ; i < fragments.length ; i++) {
80 element = fragments[i];
81 switch (element.nodeName) {
82 case 'fragment' :
83 dest = document.getElementById(element.getAttribute('id'));
84 if(dest) {
85 dest.innerHTML = element.firstChild.nodeValue;
86 scripts = dest.getElementsByTagName('script');
87 for (j=0 ; j < scripts.length ; j++) {
88 globalScriptRegistry.loadScript(scripts[j]); }
89 }
90 break;
91 case 'base' :
92 var headBase = document.getElementsByTagName('base');
93 if (headBase.length > 0) {
94 headBase[0].setAttribute('href', element.getAttribute('href'));
95 }
96 else {
97 headBase = document.createElement('base');
98 headBase.setAttribute('href', element.getAttribute('href'));
99 document.head.appendChild(headBase);
100 }
101 break;
102 }
103 }
104 }
105 this.onAfterPopulate();
106 };
107
108 }());