/* Global functions for Cognoti */

var processingFavorites = false;

var toggleFavorite = function(link, type, id, ontext, offtext)
{
    if(!processingFavorites)
    {
        processingFavorites = true;
        
        link = $(link)
        
        var op = 'add';
        var img = link.down('img'); 
        
        if(link.hasClassName('removefav'))
        {
            op = 'del';        
        }
        
        //do a check here for removing... only addding for now
        
        var url = '/cognoti/helper/favorites.nn?id='+id+'&type='+type;
    
        
        var effect = new Object();
        if(img)
        {
            pulseEffect = function()
            {
                if(effect != null)
                {
                    effect = new Effect.Pulsate(img, {pulses: 2, duration: 1.0, afterFinish: pulseEffect});
                }
                     
            };
        
            pulseEffect();
        }
        
        new Ajax.Request(url+'&op='+op, 
            {
                method: 'get',
                onSuccess: function(transport)
                {
                    var root = transport.responseXML.documentElement;
                    var status = root.getAttribute("status");
                    
                    effect = null;
                    
                    if(status == "success")
                    {
                        if(op == 'add')
                        {
                            link.removeClassName("addfav");
                            link.addClassName("removefav");
                            
                            var text = offtext ? offtext : "Remove From Favorites";
                            if(img)
                            {
                                img.src = '/cognoti/img/heart.gif';
                                img.alt = text;
                            }
                            
                            link.title = text;
                            link.down('span').update(text);
                        }
                        else if(op == 'del')
                        {
                            link.addClassName("addfav");
                            link.removeClassName("removefav");
                            
                            var text = ontext ? ontext : "Add to Favorites";
                            
                            if(img)
                            {
                                img.src='/cognoti/img/heart_gray.gif';
                                img.alt = text;
                            }
                            link.title = text;
                            link.down('span').update(text);
                        }
                    }
                    else
                    {
                        var message = root.getElementsByTagName("message")[0].childNodes[0].nodeValue;
                        
                        
                        popupBubble(img ? img : link, message);
                        //do nothing for now... should probably alert user though    
                    }
                    
                    processingFavorites = false;    
                },
                onComplete: function()
                {
                    effect = null;
                    processingFavorites = false;    
                }
            });
    }
    
    return false;
}

var popupEditorContent = null;
var popupEditor = function(editorText)
{
    var options = Object.extend({
        width: 650,
        height: null,
        rows: 8,
        submitText: 'Submit',
        cancelText: 'Cancel',
        title: 'Cognoti Popup Editor',
        toolbarSize: 'small',
        onSubmit: Prototype.emptyFunction,
        onCancel: Prototype.emptyFunction,
        multiline: true,
        description: '',
        additionalControls: null,
        additionalControlsOnTop: false
            
    }, arguments[1] || { });
    
    var firstLoad = false;
    
    if(true || !popupEditorContent)
    {
        popupEditorContent = new Element('div', { id: 'popup_wysiwyg', 'class': 'popupeditor'});
    
        var textarea;
        
        if(options.multiline)
        {
            var textarea = new Element('textarea', { 
                'style': 'width: 100%', 
                id: 'popup_wysiwyg_editor'
            });
        }
        else
        {
            var textarea = new Element('input', { 
                'style': 'width: 98%', 
                type: 'input',
                id: 'popup_wysiwyg_editor'
            });
        }
        
        var label = options.description ? new Element('label', { 'for': 'popup_wysiwyg_editor' }).update(options.description) : null;
        
        var p = new Element('p', { 'class': 'formsubmit' });
        
        var submit = new Element('input', { 'class': 'button', type: 'button', value: options.submitText, id: 'popup_wysiwyg_editor_submit' });
        var cancel = new Element('input', { 'class': 'button cancel', type: 'button', value: options.cancelText, id: 'popup_wysiwyg_editor_cancel' });
        
        
        var additionalControlsInsert = null;
        if(options.additionalControls)
        {
            additionalControlsInsert = options.additionalControlsOnTop ? {top: options.additionalControls} : options.additionalControls;
        }
        
        
        p.insert(submit).insert(cancel);
        popupEditorContent
            .insert(label)
            .insert(textarea)
            .insert(additionalControlsInsert)
            .insert(p);
    }
    
    var mainClose = function()
    {
        Modalbox.hide();
        $('popup_wysiwyg_editor_submit').stopObserving('click');
        $('popup_wysiwyg_editor_cancel').stopObserving('click');
    }
    
    var setup = function()
    {
        var editor = $('popup_wysiwyg_editor');
        editor.value = editorText;
        editor.setAttribute('rows', options.rows);
        
        $('popup_wysiwyg_editor_cancel').observe('click', function()
            {
                options.onCancel();
                mainClose();
            });
        $('popup_wysiwyg_editor_submit').observe('click', function()
            {
                var results = new Object(); 
                
                $('popup_wysiwyg').select('input', 'select', 'textarea').each(function(elem)
                    {
                       results[elem.name] = elem.getValue(); 
                    });
                
                if(options.multiline)
                {
                    results.text = getWysiwygContent('popup_wysiwyg_editor');
                }
                else
                {
                    results.text = $('popup_wysiwyg_editor').getValue();    
                }
                
                options.onSubmit(results);
                mainClose();
            });
        
        $('popup_wysiwyg_editor_submit').setAttribute('value', options.submitText);
        $('popup_wysiwyg_editor_cancel').setAttribute('value', options.cancelText);
        
        if(options.multiline)
        {
            registerTextArea('popup_wysiwyg_editor', options.toolbarSize);
        }
        
        Modalbox.resizeToContent();
    }
    
    var cleanup = function()
    {
        if(options.multiline)
        {
            closeTextArea('popup_wysiwyg_editor');
        }            
    }
    
    var ModalBoxOptions = { 
        width: options.width,
        /* height: options.height, */
        title: options.title,
        overlayClose: false,
        afterLoad: setup
    }
    
    Modalbox.show(popupEditorContent, ModalBoxOptions);
}

