// Diskuze

//diskuze - topic

function addPost(re_id,title, scroll) {
	if(!scroll) {
		scroll = 0;
		obj = $("#addPostDialog").parent();
		scroll = $("#addPostDialog").offset().top;
		while($(obj).attr("id") != "container") {
			scroll += $(obj).offset().top;
			obj = $(obj).parent();
		}
		val = $(document).scrollTop() - scroll;
		max = Math.round( window.innerHeight * 0.7 );
		if((val > max) || (val < 0)) window.scroll(0,(scroll+Math.round( window.innerHeight * 0.4 ))); //Math.round( window.innerHeight * 0.4 )
	} else {
		if(scroll == 'top') scroll = 0;
		window.scroll(0,scroll);
	}
	
	
	if(title != '') document.getElementById('subject').value = "RE: " + title;
	document.getElementById('reID').value = re_id;
	
	if(nm = document.getElementById('nname')) {
		nm.value = (person['name'] || '');
//		document.getElementById('email').value = (person['email'] || '@');
	}
	
	setTimeout("animatedcollapse.show('addPostDialog');", 150);
	return false;
}

function cancelPost() {
	$("#nname").removeClass("error");
//	$("#email").removeClass("error");
	$("#subject").removeClass("error");
	$("#txtdata").removeClass("error");
	animatedcollapse.hide('addPostDialog');
}

function writePosts(responseXML, statusText) {
	animatedcollapse.hide('addPostDialog');
	if($('Status', responseXML).text() != "OK") {
		document.getElementById('output1').innerHTML = $('Message', responseXML).text();
	} else {
		if(page != 1) {
			window.location.href = topic_url;
		} else {
			person = { name: $('sender', responseXML).text(), email: $('sender', responseXML).attr('email')};
			$('#totalResponses').html($('posts',responseXML).attr('total'));
			if($('posts',responseXML).attr('count') > 0) {
				cont = document.getElementById('post_container');
				ss = document.createElement('div');
				ss.style.display = 'none';
				node = cont.firstChild;
				lid = null;
				
				psts = $(responseXML).find("post").each( function() {
					var post = $(this);
					var pst = document.createElement("div");
					if(!lid) lid = post.attr('id');
					pst.className = "postbox";
					html = '<div class="top"><a name="post' + post.attr('id') + '"></a>&nbsp;</div><div class="posthead">';
					ucc = $('author', post);
					if(ucc.attr('link')) {
						html += '<div><a href="' + ucc.attr('link') + '">' + ucc.text() + '</a></div>';
						if(ucc.attr('img')) html +=	'<img src="' + ucc.attr('img') + '" />';
						html += post.attr('created') + '<br /><strong>Aura: ' + ucc.attr('aura') +'</strong>';
					} else {
						html += '<div>' + ucc.text() + '</div>' + post.attr('created');
					}
					html +=	'</div><div class="postbody">' +
							'<div class="postbody_h"><a href="#post' +post.attr('reid') +'">' + $('title', post).text() + '</a></div>' +
							'<p>' + $('text', post).text() + '</p>' +
						'</div>' +
						'<div class="postbutton">' +
						'	<a href="javascript:void(0);" onclick="addPost(' + post.attr('id') + ',\'' + $('title', post).text() + '\',1);" class="midbut">Reagovat</a>' +
						'</div>'+
						(ucc.attr('own') ? '<a href="javascript:void(0);" onclick="editPost('+post.attr('id')+',this.parentNode);" class="editcorner">&nbsp;</a>' : '') +
						'<div class="bottom">&nbsp;</div>';
					pst.innerHTML = html;
					ss.appendChild(pst);
				});
				if(node) {
					cont.insertBefore(ss,node);
				} else {
					cont.appendChild(ss);
				}
				lastPostID = lid;
				$(ss).fadeIn();
			}
		}
	}
}

function crossPageNav(topic_id, target_id) {
	$.get("/_ajax/dis_cpn/"+topic_id + "/" + target_id, function(data) {
		window.location.href = data;
		return false
	});
	return false;
}

