﻿/// <reference path="jquery-1.3.2.min.js" />
/// <reference path="reflection.js" />
/// <reference path="../flash/framework/swfobject/swfobject.js" />

/* This is a JSON class for the video player.*/
var twVideoPlayer = {
	playlist: null,
	autoplay: false,
	playerId: "twvideoplayer",
	width: 290,
	height: 280,
	artist: "",
	title: "",
	user: "",

	player: null,
	isInit: false,
	isMobile: false,
	isImage: false,
	isEditor: 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.user = args.user || this.user;
			this.playerId = args.playerId || this.playerId;
			this.autoplay = args.autoplay || this.autoplay;
			this.isEditor = args.isEditor || this.isEditor;
			if ($.isArray(args.playlist)) {
				this.playlist = args.playlist;
				try {
					this.artist = this.playlist[0][0];
					this.title = this.playlist[0][1];
				} catch (err) { }
			}
		} else {
			return;
		}

		// Detect iphone
		if (navigator.userAgent.toLowerCase().search("iphone") > -1 || navigator.userAgent.toLowerCase().search("ipod") > -1)
			this.isMobile = true;

		if (this.isMobile) {
			// Load youtube player
			this.loadYouTube();
		} else if (this.autoplay) {
			// load video player
			this.play();
		} else {
			// load preview image
			this.cue()
		}

	},
	cue: function(artist, title, forceClose) {
		// check for defaults
		this.artist = artist || this.artist;
		this.title = title || this.title;

		// allow player to be force closed
		if (this.isInit) {
			if (!forceClose) return;
			try {
				// Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
				var t = this.player.getPlayerState();
				if (t != 0 && t != 2) return;
			} catch (err) {
				return;
			}
			this.isInit = false;
		} else if (this.isImage) {
			$('#twvideoplayer_imgContainer').animate({ paddingLeft: this.width }, "slow", function() {
				twVideoPlayer.isImage = false;
				twVideoPlayer.cue();

			});
			return;
		}

		$('#' + this.playerId).html(
			"<div class='videoPlayerStatic' style='text-align:center; height:" + this.height + "px; width: " + this.width + "px;'>" +
			"<a href='#' onclick='twVideoPlayer.play(); return false;' style='text-decoration:none;'><div style='width:200px;height:" + parseInt(twVideoPlayer.height - 80) + "px;'>&nbsp;</div>" +
			"<div style='color:#ffffff; text-decoration:none;'>" + this.artist + " - " + this.title + "</div>" +
			"<img src='/static_images/ui/assets/video_player_static.gif' height='44' width='" + this.width + "' style='margin:0 auto; border-width:0;' /></a></div>"
		);

		// load
		var url = "/Handlers/WebFetch.aspx?getUrl=";
		url += encodeURIComponent("http://lyrics.tunewiki.com/tunewiki/services/getYouTubeVideoXML?youtube=false&max=1");
		url += encodeURIComponent("&artist=" + this.artist + "&title=" + this.title);
		$.get(url, function(xmlData) {
			if ($('#twvideoplayer_flash').length > 0) return;
			var w2 = parseInt(twVideoPlayer.width - 80);
			var w3 = parseInt(twVideoPlayer.height - 80);
			var h2 = parseInt(w2 * .75);
			var html = "<div class='videoPlayerStatic' style='text-align:center; height:" + twVideoPlayer.height + "px; width: " + twVideoPlayer.width + "px; overflow:hidden;'>" +
				"<a href='#' onclick='twVideoPlayer.play(); return false;' style='text-decoration:none;'>" +
				"<div style='margin:0 auto; text-align:left; width:" + twVideoPlayer.width + "px; height:" + w3 + "px; padding-left:" + twVideoPlayer.width + "px;' id='twvideoplayer_imgContainer'>" +
				"<img id='twvideoplayer_img' src='http://img.youtube.com/vi/" + $(xmlData).find("video_id:first").text() + "/0.jpg' height='" + h2 + "' width='" + w2 + "' style='text-align:center; border-width:0;' /></div>" +
				"<div style='color:#ffffff; text-decoration:none; white-space:nowrap;'>" + twVideoPlayer.artist + " - " + twVideoPlayer.title + "</div>" +
				"<img src='/static_images/ui/assets/video_player_static.gif' height='44' width='" + twVideoPlayer.width + "' style='margin:0 auto; border-width:0;' /></a>";
			if (twVideoPlayer.playlist != null) {
				html += "<a href='#' onclick='twVideoPlayer.prev(); return false;' style='display:block;float:left;padding-left:5px;'><img src='/static_images/ui/assets/video_player_prev.png' /></a>"
				html += "<a href='#' onclick='twVideoPlayer.next(); return false;' style='display:block;float:right;padding-right:5px;'><img src='/static_images/ui/assets/video_player_next.png'  /></a>"
			}
			html += "</div>";
			$('#' + twVideoPlayer.playerId).html(html);
			$('#twvideoplayer_img').reflect();
			setTimeout("$('#twvideoplayer_img').reflect();", 500);
			$('#twvideoplayer_imgContainer').animate({ paddingLeft: parseInt((twVideoPlayer.width - w2) / 2) }, "slow");
			twVideoPlayer.isImage = true;
		}, "xml");
	},
	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 = "/Handlers/WebFetch.aspx?getUrl=";
		url += encodeURIComponent("http://lyrics.tunewiki.com/tunewiki/services/getYouTubeVideoXML?youtube=false&max=1");
		url += encodeURIComponent("&artist=" + artist + "&title=" + song);
		$.get(url, function(xmlData) {
			$('#' + twVideoPlayer.playerId).html(
				'<object width="320" height="265"><param name="movie" value="http://www.youtube.com/v/' + $(xml).find("video_id:first").text() + '&hl=en&fs=1&"></param>' +
				'<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>' +
				'<embed src="http://www.youtube.com/v/' + $(xml).find("video_id:first").text() + '&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="280" height="280"></embed></object>'
			);
		}, "xml");
	},
	loadFlashPlayer: function() {
		$('#' + this.playerId).html(
			"<div class='videoHeader'><a href='#' onclick='twVideoPlayer.markBadVideo();'>Incorrect Song</a></div>" +
			"<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 = {
			auto_play: "",
			songTitle: "",
			albumName: "",
			artistName: "",
			vidSrc: "",
			songLang: "",
			user: this.user,
			lastPostion: ""
		};
		var params = {
			allowScriptAccess: "always",
			allowFullScreen: "true",
			quality: "high",
			wmode: "opaque",
			bgcolor: "#000000",
			movie: "/Flash/Protected_tunewiki-sync.swf?id=" + randomnumber
		};
		var attributes = {
			id: "twvideoplayer_video"
		};
		swfobject.embedSWF("/Flash/Protected_tunewiki-sync.swf?id=" + randomnumber, "twvideoplayer_flash", this.width, this.height - 18, "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;
			this.artist = "";
			this.title = "";
		} else if ((this.artist != "" && this.title != "") || (args.length >= 2)) { // user passed in a song
			if (args.length >= 2) {
				this.artist = args.shift();
				this.title = 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.artist = "";
						this.title = "";
					}
				}
			}
		} else if ($.isArray(this.playlist) && this.artist == "" && this.title == "") { // previous playlist
			isInPlaylist = true;
		}

		// animation
		if (this.isImage) {
			$('#twvideoplayer_imgContainer').animate({ paddingLeft: this.width }, "slow", function() {
				twVideoPlayer.isImage = false;
				twVideoPlayer.play();
			});
			return;

			// init
		} else if (!this.isInit) {
			this.loadFlashPlayer();
		}

		//play
		try {
			// Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
			var t = this.player.getPlayerState();
			this.player.loadPlaylist((isInPlaylist ? this.playlist : [[this.artist, this.title]]), true, 0, 0);
		} 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/getLyricGroupId.php?lang=&artist=" + encodeURIComponent(this.artist) + "&album=&title=" + encodeURIComponent(this.title) + "&vidSrc=brightcove&videoId=" + $("#txtId").val()), function(txtData) {
				var lyricGroup = txtData;
				$.get("/Handlers/WebFetch.aspx?type=plain&getUrl=" + encodeURIComponent("http://lyrics.tunewiki.com/tunewiki/services/setBadGroupIdXML?bad=true&type=video&groupId=" + lyricGroup), function() {
					alert("Thank you for marking this video as incorrect.");
				});
			});
		}
	}
};
////////////////////////////////////////////////////////////////////////

function onPlayerError(errorCode) {
	/* 100 = Removed or marked as private, 101 = Can not be embeded */
	if (errorCode == 101 || errorCode == 150) {
		alert("We're sorry, this video is currently being blocked by user request.")
	} else {
		alert("We're sorry, this video is currently unavailable.")
	}
}
function onYouTubePlayerReady(playerId) {
	twVideoPlayer.player = document.getElementById("twvideoplayer_video");
}
function editVideoLyrics(vidSrc, videoId, lang) {
	if (twVideoPlayer.isEditor && !$("#videoHeaderEditLink").length) {
		$(".videoHeader").prepend('<a id="videoHeaderEditLink" href="/AddEditLyrics.aspx?artist=' + twVideoPlayer.artist + '&album=&title=' + twVideoPlayer.title + '&vidSrc=' + vidSrc + '&videoId=' + videoId + '&lang=' + lang + '" >Edit Video Lyrics</a> | ');
	}
}