
var FeedHandler = function( feed_container_id, max_messages, max_message_id, asynchronous_calls, public_only, people_filter, people_filter_id, check_messages_url, msgs_type, user_feed_id, search_str, tag_id)
{
    var SEARCH_CLOSE_ID      = '#search-header>a.close-link';
    var EVERYTHING_HEADER_ID = '#everything-header';
    var REFRESH_FEED_ID      = '#everything-header>#refresh-link';
    var FILTER_CLOSE_ID      = '#everything-header>a.close-link';
    var FILTER_SPAN_ID       = '#filter-span';
    var SEARCH_SPAN_ID       = '#search4span';
    var SEARCH_HEADER_ID     = '#search-header';

    //--------------------------------
    // Reference to "this" for scopes of event handlers
    var that = this;

    //---------------------
    // Message Feed
    this.message_feed = new MessageFeed( feed_container_id );

    //---------------------
    // Constants for the filters
    this.F_EVERYTHING = 'EVERYTHING';
    this.F_DIRECT     = 'DIRECT';

    this.F_ALERTS      = 'alert';
    this.F_ASSIGNMENTS = 'assignment';
    this.F_CHALKS      = 'chalk';
    this.F_FEEDS       = 'feed';
    this.F_FILES       = 'file';
    this.F_LINKS       = 'link';
    this.F_POLLS       = 'poll';
    this.F_RECENT_REPLIES = 'recent_replies';
    this.F_TAG = 'tag';

    //---------------------
    // Params to be send to 
    // the Server as message filters
    this.check_msgs_params = {
        'all_msgs'       : false,
        'msgs_type'      : (typeof msgs_type  != 'undefined' )? msgs_type : null, // values are: ALERTS, ASSIGNMENTS, FEEDS, FILES, LINKS, POLLS, RECENT_MSGS, TAG
        'people_filter'  : (typeof people_filter != 'undefined' ) ? people_filter : 'EVERYONE', // values are: EVERYONE, DIRECT, GROUP, SENDER, SCHOOL, DISTRICT
        'search_str'     : (typeof search_str  != 'undefined' )? search_str : '', 
        'group_id'       : (typeof people_filter != 'undefined' && people_filter != 'EVERYONE' && people_filter != 'DIRECT' ) ? people_filter_id : null,
        'start_msg_pos'  : 0,               //for pagination of the feed: by default, only display one page worth of results
        'max_messages'   : max_messages,    //max message count for a one page
        'max_message_id' : max_message_id,  //biggest message id currently in the feed
        'public_only'    : (typeof public_only  != 'undefined' )? public_only : false, //fetch only public messages?
        'sender_id'      : (typeof people_filter != 'undefined' && people_filter == 'SENDER' ) ? people_filter_id : null, //fetch only messages sent by this user
        'user_feed_id'   : (typeof user_feed_id != 'undefined' ) ? user_feed_id : null, //fetch messages sent by and to this user
        'tag_id'         : (typeof tag_id != 'undefined' ) ? tag_id : null //fetch messages sent by and to this user
    };

     //---------------------
    // In charge of the ajax asynchronous calls
    asynchronous_calls = typeof asynchronous_calls != 'undefined' ? asynchronous_calls : true ;
    check_messages_url = typeof check_messages_url != 'undefined' && check_messages_url != null? check_messages_url : '/message-feed/check-messages';
    this.ajax_updater = new AjaxUpdater(check_messages_url, null, 'text', that.check_msgs_params, asynchronous_calls, feed_container_id == 'feed');

    //see_older_posts = true if the "More" button was clicked to see older posts in the feed
    this.see_older_posts = false;

    that.main = function()
    {
        var parent_container_j = $j( '#content>#content_middle' );
    
        that.refresh_feed_j = parent_container_j.find( REFRESH_FEED_ID )
            .click(function(){
                that.refreshFeedWithCurrentFilters();
            });
        that.search_close_j = parent_container_j.find( SEARCH_CLOSE_ID )
            .click( function(){
                that.searchClose();
            });
        that.filter_close_j = parent_container_j.find( FILTER_CLOSE_ID )
            .click(function(){ 
                that.msgFilterClose();
            });
            
        //-------------------------------------
        // Binds the Ajax response call to the Activity handler
        $j( this.ajax_updater ).bind( AjaxUpdater.RESPONSE, function(event, activities){that.handleActivities(activities);} );
    };

   /**
    * Handles the Ajax Callback for the Message Feed
    * @param array activities Set of activities to refresh the Feed with
    */
    this.handleActivities = function(activities)
    {
        activities = eval('(' + activities + ')');

        if( activities != null )
        {
            // ------------------------------
            // If all the messages where fetched it usually means that a filtering option was used
            var append = that.check_msgs_params.all_msgs;

            if(that.check_msgs_params.all_msgs){
                //One of the filtering options was used
                that.message_feed.hideMoreOption();

                if(that.see_older_posts){
                    //The user clicked on the "More" button at the bottom of the feed to see older posts
                    append = true;
                    that.see_older_posts = false;
                }
            }

            that.message_feed.handleActivities(activities, append, that.check_msgs_params.max_messages);

            //gotta see which is the new highest message_id
            that.check_msgs_params.max_message_id = that.message_feed.getMaxMessageId();

        	//added to add events to the system message of new user if exists
        	if(typeof(view.bindNewTeacherLinks) != 'undefined')
        		 view.bindNewTeacherLinks();
        	if(typeof(view.showWhatToDo) != 'undefined')
        		 view.showWhatToDo(activities.length);        		 
        }

        if( that.check_msgs_params.all_msgs )
        {
            that.check_msgs_params.all_msgs = false;
            that.ajax_updater.setData(that.check_msgs_params);
        }
    };

    this.forceUpdate4Comment = function()
    {
        var tmp_start_msg_pos = that.check_msgs_params.start_msg_pos;
        that.check_msgs_params.start_msg_pos = 0;
        //that.check_msgs_params.start_msg_pos += that.check_msgs_params.max_messages;

        that.ajax_updater.setData(that.check_msgs_params);
        that.ajax_updater.forceUpdate();

        that.check_msgs_params.start_msg_pos = tmp_start_msg_pos;
        that.ajax_updater.setData(that.check_msgs_params);
    };

    /**
    * Searches the Message Feed
    */
    this.filterBySearch = function(search_str)
    {
        //-------------------------------------
        // Search the string and refresh the message feed
        if( search_str != '')
        {
            $j( SEARCH_SPAN_ID ).html( search_str );
            $j( SEARCH_HEADER_ID ).show();
            $j( EVERYTHING_HEADER_ID ).hide();

            // ------------------------------
            // Set the parameters for the Ajax Call (ie: Feed Refresh)
            that.check_msgs_params.all_msgs = true;
            that.check_msgs_params.search_str = search_str;
            that.check_msgs_params.start_msg_pos = 0;
            that.ajax_updater.setData(that.check_msgs_params);
			that.beforeFiltering();

            // ------------------------------
            // Trigger the Ajax Call
            that.message_feed.clearFeed();
            that.ajax_updater.forceUpdate();

        }
    };

    this.filterByType = function( msgs_type, filter_id )
    {
        // ------------------------------
        // Set the parameters for the Ajax Call (ie: Feed Refresh)
        that.check_msgs_params.all_msgs = true;
        that.check_msgs_params.msgs_type = msgs_type;
        that.check_msgs_params.start_msg_pos = 0;

        if( msgs_type == that.F_TAG){
            that.check_msgs_params.tag_id = filter_id;
        }
        that.beforeFiltering();
        that.ajax_updater.setData(that.check_msgs_params);

        // ------------------------------
        // Trigger the Ajax Call
        that.message_feed.clearFeed();
        that.ajax_updater.forceUpdate();

        //Set up the filter UI
        var filter_name = translateFilterName( msgs_type );

        $j( FILTER_SPAN_ID ).text(filter_name);
        $j( FILTER_CLOSE_ID ).show();
        $j( REFRESH_FEED_ID ).hide();
    };

    this.filterByPeople = function(people_filter, group_id)
    {
        // ------------------------------
        // Set the parameters for the Ajax Call (ie: Feed Refresh)
        that.check_msgs_params.all_msgs = true;
        that.check_msgs_params.people_filter = people_filter;
        that.check_msgs_params.start_msg_pos = 0;

        if( typeof(group_id) != 'undefined' )
        {
            that.check_msgs_params.group_id = group_id;
        }

		that.beforeFiltering();
        that.ajax_updater.setData(that.check_msgs_params);

        // ------------------------------
        // Trigger the Ajax Call
        that.message_feed.clearFeed();
        that.ajax_updater.forceUpdate();
    };

    this.filterByTeacherPosts = function()
    {
        alert('filterByTeacherPosts');
    };

	this.beforeFiltering = function()
	{
		if(typeof (view.beforeFilters) != 'undefined')
		{
			view.beforeFilters();
		}
	};

   /**
    * Closes the search headers and turns feed back to normal
    */
    this.searchClose = function()
    {
        $j( SEARCH_SPAN_ID ).html( '' );
        $j( SEARCH_HEADER_ID ).hide();
        $j( EVERYTHING_HEADER_ID ).show();

        // ------------------------------
        // Set the parameters to remove the search filter
        that.check_msgs_params.search_str = '';
        that.check_msgs_params.all_msgs = true;
        that.check_msgs_params.start_msg_pos = 0;
        that.ajax_updater.setData(that.check_msgs_params);

        // ------------------------------
        // Trigger the Ajax Call
        that.message_feed.clearFeed();
        that.ajax_updater.forceUpdate();
    };

    this.msgFilterClose = function()
    {
        // ------------------------------
        // Set the parameters to remove the msg filter
        that.check_msgs_params.msgs_type = null;
        that.check_msgs_params.all_msgs = true;
        that.check_msgs_params.start_msg_pos = 0;
        that.ajax_updater.setData(that.check_msgs_params);

        // ------------------------------
        // Trigger the Ajax Call
        that.message_feed.clearFeed();
        that.ajax_updater.forceUpdate();

        rightNavbar.removeFilters();
        $j( FILTER_CLOSE_ID ).hide();
        $j( REFRESH_FEED_ID ).show();
    }

   /**
    * Refreshes the Entire Message Feed
    */
    this.refreshFeedWithCurrentFilters = function()
    {                
        // ------------------------------
        // Set the parameters for the Ajax Call (ie: Feed Refresh)
        that.check_msgs_params.start_msg_pos = 0;
        that.check_msgs_params.all_msgs = true;
        that.ajax_updater.setData(that.check_msgs_params);

        // ------------------------------
        // Trigger The Ajax Call
        that.message_feed.clearFeed();
        that.ajax_updater.forceUpdate();
    };

   /**
    * Removes all filters, turns UI back to how it was
    */
    this.removeFilters = function()
    {
        // ------------------------------
        // Set the parameters for the Ajax Call (ie: Feed Refresh)
        that.check_msgs_params = {
        'all_msgs'       : true,
        'msgs_type'    : null,
        'people_filter'  : 'EVERYONE',
        'search_str'     : '',
        'group_id'       : null,
        'start_msg_pos'  : 0,
        'max_messages'   : that.check_msgs_params.max_messages,    //max message count for one page
        'max_message_id' : null,
        'public_only'    : that.check_msgs_params.public_only
        };
        that.ajax_updater.setData(that.check_msgs_params);
		that.beforeFiltering();
		
        // ------------------------------
        // Trigger the Ajax Call
        that.message_feed.clearFeed();
        that.ajax_updater.forceUpdate();

        rightNavbar.removeFilters();
        $j( FILTER_CLOSE_ID ).hide();
        $j( REFRESH_FEED_ID ).show();

    };

    /**
    * Shows the next page of older messages
    */
    this.showMoreMessages = function()
    {
        this.see_older_posts = true;
        //shift the starting position one page up
        that.check_msgs_params.start_msg_pos += that.check_msgs_params.max_messages;
        that.check_msgs_params.all_msgs = true;
        that.ajax_updater.setData(that.check_msgs_params);

        // ------------------------------
        // Trigger The Ajax Call
        that.ajax_updater.forceUpdate();
    };

    /**
    * Returns the empty error text to be displayed depending on the filters
    */
    this.getEmptyErrorText = function()
    {
        var t_txt = translated_text;
        var filter = that.check_msgs_params.msgs_type;

        var error_text = {
            strong : t_txt['no-posts'].replace(/{TYPE}/g, t_txt['posts']),
            span : t_txt['try-others']
        };

        if( filter != null )
        {

            if( filter == that.F_TAG)
            {
                error_text.span = t_txt['try-other-tags'];
                error_text.strong = t_txt['no-posts'].replace( /{TYPE}/g, translated_text['tags'].toLowerCase() );
            }
            else
            {
                error_text.strong = t_txt['no-posts'].replace( /{TYPE}/g, translateFilterName(filter).toLowerCase() );
            }
        }
        return error_text;
    };

    function translateFilterName( msgs_type )
    {
        var filter_name = '';
        switch( msgs_type ){
            case 'alert':      filter_name = translated_text['alerts-filter']; break;
            case 'assignment': filter_name = translated_text['assignments'];   break;
            case 'file':       filter_name = translated_text['files'];         break;
            case 'link':       filter_name = translated_text['links'];         break;
            case 'poll':       filter_name = translated_text['polls'];         break;
            default:           filter_name = translated_text[msgs_type];       break;
        }
        return filter_name;
    };

};