$.fn.extend({
	serializeForm: function(formId){
		return(
			this
			.find("input, textarea, select, button")
			.map(function(){
				if($(this).attr("name")){
					return $(this).attr("name")+"="+escape($(this).val());
				}
			})
			.get()
			.join("&"));
	},
	
	serialPost: function(options){
		options = options || {};
		options.url = options.url || this.attr("action") || this.find("form:first").attr("action");
		
		if(!options.url){		
			return;
		}	
			
		$.ajax({
			type: "POST",
			url: options.url,
			data: $(this).serializeForm(),
			success: function(msg){
				if(options.callback){
					options.callback(msg);
				}
				else{
					alert(msg);
				}
			}
		});
		
	},
	
	initDynThumb:function(){
		$(this).each(function(){
			if(!this.isDynThumb){
				var thumbContainer = $(this);
				var preload = true;
				$(this)
					.each(function(){
						this.mouseIn = false;
						this.rotating = false;
						this.timer = null;
						this.loadedThumbs=0;
						this.thumbs = [];
						this.activeThumb = -1;
						this.intervalTime = 600;
						this.fadeTime = 300;
						
						this.startRotation = function(){
							if(this.rotating || !this.mouseIn || this.loadedThumbs<2){
								return false;
							}
							this.rotating = true;
							$(this).find(".dynThumb").hide();	
							$(this).find("span").css("background-position", "-9999px -9999px");
							activeThumbContainer = this;
							clearTimeout(this.timer);
							this.timer = window.setInterval(function(){
								activeThumbContainer.showNext();
							}, this.intervalTime);
						};
						this.stopRotation = function(){
							this.rotating = false;
							$(this)
								.find("span")
								.css("background-position", "0 0")
								.prev()
									.hide();
							clearTimeout(this.timer);
							this.timer = null;
						};
						this.getNextLoadedThumbIndex = function(){	
							var start = this.activeThumb+1;
							for(var i = start; i <= this.thumbs.length*2; i++){
								index = (i%this.thumbs.length)
								if(this.thumbs && this.thumbs[index] && this.thumbs[index].loaded){
									return index;
								}
							}
							return false;
						}
						this.showNext = function(){
							var nextIndex = this.getNextLoadedThumbIndex();
							$(this)
								.find("img.dynThumb")
								.attr("src", $(this.thumbs[nextIndex].img).attr("src"))
								.hide()
								.fadeIn(this.fadeTime, function(){
									$(this)
										.prev()
										.attr("src", $(this).attr("src"));
									$(this).hide();
								});
							
							this.activeThumb = nextIndex;
						}
					})
					.mouseover(function(){
						this.mouseIn = true;
						if(this.thumbs.length == 0){
							//load thumbs first				
							var thumbContainer = this;
							
							$.getJSON("http://ws.kinkimag.com/json.php/PublicServices.getThumbnails/"+$(this).attr("rel")+"/?callback=?", function(data){
								if(data && data.items && data.items.thumbs){							
									$.each(data.items.thumbs, function(i,thumb){
										thumbContainer.thumbs[i] = {img:null, loaded:false}
										$("<img/>")
											.load(function(){
												thumbContainer.thumbs[i].loaded = true;
												thumbContainer.thumbs[i].img = this;
												thumbContainer.loadedThumbs++;
												//try to start the rotation
												thumbContainer.startRotation();
											})
											.attr("src", kinkiThumbUrl+thumb);
									});
									$("<img/>")
										.attr("class", "dynThumb")
										.hide()
										.appendTo(thumbContainer);
									$("<span/>")
										.text(" ")
										.css("background", "url("+$(thumbContainer).find("img:first").attr("src")+") no-repeat -9999px -9999px")
										.appendTo(thumbContainer);
								}
							});
						}
						else{						
							this.startRotation();
						}
						
					})
					.mouseout(function(){
						this.mouseIn = false;
						this.stopRotation();
					});				

				this.isDynThumb = true;
				thumbContainer.parent().parent()
						.mouseover(function(){
							thumbContainer.mouseover();							
						})
						.mouseout(function(){
							thumbContainer.mouseout();				
						});	
								
			}
		});
	},
	
	inputField: function(){
		$(this)
			.focus(function(){
				$(this).parent().parent().css("border-color", "#"+kinkiColorCode);
				if(!this.changed){
					$(this).val("");
				}
			})
			.blur(function(){
				$(this).parent().parent().css("border-color", "#bfbfbf");
				if(!this.changed){
					$(this).val($(this).attr("title"));
				}
			})
			.keyup(function(){
				this.changed = ($(this).val()? true : false);
			})
			.keyup()
			.blur()
			.each(function(){
				if($(this).val() == $(this).attr("title")){
					this.changed = false;
				}
			});
		return $(this);
	},
	
	jsonPost: function(callback){
				var postData = {};
				$(this)
					.find("input, textarea").each(function(){
						if($(this).attr("title") == $(this).val()){
							$(this).val("");
						}
						var name = $(this).attr("name");
						var value = $(this).val()
						postData[name] = value;
					});
					
				var postUrl = $(".comment-form form").attr("action");
					
				$.post(postUrl, postData, function(data){
					if(callback){
						callback(data);
					}
				}, "json");				
				
				return this;
			}

});	


