(function($){
	
    $.AttachDialog = function(el, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;
        
        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;
        
        // Add a reverse reference to the DOM object
        base.$el.data("AttachDialog", base);
        
        base.init = function(){
            base.options = $.extend({},$.AttachDialog.defaultOptions, options);
			
			base.setupOverlayAndFrame();
			base.setupContent();
			base.setupActions();
        }

		base.setupOverlayAndFrame = function(){
			base.$overlay = $("<div class='overlay' style='display:none'></div>").appendTo(document.body);
			base.$shadow = $("<div class='uploader-mask' style='display:none'></div>").appendTo(document.body);
			base.$frame = $("<div class='uploader' style='display:none'></div>").appendTo(document.body);
		}
		
		base.setupContent = function(){
			base.$title = $("<h2>" + base.options.title + "</h2>").appendTo(base.$frame);
			base.$el.appendTo(base.$frame);
		}
		
		base.setupActions = function(){
			base.$actions = $("<div class='uploader-actions'></div>").appendTo(base.$frame);
			
			base.$begin = $("<a href='#' class='button'>" + base.options.actionLabel + "</a>").click(function(e){
				base.$el.submit();
				e.preventDefault();
			}).appendTo(base.$actions);
			
			$("<span> or </span>").appendTo(base.$actions);
			
			base.$cancel = $("<a href='#'>" + base.options.cancelLabel + "</a>").click(function(e){
				base.hide();
				e.preventDefault();
			}).appendTo(base.$actions);
		}
	

		base.show = function(){
			$("#url_err, #title_err").text('');
			base.$overlay.css({opacity: 0}).show().animate({opacity:0.7},"fast");
			base.$shadow.css({opacity: 0}).show().animate({opacity:0.5},"fast");
			base.$frame.fadeIn("fast");
			return base.$el
		}
		
		base.hide = function(){
			base.$overlay.fadeOut("fast");
			base.$shadow.fadeOut("fast");
			base.$frame.fadeOut("fast");
			return base.$el
		}
        
        base.init();
    }

	
    $.AttachDialog.defaultOptions = {
        type: "video",
        path: "",
		title: "Attach Video",
		actionLabel: "Attach!",
		cancelLabel: "Cancel"
    }
	

    $.fn.attachDialog = function(options){
		if(options == "show"){
			return this.getAttachDialog().show();
		} else if (options == "hide"){
			return this.getAttachDialog().hide();			
		} else {
		    return this.each(function(){
	            (new $.AttachDialog(this, options));				
	        });
		}
    }


	
    // This function breaks the chain, but returns
    // the AttachDialog if it has been attached to the object.
    $.fn.getAttachDialog = function(){
        return this.data("AttachDialog");
    }
	
})(jQuery);