//kategorie

function addTopic() {
	window.scroll(0,0);
	$('#newTopic').fadeOut(100, function() {animatedcollapse.show('addPostDialog');});
	return false;
}

function cancelTopic() {
	animatedcollapse.hide('addPostDialog');
	setTimeout("$('#newTopic').fadeIn();", 450);
	$("#nname").removeClass("error");
//	$("#email").removeClass("error");
	$("#subject").removeClass("error");
	$("#txtdata").removeClass("error");
}

function writeTopic(responseXML, statusText) {
	cancelTopic();
	if($('Status',responseXML).text() == 'OK') {
		setTimeout(function() {window.location.href = $("url", responseXML).text();}, 500);
	}
}

var editPostState = 0;
//var editPostContainer = null;

function editPost(post_id, container) {

	if(!editPostState && document.getElementById("postEditBox")) {
		editPostState = 1;
		$("#epfCancel").click();
	}
	
	if(editPostState) {
		setTimeout( function() { editPost(post_id,container);},250);
		return;
	}
	
	$('<div id="postEditBox"><form id="postEditForm"><input type="hidden" name="post" value="'+post_id+'" /><textarea name="edited" class="longTextarea"></textarea><div><input type="button" value="Uožit" class="smbut" id="epfOK" /> <input type="button" value="Storno" class="smbut" id="epfCancel" /></div></form></div>')
		.hide(1)
		.appendTo ( $(".postbody", container) )
	;
	
	$( container ).addClass("edited");

	
	animatedcollapse.addDiv('postEditBox', 'fade=1,hide=1,speed=450');
	animatedcollapse.init();
	
	$("#epfOK").click(function() {
		$("#postEditForm").ajaxSubmit({
			type: "POST",
			url: "/_ajax/dis_postedit/"+UccID+"/",
			dataType: "text",
			success: function(data) {
				targ = $(".postbody p", $('#postEditBox').parent().parent());
				$( targ )
					.html( $( targ ).html() + data )
				;
				$("#epfCancel").click();
			}
		});
	});
	
	$("#epfCancel").click(function() {
		animatedcollapse.ontoggle = function($, divobj, state) {
			if(divobj.id == 'postEditBox') {
				$("#postEditBox").parent().parent().removeClass("edited");
				$(".postbutton", $("#postEditBox").parent().parent() ).slideDown("fast");
				$("#postEditBox").remove();
				editPostState = 0;
				animatedcollapse.ontoggle = null;
			}
		};
		animatedcollapse.hide('postEditBox');
	});
	
	$(".postbutton", container).slideUp("fast", function() {
		animatedcollapse.show('postEditBox');
	});
}

//komentare

function writeComments(responseXML) {
	if($("Clear", responseXML).text() != 1) animatedcollapse.hide('addPostDialog');
	if($('Status', responseXML).text() == "OK") {
		person = { name: $('sender', responseXML).text(), email: $('sender', responseXML).attr('email')};
		locked = parseInt($('Locked', responseXML).text());
		lid = 0;
		if($("Clear", responseXML).text() == 1) {
			$("#postChild_"+firstPostID).empty();
			$("#postNum").html($("posts", responseXML).attr('count'));
		} else {
			$("#postNum").html(viewPosts + parseInt($("posts", responseXML).attr('count')));
		}		
		psts = $(responseXML).find("post").each( function() {
			var post = $(this);
			lastPostID = Math.max(post.attr('id'), lastPostID);
			ucc = $('author', post);
			$('<div></div>')
				.addClass('comment_item')
				.append(
					$('<div class="comment_body'+(viewMode && (post.attr('reid') == firstPostID) ? ' topItem' : '')+'">\n' +
						'	<div class="cmm_head"><span>'+(ucc.attr('link') ? '<a href="'+ucc.attr('link')+'">'+ucc.text()+'</a>' : '<strong>'+ucc.text()+'</strong>')+' | '+post.attr('created')+'</span>'+(locked ? '&nbsp;' : '<a href="javascript:void(0);" onclick="setPostUnfit('+post.attr('id')+',this);">Nevhodný</a> | <a href="javascript:void(0);" onclick="addPost('+post.attr('id')+',\''+$('title', post).text()+'\');" class="react">Reagovat</a>')+'</div>\n' +
						'	<div class="cmm_body"><div>'+$('title', post).text()+'</div>'+$('text', post).text()+'</div>\n' +
						'	<div class="lt_corner">&nbsp;</div><div class="rt_corner">&nbsp;</div><div class="lb_corner">&nbsp;</div><div class="rb_corner">&nbsp;</div>\n' +
					'</div>\n')
				)
				.append(
					$('<div class="comment_children" id="postChild_'+post.attr('id')+'"></div>')
				)
				.prependTo($("#postChild_"+(viewMode ? post.attr('reid') : firstPostID)))
				.slideDown('slow')
			;			
			
		});
		if($("posts", responseXML).attr('count')) {
			$('#showAllLink').show(1);
			$('#hideAllLink').show(1);
		}
	}
}

