/* 
 * Article comments common library
 * urze_articleComments.js
 *
 * @author Dawid Opis
 * @since 2011-10-21
 * @version 1.0.20111021.0001
 */

var articleComments = function() {
	return true;
};

/*
 * Article comments global settings
 */
articleComments.settings = {
	userId: null,
	newsItemId: null,
	showAllComments : false,
	maxCommentLength : 2500
};

var ACS = articleComments.settings; /* shortcut */

/*
 * Check comment text length
 */
articleComments.checkCommentLength = function(element) {
	var currLength = jQuery(element).val().length;

	jQuery('#charsLeft').html(parseInt(ACS.maxCommentLength - currLength));

	return (currLength < ACS.maxCommentLength);
};

/*
 * Validate given email address
 */
articleComments.validateEmail = function(element) {
	var emailRegExp = /^([a-zA-Z0-9])([a-zA-Z0-9_\.\-\+])*@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,6})+$/;
	
	return emailRegExp.test(jQuery(element).val());
};

/*
 * Validate given input field
 */
articleComments.validateInput = function(element, alertMsg, minLength) {
	if(jQuery(element).val() == '' || typeof jQuery(element).val() == 'undefined' || jQuery(element).val() == null) {
		articleComments.showError(alertMsg);
		return false;
	} 
	
	if(jQuery(element).val().length < minLength) {
		articleComments.showError('Wpisz minimum ' + minLength + ' znaki.');
		return false;
	}
		
	return true;
};

/*
 * Comment form validation
 */
articleComments.validateForm = function() {
	if(!articleComments.validateInput('#commentSign', "Podpis nie może być pusty.", 3) || !articleComments.validateInput('#commentText', "Wpisz treść komentarza.", 3)) {
		return false;
	}
	
	if(!articleComments.validateEmail('#commentEmail')) {
		articleComments.showError("Podany adres e-mail jest nieprawidłowy.");
		return false;
	}
	
	if(!jQuery('#agreement').is(':checked')) {
		articleComments.showError("Musisz zaakceptować regulamin by dodać komentarz.");
		return false;
	}
	
	return true;
};

/*
 * Article comments - tabs engine
 */
articleComments.tabsEngineInit = function(newsItemId) {
	var allTabs = jQuery('.articleTabs_Panel h3'); 
	
	allTabs.each(function(){
		var thisTab = jQuery(this);
		var thisType = thisTab.attr('id').split("_")[1];
		
		thisTab.bind('click', function() {
            
            if(jQuery(this).hasClass('locked')) {
                return false;     
            }
            
			if(!thisTab.hasClass('articleTab_Active')) {
				allTabs.removeClass('articleTab_Active').removeClass('articleTab_noBorder');
				
				thisTab.addClass('articleTab_Active');
				thisTab.next('h3').addClass('articleTab_noBorder');
				
				if(thisType == 'recommended' && ACS.showAllComments == true) {
					articleComments.loadComments(newsItemId, 'recommendedAll', '-1');
				} else {
					articleComments.loadComments(newsItemId, thisType);
				}
				
			}
			return false;
		});
	});
};

/*
 * Method for loading desired comments
 */
