// *************************
// Threaditor panel.
// *************************
function Threaditor() {
	this.template = "<form> \
						<input id='GC_thread_title' type='text' name='title' value='' /> \
						<div id='GC_handle'>drag me</div> \
						<textarea id='GC_thread_wysiwyg' name='body' cols='128' rows='6'></textarea> \
						<div id='GC_thread_info'><a href='http://www.phpbb.com/community/faq.php?mode=bbcode#f0r0' target='_blank'>BBCode</a> | <a href='http://www.w3schools.com/html/html_intro.asp' target='_blank'>HTML</a></div> \
						<a id='GC_thread_cancel' href='#'>Cancel</a> \
						<button id='GC_thread_submit' type='submit'><span>Submit</span></button>  \
					</form>";
	this.isAppended = false;
	this.panel      = undefined;
	this.quote      = undefined;
	// Post information
	this.post = {
		title: $('#thread_topic_title').html(),
		topic: undefined,
		cat:   undefined,
		body:  undefined
	};
	// Initializer
	this.init = function() {
		// Cache ThreadPoster object.
		var thread = this;
		// Bind replies/quotes. We should probably put id's to make the selector not quite so brutal.
		$('.thread_reply, .thread_quote').click( function() {
			thread.reply(this.href); return false;
		});

		// Bind the cancel button.
		$('#GC_thread_cancel').live('click', function() { thread.panelToggle(true); return false; });
	};
	// Builds and slaps the forum panel in the DOM.
	this.panelAppend = function() {
		var thread = this;
		
		// Build the panel container
		this.panel = $('<div/>').attr('id', 'GC_thread_panel');

		// Add the form template and markItUp bro.
		this.panel.html(this.template).find('#GC_thread_wysiwyg').markItUp(mySettings);
		// Bind and attach handle properties to the handle.
		this.bindHandle(this.panel, this.panel.find('#GC_handle'));
		
		this.panel.appendTo('body');
		
		// Bind the panels submit.
		$('#GC_thread_panel form').submit(function() {
			thread.submitPost(this); return false;
		});
		
		this.isAppended = true;
	};
	this.bindHandle = function(panel, h) {
		h.bind("mousedown", function(e) {
			var p  = panel.height(), w = window.innerHeight;
			mouseMove = function(e) {
				var h = w-e.clientY;
				if ( (h > 280) && (h <= w) ) { panel.css("height", h+"px"); }
				return false;
			};
			mouseUp = function(e) {
				$("html").unbind("mousemove", mouseMove).unbind("mouseup", mouseUp);
				return false;
			};
			$("html").bind("mousemove", mouseMove).bind("mouseup", mouseUp);
			return false;
		});
	};
	this.panelToggle = function(close) {
		// Default attr to false.
		if ( close === undefined) { close = false; }
		// Add the drawer if it's not there
		if (this.panel == undefined) { this.panelAppend(); }
		// Toggle drawer open and closed
		if ( (close === true) || !this.panel.hasClass('active') ) {
			this.panel.slideToggle(200).toggleClass('active');
		}
	};
	this.reply = function(threadUri) {
	
		// Split the uri for post data and cache the length
		var uriSegs = threadUri.split('/'), lng = uriSegs.length;
		
		// Toggle the panel.
		this.panelToggle();
		
		// Set our default input
		$('#GC_thread_title').val('Re: '+ this.post.title);
		
		// We be quotin. 
		if (uriSegs[lng - 1].match(/\d+/)) {
			
			// Same post? return nothing.
			if ( this.quote == uriSegs[lng - 1] ) { return; }
			
			// Store the info we need
			this.quote      = uriSegs[lng - 1];
			this.post.topic = uriSegs[lng - 3];
			this.post.cat   = uriSegs[lng - 4];
			
			// Load up the quote from the db.
			this.loadQuote(this.quote, this);
		// We be replyin.
		} else {
			$('#GC_thread_wysiwyg').val('');
			this.quote      = undefined; 
			this.post.topic = uriSegs[lng - 2]; 
			this.post.cat   = uriSegs[lng - 3];
		}
		
	};
	this.loadQuote = function(replyId, thread) {
		// Cache the body.
		var body = $('#GC_thread_wysiwyg');
		
		// Ajax call, if you didn't notice.
		this.sendPost('getQuote', {'reply_id': replyId }, 
			function()     { body.val('Fetching user quote, Please Wait...'); },
			function(data) { body.val(data.response); }
		);
	};
	// Ajax utility function
	this.sendPost = function(m,d,b,s) {
		$.ajax({
			type: "POST", url: "/ajax/forum",
			data: { 'f': m, 'data': d}, dataType: 'json',
			beforeSend: b, success: s
		});
	};
	// Process post.
	this.submitPost = function(form) {
		// Fail if there is client side errors
		if ( this.validate() === false ) { return false; }

		var inputs = $(form).serializeArray(), submitBtn = $('#GC_thread_submit'), panel = this.panel;
		this.post.title = inputs[0].value; 
		this.post.body  = inputs[1].value;
		
		this.sendPost( 'post', this.post,
			function(){ submitBtn.attr('disabled', 'true').find('span').html('Posting...'); },
			function(data){ 
				// We errored. handle it.
				if (data.status == 'FAIL') {
					submitBtn.removeAttr('disabled').find('span').html('Post');
					return false;
				}
				// Close the panel and redirect to their post.
				panel.slideToggle(200, function() { 
					var d = $('<div/>').attr({'id': 'dialog', 'title': 'Your post was successful!'});
					d.html('<p>We are redirecting to your post in 2 seconds, <a href='+data.redirect+'>click here</a> to go there now</p>');
					d.appendTo('body').dialog({modal: true});
					
					// Redirect to post.
					window.location.replace(data.redirect);
				});
			}
		);
	};
	this.validate = function() {
		// Validate against an empty body
		var threadBody = $('#GC_thread_wysiwyg');
		if (threadBody.val().length < 3) { 
			// Adds listener to remove the error.
			threadBody.focus(function() { threadBody.removeClass('error'); });
			// Add error class
			threadBody.addClass('error'); return false; 
		} else { 
			threadBody.removeClass('error'); return true; 
		}
	};
}


