/**********************************
*
*  Author: 		P. Belenski
*  Project: 	Comments Web Service ( CWS )
*  Filename: 	comments.js
*  Created on:	13.04.2009
*  Contents: 	Event handler
*  Requires:	jQuery 1.3 or greater
*
**********************************/

(function($) {

var root = '/lib/ibgws/ibgws_comments/';

$.ibgws_comments = function( options )
{
	var opt = $.extend( {}, defaults, options ),
		cookieset = navigator.cookieEnabled,
		
		form = (opt.party == 1 ? $(opt.form) : $(opt.form).remove().css('display','block').find(opt.counter).val(defaults.maxText).parents(opt.form));
		//form = $(opt.form).remove().css('display','block');

	$(opt.newComment +', '+opt.reply).live( 'click', function(){ 
		if( opt.guestPost || opt.userid != 0 )
		{
			if( $(opt.form).attr('id') != undefined )
				$(opt.form).removeForm( opt.text );
			
			if( $(this).hasClass(opt.reply) )
			{
				var parent = $(this).parents(opt.commentbox);
				parent.append( form );
				$(opt.parent).val(parent.attr('id').match(/[0-9]+/));
				$(opt.title).val(parent.find('.author').text());
				
				$(opt.form).showCaptcha();
			}
			else
			{
				$(opt.mainBox).prepend( form );
				
				$(opt.form).showCaptcha();
			}			
		}
		else
		{
			alert( 'Трябва да сте логнат!' );
		}
		return false;
	});
	
	$(opt.cancel).live( 'click', function(){
		$(opt.form).removeForm( opt.text );
	});
	
	$(opt.ajaxpaging).live( 'click', function(){
		$('#comments-frame').load(root + 'engine/reload.php', { 'ref': $(this).attr('rel') });
		$.scrollTo($('#comments-frame'), 800);
		return false;
	});
	
	$(opt.hidenav).bind( 'click', function(){
		var $this = $(this),
			parent = $this.parents(opt.commentbox);

		if( parent.hasClass(opt.hide) )
		{
			parent.removeClass(opt.hide);
			$this.text('Скрий Коментара');
		}
		else
		{
			parent.addClass(opt.hide);
			$this.text('Покажи Коментара');
		}		
		return false;
	}); 
	
	$(opt.delcomment).bind('click',function(){
		var parent = $(this).parents('.comment-box'),
			_id = parent.attr('id').match(/[0-9]+/);
		if( confirm( 'Наистина ли искате да изтриете този коментар?' ) )
		{
			$.post(
				root + 'engine/delComment.php',
				{ id: _id, item: opt.item, itemid: opt.itemid },
				function()
				{
					window.location.reload();
				}
			);
		}
		return false;
	});
	
	var alphaRegxp = /([a-zA-Z])/;
	
	$(opt.submit).live( 'click', function(){
		

		if( opt.authorMust && $(opt.author).val().length < 1 &&  opt.userid == 0  )
		{
			alert('Трябва да въведете автор!');
			$(opt.author).focus();
			return false;
		}
		else if( $(opt.text).val().length < 1 )
		{
			alert('Трябва да въведете текст на коментара!');
			$(opt.text).focus();
			return false;
		}		
		/*
		else if( alphaRegxp.test($(opt.text).val()) )
		{
			alert('Не можете да пишете на латиница!');
			$(opt.text).focus();
			return false;
		}
		*/		
		if( opt.userid == 0 )
		{
			$.post(
				root + 'validate/validate.php',
				{ code: $(opt.code).val() },
				function( responce )
				{
					if( responce == '0' )
					{
						alert('Грешен код!');
						$(opt.code).val('');
						$(opt.code).focus();
					}
					else	
					{
						if (opt.ajax == 1) {
							//contentType not work to set request as windows-1251
							$('#comments-frame').load(root + 'engine/postComment.php', $('#comment-post').serializeArray());
							$(opt.code).val('');
							$(opt.text).val('');
							$(opt.author).val('');
							$(opt.form).replaceCaptcha();
							
						} else {
	
							$(opt.form).submit();
							countSymbols();
						
						}
					}
				},
				'text'
			);
		}
		else if( $(opt.text).val().length > 0 )
		{
			if (opt.ajax == 1) {
				$('#comments-frame').load(root + 'engine/postComment.php', $('#comment-post').serializeArray());
				$(opt.code).val('');
				$(opt.text).val('');
				$(opt.author).val('');
				$(opt.form).replaceCaptcha();
				
			} else {

				$(opt.form).submit();
				countSymbols();
			}
		}		
		return false;
	});
	
	$(opt.nav + ' > div').live('click', function(){
		var parent = $(this).parent();
		
		if( parent.hasClass('grade') && cookieset && ( opt.guestGrade || opt.userid != 0 ) )
		{
			var grade 	= $(this).hasClass(opt.gradeup) ? 1 : -1,
				span_up	= $(this).siblings('.comments-grades-up'),
				span_down = $(this).siblings('.comments-grades-down'),
				numPos 	= $(this).siblings('.comments-num').children('.comments-positive-num'),
				numNeg 	= $(this).siblings('.comments-num').children('.comments-negative-num'),
				comment = Number($(this).parents(opt.commentbox).attr('id').match(/[0-9]+/));

			parent.removeClass('grade');
			
			$.post(
				root + 'engine/gradeComments.php',
				{ 
					grade: 		grade,
					site:		opt.site,
					item:		opt.item,
					itemid: 	opt.itemid,
					page: 		opt.page,
					usersite: 	opt.usersite,
					userid: 	opt.userid,
					commentid: 	comment
				},
				function( responce )
				{
					if( grade > 0 ){
						numPos.html( Number( numPos.text() ) + 1 );
						span_up.html( Number( span_up.text() ) + Math.abs(grade) );
					}
					else{
						numNeg.html( Number( numNeg.text() ) + 1 );
						span_down.html( Number( span_down.text() ) + Math.abs(grade) );
					}
					span_up.text() == '' ? span_up.html('0') : span_up.text() ;
					span_down.text() == '' ? span_down.html('0') : span_down.text() ;
					
					/*
					if( span_up.text() > 0 )
					{
						span.css( 'color', 'green' ); 
						span.html( span.text() );
					}
					else if( span_up.text() < 0 )
					{
						span.css( 'color', 'red' );
						span.html( '&nbsp;' + span.text() );
					}
					else
					{
						span.css( 'color', 'grey' );
						span.html( '&nbsp;&nbsp;' + span.text() );
					}
					*/
				},
				'text'
			);	
		}
		else if( $(this).parent().hasClass('grade') )
		{
			alert('Трябва да се логнете, за да гласувате!');
		}
	});

	
	$(opt.complain).live('click', function(){

		comment = $(this).parents(opt.commentbox).attr('id').match(/[0-9]+/);
		link = $(this);
		
		$.post(
			root + 'engine/complainComments.php',
			{ 
				site:		opt.site,
				item:		opt.item,
				itemid: 	opt.itemid,
				page: 		opt.page,
				usersite: 	opt.usersite,
				userid: 	opt.userid,
				commentid: 	Number(comment)
			},
			function( responce )
			{
				link.parent().html('Сигнализирахте за неуместен коментар');

			},
			'text'
		);	
		
		return false;

	});
	/*
	$(opt.text).live('click', function() {
		if($(this).val() == 'Във коментарите към новината се пише само на кирилица. В противен случай мненията ви ще бъдат изтривани без предупреждение. Моля спазвайте правилата на сайта.') 
			$(this).val('');
	});
	*/
	$('.'+opt.gradeup).add('.'+opt.gradedown).hover(
		function(){
			if( $(this).hasClass(opt.gradeup) )
				$(this).addClass('hover-up');
			else if( $(this).hasClass(opt.gradedown) )
				$(this).addClass('hover-down');
		},
		function(){
			if( $(this).hasClass(opt.gradeup) )
				$(this).removeClass('hover-up');
			else if( $(this).hasClass(opt.gradedown) )
				$(this).removeClass('hover-down');
		}
	);
	
	if( opt.userid == 0 && defaults.maxAuthor !=0 )
		$(opt.author).live( 'keydown', countSymbols ).live( 'keyup', countSymbols );
		
	if( defaults.maxText !=0 )
		$(opt.text).live( 'keydown', countSymbols ).live( 'keyup', countSymbols );
		
	$(opt.gotoPage).keypress(function( event ){
		var code = event.which ? event.which : event.keyCode;
		if( code > 31 && (code < 48 || code > 57) )
			return false;
		return true;
	});
	
	$(opt.gotoBtn).click(function(){
		var val = $(this).siblings(opt.gotoPage).val(),
			max = $(opt.gotoMax).val(),
			url = $(this).siblings(opt.gotoUrl).val();
		
		if( val > 0 & val != '' )
		{
			val = Number( val ) > Number( max ) ? max : val;
			window.location = 'http://' + window.location.hostname + window.location.pathname + url.replace('{pagenum}',val);
		}
	});	
};

$.fn.removeForm = function( text )
{
	return this.each(function(){
		if( $(text).val().length > 0 )
		{
			if( !confirm('Въведения от Вас текст във формата за коментари ще бъде изгубен.') )
				window.location = window.location + "#comment-post"
			else
				$(this).remove().find('textarea').val('');
		}
		else
			$(this).remove().find('textarea').val('');
	});	
}

$.fn.showCaptcha = function()
{
	if($(this).find('#comments_captcha').html() == ''){
		
		$(this).find('#comments_captcha').html('<img src="/lib/ibgws/ibgws_comments/validate/code.php" alt="" />');
	}
};	

$.fn.replaceCaptcha = function()
{
	$(this).find('#comments_captcha').html('<img src="/lib/ibgws/ibgws_comments/validate/code.php?rand=' + new Date().getTime() + '" alt="" />');
};	

function countSymbols()
{

	var counter = $(defaults.counter).val(),
		txt = $(this).val(), max;
	
	if( $(this).attr('id') == defaults.author.replace('#','') )
		max = defaults.maxAuthor;
	else
		max = defaults.maxText;

	if( txt.length > max )
		$(this).val( txt.substr( 0, max ) )
	else
		$(defaults.counter).val( max - txt.length );
}


var defaults = 
{
	mainBox:			'#comments-cont',
	form:				'#comment-post',
	code:				'#comment-code',
	cancel:				'#comment-cancel',
	author:				'#comment-author',
	text:				'#comment-text',
	counter:			'#comment-count',
	submit:				'#comment-submit',
	title:				'#comment-title',
	parent:				'#comment-parent',
	hidenav:			'.comment-hide-nav',
	delcomment:			'.comment-delete',
	newComment: 		'.comment-new',
	reply: 				'.comment-reply',
	nav:				'.comment-nav',
	commentbox:			'.comment-box',
	hide:				'comment-hide-row',
	ajaxpaging:			'.comments-ajax a',
	gotoPage:			'.comments-goto-page',
	gotoBtn:			'.comments-goto-go',
	gotoUrl:			'.comments-goto-url',
	gotoMax:			'.comments-goto-max',
	gradeup:			'comments-grade-up',
	gradedown:			'comments-grade-down',
	complain:			'.comment-complain',
	userid:				0,
	maxAuthor:			20,
	maxText:			500,
	guestPost:			true,
	guestGrade:			true,
	authorMust:			false
};

})(jQuery);
