/* KOMENTARZE by mh (c) 2007 v1.0 */

var EditoComments = function(domid, id_kategorii, id_elementu, kategoria_nazwa, element_tytul)
{
	this.domid = domid;
	if (id_kategorii)
	{
		this.id_kategorii = id_kategorii;
	}
	if (id_elementu)
	{
		this.id_elementu = id_elementu;
	}
	this.kategoria_nazwa = kategoria_nazwa;
	this.element_tytul = element_tytul;
	this.cache_id = $('#cache_modul_'+this.id_kategorii+'_id').val();
}

EditoComments.prototype = {
	id_kategorii: 0,
	id_elementu: 0,
	limit: 30,
	offset: 0,
	commentIdPrefix: 'c_',
	kategoria_nazwa: '',
	element_tytul: '',
	loginLink: '/go:login',
	linkBack: '',
	register_captcha: 0,
	ownComments: 0,
	showCommented: 0,
	// teksty mozna nadpisac przy wywolaniu skryptu, pobrac z langa
	modifiedText: 'edytowany [ilosc_modyfikacji]. raz: [data_modyfikacji] przez użytkownika \'[edytowal]\'',
	deletedText: 'Ten komentarz został usunięty przez użytkownika \'[usunal]\' ([data_usuniecia]).',
	headerText: 'Komentarze użytkowników',
	addText: 'Dodaj komentarz',
	editText: 'edytuj',
	deleteText: 'usuń',
	saveText: 'Zapisz',
	prevText: '&laquo; nowsze',
	nextText: 'starsze &raquo;',
	commentedText: 'Komentowany element: ',
	deleteQuestionText: 'Czy na pewno chcesz usunąć ten komentarz?',
	addMsgText: 'Komentarz został dodany.',
	addMsgTextError: 'Odczekaj chwilę przed dodaniem kolejnego komentarza! Komentarz nie został dodany!',
	editMsgText: 'Zmiany w komentarzu zostały zapisane.',
	deleteMsgText: 'Komentarz został usunięty.',
	errorEmptyCommentText: 'Komentarz nie może być pusty.',
	loginText: 'Zaloguj się, aby dodać komentarz.',
	
	fullRegister: '',
	loginRegister: 'login',
	passwordRegister: 'haslo',
	emailRegister: 'email',
	registerText: 'Nie masz konta? SZYBKA REJESTRACJA',
	addRegisterText: 'Twoja rejestracja zakończyła się sukcesem! Jesteś już zalogowany i możesz korzystać z dodatkowych opcji.',
	registerButton: 'Rejestruj',
	registerOpis:'Jeśli w tym momencie nie masz czasu na uzupełnienie profilu skorzystaj z szybkiej rejestracji.<br />'+
				'W pola poniżej wpisz swój login, hasło oraz e-mail, na który otrzymasz link aktywujący konto. <br />Całość zajmuje mniej niż minutę!'+
				'<br />Możesz też skorzystać z <a href="%s">pełnego formularza</a> rejestracji jeśli już teraz chcesz uzupełnić profil.',

	addCaptchaError: 'Kod przepisany z obrazka jest niepoprawny',
	captchaText: 'Przepisz powyższy kod:',
	nick: 'Twój nick:',
	render: function()
	{
		this.get();
	},

	get: function(id)
	{
		var tmpThis = this;
	
		$.ajax({
			type: "POST",
			url: $.ajaxUrl('comments', 'get'),
			data: 'id_kategorii=' + this.id_kategorii +
				'&id_elementu=' + this.id_elementu +
				'&limit=' + this.limit +
				'&offset=' + this.offset +
				(id ? '&id=' + id : '') +
				(this.ownComments ? '&own_comments=1' : ''),
			dataType: "xml",
			async: 'false',
			success: function(xml){
				// wyczyszczenie listy, gdy ladujemy cala od nowa
				if (!id)
				{
					$('#' + tmpThis.domid).empty();
					if ($.browser.msie)
					{
						$('#' + tmpThis.domid).width($('#' + tmpThis.domid).parent().width()); // ie6 hack - rozjezdzanie
					} 
					tmpThis.addHeader(false, $("comments > count", xml).text());
					tmpThis.addPager($("comments > count", xml).text());
				}
				
				$("comments > comment", xml).each(function(){
					tmpThis.addToList(this, id ? true : false);
				});
				
				// pokolorowanie listy
				$('#' + tmpThis.domid + ' .comment:odd').addClass('even');
				
				if (!id && $("comments > count", xml).text() > 0)
				{
					tmpThis.addPager($("comments > count", xml).text(), true);
					tmpThis.addHeader(true);
				}
			}
		});
	},


	addToList: function(commentXml, replace)
	{
		var tmpThis = this;

		comment = $('<div class="comment" id="' + this.commentIdPrefix + $('id', commentXml).text() + '">');
		vcard = $('<div class="vacrd">');

		
		if (this.showCommented)
		{
			commented = $('<div class="commented">').html(this.commentedText);
			element = $('kategoria_nazwa', commentXml).text() + ($('element_tytul', commentXml).text() != '' ? ' &raquo; ' + $('element_tytul', commentXml).text() : '');
			commented.append($('<a></a>').attr('href', $('element_link', commentXml).text()).html(element));
			commented.appendTo(vcard);
		}
		
		dateAdded = $('<div class="commentDateAdded">');
		dateAdded.append($('data_dodania', commentXml).text());
		dateAdded.appendTo(vcard);

		commentAuthor = $('<div class="commentAuthor">');
		commentAuthor.append($('wlasciciel', commentXml).text());	
		commentAuthor.appendTo(vcard);
		vcard.appendTo(comment);
				
		if ($('usuniety', commentXml).text() == '1')
		{
			deleted = $('<div class="commentDeleted">');
			str = this.deletedText;
			str = str.replace(/\[data_usuniecia\]/, $('data_usuniecia', commentXml).text());
			str = str.replace(/\[usunal\]/, $('usunal', commentXml).text());
			deleted.append(str);
			deleted.appendTo(comment);
		}
		else
		{
			content = $('<div class="commentContent">');
			content.append(nl2br(show($('tresc', commentXml).text())));
			content.appendTo(comment);
			
			if ($('ilosc_modyfikacji', commentXml).text() > 0)
			{
				modified = $('<div class="commentModified">');
				str = this.modifiedText;
				str = str.replace(/\[ilosc_modyfikacji\]/, $('ilosc_modyfikacji', commentXml).text());
				str = str.replace(/\[data_modyfikacji\]/, $('data_modyfikacji', commentXml).text());
				str = str.replace(/\[edytowal\]/, $('edytowal', commentXml).text());
				modified.append(str);
				modified.appendTo(comment);
			}
			
			if ($('edytowalny', commentXml).text() == '1')
			{
				options = $('<div class="commentOptions">');
				options.append($('<a class="buttonSmall buttonSmallRight"></a>').text(this.deleteText).click(function(){tmpThis.remove(commentXml)}));
				options.append($('<a class="buttonSmall buttonSmallRight"></a>').text(this.editText).click(function(){tmpThis.edit(commentXml)}));
				options.append($('<div class="clear">'));
				options.appendTo(comment);
			}
		}

		if (replace)
		{
			$('#' + this.commentIdPrefix + $('id', commentXml).text()).replaceWith(comment);
		}
		else
		{
			$('#' + this.domid).append(comment);
		}
	},


	addHeader: function(footer, commentCount)
	{
		var tmpThis = this;
		
		header = $('<div class="commentsHeader ' + (footer ? 'commentsHeaderF' : 'commentsHeaderH') + '">');
		headerL = $('<div class="commentsHeaderL">');
		headerL.appendTo(header);
		headerR = $('<div class="commentsHeaderR">');
		headerR.appendTo(headerL);
		
		if (!footer)
		{
			header1 = $('<div class="commentsHeader1">').text(this.headerText);
			header1.append($('<div class="commentsCount">').text(' (' + commentCount + ')'));
			headerR.append(header1);
		} 
		
		if (this.id_kategorii)
		{
			header2 = $('<div class="commentsHeader2">');
			header2.append($('<a></a>').text(this.addText).click(function(){tmpThis.add(footer)}));
			headerR.append(header2);
		}	
		
		if (headerR.html() != '')
		{
			$('#' + this.domid).append(header);
		}
	},


	add: function(footer)
	{
		var tmpThis = this;
		
		// sprawdzenie, czy user jest zalogowany
		$.post($.ajaxUrl('user', 'islogged'), function(response){
			// jesli juz wyrenderowany formularz, to nie ruszac
			if (!$('#' + tmpThis.domid + (footer ? ' .commentAddF' : ' .commentAddH') + ':visible').size())
			{
				// ukrycie drugiego formularza
				otherForm = '#' + tmpThis.domid + (footer ? ' .commentAddH' : ' .commentAddF');
		
				commentAdd = $('<div class="commentAdd ' + (footer ? 'commentAddF' : 'commentAddH') + '">');

				if (response == '1')
				{
					form = $('<form></form>');
					
					form.append(
						$('<input type="hidden">').attr({
							name: 'kategoria_nazwa',
							value: tmpThis.kategoria_nazwa
						})
					);
					form.append(
						$('<input type="hidden">').attr({
							name: 'element_tytul',
							value: tmpThis.element_tytul
						})
					);
					textarea = $('<textarea></textarea>').attr({
							name: 'tresc',
							'class': 'formularzInput'
						});
					// przepisanie wartosci
					if ($(otherForm).size())
					{
						textarea.val($(otherForm + ' textarea').val());
					}
					form.append(textarea);
				
					form.append(
						$('<input type="submit">').attr({
							value: tmpThis.saveText,
							'class': 'buttonRounded'
						})
					);
					
					form.bind('submit', function(event){
						event.preventDefault();
						event.stopPropagation();
						tmpThis.addSave(this);
					});
					form.appendTo(commentAdd);
				}
				else
				{
					form = $('<form></form>');
					
					form.append(
						$('<input type="hidden">').attr({
							name: 'kategoria_nazwa',
							value: tmpThis.kategoria_nazwa
						})
					);
					form.append(
						$('<input type="hidden">').attr({
							name: 'element_tytul',
							value: tmpThis.element_tytul
						})
					);
					textarea = $('<textarea></textarea>').attr({
							name: 'tresc',
							'class': 'formularzInput'
						});
					// przepisanie wartosci
					if ($(otherForm).size())
					{
						textarea.val($(otherForm + ' textarea').val());
					}
					form.append(textarea);
					
					//nick
					var html = '<div class="comments-captcha">'+
							'<p>'+tmpThis.nick+'</p>'+
							'<div class="inputRoundedL"></div><input class="inputRounded" type="text" name="nick" maxlength="64" /><div class="inputRoundedR"></div>'+
						'</div><div class="clear"></div>';
					
					//captcha
					if(tmpThis.register_captcha == 1)
					{
						html += '<div class="comments-captcha">'+
							'<iframe src="/captcha.php" width="200" height="75" frameborder="no" marginheight="0" marginwidth="0" scrolling="no"></iframe>'+
							'<p>'+tmpThis.captchaText+'</p>'+
							'<div class="inputRoundedL"></div><input class="inputRounded" type="text" name="captcha" maxlength="64" /><div class="inputRoundedR"></div>'+
						'</div><div class="clear"></div>';
					}
					form.append(html);
					
					//submit dodaj
					form.append(
						$('<input type="submit">').attr({
							value: tmpThis.saveText,
							'class': 'buttonRounded'
						})
					);
					
					form.bind('submit', function(event){
						event.preventDefault();
						event.stopPropagation();
						tmpThis.addSave(this);
					});
					form.appendTo(commentAdd);
					
					
					msg = $('<div class="commentsLogin">');
					$('<a></a>').attr('href', tmpThis.loginLink).html(tmpThis.loginText).appendTo(msg);
					commentAdd.append(msg);
					
					// D.Basznianin fastRegister
					pokaz = $('<a id="hideusLink"></a>').html('<h2 class="blockTitle">'+tmpThis.registerText+'</h2>');
					pokaz.bind('click', function()
					{
						$('#hideus').slideToggle('slow');
					});
					pokaz.appendTo(commentAdd);
					
					form = $('<form></form>');
					var html='';
					//fastregister
					html += '<div style="display: none" id="hideus">'+
					'<center><table cellspacing="0" cellpadding="0" border="0" width="480px">'+
					'<tr>'+
						'<td colspan="4"><p class="fastRegister">'+ tmpThis.registerOpis.replace('%s',tmpThis.fullRegister) +
						'</p></td>'+
					'</tr>'+
					'<tr class="formularzRamkaGora">'+
					'<td id="registerLogin">'+
					'<div>'+
						'<div class="inputRoundedL"> </div>'+
						'<input type="text" maxlength="32" value="'+tmpThis.loginRegister+'" onfocus="if(this.value == \''+tmpThis.loginRegister+'\')this.value=\'\'" onblur="if(this.value == \'\')this.value=\''+tmpThis.loginRegister+'\'" name="login" class="inputRounded w100"/>'+
						'<div class="inputRoundedR"> </div></div></td>'+
					
					'<td id="registerPassword">'+
					 '<div>'+
						'<div class="inputRoundedL"> </div>'+
						'<input type="password" maxlength="32" value="'+tmpThis.passwordRegister+'" onfocus="if(this.value == \''+tmpThis.passwordRegister+'\')this.value=\'\'" onblur="if(this.value == \'\')this.value=\''+tmpThis.passwordRegister+'\'" name="password" class="inputRounded w100"/>'+
						'<div class="inputRoundedR"> </div></div>'+
					'</td>'+
						
					'<td id="registerEmail">'+
					'<div>'+
						'<div class="inputRoundedL"> </div>'+
						'<input type="text" maxlength="32" value="'+tmpThis.emailRegister+'" onfocus="if(this.value == \''+tmpThis.emailRegister+'\' )this.value=\'\'" onblur="if(this.value == \'\')this.value=\''+tmpThis.emailRegister+'\'" name="email" class="inputRounded w100"/>'+
						'<div class="inputRoundedR"> </div></div></td>'+

					'</td ><td class="w70">'+
					'<div class="fl di ml1"><div class="buttonGrayL"><div class="buttonGrayR">'+
					'<input type="submit" class="buttonGray" value="'+tmpThis.registerButton+'"/>'+
					'</div></div></div>'+
					'</td></tr></table></center></div>';
					
					form.append(html);
					
					
					form.bind('submit', function(event){
						event.preventDefault();
						event.stopPropagation();
						tmpThis.addfastRegister(this);
					});
					
					form.appendTo(commentAdd);
				}
				
				$(otherForm).slideUp('slow');
				
				commentAdd.hide()
					.insertAfter($('#' + tmpThis.domid + (footer ? ' .commentsHeaderF' : ' .commentsHeaderH')))
					.slideDown('slow', function(){$(otherForm).remove()})
			}
		});
	},
	
	
	addPager: function(commentCount, footer)
	{
		var tmpThis = this;
		
		if (this.limit > 0 && this.limit < commentCount)
		{
			pager = $('<div class="commentsPager ' + (footer ? 'commentsPagerF' : 'commentsPagerH') + '">');
			prev = $('<a class="commentsPrev"></a>').html(this.prevText);
			if (this.offset <= 0)
			{
				prev.addClass('disabled');
			}
			else
			{
				prev.bind('click', function(){
					tmpThis.offset -= tmpThis.limit;
					if (tmpThis.offset < 0)
					{
						tmpThis.offset = 0;
					}
					tmpThis.get();
				});
			}
			next = $('<a class="commentsNext"></a>').html(this.nextText);
			if (this.offset + this.limit >= commentCount)
			{
				next.addClass('disabled');
			}
			else
			{
				next.bind('click', function(){
					tmpThis.offset += tmpThis.limit;
					if (tmpThis.offset + tmpThis.limit > commentCount)
					{
						tmpThis.offset = (Math.ceil(commentCount / tmpThis.limit) - 1) * tmpThis.limit;
					}
					tmpThis.get();
				});
			}
			
			prev.appendTo(pager);
			next.appendTo(pager);
		
			$('#' + this.domid).append(pager);	
		}
	},


	edit: function(commentXml)
	{
		var tmpThis = this;
	
		$('#' + this.domid + ' .commentEdit').hide().remove();
		$('#' + this.domid + ' .commentContent').show();
		$('#' + this.domid + ' .commentOptions').show();
		$('#' + this.domid + ' .commentModified').show();
		
		commentEdit = $('<div class="commentEdit">');
		
		form = $('<form></form>');
		form.append(
			$('<input type="hidden">').attr({
				name: 'id',
				value: $('id', commentXml).text()
			})
		);
		form.append(
			$('<textarea></textarea>').attr({
				name: 'tresc',
				'class': 'formularzInput'
			}).val($('tresc', commentXml).text())
		);
		form.append(
			$('<input type="submit">').attr({
				value: this.saveText,
				'class': 'buttonRounded'
			})
		);
		
		form.bind('submit', function(event){
			event.preventDefault();
			event.stopPropagation();
			tmpThis.editSave(commentXml, this);
		});
		form.appendTo(commentEdit);
	
		$('#' + this.commentIdPrefix + $('id', commentXml).text() + ' .commentOptions').hide();
		$('#' + this.commentIdPrefix + $('id', commentXml).text() + ' .commentModified').hide();
		$('#' + this.commentIdPrefix + $('id', commentXml).text() + ' .commentContent').hide().after(commentEdit);
	},

	addSave: function(form)
	{
		var tmpThis = this;

		// trimowanie
		$(form).find('textarea').val($.trim($(form).find('textarea').val()));
	
		if ($(form).find('textarea').val() == '')
		{
			showAlert($(form).parent(), this.errorEmptyCommentText, 1);
		}
		else
		{
			$.ajax({ 
				type: 'POST', 
				url: $.ajaxUrl('comments', 'add'),
				data: 'id_kategorii=' + this.id_kategorii + 
					'&id_elementu=' + this.id_elementu + 
					'&' + $(form).find(':input').serialize()+'&cache_id='+this.cache_id,
				async: 'false',
				success: function(response){
					if (response > 0)
					{
						if(response == 2)
						{
							showAlert($('#' + tmpThis.domid), tmpThis.addCaptchaError, 'error');
						}
						else
						{
							// odswiezenie listy komentarzy
							tmpThis.offset = 0;
							tmpThis.get();
							
							// ukrycie formularzy
							$('.commentAdd').hide().remove();
									  				
							// powiadomienie
							showAlert($('#' + tmpThis.domid), tmpThis.addMsgText);
						}
					}
					else 
					{
						showAlert($('#' + tmpThis.domid), tmpThis.addMsgTextError, 'error');//alert('error: ' + response);
					}
				}
			});
		}
	},


	addfastRegister: function(form)
	{
		var tmpThis = this;
		
		$.ajax({ 
			type: 'POST', 
			url: $.ajaxUrl('user', 'fastRegister'),
			data: 'id_kategorii=' + this.id_kategorii +
				'&linkBack='+this.linkBack +
				'&' +	$(form).find(':input').serialize(),
			async: 'false',
			success: function(response){
				$('#registerLogin').removeClass('userErrorField');
				$('#registerPassword').removeClass('userErrorField');
				$('#registerEmail').removeClass('userErrorField');
				if (response == 'ok')
				{
					// ukrycie formularzy
					$('.commentAdd').hide().remove();

					// powiadomienie
					showAlert($('#' + tmpThis.domid), tmpThis.addRegisterText, '', 6000);
					
					//refresh
					setTimeout('window.location.href = \"'+tmpThis.linkBack+'\"', 1000);
				}
				else
				{
					response = response.split(':');
					switch (response[0])
					{
						case 'login_istnieje': 
							$('#registerLogin').addClass('userErrorField');
						break;
						case 'email_istnieje':
						case 'email':
							$('#registerEmail').addClass('userErrorField');
						break;
						case 'password_short':
						case 'password':
							$('#registerPassword').addClass('userErrorField');
						break;
						case 'error':
							$('#registerLogin').addClass('userErrorField');
							$('#registerEmail').addClass('userErrorField');
							$('#registerPassword').addClass('userErrorField');
						break;
					}
				
					showAlert($('#' + tmpThis.domid), response[1], 'error', 5000);
				}
			}
		});
	},


	editSave: function(commentXml, form)
	{
		var tmpThis = this;
		
		// trimowanie
		$(form).find('textarea').val($.trim($(form).find('textarea').val()));
	
		if ($(form).find('textarea').val() == '')
		{
			showAlert($('#' + tmpThis.commentIdPrefix + $('id', commentXml).text()), this.errorEmptyCommentText, 1);
		}
		else
		{
			$.ajax({ 
		  		type: 'POST', 
		  		url: $.ajaxUrl('comments', 'edit'),
		  		data: 'id_kategorii=' + this.id_kategorii + 
		  			'&id_elementu=' + this.id_elementu + 
		  			'&' + $(form).find(':input').serialize(),
				async: 'false',
		  		success: function(response){
		  			if (response > 0)
		  			{
			  			if (response == '1') 
			  			{
				  			// odswiezenie komentarza, gdy zmieniony
			  				id = $('id', commentXml).text().split('_');
			  				tmpThis.get(id[0]);
			  			}
			  			
			  			// pokazanie komentarza, ukrycie formularza
			  			$('#' + tmpThis.domid + ' .commentContent').show();
			  			$('#' + tmpThis.domid + ' .commentOptions').show();
			  			$('#' + tmpThis.domid + ' .commentModified').show();
		  				$('#' + tmpThis.domid + ' .commentEdit').hide().remove();
		  						  				
		  				// powiadomienie
		  				showAlert($('#' + tmpThis.commentIdPrefix + $('id', commentXml).text()), tmpThis.editMsgText);
			  		}
			  		else alert('error: ' + response);
		  		}
			});
		}
	},


	remove: function(commentXml)
	{
		var tmpThis = this;
		
		if (confirm(this.deleteQuestionText))
		{
			$.ajax({ 
				type: 'POST', 
				url: $.ajaxUrl('comments', 'remove'),
				data: 'id=' + $('id', commentXml).text() + '&cache_id='+this.cache_id,
				async: 'false',
				success: function(response){
					if (response > 0)
					{
						id = $('id', commentXml).text().split('_');
						
						// odswiezenie
						tmpThis.get(id[0]);
								  				
						// powiadomienie
						showAlert($('#' + tmpThis.commentIdPrefix + $('id', commentXml).text()), tmpThis.deleteMsgText);
					}
					else alert('error: ' + response);
				}
			});
		}
	}
}



// implementacja funkcji phpowych
function stripslashes(str)
{
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

function htmlspecialchars(str)
{
	str = str.replace(/&/g, '&amp;' );
	str = str.replace(/</g, '&lt;' );
	str = str.replace(/>/g, '&gt;' );
	str = str.replace(/"/g, '&quot;' );
	return str;
}

function show(str)
{
	return htmlspecialchars(stripslashes(str));
}

function nl2br(str)
{
	return str.replace(/(\r\n)|(\n\r)|\r|\n/g,"<br />");
}

