var blogScript = function () {

	var commentStored = false;

	
	
	
	var bindObservers = function () {
		unbindObservers();

		// Comments	
		var save_btns = $$('.btn_comment_save');
		if(save_btns) {
			save_btns.each(function(btn) {
				btn.addEvent('click', function(event) {blogScript.saveComment(event)});
			});
		}
		
		cancel_btns = $$('.btn_comment_cancel');
		if(cancel_btns) {
			cancel_btns.each(function(btn) {
				btn.addEvent('click', function(event) {blogScript.cancelComment(event)});
			});
		}
	}

	
	
	var unbindObservers = function () {
		var save_btns = $$('.btn_comment_save');
		if(save_btns) {
			save_btns.each(function(btn) {
				btn.removeEvents('click');
			});
		}
	}
	
	
	
	
	var cancelComment = function (event) {
		var commentButton = $(event.target);
		if (confirm('Are you sure you want to cancel this comment?')) {
			commentButton.getParent("form").getElement('textarea').value = '';
			var title = commentButton.getParent(".blog_item").getElement('.title').innerHTML;
			commentButton.getParent("form").getElement('input.commentTitle').value = 'Re: '+title;
		}
	}
	
	var saveComment = function (event) {
		var commentButton = $(event.target);
		var id = 'new';
		var comment = commentButton.getParent("div.comment");
		var form = commentButton.getParent("form");
		var blogID = comment.getElement('input.commentBlogID')? comment.getElement('input.commentBlogID').value : 0;
		var sectionID = comment.getElement('input.commentSectionID')? comment.getElement('input.commentSectionID').value : 0;
		var blogversion = comment.getElement('input.blogVersion')? comment.getElement('input.blogVersion').value : 0;
		
		var data = new Hash({
			'itemID'		 : blogID,
			'sectionID'	 : sectionID,
			'commentID' : id,
			'class' : blogversion
		});
		
		var qString = data.toQueryString();
		qString = qString  +"&"+ form.toQueryString();
		
		//alert(qString);
		
		req = new Request.JSON({
			url: '/views/ajax/ajax_saveComment.php',
			data: qString,
			method: 'post',
			onSuccess: function(res) {
				//alert(res);
				if (res.view) {
					blogScript.commentStored = false;
					comment.innerHTML = res.view;
				}
								
				//if (res.errors) $('ErrorCode').innerHTML = res.errors;
				bindObservers();
			},
			onFailure: function() {
				throw("Failed ajax connect in blogScript.editComment");
			}
		}).send();
	}

	var init = function () {
		bindObservers();
	}

	return {
		// Properties
		commentStored: commentStored,
		
		// Methods
		init: init,
		saveComment: saveComment,
		cancelComment: cancelComment
	}

}();

window.addEvent('load', function(){blogScript.init();});