
var viewsDone = [];

function dynamicLoad(what){
  headID = document.getElementsByTagName("head")[0];
  notDoneView = true;
  for (i=0; i<viewsDone.length; i++){
    if (viewsDone[i]==what.widgetView){
      notDoneView = false;
    }
  }
  if (notDoneView){
    dynamicLoadFunction(what.perViewFunctions);
  }
    dynamicLoadSrc(what.perViewSrc);
  
  if(typeof what.perWidgetJs != 'undefined') dynamicLoadJs(what.perWidgetJs);
  viewsDone.push(what.widgetView);
}



function dynamicLoadSrc(perViewSrc){
  //per_view_src
  for (i=0; i<perViewSrc.length; i++){
    src = perViewSrc[i].src;
    onload_doc = (typeof perViewSrc[i]['onload'] != 'undefined') ? perViewSrc[i]['onload'] : undefined;
    existingScripts = headID.getElementsByTagName('script');
    addscript = true;
    for (j in existingScripts){
      if (src == existingScripts[j].src){
	addscript=false;
	break;
      }
      existingsrc = existingScripts[j].src;
      if (typeof existingsrc !== "undefined"){
	if (existingsrc.indexOf(src) !=-1){
	  addscript=false;
	}
      }
    }
    if (addscript){

     $$('head').first().insert({
    	    bottom: new Element('script', {
	      type: 'text/javascript',
	      src:src
    	    }).update()
    	});


      if (typeof onload_doc !== "undefined"){
      //this is some ways I looked out to add the onload event.
      //whilst it does go through this code, the javascript doesn't apear to be invoked, 
     $$('head').first().insert({
    	    bottom: new Element('script', {
	      type: 'text/javascript'
				    }).update('window.onload =' + onload_doc+';')});



      }



    }
  }
}

function dynamicLoadFunction(perViewFunctions){
  if (typeof perViewFunctions !== "undefined"){

     $$('head').first().insert({
    	    bottom: new Element('script', {
    	        type: 'text/javascript'
    	    }).update(perViewFunctions)
    	});

  }
}

function dynamicLoadJs(perViewJs){
   if (typeof perViewJs !== "undefined"){

     $$('head').first().insert({
    	    bottom: new Element('script', {
    	        type: 'text/javascript'
    	    }).update(perViewJs)
    	});

   }
}

