
function initQuotable() 
{
    $$('a').each(function(s) {
        if (s.getAttribute('rel') != 'quote') return;
        
        // Add onclick event handler to quote the message
        s.observe('click', function(event) {
            try {
                var container = event.findElement('div.post');
                var post = container.down('div.body');
                var author = container.down('div.author');
                var quote = post.cloneNode(true);
                
                // Remove all existing block quotes from quoted post
                quote.select('blockquote[cite=*]').invoke('remove');
                
                // Get editor
                var editor = FCKeditorAPI.GetInstance('post');
                if (typeof(editor) == 'undefined') return;
    
                // Build quote template
                var blockquote = '<blockquote cite="#{url}">';
                blockquote += '<div class="author">Quoting ';
                blockquote += '<a href="#{profile}" rel="profile">';
                blockquote += '#{author}';
                blockquote += '</a>';
                blockquote += ':</div>';
                blockquote += '<div class="quote">';
                blockquote += '#{quote}';
                blockquote += '</div>';
                blockquote += '</blockquote><p></p>';
                
                var template = new Template(blockquote);
                
                // Assign values to template
                var show = {
                    url:        location.href,
                    author:     author.innerHTML,
                    profile:    author.readAttribute('href'),
                    quote:      quote.innerHTML
                };
                
                // Insert quote and scroll to editor
                var quoted = template.evaluate(show);
                editor.InsertHtml(quoted);
                $("reply").scrollTo();
                editor.Focus();
                event.stop();
            } catch (e) {
                // Ignore
            }
        });
    });
}


function initSummaryWindow()
{
    var element,
        titleTemplate,
        contentTemplate,
        title,
        content;
        
    contentTemplate = new Template('#{post}');
    titleTemplate = new Template('<h3>#{title}</h3><div class="author">#{author}</div><div class="date">#{date}</div>');
    
    var makeSummary = function(row) {
        element = row.down('td.subject');
        
        content = contentTemplate.evaluate({
            post:           row.down('.summary').innerHTML.unescapeHTML().stripScripts()
        });
        
        title = titleTemplate.evaluate({
            title:          row.down('.subject a').innerHTML.stripScripts(),
            author:         row.down('td.created-by a').innerHTML.stripScripts(),
            date:           row.down('.date').innerHTML.stripScripts()
        });
        
        var tooltip = new RT.Tooltip(element, content, {
            title:              title,
            placement:          {
                element:            'topLeft',
                tooltip:            'topLeft'
            },
            closeButton:        '/images/main/close-blue.png',
            closeButtonHover:   '/images/main/close-blue.png',
            width:              360,
            height:             200,
            offsetLeft:         260,
            delay:              false,
            beforeOpen:         function() {
                if (!$('summaryToggler') || !$('summaryToggler').checked) throw $break;
            },
            afterUserClose:     function() {
                if ($('summaryToggler')) $('summaryToggler').checked = false;
            }
        });
    }
    
    $$('table.threads tbody tr').each(makeSummary);
    
    if ($('summary-toggler-container')) {
        $('summary-toggler-container').update('<div id="summary-toggler"><label id="summary-toggler-label" class="tooltipable"><input type="checkbox" id="summaryToggler" name="summaryToggler" />Show Summaries<img src="/images/icons/help.png" class="icon" alt="" /></label></div>');
        //hacked Brian Lange 1-22-09 so default is unchecked 
        //$('summaryToggler').checked = Cookie.get('disable_groups_summary') == 'true' ? false : true;
        $('summaryToggler').checked = false;
        handleChangeSummmaryCheckbox = function()
        {
            Cookie.set('disable_groups_summary', $('summaryToggler').checked ? 'false' : 'true');
        }
        
        $('summaryToggler').observe('change', handleChangeSummmaryCheckbox);
        $('summaryToggler').observe('click', handleChangeSummmaryCheckbox);
        
        if ($('summary-toggler-label')) {
            var tooltipMessage = 'Enabling summaries will display a preview of the first post in the discussion when the cursor is placed over the subject line.';

            new RT.Tooltip($('summary-toggler-label'), tooltipMessage, {
                width:          280,
                placement:      {
                    element:        'topLeft',
                    tooltip:        'bottomRight'
                },
                stem:           'bottomRight',
                offsetTop:      -18,
                offsetLeft:     4
            });
        }
    }
}


