// Custom banner loading functions
//
// (c) 2010 JHED Media
// Author: Jip Moors
// Last Modified: 19 August 2010
// Last Modified By: Jip Moors
// 
// Version: 1.0
//
// Description:
// Script to load banners more efficiently
// Wait until the page is ready, then load the javascript and override the document.write to place it on the correct position

var scriptSourceToID = [];
var currentScriptSourceID;
var documentReady = false;

function addScriptSrc(id, source) {
  scriptSourceToID.push({id:id, source:unescape(source)});
  
  // if the document has been loaded and no script is working, apply it
  if( documentReady ) {
    applyScriptSource();
  }
}

function applyScriptSources() {
  if(scriptSourceToID.length > 0) {
    var item = scriptSourceToID.shift();
    
    currentScriptSourceID = item.id;
    
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = item.source;
    
    // this is needed, so the document.write is called:
    document.body.appendChild(script);
  }
}

// save original function
window.document._write = window.document.write;

// override the document.write function, this is used by all banners to inject code
window.document.write = function(data) {
  // if a script is loaded, the ID is set and inject to the connecting div
  if( typeof(currentScriptSourceID) != 'undefined' && currentScriptSourceID != null ) {
    $('#'+currentScriptSourceID).html(data);
    // unset the ID
    currentScriptSourceID = null;
    // try to load next item
    applyScriptSources();
  } else {
    try {
      window.document._write(data);
    } catch(e) {
      if( !window.document.body ) {
        window.document.body = window.document.createElement('body');
      }
      
      $(window.document.body).css({padding:0, margin:0, width:'100%', height:'100%'});
      window.document.body.innerHTML = data;
    }
  }
}

$(window.document).ready( function() {
  documentReady = true;
  applyScriptSources();
});
