/**
 * Next Comments Plugin 
 * 
 * @author Dan Rades  dan.rades@gmail.com
 * @lastmod 05.11.2008
 * 
 * 
 */

(function($) {
	$.fn.setCursorPosition = function(pos) 
	{
		if ($(this).get(0).setSelectionRange) 
		{
			$(this).get(0).setSelectionRange(pos, pos);
		} 
		else if ($(this).get(0).createTextRange) 
		{
			var range = $(this).get(0).createTextRange();
			range.collapse(true);
			range.moveEnd('character', pos);
			range.moveStart('character', pos);
			range.select();
		}
		return this;
	}
})(jQuery);
 
(function($) {                                         
$.fn.nextComments = function(o) {   
    o = $.extend({
		url : '/?ajax_service=1',
		captchaPath : '/cms/images/captcha.jpg.php'
	}, o || {});

	
	$('.commentsReply').live('click', function()
	{
		var author = $(this).prevAll('.commentsAuthor').eq(0).text();
		author = '@' + author;
		$('#commentsDetails').val(author).focus().setCursorPosition(author.length);
		
	});	
	
	function validate() {
		$('label, input, textarea').removeClass('error');
		
		
		var author  = $('#commentsAuthor');
		var email   = $('#commentsEmail');		
		var details = $('#commentsDetails');

		var hasError = false;	
		if (author.val() == '' ) {
			$('label, input', author.parent()).addClass('error');
			hasError = true;
		}

	   var regxp = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	   var emailVal = email.val();
		
		if (regxp.test(emailVal) == false ) {
			$('label, input', email.parent()).addClass('error');
			
			hasError = true;
		}
		if (details.val() == '' ) {
			$('label, textarea', details.parent()).addClass('error');
			hasError = true;
		}				
		if (hasError) {
			$('#commentsValidationError').show();
		}
		else {
			$('#commentsValidationError').hide();
		}
		
		return !hasError;
	};
		
	function resetCaptcha() {
		var randNr = randNum = Math.floor(Math.random() * 30000);
		$('#commentsCaptchaImage').eq(0).attr('src', o.captchaPath + '?rnd=' + randNr);
	};
	
	function initCommentsReport() {
		$('a.commentsReport').click(function(){
			var _self = $(this);
			var id = _self.attr('title');
			var url = o.url + '&boxID=' + boxId + '&reportId='+id;
			var _parent = _self.parent();
			_parent.html('<b>Raportam...</b>');
			$.get(url, null, function() {
				_parent.html('<b>Comentariu raportat!</b>');				
			});
		});
	};
	
	function getFirstPage() {
		$('#commentsContainer').html('Se incarca comentariile...');		
		var url = o.url + '&item=' + itemId + '&boxID=' + boxId + '&' + $('#commentsPaginationVar').val() + '=1';		
		
		$.get(url, null, function(data) {
			$('#commentsContainer').html(data.comments);
			initPagination();
			initCommentsReport();
	
		}, 'json');		
	};
	
	function initPagination() {

		$('a', $('#commentsPagination')).click(function(){
			$('#commentsContainerOverlay').block({
				message: '<h3 style="font-size:14px;font-weight:bold;">Incarc comentariile</h3>',
				css: {
					border: '2px solid #a00'
				}
			});		
			var url = o.url + '&item=' + itemId + '&boxID=' + boxId + '&' + $('#commentsPaginationVar').val() + '=' + $(this).attr('title');
			$.get(url, null, function(data) {
				$('#commentsContainer').html(data.comments);
				initPagination();
				initCommentsReport();
				setTimeout(function(){
					$('#commentsContainerOverlay').unblock();
				}, 700);
			}, 'json');
			return false;
		});
	};


	var form = $('form', $('#commentsForm')).eq(0);
	if (form.length == 0)
	{
		return false;
	}
	var container = $('#commentsContainer');	
	var boxId = $('#commentsBoxId').val();
	var itemId = $('#commentsItemId').val();
	
	var ajaxSubmit = true;
	var ajaxPagination = ($('#commentsAjaxPagination').val() == 1) ? true : false;
	var useCaptcha = parseInt($('#commentsUseCaptcha').val());
	var captchaContainer = $('#commentsCaptchaContainer');
	
	if (useCaptcha == 1) {
		var showCaptchaButton = $('#commentsShowCaptcha');

		showCaptchaButton.click(function() {			
			captchaContainer.show();
			showCaptchaButton.hide();			
			return false;	
		});			
		
		$('#commentsCancel').click(function() {
			captchaContainer.hide();
			showCaptchaButton.show();
			return false;	
		});	
	}

	if (ajaxPagination) {
		initPagination();
	}

	initCommentsReport();
	


	form.submit(function() {
		var v = validate();
		if (v == true) {
			if (ajaxSubmit) {
				var url = o.url + '&boxID=' + boxId;
	            $('#commentsForm').block({  
	                message: '<h3 style="font-size:14px;font-weight:bold;">Postam comentariul</h3>',  
	                css: { 
						border: '2px solid #a00'
					}  
	            });				
				$.post(o.url, form.serialize(), function(data){
					
					if (typeof data.captcha_error != 'undefined') {
						resetCaptcha();
						$('#commentsCaptchaError').show();
						$('#commentsForm').unblock();
					}
					else {
						$('#commentsCaptchaError').hide();
						container.html(data.comments);
						form.get(0).reset();
	
						if (useCaptcha == 1) {
							captchaContainer.hide();
							resetCaptcha();
							showCaptchaButton.show();				
						}	
						
						initCommentsReport();
						initPagination();	
						
						
						setTimeout(function(){
							$('#commentsForm').unblock();
						}, 1700);
			
					}
					
				}, 'json');
				return false;
			}
			else {
				return true;
			}
		}
		return false;
	});
	
	getFirstPage();
	
};

})(jQuery);