/**
 * Funkce pouzite ve frontendu.
 */

$(function() {
	// zobrazovani prihlasovaciho formulare
	$("#login-button").click(function(e) {
		e.preventDefault();
		$("#login-button-div").hide();
		$("#login-form-show").show();
	});
	
	// prihlasovani
	$("#login-submit").click(function(e) {
		e.preventDefault();
		LoginDWRController.login($("#j_username").val(), $("#j_password").val(), function(data){
			if (data.message == 'success') {
				if (data.cookie != null) {
					setRememberMeCookie(data.cookie);
				}
				var loginUrl = $("#login-url").val();
				if (loginUrl != '') {
					window.location = loginUrl;
				} else {
					window.location.reload();
				}
			} else {				
				alert(data.message);
			}
		});
	});
	
	// prihlasovani pri pridavani oblibenych polozek
	$("#login-submit-favorite").click(function(e) {
		e.preventDefault();
		LoginDWRController.login($("#j_username_favorite").val(), $("#j_password_favorite").val(), function(data){
			if (data.message == 'success') {
				if (data.cookie != null) {
					setRememberMeCookie(data.cookie);
				}
				window.location.reload();
			} else {
				alert(data.message);
			}
		});		
	});
	
	// schova uzivatelskou hlasku
	$("#close-user-message").click(function(event) {
		event.preventDefault();
		hideUserMessageBox();
	});
	
	// schova popup pro pridavani oblibenych polozek
	$("#favorites-popup .close-favorites-popup").click(function(event) {
		event.preventDefault();
		$("#favorites-popup").fadeOut();
		resetFavoritePopup();
	});
	
	// odesle email pro aktivaci emailu
	$("#favorite-activate-email a").click(function(event) {
		event.preventDefault();
		WatchedEntityDwrManager.sendEmailActivationEmail(function(data) {
			if (data.successMessage != null) {
				$("#favorite-activate-email").hide();
				var successElement = $("#favorite-activate-email-success");
				successElement.text(data.successMessage);
				successElement.show();
			}
		});
	});
	
	// ulozi uzivateluv email a odesle email pro jeho aktivaci
	$("#favorite-registrate-email input[type='submit']").click(function(event) {
		event.preventDefault();
		WatchedEntityDwrManager.registrateEmailAndSendActivationEmail($("#user-email").val(),function(data) {				
			if (data.errors.length > 0) {
				var html = "";
				// zobrazi chyby
				for(i = 0; i < data.errors.length; i++) {
					html += data.errors[i] + "<br/>";
				}
				$("#favorite-registrate-email p.errors").html(html).show();				
			}else if (data.successMessage != null) {
				$("#favorite-registrate-email").hide();
				var successElement = $("#favorite-email-registration-success");
				successElement.text(data.successMessage);
				successElement.show();
			}
		});
	});
	
	// zobrazi popup pro dopouceni stranky jinym fanouskum
	$("#sendToFanLink").click(function(event) {
		event.preventDefault();
		$("#url").val("" + window.location);
		showPopupback();
		showFrontendPopup($("#send-to-fan-popup"), null, false);
	});
	
	// schova popup pro dopouceni stranky jinym fanouskum
	$("#send-to-fan-popup .close-send-to-fan-popup").click(function(event) {
		event.preventDefault();		
		$("#popupback").fadeOut("slow"); 
		$("#send-to-fan-popup").fadeOut();
		cleanSendToFanPopup();
	});
	
	$("#sendToFanButton").click(function(event) {
		event.preventDefault();
		sendToFan();
	});
	
	$("#comments-popup .close-comments-popup").click(function(event) {
		event.preventDefault();
		$("#comments-popup").fadeOut("slow", function() {
			// vycistime popup
			$("#comment").val("");
			$("#comments").html("");
			$('#popupNumber').parent().html('<span id="popupNumber"></span>');
			
			// zresetujeme informacie o tyme
			$('#team-code').val("");
			$('#team-home').val("");
		});		
	});
	
	$("#submitCommentButton").click(function(event) {
		event.preventDefault();
		addComment();
	});		
});

/**
 * Zobrazi zluty box se zadanou uzivatelskou hlaskou.
 */
function showMessageInUserMessagBox(message) {
	$("#userMessage p").text(message);
	showUserMessageBox();
}

function cleanSendToFanPopup() {
	$("#text").val("");
	$("#senderName").val("");
	$("#recipientEmail").val("");
	$("#send-to-fan-popup p.errors").hide();
}

/**
 * Posle zpravu jinemu fanouskovi.
 */
function sendToFan() {
	var message = { senderName:null, recipientEmail:null, text:null, url:null };
	dwr.util.getValues(message);
	dwr.engine.beginBatch();
	SendToFansDWRManager.sendToFan(message, function(data) {	
		if (data.errors.length > 0) {
			var html = "";
			// zobrazi chyby
			for(i = 0; i < data.errors.length; i++) {
				html += data.errors[i] + "<br/>";
			}
			$("#send-to-fan-popup p.errors").html(html).show();				
		}else if (data.successMessage != null) {
			$("#popupback").fadeOut("slow");
			$("#send-to-fan-popup").fadeOut();			
			cleanSendToFanPopup();
			showMessageInUserMessagBox(data.successMessage);			
		}
	});
	dwr.engine.endBatch();
}

