
/**
 * Flowplayer forum software By Tero Piirainen 2009
 *
 * http://www.flowplayer.org/forum
 *
 * Any questions to: these forums of course!
 *
 * Last modified: 	20.04.2009
 * Since: 				July 30 2008
 */
var forum = {

	// load chili only if nessessary
	format: function(els)  {

		if (typeof ChiliBook == 'object') {
			els.chili();

		} else {
			$.getScript("/js/jquery.chili.js", function() {
				forum.format(els);
			});
		}
	},

	progress: '<div id="progress"><img src="http://static.flowplayer.org/img/forum/progress.gif" /></div>',

	load: function(post, isReply) {

		var wrap = isReply ? $("#reply") : post.parent();
		var postId = post.attr("postId");
		var parentId = (isReply ? postId : post.attr("parentId")) || 0;
		var level = post.attr("level") || 0;
		if (isReply) level++;
		var edit = wrap.hasClass("editmode") || $("#newThread").length;


		// construct url
		var url = "/forum/post.jsp?parentId=" + parentId + "&level=" + level;
		if (!isReply && postId) url += "&id=" + postId;
		if (edit) url += "&edit=true";
		url += "&_=" + Math.random();
		if (isReply) $.scrollTo('#reply', {duration:1000, offset:-300});

		wrap.html(this.progress).load(url, function()  {

			wrap.find('ul.tabs').tabs('div.pane');
			wrap.find('textarea').TextAreaResizer();

			// new thread
			if (parentId == 0) {
				var title = $("#content h1:first em");
				wrap.find("input[name=title]").keyup(function() {
					title.text($(this).val() || 'New thread');
				});
			}
			forum.format(wrap.find("code"));

			// everything is read
			$("div.unread").removeClass("unread");

		});
	},


	newThread: function() {
		this.load($("#newThread div"));
	},

	reply: function (btn) {

		// remove previous reply
		$("#reply").remove();

		// remove edit buttons
		if (!account.admin) $("button:contains(Edit)").remove();

		var post = $(btn).parents("div.box");
		var spot = null;

		post.parent().nextAll("div.wrap").each(function() {
			var wrap = $(this);
			var level = wrap.children("div.box").attr("level");
			if (spot == null && level <= post.attr("level")) {
				spot = wrap;
			}
		});

		var wrap = $("#reply");
		if (!wrap.length) wrap = $('<div class="wrap" id="reply"></div>');

		if (spot != null) {
			wrap.insertBefore(spot);
		} else {
			wrap.insertAfter($("div.wrap:last"));
		}

		forum.load(post, true);
	},


	edit: function(btn) {
		var post = $(btn).parents("div.box");
		post.parent().addClass("editmode");
		forum.load(post);
	},


	save: function(btn) {
		var post = $(btn).parents("div.box"),
			 url = post.parent().hasClass("editmode") ?
			"/forum/edit?id=" + post.attr("postId") :
			"/forum/post?forumId=" + $("#forumId").val()
		;

		if ($("#newThread").length) {
			url += "&id=" + post.attr("postId");
		}

		$.post(url + "&" + post.find(":input").serialize(), function(json) {
			json = eval("(" + json + ")");

			if (json.message) {
				alert(json.message);
				
				// make it a little harder for spammers
				if (json.type == 'SPAM') {
					post.remove();	
					$(":button").hide();
				}

			} else {

				if ($("#newThread").length) {
					if (location.href.indexOf(".html") != -1) location.href = "?id=" + json.id;
					else location.href = json.id;

				} else {

					// remove all states
					post.parent().removeClass("editmode");
					$("#reply").removeAttr("id");

					post.attr("postId", json.id);
					forum.load(post);
				}
			}
		});

	},

	cancel: function(btn) {
		var post = $(btn).parents("div.box");

		// edit mode
		if (post.parent().hasClass("editmode")) {
			post.parent().removeClass("editmode");
			forum.load(post);

		// thread start topic
		} else if (!post.attr("parentId")) {
			var url = "../" + $("#forumId").val();
			if (location.href.indexOf("support") != -1) url = "support.html";
			location.href = url;

		// reply
		} else {
			post.slideUp(600, function()  {
				post.parent().hide();
			});

		}

	},

	preview: function() {
		var val = $("#postEdit textarea").val();
		var el = $("#postPreview");
		if (val != '') {
			el.html(forum.progress);
			$.post("/forum/preview", {body: val}, function(val) {
				el.html(val);
				forum.format(el.find("code"));
			});
		}
		else el.html("");
	},


	login: function(form) {
		form = $(form);
		var post = form.parents("div.box");
		post.fadeTo(400, 0.4);

		$.getJSON("/account/login?" + form.serialize(), function(json) {

			if (json.message) {
				form.find("div.error").html(json.message).show();
				post.fadeTo(400, 1);

			} else {
				forum.load(post);
			}

		});

		return false;
	},

	deletePost: function(btn, threadId) {

		var msg = "Are you sure you want to delete this post";
		if (account.admin) msg += " and its replies";

		if (confirm(msg + "?")) {

			var post = $(btn).parents("div.box");
			$.getJSON("/forum/delete?id=" + post.attr("postId"), function(json) {

				if (json.message) {
					alert(json.message);

				} else {
					if (account.admin) {
						alert(json.count + " posts deleted");
						location.reload();
					} else {
						var post = $(btn).parents("div.box").fadeOut();
					}
				}

			});
		}
	},

	markSolved: function(btn, threadId) {

		if (confirm("The issue in this thread will be marked as solved. Continue?")) {

			$.getJSON("/forum/markSolved?threadId=" + threadId, function(json) {

				if (json.message) {
					alert(json.message);
				} else {
					btn = $(btn);
					$("#content div.box:first").addClass("dark").find("h2").fadeIn();
					btn.remove();
				}
			});
		}

	}

}

