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('.element_popup');
		var submit = popupBox.find('input.submit');
		var select = popupBox.find('select.move-location');
		
		select.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);
				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');
		
		$.post(location.href, { m: Forum.preset_id, op: "delete-post", post_id: post_id },
			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;
				}
			}
		);
		
	},
	
	moderateThread: function(operation, setting, gotoURL)
	{
		$.post(location.href, { m: Forum.preset_id, op: operation, setting: setting},
			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;
	},
	
	autoImgResize: function()
	{
		$('.m_forum img.bbcode_img').each(function(i){
			if(this.width > 499)
			{
				var myParent = $(this).parent().get(0);
				if(myParent.tagName != 'A')
				{
					this.style.cursor = 'pointer';
					this.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;
	},
	
	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);
	}
}