/**
 * Sestavi remember-me cookie podle cookie vytvorene v java aplikaci.
 * 
 * @param javaCookie cookie sestavena v aplikaci
 */
function setRememberMeCookie(javaCookie) {
	var nowMiliseconds = new Date().getTime();
	var expireDate = new Date(nowMiliseconds + (javaCookie.maxAge * 1000));	
	document.cookie = javaCookie.name + "=" + escape(javaCookie.value) + ";expires=" + expireDate.toGMTString() + ";path=" + javaCookie.path;
}

/**
 * Zobrazi boxik v hlavicce s uzivatelskou hlaskou.
 */
function showUserMessageBox() {
	$("#userMessage").slideDown(600);
	setTimeout("hideUserMessageBox()", 3000);
}

/**
 * Schova boxik v hlavicce s uzivatelskou hlaskou.
 */
function hideUserMessageBox() {
	$("#userMessage").slideUp(600);
}

/* OBLIBENE A SLEDOVANE POLOZKY */

/**
 * Restuje zobrazeni popupu pro pridani oblibenych polozek do implicitni podoby.
 */
function resetFavoritePopup() {
	$("#favorite-activate-email-success").hide();
	$("#favorite-email-registration-success").hide();
	$("#favorite-activate-email-success").hide();
	$("#favorite-activate-email").show();
	$("#favorite-registrate-email").show();
	$("#favorites-popup .col-in").hide();
}

/**
 * Prida hrace do oblibenych polozek.
 */
function addPlayerToFavorites(playerId, element) {
	if ($("#registered-user").val() == 'false') {
		showLoginPopup(element);
		return;
	}
	element.data("originalText", element.text());
	element.text(favoritesAdding);
	WatchedEntityDwrManager.addPlayerToFavorites(playerId, function(data) {				
		handleFavoritesDWRResult(data, element, true, "Player");
	});
}

/**
 * Prida tym do oblibenych polozek.
 */
function addTeamToFavorites(teamId, element) {
	if ($("#registered-user").val() == 'false') {
		showLoginPopup(element);
		return;
	}
	element.data("originalText", element.text());
	element.text(favoritesAdding);
	WatchedEntityDwrManager.addTeamToFavorites(teamId, function(data) {				
		handleFavoritesDWRResult(data, element, true, "Team");
	});
}

/**
 * Prida hrace do sledovanych polozek.
 */
function watchPlayer(playerId, element) {
	if ($("#registered-user").val() == 'false') {
		showLoginPopup(element);
		return;
	}
	element.data("originalText", element.text());
	element.text(favoritesAdding);
	WatchedEntityDwrManager.watchPlayer(playerId, function(data) {				
		handleWatchedDWRResult(data, element, true, "Player");
	});
}

/**
 * Prida tym do sledovanych polozek.
 */
function watchTeam(teamId, element) {
	if ($("#registered-user").val() == 'false') {
		showLoginPopup(element);
		return;
	}
	element.data("originalText", element.text());
	element.text(favoritesAdding);
	WatchedEntityDwrManager.watchTeam(teamId, function(data) {				
		handleWatchedDWRResult(data, element, true, "Team");
	});
}

/**
 * Prida zapas do sledovanych polozek.
 */
function watchMatch(matchId, element) {
	if ($("#registered-user").val() == 'false') {
		showLoginPopup(element);
		return;
	}
	element.data("originalText", element.text());
	element.text(favoritesAdding);
	WatchedEntityDwrManager.watchMatch(matchId, function(data) {				
		handleWatchedDWRResult(data, element, true, "Match");
	});
}

/**
 * Odstrani oblibeneho hrace. Pokud je atribut watch = true, tak ho pouze
 * prestane sledovat.
 */
function removePlayerFromFavorites(watchedPlayerId, watch, element) {
	element.data("originalText", element.text());
	element.text(favoritesRemoving);
	WatchedEntityDwrManager.removePlayerFromFavorites(watchedPlayerId, watch, function(data) {
		if (watch) {
			handleWatchedDWRResult(data, element, false, "Player");
		} else {
			handleFavoritesDWRResult(data, element, false, "Player");
		}
	});
}

/**
 * Odstrani oblibeny tym. Pokud je atribut watch = true, tak ho pouze
 * prestane sledovat.
 */
function removeTeamFromFavorites(watchedTeamId, watch, element) {
	element.data("originalText", element.text());
	element.text(favoritesRemoving);
	WatchedEntityDwrManager.removeTeamFromFavorites(watchedTeamId, watch, function(data) {				
		if (watch) {
			handleWatchedDWRResult(data, element, false, "Team");
		} else {
			handleFavoritesDWRResult(data, element, false, "Team");
		}
	});
}

/**
 * Odstrani sledovany zapas.
 */
function removeMatchFromFavorites(watchedMatchId, watch, element) {
	element.data("originalText", element.text());
	element.text(favoritesRemoving);
	WatchedEntityDwrManager.removeMatchFromWatched(watchedMatchId, function(data) {				
		handleWatchedDWRResult(data, element, false, "Match");
	});
}

/**
 * Zpracuje vysledek volani DWR metody pro ukladani oblibenych polozek.
 */
