Coverleaf.My_Stuff = {
    clippings : {},
    documents : {},
    initialized : false,
    item : {},
    subscriptions : {},
    folder : "all_clippings",
    folders : {},
    templates : {},
    init : function(){
        if(Coverleaf.My_Stuff.initialized===false){
            $.extend(Coverleaf.My_Stuff.Clipping,Coverleaf.My_Stuff.Item);
            $.extend(Coverleaf.My_Stuff.Document,Coverleaf.My_Stuff.Item);
            $.extend(Coverleaf.My_Stuff.Subscription,Coverleaf.My_Stuff.Item);
            Coverleaf.My_Stuff.Model.init();
            Coverleaf.My_Stuff.View.init();
            Coverleaf.My_Stuff.Controller.init();
            Coverleaf.My_Stuff.initialized = true;
            
            Coverleaf.My_Stuff.View.reloadTab.subscribe(Coverleaf.Account.onSignIn);
            Coverleaf.My_Stuff.View.reloadTab.subscribe(Coverleaf.Account.onSignOut);
        }
    },
    reset : function(){
        this.initialized = false;
        this.clippings = {};
        this.documents = {};
        this.item = {};
        this.subscriptions = {};
        this.folder = {};
        this.folders = {};
        
        Coverleaf.My_Stuff.View.reloadTab.unsubscribe(Coverleaf.Account.onSignIn);
        Coverleaf.My_Stuff.View.reloadTab.unsubscribe(Coverleaf.Account.onSignOut);
    }
};

