$(function(){
	//Get our elements for faster access and set overlay width
	var div = $('#topic'),
		ul = $('#topic-table'),
		ulPadding = 15;
	
	//Get menu width
	var divWidth = div.width();
	$(window).resize(function(){
  		divWidth = div.width();
	});
	
	//Remove scrollbars	
	div.css({overflow: 'hidden'});

	//Find last image container
	var lastLi = ul.find('tr:last-child');
	
	//When user move mouse over menu
	div.mousemove(function(e){
		//As images are loaded ul width increases,
		//so we recalculate it each time
		var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;	
		var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
		div.scrollLeft(left);
		//console.log("left: "+left);
	});
	
	var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;	
		var left = (ulWidth - div.offset().left) * (ulWidth-divWidth) / divWidth;
		div.scrollLeft(left);
	//setTimeout(function(){},500);
	
	$('div.gallery > a').each(function(){
		
		$(this).click(function(){
			$('#image > img').attr('src',$(this).attr('rel'));
		});
		
		$(this).attr('rel',$(this).attr('href'));
		$(this).attr('href','javascript:void(0);');
		$(this).removeAttr('target');
	});
	
	$.nyroModalSettings({
			processHandler: function(settings) {
				var url = settings.url;
				if (url && url.indexOf('http://www.youtube.com/watch?v=') == 0) {
					$.nyroModalSettings({
						type: 'swf',
						height: 355,
						width: 425,
						url: url.replace(new RegExp("watch\\?v=", "i"), 'v/')
					});
				}
				
				if (url && url.indexOf('http://vimeo.com/') == 0) {
					$.nyroModalSettings({
						type: 'swf',
						height: 355,
						width: 425,
						url: url.replace('http://vimeo.com/', 'http://vimeo.com/moogaloop.swf?server=vimeo.com&amp;clip_id=')
					});
				}
			},
			endShowContent: function(elts, settings) {
				$('.resizeLink', elts.contentWrapper).click(function(e) {
					e.preventDefault();
					$.nyroModalSettings({
						width: Math.random()*1000,
						height: Math.random()*1000
					});
					return false;
				});
				$('.bgLink', elts.contentWrapper).click(function(e) {
					e.preventDefault();
					$.nyroModalSettings({
						bgColor: '#'+parseInt(255*Math.random()).toString(16)+parseInt(255*Math.random()).toString(16)+parseInt(255*Math.random()).toString(16)
					});
					return false;
				});
			}
		});
		
		function preloadImg(image) {
			var img = new Image();
			img.src = image;
		}

		preloadImg('gfx/ajaxLoader.gif');
		preloadImg('gfx/prev.gif');
		preloadImg('gfx/next.gif');

});