function handleFavoritesDWRResult(result, element, add, entityName) {
	if (result.errors.length > 0) {
		var html = "";
		// zobrazi chyby
		for(i = 0; i < result.errors.length; i++) {
			html += result.errors[i] + "\n";
		}
		element.text(element.data("originalText"));
		alert(html);				
	}
	if (result.successMessage != null) {
		if (add) {
			newElement = "<a class=\"button\" href=\"\" onclick=\"remove"+entityName+"FromFavorites("+result.successMessage+", false, $(this)); return false;\">" + favoritesRemove.toUpperCase() + "</a>";
		} else {
			newElement = "<a class=\"button\" href=\"\" onclick=\"add"+entityName+"ToFavorites("+result.successMessage+", $(this)); return false;\">" + favoritesAdd.toUpperCase() + "</a>";
			// pokud odeberu z oblibenych, musim zmenit take tlacitko pri pripominani hodnoceni
			watchElement = element.parent().next("p").children("a");
			newWatchElement = "<a class=\"button\" href=\"\" onclick=\"watch"+entityName+"("+result.successMessage+", $(this)); return false;\">" + favoritesMentionStart.toUpperCase() + "</a>";
			watchElement.replaceWith(newWatchElement);
		}
		element.replaceWith(newElement);
	}
	if (result.failureMessage != null) {
		element.text(element.data("originalText"));
		handleFailureDWR(result.failureMessage, element);
	}
}

/**
 * Zpracuje vysledek volani DWR metody pro ukladani sledovanych polozek.
 */
function handleWatchedDWRResult(result, element, add, entityName) {
	if (result.errors.length > 0) {
		var html = "";
		// zobrazi chyby
		for(i = 0; i < result.errors.length; i++) {
			html += result.errors[i] + "\n";
		}
		element.text(element.data("originalText"));
		alert(html);				
	}
	if (result.successMessage != null) {
		if (add) {			
			newElement = "<a class=\"button\" href=\"\" onclick=\"remove"+entityName+"FromFavorites("+result.successMessage+", true, $(this)); return false;\">" + favoritesMentionStop.toUpperCase() + "</a>";
			// pokud pridavam do sledovanych, musim zmenit take tlacitko pri pridavani do oblibenych
			watchElement = element.parent().prev("p").children("a");
			if(watchElement.length) {
				newWatchElement = "<a class=\"button\" href=\"\" onclick=\"remove"+entityName+"FromFavorites("+result.successMessage+", false, $(this)); return false;\">" + favoritesRemove.toUpperCase() + "</a>";
				watchElement.replaceWith(newWatchElement);
			}
		} else {
			newElement = "<a class=\"button\" href=\"\" onclick=\"watch"+entityName+"("+result.successMessage+", $(this)); return false;\">" + favoritesMentionStart.toUpperCase() + "</a>";
		}
		element.replaceWith(newElement);
	}
	if (result.failureMessage != null) {
		element.text(element.data("originalText"));
		handleFailureDWR(result.failureMessage, element);
	}
}

/**
 * Zpracuje vysledek volani DWR metody, ktera ma mit za nasledek zobrazeni
 * popupu s informacni hlaskou.
 */
function handleFailureDWR(failureMessage, element) {
	// uzivatel chtel sledovat entitu, ale nema aktivni email
	if (failureMessage == "favorites.user.email.notActive") {
		$("#favorite-email-not-active").show();
		showFrontendPopup($('#favorites-popup'), element, false);	
	} else if (failureMessage == "favorites.user.email.notRegistered") {
		$("#favorite-email-not-registered").show();
		showFrontendPopup($('#favorites-popup'), element, false);
	}
}

/**
 * Zobrazi popup pro prihlaseni, pokud si chtel uzivatel pridat oblibenou
 * polozku, ale nebyl prihlasen
 */
function showLoginPopup(buttonElement) {
	var element = $("#favorite-user-not-logged");
	element.parent().css("width", "320px");
	element.show();
	showFrontendPopup($('#favorites-popup'), buttonElement, false);	
}

/**
 * Zobrazi popup pro pridavani oblibenych polozek a sledovani hodnoceni.
 */
function showFrontendPopup(popupElement, buttonElement, commentPopup) {
    var popup = popupElement,
        left = 0,
        top = 0,
        screen = Utils.getWindowDimensions();      
    
    // pokud se ma popup zobrazit vedle tlacitka
    if (buttonElement != null && buttonElement.length) {
    	var position = buttonElement.offset();
    	top = position.top - (popup.height() / 2);
    	// popup zobrazime vlevo od tlacitka
    	if (buttonElement.data("left") != null) {
    		left = position.left - popup.width() - 10;
        // jinak vpravo
    	} else {
    		left = position.left + buttonElement.outerWidth() + 10;
    	}
    } else {
    	screen.width = $("#page").outerWidth();
	    // Netscape compliant
	    if (typeof window.pageXOffset === 'number') {
	        left = window.pageXOffset;
	        top = window.pageYOffset;
	    }
	    // DOM compliant
	    else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
	        left = document.body.scrollLeft;
	        top = document.body.scrollTop;
	    }
	    // IE6 standards compliant mode
	    else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
	        left = document.documentElement.scrollLeft;
	        top = document.documentElement.scrollTop;
	    }
	    
	    // horizontalne na stred obrazovky
	    left = left + (screen.width / 2) - (popup.width() / 2);
	    if (left < 0) {
	        left = 0;
	    }
	    
	    // vertikalne na stred obrazovky
	    if (!commentPopup) {
	    	top = top + (screen.height / 2) - (popup.height() / 2);
	    } else {
	    	// ak je to popup s komentarmi musi ist o nieco vyssie
	    	top = top + (screen.height / 2) - (popup.height() / 1.1);
	    }
	    if (top < 0) {
	        top = 0;
	    }
    }    
    
    if (popup.is(':visible')) {
        popup.fadeOut();
        return false;
    }

    popup.css( {
        left: left + 'px',
        top: top + 'px'
    });
    popup.fadeIn();
    return false;
}