Coverleaf.My_Stuff.Model = (function(){
    var items;
    var folders;
    var data_url = "http://" + document.location.hostname + "/memberLibrary?cmd=get_json";
    
    function get_data(){
        $.ajax({
            type:"GET",
            url:data_url,
            dataType: "json",
            success: function(data){  }
        });
    }
    
    /**
    * Creates new Coverleaf.My_Stuff.clippings|documents|subscriptions objects via clone() 
    * <p>
    * looks more confusing than it is:
    * 1) Use json data to figure out which type of object to create using item_type attribute.
    * 2) Clone corresponding Coverleaf.My_Stuff stubb object (Clipping, Document, etc)
    *    Saved in pluralized item_type attribute of Coverleaf.My_Stuff (clippings, documents, etc)
    * 3) Call the initialize method on the newly cloned object, passing in json data object
    * 
    * Example: 
    *     Coverleaf.My_Stuff[clippings][clipping_123] = clone(Coverleaf.My_Stuff['Clipping'])
    *     Coverleaf.My_Stuff[clippings][clipping_123].initialize(clipping data)
    *
    */
    function process_data(){
        if(typeof mystuffJsonData != "undefined"){
            for(var i in mystuffJsonData){
                if(mystuffJsonData.hasOwnProperty(i)){
                    if(i.indexOf("_template")!=-1){
                        Coverleaf.My_Stuff.templates[i.replace("_template","")] = unescape(mystuffJsonData[i]);
                    }else if(i.indexOf("_data"!=-1)){
                        var item_type_length = mystuffJsonData[i].length;
                        if(item_type_length==1 && mystuffJsonData[i][0].hasOwnProperty("item_type")){
                            var data_class = mystuffJsonData[i][0]["item_type"];
                            Coverleaf.My_Stuff[data_class+"s"][data_class+"_"+mystuffJsonData[i][0][data_class+"_id"]] = clone(Coverleaf.My_Stuff[Coverleaf.ucFirst(data_class)]);
                            Coverleaf.My_Stuff[data_class+"s"][data_class+"_"+mystuffJsonData[i][0][data_class+"_id"]].initialize(mystuffJsonData[i][0]);
                            
                        }else if(item_type_length > 1){
                            for(var j=0;j<mystuffJsonData[i].length;j++){
                                if(mystuffJsonData[i][j].hasOwnProperty("item_type")){
                                    var data_class = mystuffJsonData[i][j]["item_type"];
                                    Coverleaf.My_Stuff[data_class+"s"][data_class+"_"+mystuffJsonData[i][j][data_class+"_id"]] = clone(Coverleaf.My_Stuff[Coverleaf.ucFirst(data_class)]);
                                    Coverleaf.My_Stuff[data_class+"s"][data_class+"_"+mystuffJsonData[i][j][data_class+"_id"]].initialize(mystuffJsonData[i][j]);
                                }
                            }
                        }
                    }
                }
            }
            delete mystuffJsonData;
        }
    }
    
    function process_new_folder(data,textStatus,clipping){
        var clipping_id = clipping || false;
        if(textStatus=="success" && data.hasOwnProperty('folder')){
            Coverleaf.My_Stuff.folders["folder_"+data.folder.folder_id] = clone(Coverleaf.My_Stuff.Folder);
            Coverleaf.My_Stuff.folders["folder_"+data.folder.folder_id].initialize(data.folder);
            Coverleaf.My_Stuff.Controller.resetFolderWidgetHaystack();
            if(clipping_id && !isNaN(clipping_id)){
                Coverleaf.My_Stuff.folders["folder_"+data.folder.folder_id].add_clipping(clipping_id,function(d,s){
                    var clipping_obj = Coverleaf.My_Stuff.clippings['clipping_'+clipping_id];
                    clipping_obj.after_added_to_folder(d,s,data.folder.folder_id);
                    Coverleaf.My_Stuff.View.addFolder(data.folder);
                    Coverleaf.My_Stuff.View.folderWidgetSuccess(data.folder,clipping_obj);
                });
            }else{
                Coverleaf.My_Stuff.View.addFolder(data.folder);
                Coverleaf.My_Stuff.View.folderWidgetSuccess(data.folder);
            }
        }
    }
    
    function process_new_clipping(data,textStatus){
        if(textStatus=="success" && data.hasOwnProperty('clipping')){
            Coverleaf.My_Stuff.clippings["clipping_"+data.clipping.clipping_id] = clone(Coverleaf.My_Stuff.Clipping);
            Coverleaf.My_Stuff.clippings["clipping_"+data.clipping.clipping_id].initialize(data.clipping);
            Coverleaf.My_Stuff.View.addClipping(data.clipping);            
        }
    }
    
    function process_new_document(data,textStatus){     
    }
    
    return {
        init : function(){
            process_data();
            this.anchor = $("a[href='#My_Stuff']",Coverleaf.primaryNav);
            this.panel = $("#panel_My_Stuff");
            this.nav = $("#mystuff_nav",this.panel);
            this.dashboardLink = $("#dashboard_link",this.nav);
            this.folderLinks = $("a.folder",this.nav);
            this.dashboardWrapperDiv = $("#mystuff_dashboard_wrapper",this.panel);
            this.itemsDiv = $("#mystuff_items",this.panel);
            this.itemsListHeader = $("#items_header h2",this.itemsDiv);
            this.itemsList = $("#items_list > li",this.itemsDiv);
            this.itemsLinks = $("a.item",this.itemsDiv);
            this.clippingLinks = $("li.all_clippings a.item",this.itemsDiv);
            this.dashboardItems = $("a.dashboard_item",this.dashboardWrapperDiv);
            this.detailWrapper = $("#mystuff_detail_wrapper",this.panel);
            this.folderWidget = $("#folder_widget",this.nav)
            this.widgetCover = $("#folder_widget_cover",this.folderWidget);
            this.documentTocLinks = $("a.toc_link",this.panel);
        }, 
        
        getItemDetailDiv : function(){
            return $("#item_detail",this.panel);
        },
        
        /**
        * Registers the passed doc as the currently active library document 
        *
        * @param  doc json doc object
        * @return void
        * @see    handle_document_list_click
        */
        setCurrentItem : function(item){
            Coverleaf.My_Stuff.item = item;
        },
        
        setCurrentFolder : function(folder_name){
            if (Coverleaf.My_Stuff.folders.hasOwnProperty("folder_"+folder_name)){
                Coverleaf.My_Stuff.folder = Coverleaf.My_Stuff.folders["folder_"+folder_name];
            }else{
                Coverleaf.My_Stuff.folder = folder_name;
            }
        },
        addFolder : function(folder_name,folder_input,clipping_id){
            CommunicationManager.post(
                '/memberLibrary',
                '&cmd=add_folder&add_folder='+escape(folder_name),
                function(data,textStatus){
                    folder_input.val("");
                    process_new_folder(data,textStatus,clipping_id);
                    Coverleaf.My_Stuff.Controller.updateFolderListDroppables();
                    Coverleaf.ReportingManager.trackPage("memberlibrary/add_folder/" + folder_name);
                },
                "json"
            );
        },
        addFolderFromWidget : function(){
            var clipping_id = parseInt(Coverleaf.My_Stuff.Model.widgetCover.attr("rel"),10);
            var folder_input = $("#folder_widget_input",Coverleaf.My_Stuff.Model.folderWidget)
            var folder_name = folder_input.val();

            if(folder_name != ""){
                var folder = Coverleaf.My_Stuff.Model.getFolder(folder_name);
                if(folder){
                    if(clipping_id && !isNaN(clipping_id)){
                        folder.add_clipping(clipping_id,function(data,textStatus){
                            var clipping_obj = Coverleaf.My_Stuff.clippings['clipping_'+clipping_id];
                            clipping_obj.after_added_to_folder(data,textStatus,folder.folder_id);
                            Coverleaf.My_Stuff.View.folderWidgetSuccess(folder,clipping_obj);
                            folder_input.val("");
                        });
                    }
                }else{
                    Coverleaf.My_Stuff.Model.addFolder(folder_name,folder_input,clipping_id);
                }
            }
                
        },
        
        getFolder : function(folder_name){
            var folder = false;
            for(var t in Coverleaf.My_Stuff.folders){
                if(Coverleaf.My_Stuff.folders.hasOwnProperty(t) && Coverleaf.My_Stuff.folders[t].folder_name == folder_name){
                    folder = Coverleaf.My_Stuff.folders[t];
                    break;
                }
            };
            return folder;
        },
        
        addClipping : function(document_url, pg, portal_domain, lbl, nts){
            var page = "&page=" + pg || "&page=1";
            var label = lbl ? escape(lbl) : "";
            var notes = nts ? escape(nts) : "";
            var clipping_exists = $.oGrep(Coverleaf.My_Stuff.documents,"url",document_url).length > 0;
            
            if(clipping_exists===false){
                var url = (portal_domain ? 'http://' + portal_domain : '') + '/memberLibrary';
                var data = "&cmd=copy_clipping" + "&document_url=" + document_url + page + "&label=" + label + "&notes=" + notes + "&request_type=json";
                CommunicationManager.post(url,data,process_new_clipping,"json");
                Coverleaf.ReportingManager.trackPage("memberlibrary/add_clipping/" + label);
            }else{
                Coverleaf.setVariable('flash_message', Constants.flashDuplicateClipping);
                Coverleaf.flashMessage(); 
            }
        },
        
        addDocument : function(document_url, page, portal_domain, label, notes){
            var document_exists = $.oGrep(Coverleaf.My_Stuff.documents,"url",document_url).length > 0;
            var subscription_exists = $.oGrep(Coverleaf.My_Stuff.documents,"url",document_url).length > 0;
            
            if(document_exists===false && subscription_exists===false){
                var url = (portal_domain ? 'http://' + portal_domain : '') + '/memberLibrary';
                var data = "&cmd=add_document" + "&document_url=" + document_url + "&label=" + (label ? escape(label) : "") + "&notes=" + (notes ? escape(notes) : '') + "&request_type=json";
                CommunicationManager.post(url,data,process_new_document,"json");
            }else{
                Coverleaf.setVariable('flash_message', Constants.flashDuplicateClipping);
            }
            Coverleaf.flashMessage(); 
        },
        
        findMemberSubscriptionId : function(property,value){
            var doc = $.oGrep(Coverleaf.Home.documents,property,value,true)[0];
            if(typeof doc == "undefined"){
                doc = Coverleaf.Home.document;
            }
            var my_collection = $.oGrep(Coverleaf.My_Stuff.subscriptions,'collection_collection',doc.collection_collection,true);
            var my_document = $.oGrep(Coverleaf.My_Stuff.documents,'collection_collection',doc.collection_collection,true);
            var my_subscription_id = false;
            if(my_collection.length > 0 || my_document.length > 0){
                var my_doc = my_collection.length ? my_collection[0] : my_document[0];
                if(my_doc.hasOwnProperty('subscription_id') && my_doc.subscription_id != ""){
                    my_subscription_id = my_doc.subscription_id;
                }
            }
            return my_subscription_id;
        },

        getMostClipped : function(fn_callback){
            CommunicationManager.get(
                "/library",
                {request_type: "most_clipped"},
                fn_callback
            );
        }
    }
})();

