// $id $

if (typeof(Drupal) == "undefined" || !Drupal.tribune) {    
   Drupal.tribune = {};
}

Drupal.tribune.isElementVisible = function (jq) {
    element = jq.get(0);

    var scrollY = 0;
    if (window.pageYOffset) {
        scrollY = window.pageYOffset;
    } else if (document.body && document.body.scrollTop) {
        scrollY = document.body.scrollTop;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        scrollY = document.documentElement.scrollTop;
    }

    var posY = 0;
    if (element.offsetParent) {
        for (var posY = 0 ; element.offsetParent ; element = element.offsetParent) {
            posY += element.offsetTop;
        }
    } else {
        posY = element.y;
    }

    return posY < scrollY;
}

/*
 * Submit comment with javascript.
 *
 */

Drupal.tribune.ajaxifyForm = function () {
        
	var options = {
		url: Drupal.settings.tribune.path.post,
        resetForm: true,
        beforeSubmit: Drupal.tribune.validate,
        success: Drupal.tribune.formSuccess,
		error: Drupal.tribune.formError
    };

	if (Drupal.settings.tribune.block) {
		$("#tribune-add-form-block").ajaxForm(options);
	} else {
		$("#tribune-add-form").ajaxForm(options);
	}
}

/**
  * Display response text and update the color
  * field. Remove top message if we are over 
  * the max count. 
  */

Drupal.tribune.formSuccess = function (responseText) {
    $(".tribune-post-form .form-submit").removeAttr("disabled");
    Drupal.tribune.palmipede.removeAttr("disabled").removeAttr("readonly");
    Drupal.tribune.palmipede.removeClass("tribune-error");
	
    Drupal.tribune.loadPosts();

	Drupal.tribune.palmipede.get(0).focus();
}

Drupal.tribune.formError = function (responseText) {
    $(".tribune-post-form .form-submit").removeAttr("disabled");
    Drupal.tribune.palmipede.removeAttr("disabled").removeAttr("readonly");
    Drupal.tribune.palmipede.addClass("tribune-error");

	Drupal.tribune.palmipede.get(0).focus();
}


/**
 * Creates a timer that triggers every delay seconds.
 */
Drupal.tribune.startTimer = function(delay) {
	Drupal.tribune.interval = setInterval("Drupal.tribune.loadPosts()", delay);	
}

Drupal.tribune.startReloading = function() {
    $('#tribune-reload-img').addClass("tribune-active");
}

Drupal.tribune.endReloading = function() {
    $('#tribune-reload-img').removeClass("tribune-active");
}

/**
 * Reloads all posts from the server.
 */
Drupal.tribune.loadPosts = function() {
    Drupal.tribune.startReloading();

    Drupal.tribune.loadJSONPosts();
}

Drupal.tribune.loadJSONPosts = function() {
    res = $.ajax({url: Drupal.settings.tribune.path.json_posts + "/" + Drupal.settings.tribune.last_load_time + "/" + Math.random() + "/json-reload",
			     dataType: "json",
			     success: Drupal.tribune.JSONSuccess,
			     error: Drupal.tribune.JSONError,
			     complete: Drupal.tribune.JSONComplete
	});
}

Drupal.tribune.JSONSuccess = function (json) {
    Drupal.tribune.palmipede.removeClass("tribune-error");

	if (json.help.length > 0) {
		for (i = 0 ; i < json.help.length ; i++) {
			if (json.help[i] && json.help[i].filter) {
				$('#tribune-description-' + json.help[i].filter).html (json.help[i].string);
			}
		}
	}

	var new_posts = [];

	if (json.posts.length > 0) {
		Drupal.settings.tribune.last_load_time = json.time;

		for (i = 0 ; i < json.posts.length ; i++) {
			if (json.posts[i]) {
				post = $(json.posts[i].text);

				existing_post = Drupal.tribune.pinnipede.find('li#post-' + json.posts[i].id);
				if (json.posts[i].text) {
					if (json.posts[i].moderated) {
						post.addClass("tribune-moderated-post");
					}

					if (existing_post.length == 1) {
						existing_post.replaceWith(post);

						new_posts.push(post);
						Drupal.tribune.postElements[json.posts[i].id] = post;
					} else {
						var first_id = 0;
						var first = Drupal.tribune.pinnipede.find('li:first');

						if (first.length > 0) {
							var first_id_array = first.attr("id").split("-");
							if (first_id_array.length == 2) {
								first_id = first_id_array[1];
							}
						}

						if (json.posts[i].id >= first_id) {
							while (Drupal.tribune.pinnipede.find('li').length >= Drupal.settings.tribune.history_size) {
								Drupal.tribune.pinnipede.find('li:first').each(function () {
									var id_array = $(this).attr("id").split("-");
									if (id_array.length == 2) {
										delete Drupal.tribune.postElements[id_array[1]];
									}
									$(this).remove();
								});
							}

							post.appendTo(Drupal.tribune.pinnipede);
							new_posts.push(post);
							Drupal.tribune.postElements[json.posts[i].id] = post;
						}
					}
				} else if (json.posts[i].ref && existing_post) {
					existing_post.attr("ref", json.posts[i].ref);
				} else {
					if (existing_post.length == 1) {
						existing_post.remove();
						delete Drupal.tribune.postElements.remove[json.posts[i].id];
					}
				}
			}
		}

		for (i in Drupal.settings.tribune.after_reload) {
			for (j in new_posts) {
				Drupal.settings.tribune.after_reload[i](new_posts[j]);
			}
		}
	}
}