/* KONEC OBLIBENYCH A SLEDOVANYCH POLOZEK */

function showPopupback() {
	$("#popupback").css({"opacity": "0.7"});
    // opacity pro IE6
    $("#popupback").css({"filter": "alpha(opacity=70)"});
    $("#popupback").show(); 
}

/* SLOVNE HODNOTENIE */

/**
 * Globálna premenná, ktorá bude slúžiť ako príznak či sa v popupe nachádza môj komentár. Ak áno textarea sa nezobrazí
 */
var containsMyComment;
var authenticatedUserID;

/**
 * Funkcia zobrazí popup pre pridávanie a zobrazovanie slovného hodnotenia hráča/trénera/rozhodcu/komentátora/tymu v zápase.
 * V prípade, že sa jedná o tým je id = id zápasu a surname je kód týmu
 */
function showComments(authUserId, max_likes, id, name, surname, type, authUsername, role_admin, home, number) {	
	var popupTitle, 
	    prefix = how + ' ', 
	    sufix = name + ' ' + surname, 
	    comment, 
	    link, homeTeamName, visitorTeamName, rate, sumOfComments,
	    divMatchLink = $('#matchLink');
	
	containsMyComment = false;
	authenticatedUserID = authUserId;
	
	$('#entity-type').val(type);
	$('#entity-id').val(id);		
	
	UserCommentsDwrManager.getPopupInfo(id, surname, type, function(popupInfo) {
		// vykreslime nadpis popupu podla toho na ktoru osobu bolo kliknute
		if (type === 'player') {
			popupTitle = prefix + played + ' ';
			if (number != undefined) {
				$('#popupNumber').text('#' + number + ' ');
			}
			$('#popupNumber').parent().html($('#popupNumber').parent().html() + name + ' ' + surname);
			divMatchLink.html(createMatchLink(false, popupInfo));
		} else if (type === 'coach') {
			popupTitle = prefix + coached + ' ';
			$('#popupNumber').parent().html($('#popupNumber').parent().html() + name + ' ' + surname);
			divMatchLink.html(createMatchLink(false, popupInfo));
		} else if (type === 'referee') {
			popupTitle = prefix + umpire + ' ';
			$('#popupNumber').parent().html($('#popupNumber').parent().html() + name + ' ' + surname);
			divMatchLink.html(createMatchLink(true, popupInfo));
		} else if (type === 'commentator') {
			popupTitle = prefix + commented + ' ';
			$('#popupNumber').parent().html($('#popupNumber').parent().html() + name + ' ' + surname);
			divMatchLink.html(createMatchLink(true, popupInfo));
		} else if (type === 'team') {
			popupTitle = prefix + playedMany + ' ';
			$('#popupNumber').parent().html($('#popupNumber').parent().html() + name);
			divMatchLink.html(createMatchLink(false, popupInfo));
			sufix = name;
			$('#team-code').val(surname);
			$('#team-home').val(home);
		}
		$('#commentsPopupTitle').text(popupTitle + sufix + '?');
	});
	
	// ak uz je ukoncene hodnotenie schovame formular na pridavanie komentarov
	if (authUsername == null) {
		$('#hidable-comment').css('display', 'none');
	} else {
		$('#hidable-comment').css('display', 'block');
	}
	
	// vykreslime komentare do popupu
	if (type != 'team') {
		UserCommentsDwrManager.getCommentsForRateableRecord(id, function(list) {				
			createComments(list, authUsername, role_admin, max_likes);
			
			// ak popup obsahuje moj komentar, nemozem uz hodnotit takze sa mi schova textarea
			if (containsMyComment) {
				$('#hidable-comment').css('display', 'none');
			}
		});
	} else {
		UserCommentsDwrManager.getCommentsForTeamRecord(surname, id, function(list) {				
			createComments(list, authUsername, role_admin, max_likes);
			
			// ak popup obsahuje moj komentar, nemozem uz hodnotit takze sa mi schova textarea
			if (containsMyComment) {
				$('#hidable-comment').css('display', 'none');
			}
		});
	}
	
	// zobrazime popup
	showFrontendPopup($('#comments-popup'), null, true);
	
	// zresetujeme priznak
	containsMyComment = false;
}

/**
 * Funkcia vytvorí div s komentármi
 * @param list zoznam UserCommentDTO s komentármi
 */
function createComments(list, authUsername, role_admin, max_likes) {
	var commentDiv, tmp, inserted = false;
	for (var i = 0;i < list.length;i++) {
		commentDiv = createCommentDiv(max_likes, list[i], authUsername, role_admin);
		// vlozime si bod pred ktory budeme vkladat nove komentare
		if (list[i].sumOfVotes == 0 && !inserted) {
			tmp = $('#comments').html();
			$('#comments').html(tmp + '<input type="hidden" id="popup-insert-point" value="true" />');
			inserted = true;
		}
		tmp = $('#comments').html();
		$('#comments').html(tmp + commentDiv);
	}
	
	if (!inserted) {
		tmp = $('#comments').html();
		$('#comments').html(tmp + '<input type="hidden" id="popup-insert-point" value="true" />');
	}
	
	if (list.length == 0 && $('#comments').text() == "" && authUsername != null && authUsername != "") {
		tmp = $('#comments').html();
		$('#comments').html(tmp + '<p id="no-comments">' + addFirst + '</p>');
	} else if (list.length == 0 && $('#comments').text() == "" && (authUsername == null || authUsername == "")) {
		tmp = $('#comments').html();
		$('#comments').html(tmp + '<p id="no-comments">' + commentNoAvailable + '</p>');
	}
}


