/* Global functions for Cognoti */

//explicit calls of swapOnClass for favorite and watch icons
var favoriteOver = function(img)
{
	swapOnClass(img, '/cognoti_theme/img/cte/favorite_star_gray.png', '/cognoti_theme/img/cte/favorite_star.png', 'removefav');
}
var favoriteOut = function(img)
{
	swapOnClass(img, '/cognoti_theme/img/cte/favorite_star.png', '/cognoti_theme/img/cte/favorite_star_gray.png', 'removefav');
}
var watchOver = function(img)
{
	swapOnClass(img, '/cognoti_theme/img/cte/watch_closed.png', '/cognoti_theme/img/cte/watch.png', 'removewatch');
}
var watchOut = function(img)
{
	swapOnClass(img, '/cognoti_theme/img/cte/watch.png', '/cognoti_theme/img/cte/watch_closed_gray.png', 'removewatch');
}

//changes the src of img to image1src if it has class classname or image2src otherwise
var swapOnClass = function(img, image1src, image2src, classname)
{
	if ($(img).hasClassName(classname))
	{
		img.src = image1src;
	}
	else
	{
		img.src = image2src;
	}
}

var processingFavorites = false;
var processingWatch = false;

//* NEW WATCHLIST FUNCTIONS *//
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 setupFavorite = function(id, type, active, count)
{
	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');
	}
	
	if (count >=0)
	{
		base.insert('<div class="fav_count">' + '</div>');
		setCount(type, id, count);
	}
}

var setCount = function(type, id, count)
{
		base = $('fav_' + type + '_' + id);
			
		var numberMessage = '';
		if (count == 0)
			numberMessage = Cognoti.getI18N('resources', 'user_like_0', 'users like this');
		else if (count == 1)
			numberMessage = Cognoti.getI18N('resources', 'user_like_1', 'user likes this');
		else
			numberMessage = Cognoti.getI18N('resources', 'user_like_x', 'users like this');

		var number = count;
		if (count == 0)
			number = 'No';
			
		base.down('.fav_count').update('<span class="favorite_number">' + number + ' </span>' + numberMessage + '</div>');
}

var changeCount = function(type, id, op)
{
	base = $('fav_' + type + '_' + id);

	var favNum = base.down('.favorite_number');
	if (favNum != null)
	{
		var count = parseInt(favNum.innerHTML);
		if (isNaN(count))
			count = 0;
		var delta = 1;
		if (op == 'del')
			delta = -1;
		setCount(type, id, parseInt(count) + delta);
	}
}

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);
					changeCount(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 toggleFavorite = function(link, type, id, addtext, removetext)
{
    if(!processingFavorites)
    {
        processingFavorites = true;
        
        link = $(link)
        
        var op = 'add';
        var img = link.down('img'); 
        
        if(img.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();
        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')
                        {
                            img.removeClassName("addfav");
                            img.addClassName("removefav");
                            img.src = '/cognoti_theme/img/cte/favorite_star.png';
                            var text = "Remove From Favorites";
                            img.alt = text;
                            link.title = text;
							link.down('span').innerHTML = removetext;
                        }
                        else if(op == 'del')
                        {
                            img.addClassName("addfav");
                            img.removeClassName("removefav");
                            img.src = '/cognoti_theme/img/cte/favorite_star_gray.png';
                            var text = "Add to Favorites";
                            img.alt = text;
                            link.title = text;
							link.down('span').innerHTML = addtext;
                        }
                    }
                    else
                    {
                        var message = root.getElementsByTagName("message")[0].childNodes[0].nodeValue;
                        
                        popupBubble(img, message);
                        //do nothing for now... should probably alert user though    
                    }
                    
                    processingFavorites = false;    
                },
                onComplete: function()
                {
                    effect = null;
                    processingFavorites = false;    
                }
            });
    }
    
    return false;
}


