/**
 * summary 
 * <p>
 * description
 *
 * @param  url  an absolute URL giving the base location of the image
 * @param  name the location of the image, relative to the url argument
 * @return      the image at the specified URL
 * @see         Image
 */
Coverleaf.Home = { 
    initialized : false,
    categories : {},
    general_categories : {},
    non_general_categories : {},
    category : {},
    document : {},
    documents : {},
    templates : {},
    init: function(){
        if(Coverleaf.Home.initialized===false){
            Coverleaf.Home.Model.init();
            Coverleaf.Home.View.init();
            Coverleaf.Home.Controller.init();
            Coverleaf.Home.initialized=true;
        }
    },
    reset : function(){
        this.initialized = false;
        this.categories = {};
        this.category = {};
        this.document = {};
        this.documents = {};
    }
};

Coverleaf.Home.Model = (function(){

    var data_url = "http://" + document.location.host + "?request_type=template_request";
  
    function get_data(){
        $.ajax({
            type:"GET",
            url:data_url,
            dataType: "json",
            success: function(data){  }
        });
    }
  
    function process_data(){
        if(typeof libraryJsonData != "undefined"){
            for(var i in libraryJsonData){
                if(libraryJsonData.hasOwnProperty(i)){
                    if(i.indexOf("_template")!=-1){
                        Coverleaf.Home.templates[i.replace("_template","")] = unescape(libraryJsonData[i]);
                    }else if(i.indexOf("_data"!=-1)){
                        var data_class = libraryJsonData[i][0]["item_type"];
                        if(libraryJsonData[i].length==1){
                            Coverleaf.Home[data_class] = clone(Coverleaf.Home[Coverleaf.ucFirst(data_class)]);
                            Coverleaf.Home[data_class].initialize(libraryJsonData[i][0]);
                            
                        }else{
                            var plural_class = data_class.match(/y$/) ? data_class.replace(/y$/,"ies") : data_class+"s";
                            for(var j=0;j<libraryJsonData[i].length;j++){
                                Coverleaf.Home[plural_class][libraryJsonData[i][j][data_class+"_id"]] = clone(Coverleaf.Home[Coverleaf.ucFirst(data_class)]);
                                Coverleaf.Home[plural_class][libraryJsonData[i][j][data_class+"_id"]].initialize(libraryJsonData[i][j]);
                            }
                        }
                    }
                }
            }
            delete libraryJsonData;
        }
    }
    
    function set_category_meta_objects(){
        var cat_interval = setInterval(function(){
            if(Coverleaf.Home.hasOwnProperty("categories")){
                $.each(Coverleaf.Home.categories, function(i,val){
                    if($.inArray(Coverleaf.Home.categories[i]["name"],Constants.generalDocumentCategories)==-1){
                        Coverleaf.Home.non_general_categories[i] = Coverleaf.Home.categories[i];
                    }else{
                        Coverleaf.Home.general_categories[i] = Coverleaf.Home.categories[i];
                    }
                });
            }
        },500);
    }
  
    return {
        
        init : function(){
            process_data();
            set_category_meta_objects();
            this.anchor = $("a[href='#Home']",Coverleaf.primaryNav);
            this.panel = $("#panel_Home");
            this.nav = $("#content_nav_categories a",this.panel);
            this.documentsWrapperDiv = $("#library_documents_wrapper",this.panel);
            this.documentsDiv = $("#library_documents",this.panel);
            this.documentsDivList = $("li",this.documentsDiv);
            this.documentsDivLinks = $(".doc_detail_link",this.documentsDiv);
            this.detailWrapper = $("#library_detail_wrapper",this.panel);
            this.documentAddcompLinks = $(".doc_addcomp_link");
            this.documentAddcompTriggerLinks = $(".doc_addcomp_link_trigger");
            this.purchaseOptionsLinks = $(".purchase_option");
        },    
        
        /**
        * Returns a document object from the full list of library docs 
        * <p>
        * Called when clicking on an document cover on Library page. A document_id
        * is passed in and used to find the correstponding document object 
        *
        * @param  document_id  string value corresponding to document_id prop on doc obj
        * @return doc json object
        * @see    handle_document_list_click
        */
        getDocument : function(document_id){
            return Coverleaf.objectFilter(Coverleaf.Home.documents,'document_id',document_id);
        },
          
        /**
        * Registers the passed doc as the currently active library document 
        *
        * @param  doc json doc object or doc_id
        * @return void
        * @see    handle_document_list_click
        */
        setCurrentDocument : function(doc){
            if(typeof value == "string"){
                doc = Coverleaf.objectFilter(Coverleaf.Home.documents,'document_id',doc);
            }
            Coverleaf.Home.document = doc;
        },
          
        /**
        * Registers the passed category as the currently active library category 
        *
        * @param  category json category object or category_id
        * @return void
        * @see    handle_category_list_click
        */        
        setCurrentCategory : function(category){
            if(typeof category == "string"){
                category = Coverleaf.Home.categories[category];
            }
            Coverleaf.Home.category = category
        },
        getDocumentDetailDiv : function(){
            return $("#document_detail",this.panel);
        },
        getDocumentTocDiv : function(){
            return $("#library_toc",this.panel);
        },
        
        getDocumentArchivesDiv : function(){
            return $("#document_detail_archives",this.panel);
        },
        getDocumentArchivesLinks : function(){
            return $("li a",this.getDocumentArchivesDiv());
        },
        getDocumentRelatedDocumentsDiv : function(){
            return $("#document_detail_related",this.panel);
        },
        getDocumentRelatedDocumentsLinks : function(){
            return $("li a",this.getDocumentRelatedDocumentsDiv());
        },
        getDocumentSuggestionsDiv : function(){
            return $("#suggestions",this.panel);
        },
        getDocumentSuggestionsLinks : function(){
            return $("li a",this.getDocumentSuggestionsDiv());
        },
        getDocumentSlideshowDiv : function(){
            return $("#slideshow",this.panel);
        },
        getDocumentSlideshowPagesDiv : function(){
            return $("#slideshow_pages",this.panel);
        },  
        getDocumentPurchaseOptionsDiv : function(){
            return $("#library_purchase_options",this.panel);
        }
    }
})();