function initLegend()
{
    if (!$('legend')) return;
    var legend = $('legend');
    
    var threads = $$('.threads')[0];
    if (!threads) return;
    
    legend.observe('click', function(event) {
        legend.toggleClassName('show');
        Event.stop(event);
    });
    
    $(document.body).observe('click', function(event) {
        if (legend.hasClassName('show')) legend.removeClassName('show');
    });
}



function initDraftable()
{

}

function initInviteFriendsLinks()
{
    var submitForm = function(event)
    {
        var button = Event.element(event);
        Event.stop(event);
        
        if (!button
        || button.getAttribute('type') != 'submit' 
        || button.getAttribute('name') != 'confirm') {
            // Close ajax window.
            Control.Window.windows.invoke('close');
            return;
        }
        
        // Post form via ajax and read response via json
        //var form = $('send-invite-confirmation');
        var form = Event.findElement(event, 'form');
        postData = form.serialize();
        postData += '&format=json';
        //alert(postData); return;
        
        var handleInviteSuccess = function(t)
        {
            //alert('Response: ' + t.responseJSON);
            response = t.responseJSON;
            if (response.success) {
                var message = response.member_fullname + ' has been invited to "' + response.group_title + '"!';
                //alert(message);
                var myTemplate = new Template('<h3>#{message}</h3><div style="text-align: center; padding-top: 1em;"><input class="ok_button" type="button" value="OK" /></div>');
                var show = {message: message};
                
                var template = myTemplate.evaluate(show);
                
                $$('.ajax-window').invoke('update', template);
                
                $$('.ok_button').invoke('observe', 'click', function(event) {
                    Control.Window.windows.invoke('close');
                    $$('.ajax-window').invoke('update');
                });
                
                // Replace link with span to prevent double-invites
                var span = '<span class="action pending">Invitation Sent</span>';
                $$('a#invite_' + response.member_id).invoke('replace', span);
            } else {
                alert('Error: ' + response.error);
                Control.Window.windows.invoke('close');
            }
        }
        
        var handleInviteFailure = function()
        {
            alert('There was an error while processing your request. Please try again later.');
            Control.Window.windows.invoke('close');
        }
        
        var url = form.getAttribute('action');
        
        new Ajax.Request(url, {
            method: 'post',
            postBody: postData,
            onSuccess: handleInviteSuccess,
            onFailure: handleInviteFailure
        });

        // Show loading animation
        var loading = '<div style="text-align: center;">';
        loading += '<img src="http://www.realtown.com/img/main/rt_loading2.gif" alt="Loading, please wait..." />';
        loading += '<div id="divLoadingText">Sending invitation...</div>';
        loading += '</div>';
        $$('.ajax-window').invoke('update', loading);
    }
    
    var onRemoteContentLoaded = function() 
    {
        $$('.ajax-window form input[type=submit]').invoke('observe', 'click', submitForm);
    }
    
    
    $$('.invite-friends a.invite').each(function(link) {
        link.setAttribute('href', link.getAttribute('href') + '?format=html');
        var ajax = new Control.Modal(link, {
            overlayOpacity: 0.5,
            className: 'ajax-window',
            width: 550,
            fade: true,
            fadeDuration: 0.25
        });
        ajax.observe('onRemoteContentLoaded', onRemoteContentLoaded);
    });
}



    
function initRaters() {
    if (!RT.Rater) return;
    
    var onUpdateSuccess = function(t)
    {
        var json = t.responseText.evalJSON(true);
        
        if (json.error) {
            alert('Error: ' + json.error);
            return;
        }
        
        $('post' + json.post_id).down('.post_rating').update(json.newRating);
        $('post' + json.post_id).down('.post_user_rating').update(json.userRating);
    }
    
    var initRater = function(post)
    {
        var id = post.identify();
        var container = new Element('div', {'class' : 'post_rater_container'});
        post.down('.info .post_rater').update(container);
        new RT.Rater(container, {
            value:          $F(id + '_rating'),
            locked:         $F(id + '_ratable') == 1 ? false : true,
            updateUrl:      $F(id + '_ajax'),
            lockOnClick:    false,
            onSuccess:      onUpdateSuccess,
            classes:        {
                container:      'rater_container_house',
                off:            'rater_off',
                on:             'rater_on',
                selected:       'rater_selected'
            }
        });
        
        // Tooltip for Rater
        if ($F(id + '_ratable') == 1) {
            new RT.Tooltip(container, 'Click to rate this post', {
                placement:      {
                    element:        'topLeft',
                    tooltip:        'bottomLeft'
                },
                offsetTop:      -18,
                offsetLeft:     72,
                stem:           'bottomLeft'
            });
        }
    }
    
    $$('div.thread div.post').each(initRater);
}


