/* Global functions for Cognoti */

//* NEW WATCHLIST FUNCTIONS *//
var processingWatch = false;

var setupWatch = function(id, type, active)
{
	base = $('watch_' + type + '_' + id);

	var paramString = "'" + id + "'" + "," + "'" + type + "'";
	
	if (active)
	{
		base.update('<a href="#" onClick="changeWatch(' + paramString + '); return false;">' + Cognoti.getI18N('resources', 'already_watched','Stop Watching') + '</a>');
		base.addClassName('watch_on');
	}
	else
	{
		base.update('<a href="#" onClick="changeWatch(' + paramString + '); return false;">' + Cognoti.getI18N('resources', 'add_to_watch','Watch This') + '</a>');
		base.addClassName('watch_off');
	}
}

var changeWatch = function(id, type)
{
	base = $('watch_' + type + '_' + id);
	anchor = base.down('a');

	var op = 'add';
	if (base.hasClassName('watch_on'))
	{
		op = 'del';
	}
	
	processWatch(type, id, op);
}

var switchWatch = function(type, id, op)
{
	base = $('watch_' + type + '_' + id);
	anchor = base.down('a');

	if (op == 'add')
	{
		base.removeClassName('watch_off');
		base.addClassName('watch_on');
		anchor.update(Cognoti.getI18N('resources', 'already_watched','Stop Watching'));
	}
	else
	{
		base.removeClassName('watch_on');
		base.addClassName('watch_off');
		anchor.update(Cognoti.getI18N('resources', 'add_to_watch','Watch This'));
	}
}

var processWatch = function(type, id, op)
{
	if(!processingWatch)
    {
        processingWatch = true;

        var url = '/cognoti/helper/watchlist.nn';
        var params = { id: id, type: type, op: op };
        
        new Ajax.Request(url, 
            {
                parameters: params,
                method: 'post',
                onSuccess: function(transport)
                {
                    var root = transport.responseXML.documentElement;
                    var status = root.getAttribute("status");
                    
                    if(status == "success")
                    {
						switchWatch(type, id, op);
                    }
                    else
                    {
                        var message = root.getElementsByTagName("message")[0].childNodes[0].nodeValue;
                        base = $('watch_' + type + '_' + id);
                        popupBubble(base, message);   
                    }
                    
                    processingWatch = false;    
                },
                onComplete: function()
                {
                    processingWatch = false;    
                }
            });
    }
    
    return false;
}
//* END NEW WATCHLIST FUNCTIONS *//

//* NEW FAVORITES FUNCTIONS *//
var processingFavorites = false;

var setupFavorite = function(id, type, active)
{
	base = $('fav_' + type + '_' + id);
	
	var paramString = "'" + id + "'" + "," + "'" + type + "'";
	
	if (active)
	{
		base.update('<a href="#" onClick="changeFavorite(' + paramString + '); return false;" >' + Cognoti.getI18N('resources', 'already_favorited','Remove from Favorites') + '</a>');
		base.addClassName('favorite_on');
	}
	else
	{
		base.update('<a href="#" onClick="changeFavorite(' + paramString + '); return false;" >' + Cognoti.getI18N('resources', 'add_to_favorites','Add to Favorites') + '</a>');
		base.addClassName('favorite_off');
	}
}

var changeFavorite = function(id, type)
{
	base = $('fav_' + type + '_' + id);
	anchor = base.down('a');

	var op = 'add';
	if (base.hasClassName('favorite_on'))
	{
		op = 'del';
	}
	
	processFavorite(type, id, op);
}

var switchFavorite = function(type, id, op)
{
	base = $('fav_' + type + '_' + id);
	anchor = base.down('a');

	if (op == 'add')
	{
		base.removeClassName('favorite_off');
		base.addClassName('favorite_on');
		anchor.update(Cognoti.getI18N('resources', 'already_favorited','Remove from Favorites'));
	}
	else
	{
		base.removeClassName('favorite_on');
		base.addClassName('favorite_off');
		anchor.update(Cognoti.getI18N('resources', 'add_to_favorites','Add to Favorites'));
	}
}

