/* Global functions for Cognoti */


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: {} };

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)
{
    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);
    
    return bubble;
}

var popupBubble = function(target, text)
{
    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: 1.0, afterFinish: function() { bubble.remove(); }}); 
        
        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(/* options.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);
    
    //$(document.body).insert(bubble);
    target.getOffsetParent().insert(bubble);
    
    bubble.resize();
    
    
    new Effect.Appear(bubble, {duration: .5});
    
    return bubble; 
}


var treeNav = function(ul, forceNow)
{
    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();
              }
           };
        
        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.select('input[checked]', 'li.active').length == 0 && nohideli != li)
                   {
                       tree.hide();
                       handle.addClassName('handleup');
                   }
                   else
                   {
                       handle.addClassName('handledown');                                      
                   }
               }
               
            });
        }
    
    if(forceNow)
    {
        treeFunction();    
    }
    else
    {
        Event.observe(document, 'dom:loaded', treeFunction);
    }
}


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

function setupMonitorActivity(form)
{
    form = $(form);
    form.hasChanged = false;    
    
    form.observe('submit', monitoredFormSubmitted);
    
    Event.observe(window, 'load', function()
        {
            form.select('input', 'textarea', 'select').each(function (i)
                {
                    i.observe('change', function() { monitoredFormChanged(form) }); 
                });
        });
    
        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.";                                  
           }
        };
}

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

function monitoredFormSubmitted()
{
    $(this).hasChanged = false;
}


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 setupComments = function(id)
{
    var commentslist = $('commentslist'+id);
    var commentcontrols = $('commentcontrols'+id);    
    var commentform = $('commentform'+id);
    var commenttitleform = $('commenttitleform'+id);
    
    commentform.hide();
    
    if(commenttitleform)
    {
        commenttitleform.hide();
    }
    
    commentcontrols.show();
    
    commentslist.select('span.options').each(function(span)
        {
            var id = span.id.substring(3);
            
            var reply = new Element('a', {'href':'#'}).update('Reply');
            reply.observe('click', function(e) { showCommentForm(commentform, 'add', id);  Event.stop(e);  });
            
            if(span.childElements().length > 0)
            {
                span.insert({top : new Element('span').update(' | ')});    
            }
            
            span.insert({top : reply});

            if(span.hasClassName('mycomment'))
            {
                var edit = new Element('a', {'href':'#'}).update('Edit');
                edit.observe('click', function(e) { showCommentForm(commentform, 'edit', id); Event.stop(e); });
                
                span.insert({top : new Element('span').update(' | ')})
                    .insert({top : edit});
            }
                            
            
        });
}

var showCommentTitleForm = function(form)
{
    Modalbox.show($(form), { title: 'Update Discussion Title' });    
}

var showCommentForm = function(form, process, commentid)
{
    Modalbox.show($(form), { title: 'Comments', overlayClose: false, width: 700 });
    
    form = $(form);
    var actualform = form.down('form');
    
    actualform.reset();
    actualform.process.value = process;
    actualform.commentid.value = commentid;
    
    if(process == "edit")
    {
        var li = $('discussioncomment'+commentid);
        
        var title = li.down('span.title').innerHTML;
        var content = li.down('p.comment_text').innerHTML;
        actualform.select('.addonly').invoke('hide');
        
        actualform.title.value = title;
        actualform.content.innerHTML = content.replace(/<br ?\/?>/g, '\n');
        actualform.submitMe.value = "Update Comment";
    }
    else
    {
        actualform.select('.addonly').invoke('show');
        actualform.content.innerHTML = '';
        actualform.submitMe.value = "Add Comment";
    }
    
    return false;
}

var deleteComment = function(link, commentblock)
{
    
    confirmBubble(link, 'Are you sure you want to delete this comment?', ['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")
                {
                    commentblock = $(commentblock);
                    if(commentblock)
                    {
                        new Effect.SlideUp(commentblock, 
                            { duration: 0.5, 
                            afterFinish: function() { commentblock.remove(); }
                            });
                    }
                }
                else if(status == "partialdelete")
                {
                    commentblock = $(commentblock);
                    if(commentblock)
                    {
                        commentblock.down('p.comment_text').update('*Deleted*');
                    }
                }
                else
                {
                    popupBubble(link, message);        
                }
                
            }
        });
    });
    
    return false;        
}

var submitComments = function(form, commentslist, addtop)
{
    form = $(form);
    commentslist = $(commentslist);
    
    var params = form.serialize(true);
    params.ajax = 'true';
    
    form.disable();
    
    new Ajax.Request(form.action, 
    {
        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")
            {
                form.reset();
                form.enable();
                
                if(params.process == "edit")
                {
                    
                    var comment = $('discussioncomment'+params.commentid);
                    comment.down('span.title').update(params.title);
                    comment.down('p.comment_text').update(params.content.replace(/\n/g, '<br />'));
                    
                    if(params.title.strip() == '')
                    {
                        comment.down('span.titlewrapper').hide();                            
                    }
                }
                else
                {
                    var nocomment = commentslist.down('.nocomments');
                    
                    if(nocomment)
                    {
                        nocomment.hide();    
                    }
                    
                    var section = 0;
                    
                    
                    var wrapper = new Element('div', {'class': 'wrapper'});
                    var header = new Element('div', {'class': 'header'});
                    var options = new Element('span', {'class': 'options'});
                    
                    
                    header.insert(options);
                    
                    var titlewrapper = new Element('span', {'class': 'titlewrapper'});
                    titlewrapper.insert(new Element('span', {'class': 'title'}).update(params.title));
                    titlewrapper.insert(' ');
                    titlewrapper.insert(new Element('span', {'class': 'by'}).update('from'));
                    titlewrapper.insert(' ');
                    header.insert(titlewrapper);
                    if(params.title.strip() == '')
                    {
                        titlewrapper.hide();
                    }
                    
                    header.insert(new Element('span', {'class': 'username'}).update('Me'));
                    header.insert(' ');
                    header.insert(new Element('span', {'class': 'date'}).update('Less than 5 minutes ago'));
                    
                    
                    wrapper.insert(header);
                    wrapper.insert(new Element('p', {'class': 'comment_text'}).update(params.content.replace(/\n/g, '<br />')));
                    
                    var li = new Element('li').update(new Element('div', {'class': 'comment'}).update(wrapper));
                    
                    /* var newid = li.identify();
                    li.id = 'discussioncomment'+newid;
                    
                    var edit = new Element('a', {'href':'#'}).update('Edit');
                    edit.observe('click', function(e) { showCommentForm(form.up(), 'edit', newid); Event.stop(e); });
                    options.insert({top : edit}); */
                    
                    if(!params.commentid)
                    {
                        if(addtop)
                        {
                            commentslist.insert({top: li});
                        }
                        else
                        {
                            commentslist.insert(li);
                        }
                    }
                    else //params.process == "reply"
                    {
                        var parent = $('discussioncomment'+params.commentid);
                        var childlist = parent.down('ul.sublist');
                        if(!childlist)
                        {
                            childlist = new Element('ul', {'class':'sublist'});
                            parent.insert(childlist);
                        }
                        
                        childlist.insert(li);
                    }
                }
                
                Modalbox.hide();
            }
            else
            {
                popupBubble(form, message);
                //do nothing for now... should probably alert user though    
            }
            
        }
    });
    
    return false;    
}


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 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 switchTab = function(tabs, targettab, tabsheets, targettabsheet)
{
    tabs = $(tabs);
    targettab = $(targettab);
    tabsheets = $(tabsheets);
    targettabsheet = $(targettabsheet);
    
    tabs.select('li').invoke('removeClassName', 'current');
    targettab.addClassName('current');
    
    tabsheets.select('.tabsheet').invoke('hide');
    targettabsheet.show();
    
    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)
    {
         o = node.childNodes[0].nodeValue; 
    }
    else
    {
        for(var i = 0; i < len; ++i)
        {
            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 inputBox = function(inputname, labeltext, inputoptions, labeloptions)
{
    labeloptions = Object.extend({'class': 'label_text'}, labeloptions || {});
    inputoptions = Object.extend({name: inputname}, inputoptions || {});
    
    var p = new Element('p');
    p.insert(new Element('label', labeloptions).update(labeltext));
    p.insert(new Element('input', inputoptions));

    return p;    
}

var Cognoti = {
    log: function(content, force)
    {
        if(window.console)
        {
            console.log(content);    
        }
        else if(force)
        {
            alert(content);    
        }
    }
    
}