var toggleWatching = function(link, type, id, addtext, removetext)
{
    if(!processingWatch)
    {
        processingWatch = true;
        
        link = $(link)
        
        var op = 'add';
        var img = link.down('img'); 
        
        if(img.hasClassName("removewatch"))
        {
            op = 'del';        
        }
        
        
        var url = '/cognoti/helper/watchlist.nn';
        var params = { id: id, type: type, op: op };
        
    
        var effect = new Object();
        pulseEffect = function()
        {
            if(effect != null)
            {
                effect = new Effect.Pulsate(img, {pulses: 2, duration: 1.0, afterFinish: pulseEffect});
            }
                 
        };
        
        pulseEffect(); 
        new Ajax.Request(url, 
            {
                parameters: params,
                method: 'post',
                onSuccess: function(transport)
                {
                    var root = transport.responseXML.documentElement;
                    var status = root.getAttribute("status");
                    
                    effect = null;
                    
                    if(status == "success")
                    {
                        if(op == 'add')
                        {
                            img.removeClassName("addwatch");
                            img.addClassName("removewatch");
                            img.src = '/cognoti_theme/img/cte/watch.png';
                            var text = "Remove From Watch List";
                            img.alt = text;
                            link.title = text;
							link.down('span').innerHTML = removetext;
                        }
                        else if(op == 'del')
                        {
                            img.addClassName("addwatch");
                            img.removeClassName("removewatch");
                            img.src='/cognoti_theme/img/cte/watch_closed_gray.png';
                            var text = "Add to Watch List";
                            img.alt = text;
                            link.title = text;
							link.down('span').innerHTML = addtext;
                        }
                    }
                    else
                    {
                        var message = root.getElementsByTagName("message")[0].childNodes[0].nodeValue;
                        
                        popupBubble(img, message);
                        //do nothing for now... should probably alert user though    
                    }
                    
                    processingWatch = false;    
                },
                onComplete: function()
                {
                    effect = null;
                    processingWatch = 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)
{
	target = $(target);

    popupOptions = Object.extend({
        right: false,
        fadeInSpeed: 0.5,
        fadeOutSpeed: 1.0,
        bubbleStyle: null,
        relativePlacement: true,
        relativePlacementElem: null,
        above: true
            
    }, popupOptions || {});
	
	var alreadyexists = target.getOffsetParent().up().down('.popupFlag');
	if (alreadyexists != null)
	{
		alreadyexists.close();
		return;
	}
	
    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)
{
    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(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({
    
    register: function(rotator, options)
    {
        var r = $(rotator);   
        if(r)
        {
            this.registered = this.registered || {};
            this.registered[rotator] = r;
        
            this._setupFeaturedRotator(r, options);
        }
    },
    
    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        
                
        }, options || {});
        
        r.list = r.down('.list');
        r.list.setStyle({height: r.list.getHeight()+'px'});
        r.featured = r.down('.recommended');
        r.featured.container = r.featured.down('.recommendedcontainer');
        r.featured.info = r.featured.down('.info');
        r.timer = setTimeout(function() { fr._timer(r); }, r.options.rotateFreq*1000);
    },
    
    _timer: function(r)
    {
        var fr = this;
        this._doRotate(r);    
        r.timer = setTimeout(function() { fr._timer(r); }, r.options.rotateFreq*1000);
    },

    _doRotate: function(r)
    {
        if(r.rotating) { return; }
        
        r.rotating = true;
        var current = r.list.down('li.active');
        var next = current.next('li');
        
        if(!next)
        {
            next = r.list.down('li');    
        }
        
        var title = next.down('.title').innerHTML;
        var extra = next.down('.description').innerHTML;
        var imgsrc = next.down('.imgsrc').innerHTML;
        var targeturl = next.down('a.targeturl').href;
        
        this._doFeaturedSwitch(r, title, extra, imgsrc, targeturl);
        this._doListSwitch(r, current, next);
    },
    
    _doListSwitch: function(r, oldLi, newLi)
    {
        oldLi.removeClassName('active');
        newLi.addClassName('active');
        
        /* new Effect.Fade(newLi, {afterFinish: function() { r.list.insert({bottom: newLi}); new Effect.Appear(oldLi); }}); */
        
    },
    
    _doFeaturedSwitch: function(r, title, extra, imgsrc, targeturl)
    {
        var fr = this;
        var h4 = r.featured.info.down('h4'); 
        var p = r.featured.info.down('p');
        var img = r.featured.down('img');
        
        var container = r.down('.rotatinginfo');
        
        r.featured.container.select('a').each(function(a)
            {
                a.setAttribute('href', targeturl);    
            });
        
        new Effect.Fade(container, 
            { 
                to: 0.01, 
                afterFinish: function()
                {
                    h4.update(title);
                    p.update(extra);
                    img.src = imgsrc;
                    img.alt = title;
                    new Effect.Appear(container, { afterFinish: function() { r.rotating = false; }});
                }
            });
        
    },
    
    _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 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));
                    
                    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.down('input[type="submit"]'), message);
                //do nothing for now... should probably alert user though    
            }
            
        }
    });
    
    return false;    
}


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

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.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(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, modalbox)
{
    tabs = $(tabs);
    targettab = $(targettab);
    tabsheets = $(tabsheets);
    targettabsheet = $(targettabsheet);
    
    tabs.select('li').invoke('removeClassName', 'current');
    targettab.addClassName('current');
    
    tabsheets.select('.tabsheet').invoke('hide');
    targettabsheet.show();
    
    if(modalbox)
    {
        Modalbox.resizeToContent();
    }
    
    return false;
}