Coverleaf.My_Stuff.View = (function(){
    var m = Coverleaf.My_Stuff.Model;
    var folder_editable_opts = {
        onBlur : function(input_val){
            var already_exists = $.oGrep(Coverleaf.My_Stuff.folders,'folder_name',input_val)
            if(input_val.length && already_exists.length==0){
                Coverleaf.My_Stuff.folder.do_edit(input_val);
            }            
        },
        onClick : function(){
            return Coverleaf.My_Stuff.folder != "all_clippings";
        },
        width : 200,
        height: 20
    };

    return {
        init : function(){
            Coverleaf.roundCorners();
        },
        
        reloadTab : function(){
            Coverleaf.reloadTab(Constants.tabNameMystuff);
        },
        
        /**
        * Transitions Library/Home tab from detail view to list view
        *
        * @return void 
        */ 
        showDashboard : function(){
            m.anchor.trigger('click');
            m.detailWrapper.css("display","none");
            m.dashboardWrapperDiv.css("display","block");
        },

        /**
        * Transitions Library/Home tab from list view to detail view.
        * Apply necessary UI behaviors
        *
        * @return void 
        */         
        showDetailWrapper : function(){
            m.anchor.trigger('click');
            m.dashboardWrapperDiv.css("display","none");
            m.detailWrapper.css("display","block");
        },
        
        /**
        * Finds and displays the documents in a given category 
        * <p>
        * Called when clicking on an item in the category menu. A category
        * object or category name can be passed in and used to find matching
        * documents links from the document list. We also set .selected on 
        * the newly clicked category and remove .selected from other categories
        *
        * @param  foo_category  category object or name
        * @return void
        * @see    handle_category_list_click
        */
        filterItemList : function(folder_id,callback){
            // find category, mark as selected. Unmark previously .selected category
            if(folder_id){
                m.itemsList.css("display","none");
                var folder_items = m.itemsList.filter("." + folder_id);
                if(folder_items.length){
                    folder_items.css("display","block");    
                }else{
                    Coverleaf.My_Stuff.View.updateFolderWidget("all_documents");
                }
                if(typeof callback == "function"){
                    setTimeout(function(){
                        callback();
                    },100);
                }
            }
        },
        
        selectFirstVisibleListItem : function(){
            var first_item = $("a.item:visible:first",m.itemsDiv);
            if(first_item.length){
                $(first_item).trigger('click');
            }else{
                $("#no_clippings",this.itemsDiv).css("display","block");
                m.getItemDetailDiv().slideUp("slow");
            }
        },
        
        initNavLink : function(item_type){
            $("#all_" + item_type + "s").addClass("folder");
        },
        
        /**
        * Replaces existing document toc div wth template_html
        *
        * @return void 
        */        
        setDocumentTocHtml : function(template_html){
            $("#mystuff_toc",Coverleaf.My_Stuff.Model.panel).html(template_html);
            if(Constants.browserIeSix === false){
                Scroller.destroy("mystuff_toc");
                setTimeout(function(){
                   var toc_scroller = new Scroller("toc_content",{height:220,scope:Coverleaf.My_Stuff.Model.panel,name:"mystuff_toc"}); 
                },500);
            }
        },

        setMostClippedHtml : function(template_html){
            $(".most_clipped",Coverleaf.My_Stuff.Model.panel).html(template_html);
            $(".most_clipped",Coverleaf.My_Stuff.Model.panel).simpleScroll();
        },

        /**
        * 
        *
        * @return void 
        */ 
        updateFolderMenu : function(link){
            var text = link.text() || "";
            var folder_name = $(".folder_name",m.itemsListHeader);
            if(Coverleaf.My_Stuff.folder.folder_name == text){
                $("#folder_menu",m.itemsDiv).css("visibility","visible");
                folder_name.editable(folder_editable_opts);
            }else{
                $("#folder_menu",m.itemsDiv).css("visibility","hidden");
                if(folder_name.hasClass("is_editable")){
                    folder_name.editable('disable');
                }
            }
            $(".folder_name",m.itemsListHeader).text(text);

            Coverleaf.My_Stuff.Model.itemsListHeader.attr("class",link.attr("id"));
        },

        updateFolderWidget : function(folder_id){
            //if starts with all_(documents|subscriptions)
            if(folder_id.match(/all_documents|all_subscriptions|dashboard_link/)){
                $("#clipping_area:visible",m.folderWidget).css("display","none");
                $("#folder_widget_head_folder",m.folderWidget).css("display","block");
                $("#folder_widget_head_clipping, #folder_widget_trigger",m.folderWidget).css("display","none");
                $("#folder_widget_input",m.folderWidget).completable('deactivate');
            }else if(Coverleaf.My_Stuff.Model.itemsList.length){
                $("#clipping_area:hidden",m.folderWidget).css("display","block");
                $("#folder_widget_head_clipping, #folder_widget_trigger",m.folderWidget).css("display","block");
                $("#folder_widget_head_folder",m.folderWidget).css("display","none");
                $("#folder_widget_input",m.folderWidget).completable('activate');
            }
        },

        addFolder : function(folder){
            var folder_list = $("a.folder",this.nav)
            var folder_count = folder_list.length;
            var last_folder = folder_list.filter(":last").parent();
            var first_folder = last_folder.hasClass("never_show");
            if(first_folder === true){
                var folder_template = last_folder;
                folder_template.removeClass("never_show");
            }else{
                var folder_template = last_folder.clone().removeClass("selected");
            }

            var folder_link = folder_template.find("a");
            var folder_href = folder_link.attr("href");
            folder_href = folder_href.substring(0,folder_href.indexOf("Folder=")+7) + folder.folder_id;
            var folder_attrs = {
                "id": "folder_"+folder.folder_id,
                "title": Constants.folderTitleTemplate + folder.folder_name,
                "href": folder_href
            };
            folder_link.attr(folder_attrs).text(folder.folder_name);
            $(folder_list[folder_count-2]).parent().after(folder_template)
        },
        
        folderWidgetSuccess : function(folder,clipping){
            var success = $("#folder_widget_success",this.folderWidget).clone();
            var folder_name = $(".folder_name",success);
            var clipping_label = $(".clipping_label",success);
            var new_folder = $("#new_folder",success);
            var clipping_label_default = clipping_label.html();
            var folder_label_default = folder_name.html();
            
            if(clipping){
                clipping_label.html("<strong>"+clipping.label+"</strong>").parent().removeClass('display_none');
                new_folder.addClass("display_none");
            }else{
                clipping_label.parent().addClass('display_none');
                new_folder.removeClass("display_none");
            }
            folder_name.text(folder.folder_name);
            success.removeClass("display_none").dialog({ 
                buttons: { 
                    "Close": function() { 
                        $(this).dialog("close"); 
                    }
                },
                resizable: false,
                title: "Success!",
                show: Constants.dialogShowEffect,
                hide: Constants.dialogHideEffect,
                open: function(){
                    var that = $(this);
                    setTimeout(function(){
                        that.dialog('close');
                    },5000);
                },
                close: function(){
                    $(this).dialog('destroy').remove();
                }
            });
        },
        
        addClipping : function(clipping){
            //need to clone the last clipping
            
            var clipping_html = Coverleaf.processTemplate(Coverleaf.My_Stuff.templates.clipping_item,clipping);
            $("#items_list",m.itemsDiv).append(clipping_html);
            
            Coverleaf.flashMessage(Constants.flashAddItemSuccess);
        },
        
        addDocument : function(){
            Coverleaf.flashMessage(Constants.flashAddItemSuccess);
        }
    }
})();

