// the timeout variable that will be used to close menu bar
var jiveMenuTimeout;
var jiveMenuIndex = -1;
var jiveMenuID;

function jiveKeypressMenuHandler (event) {
    if (Element.visible(jiveMenuID)) {
        var key = event.which || event.keyCode;
        var links;
        switch (key) {
            case Event.KEY_DOWN:
                links = $(jiveMenuID).getElementsByTagName('li');
                if (jiveMenuIndex > -1 && jiveMenuIndex < (links.length - 1)) {
                    links[jiveMenuIndex].className = 'jive-userbar-menu-nohover';
                }

                if (jiveMenuIndex < (links.length - 1)) {
                    jiveMenuIndex++;
                    links[jiveMenuIndex].className = 'jive-userbar-menu-hover';
                }

                break;
            case Event.KEY_UP:
                links = $(jiveMenuID).getElementsByTagName('li');
                if (jiveMenuIndex > 0) {
                    links[jiveMenuIndex].className = 'jive-userbar-menu-nohover';
                }

                if (jiveMenuIndex > 0) {
                    jiveMenuIndex--;
                    links[jiveMenuIndex].className = 'jive-userbar-menu-hover';
                }

                break;
            case Event.KEY_RETURN:
                var listElements = $(jiveMenuID).getElementsByTagName('li');
                var listElement = listElements[jiveMenuIndex];
                var link = listElement.getElementsByTagName("a");
                if (link.length > 0) {
                    document.location.href = link[0].href;
                }
                break;
        }
        Event.stop(event);
    }
}

/*
jivetoggleMenu function
This is for showing and hiding the choose user menu 'dropdowns'.
This toggles the panel (slides up and down) from the button.
*/
function jivetoggleMenu(jiveMenu) {
    clearTimeout(jiveMenuTimeout);

    // close the choose container panel, if open
    if ($('jiveContentCreatePanel')) {
        if ($('jiveContentCreatePanel').visible()) {
            $('jiveContentCreatePanel').hide();
            var children = $('jiveContentCreateContainer').childElements();
            children.each(function(child) {
                $(child).remove();
            });
        }
    }

    // close the task create panel, if open
    if ($('jiveTaskCreatePanel')) {
        if ($('jiveTaskCreatePanel').visible()) {
            $('jiveTaskCreatePanel').hide();
            var children = $('jiveTaskCreateContainer').childElements();
            children.each(function(child) {
                $(child).remove();
            });
        }
    }

    var open = $(jiveMenu).hasClassName('jive-userbar-menu-hidden') != true;
    if (!open) {
        jiveCloseAllMenus();
        //$(jiveMenu).style.visibility = 'visible';
        $(jiveMenu).removeClassName('jive-userbar-menu-hidden');
        $(jiveMenu + "Link").addClassName('jive-userbar-droplink-on');
        jiveMenuID = jiveMenu;
        Event.observe(document, 'keypress', jiveKeypressMenuHandler, true);
    }
}

/*
jiveSwapMenu function
This is for showing and hiding the choose user menu 'dropdowns'.
This toggles the panel (slides up and down) from the button.
*/
function jiveSwapMenu(jiveMenu) {
    clearTimeout(jiveMenuTimeout);

    var openMenu = null;
    var menus = $$('.jive-userbar-menu');
    for (var i = 0; i < menus.length; i++) {
        if (menus[i].hasClassName('jive-userbar-menu-hidden') != true) {
            openMenu = menus[i];
            break;
        }
    }
    if (openMenu != null) {
        if (openMenu.id != jiveMenu) {
            jiveCloseAllMenus();
            $(jiveMenu).removeClassName('jive-userbar-menu-hidden');
            $(jiveMenu + "Link").addClassName('jive-userbar-droplink-on');
        }
    }
}

// cancels any timeout set to close a jive menu bar
function jiveInsideMenu() {
    clearTimeout(jiveMenuTimeout);
}

// sets a timeout that will close the jive menu bar
function jiveOutsideMenu(evt) {
    try {
        var elem = evt.relatedTarget || evt.toElement;
        if (typeof(elem) != 'undefined') {
            while (elem.parentNode && (typeof(elem.tagName) == 'undefined' || elem.tagName.toUpperCase() != 'DIV')) {
                elem = elem.parentNode;
            }
        }

        if (typeof(elem) == 'undefined' || !elem.tagName || (!Element.hasClassName(elem, 'jive-userbar-menu'))) {
            jiveMenuTimeout = setTimeout('jiveCloseAllMenus()', 1500);
        }
    }
    catch (e) {
        jiveMenuTimeout = setTimeout('jiveCloseAllMenus()', 1500);
    }

}

// dynamically loads the jive menu positions
function jiveLoadMenus() {
    var menus = $$('.jive-userbar-menu');
    for (var i = 0; i < menus.length; i++) {
        var link = document.getElementById(menus[i].id + "Link");
        //menus[i].style.left = jiveGetX(link) + "px";
        //menus[i].style.top = (jiveGetY(link) + 34) + "px";
    }
}