function setDisViewMode(mode) {
	if(mode) {
		srt0 = $("#commSortingBy > span");
		srt1 = $("#commSortingBy > a");
		srt0.replaceWith('<a href="javascript:void(0);" onclick="setDisViewMode(0);">'+srt0.html()+'</a>');
		srt1.replaceWith('<span>'+srt1.html()+'</span>');
	} else {
		srt0 = $("#commSortingBy > a");
		srt1 = $("#commSortingBy > span");
		srt0.replaceWith('<span>'+srt0.html()+'</span>');
		srt1.replaceWith('<a href="javascript:void(0);" onclick="setDisViewMode(1);">'+srt1.html()+'</a>');
	}
	viewMode = mode;
//	if($("#showAllLink")) $("#showAllLink").attr("href","?dis=all:"+mode);
	$.ajax({
		url: "/_ajax/dis_load_comm/"+topicID+"/"+viewMode+"/"+viewAll+"/",
		type: "GET",
		dataType: "xml",
		success: writeComments
	});
}

var unfitPost = null;

function setPostUnfit(post_id, obj) {
	unfitPost = obj;
	$.ajax({
		url: "/_ajax/dis_post_unfit/"+post_id+"/",
		type: "GET",
		success: function(data) {
			$(unfitPost).replaceWith("uloženo");
		}
	});
	
}

// User Profile Functions

function SaveBox(box_type, box) {
	//saving procedure ...
	switch(box_type) {
		case 1: { 
			$("#descrForm").ajaxForm({
				url: "/_ajax/ucc_save_box/"+UccID+"/"+box_type +"/",
				type: "POST",
				dataType: "xml",
				success: function(xml) {
					$('#uccDescr').html(""+$("description", xml).text());
					CancelBox(1, $("#uccDescr").parent().parent().parent(), 1);
				}
			})
			.submit();
			break;
		}
		case 2: {

			$("#personalForm").ajaxForm({				
				url: "/_ajax/ucc_save_box/"+UccID+"/"+box_type +"/",
				type: "POST",
				dataType: "xml",
				success: function(xml) {
					$("#names").html( $("name", xml).text() || "nevyplněno" );
					if(!$("name", xml).text()) $("#names").parent().addClass('nodata');
		
					$("#city").html( $("city", xml).text() || "nevyplněno");
					if(!$("city", xml).text()) $("#city").parent().addClass('nodata');
					$("#www").html( $("www", xml).text() || "nevyplněno");
					if(!$("www", xml).text()) $("#www").parent().addClass('nodata');
					$("#gender").html( $("gender", xml).text() || "nevyplněno");
					if(!$("gender", xml).text()) $("#gender").parent().addClass('nodata');
					$("#birth").html( $("birth", xml).text() || "nevyplněno");
					if(!$("birth", xml).text()) $("#birth").parent().addClass('nodata');
					tp = $("gender",xml).attr('type');
					$("#gbirthtitle").html ("Narozen" + (tp > 0 ? (tp == 2 ? "a" : "") : "(a)") + ":");
					CancelBox(2, $("#names").parent().parent().parent().parent(), 1);
				}
			})
			.submit();
			break;
		}
		case 3: {
			$("#friendsForm").ajaxForm({
				url: "/_ajax/ucc_save_box/"+UccID+"/"+box_type +"/",
				type: "POST",
				dataType: "xml",
				success: function(xml) {
					$("#friendList").empty();
					$("item", xml).each(function() {
						itm = $(this);
						$('<div class="fr_item"><a href="'+ $("link", itm).text() +'">'+ $("name", itm).text() +'</a>'+($("descr", itm).text() ? " - " + $("descr", itm).text() : '') + '</div>')
							.appendTo($("#friendList"));
					});
				}
			})
			.submit();
			return true;
		}
	}
	return false;
}