Coverleaf.My_Stuff.Controller = (function(){
    var m = Coverleaf.My_Stuff.Model;
    var v = Coverleaf.My_Stuff.View;
    var hover_timeouts = {};
    
    function init_dashboard(){
        m.dashboardItems.die('click').live('click',handle_dashboard_item_click);
        var item_types = Constants.mystuffItemTypes;
        for(var i=0; i < item_types.length; i++){
            var items_list = Coverleaf.My_Stuff[item_types[i].toLowerCase()+"s"];
            var content_block = $("#dashboard_"+item_types[i],m.panel);
            var list_html = "";
            var item_counter = 0;
    
            for(var item in items_list){
                if(items_list.hasOwnProperty(item)){
                    items_list[item].dashboard_item_id = item;
                    list_html += Coverleaf.processTemplate(Coverleaf.My_Stuff.templates.dashboard_item,items_list[item]);
                    v.initNavLink(item_types[i].toLowerCase());
                    if(item_counter==5){
                        $("a.view_more",content_block)
                            .removeClass("hidden")
                            .unbind()
                            .bind('click',handle_dashboard_more_click);
                        break;
                    }
                    item_counter++;
                }
            }
            if(list_html!=""){
                $("ul",content_block).html(list_html);
            }
        }
    }    
    
    function init_links(){
        m.dashboardLink
            .unbind('click.dashboard_link_click',handle_dashboard_link_click)
            .bind('click.dashboard_link_click',handle_dashboard_link_click);
            
        m.itemsList.hover(handle_item_list_hover_over,handle_item_list_hover_out);
        
        m.itemsLinks
            .die('click.items_list_click', handle_items_list_click)
            .live('click.items_list_click', handle_items_list_click);
        m.folderLinks
            .die('click.folder_list_click',handle_folder_list_click)
            .live('click.folder_list_click',handle_folder_list_click);
        $(".social_network")
            .die('click.social_network_click',handle_social_network_click)
            .live('click.social_network_click',handle_social_network_click);
        $(".delete_clipping")
            .die('click.delete_clipping',handle_delete_clipping_click)
            .live('click.delete_clipping',handle_delete_clipping_click);
        $(".remove_clipping")
            .die('click.remove_clipping',handle_remove_clipping_click)
            .live('click.remove_clipping',handle_remove_clipping_click);
        $(".read_item")
            .die('click.read_item',handle_read_item_click)
            .live('click.read_item',handle_read_item_click);
        $("a.delete_folder")
            .die('click.delete_folder',handle_delete_folder_click)
            .live('click.delete_folder',handle_delete_folder_click);
        $("a.edit_folder")
            .die('click.edit_folder',handle_edit_folder_click)
            .live('click.edit_folder',handle_edit_folder_click);
    };

    function init_folder_list_droppable(){
        $("#folder_list a:not(#folder_ungrouped)",m.nav).droppable('destroy').droppable({
            accept: ".item",
            tolerance: "pointer",
            activeClass: "droptarget_highlight",
            hoverClass: "droptarget_hover",
            drop: function(e,ui){
                var clipping_id = $(ui.draggable).attr("id");
                var target_id = e.target.id;
                if(Coverleaf.My_Stuff.folders.hasOwnProperty(target_id)){
                    var folder = Coverleaf.My_Stuff.folders[target_id];
                    folder.add_clipping(clipping_id.replace("clipping_",""),function(d,s){
                        Coverleaf.My_Stuff.clippings[clipping_id].after_added_to_folder(d,s,folder.folder_id);
                        Coverleaf.My_Stuff.View.folderWidgetSuccess(folder,Coverleaf.My_Stuff.clippings[clipping_id]); 
                    });
                }
            }
        });        
    }
    
    function init_folder_widget(){
        var member = Coverleaf.getActiveMember();
        if(member){
            m.folderWidget.removeClass("display_none");
            init_folder_list_droppable();
            $("#clipping_area",m.folderWidget).droppable({
                accept: ".item",
                activeClass: "droptarget_highlight",
                hoverClass: "droptarget_hover",
                drop: function(e,ui){
                    var clipping = ui.draggable;
                    var cover_wrapper = clipping.find("span");
                    m.widgetCover
                        .attr("rel",clipping.attr("id")
                        .replace("clipping_",""))
                        .html(cover_wrapper.html());
                }
            });

            m.clippingLinks.draggable({
                helper: 'clone',
                cursor: 'move',
                start: function(e,ui){
                    ui.helper.find(".collection_title").css("display","none");
                },
                zIndex: 2700
            });

            $("#folder_widget_form",m.folderWidget)
                .unbind()
                .bind('submit',function(event){
                    event.preventDefault();
                    event.stopPropagation();
                    Coverleaf.My_Stuff.Model.addFolderFromWidget()
                });
                
            $("#folder_widget_submit",m.folderWidget)
                .unbind()
                .bind('click',Coverleaf.My_Stuff.Model.addFolderFromWidget);
                
            $("#folder_widget_input",m.folderWidget).completable({"haystack":$.oGrep(Coverleaf.My_Stuff.folders,"folder_name"),"active":false});
            $("#folder_widget_trigger",m.folderWidget)
                .unbind()
                .bind('click',function(){
                    $("#folder_widget_input",m.folderWidget).completable('toggle');
                    return false;
                });
        }
    };
    
    function handle_dashboard_more_click(e){
        if(Coverleaf.isRightClick(e)){
            return false;
        }
        $(this).parents('.content_block')
            .find("a.dashboard_item:first")
            .trigger('click');
    };
    
    /**
    * Click event for the subscription/document/clipping items from dashboard
    * <p>
    * Triggers transition to detail view featuring selected mystuff item
    *
    * @return false cancels default link behavior
    */
    function handle_dashboard_item_click(e){
        if(Coverleaf.isRightClick(e)){
            return false;
        }
        var data_class, item, item_id, key_data, folder_element;
        
        key_data = $(this).attr('id').split("_");
        data_class = key_data[0];
        item_id = key_data[1];
        item = Coverleaf.My_Stuff[data_class+"s"][data_class+"_"+item_id];
        folder_element = $("#all_"+data_class+"s",m.nav);
        
        m.setCurrentItem(item);
        v.showDetailWrapper();
        v.filterItemList("all_"+data_class+"s");
        
        Coverleaf.markParentAsSelected.call(folder_element,"a");
        v.updateFolderMenu(folder_element);
        v.updateFolderWidget("all_"+data_class+"s");
        item.show();
        location.hash = "#My_Stuff&" + capitalize(data_class) + "=" + item_id;
        Coverleaf.updateHistory(this.hash);
        return false;
    };
    
    /**
    * Click event for the subscription/document/clipping items in clippings view
    * <p>
    * Triggers transition to detail view featuring selected mystuff item
    *
    * @return false cancels default link behavior
    */
    function handle_items_list_click(e){
        if(Coverleaf.isRightClick(e)){
            return false;
        }
        var data_class, item, item_id, key_data;
        
        key_data = $(this).attr('id').split("_");
        data_class = key_data[0];
        item_id = key_data[1];
        if(Coverleaf.My_Stuff[data_class+"s"].hasOwnProperty(data_class+"_"+item_id)){
            item = Coverleaf.My_Stuff[data_class+"s"][data_class+"_"+item_id];
            if(!Coverleaf.My_Stuff.item.item_type || item.item_type!=Coverleaf.My_Stuff.item.item_type || item[data_class+"_id"] != Coverleaf.My_Stuff.item[data_class+"_id"]){
                m.setCurrentItem(item);
                item.show();
                Coverleaf.markParentAsSelected.call(this);
                Coverleaf.ReportingManager.trackPage("memberlibrary/"+item.collection_title+"/"+item.short_title);
                Coverleaf.updateHistory(this.hash);
            }
            v.showDetailWrapper();
            if(Coverleaf.My_Stuff.folder=="all_clippings"){
                Coverleaf.markParentAsSelected.call($("#all_clippings",m.nav),"a");
                v.filterItemList("all_clippings");
                v.updateFolderMenu($("#all_clippings",m.nav));
                v.updateFolderWidget("all_clippings");
            }
            return true;
        }
        return false;
    };
    
    function handle_item_list_hover_over(){
        var item_id = this.id;
        var list = $("ul",$(this));
        hover_timeouts[item_id+"_over"] = setTimeout(function(){
            if(Coverleaf.My_Stuff.folder.hasOwnProperty('folder_name')){
                $(".remove_clipping",list).parent().removeClass("never_show");
            }
            list.parent().css("z-index","2");
            list.css("display","block");
        },500);
        if(hover_timeouts.hasOwnProperty(item_id+"_out")){
            clearTimeout(hover_timeouts[item_id+"_out"]);
        }
    }
    
    function handle_item_list_hover_out(){
        var item_id = this.id;
        var list = $("ul",$(this));
        
        hover_timeouts[item_id+"_out"] = setTimeout(function(){
            if(Coverleaf.My_Stuff.folder.hasOwnProperty('folder_name')){
                $(".remove_clipping",list).parent().addClass("never_show");
            }
            list.parent().css("z-index","1");
            list.css("display","none");
        },500);
                
        if(hover_timeouts.hasOwnProperty(item_id+"_over")){
            clearTimeout(hover_timeouts[item_id+"_over"]);
        }
    }
    
    /**
    * Click event for the category menu items  
    * <p>
    * Triggers finding and displaying category documents on main library page
    *
    * @return false cancels default link behavior
    */
    function handle_folder_list_click(e){
        if(Coverleaf.isRightClick(e)){
            return false;
        }     
        var folder_id = $(this).attr("id").replace("folder_","");
        var parent_selector = folder_id.indexOf("all_") != -1 ? "a" : "li";
        if(folder_id != Coverleaf.My_Stuff.folder.folder_id){
            m.setCurrentFolder(folder_id);
            v.updateFolderMenu($(this));
            v.updateFolderWidget(folder_id);
            v.filterItemList($(this).attr("id"),v.selectFirstVisibleListItem);
            Coverleaf.markParentAsSelected.call(this,parent_selector);
            Coverleaf.ReportingManager.trackPage("memberlibrary/"+Coverleaf.My_Stuff.folder.folder_name);
            Coverleaf.updateHistory(this.hash);
        }
        v.showDetailWrapper();
    };
    
    function handle_dashboard_link_click(e){
        if(Coverleaf.isRightClick(e)){
            return false;
        }
        if(m.dashboardWrapperDiv.not(":visible")){
            v.showDashboard();
            v.updateFolderWidget($(this).attr('id'));
            Coverleaf.markParentAsSelected.call(this);
            Coverleaf.ReportingManager.trackPage("memberlibrary/dashboard");
            Coverleaf.updateHistory(this.hash);
        }
    };
    
    function handle_social_network_click(e){
        if(Coverleaf.isRightClick(e)){
            return false;
        }
        var href = $(this).attr("href");
        
        Coverleaf.ReportingManager.trackPage("memberlibrary/"+Coverleaf.My_Stuff.item.collection_title+"/network/"+$(this).attr("title"));
        window.open(
          href,
          'social_bookmarking',
          'toolbar=no,width=700,height=480,resizable=yes,scrollbars=1'
        );
        return false;
    }
    
    function handle_read_item_click(e){
        if(Coverleaf.isRightClick(e)){
            return false;
        }
        var link = $(e.target);
        var is_flyout = link.is(".flyout");
        if(is_flyout){
            var clipping_id = $(this).closest("li.all_clippings").attr("id").replace("li_","");
            var item = Coverleaf.My_Stuff.clippings[clipping_id];
        }else{
            var item = Coverleaf.My_Stuff.item;
        }
        var href = "http://" + item.domain + item.url + "?u1=coverleaf";
        if(item.hasOwnProperty("subscription_id") && item.subscription_id != ""){
            href += "&sub_id=" + item.subscription_id;
        }
        if(item.hasOwnProperty("page") && item.page != ""){
            href += "&pg=" + item.page;
        }
        window.open(href);
        return false;
    }
    
    function handle_delete_clipping_click(e){
        e.stopPropagation();
        var link = $(e.target);
        var is_flyout = link.is(".flyout");
        if(is_flyout){
            var clipping_id = $(this).closest("li.all_clippings").attr("id").replace("li_","");
            var item = Coverleaf.My_Stuff.clippings[clipping_id];
        }else{
            var item = Coverleaf.My_Stuff.item;
        }
        item.remove();
        return false;
    }
    
    function handle_remove_clipping_click(e){
        e.stopPropagation();
        var clipping_id = $(this).closest("li.all_clippings").attr("id").replace("li_","");
        var clipping = Coverleaf.My_Stuff.clippings[clipping_id];
        Coverleaf.My_Stuff.item.remove_from_folder.call(clipping);
        return false;
    }
    
    function handle_edit_folder_click(e){
        e.stopPropagation();
        $(".folder_name",m.itemsListHeader).trigger("click");
        return false;
    }
    
    function handle_delete_folder_click(e){
        e.stopPropagation();
        Coverleaf.My_Stuff.folder.remove();
        return false;
    }

    function get_most_clipped(){
        Coverleaf.My_Stuff.Model.getMostClipped(Coverleaf.My_Stuff.View.setMostClippedHtml)
    }
    
    return {
        init : function(){
            // initialize the click behaviors on page elements
            Coverleaf.schedule([
                get_most_clipped,
                init_dashboard,
                init_links,
                init_folder_widget
            ],this);
        },
        resetFolderWidgetHaystack : function(){
            var haystack = $.oGrep(Coverleaf.My_Stuff.folders,"folder_name")
            $("#folder_widget_input",m.folderWidget).completable('set_haystack',haystack);
        },
        updateFolderListDroppables : function(){
            init_folder_list_droppable();
        }
    }
})();