// loops through all open menu bars and closes them
function jiveCloseAllMenus() {
    var menus = $$('.jive-userbar-menu');
    for (var i = 0; i < menus.length; i++) {
        if (menus[i].hasClassName('jive-userbar-menu-hidden') != true) {
            $(menus[i]).addClassName('jive-userbar-menu-hidden');
            $(menus[i].id + "Link").removeClassName('jive-userbar-droplink-on');
            var links = menus[i].getElementsByTagName('li');
            for (var k = 0; k < links.length; k++) {
                links[k].className = 'jive-userbar-menu-nohover';
            }
        }
    }
    Event.stopObserving(document, 'keypress', jiveKeypressMenuHandler, true);
    jiveMenuIndex = -1;
}

// get pixel position of an object
function jiveGetY(o) {
    var y = 0
    if (o.offsetParent) while (o.offsetParent) {
        y += o.offsetTop;
        o = o.offsetParent;
    }
    return y
}
function jiveGetX(o) {
    var x = 0
    if (o.offsetParent) while (o.offsetParent) {
        x += o.offsetLeft;
        o = o.offsetParent;
    }
    return x
}

function jiveEscapeKey(evt) {
    var keyCode = document.layers ? evt.which : document.all ? event.keyCode : document.getElementById ? evt.keyCode
            : 0;
    if (keyCode == 27) { // esc - close open menu
        jiveCloseAllMenus();
    }
}

function jiveBodyClick(evt) {
    evt = evt || window.event; // IE required window.event
    var elem = Event.findElement(evt, 'div');
    if (elem) {
        // check parent or parent's parent for class dhtmlTreeStyle for tree dropdown in menu
        var parentElem = Event.element(evt).parentNode;
        if (!elem.tagName || (elem.id != 'jive-userbar-droplink' && !Element.hasClassName(elem, 'jive-userbar-menu')
                && !Element.hasClassName(parentElem, "dhtmlTreeStyle")
                && !Element.hasClassName(parentElem.parentNode, "dhtmlTreeStyle")))
        {
            jiveCloseAllMenus();
        }
    }
}

function jiveChooseContainerForm(url) {
    jiveCloseAllMenus();
    Element.addClassName(document.body, 'jive-progresscursor');
    new Ajax.Updater('jiveContentCreateContainer', url, {
        evalScripts: true,
        onComplete: function() {
            new Effect.SlideDown('jiveContentCreatePanel', {
                duration:.7
            });
            Element.removeClassName(document.body, 'jive-progresscursor');
        }
    });
}

function jiveSubmitChooseContainerForm(containerType, containerID) {
    $('jive-choose-container-type').value = containerType;
    $('jive-choose-container-id').value = containerID;
    $('jiveChooseContainerForm').submit();
}

function jiveRemoveChooseContainerForm() {
    new Effect.SlideUp('jiveContentCreatePanel', {
        duration:.7,
        afterFinish: function() {
            var children = $('jiveContentCreateContainer').childElements();
            children.each(function(child) {
                child.remove();
            });
        }
    });
}

function jiveAdvancedChooseContainerForm(url) {
    var pars = $('jiveChooseContainerForm').serialize(true);
    url += '?contentType=';
    url += pars.contentType;
    if (pars.upload) {
        url += "&upload=";
        url += pars.upload;
    }
    parent.location.href = url;
}

function jiveShowQuickTaskForm(url) {
    jiveCloseAllMenus();
    Element.addClassName(document.body, 'jive-progresscursor');
    var subject = jiveGetSelectedText();
    var pars;
    if (subject != '') {
        pars = {"subject": subject};
    }
    new Ajax.Updater('jiveTaskCreateContainer', url, {
        parameters: pars,
        evalScripts: true,
        onComplete: function() {
            new Effect.SlideDown('jiveTaskCreatePanel', {
                duration:.7,
                afterFinish: function() {
                    document.jivequicktaskform.subject.focus();                        
                }
            });
            Element.removeClassName(document.body, 'jive-progresscursor');            
        }
    });
}

function jiveSubmitQuickTaskForm(url) {
    new Ajax.Updater('jiveTaskCreateContainer', url, {
        parameters: $('jivequicktaskform').serialize(true),
        evalScripts: true
    });
}

function jiveRemoveQuickTaskForm() {
    new Effect.SlideUp('jiveTaskCreatePanel', {
        duration:.7,
        afterFinish: function() {
            var children = $('jiveTaskCreateContainer').childElements();
            children.each(function(child) {
                child.remove();
            });
        }
    });
}

function jiveSendToAdvancedTaskForm(url) {
    var pars = $(document.jivequicktaskform).serialize(true);
    url += '?subject=';
    url += pars.subject;
    if (pars.project) {
        url += '&project=';
        url += pars.project;
    }
    if (pars.owner) {
        url += '&owner=';
        url += pars.owner;
    }
    if (pars.dueDate) {
        url += '&dueDate=';
        url += pars.dueDate;
    }
    parent.location.href = url;
}

function jiveGetSelectedText() {
    var selectedText = '';
    if (window.getSelection) { // recent Mozilla versions
        selectedText = window.getSelection();
    } else if (document.all) { // MSIE 4+
        selectedText = document.selection.createRange().text;
    } else if (document.getSelection) { //older Mozilla versions
        selectedText = document.getSelection();
    }
    return selectedText;
}