/**
 * Funkcia pridá komentár danej entite a zobrazí ho na prvom mieste v zozname komentárov v popupe
 */
function addComment(param, entityId, entityType) {
	if ($('#entity-type').val() != 'team') {
		var content, comments, insertPoint;
		if (param == 2) {
			content = $('#comment2');
			comments = $('#comments2');
			insertPoint = $('#page-insert-point');
		} else {
			content = $('#comment');
			comments = $('#comments');
			entityId = $('#entity-id').val();
			entityType = $('#entity-type').val();
			insertPoint = $('#popup-insert-point');
		}
		UserCommentsDwrManager.addComment(entityId, content.val(), entityType, function(commentDTO) {
			var commentDiv = createCommentDiv(null, commentDTO, commentDTO.userCommented);
			
			// pridame komentar na prve miesto v boxiku komentarov			
			content.val("");
			comments.fadeOut("slow", function() {
				$('#no-comments').remove();
				$(commentDiv).insertAfter(insertPoint);
				
				if (comments.attr('id') == 'comments') {
					$(commentDiv).insertAfter('#page-insert-point');
				}
				
				// schovame textarea v popupe aj na stranke
				$('#hidable-comment').fadeOut("slow", function() {
					$('#hidable-comment').css('display', 'none');
				});
				
				$('#hidable-comment2').fadeOut("slow", function() {
					$('#hidable-comment2').css('display', 'none');
				});
				
				// ak je to prvy komentar daneho hraca v zapase tak ho zobrazime v boxiku pri jeho mene v zalozke komentare
				var blockquote = $("blockquote[id='player-blockquote_" + entityId + "__']");
				if (blockquote.text() == "") {
					blockquote.text(commentDTO.comment);
					blockquote.attr('id', 'player-blockquote_' + entityId + '_' + commentDTO.commentId + '_' + commentDTO.userID);
				}
			});		
			comments.fadeIn();
			
			$('#popupCommentCount').text(commentDTO.recordCommentCount);
			
			// upravime pocet komentarov v odkaze na popup
			editCommentSumInPersonLink(commentDTO.recordCommentCount, commentDTO.recordId, commentDTO.userID);
		});
	} else {
		addTeamComment();
	}
}

/**
 * Funkcia pripraví formulár pre editáciu komentára
 */
function prepareCommentEditForm() {
	UserCommentsDwrManager.getUserCommentIfNotVotedYet($('#entity-id').val(), function(content) {
		$('#comment').fadeOut("fast", function() {
			$('#comment').val(content)
			$('#submitCommentButton').attr('value', edit);
		});
		$('#comment').fadeIn();
	});
}

/**
 * Funkcia edituje komentár
 */
function editComment() {
	UserCommentsDwrManager.editComment($('#entity-id').val(), $('#comment').val(), function(commentDTO) {
		var commentId = 'comment_' + commentDTO.commentId;
		var commentCell = $("div[id='" + commentId + "']").find(".comment-content");
		commentCell.fadeOut("slow", function() {
			commentCell.text(commentDTO.comment);
			$('#comment').val("");
			$('#submitCommentButton').attr('value', send);
		});
		commentCell.fadeIn();
	});
}

/**
 * Funkcia zahlasuje za komentár.
 * @param commentId id komentáru
 */
function voteForComment(commentId, teamCode, matchId, authUserID) {
	var tmp = teamCode;
	if (teamCode == undefined) {
		teamCode = $("#team-code").val();
	} else {
		$("#team-code").val(teamCode);
	}
	
	if (authUserID != undefined) {
		authenticatedUserID = authUserID;
	}
	
	if (matchId == undefined) {
		matchId = $("#entity-id").val();
	}
	UserCommentsDwrManager.voteForComment(commentId, teamCode, matchId, function(commentDTO) {
		var thumbId, 
		    commentIdentificator = 'comment_' + commentDTO.commentId,
		    commentDiv = $("div[id='" + commentIdentificator + "']"),
		    commentRate = commentDiv.find(".like-it");
		
		if (commentRate.hasClass('off')) {
			commentRate.attr('class', 'like-it');
		} else {
			commentRate.addClass('off');
		}
		
		// upravime pocet komentarov na odkazoch
		$('#popupCommentCount').text(commentDTO.recordCommentCount);
		
		commentRate.text(commentDTO.sumOfVotes);
		if ($("#team-code").val() == "") {
			editCommentSumInPersonLink(commentDTO.recordCommentCount, commentDTO.recordId, commentDTO.userID);
		} else {
			editCommentSumInTeamLink(commentDTO.recordCommentCount, $('#team-home').val(), commentDTO.recordId, commentDTO.userID);
			// ak sme manualne nastavovali input team-code (hlasovanie zo stranky, nie z popupu) tak ho resetujeme
			if (tmp != undefined) {
				$("#team-code").val("");
			}
		}
	});
}