Coverleaf.My_Stuff.Item = {
    tabify : function(){
        var that = this;
        var starting_tab = that.starting_tab || 0;
        var tab_me = $("#nav_primary_item_tabs",Coverleaf.My_Stuff.Model.getItemDetailDiv());
        var tab_options = {
            ajaxOptions: { success: function(){}},
            cache: true,
            load: function(e,ui){
                that.load_tab(e,ui)
            },
            select: function(e,ui){
                return that.select_tab(e,ui)
            },
            selected: starting_tab,
            spinner: ""
        };
        if(tab_me.length){
            tab_me.parent().tabs(tab_options);
            tab_me.removeClass("tabify");
        }
    },
    select_tab : function(e,ui){
        var that = this;
        var retval = true;
        if(typeof that["select_"+ui.tab.id] == "function"){
            retval = that["select_"+ui.tab.id].call(that,e,ui);
        }
        return retval;
    },
    select_tab_item_folders : function(){
        this.init_folder_management();
    },
    select_tab_item_print : function(){
        var that = this;
        var page = that.hasOwnProperty("page") ? that.page : 1;
        var print_href = "http://" + that.domain + that.url + "/Print_submit.action?start=" + page + "&end=" + page + "&prettyPrint=false";
        var oDefWinProp = {
            fullscreen: 'no',
            width: 800,
            height: 600, 
            resizable: 'yes',
            scrollbars: 'yes',
            menubar: 'no',
            toolbar: 'no',
            status: 'no',
            location: 'no'
        };
        
        if (self.screen.width && self.screen.height) {
            oDefWinProp.top = self.screen.height/2 - oDefWinProp.height/2;
            oDefWinProp.left = (self.screen.width - oDefWinProp.width)/2;
        }
        setTimeout(function(){
            var popup_properties = Coverleaf.buildPropertyString(oDefWinProp);
            var w = window.open(print_href, 'print', popup_properties);
            if(w){
                w.focus();
            }
        },500);
        return false;   
    },
    load_tab : function(e,ui){
        var that = this;
        if(typeof that["load_"+ui.tab.id] == "function"){
            that["load_"+ui.tab.id].call(that,e,ui);
        }
    },
    load_tab_item_share : function(e,ui){
        var member = Coverleaf.getActiveMember();
        if(member){
            $("#from").val(member.username);
        }
        CommunicationManager.prepareForm("item_share_form", "/share", this.after_email);
    },
    load_tab_item_network : function(e,ui){
        $("#custom_link_label, #custom_link_input, #custom_link_button",ui.panel).unbind().bind('click',function(){
            $("#custom_link_input",ui.panel).select();
        });    
    },
    load_tab_item_embed : function(e,ui){
        $("#custom_widget_title",Coverleaf.My_Stuff.Model.panel).editable({
            saveButton:false,
            width:"95%",
            afterBlur : function(){
                $("#custom_widget_html",ui.panel).val($("#custom_widget_wrapper",Coverleaf.My_Stuff.Model.panel).html());
            }
        });
        $("#custom_widget_text",Coverleaf.My_Stuff.Model.panel).editable({
            saveButton:false,
            width:"95%",
            inputType:"textarea",
            afterBlur : function(){
                $("#custom_widget_html",ui.panel).val($("#custom_widget_wrapper",Coverleaf.My_Stuff.Model.panel).html());
            }
        });

        $("#custom_widget_label, #custom_widget_html",Coverleaf.My_Stuff.Model.panel).unbind().bind('click',function(){
            $("#custom_widget_html",ui.panel).select();
        });
        $("#custom_widget_html",ui.panel).val($("#custom_widget_wrapper",Coverleaf.My_Stuff.Model.panel).html());
    },
    toc_click : function(e){
        var that = $(e.target);
        if(that.is('a')){
            e.preventDefault();
            e.stopPropagation();
            var pg = that.attr("id").replace("toc_entry_","");
            var doc = Coverleaf.My_Stuff.item;
            var link = "http://" + doc.domain + doc.url + "?folio=" + pg;
            if(doc.subscription_id != ""){
                link += "&sub_id=" + doc.subscription_id;
            }
            window.open(link);
        }
    }
}