var Preview = { types: {

    'resource': '/resources/view.nn?view=preview&resourceid={id}',    
    'userpost': '/cognoti/user/userpost.nn?view=read&userpostid={id}',
    'standard': '/standards/standards.nn?view=preview&id={id}',
    'standardintro': '/standards/standards.nn?view=intro&id={id}'
} 

};


var popupPreview = function(type, id, title, props, gobackurl)
{
    var url = null;

    var url = Preview.types[type];
    
    if(url != null)
    {
        url = url.replace(/{id}/, id);
        
        var hash = new Hash(props ? props : { width: 650 });
        hash.set('afterLoad', function() { Modalbox.resizeToContent(); });
        
        if(title)
        {
            hash.set('title', title);
        }
        
        if(gobackurl)
        {
            url = url+'&gobackurl='+escape(window.location.pathname+window.location.search);    
        }
        
        
        Modalbox.show(url, hash.toObject());
        
        return false;
    }
    
    return true;
}

var confirmBubble = function(target, text, options, result, popupOptions)
{
    result = result || Prototype.emptyFunction;
    
    var block = new Element('div');
    var optionblock = new Element('div');
    block.insert(new Element('div').update(text));
    block.insert(optionblock);
    
    
    var bubble;
    var resultFunc = function(e)
    {
        bubble.close(e);
        bubble.select('input').each(function (input) { input.stopObserving(); });
        result(this.value);
    }
    
    options.each(function(opt)
    {
       var input = new Element('input', { type: 'button', value: opt } );
       input.observe('click', resultFunc);
       optionblock.insert(input); 
    });
    
    bubble = popupBubble(target, block, popupOptions);
    
    return bubble;
}

var popupBubble = function(target, text, popupOptions)
{
    popupOptions = Object.extend({
        right: false,
        fadeInSpeed: 0.5,
        fadeOutSpeed: 1.0
            
    }, popupOptions || {});
    
    var bubble = new Element("div", { style: 'display: none;' }).addClassName('popupFlag');
    var textdiv = new Element('div').addClassName('text').update(text);
    var a = new Element('a', { href: '#' }).addClassName('close').update('&times;');
    var tip = new Element('div', { style: 'left: 9px;'}).addClassName('tip');
    
    
    bubble.insert({bottom: a});    
    bubble.insert({bottom: textdiv});
    bubble.insert({bottom: tip});
    
    bubble.target = $(target);
    bubble.tip = tip;
    bubble.close = function(e)
    {
        a.stopObserving();
        a.observe('click', Event.stop);
        new Effect.Fade(bubble, {duration: popupOptions.fadeOutSpeed, afterFinish: function() { bubble.remove(); }}); 
        
        Event.stopObserving(window, 'resize', bubble.resize);
        
        if(e)
        {
            Event.stop(e);
        }
    }
    
    bubble.resize = function()
    {
        var offset = bubble.target.positionedOffset();
        var top = offset.top - bubble.getHeight();
        var left = offset.left - 10;
        
        var width = bubble.getWidth();
        if( popupOptions.right ||  left + width > document.viewport.getWidth()+document.viewport.getScrollOffsets().left)
        {
            left = offset.left + bubble.target.getWidth() - width;
            bubble.tip.setStyle({ left: (width-29)+'px'});
        }
        
        bubble.setStyle({top: top+'px', left: left+'px'});        
    }
    
    a.observe('click', bubble.close);
    Event.observe(window, 'resize', bubble.resize);
    
    target.getOffsetParent().insert(bubble);
    
    bubble.resize();
    
    
    new Effect.Appear(bubble, {duration: popupOptions.fadeInSpeed});
    
    return bubble; 
}