var processFavorite = function(type, id, op)
{
	if(!processingFavorites)
	{
		processingFavorites = true;
		var url = '/cognoti/helper/favorites.nn?id='+id+'&type='+type;
		
		new Ajax.Request(url+'&op='+op, 
		{
			method: 'get',
			onSuccess: function(transport)
			{
				var root = transport.responseXML.documentElement;
				var status = root.getAttribute("status");

				if(status == "success")
				{
					switchFavorite(type, id, op);
				}
				else
				{
					var message = root.getElementsByTagName("message")[0].childNodes[0].nodeValue;
					base = $('fav_' + type + '_' + id);
					popupBubble(base, message);
				}
				processingFavorites = false;    
			},
			onComplete: function()
			{
				processingFavorites = false;				
			}
		});	
	}
	return false;
}
//* END NEW FAVORITES FUNCTIONS *//

var favoritesUserList = function(type, id, title, page)
{
    page = page || 1;
    
    var params = { 
        page: page,
        type: type,
        id: id,
        title: title        
    }
    
    Modalbox.show('/cognoti/helper/favoriters.nn', {
        title: title || 'Favoriters', 
        width: 700,
        params: params
    });
    
    return 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/star.png';
                                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/star-gray.png';
                                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)
{
    popupOptions = Object.extend({
        sidePopup: false,
        closeOnClick: true
    }, 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)
    {
        if(popupOptions.closeOnClick)
        {
            bubble.close(e);
        }
        bubble.select('input').each(function (input) { input.stopObserving(); });
        if(result)
        {
            result(this.value);
        }
    }
    
    options.each(function(opt)
    {
       var input = new Element('input', { type: 'button', value: opt } );
       input.observe('click', resultFunc);
       optionblock.insert(input); 
    });
    
    
    if(popupOptions.sidePopup)
    {
        bubble = popupBubbleSide(target, block, popupOptions);    
    }
    else
    {
        bubble = popupBubble(target, block, popupOptions);    
    }
    
    return bubble;
}

