﻿/// <reference path="jquery.js" />
/// <reference path="../flash/framework/swfobject/swfobject.js" />

var twVideoPlayer = {
	playlist: null,
	autoplay: false,
	playerId: "twvideoplayer",
	width: 580,
	height: 472,
	deviceId: "",
	artist: "",
	title: "",
	album: "",
	songId: "",
	lang: "",
	user: "",
	groupId: "",
	videoId: "",
	vidSrc: "",
	player: null,
	isInit: false,
	isLoaded: false,
	init: function (args) {
		if (args != null) {
			this.width = args.width || this.width;
			this.height = args.height || this.height;
			this.artist = args.artist || this.artist;
			this.title = args.title || this.title;
			this.album = args.album || this.album;
			this.lang = args.lang || this.lang;
			this.user = args.user || this.user;
			this.deviceId = args.deviceId || this.deviceId;
			this.playerId = args.playerId || this.playerId;
			this.autoplay = args.autoplay || this.autoplay;
			this.videoId = args.videoId || this.videoId;
			this.vidSrc = args.vidSrc || this.vidSrc;
			if ($.isArray(args.playlist)) {
				this.playlist = args.playlist;
			}
		}

		if ($.isArray(this.playlist) && !this.artist && !this.title) {
			try {
				this.artist = this.playlist[0][0];
				this.title = this.playlist[0][1];
				this.album = this.playlist[0][2];
				this.songId = this.playlist[0][3];
			} catch (err) { }
		}

		if (this.artist && this.title) {
			$('body').trigger('nextVideo', [twVideoPlayer.artist, twVideoPlayer.title, twVideoPlayer.album, twVideoPlayer.songId]);

			if (navigator.userAgent.toLowerCase().search("iphone") > -1 || navigator.userAgent.toLowerCase().search("ipod") > -1) {
				// Load youtube player
				this.loadYouTube();
			} else if (this.playlist && this.playlist.length < 2) {
				this.loadFlashPlayer(true);
			} else if (this.autoplay) {
				// load video player
				this.play();
			} else {
				this.cue();
			}
		}
	},
	cue: function () {
		// Args handler
		var args = $.makeArray(arguments);
		var isInPlaylist = false;
		if (args.length >= 1 && $.isArray(args[0])) { // user passed in a playlist
			this.playlist = args.shift();
			isInPlaylist = true;
		} else if ((args.length >= 2)) { // user passed in a song
			if (args.length >= 2) {
				this.artist = args.shift();
				this.title = args.shift();
				this.album = args.shift() || "";
				this.vidSrc = args.shift() || "";
				this.videoId = args.shift() || "";
				this.songId = "";
			}
			if ($.isArray(this.playlist)) {
				for (var i = 0; i < this.playlist.length; i++) { // find the song in the last playlist
					if (!isInPlaylist && this.artist.toLowerCase() == this.playlist[i][0].toLowerCase() && this.title.toLowerCase() == this.playlist[i][1].toLowerCase()) {
						var temp1 = this.playlist.slice(0, i);
						var temp2 = this.playlist.slice(i);
						this.playlist = $.merge(temp2, temp1);
						isInPlaylist = true;
						this.album = this.playlist[0][2];
						this.songId = this.playlist[0][3];
						$('body').trigger('nextVideo', [twVideoPlayer.artist, twVideoPlayer.title, twVideoPlayer.album, twVideoPlayer.songId]);
					}
				}
			}
		} else if (args.length == 0 && $.isArray(this.playlist)) { // previous playlist
			isInPlaylist = true;
		}

		if (!this.isInit) {
			this.loadFlashPlayer();
		}

		if (!this.isLoaded) {
			setTimeout("twVideoPlayer.cue()", 1000);
			return;
		}

		//play
		try {
			if (this.videoId != "") {
				this.player.loadVideoById(this.vidSrc, this.videoId, this.artist, this.title, this.album, false);
			} else {
				this.player.loadPlaylist((isInPlaylist ? this.playlist : [[this.artist, this.title, this.album]]), 0, false);
			}
		} catch (err) {
			setTimeout("twVideoPlayer.cue()", 1000);
		}
	},
	loadYouTube: function (artist, title, autoplay) {
		// check for defaults
		this.artist = artist || this.artist;
		this.title = title || this.title;
		this.autoplay = autoplay || this.autoplay;

		// load
		var url = "http://lyrics.tunewiki.com/tunewiki/services/getYouTubeVideoXML?youtube=false&max=1&artist=" + encodeURIComponent(artist) + "&title=" + encodeURIComponent(title) + "&json=true&callback=?";
		$.getJSON(url, function (data) {
			$('#' + twVideoPlayer.playerId).html(
				'<object width="' + this.width + '" height="' + this.height + '"><param name="movie" value="http://www.youtube.com/v/' + data.results.video.video_id + '&hl=en&fs=1&"></param>' +
				'<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>' +
				'<embed src="http://www.youtube.com/v/' + data.results.video.video_id + '&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + this.width + '" height="' + this.height + '"></embed></object>'
			);
		});
	},
	loadFlashPlayer: function (initSong) {
		$('#' + twVideoPlayer.playerId).html("<div id='twvideoplayer_flash'>You need <a href='http://get.adobe.com/flashplayer/'>Flash player 10</a> and JavaScript enabled to view this video.</div>");
		var randomnumber = Math.floor(Math.random() * 100000000)
		var flashvars = {
			autoplay: this.autoplay,
			lang: this.lang,
			uuid: this.user,
			deviceId: this.deviceId
		};
		if (initSong) {
			flashvars.artist = encodeURIComponent(this.artist);
			flashvars.album = encodeURIComponent(this.album);
			flashvars.title = encodeURIComponent(this.title);
		}
		var params = {
			allowScriptAccess: "always",
			allowFullScreen: "true",
			quality: "high",
			wmode: "opaque",
			bgcolor: "#E1E3F0",
			movie: "/flash/videoplayer.swf?id=" + randomnumber
		};
		var attributes = {
			id: "twvideoplayer_video"
		};
		swfobject.embedSWF("/flash/videoplayer.swf?id=" + randomnumber, "twvideoplayer_flash", this.width, this.height, "10", "/Flash/Framework/swfobject/expressInstall.swf", flashvars, params, attributes);
		this.isInit = true;
	},
	play: function () {
		// Args handler
		var args = $.makeArray(arguments);
		var isInPlaylist = false;
		if (args.length >= 1 && $.isArray(args[0])) { // user passed in a playlist
			this.playlist = args.shift();
			isInPlaylist = true;
		} else if ((args.length >= 2)) { // user passed in a song
			if (args.length >= 2) {
				this.artist = args.shift();
				this.title = args.shift();
				this.album = args.shift() || "";
				this.vidSrc = args.shift() || "";
				this.videoId = args.shift() || "";
			}
			if ($.isArray(this.playlist)) {
				for (var i = 0; i < this.playlist.length; i++) { // find the song in the last playlist
					if (!isInPlaylist && this.artist.toLowerCase() == this.playlist[i][0].toLowerCase() && this.title.toLowerCase() == this.playlist[i][1].toLowerCase()) {
						var temp1 = this.playlist.slice(0, i);
						var temp2 = this.playlist.slice(i);
						this.playlist = $.merge(temp2, temp1);
						isInPlaylist = true;
						this.album = this.playlist[0][2];
						this.songId = this.playlist[0][3];
						$('body').trigger('nextVideo', [twVideoPlayer.artist, twVideoPlayer.title, twVideoPlayer.album, twVideoPlayer.songId]);
					}
				}
			}
		} else if (args.length == 0 && $.isArray(this.playlist)) { // previous playlist
			isInPlaylist = true;
		}

		if (!this.isInit) {
			this.loadFlashPlayer();
		}

		if (!this.isLoaded) {
			setTimeout("twVideoPlayer.play()", 1000);
			return;
		}

		//play
		try {
			// Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
			if (this.videoId != "" && this.vidSrc != "") {
				this.player.loadVideoById(this.vidSrc, this.videoId, this.artist, this.title, this.album, true);
			} else {
				this.player.loadPlaylist((isInPlaylist ? this.playlist : [[this.artist, this.title, this.album]]), 0, true);
			}
		} catch (err) {
			setTimeout("twVideoPlayer.play()", 1000);
		}
	},
	next: function () {
		if ($.isArray(this.playlist)) {
			var temp1 = this.playlist.slice(0, 1);
			var temp2 = this.playlist.slice(1);
			this.playlist = $.merge(temp2, temp1);
			this.cue(this.playlist[0][0], this.playlist[0][1]);
		}
	},
	prev: function () {
		if ($.isArray(this.playlist)) {
			var temp1 = this.playlist.slice(0, this.playlist.length - 1);
			var temp2 = this.playlist.slice(this.playlist.length - 1);
			this.playlist = $.merge(temp2, temp1);
			this.cue(this.playlist[0][0], this.playlist[0][1]);
		}
	},
	formatName: function (str) {
		return str.replace(/[']/g, '\\\'').toLowerCase();
	},
	markBadVideo: function () {
		if (confirm("Are you sure you want to mark this as an incorrect video for this song?")) {
			$.get("/handlers/webfetch.aspx?type=plain&getUrl=" + encodeURIComponent("http://lyrics.tunewiki.com/tunewiki/services/setBadGroupIdXML?bad=true&type=video&groupId=" + twVideoPlayer.groupId), function () {
				alert("Thank you for marking this video as incorrect.");
			});
		}
	}
};
////////////////////////////////////////////////////////////////////////

function onPlayerReady() {
	twVideoPlayer.player = document.getElementById("twvideoplayer_video");
	twVideoPlayer.isLoaded = true;
}
function editVideoLyrics(groupId) {
	twVideoPlayer.groupId = groupId;
	$('#lnkEditVideoLyrics').attr("href" , "/addeditlyrics.aspx?groupid=" + groupId).css("visibility", "");
}
function onLyricsLoaded(songId, vidSrc, videoId) {
	$('#lnkEditVideoLyrics').attr("href", "/addeditlyrics.aspx?id=" + songId + "&vidsrc=" + vidSrc + "&videoId=" + videoId).css("visibility", "");
}
function videoStarted(artist, title){
	if ($.isArray(twVideoPlayer.playlist)) {
		for (var i = 0; i < twVideoPlayer.playlist.length; i++) { // find the song in the last playlist
			if (artist.toLowerCase() == twVideoPlayer.playlist[i][0].toLowerCase() && title.toLowerCase() == twVideoPlayer.playlist[i][1].toLowerCase()) {
				twVideoPlayer.artist = twVideoPlayer.playlist[i][0];
				twVideoPlayer.title = twVideoPlayer.playlist[i][1];
				twVideoPlayer.album = twVideoPlayer.playlist[i][2];
				twVideoPlayer.songId = twVideoPlayer.playlist[i][3];
				$('body').trigger('nextVideo', [ twVideoPlayer.artist, twVideoPlayer.title, twVideoPlayer.album, twVideoPlayer.songId ]);
				return;
			}
		}
	}
}