$(function(){

	$.cookie = function(name, value, options) {
	    if (typeof value != 'undefined') {
	        options = options || {};
	        if (value === null) {
	            value = '';
	            options.expires = -1;
	        }
	        var expires = '';
	        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
	            var date;
	            if (typeof options.expires == 'number') {
	                date = new Date();
	                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
	            } else {
	                date = options.expires;
	            }
	            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
	        }
	        // CAUTION: Needed to parenthesize options.path and options.domain
	        // in the following expressions, otherwise they evaluate to undefined
	        // in the packed version for some reason...
	        var path = options.path ? '; path=' + (options.path) : '';
	        var domain = options.domain ? '; domain=' + (options.domain) : '';
	        var secure = options.secure ? '; secure' : '';
	        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	    } else { // only name given, get cookie
	        var cookieValue = null;
	        if (document.cookie && document.cookie != '') {
	            var cookies = document.cookie.split(';');
	            for (var i = 0; i < cookies.length; i++) {
	                var cookie = jQuery.trim(cookies[i]);
	                // Does this cookie string begin with the name we want?
	                if (cookie.substring(0, name.length + 1) == (name + '=')) {
	                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
	                    break;
	                }
	            }
	        }
	        return cookieValue;
	    }
	}
	
	$("a[href^='http:']").not("[href*='kinkimag.com']").not("[href*='kinki-dev']").attr('target','_blank');
	
	//create thickbox links
	/*
	$(".loginlink").each(function(){
		var hrefatt = $(this).attr("href");
		$(this).attr("href", hrefatt+"#?height=370&width=250&modal=true");
	});*/
	
	//scroll to samepage links
	function filterPath(string) {
		return string
			.replace(/^\//,'') 
			.replace(/(index|default).[a-zA-Z]{3,4}$/,'') 
			.replace(/\/$/,'');
	}
	$('a[href*=#]').each(function(){
		if(filterPath(location.pathname) == filterPath(this.pathname)
					&& location.hostname == this.hostname
					&& this.hash.replace(/#/,'') ) {
			var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
			var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
			if($target){
				var targetOffset = $target.offset().top;
				$(this).click(function() {
					$('html, body').animate({scrollTop: targetOffset}, 400);
					return false;
				});
			}
		}
	});

		
	//galleries
	var lightboxConf = {
				overlayBgColor: '#000',
				overlayOpacity: 0.6,
				imageLoading: '/img/ajax-loader.gif',
				imageBtnClose: '/images/colored/lightbox-close.'+kinkiColorCode+'.png',
				imageBtnPrev: '/images/colored/lightbox-prev.'+kinkiColorCode+'.png',
				imageBtnNext: '/images/colored/lightbox-next.'+kinkiColorCode+'.png',
				containerResizeSpeed: 350,
				txtImage: 'Bild',
				txtOf: 'von'
			};
	$(".gallery .thumb").each(function(){
		$(this)
			.after(
				$("<img/>")
					.attr("class", "zoombutton")
					.attr("src", "/img/zoom-button.png")
			);
		
		})
		.parent()
			.lightBox(lightboxConf);
	//manuel lightbox
	$("a[href$=lightbox]").lightBox(lightboxConf);
	
	//show Login Window
	var showLogin = function(link){
		if(!link){ return; }	
		$(link).attr("href", "/users/ajaxlogin/?height=160&width=300")
		tb_init(link);
		$(link).click();
	}
	
	//recover layer
	$("a[href*='recover']")		
		.one("click", function(e){
			e.preventDefault();
			$(this).attr("href","/recover/?height=120&width=270");
			tb_init(this);
			$(this).click();			
		});
	
	//favorites
	$("#content a.favorite")
		.one("click",function(e){
			e.preventDefault();
			if($(this).hasClass("disabled")){
				showLogin(this);			
			}
			else{
				var favLink = $(this);
				$.getJSON($(this).attr("href"), function(data){
						if(data.status == 1){
							favLink.replaceWith($("<span class='favorite' style='background-image:url(/images/colored/ico-heart."+kinkiColorCode+".png)'>zu Favoriten hinzugef&uuml;gt</span>"));
						}
						else{
							alert("Vorgang fehlgeschlagen\n"+data.message )
						};
					});		
			}
		});
	
	//tabs
	$(".tabs a")
		.each(function(){
			$(this).after($("<span>"+$(this).text()+"</span>").hide());
		})
		.click(function(e){
			e.preventDefault();
			var container = $("#"+$(this).attr("rel"));
			var data = this.postData || window.srPostData || {};
			data = $.extend(window.srPostData, data);
			container
				.load($(this).attr("href"), data, function(){
					$(container).find(".dynThumbBox").initDynThumb();
					$(".hintlink").css("background-image", "url(/images/colored/raquo."+kinkiColorCode+".png)");
				})
				.children().hide();
			
			var tabs = $(this).parent().parent();
			tabs.children(".active").removeClass("active");
			$(this).parent().addClass("active");
			tabs.each(function(){
				this.updateTabs();
				});
		})
		.parent()
			.parent()
			.each(function(){
				this.updateTabs = function(){
					$(this)
						.children()
						.each(function(){
							if($(this).hasClass("active")){
								$(this).children("span").show();
								$(this).children("a").hide();
							}
							else{
								$(this).children("span").hide();
								$(this).children("a").show();
							}
						});
				}
			})
			.each(function(){
				this.updateTabs();
				});
	
	
	//search driving tab links
	$("#srRandomTab")
		.each(function(){
			this.postData = {
					//"data[type]": "", 		//keep type
					"data[searchterm]": "",
					"data[tags]": "",
					"data[selection]": 0,
					"data[page]": 1,
					"data[order]": "random",
					"data[showSorters]": 0
				};
		});
	$("#srSearchedTab")
		.each(function(){
				this.postData = {};
				$.extend(this.postData, window.srPostData);
			});
	$("#srSelectionTab")
		.each(function(){
			this.postData = {
				//"data[type]": "", 		//keep type
				"data[searchterm]": "",
				"data[tags]": "",
				"data[selection]": 1,
				"data[page]": 1,
				"data[order]": "",
				"data[showSorters]": 1
			};
		});
	$("#srAllTab")
		.each(function(){
			this.postData = {
					//"data[type]": "", 		//keep type
					"data[searchterm]": "",
					"data[tags]": "",
					"data[selection]": "",
					"data[page]": 1,
					"data[order]": "chrono",
					"data[showSorters]": 1
				};
		});
	
	
	$("#srSearchForm")
		.submit(function(e){
			var searchForm = $(this);
			searchForm.find(".dynHidden").remove();
			$.each(window.srPostData, function(name, val){					
					var id = "";
					var value = val;
					if(name == "data[searchterm]"){
						id = " id='dynSearchterm' ";
						value = $("ContentSearchterm").val();
					}
					if(name == "data[tags]"){ 		value = ""; }
					if(name == "data[selection]"){	value = "0"; }
					if(name == "data[page]"){		value = "1"; }
					if(name == "data[order]"){		value = ""; }
					searchForm.append($("<input "+id+" class='dynHidden' type='hidden' name='"+name+"' value='"+value+"' />"))
				});
		$("#dynSearchterm").val($("#ContentSearchterm").val());	
	});
	$("#srSearchSubmit")
		.click(function(e){
			e.preventDefault();
			$("#srSearchForm").submit();
		});
	$("#ContentSearchterm")
		.keypress(function(){
			$("#dynSearchterm").val($(this).val());
		});
	$("#srNextButton")
		.each(function(){
			this.pageModifier = 1;
		});
	$("#srBackButton")
		.each(function(){
			this.pageModifier = -1;
		});
	$("#srBackButton, #srNextButton")
		.click(function(e){
			e.preventDefault();
			var container = $("#"+$(this).attr("rel"));
			var data = this.postData || window.srPostData || {};
			data["data[page]"] = (parseInt(data["data[page]"]) || 1) + this.pageModifier;
			data = $.extend(window.srPostData, data);
			container
				.load($(this).attr("href"), data, function(){
					$(container).find(".dynThumbBox").initDynThumb();
					$(".hintlink").css("background-image", "url(/images/colored/raquo."+kinkiColorCode+".png)");
				})
				.children().hide();			
		});	
	

	//ratings
	var calcXpos =  function(value){
		return (value? (value*14-70+40) : 40-70);
	}
	var placeholderizeRating = function(rating){
		rating = $(rating);
		rating.each(function(){
			if(!this.isPlaceholder){
				$(this)
					.css("background-position", calcXpos(rating.attr("title"))+"px 0px")
					.find("a")
					.hide()
					.after($("<span class='placeholder'>*</span>"));	
				this.isPlaceholder = true;
			}		
		});		
	}
	$(".star-rating")
		.each(function(){
			//read cookie
			var cookieValue = $.cookie($(this).attr("id"));
			if(cookieValue){
				this.rated = "<em>sorry, du hast schon</em>";
				//$(this).attr("title", cookieValue)
				placeholderizeRating(this);
			}
		})
		.mouseout(function(){				
			$(this)
				.css("background-position", calcXpos($(this).attr("title"))+"px 0px")
				.children(":last").text("");
				
			if(this.rated){
				$(this).children(":last").html(this.rated);
			}
		})
		.mouseout()
		.find("a")
			.mouseover(function(){
				$(this)
					.parent().parent()
					.css("background-position", calcXpos($(this).text())+"px 0px")
					.children(":last").text($(this).attr("rel"));
				
			})
			.click(function(e){
				e.preventDefault();
				var rating = $(this).parent().parent();
				$.getJSON($(this).attr("href")+"?jsonrate=1", function(data){
					if(data.success){
						//set cookie
						$.cookie($(rating).attr("id"), data.score, { expires: 7 });
					
						rating.attr("title", data.score);
								
						placeholderizeRating(rating);
						
						$(rating).each(function(){
							this.rated = "<em>"+data.success+"</em>";
							$(this).mouseout();							
						});						
					}
					else{
						alert(data.error || "Rating fehlgeschlagen");
					}
				});
			});
	
	// dynamic thumbnails		
	$(".dynThumbBox").initDynThumb();
		
	 
	//for teh lulz
	var kkeys = [], lolwut = "38,38,40,40,37,39,37,39,66,65";
	$(document).keydown(function(e) {
		kkeys.push( e.keyCode );
		if ( kkeys.toString().indexOf( lolwut ) >= 0 ){
			$(document).unbind('keydown',arguments.callee);				      
			$("#headimage, #logo, #profileinfo").fadeOut("fast");
			$("#header, #header .container")
				.css("background-position", "left bottom")
				.animate({
					height: "29px"
				}, 1000, function(){ 
					$(	"body, " +
						"#content .search-tabs li, " +
						"#content .tabs li, #footer, " +
						"#content .content-list, " +
						"#content .search-result-list .rating-play, " +
						"#content .content-list .rating-play, " +
						"#content .blog-list, " +
						"#content .blog-list .rating-play, " +
						"#content .video-teaser, " +
						"#sidebar .blog-tabs-content, " +
						"#content .star-rating li.textvalue, " +
						"#content .star-rating li.title")
					.css("color", "#fff")
					.css("background-color", "#000");
					$("#header")
						.css("background-image", "none")
						.css("border-bottom", "2px solid #fff");
					$(	"#content .content-block, " +
						".fattop")
					.css("border-color", "#fff")
					$("#fortehfun").remove(); 
				});	
		}	
	});
	
	//form fields
	$(".inputtext input, .textarea textarea").inputField();		
	
});
