var Forum = function(){
	var instance = this;
	
	$(document).ready(function() {
		instance.autoImgResize();
	});
}
Forum.prototype = {
	
	showActionBox: function(event)
	{
		var forumModule = $(this).closest('.m_forum');
		var forum_id = forumModule.attr('forum_id');
		var popupBox = forumModule.find('.moderator-popup');
		var submit = popupBox.find('input.submit');
		var select = popupBox.find('select.move-location');
		var input = popupBox.find('div.text-field');
		
		select.hide();
		input.hide();
		
		// Deleting post
		if($(this).hasClass('link-delete-post'))
		{
			submit.val('Delete');
			popupBox.find('.message').html('Delete this post?');
			
			var post = $(this).closest('.row');
			
			submit.unbind("click").click(function(event) {
				forum.deletePost( post.attr('post_id') );//post);
				popupBox.fadeOut(160);
			});
		}
		
		// Sticky thread
		if($(this).hasClass('link-sticky-thread'))
		{
			submit.val('Sticky');
			popupBox.find('.message').html('Make this thread sticky?');
			
			submit.unbind("click").click(function(event) {
				forum.moderateThread("sticky-thread", "sticky", location.href);
				popupBox.fadeOut(160);
			});
		}
		else if($(this).hasClass('link-unsticky-thread'))
		{
			submit.val('Unsticky');
			popupBox.find('.message').html('Unsticky this thread?');
			
			submit.unbind("click").click(function(event) {
				forum.moderateThread("sticky-thread", "normal", location.href);
				popupBox.fadeOut(160);
			});
		}
		
		// Lock thread
		if($(this).hasClass('link-lock-thread'))
		{
			submit.val('Lock');
			popupBox.find('.message').html('Lock this thread?');
			
			submit.unbind("click").click(function(event) {
				forum.moderateThread("lock-thread", "locked", location.href);
				popupBox.fadeOut(160);
			});
		}
		else if($(this).hasClass('link-unlock-thread'))
		{
			submit.val('Unlock');
			popupBox.find('.message').html('Unlock this thread?');
			
			submit.unbind("click").click(function(event) {
				forum.moderateThread("lock-thread", "normal", location.href);
				popupBox.fadeOut(160);
			});
		}
		
		// Move thread
		if($(this).hasClass('link-move-thread'))
		{
			submit.val('Move');
			
			if(select.html() == "")
			{
				popupBox.find('.message').html('Move thread to forum:<span style="margin: 13px 0px -7px 0px; display: block; color: gray;">Loading...</span>');
				
				$.getJSON(Forum.URL.getModerationList, function(json){
					var options = '';
					for(var i in json)
					{
						if(i != forum_id) options += '<option value="' + i + '">' + json[i] + '</option>';
					}
					if(options == "") options = "<option value='0'>-- You do not have access to other forums --</option>";
					
					select.html(options);
					select.show();
					popupBox.find('.message').html('Move thread to forum:');
				});
			}
			else
			{
				select.show();
				popupBox.find('.message').html('Move thread to forum:');
			}
			
			submit.unbind("click").click(function(event) {
				forum.moderateThread("move-thread", select.val(), Forum.URL.returnURL);
				popupBox.fadeOut(160);
			});
		}
		
		// Delete thread
		if($(this).hasClass('link-delete-thread'))
		{
			submit.val('Delete');
			popupBox.find('.message').html('Delete entire thread?');
			
			submit.unbind("click").click(function(event) {
				forum.moderateThread("delete-thread", "", Forum.URL.returnURL);
				popupBox.fadeOut(160);
			});
		}
		
		
		/*
		 * Generic popup box functionality
		 */
		
		popupBox.fadeIn(160);
		
		popupBox.find('a.cancel').click(function(event) {
			popupBox.fadeOut(160);
			popupBox.find('select.move-location').hide();
		});
		
		if($(this).hasClass('link-delete-post')) {
			popupBox.css({
				top: event.pageY - forumModule.offset().top + 20,
				left: event.pageX - forumModule.offset().left - popupBox.width() + 10
			});
		}
		else {
			popupBox.css({
				top: event.pageY - forumModule.offset().top + 20,
				left: event.pageX - forumModule.offset().left - (popupBox.width()/2)
			});
		}
		
		
		event.stopPropagation();
		
		$(document).one("click", function(event) {
			popupBox.fadeOut(160);
			popupBox.find('select.move-location').hide();
		});
		
		popupBox.bind('click', function(event) {
			event.stopPropagation();
		});
		
		return false;
	},
	
	deletePost: function(post)
	{
		//var post_id = post.attr('post_id');
		if ( post instanceof Array ) { post = post.join(','); }
		
		$.post(location.href, { m: Forum.preset_id, op: "delete-post", post_id: post },
			function(data){ 
				if(data == 'success')
				{
		/*			num = post.closest('.postbox').find('.title .left span.num');
					var num_of_posts = parseInt(num.text(), 10) - 1;
					num.text(num_of_posts);
					
					var posts_string = 'Post';
					if(num_of_posts > 1) posts_string += 's';
					num.siblings('.numtext').text(posts_string);
			*/		
					// refresh
					//document.location = location.href;
					document.location.reload();
				}
			}
		);
		
	},
	
	/**
	 *
	 */
	showBulkModerateTools: function()
	{
        $('div .bulk-moderator-tool').css( {'display':'block'} );
        $('input:checkbox.bulk-moderator-item').css( {'display':'inline'} ); 
        $('input:checkbox.bulk-moderator-item-all').css( {'display':'inline'} );         
        // 
        $('input:checkbox.bulk-moderator-item').click( function() { forum.updateModeratorPostCount(); } );
        $('input:checkbox.bulk-moderator-item-all').click( function() { forum.selectAllItems($(this).attr('checked')); }  ); 
        
        return false;
	},
	
	
	/**
	 *
	 */
	hideBulkModerateTools: function()
	{
        $('div .bulk-moderator-tool').css( {'display':'none'} );
        $('.bulk-moderator-count').text( '0' );
        $('input:checkbox.bulk-moderator-item').css( {'display':'none'} ).attr('checked', false); 
        $('input:checkbox.bulk-moderator-item-all').css( {'display':'none'} ).attr('checked', false); 
        
        return false;
	},
    
    selectAllItems: function( isChecked )
    {
        $('input:checkbox.bulk-moderator-item').attr('checked', isChecked);
        this.updateModeratorPostCount();
    },
    
    updateModeratorPostCount: function()
    {
        $('.bulk-moderator-count').text( this.getModeratorPostCount() );
	},
	
	getModeratorPostCount: function()
	{
	    return $('input:checked.bulk-moderator-item').length;
	},
	
	/**
	 *
	 */
	applyModeratorAction: function( button, event)
	{
		var forumModule = button.closest('.m_forum');
		var forum_id = forumModule.attr('forum_id');
		var popupBox = forumModule.find('.moderator-popup');
		var submit = popupBox.find('input.submit');
		var select = popupBox.find('select.move-location');
		var mergeType = popupBox.find('select.merge-type');
		var input = popupBox.find('div.text-field');
		
		select.hide();
		input.hide();
        mergeType.hide();
                
		var posts = [];
		$('input:checked.bulk-moderator-item').each( function() { posts.push($(this).val()); } );
        
	    switch ( $('.bulk-moderator-tool select').val() )
	    {
	        case "delete-post": 
        	    if ( this.getModeratorPostCount() == 0 ) 
        	    {
        	        Enjin_Core.showMessagePopup({message:'Please select one or more posts to delete'});
        	        return;
        	    }   
        	    
	    		submit.val('Delete');
    			popupBox.find('.message').html('Delete all selected posts?');
    			
    			submit.unbind("click").click(function(event) {
    				forum.deletePost( posts );
    				popupBox.fadeOut(160);
    			});
	        break;   
	        
	        case "move-post": 
        	    if ( this.getModeratorPostCount() == 0 ) 
        	    {
        	        Enjin_Core.showMessagePopup({message:'Please select one or more posts to move'});
        	        return;
        	    }   
        	    
	    		submit.val('Move');
    			popupBox.find('.message').html('Enter URL of the thread to move posts to:');
    			input.show();
    			
    			submit.unbind("click").click(function(event) {
    				forum.moderateThread("move-post", $('div.text-field input').val(), document.location.href, posts);
    				popupBox.fadeOut(160);
    			});	       
    		 break;   
    		 
    		 case "delete-thread":
        	    if ( this.getModeratorPostCount() == 0 ) 
        	    {
        	        Enjin_Core.showMessagePopup({message:'Please select the threads to delete'});
        	        return;
        	    }      		 
        	    
	    		submit.val('Delete');
    			popupBox.find('.message').html('Delete all selected threads?');
    			
    			submit.unbind("click").click(function(event) {
    				forum.moderateThread("delete-thread", "", Forum.URL.returnURL, posts);
    				popupBox.fadeOut(160);
    			});
    		 break;

    		 case "move-thread":
        	    if ( this.getModeratorPostCount() == 0 ) 
        	    {
        	        Enjin_Core.showMessagePopup({message:'Please select the threads to move'});
        	        return;
        	    }      		 

				popupBox.find('.message').html('Move threads to forum:<span style="margin: 13px 0px -7px 0px; display: block; color: gray;">Loading...</span>');
				
				$.getJSON(Forum.URL.getModerationList, function(json){
					var options = '';
					for ( var i in json )
					{
						if ( i != forum_id ) options += '<option value="' + i + '">' + json[i] + '</option>';
					}
					if(options == "") options = "<option value='0'>-- You do not have access to other forums --</option>";
					
					select.html(options);
					select.show();
					popupBox.find('.message').html('Move threads to forum:');
				});
        	    
	    		submit.val('Move');    			
    			submit.unbind("click").click(function(event) {
    				forum.moderateThread("move-thread", select.val(), Forum.URL.returnURL, posts);
    				popupBox.fadeOut(160);
    			});
    		 break;

    		 case "sticky-thread":
        	    if ( this.getModeratorPostCount() == 0 ) 
        	    {
        	        Enjin_Core.showMessagePopup({message:'Please select the threads to move'});
        	        return;
        	    }      		 
        	    
	    		submit.val('Make Sticky');
    			popupBox.find('.message').html('Make selected threads sticky?');
    			
    			submit.unbind("click").click(function(event) {
    				forum.moderateThread("sticky-thread", "sticky", location.href, posts );
    				popupBox.fadeOut(160);
    			});
    		 break;    		

    		 case "unsticky-thread":
        	    if ( this.getModeratorPostCount() == 0 ) 
        	    {
        	        Enjin_Core.showMessagePopup({message:'Please select the threads to move'});
        	        return;
        	    }      		 
        	    
	    		submit.val('Make Unsticky');
    			popupBox.find('.message').html('Remove the sticky status on selected threads?');
    			
    			submit.unbind("click").click(function(event) {
    				forum.moderateThread("sticky-thread", "normal", location.href, posts );
    				popupBox.fadeOut(160);
    			});
    		 break;        		  

    		 case "lock-thread":
        	    if ( this.getModeratorPostCount() == 0 ) 
        	    {
        	        Enjin_Core.showMessagePopup({message:'Please select the threads to lock'});
        	        return;
        	    }      		 
        	    
	    		submit.val('Lock');
    			popupBox.find('.message').html('Lock there selected threads?');
    			
    			submit.unbind("click").click(function(event) {
    				forum.moderateThread("lock-thread", "locked", location.href, posts );
    				popupBox.fadeOut(160);
    			});
    		 break; 

    		 case "unlock-thread":
        	    if ( this.getModeratorPostCount() == 0 ) 
        	    {
        	        Enjin_Core.showMessagePopup({message:'Please select the threads to move'});
        	        return;
        	    }      		 
        	    
	    		submit.val('Unlock');
    			popupBox.find('.message').html('Unlock the selected threads?');
    			
    			submit.unbind("click").click(function(event) {
    				forum.moderateThread("lock-thread", "normal", location.href, posts );
    				popupBox.fadeOut(160);
    			});
    		 break;     	

    		 case "merge-thread":
        	    if ( this.getModeratorPostCount() < 2 ) 
        	    {
        	        Enjin_Core.showMessagePopup({message:'Please select at least 2 threads to merge'});
        	        return;
        	    }      		 

        	    var options = select.attr('options'); 
        	    options.length = 0;
        	    $('input:checked.bulk-moderator-item').each( function() { var t = $(this).attr('data-thread');          
        	                                                              if(t.length > 56) { t = t.substr(0,56)+'...'; }; 
        	                                                              options[options.length] = new Option(t, $(this).attr('value')); 
        	                                                            }); 

	    		submit.val('Merge');
	    		select.show();
	    		mergeType.show();
	    		
    			popupBox.find('.message').html('Select main thread to merge to:');
    			
    			submit.unbind("click").click(function(event) {
    				forum.mergeThreads( select.val(), mergeType.val(), posts, location.href );
    				popupBox.fadeOut(160);
    			});
    		 break;     	    		 
    		 	              
             default: return;   	    	 
        }	        
		
		
		/*
		 * Generic popup box functionality
		 */
		
		popupBox.fadeIn(160);
		
		popupBox.find('a.cancel').click(function(event) {
			popupBox.fadeOut(160);
			popupBox.find('select.move-location').hide();
			popupBox.find('div.text-field').hide();
		});
		
    	popupBox.css({
				top: event.pageY - forumModule.offset().top + 20,
				left: event.pageX - forumModule.offset().left - (popupBox.width()/2)
			});
		
		event.stopPropagation();
		
		$(document).one("click", function(event) {
			popupBox.fadeOut(160);
			popupBox.find('select.move-location').hide();
			popupBox.find('div.text-field').hide();
		});
		
		popupBox.bind('click', function(event) {
			event.stopPropagation();
		});
		
		return false;
	},              
	
	/**
	 * 
	 * @param array itemList Optional list of threads/posts to operate on if not current thread
	 */
	moderateThread: function(operation, setting, gotoURL, itemList )
	{
	    var params = { m: Forum.preset_id, op: operation, setting: setting};
	    if ( itemList instanceof Array ) { params.threads = itemList.join(','); }
		$.post(location.href, params,
			function(data){
				if ( data == 'success' ) 
				{
				    // navigate to target page, if the target is this page, we must force a reload
				    // some browsers won't refresh if the URL is the same
				    if ( document.location.href == gotoURL )
				    {
				        document.location.reload();
				    }
				    else
				    {
				        document.location = gotoURL;
                    }				        
                }				    
                else
                {
                    Enjin_Core.showMessagePopup( {message:data} );
                }
			}
		);
	},
	
	/**
	 * Applies the merge threads moderate action, seperate to moderateThread() as it has extra params
	 */
	mergeThreads: function( mainThreadId, mergeType, threads, gotoURL )
	{
	    var params = { m: Forum.preset_id, op: 'merge-thread', mergeType: mergeType, mainThreadId:mainThreadId, threads: threads.join(',')};
		$.post(location.href, params,
			function(data){
				if(data == 'success') document.location = gotoURL;
			}
		);	    
	},
	
	showPreview: function(preset_id, type, element)  {
		var info;
		var data = {};
		
		switch(type) {
			case 'thread':
				info = this.showPreviewThread(element);
				break;
			case 'reply':
				info = this.showPreviewReply(element);
				break;
			case 'edit':
				info = this.showPreviewEdit(element);
				break;				
		}
		
		data = info.data;
		data.op = 'preview';
		data.type = type;
		data.m = preset_id;
		
		$.post(location.href, data,
				function(response){
					info.element.html(response);
					info.element_parent.show();
				}
		);
	},
	
	showPreviewThread: function(element) {
		var info = {
			data: {},
			element: null
		};
		
		var parent = $(element).closest('.forum-area');
		
		info.element = parent.find('.preview .post-content');
		info.element_parent = parent.find('.preview');
		info.data.content = parent.find('.thread textarea[name=content]').val();
		//info.data.title = parent.find('.thread input[name=subject]').val();
		
		return info;
	},
	
	showPreviewReply: function(element) {
		var info = {
			data: {},
			element: null
		};
		
		var parent = $(element).closest('.forum-area');
		
		info.element = parent.find('.preview .post-content');
		info.element_parent = parent.find('.preview');
		info.data.content = parent.find('.reply textarea[name=content]').val();
		
		return info;
	},
	
	showPreviewEdit: function(element) {
		var info = {
			data: {},
			element: null
		};
		
		var parent = $(element).closest('.forum-area');
		
		info.element = parent.find('.preview .post-content');
		info.element_parent = parent.find('.preview');
		info.data.content = parent.find('.post textarea[name=content]').val();
		
		return info;
	},
	
	toggleHiddenPost: function( el, post_id )
	{
	    var post = $('tr[post_id=' + post_id +']');
	    if ( post.hasClass('hidden') )
	    {
			$('tr[data-hidden-post-trigger=' + post_id + ']').hide();
	        post.removeClass('hidden');
	        el.text('Hide Post');
        }
        else
        {
	        post.addClass('hidden');
	        el.text('Show Post');
        }	        
	},

	
	autoImgResize: function()
	{		
		var self = this;
		$('.m_forum img.bbcode_img,.m_forum .post-attachments-images img').each(function(i){
			if (this.complete) {
				self.autoImgResizeItem(this);
			} else {
				var image = this;				
				$(this).bind('load', function() {
					self.autoImgResizeItem(image);
				});
			}
		});
	},
	
	autoImgResizeItem: function(image) {
		if(image.width > 499)
		{
			var myParent = $(image).parent().get(0);
			if(myParent.tagName != 'A')
			{
				image.style.cursor = 'pointer';
				image.onclick = function(e) {
					if(window.event)
						window.open(window.event.srcElement.src, 'enjinImg', 'menubar=no, toolbar=no, location=no, directories=no, fullscreen=no, titlebar=yes, hotkeys=no, status=no, scrollbars=yes, resizable=yes');
					else
						window.open(e.target.src, 'enjinImg', 'menubar=no, toolbar=no, location=no, directories=no, fullscreen=no, titlebar=yes, hotkeys=no, status=no, scrollbars=yes, resizable=yes');
				}
			}
		}		
	},
	
	
	//poll part
	poll_inited: {},
	poll_template: null,
	poll_count: {},
	poll_max_answers: 25,
	
	initPoll: function(preset_id, element) {
		//get template
		var pt = element.find('.area-poll .answers .template');
		pt.removeClass('template');
		this.poll_template = pt.clone();
		pt.remove(); //don't show it
		
		this.poll_count[preset_id] = 1;
		this.poll_inited[preset_id] = true;
		
		if (forum_data 
			&& typeof forum_data[preset_id] != 'undefined') {
			var self = this;
			
			jQuery.each(forum_data[preset_id], function(key, value) {
				self.addAnswerPoll(preset_id, element, value);
			});
			
		} else {
			//add first elements
			this.addAnswerPoll(preset_id, element); 
			this.addAnswerPoll(preset_id, element);
		}
	},
	
	addAnswerPoll: function(preset_id, element, value) {		
		var main_form = $(element).closest('form[name=postform]').find('.area-poll .answers');
		var nelement = this.poll_template.clone();
		var count_id = this.poll_count[preset_id]++;
				
		nelement.addClass('answer-'+count_id);
		nelement.find('.text-labeling .count').html(count_id);
		nelement.find('.input-text input[type=text]').attr('name', 'poll_answer_'+count_id);
		
		if (value)
			nelement.find('.input-text input[type=text]').val(value);
		
		main_form.append(nelement);
		
		if (count_id < 3) {
			//don't show close
			main_form.find('.answer .close').hide();
		} else {
			//show close button
			main_form.find('.answer .close').show();
		}
		
		if (count_id >= this.poll_max_answers) {
			//don't allow more
			$(element).closest('form[name=postform]').find('.area-poll .answer-add').hide();			
		}
	},
	
	removeAnswerPoll: function(preset_id, element) {
		var area_poll = $(element).closest('form[name=postform]').find('.area-poll');
		var main_form =  area_poll.find('.answers');
		var count_id=1;
		var nelement = $(element).closest('.answer');
		nelement.remove();
		
		this.poll_count[preset_id]--;
		
		main_form.find('.answer').each(function() {			
			$(this).find('.text-labeling .count').html(count_id);
			$(this).find('.input-text input[type=text]').attr('name', 'poll_answer_'+count_id);
			count_id++;
		});
		
		if (count_id <= 3) {
			main_form.find('.answer .close').hide();
		}
		
		if (count_id <= this.poll_max_answers) {
			area_poll.find('.answer-add').show();
		}
	},
	
	initPostPoll: function(preset_id) {
		var element = $('.m_forum_'+preset_id+' .area-poll');
		this.showPoll(preset_id, element);
	},
	
	showPoll: function(preset_id, element) {
		var main_form = $(element).closest('form[name=postform]');
		
		if (!this.poll_inited[preset_id])
			this.initPoll(preset_id, main_form);
				
		//main_form.find('.text-labeling.body').html('Body and Poll Question');
		main_form.find('.area-poll').show();
		main_form.find('.buttons-area .poll .element-remove').show();
		main_form.find('.buttons-area .poll .element-add').hide();		
		main_form.find('input[name=poll_have]').val('1');
	},
	
	removePoll: function(preset_id, element) {
		var main_form = $(element).closest('form[name=postform]');
		//main_form.find('.text-labeling.body').html('Body');
		main_form.find('.area-poll').hide();
		main_form.find('.buttons-area .poll .element-remove').hide();
		main_form.find('.buttons-area .poll .element-add').show();
		main_form.find('input[name=poll_have]').val('0');
	},
	
	
	/* view part */
	showViewResultsPoll: function(element) {
		var main_form = $(element).closest('.post-poll-area');
		
		main_form.find('.view-poll').show();
		main_form.find('.post-poll').hide();
	},
	
	hideViewResultsPoll: function(element) {
		var main_form = $(element).closest('.post-poll-area');
		
		main_form.find('.view-poll').hide();
		main_form.find('.post-poll').show();
	},
	
	clearThreadGhost: function(event)
	{
		var thread_id = $(this).attr('thread_id');
		
		$.post(location.href, { m: Forum.preset_id, op: "clear-thread-ghost", thread_id: thread_id},
			function(data){
				if(data == 'success') document.location = location.href;
			}
		);
		
		return false;
	},
	
	markForumRead: function(event)
	{
		var forum_id = $(this).attr('forum_id');
		
		var op = "mark-forum-read";
		if(forum_id == 'all') op = "mark-forums-read";
		
		$.post(location.href, { m: Forum.preset_id, op: op, forum_id: forum_id},
			function(data){
				if(data == 'success') document.location = location.href;
			}
		);
		
		 $(this).replaceWith("<span>Marking...</span>");
		
		return false;
	},
	
	/**
	 * 
	 */
	markThreadUnread: function(event)
	{
		var thread_id = $(this).attr('data-threadid');
		
		var op = "mark-thread-unread";		
		$.post(location.href, { m: Forum.preset_id, op: op, thread_id: thread_id},
			function(data){
				if (data == 'success') document.location = location.href;
			}
		);
		
		 $(this).replaceWith("<span>Marking...</span>");
		
		return false;
	},
	
	/**
	 * 
	 */
	markThreadRead: function(event)
	{
		var thread_id = $(this).attr('data-threadid');
		
		var op = "mark-thread-read";		
		$.post(location.href, { m: Forum.preset_id, op: op, thread_id: thread_id},
			function(data){
				if (data == 'success') document.location = location.href;
			}
		);
		
		 $(this).replaceWith("<span>Marking...</span>");
		
		return false;
	},
			
	search: function(text, page, mode, mode_id)
	{
		$.ajax({
    		type: "POST",
    		url: "/ajax.php?s=forum",
    		data: {cmd: 'search', preset_id: Forum.preset_id, q: text, page: page, mode: mode, mode_id: mode_id},
    		dataType: "json",
    		success: function(data){
    			if(data.success == 'false') alert(data.error);
    			else {
    				forum.displaySearchResults(data);
    			}
    		},
    		error: function (XMLHttpRequest, textStatus, errorThrown) {
    			alert('Error', 'There was an error performing the search, please try again later.');
    		}
    	});
	},
	
	clearSearch: function() {
		$('.forum-area.search-results').remove();
		$('.m_forum .breadcrumbs.search').hide();
		$('.m_forum .breadcrumbs.standard').show();
		$('.forum-area.forum-content').show();
	},
	
	displaySearchResults: function(data)
	{
		data.page = parseInt(data.page);
		data.pages = parseInt(data.pages);
		
		$('.forum-area.forum-content').hide();
		$('.forum-area.search-results').remove();
		$('.m_forum .breadcrumbs.standard').hide();
		$('.m_forum .breadcrumbs.search').show();
		
		var searchtext = "Search";
		if(data.mode == 'forum') searchtext = "Search Forum";
		else if(data.mode == 'thread') searchtext = "Search Thread";
		
		var searchbox = "<form onsubmit='forum.search($(this).find(\"input[name=search]\").val(), 1, \"" + data.mode + "\", " + data.mode_id + "); Enjin_Core.disableButton($(this).find(\"input[type=submit]\"), 4, \"Searching...\"); return false;'><div class='search-box'>\
				<div class='element_button'><div class='l'><!-- --></div><div class='r'><!-- --></div><input type='submit' value='" + searchtext + "'></div>\
				<div class='input-text'>\
					<div class='tl'></div><div class='tr'></div><div class='bl'></div><div class='br'></div>\
					<input name='search' maxlength='100' value=\"" + data.q + "\">\
				</div>\
			</div></form>";
		
		var pagewidget = "";
		if(data.pages > 1)
		{
			pagewidget = "<div class='element_pagewidget search-pages'>\
				<span class='text'>Page</span>\
				<div class='input-text'><input value='" + data.page + "' maxlength='3'></div>\
				<div class='element_smallbutton'><div class='l'></div><div class='r'></div><input type='button' onclick='forum.search($(this).parent().parent().parent().parent().attr(\"q\"), $(this).parent().siblings(\".input-text\").children(\"input\").val(), \"" + data.mode + "\", " + data.mode_id + "); Enjin_Core.disableButton(this, 4);' value='Go'></div>\
				<span class='text rightmost'>of " + data.pages + "</span>";
			if(data.page > 1)
				pagewidget += "<div class='element_smallbutton'><div class='l'></div><div class='r'></div><input type='button' onclick='forum.search($(this).parent().parent().parent().parent().attr(\"q\"), " + (data.page - 1) + ", \"" + data.mode + "\", " + data.mode_id + "); Enjin_Core.disableButton(this, 4);' class='left' value='<'></div>";
			if(data.page < data.pages)
				pagewidget += "<div class='element_smallbutton'><div class='l'></div><div class='r'></div><input type='button' onclick='forum.search($(this).parent().parent().parent().parent().attr(\"q\"), " + (data.page + 1) + ", \"" + data.mode + "\", " + data.mode_id + "); Enjin_Core.disableButton(this, 4);' class='left' value='>'></div>";
			pagewidget += "</div>";
		}
		
		
		var html = "<div class='contentbox results'>\
			<div class='block-title'>\
				<div class='left'><!-- --></div>\
				<div class='right'><!-- --></div>\
				<div class='text'><span class='mask'>Found " + data.found + " entries for <span class='highlighted'>\"" + data.q + "\"</span></span></div>\
			</div>\
			<div class='block-container'>\
				<div class='he l'><!--  --></div>\
				<div class='he r'><!--  --></div>\
				<div class='he tl'><!--  --></div>\
				<div class='he tr'><!--  --></div>\
				<div class='he bl'><!--  --></div>\
				<div class='he br'><!--  --></div>\
				<div class='structure'>";
		
		for(var i=0; i<data.results.length; i++)
		{
			if(i == 0) html += "<div class='search-result-post first'>";
			else html += "<div class='search-result-post'>";
			
			html += "<div class='result-subject'><a href='" + Forum.baseurl + "/viewthread/" + data.results[i].thread_id + "/post/" + data.results[i].post_id + "#p" + data.results[i].post_id + "' target='_blank'>" + data.results[i].thread_subject + "</a></div>";
			html += "<div class='result-content'>" + data.results[i].post_content + "</div>";
			html += "<div class='result-info'><a class='forum-name' href='" + Forum.baseurl + "/viewforum/" + data.results[i].forum_id + "'>" + data.results[i].forum_name + "</a> &nbsp;&middot;&nbsp; " + (parseInt(data.results[i].thread_replies) + 1) + " posts &nbsp;&middot;&nbsp; Posted " + data.results[i].post_time + " &nbsp;&middot;&nbsp; By " + data.results[i].username +  "</div>"
			html += "</div>";
		}
		html += "</div></div></div>";
		
		$('.m_forum').append("<div class='forum-area search-results' q=\"" + data.q + "\"></div>");
		$('.forum-area.search-results').append("<div class='above-forum'>" + searchbox + pagewidget + "<br></div>" + html);
	},
	
	showAvatarHover: function( event )
	{
	    var el = $(event.currentTarget).parent();
	    
	    var userId = el.attr('data-userid');
	    var registeredId = parseInt(el.attr('data-registeredid'),10);
	    var siteId = el.attr('data-siteid');
	    var joinDate = el.attr('data-date');
	    var postCount = parseInt(el.attr('data-postcount'),10);
	    var userIP = el.attr('data-ip');
	    var adminFeatures = parseInt(el.attr('data-admin'),10);
	    var isOwner = parseInt(el.attr('data-owner'),10);
	    var username = el.attr('data-username');
	    var postId = el.attr('data-id');
	    var votes = parseInt(el.attr('data-votes'),10);;
	    var displayVotes = parseInt(el.attr('data-showvotes'),10);
	    var upVotes = parseInt(el.attr('data-up-votes'),10);
	    var downVotes = parseInt(el.attr('data-down-votes'),10);
	    
        var items = [ ['<a href="/profile/' + userId + '" class="menu-link">Profile</a>','html'] ];
        
        // only show messages if there is a registered user viewing the site
        if ( registeredId )
        {
	        items.push( ['<a href="/dashboard/messages/compose/to/id-' + userId + '" class="menu-link">Message User</a>','html'] );
        }
        	                 
	    items.push( ['<a href="/profile/' + userId + '/posts" class="menu-link">View User\'s Posts</a>','html'] );
	    items.push( ['','divider'] );	                 
                            
        if ( adminFeatures ) { items.push( ['<span class="menu-link">' + userIP + '</span>','html'] ); }
                        
        items.push( ['<span  class="menu-link">Joined on ' + joinDate + '</span>','html'] );
        
        // only show a post count if there is one available
        if ( postCount >= 0 ) { items.push( ['<span class="menu-link">' + postCount + ' posts</span>','html'] ); }
        
        if ( displayVotes )
        {                                          
            var text = ( votes > 0 ? '+' : '' ) + el.attr('data-votes') + ' ' + el.attr('data-vote-label');
            text += ' (' + ( upVotes > 0 ? '+' : '' ) + upVotes + '/' + downVotes + ')';
            items.push( ['<span  class="menu-link ' + ( votes > 0 ? 'votes-positive' : (votes < 0 ? 'votes-negative' : '') ) + '">' + text + '</span>','html'] ); 
        }
                        
        // the ban actions are only available to the administrators, however the clear user votes action
        // is available to administrators as well the normal user if he is hovering his own avatar
        if ( adminFeatures ) 
        { 
            items.push( ['','divider'] );
            items.push( ['<div data-id="'+postId+'" data-userid="'+userId+'" data-ip="'+userIP+'" data-username="'+username+'" class="menu-link"><a href="#" class="ban-user">Ban User</a>&nbsp;&middot;&nbsp;<a href="#" class="ban-ip">Ban IP</a>&nbsp;&middot;&nbsp;<a href="#" class="clear-votes">Clear ' + el.attr('data-vote-label') + '</a></div>','html'] ); 
        }

	    Enjin_Core.dropdownMenu( items, el, 'forum-user-dropdown', false );
	    
	    $('.element_dropdown_menu div[data-id] .ban-user').click( $.proxy(forum.banUser,forum) );
	    $('.element_dropdown_menu div[data-id] .ban-ip').click( $.proxy(forum.banIP,forum) );
	    $('.element_dropdown_menu div[data-id] .clear-votes').click( $.proxy(forum.clearUserVotes,forum) );
	},
	
	
	/**
	 * Display the popup showing the users IP/Host and username, and giving moderator options to ban this user
	 */
	showIPBanBox: function(event, preset_id, post_id, ip, host, userId, userName ) 
	{
		var forumModule = $(event.currentTarget).closest('.m_forum');
        var popupBox = forumModule.find('.ip-popup');
        
        // store the data fields needed for the ban actions to ban the right IP and user
        popupBox.attr( 'data-ip', ip );
        popupBox.attr( 'data-id', post_id );                                    
        popupBox.attr( 'data-username', userName );                                    
        
        // display the IP address and host name
        popupBox.find('.ip-name').text(ip);
        popupBox.find('.host-name').text(host);
        
        this.showPopupBox( popupBox, event );
    },

    /**
     * Ban the IP address of that was user to make the post the user is viewing, we get the 
     * IP from the data attribute set into the popup when it is displayed
     */
    banIP: function(event)
    {     
        var ipPopup = $(event.currentTarget).closest('div[data-ip]');
        this.showBanPrompt( event, 'Are you sure you want to ban the IP ' + ipPopup.attr('data-ip') + ' from accessing this site?', 'ban-ip' );
        return false;
    },
    
    banUser: function(event)
    {
        var ipPopup = $(event.currentTarget).closest('div[data-ip]');
        this.showBanPrompt( event, 'Are you sure you want to ban the user ' + ipPopup.attr('data-username') + ' from accessing this site?', 'ban-user' );
        return false;
    },
    
    banBoth: function(event)
    {
        var ipPopup = $(event.currentTarget).closest('.ip-popup');
        this.showBanPrompt( event, 'Are you sure you want to ban both the user ' + ipPopup.attr('data-username') + ' and the IP ' + ipPopup.attr('data-ip') + ' from accessing this site?', 'ban-both' );
        return false;
    },
    
    showBanPrompt: function( event, msg, op)
    {
        var ipPopup = $(event.currentTarget).closest('div[data-ip]');
        
        Enjin_Core.showPopup({  message: msg,
                                callback: function(event) {
                                                			$.post( location.href
                                                			       ,{m: Forum.preset_id, op: op, post_id:ipPopup.attr('data-id')}
                                                                   ,function(response)  { 
                                                                            if ( response == "success" ) {
                                                                                Enjin_Core.alert("Ban successful");
                                                                            }
                                                                            else { Enjin_Core.alert(response);  }
                                                                        }    
                                                			      ); 
                                                          }                                                			             
                             });

		ipPopup.fadeOut(160);
        
    },
    
    /**
     * 
     */
    preferences: function( event )
    {
        if (event.stopPropagation) event.stopPropagation();
	    else event.cancelBubble = true; 
        
        var body = '<div class="forum-preferences"><div class="input-label">Set number of threads per page</div>';
        body += '<select id="threads_per_page">';
        for ( var i= 15; i <= 30; i+=5 ) { body += '<option value="' + i + '"' + (Forum.preferences.threads_per_page == i ? ' SELECTED' : '') + '>' + i + '</option>'; } 
        body += '</select>';
        body += '<div class="input-label" style="margin-top:8px;">Set number of posts per page</div>';
        body += '<select id="posts_per_page">';
        for ( var i= 10; i <= 30; i+=5 ) { body += '<option value="' + i + '"' + (Forum.preferences.posts_per_page == i ? ' SELECTED' : '') + '>' + i + '</option>'; } 
        body += '</select>';
        body += '<div style="padding-top:8px"><input type="checkbox" ' + (parseInt(Forum.preferences.auto_subscribe,10)==1 ? 'CHECKED' : '') + '> Automatically subscribe me to threads that I reply to.</div>';
        body += '</div>';
        
        Enjin_Core.showPopup({  message: "Personal Forum Settings",
                                message1: body,
                                button_continue: "Save Changes",
                                callbackFirst: true,
                                callback: function(event) {
															var data  = { m: Forum.preset_id        
                                                			         ,op:'forum-preferences'
                                                			         ,preset_id:Forum.preset_id
                                                			         ,threads_per_page: $('.forum-preferences #threads_per_page').val()
                                                			         ,posts_per_page: $('.forum-preferences #posts_per_page').val()
                                                			         ,auto_subscribe: $('.forum-preferences input:checked').length == 1 ? 1 : 0
                                                			        };
                                                			$.post( location.href
                                                			       ,data
                                                                   ,function(response)  { 
                                                                            if ( response == "success" ) 
																			{
                                                                                Enjin_Core.alert("Preferences Updated");
																				$.extend(Forum.preferences,data);
                                                                            }
                                                                            else { Enjin_Core.alert(response);  }
                                                                        }    
                                                			      ); 
                                                          }                                                			             
                             });
    },
    
    replyReviewQuote: function(event,username)
    {
        var message = $(event.currentTarget).closest('.reply').find('.bbcode').html();
        message = '[quote=' + username + ']' + message + '[/quote]';

        $('#post-content').focus();

        // based on jquery.markitup.js function insert(block) line 479        
		if ( document.selection ) 
		{
			var newSelection = document.selection.createRange();
			newSelection.text = message;
		} 
		else 
	    {
	        var textarea = $('#post-content').get(0);
	        var caretPosition = textarea.selectionStart;
	        var selection = textarea.value.substring(caretPosition, textarea.selectionEnd);
			textarea.value =  textarea.value.substring(0, caretPosition) + message + textarea.value.substring(caretPosition + selection.length, textarea.value.length);
		}   
    },
    
    showPostHistory: function(event)
    {                       
        $(event.currentTarget).closest('.show-link').addClass('hidden');
        $(event.currentTarget).closest('.post-review').find('.replies').removeClass('hidden');
        $(event.currentTarget).closest('.post-review').find('.hide-review').removeClass('hidden');
    },
    
    hidePostHistory: function(event)
    {                        
        $(event.currentTarget).closest('.post-review').find('.show-link').removeClass('hidden');
        $(event.currentTarget).closest('.post-review').find('.replies').addClass('hidden');
        $(event.currentTarget).closest('.post-review').find('.hide-review').addClass('hidden');
    },
    
    /**
     * 
     */
    threadSubscription: function( el, event, threadId, title )
    {
        var el = $(el);
        var subscribed = parseInt( el.attr('data-subscribed'), 10 );
        if ( subscribed )
        {
       	$.post( location.href, {m: Forum.preset_id, op: 'unsubscribe-thread', thread_id:threadId}
                   ,function()  { el.attr('value','Subscribe').attr('data-subscribed',0); }    
        	      ); 
        }
        else
        {
            this.subscribePopup( el, event, threadId, true, title );
        }
    },
    
    /**
     * 
     */
    forumSubscription: function( el, event, forumId, title )
    {
        var el = $(el);
        var subscribed = parseInt( el.attr('data-subscribed'), 10 );
        if ( subscribed )
        {
       	$.post( location.href, {m: Forum.preset_id, op: 'unsubscribe-forum', forum_id:forumId}
                   ,function()  { el.attr('value','Subscribe').attr('data-subscribed',0); }    
        	   ); 
        }
        else
        {
            this.subscribePopup( el, event, forumId, false, title );
        }
    },
    
    subscribePopup: function( el, event, id, isThread, title )
    {
        if (event.stopPropagation) event.stopPropagation();
	    else event.cancelBubble = true;         
                                                                            
        var body = '<div class="forum-subscribe"><div class="title">' + ( title.length > 45 ? title.substr(0,45) + '...' : title ) + '</div>';
        body += '<div class="item"><input type="radio" value="email" name="forum-subscribe-option" checked> Instant Email Notification</div>';
        body += '<div class="note">Send out instant notification to your toolbar &amp; email.</div>';
        body += '<div class="item"><input type="radio" value="notify" name="forum-subscribe-option"> Toolbar Notification only</div>';
        body += '<div class="note">Send out instant notification to your toolbar only.</div>';
        body += '</div>';
        var params = { m: Forum.preset_id        
			          ,op:'subscribe-' + ( isThread ? 'thread' : 'forum' )
			         };
        params[ isThread ? 'thread_id' : 'forum_id' ] = id;

        Enjin_Core.showPopup({  message: "Subscribe to Forum" + ( isThread ? " Thread" : ""),            
                                message1: body,
                                button_continue: "Subscribe",
                                callbackFirst: true,
                                callback: function() {
                                                        params.subscription = $('.forum-subscribe input:checked').val();
                                            			$.post( location.href       
                                            			       ,params
                                                               ,function(response)  { el.attr('value','Unsubscribe').attr('data-subscribed',1); }    
                                            			      ); 
                                                      }                                                			             
                             });
            
        
    },
        
    /**
     * Shows permalink to this post so the user can copy it to the clipboard
     */                 
    permalink: function( event, post_id )
    { 
		var forumModule = $(event.currentTarget).closest('.m_forum');
        var popupBox = forumModule.find('.permalink-popup');
        
        // store the data fields needed for the ban actions to ban the right IP and user
        var url  = document.location.href.split('/viewthread/');
        var thread = url[1].split('/');
        popupBox.find('input').val( url[0] + '/viewthread/' + thread[0] + '/post/' + post_id + '#p' + post_id );
        
        this.showPopupBox( popupBox, event );    
        popupBox.find('input').select();
    },
    
    /**
     *
     */
    dislikePost: function( event, post_id )
    {
        this.likeDislikeAction( event, post_id, 'dislike-post' );
    },    
    
    /**
     * 
     */
    likePost: function( event, post_id )
    {
        this.likeDislikeAction( event, post_id, 'like-post' );
    },    
    
    likeDislikeAction: function( event, post_id, op )
    {
    	$.post( location.href
    	       ,{m: Forum.preset_id, op: op, post_id:post_id}
               ,function(response)  
                    { 
                        // "success" means vote was processed, but there are no updates to the UI required    
                        // otherwise the response is a JSON encoded dataset with new UI display values
                        if ( response != "success" ) 
                        {
                            eval("response=" + response);
                            forum.updatePostVotes( $(event.target), response );
                        }
                    }    
    	      ); 
    },
	
	/** 
	 * Clears all the votes from this specific post
	 */  	 
	resetVotes: function( el, post_id )
	{
		if(confirm("Are you sure you want to reset all votes in this post?")) {
			$.post(location.href, { m: Forum.preset_id, op: 'reset-votes', post_id: post_id },
				function(response){
					// "success" means vote was processed, but there are no updates to the UI required
					// otherwise the response is a JSON encoded dataset with new UI display values
					if ( response == "success" )
					{
						document.location = location.href;
						location.reload(true);
					}
				}
			);
		}
	},    
	
	
	/**
	 * Clears all the votes in this module from every post from this specific user
	 */
	clearUserVotes: function( event )
	{
		if(confirm("Are you sure you want to clear all votes this user has received?")) {
			var avatarHover = $(event.currentTarget).closest('div[data-userid]');

			$.post(location.href, { m: Forum.preset_id, op: 'clear-user-votes', user_id: avatarHover.attr('data-userid') },
				function(response){
					// "success" means vote was processed, but there are no updates to the UI required
					// otherwise the response is a JSON encoded dataset with new UI display values
					if ( response == "success" )
					{
						document.location = location.href;
						location.reload(true);
					}
				}
			);
		}
		return false;
	},
	
	unhidePost: function( el, post_id )
	{       
	    var triggerBlock = $('tr[data-hidden-post-trigger=' + post_id + ']');
	    var action = ( triggerBlock.hasClass('hidden') ? 'hide' : 'unhide' );
		$.post(location.href, { m: Forum.preset_id, op: 'unhide-post', post_id: post_id, postAction: action },
			function(response){
                // "success" means vote was processed, but there are no updates to the UI required    
                // otherwise the response is a JSON encoded dataset with new UI display values
                if ( response == "success" ) 
                {           
                    // if we marked the post as unhidden, then we must not show the trigger block
                    // any more, admin still sees the vote admin conrols though
                    if ( action == 'unhide' )
                    {   
                        triggerBlock.addClass('hidden');		        
                        el.text('Hide Post');
                    }
                    // we re-hide a previously unhidden post, so show the post trigger block again
                    else    
                    {                       
                        triggerBlock.removeClass('hidden');
						$('tr[post_id=' + post_id + ']').addClass('hidden');
                        el.text('Unhide Post');
                    }
                }				    
			}
		);
	}, 
	    
    updatePostVotes: function( el, response )
    {
        var el = el.closest('.post-bottom');
        
        // display the the like avatars and count if the post is liked, hide it otherwise
        if ( typeof response.avatar_list === 'undefined' || response.avatar_list == '' )
        {
            el.find('.post-vote-avatars').hide();
        }
        else
        {
            el.find('.post-vote-avatars').show();
            el.find('.post-vote-avatars .avatar').html(response.avatar_list);
            el.find('.post-vote-avatars .votes').text(response.likes);
        }
     	
        // update the post users total forum vote count, do this access every avatar hover on this page for this user
        $('.avatar-hover-trigger[data-userid=' + response.user_id + ']').attr( 'data-votes', response.forum_votes);
        $('.avatar-hover-trigger[data-userid=' + response.user_id + ']').attr( 'data-up-votes', response.forum_up_votes);
        $('.avatar-hover-trigger[data-userid=' + response.user_id + ']').attr( 'data-down-votes', response.forum_down_votes);
        
        var votes = parseInt(response.forum_votes,10);
        var profileEl = $('div[data-userid=' + response.user_id + ']');
        profileEl.removeClass('positive').removeClass('negative');
        profileEl.addClass( (votes > 0 ? 'positive' : (votes < 0 ? 'negative' : '')) );
        profileEl.find('span').text( (votes > 0 ? '+' : '') + response.forum_votes );
        
        // update the vote count of this post
        votes = parseInt(response.votes,10);
        el.find('.post-controls .votes').text( (votes > 0 ? '+' : '') + response.votes);
        
        // remove the classes showing the button icon
        el.find('.post-controls .vote-button').removeClass('has-voted-down').removeClass('has-voted-up').removeClass('not-voted-down').removeClass('not-voted-up');
        
        // replace them with the button indicator showing what the user voted
        if ( response.thisVote == 1 )
        {
            el.find('.post-controls .vote-button.like').addClass('has-voted-up');
            el.find('.post-controls .vote-button.dislike').addClass('not-voted-down');
        }
        else if ( response.thisVote == -1 )
        {
            el.find('.post-controls .vote-button.like').addClass('not-voted-up');
            el.find('.post-controls .vote-button.dislike').addClass('has-voted-down');
        }
        else
        {
            el.find('.post-controls .vote-button.like').addClass('not-voted-up');
            el.find('.post-controls .vote-button.dislike').addClass('not-voted-down');
        }
    },
    
    showPopupBox: function( popupBox, event )
    {
		var forumModule = $('.m_forum');
		popupBox.css({
			top: event.pageY - forumModule.offset().top - popupBox.height() - 20,
			left: event.pageX - forumModule.offset().left - (popupBox.width()/2)
		});        
		popupBox.fadeIn(160);
		
		event.stopPropagation();
		
		$(document).one("click", function(event) { popupBox.fadeOut(160); });
		popupBox.find('a.cancel').click(function(event) {
			popupBox.fadeOut(160);
		});
		
		popupBox.bind('click', function(event) { event.stopPropagation(); });        
    },
    
    
    
	report: function(event, preset_id, post_id) {
		var limit_length = 256;
		event.stopPropagation();
		
		Enjin_Core.showPromptPopup({
			message: 'Report this post',
			width: 300,
			callback: function(msg) 
			{
				msg = $.trim(msg).substr(0, limit_length);				
				if (msg != '') 
				{
					$.post(Forum.ajaxurl, {
							cmd: 'report-forum', 
							preset_id: preset_id,
							post_id: post_id,
							reason: msg
						},
			    		function (response) {
							if (response.error != '') {
								Enjin_Core.alert(response.error);
							} else {
								
							}
						}, 'json');
				}
			}
		});
	}
}
