var PubLoader = {
	oWhereToDocWrite: null,	// Noeud où insérer le document.write
	docwritebuffer: "",		// document.write sur plusieurs lignes qu'il faux bufferiser avant de l'écrire
	bInTag: false,
	CurrentTag: "",
	BodyScripts: [],		// Scripts à insérer dans le body
	OtherScripts: [],		// Scripts des tags de pub
	aTags: [],				// Adresses des tags de pub
	bFirstCall: true,		// Premier appel -> ne pas recharger
	bResendTags: true,		// Rechargement des tags de tracking en même temps que les pubs
	bLoadedOnce: false,		// Premier chargement effecfue
	bReloadOk: false,		// Rechargement auto ok 5s apres premier chargement
	
	/**
	 * Remet tout à zéro 
	 */
	reset: function() {
		this.oWhereToDocWrite = null;
		this.docwritebuffer = "";
		this.bInTag = false;
		this.CurrentTag = "";
		this.BodyScripts = [];
		for ( e in this.OtherScripts ) {
			this.OtherScripts[e] = [];
		}
	},

	recharge: function(tagPage,bForce,gaHash) {
		var sElem = document.createElement("script");
		var parentNode = jQuery("body")[0];
		
		if ( !this.bLoadedOnce || this.bReloadOk ) {
			PubLoader.aTags = [];
			
			OAS_listpos = "";
			
			if ( jQuery('#TagPub').length > 0 ) {
				jQuery("#TagPub").empty();
				PubLoader.aTags["TagPub"] = new Object();
				PubLoader.aTags["TagPub"].bFirst = true;
				PubLoader.aTags["TagPub"].script = "OAS_AD('Top');";
				PubLoader.OtherScripts["TagPub"] = [];
				OAS_listpos = "Top"
			}
			
			if ( jQuery('#TagPave').length > 0 ) {
				jQuery("#TagPave").empty();
				PubLoader.aTags["TagPave"] = new Object();
				PubLoader.aTags["TagPave"].bFirst = true;
				PubLoader.aTags["TagPave"].script = "OAS_AD('Middle1');";
				PubLoader.OtherScripts["TagPave"] = [];
				if (OAS_listpos != "") { OAS_listpos += ","; }
				OAS_listpos += "Middle1";
			}
					
			for (var i=1;i<=3;i++) {
				if ( jQuery('#pubInterPA'+i).length > 0 ) {
					jQuery("#pubInterPA"+i).empty();
					PubLoader.aTags["pubInterPA"+i] = new Object();
					PubLoader.aTags["pubInterPA"+i].bFirst = true;
					PubLoader.aTags["pubInterPA"+i].script = "OAS_AD('x1"+i+"');";
					PubLoader.OtherScripts["pubInterPA"+i] = [];
					if (OAS_listpos != "") { OAS_listpos += ","; }
					OAS_listpos += "x1" + i;
				}
			}
			
			if (OAS_version >= 11) { 
				sElem.src = OAS_url + 'adstream_mjx.ads/' + OAS_sitepage + '/1' + OAS_rns + '@' + OAS_listpos + '?' + OAS_query;
				// Attach handlers for all browsers
				sElem.onload = sElem.onreadystatechange = function(){
					if ( !this.readyState ||
							this.readyState === "loaded" || this.readyState === "complete" ) {
						// Handle memory leak in IE
						sElem.onload = sElem.onreadystatechange = null;
						parentNode.removeChild( sElem );
						// Charge le script suivant
						PubLoader._recharge(tagPage,bForce,gaHash);
					}
				};
				parentNode.appendChild(sElem);
			}
		}
	},
	
	/**
	 * Ajoute un élément script dans le div actif 
	 */
	_loadScript: function(scripts, parentNode) {
		var sElem, s;
		s = scripts.shift();
		if ( s.src ) {
			sElem = document.createElement("script");
			sElem.src = s.src;
			if (s.id) {
				sElem.id = s.id;
			}
			if (s.scriptCharset) {
				sElem.charset = s.charset;
			}
			// Node où insérer le résultat du script
			this.oWhereToDocWrite = parentNode;
			// Attach handlers for all browsers
			sElem.onload = sElem.onreadystatechange = function(){
				if ( !this.readyState ||
						this.readyState === "loaded" || this.readyState === "complete" ) {
					// Handle memory leak in IE
					sElem.onload = sElem.onreadystatechange = null;
					parentNode.removeChild( sElem );
					// Charge le script suivant
					PubLoader.loadScripts();
				}
			};
			parentNode.appendChild(sElem);
		} else {
			this.oWhereToDocWrite = parentNode;
			// Insère le noeud en recréant un element script dans le document.
			sElem = document.createElement("script");
			sElem.setAttribute('type','text/javascript'); 
			if ( s.firstChild ) {
				while (s.firstChild) {
					e = document.createTextNode(s.firstChild.nodeValue);
					sElem.appendChild(e);
					s.removeChild(s.firstChild);
				}
			} else {
				// Dans IE un noeud script n'a pas de fils mais directement le code dans un attribut text
				sElem.text = s.text;
			}
			parentNode.appendChild(sElem);
			PubLoader.loadScripts();
		}
	},

	/**
	 * Ajoute tous les éléments scripts dans l'ordre, l'un après l'autre 
	 */
	loadScripts: function() {
		for ( var e in this.OtherScripts ) {
			if ( this.OtherScripts[e].length > 0 ) {
				this._loadScript(this.OtherScripts[e], jQuery("#" + e)[0]);
				break;
			}
		}
		if ( this.BodyScripts.length > 0 ) {
			this._loadScript(this.BodyScripts, jQuery("body")[0]);
		}
	},

	/**
	 * Remplace document.write 
	 */
	write: function(str) {
		var match, rx;
		// Remplace language=vbscript en type="text/vbscript"
		str = str.replace(/language=["|']*vbscript["|']*/gi, "type=\"text/vbscript\"");
		str = str.replace(/language=["|']*javascript["|']*/gi, "type=\"text/javascript\"");
		PubLoader.docwritebuffer += str;
		if ( !PubLoader.bInTag ) {
			match = /^<(\w+)\s*/.exec(str);
			if ( match ) {
				PubLoader.CurrentTag = match[1];
			}
		}
		if ( PubLoader.CurrentTag.match(/IMG/i) ) {
			// Pas de fermeture sur ce type de tag
			match = true;
		} else {
			rx = new RegExp("</" + PubLoader.CurrentTag, "i");
			match = rx.exec(str);
		}
		if ( match ) {
			// Le tag se ferme dans str courant, on peut afficher
			
			var fragment = document.createDocumentFragment();
			var scripts = PubLoader.clean([PubLoader.docwritebuffer], document, fragment);
			parentNode = PubLoader.oWhereToDocWrite;
			if ( parentNode === null ) {
				parentNode = jQuery("body")[0];
			}
			while (fragment.firstChild) {
				parentNode.appendChild(fragment.firstChild);
			}
	
			if ( scripts ) {
				if ( typeof(parentNode.id) === "undefined" ) {
					PubLoader.BodyScripts = PubLoader.BodyScripts.concat(scripts);
				} else if ( typeof(PubLoader.OtherScripts[parentNode.id]) !== "undefined" ) {
					PubLoader.OtherScripts[parentNode.id] = PubLoader.OtherScripts[parentNode.id].concat(scripts); 
				}
			}
			
			PubLoader.docwritebuffer = "";
			PubLoader.CurrentTag = "";
			PubLoader.bInTag = false;
		} else {
			// le tag n'est pas fermé, on attend le prochain document.write
			PubLoader.bInTag = true;
		}
	
		return undefined;
	},
	
	/**
	 * Remplace document.writeln
	 */
	writeln: function(str) {
		return PubLoader.write(str + "\n");
	},

	/**
	 * Transforme une chaîne contenant du code html en noeud DOM + tableau de noeuds DOM des tags scripts
	 * Repris de jquery 1.3.2 
	 */
	clean: function( elems, context, fragment ) {
		context = context || document;
	
		// !context.createElement fails in IE with an error but returns typeof 'object'
		if ( typeof context.createElement === "undefined" ) {
			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
		}
	
		// If a single string is passed in and it's a single tag
		// just do a createElement and skip the rest
		if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
			var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
			if ( match ) {
				return [ context.createElement( match[1] ) ];
			}
		}
	
		var ret = [], scripts = [], div = context.createElement("div");
	
		jQuery.each(elems, function(i, elem){
			if ( typeof elem === "number" ) {
				elem += '';
			}
	
			if ( !elem ) {
				return;
			}
	
			// Convert html string into DOM nodes
			if ( typeof elem === "string" ) {
				// Fix "XHTML"-style tags in all browsers
				elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
					return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
						all :
						front + "></" + tag + ">";
				});
	
				// Trim whitespace, otherwise indexOf won't work as expected
				var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();
	
				var wrap =
					// option or optgroup
					!tags.indexOf("<opt") &&
					[ 1, "<select multiple='multiple'>", "</select>" ] ||
	
					!tags.indexOf("<leg") &&
					[ 1, "<fieldset>", "</fieldset>" ] ||
	
					tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
					[ 1, "<table>", "</table>" ] ||
	
					!tags.indexOf("<tr") &&
					[ 2, "<table><tbody>", "</tbody></table>" ] ||
	
					// <thead> matched above
					(!tags.indexOf("<td") || !tags.indexOf("<th")) &&
					[ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
	
					!tags.indexOf("<col") &&
					[ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
	
					// IE can't serialize <link> and <script> tags normally
					!jQuery.support.htmlSerialize &&
					[ 1, "div<div>", "</div>" ] ||
	
					[ 0, "", "" ];
	
				// Go to html and back, then peel off extra wrappers
				div.innerHTML = wrap[1] + elem + wrap[2];
	
				// Move to the right depth
				while ( wrap[0]-- ) {
					div = div.lastChild;
				}
	
				// Remove IE's autoinserted <tbody> from table fragments
				if ( !jQuery.support.tbody ) {
	
					// String was a <table>, *may* have spurious <tbody>
					var hasBody = /<tbody/i.test(elem),
						tbody = !tags.indexOf("<table") && !hasBody ?
							div.firstChild && div.firstChild.childNodes :
	
						// String was a bare <thead> or <tfoot>
						wrap[1] == "<table>" && !hasBody ?
							div.childNodes :
							[];
	
						for ( var j = tbody.length - 1; j >= 0 ; --j ) {
							if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
								tbody[ j ].parentNode.removeChild( tbody[ j ] );
							}
						}
	
					}
	
				// IE completely kills leading whitespace when innerHTML is used
				if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) ) {
					div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
				}
				
				elem = jQuery.makeArray( div.childNodes );
			}
	
			if ( elem.nodeType ) {
				ret.push( elem );
			} else {
				ret = jQuery.merge( ret, elem );
			}
	
		});
	
		if ( fragment ) {
			for ( var i = 0; ret[i]; i++ ) {
				if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
					scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
				} else {
					if ( ret[i].nodeType === 1 ) {
						if ( jQuery.nodeName( ret[i], "script" ) && (ret[i].type.toLowerCase() === "text/vbscript") ) {
							/**
							 * En cas de tag script en vb/script
							 * Le contenu du tag va être évalué immédiatement.
							 * Généralement, il s'agit de code pour vérifier la version de flash installé avec une ligne du type
							 * pvar = CreateObject(.... 
							 */
							// script vbscript
							var s = ret[i].innerHTML;
							s = s.replace("on error resume next",""); // Supprime le on error resume next qui ne sert pas
							s = s.replace(/^[^\w]*/, ""); // trim de la chaîne
							s = s.split("=");
							if ( s.length === 2) {
								// script du type v = x, on appelle la fonction EvalVB qui retourne le résultat de x
								eval(s[0] + " = EvalVB(\"" + s[1].replace(/"/g, "\\\"") + "\");");
							} else {
								// Le script n'est pas au format attendu, on l'insère normalement
								fragment.appendChild( ret[i] );
							}
						} else {
							ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
							fragment.appendChild( ret[i] );
						}
					} else {
						fragment.appendChild( ret[i] );
					}
				}
			}
			
			return scripts;
		}
	
		return ret;
	},

	setParamPubMarque: function(cat,marque) {
		reloadPub("cat="+cat.toUpperCase()+";marq="+marque.toUpperCase()+";");
	},
	
	getParamPub: function(sKm,sCat,sPrix,sMill,sTag) {
		var sTag = OAS_query;
		var lst,p, re = /([0-9]+)/gi;
		if ( typeof(sKm) !== "undefined" ) {
			var match = sKm.match(re);
			if ( match && match[0] ) {
				if ( sTag.match(/kmMin=[0-9]*;/) ) {
					sTag = sTag.replace(/kmMin=[0-9]*;/,"kmMin=" + match[0] + ";");
				} else {
					sTag += ";kmMin=" + match[0];
				}
			} else {
				sTag = sTag.replace(/kmMin=[0-9]*;/,"kmMin=;");
			}
			
			if ( match && match[1] ) {
				if ( sTag.match(/kmMax=[0-9]*;/) ) {
					sTag = sTag.replace(/kmMax=[0-9]*;/,"kmMax=" + match[1] + ";");
				} else {
					sTag += ";kmMax=" + match[1];
				}
			} else {
				sTag = sTag.replace(/kmMax=[0-9]*;/,"kmMax=;");
			}
		} else {
			sTag = sTag.replace(/kmMin=[0-9]*;/,"kmMin=;");
			sTag = sTag.replace(/kmMax=[0-9]*;/,"kmMax=;");
		}
		if ( typeof(sCat) !== "undefined" ) {
			if ( (sCat.length == 0) || (sCat.toUpperCase().indexOf("VOITURE") !== -1) ) {
				sCat = "VP";
			} else if ( sCat.toUpperCase().indexOf("UTILITAIRE") === 0 ) {
				sCat = "VU";
			}
			if ( sTag.match(/cat=[^;]*;/) ) {
				sTag = sTag.replace(/cat=[^;]*;/,"cat=" + sCat.toUpperCase().replace(/[ |+]/g,"") + ";");
			} else {
				sTag += ";cat=" + sCat.toUpperCase().replace(/[ |+]/g,"");
			}
		} else {
			sTag = sTag.replace(/cat=[^;]*;/,"cat=;");
		}
		if ( (arguments.length > 1) && typeof(sPrix) !== "undefined" && (sPrix !== "") ) {
			match = sPrix.match(re);
			if ( match && match[0] ) {
				if ( sTag.match(/prixMin=[0-9]*;/) ) {
					sTag = sTag.replace(/prixMin=[0-9]*;/,"prixMin=" + match[0] + ";");
				} else {
					sTag += ";prixMin=" + match[0];
				}
			} else {
				sTag = sTag.replace(/prixMin=[0-9]*;/,"prixMin=;");
			}
			if ( match && match[1] ) {
				if ( sTag.match(/prixMax=[0-9]*;/) ) {
					sTag = sTag.replace(/prixMax=[0-9]*;/,"prixMax=" + match[1] + ";");
				} else {
					sTag += ";prixMax=" + match[1];
				}
			} else {
				sTag = sTag.replace(/prixMax=[0-9]*;/,"prixMax=;");
			}
		} else {
			sTag = sTag.replace(/prixMin=[0-9]*;/,"prixMin=;");
			sTag = sTag.replace(/prixMax=[0-9]*;/,"prixMax=;");
		}
		if ( (arguments.length > 1) && typeof(sMill) !== "undefined" && (sMill !== "") ) {
			match = sMill.match(re);
			if ( match && match[0] ) {
				if ( sTag.match(/ageMin=[0-9]*;/) ) {
					sTag = sTag.replace(/ageMin=[0-9]*;/,"ageMin=" + match[0] + ";");
				} else {
					sTag += ";ageMin=" + match[0];
				}
			} else {
				sTag = sTag.replace(/ageMin=[0-9]*;/,"ageMin=;");
			}
			var lastIndex = match.length - 1;
			if ( match && match[lastIndex] ) {
				if ( sTag.match(/ageMax=[0-9]*;/) ) {
					sTag = sTag.replace(/ageMax=[0-9]*;/,"ageMax=" + match[lastIndex] + ";");
				} else {
					sTag += ";ageMax=" + match[lastIndex];
				}
			} else {
				sTag = sTag.replace(/ageMax=[0-9]*;/,"ageMax=;");
			}
		} else {
			sTag = sTag.replace(/ageMin=[0-9]*;/,"ageMin=;");
			sTag = sTag.replace(/ageMax=[0-9]*;/,"ageMax=;");
		}
		return sTag;
	},
	
	track: function(tagPage,gaHash) {
		if ( window._gaq && window._gaq.push ) {
			if ( (arguments.length > 1) && (typeof(gaHash) !== "undefined") && (gaHash !== "") ) {
				window._gaq.push(['_trackPageview', location.pathname + "#" + gaHash]);
			} else {
				gaHash = document.location.hash.split("/")[0];
				if ( gaHash.match(/#[f|p]{1}[0-9]+/) || (gaHash === "#") ) {
					gaHash = "";
				}
				window._gaq.push(['_trackPageview', location.pathname + gaHash]);
			}
		}
	},
	
	setBResendTags: function(b) {
		this.bResendTags = b;
	},
	
	setReloadOk: function(b) {
		this.bReloadOk = true;
	},
	
	_recharge: function(tagPage,bForce,gaHash) {
		var bLoadScripts = false;
		if ( arguments.length < 2 ) {
			bForce = false;
		}
		if ( !this.bLoadedOnce || this.bReloadOk ) {
			this.reset();
			for ( e in this.aTags ) {
				if ( !this.bFirstCall || bForce || this.aTags[e].bFirst ) {
					jQuery("#" + e).empty();
					this.oWhereToDocWrite = jQuery("#" + e)[0];
					if ( typeof this.oWhereToDocWrite !== "undefined" ) {
						ord=Math.random()*10000000000000000;
						eval(this.aTags[e].script);
					}
					bLoadScripts = true;
				}
			}
			if ( bLoadScripts ) {
				this.loadScripts();
				if ( !this.bFirstCall && this.bResendTags ) {
					this.track(tagPage,gaHash);
				}
			}
			this.bFirstCall = false;
			this.bLoadedOnce = true;
			setTimeout("PubLoader.setReloadOk(true);",3000); // La pub ne peut-etre rechargee que 3s apres le tout premier chargement
		}
	}
};
jQuery(function(){
	document.write = PubLoader.write;
	document.writeln = PubLoader.writeln;
});