var popupBubbleSide = function(target, text, popupOptions)
{
    popupOptions = Object.extend({
        right: false,
        fadeInSpeed: 0.5,
        fadeOutSpeed: 1.0,
        beforeShow: Prototype.emptyFunction,
        afterShow: Prototype.emptyFunction,
        beforeClose: Prototype.emptyFunction,
        afterClose: Prototype.emptyFunction,
        width: null,
        align: 'middle'
            
    }, popupOptions || {});
    
    var bubble = new Element("div", { style: 'display: none;' }).addClassName('popupFlag');
    var textdiv = new Element('div').addClassName('text').update(text);
    var a = new Element('a', { href: '#' }).addClassName('close').update('&times;');
    var tip = new Element('div').addClassName('lefttip');
    
    if(popupOptions.width)
    {
        bubble.setStyle({'width': popupOptions.width+'px'});    
    }
    
    bubble.insert({bottom: a});    
    bubble.insert({bottom: textdiv});
    bubble.insert({bottom: tip});
    
    bubble.target = $(target);
    bubble.tip = tip;
    bubble.close = function(e)
    {
        popupOptions.beforeClose.bind(bubble)();
        a.stopObserving();
        a.observe('click', Event.stop);
        new Effect.Fade(bubble, {duration: popupOptions.fadeOutSpeed, afterFinish: function() { bubble.remove(); popupOptions.afterClose.bind(bubble)(); }}); 
        
        Event.stopObserving(window, 'resize', bubble.resize);
        
        if(e)
        {
            Event.stop(e);
        }
    }
    
    bubble.resize = function()
    {
        var offset = bubble.target.positionedOffset();
        var size = bubble.target.getDimensions();
        var bubbleHeight = bubble.getHeight();
        var bubbleHeightHalf = (bubbleHeight / 2);
        var top = offset[1] + (size.height / 2) - bubbleHeightHalf;
        var left = offset[0] + size.width + 10;
        
        var width = bubble.getWidth();
        
        var bubbleTipTop = (bubbleHeightHalf - 9);
        
        if(popupOptions.right)
        {
            tip.className = 'righttip';
            left = offset[0] - width - 10;
            bubble.tip.setStyle({ left: (width - 2)+'px'});
        }
        
        var vpScroll = document.viewport.getScrollOffsets();
        var vpHeight = document.viewport.getHeight();
        var viewportBottom = vpHeight + vpScroll[1];
        
        if(popupOptions.align == 'bottom' || top + bubbleHeight > viewportBottom)
        {
            top = offset[1] + (size.height / 2) - bubbleHeight + 15; 
            bubbleTipTop = (bubbleHeight - 25)
        }
        /* else if(popupOptions.align == 'top' || top < vpScroll[1])
        {
            top = offset[1] + (size.height / 2) - 15; 
            bubbleTipTop = 7;
        } */
        
        bubble.tip.setStyle({ top: bubbleTipTop+'px'});
        bubble.setStyle({top: top+'px', left: left+'px'});        
    }
    
    a.observe('click', bubble.close);
    Event.observe(window, 'resize', bubble.resize);
    
    target.getOffsetParent().insert(bubble);
    
    bubble.resize();
    
    new Effect.Appear(bubble, {duration: popupOptions.fadeInSpeed, afterSetup: popupOptions.beforeShow.bind(bubble), afterFinish: popupOptions.afterShow.bind(bubble)});
    
    return bubble; 
}

/** FLAGGING */

var flagCount = 1;
var startFlag = function()
{
    $('testbox').setStyle({cursor: 'pointer'});
    $('testbox').observe("click", doFlag);
    return false;
}
                                                        
var doFlag = function(e) 
{ 
    if(e.button == 0)
    {
        var offset = $(e.target).viewportOffset();
        /* alert("Target: "+e.target.id+"\n"+
            "Page: ( " + e.pageX + ", " + e.pageY + " )\n"+
            "Layer: ( " + e.layerX + ", " + e.layerY + " )\n"+
            "Client: ( " + e.clientX + ", " + e.clientY + " )\n"+
            "Screen: ( " + e.screenX + ", " + e.screenY + " )\n"+
            "Relative: ( " + (e.pageX - offset.left) + ", " + (e.pageY - offset.top) + " )\n"); */
        
        var note = prompt("Enter details", "");
        if(note != null)
        {
            var div = new Element('div',
            {                
                title: note/* +" [#"+e.target.id+" @ "+ (e.pageX - offset.left) + ", " + (e.pageY - offset.top)+"]" */
            
            }).addClassName('notetag').update(flagCount++);
            
            div.setStyle({
                width: '16px',
                height: '16px',
                backgroundColor: 'yellow',
                position: 'absolute',
                color: '#000',
                fontSize: '12px',
                top:  (e.pageY - offset.top)+"px",
                left: (e.pageX - offset.left)+"px"
            });
            
            $(e.target).insert({bottom: div});
            div.observe("click", function () { popupBubble(div, div.title); });
        }
    }
    endFlag();
}

var endFlag = function()
{
    $('testbox').setStyle({cursor: 'default'});
    $('testbox').stopObserving("click", doFlag);
}




var treeNav = function(ul, forceNow, savedStateId)
{
    ul = $(ul);
    
    var treeFunction = function()
    {
        var nohideli = null;
        
        var children = ul.childElements();
        
        if(children.length == 1) { nohideli = children[0]; }
        
        var handleClick = function(tree, handle)
           {                      
              if(handle.hasClassName('handleup'))
              {
                  tree.show();
                  handle.removeClassName('handleup');
                  handle.addClassName('handledown');
                  
              }
              else
              {
                  handle.addClassName('handleup');
                  handle.removeClassName('handledown');
                  tree.hide();
              }
              
              if(savedStateId) 
              { 
                Cognoti.saveTreeState(ul, savedStateId); 
              }
           };
        
        ul.select('li').each(function(li)
            {
               
               var handle = new Element('div').addClassName('handle'); 
               li.insert({top: handle}); 
                
               var tree =  li.down('ul.treenav');
               if(tree)
               {
                   handle.observe('click', function() { handleClick(tree, handle); });
                   var handle2 = li.down('.h');
                   if(handle2)
                   {
                       handle2.observe('click', function() { handleClick(tree, handle); });
                   }
                   
                   if(!tree.hasClassName('keepopen') && tree.select('input[checked]', 'li.active').length == 0 && nohideli != li)
                   {
                       tree.hide();
                       handle.addClassName('handleup');
                   }
                   else
                   {
                       handle.addClassName('handledown');                                      
                   }
               }
               
            });
        
            if(savedStateId) 
            { 
                Cognoti.loadTreeState(ul, savedStateId); 
            }
        }
    
    if(forceNow)
    {
        treeFunction();    
    }
    else
    {
        Event.observe(document, 'dom:loaded', treeFunction);
    }
}


