// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function addLoadEvent(func){
	var oldonload = window.onload;
	if(typeof window.onload != 'function'){
		window.onload = func;
	}else{
		window.onload = function(){
			oldonload();
			func();
		}
	}
}

function insert_gadgets(){
	$$('.iam_gadget').each(function(e){
		var cnames = e.className
		var replacement_url = cnames.split(' ').last()

		var elem_id = e.id+"_g"
		new Insertion.After(e,'<span id="'+elem_id+'"">Loading Gadget...</span>');
		e.remove()
		new Ajax.Request("/gadgets/get"+replacement_url,
		 {asynchronous:true, evalScripts:true, 
	    		  onFailure:function(request){$(elem_id).innerHTML= 'Error loading Gadget...'},
			   onSuccess:function(request){
				post_gadget_update(elem_id,request.responseText)
			}
		 }
		);

	})
}

addLoadEvent(insert_gadgets)

function post_gadget_update(elem,text){
	var text = text.strip();
	var e2 = $(elem)
	
	var agt=navigator.userAgent.toLowerCase();
	if(agt.indexOf('msie') != -1){
		//crickey 
		// we can't just use replace or update because IE is insane
		e2.innerHTML = ''
		var d = document.createElement('span')
		d.innerHTML = text;
		e2.appendChild(d)
		setTimeout(function() {text.evalScripts()}, 3);

	}else{//sane browsers
		e2.update(text)
	}
}

/* This is broken. But I'm not sure how...
function inspect(object){
	var s = ''
	for(property in object){
		var val = object[property];
		if(typeof(val)  == 'function') s+= property+",function; "
		else s+= property+","+val+"; "
	}
	return s
}
*/