$(function() {

	$("#subscribe").change(function()  {
		var el = $(this);
		var checked = this.checked;

		$.getJSON("/forum/subscribe?threadId=" +el.val()+ "&toggle=" + checked, function(json) {
			var label = el.next("label");
			if (checked) {
				label.html("Subscribed");
			} else {
				label.html("Subscribe to this thread");
			}
		});
	});

	$("#spam").click(function()  {
		var el = $(this), checked = this.checked, rand = Math.random().toString().substring(3, 7);

		// a simple validation
		if (!account.admin && prompt("Please supply this number " +rand+ "\nso that we know you are a human: ", "") != rand) {
			return this.checked = false
		};

		$.getJSON("/forum/spam?threadId=" +el.val()+ "&toggle=" + checked + "&check=" + rand, function(json) {
			var label = el.next("label");
			if (checked) {
				label.html("Spammed. Thanks!");
				el.attr("disabled", true);

			} else {
				label.html("Report spam");
			}
		});
	});



	$("#mover").change(function() {

		var el = $(this);
		var forumId = el.val();
		var title = el.find("option:selected").text();

		if (forumId && confirm("This thread will be moved to \"" + title + "\", continue?")) {

			var threadId = el.attr("threadId");
			el.fadeTo(100, 0.2);

			$.getJSON("/forum/move?threadId=" + threadId + "&forumId=" + forumId, function(json) {
				el.fadeTo(400, 1);
				el.next("span").html('Moved to <a href="/forum/' +forumId+ '/' +threadId+ '">' +title+ '</a>');
			});
		}

	});

});





