(function($) {	
	$.ux.behavior("NotifyUser", {
		displayMessage: function(message, level) {
			var self = this;
			var messageClass;
			switch(level) {
				case "confirm":
					messageClass = "Confirm";
					break;
				case "warning":
					messageClass = "Warning";
					break;
				case "error":
					messageClass = "Error";
					break;
				case "button":
					messageClass = "text ButtonMessage";
					break;
				default:
					messageClass = "Confirm";
			}
			this.element.html('<span class="'+messageClass+'">'+message+'</span>');
			var spanElement = this.element.find("span");
			spanElement.hide().fadeIn("slow", function(){
				if (level != 'button')
					setTimeout(function(){self.hideMessage(spanElement);},5000);
			});
		},
		hideMessage: function(element) {
			element.fadeOut("slow", function(){
				$(this).remove();
			});
		}
	});
	
	$.ux.behavior("AddToPlaylistButton", {
		onclick: function(event) {
			if (this.options.loginUrl != "") {
				var returnUrl = window.location;
				var loginUrl = this.options.loginUrl + '?return=1&url=' + returnUrl.href;
				window.location = loginUrl;
			} else {
				var videosSelected = $(this.options.playlistVideosList).find(".jsVideoOptions input:checked");
				if (this.options.multiAdd) {
					if (videosSelected.length > 0) {
						this.createDropDown();
					} else {
						alert("Please choose at least one video to add");
					}
				} else {
					this.createDropDown();
				}
			}
			return false;
		},
		createDropDown: function() {
			var self = this;
			var playlistDropDown = $(this.options.playlistDropDown);
			
			if (playlistDropDown.length == 0) {
				services.videoPlaylist.getPlaylistsHtml(this.options.username, function(html){
					if (html) {
						$("body").append(html);
						var videoId = (!self.options.multiAdd)?self.element.attr("id").split("_")[1]:-1;
						$(self.options.playlistDropDown).attach($.ux.AddToPlaylistDropDown, { multiAdd: self.options.multiAdd, videoId: videoId, button: self.element });
						self.showDropDown();
					} else {
						// List not created
					}
				});
			} else if (playlistDropDown.css("display") != "none") {
				self.removeDropDown();
			}
		},
		showDropDown: function() {
			var buttonPos = this.element.offset();
			var buttonHeight = this.element.height();
			$(this.options.playlistDropDown).css({ top: (buttonPos.top+buttonHeight)+'px', left: buttonPos.left+'px' }).slideDown();
		},
		removeDropDown: function() {
			$(this.options.playlistDropDown).slideUp("normal", function(){
				$(this).remove();
			});
		}
	}, {
		username: "",
		loginUrl: "",
		multiAdd: false,
		playlistVideosList: "ol.jsPlaylistView",
		playlistDropDown: "#jsAddToPlaylistDropDown"
	});

	$.ux.behavior("AddToLibraryButton", {
		onclick: function() {
			var self = this;
			if (this.options.add) {
				services.videoPlaylist.addToLibrary([this.options.videoId], function(data) {
					self.element.html("My Favorites");
					self.element.attr("href", self.options.libraryUrl);
					self.element.unbind("click");
				});
				self.options.add = false;
				return false;
			}
		}
	}, {
		add: true,
		videoId: 0,
		libraryUrl: "",
		loginUrl: ""
	});
	
	$.ux.behavior("AddToPlaylistDropDown", {
		initialize: function() {
			var self = this;
			this.updatePlaylistHeight();
			this.element.find("input:text").bind("keyup", function(e){
				if (e.keyCode == 13) {
					self.submitList();
				}
			});
		},
		updatePlaylistHeight: function() {
			var ul = this.element.find("ul");
			var lis = ul.children("li");
			if (lis.length == 0) { //check if user has any existing playlists
				this.element.find("fieldset:eq(0)").hide();
				ul.hide();
				var createNew = this.element.find(".createNew");
				createNew.children("label").html("new playlist");
				createNew.children("input:radio").attr("checked", "checked");
				createNew.css({marginTop:"0", padding:"0", borderTop:"none"});
			} else if (lis.length < 5) { //if user has less than 5
				var height = 24;
				ul.css("height", height * lis.length).css("overflow-y", "hidden");
			}
		},
		onclick: $.delegate({
			".jsSubmitPlaylistAdd": function() {
				this.submitList();
			},
			".jsCancelAdd": function() {
				this.removeList();
			},
			".jsNewPlaylistInput": function() {
				this.element.find(".createNew input:radio").attr("checked", "checked");
			},
			".jsToExisting ul li input:checkbox": function(item) {
				if (item.is(":checked"))
					$(".jsToExisting").find("input:radio").attr("checked", "checked");
			}
		}),
		submitList: function() {
			var self = this;
			var videos = new Array();
			if (this.options.multiAdd == true) {
				$("ol.jsPlaylistView li input:checked").each(function(){
					videos.push($(this).val());
				});
			} else {
				var videoId = this.options.videoId;
				videos.push(videoId);
			}
			if (videos.length > 0) {
				if ($("#existingPlaylist").attr("checked") == true) {
					var playlistIds = new Array();
					this.element.find("li input:checked").each(function(){
						playlistIds.push($(this).val());
					});
					if (playlistIds.length > 0) {
						services.videoPlaylist.addToPlaylist(playlistIds, videos, function(data){
							self.options.onVideoAdded(data.message, self.options.button);
							if (!data.message) {
								self.removeList();
								if (self.options.multiAdd == true)
									$("ol.jsPlaylistView li input:checked").removeAttr("checked");
							}
						});
					} else {
						alert("Please choose at least one playlist");
					}
				} else {
					var newPlaylistName = this.element.find("input:text").val();
					if (newPlaylistName != '') {
						services.videoPlaylist.createAndAddToPlaylist(newPlaylistName, videos, function(data){
							self.options.onPlaylistCreate(data.message, data.playlist, self.options.button);
							if (!data.message) {
								self.removeList();
								if (self.options.multiAdd == true)
									$("ol.jsPlaylistView li input:checked").removeAttr("checked");
							}
						});
					} else {
						alert("Please enter a name for your new playlist");
					}
				}
			} else {
				alert("Please choose at least one video to add");
			}
		},
		removeList: function() {
			this.element.slideUp("normal", function(){
				$(this).remove();
			});
		}
	}, {
		multiAdd: false,
		videoId: 0,
		button: "",
		onPlaylistCreate: function(){},
		onVideoAdded: function(){}
	});
	
	$.ux.behavior("PlaylistCreateAction", {
		onclick: function() {
			this.createInput();
		},
		createInput: function() {
			var self = this;
			var playlistsList = $(this.options.playlistsList);
			playlistsList.prepend('<li class="FLC"><input type="text" /></li>');
			var firstLI = playlistsList.find("li:first");
			firstLI.hide().slideDown("normal", function(){
				firstLI.find("input").focus().bind("blur", function(){
					self.submitPlaylist(firstLI);
				}).bind("keyup", function(e){
					if (e.keyCode == 13) {
						self.submitPlaylist(firstLI);
					} else if (e.keyCode == 27) {
						self.cancelCreate(firstLI);
					}
				});
			});
		},
		submitPlaylist: function(firstLI) {
			var self = this;
			var playlistName = firstLI.find("input").attr("value");
			var container = $(self.options.playlistsList);
			if (playlistName != '') {
				services.videoPlaylist.createPlaylist(playlistName, function(data){
					if (data.playlist) {
						services.videoPlaylist.getPlaylists(self.options.username, function(result){
							if (result.playlists) {
								container.fadeOut("fast", function(){
									firstLI.find("input").remove();
									var selectedListId = container.find("li.selected a.jsUpdateVideosList").attr("id");
									container.html("");
									container.template("playlistsTemplate", result);
									container.find("li").attach($.ux.Playlist)
									container.find("li a.jsDeletePlaylist").attach($.ux.PlaylistDeleteAction).hide();
									container.find("li a.jsUpdateVideosList").attach($.ux.UpdateVideoListAction);
									container.find("li a#"+selectedListId).parent().addClass("selected");
									container.fadeIn("fast");
									self.options.onPlaylistCreate();
								});
							} else {
								self.options.onPlaylistCreate(result.message);
							}
						});
					} else {
						self.cancelCreate(firstLI);
						self.options.onPlaylistCreate(data.message);
					}
				});
			} else {
				self.cancelCreate(firstLI);
			}
		},
		cancelCreate: function(li) {
			li.slideUp("normal", function(){
				$(this).remove();
			});
		}
	}, {
		username: "",
		playlistsList: "ul.jsPlaylists",
		removeClass: "removeIcon",
		onPlaylistCreate: function(){}
	});
	
	$.ux.behavior("Playlist", {
		initialize: function() {
			this.deleteButton = this.element.find(this.options.deleteButtonSelector);
		},
		onclick: function() {
			return true;
			//ajax here
		},
		onmouseover: function() {
			this.deleteButton.show();
		},
		onmouseout: function() {
			this.deleteButton.hide();
		}
	}, { deleteButtonSelector: "a.jsDeletePlaylist" });

	$.ux.behavior("PlaylistDeleteAction", {
		onclick: function() {
			this.deletePlaylist();
		},
		deletePlaylist: function() {
			var confoMsg = "Are you sure you want to delete this playlist?";
			var self = this;
			if (confirm(confoMsg)) {
				var playlistId = this.element.attr("id").split("_")[1];
				var currentPlaylistId = $(self.options.currentPlaylistSelector).attr("id").split("_")[1];
				services.videoPlaylist.deletePlaylist(playlistId, function(data){
					if (data.success == true) {
						if (playlistId == currentPlaylistId) {
							window.location = $(self.options.librarySelector).attr("href");
						} else {
							self.element.parent().slideUp("normal", function(){
								$(this).remove();
								self.options.onPlaylistDelete();
							});
						}
					} else {
						// Delete failed.
					}
				});
			}
		}
	}, { 
		librarySelector: "li.jsUserLibrary a",
		currentPlaylistSelector: "div.library",
		onPlaylistDelete: function(){}
	});


	$.ux.behavior("RemoveVideoAction", {
		removeVideoElements: function(ids) {
			for (var i = 0; i < ids.length; i++) {
				$("#Video_"+ids[i]).fadeOut("normal", function(){
					$(this).remove();
				});
			}
		},
		removeVideos: function(itemArray) {
			var self = this;
			if (this.options.playlistId == 0) {
				services.videoPlaylist.removeFromLibrary(itemArray, this.options.order, function(response) {
					if (response) {
//						self.removeVideoElements(itemArray);
//						self.options.onVideoRemove();
						self.options.onLibraryVideoRemove(response.redirecturl);
					}
				});
			} else {
				services.videoPlaylist.removeFromPlaylist(this.options.playlistId, itemArray, function(response) {
					if (response) {
						self.removeVideoElements(itemArray);
						self.options.onVideoRemove();
						if (self.options.videoCounter != '')
							self.updateCounter(itemArray.length);
					}
				});
			}
		},
		updateCounter: function(x) {
			var currentCount = $(this.options.videoCounter).html();
			$(this.options.videoCounter).html(parseInt(currentCount)-x);
		},
		onclick: function(event) {
			if (this.options.multiDelete) {
				var videosSelected = $(this.options.playlistVideosList).find(".jsVideoOptions input:checked");
				if (videosSelected.length > 0) {
					if (confirm("Are you sure you want to remove these videos?")) {
						var inputs = $(this.options.inputsSelector);
						var ids = [];
						inputs.each(function() {
							ids.push(this.value);
						});
						this.removeVideos(ids);
					}
				} else {
					alert("Please choose at least one video to remove.");
				}
			} else {
				if (confirm("Are you sure you want to remove this video?")) {
					var id = this.element.attr("id").split("_")[1];
					this.removeVideos([id]);
				}
			}
		}
	}, {
		playlistId: 0,
		multiDelete: false,
		playlistVideosList: "ol.jsPlaylistView",
		inputsSelector: "",
		videoCounter: "dl.stats dd:first",
		onVideoRemove: function(){},
		order: "",
		onLibraryVideoRemove: function(){}
	});
	
	$.ux.behavior("AttachAddIcon", {
		initialize: function() {
			var self = this;
			if (self.element[0].complete) {
				self.attachIcon();
			} else {
				self.element.load(function() {
					self.attachIcon();
				})
			}
		},
		attachIcon: function() {
			var id = this.element.attr("id").split("_")[1];
			this.element.parent().css("position","relative");
			this.element.before('<div class="AddToPlaylistIcon jsAddToPlaylistIcon" id="video_'+id+'"></div>');
			var icon = $(this.element).siblings("div.jsAddToPlaylistIcon");
			var imgPadRight = parseInt(this.element.css("paddingRight").replace("px",""));
			var imgPadBottom = parseInt(this.element.css("paddingBottom").replace("px",""));
			if (this.element.css("borderRightWidth") == 'medium') {
				var imgBorderRight = 0;
			} else {
				var imgBorderRight = parseInt(this.element.css("borderRightWidth").replace("px",""));
			}
			if (this.element.css("borderBottomWidth") == 'medium') {
				var imgBorderBottom = 0;
			} else {
				var imgBorderBottom = parseInt(this.element.css("borderBottomWidth").replace("px",""));
			}
			var parentPadRight = parseInt(this.element.parent().css("paddingRight").replace("px",""));
			var parentPadBottom = parseInt(this.element.parent().css("paddingBottom").replace("px",""));
			var xPos = this.element.width() - icon.width() + imgPadRight + imgBorderRight + parentPadRight;
			var yPos = this.element.height() - icon.height() + imgPadBottom + imgBorderBottom + parentPadBottom;
			icon.css({ left: xPos, top: yPos });
			if (this.options.loginUrl != "") {
				icon.attach($.ux.AddToPlaylistButton, { username: this.options.username, loginUrl: this.options.loginUrl });
			} else {
				icon.attach($.ux.AddToPlaylistButton, { username: this.options.username });
			}
		}
	}, {
		username: "",
		loginUrl: ""
	});
	
	$.ux.behavior("UpdateVideoListAction", {
		onclick: function() {
			if (this.options.username != '') {
				this.getLibraryList();
			} else {
				var playlistId = this.element.attr("id").split("_")[1];
				this.getPlaylist(playlistId);
			}
			return false;
		},
		getLibraryList: function() {
			var self = this;
			var page = 1;
			if (this.element.hasClass(".jsPager")) {
				page = this.element.attr("id").split("_")[1];
				this.options.order = this.element.attr("id").split("_")[3];
			}
			services.videoPlaylist.getLibrary(this.options.username, function(data) {
				if (data) {
					self.sendDataToTemplate(data, "library");
				}
			}, this.options.order, page);
		},
		getPlaylist: function(playlistId) {
			var self = this;
			services.videoPlaylist.getPlaylist(playlistId, function(data) {
				if (data) {
					self.sendDataToTemplate(data.playlist, "playlist");
				}
			});
		},
		sendDataToTemplate: function(playlist, pageMode) {
			var self = this;
			var container = $(this.options.container);
			var data = {
				playlist: playlist,
				pageMode: pageMode
			}
			if (pageMode == "library") {
				var pageCount = Math.ceil(playlist.total / playlist.itemsperpage);
				var startPage = (playlist.page > 4) ? playlist.page - 4 : 1;
				var endPage = startPage + (4 * 2) + 1;
                if (endPage > pageCount)
                    endPage = pageCount;
				data = {
					playlist: playlist,
					pageMode: pageMode,
					pageCount: pageCount,
					startPage: startPage,
					endPage: endPage,
					nextPage: (playlist.page < pageCount) ? playlist.page + 1 : pageCount,
					order: self.options.order
				}
			}
			if (!playlist.playlistid)
				playlist.playlistid = 0;
			container.template("videosTemplate", data);
			container.attr("id", "Playlist_"+playlist.playlistid);
			this.markItemsSelected(pageMode);
			this.options.onAjaxComplete(pageMode, this.options.order, playlist.title);
		},
		markItemsSelected: function(pageMode) {
			$("ul.list").find("li.selected").removeClass("selected");
			if (pageMode == "library") {
				$("ul.list").find("li.jsUserLibrary").addClass("selected");
				var sortList = $(this.options.container).find("ul.sort");
				sortList.find("li.selected").removeClass("selected");
				if (this.options.order == "views") {
					sortList.find("a.jsSortLibraryByViews").parent("li").addClass("selected");
				} else if (this.options.order == "rating") {
					sortList.find("a.jsSortLibraryByRatings").parent("li").addClass("selected");
				} else {
					sortList.find("a.jsShowLibrary").parent("li").addClass("selected");
				}
			} else {
				this.element.parent("li").addClass("selected");
			}
		}
	}, {
		username: "",
		order: "date",
		page: 1,
		container: "div.VideoLibrary div.library",
		onAjaxComplete: function(){}
	});
}(jQuery))

var addToPlaylistButtons = function(message, button, notifier){
	if (message) {
		alert(message);
	} else {
		if (button.hasClass("jsAddToPlaylist")) {
			notifier.displayMessage("Added to Playlist", "button");
		} else if (button.hasClass("jsAddToPlaylistIcon")) {
			var img = button.siblings("img");
			var imgPadRight = parseInt(img.css("paddingRight").replace("px",""));
			if (img.css("borderRightWidth") == 'medium') {
				var imgBorderRight = 0;
			} else {
				var imgBorderRight = parseInt(img.css("borderRightWidth").replace("px",""));
			}
			var parentPadRight = parseInt(button.parent().css("paddingRight").replace("px",""));
			button.css("backgroundImage","none")
				.html("Added")
				.animate({
					left: imgPadRight+imgBorderRight+parentPadRight+'px', width: img.width()
				}, "normal");
		}
	}
}