Drupal.tribune.JSONError = function (json) {
    $(".tribune-post-form .form-submit").removeAttr("disabled");
    Drupal.tribune.palmipede.removeAttr("disabled").removeAttr("readonly");
    Drupal.tribune.palmipede.addClass("tribune-error");
}

Drupal.tribune.JSONComplete = function (json) {
    Drupal.tribune.endReloading();
}

/**
 * Validate input before submitting.
 * Don't accept empty strings.
 */

Drupal.tribune.validate = function (formData, jqForm, options) {
    var form = jqForm[0];		
    if (!form.message.value) {
        return true;
    }

    $(".tribune-post-form .form-submit").attr("disabled", "disabled");
    Drupal.tribune.palmipede.attr("disabled", "disabled").attr("readonly", "readonly");
    return true;	
}

Drupal.tribune.setOnHovers = function(nodes) {
	nodes.find(".tribune-clock").mouseover(function() {
			var attr = $(this).attr('ref');
			if (attr) {
				var refs = attr.split('|');
				var search_ajax = "";
				for (var i = 0 ; i < refs.length ; i++) {
					var node = Drupal.tribune.postElements[refs[i]];
					if (node) {
						Drupal.tribune.showPreview(node);
						Drupal.tribune.highlightMainPost(node);
					} else {
						search_ajax = search_ajax + ",#post-" + refs[i];
					}
				}
				if (search_ajax.length) {
					var nodes = Drupal.tribune.pinnipede.find("#tribune-nothing," + search_ajax);
					Drupal.tribune.highlightElement($(this));
					Drupal.tribune.showAjaxPreview(refs[0]);
				}
			}
		});

	nodes.find(".tribune-clock").mouseout(Drupal.tribune.unHighlightAllPosts);

	nodes.find(".tribune-first-clock").click(function() {
			Drupal.tribune.insertIntoPalmipede($(this).text() + " ");
		});
	
	nodes.find(".tribune-first-clock").mouseover(function() {
			Drupal.tribune.highlightMainPost($(this).parent());
		});
	
	nodes.find(".tribune-first-clock").mouseout(Drupal.tribune.unHighlightAllPosts);

	nodes.find(".tribune-login").click(function() {
			Drupal.tribune.insertIntoPalmipede($(this).text() + "< ");
		});

	nodes.find(".tribune-moderate-post a").click(function() {
			$.ajax({
				url: $(this).attr('href'),
			    success: Drupal.tribune.loadPosts
			});

			return false;
		});
}

Drupal.tribune.insertIntoPalmipede = function(text) {
	var palmipede = Drupal.tribune.palmipede;
	var message = palmipede.val();
	var range = Drupal.tribune.getSelectionRange(palmipede.get(0));
	palmipede.get(0).focus();
	palmipede.val(message.substring(0, range[0]) + text + message.substring(range[1], message.length));
    Drupal.tribune.setSelectionRange(palmipede.get(0), range[0] + text.length, range[0] + text.length);
}

Drupal.tribune.insertTagIntoPalmipede = function(tag) {
	var palmipede = Drupal.tribune.palmipede;
	var message = palmipede.val();
	var range = Drupal.tribune.getSelectionRange(palmipede.get(0));
	palmipede.get(0).focus();
	palmipede.val(message.substring(0, range[0]) + "<" + tag + ">" + message.substring(range[0], range[1]) + "</" + tag + ">" + message.substring(range[1], message.length));
    Drupal.tribune.setSelectionRange(palmipede.get(0), range[1] + 3, range[1] + 3);
}

Drupal.tribune.getSelectionRange = function(field) {
    if (field.setSelectionRange) {
        return [field.selectionStart, field.selectionEnd];
	} else if (field.createTextRange) {
        var range = document.selection.createRange();

		if (range.parentElement() == field) {
			var range2 = field.createTextRange();
			range2.collapse(true);
			range2.setEndPoint('EndToEnd', range);
			return [range2.text.length - range.text.length, range2.text.length];
		}
    }
    return [field.value.length, field.value.length];
}

