try {
	document.execCommand("BackgroundImageCache", false, true);
} catch (e) {
}

JSHTML.config.delimiters = ['', ''];

$(document).ready(function() {
	JSHTML.parse();
	
	// Comments
	$.fn.insertAtCaret = function (myValue) {
		return this.each(function() {
			// IE support
			if (document.selection) {
					this.focus();
					sel = document.selection.createRange();
					sel.text = myValue;
					this.focus();
			}
			// MOZILLA / NETSCAPE support
			else if (this.selectionStart || this.selectionStart == '0') {
					var startPos = this.selectionStart;
					var endPos = this.selectionEnd;
					var scrollTop = this.scrollTop;
					this.value = this.value.substring(0, startPos)+ myValue+ this.value.substring(endPos,this.value.length);
					this.focus();
					this.selectionStart = startPos + myValue.length;
					this.selectionEnd = startPos + myValue.length;
					this.scrollTop = scrollTop;
			} else {
					this.value += myValue;
					this.focus();
			}
		});
	};

	if (!window.addthis) {
		$(".addthis_toolbox .vertical").css('display', 'none');
		$(".addthis_toolbox .js-warning").css('display', 'block');
	}
	
	// Comment presets
	$(".comments-add p.comments-presets a").click(function() {
		var message = $(this).parent().find("option:selected").text() + ' ';
		var textarea = $(this).parent().parent().find("textarea");
		textarea.insertAtCaret(message);
		textarea.focus();
		return false;
	 });
	
	$(".comments-add p.comments-presets select option").click(function() {
		var message = $(this).parent().find("option:selected").text() + ' ';
		var textarea = $(this).parent().parent().parent().find("textarea");
		textarea.insertAtCaret(message);
		textarea.focus();
	 });
	
	// Comment response
	$("#comments-list div.comment-control a.replyto").click(function() {
		var quote = $(this).parent().parent().parent().find("p.comment").html();
		var meta = $(this).parent().parent().parent().find("h4 span.comment-author").html();
		var commentid = $(this).parent().parent().parent().attr("id").slice(8);
		$(".responseto p.responseto-quote").html(quote);
		$(".responseto p.responseto-title span").html(meta);
		$(".responseto input[name='replyto']").val(commentid);
		
		$(".responseto").show();
		$(".comments-add textarea").focus();

		return false;
	});
	
	$(".responseto p.responseto-cancel a").click(function() {
		$(".responseto").hide();
		$(".responseto p.responseto-quote").html('');
		$(".responseto p.responseto-title span").text('');
		$(".responseto input[name='replyto']").val('');
		
		return false;
	});
	
	// Post/edit idea
	$("input[name='picture']").change(function() {
		$("input#pictureedit_new").click();
	});
	
	$("input#pictureedit_keep, input#pictureedit_no").change(function() {
		$("input[name='picture']").val('');
	});
	
	if($("#page-post form").length) {
		$("form input#title").focus();
		setInterval(validate_form_idea, 500);
	}
	
	$("#page-post #main form, #page-edit_idea #main form").submit(function() {
		return submit_form_idea();
	});
	
	if($("#page-edit_idea form").length) {
		setInterval(validate_form_idea, 500);
	}
	
	function validate_form_idea(){
		var title = $("form input#title");
		var helpsto = $("form textarea#helpsto");
		var worksby = $("form textarea#worksby");
		
		if (jQuery.trim(title.val()) == '') {
			title.addClass("field_error");
		}else{
			title.removeClass("field_error");
		}
		
		if (jQuery.trim(helpsto.val()) == '') {
			helpsto.addClass("field_error");
		}else{
			helpsto.removeClass("field_error");
		}
		
		if (jQuery.trim(worksby.val()) == '') {
			worksby.addClass("field_error");
		}else{
			worksby.removeClass("field_error");
		}
	}
	
	function submit_form_idea(){
		var title = jQuery.trim($("form input#title").val());
		var helpsto = jQuery.trim($("form textarea#helpsto").val());
		var worksby = jQuery.trim($("form textarea#worksby").val());
		var errors = '';
		
		if (title == '') {
			errors = errors + 'The idea title cannot be left blank.' + "<br/>";
		}
		
		if (helpsto == '') {
			errors = errors + 'The "Helps to" field cannot be left blank.' + "<br/>";
		}
		
		if (worksby == '') {
			errors = errors + 'The "Works by" field cannot be left blank.' + "<br/>";
		}
		
		if (errors == '') {
			return true;
		}else{
			blockUI('Some required fields are not completed', errors);
			return false;
		}
	}
	
	// Edit comment
	$("#page-edit_comment form").submit(function() {
		var comment = jQuery.trim($("#page-edit_comment form textarea").val());
		
		if (comment == '') {
			blockUI('Empty comment', 'The comment field cannot be left blank.');
			return false;
		}
	});
	
	// User settings
	if($("#page-settings").length) {
		setInterval(validate_form_settings, 500);
	}
	
	$("#page-settings form").submit(function() {
		return submit_form_settings();
	});
	
	function validate_form_settings(){
		var email = $("form input#email");
		
		if (email.val() == '') {
			email.addClass("field_error");
		}else{
			email.removeClass("field_error");
		}
	}
	
	function submit_form_settings() {
		var email = jQuery.trim($("form input#email").val());
		var errors = '';
		
		if (email == '') {
			errors = errors + 'The e-mail address field cannot be left blank.' + "<br />";
		}
		
		if (errors == '') {
			return true;
		} else {
			blockUI('Some required fields are not completed', errors);
			return false;
		}
	}
	
	// Post
	$("#page-post form input#tags, #page-edit_idea form input#tags").autocomplete(siteurl+'ajax/tags/', {
		width: 561,
		highlight: false,
		multiple: true,
		multipleSeparator: ", ",
		scroll: true,
		scrollHeight: 100
	});
	
	// Register
	if($("#page-register").length) {
		validate_form_register_username();
		setInterval(validate_form_register, 500);
	}
	
	$("#page-register input#name").blur(function() {
		validate_form_register_username();
	});
	
	function validate_form_register(){
		var email = $("form input#email");
				
		if (email.val() == '') {
			email.addClass("field_error");
		}else{
			email.removeClass("field_error");
		}
	}
	
	function validate_form_register_username() {
		var username = $("form input#name");
		
		$.ajax({
			  mode: "abort",
			  port: "username",
			  url: siteurl+'ajax/username/',
			  data: 'name='+username.val(),
			  success: function(data) {
				  if(data=='good') {
					  username.removeClass("field_error");
					  username.addClass("field_ok");
				  }else{
					  username.addClass("field_error");
					  username.removeClass("field_ok");
				  }
			  }
		});
	}
	
	// View
	$('#comments ol li.userHidden .toggle').click(function() {
		var id = $(this).parent().parent().parent().attr('id').split('-');
		var id = id[1];
		
		var prefix = '#comments ol li#comment-'+id+' ';
		var duration = 300;
		
		$(this).blur();
		
		if ($(prefix+'.comment-body p').is(':animated')) {
			return false;
		}
		
		if ($(prefix+'.comment-body p').is(':hidden')) {
			$(this).text('(collapse)');
			$(prefix+'.comment-body p').slideDown(duration, function() {
				$(prefix+'.comment-control p').fadeIn(duration);
			});
		} else {
			$(this).text('(expand)');
			$(prefix+'.comment-control p').fadeOut(duration, function() {
				$(prefix+'.comment-body p').slideUp(duration);
			});
		}
		
		return false;
	});
	
	$("#page-view #comments-post form button").click(function() {
		var comment = jQuery.trim($("#page-view #comments-post form textarea").val());
		
		if(comment == ''){
			blockUI('Empty comment', 'Empty comment is empty.');
			return false;
		}
	});
	
	$("#page-view a.button.subscribe, #page-view a.button.unsubscribe").click(function() {
		// determine what are we doing
		var button = $(this);
		var buttonid = button.attr('id').split('-');
		var mode = buttonid[0];
		var id = buttonid[1];
		
		var b_subscribe = $("#page-view a.button.subscribe");
		var b_unsubscribe = $("#page-view a.button.unsubscribe");
		
		/* Logged in? */
		if (!username) {
			blockUI('Not signed in', 'You need to sign in to subscribe to email updates.');
		}else{
		
			button.fadeTo(200,0.1);
			
			if((mode=='subscribe') || (mode=='unsubscribe')){
			  $.ajax({
					url: siteurl+'ajax/'+mode+'/',
					data: 'id='+id,
					success: function(data) {
						button.fadeTo(200,1, function(){if ($.browser.msie) this.style.removeAttribute('filter')});
						if(data=='subscribed') {
							b_subscribe.hide();
							b_unsubscribe.show();
						}else if(data=='unsubscribed') {
							b_subscribe.show();
							b_unsubscribe.hide();
						}else if(data=='login') {
							blockUI('Not signed in', 'You need to sign in to subscribe to email updates.');
						}
					}
			  });
			}
			
			switch(mode) {
				case 'subscribe':
					$("input#subscribe").attr('checked','checked');
					break;
				case 'unsubscribe':
					$("input#subscribe").removeAttr('checked');
					break;
		}
		
		}
		
		return false;
	});
	
	// Reputation
	$("#comments ol li .promote, #comments ol li .demote").click(function() {
		/* Determine what are we doing */
		var buttonid = $(this).parent().parent().parent().parent().attr('id').split('-');
		var id = buttonid[1];
		
		/* Logged in? */
		if (!username) {
			blockUI('Not signed in', 'You need to sign in to vote.');
		} else {
			$.ajax({
				url: siteurl+'ajax/commentVote/',
				data: 'id='+id+'&vote='+($(this).attr('class')),
				success: function(data) {
					if (data == 'login') {
						blockUI('Not signed in', 'You need to sign in to vote.');
					} else if (data == 'throttle') {
						blockUI('', 'You have reached the maximum number of votes at this time, please vote later.');
					} else if (data == 'noSelfVoting') {
						blockUI('Um...', 'You cannot vote for yourself, that\'s quite silly.');
					} else if (data == 'alreadyVoted') {
						blockUI('Already voted', 'You have already voted on this comment.');
					} else if (data == 'not_exist') {
						blockUI('Comment deleted', 'The comment does not exist or has been deleted.');
					} else if (data == 'incorrect_usage') {
						blockUI('', 'Incorrect usage for this action.');
					} else {
						$('#comment-'+id+' .reputation .rep').html(data);
						$('#comment-'+id+' .reputation').addClass('voted');
					
						commentRepView(id, data);
					}
				}
			});
		}
		
		return false;
	});
	
	$("#comments ol li .changeVote").click(function() {
		/* Determine what are we doing */
		var buttonid = $(this).parent().parent().parent().parent().attr('id').split('-');
		var id = buttonid[1];
		
		$.ajax({
			url: siteurl+'ajax/commentVoteChange/',
			data: 'id='+id,
			success: function(data) {
				if (data == 'login') {
					blockUI('Not signed in', 'You need to sign in to vote.');
				} else if (data == 'notVoted') {
					$('#comment-'+id+' .reputation').removeClass('voted');
					blockUI('Not voted yet', 'You haven\'t voted on this comment yet.');
				} else if (data == 'not_exist') {
					blockUI('Comment deleted', 'The comment does not exist or has been deleted.');
				} else if (data == 'incorrect_usage') {
					blockUI('', 'Incorrect usage for this action.');
				} else {
					$('#comment-'+id+' .reputation .rep').html(data);
					$('#comment-'+id+' .reputation').removeClass('voted');
					
					commentRepView(id, data);
				}
			}
		});
		
		return false;
	});
	
	function commentRepView(id, vote) {
		if (vote > 0) {
			$('#comment-'+id+' .reputation').addClass('positive');
			$('#comment-'+id+' .reputation').removeClass('negative');
			$('#comment-'+id).removeClass('very-negative');
		} else if (vote < 0 && vote > -10) {
			$('#comment-'+id+' .reputation').removeClass('positive');
			$('#comment-'+id+' .reputation').addClass('negative');
			$('#comment-'+id).removeClass('very-negative');
		} else if (vote <= -10) {
			$('#comment-'+id+' .reputation').removeClass('positive');
			$('#comment-'+id+' .reputation').addClass('negative');
			$('#comment-'+id).addClass('very-negative');
		} else {
			// 0
			$('#comment-'+id+' .reputation').removeClass('positive');
			$('#comment-'+id+' .reputation').removeClass('negative');
			$('#comment-'+id).removeClass('very-negative');
		}
	}
	
	// blockUI
	$(window).keydown(function(event) {
		if (event.keyCode == 27) {
			$.unblockUI();
		}
	});
	
	$('.blockOverlay').live("click",function() {
   		$.unblockUI();
   	});
	
	$('div.blockUI a#no').live("click",function() {
		$.unblockUI();
    	return false;
    });
});

function blockUI(heading, message) {
	try {
		$('input, button').blur();
	} catch (e) {}
	
	msg = '';
	if (heading) {
		msg += '<h4>'+heading+'</h4>';
	}
	msg += '<br /><div class="errors"><p>'+message+'</p></div><p class="formbuttons"><a class="button" id="no"><img src="'+siteurl+'static/images/cancel.png" alt="" /> Close</a></p>';
	
	$.blockUI({message:msg});
	//$('#no').focus();
}
