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