articleComments.loadComments = function(newsItemID, type, page) {
	var dataToLoad = 'newsitemId=' + newsItemID + '&sortType=' + type;
	
	if(page !== null && typeof page !== 'undefined' && page !== '' && page !== '-1') {
		dataToLoad = 'newsitemId=' + newsItemID + '&sortType=' + type + '&offset=' + page;
	}
	articleComments.lockUnlockButtons(jQuery('.articleTabs_Panel h3, #showAllRComments'), true);
    
	jQuery.ajax({
		type: 'POST',
		url: '/app-komentarze/',
		data: dataToLoad,
		dataType: 'html',
		success: function(sSuccess) {
			jQuery('#articleCommentsContent').html(sSuccess);
			if(type == 'recommended' && ACS.showAllComments == false) {
				jQuery('#showAllRComments').live('click', function() {
					if(jQuery(this).hasClass('locked')) {
						return false;     
					}
					articleComments.loadComments(ACS.newsItemId, 'recommendedAll', '-1');
					return false;
				});
			}
			
			if(type == 'recommendedAll' && ACS.showAllComments == false) {
				ACS.showAllComments = true;
			}
			
			articleComments.parseRecommendButtons();
            articleComments.lockUnlockButtons(jQuery('.articleTabs_Panel h3, #showAllRComments'), false);
            
        	if (jQuery('#komentarzeCount').size() > 0) {
        		jQuery('.socialNewTools .addCommentNewRightContent').html(jQuery('#komentarzeCount').val());
        		jQuery('.socialNewTools .socialNewLeft').show();
        	}
		},
		error: function(sError) {
			commentsErrorInfo();
		}
	});
};

/*
 * Lock / unlock buttons
 */
articleComments.lockUnlockButtons = function(buttons, lock) {
    if (lock == true) {
        buttons.addClass('locked');
    }
    else if (lock == false) {
        buttons.removeClass('locked');
    }
};

/* 
 * Comment pagination actions
 */
articleComments.bindPaginationNav = function() {
	jQuery('#articleCommentsPagination .articlePaged_Prev a, #articleCommentsPagination .articlePaged_Next a, #articleCommentsPagination .articlePaged_Page a').live('click', function(){
		var pActionBtn = jQuery(this);
		var pActionHref = pActionBtn.attr('href').split('_');
		var commentType = pActionHref[0].replace('#', '');
		var page = pActionHref[1];
	
		articleComments.loadComments(ACS.newsItemId, commentType, page);
		
		return false;
	});
};

/*
 * Method to (re)parse buttons for recommending a comment
 */
articleComments.parseRecommendButtons = function() {
	jQuery('span.commentRecommendationButton').each(function(){
		var thisButton = jQuery(this);
		
		thisButton.bind('click', function(){
			var commentID = thisButton.parents('.addCommentRecommendation').parent().attr('id').split('_')[1];
			
			if(commentID !== null || typeof commentID !== 'undefined' || commentID !== '') {
				articleComments.recommendComment(commentID, thisButton);
			} else {
				articleComments.showError("Wystąpił błąd podczas oddawania głosu na wybrany komentarz.");
			}
			
			jQuery('a', thisButton).bind('click', function(){return false;});
			
			return false;
		});
	});
};

articleComments.recommendComment = function(id, parent) {
	var commentRCounter = jQuery('#totalCommentRecommendations_' + id);
	
	jQuery.ajax({
		type: 'GET',
		url: '/app-komentarze/rekomenduj',
		data: 'commentId=' + id + '&rekomendacja=Y',
		async: false, 
		success: function(sSuccess) {
			var rAnswer = sSuccess.split(' ');
			
			if(rAnswer.length > 0 && (rAnswer[0] == 'OK' || rAnswer[0] == 'ALREADY_VOTED')) {
				parent.html('Dziękujemy za oddanie głosu!');
				commentRCounter.html(parseInt(rAnswer[1]));
				parent.unbind('click');
			} else {
				articleComments.showError("Wystąpił błąd podczas oddawania głosu na wybrany komentarz.");
			}
		},
		error: function(sError) {
			articleComments.showError("Wystąpił błąd podczas oddawania głosu na wybrany komentarz.");
		}
	});
	
};

/*
 * Validate comment, lock inputs and send it to the server 
 */