function CancelBox(box_type, box, fromsave) {
	if(!fromsave) {
		if(box_type == 1) {
			$(".pb1_body", box).html( box.$oldContent );
		} else {
			$(".pb_body", box).html( box.$oldContent ); 
		}
	}
	$(box).removeClass('pb'+box_type+'_edited');
	
}

function EditBox(box_type, box) {
	box.$oldContent = (box_type == 1 ? $(".pb1_body", box).html() : $(".pb_body", box).html());
	switch(box_type) {
		case 1: {
			
			text = $('#uccDescr').html();
			$('#uccDescr').html("");
			// id="inDescr" class="longTextarea"
			$('<textarea name="descr"></textarea>')
				.addClass("longTextarea")
				.val(text)
				.appendTo('#uccDescr')
			;
			$(box).addClass('pb'+box_type+'_edited');
			return true;
		}
		
		case 2: {
			$.ajax({
				type: "GET",
				url: "/_ajax/ucc_info/"+UccID+"/",
				dataType: "xml",
				success: function(xml) {			
					$("#names").html('<input type="text" value="' + $("name",xml).text() +'" name="name" class="smalltextinput" /> <input type="text" value="' + $("sname",xml).text() +'" name="surname" class="smalltextinput" />');
					$("#city").html('<input type="text" value="' + $("city",xml).text() +'" name="city" class="textinput" />');
					$("#www").html('<input type="text" value="' + $("www",xml).text() +'" name="www" class="textinput" />');
					$("#gender").html('<select id="inGender" name="gender"><option value="">---</option><option value="1">muž</option><option value="2">žena</option></select>');
					$("#gender > select").val( $("gender",xml).text() );
					
					$('#birth').html("");
					val = $('birth', xml).attr('day');
					var day_s = $("<select></select>")
						.attr({ name: "birth_day"})
						.addOption("","--")
						.addOption( range(1,31,1,1) , false)
						.appendTo('#birth')
					;
					if(val != "0") $(day_s).selectOptions( val , true );
					$('#birth').append(" . ");

					val = $('birth', xml).attr('month');
					var month_s = $("<select></select>")
						.attr({ name: "birth_month"})
						.addOption("","--")
						.addOption( range(1,12,1,1) , false)
						.appendTo('#birth')
					;
					if(val != "0") $(month_s).selectOptions( val , true );
					$('#birth').append(" . ");

					yea = new Date();
					max = yea.getFullYear();
					min = max - 100;
					val = $('birth', xml).attr('year');
					var year_s = $("<select></select>")
						.attr({ name: "birth_year"})
						.addOption("","----")
						.addOption( range(min,max,1, min) , false)
						.appendTo('#birth')
					;
					if(val != "0") $(year_s).selectOptions( val , true );
					
					$("div.line", box).removeClass("nodata");
					
					$(box).addClass('pb'+box_type+'_edited');
					
					return true;
				}
			});			
			break;
		}
		case 3: {
			$.ajax({
				type: "GET",
				url: "/_ajax/ucc_fedit/"+UccID+"/",
				dataType: "html",
				success: function(data) {
					$(box).addClass('pb'+box_type+'_edited');
					mdShow(data, { 
						title: 'Nastavení přátel',
						w: '600px',
//						h: "350px",
						close: function() {
							$('#uploadAlay').show();
							CancelBox(3, $("#friendList").parent());
						},
						open: function() {
							$('#uploadAlay').hide();
						}
					});
				}
			});
			return true;
		}
		default: return false;	
	}
}

