﻿


// Initialization of toolbox on any page
// requires a userid to be present
var maxHeight = 400;
var expandedHeight = 300;
var initHeight = 34;
var noContentHeight = 150;
var isOpen = false;
var handleOpen = false;
var isAnimating = false;
var isPrompt = false;
var defaultEasing = "swing";
var bkgdColor = "#505050";
var brdrColor = "#000";
var bkgdHighlight = "#6a7f95";
var wrapperID = "#dcToolboxWrapper";
var handleID = "#dcToolboxHandle";
var contentWrapperID = "#dcToolboxContentWrapper";
var contentID = "#dcToolboxContent";
var overlay = "#dcOverlay";
var urlRoot = "/ProviderToolbox/";
//var urlRoot = "/DCare2/ProviderToolbox/";
var defaultContent = "<h1>DiabetesCare.net Provider Toolbox</h1><p>Use the provider toolbox to keep track of any content you find on the site that you want to save for later.</p><p class='shaded'><img alt='icon' src='" + urlRoot + "icoToolboxAdd.png'/>Anywhere you see this icon, click it to add that page to your toolbox.</p>";
var hasDataHeader = "<p>Your DiabetesCare.net Provider Toolbox links:</p>";


function InitToolbox(uid, type) {
    
    // Establish user id from arguments
    var userID = parseInt(uid || 0) || 0;
    
    // Only proceed if user id is valid int not zero
    if (userID != 0 && type == "PROVIDER") {
        
        // Create toolbox container
        var tbWrapper = document.createElement("div");
        var tbHandle = document.createElement("div");
        var tbContent = document.createElement("div");
        var tbContentWrapper = document.createElement("div");
        var tbOverlay = document.createElement("div");

        // Append handle to wrapper
        $(tbWrapper).append(tbHandle);
        $(tbContentWrapper).append(tbContent);
        $(tbWrapper).append(tbContentWrapper);

        // Append control to document body        
        $('body').append(tbWrapper);
        $('body').append(tbOverlay);
        // Set wrapper attributes
        $(tbWrapper).attr("id", "dcToolboxWrapper").addClass("fixed-bottom").css("height", initHeight + "px");        
        // Set handle attributes
        $(tbHandle).attr("id", "dcToolboxHandle").css("height", initHeight + "px").css("background-color", bkgdColor).css("border-color", brdrColor);
        $(tbHandle).html("<div class='close'></div>");
        // Content attributes
        $(tbContentWrapper).attr("id", "dcToolboxContentWrapper").css("background-color", bkgdColor).css("border-color", brdrColor);
        $(tbContent).attr("id", "dcToolboxContent").css("height", "auto");
        $(tbOverlay).attr("id", "dcOverlay");
        // Default text for overlay
        $(tbOverlay).html("<span>This page has been added to your toolbox!</span>");

        // Process any links on this page
        $(".toolboxItem").each(function () {
            // Iterating through all toolbox items
            var url = $(this).attr("href");
            var title = $(this).attr("rel");
            var ctl = this;
            $(this).attr("href", "javascript:void(0);");
            $(this).attr("title", "Add this page to your toolbox");
            $(this).attr("rel", title.replace(/[\.,-\/#!$%\^&\*;:?{}=\-_`~()]/g, ""));
            $(this).click(function () {
                $(this).unbind("click");
                $(ctl).animate({ "opacity": "0.0" }, 100, defaultEasing, function () { $(this).css("display", "none"); });
                // Add the new item to the system
                AddItem(uid, escape(title), url);
                // Clone base overlay
                var ol = $(overlay).clone().appendTo('body');
                // Obtain clicked element position
                var pos = $(ctl).offset();
                // offset position to account for element width and overlay width
                //pos.left = pos.left - ($(ol).width() / 2) + ($(ctl).width() / 2);
                // position the overlay
                $(ol).css("top", pos.top).css("left", pos.left - 200).css("display", "block");
                // Animate
                setTimeout(function () {
                    $(ol).animate({ "opacity": "0.0", "top": "-=10px" }, 500, defaultEasing, function () { });
                }, 1000);
            });
        });


        // Populate items in content panel
        GetItems(uid);
        // Bind mouse events
        BindEvents(uid);

    }
}

function TogglePanel() {
    isAnimating = true;
    if (!isOpen) {
        $(wrapperID).animate({ "height": "+=" + ($(contentID).height() + initHeight - 1) + "px" }, 300, defaultEasing, function () { isAnimating = false; ToggleHandle(true); });
        $(handleID).addClass("down");
        isOpen = true;
    }
    else {
        $(wrapperID).animate({ "height": "-=" + ($(wrapperID).height() - initHeight) + "px" }, 300, defaultEasing, function () { isAnimating = false; ToggleHandle(false); });
        $(handleID).removeClass("down");
        isOpen = false;
    }
}

function ToggleHandle(open) {

    if (open && $(handleID).width() == 45 && !isAnimating)
        $(handleID).stop().animate({ "width": "+=180px" }, 110, defaultEasing);
    else if ($(handleID).width() == 225 && !isOpen && !isAnimating) {  
        $(handleID).stop().animate({ "width": "-=180px" }, 110, defaultEasing);
    }
    // Failsafe for sizing
    //if ($(handleID).width() < 45) { $(handleID).css("height", "35px"); }
    //if ($(handleID).width() > 225) { $(handleID).css("height", "225px"); }
}

function BindEvents(uid) {
    // Bind click and mouse events
    $(handleID).live("click", function () {
        if (!isOpen)
            GetItems(uid, true);
        else
            TogglePanel();
    }).live("mouseenter", function () {
        ToggleHandle(true)
    }).live("mouseleave", function () {
        ToggleHandle(false)
    });
    $(wrapperID).live("mouseleave", function () {
        //if (isOpen && !isPrompt)
        //    TogglePanel();
    });
}

function ResolveWrapperHeight(initialHeight, newHeight) {

    var adjustedHeight = $(wrapperID).height() - (initialHeight - newHeight);

    if (adjustedHeight > 0 && isOpen)
        $(wrapperID).css("height", adjustedHeight + "px");

    // If height exceeds maximum height, then set height to auto
    // which enables overflow scrollbars
    if ($(contentID).height() > maxHeight)
        $(contentID).css("height", (maxHeight - initHeight - 5) + "px");
    else
        $(contentID).css("height", "auto");
}
// Determines whether JSON object is empty
function isEmpty(object) {
    for (var i in object)
        return false;
    return true;
}

// Retrieves current list of links
function GetItems(uid, toggleOnComplete) {

    $(handleID).addClass("loading");

    // Disable caching of ajax request 
    // Fix for IE JSON Caching issue
    $.ajaxSetup({ cache: true });

    var jqxhr = $.getJSON(urlRoot + "handler.aspx?tm=" + (new Date().getTime()) + "&a=Read&uid=" + uid, function (result) {

        // Pre height of content area
        var initialHeight = $(contentID).outerHeight()

        $(contentID).html("");

        // Check for error     
        if (result.error == "invalid user" ||
            result.error == "read error") {
            // Handle Error            
            $(contentID).append(defaultContent);
            $(handleID).removeClass("loading");
            ResolveWrapperHeight(initialHeight, $(contentID).outerHeight());
            if (toggleOnComplete) { TogglePanel(); }
            return;
        }

        // Check for empty object
        if (isEmpty(result)) {
            // Object is empty so no items exist yet. Defer to default content.            
            //expandedHeight = noContentHeight;
            $(contentID).append(defaultContent);
            $("a.toolboxItem").css("display", "inline-block");
        }
        else {
            // Create new list control
            var linkList = document.createElement("ul");
            var itemData;
            // Append default header and unordered list         
            $(contentID).append(hasDataHeader).append(linkList);

            $.each(result, function (i, resultItem) {
                // Evaluate data tiem
                itemData = eval(resultItem);
                // Create Date                
                var dt = new Date(+itemData.createDate.replace(/\/Date\((\d+)\)\//, '$1'));
                // Create new list item
                var listItem = document.createElement("li");
                // Append to link list
                $(linkList).append(listItem)
                // Set attributes
                $(listItem).attr("id", "item" + i);
                $(listItem).attr("title", "Jump to '" + itemData.title + "'");
                $.data(listItem, "target", itemData.url);
                // Create li content
                $(listItem).html("<div class='item'>" + itemData.title + "<div>Link aa added " + dt.toDateString() + "</div></div></a><div id='del_" + i + "' class='delete'>");
                // Create click handler for  item
                $("#item" + i + " div.item").click(function () {
                    var tgt = $(listItem).data('target');
                    //if (window.opener)
                        //location.href = tgt;
                    //else {
                        //if (typeof popUp == 'function')
                            //popUp(tgt);
                        //else
                    location.href = tgt;
                    //}
                });
                // Bind delete item event
                $("#del_" + i).click(function (e) {
                    // Handle event propogation for the delete icon
                    if (!e)
                        e = window.event;
                    if (e.cancelBubble)
                        e.cancelBubble = true;
                    else
                        e.stopPropagation();
                    // Set prompt state to active to "pause" handle/panel toggling
                    isPrompt = true;
                    // Confirm user action
                    if (confirm('Are you sure you want to delete this toolbox link?')) {
                        // Delete the link
                        DeleteItem(uid, i);
                    }
                });
                // ensure that any existing items that are
                // already in the list do not appear as links    
                $("a.toolboxItem[rel]").each(function (idx, linkItem) {
                    var lnk = linkItem;
                    if ($(lnk).attr("rel").replace(/[\.,-\/#!$%\^&\*;:?{}=\-_`~()]/g, "") == itemData.title.replace(/[\.,-\/#!$%\^&\*;:?{}=\-_`~()]/g, "")) {
                        $(lnk).css("display", "none");
                        $(lnk).data("disabled", "true");
                    }
                    else {
                        if ($(lnk).data("disabled") != "true")
                            $(lnk).css("display", "inline-block");
                    }
                });


            });
            // Set hover events for all list items
            $(contentID + " ul li").hover(function () { $(this).addClass("hover"); }, function () { $(this).removeClass("hover"); });
        }
        // If an item has been added or removed, we need to resolve the 
        // wrapper height accordingly
        ResolveWrapperHeight(initialHeight, $(contentID).outerHeight());
        // If caller requests, toggle the panel
        if (toggleOnComplete) {
            TogglePanel();
        }

        $(handleID).removeClass("loading");
    });
}

function DeleteItem(uid, tbid) {
    var jqxhr = $.getJSON(urlRoot + "handler.aspx?tm=" + (new Date().getTime()) + "&a=Delete&tbid=" + tbid + "&uid=" + uid, function (result) { GetItems(uid); isPrompt = false; });
}

function AddItem(uid, t, url) {    
    var jqxhr = $.getJSON(urlRoot + "handler.aspx?tm=" + (new Date().getTime()) + "&a=Insert&t=" + t + "&url=" + url + "&uid=" + uid, function (result) { GetItems(uid); });
}

function getQuerystring(key, default_) {
    
    if (default_ == null) default_ = "";
    
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    
    var qs = regex.exec(window.location.href);
    
    if (qs == null)
        return default_;
    else
        return qs[1];
}
