// This override is here for ad tags that call document.write which doesn't work
// in a non-iframe popup since the document is already loaded. We will instead
// add the elements written in the original document.write to the parent of the
// ad tag script that has an id of "hotelPopupAd".

var oldDocWrite = document.write;
//Keep track of when the document has been loaded
var isDOMLoaded = false;
function markLoaded(){
	document.write = function(str){
	    var moz = !window.opera && !/Apple/.test(navigator.vendor);
	       
	    // Watch for writing out closing tags, we just
	    // ignore these (as we auto-generate our own)
	    if ( str.match(/^<\//) ) return;
	
	    // Make sure & are formatted properly, but Opera
	    // messes this up and just ignores it
	    if ( !window.opera )
	        str = str.replace(/&(?![#a-z0-9]+;)/g, "&amp;");
	
	    // Watch for when no closing tag is provided
	    // (Only does one element, quite weak)
	    str = str.replace(/<([a-z]+)(.*[^\/])>$/, "<$1$2></$1>");
	       
	    // Mozilla assumes that everything in XHTML innerHTML
	    // is actually XHTML - Opera and Safari assume that it's XML
	    if ( !moz )
	        str = str.replace(/(<[a-z]+)/g, "$1 xmlns='http://www.w3.org/1999/xhtml'");
	       
	    // The HTML needs to be within a HTML element
	    var div = document.createElement("div");
	    div.innerHTML = str;
	       
	    // Find the script for the hotel popup ad tag so we 
	    // can append the elements to it's parent
	    var pos;
	    
	    var scripts = document.getElementsByTagName('script');
	    for(var i = 0; i < scripts.length; i++)
	    {
	    	if (scripts[i].id == "hotelPopupAd")
	    	{
	    		pos = scripts[i];
	    		break;
	    	}
	    }
	       
	    // Add all the nodes in that position
	    var nodes = div.childNodes;
	    while ( nodes.length )
	        pos.parentNode.appendChild( nodes[0] );
	};
}

if(document.addEventListener)
	document.addEventListener('DOMContentLoaded', markLoaded, false);
if(window.addEventListener)
	window.addEventListener('load', markLoaded, false);
if(window.attachEvent)
	window.attachEvent('onload', markLoaded);