Coverleaf.My_Stuff.Clipping = {
    initialize : function(obj){
        for(prop in obj){
            if(obj.hasOwnProperty(prop)){
                this[prop] = obj[prop];
            }
        }
    },
    show : function(callback){
        var that = this;
        var templates = Coverleaf.My_Stuff.templates;
        var template_data = {};
        var assigned_folder_list = "";
        var unassigned_folder_list = "";
        var assigned_folders = that.get_assigned_folders();
        var unassigned_folders = that.get_unassigned_folders();
        
        // generate and insert the template HTML
                        
        // the rest of the html is more straight forward
        template_data.label = this.label;
        template_data.nav_html = Coverleaf.processTemplate(templates.item_nav,that);
        template_data.info_html = Coverleaf.processTemplate(templates.item_info_clipping,that);
        template_data.detail_html = Coverleaf.processTemplate(templates.item_wrapper_clipping,template_data); 

        // insert the generated html into the DOM
        Coverleaf.My_Stuff.Model.getItemDetailDiv().replaceWith(template_data.detail_html);
        // setup behaviors for the clipping
        that.tabify();
        CommunicationManager.prepareForm(
            "clipping_details_form",
            "memberLibrary?cmd=update_clipping",
            function(){
                that.after_edit_info();
            }
        );
        $("#mystuff_detail_header .clipping_label",Coverleaf.My_Stuff.Model.getItemDetailDiv()).editable({
            onBlur : function(input_val){
                Coverleaf.My_Stuff.item.edit_label(input_val);
            },
            onClick : function(){
                return Coverleaf.My_Stuff.item.item_type == "clipping";
            },
            width : 400,
            height: 20
        });
        if(typeof callback == "function"){
            callback.call(this);
        }
    },
    remove_from_folder : function(){
        if(Coverleaf.My_Stuff.folder.hasOwnProperty("folder_name")){
            var clipping = this;
            var dialog_html = Constants.clippingRemoveFromGroupDialog.replace("#{folder_name}",Coverleaf.My_Stuff.folder.folder_name);
            var button_opts = { 
                "Cancel" : function() { $(this).dialog("close"); },
                "Remove From Group" : function() { 
                    clipping.do_remove_from_folder(); 
                    $(this).dialog("close");
                }
            }
            var remove_clipping = $(dialog_html).dialog({ 
                buttons: button_opts,
                resizable: false,
                title: Constants.clippingRemoveFromGroupTitle,
                show: Constants.dialogShowEffect,
                hide: Constants.dialogHideEffect,
                modal: true,
                close: function(){
                    $(this).dialog('destroy').remove();
                }
            });
        }
        return false;    
    },
    do_remove_from_folder : function(){
        var that = this;
        Coverleaf.My_Stuff.folder.remove_clipping(
            that.clipping_id,
            function(data,textStatus){
                that.after_remove_from_folder(data,textStatus)
            });
    },
    remove : function(){
        var clipping = this;
        var current_folder = Coverleaf.My_Stuff.folder;
        var button_opts = { 
            "Cancel" : function() { $(this).dialog("close"); },
            "Delete From All Groups" : function() { 
                clipping.do_remove(); 
                $(this).dialog("close");
            }
        }
        var width_opt = 300;
        if(current_folder.hasOwnProperty("folder_name")){
            var folder_button = "Remove From ";
            folder_button += current_folder.folder_name.length > 20 ? current_folder.folder_name.substr(0,17) + "..." : current_folder.folder_name;
            button_opts[folder_button] = function() { 
                clipping.do_remove_from_folder(); 
                $(this).dialog("close");
            }
            width_opt = 450;
        }
        var remove_clipping = $("#remove_clipping",Coverleaf.My_Stuff.Model.detailWrapper).clone().removeClass("display_none").dialog({ 
            buttons: button_opts,
            resizable: false,
            title: Constants.clippingDeleteTitle,
            show: Constants.dialogShowEffect,
            width: width_opt,
            hide: Constants.dialogHideEffect,
            modal: true,
            close: function(){
                $(this).dialog('destroy').remove();
            }
        });
        return false;
    },
    do_remove : function(){
        var that = this;        
        CommunicationManager.post(
            '/memberLibrary',
            "&cmd=delete_clipping&clipping_id=" + that.clipping_id,
            function(data) {
                var clipping = $("#clipping_" + that.clipping_id,Coverleaf.My_Stuff.Model.itemsDiv);
                clipping.parent().next().find('a.item').trigger('click');
                clipping.parent().remove();
                $("#clipping_" + that.clipping_id,Coverleaf.My_Stuff.Model.dashboardWrapperDiv).remove();
                Coverleaf.ReportingManager.trackPage("memberlibrary/"+that.title+"/remove_from_my_stuff");
                delete Coverleaf.My_Stuff.clippings["clipping_" + that.clipping_id];
                return true;
            }
        );
    },
    after_added_to_folder : function(data,textStatus,folder_id){
        if(textStatus=="success"){
            var clipping_parent = $("#clipping_" + this.clipping_id,Coverleaf.My_Stuff.Model.itemsDiv).parent();
            if(this.folders.length == 0){
                clipping_parent.hide();
            }
            this.folders.push(folder_id);
            clipping_parent.addClass("folder_"+folder_id).removeClass("folder_ungrouped");
        }
    },
    after_remove_from_folder : function(data,textStatus){
        var folder_id = Coverleaf.My_Stuff.folder.folder_id
        if(textStatus=="success"){
            this.folders = $.grep(this.folders, function(a){
                return (a != folder_id);
            });
            var clipping_parent = $("#clipping_" + this.clipping_id,Coverleaf.My_Stuff.Model.itemsDiv).parent();
            if(this.folders.length == 0){
                clipping_parent.addClass("folder_ungrouped");
            }
            clipping_parent.removeClass("folder_"+folder_id).hide();
        }
    },
    edit_label : function(new_name){
        var that = this;
        CommunicationManager.post(
            '/memberLibrary',
            '&cmd=update_clipping&clipping_id=' + that.clipping_id + '&notes=' + escape($.trim(that.notes))+'&label='+escape(new_name),
            function(data) {
                that.label = new_name;
                $("#label",Coverleaf.My_Stuff.Model.panel).val(new_name);
                $("#clipping_"+that.clipping_id+" .collection_title",Coverleaf.My_Stuff.Model.panel).text(new_name);
                Coverleaf.ReportingManager.trackPage("memberlibrary/clipping_edit_title/" + this.label);
            }
        );    
    },
    after_edit_info : function(data,status){
        this.label = $("#label",Coverleaf.My_Stuff.Model.panel).val();
        this.notes = $("#notes",Coverleaf.My_Stuff.Model.panel).val();
        $(".clipping_label, #clipping_"+this.clipping_id+" .collection_title",Coverleaf.My_Stuff.Model.panel).text(this.label);
        Coverleaf.ReportingManager.trackPage("memberlibrary/clipping_edit_title/" + this.label);
    },
    after_email : function(){
        $("#to").val("");
    },
    get_assigned_folders : function(){
        var assigned_folders = {};
        for(var i=0;i<this.folders.length;i++){
            if(Coverleaf.My_Stuff.folders.hasOwnProperty("folder_"+this.folders[i])){
                assigned_folders["folder_"+this.folders[i]] = Coverleaf.My_Stuff.folders["folder_"+this.folders[i]];
            }
        }
        return assigned_folders;
    },
    get_unassigned_folders : function(){
        var unassigned_folders = {};
        for(var t in Coverleaf.My_Stuff.folders){
            if(Coverleaf.My_Stuff.folders.hasOwnProperty(t) && $.inArray(Coverleaf.My_Stuff.folders[t].folder_id,this.folders)==-1){
                unassigned_folders[t] = Coverleaf.My_Stuff.folders[t];
            }
        }
        return unassigned_folders;
    }
};