var popupBubble = function(target, text, popupOptions)
{
    popupOptions = Object.extend({
        right: false,
        fadeInSpeed: 0.5,
        fadeOutSpeed: 1.0,
        bubbleStyle: null,
        relativePlacement: true,
        relativePlacementElem: null,
        above: true
            
    }, popupOptions || {});
    
    var bubble = new Element("div", { style: 'display: none;' }).addClassName('popupFlag');
    
    if(popupOptions.bubbleStyle)
    {        
        bubble.setStyle(popupOptions.bubbleStyle);    
    }
    
    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(popupOptions.above ? 'tip' : 'tipup');
    
    
    if(popupOptions.above)
    {
        bubble.insert({bottom: a});    
        bubble.insert({bottom: textdiv});
        bubble.insert({bottom: tip});
    }
    else
    {
        bubble.insert({bottom: tip});
        bubble.insert({bottom: a});    
        bubble.insert({bottom: textdiv});
    }
    
    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 = {};
        
        if(popupOptions.relativePlacementElem)
        {
            offset = bubble.target.cumulativeOffset();
            var otherOffset = popupOptions.relativePlacementElem.cumulativeOffset();
            var baseOffset = popupOptions.relativePlacementElem.positionedOffset();
            
            offset = { '0': baseOffset.left + offset.left - otherOffset.left, '1': baseOffset.top + offset.top - otherOffset.top };
            
            offset.top = offset[1];
            offset.left = offset[0]; 
        }
        else
        {
            offset = popupOptions.relativePlacement ? bubble.target.positionedOffset() : bubble.target.cumulativeOffset()    
        }
        
        var top = popupOptions.above ? offset.top - bubble.getHeight() : offset.top + bubble.target.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 + 12;
            bubble.tip.setStyle({ left: (width-29)+'px'});
        }
        
        bubble.setStyle({top: top+'px', left: left+'px'});        
    }
    
    bubble.setContent = function(text)
    {
        textdiv.update(text);
        bubble.resize();
    }
    
    a.observe('click', bubble.close);
    Event.observe(window, 'resize', bubble.resize);
    
    if(popupOptions.relativePlacement)
    {
        if(popupOptions.relativePlacementElem)
        {
            popupOptions.relativePlacementElem.insert(bubble);    
        }
        else
        {
            target.getOffsetParent().insert(bubble);
        }
    }
    else
    {
        $$('body')[0].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',
        dragHandle: null,
        relativePlacement: true,
        relativePlacementElem: null,
        bubbleStyle: null
            
    }, popupOptions || {});
    
    var bubble = new Element("div", { style: 'display: none;' }).addClassName('popupFlag');
    
    if(popupOptions.bubbleStyle)
    {        
        bubble.setStyle(popupOptions.bubbleStyle);    
    }
    
    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 = {};
        
        if(popupOptions.relativePlacementElem)
        {
            offset = bubble.target.cumulativeOffset();
            var otherOffset = popupOptions.relativePlacementElem.cumulativeOffset();
            var baseOffset = popupOptions.relativePlacementElem.positionedOffset();
            
            offset = { '0': baseOffset.left + offset.left - otherOffset.left, '1': baseOffset.top + offset.top - otherOffset.top };
            
            offset.top = offset[1];
            offset.left = offset[0];
        }
        else
        {
            offset = popupOptions.relativePlacement ? bubble.target.positionedOffset() : bubble.target.cumulativeOffset()    
        }
        
        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'});        
    }
    
    bubble.setContent = function(text)
    {
        textdiv.update(text);
        bubble.resize();
    }
    
    a.observe('click', bubble.close);
    Event.observe(window, 'resize', bubble.resize);
    
    if(popupOptions.relativePlacement)
    {
        if(popupOptions.relativePlacementElem)
        {
            popupOptions.relativePlacementElem.insert(bubble);    
        }
        else
        {
            target.getOffsetParent().insert(bubble);
        }
    }
    else
    {
        $$('body')[0].insert(bubble);    
    }
    
    bubble.resize();
    
    new Effect.Appear(bubble, {duration: popupOptions.fadeInSpeed, afterSetup: popupOptions.beforeShow.bind(bubble), afterFinish: popupOptions.afterShow.bind(bubble)});
    
    if(popupOptions.dragHandle)
    {
        new Draggable(bubble, { handle: popupOptions.dragHandle });
        popupOptions.dragHandle.setStyle({'cursor': 'move'});
    }
    
    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();
        
        var note = prompt("Enter details", "");
        if(note != null)
        {
            var div = new Element('div',
            {                
                title: note
            
            }).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
                       && !li.hasClassName('active'))
                   {
                       tree.hide();
                       handle.addClassName('handleup');
                   }
                   else
                   {
                       handle.addClassName('handledown');                                      
                   }
               }
               
            });
        
            if(savedStateId) 
            { 
                Cognoti.loadTreeState(ul, savedStateId); 
            }
        }
    
    if(Cognoti.domLoaded || forceNow)
    {
        treeFunction();    
    }
    else
    {
        Event.observe(document, 'dom:loaded', treeFunction);
    }
}


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