function UploadAvatarInit() {
	new AjaxUpload( "#uploadAlay" , {
		autoSubmit: 1,
		action: '/_ajax/ucc_avatar/'+UccID+"/",		
		onSubmit : function(file , ext){
			if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){
				$('<img alt="" id="loadingImg" />')
					.attr("src", "/media/img/admin/loading_bar.gif")
					.css({ position: "absolute", bottom: "-15px", left: "-14px", height: "2px", width: "128px"  })
					.appendTo ( $("#uploadAlay") )
				;
			} else {
				alert("Špatný formát souboru");
				return false;				
			}
	
		},
		onComplete : function(file, xml){
			imgPar = $('#avatar').parent();
			$('#avatar').remove();
			$('<img id="avatar" />')
				.attr("src", $("path", xml).text())
				.appendTo( imgPar )
			;
			$(imgPar).addClass("imagePresent");
			$("#loadingImg").remove();
		}
	});
}

function mdShow(content, par ) {
	title = "Info";
	p = par || null;
	ce = p['close'] || null;
	oe =  p['open'] || null;
	css = {};
	
	if(p['title']) title = p['title'];
	if(p['w']) css['width'] = p['w'];
	if(p['h']) css['height'] = p['h'];
	
	data = '<div class="modalDialog"><div class="mdHead">'+title+'</div><div class="mdContent">' + content + '</div></div>';
	if(oe) oe();
	$(data).modal({onClose: mdClose, onOpen: mdOpen, containerCss: css, position: ['15%',]});
	document.getElementById('simplemodal-container').$cEvent = ce;
	
}

function mdClose( dialog ) {
	
	dialog.container.slideUp('fast',function() {
		dialog.overlay.fadeOut('fast',function() {
			if(func = document.getElementById('simplemodal-container').$cEvent) func();
			$.modal.close();
		});
	});
	return true;
}

function mdOpen( dialog ) {

	dialog.overlay.fadeIn('fast',function() {
		dialog.data.show(1,function() {
			dialog.container.slideDown('slow');
		});
	});
	return true;
}

function mdFrSave() {
	if(SaveBox(3,$("#friendList").parent(), 1)) {
		$.modal.close();
		return;
	}
	$.modal.close();
}

function addToFriends(target_id, link) {
	atfDia = $('<div id="addToFriends"><div class="atfBody"><form id="atfForm"><input type="hidden" name="target_id" value="'+target_id+'" />Poznámka:<br /><textarea name="note" class="longTextarea"></textarea><div><input type="button" value="OK" id="atfOK" class="smbut smbut_grey" /><input type="button" value="Storno" id="atfCancel" class="smbut smbut_grey" /></div></form></div><div>')
		.hide(1)
		.appendTo($(link).parent())
	;
	$("#addToFriends .atfBody").dropShadow();
	$("#addToFriends")		
		.fadeIn('fast', function() {
			$('#atfCancel').click ( function() {
				$("#addToFriends")
					.fadeOut('fast', function(){
					$("#addToFriends").remove();
				});
			});
			
			$('#atfOK').click ( function() {
				$("#atfForm").ajaxSubmit({
					type: "POST",
					url: "/_ajax/ucc_fadd/"+UccID+"/",
					dataType: "xml",
					success: function(xml) {
						jQuery.noticeAdd({
					        text: $("text",xml).text(),
					        type: ($("status", xml).text() == 1 ? 'success' : 'error')
						});
					}
				});
				$('#atfCancel').click();
				return false;
			});
		})
	;
}