Plugin shows configuration from first call, when its initialized twice
[openx] / jquery.openx.js
1 /*
2  * (C) Copyright 2012 juplo (http://juplo.de/).
3  *
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the GNU Lesser General Public License
6  * (LGPL) version 3.0 which accompanies this distribution, and is available at
7  * http://www.gnu.org/licenses/lgpl-3.0.html
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * Contributors:
15  * - Kai Moritz
16  */
17
18 /*
19  * See http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/
20  * for detailed explanations for the applied best practices.
21  *
22  * The semicolon guides our code for poorly written concatenated scripts.
23  */
24 ;(function( $, window, document, undefined ) {
25
26   var
27
28   settings, _zones, _options, domain, id, node,
29
30   count = 0,
31   slots = {},
32   queue = [],
33   ads = [],
34   output = [];
35
36
37   $.openx = function( zones, options ) {
38
39     if (domain) {
40       if (console.error) {
41         console.error('jQuery.openx was already initialized!');
42         console.log('Configured zones: ', _zones);
43         console.log('Configured options: ', _options);
44       }
45       return;
46     }
47
48     _zones = zones;
49     _options = options;
50
51     settings = $.extend(
52       {
53         'protocol': document.location.protocol,
54         'server': 'localhost'
55       },
56       options
57       );
58
59     domain = settings.protocol + '//';
60     domain += settings.server;
61     if (settings.protocol === 'http:' && settings.http_port)
62       domain += ':' + settings.http_port;
63     if (settings.protocol === 'https:' && settings.https_port)
64       domain += ':' + settings.https_port;
65
66     var
67     name,
68     src = domain;
69
70     /**
71      * Without this option, jQuery appends an timestamp to every URL, that
72      * is fetched via $.getScript(). This can mess up badly written
73      * third-party-ad-scripts, that assume that the called URL's are not
74      * altered.
75      */
76     $.ajaxSetup({ cache: true });
77
78     src += "/www/delivery/spc.php?zones=";
79
80     /** Only fetch banners, that are really included in this page */
81     for(name in zones) {
82       $('.oa').each(function() {
83         var
84         node = $(this),
85         id;
86         if (node.hasClass(name)) {
87           id = 'oa_' + ++count;
88           slots[id] = node;
89           queue.push(id);
90           src += escape(id + '=' + zones[name] + "|");
91         }
92       });
93     }
94
95     if (typeof OA_source !== 'undefined')
96       src += "&source=" + escape(OA_source);
97     src += "&nz=1&r=" + Math.floor(Math.random()*99999999);
98     src += "&block=1&charset=UTF-8";
99
100     if (window.location)   src += "&loc=" + escape(window.location);
101     if (document.referrer) src += "&referer=" + escape(document.referrer);
102
103     $.getScript(src, load_flash);
104
105   }
106
107   function load_flash() {
108
109     $.getScript(domain + '/www/delivery/fl.js', init_ads);
110
111   }
112
113   function init_ads() {
114
115     var i, id;
116     for (i=0; i<queue.length; i++) {
117       id = queue[i];
118       if (typeof(OA_output[id]) != 'undefined' && OA_output[id] != '')
119         ads.push(id);
120     }
121
122     document.write = document_write;
123     document.writeln = document_write;
124
125     render_ads();
126
127   }
128
129   function render_ads() {
130
131     while (ads.length > 0) {
132
133       var result, src, inline;
134
135       id = ads.shift();
136       node = slots[id];
137
138       node.slideDown();
139
140       // node.append(id + ": " + node.attr('class'));
141
142       /**
143        * If output was added via document.write(), this output must be
144        * rendered before other banner-code from the OpenX-server is rendered!
145        */
146       insert_output();
147
148       while ((result = /<script/i.exec(OA_output[id])) != null) {
149         node.append(OA_output[id].slice(0,result.index));
150         /** Strip all text before "<script" from OA_output[id] */
151         OA_output[id] = OA_output[id].slice(result.index,OA_output[id].length);
152         result = /^([^>]*)>([\s\S]*?)<\\?\/script>/i.exec(OA_output[id]);
153         if (result == null) {
154           /** Invalid syntax in delivered banner-code: ignoring the rest of this banner-code! */
155           // alert(OA_output[id]);
156           OA_output[id] = "";
157         }
158         else {
159           /** Remember iinline-code, if present */
160           src = result[1] + ' ' // << simplifies the following regular expression: the string ends with a space in any case, so that the src-URL cannot be followed by the end of the string emediately!
161           inline = result[2];
162           /** Strip all text up to and including "</script>" from OA_output[id] */
163           OA_output[id] = OA_output[id].slice(result[0].length,OA_output[id].length);
164           result = /src\s*=\s*['"]?([^'"]*)['"]?\s/i.exec(src);
165           if (result == null) {
166             /** script-tag with inline-code: execute inline-code! */
167             result = /^\s*<.*$/m.exec(inline);
168             if (result != null) {
169               /** Remove leading HTML-comments, because IE will stumble otherwise */
170               inline = inline.slice(result[0].length,inline.length);
171             }
172             $.globalEval(inline);
173             insert_output(); // << The executed inline-code might have called document.write()!
174           }
175           else {
176             /** script-tag with src-URL! */
177             if (OA_output[id].length > 0)
178               /** The banner-code was not rendered completely yet! */
179               ads.unshift(id);
180             /** Load the script and halt all work until the script is loaded and executed... */
181             $.getScript(result[1], render_ads); // << jQuery.getScript() generates onload-Handler for _all_ browsers ;)
182             return;
183           }
184         }
185       }
186
187       node.append(OA_output[id]);
188       OA_output[id] = "";
189     }
190
191     /** All entries from OA_output were rendered */
192
193     id = undefined;
194     node = undefined;
195   }
196
197   /** This function is used to overwrite document.write and document.writeln */
198   function document_write() {
199
200     if (id == undefined)
201       return;
202
203     for (var i=0; i<arguments.length; i++)
204       output.push(arguments[i]);
205
206     if (id != ads[0])
207       /**
208        * Re-Add the last banner-code to the working-queue, because included
209        * scripts had added markup via document.write(), which is not
210        * proccessed yet.
211        * Otherwise the added markup would be falsely rendered together with
212        * the markup from the following banner-code.
213        */
214       ads.unshift(id);
215
216   }
217
218   /**
219    * This function prepends the collected output from calls to
220    * document_write() to the current banner-code.
221    */
222   function insert_output() {
223
224     if (output.length > 0) {
225       output.push(OA_output[id]);
226       OA_output[id] = "";
227       for (i=0; i<output.length; i++)
228         OA_output[id] += output[i];
229       output = [];
230     }
231
232   }
233
234 })( jQuery, window, document );
235
236 var OA_output = {}; // << Needed, because IE will complain loudly otherwise!