var MadLogo = window.MadLogo = {
	width:	270,	// Ширина
	height:	100,	// Высота анимируемой области
	image1: $( '#logo-patten-1' ), // Картинки, которые будут елозить, первая
	image2: $( '#logo-patten-2' ), // и вторая
	delay:	8.0,		// Задержка между шагами анимации, в секундах
	patterns: [],	// Паттерны, массив объектов Image
	prev:	null
};

MadLogo.loadPatterns = function ( patterns ) {
	for( var i = 0; i < patterns.length; i++ ) {
		var pattern = new Image( this.width, this.height );
		pattern.src = patterns[ i ];
		this.patterns.push( pattern );
	}
	return this;
};

MadLogo.getNextPattern = function () {
	var next;
	do {
		next = Math.floor( Math.random() * this.patterns.length );
	} while( next === this.prev );
	this.prev = next;
	return this.patterns[ next ];
};

MadLogo.waitForImage = function ( image, callback ) {
	if( image.complete ) {
		callback( image );
	} else {
		setTimeout( Function.callback( Function.delegate( this, this.waitForImage ), image, callback ), 100 );
	}
	return this;
};

MadLogo.animate = function ( patterns ) {
	// Прячем первую картинку
	this.image2.fadeOut( 0 );

	// Инициируем загрузку паттернов
	this.loadPatterns( patterns );

	// Выбираем следующий паттерн, ждем его загрузки и выполняем fadeIn первого кадра
	this.waitForImage( this.getNextPattern(), Function.delegate( this, function ( image ) {
		this.image2.attr( 'src', image.src ).fadeIn( 1200, Function.delegate( this, this.wheee ) );
	} ) );
	
	return this;
};

MadLogo.wheee = function () {
	this.waitForImage( this.getNextPattern(), Function.delegate( this, this.doWheee ) );
	return this;
};

MadLogo.doWheee = function ( image ) {
	// image1 приезжает из pos1 в 0,0
	// image2 уезжает из 0,0 в pos2
	
	var pos1 = { left: '0px', top: '0px' };
	var pos2 = { left: '0px', top: '0px' };
	switch( Math.floor( Math.random() * 4 ) ) {
	case 0:
		pos1.left = '-' + this.width + 'px';
		pos2.left = this.width + 'px';
		break;
	case 1:
		pos1.top = '-' + this.height + 'px';
		pos2.top = this.height + 'px';
		break;
	case 2:
		pos1.left = this.width + 'px';
		pos2.left = '-' + this.width + 'px';
		break;
	case 3:
		pos1.top = + this.height + 'px';
		pos2.top = '-' + this.height + 'px';
		break;
	}
	
	// Переместим image1 на стартовую позицию, назначим картинку и включим перекрывание
	this.image1.attr( 'src', image.src ).css( pos1 ).css( { zIndex: 1 } );

	jTweener.addTween( this.image1, {
		delay: this.delay - 2.0,
		time: 1.5,
		transition: 'easeInOutQuad',
		left: '0px',
		top: '0px'
	} );

	jTweener.addTween( this.image2, {
		delay: this.delay - 1.5,
		time: 1.5,
		transition: 'easeInOutQuad',
		left: pos2.left,
		top: pos2.top,
		onComplete: Function.delegate( this, function () {
			this.image1.css( { zIndex: 0 } );
			var tmp = this.image1;
			this.image1 = this.image2;
			this.image2 = tmp;
			this.wheee();
		} )
	} );
	
	return this;
};
