function init_serp_sheriff(){
    set_sheriff_tools();
    
    //Use event bubbling to set all sheriff tool links and buttons
    //Avoids using class selectors (slower) - speeds for IE
    $("#content").live("click", function(e){
        var node = $(e.target);

        if (node.hasClass("include-code")) {
            onclick_section_transclude(e, node);
        }
        
        //click handler for page section edit links
        else if(node.hasClass("section-edit-link")){
            onclick_section_edit(e, node);
        } 

        //click handler for item (links, images, videos, etc.) edit links
        else if(node.hasClass("edit-link")){
            onclick_item_edit(e, node);
        }

        //click handlers for pin toolbar buttons
        else if(node.hasClass("pin-button") || node.hasClass("pinned-button")){
            onclick_toggle_pinned(e, node);
        }
        
        //click handlers for remove toolbar buttons
        else if(node.parent(0).hasClass("page-section-remove")){
            onclick_section_remove(e, node.parent(0));
        } 
        else if(node.parent(0).hasClass("page-item-remove")){
            onclick_item_remove(e, node.parent(0));
        }

        //click handlers for top 7 toolbar buttons
        else if(node.parent(0).hasClass("add-to-7")){
            onclick_top7(e, node.parent(0));
        } 
        
        else if(node.hasClass("warning-button")) {
            onclick_report(e, node);
        }
        
        //click handler for vanishing comments
        else if(node.hasClass("delete-comment-link")) {
            onclick_delete_comment(e, node);
        }
        
        // click handler for unvanishing comments
        else if(node.hasClass("undelete-comment-link")) {
            onclick_undelete_comment(e, node);
        }
        
        //Homepage only click handlers
        /*
        //click handler for page section edit links
        if(node.parent(0).hasClass("hp-section-edit-link")){
            onclick_hp_section_edit(e, node.parent(0));
        } 

        //click handlers for remove toolbar buttons
        else if(node.parent(0).hasClass("hp-page-section-remove")){
            onclick_hp_section_remove(e, node.parent(0));
        }

        //click handlers for remove toolbar buttons
        else if(node.parent(0).hasClass("hp-page-item-remove")){
            onclick_hp_item_remove(e, node.parent(0));
        }

        //click handler for item edit links
        else if(node.parent(0).hasClass("hp-add-item")){
            onclick_hp_item_add(e, node.parent(0));
        }

        //click handler for item edit links
        else if(node.parent(0).hasClass("hp-edit-item")){
            onclick_hp_item_edit(e, node.parent(0));
        }
        */
        //click handler for item edit links
        else if(node.is("#liberate-link")){
            onclick_liberate(e, node);
        }
    });
    
    $("#edit-categories-link").click(function (e) {
        e.preventDefault();
        
        $(this).hide();
        $("#catlist").hide();
        $("#category-loader").html("<span style='display:inline;padding:0 0 6px 0;color:#666;' class='loading'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Loading Categories...</span>");
        
        var args = $("#generic-form").serializeArray().concat(API_KEYS);
        $.ajax({
            type: "GET",
            url: API_URL + "/guides/pages/get_categories/",
            data: args,
            success: function(data){
                $("#page-categories").html(data.edit_form);
                $("#category-loader").hide();
                $("#catlist").show();
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong fetching categories. (" + msg + " : " + xhr.status + ")");
            }
        });
    });
    
    $("#add-redirect-link").click(function (e) {
        e.preventDefault();

        var args = $("#generic-form").serializeArray().concat(API_KEYS);
        $.ajax({
            type: "GET",
            url: API_URL + "/guides/get_add_redirect/",
            data: args,
            success: function(data){
                $("#add-redirect-container").html(data.add_form);
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong fetching add redirect form. (" + msg + " : " + xhr.status + ")");
            }
        });
    }, "json");

    $("#transclude-button").click(function (e) { 
        e.preventDefault();
        
        $("#add_section_throbber").html( "<span class='loading-text'>&nbsp;&nbsp;Adding...</span>" );
        $("#add_section_throbber").show();
        
        args = $("#transclude_form").serializeArray();
        args = args.concat(API_KEYS);
        
        $.ajax({
            url: API_URL + "/guides/transclude_section/",
            data: args,
            success: function(data){
                $("#add_section_throbber").hide();

                if (data.status == false) {
                    error(data.msg);
                }
                else {
                    var column = "guidenote";

                    if ($("#transclude_column").val() == "links") {
                        column = "links";
                    }

                    add_section(column, data.page_section_pk, data.section_pk, data.rendered);
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong fetching trancluding this section. (" + msg + " : " + xhr.status + ")");
            }
        });
    });
    
    //setup sortables
    create_sortable_section(".sortable-sections-gn");
    create_sortable_section(".sortable-sections-links");

    //instead of loading from each section with inline javascript, load all at once here
    sections = $(".linkslist");
    for(i=0; i < sections.length; i++){
       var section_pk = $(sections[i]).attr("section_id");
       var section_type = $(sections[i]).attr("section_type");
       var container = "." + section_type + "-sortable-items-" + section_pk;
       var elementId = section_type + "-" + section_pk + "_";
       create_sortable_items(container, elementId);
    }
    
    //much faster way to set movable buttons for current and new sections
    $('a.movable-section').live("click", function(e){
        e.preventDefault();
        direction = $(this).attr("direction");

        if($(this).parents(".sortable-sections-gn").get(0))
            container = ".sortable-sections-gn"
        else
            container = ".sortable-sections-links"
    
        elementId = "sort-section_";

        move($('#' + this.id).parents(elm_type + '[id^=' + elementId + ']').get(0).id, direction, container, true, elementId);
    });

    //much faster way to set movable buttons for current and new items
    $('a.movable-item').live("click", function(e){
        e.preventDefault();
        direction = $(this).attr("direction");
        container = $(this).attr("container");
        elementId = $(this).attr("elementid");
        
        move($('#' + this.id).parents(elm_type + '[id^=' + elementId + ']').get(0).id, direction, container, false, elementId);
        
        if ($(this).attr("direction") == 'up') {
            favorite(this);
        }
    });
    
    // insert togglers that shows/hides section-edit-icons, insert them within the entire content container
    //insertToolbarTogglers("#content");

    // add section comment admin bar when sheriff present
    var commentAdminBar = "| <a href='#' class='delete-comment-link' comment_id='COMMENT_ID'>Vanish</a>";
    var comments = $(".section-comment");
    comments.each(function() {
        if(isSheriff) {
            var comment_id = $(this).attr("comment_id");
            $(this).find(".section-comment-admin").append(commentAdminBar.replace(/COMMENT_ID/, comment_id));
        }
    });
    
    //Handlers for footer editing
    $("#serp-footer").live("click", function(e){
        var node = $(e.target);

        if(node.is("#footer-top-searches-edit")){
            onclick_edit_footer_section(e, node);
        }
        if(node.is("#footer-questions-edit")){
            onclick_edit_footer_section(e, node);
        }
        if(node.is("#footer-most-viewed-edit")){
            onclick_edit_footer_section(e, node);
        }
        else if(node.is("#footer-recent-updates-edit")){
            onclick_edit_footer_section(e, node);
        }
        else if(node.is("#footer-most-earned-edit")){
            onclick_edit_footer_section(e, node);
        }
    });
}

function set_sheriff_tools(){
    //Set Upgrade link event handler
    $("#upgrade").live("click", function(e){
        e.preventDefault();

        $('#upgrade').hide();
        $("#mahalo-loading").html( "<span class='loading-text'>&nbsp;&nbsp;Upgrading...</span>" );
        $("#mahalo-loading").show();

        args = $("#upgrade-form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/guides/create_page/",
            data: args,
            success: function(data){
                if (data.status == false) {
                    error(data.msg);
                }
                else {
                    document.location.reload();
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong upgrading this page. (" + msg + " : " + xhr.status + ")");
            }
        });
    });
    
    $("#edit-page-title").live("click", function (e) {
        e.preventDefault();
        
        var args =  $("#generic-form").serializeArray().concat(API_KEYS);

        $.ajax({
            type: "GET",
            url: API_URL + "/guides/get_edit_page/",
            data: args,
            success: function(data){
                $("#title-text").html(data.edit_form);
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong editing this page. (" + msg + " : " + xhr.status + ")");
            }
        });
    });

    //Set Delete link event handler
    $("#delete").live("click", function(e) {
        e.preventDefault();
        
        if (confirm("Are you absolutely sure you want to DELETE this page?")) {
            $("#delete").hide();
            $("#mahalo-loading").html( "<span class='loading-text'>&nbsp;&nbsp;Deleting...</span>" );
            $("#mahalo-loading").show();
        
            args = $("#delete-form").serializeArray();
            args = args.concat(API_KEYS);

            $.ajax({
                url: API_URL + "/guides/delete_page/",
                data: args,
                success: function(data){
                    if (data.status == false) {
                        error(data.msg);
                    }
                    else {
                        document.location.href = '/';
                    }
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong deleting this page. (" + msg + " : " + xhr.status + ")");
                }
            });
        }
    });

    //Set Add to Notes Column drop down event handler
    $("#add-guidenote-select").live("click", function (e) {
        e.preventDefault();
        
        if ($('#add-guidenote-select').val() == "transclude") {
            $("#transclude_column").val("note");
            $("#transclude_form").css({"visibility": "visible"});
            $("#transclude_form").css({"display": "block"});
            $("#transclude_code").focus();
            $("#add-guidenote-select").val("");
        }
        else if($("#add-guidenote-select").val() != ""){
            $("#transclude_form").css({"visibility": "hidden"});
            $("#transclude_form").css({"display": "none"});

            $("#add_section_throbber").html( "<span class='loading-text'>&nbsp;&nbsp;Adding...</span>" );
            $("#add_section_throbber").show();
            
            // Create the section, get the HTML for the section form back.
            args = $("#add_guidenote_section_form").serializeArray();
            args = args.concat(API_KEYS);

            $.ajax({
                url: API_URL + "/guides/add_page_section/",
                data: args,
                success: function(data){
                    $("#add_section_throbber").hide();
                    if (data.status == false) {
                        error(data.msg);
                    } else {
                        add_section("guidenote", data.page_section_pk, data.section_pk, data.rendered);
                        $("#add-guidenote-select").val("");
                    }
                },
                error: function(xhr, msg, thrownError){
                    $("#add_section_throbber").hide();
                    on_ajax_request_error("Something went wrong adding this section. (" + msg + " : " + xhr.status + ")");
                }
            });
        }
    });

    //Set Add to Links Column drop down event handler
    $("#add-links-select").live("click", function (e) {
        e.preventDefault();
        
        if ($('#add-links-select').val() == "transclude") {
            $("#transclude_column").val("links");
            $("#transclude_form").css({"visibility": "visible"});
            $("#transclude_form").css({"display": "block"});
            $("#transclude_code").focus();
            $("#add-links-select").val("");
        }
        else if($('#add-links-select').val() != ""){
            $("#transclude_form").css({"visibility": "hidden"});
            $("#transclude_form").css({"display": "none"});

            $("#add_section_throbber").html( "<span class='loading-text'>&nbsp;&nbsp;Adding...</span>" );
            $("#add_section_throbber").show();
            
            // Create the section, get the HTML for the section form back.
            args = $("#add_links_section_form").serializeArray();
            args = args.concat(API_KEYS);
            
            $.ajax({
                url: API_URL + "/guides/add_page_section/",
                data: args,
                success: function(data){
                    $("#add_section_throbber").hide();
                    if (data.status == false) {
                        error(data.msg);
                    }
                    else {
                        add_section("links", data.page_section_pk, data.section_pk, data.rendered);
                        $("#add-links-select").val("");
                    }
                },
                error: function(xhr, msg, thrownError){
                    $("#add_section_throbber").hide();
                    on_ajax_request_error("Something went wrong adding this section. (" + msg + " : " + xhr.status + ")");
                }
            });
        }
    });
    
    //Set Add Section link
    $('#add-section').live("click", function(e){
        $('#section-add-box').show(500);
    });
    
    //Set Add Section close link
    $('#close-add-section').live("click", function(e){
        $('#section-add-box').hide(500);
    });
}

function onclick_liberate(e, node){
    e.preventDefault();
    
    var page_slug = $(node).attr("page_slug");
 
    args = [{"name": "page_slug", "value": page_slug}];
    args = args.concat(API_KEYS);   
    
    $.ajax({
        url: API_URL + "/pages/liberate/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg);
            }
            else {
                document.location.reload();
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong adding this section. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function onclick_edit_footer_section(e,node) {
    e.preventDefault();

    var container = node.attr("container");
    var list = node.attr("list");
    
    var args = [ {"name": "section", "value": node.attr("id") } ];
    args = args.concat(API_KEYS);

    $.ajax({
        type: "GET",
        url: API_URL + "/guides/get_edit_footer_section/",
        data: args,
        success: function(data){
            $("#" + container).html(data.edit_form + '<br />');
            $("#" + list).hide();
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong editing this footer section. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function onclick_section_transclude(e, node) {
    e.preventDefault();
    var node = $(node);
    node.after('<input type="text" size="10" value="'+node.attr("code")+'" />').remove()
}

function onclick_section_edit(e, node){
    e.preventDefault();
    var type = $(node).attr("type");
    var section_pk = $(node).attr("section_id");
    var page_section_pk = $(node).attr("page_section_id");
    
    if($("#" + type + "-form-" + section_pk).length == 0){
        html = "";
        if(type == "text" || type == "ads"){
            $("#" + type + "-section-"+ section_pk).find(".section-text").html("");
        } else {
            html = $("#" + type + "-section-"+ section_pk).find(".section-text").html();
        }
        
        var args = [ {"name": "page_section_id", "value": page_section_pk }, {"name": "section_id", "value": section_pk}, {"name": "type", "value": type } ];
        args = args.concat(API_KEYS);
        
        $.ajax({
            type: "GET",
            url: API_URL + "/guides/get_edit_section/",
            data: args,
            success: function(data){
                $("#" + type + "-section-"+ section_pk).find(".section-text").html(data.edit_form + '<br />' + html);
                set_button_focus();
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong editing this section. (" + msg + " : " + xhr.status + ")");
            }
        });
    }
}

function onclick_item_edit(e, node){
    e.preventDefault();
    var type = $(node).attr("type");
    var section_pk = $(node).attr("section_id");
    var link_id = $(node).attr("meta_id");
    var page_section_id = $(node).attr("page_section_id");
    
    args = [{"name": "link_id", "value": link_id}, {"name": "page_section_id", "value": page_section_id}];
    args = args.concat(API_KEYS); 
    
    $.ajax({
        type: "GET",
        url: API_URL + "/guides/get_link_edit/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg);
            }
            else {
                var linkNode = $("#" + type + "-" + section_pk + "_" + link_id);
                $("#link-storage-" + link_id).html(linkNode.html());
                $("#" + type + "-" + section_pk + "_" + link_id).html(data.edit_form);
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong editing this link item. (" + msg + " : " + xhr.status + ")");
        }
    });
}

// Update the item order before pinning
function onclick_toggle_pinned(e, node){
    var type = $(node).parent(0).attr("type");
    
    var isSection = false;
    if( type == "section") isSection = true;
    
    if (isSection) {
        var container = $(node).parent();
        
        while (container.get(0).tagName.toUpperCase() != 'UL') {
            container = $(container).parent();
            
            if (container.get(0).tagName.toUpperCase() == 'BODY') {
                return false;
            }
        }
    }
    else {
        var container = $(node).parent(0).attr("container");
    }
    
    function callback() {
        var item_pk = $(node).parent(0).attr("meta_id");
        var elementid = $(node).parent(0).attr("elementid");

        args = [{ "name":"item_pk", "value": item_pk }, { "name":"type", "value": type }, {"name":"pinned", "value": "1"}];
        args = args.concat(API_KEYS); 
    
        if ($(node).attr("alt") == "pin"){
            $.ajax({
                url: API_URL + "/guides/set_pinned/",
                data: args,
                success: function(data){
                    if (data.status == false) {
                        error(data.msg); 
                    }
                    else {
                        if(isSection){
                            $("#"+elementid).attr("pinned", "1");
                        } else {
                            $("#"+elementid+item_pk).attr("pinned", "1");
                        }

                        $(node).removeClass("hover-pin-button");
                        $(node).removeClass("pin-button");
                        $(node).addClass("pinned-button");
                        $(node).attr("alt", "pinned");

                        $(node).unbind("hover");
                        $(node).hover(function(e){ 
                            $(this).addClass("hover-pinned-button");
                        }, function(e){
                            $(this).removeClass("hover-pinned-button");
                        });

                        hide_pinned(node.parent(0));
                    }
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong pinning this item. (" + msg + " : " + xhr.status + ")");
                }
            });
        } else {
            args = [{ "name":"item_pk", "value": item_pk }, { "name":"type", "value": type }, {"name":"pinned", "value": "0"}];
            args = args.concat(API_KEYS); 

            $.ajax({
                url: API_URL + "/guides/set_pinned/",
                data: args,
                success: function(data){
                    if (data.status == false) {
                        error(data.msg);
                    }
                    else {
                        if(isSection){
                            $("#"+elementid).attr("pinned", "0");
                        } else {
                            $("#"+elementid+item_pk).attr("pinned", "0");
                        }

                        $(node).removeClass("hover-pinned-button");
                        $(node).removeClass("pinned-button");
                        $(node).addClass("pin-button");
                        $(node).attr("alt", "pin");

                        $(node).unbind("hover");
                        $(node).hover(function(e){ 
                            $(this).addClass("hover-pin-button");
                        }, function(e){
                            $(this).removeClass("hover-pin-button");
                        });

                        show_pinned(node.parent(0));
                    }
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong pinning this item. (" + msg + " : " + xhr.status + ")");
                }
            });
        }
    }
    
    if (isSection) {
        set_section_order($(container), callback);
    }
    else {
        set_item_order($(container), callback);
    }
}

function show_pinned( elm ){
    $(elm).parent("span").find(".drag-button").show();
    $(elm).parent("span").find(".up-button").show();
    $(elm).parent("span").find(".down-button").show();
    $(elm).parent("span").find(".top-button").show();
    $(elm).parent("span").find(".bottom-button").show();
    $(elm).parent("span").find(".left-button").show();
    $(elm).parent("span").find(".right-button").show();
    $(elm).parent("span").find(".first-button").show();
    $(elm).parent("span").find(".last-button").show();
    $(elm).parent("span").find(".remove-button").show();
    $(elm).parent("span").find(".favorite-button").show();
    $(elm).parent("span").find(".warning-button").show();
    $(elm).parent("span").find(".seven-button").show();
    $(elm).parent("span").find(".double-seven-button").show();
}

function hide_pinned( elm ){
    $(elm).parent("span").find(".drag-button").hide();
    $(elm).parent("span").find(".up-button").hide();
    $(elm).parent("span").find(".down-button").hide();
    $(elm).parent("span").find(".top-button").hide();
    $(elm).parent("span").find(".bottom-button").hide();
    $(elm).parent("span").find(".left-button").hide();
    $(elm).parent("span").find(".right-button").hide();
    $(elm).parent("span").find(".first-button").hide();
    $(elm).parent("span").find(".last-button").hide();
    $(elm).parent("span").find(".remove-button").hide();
    $(elm).parent("span").find(".favorite-button").hide();
    $(elm).parent("span").find(".warning-button").hide();
    $(elm).parent("span").find(".seven-button").hide();
    $(elm).parent("span").find(".double-seven-button").hide();
}

function onclick_section_remove(e, node){
    var section = $(node).attr("section");
    var type = $(node).attr("type");

    // Edit the section, get the HTML for the section form back.
    args = [{ "name":"section_id", "value": section }, { "name":"type", "value": type }];
    args = args.concat(API_KEYS);

    $.ajax({
        url: API_URL + "/guides/remove_page_section/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg);
            }
            else {
                $("#sort-section_" + section).remove();
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong removing  this section. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function onclick_item_remove(e, node){
    var item = $(node).attr("item");
    var container = $(node).attr("container");
    var elementid = $(node).attr("elementid");
    var type = $(node).attr("type");

    var args = [{ "name":"item_id", "value": item }, { "name":"type", "value": type }];
    args = args.concat(API_KEYS); 
    
    // Edit the section, get the HTML for the section form back.
    $.ajax({
        url: API_URL + "/guides/remove_item/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg);
            }
            else {
                $("#" + elementid + item).remove();
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong removing  this item. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function onclick_report(e, node){
    e.preventDefault();
    
    var type = $(node).parent(0).attr("type");
    var pk = $(node).parent(0).attr("item");
    
    document.location.href = "/contact/?report="+pk+"&type="+type+"&returnto="+PAGE_SLUG;
}

function onclick_delete_comment(e, node) {
    e.preventDefault();
    var comment_id = $(node).attr("comment_id");
    var args = [{ "name":"comment_id", "value": comment_id }];
    args = args.concat(API_KEYS);
    
    $.ajax({
        url: API_URL + "/mahalo2/comments/delete/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg);
            }
            else {
                // update link
                $(node).removeClass("delete-comment-link").addClass("undelete-comment-link").html("Unvanish");
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong removing this comment. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function onclick_undelete_comment(e, node) {
    e.preventDefault();
    var comment_id = $(node).attr("comment_id");
    var args = [{ "name":"comment_id", "value": comment_id }];
    args = args.concat(API_KEYS);
    
    // Unelete the comment
    $.ajax({
        url: API_URL + "/mahalo2/comments/undelete/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg);
            }
            else {
                // update link
                $(node).removeClass("undelete-comment-link").addClass("delete-comment-link").html("Vanish");
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong undeleting this comment. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function onclick_top7(e, node){
    e.preventDefault();
    var type = $(node).attr("type");
    var section_pk = $(node).attr("section_id");
    var meta_id = $(node).attr("meta_id");
    
    if(type == "image" || type == "video"){
        var listItem = $(node).parents(".image-thumb");
    } else {
        var listItem = $(node).parents(".sort-link-item");
    }
    
    args = [{"name": "item_id", "value": meta_id}, {"name": "type", "value": type} ];
    args = args.concat(API_KEYS);

    $.ajax({
        url: API_URL + "/guides/add_item_to_top7/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg);
            }
            else {
                if (data.remove) {
                    listItem.hide();
                }

                if ($("#"+data.top7.section_type+"-section-"+data.top7.section_id).length) {
                    replaceSection(data.top7.section_type+"-section-"+data.top7.section_id, data.top7.page_section_id, data.top7.section_id, data.top7.rendered);
                }
                else {
                    document.location.reload();
                }
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong adding this item to the top 7. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function add_section( column, page_section_pk, section_pk, html){
    var selectValue; 
    
    li = $("<li>").attr("id","sort-section_" + page_section_pk).html(html);
    li.hide();
    if(column == "guidenote"){
        li.show();
        $(".sortable-sections-gn").append(li);
        li.effect("highlight", {"color": "#fff5ca"}, 2000);

        //Reset UI
        $(".sortable-sections-gn").sortable('refresh');
        section_type = $('#add-guidenote-select').val();
        $('#add-guidenote-select').val('');
    }else{
        $(".sortable-sections-links").append(li);
        li.show();
        li.effect("highlight", {"color": "#fff5ca"}, 2000);

        //Reset UI
        $(".sortable-sections-links").sortable('refresh');
        section_type = $('#add-links-select').val();
        $('#add-links-select').val('');
    }

    section_type = section_type.toLowerCase();
    
    elementIdentifier = section_type + "-" + section_pk + "_" ;    
    create_sortable_items("." + section_type + "-sortable-items-" + section_pk, elementIdentifier);

    insertToolbarTogglers("#" + elementIdentifier)

    //scroll to new section        
    var offset = li.offset().top - 60;
    $('html,body').animate({scrollTop: offset}, 0);

    if(section_type == "video" || section_type == "image"){
        set_media_hovers(section_type, section_pk);
    }
    
    if(section_type == "ads"){
        li.find(".section-text").html('Sheriff Note: Click edit to customize this ad unit. Standard Adsense Unit will display on next page reload.');
    }
    
}

function replaceSection(container_id, page_section_pk, section_pk, html) {
    var container = $("#"+container_id);
    container.html(html);
    replacedSection(container);
    reset_page_sortables();
}

function replacedSection(container) {
    var type = container.attr("section_type");
    if (container.attr("id") == "top7") {
        type = "top7";
    }
    container.find(".link-edit-toolbar img").mouseout();
    if(type == "video" || type == "image"){
        reset_media_hovers(container);
    }
    
    try {
        if(typeof showCitations == 'function') {
            showCitations();
        }
    } catch (e) { }
}

//Sortable Functions
function reset_page_sortables(){
    sections = $(".linkslist");
    for(i=0; i < sections.length; i++){
       var section_pk = $(sections[i]).attr("section_id");
       var section_type = $(sections[i]).attr("section_type");
       var container = "." + section_type + "-sortable-items-" + section_pk;
       var elementId = section_type + "-" + section_pk + "_";
       $(container).sortable("destroy");
       create_sortable_items(container, elementId);
    }
}

function create_sortable_section(container){
    $(container).sortable({
        placeholder: 'ui-state-highlight',
        helper: 'clone',
        cursor: 'move',
        opacity: 0.8,
        handle: '.dragable-section.drag-handle',
        start: function(event, ui){
            ui.helper.css("background", "white");
            ui.helper.css("border", "1px dotted #2691d0");
            ui.helper.css("padding", "10px");

            var content = ui.helper.find('.section-text');
            $(content).hide("");
            ui.helper.height('');
        },
        update: function(event, ui){
            ui.item.effect("highlight", {"color": "#fff5ca"}, 2000);
            set_section_order(container);
        }
    });
}

function create_sortable_items(container, elementIdentifier){
    $(container).sortable({
        placeholder: 'ui-state-highlight',
        helper: 'clone',
        cursor: 'move',
        opacity: 0.8,
        handle: '.dragable-item.drag-handle',
        start: function(event, ui){
            ui.helper.css("background", "white");
            ui.helper.css("border", "1px dotted #2691d0");
            ui.helper.css("padding", "10px");

            ui.helper.height('');
        },
        update: function(event, ui){
            ui.item.effect("highlight", {"color": "#fff5ca"}, 2000);
            set_item_order($(container));
        }
    });
    
    var type = elementIdentifier.split("-")[0];
    if(type == "image" || type == "video")
        $(container).sortable('option', 'placeholder', '');
}

function set_section_order(elm, callback){
    var items = $(elm).find("> li");
    
    var order = "page_slug="+PAGE_SLUG+"&key_owner=" + MAHALO_KEY_OWNER + "&access_key=" + MAHALO_ACCESS_KEY + "&public_key=" + MAHALO_PUBLIC_KEY + "&app_key=" + MAHALO_APP_KEY;
    
    items.each(function() {
        order += "&sort-section[]=" + $(this).attr("id").replace("sort-section_", "");
    });
    
    $.ajax({
        url: API_URL + "/guides/order_page_sections/",
        data: order,
        success: function(data){
            reset_page_sortables();
            if (callback) {
                callback();
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong setting the order of sections on this page. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function set_item_order(elm, callback){
    
    var order = API_KEYS.concat({"name": "item_type", "value": $(elm).attr("item_type")});

    var query_string = $(elm).sortable("serialize", { key:'sort-items[]' });
    var query_pieces = query_string.split("&");
    
    for (var i = 0; i < query_pieces.length; i++) {
        var parts = query_pieces[i].split("=");
        order.push({"name": "sort-items[]", "value": parts[1]});
    }
    
    order.push({"name": "section_id", "value": $(elm).attr("section_id")});
    
    $.ajax({
        url: API_URL + "/guides/order_items_in_section/",
        data: order,
        success: function(data){
            if (callback) {
                callback();
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong setting the order of these items. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function move(elementId, direction, container, isSection, elementIdentifier){
    var i;
    var set = $(container + " " + elm_type + '[id^=' + elementIdentifier + ']');
    var total = set.length;
    var clone = '';
    var lookup_id = $("#"+elementId).parent().attr("lookup_id");
    
    var itemOrder = [];
    
    for (i = 0; i < total; i++) {
        itemOrder.push(set.get(i).id);
    }
    
    function insertAfter(id) {
        for (var i = 0; i < itemOrder.length; i++){ 
            if (itemOrder[i] == elementId) {
                itemOrder.splice(i, 1);
                break;
            }
        }
        
        for (var i = 0; i < itemOrder.length; i++){ 
            if (itemOrder[i] == id) {
                itemOrder.splice(i+1, 0, elementId);
                break;
            }
        }
    }
    
    function insertBefore(id) {
        for (var i = 0; i < itemOrder.length; i++){ 
            if (itemOrder[i] == elementId) {
                itemOrder.splice(i, 1);
                break;
            }
        }
        
        for (var i = 0; i < itemOrder.length; i++){ 
            if (itemOrder[i] == id) {
                itemOrder.splice(i, 0, elementId);
                break;
            }
        }
    }
    
    mainLoop : for(i=0; i<total; i++){
        if(set.get(i).id == elementId){
            if(direction == 'down' && i == (total - 1)){
                // can’t move down
                break;
            }else if(direction == 'up' && i == 0){
                // can’t move up
                break;
            }else if(direction == 'top' && i == 0){
                // can’t move to top
                break;
            }else if(direction == 'bottom' && i == (total - 1)){
                // can’t move to bottom
                break;
            }

            if(direction == 'down'){
                var after = $(set.get(i+1));
            
                while (after.attr("pinned") == "1") {
                    i++;
                
                    if (i == (total - 1)) {
                        break mainLoop;
                    }
                
                    after = $(set.get(i+1));
                }

                insertAfter(set.get(i+1).id);
            }else if(direction == 'up'){
                var before = $(set.get(i-1));
            
                while (before.attr("pinned") == "1") {
                    i--;
                
                    if (i == 0) {
                        break mainLoop;
                    }
                
                    before = $(set.get(i-1));
                }
                
                insertBefore(set.get(i-1).id);
            }else if(direction == 'top'){
                var i = 0;
                
                var after = $(set.get(i));
            
                while (after.attr("pinned") == "1") {
                    i++;
                
                    if (i == (total - 1)) {
                        break mainLoop;
                    }
                
                    after = $(set.get(i+1));
                }

                insertBefore(set.get(i).id);
            }else if(direction == 'bottom'){
                var i = total - 1;
                
                var after = $(set.get(i));
            
                while (after.attr("pinned") == "1") {
                    i--;
                
                    if (i == -1) {
                        break mainLoop;
                    }
                
                    after = $(set.get(i));
                }
                
                insertAfter(set.get(i).id);
            }
            
            break;
        }
    }
    
    try {
        var items = itemOrder;
        items.reverse();
        ordered_links = []
    
        for (var i = 0; i < total; i++) {
            ordered_links.push(null);
        }
    
        for (var i = items.length - 1; i >= 0; i--) {
            var item = $("#" + items[i]);
        
            if (item.attr("pinned") == "1"){
                ordered_links[item.attr("layout_order")] = item;
                items.splice(i, 1);
            }
        }

        for (var empty_slot = 0; empty_slot < ordered_links.length; empty_slot++) {
            if (!ordered_links[empty_slot]) {
                var item = items.pop();
                ordered_links[empty_slot] = $("#"+item);
            }
        }
    
        for (var i = 0; i < ordered_links.length; i++) {
            var item = $(ordered_links[i]);
            item.remove();
        }
        
        var parent = $(container).parent();
        var cont = $($(container).get(0));
        $(container).remove();
        parent.prepend(cont);
        for (var i = ordered_links.length - 1; i >= 0; i--) {
            var item = $(ordered_links[i]);
            cont.prepend(item);

            item.attr("layout_order", i);
        }
        
        $(".add-" + elementIdentifier.split("_")[0]).appendTo(cont);
        
        if (!isSection) {
            replacedSection(cont);
        }else {
            reset_media_hovers(container);
        }
        
        reset_page_sortables();
        
        //if moving to top or bottom, scroll to the section
        if((direction == 'top' || direction == "bottom") && isSection){
            var offset = $('#' + elementId).offset().top - 20;
            $('html,body').animate({scrollTop: offset}, 1000);
        }
        
        $("#"+elementId).effect("highlight", {"color": "#fff5ca"}, 2000);
    } catch (e) {
        // Don't want the javascript reordering to interfere with saving it server-side
    }
    
    if (isSection) {
        set_section_order($(container));
    }
    else {
        var section_type = cont.attr("section_type");
        var section_id = cont.attr("section_id");
    
        if (cont.attr("id") == "top7") section_type = "top7";
        
        var args = API_KEYS.concat({"name": "item_type", "value": cont.attr("item_type")});
        args.push({"name": "section_id", "value": section_id});
        args.push({"name": "lookup_id", "value": cont.attr("lookup_id")});
    
        for (var i = 0; i < ordered_links.length; i++) {
            args.push({"name": "sort-items[]", "value": ordered_links[i].attr("id").split("_")[1] });
        }

        $.ajax({
            url: API_URL + "/guides/order_items_in_section/",
            data: args,
            success: function(data){
                if (data.status == false) {
                    error(data.msg);
                }
                else {
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong setting the order of these items. (" + msg + " : " + xhr.status + ")");
            }
        });
    }
}

function favorite(node) {
    var node = $(node);
    
    var pieces = node.attr("id").split("_");
    var item_type = pieces[1];
    var item_id = pieces[2];
    
    var args = API_KEYS.concat({"name": "item_type", "value": item_type});
    args.push({"name": "item_id", "value": item_id});
    
    $.ajax({
        url: API_URL + "/items/favorite/",
        data: args,
        success: function(data){
        },
        error: function(xhr, msg, thrownError){
        }
    });
}

function set_button_focus() {
    $(".blue-button").unbind("focus");
    $(".blue-button").focus(function (e) {
        $(this).addClass("focused-button");
    });
    
    $(".blue-button").unbind("blur");
    $(".blue-button").blur(function (e) {
        $(this).removeClass("focused-button");
    });
}

function set_tabbing() {
    var tab_sections = $(".sortable-sections-gn > li, .sortable-sections-links > li");
    var tab_index = -1;
    
    $(document).unbind("keydown");
    
    $(document).keydown(function (e) {
        if (e.keyCode == 9) {
            if (e.target.tagName != 'INPUT' && e.target.tagName != 'TEXTAREA' && e.target.tagName != 'A') {
                e.preventDefault();
            
                if (e.shiftKey) {
                    if (tab_index <= 0 || (tab_index >= tab_sections.length)) {
                        tab_index = tab_sections.length - 1;
                    }
                    else {
                        tab_index--;
                    }
                }
                else {
                    if (tab_index < 0 || (tab_index >= tab_sections.length - 1)) {
                        tab_index = 0;
                    }
                    else {
                        tab_index++;
                    }
                }
            
                var offset = $(tab_sections[tab_index]).offset().top - 10;
                $('html,body').animate({scrollTop: offset}, 500);    
        
                $(tab_sections[tab_index]).effect("highlight", {"color": "#fff5ca"}, 2000);
            }
        }
        else if (e.keyCode == 13) {
            if (e.target.tagName != 'INPUT' && e.target.tagName != 'TEXTAREA') {
                // Edit the current section.
                $(tab_sections[tab_index]).find("a.section-edit-link").click();
            }
        }
    });
}

function removeRedirect(e, slug, link) {
    e.preventDefault();
    
    var args = [ {"name": "redirect_slug", "value": slug}];
    args = args.concat(API_KEYS);

    $.ajax({
        url: API_URL + "/guides/remove_redirect/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg, "page-redirects", 275);
            }
            else {
                $(link).parent().remove();
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong removing this redirect. (" + msg + " : " + xhr.status + ")");
        }
    });
}

// insert controls for hiding/showing section-edit-icon-bar below a given selector
function insertToolbarTogglers(selector) {
    $(selector).find(".section-edit-icon-bar")
    .hide()
    .before(' | <img src="' + CONTENT_URL + '/content/skins/mahalo/images/clear.gif" class="more-icons-button" />')
    .prev()         // toggler
    .click(function(){
        $(this)     // toggler
        .next()     // toolbar
        .toggle()   // hide/show
        .prev()     // span.section-edit-tools-control
        .toggleClass("hide-icons-button");
    });
}

function init_announcements() {
    var flip = 0;
    
    $(".hp-help").click(function(){
        $(".hp-announcement-section").toggle();
    });
    
    $("#hp-announcement-extra-toggler").click(function(){
        if(flip++ % 2 == 0) {
            $(".hp-announcement-extra").slideDown();
            $("#hp-announcement-extra-toggler").html("Hide");
        }
        else {
            $(".hp-announcement-extra").slideUp();
            $("#hp-announcement-extra-toggler").html("More");
            $(".hp-announcement-section").hide();
        }
        $(".hp-announcement-section").stop();
    });
    
    var startAnnouncementAnimation = function() {
        // make announcement fade out after 15 sec. 
        if(!editMode)
            $(".hp-announcement-section").animate({opacity:1.0}, 15000, function(){ $(this).fadeOut("slow"); });
    }
    
    var stopAnnouncementAnimation = function() {
        $(".hp-announcement-section").stop();
    }
    
    // config for intent plugin that will cancel announcement fadeOut if user shows intent to read (hover)    
    var hiConfig = {    
         sensitivity: 3,                    // from 1-7, 1 being closest to built in hover event
         interval: 200,     
         over: stopAnnouncementAnimation,
         timeout: 500, 
         out: startAnnouncementAnimation
    };
    $(".hp-announcement-section").hoverIntent(hiConfig);
    startAnnouncementAnimation();
} 