// ***********************************************
//
// AJAX method to flag a forum post.
//
//***********************************************
function AJAX_REQ_flagPost(id, reason) {
	$.ajax({
		type: "POST",
		url: "/ajax/forum",
		data: {"f":"flagPost", "id":id, "reason":reason},
		dataType: "json",
		success: AJAX_RES_flagPost
	});
}

function AJAX_RES_flagPost(data, status) {
	// Stub function for future development
	return true;
}
//***********************************************


//***********************************************
//
// AJAX method to UN-flag a forum post.
//
//***********************************************
function AJAX_REQ_unflagPost(id) {
	$.ajax({
		type: "POST",
		url: "/ajax/forum",
		data: {"f":"unflagPost", "id":id},
		dataType: "json",
		success: AJAX_RES_flagPost
	});
}

function AJAX_RES_unflagPost(data, status) {
	// Stub function for future development
	return true;
}
//***********************************************


$(document).ready(function() {
	// Add event listener for flagging a post
	$("a[name^=flag_post]").live('click', function() {
		// Get reason
		if($(this).attr('name') == 'flag_post_inappropriate') var reason = 'inappropriate';
		else var reason = 'spam';
		
		// Submit request
		AJAX_REQ_flagPost($(this).attr('rel'), reason);
		
		// Change button name
		$(this).attr('name', 'unflag_post');
		
		// Change button label
		$(this).find('span').html('Unflag post');
		
		// Remove other button
		if(reason == 'spam') $('a[name=flag_post_inappropriate][rel='+$(this).attr('rel')+']').remove();
		else $('a[name=flag_post_spam][rel='+$(this).attr('rel')+']').remove();
	});
	
	// Add event listener to UN-flag a forum post
	$("a[name=unflag_post]").live('click', function() {
		// Submit request
		AJAX_REQ_unflagPost($(this).attr('rel'));
		
		// Change button name
		$(this).attr('name', 'flag_post_inappropriate');
		
		// Change button label
		$(this).find('span').html('Flag post as inappropriate');
		
		// Add SPAM button back
		$(this).parent().append("<a name='flag_post_spam' rel='"+$(this).attr('rel')+"'><span>Flag post as spam</span></a>");
	});
	
	// Setup our thread object.
	var thread = new Threaditor();
	// Remove comment below to play.
	thread.init();
	
});