/*
jivetoggleLogin function
This is for showing and hiding the choose user login form.
*/

function jivetoggleLogin() {

    Element.toggle('jiveLoginWelcome');
    Element.toggle('jiveLoginForm');

    if ($('jiveLoginForm').style.display != 'none') {
        $('login-username').focus();
    }
    else
    {
        $('login-username').blur();
    }
}

function selectDocument() {
    $('jive-doc-collab').checked = true;
    $('jive-doc-type-write').addClassName('jive-choose-doc-type-selected');
    $('jive-doc-type-upload').removeClassName('jive-choose-doc-type-selected');
}

function selectUpload() {
    $('jive-doc-upload').checked = true;
    $('jive-doc-type-upload').addClassName('jive-choose-doc-type-selected');
    $('jive-doc-type-write').removeClassName('jive-choose-doc-type-selected');
}

var JiveSpotlightSearch = Class.create();
JiveSpotlightSearch.prototype = {

/*
* Initialize the JiveSpotlightSearch object.
* @spotlightSearchInput The id of the spotlight search input element - jive-query
* @spotlightSearchContainer The id of the spotlight search results container - jive-spotlight-search-container
* @spotlightSearchURL The url to perform the search - action 'spotlight-search'
*/
    initialize: function(spotlightSearchInput, spotlightSearchContainer, spotlightSearchURL)
    {
        this.spotlightSearchInput = spotlightSearchInput;
        this.spotlightSearchContainer = spotlightSearchContainer;
        this.spotlightSearchURL = spotlightSearchURL;

        this.spotlightSearchIndex = 0;
        $(this.spotlightSearchInput).observe("keyup", this.observeSpotlightSearchQuery.bind(this));
        $(this.spotlightSearchInput).observe("blur", this.onBlur.bind(this));
    },

    observeSpotlightSearchQuery: function(event) {
        switch(event.keyCode) {
            case Event.KEY_UP:
                this.selectIndex(this.spotlightSearchIndex-1);
                Event.stop(event);
                return;
            case Event.KEY_DOWN:
                this.selectIndex(this.spotlightSearchIndex+1);
                Event.stop(event);
                return;
            case Event.KEY_RETURN:
                this.clearSpotlightSearchEvent();
                if (this.spotlightSearchIndex > 0) {
                    this.loadSelectedIndex();
                } else {
                    $(this.spotlightSearchInput).form.submit();
                }
                Event.stop(event);
                return;
            case Event.KEY_ESC:
                this.clearSpotlightSearch();
                Event.stop(event);    
                return;
            case Event.KEY_LEFT:
            case Event.KEY_RIGHT:
            case Event.KEY_TAB:
            case Event.KEY_HOME:
            case Event.KEY_END:
            case Event.KEY_PAGEUP:
            case Event.KEY_PAGEDOWN:
                Event.stop(event);
                return;
        }

        this.clearSpotlightSearchEvent();
        this.spotlightSearchEvent = setTimeout(this.executeSpotlightSearch.bind(this), 400);
    },

    onBlur: function() {
        // needed to make click events working
        setTimeout(this.clearSpotlightSearch.bind(this), 250);
    },

    clearSpotlightSearch: function() {
        $(this.spotlightSearchContainer).update('');
    },

    executeSpotlightSearch: function() {
        var query = $F(this.spotlightSearchInput);
        if (query.length >= 3) {
            query = query + '*';
            new Ajax.Updater(this.spotlightSearchContainer, this.spotlightSearchURL, {
                method: 'get',
                asynchronous:true,
                evalScripts:true,
                parameters: {
                    'query': query
                }
            });
        } else {
            this.clearSpotlightSearch();
        }
        this.spotlightSearchIndex = 0;
    },

    viewAllResults: function() {
        var query = $F(this.spotlightSearchInput);
        if (query.length > 0) {
            query = query + '*';
            $(this.spotlightSearchInput).value = query;
            $(this.spotlightSearchInput).form.submit();
        }
    },

    selectIndex: function(index) {
        if (index > 0) {
            var elem = $('spotlight-index-' + index);
            if (elem) {
                $('jive-spotlight-search').select('li.hover').each(function(el) {
                    el.removeClassName('hover');
                });
                elem.addClassName('hover');
                elem.scrollIntoView(false);
                this.spotlightSearchIndex = index;
            }
        } else {
            $('jive-spotlight-search').select('li.hover').each(function(el) {
                el.removeClassName('hover');
            });
            $(this.spotlightSearchInput).scrollIntoView(false);
            this.spotlightSearchIndex = 0;
        }
    },

    loadSelectedIndex: function() {
        var elem = $('spotlight-index-' + this.spotlightSearchIndex);
        if (elem) {
            elem.select('a').each(function(anchor) {
                location.href = anchor.href;
            });
        }
    },

    clearSpotlightSearchEvent: function() {
        if (this.spotlightSearchEvent) {
            clearTimeout(this.spotlightSearchEvent);
        }
    }
}