/* ===== FORM MONITORING ===== */
//form monitoring (for knowing when things change...)

function setupMonitorActivity(form, immediate, supportedSubmit)
{
    form = $(form);
    form.hasChanged = false;    
    form.supportedSubmit = supportedSubmit;
    
    var observeFunction = function()
    {
        form.select('input', 'textarea', 'select').each(function (i)
            {
                i.observe('change', function() { monitoredFormChanged(form) }); 
            });
    }
    
    form.select('input[type="submit"]').each(function(submit)
        {
            if(supportedSubmit && supportedSubmit.indexOf(submit.name) > -1)
            {
                submit.observe('click', function() { form.hasChanged = false; });
            }
            
        });
    
    window.onbeforeunload = function()
    {
       if(form.hasChanged)
       {
            return "It appears that you have made changes without saving.  Leaving now will cause you to lose your changes.";                                  
       }
    };
    
    if(immediate)
    {
        observeFunction();    
    }
    else
    {
        Event.observe(document, 'dom:loaded', observeFunction);
    }
}

function monitoredFormChanged(form)
{
    $(form).hasChanged = true;
}


/* ============ FEATURED ROTATE ============ */

var FeaturedRotator = Object.extend({
    registered: {},
    register: function(rotator, options)
    {
        var rcontent = $(rotator+'_content');
        var rlist = $(rotator+'_list');
        if(rcontent && rlist)
        {
            var robject = {
                content: rcontent, 
                list: rlist, 
                options: options
            };
            this.registered[rotator] = robject;
        
            this._setupFeaturedRotator(robject);
        }
    },
    
    doRotate: function(rotator)
    {
        var r = this.registered[rotator];
        
        if(r)
        {
            this._doRotate(r);    
        }
    },

    _setupFeaturedRotator: function(r, options)
    {
        var fr = this;
        
        r.options = Object.extend({
            rotateFreq: 8        
        }, r.options || {});
        
        r.timer = setTimeout(function() { fr._timer(r); }, r.options.rotateFreq*1000);
    },
    
    _timer: function(r)
    {
        var fr = this;
        r.timer = setTimeout(function() { fr._timer(r); }, r.options.rotateFreq*1000);
        this._doRotate(r);
    },

    _doRotate: function(r)
    {
        if(r.rotating) { return; }
        
        r.rotating = true;
        var current = r.list.down('li.active');
        var next = current.next('li');
        
        if(!next) //go back to first
        {
            next = r.list.down('li');    
        }
        
        if(next)
        {
            var link = next.down('h3 a');
            
            var title = link.innerHTML;
            var targeturl = link.href;
            var extra = next.down('div.description').innerHTML;
            var imgsrc = next.down('img').src;
            
            this._doFeaturedSwitch(r, title, extra, imgsrc, targeturl);
            this._doListSwitch(r, current, next);
        }
        
        r.rotating = false;
    },
    
    _doListSwitch: function(r, oldLi, newLi)
    {
        oldLi.removeClassName('active');
        newLi.addClassName('active');
    },
    
    _doFeaturedSwitch: function(r, title, extra, imgsrc, targeturl)
    {
        var fr = this;
        var a = r.content.down('.description h1 a');
        
        a.href = targeturl;
        a.innerHTML = title;
        
        r.content.down('p').innerHTML = extra;
        
        var aimg = r.content.down('a img');
        
        aimg.src = imgsrc;
        aimg.up('a').href = targeturl;
        
        
    },
    
    _swapImg: function(img, newsrc, alt)
    {
        var startWidth = img.getWidth();
        var startHeight = img.getHeight();
        
        
        new Effect.Fade(img, {  
            to: 0.01,
            afterFinish: function() 
            { 
                img.src = newsrc;
                img.alt = alt;
                new Effect.Appear(img);
            }
        });
    }
});

var setupAutocomplete = function(textbox, acbox, hiddeninput, type, callback)
{
    textbox = $(textbox);
    hiddeninput = $(hiddeninput);
    
    new Ajax.Autocompleter(textbox, acbox, '/cognoti/helper/autocomplete.nn',
    {
        paramName: 's',
        minChars: 2,
        parameters: 'type='+type,
        method: 'get',
        afterUpdateElement: function(input, li)
        {
            var value = input.getValue();
            var id = li.id;
            textbox.currvalue = value; 
            textbox.currid = id;
            hiddeninput.value = id;
            
            if(callback)
            {
                callback(value, id);    
            }
        }
    });  
    
    $(textbox).observe('change', function(){
        if(this.currvalue != this.value)
        {
            hiddeninput.value = 0;    
        }
        else if(this.currid)
        {
            hiddeninput.value = this.currid;                    
        }
    });        
}