//Event.observe(window, 'load', function(event)
document.observe('dom:loaded', function(event)
{
    if ($('selectAllGroups')) {
        $('selectAllGroups').disabled = false;
        if ($('selectAllGroups').hasClassName('hidden')) $('selectAllGroups').removeClassName('hidden');
        $('selectAllGroups').observe('click', function()
        {
            $$('table.invite tbody input[type=checkbox]').each(function(cb)
            {
                if (cb.disabled) return;
                cb.checked = $('selectAllGroups').checked;
            });
        });
    }
    
    // Auto-set URL for group forms
    if ($('new-group') && $('name') && $('url')) {
        var updateGroupUrl = function(event) {
            $('url').value = $('name').value.replace(/[^a-zA-Z0-9-]+/g, '-').replace(/^\-+/, '').replace(/\-+$/, '').toLowerCase();
        };
        
        var generate = document.createElement('input');
        generate.setAttribute('type', 'button');
        generate.setAttribute('value', 'Suggest URL');
        $('url').insert({after: generate});
        $(generate).observe('click', updateGroupUrl);
        
        Event.observe($('name'), 'change', updateGroupUrl);
        Event.observe($('name'), 'keydown', updateGroupUrl);
        Event.observe($('name'), 'keyup', updateGroupUrl);
    }
    
    // Make quotable links easier to work with.
    try {
        initQuotable();
    } catch(e) {
        // Ignore
    }
    
    // Summary window
    try {
        initSummaryWindow();
    } catch (e) {
        // Ignore
    }
    
    // Allow drafts to be saved
    try {
        initDraftable();
    } catch (e) {
        // Ignore
    }
    
    // Legend popup
    try {
        initLegend();
    } catch (e) {
        // Ignore
    }
    
    // Ajax-powered Invite Friends Links
    try {
        initInviteFriendsLinks();
    } catch (e) {
        // Ignore
    }
    
    // Ajax-powered raters for the posts
    try {
        initRaters();
    } catch (e) {
        // Ignore
    }
    
    
    //Disable submit button after click
    
    $$('form').each(function(form) {
        form.observe('submit', function() {
            $$('input[type="submit"]').invoke('disable');
            $$('form').observe('submit', function(evt) { // once any form is submitted
                evt.stop(); // prevent any other form submission
            } );
        } );
    }); 
    
    function handleResponse(transport) {
        alert('Successfully sent welcome email');
        
    }
    
    $$('.welcomeEmail').each(function(e) {
    
        e.observe('click', function(e) {
            
            var link = e.element();
            var myAjax = new Ajax.Request('/groups/subscription/send-welcome-letter',
                {method: 'get', parameters: {group: link.name,
                             user: link.id},
                 onComplete: handleResponse});
        });
        
    });
    

});



