
$(document).ready(function() {

    $('#global-search-form').submit(function(){
        var val = $('#global-search-form input[name=free_text]').val();
        $( '#global-search-form input[name=qstream]' ).val(val);        
    });

    $('#global-search-type').change(function(){
        var val = $(this).val();
        if( val == '' )
        {
            val = '/stream';
        }
        else
        {
            val += '/search';
        }
        $('#global-search-form').attr('action',val );
    });
    
    if( $( ".tease-button" ).length )
    {
        $('.tease-button a').click(function(e) {
            e.preventDefault();
            if( $(this).parent().parent().children('.tease-content').length )
            {
                $(this).parent().parent().children('.tease-content').addClass('tease-content-show');
                $(this).parent().parent().children('.tease-content').removeClass('tease-content');
                $(this).html('show less');
            }
            else
            {
                $(this).parent().parent().children('.tease-content-show').addClass('tease-content');
                $(this).parent().parent().children('.tease-content-show').removeClass('tease-content-show');
                $(this).html('show more');
            }
        });
    }

/*
    $(".button-link").click(function() {
        $(this).parent().children('.button-link-list').toggle();
        $(this).toggleClass('menu-open');
    });
        
    $(".button-link-list").mouseup(function() {
        return false
    });

    $(document).mouseup(function(e) {
        if($(e.target).parent('a.button-link').length==0) {
            $(e.target).parent('a.button-link').removeClass("menu-open");
            $(e.target).parent('a.button-link').children('.button-link-list').hide();
        }
    });
  */      
//    $('.input-hint').tipsy({gravity: 'w'});   

/*
    if( $( ".bible-verse-link" ).length )
    {
        $('.bible-verse-link').live( 'hover', function(e) {
            var me = $(this);
            $.ajax({
                 url: '/entity/api/search'
                ,data: 'entity_type=21&free_text=' + me.attr('title')
                ,success: function(result) {
                    me.attr( 'title', 'boogers' );
                }
            });
        });
        $('.bible-verse-link').tipsy({gravity: 'w' });
//        $('.bible-verse-link').tipsy({gravity: 'w', live : true});
    }
*/

/*
    if( $( '.hover-show' ).length )
    {
        $('.hover-show').parent().hover(function(e){
            e.preventDefault();
            $('.hover-show', $(this) ).show();
        },function(e){
            e.preventDefault();
            $('.hover-show', $(this) ).hide();
        });
    }
*/

    if( $( '.dialogue-link-opener' ).length )
    {
        $('.dialogue-link-opener').click(function(e){
            e.preventDefault();

            var id_attr      = $(this).attr( 'data-dialogue-selector' );

            var el_dialog = $(id_attr);
            $('.input-date', el_dialog).datepicker('disable');
            $('.input-date-time', el_dialog).blur();
            el_dialog.dialog('open'); 
            $('.input-date-time', el_dialog).blur();
            $('.input-date', el_dialog).datepicker('enable');

            var copy_attr      = $(this).attr( 'data-copy-fields' );

            if( copy_attr )
            {
                var json_fields = JSON.parse(copy_attr);
                for(var f in json_fields )
                {
                    var v = json_fields[f];
                    $('input[name="'+f+'"]', el_dialog).val(v);
                }
            }

            return false;
        });
    }

    if( $( ".remove-item" ).length )
    {
        $('.remove-item').click(function(e) {
            e.preventDefault();
            var response = confirm ('Are you sure you want to remove this?');
            if( response )
            {
                $.ajax({ url: $(this).attr('href') });
                $(this).parent().parent().fadeOut('fast', 'linear');
            }    
        });
    }

    if( $( ".remove-entity-post" ).length )
    {
        $('.remove-entity-post').click(function(e) {
            e.preventDefault();
            var response = confirm ('Are you sure you want to remove this post?');
            if( response )
            {
                $.ajax({ url: $(this).attr('href') });
                $(this).parent().parent().parent().fadeOut('slow', 'linear');
            }
        });
    }

    $('.input-prefill').focus(function() {
        $(this).css('color','#000');
        if( $(this).val().indexOf('keywords') != -1 || $(this).val().indexOf('search') != -1 || $(this).val().indexOf('Enter') != -1 )
        {
            $(this).val('');
        }
    });


    if( $('#stream-filter').length )
    {
        $('#stream-filter').multiselect({
            header : false
            , selectedList: 10
            , noneSelectedText : 'Filter'
            , height: 250
            , minWidth: 170
    //        , selectedText: function(numChecked, numTotal, checkedItems){ return numChecked + ' of ' + numTotal + ' checked'; }
            , click: function(e,ui){ 
                if( $(this).multiselect('widget').find('input:checked').length > 10 ){ return false; } 
                $('#search_stream_page').val( 1 );
                if( ui.value == 'network' && ui.checked )
                {
                    $(this).multiselect('widget').find("input[value=public]").each(function(i,el) {
                        if( $(el).attr('checked') )
                        {
                            $(el).attr('checked', false);
                        }
                    });
                    $(this).multiselect('widget').find("input[value=me]").each(function(i,el) {
                        if( $(el).attr('checked') )
                        {
                            $(el).attr('checked', false);
                        }
                    });
                }
                else if( ui.value == 'public' && ui.checked )
                {
                    $(this).multiselect('widget').find("input[value=network]").each(function(i,el) {
                        if( $(el).attr('checked') )
                        {
                            $(el).attr('checked', false);
                        }
                    });
                    $(this).multiselect('widget').find("input[value=me]").each(function(i,el) {
                        if( $(el).attr('checked') )
                        {
                            $(el).attr('checked', false);
                        }
                    });
                }    
                else if( ui.value == 'me' && ui.checked )
                {
                    $(this).multiselect('widget').find("input[value=network]").each(function(i,el) {
                        if( $(el).attr('checked') )
                        {
                            $(el).attr('checked', false);
                        }
                    });
                    $(this).multiselect('widget').find("input[value=public]").each(function(i,el) {
                        if( $(el).attr('checked') )
                        {
                            $(el).attr('checked', false);
                        }
                    });
                }    
            }
            , close: function(){
            /*
                $('.stream-feed').hide('blind', 'fast')    
                $('#search_stream_page').val( 1 );
                var search_form = $('.stream-search-form');
                $.ajax({
                     url: '/entity/api/search'
                    ,data: search_form.serialize()
                    ,success: handleStreamResults
                });
                */

                return false;                    
            }

        });


        $('.stream-filter-field').click( function() {
            $('.stream-filter-field').removeClass('active');
            $(this).addClass('active');

            $('.stream-feed').hide('blind', 'fast')    
            $('#search_stream_page').val( 1 );
            

            var type_map    = { 'Everything' : '', 'Events' : 16, 'Prayers' : 57, 'Facebook + Twitter' : 56, 'Blogs' : 24, 'Sermons' : 50, 'Stories' : 64, 'Needs' : 52, 'Projects' : 42, 'Questions' : 17 };
            var label       = $(this).html();
            var type        = type_map[label];

            $('#stream-filter').multiselect('widget').find(":checkbox").each(function(i,el) {
                var val = $(el).val();
                if( val != 'public' && val != 'network' && val != 'me')
                {
                    if( val == type )
                    {
                        if( $(el).attr('checked') == false )
                        {
                            $(el).attr('checked', true);
                        }
                    }
                    else
                    {                
                        $(el).attr('checked', false);
                    }
                }
            });

            $('#stream-filter').multiselect('update');
            
            var search_form = $('.stream-search-form');
            var params      = search_form.serialize();
            params          = params.replace( /multiselect_stream-filter/gi, 'multiselect_stream-filter[]' );
            $.ajax({
                 url: '/entity/api/search'
                ,data: params
                ,success: handleStreamResults
            });

            return false;            
        });
        

        $('.hide').click(function() {
          $(this).parent().fadeOut('slow', 'linear');
        });


        
    
/*
    $( '.share-post-dialog' ).dialog({
         autoOpen: false
        ,show: 'fade'
        ,hide: 'fade'
        ,width: 500
        ,height: 200
        ,autoResize: true
        ,resize: 'auto'

    });

    $( '.share-post-button a' ).click(function() {
        $('.share-post-dialog').dialog('option', 'position', [$(this).offset().left, $(this).offset().top + 15]);
        $( '.share-post-dialog' ).dialog( 'open' );

        return false;
    });
*/

        $( '.share-post-button' ).click(function() {
        return;
        /*
            var html  = $('.share-button-current').html();
            var label = $(this).html();
            var label_lc = label.toLowerCase();

            if( html.indexOf('<b>') < 0 )
            {
                $('.share-post-dialog-'+label_lc ).show();
                $('.share-post-dialog').show('fast');
                $('.share-button-current').html( '<b>Post a '+label+'</b>' );
                $('.share-button-current').data( 'label', label_lc );
                $('.share-button-list').hide();
            }
    */
            var label = $(this).html();
            var label_lc = label.toLowerCase().replace(' ', '-' );
            var old_label = $('.share-post-dialog').data( 'label' ); 

            if( old_label )
            {
                $('.share-post-dialog-'+old_label).hide('blind', 'fast'); 
            }
            else
            {
                $('.share-post-dialog').show('blind', 'fast');
            }

            $('.share-post-dialog-'+label_lc ).show('blind', 'fast');
            $('.share-post-dialog').data( 'label', label_lc ); 

            $('.share-button-list').hide();

            return false;
        });

        $('.close-post-dialog').click(function() {
            var label = $('.share-post-dialog').data( 'label' ); 
            $('.share-post-dialog-'+label).hide('blind', 'fast'); 
            $('.share-post-dialog').hide('blind', 'fast');
            $('.share-post-dialog').data( 'label', '' ); 
            $('.share-button-list').show();
        });

        $('.stream-search-form').submit(function(e) {
            e.preventDefault();
            $('.stream-info-message').show().html('<p><img src="/static/img/ajax-loader-blue.gif" /><span>processing search, please wait...</span></p>');
            var search_form = $(this);
            var params      = search_form.serialize();
            params          = params.replace( /multiselect_stream-filter/gi, 'multiselect_stream-filter[]' );
            $.ajax({
                 url: '/entity/api/search'
                ,data: params
                ,success: handleStreamResults
            });
        });
        
        $('.reset-stream').click(function(e) {
            e.preventDefault();

            $('#stream-filter').multiselect('widget').find(":checkbox").each(function(i,el) {
                var val = $(el).val();
                if( val != 'public' && val != 'network'  && val != 'me')
                {
                    $(el).attr('checked', false );
                }
            });
            $('#stream-filter').multiselect('update');
            $('.search-stream-input input').val('');
            $('.stream-tabs ul li a').removeClass('active');
            $('.stream-tabs ul li:first a').addClass('active');

            var search_form = $('.stream-search-form');
            var params      = search_form.serialize();
            params          = params.replace( /multiselect_stream-filter/gi, 'multiselect_stream-filter[]' );
            $.ajax({
                 url: '/entity/api/search'
                ,data: params
                ,success: handleStreamResults
            });

            return false;
        });
    }
    
    

    if( $( '.stream-filter-menu' ).length )
    {
        
        if( $( '.stream-filter-menu-dialog' ).length )
        {
            $( '.stream-filter-menu-dialog' ).dialog({
                 autoOpen: false
                ,show: 'fade'
                ,hide: 'fade'
                ,width: 600
                ,autoResize: true
                ,resize: 'auto'
                ,modal: true
                ,zIndex: 2002
                ,title : 'Customize News Feed'

            });
        }

        $( '.stream-filter-menu a' ).click(function() {
            $( '.stream-filter-menu-dialog' ).dialog( 'open' );
            return false;
        });
    }
    
    if( $( '.form-customize-stream-filter' ).length )
    {
        $('.form-customize-stream-filter').live( 'submit', function(e) {
            e.preventDefault();
            var search_form = $(this);
            var params      = search_form.serialize();
            $.ajax({
                 url: '/entity/api/post'
                ,data: params
                , success : function() {
                    location.reload();
                    /*
                    setTimeout( function() {
                    var search_form = $('.stream-search-form');
                    var params      = search_form.serialize();
                    params          = params.replace( /multiselect_stream-filter/gi, 'multiselect_stream-filter[]' );
                    $.ajax({
                         url: '/entity/api/search'
                        ,data: params
                        ,success: handleStreamResults
                    }); }, 200 );
                    */
                }
            });
        });
    }

    attachStreamEvents();


    if( $( '.show-more-stream-posts' ).length )
    {
        $('.show-more-stream-posts').click(function(e) {
            $('#search_stream_page').val( ($('#search_stream_page').val() * 1) + 1 );
            
            $('.show-more-stream-posts').html('Loading...');

            var search_form = $('.stream-search-form');
            var params      = search_form.serialize();
            params          = params.replace( /multiselect_stream-filter/gi, 'multiselect_stream-filter[]' );
            $.ajax({
                 url: '/entity/api/search'
                ,data: params
                ,success: function(data) {
                    var html = data;
                                
                    if( html == '' )
                    {
                        html = '<div class="stream-no-results">End of the line, no more posts</div>';
                        $('.more-stream-button').hide();
                        setTimeout( function() { $('.stream-no-results').hide('blind', 'slow'); }, 3000 );
                        $('#search_stream_page').val( 1 );    
                    }
                    else
                    {
                        attachStreamEvents();
                        $('.stream-no-results').hide();
                        $('.more-stream-button').show();
                    }
                    
                    $('.show-more-stream-posts').html('Show more posts');

                    var stream_page_id = 'more-stream-page-'+$('#search_stream_page').val();
                    $('.stream-feed').append('<div id="'+stream_page_id+'" class="more-posts-wrapper" style="display:none;">'+html+'</div>');
                    $('.stream-feed').children(':last').show('blind', 'slow');    
                    attachToolTips('#'+stream_page_id+' div.post div.tools');
                }
            });
            return false;
        });
    }

    
    if( $( "#commentform" ).length )
    {
        $('#commentform').submit(function(e) {
            e.preventDefault();
            $.ajax({
                 url: '/entity/api/post'
                ,data: $(this).serialize()
                ,success: function(data) {
                    data        = $.parseJSON(data);
                    
                    var post_access  = data.allow_comment_posts;
                    var admin_access = data.has_admin_access; 

                    var comment = data['comment'];
                    if( comment['website'] == '' )
                    {
                        comment['website'] = '#nosite';
                    }

                    var message = 'Your comment has been posted.';
                    if( comment['publish_status'] == 1 )
                    {
                        message += ' Moderation is required before it appears.';
                    }
                    var html    =    '<a name="#comment-'+comment['entityid']+'"></a><div class="success-message">'+message+'</div><div class="flag"><a href="#flag">Flag</a></div><p>'+comment['body']+'</p>'
                                    +'<div class="credits">Posted by <a href="'+comment['website']+'">'+comment['person_name']+'</a> on '+comment['date_label']+'</div>'
                                    +'<div class="clearfloat"></div>';
                                    
                    $('#newcomment').html(html);
                    $('#comments-label').hide('blind', 'fast');
                    $('#newcomment').show('blind', 'slow');
                    $('#post-comment-form').hide();
                    
                    var target_offset = $("#newcomment").offset();
                    var target_top = target_offset.top;
                   $('html, body').animate({scrollTop:target_top}, 500);

                 }
            });

            return false;
        });

        $('.remove-comment').click(function(e) {
            e.preventDefault();
            $.ajax({ url: $(this).attr('href') });

            $(this).parent().parent().fadeOut('slow', 'linear');


        });
        
        $('.approve-comment').click(function(e) {
            e.preventDefault();
            $.ajax({ url: $(this).attr('href') });
            $(this).parent().parent().removeClass('comment-pending');
            $(this).fadeOut('fast', 'linear');
    
        });
    }


    if( $( ".datefield" ).length )
    {
        $( ".datefield" ).datepicker({
            changeMonth: true,
            changeYear: true
        });
        $( ".datefield" ).datepicker( "option", "showAnim", 'slideDown' );
    }
    // share-button-list

    //$('.elastic-textarea').elastic();

    //attachToolTips('div.post div.tools');

    
    if( $('.share-post-form').length )
    {
        $('.share-post-form').submit(function(e) {
        
            e.preventDefault();
            var post_form = $(this);
            $.ajax({
                 url: '/entity/api/post'
                ,data: post_form.serialize()
                ,success: function(data) {
                
                var fields   = post_form.serializeArray();
                $.each(fields, function(i, field){
                    if( field.name != 'save' && field.name != 'entity_type' )
                    {
                        $(':input[name='+ field.name +']').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
                    }
                });

                var label = $('.share-post-dialog').data( 'label' ); 
                $('.share-post-dialog-'+label).hide('blind', 'fast'); 
                $('.share-post-dialog').hide('blind', 'fast');
                $('.share-post-dialog').data( 'label', '' ); 
                
                $('.share-button-list').show();

    //            $('.share-post-button a').html( $('.share-post-button a').data( 'show_html' ) );

    /*
                    var data     = { 'post' : { 'id' : '1'
                                                , 'title' : 'post title'
                                                , 'date_label' : 'Wed 10/29 @ 2pm'
                                                , 'entity_label' : 'Jeff Collier'
                                                , 'entity_url' : '/profile/view/123/jeff4e'
                                                , 'location_label' : 'Austin, TX' 
                                                , 'body' : input['body'] } 
                                    };
    */
                    setTimeout( function() {
                        var post     = $.parseJSON( data );
                        if( post )
                        {
                            post['body'] = (post['body_markup'] + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br/>$2');
                            var html     =  '<div class="post newpost" id="post'+post['entityid']+'"><div class="pad '+post['post_type']+'">'
                                            +'<div class="hd"><div class="tools"><div class="hide"><a title="Hide posts from this account" onclick="whatUp.hideStreamSource(\'hide'+post['entityid']+'\');return false;" id="hide'+post['entityid']+'" href="#hidepost" class="hidepost"><span>hide</span></a></div></div>'
                                            +'<a title="'+post['entity_label']+'" target="_blank" rel="nofollow" href="'+post['entity_url']+'">'+post['entity_label']+'</a><br/>'+post['date_label']+' in '+post['location_label']
                                            +'</div>'
                                            +'<div class="bd">'
                                            +'<div title="'+post['post_type']+' post" class="marker"><span>'+post['post_type']+'</span></div>'
                                            +'<div class="message"><a href="'+post['view_url']+'">'+post['label']+'</a><br/>'+post['body']+'</div>'
                                            +'</div>'
                                            +'</div></div>';

                            
                            $('.stream-feed').prepend(html);
                            $('.stream-feed').children(':first').show('blind', 'slow');        
                        }
                    }, 900 );
            } 
            });

            return false;
        });
    }
});

function attachToolTips(selctor)
{
    return ;
    $(selctor).qtip({ 
       position: { 
          corner: { 
             target: 'rightMiddle', 
             tooltip: 'leftMiddle' 
          } 
       } 
       ,show: {
            when: 'mouseover' // Show it on click...
            ,solo: true // ...and hide all others when its shown
         }
       ,hide: { delay : 1000, when : { event : 'inactive' } } // Hide it when inactive...
       ,style: { 
          border: { 
             width: 5, 
             radius: 10, 
             color: '#017DC3' 
          }, 
          background: '#ffffff', 
          color: '#000000', 
          padding: 10, 
          textAlign: 'left', 
          tip: true 
       } 
    });

}

function handleStreamResults(data)
{
    $('.stream-info-message').hide();
    var html = data;
    if( html == '' )
    {
        html = '<div class="stream-no-results">No posts found</div>';
        $('.more-stream-button').hide();
        setTimeout( function() { $('.stream-no-results').hide('blind', 'slow'); }, 5000 );
    }
    else
    {   
        attachStreamEvents();
        $('.stream-no-results').hide();
        $('.more-stream-button').show();
    }
    var stream_page_id = 'more-stream-page-'+$('#search_stream_page').val();
    $('.stream-feed').html(html);
    $('.stream-feed').show('blind', 'slow');
    $('#search_stream_page').val( 1 );    
    //                    attachToolTips('#'+stream_page_id+' div.post div.tools');
    
}

function attachStreamEvents()
{
    if( $( '.hide-stream-post' ).length )
    {
        $('.hide-stream-post').die('click');
        $('.hide-stream-post').live('click',function(e) {
            e.preventDefault();
            
            var response = confirm ('Are you sure you want to hide this post?');
            if( response )
            {
                $.ajax({
                     url: $(this).attr('href')
                });
                $(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().fadeOut('slow', 'linear');
            }
        });
    }

    if( $( '.hide-stream-entity' ).length )
    {
        $('.hide-stream-entity').die('click');
        $('.hide-stream-entity').live('click',function(e) {
            e.preventDefault();
            
            var response = confirm ('Are you sure you want to hide all posts from this user?');
            if( response )
            {
                $.ajax({
                     url: $(this).attr('href')
                });
                var postedby_id = $(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().attr('id');
                $('.' + postedby_id).fadeOut('slow','linear');
            }
        });
    }
    
    if( $( '.flag-stream-post' ).length )
    {
        $('.flag-stream-post').die('click');
        $('.flag-stream-post').live('click',function(e) {
            e.preventDefault();
            var response = confirm ('Are you sure you want to flag this post?');
            if( response )
            {
                $.ajax({
                     url: $(this).attr('href')
                });
                $(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().fadeOut('slow', 'linear');
            }
        });
    }
    

    if( $( '.remove-stream-post' ).length )
    {
        $('.remove-stream-post').die('click');
        $('.remove-stream-post').live('click',function(e) {
            e.preventDefault();
            var response = confirm ('Are you sure you want to remove this post?');
            if( response )
            {
                $.ajax({
                     url: $(this).attr('href')
                });
                $(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().fadeOut('slow', 'linear');
            }
        });
    }

    if( $( '.show-grouped-posts' ).length )
    {
        $('.show-grouped-posts a').die('click');
        $('.show-grouped-posts a').live('click',function(e) {
            e.preventDefault();
            var id = $(this).attr('class').replace('post-group-','');
            $('.post-group-'+id).removeClass('hide-post');
            $(this).parent().hide();
        });    
    }
    
    $('.vote-stream-post').die('click');
    $('.vote-stream-post').live('click',function(e) {
        e.preventDefault();

        var vote_url = $(this).attr('href'), new_vote_url = '', vote_label = 'votes', action_label = ' - undo', count = $(this).children( '.count' ).html() * 1, direction = 1;

        if( vote_url.indexOf('&vote=') != -1 )
        {
            if( vote_url.indexOf('&vote=1') == -1 )
            {
                direction = -1;
                //action_label = ' - up vote';
                new_vote_url = vote_url.replace('&vote=-1','&vote=1');
            }
            else 
            {
                new_vote_url = vote_url.replace('&vote=1','&vote=-1');
            }
        }
        else if( vote_url.indexOf('&likes=') != -1 )
        {

            if( vote_url.indexOf('&likes=1') == -1 )
            {
                direction = -1;
                new_vote_url = vote_url.replace('&likes=-1','&likes=1');
            }
            else 
            {
                new_vote_url = vote_url.replace('&likes=1','&likes=-1');
            }
        }
        else
        {
            new_vote_url = vote_url;
        }

        $(this).attr('href', new_vote_url);

        if( count == 1 )
        {
//            vote_label = 'vote';
        }

        count += direction;

        //$(this).children( '.label' ).html( vote_label + action_label );
        $(this).children( '.count' ).html( count );


        $.ajax({ url: vote_url });

//            $(this).parent().parent().parent().parent().parent().fadeOut('slow', 'linear');


    });
    
    $('.favorite-stream-post').die('click');
    $('.favorite-stream-post').live('click',function(e) {
        e.preventDefault();

        var favorite_url = $(this).attr('href'), favorite_label = 'favorites', action_label = ' - undo', count = $(this).children( '.count' ).html() * 1, direction = 1;


        if( $(this).children( '.label' ).html().indexOf( action_label ) != -1 )
        {
            direction = -1;
            action_label = ' - up favorite';
            favorite_url = favorite_url.replace('&add_fav=1','&remove_fav=1');
        }

        if( count == 1 )
        {
            favorite_label = 'favorite';
        }

        count += direction;

        $(this).children( '.label' ).html( favorite_label + action_label );
        $(this).children( '.count' ).html( count );


        $.ajax({ url: favorite_url });

//            $(this).parent().parent().parent().parent().parent().fadeOut('slow', 'linear');


    });

    if($('a.expand-comment-area').length)
    {
        $('a.expand-comment-area').die('click');
        $('a.expand-comment-area').live('click',function(e) {
            var el          = $(this);
            var post_url    = el.attr('data-url');
            var id          = el.attr('data-id');
            var comment_area = $('#post'+id+' .post-comment-area');
            var admin_access = '';
            var post_access  = '';

            if( comment_area.html() != '' )
            {
                if( comment_area.css('display') != 'none' )
                {
                    comment_area.hide();
                }
                else
                {
                    comment_area.show();
                }
            }
            else
            {
                comment_area.html('<div class="comment-block"><p>Loading comments...</p></div>');
                var params      = 'no_geo=1&format=json&include_acls='+id+'&include_comment_acl='+id+'&rows=30&sortby=postedon&sortdir=asc&entity_type=25&master_id='+id;
                $.ajax({
                     url: '/entity/api/search'
                    ,data: params
                    ,success: function(data){
                        var i = 0;
                        var html         = '';
                        var post_html    = '';
                        
                        if( data != '' )
                        {
                            data = JSON.parse(data);

                            post_access  = data.allow_comment_posts;
                            admin_access = data.has_admin_access; 

                            if( data.results && data.results.length > 0 )
                            {
                                var comment_html = '';

                                if( data.found > data.results.length )
                                {
                                    comment_html += '<div class="comment-block">'
                                    comment_html += '<div class="comment-post-info"><p>Showing '+data.results.length+' most recent comments. <a href="'+post_url+'">View all '+data.found+' comments.</a></p></div>';                             
                                    comment_html += '</div>';
                                }

                                for( i = 0; i < data.results.length; i++ )
                                {
                                    var comment = data.results[i];

                                    comment_html += '<div class="comment-block">'

                                    if( admin_access || data.has_admin_access )
                                    {
                                        comment_html += '<div class="comment-admin-links"><a href="/entity/api/post?entityid='+id+'&remove_comment=' + comment['id'] + ' "class="remove-comment">x</a></div>';
                                    }
                                    comment_html += '<div class="comment-body"><p>' + comment['body'] + '</p></div>';
                                    comment_html += '<div class="comment-post-info"><p>' + 'Posted by  <a title="'+comment['postedby_label']+'" target="_blank" rel="nofollow" href="'+comment['postedby_url']+'">'+comment['postedby_label']+'</a> &middot; '+comment['postedon_label'] + '</p></div>';                                
                                    comment_html += '</div>';
                                }

                                html += comment_html;

                            }

                            
                            
                            if( post_access )
                            {
                                post_html = '<div id="comment-form-wrap'+id+'" class="comment-form-wrap"><form id="comment-form-'+id+'" action="" method="post"><input type="hidden" value="'+id+'" name="entityid"><input type="hidden" value="25" name="entity_type"><input type="hidden" value="1" name="save"><input type="hidden" value="1" name="comment"><table class="form"><input type="hidden" class="input-text" value=" name="person_name"><input type="hidden" class="input-text" value="" name="email"><input type="hidden" class="input-text" value="" name="website"><tbody><tr><td><textarea id="comment-body-'+id+'" class="input-textarea elastic " style="height:10px; color: #CCC" cols="30" rows="1" name="body">Write your comment</textarea></td><td><input type="submit" class="comment-button form-submit-button" value="submit"><div class="submit-message"></div></td></tr></tbody></table></form></div>';
                            }
                        }


                        comment_area.html(html+post_html);
                        $('#comment-body-'+id).elastic(); 
                        $('#comment-body-'+id).focus(function() {
                            if( $(this).val().indexOf('Write your comment') != -1 )
                            {
                                $(this).val('');
                                $(this).css('color','#000');
                            }
                        });
                        
                        $('#post'+id+' .post-comment-area .comment-admin-links a.remove-comment').live('click',function(e) {
                            e.preventDefault();
                            var response = confirm ('Are you sure you want to remove this comment?');
                            if( response )
                            {
                                $.ajax({
                                     url: $(this).attr('href')
                                });
                                $(this).parent().parent().fadeOut('slow', 'linear');
                            }
                        });

                         $('#comment-form-'+id).submit(function(e) { 
                            e.preventDefault();
                            
                            $.ajax({
                                 url: '/entity/api/post'
                                ,data: $(this).serialize()
                                ,success: function(data) {
                                    data        = $.parseJSON(data);
                                    
                                    post_access  = data.allow_comment_posts;
                                    admin_access = data.has_admin_access; 

                                    var comment = data['comment'];
                                
                                    if( comment['publish_status'] == 1 )
                                    {
                                        $('#comment-form-wrap'+id).html('<div class="success-message comment-post-success"><p>Your comment has been posted, moderation is required before it appears.</p></div>'); 
                                    }
                                    else
                                    {

                                        var comment_html = '<div class="comment-block">';
                                        comment_html += '<div class="comment-admin-links"><a href="/entity/api/post?entityid='+id+'&remove_comment=' + comment['entityid'] + ' "class="remove-comment">x</a></div>';
                                        comment_html += '<div class="comment-body"><p>' + comment['body'] + '</p></div>';
                                        comment_html += '<div class="comment-post-info"><p>' + 'Posted by  <a title="'+comment['postedby_label']+'" target="_blank" rel="nofollow" href="'+comment['postedby_url']+'">'+comment['postedby_label']+'</a> &middot; '+comment['postedon_label'] + '</p></div>';                                
                                        comment_html += '</div>';
                                        $('#comment-form-wrap'+id).html(comment_html); 
                                    }
                                }
                            });
                            return false;
                        });
                    }
                });
            }
        });
    }
}

function hidePopupFormDialogue(popup_button,form_id, message)
{
    $(popup_button).hide();
    $('.form-'+form_id+'-container').hide();
    $(popup_button).attr('disabled', true);
    $('#form-'+form_id+' div.ajax-submit-message').html('<p><span>'+message+'</span></p>');
    //$('#form-{FORM_ID}').hide();

    setTimeout(function() {
        $('#form-'+form_id).dialog('close');
        /*
        $(':input','form#{FORM_ID}')
         .not(':button, :submit, :reset, :hidden')
         .val('')
         .removeAttr('checked')
         .removeAttr('selected');
         */

        $('form#'+form_id)[0].reset();

        $(popup_button).show();
        $('.form-'+form_id+'-container').show();
        $(popup_button).attr('disabled', false);
        $('#form-'+form_id+' div.ajax-submit-message').html('');

    }, 1500);
}

function hideInlineFormDialogue(popup_button,form_id, message)
{
    $(popup_button).hide();
    //$('.form-'+form_id+'-container').hide();
    $(popup_button).attr('disabled', true);
    $('#form-'+form_id+' div.submit-message').html('<p><span>'+message+'</span></p>');
    $('#form-'+form_id).hide('blind', 'fast');

    if( $('.stream-feed').length )
    {
        var args      =  { };
        if( $('#form-'+form_id+' input[name="master_id"]').length )
        {
            args.master_id = $('#form-'+form_id+' input[name="master_id"]').val();
        }
        args.postedby_current_user = true;
        args.sortby                = 'postedon';
        args.sortdir               = 'desc';
        args.rows                  = 1;
        args.highlight             = 1;

        updateStream(args);
    }

    setTimeout(function() {

        //$('#form-'+form_id).show();

        $(popup_button).show();
        //$('.form-'+form_id+'-container').show();
        $(popup_button).attr('disabled', false);
        $('#form-'+form_id+' div.ajax-submit-message').html('');
        $('form#'+form_id+' div.submit-message').html('');

    }, 1500);
}


function updateStream(args) 
{
    //var search_form = $('.stream-search-form');
    //var params      = search_form.serialize();
    var params      = 'stream=1&do_search=1&search_stream_data=1';
    if( args.master_id )
    {
        params += '&master_id='+ args.master_id;
    }
    if( args.user_id )
    {
        params += '&postedby='+ args.user_id;
    }
    if( args.postedby_current_user )
    {
        params += '&postedby_current_user='+ args.postedby_current_user;
    }
    if( args.sortby )
    {
        params += '&sortby='+ args.sortby;
    }
    if( args.sortdir )
    {
        params += '&sortdir='+ args.sortdir;
    }
    if( args.rows )
    {
        params += '&rows='+ args.rows;
    }
    
    //params          = params.replace( /multiselect_stream-filter/gi, 'multiselect_stream-filter[]' );
    $.ajax({
         url: '/entity/api/search'
        ,data: params
        ,success: function(data) {
            var html = data;
                        
            if( html == '' )
            { 
            }
            else
            {
                attachStreamEvents();
                $('.stream-no-results').hide();
                $('.more-stream-button').show();
            }
            
            var stream_page_id = 'more-stream-page-'+$('#search_stream_page').val();
            $('.stream-feed').prepend('<div id="'+stream_page_id+'" class="more-posts-wrapper" style="display:none;">'+html+'</div>');
     
            if( args.highlight)
            {
                $('#'+stream_page_id).show('blind', 'slow').effect("highlight", {}, 2500)
            }
            else
            {
                $('#'+stream_page_id).show('blind', 'slow');
            }

            attachToolTips('#'+stream_page_id+' div.post div.tools');
        }
    });
}



var Base64 = {

// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

// public method for encoding
encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = Base64._utf8_encode(input);

    while (i < input.length) {

        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
        this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
        this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

    }

    return output;
},

// public method for decoding
decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

        enc1 = this._keyStr.indexOf(input.charAt(i++));
        enc2 = this._keyStr.indexOf(input.charAt(i++));
        enc3 = this._keyStr.indexOf(input.charAt(i++));
        enc4 = this._keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

    }

    output = Base64._utf8_decode(output);

    return output;

},

// private method for UTF-8 encoding
_utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return utftext;
},

// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

        c = utftext.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }

    return string;
}

}

