//<!--
var currentPage = '0';
var messageBoardPosts; //declare variable in global scope for posts
var messageBoardLoaded = 'false';

jQ('document').ready(function() { //always init when the dom is ready
	board_init();
});

function board_init(){
	if(cobj_mb_cat!='') {
		ONAPI.getMessages({
			data:{user_id:userId, cat_id:cobj_mb_cat},
			callback: function(data) {
				messageBoardPosts = data; //store data in global var. You were already doing this when you stored in posts earlier, because js has lazy scope rules. It's best to declare the variable in global scope first.
				showMessages();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){ //this was wrong in the code I copied to you from the old mb
				alert(message);
			}
		});
	} else {
		jQ('#loading_message_board').html('No Message Board Category Chosen');
	}
}

function showMessages(){
	if(jQ('#message_board_object > .post').length < 1) { jQ('#message_board_object').append('<div class="post"></div>'); } // gotta put in a dummy one cuz callback of the fadeOut function will not execute unless theres at least one class post
	jQ('#message_board_object > .post').not('#message_board_object > .post:last').fadeOut(300);
	jQ('#message_board_object > .post:last').fadeOut(300, function() { //if you want these to fade out before they are replaced you need to run the rest of the function from the callback, and I'm running the callback only on the last one so it doesn't run it 40 times
		if (messageBoardLoaded == 'false') { //need to run paginate in here so it fades in with the posts, otherwise it looks weird
			paginateMessageBoard(); //only needs to be run once.
			messageBoardLoaded = 'true';
		}
		var start = currentPage*postsPerPage;
		var end = start + parseInt(postsPerPage);
		if (end > messageBoardPosts.length) { //length is 1 through n, indexes in the array are 0 through (n-1) --This was causing the pagination to display in the wrong place probably because it opened a div and then errored in the for loop and couldn't close it.
			end = messageBoardPosts.length;
		}
		jQ('#message_board_object > .post').remove();
		for(i=start;i<end;i++){
			var openingDiv = '<div class="post">';
			if(i%2 == 0){
				openingDiv = '<div class="post alt-post">';
			}	
			//jQ('#message_board_object > .pages_list:eq(1)').before(openingDiv + '<img class="author_avatar" src="' + messageBoardPosts[i].profile_photo_location + '?w=80&h=80&b=c&bg=000000000" alt="profile" />
			jQ('#message_board_object > .pages_list:eq(1)').before(openingDiv + '\
					<div class="post_content"> \
						<h4 class="post_author">' + messageBoardPosts[i].name + '</h4> \
						<p>' + messageBoardPosts[i].post + '</p> \
						<p class="post_time">Posted on ' + messageBoardPosts[i].created_at + '</p> \
					</div> \
			</div>');
		}
		bindComments();
		jQ('#message_board_object > .post').fadeIn(300);
	});
}