Coverleaf.My_Stuff.Document = {
    starting_tab : 3,
    initialize : function(obj){
        for(prop in obj){
            if(obj.hasOwnProperty(prop)){
                this[prop] = obj[prop];
            }
        }        
    },
    show : function(callback){
        var that = this;
        var templates = Coverleaf.My_Stuff.templates;
        var template_data = {};
        
        template_data.label = this.label;
        template_data.info_html = Coverleaf.processTemplate(templates.item_info_document,this);
        template_data.nav_html = Coverleaf.processTemplate(templates.item_nav,this);
        template_data.detail_html = Coverleaf.processTemplate(templates.item_wrapper_document,template_data); 
        
        // insert the generated html into the DOM
        Coverleaf.My_Stuff.Model.getItemDetailDiv()
            .fadeOut(Constants.tabAnimationDuration,function(){
                $(this).replaceWith(template_data.detail_html);
                $(this).fadeIn(Constants.tabAnimationDuration,function(){
                    // setup behaviors for the clipping
                    that.tabify();
                    that.getToc(Coverleaf.My_Stuff.View.setDocumentTocHtml)
                    if(typeof callback == "function"){
                        callback.call(this);
                    }
                });
            });
    },
    getToc : function(callback){
        var that = this;
        $.ajax({
            type:"GET",
            url:"/toc?document_id=" + that.document_id,
            beforeSend: function(){
                $("#mystuff_toc",Coverleaf.My_Stuff.Model.panel).append(Constants.ajaxLoader);
            },
            success: function(html){
                $("#mystuff_toc",Coverleaf.My_Stuff.Model.panel)
                    .unbind('click.item_toc_click',that.toc_click)
                    .bind('click.item_toc_click', that.toc_click);
                    
                if(typeof callback == "function"){
                    callback.call(that,html);
                }
            }
        });
    }
};

