/**
 * Blog JS
 *	
 * @author J-P Stacey
 * @created 2007-11-26
 */
window.Blog = {
	p: {
		jQ: {
			guidelines: 'a.guidelines-link',
			commentText: '#form-comment_text',
			remaining: '#form-comment_remaining',
			required: 'span.form-required',
			topics: 'select#choose-topic'
		},
		n: {
			maxchars: 0
		},
		txt: {
			remaining: 'Characters remaining'
		},
		w: {
		}
	},

	/* Guidelines in separate window */
	Guidelines: {
		makeWindow: function(u,n) {
			return window.open(
				u,
				n,
				"width=500,height=400,resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no"
			);
		},
		linkClick: function(ev) {
			Blog.p.w.guidelines = Blog.Guidelines.makeWindow(this.href, 'guidelines');
			ev.preventDefault();
		}
	},

	Topics: {
		selectSubmit: function(ev) {
			if (this.value != "") {
				this.form.submit();
			}
		}
	},

	Comments: {
		getNum: function() {
			// Get the number from the non-Javascripted page
			var rem = jQuery(Blog.p.jQ.remaining);
			Blog.p.n.maxchars = rem.html() * 1;
			// Replace
			rem.siblings(".fakelabel").html(Blog.p.txt.remaining);
			jQuery('<input type="text" size="4" maxlength="4">')
				.attr("id", rem.attr("id"))
				.addClass("input-text")
				.val(Blog.p.n.maxchars)
				.replaceAll(Blog.p.jQ.remaining);
			// Recalculate
			Blog.Comments.docount();	
		},
		docount: function(ev) {
			if (!Blog.p.n.maxchars) {
				return;
			}

			var rem = jQuery(Blog.p.jQ.remaining);
			var comment = jQuery(Blog.p.jQ.commentText);
			var comtext = comment.val();
			var len = comtext.length;

			if (rem[0].value < 0) {
				rem[0].value = 0;
			}
			
			var newremval = Blog.p.n.maxchars - len;
			if(newremval >= 0){
				/*rem[0].value = 55;*/
				rem[0].value = newremval;
				comment.css('color','black');
			} else {
				/*comment.val(comtext.substring(0,Blog.p.n.maxchars));*/
				comment.css('color','red');
			}
		},
		validate: function(ev){
			var OK = true;
			jQuery(this).find(Blog.p.jQ.required).siblings("input.required").each(function(i) {
				OK = OK && Blog.Comments.isNotEmpty(this);
			});
			
			return OK;
		},

		isNotEmpty: function (el) {
			var jQ = jQuery(el);
			jQ.removeClass("error");
			var val = jQ.val().replace(/^\s*(.*?)\s*$/,"$1");
			var lab = jQ.siblings("label").html();

			if (val == "") {
				alert("The field '" + lab + "' is required.");
				jQ.parent().addClass("error");
				return false;
			}
			
			return true;
		}
	},

	go: function() {
		// Topics dropdown autochange
		jQuery(Blog.p.jQ.topics).change(Blog.Topics.selectSubmit);
		// Guidelines link as a popup
		jQuery(Blog.p.jQ.guidelines).click(Blog.Guidelines.linkClick);
		// Comments count
		if (jQuery(Blog.p.jQ.commentText).keyup(Blog.Comments.docount).keydown(Blog.Comments.docount).length) {
			Blog.Comments.getNum();
			jQuery(Blog.p.jQ.commentText).parents("form").submit(Blog.Comments.validate);
		}
		
	}
};

if (window.jQuery) {
	jQuery().ready(Blog.go);
	jQuery("html").addClass("js");
}