/*
	jQuery TextAreaResizer plugin
	Created on 17th January 2008 by Ryan O'Dell
	Version 1.0.4

	Converted from Drupal -> textarea.js
	Found source: http://plugins.jquery.com/misc/textarea.js
	$Id: textarea.js,v 1.11.2.1 2007/04/18 02:41:19 drumm Exp $

	1.0.1 Updates to missing global 'var', added extra global variables, fixed multiple instances, improved iFrame support
	1.0.2 Updates according to textarea.focus
	1.0.3 Further updates including removing the textarea.focus and moving private variables to top
	1.0.4 Re-instated the blur/focus events, according to information supplied by dec


*/
(function($) {
	/* private variable "oHover" used to determine if you're still hovering over the same element */
	var textarea, staticOffset;  // added the var declaration for 'staticOffset' thanks to issue logged by dec.
	var iLastMousePos = 0;
	var iMin = 32;
	var grip;
	/* TextAreaResizer plugin */
	$.fn.TextAreaResizer = function() {
		return this.each(function() {
		    textarea = $(this).addClass('processed'), staticOffset = null;

			// 18-01-08 jQuery bind to pass data element rather than direct mousedown - Ryan O'Dell
		    // When wrapping the text area, work around an IE margin bug.  See:
		    // http://jaspan.com/ie-inherited-margin-bug-form-elements-and-haslayout
		    $(this).wrap('<div class="resizable-textarea"><span></span></div>')
		      .parent().append($('<div class="grippie"></div>').bind("mousedown",{el: this} , startDrag));

		    var grippie = $('div.grippie', $(this).parent())[0];
		    grippie.style.marginRight = (grippie.offsetWidth - $(this)[0].offsetWidth) +'px';

		});
	};
	/* private functions */
	function startDrag(e) {
		textarea = $(e.data.el);
		textarea.blur();
		iLastMousePos = mousePosition(e).y;
		staticOffset = textarea.height() - iLastMousePos;
		textarea.css('opacity', 0.25);
		$(document).mousemove(performDrag).mouseup(endDrag);
		return false;
	}

	function performDrag(e) {
		var iThisMousePos = mousePosition(e).y;
		var iMousePos = staticOffset + iThisMousePos;
		if (iLastMousePos >= (iThisMousePos)) {
			iMousePos -= 5;
		}
		iLastMousePos = iThisMousePos;
		iMousePos = Math.max(iMin, iMousePos);
		textarea.height(iMousePos + 'px');
		if (iMousePos < iMin) {
			endDrag(e);
		}
		return false;
	}

	function endDrag(e) {
		$(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag);
		textarea.css('opacity', 1);
		textarea.focus();
		textarea = null;
		staticOffset = null;
		iLastMousePos = 0;
	}

	function mousePosition(e) {
		return { x: e.clientX + document.documentElement.scrollLeft, y: e.clientY + document.documentElement.scrollTop };
	};
})(jQuery);


/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com
 * Licensed under GPL license (http://www.opensource.org/licenses/gpl-license.php).
 * Date: 2/8/2008
 * @author Ariel Flesler
 * @version 1.3.2
 */
;(function($){var o=$.scrollTo=function(a,b,c){o.window().scrollTo(a,b,c)};o.defaults={axis:'y',duration:1};o.window=function(){return $($.browser.safari?'body':'html')};$.fn.scrollTo=function(l,m,n){if(typeof m=='object'){n=m;m=0}n=$.extend({},o.defaults,n);m=m||n.speed||n.duration;n.queue=n.queue&&n.axis.length>1;if(n.queue)m/=2;n.offset=j(n.offset);n.over=j(n.over);return this.each(function(){var a=this,b=$(a),t=l,c,d={},w=b.is('html,body');switch(typeof t){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(t)){t=j(t);break}t=$(t,this);case'object':if(t.is||t.style)c=(t=$(t)).offset()}$.each(n.axis.split(''),function(i,f){var P=f=='x'?'Left':'Top',p=P.toLowerCase(),k='scroll'+P,e=a[k],D=f=='x'?'Width':'Height';if(c){d[k]=c[p]+(w?0:e-b.offset()[p]);if(n.margin){d[k]-=parseInt(t.css('margin'+P))||0;d[k]-=parseInt(t.css('border'+P+'Width'))||0}d[k]+=n.offset[p]||0;if(n.over[p])d[k]+=t[D.toLowerCase()]()*n.over[p]}else d[k]=t[p];if(/^\d+$/.test(d[k]))d[k]=d[k]<=0?0:Math.min(d[k],h(D));if(!i&&n.queue){if(e!=d[k])g(n.onAfterFirst);delete d[k]}});g(n.onAfter);function g(a){b.animate(d,m,n.easing,a&&function(){a.call(this,l)})};function h(D){var b=w?$.browser.opera?document.body:document.documentElement:a;return b['scroll'+D]-b['client'+D]}})};function j(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