/**
 * Metóda pridá komentár ku týmu
 * @param teamCode kód týmu
 * @param matchId id zápasu
 * @param home príznak, či sa jedná o domáci alebo hosťujúci tým
 */
function addTeamComment(teamCode, matchId, home, param) {
	var content, 
	    count, comments, commentDiv;
	
	if (param == 2) {
		content = $('#comment2');
		comments = $('#comments2');
		insertPoint = $('#page-insert-point');
	} else {
		// ak pridavame komentar z popupu
		content = $('#comment');
		comments = $('#comments');		
		matchId = $('#entity-id').val();
		teamCode = $('#team-code').val();
		home = $('#team-home').val();
		insertPoint = $('#popup-insert-point');
	}
	
	UserCommentsDwrManager.addTeamComment(teamCode, matchId, content.val(), function(commentDTO) {
		if (param == 2) {
			commentDiv = createCommentDiv(null, commentDTO, commentDTO.userCommented, null, teamCode, matchId);
		} else {
			commentDiv = createCommentDiv(null, commentDTO, commentDTO.userCommented);
		}
		
		// pridame komentar na prve miesto v boxiku komentarov			
		content.val("");
		comments.fadeOut("slow", function() {
			$('#no-comments').remove();
			$(commentDiv).insertAfter(insertPoint);
			
			if (comments.attr('id') == 'comments') {
				commentDiv = createCommentDiv(null, commentDTO, commentDTO.userCommented, null, teamCode, matchId);
				$(commentDiv).insertAfter('#page-insert-point');
			}
			
			// schovame textarea v popupe aj na stranke
			$('#hidable-comment').fadeOut("slow", function() {
				$('#hidable-comment').css('display', 'none');
			});
			
			$('#hidable-comment2').fadeOut("slow", function() {
				$('#hidable-comment2').css('display', 'none');
			});
			
			// ak to je prvy komentar daneho tymu zobrazime ho aj v boxiku "POSLEDNI ZAPASY A HODNOCENI"
			var blockquote = $("blockquote[id='team-blockquote_" + teamCode + "__']");
			if (blockquote.text() == "") {
				blockquote.text(commentDTO.comment);
				blockquote.attr('id', 'team-blockquote_' + teamCode + '_' + commentDTO.commentId + '_' + commentDTO.userID);
			}
			
		});		
		comments.fadeIn();

		// aktualizujeme texty kde sa nachadza pocet komentarov
		$('#popupCommentCount').text(commentDTO.recordCommentCount);
		editCommentSumInTeamLink(commentDTO.recordCommentCount, home, commentDTO.recordId, commentDTO.userID);
	});
}

/**
 * Funkcia zmaže komentár aj s jeho všetkými palcami
 * @param commentId id komentára
 */
function removeComment(commentId, teamCode, matchId) {
	var tmp = teamCode, blockquote;
	if (teamCode == undefined) {
		teamCode = $("#team-code").val();
	} else {
		$("#team-code").val(teamCode);
	}
	
	if (matchId == undefined) {
		matchId = $("#entity-id").val();
	}
	
	UserCommentsDwrManager.removeComment(commentId, teamCode, matchId, function(commentDTO) {
		var commentIdentificator = 'comment_' + commentId,
		    commentDiv = $("div[id='" + commentIdentificator + "']"); 
		
		commentDiv.fadeOut(300, function() {
			commentDiv.remove();
		});
		
		if ($("#team-code").val() == "") {
			editCommentSumInPersonLink(commentDTO.sumOfVotes, commentDTO.recordId, commentDTO.userID);
			// ak by nahodou bol nas mazany komentar niekde na stranke pod popupom tak ho zmazeme
			blockquote = $("blockquote[id='player-blockquote_" + commentDTO.recordId + "_" + commentDTO.commentId + "_" + commentDTO.userID + "']");
			blockquote.text("");
			if (commentDTO.sumOfVotes == 0) {
				blockquote.attr('id', 'player-blockquote_' + commentDTO.recordId + '__');
			}
		} else {
			editCommentSumInTeamLink(commentDTO.sumOfVotes, $('#team-home').val(), commentDTO.recordId);
			// ak sme manualne nastavovali input team-code (hlasovanie zo stranky, nie z popupu) tak ho resetujeme
			if (tmp != undefined) {
				$("#team-code").val("");
			}
			blockquote = $("blockquote[id='team-blockquote_" + teamCode + "_" + commentDTO.commentId + "_" + commentDTO.userID + "']");
			blockquote.text("");
			if (commentDTO.sumOfVotes == 0) {
				blockquote.attr('id', 'team-blockquote_' + teamCode + '__');
			}
		}
		$('#popupCommentCount').text(commentDTO.sumOfVotes);
		
		if (commentDTO.sumOfVotes == 0) {
			$('#comments').html('<input type="hidden" id="popup-insert-point" value="true" /><p id="no-comments">' + addFirst + '</p>');
		}
		
		// zobrazime textarea v popupe aj na stranke
		$('#hidable-comment').fadeIn("slow", function() {
			$('#hidable-comment').css('display', 'block');
		});
		
		$('#hidable-comment2').fadeIn("slow", function() {
			$('#hidable-comment2').css('display', 'block');
		});
	});
}