function paginateMessageBoard(){
	jQ('.pages_list').remove();
	jQ('#message_board_object').empty().append('<div class="comment_tab" id="post_comment"><span id="post_button">Post Comment</span></div>').append('<ul class="pages_list"></ul><ul class="pages_list"></ul>');
	jQ('.pages_list').fadeIn(300);
	var numPages = messageBoardPosts.length/postsPerPage;
	if (numPages > 1) {
		for (i = 0; i < numPages; i++) {
			var j = i + 1;
			jQ('.pages_list').append('<li id="page_' + i + '" class="page_' + i + ' pagination">' + j + '</li>'); //pages_# needs to be a class so both page boxes (top and bottom) get the active page style AND it needs the id to get the current page. A more proper way to do this is by using i to add the class to the li at that index of each page list instead of having two elements with the same id.
		}
		if(numPages > 10)
		{
			var list = jQ('.pages_list'); // always cache 
			var pagePNum = Math.ceil(numPages/10); 
			var on_num = 1;
			list.children('li').css('display', 'none');
			list.append("<li class='toggle_pages' id='next'>Next >>></li>");
			for(j=0;j<10;j++)
			{
				jQ('.pages_list').each(function(){
					jQ(this).children('.pagination').eq(j).css('display', 'block');
				});
			}
			jQ('.toggle_pages').live('click',function(){
				var type = this.id;
				if(type == 'next') {
					if(on_num <= pagePNum)
					{
						if(list.children('#last').length < 1) {
							list.prepend("<li class='toggle_pages' id='last'><<< Last</li>");
						}
						on_num++;
						if(on_num == pagePNum)
						{
							jQ('.toggle_pages').each(function(){
								if(this.id == 'next')
								{
									jQ(this).remove();
								}
							});
						}
						list.children('.pagination').css('display', 'none');
						var start = (on_num*10) -10;
						for(j=start;j<(start+10);j++)
						{
							list.each(function(){
								jQ(this).children('li').eq(j).css('display', 'block');
							});					
						}
					}
				} else if (type=='last') {
					if(on_num > 1)
					{
						if(list.children('#next').length < 1) {
							list.append("<li class='toggle_pages' id='next'>Next >>></li>");
						}
						on_num--;
						if(on_num == 1)
						{
							jQ('.toggle_pages').each(function(){
								if(this.id == 'last')
								{
									jQ(this).remove();
								}
							});						
						}
						list.children('.pagination').css('display', 'none');
						var start = (on_num*10) -10;
						for(j=start;j<(start+10);j++)
						{
							list.each(function(){
								jQ(this).children('li').eq(j).css('display', 'block');
							});					
						}						
					}
				}
			});
		} // end page pagination
		jQ('.pagination').click(function(){
			if(jQ(this).hasClass('pages_here')){ return false; }
			var mbpage = jQ(this).attr('id'); //IE doesn't like page as a variable name for some reason
			currentPage = mbpage.split('_')[1];
			jQ('.pages_here').removeClass('pages_here');
			jQ('.page_' + currentPage).addClass('pages_here');
			showMessages();
		});
	}
	jQ('.page_0').addClass('pages_here');//this function runs once, the first page is showing
}

function bindComments(){
	jQ('#post_button').unbind().bind('click', function(){
		if(jQ('#comment_wrapper').length > 0) {
			jQ('#comment_wrapper').fadeOut(1000, function(){
				jQ(this).remove();
			});
			return;
		}
		jQ('#post_button').before('<div id="comment_wrapper">\
											<input type="text" id="comment_name" value="Name">\
											<br class="clear" />\
											<textarea id="comment_text">Post</textarea>\
											<br class="clear" />\
											<div id="submit_comment">Submit</div>\
									</div>');
		jQ('#comment_wrapper').fadeIn(1000);
		jQ('#submit_comment').unbind().bind('click', function(){
		    function stripTags(string) {
                return string.replace(/(<([^>]+)>)/ig,"");
            }
            
			jQ('#submit_comment').unbind('click'); // prevent double click
			var name = jQ('#comment_name').val();
			var post = jQ('#comment_text').val();
			if((name==''||name=='Name') && (post==''||post=='Post')) {
				jQ('#comment_wrapper').prepend('<div id="comment_error"><p>* Please Fill Fields</p></div>');
				jQ('#comment_error').fadeIn(1000);
				return;
			}
			var strip_name = stripTags(name);
			var strip_post = stripTags(post);
			if(typeof(cobj_mb_cat) !='undefined' && cobj_mb_cat!='') {
				ONAPI.postMessage({
					data:{user_id:userId, cat_id:cobj_mb_cat, name:strip_name, post:strip_post},
					callback:function(data){
						jQ('#comment_wrapper').fadeOut(1000, function(){
							jQ(this).remove();
							//jQ('#message_board_object').html('<div id="loading_message_board" class="post" style="display:block;">Loading posts...</div>');
							board_init();
						});
					}
				});
			}
		});
	});
}
//-->
