﻿/*
______   __                  __    _          _    
|_   __ \[  |                [  |  (_)        / |_  
| |__) || |  ,--.    _   __ | |  __   .--. `| |-' 
|  ___/ | | `'_\ :  [ \ [  ]| | [  | ( (`\] | |   
_| |_    | | // | |,  \ '/ / | |  | |  `'.'. | |,   
|_____|  [___]\'-;__/[\_:  / [___][___][\__) )\__/  
\__.'                         

*/
var myplaylist = null;
$(function () {
	myplaylist = {
		currentIndex: null,
		// View Data
		trackRow: "<li class='now-playing-toggled-list clearfix'>" +
						"<div class='now-playing-toggled-title' title='Click and drag to move this video to another location'>" +
							"<a href='{path}' title=''>" +
								"<span class='now-playing-toggled-title-song'>{trackName}</span> " +
								"<span class='now-playing-toggled-title-artist'>{artistName}</span>" +
							"</a>" +
						"</div>" +
						"<div class='now-playing-toggled-delete'>" +
							"<a href='#' title='Remove this Track'>Remove</a>" +
						"</div>" +
					"</li>",
		data: [],
		init: function () {
			//load the cookies
			this.load();

			// Drag and drop the tracks. 
			$(".now-playing-toggled ul")
				.sortable({
					axis: 'y',
					placeholder: 'now-playing-toggled-blank',
					cursor: 'move',
					opacity: 0.6,
					update: function (event, ui) {
						myplaylist.resortVideos();
					},
					start: function (event, ui) {
						$(".now-playing-toggled-blank")
							.html("<span>Drop Here...</span>");

					}
				})


			$(".now-playing-toggled ul")
				.disableSelection();

			//Playing a track
			$(".now-playing-toggled ul .now-playing-toggled-title a").click(function (event) {
				event.preventDefault();
				myplaylist.playVideo($('.now-playing-toggled ul li').index($(this).parents('li.now-playing-toggled-list')));
				return false;
			});
			$(".current-playlist-play #current-playlist-play-button").click(function (event) {
				event.preventDefault();
				if (myplaylist.currentIndex != null) {
					myplaylist.stopPlaylist();
				} else {
					myplaylist.playVideo(0);
				}

				return false;
			});
			$("#delete-playlist-dialog-message").dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				closeOnEscape: true,
				show: 'fade',
				dialogClass: 'delete-all-tracks',
				zIndex: 3000000,
				buttons: {
					Ok: function () {
						myplaylist.deleteAllPlaylistItems();
						$(this).dialog("close");
					},
					Cancel: function () {
						$(this).dialog("close");
					}
				}
			});

			//Deleting a single track
			$(".now-playing-toggled ul li .now-playing-toggled-delete a").click(function (event) {
				event.preventDefault();
				myplaylist.deleteVideo($('.now-playing-toggled ul li').index($(this).parents('li.now-playing-toggled-list')));
				$(this).parents('li.now-playing-toggled-list').remove();
				return false;
			});

			//"Add To Playlist" Links on the page
			$(".add-to-playlist").click(function () {
				try {
					var video = $(this).attr('rel').split(',');
				} catch (e) { alert('Error parsing video data'); }

				if (video) {
					myplaylist.addVideo(video[0], video[1], video[2], video[3]);
				} else {
					alert("playlist link has no data.");
				}
				return false;
			});
			if (this.currentIndex != null) {
				$(".global-currently-playing-list p span#min-playing").show();
				$(".current-playlist-play .wunderbar-spinner").show();
				$(".current-playlist-play").addClass("current-playlist-playing");
			}
			// update the delete all tracks toolbar button:
			this.updateDeleteAllTracksBtn();
		},
		// Events
		onVideoPlaying: function (e) {
			//Sweet;
		},
		onVideoComplete: function (e) {
			this.nextVideo();
		},
		onVideoPaused: function (e) {

		},
		stopPlaylist: function (e) {
			$(".global-currently-playing-list p span#min-playing").hide();
			$(".current-playlist-play .wunderbar-spinner").hide();
			$(".current-playlist-play").removeClass("current-playlist-playing");
			this.currentIndex = null;
		},
		//API
		playVideo: function (index) {
			//set a cookie for the index
			var d = new Date(2020, 02, 02);
			var p = '/';
			document.cookie = "soundcheck_playlist_track=" + index
			+ ';path=' + p
			+ ';expires=' + d.toUTCString();

			top.location.href = "/" + this.data[index].path;
			return false;
		},
		nextVideo: function (currentVideoID) {
			if (this.currentIndex != null && currentVideoID == this.data[this.currentIndex].videoID) {
				this.currentIndex = (this.currentIndex + 1 >= this.data.length) ? 0 : this.currentIndex + 1;
				this.playVideo(this.currentIndex);
			}
		},
		prevVideo: function () {
			if (this.currentIndex != null) {
				this.currentIndex = (this.currentIndex - 1 < 0) ? this.data.length - 1 : this.currentIndex - 1;
				this.playVideo(this.currentIndex);
			}
		},
		addVideo: function (artistName, trackName, videoID, path) {
			var trackData = { artistName: artistName, trackName: trackName, videoID: videoID, path: path };
			this.data.push(trackData);
			this.save();
			var newTrackRow = this.trackRow.replace('{trackName}', trackName);
			newTrackRow = newTrackRow.replace('{artistName}', artistName);
			newTrackRow = newTrackRow.replace('{path}', "/" + path);
			var trackRowListItem = $(newTrackRow);
			//Storing the track data in the playbutton because I dont want it 
			//to be mixed in with the sorting data from jQuery UI.
			$(trackRowListItem).children('.now-playing-toggled-title')
				.data(trackData)
				.tipTip({
					defaultPosition: "left",
					delay: 300
				})
				.hover(function (event) {
					$(this).find('span').addClass("now-playing-toggled-title-hover");
				}, function (event) {
					$(this).find('span').removeClass("now-playing-toggled-title-hover");
				});
			$(trackRowListItem).children(".now-playing-toggled-title a").click(function (event) {
				event.preventDefault();
				myplaylist.playVideo($('.now-playing-toggled ul li').index($(this).parents('li.now-playing-toggled-list')));
				return false;
			});
			//$(trackRowListItem).children('a').click(  this.setToPlayTrack);
			$('.now-playing-toggled ul').append($(trackRowListItem));
			this.updatePlaylistCount();
		},
		resortVideos: function () {
			var oldData = this.data;
			this.data = [];
			$(".now-playing-toggled ul .now-playing-toggled-title")
				.each(function (index, item) {
					//if this item is currently selected then reset the index to this one.
					myplaylist.data.push($(this).data());
				})
				.removeClass(".now-playing-toggled-title-hover");

			this.save();
		},
		deleteVideo: function (index) {
			this.data.splice(index, 1);
			this.save();
			this.updatePlaylistCount();
		},
		updatePlaylistCount: function () {
			$(".global-currently-playing-list span").html("My Custom Playlist (" + this.data.length + " Tracks)");
			$(".current-playlist-module .current-playlist-title h4 span").html("(" + this.data.length + " Tracks)");
			this.updateDeleteAllTracksBtn();
		},
		// Cookies
		load: function () {
			//Load the playlist as a JSON string
			var cookies = document.cookie.split(';');
			var playlist_cookie = null;
			for (cookie in cookies) {
				if (cookies[cookie].indexOf("soundcheck_playlist=") != -1) {
					playlist_cookie = unescape(cookies[cookie].substring(21, cookies[cookie].length));
					this.data = JSON.parse(playlist_cookie);
					//Storing the track data in the playbutton because I dont want it 
					//to be mixed in with the sorting data from jQuery UI.
					$(".now-playing-toggled ul .now-playing-toggled-title").each(function (index) {
						$(this).data(myplaylist.data[index]);
					});
					//alert(playlist_cookie);
				} /*else if (cookies[cookie].indexOf("soundcheck_playlist_track=") != -1) {
					this.currentIndex = parseInt(cookies[cookie].substring(27, cookies[cookie].length));
				}*/
			}
			this.currentIndex = currentTrackIndex;
			/*
			if (the_cookie[0]) {
			this.data = unescape(JSON.parse(the_cookie[0].substring(1,));
			}*/
			return this.data;

		},
		save: function (expires, path) {
			// Write the object as a JSON string
			var d = expires || new Date(2020, 02, 02);
			var p = path || '/';
			document.cookie = "soundcheck_playlist=" + escape(JSON.stringify(this.data))
			+ ';path=' + p
			+ ';expires=' + d.toUTCString();

		},
		deleteAllPlaylistItems: function () {
			$('.now-playing-toggled ul li').remove();
			myplaylist.data = [];
			myplaylist.save();
			this.disableDeleteAllTracksBtn();
		},
		updateDeleteAllTracksBtn: function () {
			// if there are no items in the playlist, then there is no need for the Delete All Tracks button, so disabled it:
			if (this.data.length > 0) {
				this.enableDeletaAllTracksBtn()
			} else {
				this.disableDeleteAllTracksBtn();
			}
		},
		enableDeletaAllTracksBtn: function () {
			// enables the button:
			$('#now-playing-toggled-toolbar-delete-all')
				.removeClass('now-playing-toggled-toolbar-item-disabled')
				.addClass('now-playing-toggled-toolbar-item-active')
				.unbind('click')
				.bind('click', function (event) {
					event.preventDefault();
					$("#delete-playlist-dialog-message").dialog('open');
				});
		},
		disableDeleteAllTracksBtn: function () {
			// disables the button:	
			$('#now-playing-toggled-toolbar-delete-all')
				.unbind('click')
				.bind('click', function(event) { event.preventDefault() } )
				.removeClass('now-playing-toggled-toolbar-item-active')
				.addClass('now-playing-toggled-toolbar-item-disabled');
		},
	}
	myplaylist.init();
});