Coverleaf.My_Stuff.Subscription = {
    starting_tab : 3,
    initialize : function(obj){
        for(prop in obj){
            if(obj.hasOwnProperty(prop)){
                this[prop] = obj[prop];
            }
        }        
    },
    show : function(callback){
        var that = this;
        var templates = Coverleaf.My_Stuff.templates;
        var template_data = {};
        
        template_data.label = this.label;
        template_data.nav_html = Coverleaf.processTemplate(templates.item_nav,this);
        template_data.info_html = Coverleaf.processTemplate(templates.item_info_subscription,this);
        template_data.detail_html = Coverleaf.processTemplate(templates.item_wrapper_subscription,template_data); 
        
        // insert the generated html into the DOM
        Coverleaf.My_Stuff.Model.getItemDetailDiv()
            .fadeOut(Constants.tabAnimationDuration,function(){
                $(this).replaceWith(template_data.detail_html);
                $(this).fadeIn(Constants.tabAnimationDuration,function(){
                    // setup behaviors for the clipping
                    that.tabify(); 
                    that.getToc(Coverleaf.My_Stuff.View.setDocumentTocHtml)
                });
                if(typeof callback == "function"){
                    callback.call(this);
                }
            });
    },
    getToc : function(callback){
        var that = this;
        $.ajax({
            type:"GET",
            url:"/toc?document_id=" + that.document_id,
            beforeSend: function(){
                $("#mystuff_toc",Coverleaf.My_Stuff.Model.panel).append(Constants.ajaxLoader);
            },
            success: function(html){
                $("#mystuff_toc",Coverleaf.My_Stuff.Model.panel)
                    .unbind('click.item_toc_click',that.toc_click)
                    .bind('click.item_toc_click', that.toc_click);
                if(typeof callback == "function"){
                    callback.call(that,html);
                }
            }
        });
    }
};

Coverleaf.My_Stuff.Folder = {
    initialize : function(obj){
        for(prop in obj){
            if(obj.hasOwnProperty(prop)){
                this[prop] = obj[prop];
            }
        }        
    },
    do_edit : function(new_name){
        var that = this;
        CommunicationManager.post(
            '/memberLibrary',
            '&cmd=update_folder&folder_id=' + that.folder_id+'&label='+new_name,
            function(data) {
                var folder_header = $("#items_header .folder_name",Coverleaf.My_Stuff.Model.itemsDiv);
                var folder_menu_item = $("#folder_"+that.folder_id,Coverleaf.My_Stuff.Model.nav);
                that.folder_name = new_name;
                folder_header.text(new_name);
                folder_menu_item.text(new_name);
                
                Coverleaf.ReportingManager.trackPage("memberlibrary/edit_folder/" + that.folder_id);
                Coverleaf.My_Stuff.Controller.resetFolderWidgetHaystack();
            }
        );    
    },
    remove : function(){
        var folder = this;
        var remove_clipping = $("#remove_folder",Coverleaf.My_Stuff.Model.itemsDiv)
              .clone()
              .removeClass("display_none")
              .dialog({ 
                  buttons: { 
                      "Delete Folder" : function() { 
                          setTimeout(function(){
                              folder.do_remove();
                          },500);
                          $(this).dialog("close");
                      }, 
                      "Cancel": function() { $(this).dialog("close"); }
                  },
                  resizable: false,
                  title: Constants.folderDeleteTitle,
                  show: Constants.dialogShowEffect,
                  hide: Constants.dialogHideEffect,
                  modal: true,
                  close: function(){
                      $(this).dialog('destroy').remove();
                  }
              });
        return false;
    },
    do_remove : function(){
        var that = this;
        CommunicationManager.post(
            '/memberLibrary',
            '&cmd=delete_folder&folder_id=' + that.folder_id,
            function(data) {
                var folder = $("#folder_"+that.folder_id,Coverleaf.My_Stuff.Model.nav);
                var prev_folder = folder.parent().prev().find('a.folder');
                if(prev_folder.length){
                    prev_folder.trigger('click');
                    folder.parent().remove();
                }else{
                    folder.parent().addClass("never_show");
                    Coverleaf.My_Stuff.Model.dashboardLink.trigger('click');
                }
                Coverleaf.My_Stuff.Model.itemsLinks.filter("folder_" + folder).removeClass("folder_" + folder);
                Coverleaf.ReportingManager.trackPage("memberlibrary/remove_folder/" + that.folder_id);
                delete Coverleaf.My_Stuff.folders["folder_" + that.folder_id];
                Coverleaf.My_Stuff.Controller.resetFolderWidgetHaystack();
            }
        );
    },
    add_clipping : function(clipping_id,fn_callback) {
        var that = this;
        var menu_link = Coverleaf.My_Stuff.Model.folderLinks.filter("#folder_"+that.folder_id);
        CommunicationManager.post(
            '/memberLibrary',
            "&cmd=update_folder&folder_id=" + that.folder_id + "&clipping_id=" + clipping_id,
            fn_callback
        );
        if(menu_link.parent().hasClass("selected")){
            Coverleaf.My_Stuff.Model.itemsLinks.filter("#clipping_"+clipping_id).parent().css("display","block");
        }
        Coverleaf.ReportingManager.trackPage("memberlibrary/folder_add_clipping/" + clipping_id);
    },
    remove_clipping : function(clipping_id,fn_callback) {
        var that = this;
        CommunicationManager.post(
            '/memberLibrary',
            "&cmd=update_folder&folder_id=" + that.folder_id + "&clipping_id=" + clipping_id + "&delete_clipping=true",
            fn_callback
        );
        Coverleaf.ReportingManager.trackPage("memberlibrary/folder_remove_clipping/" + clipping_id);
    }
};


/*###############Copyright##################
 *####   Copyright 2009 Texterity, Inc  ####
 *###############Copyright##################
 */
