function kbummInit() {
	//Fancybox for lightbox rel attribute
	$("a[rel=lightbox]").fancybox();
	$("a[rel=lightbox[imagegroup]]").fancybox();

	//Fancybox for dialogs
	$("a[rel=dialog]").fancybox({ 
		'hideOnContentClick': false,
		'centerOnScroll': false,
		'width' : 580,
		'height' : 431,
		'autoDimensions' : true,
		'scrolling' : 'no', 
		'showNavArrows' : false,
		'enableLeftRight' : false,
		'titleShow' : false,
		'onComplete' : function() {
			//$('input[type!=hidden]:first').focus();
			$('input#searchinput').focus();
		}
	});

	//Fancybox for pn dialogs
	$("a[rel=dialog_pn]").fancybox({ 
		'hideOnContentClick': false,
		'centerOnScroll': false,
		'width' : 522,
		'height' : 550,
		'autoDimensions' : true,
		'scrolling' : 'no', 
		'showNavArrows' : false,
		'enableLeftRight' : false,
		'titleShow' : false,
		'onComplete' : function() {
			//$('input[type!=hidden]:first').focus();
			//$('input#searchinput').focus();
		}
	});	
	
	//Fancybox for pn dialogs
	$("a[rel=dialog_posting]").fancybox({ 
		'hideOnContentClick': false,
		'centerOnScroll': false,
		'width' : 522,
		'height' : 440,
		'autoDimensions' : true,
		'scrolling' : 'no', 
		'showNavArrows' : false,
		'enableLeftRight' : false,
		'titleShow' : false,
		'onComplete' : function() {
			//$('input[type!=hidden]:first').focus();
			$('input#searchinput').focus();
		}
	});		
	
	//Fancybox for form rel attribute (forms)
	$("a[rel=form]").fancybox({ 
		'hideOnContentClick': false,
		'centerOnScroll': false,
		'width' : 615,
		'height' : 615, 
		'showNavArrows' : false,
		'enableLeftRight' : false
	});

	//Close fancybox
	$('a.fancyclose').click(function(){
	    parent.top.$('#fancy_close').trigger('click');
	});
	
	//Autoresize every textarea
	$("textarea").autoResize({
	    // On resize:
	    onResize : function() {
	        $(this).css({opacity:0.8});
	    },
	    // After resize:
	    animateCallback : function() {
	        $(this).css({opacity:1});
	    },
	    // Quite slow animation:
	    animateDuration : 300,
	    // More extra space:
	    extraSpace : 20
	});
}

function string2integer(id) {
	$("#"+id).val($("#"+id).val().replace(new RegExp(/[^0-9]/g), ""));
}

function string2url(id) {
	$("#"+id).val($("#"+id).val().replace(new RegExp(/[^0-9a-z_-]/g), ""));
}

function json_parse(json_string) {
	return jQuery.parseJSON(json_string);
}

function beforeAjax() {
	$("#messagecontainer").slideUp();
}

function displayLoadingImage(id) {
	$(id).html('<img src="/templates/kbumm/img/ajax-loader.gif" width="16" height="16" alt="Loading" />');
}

////////////////// COMMENTS ////////////////////
function toggleWriteComment(form_id) {
	$("#"+form_id+"_formdivcomment").slideToggle();
	$("#"+form_id+"_comment_textarea").focus();
}