var TopicWindow = Object.extend({
    collapseTree: function(tree, expandtoplevel, name)
    {
        var thisObj = this;
        tree = $(tree);
        
        if(!name) 
        {
            name = 'subject';
        }
        
        if(tree)
        {
            if(!expandtoplevel)
            {
                var ul = tree.down('ul');
                
                this._recurseTreeCollapse(ul, name);
            }
            else
            {
                tree.select('ul ul').each(function(ul) { thisObj._recurseTreeCollapse(ul, name); });    
            }
        }
        
        
        var cbChangeFunc = function()
            {
               var thisCB = $(this);
               var hasChildren = thisCB.next('ul');
               
               if(hasChildren)
               {
                   var childrenCB = hasChildren.select('input[type="checkbox"]');
                   if(thisCB.checked)
                   {
                        childrenCB.each(function(cb)
                            {
                                if(Object.isUndefined(cb.oldChecked))
                                {
                                    cb.oldChecked = cb.checked;
                                }
                                cb.checked = true;
                                cb.disabled = true;  
                                cb.disabledNum = (cb.disabledNum || 0) + 1;
                            });
                   }
                   else
                   {
                       childrenCB.each(function(cb)
                            {
                                cb.disabledNum = cb.disabledNum - 1;
                                if(cb.disabledNum == 0)
                                {
                                    cb.checked = cb.oldChecked;
                                    delete cb.oldChecked;
                                    cb.disabled = false;
                                }
                            });
                   }
               }
                
            };
        
        tree.select('input[type="checkbox"]').each(function(cb)
            {
                cb.observe('change', cbChangeFunc);
                cb.disabled = false;
            });
        
        tree.select('input[type="checkbox"]').each(function(cb)
            {
                cbChangeFunc.bind(cb)();                
            });
        
        
        
    
        
    },
    
    _recurseTreeCollapse: function(ul,name)
    {
        var thisObj = this;
        
        var retVal = false;
        
        ul.childElements().each(function(li)
            {
                var expand = li.down('div.expand');
                
                retVal = retVal || li.down('input[name="'+name+'"]').checked;
                
                if(expand.hasClassName('open') || expand.hasClassName('closed'))
                {
                    var child = li.down('ul');
                    var ret = thisObj._recurseTreeCollapse(child, name);
                    retVal = retVal || ret;
                    
                    if(!ret)
                    {
                        thisObj._close(expand);
                    }
                    else
                    {
                        thisObj._open(expand);
                    }
                }
            });
        
        return retVal;
        
    },
    
    _open: function(expander)
    {
        expander.next('ul').show();
        expander.removeClassName('closed');
        expander.addClassName('open');
    },
    
    _close: function(expander)
    {
        expander.next('ul').hide();
        expander.addClassName('closed');
        expander.removeClassName('open');    
    },
    
    toggle: function(expander)
    {
        expander = $(expander);
        if(expander)
        {
            if(expander.hasClassName('closed'))
            {
                this._open(expander);
            }
            else if(expander.hasClassName('open'))
            {
                this._close(expander);
            }
        }
    }
        
});

function checkAll(fieldName) {
    var checkboxes = [];
    checkboxes = $$('input[name="'+fieldName+'"]').each(function(e){ if(e.type == 'checkbox') checkboxes.push(e) });
    checkboxes.each(function(e){ e.checked = 1 });
}

var recommendationPopup = function(type, id, title, props)
{
    var url = '/cognoti/helper/recommend.nn';

    
    if(url != null)
    {
        var params = { 'reftype': type, 'refid': id };
        
        var hash = new Hash(props ? props : { width: 650, height: 400, method: 'get', params: params });
        //hash.set('afterLoad', function() { Modalbox.resizeToContent(); });
        
        if(title)
        {
            hash.set('title', title);
        }
        
        Modalbox.show(url, hash.toObject());
        
        return false;
    }
    
    return true;    
}

var deleteRecommendation = function(link, recommendationblock)
{
    
    confirmBubble(link, 'Are you sure you want to delete this recommendation?', ['Yes', 'No'], 
        function(val)
    {
        if(val == 'No') { return; }
        var href = link.href.split("?");
        
        var target = href[0];
        var params = href[1]+"&ajax=true";
        
        new Ajax.Request(target, 
        {
            method: 'post',
            parameters: params,
            onSuccess: function(transport)
            {
                var root = transport.responseXML.documentElement;
                var status = root.getAttribute("status");
                
                var message = root.getElementsByTagName("message")[0].childNodes[0].nodeValue;
                
                if(status == "success")
                {
                    recommendationblock = $(recommendationblock);
                    if(recommendationblock)
                    {
                        new Effect.BlindUp(recommendationblock, 
                            { duration: 0.5, 
                            afterFinish: function() { recommendationblock.remove(); }
                            });
                    }
                }
                else
                {
                    popupBubble(link, message);        
                }
                
            }
        });
    });
    
    return false;        
}

var bookmarkPopup = function(type, id, title, props)
{
    var url = '/cognoti/helper/bookmark.nn';

    
    if(url != null)
    {
        var params = { 'reftype': type, 'refid': id };
        
        var hash = new Hash(props ? props : { width: 650, method: 'get', params: params });
        hash.set('afterLoad', function() { Modalbox.resizeToContent(); });
        
        if(title)
        {
            hash.set('title', title);
        }
        
        Modalbox.show(url, hash.toObject());
        
        return false;
    }
    
    return true;    
}

