86f911a8a460cdadc4f3482adb6f5b5ba5726fba
[koha.git] / koha-tmpl / intranet-tmpl / prog / en / lib / yui / get / get-debug.js
1 /*
2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
5 version: 2.8.0r4
6 */
7 /**
8  * Provides a mechanism to fetch remote resources and
9  * insert them into a document
10  * @module get
11  * @requires yahoo
12  */
13
14 /**
15  * Fetches and inserts one or more script or link nodes into the document 
16  * @namespace YAHOO.util
17  * @class YAHOO.util.Get
18  */
19 YAHOO.util.Get = function() {
20
21     /**
22      * hash of queues to manage multiple requests
23      * @property queues
24      * @private
25      */
26     var queues={}, 
27         
28     /**
29      * queue index used to generate transaction ids
30      * @property qidx
31      * @type int
32      * @private
33      */
34         qidx=0, 
35         
36     /**
37      * node index used to generate unique node ids
38      * @property nidx
39      * @type int
40      * @private
41      */
42         nidx=0, 
43
44         // ridx=0,
45
46         // sandboxFrame=null,
47
48     /**
49      * interal property used to prevent multiple simultaneous purge 
50      * processes
51      * @property purging
52      * @type boolean
53      * @private
54      */
55         purging=false,
56
57         ua=YAHOO.env.ua, 
58         
59         lang=YAHOO.lang;
60     
61     /** 
62      * Generates an HTML element, this is not appended to a document
63      * @method _node
64      * @param type {string} the type of element
65      * @param attr {string} the attributes
66      * @param win {Window} optional window to create the element in
67      * @return {HTMLElement} the generated node
68      * @private
69      */
70     var _node = function(type, attr, win) {
71         var w = win || window, d=w.document, n=d.createElement(type);
72
73         for (var i in attr) {
74             if (attr[i] && YAHOO.lang.hasOwnProperty(attr, i)) {
75                 n.setAttribute(i, attr[i]);
76             }
77         }
78
79         return n;
80     };
81
82     /**
83      * Generates a link node
84      * @method _linkNode
85      * @param url {string} the url for the css file
86      * @param win {Window} optional window to create the node in
87      * @return {HTMLElement} the generated node
88      * @private
89      */
90     var _linkNode = function(url, win, attributes) {
91
92         var o = {
93             id:   "yui__dyn_" + (nidx++),
94             type: "text/css",
95             rel:  "stylesheet",
96             href: url
97         };
98
99         if (attributes) {
100             lang.augmentObject(o, attributes);
101         }
102
103         return _node("link", o, win);
104     };
105
106     /**
107      * Generates a script node
108      * @method _scriptNode
109      * @param url {string} the url for the script file
110      * @param win {Window} optional window to create the node in
111      * @return {HTMLElement} the generated node
112      * @private
113      */
114     var _scriptNode = function(url, win, attributes) {
115         var o = {
116             id:   "yui__dyn_" + (nidx++),
117             type: "text/javascript",
118             src:  url
119         };
120
121         if (attributes) {
122             lang.augmentObject(o, attributes);
123         }
124
125         return _node("script", o, win);
126     };
127
128     /**
129      * Returns the data payload for callback functions
130      * @method _returnData
131      * @private
132      */
133     var _returnData = function(q, msg) {
134         return {
135                 tId: q.tId,
136                 win: q.win,
137                 data: q.data,
138                 nodes: q.nodes,
139                 msg: msg,
140                 purge: function() {
141                     _purge(this.tId);
142                 }
143             };
144     };
145
146     var _get = function(nId, tId) {
147         var q = queues[tId],
148             n = (lang.isString(nId)) ? q.win.document.getElementById(nId) : nId;
149         if (!n) {
150             _fail(tId, "target node not found: " + nId);
151         }
152
153         return n;
154     };
155
156     /*
157      * The request failed, execute fail handler with whatever
158      * was accomplished.  There isn't a failure case at the
159      * moment unless you count aborted transactions
160      * @method _fail
161      * @param id {string} the id of the request
162      * @private
163      */
164     var _fail = function(id, msg) {
165         YAHOO.log("get failure: " + msg, "warn", "Get");
166         var q = queues[id];
167         // execute failure callback
168         if (q.onFailure) {
169             var sc=q.scope || q.win;
170             q.onFailure.call(sc, _returnData(q, msg));
171         }
172     };
173
174     /**
175      * The request is complete, so executing the requester's callback
176      * @method _finish
177      * @param id {string} the id of the request
178      * @private
179      */
180     var _finish = function(id) {
181         YAHOO.log("Finishing transaction " + id);
182         var q = queues[id];
183         q.finished = true;
184
185         if (q.aborted) {
186             var msg = "transaction " + id + " was aborted";
187             _fail(id, msg);
188             return;
189         }
190
191         // execute success callback
192         if (q.onSuccess) {
193             var sc=q.scope || q.win;
194             q.onSuccess.call(sc, _returnData(q));
195         }
196     };
197
198     /**
199      * Timeout detected
200      * @method _timeout
201      * @param id {string} the id of the request
202      * @private
203      */
204     var _timeout = function(id) {
205         YAHOO.log("Timeout " + id, "info", "get");
206         var q = queues[id];
207         if (q.onTimeout) {
208             var sc=q.scope || q;
209             q.onTimeout.call(sc, _returnData(q));
210         }
211     };
212
213     /**
214      * Loads the next item for a given request
215      * @method _next
216      * @param id {string} the id of the request
217      * @param loaded {string} the url that was just loaded, if any
218      * @private
219      */
220     var _next = function(id, loaded) {
221         YAHOO.log("_next: " + id + ", loaded: " + loaded, "info", "Get");
222         var q = queues[id];
223
224         if (q.timer) {
225             // Y.log('cancel timer');
226             q.timer.cancel();
227         }
228
229         if (q.aborted) {
230             var msg = "transaction " + id + " was aborted";
231             _fail(id, msg);
232             return;
233         }
234
235         if (loaded) {
236             q.url.shift(); 
237             if (q.varName) {
238                 q.varName.shift(); 
239             }
240         } else {
241             // This is the first pass: make sure the url is an array
242             q.url = (lang.isString(q.url)) ? [q.url] : q.url;
243             if (q.varName) {
244                 q.varName = (lang.isString(q.varName)) ? [q.varName] : q.varName;
245             }
246         }
247
248         var w=q.win, d=w.document, h=d.getElementsByTagName("head")[0], n;
249
250         if (q.url.length === 0) {
251             // Safari 2.x workaround - There is no way to know when 
252             // a script is ready in versions of Safari prior to 3.x.
253             // Adding an extra node reduces the problem, but doesn't
254             // eliminate it completely because the browser executes
255             // them asynchronously. 
256             if (q.type === "script" && ua.webkit && ua.webkit < 420 && 
257                     !q.finalpass && !q.varName) {
258                 // Add another script node.  This does not guarantee that the
259                 // scripts will execute in order, but it does appear to fix the
260                 // problem on fast connections more effectively than using an
261                 // arbitrary timeout.  It is possible that the browser does
262                 // block subsequent script execution in this case for a limited
263                 // time.
264                 var extra = _scriptNode(null, q.win, q.attributes);
265                 extra.innerHTML='YAHOO.util.Get._finalize("' + id + '");';
266                 q.nodes.push(extra); h.appendChild(extra);
267
268             } else {
269                 _finish(id);
270             }
271
272             return;
273         } 
274
275
276         var url = q.url[0];
277
278         // if the url is undefined, this is probably a trailing comma problem in IE
279         if (!url) {
280             q.url.shift(); 
281             YAHOO.log('skipping empty url');
282             return _next(id);
283         }
284
285         YAHOO.log("attempting to load " + url, "info", "Get");
286
287         if (q.timeout) {
288             // Y.log('create timer');
289             q.timer = lang.later(q.timeout, q, _timeout, id);
290         }
291
292         if (q.type === "script") {
293             n = _scriptNode(url, w, q.attributes);
294         } else {
295             n = _linkNode(url, w, q.attributes);
296         }
297
298         // track this node's load progress
299         _track(q.type, n, id, url, w, q.url.length);
300
301         // add the node to the queue so we can return it to the user supplied callback
302         q.nodes.push(n);
303
304         // add it to the head or insert it before 'insertBefore'
305         if (q.insertBefore) {
306             var s = _get(q.insertBefore, id);
307             if (s) {
308                 s.parentNode.insertBefore(n, s);
309             }
310         } else {
311             h.appendChild(n);
312         }
313         
314         YAHOO.log("Appending node: " + url, "info", "Get");
315
316         // FireFox does not support the onload event for link nodes, so there is
317         // no way to make the css requests synchronous. This means that the css 
318         // rules in multiple files could be applied out of order in this browser
319         // if a later request returns before an earlier one.  Safari too.
320         if ((ua.webkit || ua.gecko) && q.type === "css") {
321             _next(id, url);
322         }
323     };
324
325     /**
326      * Removes processed queues and corresponding nodes
327      * @method _autoPurge
328      * @private
329      */
330     var _autoPurge = function() {
331
332         if (purging) {
333             return;
334         }
335
336         purging = true;
337         for (var i in queues) {
338             var q = queues[i];
339             if (q.autopurge && q.finished) {
340                 _purge(q.tId);
341                 delete queues[i];
342             }
343         }
344
345         purging = false;
346     };
347
348     /**
349      * Removes the nodes for the specified queue
350      * @method _purge
351      * @private
352      */
353     var _purge = function(tId) {
354         if (queues[tId]) {
355
356             var q     = queues[tId],
357                 nodes = q.nodes, 
358                 l     = nodes.length, 
359                 d     = q.win.document, 
360                 h     = d.getElementsByTagName("head")[0],
361                 sib, i, node, attr;
362
363             if (q.insertBefore) {
364                 sib = _get(q.insertBefore, tId);
365                 if (sib) {
366                     h = sib.parentNode;
367                 }
368             }
369
370             for (i=0; i<l; i=i+1) {
371                 node = nodes[i];
372                 if (node.clearAttributes) {
373                     node.clearAttributes();
374                 } else {
375                     for (attr in node) {
376                         delete node[attr];
377                     }
378                 }
379
380                 h.removeChild(node);
381             }
382
383             q.nodes = [];
384         }
385     };
386
387     /**
388      * Saves the state for the request and begins loading
389      * the requested urls
390      * @method queue
391      * @param type {string} the type of node to insert
392      * @param url {string} the url to load
393      * @param opts the hash of options for this request
394      * @private
395      */
396     var _queue = function(type, url, opts) {
397
398         var id = "q" + (qidx++);
399         opts = opts || {};
400
401         if (qidx % YAHOO.util.Get.PURGE_THRESH === 0) {
402             _autoPurge();
403         }
404
405         queues[id] = lang.merge(opts, {
406             tId: id,
407             type: type,
408             url: url,
409             finished: false,
410             aborted: false,
411             nodes: []
412         });
413
414         var q = queues[id];
415         q.win = q.win || window;
416         q.scope = q.scope || q.win;
417         q.autopurge = ("autopurge" in q) ? q.autopurge : 
418                       (type === "script") ? true : false;
419
420         if (opts.charset) {
421             q.attributes = q.attributes || {};
422             q.attributes.charset = opts.charset;
423         }
424
425         lang.later(0, q, _next, id);
426
427         return {
428             tId: id
429         };
430     };
431
432     /**
433      * Detects when a node has been loaded.  In the case of
434      * script nodes, this does not guarantee that contained
435      * script is ready to use.
436      * @method _track
437      * @param type {string} the type of node to track
438      * @param n {HTMLElement} the node to track
439      * @param id {string} the id of the request
440      * @param url {string} the url that is being loaded
441      * @param win {Window} the targeted window
442      * @param qlength the number of remaining items in the queue,
443      * including this one
444      * @param trackfn {Function} function to execute when finished
445      * the default is _next
446      * @private
447      */
448     var _track = function(type, n, id, url, win, qlength, trackfn) {
449         var f = trackfn || _next;
450
451         // IE supports the readystatechange event for script and css nodes
452         if (ua.ie) {
453             n.onreadystatechange = function() {
454                 var rs = this.readyState;
455                 if ("loaded" === rs || "complete" === rs) {
456                     YAHOO.log(id + " onload " + url, "info", "Get");
457                     n.onreadystatechange = null;
458                     f(id, url);
459                 }
460             };
461
462         // webkit prior to 3.x is problemmatic
463         } else if (ua.webkit) {
464
465             if (type === "script") {
466
467                 // Safari 3.x supports the load event for script nodes (DOM2)
468                 if (ua.webkit >= 420) {
469
470                     n.addEventListener("load", function() {
471                         YAHOO.log(id + " DOM2 onload " + url, "info", "Get");
472                         f(id, url);
473                     });
474
475                 // Nothing can be done with Safari < 3.x except to pause and hope
476                 // for the best, particularly after last script is inserted. The
477                 // scripts will always execute in the order they arrive, not
478                 // necessarily the order in which they were inserted.  To support
479                 // script nodes with complete reliability in these browsers, script
480                 // nodes either need to invoke a function in the window once they
481                 // are loaded or the implementer needs to provide a well-known
482                 // property that the utility can poll for.
483                 } else {
484                     // Poll for the existence of the named variable, if it
485                     // was supplied.
486                     var q = queues[id];
487                     if (q.varName) {
488                         var freq=YAHOO.util.Get.POLL_FREQ;
489                         YAHOO.log("Polling for " + q.varName[0]);
490                         q.maxattempts = YAHOO.util.Get.TIMEOUT/freq;
491                         q.attempts = 0;
492                         q._cache = q.varName[0].split(".");
493                         q.timer = lang.later(freq, q, function(o) {
494                             var a=this._cache, l=a.length, w=this.win, i;
495                             for (i=0; i<l; i=i+1) {
496                                 w = w[a[i]];
497                                 if (!w) {
498                                     // if we have exausted our attempts, give up
499                                     this.attempts++;
500                                     if (this.attempts++ > this.maxattempts) {
501                                         var msg = "Over retry limit, giving up";
502                                         q.timer.cancel();
503                                         _fail(id, msg);
504                                     } else {
505                                         YAHOO.log(a[i] + " failed, retrying");
506                                     }
507                                     return;
508                                 }
509                             }
510                             
511                             YAHOO.log("Safari poll complete");
512
513                             q.timer.cancel();
514                             f(id, url);
515
516                         }, null, true);
517                     } else {
518                         lang.later(YAHOO.util.Get.POLL_FREQ, null, f, [id, url]);
519                     }
520                 }
521             } 
522
523         // FireFox and Opera support onload (but not DOM2 in FF) handlers for
524         // script nodes.  Opera, but not FF, supports the onload event for link
525         // nodes.
526         } else { 
527             n.onload = function() {
528                 YAHOO.log(id + " onload " + url, "info", "Get");
529                 f(id, url);
530             };
531         }
532     };
533
534     return {
535
536         /**
537          * The default poll freqency in ms, when needed
538          * @property POLL_FREQ
539          * @static
540          * @type int
541          * @default 10
542          */
543         POLL_FREQ: 10,
544
545         /**
546          * The number of request required before an automatic purge.
547          * property PURGE_THRESH
548          * @static
549          * @type int
550          * @default 20
551          */
552         PURGE_THRESH: 20,
553
554         /**
555          * The length time to poll for varName when loading a script in
556          * Safari 2.x before the transaction fails.
557          * property TIMEOUT
558          * @static
559          * @type int
560          * @default 2000
561          */
562         TIMEOUT: 2000,
563         
564         /**
565          * Called by the helper for detecting script load in Safari
566          * @method _finalize
567          * @param id {string} the transaction id
568          * @private
569          */
570         _finalize: function(id) {
571             YAHOO.log(id + " finalized ", "info", "Get");
572             lang.later(0, null, _finish, id);
573         },
574
575         /**
576          * Abort a transaction
577          * @method abort
578          * @param {string|object} either the tId or the object returned from
579          * script() or css()
580          */
581         abort: function(o) {
582             var id = (lang.isString(o)) ? o : o.tId;
583             var q = queues[id];
584             if (q) {
585                 YAHOO.log("Aborting " + id, "info", "Get");
586                 q.aborted = true;
587             }
588         }, 
589
590         /**
591          * Fetches and inserts one or more script nodes into the head
592          * of the current document or the document in a specified window.
593          *
594          * @method script
595          * @static
596          * @param url {string|string[]} the url or urls to the script(s)
597          * @param opts {object} Options: 
598          * <dl>
599          * <dt>onSuccess</dt>
600          * <dd>
601          * callback to execute when the script(s) are finished loading
602          * The callback receives an object back with the following
603          * data:
604          * <dl>
605          * <dt>win</dt>
606          * <dd>the window the script(s) were inserted into</dd>
607          * <dt>data</dt>
608          * <dd>the data object passed in when the request was made</dd>
609          * <dt>nodes</dt>
610          * <dd>An array containing references to the nodes that were
611          * inserted</dd>
612          * <dt>purge</dt>
613          * <dd>A function that, when executed, will remove the nodes
614          * that were inserted</dd>
615          * <dt>
616          * </dl>
617          * </dd>
618          * <dt>onFailure</dt>
619          * <dd>
620          * callback to execute when the script load operation fails
621          * The callback receives an object back with the following
622          * data:
623          * <dl>
624          * <dt>win</dt>
625          * <dd>the window the script(s) were inserted into</dd>
626          * <dt>data</dt>
627          * <dd>the data object passed in when the request was made</dd>
628          * <dt>nodes</dt>
629          * <dd>An array containing references to the nodes that were
630          * inserted successfully</dd>
631          * <dt>purge</dt>
632          * <dd>A function that, when executed, will remove any nodes
633          * that were inserted</dd>
634          * <dt>
635          * </dl>
636          * </dd>
637          * <dt>onTimeout</dt>
638          * <dd>
639          * callback to execute when a timeout occurs.
640          * The callback receives an object back with the following
641          * data:
642          * <dl>
643          * <dt>win</dt>
644          * <dd>the window the script(s) were inserted into</dd>
645          * <dt>data</dt>
646          * <dd>the data object passed in when the request was made</dd>
647          * <dt>nodes</dt>
648          * <dd>An array containing references to the nodes that were
649          * inserted</dd>
650          * <dt>purge</dt>
651          * <dd>A function that, when executed, will remove the nodes
652          * that were inserted</dd>
653          * <dt>
654          * </dl>
655          * </dd>
656          * <dt>scope</dt>
657          * <dd>the execution context for the callbacks</dd>
658          * <dt>win</dt>
659          * <dd>a window other than the one the utility occupies</dd>
660          * <dt>autopurge</dt>
661          * <dd>
662          * setting to true will let the utilities cleanup routine purge 
663          * the script once loaded
664          * </dd>
665          * <dt>data</dt>
666          * <dd>
667          * data that is supplied to the callback when the script(s) are
668          * loaded.
669          * </dd>
670          * <dt>varName</dt>
671          * <dd>
672          * variable that should be available when a script is finished
673          * loading.  Used to help Safari 2.x and below with script load 
674          * detection.  The type of this property should match what was
675          * passed into the url parameter: if loading a single url, a
676          * string can be supplied.  If loading multiple scripts, you
677          * must supply an array that contains the variable name for
678          * each script.
679          * </dd>
680          * <dt>insertBefore</dt>
681          * <dd>node or node id that will become the new node's nextSibling</dd>
682          * </dl>
683          * <dt>charset</dt>
684          * <dd>Node charset, deprecated, use 'attributes'</dd>
685          * <dt>attributes</dt>
686          * <dd>A hash of attributes to apply to dynamic nodes.</dd>
687          * <dt>timeout</dt>
688          * <dd>Number of milliseconds to wait before aborting and firing the timeout event</dd>
689          * <pre>
690          * // assumes yahoo, dom, and event are already on the page
691          * &nbsp;&nbsp;YAHOO.util.Get.script(
692          * &nbsp;&nbsp;["http://yui.yahooapis.com/2.7.0/build/dragdrop/dragdrop-min.js",
693          * &nbsp;&nbsp;&nbsp;"http://yui.yahooapis.com/2.7.0/build/animation/animation-min.js"], &#123;
694          * &nbsp;&nbsp;&nbsp;&nbsp;onSuccess: function(o) &#123;
695          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;YAHOO.log(o.data); // foo
696          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new YAHOO.util.DDProxy("dd1"); // also new o.reference("dd1"); would work
697          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.log("won't cause error because YAHOO is the scope");
698          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.log(o.nodes.length === 2) // true
699          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// o.purge(); // optionally remove the script nodes immediately
700          * &nbsp;&nbsp;&nbsp;&nbsp;&#125;,
701          * &nbsp;&nbsp;&nbsp;&nbsp;onFailure: function(o) &#123;
702          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;YAHOO.log("transaction failed");
703          * &nbsp;&nbsp;&nbsp;&nbsp;&#125;,
704          * &nbsp;&nbsp;&nbsp;&nbsp;data: "foo",
705          * &nbsp;&nbsp;&nbsp;&nbsp;timeout: 10000, // 10 second timeout
706          * &nbsp;&nbsp;&nbsp;&nbsp;scope: YAHOO,
707          * &nbsp;&nbsp;&nbsp;&nbsp;// win: otherframe // target another window/frame
708          * &nbsp;&nbsp;&nbsp;&nbsp;autopurge: true // allow the utility to choose when to remove the nodes
709          * &nbsp;&nbsp;&#125;);
710          * </pre>
711          * @return {tId: string} an object containing info about the transaction
712          */
713         script: function(url, opts) { return _queue("script", url, opts); },
714
715         /**
716          * Fetches and inserts one or more css link nodes into the 
717          * head of the current document or the document in a specified
718          * window.
719          * @method css
720          * @static
721          * @param url {string} the url or urls to the css file(s)
722          * @param opts Options: 
723          * <dl>
724          * <dt>onSuccess</dt>
725          * <dd>
726          * callback to execute when the css file(s) are finished loading
727          * The callback receives an object back with the following
728          * data:
729          * <dl>win</dl>
730          * <dd>the window the link nodes(s) were inserted into</dd>
731          * <dt>data</dt>
732          * <dd>the data object passed in when the request was made</dd>
733          * <dt>nodes</dt>
734          * <dd>An array containing references to the nodes that were
735          * inserted</dd>
736          * <dt>purge</dt>
737          * <dd>A function that, when executed, will remove the nodes
738          * that were inserted</dd>
739          * <dt>
740          * </dl>
741          * </dd>
742          * <dt>scope</dt>
743          * <dd>the execution context for the callbacks</dd>
744          * <dt>win</dt>
745          * <dd>a window other than the one the utility occupies</dd>
746          * <dt>data</dt>
747          * <dd>
748          * data that is supplied to the callbacks when the nodes(s) are
749          * loaded.
750          * </dd>
751          * <dt>insertBefore</dt>
752          * <dd>node or node id that will become the new node's nextSibling</dd>
753          * <dt>charset</dt>
754          * <dd>Node charset, deprecated, use 'attributes'</dd>
755          * <dt>attributes</dt>
756          * <dd>A hash of attributes to apply to dynamic nodes.</dd>
757          * </dl>
758          * <pre>
759          *      YAHOO.util.Get.css("http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css");
760          * </pre>
761          * <pre>
762          *      YAHOO.util.Get.css(["http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css",
763          *                          "http://yui.yahooapis.com/2.7.0/build/logger/assets/skins/sam/logger.css"]);
764          * </pre>
765          * @return {tId: string} an object containing info about the transaction
766          */
767         css: function(url, opts) {
768             return _queue("css", url, opts); 
769         }
770     };
771 }();
772
773 YAHOO.register("get", YAHOO.util.Get, {version: "2.8.0r4", build: "2449"});