function saveComment(form_id, type, type_id) {
	beforeAjax();
	var data = $("#"+form_id).serialize();
	$("#"+form_id+"_submit_comment_button").attr("disabled", "disabled");
	$("#"+form_id+"_submit_comment_loading").css("display", "inline");
	$.ajax({
		type: "POST",
		url: '/kbumm/ajax/actions/comments.php',
		data: data,
		success: function(json) {
			if (typeof json == "object" && 'success' in json && json['success']) {
				// success
				$("#"+form_id+"_submit_comment_loading").css("display", "none");
				$("#"+form_id+"_comment_textarea").html('');
				$("#"+form_id+"_submit_comment_button").removeAttr("disabled");
				$("#"+form_id+"_formdivcomment").slideToggle(400, function() {
					if(form_id == "form_comment_bottom") {
						window.location.href = "#comments"; 
					}
					getComments(type, type_id, 0);
				});				
			} else {
				$("#"+form_id+"_submit_comment_loading").css("display", "none");
				$("#"+form_id+"_submit_comment_button").removeAttr("disabled");
				if (typeof json == "object" && 'messages' in json) {
					$("#"+form_id+"_formerrorscomment").html(json['messages']);
				}
				else {
					alert("Es ist ein unbekannter Fehler aufgetreten.\n" + json);
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			$("#"+form_id+"_submit_comment_loading").css("display", "none");
			$("#"+form_id+"_submit_comment_button").removeAttr("disabled");
			alert("Ajax Fehler. Bitte versuchen Sie es noch einmal.");
		}
	});
}

function deleteComment(id) {
	if(confirm("Soll der Kommentar wirklich gelöscht werden?")) {
		beforeAjax();
		$.ajax({
			type: "POST",
			url: '/kbumm/ajax/actions/comments.php',
			data: "request=deleteComment&id="+id,
			success: function(json) {
				if ('success' in json && json['success']) {
					$("#divcomment"+id).slideUp();
				} else {
					if ('messages' in json) {
						showMessages(json['messages']);
					}
					else {
						alert("Es ist ein unbekannter Fehler aufgetreten.");
					}
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				alert("Ajax Fehler. Bitte versuchen Sie es noch einmal.");
			}
		});
	}
}

function getComments(type, type_id, start, isPrivate) {
	beforeAjax();
	displayLoadingImage(".commentpagination");
	$.ajax({
		type: "POST",
		url: '/kbumm/ajax/actions/comments.php',
		data: "request=getComments&type="+type+"&type_id="+type_id+"&start="+start+"&isPrivate="+isPrivate,
		success: function(json) {
			if ('success' in json && 'html' in json && json['success']) {
				// success
				$("#comments").html(json['html']);
			} else {
				if ('messages' in json) {
					showMessages(json['messages']);
				}
				else {
					alert("Es ist ein unbekannter Fehler aufgetreten.");
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("Ajax Fehler. Bitte versuchen Sie es noch einmal.");
		}
	});
}

function getImageGallery(type, type_id, start) {
	beforeAjax();
	displayLoadingImage("#imagegallery_pagination");
	$.ajax({
		type: "POST",
		url: '/kbumm/ajax/actions/imagegallery.php',
		data: "request=getImageGallery&type="+type+"&type_id="+type_id+"&start="+start,
		success: function(json) {
			if (typeof json == "object" && 'success' in json && 'html' in json && json['success']) {
				// success
				$("#imagegallery").html(json['html']);
			} else {
				if (typeof json == "object" && 'message' in json) {
					showMessages(json['message']);
				}
				else {
					alert("Es ist ein unbekannter Fehler aufgetreten. " + json);
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("Ajax Fehler. Bitte versuchen Sie es noch einmal.");
		}
	});	
}

//////////////////LOGIN, LOGOUT ////////////////////
function showPersistentBox() {
	$("#persistent_box").show();
}

function login() {
	beforeAjax();
	$("#loginbutton").css("display", "none");
	$("#loginloading").css("display", "inline");
	var data = $("#login_bottom").serialize();
	
	if($('#login_persistent').is(':checked')) {
		data = data + "&login_persistent=1";
	}
	
	$.ajax({
		type: "POST",
		url: '/kbumm/ajax/actions/login.php',
		data: data,
		success: function(json) {
			if ('success' in json && 'html' in json && json['success']) {
				// successful login		
				if ('messages' in json) {
					showMessages(json['messages']);
				}				
				$("#communitybar").html(json['html']);
				kbummInit();
				 $("div.chatmessages").each(function(index) {
					 $(this).scrollTop($(this)[0].scrollHeight);
				 });
			} else {
				$("#loginloading").css("display", "none");
				$("#loginbutton").css("display", "inline");

				if ('messages' in json) {
					showMessages(json['messages']);
				}
				else {
					alert("Es ist ein unbekannter Fehler aufgetreten.");
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("Ajax Fehler. Bitte versuchen Sie es noch einmal.");
		}
	});	
}

function logout() {
	beforeAjax();
	$.ajax({
		type: "POST",
		url: '/kbumm/ajax/actions/logout.php',
		data: "kbumm_logout=kbumm_users",
		success: function(json) {
			if ('success' in json && 'html' in json && json.success) {
				// successful logout
				if ('messages' in json) {
					showMessages(json['messages']);
				}				
				$("#communitybar").html(json['html']);
				kbummInit();
				 $("div.chatmessages").each(function(index) {
					 $(this).scrollTop($(this)[0].scrollHeight);
				 });				
			} else {
				if ('messages' in json) {
					showMessages(json['messages']);
				}
				else {
					alert("Es ist ein unbekannter Fehler aufgetreten.");
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("Ajax Fehler. Bitte versuchen Sie es noch einmal.");
		}
	});	
}

function showMessages(messages_html) {
	if($("#messagecontainer").css("display") == "none") {
		$("#messagecontainer").html(messages_html);
		$("#messagecontainer").slideDown();		
	}
	else {
		$("#messagecontainer").slideUp('medium', function() {
			$("#messagecontainer").html(messages_html);
			$("#messagecontainer").slideDown();
		});
	}
}

//////////////////HOME ////////////////////
function getTeaser(type, start) {
	var teasernav_html = $("#teasernav_"+type).html();
	displayLoadingImage("#teasernav_"+type);
	
	$.ajax({
		type: "POST",
		url: '/kbumm/ajax/content/home/teaser.php',
		data: "request=getTeaser&type="+type+"&start="+start,
		success: function(json) {
			if ('success' in json && 'teasernav' in json && json['success']) {
				// successful teaser request
				if ('messages' in json) {
					showMessages(json['messages']);
				}
				$("#teasernav_"+type).html(json['teasernav']);
				
				if ('html' in json) {
					$("#teasercontent_"+type).html(json['html']);
				}
				else if('newssport' == type) {
					if ('html1' in json) {
						$("#teasercontent_"+type+"1").html(json['html1']);
					}
					if ('html2' in json) {
						$("#teasercontent_"+type+"2").html(json['html2']);
					}
				}
				
			} else {
				if ('messages' in json) {
					showMessages(json['messages']);
				}
				else {
					alert("Es ist ein unbekannter Fehler aufgetreten.");
				}
				
				$("#teasernav_"+type).html(teasernav_html);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("Ajax Fehler. Bitte versuchen Sie es noch einmal.");
			$("#teasernav_"+type).html(teasernav_html);
		}
	});	
}

//////////////////CONTENT////////////////////
function showCitySelect(id) {
	$("#divselect_"+id).show();

	setTimeout("setHideCitySelectEventHandler('divselect_"+id+"')", 500);
}

function selectCity(id, select_id, location_select_id) {
	var value = $('#'+id).attr("title");
	var label = $('#'+id).html();
	$('#'+select_id).html('');
	
	$('#'+select_id).append(
	   $('<option></option>').val(value).html(label)
	);
	$('#'+select_id).append(
		$('<option></option>').val('0').html('Ort auswählen ...')
	);
	
	$('#'+select_id+':first-child').attr("selected", "selected");
	
	if(location_select_id.length > 0) {
		updateLocations(location_select_id, value);
	}
	$('#divselect_'+select_id).hide();
	$('body').unbind('click');
}

function updateLocations(select_id, city) {
	$.ajax({
		type: "POST",
		url: '/kbumm/ajax/content/contentController.php',
		data: "request=getLocations&city="+city,
		success: function(json) {
			if ('success' in json && json['success'] && 'options' in json) {
				$('#'+select_id).html('');
				for (var value in json['options']) {
					$('#'+select_id).append(
							$('<option></option>').val(value).html(json['options'][value])
					);
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			//doNothing
		}
	});	
}

function setHideCitySelectEventHandler(id) {
	$('body').click(function() {
	  $('#'+id).hide();
	  $('body').unbind('click');
	});
}

function pressedPrev() {
	if ($('#image').length) {
		var gallery_id = $("#image").attr("gallery_id");
		var prev_id = $("#image").attr("prev_id");
		var pc = $("#image").attr("pc");
		if(gallery_id > 0 && prev_id > 0) {
			changeImage(gallery_id, prev_id, pc);	
		}
	}
}

function pressedNext() {
	if ($('#image').length) {
		var gallery_id = $("#image").attr("gallery_id");
		var next_id = $("#image").attr("next_id");
		var pc = $("#image").attr("pc");
		if(gallery_id > 0 && next_id > 0) {
			changeImage(gallery_id, next_id, pc);	
		}
	}
}

function changeImage(gallery_id, image_id, pc) {
	$.ajax({
		type: "POST",
		url: '/kbumm/ajax/content/imageChanger.php',
		data: "request=changeImage&id="+gallery_id+"&image="+image_id+"&pc="+pc,
		success: function(json) {
			if ('success' in json && json['success']) {
				// successful teaser request
				pic = new Image(100,100); 
				pic.src = json['imageurl'];
				$("#image").fadeOut(400, function() {
					$("#image").html(json['html']);
					document.title = json['title'];
					$("#image").attr("prev_id", json['prev_id']);
					$("#image").attr("next_id", json['next_id']);
					$("#image").fadeIn(400, function() {
						FB.XFBML.parse();
				    });
					kbummInit();
					document.location.assign(document.location.pathname+document.location.search+"#"+json['url']);
				});
			} else {
				if ('messages' in json) {
					showMessages(json['messages']);
				}
				else {
					alert("Es ist ein unbekannter Fehler aufgetreten.");
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("Ajax Fehler. Bitte versuchen Sie es noch einmal.");
		}
	});	
}

function deleteContentItem(type, id, label) {
	if(label == undefined) {
		label = "Soll dieser Beitrag wirklich gelöscht werden?";
	}
	if(confirm(label)) {
		$.ajax({
			type: "POST",
			url: '/kbumm/ajax/content/contentController.php',
			data: "request=delete&type="+type+"&id="+id,
			success: function(json) {
				if (typeof json == "object" && 'success' in json && json['success']) {
					// successful teaser request
					$("#template").fadeOut();
					if ('messages' in json) {
						showMessages(json['messages']);
					}
				} else {
					if (typeof json == "object" && 'messages' in json) {
						showMessages(json['messages']);
					}
					else {
						alert("Es ist ein unbekannter Fehler aufgetreten." + json);
					}
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				alert("Ajax Fehler. Bitte versuchen Sie es noch einmal.");
			}
		});	
	}
}

function subscribeNewsletter() {
	beforeAjax();
	var submitbutton = $("#newsletter_submit").html();
	displayLoadingImage("#newsletter_submit");
	var formdata = $("#newsletter_form").serialize();
	$.ajax({
		type: "POST",
		url: '/kbumm/ajax/newsletter/subscribe.php',
		data: formdata,
		success: function(json) {
			if (typeof json == "object" && 'success' in json && json['success']) {
				// successful teaser request
				$("#template").fadeOut();
				if ('messages' in json) {
					showMessages(json['messages']);
				}
				$("#newsletter_email").html('&nbsp;');
				$("#newsletter_submit").html('&nbsp;');
			} else {
				$("#newsletter_submit").html(submitbutton);
				if (typeof json == "object" && 'messages' in json) {
					showMessages(json['messages']);
				}
				else {
					alert("Es ist ein unbekannter Fehler aufgetreten." + json);
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			$("#newsletter_submit").html(submitbutton);
			alert("Ajax Fehler. Bitte versuchen Sie es noch einmal.");
		}
	});	
}

function kbummFacebookLogin() {
	alert("FacebookLogin call");
	beforeAjax();
	$("#loginbutton").css("display", "none");
	$("#loginloading").css("display", "inline");
	$.ajax({
		type: "POST",
		url: '/kbumm/ajax/actions/login_facebook.php',
		data: '',
		success: function(json) {
			if ('success' in json && 'html' in json && json['success']) {
				// successful login		
				if ('messages' in json) {
					showMessages(json['messages']);
				}				
				$("#communitybar").html(json['html']);
				kbummInit();
				 $("div.chatmessages").each(function(index) {
					 $(this).scrollTop($(this)[0].scrollHeight);
				 });
			} else if ('success' in json && 'register' in json && json['success']) {
				//Fancybox
				alert("fancybox");
			} else {
				$("#loginloading").css("display", "none");
				$("#loginbutton").css("display", "inline");

				if ('messages' in json) {
					showMessages(json['messages']);
				}
				else {
					alert("Es ist ein unbekannter Fehler aufgetreten.");
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("Ajax Fehler. Bitte versuchen Sie es noch einmal.");
		}
	});	
}
