$(document).ready(function(){	
		$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8" });
		jQuery("[class*='sjLimit']").sjLimit();
		jQuery("[class*='swSelect']").swSelect();
		jQuery(".formDescription").each(function(){
			$(this).hide();
		})
		if($("#showTop .contentData").html().length > 0) {
			showTop.show();
		}
				$.fn.insertAtCaret = function (tagName) {
			return this.each(function(){
				if (document.selection) {
					//IE support
					this.focus();
					sel = document.selection.createRange();
					sel.text = tagName;
					this.focus();
				}else if (this.selectionStart || this.selectionStart == '0') {
					//MOZILLA/NETSCAPE support
					startPos = this.selectionStart;
					endPos = this.selectionEnd;
					scrollTop = this.scrollTop;
					this.value = this.value.substring(0, startPos) + tagName + this.value.substring(endPos,this.value.length);
					this.focus();
					this.selectionStart = startPos + tagName.length;
					this.selectionEnd = startPos + tagName.length;
					this.scrollTop = scrollTop;
				} else {
					this.value += tagName;
					this.focus();
				}
			});
		};
		$.fn.insertRoundCaret = function (tagName) {
			return this.each(function(){
				strStart = '['+tagName+']';
				strEnd = '[/'+tagName+']';
				if (document.selection) {
					//IE support
					stringBefore = this.value;
					this.focus();
					sel = document.selection.createRange();
					insertstring = sel.text;
					fullinsertstring = strStart + sel.text + strEnd;
					sel.text = fullinsertstring;
					document.selection.empty();
					this.focus();
					stringAfter = this.value;
					i = stringAfter.lastIndexOf(fullinsertstring);
					range = this.createTextRange();
					numlines = stringBefore.substring(0,i).split("\n").length;
					i = i+3-numlines+tagName.length;
					j = insertstring.length;
					range.move("character",i);
					range.moveEnd("character",j);
					range.select();
				}else if (this.selectionStart || this.selectionStart == '0') {
					//MOZILLA/NETSCAPE support
					startPos = this.selectionStart;
					endPos = this.selectionEnd;
					scrollTop = this.scrollTop;
					this.value = this.value.substring(0, startPos) + strStart + this.value.substring(startPos,endPos) + strEnd + this.value.substring(endPos,this.value.length);
					this.focus();
					this.selectionStart = startPos + strStart.length ;
					this.selectionEnd = endPos + strStart.length;
					this.scrollTop = scrollTop;
				} else {
					this.value += strStart + strEnd;
					this.focus();
				}
			});
		};
		$(".showDesc").bind('focus', function() {
			$(this).parent().find(".formDescription").fadeIn();
		})
		$(".showDesc").focusout(function(){
			$(this).parent().find(".formDescription").fadeOut();
		})
		$(".clearMe").one("focus", function(){
			$(this).val(null);
		});
		$.fn.swShowTop = function(){
				$("#showTop").css({'top' : ($(window).height() / 2), 'left' : ($(window).width() / 2 - ($("#showTop").outerWidth() / 2))});
				$("#showTop").delay(500).fadeIn();
				if($(this).hasClass("time")) {
					classes = $(this).attr("class").split(" ");
					time = classes[1].substring(1);
					t=setTimeout(function(){
						$("#showTop").fadeOut();
					},time);
				}
	
			return false;
		}
		$("#showTop .close").click(function(){
			showTop.hide();
		})
				$("#write .selectCats").parent().hide();
		$("#write .selectCatsJs").show();
		$(".dropFieldset").each(function(){
			$(this).slideUp();
		})
		$(".expand").click(function(){
			 $(this).parent().find(".dropFieldset").slideToggle();
		})
		$(".addChapter").click(function(){
			alert("clock");
			//var range = $("#field").caret();
			return false;
		})
		$("#toggleQuickSelection").click(function(){
			$("#quickSelection").fadeToggle();
			return false;
		})
		$("#quickSelection").removeClass("std");
		$("#quickSelection").addClass("stdjquery");
		$(".toggleComments").click(function(){
			$(this).parent().find(".content").fadeToggle();
			return false;
		})
		$(".toggleNewComment").click(function(){
			$("#newComment").fadeToggle();
			return false;
		})
		$(".more").click(function(){
			comments.get();
		});
		$(".toggleComments").one("click",function() {
			comments.get();
		})
		$("#read .text, #read #readerText").scroll(function(){
			if($(this)[0].scrollHeight - $(this).scrollTop() < 1250) {
				fillEmpty = $(".lastSite").nextAll(".empty").eq(0);	
				id = fillEmpty.attr("title");
				if(fillEmpty.length != 0) {
					$.post("/api/api.php", { get: "singleSite", id: id},
					function(data){
						$("#"+'fastSel'+id).removeClass("notLoaded").addClass("loaded").attr("title", "Seite geladen");
						$("#read .text .lastSite").removeAttr("title");
						$("#read .text .lastSite").removeClass("lastSite");
						fillEmpty.html(data);
						fillEmpty.removeClass("empty");
						fillEmpty.removeAttr("title");
						fillEmpty.addClass("lastSite");
					});		
				}
			}
		})
		$("#quickSelection a").click(function(){
			var jumpId = $("#"+$(this).attr("href").slice(1));
			var changeFast = $("#"+'fastSel'+$(this).attr("href").slice(5));
			var hash = $(this).attr("hash");
			if(jumpId.hasClass("empty")) {
				$.post("/api/api.php", { get: "singleSite", id: jumpId.attr("title")},
					function(data){
						$("#read .text .lastSite").removeAttr("title");
						$("#read .text .lastSite").removeClass("lastSite");
						changeFast.removeClass("notLoaded").addClass("loaded").attr("title", "Seite geladen");
						jumpId.html(data);
						jumpId.addClass("lastSite");
						jumpId.removeClass("empty");
						jumpId.removeAttr("title");
						window.location.href = hash;
					});	
				return false;
			}
			$("#quickSelection").fadeToggle();
			
		})
		$(".toggleDesc").click(function(){
			$(".descriptionText").toggle();
		})
		$(".deletePic").click(function(event){
			event.preventDefault();
			showTop.show();
			showTop.set("Bild wirklich löschen? <a href='"+$(this).attr("href")+"'>Ja</a> / <a href='' class='closeTop'>Nein</a>");
		})
		$(".deleteBook").click(function(event){
			event.preventDefault();
			showTop.show();
			showTop.set("Buch wirklich löschen? <a href='"+$(this).attr("href")+"'>Ja</a> / <a href='' class='closeTop'>Nein</a>");
		})
		$(".closeTop").live("click",function(event){
			event.preventDefault();
			showTop.hide();
		})
		$(".switchPicForm").click(function(){
			$("#picBook_addPhoto").toggle();
			$("#picBook_adPhotoNoForm").toggle();
		})
		$(".getMyPics").click(function(event) {
			event.preventDefault();
			var eachClass = string.split($(this).attr("class")," ");
			var singleVars = string.split(eachClass[1],"_");
			choosePic.setTarget(singleVars[1], singleVars[0], singleVars[2]);
			callApi.call("pics",null,"api.pics");		
		})
		$(".choosePic").live("click",function(event){
			event.preventDefault();
			choosePic.insert($(this).attr("href"),"text");
			showTop.hide();
		})
		$(".starRating li a").live("click", function(event){
			event.preventDefault();	
			var starRating = $(".starRating");
			starRating.removeClass().addClass("starRating "+$(this).parent().attr("class")+"star");
			
			var singleVars = string.split($(this).attr("href"), "/");
//			$.post("/api/api.php", { get: "rating", id: singleVars[2], like: singleVars[3]});
			
			callApi.call("rating","&bookId="+singleVars[2]+"&stars="+singleVars[4],"comments.refresh");	
		})
		$("#newComment .submit").live("click", function(event){
			event.preventDefault();
			if( $("#newComment #commentText").val().length < 3) {
				$("#newComment #commentText").addClass("formError");
			} else {
				singleVars = string.split($("#newComment").attr("action"), "/");
				callApi.call("addComment","&bookId="+singleVars[2]+"&text="+encodeURI($('#newComment #commentText').val()),"comments.refresh");
				$("#newComment").fadeOut();
			}
		})
		$(".fav a").click(function(){
			var singleVars = $(this).attr("href").split("/");
			$.post("/api/api.php", { get: "favorite",favId: singleVars[4], type: singleVars[5]});	
			$(this).parent().find(".addFav").toggleClass("hide");
			$(this).parent().find(".delFav").toggleClass("hide");
			return false;
		})
		$(".addFavAuthor").click(function(){
			var favLink = $(this);
			var singleVars = $(this).attr("href").split("/");
			$.post("/api/api.php", { get: "favorite",favId: singleVars[4], type: singleVars[5]},
					function(data){
				if(data == 1) {
					favLink.addClass("favorite");
				} 
				if(data == 0) {
					favLink.removeClass("favorite");
				}
			});
			return false;
		})
		$("#newIm").swNewIm();
		$("#profileNewIm").swNewIm();
		$("#profile .action .mes").click(function(){
			$("#profileNewIm").slideToggle("slow");
			return false;
		})
		$("#conversation").conInterval();
		$("#loginButton").click(function(){
			$(this).toggleClass("loginButtonInactive loginButtonActive");
			$("#loginForm").toggle();
			return false;
		})
		$.fn.showTooltip = function(id) {
			var tooltip = $("#"+id);
			var tipOff = $(this).offset();
			var top = tipOff.top - tooltip.outerHeight(true) - 5;
			var left = (tipOff.left - (tooltip.outerWidth(true) / 2) + ($(this).outerWidth(true) / 2));
			tooltip.css({left: left, top: top});
			tooltip.fadeIn();
		}
		$.fn.hideTooltip = function(id) {
			var tooltip = $("#"+id);
			tooltip.fadeOut();
		}
		$.fn.getToolClass = function() {
			var eachClass = $(this).attr("class").split(" ");
			var singleVars = eachClass[1].split("_");
			return(singleVars[1]);
		}
		$(".user").live("mouseover mouseout", function (event) {
			if ( event.type == "mouseover" ) {
				  var currentHover = $(this);
				  var tipId = $(this).getToolClass();
				  	uTime = setTimeout(function() {
						if($("#"+tipId).length == 0) {
							$.post("/api/api.php", { get: "userTooltip", username: tipId},
									function(data){
								$("body").append("<div id='"+tipId+"' class='tooltip'>"+data+"</div>");
								currentHover.showTooltip(tipId);
							});
						} else {
							currentHover.showTooltip(tipId);
						}
					},550)	
			} else {
				  clearTimeout(uTime);
				  var currentHover = $(this);
				  hideTimeout = setTimeout(function() {
					  currentHover.hideTooltip(currentHover.getToolClass());
				  }, 500);
			}
		  }
		);
		$(".book").live("mouseover mouseout",function(event) {
			if ( event.type == "mouseover" ) {
				 var tipId = $(this).getToolClass();
				 var currentHover = $(this);
				  	uTime = setTimeout(function() {
						if($("#"+tipId).length == 0) {
							$.post("/api/api.php", { get: "bookTooltip", bookId: tipId},
									function(data){
								$("body").append("<div id='"+tipId+"' class='tooltip'>"+data+"</div>");
								currentHover.showTooltip(tipId);
							});
						} else {
							currentHover.showTooltip(tipId);
						}
					},'1000')
			} else {
			  clearTimeout(uTime);
			  var currentHover = $(this);
			  hideTimeout = setTimeout(function() {
				  currentHover.hideTooltip(currentHover.getToolClass());
			  }, 500);
			}
		});
		$('.tooltip').live('mouseover mouseout', function(event) {
			var tooltip = $(this);
			  if (event.type == 'mouseover') {
				  clearTimeout(hideTimeout);
			  } else {
				  hideTimeout = setTimeout(function() {
					 tooltip.fadeOut();
				  }, 500);
			  }
		});
		$.fn.randomNumber = function(from, to){
		       return Math.floor(Math.random() * (to - from + 1) + from);
		}
		$(".toggleRating").click(function(event){
			event.preventDefault();
			$("#addRating").fadeToggle();
		})
		$(".addBookmark").click(function(){
			$("#read .text span").toggleClass("setBookmark");
			return false;
		})
		$(".setBookmark").live("click", function(){
			$.post("/api/api.php", { get: "setBookmark", bookId: $(".addBookmark").attr("href"), siteNum: $(this).attr("id")},
					function(data){
				if(data = 1) {
					$(".addBookmark").addClass("bookmarked");
				}
				$("#read .text span").removeClass("setBookmark");	
			});
			return false;
		})
		$(".showSize").click(function(){
			$("#editPicture").find("img").toggleClass("maxImg");
			$("#editPicture .orig").toggle();
			$("#editPicture .size").toggle();
			$(this).width($("#editPicture").find("img").width());
			return false;
		})
		$(".delFav").click(function(){
			var attr = $(this).parent().attr("href").split("/");
			if(attr[1] == "profile") {
				var type = 2;
			}
			if(attr[1] == "read") {
				var type = 1;
			}
			$("#showTop").html("Favorit wirklich entfernen? <a href='/myAmobo/favorites/delete/"+attr[2]+"/"+type+"'>Ja</a> / <a href='' class='closeTop'>Nein</a>");
			$("#showTop").swShowTop();
			return false;
		})
		$(".delBookmark").click(function(){
			var attr = $(this).parent().attr("href").split("/");
			$("#showTop").html("Lesezeichen wirklich entfernen? <a href='/myAmobo/bookmarks/delete/"+attr[2]+"'>Ja</a> / <a href='' class='closeTop'>Nein</a>");
			$("#showTop").swShowTop();
			return false;
		})
		$(".share").click(function(event){
			event.preventDefault();
			share = window.open($(this).attr("href"), "Share", "width=750,height=650,resizable=yes,scrollbars=yes");
			share.focus();
		})
		$(".readerButton").click(function(event) {
			event.preventDefault();
			reader.init();
		})

		$("#addPage").click(function(){
			$('#text').insertAtCaret('[SEITE]');
		});
		$("#addChapter").click(function(){
			$('#text').insertRoundCaret('KAPITEL')
		});
		$("#write .submit").click(function(event){
			if($("#indicators > .iBad").size() > 0 && $('[name="status"] :selected').val() == 1) {
				event.preventDefault();
				$(".statusAgbWarning").fadeIn();
				$(this).unbind();
			}
			$(this).unbind();
		})
		$(".statusAgbWarning").click(function(){
			$(this).fadeOut();
		})
		$(".singleFaq h2").click(function(){
			$(this).parent().find(".answer").fadeToggle();
		})
		$("#help .singleFaq .answer").each(function(){
			$(this).toggle();
		})
		$(".emailShare").click(function() {
			var pos = $(this).position();
			$("#shareForm").css({top: pos.top+$(".emailShare").outerHeight()+5, left: pos.left});
			$("#shareForm").fadeToggle();
			$(".emailShare").toggleClass("emailShareActive");
			return false;
		})
		$("#shareForm .submit").click(function(){
			var singleVars = $(".emailShare").attr("href").split("/");
			$.post("/api/api.php", { get: "recommend", email: $("#shareForm .email").val(), addText: $("#shareForm .addText").val(), bookId: singleVars[2]}, 
					function(data){
				if(data == 1) {
					$("#shareForm").html("E-Mail wurde versendet");
					$(".emailShare").delay(1500).toggleClass("emailShareActive");
					$("#shareForm").delay(1500).fadeOut();
				}
			});
			return false;
		})
		$("#landing .subContainer").each(function(){
			$(this).css("opacity","0.5");
		})
		$("#landing .subContainer").hover(
		function () {
			$(this).animate({opacity:'1'}, 500);
		}, 
		function () {
			$(this).animate({opacity:'0.5'}, 500);
		});
		$("#vanity #suggestions li").click(function(){
			$("#vanity #vanityForm .vanity").val($(this).html());
		})
		$("#write #text").focus();
		$(".loggedInError").click(function() {
			if($(".logout").length == 0) {
				showTop.set("<div class='loggedInError'><p>Für diese Funktion musst du angemeldet sein.</p><div class='noAccount'>Noch keinen Account?</div><a class='registerLink' href='/register'></a></div>");
				showTop.show();	
			}
		})
		$("#searchUserResults .searchMore").click(function(event) {
			event.preventDefault();
			callApi.call("searchUser","&search="+$(".searchTag").html()+"&limit=8&offset="+$("#searchUserResults .singleUser").length,"api.search","{\"target\":\"#searchUserResults\",\"type\":\"user\"}");
		})
		$("#searchBookResults .searchMore").click(function(event) {
			event.preventDefault();
			callApi.call("searchBooks","&search="+$(".searchTag").html()+"&limit=6&offset="+$("#searchBookResults .singleBook").length,"api.search","{\"target\":\"#searchBookResults\",\"type\":\"book\"}");
		})
		$("#searchForm .searchField").bind("keydown keyup click", function() {
			if($(this).val().length > 2) {
				liveSearch.init($(this));	
			}
		})
		$("#searchForm .searchField").focusout(function(){
			liveSearch.clear();
		})
		$("#liveSearch").live("mouseover mouseout", function(event){
			if(event.type == "mouseover"){
				$("#searchForm .searchField").unbind("focusout");
			} else {
				$("#searchForm .searchField").bind("focusout", function(){
					liveSearch.clear();
				})
			}
		})
		$(".selectCatJs .std").click(function() {
			categories.setTarget($(this).parent().attr("id"));
			categories.show();
		})
		$(".closeSelectList").click(function(){
			categories.hide();
		})
		$("#selectList a").click(function(event){
			event.preventDefault();
			categories.set($(this).attr("class"), true);
		})
		$(".deleteCat").click(function(){
			categories.unset($(this).parent().attr("id"));
		})
		$("#write #text").bind("focusout focus", function() {
			indiWrite.text();
		})
		$("#write input[name='title']").bind("focusout focus", function() {
			indiWrite.title();
		})
		$("#write .coverText").bind("focusout", function() {
			indiWrite.coverText();
		})
		$("#write input[name='cover']").bind("focus", function() {
			indiWrite.cover();
		})
		$("#write select[name='mainCat']").bind("change", function() {
			indiWrite.cat();
		})
		$("#write input[name='tags']").bind("focusout", function() {
			indiWrite.tags();
		})
		$("#write input[name='accAgb']").bind("change", function() {
			indiWrite.agb();
		})
		$("#write #indicators .indicator").hover(function(){
			indiTip.init($(this).attr("id"));
		},function(){
			indiTip.hide($(this).attr("id"));
		})
		$("#write").each(function(){
			indiWrite.checkAll();
			categories.checkAll();
		})
})



