/**
 * @author ricky
 */
window.addEvent('domready', function() {
	var play_list_items = $$('.play-list li');
	var track_title_places = $$('.track-title');

	var track_usage_places = $$('.usage-place');
	var track_feeling_places = $$('.feeling-place');
	var track_instrument_places = $$('.instrument-place');
	var track_association_places = $$('.association-place');
	var track_lyrics_places = $$('.lyrics-place');
	var track_genre_places = $$('.genre-place');

	var album_title_places = $$('dd.album-title');
	var category_title_places = $$('dd.category-title');
	var player_play = $('play');
	var progress_load = $('progress-load');
	var progress_play = $('progress-play');
	var progress_handler = $('progress-handler');
	var progress_handler_container = $('progress-handler-container');
	var overlay = $('popup-background');
	var form = $('form-container');
	var track_title_container = $('track-title-container');
	var track_id = $('track-id');
	var album_pic_places = $$('.album_pic');

	function buy(e) {
		var evt = new Event(e);
		evt.stop();

		overlay.show();
		form.show();
		track_title_container.set('text', this.getPrevious('.title')
						.get('text'));
		track_id.value = this.getPrevious('.track-id').value;
	}

	function toHTML(str) {
		str = str.replace('&gt;', '>');
		str = str.replace('&lt;', '<');
		return str;
	}

	function soundComplete() {
		Playlist.stopSounds();

		for (var i = 0, len = play_list_items.length; i < len; i++) {
			if (play_list_items[i].hasClass('playing')) {
				play_list_items[i].removeClass('playing');
				if (play_list_items[i + 1]) {
					var index = i + 1;
				} else {
					var index = 0;
				}
				$each(track_title_places, function(place) {
					place.set('text', play_list_items[index].retrieve('title'));
				});
				$each(track_genre_places, function(place) {
							place.set('html', play_list_items[index]
											.retrieve('genres')
											+ '&nbsp;');
						});
				$each(track_usage_places, function(place) {
							place.set('html', play_list_items[index]
											.retrieve('usages')
											+ '&nbsp;');
						});
				$each(track_feeling_places, function(place) {
							place.set('html', play_list_items[index]
											.retrieve('feelings')
											+ '&nbsp;');
						});
				$each(track_instrument_places, function(place) {
							place.set('html', play_list_items[index]
											.retrieve('instruments')
											+ '&nbsp;');
						});
				$each(track_lyrics_places, function(place) {
							place.set('html', play_list_items[index]
											.retrieve('lyrics')
											+ '&nbsp;');
						});
				$each(track_association_places, function(place) {
							place.set('html', play_list_items[index]
											.retrieve('associations')
											+ '&nbsp;');
						});
				if (play_list_items[index].retrieve('album_pic')) {
					$each(album_pic_places, function(place) {
								place.set('html', play_list_items[index]
												.retrieve('album_pic'));
							});
				}
				$each(album_title_places, function(place) {
							place.set('html', '<a href="/catalog/'
											+ play_list_items[index]
													.retrieve('category_id')
											+ '/'
											+ play_list_items[index]
													.retrieve('album_id')
											+ '/">'
											+ play_list_items[index]
													.retrieve('album_title')
											+ '</a>');
						});
				$each(category_title_places, function(place) {
							place.set('html', '<a href="/catalog/'
											+ play_list_items[index]
													.retrieve('category_id')
											+ '/">'
											+ play_list_items[index]
													.retrieve('category_title')
											+ '</a>');
						});
				play_list_items[index].addClass('playing');
				player_play.removeClass('play').addClass('pause');
				Playlist.getSound(play_list_items[index].retrieve('sound'))
						.start();
				break;
			}
		}
	}

	function play(e, sound) {
		new Event(e).stop();
		var li = this.getParent();

		if (li.hasClass('playing')) {
			li.removeClass('playing').addClass('paused');
			player_play.addClass('play').removeClass('pause');
			Playlist.getSound(sound).pause();
		} else if (li.hasClass('paused')) {
			li.removeClass('paused').addClass('playing');
			player_play.addClass('pause').removeClass('play');
			Playlist.getSound(sound).start();
		} else {
			// стартуем трек
			$each(play_list_items, function(/* Element */item) {
						item.removeClass('playing').removeClass('paused');
					});
			li.removeClass('paused').addClass('playing');
			$each(track_title_places, function(place) {
						place.set('html', li.retrieve('title') + '&nbsp');
					});
			$each(track_genre_places, function(place) {
						place.set('html', li.retrieve('genres'));
					});
			$each(track_lyrics_places, function(place) {
						place.set('html', li.retrieve('lyrics'));
					});
			$each(track_association_places, function(place) {
						place.set('html', li.retrieve('associations'));
					});
			$each(track_instrument_places, function(place) {
						place.set('html', li.retrieve('instruments'));
					});
			$each(track_usage_places, function(place) {
						place.set('html', li.retrieve('usages'));
					});
			$each(track_feeling_places, function(place) {
						place.set('html', li.retrieve('feelings'));
					});
			$each(album_title_places, function(place) {
						place.set('html', '<a href="/catalog/'
										+ li.retrieve('category_id') + '/'
										+ li.retrieve('album_id') + '/">'
										+ li.retrieve('album_title') + '</a>');
					});
			$each(category_title_places, function(place) {
						place.set('html', '<a href="/catalog/'
										+ li.retrieve('category_id') + '/">'
										+ li.retrieve('category_title')
										+ '</a>');
					});
			if (li.retrieve('album_pic')) {
				$each(album_pic_places, function(place) {
							place.set('html', li.retrieve('album_pic'));
						});
			}
			player_play.removeClass('play').addClass('pause');
			Playlist.stopSounds();
			Playlist.getSound(sound).start();
		}
	}

	var updatePosition = (function() {
		var position_holder = $('position');

		return function(pos, total, sound) {
			var minutes = Math.floor(pos / 60);
			var seconds = pos - (minutes * 60);
			seconds = (seconds + '').length > 1 ? seconds : '0' + seconds
			minutes = (minutes + '').length > 1 ? minutes : '0' + minutes
			position_holder.set('text', minutes + ':' + seconds);
			var position = ((pos / total) * 182).toInt();
			progress_play.setStyle('backgroundPosition', (position - 181)
							+ 'px');
			progress_handler.setStyle('left', position);
		}
	})();

	$each(play_list_items, function(/* Element */item) {
		var sound = item.getElement('input.path').value;
		item.store('sound', sound);
		var title = item.getElement('span.title').get('html').trim();
		item.store('title', title);
		var album_id = item.getElement('input.album-id').value.trim();
		item.store('album_id', album_id);
		var album_title = item.getElement('input.album-title').value.trim();
		item.store('album_title', album_title);
		var category_id = item.getElement('input.category-id').value.trim();
		item.store('category_id', category_id);
		var category_title = item.getElement('input.category-title').value
				.trim();
		item.store('category_title', category_title);
		var genres = toHTML(item.getElement('input.genres').value.trim());
		item.store('genres', genres);
		var associations = toHTML(item.getElement('input.associations').value
				.trim());
		item.store('associations', associations);
		var usages = toHTML(item.getElement('input.usages').value.trim());
		item.store('usages', usages);
		var feelings = toHTML(item.getElement('input.feelings').value.trim());
		item.store('feelings', feelings);
		var instruments = toHTML(item.getElement('input.instruments').value
				.trim());
		item.store('instruments', instruments);
		var lyrics = toHTML(item.getElement('input.lyrics').value.trim());
		item.store('lyrics', lyrics);
		var album_pic = item.getElement('input.album-pic');
		if (album_pic) {
			item.store('album_pic', '<img src="/i/catalog/108/119/'
							+ album_pic.value.trim() + '" />');
		}

		var play_button = item.getElement('a.play');
		play_button.addEvent('click', play.bindWithEvent(play_button, sound));

		var buy_button = item.getElement('a.buy');
		if (buy_button) {
			buy_button.addEvent('click', buy);
		}

		Playlist.loadSound(sound, {
					onPosition : updatePosition,
					onComplete : soundComplete,
					onProgress : function(loaded, total) {
						if (arguments.length > 1) {
							if (!loaded && !total && total !== 'undefined') {
								loaded = 0;
								total = 1;
							}
						} else {
							loaded = 0;
							total = 1;
						}
						progress_load
								.setStyle(
										'backgroundPosition',
										(((loaded / total) * 195).toInt() - 194)
												+ 'px');
					},
					volume : 100,
					positionInterval : 1000
				});
	});

	player_play.addEvent('click', function(e) {
		new Event(e).stop();
		if (this.hasClass('pause')) {
			// если трек нужно поставить на паузу
			this.removeClass('pause').addClass('play');
			$each(play_list_items, function(item) {
						if (item.hasClass('playing')) {
							item.addClass('paused').removeClass('playing');
							Playlist.getSound(item.retrieve('sound')).pause();
						}
					});
			return;
		}
		if (this.hasClass('play')) {
			// если трек нужно заиграть
			this.addClass('pause').removeClass('play');

			if (Playlist.playing.length) {
				// если уже играл какой-то трек
				$each(play_list_items, function(item) {
							if (item.hasClass('paused')) {
								item.removeClass('paused').addClass('playing');
								Playlist.getSound(item.retrieve('sound'))
										.start();
							}
						});
			} else {
				// если мы только загрузили трек
				play_list_items[0].addClass('playing');
				Playlist.getSound(play_list_items[0].retrieve('sound')).start();
				$each(track_title_places, function(place) {
							place.set('text', play_list_items[0]
											.retrieve('title'));
						});
				$each(track_genre_places, function(place) {
							place.set('html', play_list_items[0]
											.retrieve('genres')
											+ '&nbsp;');
						});
				if (play_list_items[0].retrieve('album_pic')) {
					$each(album_pic_places, function(place) {
								place.set('html', play_list_items[0]
												.retrieve('album_pic'));
							});
				}
				$each(album_title_places, function(place) {
							place.set('html', '<a href="/catalog/'
											+ play_list_items[0]
													.retrieve('category_id')
											+ '/'
											+ play_list_items[0]
													.retrieve('album_id')
											+ '/">'
											+ play_list_items[0]
													.retrieve('album_title')
											+ '</a>');
						});
				$each(category_title_places, function(place) {
							place.set('html', '<a href="/catalog/'
											+ play_list_items[0]
													.retrieve('category_id')
											+ '/">'
											+ play_list_items[0]
													.retrieve('category_title')
											+ '</a>');
						});
			}
			return;
		}
	});

	var volume_container = $('volume-container');
	new Slider($('volume-drag-container'), $('volume-drag-handler'), {
				steps : 12,
				mode : 'horizontal',
				onChange : function(step) {
					volume_container.setStyle('backgroundPosition',
							(-35 + (step * 2.918).toInt()) + 'px 50%');
				},
				onComplete : function(step) {
					if (Playlist.flashLoaded) {
						var sounds = Playlist.getSounds();
						for (var i = 0, len = sounds.length; i < len; i++) {
							sounds[i]
									.setVolume((step * 2.9 / 35 * 100).round());
						}
					}
				}
			}).set(35);

	progress_handler_container.addEvent('click', function(e) {
				var playing_sound = Playlist.getPlayingSound();
				if (playing_sound && playing_sound.isLoaded()) {
					var relative_x = new Event(e).client.x
							- this.getPosition().x;
					if (relative_x > 182)
						relative_x = 180;
					var duration = playing_sound.getDuration() * 10;
					var needed_progress = (relative_x - 6) / 182;
					var pos = (needed_progress * duration).round();

					playing_sound.jumpTo(pos);
					updatePosition(pos, duration.round(), playing_sound);
				}
			});
});