Coverleaf.Home.View = (function(){
    var m = Coverleaf.Home.Model;
    return {
        init : function(){
            $(".most_clipped",m.documentsWrapperDiv).simpleScroll();
            // initialize the click behaviors on page elements
            Coverleaf.schedule([
                Coverleaf.Home.View.setMiniCartHtml,
                Coverleaf.getBlogContent
            ],this);
        },
        
        /**
        * Transitions Library/Home tab from detail view to list view
        *
        * @return void 
        */ 
        showIndex : function(){
            m.anchor.trigger('click');
            m.detailWrapper.css("display","none");
            m.documentsWrapperDiv.fadeIn("normal");
        },

        /**
        * Transitions Library/Home tab from list view to detail view.
        * Apply necessary UI behaviors
        *
        * @return void 
        */         
        showDetailWrapper : function(){
            m.anchor.trigger('click');
            m.documentsWrapperDiv.css("display","none");
            m.detailWrapper.css("display","block");
            var detail_div = m.getDocumentDetailDiv();
            Coverleaf.roundCorners(detail_div)
            Coverleaf.accordionize(detail_div);
        },
        
        /**
        * 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
        */
        filterDocumentList : function(foo_category){
            var foo_type = typeof foo_category;
            
            // get category_id whether we've received object or string
            if(foo_type == "object" && foo.hasOwnProperty("category_id")){
                var category = foo;
            }else if (foo_type == "string"){
                var category = Coverleaf.Home.categories[foo_category];
            }
            
            // find category, mark as selected. Unmark previously .selected category
            if(category){
                var category_link = m.nav.filter("[href*='category_id=" + category.category_id + "']");
                category_link.parent().addClass("selected").siblings().removeClass("selected");

                m.documentsDivList.css("display","none").filter("." + category.category_id).css("display","block");

                $(".category_name",m.panel).html(category.name);
            }
        },

        /**
        * Replaces existing document detail div with template_html
        *
        * @return void 
        */          
        setDocumentDetailHtml : function(doc){
            m.getDocumentDetailDiv().replaceWith(doc.detail_html);
            setTimeout(function(){
                $("#document_detail_related",m.getDocumentDetailDiv()).simpleScroll();
            },Constants.detailPageBehaviorPad);
        },
        
        /**
        * Replaces existing document toc div wth template_html
        *
        * @return void 
        */        
        setDocumentTocHtml : function(template_html){
            m.getDocumentTocDiv().html(template_html);
            if(Constants.browserIeSix === false){
                Scroller.destroy("home_toc");
                setTimeout(function(){
                   var toc_scroller = new Scroller("toc_content",{height:160,scope:Coverleaf.Home.Model.panel,name:"home_toc"}); 
                },Constants.detailPageBehaviorPad);
            }
        },

        /**
        * Replaces existing document archives div wth template_html
        *
        * @return void 
        */          
        setDocumentArchivesHtml : function(){
            var doc = Coverleaf.Home.document;
            m.getDocumentArchivesDiv().replaceWith(doc.archives_html);
            setTimeout(function(){
                m.getDocumentArchivesDiv().simpleScroll({animation_easing : "easeInOutQuad"});
                $("#more_archives",m.getDocumentArchivesDiv())
                    .unbind('click.more_archives',doc.moreArchivesClick)
                    .bind('click.more_archives',doc.moreArchivesClick);
            },Constants.detailPageBehaviorPad);
        },
        
        updateDocumentArchivesHtml : function(doc){
            var doc = Coverleaf.Home.document;
            var archives_list = $("ul",m.getDocumentArchivesDiv());
            archives_list.append(doc.new_archives);
        },
        
        /**
        * Replaces existing document cover slideshow div wth template_html
        *
        * @return void 
        */                  
        setDocumentSlideshowHtml : function(doc){
            m.getDocumentSlideshowDiv().replaceWith(doc.slideshow_html);
            m.getDocumentSlideshowDiv().slideshow({animate:Constants.animateSlideshow,autoplay:false,slide_click_callback:Coverleaf.Home.View.slideshowSlideClick});
            setTimeout(function(){
                $("#slideshow_loading").fadeOut("normal",function(){
                    $(this).remove();
                    if (navigator.userAgent.toLowerCase().indexOf("msie 6") != -1){ 
                        $(".slide_cover",m.panel).each(function(){
                            var w = $(this).prev().outerWidth();
                            $(this).width(w);
                        });
                    }
                });
            },1000);
        },
        
        initSlideshowTransition : function(){
            $("#slideshow_loading").css({"display":"block","z-index":10});
        },
        
        slideshowSlideClick : function(){
            var href = $(this).attr("href");
            var url = jQuery.url.setUrl(href).attr("path");
            var subscription_id = Coverleaf.My_Stuff.Model.findMemberSubscriptionId('url',url);
            if(subscription_id !== false){
                href += "&sub_id=" + subscription_id;
            }
            window.open(href);
        },
        
        /**
        * Replaces existing document purchase options div wth template_html
        *
        * @return void 
        */  
        setDocumentPurchaseOptionsHtml : function(doc){
            m.getDocumentPurchaseOptionsDiv().replaceWith(doc.purchase_options_html)
        },
        
        restoreAddcompButton : function(){
            if(TmpVars.hasOwnProperty('addcompButton')){
                var btn = TmpVars['addcompButton'];
                btn.object.html(btn.content);
            }
        },
        
        setMiniCartHtml : function(){
            var cart_wrapper = document.getElementById("cart_wrapper");
            var mini_cart = document.getElementById("mini_cart");
            if(mini_cart!=null){
                cart_wrapper.removeChild(mini_cart);
            }
            cart_wrapper.innerHTML='<iframe id="mini_cart" name="mini_cart" src="'+Constants.miniCartUrl+'" frameborder="0" width="208" height="300" scrolling="no"><a href="'+Constants.cartUrl+'" title="Click to view your cart">Your Cart</a></iframe>';        
        }
    }
})();