/**
 * Funkcia aktualizuje text odkazu na popup s komentármi u osoby v zápase
 * @param commentSum počet komentárov, ktorý sa tam má zobraziť
 */
function editCommentSumInPersonLink(commentSum, recordId, userID) {
	var commentCount, commentLink;
	if ($('#entity-id').val() == "") {
		commentCount = 'commentCount_' + recordId;
	} else {
		commentCount = 'commentCount_' + $('#entity-id').val();
		recordId = $('#entity-id').val();
	}
    commentLink = $('a[id="' + commentCount + '"]');
    
    // ak sme na zalozke s ciselnym hodnotenim tak je text odlisny ako na zalozke so slovnym hodnotenim
    if ($('#comment-section').val() != 'comments') {
    	if (commentSum == 0) {
    		commentLink.text(addFirst);
    	} else if (commentSum > 4) {
    		commentLink.text(show + ' ' + commentSum + ' ' + commentsShow1);
    	} else if (commentSum == 1) {
    		commentLink.text(showOne);
    	} else if (commentSum > 1 && commentSum < 5) {
    		commentLink.text(show + ' ' + commentSum + ' ' + commentsShow2);
    	}
    } else {
    	if (commentSum == 0) {
    		commentLink.text(addFirst + ' »');
    	} else if (commentSum == 1 && authenticatedUserID != userID) {
    		commentLink.text(addYours + ' »');
    		$('.' + bwPlayer).text(oneComment)
    	} else if (commentSum == 1 && authenticatedUserID == userID) {
    		commentLink.text(nextComments + ' »');
    		$('.' + bwPlayer).text(oneComment)
    	} else if (commentSum == 2) {
    		commentLink.text(nextComment + ' »');
    		$('.' + bwPlayer).text('2 ' + commentsShow2)
    	} else if (commentSum > 2 && commentSum < 6) {
    		commentLink.text(next + ' ' + (commentSum - 1) + ' ' + commentsShow2 + ' »');
    	} else if (commentSum > 5) {
    		commentLink.text(next1 + ' ' + (commentSum - 1) + ' ' + commentsShow1 + ' »');
    	}
    }

    // v pripade ze sme na stranke hraca upravime pocty komentarov
	var commentSumClass = 'comment-sum_' + recordId, 
	    bwPlayer = 'bw-player_' + recordId;
	$('.' + commentSumClass).text(commentSum);
	
	if (commentSum == 0 || commentSum > 4) {
		$('.' + bwPlayer).text(commentSum + ' ' + commentsShow1);
	} else if (commentSum == 1) {
		$('.' + bwPlayer).text(oneComment);
	} else if (commentSum > 1 && commentSum < 5) {
		$('.' + bwPlayer).text(commentSum + ' ' + commentsShow2);
	}
}

/**
 * Funkcia aktualizuje počet komentárov v odkaze na popup s komentármi pre tým
 * @param sum nový súčet komentárov
 * @param home príznak, či aktualizujeme domáci alebo hosťujúci tým
 */
function editCommentSumInTeamLink(sum, home, recordId, userID) {
	var div;
	if (home == 'true') {
		div = $('#homeTeamCommentCount');
	} else if (home == 'false') {
		div = $('#visitorTeamCommentCount');
	}
	
	if (div != undefined) {
		// ak sme na zalozke s ciselnym hodnotenim tak je text odlisny ako na zalozke so slovnym hodnotenim
	    if ($('#comment-section').val() != 'comments') {
	    	if (sum == 0) {
	    		div.text(addFirst);
	    	} else if (sum > 4) {
	    		div.text(sum + ' ' + commentsShow1);
	    	} else if (sum == 1) {
	    		div.text(oneComment);
	    	} else if (sum > 1 && sum < 5) {
	    		div.text(sum + ' ' + commentsShow2);
	    	}
	    } else {
	    	if (sum == 0) {
	    		div.text(addFirst + ' »');
	    	} else if (sum == 1 && authenticatedUserID != userID) {
	    		div.text(addYours + ' »');
	    	} else if (sum == 1 && authenticatedUserID == userID) {
	    		div.text(nextComments + ' »');
	    	} else if (sum == 2) {
	    		div.text(nextComment + ' »');
	    	} else if (sum > 2 && sum < 6) {
	    		div.text(next + ' ' + (sum - 1) + ' ' + commentsShow2 + ' »');
	    	} else if (sum > 5) {
	    		div.text(next1 + ' ' + (sum - 1) + ' ' + commentsShow1 + ' »');
	    	}
	    }
	}

	// ak sme na stranke tymu tak mozme aktualizovat odkazy podobne ako na stranke zapasu u hracov pretoze sa nam nekryju ID hracov a tymov
    if ($('#team-site').val() == 'team') {
    	var commentSumClass = 'comment-team-sum_' + recordId,
    	    commentCountClass = 'commentCount_' + recordId, 
    	    commentLink = $('.' + commentCountClass);
    	
    	$('.' + commentSumClass).text(sum);
    	if (sum == 0) {
    		commentLink.text(addFirst + ' »');
    	} else if (sum == 1 && authenticatedUserID != userID) {
    		commentLink.text(addYours + ' »');
    	} else if (sum == 1 && authenticatedUserID == userID) {
    		commentLink.text(nextComments + ' »');
    	} else if (sum == 2) {
    		commentLink.text(nextComment + ' »');
    	} else if (sum > 2 && sum < 6) {
    		commentLink.text(next + ' ' + (sum - 1) + ' ' + commentsShow2 + ' »');
    	} else if (sum > 5) {
    		commentLink.text(next1 + ' ' + (sum - 1) + ' ' + commentsShow1 + ' »');
    	}
    	
    }
    
}

