$(document).ready(function(){

	Cufon.replace('div.quote blockquote, .base_format h1, .base_format h2, h1.page_title', { fontFamily: 'georgia-mod' });
	Cufon.replace('#header h1, #nav li, #sidebar .nav_ask, #notes h3', { fontFamily: 'georgia-mod' });
	Cufon.replace('#disqus_thread h3', { fontFamily: 'georgia-mod', fontSize: '16px' });
	var iv = setInterval(function() {
		if ($("#disqus_thread h3").length) {
			Cufon.refresh("#disqus_thread h3");
			clearInterval(iv);
		}
	}, 100);
	
	var path = window.location.pathname;
	if(path == '/ask/' || path == '/ask' || path == '/submit/' || path == '/submit'){
		$('#disqus').hide();
		$('#fbkommentare').hide();
	} else if(path == '/private/187108468/tumblr_kpxckmQnzw1qa0yz7' || path == '/private/538960216/tumblr_l18tvtf3EF1qa0yz7'){
		$('#meta').hide();
		$('#fbkommentare').hide();
	}
	
	var $contentDiv = $('#content');
	var $loader = $('#loader');
	var $sidebar = $('#sidebar');
	var $header = $('#header');
	var isPage = false;
	
	function hideLoader(){
		$loader.animate({ opacity: 0 }, 300, function(){
			$(this).remove();
		});
	}

	$('#notes ol.notes').hide();

	if($contentDiv.length > 0){
		hideLoader();
	}

	function formatColor(color){
		var formattedColor = color.split('#')[1];
		if(formattedColor.length == 3){
			var customColorVals = formattedColor.split('');
			formattedColor = customColorVals[0]+customColorVals[0]+customColorVals[1]+customColorVals[1]+customColorVals[2]+customColorVals[2];
		}
		return formattedColor;
	}
	
	customColor = formatColor(customColor);
	vimeoColor = formatColor(vimeoColor);

	if($('h1.no_results').length > 0){
		$('h1.has_results').hide();
	}
	if($('h1.has_results').length > 0){
		var parts = $('h1.has_results').html().split(' ');
		if( parts[0] == '1' ){
			$('h1.has_results .plural').hide();
		}
	}
	
	var searchInHeader = true;
	var $posts = $('div.post');
	if($posts.length == 1){
		var $onlyPost = $posts.eq(0);
		if($onlyPost.hasClass('text')){
			if($onlyPost.hasClass('narrow') || $onlyPost.hasClass('full')){
				// do not wrap
			} else 	if($contentDiv.length == 0){
				isPage = true;
				$posts.eq(0).wrap('<div id="content"></div>');
			}
		}
	}
	var imageHeader = false;
	if($('#header.with_image').length > 0){
		imageHeader = true;
	}

	function replaceYouTube(video){
		// Youtube replacement based on script by Matthew Buchanan - http://mattbu.ch/261951286
		var parent = $(video).parent();
		parent.css("visibility","hidden");
		var youtubeCode = parent.html();
		var params = "";
		if (youtubeCode.toLowerCase().indexOf("<param") == -1) {
			$("param", this).each(function () {
				params += $(this).get(0).outerHTML;
			});
		}
		var oldOpts = /rel=0/g;
		var newOpts = "rel=0&amp;color1=0xFFFFFF&amp;color2=0xFFFFFF";
		youtubeCode = youtubeCode.replace(oldOpts, newOpts);
		if (params != "") {
			params = params.replace(oldOpts, newOpts);
			youtubeCode = youtubeCode.replace(/<embed/i, params + "<embed");
		}
		// Widescreen
		if( $(video).is('object') ){
			var youtubeIDParam = $(video).find('embed').attr('src');
		} else {
			var youtubeIDParam = $(video).attr('src');
		}
		var youtubeIDPattern = /\/v\/([0-9A-Za-z-_]*)/;
		var youtubeID = youtubeIDParam.match(youtubeIDPattern);
		var youtubeWidth = $(video).attr('width');
		var youtubeHeight = Math.floor(youtubeWidth * 0.75 + 25) -2;
		var youtubeHeightWide = Math.floor(youtubeWidth * 0.5625 + 25) -2;

		$.getJSON("http://gdata.youtube.com/feeds/api/videos/" + youtubeID[1] + "?v=2&alt=json-in-script&callback=?", function (data) {
			oldOpts = /height="?([0-9]*)"?/g;
			if (data.entry.media$group.yt$aspectRatio != null) {
				newOpts = 'height="' + youtubeHeightWide + '"';
			} else {
				newOpts = 'height="' + youtubeHeight + '"';
			}
			youtubeCode = youtubeCode.replace(oldOpts, newOpts);
			if (params != "") {
				params = params.replace(oldOpts, newOpts);
				youtubeCode = youtubeCode.replace(/<embed/i, params + "<embed");
			}
			parent.html(youtubeCode).css("visibility","visible");
			parent.show();
		});
	}

	function replaceVimeo(video){
		var parent = $(video).parent();
		if(!($.browser.msie)){
			// Vimeo replacement by Matthew Buchanan - http://mattbu.ch/141302328
			var parent = $(video).parent();
			var vimeoCode = parent.html();
			var params = "";
			if (vimeoCode.toLowerCase().indexOf("<param") == -1) {
				$("param", this).each(function() {
					params += $(this).get(0).outerHTML;
				});
				params += '<param name="wmode" value="transparent" />'
			}
			var oldOpts = /show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=00ADEF/g;
			var newOpts = "show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color="+vimeoColor;
			vimeoCode = vimeoCode.replace(oldOpts, newOpts);
			if (params != "") {
				params = params.replace(oldOpts, newOpts);
				vimeoCode = vimeoCode.replace(/<embed/i, params + "<embed");
			}
			parent.html(vimeoCode);
			parent.show();			
		} else {
			parent.show();
		}
	}
	
	$posts.each(function(){
		if( $(this).hasClass('video') ){
			var $object = $(this).find('object');
			if($object.length > 0){
				if($object.attr('data') != null){
					var dataContents = $object.attr('data');
				} else {
					dataContents = '';
				}
				if (dataContents.indexOf('http://vimeo.com') > -1){
					replaceVimeo($object);
				} else if ($object.find("embed[src^='http://www.youtube.com']").length > 0) {
					replaceYouTube($object);
				} else {
					$object.closest('.video_embed').show();
				}
			} else {
				var $embed = $(this).find('embed');
				if($embed.length > 0){
					var src = $embed.attr('src');
					if(src.indexOf('http://www.youtube.com') > -1){
						replaceYouTube($embed);
					} else {
						$embed.closest('.video_embed').show();
					}
				}
			}
		}
		if( $(this).hasClass('quote') ){
			var $quote = $(this).find('blockquote.quote_text');
			$quote.append('<div class="quotemark"></div>');
			var $cite = $(this).find('div.cite');
			if( $cite.html() != '' ){
				$quote.append('<div class="ref"></div>');
				if($cite.find('p,blockquote,li').length == 0){
					$cite.wrapInner('<p></p>');
				}
			} else {
				$cite.addClass('no_content');
			}
		}
		if( $(this).hasClass('photo') ){
			if( $(this).find('.caption').length > 0 ){
				$(this).find('.photo_narrow, .photo_full').append('<div class="ref"></div>');
			}
		}
		if( $(this).hasClass('chat') ){
			$(this).find('ul.chat li:last').addClass('last');
		}
		if( $(this).hasClass('audio') ){
			var $header = $(this).find('.panel_head');
			var $footer = $(this).find('.panel_foot');
			var $notes = $('#notes');
			if( $(this).find('.audio_info').length > 0 ){
				var $audioInfo = $(this).find('.audio_info');
				$header.remove().prependTo($audioInfo);
				if($notes.length > 0){
					$notes.remove().appendTo($audioInfo);
				}
				$footer.remove().appendTo($audioInfo);
				$(this).find('.album').append('<div class="ref"></div>');
			} else {
				$header.hide();
				$footer.hide();
			}
		}
		if( $(this).hasClass('answer') ){
			$(this).find('div.ask_question, div.ask_answer').append('<div class="qa"></div>');
		}
		$(this).find('.base_format > *:last').addClass('last');
	});

	var $searchfield = $('#search_field');
	var searchDefault = 'Suche';
	
	$searchfield.val(searchDefault).addClass('empty');
	$searchfield.focus(function(){
		if($searchfield.val() == searchDefault) {
			$searchfield.val("").removeClass('empty');
		}
		$searchfield.blur(function() {
			if($searchfield.val() == "") {
				$searchfield.val(searchDefault).addClass('empty');
			}
		});
	});
	
	function setSidebar(){
		if($(window).height() > ($sidebar.outerHeight() + $header.outerHeight())){
			$sidebar.css({ position: 'fixed' });
		} else {
			$sidebar.css({ position: 'relative' });
		}
	}
	
	$sidebar.prepend('<div class="sidebar_head"></div>');
	setSidebar();
	
	$('#page').css('min-height', $sidebar.height()+'px');
	
	if( $('#meta .author_avatar').length == 0){
		$('#meta li.authored').addClass('has_icon icon_posted');
	} else {
		$('#meta .author_avatar').append('<div class="avatar_frame"></div>');
	}
	$('.has_icon').prepend('<div class="icon"></div>');
	
	var tumblrname = 'sneakup';
	$('#notes ol.notes li.tumblelog_'+tumblrname).addClass('by_author');
	$('#toggle_notes a').toggle(
		function(e){
			$(this).html('hide');
			$(this).closest('p').addClass('icon_hidenotes');
			$('#notes ol.notes').stop().slideDown();
			e.preventDefault();
		},
		function(e){
			$(this).html('show');
			$(this).closest('p').removeClass('icon_hidenotes');
			$('#notes ol.notes').stop().slideUp();
			e.preventDefault();
	});
	var hash = unescape(self.document.location.hash);
	if(hash.substring(1) == 'notes'){
		$('#toggle_notes a').trigger('click');
	}
	
	function setup(){
		var contentReplaced = false;
		
		function doMasonry(){
			if(contentReplaced && !isPage){
				$('#cols').masonry({
					singleMode: true,
					animate: true,
					itemSelector: '.post'
				}, function(){
					hideLoader();
				});
				clearTimeout(masonryTimeout);
			} else {
				if(isPage){
					hideLoader();
				}
			}
		}
		
		if($contentDiv.length == 0){
			// We are on an index page
			if($('#cols').children().length > 0){
				var $videos = $('div.video');
				if($videos.length > 0){
					$('div.video').each(function(){	
						var vids = $(this).find('object');
						$(this).find('div.video_embed').height(vids.attr('height'));
						contentReplaced = true;
					});
				} else {
					contentReplaced = true;
				}
				masonryTimeout = setTimeout(function(){
					doMasonry();
				}, 500);
			} else {
				hideLoader();
			}
		} else {
			hideLoader();
		}
	}
	
	function replacePlayers(){
		$('div.player').each(function(){
			var player = $(this).html();
			player = player.replace(/\"best\"/g, '"best" wmode="transparent"');
			// player = player.replace(/FFFFFF/g, customColor);
			$(this).html(player);
			$(this).show();
		});
	}
	
	function replacePhotosets(){
		$('div.photoset_narrow').each(function(){
			var photoset = $(this).html();
			photoset = photoset.replace(/\"high\"/g, '"high" wmode="transparent"');
			$(this).html(photoset).show();
		});
	}

	function setSearch(){
		if(!imageHeader){
			var $searchForm = $('#search');
			if($(window).scrollTop() > $('#header').outerHeight()){
				if(searchInHeader){
					$searchForm.hide().appendTo('#sidebar').fadeIn(300);
					searchInHeader = false;
				}
			} else {
				if(!searchInHeader){
					$searchForm.fadeOut(300, function(){
						$(this).appendTo('#header').fadeIn(300);
					});
					searchInHeader = true;
				}
			}
		}
	}
	
	$(window).load(function(){
		setup();
		replacePlayers();
		replacePhotosets();
	});
	
	$(window).scroll(function(){
		setSearch();
	});
	
	$(window).resize(function(){
		setSidebar();
	});

});