﻿(function($)
{
	// adds the stylesheet once, when the plugin is first loaded on the page.
	if (!$.isPopulated(window.widgetPreloadedCss) || ($.isPopulated(window.widgetPreloadedCss) && !window.widgetPreloadedCss.editVideo))
		$.addStyleSheet("Styles/gd.editVideo.css");

	var EditVideo = {
		buttonDefaults: {
			list: ['save', 'cancel'],
			save: {
				displayName: 'Save',
				click: function($this, event)
				{

				    if ($this.options.fromMyChannel && $this.options.fromMyChannel == true)
				        RecordEvent(null, 'click', '23842', '');
				    else
				        RecordEvent(null, 'click', '23828', '');
                    
                    $this._saveData($this);

					return false;
				}
			},
			cancel: {
				displayName: 'Cancel',
				click: function($this, event)
				{

				    if ($this.options.fromMyChannel && $this.options.fromMyChannel == true)
				        RecordEvent(null, 'click', '23843', '');
				    else
				        RecordEvent(null, 'click', '23829', '');
                    
                    $this.close();
       				return false;
				}
			}
		},

		dialogDefaults: {
			closeOnEscape: false,
			bgiframe: true,
			resizable: false,
			zIndex: 3000,
			position: ['50%', '50%'],
			modal: true
		},


		// == Required Methods ======================================================

		// called on widget initialization.
		_init: function()
		{
			var $this = this;
			$this._log("loading " + $this.widgetBaseClass);

			var buttons = this.options.buttons;
			// have to merge this one manually because we need a deep copy.
			this.options.buttons = $.extend(true, {}, this.buttonDefaults, this.options.buttons);
			if ($.isPopulated(buttons)) this.options.buttons.list = buttons.list;

			if ($this.options.displayAs == "modal")
			{
				var dialogOptions = this.options.dialogOptions;
				// have to merge this one manually because we need a deep copy.
				this.options.dialogOptions = $.extend(true, {}, this.dialogDefaults, this.options.dialogOptions);
				if ($.isPopulated(dialogOptions)) this.options.dialogOptions = dialogOptions;
			}

			$this.element.addClass($this.widgetBaseClass);
			$this.options.displayAs = $this.options.displayAs.toLowerCase();
			$this.element.addClass($this.widgetBaseClass + '-' + $this.options.displayAs);

			$this.options.isClosed = false;


			if ($.isFunction($this.options.preOpen)) $this.options.preOpen($this);

			$this._getInitHtml(function(html)
			{
				$this.element.html(html);

				switch ($this.options.displayAs)
				{
					case "flyout":
						$this.element.flyout({
							anchor: $this.options.anchor,
							positionX: $this.options.positionX,
							positionY: $this.options.positionY,
							offsetX: $this.options.offsetX,
							offsetY: $this.options.offsetY,
							backgroundInfo: $this.options.backgroundInfo
						});
						break;
					case "modal":

						if (!$.isPopulated($this.options.dialogOptions.width)) $this.options.dialogOptions.width = $this.element.width();

						if ($.isPopulated($this.options.dialogOptions.close))
						{
							$this.options.close = $this.options.dialogOptions.close;
							$this.options.dialogOptions.close = null;
						}
						if ($.isPopulated($this.options.dialogOptions.open))
						{
							$this.options.open = $this.options.dialogOptions.open;
							$this.options.dialogOptions.open = null;
						}

						$this.options.dialogOptions.open = function() { $this.element.corners($this.options.backgroundInfo); };

						$this.element.dialog($this.options.dialogOptions);

						var dialog = $this.element.parents(".ui-dialog");
						$(".ui-dialog-titlebar", dialog).hide();

						dialog.css({
							overflow: "visible",
							padding: 0,
                            margin: '50px 0 0 0',
							width: $this.options.dialogOptions.width,
							"font-family": "Arial, verdana, Helvetica, sans-serif",
							"font-size": "12px"
						});

						if(jQuery.browser.msie)
						{
							dialog.css("height", "750px");
                            dialog.css("background-color", "#FFFFFF");
						}

						$(".ui-dialog-content", dialog).css({
							border: "0",
							padding: "0",
							overflow: "visible"
						});
						$(".ui-widget-content", dialog).css({
							border: "0",
							backgroundImage: ""
						});

						break;
				}

				$this._configureEvents($this, $this.element);

				if ($.isFunction($this.options.open)) $this.options.open($this);
			});
		},

		// this is called when the widget element is removed from the DOM.
		destroy: function()
		{
			this._unconfigureEvents(this, this.element);

			switch (this.options.displayAs)
			{
				case "flyout":
					this.element.flyout("destroy");
					break;
				case "modal":
					this.element.dialog("destroy");
					break;
			}

			this.element.removeClass(this.widgetBaseClass);
			this.element.empty();

			$.widget.prototype.destroy.call(this);
		},

		// == Utilities =============================================================
		// to enable logging set the log true in defaults or via an option override.
		_log: function(msg)
		{
			if (!$.isPopulated(this.options) || !$.isPopulated(this.options.log)) return;

			if (window.console && console.log)
			{ // firebug logger
				console.log(msg);
			}
		},

		// called from _init to set up event handlers and bindings.
		_configureEvents: function($this, $element)
		{
            if ($this.options.displayAs == "flyout" || $this.options.displayAs == "modal") 
            {
                $("#" + $this.widgetBaseClass + "-tabs-" + $this.options.videoId).tabs();
                if (!$this.options.allowEmbedPlayer)
                    $("#" + $this.widgetBaseClass + "-tabs-" + $this.options.videoId).tabs("disable", 1);
            }

			var DisableSaveButton = function()
			{
				// video-edit dialog:
				$("." + $this.widgetBaseClass + "-button-save").hide();
				$("." + $this.widgetBaseClass + "-button-disabled-save").show();

				// upload.aspx:
				var nextEnabled = $("." + $this.widgetBaseClass + "-button-next");
				if(nextEnabled.length == 1)
				{
					nextEnabled.hide();

					var nextDisabled = $("." + $this.widgetBaseClass + "-button-disabled-next");

					if(nextDisabled.length == 0)
					{
						nextEnabled.clone(false)
								   .insertAfter(nextEnabled)
								   .removeClass("ui-editVideo-button-next")
								   .addClass("ui-editVideo-button-disabled-next")
								   .show();
					}
					else
					{
						nextDisabled.show();
					}
				}
			};

			var EnableSaveButton = function()
			{
				if($this.element.find(".ui-charCounter-text-overlimit").length == 0)
				{
					// video-edit dialog:
					$("." + $this.widgetBaseClass + "-button-save").show();
					$("." + $this.widgetBaseClass + "-button-disabled-save").hide();

					// upload.aspx:
					$("." + $this.widgetBaseClass + "-button-next").show();
					$("." + $this.widgetBaseClass + "-button-disabled-next").hide();
				}
			};
			
            $this.element.find('#' + this.widgetBaseClass + '-edit-description-'+$this.options.videoId)
				.makeSafeish()
				.charCounter({
					counter: $element.find('.' + $this.widgetBaseClass + '-counter-description'),
					charLimit: $this.options.descriptionCharLimit,
					DisableSaveButtonHandler: DisableSaveButton, 
					EnableSaveButtonHandler: EnableSaveButton
				});
			$this.element.find('#' + this.widgetBaseClass + '-edit-title-'+$this.options.videoId)
				.makeSafeish()
				.charCounter({
					counter: $element.find('.' + $this.widgetBaseClass + '-counter-title'),
					charLimit: $this.options.titleCharLimit,
					DisableSaveButtonHandler: DisableSaveButton, 
					EnableSaveButtonHandler: EnableSaveButton
				});
            $this.element.find('#' + this.widgetBaseClass + '-edit-upload-title-'+$this.options.videoId)
				.makeSafeish()
				.charCounter({
					counter: $element.find('.' + $this.widgetBaseClass + '-counter-title'),
					charLimit: $this.options.titleCharLimit
				});
			$this.element.find('#' + this.widgetBaseClass + '-edit-tags-'+$this.options.videoId)
				.makeSafeish()
				.autocomplete("getTagsAutocomplete.aspx", {
					minChars: 1,
					multiple: true,
					matchContains: true,
                    multipleSeparator: " ",
                    selectFirst: false,
					autoFill: true /* ,
					highlight: function(value, term) {
						return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
					}*/
	            }).bind('result', function (data) {
	                if (this.createTextRange) {
	                    var r = this.createTextRange();
	                    r.collapse(false);
	                    r.select();
	                }
	            });
			
			$this.element.find('#' + this.widgetBaseClass + '-edit-password-'+$this.options.videoId)
				.makeSafeish({
					filters: { list: ['html', 'charLimit'] },
					filterCharLimit: 50
				})
				.charCounter({
					counter: $element.find('.' + $this.widgetBaseClass + '-counter-password'),
					charLimit: $this.options.passwordCharLimit
				});
			
			$this.element.find('#' + $this.widgetBaseClass + '-edit-privacy-'+$this.options.videoId)
				.bind("click change", function()
				{
					var selectedValue = $(this).val();
					
					if (selectedValue == 2) // pwd
					{
						$this.element.find('.' + $this.widgetBaseClass + '-edit-password-container').css("display", "");
						$this.element.find("#embed_disabled_warning_" + $this.options.videoId).css("display", "none");
						
						if($this.options.allowEmbedPlayer)
						{
							$this.element.find("#" + $this.widgetBaseClass + "-tabs-" + $this.options.videoId).tabs("enable", 1);
						}

						$this.element.find("#allow-embed-player-" + $this.options.videoId).removeAttr("disabled");
					}
					else if(selectedValue == 3) //priv
					{
						$this.element.find('.' + $this.widgetBaseClass + '-edit-password-container').css("display", "none");
						$this.element.find("#embed_disabled_warning_" + $this.options.videoId).css("display", "block");
						$this.element.find("#" + $this.widgetBaseClass + "-tabs-" + $this.options.videoId).tabs("disable", 1);
						$this.element.find("#allow-embed-player-" + $this.options.videoId).attr("disabled", "disabled");
					}
					else
					{
						$this.element.find('.' + $this.widgetBaseClass + '-edit-password-container').css("display", "none");
						$this.element.find("#embed_disabled_warning_" + $this.options.videoId).css("display", "none");

						if($this.options.allowEmbedPlayer)
						{
							$this.element.find("#" + $this.widgetBaseClass + "-tabs-" + $this.options.videoId).tabs("enable", 1);
						}

						$this.element.find("#allow-embed-player-" + $this.options.videoId).removeAttr("disabled");
					}
				});

			for (var i = 0; i < $this.options.buttons.list.length; i++)
			{
				var buttonName = $this.options.buttons.list[i];

				$this.element.find("." + $this.widgetBaseClass + "-button-" + buttonName).bind(
					"click." + $this.widgetBaseClass,
					{ buttonName: buttonName },
					function(event)
					{
						$this.options.buttons[event.data.buttonName].click($this, event);
						return false;
					}
				);
			}

			if ($this.options.showCategories)
			{
				var options = {
					dataPersister: $this.options.categoriesDataPersister,
					displayAs: "embed",
					showControls: false
				};
				if ($.isPopulated($this.options.categoriesData)) options.categoriesData = $this.options.categoriesData;
				if ($.isPopulated($this.options.allCategories))
				{
					options.allCategories = $this.options.allCategories;
				} else
				{
					options.dataRetriever = $this.options.categoriesDataRetriever;
				}

				$this.element.find('.' + $this.widgetBaseClass + '-categories').editCategories(options);
			}

            var optionsEditThumb = {
                dataPersister: $this.options.thumbnailsDataPersister,
                displayAs: "embed",
                showControls: false,
                sender: $this.options.sender
            };
            if ($.isPopulated($this.options.selectedStillNumber))
                optionsEditThumb.selectedStillNumber = $this.options.selectedStillNumber;

            if ($.isPopulated($this.options.videoId))
                optionsEditThumb.videoId = $this.options.videoId;

            if ($.isPopulated($this.options.allVideoThumbnails)) {
                optionsEditThumb.allVideoThumbnails = $this.options.allVideoThumbnails;
            } 
            else {
                optionsEditThumb.dataRetriever = $this.options.thumbnailsDataRetriever;
            }

            $this.element.find('.' + $this.widgetBaseClass + '-videothumbnails').editVideoThumbnail(optionsEditThumb);

			$this.element.find('.' + $this.widgetBaseClass + '-fields input, .' + $this.widgetBaseClass + '-fields textarea, , .' + $this.widgetBaseClass + '-fields select').each(
			function()
			{
				var options = {};
				if ($this.options.displayAs != "embed")
				{
					options = { newWidth: 350 };
					if (this.tagName.toLowerCase() == 'textarea') options.newHeight = 100;
				}
				$(this).fancyText(options);
			});

            $(".embed-list").bind("mouseenter", function()
            {
                    $(this).css("background-color", "#E4EFC7");                    
                    if (this.id == "embed-allow-like-parent")
                    {
                        $("#embed-like-image").hide();
                        $("#embed-like-indicator-image").show();
                    }
                    else if (this.id == "embed-allow-share-parent")
                    {
                        $("#embed-share-image").hide();
                        $("#embed-share-indicator-image").show();
                    }
                    else if (this.id == "embed-show-no-views-parent")
                    {
                        $("#embed-show-no-views-image").hide();
                        $("#embed-show-no-views-indicator-image").show();
                    }
            });

            $(".embed-list").bind("mouseleave", function()
            {
                    $(this).css("background-color", "#EAEAEA");                    
                    if (this.id == "embed-allow-like-parent")
                    {
                        $("#embed-like-image").show();
                        $("#embed-like-indicator-image").hide();
                    }
                    else if (this.id == "embed-allow-share-parent")
                    {
                        $("#embed-share-image").show();
                        $("#embed-share-indicator-image").hide();
                    }
                    else if (this.id == "embed-show-no-views-parent")
                    {
                        $("#embed-show-no-views-image").show();
                        $("#embed-show-no-views-indicator-image").hide();
                    }
            });

            if ($this.options.embedShowVMELogo)
            {
                $('#embed-enable-show-vme-logo-div').show();
                $('#embed-disable-show-vme-logo-div').hide();
            }
            else
            {
                $('#embed-enable-show-vme-logo-div').hide();
                $('#embed-disable-show-vme-logo-div').show();
            }

            $('#embed-show-vme-logo-' + $this.options.videoId).click(function() {
                var isChecked = $(this).is(':checked');
                if (isChecked)
                {
                    $('#embed-enable-show-vme-logo-div').show();
                    $('#embed-disable-show-vme-logo-div').hide();
                }
                else
                {
                    $('#embed-enable-show-vme-logo-div').hide();
                    $('#embed-disable-show-vme-logo-div').show();
                }
            });

            if ($this.options.embedShowVmeBar)
                $('#embed-show-vme-bar-div').show();
            else
                $('#embed-show-vme-bar-div').hide();

            $('#embed-show-vme-bar-' + $this.options.videoId).click(function() {
                var isChecked = $(this).is(':checked');
                if (isChecked)
                    $('#embed-show-vme-bar-div').show();
                else
                    $('#embed-show-vme-bar-div').hide();
            });

            $('#allow-embed-player-' + $this.options.videoId).click(function() {
                var isChecked = $(this).is(':checked');
                if (isChecked)
				{
                    $("#" + $this.widgetBaseClass + "-tabs-" + $this.options.videoId).tabs("enable", 1);
					$this.options.allowEmbedPlayer = true;
                }
				else
				{
                    $("#" + $this.widgetBaseClass + "-tabs-" + $this.options.videoId).tabs("disable", 1);
					$this.options.allowEmbedPlayer = false;
				}
            });

			$("#" + $this.widgetBaseClass + $this.options.videoId + "_closedlgbtn").click(function()
			{
				$this.close();
				$this.destroy();
				$this.element.remove();
				return false;
			});

		},

		_unconfigureEvents: function($this, $element)
		{
			for (var i = 0; i < $this.options.buttons.list.length; i++)
			{
				$this.element.find("." + $this.widgetBaseClass + "-button-" + $this.options.buttons.list[i]).unbind("click." + $this.widgetBaseClass);
			}

			if (this.element.displayAs == "flyout") this.element.flyout("destroy");

			$this.element.find('#' + this.widgetBaseClass + '-edit-title-'+$this.options.videoId).makeSafeish("destroy");
			$this.element.find('#' + this.widgetBaseClass + '-edit-title-'+$this.options.videoId).charCounter("destroy");
			$this.element.find('#' + this.widgetBaseClass + '-edit-description-'+$this.options.videoId).makeSafeish("destroy");
			$this.element.find('#' + this.widgetBaseClass + '-edit-description-'+$this.options.videoId).charCounter("destroy");
			$this.element.find('#' + this.widgetBaseClass + '-edit-tags-'+$this.options.videoId).makeSafeish("destroy");

			this.element.removeClass(this.widgetBaseClass);
			this.element.removeClass(this.widgetBaseClass + '-' + this.options.displayAs);
		},

		// == HTML generators =======================================================

        _wrapContentForCorners: function(content, contentClass) {
			var html =
			'<div class="' + this.widgetBaseClass + '-wrapper' + ($.isPopulated(contentClass) ? ' ' + contentClass : '') + '">' +
				'<div class="' + this.widgetBaseClass + '-wrapper-left"></div>' +
				'<div class="' + this.widgetBaseClass + '-wrapper-center">' + content + '</div>' +
				'<div class="' + this.widgetBaseClass + '-wrapper-right"></div>' +
			'</div>';
			return html;
		},

		// called in init to get the html for the widget.
		_getInitHtml: function(finish)
		{
			var $this = this;
			var buildHtml = function(data)
			{
				if ($.isPopulated(data))
				{
                    $this.options.title = ($.isPopulated(data.Title)) ? data.Title : '';
					$this.options.description = ($.isPopulated(data.Description)) ? data.Description : '';
					$this.options.tags = ($.isPopulated(data.Tags)) ? data.Tags : '';
					$this.options.fileName = ($.isPopulated(data.FileName)) ? data.FileName : '';
                    $this.options.fileId = ($.isPopulated(data.FileId)) ? data.FileId : '';
					$this.options.password = ($.isPopulated(data.Password)) ? data.Password : '';
                    $this.options.selectedStillNumber = ($.isPopulated(data.SelectedStillNumber)) ? data.SelectedStillNumber : 1;
                    $this.options.embedAllowLike =  ($.isPopulated(data.EmbedAllowLike)) ? data.EmbedAllowLike : true;
                    $this.options.embedAllowSharing =  ($.isPopulated(data.EmbedAllowSharing)) ? data.EmbedAllowSharing : true;
                    $this.options.embedShowNoViews =  ($.isPopulated(data.EmbedShowNoViews)) ? data.EmbedShowNoViews : true;
                    $this.options.embedPlayerAutoPlay =  ($.isPopulated(data.EmbedPlayerAutoPlay)) ? data.EmbedPlayerAutoPlay : false;
                    $this.options.embedPlayerLoopVideo =  ($.isPopulated(data.EmbedPlayerLoopVideo)) ? data.EmbedPlayerLoopVideo : false;
                    $this.options.embedShowVMELogo =  ($.isPopulated(data.EmbedShowLargeLink)) ? data.EmbedShowLargeLink : true;
                    $this.options.embedShowVmeBar = ($.isPopulated(data.EmbedShowGreyBar)) ? data.EmbedShowGreyBar : true;
                    $this.options.allowComment = ($.isPopulated(data.AllowComment)) ? data.AllowComment : true;
                    $this.options.allowEmbedPlayer = ($.isPopulated(data.EnableVideoPlayerEmbed)) ? data.EnableVideoPlayerEmbed && !(data.VideoType == 2 && data.Password && data.Password.length == 0) : true;
					$this.options.videoType = data.VideoType;
                    $this.options.videoId = data.VideoId;
				}

				var html = '';

//                if ($this.options.displayAs == "embed")
//                {
//                    //should you do something special from the upload process edit???? SLS
//                    //html += '<div class="' + 'ui-editVideo' + '-edit"><a href="#" class="' + 'ui-editVideo' + '-button-edit ' + 'ui-editVideo' + '-actionbutton">' + $this.options.fileName + '</a></div>' + 
//                    //    '<div style="line-height:8px">&nbsp;</div><div><img src="images/clear.gif" id="imgAnchor-'+ $this.options.videoId  +'"></div>';
//                }
//                else
//                {
				if ($this.options.displayAs == "flyout" || $this.options.displayAs == "modal") 
                {
					html += "<div id=\"" + $this.widgetBaseClass + $this.options.videoId + "_closedlgbtn\" class=\"vme_close_dialog_button\"></div><div style=\"line-height:8px\">&nbsp;</div>";
                    html += '<h1 class="' + $this.widgetBaseClass + '-titlebar">Edit Details</h1>';
					html += "<div class=\"videome-tabs videome-tabs-video\">";
					html += "<div class=\"tabs-border-bottom tab-border-video\"></div>"
				    html += '<div  id="' + $this.widgetBaseClass + '-tabs-' + $this.options.videoId + '" class="clear-fix ' + $this.widgetBaseClass + '-main" style="font-size:12px;font-family:Arial,verdana,Helvetica,sans-serif;">';
				    html += "<ul class=\"generic-tabs-menu\">\
				        		<li><a onclick=\"RecordEvent(event, 'click', '42528', '');\" href=\"#tabs-" + $this.widgetBaseClass + "-video-" + $this.options.videoId + "\">Video</a></li>\
						    	<li><a onclick=\"RecordEvent(event, 'click', '42529', '');\" href=\"#tabs-" + $this.widgetBaseClass + "-embed-" + $this.options.videoId + "\">Embed Player</a></li>\
						    </ul>";
                
				    html += '<div id="tabs-' + $this.widgetBaseClass + '-video-' + $this.options.videoId + '" class="channel-properties" style="font-size:12px;max-height:600px;">';
                }
				if ($this.options.showCategories)
				{
					html += '<div class="clear-fix"><div class="tell-us-video">';
				}

                if ($this.options.displayAs == "embed")
				{
    			    html += '<div  class="' + $this.widgetBaseClass + '-main">';
				}

				html += '<div class="' + $this.widgetBaseClass + '-header">Tell Us About Your Video</div>';
				if ($.isPopulated($this.options.fileName))
				{
					html += '<div class="' + $this.widgetBaseClass + '-label-filename">Original file name:</div>' +
					   '<div class="' + $this.widgetBaseClass + '-data-filename" title="' + $this.options.fileName + '">' + $this.options.fileName + '</div>';
				}

				if ($.isPopulated($this.options.password))
				{
					html += '<div class="' + $this.widgetBaseClass + '-password-notice">This video is password protected. Only people with whom you share your password will be able to see it.</div>';
				}

				if ($this.options.displayAs == "embed")
				{
					html +=
					   '<div class="' + $this.widgetBaseClass + '-requiredNotice ' + $this.widgetBaseClass + '-red" >* Required</div>';
				}
				
				html +=
					   '<div class="' + $this.widgetBaseClass + '-fields">' +
					   '<div class="' + $this.widgetBaseClass + '-label-title">' +
						 '<span style="float:left;">' + $this.options.titleLabel + '</span>' +
						 '<span class="' + $this.widgetBaseClass + '-counter-title">' +
							$this.options.titleCharLimit +
						 '</span>' +
					   '</div>' +
					   '<div><input id="' + $this.widgetBaseClass + '-edit-title-'+$this.options.videoId+'" class="' + $this.widgetBaseClass + '-edit-title" /></div>' +
					   '<div class="' + $this.widgetBaseClass + '-label-description">' +
						 '<span style="float:left;">' + $this.options.descriptionLabel + '</span>' +
						 '<span class="' + $this.widgetBaseClass + '-counter-description">' +
							$this.options.descriptionCharLimit +
						 '</span>' +
					   '</div>' +
					   '<div><textarea id="' + $this.widgetBaseClass + '-edit-description-'+$this.options.videoId+'" class="' + $this.widgetBaseClass + '-edit-description" rows="4"></textarea></div>' +
					   '<div class="' + $this.widgetBaseClass + '-label-tags">' + $this.options.tagsLabel + '</div>' +
					   '<div><input id="' + $this.widgetBaseClass + '-edit-tags-'+$this.options.videoId+'" class="' + $this.widgetBaseClass + '-edit-tags" /></div>' +
					   '<div class="' + $this.widgetBaseClass + '-blurb-tags">Separate tags with spaces or commas. Quotes create a compound tag (e.g., "San Diego").</div>';
					   
				var downgradedToFree = ($this.options.accountType == 0 && $this.options.videoType == 2);
				if ($this.options.showPrivacy && ($this.options.accountType > 0 || downgradedToFree))
				{
					html += '<div class="' + $this.widgetBaseClass + '-privacy-container" >' +
					   '<div class="' + $this.widgetBaseClass + '-label-privacy">Privacy Settings:</div>' +
					   
					   '<select id="' + $this.widgetBaseClass + '-edit-privacy-'+$this.options.videoId+'" class="' + $this.widgetBaseClass + '-edit-privacy" >' +
								'<option value="1"' + ($this.options.videoType == 1 ? ' selected' : '') + '>Display video to everyone</option>';

					if (!downgradedToFree) html += '<option value="2"' + ($this.options.videoType == 2 && $.isPopulated($this.options.password) ? ' selected' : '') + '>Password-protect this video</option>';

					html += '<option value="3"' + ($this.options.videoType == 2 && !$.isPopulated($this.options.password) ? ' selected' : '') + '>Make this video private</option>' +
					   '</select>' +
					   '<div class="' + $this.widgetBaseClass + '-edit-password-container"' + (!($this.options.videoType == 2 && $.isPopulated($this.options.password)) ? ' style="display:none"' : '') + '>' +
					   '<div class="' + $this.widgetBaseClass + '-label-privacy">' +
					   '<span style="float:left;">Password:</span>' +
					   '<span class="' + $this.widgetBaseClass + '-counter-password" ></span></div>' +
					   '<input id="' + $this.widgetBaseClass + '-edit-password-'+$this.options.videoId+'" class="' + $this.widgetBaseClass + '-edit-password" value="' + $this.options.password + '" /></div>' +
					   '</div>' +
					   '</div>';
				}
                else
    				html += '</div>';

				html += '<div class="' + $this.widgetBaseClass + '-label-error"></div>';
				html += '</div>';

                html += '<div class="organize-video-options">';
                if ($this.options.showCategories) {

                    html += '<div class="' + $this.widgetBaseClass + '-categories" />';
                }
                html += '<div class="' + $this.widgetBaseClass + '-videothumbnails" />';

                if ($this.options.displayAs == "flyout" || $this.options.displayAs == "modal") 
                {
					var isPrivateVideo = $this.options.videoType == 2 && $this.options.password.length == 0;

                    html += '<div class="sharing-options">';
                    html += '   <div class="sharing-options-header">Set Sharing Options:</div>';
                    html += '   <div>Select whether you want to allow viewers to leave comments on this video or to embed it in other websites.</div>';
                    html += '   <div style="padding:10px 0 5px 0;">';
                    html += '       <input id="allow-comment-' + $this.options.videoId + '" type="checkbox"' + (($this.options.allowComment) ? ' checked' : '') + '/>';
                    html += '       <label for="allow-comment-' + $this.options.videoId + '">Allow Comments</label>';
                    html += '   </div>';
                    html += '   <div style="padding:0 0 5px 0;">';
                    html += '       <input id="allow-embed-player-' + $this.options.videoId + '" type="checkbox"'+ (isPrivateVideo ? ' disabled="disabled"' : '') + ($this.options.allowEmbedPlayer && !isPrivateVideo ? ' checked="checked"' : '') + '/>';
                    html += '       <label for="allow-embed-player-' + $this.options.videoId + '">Allow video player to be embedded</label>';
                    html += '   </div>';
					html += '	<div id="embed_disabled_warning_' + $this.options.videoId + '" style="border:1px solid #f5d200;background-color:#FFFBCC;color:#000000;height:35px;padding:5px;' + (isPrivateVideo ? "display:block;" : "display:none;") +'">';
					html += '		<img src="images/icon_alert_orange.png" style="margin-right:5px;float:left;" />';
					html += '		<div style="font-size:10px;margin-left:30px;width:245px;">To enable comments and embedding, first change your video&#39;s privacy setting to "Display video to everyone" or "Password-protect this video."</div>';
					html += '	</div>';
					if(!isPrivateVideo && jQuery.browser.msie)
					{
						html += '<div style="height:50px;"></div>';
					}
                    html += '</div>';
                }

				

                html += '</div></div>';

				html += '</div>';
                if ($this.options.displayAs == "flyout" || $this.options.displayAs == "modal") 
                {
				    html += '<div id="tabs-' + $this.widgetBaseClass + '-embed-' + $this.options.videoId + '" class="clear-fix channel-properties" style="max-height:470px;">';
				    html += '   <div class="' + $this.widgetBaseClass + '-password-notice">Choose the elements to display on your embedded video player.</div>';
				    html += '   <div class="embed-left">';
				    html += '       <div class="embed-section-header">Display</div>';
				    html += '       <div id="embed-allow-like-parent" class="embed-list">';
                    html += '          <input id="embed-allow-like-' + $this.options.videoId + '" type="checkbox"' + (($this.options.embedAllowLike) ? ' checked' : '') + '/>';
                    html += '          <label for="embed-allow-like-' + $this.options.videoId + '">Allow Like</label>';
                    html += '       </div>';
				    html += '       <div id="embed-allow-share-parent" class="embed-list">';
                    html += '          <input id="embed-allow-sharing-' + $this.options.videoId + '" type="checkbox"' + (($this.options.embedAllowSharing) ? ' checked' : '') + '/>';
                    html += '          <label for="embed-allow-sharing-' + $this.options.videoId + '">Allow Sharing</label>';
                    html += '       </div>';
				    html += '       <div id="embed-show-no-views-parent" class="embed-list">';
                    html += '          <input id="embed-show-no-views-' + $this.options.videoId + '" type="checkbox"' + (($this.options.embedShowNoViews) ? ' checked' : '') + '/>';
                    html += '          <label for="embed-show-no-views-' + $this.options.videoId + '">Show # of Views</label>';
                    html += '       </div>';
                    html += '       <div class="embed-section-header">Actions</div>';
				    html += '       <div class="embed-list">';
                    html += '          <input id="embed-autoplay-' + $this.options.videoId + '" type="checkbox"' + (($this.options.embedPlayerAutoPlay) ? ' checked' : '') + '/>';
                    html += '          <label for="embed-autoplay-' + $this.options.videoId + '">Autoplay on open</label>';
                    html += '       </div>';
				    html += '       <div class="embed-list">';
                    html += '          <input id="embed-loopvideo-' + $this.options.videoId + '" type="checkbox"' + (($this.options.embedPlayerLoopVideo) ? ' checked' : '') + '/>';
                    html += '          <label for="embed-loopvideo-' + $this.options.videoId + '"> Loop Video</label>';
                    html += '       </div>';
				    html += '       <div class="embed-section-header">Watch more at Video.ME</div>';
				    html += '       <div class="embed-list">';
                    html += '          <table><tr>';
                    html += '             <td style="vertical-align:middle;padding-right:5px;" >';
                    html += '                <input id="embed-show-vme-logo-' + $this.options.videoId + '" type="checkbox"' + (($this.options.embedShowVMELogo) ? ' checked' : '') + '/>';
                    html += '             </td>';
                    html += '             <td>Display logo linking back to Video.ME</td>';
                    html += '          </tr></table>';
                    html += '       </div>';
				    html += '       <div class="embed-list">';
                    html += '          <table><tr>';
                    html += '             <td style="vertical-align:middle;padding-right:5px;">';
                    html += '                <input id="embed-show-vme-bar-' + $this.options.videoId + '" type="checkbox"' + (($this.options.embedShowVmeBar) ? ' checked' : '') + '/>';
                    html += '             </td>';
                    html += '             <td>Display bar linking back to Video.ME</td>';
                    html += '          </tr></table>';
                    html += '       </div>';
    			    html += '   </div>';
				    html += '   <div class="embed-right">';
				    html += '       <div style="padding-top:24px;"><img src="Images/video_screen_sample.jpg" /></div>';
    			    html += '       <div>';
			        html += '          <div id="embed-enable-show-vme-logo-div"><img src="Images/btn_video_replay2.png" /></div>';
			        html += '          <div id="embed-disable-show-vme-logo-div"><img src="Images/btn_video_replay1.png" /></div>';                    
			        html += '          <div id="embed-show-vme-bar-div"><img src="Images/video_screen_sample_watch_more.jpg" /></div>';
    			    html += '       </div>';
    			    html += '       <div class="embed-player-bottom-controls-div" >';
    			    html += '           <div style="float:left;">';
    			    html += '               <img id="embed-like-image" src="Images/btn_like.gif" style="padding:8px 0px 8px 8px;"><img id="embed-like-indicator-image" src="Images/btn_indicator_like.gif" style="display:none;" />';
    			    html += '               <img id="embed-share-image" src="Images/btn_share_video.gif" style="padding:8px 8px 8px 0px;"><img id="embed-share-indicator-image" src="Images/btn_indicator_share_video.gif" style="display:none;" />';
    			    html += '           </div>';
    			    html += '           <div style="float:right;">';
    			    html += '               <img id="embed-show-no-views-image" src="Images/btn_views.gif" style="padding:8px 0 8px 0;"><img id="embed-show-no-views-indicator-image" src="Images/btn_indicator_views.gif" style="display:none;" />';
    			    html += '               <img src="Images/btn_rate.gif" style="padding:8px 8px 8px 0;">';
    			    html += '           </div>';
    			    html += '       </div>';
    			    html += '   </div>';
				    html += '</div>';
                }
                html += '</div>'; // '<div  id="' + $this.widgetBaseClass + '-tabs-' + $this.options.videoId
				html += '</div>'; // // class=videome-tabs
				html += '<div class="' + $this.widgetBaseClass + '-actions">';
				for (var i = 0; i < $this.options.buttons.list.length; i++)
				{
					var buttonName = $this.options.buttons.list[i];
					var buttonDef = $this.options.buttons[buttonName];

					html += '<a href="#" class="' + $this.widgetBaseClass + '-button ' + $this.widgetBaseClass + '-button-' + buttonName + '">' + buttonDef.displayName + '<a/>';

					if(buttonName == "save")
					{
						html += '<a href="#" style="display:none;" class="' + $this.widgetBaseClass + '-button ' + $this.widgetBaseClass + '-button-disabled-' + buttonName + '">' + buttonDef.displayName + '<a/>';
					}
				}


                //}
				finish(html);


				$("input#" + $this.widgetBaseClass + "-edit-title-"+$this.options.videoId).attr("value", $this.options.title).charCounter("reset");
				$("textarea#" + $this.widgetBaseClass + "-edit-description-"+$this.options.videoId).attr("value", $this.options.description).charCounter("reset");
				var showTagsList = '';
                if ($.isPopulated($this.options.tags)) {
					showTagsList = $this._tagDisplay($this.options.tags);
                }
                $("input#" + $this.widgetBaseClass + "-edit-tags-"+$this.options.videoId).attr("value", showTagsList);

			}

			if ($.isFunction($this.options.dataRetriever))
			{
				$this.options.dataRetriever(buildHtml);
			}
			else
			{
				buildHtml();
			}
		},

		// == Public methods/properties =============================================

        _tagRebuild: function(tags) {

		    var tagsList = tags.replace(/\s{2,}/g, ' ');
            
            var tagsCleaned;
            var tagRebuild = '';
            var arrTagsList = tagsList.match(/\w+|"(?:\\"|[^"])+"/g);
            if (arrTagsList)
            {
                for(var i=0;i<arrTagsList.length;i++)
                {
                    tagsCleaned = arrTagsList[i];
                    tagsCleaned = $.trim(tagsCleaned.replace(/"/g, ''));
                    if (tagsCleaned && tagsCleaned.length>0)
                    {
                        tagsCleaned = tagsCleaned.replace(/,/g, '&#44;');
                        tagRebuild = tagRebuild + tagsCleaned + ',';
                    }
                }
            }
            return tagRebuild;
        },

        _tagDisplay: function(tags) {
						
            var dataTags = '';
            var showTagsList = '';
            var showTag = '';
            var arrShowTags;

			dataTags = tags;
            
            arrShowTags = dataTags.split(',');
            if (arrShowTags)
            {
                for(var i=0;i<arrShowTags.length;i++)
                {
                    showTag = $.trim(arrShowTags[i]);
                    if (showTag.indexOf(' ')>=1)
                    {
                        showTag = '\"' + showTag + '\"';
                    }
                    if (showTag && showTag.length>0)
                    {
                        showTag = showTag.replace(/&#44;/g, ',')
                        showTagsList = showTagsList + showTag + " ";
                    }
                }
            }
			showTagsList = $.trim(showTagsList);
			return showTagsList;
		},

		open: function()
		{
			var $this = this;
			if ($.isFunction($this.options.preOpen)) $this.options.preOpen($this);
			switch (this.options.displayAs)
			{
				case "flyout":
					if ($.isFunction($this.options.open)) this.element.flyout("open", function() { $this.options.open($this); });
					else this.element.flyout("open");
					break;
				case "modal":
					//move this as an option pulled in originally? SLS
                    if ($this.options.sender=="uploadmultiple") 
                    {
                        $this.options.title = $('#ui-editVideo-edit-upload-title-'+ $this.options.fileId).val();
                        $('#ui-editVideo-edit-title-'+$this.options.videoId).val($this.options.title);
                    }
                    
                    this.element.dialog("open");
                    
					if ($.isFunction($this.options.open)) this.options.open($this);
					break;
			}
		},
		close: function()
		{
			var $this = this;
			if (this.options.displayAs == "modal")
			{
                $("#" + $this.widgetBaseClass + "-tabs-" + $this.options.videoId).tabs("destroy");

				this.element.dialog("close");
				if ($.isFunction($this.options.close)) $this.options.close($this);
			}
			else if (this.options.displayAs == "flyout")
			{
				if ($.isFunction($this.options.close)) this.element.flyout("close", function() { $this.options.close($this); });
				else this.element.flyout("close");
			}
			$this.element.find('.' + $this.widgetBaseClass + '-label-error').html('');

            $this.destroy();
            $this.element.remove();

		},

		isClosed: function()
		{
			if (this.options.displayAs == "modal")
				return !this.element.dialog("isOpen");
			else if (this.options.displayAs == "flyout")
				return this.element.flyout("isClosed");
		},

		// == Data Persistence ======================================================
		_saveData: function()
		{
			var $this = this;

            $this.element.find('.' + $this.widgetBaseClass + '-videothumbnails').editVideoThumbnail("saveData");

			var finish = function(data, callback)
			{
				if (data.success)
				{
			        if ($this.options.showCategories)
    			        $this.element.find('.' + $this.widgetBaseClass + '-categories').editCategories("saveData");

                    if ($this.options.reloadOnSuccessfulUpdate)
                    {
                        $this.close();
                        window.location.reload(true);
                        return;
                    }

					// update with any cleaned tags from server
					$this.options.tags = data.newData.Tags;
					$this.element.find('.' + $this.widgetBaseClass + '-edit-tags'+$this.options.videoId).val(data.newData.Tags);

					var privacy = $this.element.find('.' + $this.widgetBaseClass + '-privacy-container');
					if (privacy.length > 0 && $this.options.accountType == 0 && data.newData.VideoType != 2)
					{
						$this.options.videoType == data.newData.VideoType;
						$this.options.showPrivacy == false;
						privacy.hide();
					}

                    if ($this.options.displayAs != 'embed')
                    {
                        $this.options.embedAllowLike        = data.newData.EmbedAllowLike;
                        $this.options.embedAllowSharing     = data.newData.EmbedAllowSharing;
                        $this.options.embedShowNoViews      = data.newData.EmbedShowNoViews;
                        $this.options.embedPlayerAutoPlay   = data.newData.EmbedPlayerAutoPlay;
                        $this.options.embedPlayerLoopVideo  = data.newData.EmbedPlayerLoopVideo;
                        $this.options.embedShowVMELogo      = data.newData.EmbedShowLargeLink;
                        $this.options.embedShowVmeBar       = data.newData.EmbedShowGreyBar;
                    }

					if ($.isFunction(callback))
					{
						callback(data);
						if ($this.options.displayAs != 'embed') $this.close();
					}
					else $this.close();
				}
				else
				{
					$this._log(data.error);
					$this.element.find('.' + $this.widgetBaseClass + '-label-error').html(data.error);
				}
			};

			if ($.isFunction(this.options.dataPersister))
			{
			    RecordEvent(null, 'click', '23810', '');
                
                var tagsList = $.trim($this.element.find('#' + $this.widgetBaseClass + '-edit-tags-'+$this.options.videoId).makeSafeish('getSafeText'));
                var tagRebuild = $this._tagRebuild(tagsList);

                var data = {
					title: $.trim($this.element.find('#' + $this.widgetBaseClass + '-edit-title-'+$this.options.videoId).makeSafeish('getSafeText')).substring(0, $this.options.titleCharLimit),
					description: $.trim($this.element.find('#' + $this.widgetBaseClass + '-edit-description-'+$this.options.videoId).makeSafeish('getSafeText').substring(0, $this.options.descriptionCharLimit)),
					tags: tagRebuild,
					password: $.isPopulated($this.options.password) ? $this.options.password : null,
					videoType: $.isPopulated($this.options.videoType) ? $this.options.videoType : 1,
                    embedAllowLike: $this.element.find('#embed-allow-like-' + $this.options.videoId).is(':checked') ? true: false,
                    embedAllowSharing: $this.element.find('#embed-allow-sharing-' + $this.options.videoId).is(':checked') ? true: false,
                    embedShowNoViews: $this.element.find('#embed-show-no-views-' + $this.options.videoId).is(':checked') ? true: false,
                    embedPlayerAutoPlay: $this.element.find('#embed-autoplay-' + $this.options.videoId).is(':checked') ? true: false,
                    embedPlayerLoopVideo: $this.element.find('#embed-loopvideo-' + $this.options.videoId).is(':checked') ? true: false,
                    embedShowVMELogo: $this.element.find('#embed-show-vme-logo-' + $this.options.videoId).is(':checked') ? true: false,
                    embedShowVmeBar: $this.element.find('#embed-show-vme-bar-' + $this.options.videoId).is(':checked') ? true: false,
                    allowComment: $this.element.find('#allow-comment-' + $this.options.videoId).is(':checked') ? true: false,
                    allowEmbedPlayer: $this.element.find('#allow-embed-player-' + $this.options.videoId).is(':checked') ? true: false
				}

				if ($this.options.showPrivacy)
				{
					privacy = $this.element.find('#' + $this.widgetBaseClass + '-edit-privacy-'+$this.options.videoId).val();
					privacy = $.isPopulated(privacy) ? privacy : 1;
					data.videoType = privacy == 1 ? 1 : 2;
					data.password = privacy == 2 ? $.trim($this.element.find('#' + $this.widgetBaseClass + '-edit-password-'+$this.options.videoId).val()) : null;

					if ((!$.isPopulated(data.password) || data.password.length == 0) && privacy == 2)
					{
						finish({ success: false, error: 'Please enter the Password' });
						return;
					}
				}


				// if the user left a field blank, then restore it to what it was coming in
				data.title = (data.title.length == 0) ? $this.options.title : data.title;

				// Get and validate title
				if (data.title.length == 0)
				{
					finish({ success: false, error: 'Please enter the Title' });
					return;
				}

				this.options.dataPersister(data, finish);
			}
		}
	}

	// CONFIGURE: myWidget to your widget name
	$.widget("ui.editVideo", EditVideo); // create the widget

	$.ui.editVideo.getter = "isClosed";

	// CONFIGURE: myWidget to your widget name
	$.ui.editVideo.defaults = {
		titleCharLimit: 50,
		descriptionCharLimit: 400,
		passwordCharLimit: 50,
		displayAs: "flyout",
		showCategories: false,
		fileName: "",
        fileId: "",
		title: "",
		description: "",
		tags: "",
		offsetX: -7,
		offsetY: -7,
		positionX: "right",
		positionY: "top",
		titleLabel: "Video name:",
		descriptionLabel: "Video description:",
		tagsLabel: "Tags:",
		showPrivacy: true,
		accountType: 0,
		backgroundInfo: { sizes: 30, backgroundClass: 'ui-editVideo-background' },
        embedAllowLike: true,
        embedAllowSharing: true,
        embedShowNoViews: true,
        embedPlayerAutoPlay: false,
        embedPlayerLoopVideo: false,
        embedShowVMELogo: true,
        embedShowVmeBar: true,
        allowComment: true,
        allowEmbedPlayer: true,
        reloadOnSuccessfulUpdate: false,
		log: true // turn on logging.
	}

})(jQuery);