articleComments.addComment = function() {
	if(articleComments.validateForm()) {
		jQuery('#articleComments .formRow input, #articleComments .formRow textarea').each(function(){
			jQuery(this).attr('disabled', 'disabled');
		});
		
		jQuery.ajax({
			type: 'POST',
			url: '/app-komentarze/dodaj',
			data: 	'newsitemId=' + ACS.newsItemId 
				  + '&commentSign=' + jQuery('#commentSign').val() 
				  + '&commentEmail=' + jQuery('#commentEmail').val()
				  + '&commentText=' + encodeURIComponent(jQuery('#commentText').val())
				  + '&agreement=' + jQuery('#agreement').val() 
				  + '&userId=' + ACS.userId,
			async: false, 
			dataType: 'text',
			success: function(sSuccess) {
				if(sSuccess == "OK") {
					jQuery('#dialogCloseBtn').bind('click', function(){
						var docLoc = document.location.href; 
						document.location.href = docLoc;
					});
					articleComments.showInfo("Dziękujemy! Komentarz został dodany i oczekuje na zatwierdzenie.");
				} else {
					jQuery('#articleComments .formRow input, #articleComments .formRow textarea').each(function(){
						jQuery(this).removeAttr('disabled');
					});
					articleComments.showError("Wystąpił błąd podczas dodawania komentarza.");
				}
			},
			error: function(sError) {
				articleComments.showError("Wystąpił błąd podczas dodawania komentarza.");
			}
		});
	}
	return false;
};

articleComments.checkUserInfo = function(userId, userLogin) {
	jQuery.ajax({
		type: 'POST',
		url: '/app-komentarze/checkUserInfo',
		data: 'userId=' + userId + '&login=' + userLogin,
		async: false, 
		success: function(sSuccess) {
			jQuery('#userInformation').html(sSuccess);
			
			var userNickname = jQuery('#userInformation #commentSign').val();
			
			if(userNickname !== '') {
				jQuery('#userInfoCnt #userNickname').html(userNickname + " (" + userLogin + ")");
			};
		},
		error: function(sError) {
			articleComments.showError("Wystąpił błąd podczas pobierania informacji o użytkowniku.");
		}
	});
};

/*
 * Dialog boxes - errors and info
 */
articleComments.showError = function(text) {
	jQuery('#dialogBody').html(text);
	setDialogBox("Wystąpił błąd", '', 'error');
};
articleComments.showInfo = function(text) {
	jQuery('#dialogBody').html(text);
	setDialogBox("Informacja", '');
};

/*
 * Initialize article comments component
 */
articleComments.init = function() {
	jQuery('#commentText')
	.bind('keypress keyup keydown focus blur', function() {
		if(articleComments.checkCommentLength(this) == false) {
			jQuery(this).val(jQuery(this).val().substring(0, ACS.maxCommentLength));
		}
	})
	.bind('keypress keyup focus blur', function(){
		return articleComments.checkCommentLength(this);
	});
	
	jQuery('#addComment').bind('click', function() {
		articleComments.addComment();
	});
	
	articleComments.tabsEngineInit(ACS.newsItemId);
	articleComments.parseRecommendButtons();
	articleComments.bindPaginationNav();
};

jQuery(document).ready(function(){
	articleComments.init();
});



/*
 * Error info
 */
function commentsErrorInfo() {
	
	var commentsComponent = jQuery('#articleComments');
	
	commentsComponent.css('position', 'relative');
	commentsComponent.prepend('<div class="commentsErrorBG" style="z-index: 100; position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; background-color: white; opacity:0.6; filter:alpha(opacity=60);"></div>');
	commentsComponent.prepend('<div class="commentsErrorInfo" style="z-index: 101; font-size: 12px; position: absolute; width: 60%; left: 20%; top: 20%; background-color: white; border: 1px solid #666666; padding: 18px; text-align: center;">Wystąpił błąd podczas pobierania komentarzy. <br /><br />Spróbuj ponownie.</div>');
	//articleComments.showError("Wystąpił błąd podczas pobierania komentarzy. Spróbuj ponownie.");
	//articleComments.lockUnlockButtons(jQuery('.articleTabs_Panel h3, #showAllRComments'), false);
};