var ajaxSubmitForm = function(form, options)
{
    var opts = Object.extend({
        closeModal: true,
        showMessage: true
    }, options);
    
    form = $(form);
    
    var params = form.serialize(true);
    var submit = form.down('.submit');
    
    new Ajax.Request(form.action,
    {
        method: 'post',
        parameters: params,
        onSuccess: function(t)
        {
            var root = t.responseXML.documentElement;
            var status = root.getAttribute("status");
            
            var message = root.getElementsByTagName("message")[0].childNodes[0].nodeValue;
                    
            if(status == "success")
            {
                if(opts.closeModal)
                {
                    Modalbox.hide();    
                }
                else if(opts.showMessage)
                {
                    Modalbox.show(getAlertBox(message));
                }
            }
            else
            {
                popupBubble(submit, message);    
            }
        },
        onFailure: function(t)
        { 
            popupBubble(submit, t.statusText);
        }
    });
}


var getAlertBox = function(message)
{
    var div = new Element('div');
    div.insert(new Element('h3').update(message));
    var close = new Element('a', { 'href': '#', 'class': 'button', 'onclick': 'Modalbox.hide(); return false;'}).update('OK');
    div.insert(new Element('p', { 'class': 'formsubmit'}).update(close));

    return div;    
}

var progressWheel = function()
{
    return new Element('img', { 'src': '/cognoti/img/spinner.gif', 'alt': 'Loading...' })    
}

var addCollection = function(textbox, list)
{
    var name = $(textbox).getValue();
    
    list = $(list);
    
    if(list)
    {
        var cb = new Element('input', { 'name': 'newcollection', 'type': 'checkbox', 'value': name, 'checked': 'checked'});
        var label = new Element('label', { 'class': 'label_check', 'for': cb }).update(name);
        
        list.insert(new Element('li').insert(cb).insert(label));
    }
}

var switchTab = function(tabs, targettab, tabsheets, targettabsheet, modalbox)
{
    tabs = $(tabs);
    targettab = $(targettab);
    tabsheets = $(tabsheets);
    targettabsheet = $(targettabsheet);
    
    tabs.select('li').invoke('removeClassName', 'current');
    targettab.addClassName('current');
    
    tabsheets.select('.tabsheet').invoke('hide');
    targettabsheet.show();
    
    if(modalbox)
    {
        Modalbox.resizeToContent();
    }
    
    return false;
}


var setupUserAutocomplete = function(textbox, acbox, hiddeninput, callback)
{
    return setupAutocomplete(textbox, acbox, hiddeninput, 'user', callback);
}

var setupInstitutionAutocomplete = function(textbox, acbox, hiddeninput, callback)
{
    return setupAutocomplete(textbox, acbox, hiddeninput, 'institution', callback);    
}

var xmlElementToJs = function(node)
{
    var o = new Object();
    
    var len = node.childNodes.length;
    
    if(len == 0)
    {
         o = null;  
    }
    else if(len == 1)
    {
         if(node.childNodes[0].childNodes.length == 0)
         {
             o = node.childNodes[0].nodeValue;
         }
         else
         {
             o = xmlElementToJs(node.childNodes[0]);
         }
         
    }
    else
    {
        for(var i = 0; i < len; ++i)
        {
            if(Object.isArray(o)) 
            {                
                o.push(xmlElementToJs(node.childNodes[i]));    
            }
            else if(typeof o[node.childNodes[i].nodeName] == 'undefined')
            {
                o[node.childNodes[i].nodeName] = xmlElementToJs(node.childNodes[i]);
            }
            else
            {
                o = [o[node.childNodes[i].nodeName], xmlElementToJs(node.childNodes[i])];
            }
                
        }
        
    }
    return o;
}

var simpleConfirmBubble = function(link, text)
{
    confirmBubble(link, text, ['Yes', 'No'], function(result) {
       if(result == 'Yes')
       {
           window.location.assign(link.href);    
       }
    });
    
    return false;
}


