function vp_waitFor(theTest, callback) {
  if (theTest()) {
    callback();
  } else {
    window.setTimeout(function() {
      vp_waitFor(theTest, callback);
    }, 100);
  }
}
function vp_fetchScript(theTest, theName, whenDone) {
  if (theTest()) {
    whenDone();
    return;
  }

  var script = document.createElement('script');
  script.src = 'http://vodpod.com/widgets/narrow_gallery/' + theName + '.js';
  script.type = 'text/javascript';
  document.getElementsByTagName("head")[0].appendChild(script);

  vp_waitFor(theTest, whenDone);
}
function vp_fetchAllScripts(docs, whenDone) {
  if (docs.length == 0) {
    whenDone();
    return;
  }
  
  vp_fetchScript(docs[0].theTest, docs[0].theName, function() {
    docs.shift();
    vp_fetchAllScripts(docs, whenDone);
  })
}
function vp_fetchCSS(name) {
  var link = document.createElement('link');
  link.href = 'http://vodpod.com/widgets/narrow_gallery/' + name + '.css';
  link.media = 'all';
  link.rel = 'Stylesheet';
  link.type = 'text/css';
  document.getElementsByTagName("head")[0].appendChild(link);
}

var origOnLoad = window.onload;
var vpLoadNarrowGallery = function() {
  vp_fetchCSS('gallery');

  vp_fetchAllScripts([
    {
      theTest: function() {return typeof(Prototype) != 'undefined';},
      theName: 'prototype'
    }, {
      theTest: function() {return typeof(Builder) != 'undefined';},
      theName: 'builder'
    }, {
      theTest: function() {return (typeof(Vodpod) != 'undefined' && typeof(Vodpod.NarrowGallery) != 'undefined')},
      theName: 'gallery'
    }
  ], function() { vp_scriptsLoaded(); });
  
  if (origOnLoad)
    origOnLoad();
}

var vpRanOnload=false; // Flag to determine if we've ran the starting stack already.

if (document.addEventListener) {
   document.addEventListener("DOMContentLoaded", function(){if (!vpRanOnload) {vpRanOnload=true; vpLoadNarrowGallery();}}, false);
}  else if (document.all && !window.opera) {
  // This is the IE style which exploits a property of the (standards defined) defer attribute
  document.write("<scr" + "ipt id='DOMReady' defer=true " + "src=//:><\/scr" + "ipt>");  
  document.getElementById("DOMReady").onreadystatechange=function(){
    if (this.readyState=="complete"&&(!vpRanOnload)){
      vpRanOnload=true;
      vpLoadNarrowGallery();
    }
  }
}
