Changed the script into a jquery-plugin
[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   domain, id, node,
29
30   count = 0,
31   slots = {},
32   queue = [],
33   ads = [],
34   output = [];
35
36
37   $.openx = function( server, zones, options ) {
38
39     if (domain) {
40       if (console.error)
41         console.error('jQuery.openx was already initialized!');
42       return;
43     }
44
45     domain = document.location.protocol == 'https:' ? 'https://' + server + ':8443':'http://' + server;
46
47     var
48     name,
49     src = domain;
50
51     /**
52      * Without this option, jQuery appends an timestamp to every URL, that
53      * is fetched via $.getScript(). This can mess up badly written
54      * third-party-ad-scripts, that assume that the called URL's are not
55      * altered.
56      */
57     $.ajaxSetup({ cache: true });
58
59     src += "/www/delivery/spc.php?zones=";
60
61     /** Only fetch banners, that are really included in this page */
62     for(name in zones) {
63       $('.oa').each(function() {
64         var
65         node = $(this),
66         id;
67         if (node.hasClass(name)) {
68           id = 'oa_' + ++count;
69           slots[id] = node;
70           queue.push(id);
71           src += escape(id + '=' + zones[name] + "|");
72         }
73       });
74     }
75
76     if (typeof OA_source !== 'undefined')
77       src += "&source=" + escape(OA_source);
78     src += "&nz=1&r=" + Math.floor(Math.random()*99999999);
79     src += "&block=1&charset=UTF-8";
80
81     if (window.location)   src += "&loc=" + escape(window.location);
82     if (document.referrer) src += "&referer=" + escape(document.referrer);
83
84     $.getScript(src, load_flash);
85
86   }
87
88   function load_flash() {
89
90     $.getScript(domain + '/www/delivery/fl.js', init_ads);
91
92   }
93
94   function init_ads() {
95
96     var i, id;
97     for (i=0; i<queue.length; i++) {
98       id = queue[i];
99       if (typeof(OA_output[id]) != 'undefined' && OA_output[id] != '')
100         ads.push(id);
101     }
102
103     document.write = document_write;
104     document.writeln = document_write;
105
106     render_ads();
107
108   }
109
110   function render_ads() {
111
112     while (ads.length > 0) {
113
114       var result, src, inline;
115
116       id = ads.shift();
117       node = slots[id];
118
119       node.slideDown();
120
121       // node.append(id + ": " + node.attr('class'));
122
123       /**
124        * If output was added via document.write(), this output must be
125        * rendered before other banner-code from the OpenX-server is rendered!
126        */
127       insert_output();
128
129       while ((result = /<script/i.exec(OA_output[id])) != null) {
130         node.append(OA_output[id].slice(0,result.index));
131         /** Strip all text before "<script" from OA_output[id] */
132         OA_output[id] = OA_output[id].slice(result.index,OA_output[id].length);
133         result = /^([^>]*)>([\s\S]*?)<\\?\/script>/i.exec(OA_output[id]);
134         if (result == null) {
135           /** Invalid syntax in delivered banner-code: ignoring the rest of this banner-code! */
136           // alert(OA_output[id]);
137           OA_output[id] = "";
138         }
139         else {
140           /** Remember iinline-code, if present */
141           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!
142           inline = result[2];
143           /** Strip all text up to and including "</script>" from OA_output[id] */
144           OA_output[id] = OA_output[id].slice(result[0].length,OA_output[id].length);
145           result = /src\s*=\s*['"]?([^'"]*)['"]?\s/i.exec(src);
146           if (result == null) {
147             /** script-tag with inline-code: execute inline-code! */
148             result = /^\s*<.*$/m.exec(inline);
149             if (result != null) {
150               /** Remove leading HTML-comments, because IE will stumble otherwise */
151               inline = inline.slice(result[0].length,inline.length);
152             }
153             $.globalEval(inline);
154             insert_output(); // << The executed inline-code might have called document.write()!
155           }
156           else {
157             /** script-tag with src-URL! */
158             if (OA_output[id].length > 0)
159               /** The banner-code was not rendered completely yet! */
160               ads.unshift(id);
161             /** Load the script and halt all work until the script is loaded and executed... */
162             $.getScript(result[1], render_ads); // << jQuery.getScript() generates onload-Handler for _all_ browsers ;)
163             return;
164           }
165         }
166       }
167
168       node.append(OA_output[id]);
169       OA_output[id] = "";
170     }
171
172     /** All entries from OA_output were rendered */
173
174     id = undefined;
175     node = undefined;
176   }
177
178   /** This function is used to overwrite document.write and document.writeln */
179   function document_write() {
180
181     if (id == undefined)
182       return;
183
184     for (var i=0; i<arguments.length; i++)
185       output.push(arguments[i]);
186
187     if (id != ads[0])
188       /**
189        * Re-Add the last banner-code to the working-queue, because included
190        * scripts had added markup via document.write(), which is not
191        * proccessed yet.
192        * Otherwise the added markup would be falsely rendered together with
193        * the markup from the following banner-code.
194        */
195       ads.unshift(id);
196
197   }
198
199   /**
200    * This function prepends the collected output from calls to
201    * document_write() to the current banner-code.
202    */
203   function insert_output() {
204
205     if (output.length > 0) {
206       output.push(OA_output[id]);
207       OA_output[id] = "";
208       for (i=0; i<output.length; i++)
209         OA_output[id] += output[i];
210       output = [];
211     }
212
213   }
214
215 })( jQuery, window, document );
216
217 var OA_output = {}; // << Needed, because IE will complain loudly otherwise!