/**
 * Funkcia vytvorí div pre komentár
 * @param commentDTO UserCommentDTO získané cez DWR
 * @return vytvorený div element obsahujúci informácie o komentári
 */
function createCommentDiv(max_likes, commentDTO, authUsername, role_admin, teamCode, matchId) {
	var y = max_likes / 3;
	var displayComment = '<div id="comment_' + commentDTO.commentId + '" class="comment" style="margin-top: 0px">';
	
	if (max_likes == null) {
		displayComment = displayComment + '<blockquote class="cite-2">"';
	} else if (commentDTO.sumOfVotes > (2 * y) && max_likes > 2) {
		displayComment = displayComment + '<blockquote class="cite-3">"';
	} else if ((((commentDTO.sumOfVotes > y) && (commentDTO.sumOfVotes <= (2 * y))) && max_likes > 2) || max_likes < 3) {
		displayComment = displayComment + '<blockquote class="cite-2">"';
	} else if (commentDTO.sumOfVotes <= y && max_likes > 2) {
		displayComment = displayComment + '<blockquote class="cite-1">"';
	} 
	
	displayComment = displayComment + commentDTO.comment + '"</blockquote>';
	
	// ak je to moj komentar tak ho mozem zmazat, alebo ak som admin tak mozem mazat vsetky
	if (((commentDTO.userCommented === authUsername || commentDTO.userContextId === authUsername) && authUsername != null) || role_admin) {
		
		// ak nie som admin ale mam tu komentar alebo ak som admin a mam tu komentar tak prepneme containsMyComment na true, cize sa nezobrazi textarea
		if (!role_admin || (((commentDTO.userCommented === authUsername || commentDTO.userContextId === authUsername) && authUsername != null) && role_admin)) {
			containsMyComment = true;
		}
		
		displayComment = (displayComment + '<div class="remove-comment"><i><a href="" onclick="removeComment(' + commentDTO.commentId);
		
		if (teamCode != undefined && matchId != undefined) {
			displayComment = displayComment + ', \''; 
			displayComment = displayComment + teamCode; 
			displayComment = displayComment + '\', '; 
			displayComment = displayComment + matchId; 
		}
		displayComment = displayComment + '); return false;">' + commentRemove + '</a></i></div>';
	}
	
	// mozme palcovat komentar len v otvorenom zapase (v uzavretom zapase sa authUsername nepredava do modelu a nasledne do JS)
	displayComment = displayComment + '<a href="" class="like-it'; 
	if (commentDTO.votedByUser) { 
		displayComment = displayComment + ' off';
	}
	displayComment = displayComment + '" onclick="';
	
	if (authUsername != null && authUsername != '') {
		displayComment = displayComment + 'voteForComment(' + commentDTO.commentId;
		if (teamCode != undefined && matchId != undefined) {
			displayComment = displayComment + ', \'';
			displayComment = displayComment + teamCode;
			displayComment = displayComment + '\', ';
			displayComment = displayComment + matchId;
			displayComment = displayComment + '); ';
		} else {
			displayComment = displayComment + '); ';
		}
		 
	}
	displayComment = displayComment + 'return false;">' + commentDTO.sumOfVotes + '</a></div>';
	return displayComment;
}

/**
 * Funkcia vytvorí odkaz na zápas v hornej časti popupu s komentármi
 * @param noPlayer true ak je to rozhodca / komentátor, inak false
 * @param popupInfo PopupInfoDTO
 * @return html odkazu na daný zápas
 */
function createMatchLink(noPlayer, popupInfo) {
	var matchLink = '<span class="nolink-match">';
	matchLink = matchLink + '<img class="fl tlogo" src="' + popupInfo.imageLink + '" width="40" height="40" />';
	matchLink = matchLink + '<span class="name my-team">' 
	if (noPlayer) {
		matchLink = matchLink + popupInfo.homeTeamName + '</span><span class="name"><strong>' + popupInfo.visitorTeamName + '</strong> &nbsp;</span>';
	} else {
		// v tomto pripade je homeTeamName meno oponenta
		matchLink = matchLink + 'proti &nbsp;</span><span class="name"><strong>' + popupInfo.homeTeamName + '</strong> &nbsp;</span>';
	}
	matchLink = matchLink + '<span class="rating r-player r-match '
	var rate = popupInfo.rate;
	if (rate == null) {
		matchLink = matchLink + 'r-value-3">?</span></span>';
	} else if (rate < 20) {
		matchLink = matchLink + 'r-value-1">' + rate / 10 + '</span></a>';
	} else if (rate > 19 && rate < 40) {
		matchLink = matchLink + 'r-value-2">' + rate / 10 + '</span></a>';
	} else if (rate > 39 && rate < 60) {
		matchLink = matchLink + 'r-value-3">' + rate / 10 + '</span></a>';
	} else if (rate > 59 && rate < 80) {
		matchLink = matchLink + 'r-value-4">' + rate / 10 + '</span></a>';
	} else if (rate > 79) {
		matchLink = matchLink + 'r-value-5">' + rate / 10 + '</span></a>';
	} 
	return matchLink;
}