function setupMonitorActivity(form, immediate, supportedSubmit, ignoreFieldWatching)
{
    form = $(form);
    form.hasChanged = false;    
    form.supportedSubmit = supportedSubmit;
    
    var observeFunction = function()
    {
		form.getInputs().each(function (i)
            {
                i.observe('change', function() { monitoredFormChanged(form); }); 
            });
    }
    
	form.getInputs('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(!ignoreFieldWatching)
    {
        if(immediate)
        {
            observeFunction();    
        }
        else
        {
            Event.observe(document, 'dom:loaded', observeFunction);
        }
    }
	
}

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

function monitoringOff(form)
{
    $(form).hasChanged = false;    
}


/* ============ 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,
            mouseOver: false
        }, r.options || {});
        
        if(r.options.rotateFreq)
        {
            r.timer = setTimeout(function() { fr._timer(r); }, r.options.rotateFreq*1000);
        }
        
        if(r.options.mouseOver)
        {
            r.list.select('li').invoke('observe', 'mouseover', function() { fr._mouseHover(r, this); });        
        }
    },
    
    _timer: function(r)
    {
        var fr = this;
        r.timer = setTimeout(function() { fr._timer(r); }, r.options.rotateFreq*1000);
        this._doRotate(r);
    },
    
    _mouseHover: function(r, li)
    {
        if(r.hoverCurrent != li)
        {
            r.hoverCurrent = li;
            
            var link = li.down('h3 a');
                
            var title = li.innerHTML;
            var targeturl = link.href;	
            var extra = li.down('div.description').innerHTML;
            var imgsrc = li.down('img.preview').src;
            
            this._doFeaturedSwitch(r, title, extra, imgsrc, targeturl);
        }
    },

    _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.preview').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 h2 a');
        
        if(a)
        {
            a.href = targeturl;
            a.innerHTML = title;
        }
        
        r.content.down('p').innerHTML = extra;
        
        var aimg = r.content.down('a.resource 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, acparams)
{
    textbox = $(textbox);
    hiddeninput = $(hiddeninput);

    var params = acparams || {};
    params.type = type;
    params.random = new Date().getTime();
    
	var autocomplete = new Ajax.Autocompleter(textbox, acbox, '/cognoti/helper/autocomplete.nn',
	{
		paramName: 's',
		minChars: 2,
		parameters: Object.toQueryString(params),
		method: 'get',
		afterUpdateElement: function(input, li)
		{
			var value = input.getValue();
			var id = li.id.replace(/item/, '');
			textbox.currvalue = value; 
			textbox.currid = id;
			
			if(hiddeninput)
			{
				hiddeninput.value = id;
			}
			
			if(id && li && callback)
			{
				callback(value, id, li);    
			}
		}
	});

    if(hiddeninput)
    {
        $(textbox).observe('change', function(){
            if(this.currvalue != this.value)
            {
                hiddeninput.value = 0;    
            }
            else if(this.currid)
            {
                hiddeninput.value = this.currid;                    
            }
        });
    }        
}

var TopicWindow = Class.create({
    initialize: function(tree, expandtoplevel, name, allowMultiple)
    {
        var thisObj = this;
        tree = $(tree);
        
        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 && !allowMultiple)
               {
                   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');
                expand.observe('click', thisObj.toggle.bind(thisObj));
                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(e)
    {
        expander = Event.findElement(e);
        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, viewtype)
{
    var url = '/cognoti/helper/recommend.nn';

    
    if(url != null)
    {
        var params = { 'reftype': type, 'refid': id };
        
        if(viewtype)
        {
            params.viewtype = viewtype;    
        }
        
        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.getInputs('submit')[0];

    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': 'small_button', 'onclick': 'Modalbox.hide(); return false;'}).update('OK');
    div.insert(new Element('p', { 'class': 'formsubmit'}).update(close));

    return div;    
}

var progressWheel = function(text, textWrapper)
{
    var spinner = new Element('img', { 'src': '/cognoti/img/spinner.gif', 'alt': 'Loading...' }).setStyle({'verticalAlign': 'middle'});
    
    if(text)
    {
        textWrapper = textWrapper || 'span';
        spinner = new Element(textWrapper, { 'class': 'spinner' }).insert(spinner.setStyle({'paddingRight': '5px'})).insert(text);
    }
    
    return spinner;
}

if(typeof String.prototype.trim !== 'function') { 
  String.prototype.trim = function() { 
    return this.replace(/^\s+|\s+$/g, '');  
  } 
} 

var addCollection = function(textbox, list)
{
    var name = $(textbox).getValue();
    
    if(name.trim() == '')
    {
        return;    
    }
    
    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)
{
    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.active)
    {
        Modalbox.resizeToContent();
    }
    
    return false;
}

var changeGroup = function(list, entry, href)
{
	var ul = $(list);
	var input = $(entry);
	
	var id = input.currid;
	var value = input.currvalue;
	
	if (id == null)
		return;
		
	ul.innerHTML = '';
	
	var li = new Element('li', { 'class' : 'link'});
	li.insert(new Element('input', { 'type' : 'hidden', 'name' : 'link_id', 'value' : id}));
	li.insert(new Element('button', { 'onclick' : 'parentNode.remove()', 'title' : 'Remove', 'class' : 'small_button', 'type' : 'button' }).update('&times;'));
	li.insert(new Element('a', { 'href' : href + 'gid=' + id }).update(value));
	
	ul.insert(li);
	
	input.removeAttribute('currvalue');
	input.removeAttribute('currid');
	input.setAttribute('value', '');
}

var addGroup = function(list, entry, href)
{
	var ul = $(list);
	var input = $(entry);
	
	var id = input.currid;
	var value = input.currvalue;
	
	if (id == null)
		return;
	
	var li = new Element('li', { 'class' : 'affiliate'});
	li.insert(new Element('input', { 'type' : 'hidden', 'name' : 'affiliate_id', 'value' : id}));
	li.insert(new Element('button', { 'onclick' : 'parentNode.remove()', 'title' : 'Remove', 'class' : 'small_button', 'type' : 'button' }).update('&times;'));
	li.insert(new Element('a', { 'href' : href + 'gid=' + id }).update(value));
	
	ul.insert(li);
	
	input.removeAttribute('currvalue');
	input.removeAttribute('currid');
	input.setAttribute('value', '');
}

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 setupGroupAutocomplete = function(textbox, acbox, hiddeninput, callback)
{
	return setupAutocomplete(textbox, acbox, hiddeninput, 'group', callback);
}

var setupCollegeAutocomplete = function(textbox, acbox, hiddeninput, callback)
{
    return setupAutocomplete(textbox, acbox, hiddeninput, 'institution_colleges', 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, popupOptions)
{
    confirmBubble(link, text, ['Yes', 'No'], function(result) {
       if(result == 'Yes')
       {
           window.location.assign(link.href);    
       }
    }, popupOptions);
    
    return false;
}


var Cognoti = Object.extend({
    domLoaded: false,
    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 window.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);
            if(input.form)
            {
                $(input.form).observe('submit', function() 
                    { 
                        if(input.showingLabel)
                        {
                            input.setValue('');
                        }
                    });    
            }
            
            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() || input.getValue().trim() == '')
        {
            input.showingLabel = true;
            input.addClassName("hoverLabel");
            input.setValue(input.hoverLabelValue);
        }    
    },
    showOverlay: function(options)
    {
        
        var opts = Object.extend({
            allowEscape: true
        }, 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(opts.allowEscape)
        {
            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 });
            
            if(this.overlay.box)
            {
                Event.stopObserving(document, "resize", this.overlay.box.resizeHandler);    
            }
            
            this.overlay = null;
        }
    },
    overlayBox: function(content)
    {
        if(!this.overlay) { return; }
        
        if(this.overlay.box)
        {
            Event.stopObserving(window, "resize", this.overlay.box.resizeHandler);                
        }
        
        this.overlay.box = new Element('div', { 'class': 'cognoti_overlay_box' });
        this.overlay.box.update(content);
        
        this.overlay.box.resizeHandler = function(e)
        {
            var box = this;
            
            var dim = box.getDimensions();
            
            var windowDim = document.viewport.getDimensions();
            
            box.setStyle({'top': ((windowDim.height - dim.height) / 2)+'px',
                'left': ((windowDim.width - dim.width) / 2)+'px'});
                    
        };
        
        this.overlay.update(this.overlay.box);
        
        var b = this.overlay.box.resizeHandler.bind(this.overlay.box);
        Event.observe(window, 'resize', b);
        
        setTimeout(b, 50);
      
    },
    popupBubble: function(target, contents, cloneNode, popupOptions)
    {
        var popupFunction = popupOptions && popupOptions.sidePopup ? popupBubbleSide : popupBubble;
        
        if(!target.popupBubble || !target.popupBubble.visible() && contents)
        {
            contents = cloneNode ? contents.cloneNode(true) : contents;
            target.popupBubble = popupFunction(target, contents.show(), popupOptions);
            return target.popupBubble;
        }
        else if(target.popupBubble)
        {
            target.popupBubble.close();
            target.popupBubble = null;
            return null;
        }
    }, 
    confirmBubble: function(target, contents, cloneNode, options, resultFunc, popupOptions)
    {
        if(!target.popupBubble || !target.popupBubble.visible() && contents)
        {
            contents = cloneNode ? contents.cloneNode(true) : contents;
            target.popupBubble = confirmBubble(target, contents.show(), options, resultFunc, popupOptions);
            return target.popupBubble;
        }
        else if(target.popupBubble)
        {
            target.popupBubble.close();
            target.popupBubble = null;
            return null;
        }    
    },
    configureElements: function(parent)
    {
        if(!parent)
        {
            return;    
        }
        
        parent = $(parent);
        
        var newWindowLinks = Element.select(parent, 'a.newWindow').findAll(function(a) 
            {
                return !a.readAttribute("targetConfigured");
            });
        newWindowLinks.invoke('writeAttribute', 'targetConfigured', 'true');
        newWindowLinks.invoke('writeAttribute', 'target', '_blank');
        
        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');
        
        
    },
    ajaxBubble: function(target, url, ajaxOptions, bubbleOptions)
    {
        var bubble = Cognoti.popupBubble(target, progressWheel('Loading...'), null, bubbleOptions);
        
        if(bubble)
        {
            var options = Object.extend({
                mode: 'post'
            }, ajaxOptions || {});
            
            options.onSuccess = function(t)
            {
                bubble.setContent(t.responseText);    
            }
            
            options.onFailure = function(t)
            {
                bubble.setContent('Error in loading...');    
            }
            
            new Ajax.Request(url, options);
        }
        
        return false;
        
    },
    standardsBubble: function(link, id, popupOptions)
    {
        Cognoti.ajaxBubble(link, '/standards/standards.nn', 
            { parameters: {view: 'quickView', id: id}},
            Object.extend({ bubbleStyle: { width: '450px' }}, popupOptions || {})
            );
        return false;       
    },   
    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); });
        });
    },
    popupImage: function(image, title, original)
    {
        var div = new Element('div', { 'style': 'text-align: center' });
        var img = new Element('img', { 'src': image, 'alt': title });
        
        div.update(img);
        
        if(original)
        {
            var a = img.wrap('a', { 'href': original, 'class': 'newWindow', 'rel': 'external', 'title': 'Click for Original', 'target': '_blank' });
        }
        
        
        Modalbox.show(div, { title: title || '', width: 600 });    
        return false;
    },
    popupVideo: function(video, thumbnail, title, caption)
    {
        var div = new Element('div', { 'style': 'text-align: center' });
        var video = new Element('embed', { 
                type: 'application/x-shockwave-flash', 
                allowfullscreen: 'true',
                pluginspage: 'http://www.macromedia.com/go/getflashplayer',
                src: '/static/video/flvplayer.swf',
                width: '480', 
                height: '340',
				wmode: 'transparent',
            flashvars: 'file='+video+(thumbnail?'&image='+thumbnail:'')+(caption?'&plugins=captions-1,googlytics-1&captions.state=false&captions.file='+caption:'&plugins=googlytics-1')});
	 
        div.update(video);
        Modalbox.show(div, { title: title || '', width: 700 });
        return false;
    },
    
    popupSWF: function(swf, title)
    {
        var div = new Element('div', { 'style': 'text-align: center' });
        var video = new Element('embed', { 
                type: 'application/x-shockwave-flash', 
                allowfullscreen: 'true',
                pluginspage: 'http://www.macromedia.com/go/getflashplayer',
                src: swf,
                width: '680',
                height: '500',
				wmode: 'transparent'
                
        });
        
        div.update(video);
        Modalbox.show(div, { title: title || '', width: 700 });
        return false;
    },
    popupVideoNew: function(files, parameters)
    {
        
        parameters = Object.extend({
            width: 480,
            height: 360,
            title: 'Video'
        }, parameters || {});
        
        var vid = this.createVideo(files, parameters);
        
        if(vid)
        {
            var div = new Element('div', { 'style': 'text-align: center' });
            div.insert(vid);
            Modalbox.show(div, { title: parameters.title || '', width: parameters.width + 20 });
        }
    },
    createVideo: function(files, parameters)
    {
        
        files = Object.extend({
            flash: null,
            h264: null,
            ogg: null
        }, files || {});
        
        parameters = Object.extend({
            poster: null,
            controls: true,
            fullscreen: true,
            autoplay: null,
            width: 320,
            height: 240,
            preload: true,
            caption:null,
            flashVars: {
                
            }
        }, parameters || {});
        
        if((Prototype.Browser.Gecko || Prototype.Browser.Opera) && files.ogg)
        {
            return this._createVideoHTML5(files.ogg, parameters);    
        }
        else if((Prototype.Browser.Webkit || Prototype.Browser.MobileSafari) && files.h264)
        {
            return this._createVideoHTML5(files.h264, parameters);
        }
        else if(files.flash)
        {
            return this._createVideoFlash(files.flash, parameters);    
        }
        
    },
    _createVideoHTML5: function(file, parameters)
    {
        var v = new Element('video', {
                tabindex: 0,
                height: parameters.height,
                width: parameters.width,
                src: file
        });
        
        if(parameters.poster)
        {
            v.writeAttribute('poster', parameters.poster);    
        }
        
        if(parameters.preload)
        {
            v.writeAttribute('preload', 'preload');    
        }
        
        if(parameters.autoplay)
        {
            v.writeAttribute('autoplay', 'autoplay');    
        }
        
        if(parameters.controls)
        {
            v.writeAttribute('controls', 'controls');    
        }
        
        return v;
    },
    _createVideoFlash: function(file, parameters)
    {
        var video = new Element('embed', { 
            type: 'application/x-shockwave-flash', 
            pluginspage: 'http://www.macromedia.com/go/getflashplayer',
            src: '/static/video/flvplayer.swf',
            width: parameters.width, 
            height: parameters.height,
			wmode: 'transparent'
        });
        
        var flashVars = parameters.flashVars || {};
        
        flashVars.file = file;
	     
        if(parameters.poster)
        {
            flashVars.image = parameters.poster;    
        }
        
        if(parameters.caption)
        {
            flashVars.caption = 1;
            flashVars['captions.file'] = parameters.caption;
			flashVars['captions.state'] = 'false';
			flashVars['plugins'] = 'captions-1,googlytics-1';
        }
		else
		{
			flashVars['plugins'] = 'googlytics-1';
		}
        
        if(parameters.autoplay)
        {
            flashVars.autostart = true;    
        }
        
        if(parameters.fullscreen)
        {
            video.writeAttribute('allowfullscreen', true);
        }
        
        video.writeAttribute('flashvars', Object.toQueryString(flashVars));
        
        return video;
        
        
    },
    makeSelect: function(name, options, selectOptions)
    {
        var selectOptions = Object.extend(
            {
                selectAttr: {
                    'class': 'form_select'
                }
            }, selectOptions || {});
        
        selectOptions.selectAttr.name = name;
        
        var sel = new Element('select', selectOptions.selectAttr);
        
        for(var key in options)
        {
            sel.insertOption(key, options[key]);
        }
     
        return sel;
    },
    submitFakeForm: function(submitbutton, url)
    {
        var b = $(submitbutton);
        
        if(!b) { return; }
        
        var form = b.up('div.fake_form');
        
        if(!form)
        {
            return;    
        }
        
        var elements = form.select('input,textarea,select');
        var params = {};
        
        elements.each(function(elem)
            {
                if(elem.disabled || !elem.getValue()) return;
                
                if(Object.isUndefined(params[elem.name]))
                {
                    params[elem.name] = [];    
                }
                params[elem.name].push(elem.getValue());
            });
        
        if(/.*\?.+/.match(url))
        {
            url = url+'&'+Object.toQueryString(params);    
        }
        else
        {
            url = url+'?'+Object.toQueryString(params);    
        }
        
        location.href = url;
        
        return true;
    }
    
    
});

var CognotiElementUtils = {
    
    appendFormElement: function(element, labelText, formElem, options)
    {
        options = Object.extend({
            labelAttr: {},
            hoverEffect: false,
            hoverEffectOptions: {},
            labelFirst: true
        }, options || {});
        element = $(element);
        
        var labelOptions = Object.extend({
            'for': formElem.identify()
        }, options.labelAttr);
        
        var labelElem = new Element('label', labelOptions).update(labelText);
        
        if(options.labelFirst)
        {
            element.insert(labelElem).insert(formElem);
        }
        else
        {
            element.insert(formElem).insert(labelElem);
        }
        
        if(options.hoverEffect)
        {
            Cognoti.hoverLabelEffect(formElem, options.hoverEffectOptions);    
        }
        
        return element;
    },
    createLabel: function(element, labelText)
    {
        element = $(element);
        
        var labelElem = new Element('label', { 'for': element.identify() }).update(labelText);
        
        return labelElem;
    },
    insertHiddenField: function(element, name, value)
    {
        element = $(element);

        element.insert(new Element('input', {'type':'hidden', 'name': name, 'value': value }));
        return element;        
    },
    insertOption: function(element, text, value)
    {
        element = $(element);
        
        if(Object.isUndefined(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(); }
        });
    },
    update: function(element, content)
    {
        element = Element.originalUpdate(element, content);
        if(Object.isElement(element))
        {
            Cognoti.configureElements(element);
        }
        return element;
    },
    autocomplete: function(element, actype, name, value, callback, acparams)
    {
        element = $(element);
        
        var autocompleteBox = new Element('div', { 'class': 'autocomplete' });
        
        var idBox = name == null ? null :   
            new Element('input', { 'type': 'hidden', 'name': name, 'value': value });
        
        element.insert({after: autocompleteBox});
        
        if(idBox)
        {
            element.insert({after: idBox});
        }
		
        setupAutocomplete(element, autocompleteBox, idBox, actype, callback, acparams);
    },
    serializeElements: function(element, asObj)
    {
        element = $(element);
        
        var elems = element.select('input','textarea','select');
        
        var len = elems.length;
        
        if(asObj)
        {
            var obj = {};
            
            for(var i = 0; i < len; ++i)
            {
                var e = elems[i];
                
                if(!e.name) continue;
				
				if(!obj[e.name])
                {
                    obj[e.name] = []                    
                }
                
                obj[e.name].push(e.getValue());
                
            }
            
            return obj;
        }
        else
        {
            var str = '';
            
            for(var i = 0; i < len; ++i)
            {
                var e = elems[i];
                
                if(!e.name) continue;
				
				str += e.name + '=' + e.getValue();
				
				if(i < len - 1)
				{
				    str += '&';
				}
                
            }        
         
            return str;
        }
    }
};

Element.originalUpdate = Element.update;
Element.addMethods(CognotiElementUtils);

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

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


