$(document).ready(function() {
	$("a.deletePost").click(function(){
		if (!confirm("Are you sure you want to delete that post?")) return false;
	});
	$("a.quote").click(function(){
		var textarea = $("#commentForm").find('textarea');
		var href = '#' + $(this).parent().parent().get(0).id;
		var username = $(this).parent().parent().find('a').get(0).innerHTML;
		var current = textarea.val();
		// this is so we don't get existing anchors
		var url = location.protocol + '//' + location.host + location.pathname + location.search + href;
		textarea.focus();
		textarea.val('In response to "' + username + '\'s post":' + url + ': \n' + current);
		setCaretPosition(textarea, textarea.val().length);
		return false;
	});
	$("#signature").keydown(function(){
		var max = 255;
		if ($(this).val().length > max)
			$(this).val($(this).val().substring(0, max));
		else
			$("#charsLeft").html(max - $(this).val().length);
		if (!$("#charsLeft").html().length) $("#charsLeft").html('0');
	});
	$("#signature").keyup(function() {
		$("#signature").keydown();
	});
	$("#signature").keyup();
	$("a.menuButton").one("click", openMenu);
	$("a.logout").click(function() { return confirmLogOut(); });
	$("input[name=emailaddress]").focus(function(){
		if ($(this).val() == "Email Address") {
			$(this).val("");
			$("input[name=password]").val("");
		}
	});

	$(window).bind('scrollstop', function(){
		var tId = location.pathname.split("/")[3];
		if ($("div#activityFrame").size() < 1 && tId > 0) {
			var buffer = 300;
			if  ($(window).scrollTop() > $(document).height() - ($(window).height() + buffer)) {
				if ($("div#nextPost").size() < 1) {
					$.get(location.protocol + '//' + location.host + "/forum/callback/getNextThreadHTML", { threadId: tId }, function(d) {
						if ($("div#nextPost").size() < 1 && d.length > 0) {
							$("body").append('<div id="nextPost">' + d + '</div>');
							$("div#nextPost").css("left", $(window).width() + 'px');
							$("div#nextPost").css("cursor", 'pointer');
							$("div#nextPost").show();
							var getWidth = $(window).width() - $("div#nextPost").width();
							$("div#nextPost").stop().animate({left: +getWidth}, {queue: false, duration: 800});
							$("div#nextPost").click(function(){
								location.href = $(this).children("a").attr("href");
								return false;
							});
							$("div#nextPost").fadeTo("fast", 0.5);
							$("div#nextPost").hover(function(){
								$(this).fadeTo("fast", 1);
							}, function(){
								$(this).fadeTo("fast", 0.5);
							});
						}
					});
				}
			} else {
				var getWidth = $(window).width();
				$("div#nextPost").animate({left: +getWidth}, 800, function(){
					$("div#nextPost").remove();
				});
			}
		}
	});
});

function trackThreadView(tId) {
	$.get(location.protocol + '//' + location.host + "/forum/callback/trackThreadView", { threadId: tId } );
}

function sendPing() {
	$.get(location.protocol + '//' + location.host + "/forum/callback/ping", { url: escape(document.location.href) } );
	setTimeout("sendPing()", 60000);
}

function doGetCaretPosition (ctrl) {
	var CaretPos = 0;
	if (document.selection) {
		ctrl.focus ();
		var Sel = document.selection.createRange();
		Sel.moveStart ('character', -ctrl.value.length);
		CaretPos = Sel.text.length;
	} else if (ctrl.selectionStart || ctrl.selectionStart == '0')
		CaretPos = ctrl.selectionStart;
	return (CaretPos);
}

function setCaretPosition(ctrl, pos) {
	if(ctrl.setSelectionRange) {
		ctrl.focus();
		ctrl.setSelectionRange(pos,pos);
	} else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

function openMenu(e) {
	var button = $(this).addClass('activeButton');
	var menu = $("#menuButtonNav");
	var offset = button.offset();
	var h = (button.outerHeight) ? button.outerHeight() : button.height();
	var w = (button.outerWidth) ? button.outerWidth() : button.width();
	var mw = (menu.outerWidth) ? menu.outerWidth() : menu.width();
	if (jQuery.browser.safari) mw = mw + 1;
	menu.addClass('activeButton').css({ 'top': offset.top + h - 1, 'left': offset.left - (mw - w) + 1}).click(function(e) {
		e.stopPropagation();
	}).show(1, function() {
		$(document).one('click', {button: button, menu: menu}, closeMenu);
	});
	return false;
}

function closeMenu(e) {
	e.data.menu.removeClass('activeButton').hide(100, function() {
	    e.data.button.removeClass('activeButton');
	});
	e.data.button.one('click', openMenu);
	return false;
}

function confirmLogOut() {
	return confirm("Are you sure you want to logout of bmindful?");
}

(function(){
    var special = jQuery.event.special,
        uid1 = 'D' + (+new Date()),
        uid2 = 'D' + (+new Date() + 1);
 
    special.scrollstart = {
        setup: function() {
 
            var timer,
                handler =  function(evt) {
 
                    var _self = this,
                        _args = arguments;
 
                    if (timer) {
                        clearTimeout(timer);
                    } else {
                        evt.type = 'scrollstart';
                        jQuery.event.handle.apply(_self, _args);
                    }
 
                    timer = setTimeout( function(){
                        timer = null;
                    }, special.scrollstop.latency);
 
                };
 
            jQuery(this).bind('scroll', handler).data(uid1, handler);
 
        },
        teardown: function(){
            jQuery(this).unbind( 'scroll', jQuery(this).data(uid1) );
        }
    };
 
    special.scrollstop = {
        latency: 300,
        setup: function() {
 
            var timer,
                    handler = function(evt) {
 
                    var _self = this,
                        _args = arguments;
 
                    if (timer) {
                        clearTimeout(timer);
                    }
 
                    timer = setTimeout( function(){
 
                        timer = null;
                        evt.type = 'scrollstop';
                        jQuery.event.handle.apply(_self, _args);
 
                    }, special.scrollstop.latency);
 
                };
 
            jQuery(this).bind('scroll', handler).data(uid2, handler);
 
        },
        teardown: function() {
            jQuery(this).unbind( 'scroll', jQuery(this).data(uid2) );
        }
    };
 
})();