var reloadRotationTimer;
var updateRotationTimer;
var rotationIndex = 0;
var rotationFx;
var rotationData = Array();

function rotationReload() {
	var jsonRequest = new Request.JSON({url: "/ajax/media/rotation/", data: {'action': 'getMedia'}, onSuccess: function(result) {
		if(!result['errors']) {
			if(!rotationData.length) $('rotationImage').addEvent('load', function() { rotationUpdateEvent(1) });
			
			if(result['data'] && result['data'].length) {
				rotationData = result['data'];
				rotationIndex = 0;
				setRotationUpdateTimer();
				setRotationReloadTimer();
			}
		}
	}, onFailure: function() {
		logger('Ошибка при получении данных настроек!');
	}}).post();
}

function rotationUpdateEvent(mode) {
	if(!rotationFx) rotationFx = new Fx.Morph($('rotationHolder'), {duration: 600,
																	link: 'chain',
																	transition: Fx.Transitions.linear,
																	onComplete: rotationUpdate
																	});
	
	if(mode) {
		rotationFx.start({'opacity':[0,1]});
	} else {
		rotationFx.start({'opacity':[1,0]});
	}
}

function rotationUpdate(el) {
	if(!$('rotationHolder').getStyle('opacity')) {
		var item = rotationData[rotationIndex];
		
		$('rotationImage').setProperties ({
			'src': item['url'],
			'width': item['width'],
			'height': item['height'] 
		});
		
		$('rotationUserLink').setProperties ({
			'href': ('http://' + item['userLogin'] + '.sharpness.ru/'),
			'html': item['userLogin']
		});
		
		$('rotationLink').setProperties({'href': item['link'] });
		
		if(item['community']) {
			$('rotationCommLinkHolder').removeClass('hidden');
			$('rotationCommLink').setProperties({'html': item['community'], 'href': item['communityUrl']});
		} else {
			$('rotationCommLinkHolder').addClass('hidden');
		}
	
		rotationIndex++; if(rotationIndex == rotationData.length) rotationIndex = 0;
	} else {
		setRotationUpdateTimer();
	}
}

function setRotationUpdateTimer() {
	if(!updateRotationTimer) updateRotationTimer = window.setInterval('rotationUpdateEvent()', 10000);
}

function setRotationReloadTimer(n) {
	if(!n) n = 60000 * 12;
	if(!reloadRotationTimer) reloadRotationTimer = window.setInterval('rotationReload()', n);
}