/**
 * [Copyright]
 * 
 * Copyright (c) 2009, WebAlive Pty. Ltd.
 */

var closedItems = new Object();

tinyMCE.init({
	mode: 'exact',
	elements: 'CommentComment',
	tab_focus : 'ComentComment',
    theme : 'advanced',
    plugins : 'safari,inlinepopups,insertdatetime,spellchecker',
    theme_advanced_buttons1 : 'bold,italic,underline,|,link,unlink,|,spellchecker',
    theme_advanced_buttons2 : '',
    theme_advanced_buttons3 : '',
    theme_advanced_toolbar_location : 'top',
    theme_advanced_toolbar_align : 'left',
    theme_advanced_statusbar_location : "none",
    theme_advanced_resizing : false,
});

/**
 * run when the page is ready to load
 */
$(document).ready(function() {	
	// check for new comments every min
	if (window.jsonVars['topic'].status == 'Open') {
		updateTimer.init();
	}
	
	// bind a click event to all .expand elements & any future .expand elements
	$(".expand a").live("click", function(){
		minimizeComment.toggle($(this));
		return false;
	});	
	
	// bind a click event to all .vote elements & and future .vote elements
	$(".vote").live("click", function(){
		vote.send($(this));
		return false;
	});
	
	// ajax posting of comments
	var commentForm = $('#CommentAddForm');
	commentForm.ajaxForm({
		dataType: 'json',		
		success: function(data) {
			commentForm.find('div.submit img.spinner').remove();
			commentForm.find('div.submit button').removeAttr('disabled');
			
			if (data.Errors) {
				for (var i in data.Errors) {
					commentForm.find("div.input :input[name='data[Comment]["+i+"]']").addClass('form-error').after('<div class="error-message">'+data.Errors[i]+'</div>');
				}
			}
			
			if (data.ErrorMessage) {
				WC.basicDialog(data.ErrorMessage, "Error");
			}
			
			if (data.Success) {
				$("#CommentComment").val("");
				$('div.charsLeft:first span:first').html(window.jsonVars['topic'].max_comment_length);
				WC.basicDialog(data.Message, "Comment posted");
			}
		},
		beforeSubmit: function(formData, jqForm, options) {
			tinyMCE.triggerSave();
			$.each(formData, function() {
				if (this.name == 'data[Comment][comment]') {
					this.value = $('#CommentComment').val();
				}
			})			
			jqForm.find("div.input :input").removeClass('form-error');
			jqForm.find('div.error-message').remove();
			jqForm.find('div.submit button').after('<img src="/img/spinner.gif" class="spinner" alt="spinner" />');
			jqForm.find('div.submit button').attr('disabled', 'disabled');
		},
		error: function() {
			WC.basicDialog("Request failed. Please try again later.", "Error");
			commentForm.find('div.submit img.spinner').remove();
			commentForm.find('div.submit button').removeAttr('disabled');
		}
	});
});

/**
 * sends an ajax request to check if any new comments have been posted
 */
var updateTimer = {
	timer: false, 
	init: function() {
		this.setTimer();
	}, 
	doCall: function() {
		$.getJSON("/forum/topics/check_comments/"+window.jsonVars['topic'].id+"/avoidcache:"+updateTimer.randomNum(), function(data) {
			if (data.NewComments == 'yes') {
				$('div.commentList').load('/forum/topics/view/'+window.jsonVars['topic'].slug+'/avoidcache:'+updateTimer.randomNum());

				for (var i in data.Comments) {
					$.jGrowl(
						"<span>"+data.Comments[i].Comment.author+"</span> posted a new comment. Would you like to <a href='#comment-"+data.Comments[i].Comment.id+"'>view it now?</a>", 
						{ header: 'New comment', life: 10000 }
					);					
				} 
			}
		});		
		
		updateTimer.setTimer();
	}, 
	setTimer: function() {
		clearTimeout(updateTimer.timer);
		this.timer = setTimeout(updateTimer.doCall, 20000);			
	},
	randomNum: function() {
		return Math.floor(Math.random()*1000001);
	}
};

/**
 * Allows a comment group to be minimized 
 */
var minimizeComment = {
	toggle: function(element) {
		var cookieName = "topic"+window.jsonVars['topic'].id;
		var parentLi = element.toggleClass("close").parents("li:first");
		parentLi.toggleClass("closed");
		element.html((element.html() == "Hide") ? "Show" : "Hide");
	
		if (parentLi.hasClass("closed")) {
			closedItems[parentLi.attr("id")] = true;
		} else {
			closedItems[parentLi.attr("id")] = false;
		}
		
		var newCookie = $.extend($.evalJSON($.cookie(cookieName)), closedItems);
		$.cookie(cookieName, $.toJSON(newCookie), { expires: 2 });		
	}
};

/**
 * AJAX vote on a comment
 */
var vote = {
	send: function(e) {
		e.parents("cite").find(".showvote").after('<img src="/img/spinner.gif" id="voteSpinner" alt="spinner" />');
		$.get(e.attr("href"), function(data) {
			$("#voteSpinner").remove();
			if (data == '"Success"') {
				WC.basicDialog("Your vote has been cast.", "Thanks");
			} else if (data == '"LimitExceeded"') {
				WC.basicDialog("You have exceeded the voting limit for this topic.", "Warning");
			} else {
				var randomId = 'dialog'+Math.floor(Math.random()*1001);
				$('body').append('<div title="Enter your details" id="'+randomId+'">'+data+'</div>');
				$("#"+randomId+" div.submit, #"+randomId+" h3").remove();
				$("#"+randomId).dialog({
					bgiframe: true,
					modal: true,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					buttons: {
						'Vote': function() {
							var daForm = $("#commentVoteForm form");
							daForm.ajaxSubmit({
								dataType: 'json',		
								success: function(data) {
									if (data.Errors) {
										for (var i in data.Errors) {
											daForm.find("div.input :input[name='data[Voter]["+i+"]']").addClass('form-error').after('<div class="error-message">'+data.Errors[i]+'</div>');
										}
									}
									if (data == "Success") {
										$("#"+randomId).dialog("close");
										WC.basicDialog("Your vote has been cast.", "Thanks");
									}
									if (data == "LimitExceeded") {
										$("#"+randomId).dialog("close");
										WC.basicDialog("You have exceeded the voting limit for this topic.", "Warning");
									}
								},
								beforeSubmit: function(formData, jqForm, options) {
									daForm.find("div.input :input").removeClass('form-error');
									daForm.find('div.error-message').remove();
								},
								error: function() {
									WC.basicDialog("Request failed. Please try again later.", "Error");
									daForm.find('div.submit img.spinner').remove();
								}
							});
						},
						Cancel: function() {
							$(this).dialog('close');
						}
					}
				});
			}	
		});
	}
};