var Cognoti = Object.extend({
    i18nCache: {},
    cookies: typeof CookieJar != 'undefined' ? new CookieJar({
        expires: 3600,
        path: '/'
    }) : null,
    
    addI18N: function(section, key, term)
    {
        this.i18nCache[section+'//'+key] = term;       
    },
    
    getI18N: function(section, key, fallback)
    {
        var val = this.i18nCache[section+'//'+key];
        return val ? val : fallback;    
    },
    
    setupFakeDropDown: function(dd)
    {
        dd = $(dd);
        
        var arrow = dd.down('.downarrow');
        var select = dd.down('.dropdown');
        var content = dd.down('.dropdowncontent');
        
        var offset = arrow.positionedOffset(); 
        
        content.setStyle({  })
        .setStyle({
            position: 'absolute',    
            top: offset[1] + arrow.getHeight()+'px',
            left: (offset[0] + arrow.getWidth() - content.getWidth())+'px'
            })
        .hide();
        
        select.closeFunction = function(e) 
        { 
            var elem = e.element();
            if(!elem.descendantOf(dd))
            {
                content.hide();
            }
        }
        
        Event.observe(document, 'click', select.closeFunction);
        select.observe('click', function(e) { content.toggle(); Event.stop(e); return false; });
    },
    
    fixpng: function() {
        //source: http://snipplr.com/view.php?codeview&id=270
        //	this will iterate with each img element, test if its a png and then operate by
		//	replacing the background-image for the filter of that image
        if(Prototype.Browser.IE)
        {
            var version = parseFloat(navigator.appVersion.split('MSIE')[1]);
            if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
                $$('img').each(function(img) {
                    if(img)
                    {
                        var imgSrc = img.src;
                        
                        if(imgSrc.match(/\.png$/i))
                        {
                            img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+imgSrc+"', sizingMethod='scale')";
                        }
                    }
                });
            }
        }
    },
    loadTreeState: function(tree, id) {
        var thisObj = this;
        var state = this.cookies.get('treestate_'+id);
        
        $H(state).each(function(item)
            {
                if(item.value == 'open')
                {
                    var ul = tree.down('ul.item'+item.key);
                    
                    if(ul && !ul.visible())
                    {
                        ul.show();
                        var handle = ul.previous('div.handle') || ul.next('div.handle');
                        handle.removeClassName('handleup');
                        handle.addClassName('handledown');    
                    }
                }
            });
                
    },
    alert: function(message)
    {
        Modalbox.show(getAlertBox(message));    
    },
    saveTreeState: function(tree, id) {
        var state = {};
        
        tree.select('ul').each(function(ul) {
            if(ul.visible())
            {
                var ulId = null;
                $w(ul.className).each(function(c)
                {
                   if(/item.+/.test(c))
                   {
                       ulId = c.substring(4);
                   }
                });
                
                 
                if(ulId)
                {
                    state[ulId] = 'open';
                }
            }
                
        });
        
        this.cookies.put('treestate_'+id, state);
    },
    
    highlightText: function(elem, words, immediately)
    {
        var thisObj = this;
        elem = $(elem);

        if(elem)
        {
            
            if(immediately)
            {
                thisObj._highlight(elem, immediately);
            }
            else
            {
                Event.observe(document, 'dom:loaded', function() { thisObj._highlight(elem, words) });
            }
            
        }
    },
    _highlight: function(elem, words)
    {
        var spanClass = 'search_highlight';
    },
    log: function(whatToLog, forceAlternative) {
        
        if(typeof console != 'undefined' && console.log)
        {
            console.log(whatToLog);    
        }
        else if(forceAlternative)
        {
            if(Object.isArray(whatToLog) || Object.isString(whatToLog))
            {
                alert(whatToLog);    
            }
            else
            {
                alert($H(whatToLog).inspect())
            }
        }
        
    },
    XML: {
        getValue: function(node)
        {
            return node && node.childNodes.length > 0 ? node.childNodes[0].nodeValue : '';
        }
    },
    hoverLabelEffect: function(inputs, options)
    {
        if(!Object.isArray(inputs))
        {
            inputs = [inputs];
        }
        
        options = Object.extend({
            stripColons: true                
        }, options || {});
        
        
        inputs.each(function(input) {
                
            input = $(input);
            
            if(!input || !input.getValue) return;
            
            
            var label = $$('label[for="'+input.identify()+'"]')[0];
            
            if(!label) return;
            
            input.label = label;
            label.hide();
            
            input.hoverLabelValue = label.innerHTML;
            
            if(options.stripColons)
            {
                input.hoverLabelValue = input.hoverLabelValue.replace(/:\s*$/, '');    
            }
            
            input.observe('focus', Cognoti._hoverLabelFocus);
            input.observe('blur', Cognoti._hoverLabelBlur);
            
            Cognoti._hoverLabelBlur.bind(input)();
        });
    },
    _hoverLabelFocus: function(e)
    {
        var input = $(this);
        
        if(input.showingLabel)
        {
            input.showingLabel = false;
            input.removeClassName("hoverLabel");
            input.setValue('');
        }    
    },
    _hoverLabelBlur: function(e)
    {
        var input = $(this);
        
        if(input.getValue().trim() == '')
        {
            input.showingLabel = true;
            input.addClassName("hoverLabel");
            input.setValue(input.hoverLabelValue);
        }    
    },
    showOverlay: function(options)
    {
        var thisObj = this;
        if(!this.overlay)
        {
            this.overlay = new Element('div', { 'class': 'cognoti_overlay' }).hide();
            $(document.body).insert(this.overlay);
        }
        
        if(!this.overlay.visible())
        {
            new Effect.Appear(this.overlay, {duration: 0.75, to: 0.6});
        }
        
        this.overlay.keyHandler = function(event)
        {
            if(event.keyCode == Event.KEY_ESC)
            {
                thisObj.hideOverlay();
            }
        }
        
        
        if(Prototype.Browser.IE)
			Event.observe(document, "keydown", this.overlay.keyHandler);
		else
			Event.observe(document, "keypress", this.overlay.keyHandler);
        
    },
    hideOverlay: function(options)
    {
        if(this.overlay)
        {
            if(Prototype.Browser.IE)
                Event.stopObserving(document, "keydown", this.overlay.keyHandler);
            else
                Event.stopObserving(document, "keypress", this.overlay.keyHandler);
            
            new Effect.Fade(this.overlay, { duration: 0.75 });
            
        }
    },
    popupBubble: function(target, contents, cloneNode, popupOptions)
    {
        if(!target.popupBubble || !target.popupBubble.visible() && contents)
        {
            contents = cloneNode ? contents.cloneNode(true) : contents;
            target.popupBubble = popupBubble(target, contents.show(), popupOptions);                
        }
        else if(target.popupBubble)
        {
            target.popupBubble.close();
            target.popupBubble = null;
        }
    }, 
    configureElements: function(parent)
    {
        if(!parent)
        {
            parent = document;    
        }
        
        parent = $(parent);
        
        var newWindowLinks = Element.select(parent, 'a.newWindow').findAll(function(a) 
            {
                return !a.readAttribute("targetConfigured");
            });
        newWindowLinks.invoke('writeAttribute', 'targetConfigured', 'true');
        newWindowLinks.invoke('observe', 'click', function(e)
        {
            window.open(this.getAttribute("href"), '_blank').focus();
            Event.stop(e);
            return false;
        });
        
        var popupImgLinks = Element.select(parent,'a.imgPopup').findAll(function(a) 
            {
                return !a.readAttribute("popupConfigured");
            });
        popupImgLinks.invoke('writeAttribute', 'popupConfigured', 'true');
        popupImgLinks.invoke('observe', 'click', function(e)
        {
            
            var img = new Element('img', { 'src': this.href });
            
            
            var qMark = this.href.indexOf('?');
            
            
            var extra = qMark >= 0 ? this.href.substring(qMark+1).toQueryParams() : {};
            
            Modalbox.show(img, extra);
            
            Event.stop(e);
            return false;
        });
        
        var hiddenElements = Element.select(parent,'.hideMe').findAll(function(elem) 
            {
                return !elem.readAttribute("hideMeConfigured");
            });
        hiddenElements.invoke('writeAttribute', 'hideMeConfigured', 'true').invoke('hide');
        
        
    },
    setupSlideOutControls: function(controls, options)
    {
        Event.observe(document, "dom:loaded", function()
            {
            controls = $(controls);
            if(!controls) return;
            
            options = Object.extend({ 
                side: 'Left',
                duration: 0.3,
                transitionDuration: true,
                smoothTransition: true,
                startOpen: false
            }, options || {});
            
            
            if(options.side != 'Left' && options.side != 'Right')
            {
                options.side = 'Left';    
            }
            
            controls.addClassName('slideOutControls');
            
            var slideHandle = new Element('div');
            slideHandle.addClassName('slideHandle'+options.side);
            
            var contents = new Element('div').addClassName('slideOutContents').update(controls.innerHTML);
            
            controls.update('');
            
            controls.insert(slideHandle);
            controls.insert(contents);
            controls.insertClear();
            
            
            controls.show();
            
            controls.cachedWidth = controls.getWidth();
            
            var setControlHeight = function()
                {
                    var h = document.viewport.getHeight();
                    
                    var height = h*0.75;
                    
                    controls.setStyle({'height': height+'px', top: (h*0.125)+'px'});
                    slideHandle.setStyle({'height': height+'px'});
                    contents.setStyle({'height': height+'px'});
                    
                    openControls(controls.open, false);
                };
            
            Event.observe(window, 'resize', setControlHeight);
            
            
            var openControls = function(open, smooth)
            {
                if(controls.moving) return;
                
                var vpWidth = document.viewport.getWidth();
                var w =
                    options.side == 'Left' ?
                        (open ?
                        0 :
                        slideHandle.getWidth() - controls.cachedWidth)
                    :
                        (open ?
                        vpWidth - controls.cachedWidth :
                        vpWidth - slideHandle.getWidth());
                    
                controls.open = open;
                controls.moving = true;
                    
                if(smooth)
                {
                    new Effect.Move(controls, {
                        x:  w, 
                        y: parseInt(controls.getStyle('top')), 
                        mode: 'absolute',
                        duration: options.transitionDuration,
                        afterFinish: function() { controls.moving = false; }
                    });
                }
                else
                {
                    controls.setStyle({'left':  w+'px'});
                    controls.moving = false;
                }
            }
            
            
            setControlHeight();
            openControls(options.startOpen, false);
            
            slideHandle.observe('click', function() { openControls(!controls.open, options.smoothTransition); });
        });
    }
    
});