var 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
    {
        o['nodename'] = node.nodeName;
        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,
    loadedJS: {},
    loadedCSS: {},
    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(popupOptions || {}, { bubbleStyle: { width: '450px' } })
            );
        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: 'opaque',
            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: 'opaque'
                
        });
        
        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 });
        }
    },
    loadCSS: function(cssfile)
    {
        var head = $$('head')[0];
        if(!head)
        {
            head = $$('body')[0];    
        }
        
        if(!head)
        {
            return;    
        }
        
        if(head.down('link[href="'+cssfile+'"]'))
        {
            return;
        }
        
        head.insert(new Element('link', { 'type': 'text/css', 'rel': 'stylesheet', 'href': cssfile}));
    },
    loadJS: function(jsfile, callback)
    {
        var body = $$('body')[0];
        
        if(!body)
        {
            return;    
        }
        
        if(Cognoti.loadedJS[jsfile])
        {
            if(callback)
            {
                callback();
            }
            return;    
        }
        
        Cognoti.loadedJS[jsfile] = true;
        
        body.insert(new Element('script', { 'type': 'text/javascript', 'src': jsfile }));
        
        if(callback)
        {
            callback.delay(.5);    
        }
        
    },
    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: 'opaque'
        });
        
        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;
    },
    wordBreak: function(text, length)
    {
        length = length || 25;
        
        var split = text.split(' ');
        
        var ret = '';
        
        var len = split.length;
        
        for(var i = 0; i < len; i++)
        {
            var s = split[i];
            
            if(s.length > length)
            {
                var ss = s.substr(0, length);
                
                ret = ret + ss + '&#8203;' + Cognoti.wordBreak(s.substring(length), length);
            }
            else
            {
                ret = ret + s;
            }
            
            ret = ret +' ';    
        }
        
        return ret;
    },
    
    Form: {
        CHECKED: new Object(),
        build: function(elements, defaultValues, formType)
        {
            if(!Object.isArray(elements))
            {
                return null;    
            }
            
            defaultValues = defaultValues || {};
            
            var form = new Element(formType || 'form');
            
            elements.each(function(e) {
                try
                {
                    if(!e.add)
                    {
                        e = Object.extend(new Cognoti.Form[e.formType], e);
                    }
                    
                    e.add(form, defaultValues[e.name]);
                    form.insertBreak();
                }
                catch(ex) { Cognoti.log(ex); }
            });
            
            return form;
        },
        Input: Class.create({
            initialize: function(name, label, type, size, options)
            {
                this.name = name;
                this.label = label;
                this.type = type;
                this.options = options;
                this.size = size || 15;
                this.formType = 'Input';
            },
            add: function(element, value)
            {
                var input = new Element('input', { 'type': this.type, 'name': this.name, 'size': this.size });
                
                if(value === Cognoti.Form.CHECKED)
                {
                    input.writeAttribute('checked', 'checked');
                }
                else if(value)
                {
                    input.setValue(value);    
                }
                
                
                $(element).appendFormElement(this.label, input, this.options);    
            }
        }),
        Select: Class.create({
            initialize: function(name, label, selectOptions, options)
            {
                this.name = name;
                this.label = label;
                this.selectOptions = selectOptions;
                this.options = options;
                this.formType = 'Select';
            },
            add: function(element, value)
            {
                var select = Cognoti.makeSelect(this.name, this.selectOptions, this.options);
                
                if(value)
                {
                    select.setValue(value);
                }
                
                $(element).appendFormElement(this.label, select, this.options);    
            }
        }) 
    },
    createLoginWindow: function(params)
    {
        params = Object.extend({
            forceLogout: false,
            callback: Prototype.emptyFunction
        }, params || {});
        
        
        var window = new Element('iframe', { 'src': '/cognoti/doc/blank.htm' });
        
    }
});

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; });