Coverleaf.Home.Controller = (function(){
    var m = Coverleaf.Home.Model;
    var v = Coverleaf.Home.View;
    var category_pattern = /Category=([^&]+).*/;
    var document_pattern = /Document=([^&]+).*/;
    var pending_cart_request = false;
      
    function init_home_links(){
        m.documentsDivLinks
            .die('click.document_list_click', handle_document_list_click)
            .live('click.document_list_click', handle_document_list_click);
        m.nav
            .die('click.category_list_click', handle_category_list_click)
            .live('click.category_list_click', handle_category_list_click);
        m.getDocumentArchivesLinks()
            .die('click.document_archive_click', handle_document_archive_click)
            .live('click.document_archive_click', handle_document_archive_click);
        m.getDocumentRelatedDocumentsLinks()
            .die('click.related_document_click',handle_document_list_click)
            .live('click.related_document_click', handle_document_list_click);
        m.getDocumentSuggestionsLinks()
            .die('click.suggested_document_click',handle_document_list_click)
            .live('click.suggested_document_click', handle_document_list_click);
        m.documentAddcompLinks
            .die('click.addcomp_link_click', handle_document_addcomp_link_click)
            .live('click.addcomp_link_click', handle_document_addcomp_link_click);
        m.documentAddcompTriggerLinks
            .die('click.trigger_addcomp_link_click', handle_document_addcomp_trigger_link_click)
            .live('click.trigger_addcomp_link_click', handle_document_addcomp_trigger_link_click)
        m.purchaseOptionsLinks
            .die('click.purchase_option_click', handle_purchase_option_click)
            .live('click.purchase_option_click', handle_purchase_option_click);          
    }

    /**
    * 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_category_list_click(e){
        if(Coverleaf.isRightClick(e)){
            return false;
        }
        var matches = this.hash.match(category_pattern);
        if(matches.length > 0){
            var category_id = matches[1];
            if(category_id != Coverleaf.Home.category.category_id && Coverleaf.Home.categories.hasOwnProperty(category_id)){
                Coverleaf.markParentAsSelected.call(this);
                m.setCurrentCategory(category_id);
                v.filterDocumentList(category_id);
                Coverleaf.updateHistory(this.hash);
            }
            v.showIndex();
        }
        Coverleaf.ReportingManager.trackPage("/library/"+Coverleaf.Home.category.name);
    }

    /**
    * Click event for document list items 
    * <p>
    * Triggers transition to detail view featuring selected document
    *
    * @return false cancels default link behavior 
    */ 
    function handle_document_list_click(e){
        if(Coverleaf.isRightClick(e)){
            return false;
        }
        var matches = this.hash.match(document_pattern);
        if(matches && matches.length > 0){
            var doc_id = matches[1];
        
            if(doc_id != Coverleaf.Home.document.document_id && Coverleaf.Home.documents.hasOwnProperty(doc_id)){
                var doc = Coverleaf.Home.documents[doc_id];
                if(jQuery.inArray(Coverleaf.Home.category.category_id,doc.categories)==-1){
                    var first_doc_category_link = Coverleaf.Home.Model.nav.filter("[href$='Category="+doc.categories[0]+"']");
                    Coverleaf.Home.Model.setCurrentCategory(doc.categories[0]);
                    Coverleaf.markParentAsSelected.call(first_doc_category_link);
                }
                // in model, get this document's data
                m.setCurrentDocument(doc);
                doc.getDocumentDetailHtml(v.setDocumentDetailHtml);
                doc.getDocumentMetadata();
                Coverleaf.ReportingManager.trackPage("/library/"+Coverleaf.Home.category.name+"/"+doc.collection_title);
                Coverleaf.updateHistory(this.hash);
            }
            // show document detail view        
            v.showDetailWrapper();
            return true;
        }
        return false;
    }
    
    /**
    * Click event for document archive list items 
    * <p>
    * Triggers display of archive document in detail view
    *
    * @return false cancels default link behavior 
    */  
    function handle_document_archive_click(e){
        if(Coverleaf.isRightClick(e)){
            return false;
        }
        var matches = this.hash.match(document_pattern);
        if(matches.length > 0 && this.hash != location.hash){
            var doc_id = matches[1];
            var archive_doc = clone(Coverleaf.Home.Document);
            var archive_doc_obj = Coverleaf.Home.document.getArchiveDocument(doc_id);
            archive_doc_obj.archives = Coverleaf.Home.document.archives;
            archive_doc.initialize(archive_doc_obj);
            m.setCurrentDocument(archive_doc);
            Coverleaf.Home.View.initSlideshowTransition();
            Coverleaf.Home.Document.getArchiveDocumentMetadata.call(archive_doc);
            Coverleaf.updateHistory(this.hash);
            return true;
        }
        return false;
    }
    
    function handle_document_addcomp_trigger_link_click(){
        var that = $(this);
        TmpVars['addcompButton'] = {
            'object' : that,
            'content' : that.html()
        };
        var href = that.attr("href").replace(/[^#]{0,}/,"").replace("_trigger","");
        that.html(Constants.ajaxLoaderDark);
        $("a[href='"+href+"']",Coverleaf.Home.Model.documentsDiv).trigger('click');
        return false; 
    }
    
    function handle_document_addcomp_link_click(e){
        if(Coverleaf.isRightClick(e)){
            return false;
        }
        var link = $(this);
        var orig_href = link.attr("href").replace(/.*#/,"#");
        var hash_args = orig_href.replace("#Addcompanion&","");
        var href = "/addcompanion?" + hash_args;
        var tab_anchor = $("a[href$='Addcompanion']",Coverleaf.primaryNav);
        var tab_index = $("#nav_primary a").index(tab_anchor);
        var anchors = Coverleaf.tabs[0].data('tabs').anchors;
        
        Coverleaf.tabs[0].tabs('url',tab_index,href);
        Coverleaf.tabs[0].tabs('select',"Addcompanion");
        location.hash = orig_href.substring(1);
        //Coverleaf.updateHistory(orig_href.substring(1));
        return false;
    }
    
    function handle_purchase_option_click(e){
        if(Coverleaf.isRightClick(e)){
            return false;
        }
        if(pending_cart_request!==false){
            var link = $(this);
            var url_regexp = /.*(\?.*)/gi;
            var query_string = link.attr("href").replace(url_regexp,'$1')
            
            try {
                var pending_cart_request = $.getJSON(Constants.addToCartUrl + query_string + "&jsoncallback=?",function(){});
                var item_wrapper = link.closest(".purchase_option_wrapper");
                var item_name = $(".label",item_wrapper).html();
                var button_opts = { 
                    "Continue Browsing" : function() { $(this).dialog("close"); },
                    "Checkout" : function() {
                        $(this).dialog("close");
                        document.location.href = Constants.cartUrl;
                    }
                }
                $("<div><p>You&rsquo;ve added <strong>"+item_name+"</strong> to your cart</p></div>").dialog({
                    buttons: button_opts,
                    resizable: false,
                    title: "Your cart has been updated",
                    show: Constants.dialogShowEffect,
                    hide: Constants.dialogHideEffect,
                    open: function(){
                        var that = $(this);
                        setTimeout(function(){
                            that.dialog('close');
                        },5000);
                    },
                    close: function(){
                        $(this).dialog('destroy').remove();
                    }
                });
            }catch(e){}
            
            setTimeout(function(){
                Coverleaf.Home.View.setMiniCartHtml();
            },1000);
        }
        return false; 
    }
    
    function handle_preselected_document(){
        var doc = Coverleaf.Home.document;
        m.setCurrentDocument(doc);
        doc.getDocumentDetailHtml(v.setDocumentDetailHtml);
        doc.getDocumentMetadata();
        Coverleaf.updateHistory(this.hash);  
        v.showDetailWrapper();
    }
  
    return {
        init : function(){
            // initialize the click behaviors on page elements
            Coverleaf.schedule([
                init_home_links,
                Coverleaf.Home.View.setMiniCartHtml
            ],this);
            if(Coverleaf.Home.document.hasOwnProperty("document_id")){
                handle_preselected_document();
            }
        },
            
        documentTocClick : 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.Home.document;
                var href = "http://" + doc.domain + doc.url + "?folio=" + pg;
                var url = jQuery.url.setUrl(href).attr("path");
                var subscription_id = Coverleaf.My_Stuff.Model.findMemberSubscriptionId('url',url);
                if(subscription_id !== false){
                    href += "&sub_id=" + subscription_id;
                }
                
                window.open(href);
            }
        }
    }
})();

Coverleaf.Home.Category = {
    initialize : function(obj){
        for(prop in obj){
            if(obj.hasOwnProperty(prop)){
                this[prop] = obj[prop];
            }
        }    
    }
}

Coverleaf.Home.Document = {
    archive_increment : 22,
    initialize : function(obj){
        for(prop in obj){
            if(obj.hasOwnProperty(prop)){
                this[prop] = obj[prop];
            }
        }        
    },
    
    /**
    * Triggers $.ajax requests for supplemental document data  
    * <p>
    * Given a doc object, trigger methods that will pull ajax data from server.
    * This fn is called as a callback in Library.Model.getDocumentDetailHtml()
    *
    * @param  doc json doc object
    * @return void
    * @see    handle_document_list_click
    */        
    getDocumentMetadata : function(){
        var that = this;
        that.getDocumentPurchaseOptionsHtml(Coverleaf.Home.View.setDocumentPurchaseOptionsHtml);
        that.getDocumentArchives(Coverleaf.Home.View.setDocumentArchivesHtml);
        that.getDocumentSlideshow(Coverleaf.Home.View.setDocumentSlideshowHtml);
        if(Constants.browserIeSix === false){
            that.getDocumentToc(Coverleaf.Home.View.setDocumentTocHtml);
        }else{
            setTimeout(function(){
                that.getDocumentToc(Coverleaf.Home.View.setDocumentTocHtml);
            },1000);
        }
    },
    
    getArchiveDocumentMetadata : function(){
        var that = this;
        that.getDocumentPurchaseOptionsHtml(Coverleaf.Home.View.setDocumentPurchaseOptionsHtml);
        that.getDocumentSlideshow(Coverleaf.Home.View.setDocumentSlideshowHtml);
        setTimeout(function(){
            that.getDocumentToc(Coverleaf.Home.View.setDocumentTocHtml);
        },Constants.detailPageBehaviorPad);
    },
        
    /**
    * Builds or displays existing doc detail HTML  
    * <p>
    * Given a doc object, the first time this method is called for a given
    * doc it coordinates the construction of the various pieces of the 
    * doc's detail view HTML. Callback is always called, if specified
    *
    * @param  doc json doc object
    * @param  callback  method callback - usually a method to get ajax data
    * @return void
    * @see    handle_document_list_click
    */
    getDocumentDetailHtml : function(callback){
        var that = this;
        if(that.hasOwnProperty("detail_html")==false){
            var related_documents = that.getRelatedDocuments(Coverleaf.Home.category);
            var suggested_documents = that.getSuggestedDocuments(Coverleaf.Home.category);

            that.related_documents_html = related_documents.length
                                ? Coverleaf.processListTemplates(
                                    Coverleaf.Home.templates.related_documents,
                                    Coverleaf.Home.templates.related_documents_item,
                                    related_documents)
                                : "";
                              
            that.suggestions_html = suggested_documents.length 
                                ? Coverleaf.processListTemplates(
                                    Coverleaf.Home.templates.suggestions,
                                    Coverleaf.Home.templates.suggestions_item,
                                    suggested_documents)
                                : "";

            that.detail_html = Coverleaf.processTemplate(Coverleaf.Home.templates.document_detail,that); 
        }             
        if(typeof callback == "function"){
            callback.call(Coverleaf.Home.Model,that);
        }
    },
    
    /**
    * Sends HTTP request to server for fully processed HTML TOC
    * <p>
    * Given a doc json object, we issue a GET request for the full
    * HTML TOC. Before we send request we indicate activity via .gif.
    * On success, we conditionally call callback method.
    *
    * @param  doc json doc object
    * @param  callback method to be executed on success
    * @return void
    * @see    get_document_metadata, handle_document_archive_click
    */
    getDocumentToc : function(callback){
        var that = this;
        $.ajax({
            type:"GET",
            url:"/toc?document_id=" + that.document_id,
            beforeSend: function(){
                Coverleaf.Home.Model.getDocumentTocDiv().append(Constants.ajaxLoader);
            },
            success: function(html){
            
                Coverleaf.Home.Model.getDocumentTocDiv()
                    .unbind('click.document_toc_click',Coverleaf.Home.Controller.documentTocClick)
                    .bind('click.document_toc_click', Coverleaf.Home.Controller.documentTocClick);
                
                if(typeof callback == "function"){
                    callback.call(Coverleaf.Home.Model,html);
                }
            }
        });
    },

    /**
    * Sends HTTP request to server for doc slideshow in json format
    * <p>
    * Given a doc json object, we issue a GET request for the slideshow
    * data. On success, we process json response and then 
    * conditionally call callback method, passing results of data processing.
    *
    * @param  doc json doc object
    * @param  callback method to be executed on success
    * @return void
    * @see    get_document_metadata, handle_document_archive_click
    */          
    getDocumentSlideshow : function(callback){
        var that = this;
        if(that.hasOwnProperty("slideshow_html")){
            if(typeof callback == "function"){
                callback.call(Coverleaf.Home.Model,that);
            }
            return;
        }else{
            that.slideshow_html = "";
            var test_img_src = "http://" + that.domain + that.url +"/cover_lg.gif";
            var test_img = new Image();
            var slideshow_method = that.processSlidehow;
            test_img.onload = function(){
                $.ajax({
                    type:"GET",
                    url:"/library?document_id=" + that.document_id + "&request_type=slideshow",
                    dataType: "json",
                    success: function(data){
                        if(data.hasOwnProperty('slides') && data.slides.length > 0){
                            
                            if(data.slides.length < 5){
                                data.slides = that.padSlideshow(data.slides)
                            }
                            var slideshow_div = Coverleaf.Home.Model.getDocumentSlideshowPagesDiv();
                            var slideshow_h = Coverleaf.height(slideshow_div);
                            var slideshow_w = Coverleaf.width(slideshow_div);
                            var offset = test_img.width <= test_img.height ? (slideshow_w/data.slides.length) - 45 : 0;
                            if(data.slides[0].hasOwnProperty("zoom")){
                                that.slideshow_html = that.processSlideshowManual(data,offset,slideshow_h);
                            }else{
                                that.slideshow_html = that.processSlideshow(data,offset);
                            }
                            
                            
                            that.slideshow_html = Coverleaf.processTemplate(
                                Coverleaf.Home.templates.slides,
                                {list_items:that.slideshow_html}
                            );
                        }          
                        if(typeof callback == "function"){
                            callback.call(Coverleaf.Home.Model,that);
                        }
                    }
                });
            }
            test_img.src = test_img_src;
        }
    },
    
    processSlideshow : function(data,offset){
        var that = this;
        var retval = "";       
        var left = offset * -1;
        $.each(data.slides,function(j,u){
            left = left + offset;
            u.left = left;
            u.collection_title = Coverleaf.Home.document.collection_title;
            /*u.doc_href = "http://" + that.domain + that.url + "?pg="+ u.reading_order;*/
            if(u.hasOwnProperty('is_padding')){
                u.doc_href = "http://" + that.domain + that.url + "?pg="+ u.pg;
            }else{
                u.doc_href = "http://" + that.domain + that.url + "?folio="+ u.folio;
            }
            u.fg = "http://" + that.domain + that.location + "/imgpages/sstn/" + u.filename + ".png";
            retval = Coverleaf.processTemplate(
                Coverleaf.Home.templates.slides_item,
                u
            ) + retval;
        });
        return retval;    
    },
    
    processSlideshowManual : function(data,offset,slideshow_h){
        var that = this;
        var retval = "";
        var left = offset * -1;
        $.each(data.slides,function(j,u){
            left = left + offset;
            u.left = left;
            u.collection_title = Coverleaf.Home.document.collection_title;
            u.doc_href = "http://" + that.domain + that.url + "?folio="+ u.folio;
            u.bg = "http://" + that.domain + that.location + "/imgpages/" + u.zoom + "/" + u.filename + "_bg.jpg";
            u.fg = "http://" + that.domain + that.location + "/imgpages/" + u.zoom + "/" + u.filename + "_fg.png";
            u.h = slideshow_h - 12;
            retval = Coverleaf.processTemplate(
                Coverleaf.Home.templates.slides_item_manual,
                u
            ) + retval;
        });
        return retval;
    }, 
          
    getDocumentPurchaseOptionsHtml : function(callback){
        var that = this;
        if(that.open_access != "true"){
            that.digital_sub_html = that.hasOwnProperty("digital_sub") ?
                Coverleaf.processTemplate(Coverleaf.Home.templates.purchase_options_item,that.digital_sub)
                : "";
            that.digital_single_html = that.hasOwnProperty("digital_single")
                ? Coverleaf.processTemplate(Coverleaf.Home.templates.purchase_options_item,that.digital_single)
                : "";
            that.print_sub_html = that.hasOwnProperty("print_sub")
                ? Coverleaf.processTemplate(Coverleaf.Home.templates.purchase_options_item,that.print_sub)
                : "";
            that.purchase_options_html = Coverleaf.processTemplate(Coverleaf.Home.templates.purchase_options,that);
        }else{
            that.purchase_options_html = Coverleaf.processTemplate(Coverleaf.Home.templates.open_access,that);
        }
        if(typeof callback == "function"){
            callback.call(Coverleaf.Home.Model,that);
        }
    },

    /**
    * Sends HTTP request to server for doc archives in json format
    * <p>
    * Given a doc json object, we issue a GET request for the archive
    * data. On success, we trigger processing of json response and then 
    * conditionally call callback method, passing results of data processing.
    *
    * @param  doc json doc object
    * @param  callback method to be executed on success
    * @return void
    * @see    get_document_metadata
    */          
    getDocumentArchives : function(callback,incremental){
        var that = this;
        if(that.hasOwnProperty("archives_html")){
            var archive_count = typeof that.archive_count != "undefined" 
                  ? that.archive_count 
                  : that.archive_increment;
            if(that.hasOwnProperty("archives_complete")===false){
                that.doGetDocumentArchives(callback, archive_count, that.archive_increment);
            }else if(typeof callback == "function" && typeof incremental == "undefined"){
                callback.call(Coverleaf.Home.Model,that);
            }
            return;
        }else{
            that.archives_html = "";
            that.doGetDocumentArchives(callback, 0, that.archive_increment);
            return;
        }
    },
    
    doGetDocumentArchives : function(callback, start_at, quantity){
        var that = this;
        var start = typeof start_at == "undefined" ? 0 : start_at;
        that.archive_count = start == 0 ? that.archive_increment : (that.archive_count + that.archive_increment);
        $.ajax({
            type:"GET",
            url:"/library?document_id=" + that.document_id + "&request_type=archives&start=" + start + "&quantity=" + quantity,
            dataType: "json",
            success: function(data){
                if(data.hasOwnProperty('archives') && data.archives.length > 0){
                    if(start == 0){
                        that.archives = data.archives;
                        that.archives_html = Coverleaf.processListTemplates(
                            Coverleaf.Home.templates.archives,
                            Coverleaf.Home.templates.archives_item,
                            data.archives
                        );
                    }else{
                        that.archives = that.archives.concat(data.archives);
                        that.new_archives = "";
                        $.each(data.archives,function(i,val){
                            that.new_archives += Coverleaf.processTemplate(
                                Coverleaf.Home.templates.archives_item,
                                val
                            );
                        });
                    }
                }else{
                    that.archives_complete = true;
                }
                    
                if(typeof callback == "function"){
                    callback.call(Coverleaf.Home.Model,that);
                }
            }
        });        
    },

    moreArchivesClick : function(e){
        e.preventDefault();
        if(Coverleaf.isRightClick(e)){
            return false;
        }
        Coverleaf.Home.document.getDocumentArchives(
            Coverleaf.Home.View.updateDocumentArchivesHtml,
            true
        );
    },

    getArchiveDocument : function(archive_document_id){
        return this.hasOwnProperty("archives") 
                ? Coverleaf.objectFilter(this.archives,'document_id',archive_document_id)
                : {};
    },
    
    getRelatedDocuments : function(category){
        var related_docs = [];
        var that = this;
        $.each(category.documents,function(){
            if(that.document_id != this){
                related_docs.push(Coverleaf.Home.documents[this]);
            }
        });
        return related_docs;
    },
    
    //suggested docs are docs in overlapping categories (but not the current category)
    getSuggestedDocuments : function(category,quantity){
        var that = this;
        var suggested_documents = [];
        var count = quantity || 8;
        var other_categories = Coverleaf.arrayFilter(that.categories,category.category_id,true);
        
        $.each(Coverleaf.Home.general_categories,function(i,val){
            other_categories = Coverleaf.arrayFilter(other_categories,val.category_id,true);
        });
        if(other_categories.length > 0){
            $.each(Coverleaf.Home.documents,function(i,n){
                if(count > 0 && n.document_id != that.document_id && n.categories.intersect(other_categories).length > 0){
                    suggested_documents.push(Coverleaf.Home.documents[i]);
                    count--;
                }
            });
        }
        return suggested_documents
    },
    
    padSlideshow : function(slides){
        var need = 5 - slides.length;
        var src_base = slides[0].filename.split("_")[0];
        var example_slide = slides.slice(0,1)[0];
        for(i=2;i<(need+2);i++){
            var tmp_slide = {};
            tmp_slide.filename = src_base + "_000" + i;
            tmp_slide.pg = i;
            tmp_slide.zoom = example_slide.zoom;
            tmp_slide.reading_order = i;
            tmp_slide.is_padding = true;
            slides.push(tmp_slide);
        }
        return slides;
    }
};


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