Drupal.tribune.setSelectionRange = function(field, start, end) {
    if (field.setSelectionRange) {
        field.setSelectionRange(start, end);
	} else if (field.createTextRange) {
		var range = field.createTextRange();
		range.collapse(true);
		range.moveStart('character', start);
		range.moveEnd('character', end - start);
		range.select();
    }
}

Drupal.tribune.showPreview = function(node) {
	if (node.length && Drupal.tribune.isElementVisible(node)) {
		Drupal.tribune.message_preview_element.html(Drupal.tribune.message_preview_element.html() + node.html());
		Drupal.tribune.message_preview_element.addClass('tribune-displayed');
	} else {
		Drupal.tribune.message_preview_element.removeClass('tribune-displayed');
		Drupal.tribune.message_preview_element.html("");
	}
}

Drupal.tribune.showAjaxPreview = function(node_id) {
	Drupal.tribune.message_preview_element.addClass('tribune-displayed');
	Drupal.tribune.message_preview_element.html("...");

    res = $.getJSON(Drupal.settings.tribune.path.json_post + "/" + node_id, function(json) {

        if (json.text) {
			var node = Drupal.tribune.message_preview_element.html(json.text);
			node.attr('ref', json.ref);
			Drupal.tribune.highlightMainPost(node);
		} else {
			Drupal.tribune.message_preview_element.removeClass('tribune-displayed');
		}
    });
}

Drupal.tribune.highlightMainPost = function(node) {
	node.addClass('tribune-highlighted-main-post');
	Drupal.tribune.highlightedElements.push(node);
	var ref = node.attr('ref');

	if (ref) {
		var referencesTo = ref.split('|');

		for (var k = 0 ; k < referencesTo.length ; k++) {
			var ref = referencesTo[k].split('#');
			
			if (ref.length == 2) {
				var refPostId  = ref[0];
				var refClockId = ref[1];

				Drupal.tribune.highlightClock(refPostId, refClockId);
			}
		}
	}
}

Drupal.tribune.highlightClock = function(postid, clockid) {
	var node = Drupal.tribune.postElements[postid];
	if (node) {
		clock = node.find('#post-' + postid + '-clock-' + clockid);
		Drupal.tribune.highlightElement(clock);
	}
}

Drupal.tribune.highlightElement = function(node) {
	node.addClass('tribune-highlighted-answer-clock');
	Drupal.tribune.highlightedElements.push(node);
}

Drupal.tribune.unHighlightAllPosts = function() {
	Drupal.tribune.message_preview_element.removeClass('tribune-displayed');
    Drupal.tribune.message_preview_element.html("");

	while (Drupal.tribune.highlightedElements.length) {
		Drupal.tribune.highlightedElements.pop().removeClass('tribune-highlighted-main-post').removeClass('tribune-highlighted-answer-clock');
	}
}


Drupal.tribune.keyboardShortcuts = function(e) {
	var actions = {
		66: {tag: 'b'},
		73: {tag: 'i'},
		77: {tag: 'm'},
		83: {tag: 's'},
		85: {tag: 'u'},
		65: {text: '[:aloy] '},
		74: {text: '\\o/ '},
		75: {text: '/o\\ '},
		79: {text: '_o/* <b>BLAM</b> ! '},
		80: {text: '_o/* <b>paf</b> ! '},
		82: {text: '[:uxam] '}
	};

    if (e && e.altKey && actions[e.keyCode]) {
		if (actions[e.keyCode].tag) {
			Drupal.tribune.insertTagIntoPalmipede(actions[e.keyCode].tag);
		} else if (actions[e.keyCode].text) {
			Drupal.tribune.insertIntoPalmipede(actions[e.keyCode].text);
		}

        if (e.preventDefault) {
            e.preventDefault();
        }
	}
}
	
if (Drupal.jsEnabled) {
    $(document).ready(function() {
			Drupal.tribune.highlightedElements = new Array();
			Drupal.tribune.message_preview_element = $('#tribune-message-preview');
			Drupal.tribune.palmipede = $(".tribune-post-form #tribune-palmipede");
			Drupal.tribune.pinnipede = $("ul.tribune-posts");

			Drupal.tribune.postElements = {};

			Drupal.tribune.ajaxifyForm();
			Drupal.tribune.setOnHovers(Drupal.tribune.pinnipede);

			Drupal.tribune.pinnipede.find('li').each(function() {
				var id_array = $(this).attr("id").split("-");
				if (id_array.length == 2) {
					Drupal.tribune.postElements[id_array[1]] = $(this);
				}
			});

			$(document).keydown(Drupal.tribune.keyboardShortcuts);

			if (Drupal.settings.tribune.reload_delay > 0) {
				Drupal.tribune.startTimer(Drupal.settings.tribune.reload_delay);
			}	

			if (!Drupal.settings.tribune.block) {
				Drupal.tribune.palmipede.get(0).focus();
			}

			Drupal.settings.tribune.after_reload = [Drupal.tribune.setOnHovers];
		}
	);
}

