var expanded = {};
var details = {};
var xdivs = {};
var thumbwidth = 100;

window.addEvent('load', function() {
	//setup
	odivs= $$('.xpandimage');
	//copy the expanding elements so that the page doesn't reflow when expanding them
	xdivs = odivs.clone();
	xdivs.each(function(xdiv, i){
		//briefly change the position style so we can get the proper top/left values
		odivs[i].setStyle("position", "absolute");
		var w = parseInt(odivs[i].firstChild.width);
		var h = parseInt(odivs[i].firstChild.height);
		var t = parseInt(odivs[i].getPosition().y +5);
		var l = parseInt(odivs[i].getPosition().x);
		var a = w/h;
		odivs[i].setStyle("position", "static");
		//position the copied div over the 
		xdiv.setStyle("position", "absolute");
		xdiv.setStyle("top", t);
		xdiv.setStyle("left", l);
		details[i] = {top:t, left: l, aspect:a}
		//hide the copy
		xdiv.setStyle("visibility", "hidden");
		//add it into the DOM
		xdiv.injectBefore('mainContainer');
	});
	var ximages = $$('.xpandimage img');
	//transitions for the container element and the image
	var dfxo = new Fx.Elements(xdivs, {wait: false, duration: 350, transition: Fx.Transitions.Cubic.easeOut});
	var dfxi = new Fx.Elements(xdivs, {wait: false, duration: 350, transition: Fx.Transitions.Cubic.easeOut});
	var ifxo = new Fx.Elements(ximages, {wait: false, duration: 350, transition: Fx.Transitions.Cubic.easeOut});
	var ifxi = new Fx.Elements(ximages, {wait: false, duration: 350, transition: Fx.Transitions.Cubic.easeOut});
	
	var od = {}, oi = {};
	//add the mouse events to the elements
	odivs.each(function(odiv, i){
		expanded[i] = false;
		dfxi.addEvent('onComplete', function(){ if(!expanded[i]){xdivs[i].setStyle("visibility","hidden");odiv.setStyle("visibility", "visible");}});
		dfxo.addEvent('onStart', function(){ if(expanded[i]){xdivs[i].setStyle("visibility","visible")}});

		odiv.addEvent("click", function(event) {
			xdivs[i].setStyle("visibility", "visible");
			nwh = odiv.getProperty("expandto").split(",");
			nw = nwh[0];
			nh = nwh[1];
			nt = (window.getHeight()/2) - (nh/2) + window.getScrollTop();
			nl = (window.getWidth()/2) - (nw/2);
			if(nt < 10) nt=5;
			if(nl<10) nl=10;

			od[i] = {top: nt, left: nl}
			oi[i] = {width: nw, height: nh}
			odiv.setStyle("visibility", "hidden");
			dfxo.start(od);
			ifxo.start(oi);
			expanded[i] = true;
		});

		xdivs[i].addEvent("click", function(event) {
			od[i] = {top:details[i].top, left:details[i].left}
			oi[i] = {width:thumbwidth, height:(thumbwidth / details[i].aspect) }
			dfxi.start(od);
			ifxi.start(oi);
			expanded[i] = false;
		});
	});
});
