var RefGallery = {};

RefGallery.setData = function(topsites)
{
	//populate Lightbox
	for (var i=0; i<topsites.length; i++)
		Lightbox.imageArray.push([topsites[i].image, topsites[i].title]);
	
	this.data = topsites;
};

RefGallery.create = function() 
{
	var data = this.data;
	var outA = [];
	function out(s) {outA.push(s);};
	out('<div id="imgFl" style="position:relative;overflow:hidden;width:850px; height:200px;">');
	out('<div id="referenceSlide" style="width:1500px;position:relative;left:0px">');
	
	for (var i=0; i<data.length; i++)
	{
		out(
			'<a title="'+data[i].site+'" href="'+data[i].image+'" onclick="return Lightbox.start('+i+');">' +
			'<img style="float:left; margin:5px; width:140px; height: 100px" '+
			'class="reflect" '+
			'onload="Reflection.add(this)" ' +
			'src="'+data[i].thumb+'"/>' +
			'</a>');
	}

	Event.observe(window, 'load', RefGallery.start);
	
	out('<div style="clear:both"></div>');
	out('</div>');
	out('</div>');
	return outA.join('');
};

RefGallery.start = function()
{
	var newPos = 0;
	var crtPos = 0;
	var x0 = Element.cumulativeOffset($('referenceSlide')).left + 50;
	$('referenceSlide').observe('mousemove', function(evt) {
		//var x0 = 265 + 50;
		var x1 = 850 - 50;
		var diff = 1500-x1;
		newPos = (x0  - evt.pointerX())/x1 * diff;
	});
	
	$('referenceSlide').observe('click', function(evt) {
		popup({title:'domain', largeSrc:"static/images/reference/cr_big01.jpg", author:"Author 1", link:"http://www.google.com"});
	});


	setInterval(function() {
		crtPos += (newPos - crtPos) / 1.7;
		$('referenceSlide').style.left = crtPos + 'px';
	}, 50);
	
};

RefGallery.getHTML = function() {
	return '<div id="ContentContainer">' +
	'<div id="_imgPlace">' +
	RefGallery.create() +
	'</div>' +
	'<div id="imgPopup">' +
	'</div>' +
	'<div class="noFloat"></div>' +
	'</div>';
};

RefGallery.init = function() {
	//document.write(RefGallery.getHTML());
	RefGallery.multiLoad(baseUrl,
				[
				 	'/index/topsites-js',
					'/static/js/lightbox/lightbox.js',
					'/static/js/gallery/reflection.js',
					'/static/js/pop.js',
				]
			, function() {
				RefGallery.setData(topsitesData);
				$('InternalContent').innerHTML = RefGallery.getHTML();
				RefGallery.start();
				new Lightbox();
			  });
};

RefGallery.loadScript = function (url, onload)
{
	var script = document.createElement('script');
	if (document.all)
	{
		script.onreadystatechange = function() {
			if (this.readyState == 'loaded')
				onload();
		};
	}
	else
		script.onload = onload;
	script.type = 'text/javascript';
	script.src = url;
	document.getElementsByTagName("head")[0].appendChild(script);
};

RefGallery.multiLoad = function (base, urls, onload)
{
	RefGallery.loadScript(base+urls.shift(), function() {
		urls.length ? RefGallery.multiLoad(base, urls, onload) : onload();
	});
};

Event.observe(window, 'load', function() {
	setTimeout(RefGallery.init, 100);
});