var CognotiElementUtils = {
    appendFormElement: function(element, labelText, formElem, options)
    {
        options = Object.extend({
            labelAttr: {}
        }, options);
        element = $(element);
        
        var labelOptions = Object.extend({
            'for': formElem.identify()
        }, options.labelAttr);
        
        var labelElem = new Element('label', labelOptions).update(labelText);
        
        element.insert(labelElem);
        element.insert(formElem);
        
        return element;
    },
    createLabel: function(element, labelText)
    {
        element = $(element);
        
        var labelElem = new Element('label', { 'for': element.identify() }).update(labelText);
        
        return labelElem;
    },
    insertOption: function(element, text, value)
    {
        element = $(element);
        
        if(!value)
        {
            value = text;    
        }
        
        element.insert(new Element('option', { 'value': value }).update(text));
        return element;
    },
    insertBreak: function(element)
    {
        element = $(element);
        
        element.insert(new Element('br'));
        
        return element;
    },
    insertClear: function(element)
    {
        element = $(element);
        
        element.insert(new Element('div', { 'class': 'clear' }));
        
        return element;
    },
    insertElement: function(element, tag, text)
    {
        element = $(element);
        
        element.insert(new Element(tag).update(text));
        
        return element;                        
    },
    slideAndRemove: function(element, duration)
    {
        element = $(element);
        
        new Effect.SlideUp(element, 
        { duration: duration || 0.5, 
            afterFinish: function() { element.remove(); }
        });
    }
};

Element.addMethods(CognotiElementUtils);

if(Prototype.Browser.IE)
{
    Event.observe(window, 'load', Cognoti.fixpng);    
}

Event.observe(document, 'dom:loaded', function() { Cognoti.configureElements(); });

