﻿(function($) {

	var lupeAdded = false;

	/* Hauptfunktion */
	$.fn.picasaviews = function () {
	
		lupeAdded = false;
	
		addButtonsToBlogtitle();
		
		$('.entry img:not(.gmap img):not(.social_img img):not(.gallery-invert img):not(.dreieck img)').each(
			function(){
				$(this).css("cursor", "pointer");
			}
		)
		
		/* An alle vorhandenen Slideshows Gallerien anhängen */
		$("object").each(
			function(){
				addJsonToAddGalleryToSlideshow(this);
			}
		)
		
		$("embed").each(
			function(){
				addJsonToAddGalleryToEmbed(this);
			}
		)
		
		/* Alle Tabellen in Flash-Slideshows umwandeln  (callback)*/
		$("table").each(
			function(){
				addJSonToReplaceTableWithEmbed(this);
			}
		)
	};
	
	
	
	/*
	 * Das Album als Gallerie zusammenstellen und das übergebende Argument ersetzen
	 */
	$.fn.addGallery = function(json, embed) {
		var data = json.feed, i;
		var u = [], e = data.entry || [], t;
		var uCollection; 
		
		if (!$(embed).attr("picasaId")){
			embed.attr("picasaId", data.gphoto$id["$t"]);
		}
		
		// Kleine Bilder sammeln
		for (i=0; i<e.length; i++) {
			t = e[i].summary["$t"] || e[i].title["$t"];
			
			// Größenangaben hinzufügen
			var splitUrl = e[i]["media$group"]["media$content"][0]["url"].split('/');
			var bigSource = splitUrl[0];
			for( var j=1 ; j< splitUrl.length-1; j++){
				bigSource = bigSource + '/' + splitUrl[j];
			}
			bigSource = bigSource+'/s144/'+splitUrl[splitUrl.length-1];
			
			// Fuer einen Download muesste href dieselbe URL haben wie das Image
			/*var uImage = $('<img title="' + e[i].summary["$t"] +'"/>');
			uImage.load(
				function() {
					var neuerMargin = ($(this).parent().parent().height() - $(this).height())/2;
					$(this).css('margin-top', neuerMargin);
				}
			);	
			uImage.attr("src", bigSource);
			if (uCollection){	
				uCollection.after(uImage);
			} else {
				uCollection = uImage;
			}
			
			var uDiv = $('<div class="ucontainer">').$('<span class="ubox">').$(uImage);*/
			u.push(	'<div class="ucontainer"><span class="ubox"><img src="'+bigSource+'" title="'+ e[i].summary["$t"] +'" class="uImage" /></span></div>');
		}
		
		// Button zum Einblenden der Slideshow
		var dreieck = $('<div class="dreieck"><a href="#" objektart="'+ $(embed).attr("tagName") +'" slideshow="' 
							+ embed.picasaId + '" gallerie="picasa-album-'+embed.picasaId +'"><img src="/wp-content/plugins/activate_jquery/images/dreieck.gif"  id="dreieck-picasa-album-'+ 
							embed.picasaId + '" objektart="'+ $(embed).attr("tagName") +'"  style="cursor:pointer;">&nbsp;<b>Diaschau</b></a></div>');
		//$(dreieck).click(function(){
			$(dreieck).children("a").each(function(){
				$(this).click(function(){
					var filter = $(this).attr("objektart")+"[picasaId="+$(this).attr("slideshow")+']';
					// Gallerie ausblenden
					$($("#"+$(this).attr("gallerie"))).hide();
					// Slideshow einblenden
					$(filter).show();
					// Gallerieknopf einblenden
					$("#gallery-invert-"+ $(this).attr("slideshow")).parent().show();
					// Dreieck ausblenden
					
					// jump
					var targetOffset = $(filter).offset().top;
					$('html,body').animate({scrollTop:targetOffset},1000);
					$(this).parent().hide();
				});	
			});
			
		//});
		$(dreieck).hide();
		$(embed).after(dreieck);
		
		// Button zum Einblenden der einzelnen Bilder
		var galleryInvert = $('<a href="#" class="gallery-invert"><img src="/wp-content/plugins/activate_jquery/images/galleryinvert.gif" id="gallery-invert-'+ 
						embed.picasaId + '" gallerie="picasa-album-'+ embed.picasaId +'" objektart="'+ $(embed).attr("tagName")+'" slideshow="' + embed.picasaId + 
						'" style="cursor:pointer;" picasaId="' + embed.picasaId + '">&nbsp;<b>Bilder sichten</b></a>');
		$(galleryInvert).click(function(){
			$(this).hide();
			$(this).children("img").each(
				function(){
					var filter = $(this).attr("objektart")+"[picasaId="+$(this).attr("picasaId")+']';
					$($("#"+$(this).attr("gallerie"))).show();
					// Bilder zentrieren
					$(".uImage").each(
						function(){
							var rand = ($(this).parent().parent().height() - $(this).height())/2;
							$(this).css('margin-top', rand);
							$(this).css('margin-bottom', rand);
							rand = ($(this).parent().parent().width() - $(this).width())/2;
							$(this).css('margin-left', rand);
							$(this).css('margin-right', rand);
						}
					)
					$(filter).hide();
					$("#dreieck-picasa-album-" + $(this).attr("picasaId")).parent().parent().show();
			
					// jump
					var targetOffset = $(filter).offset().top;
					$('html,body').animate({scrollTop:targetOffset},1000);
			})	

		});
		$(embed).after(galleryInvert);
		//galleryInvert.after("Bilder sichten");
		
		// Jetzt die Gallerie anhängen
		var namedAnchor=$('<a name="+embed.picasaId+"/>');
		$(embed).before(namedAnchor);
		$(embed).after('<div class="picasa-gallery" style="display:none" id="picasa-album-'+ embed.picasaId +'">'+u.join("")+'</div>');
		/*var divGallery = uCollection.wrap('<div class="picasa-gallery" style="visibility:hidden" id="picasa-album-'+ embed.picasaId +'">');
		var uDiv = $(uImage).wrap('<span class="ubox"></span>').wrap('<div class="ucontainer"></div>');
		$(embed).after('<div class="picasa-gallery" style="visibility:hidden" id="picasa-album-'+ embed.picasaId +'">'+u.join("")+'</div>');
		$(embed).after(divGallery);*/
		addButtonsToBlogtitle();
	} 

	addButtonsToBlogtitle = function(){
		if (!lupeAdded){
			// Der Image-Link muß im Netz vorne um einen Backslash ergänzt werden, beim Localhost muß der weg.
			var lupetext = '<image src="/wp-content/plugins/activate_jquery/images/lupe.gif" title="Bilder anschauen" alt="Bilder anschauen" class="lupe" style="cursor:pointer; display: inline; vertical-align: middle;margin-right: 5px;"/>'
			var lupeTop = $(lupetext);
			var lupeBottom = $(lupetext);
			
			//Post-Überschrift
			$(".post h2").prepend(lupeTop);
			$(".pagetitle").prepend(lupeTop);
			
			//PostFooter
			$("#divlupe").wrap('<div class="alignleft"><a href="#" class="lupe"></a></div>');
			$("#divlupe").replaceWith(lupeBottom);
			$(lupeBottom).after('Bilder in groß');
			
			//$("#divlupe").replaceWith('<div class="alignleft"><a href="#" class="lupe">' + lupetext + 'Bilder in groß</a></div>');
			$("#partnermyblog").each(
				function(){
					var rand = ($(this).parent().parent().height() - $(this).height())/2;
					$(this).css('margin-top', rand);
					$(this).css('margin-bottom', rand);
				}
			)	
			
			$(".photoinfo .alignright").each(
				function(){
					var rand = ($(this).parent().height() - $(this).height())/2;
					$(this).css('margin-top', rand);
					$(this).css('margin-bottom', rand);
				}
			)	
		}
		
		// lightBox aktualisieren
		$('.entry img:not(.gmap img):not(.social_img img):not(.gallery-invert img):not(.dreieck img), .lupe').lightBox();
		$('.entry img:not(.gmap img):not(.social_img img):not(.gallery-invert img):not(.dreieck img)').each(
			function(){
				$(this).css("cursor", "pointer");
			}
		)
		lupeAdded = true;
	}		

	addJSonToReplaceTableWithEmbed = function(tabelle){
		$(tabelle).hide();
		var h = $(tabelle).find("a:first").attr("href");
		if (h){
			var re = /^http:\/\/picasaweb.google.([a-z\.]+)\/(.*)$/i;
			var m = h.match(re)
			var	ga;
			if (m) {
				// Zusammensetzen des Feeds
				ga = m[2].split('/');
				tabelle.picasaGallery = ga[0];
				tabelle.picasaAlbum = ga[1];
				tabelle.picasaDomain = m[1];
				$(tabelle).addClass("picasa-album");
				tabelle.picasaId = tabelle.picasaAlbum;
				tabelle.aufruf = "http://picasaweb.google." + tabelle.picasaDomain + "/data/feed/api/user/" + tabelle.picasaGallery;
				
				var pAlbum = tabelle.picasaAlbum.split('?');
				tabelle.aufruf = tabelle.aufruf + "/album/" + pAlbum[0];

				var splitFragezeichen = tabelle.picasaId.split('?')
				
				// Die Json-Funktion aktivieren
				addReplaceTables(splitFragezeichen[0], tabelle);							
			}					
		}
	}	
		
	/*
	 * Die Json-Funktion aktivieren
	 */
	function addReplaceTables(name, dieses){
		window['_f_' + name] = function(data) {
								$().replaceTablesWithSlideshows(data, dieses);
							};
		// Ein Script-Element dazu in der Datei ablegen
		var script = document.createElement( 'script' );
		script.type = 'text/javascript';
		script.src = dieses.aufruf + "?alt=json-in-script&callback=" + '_f_'+ name;
		script.charset = "utf-8";
		$('head',document).append( script );					
	}	
	
	/*
	 * Aus einer Slideshow das Feed extrahieren
	 */
	addJsonToAddGalleryToSlideshow = function(picasaslideshow) {
		var h = $(picasaslideshow).find("param[name='flashvars']").attr("value");
		if (h){
			var re = "http%3A%2F%2Fpicasaweb.google..([a-z\.]+)%2F(.*)";
			var m = h.match(re);
			var	ga, ga2, ga6;
			if (m) {
				ga2= m[2].split('%2F');
				ga6= ga2[6].split('%3F');
				ga=m[0].split('%3F');
				picasaslideshow.picasaId = ga6[0];
				picasaslideshow.aufruf = "http://picasaweb.google.de/data/feed/api/user/" + ga2[4] + "/" + ga2[5] + "/" + ga6[0];	
				var splitFragezeichen = picasaslideshow.picasaId.split('?')
				
				// Die Json-Funktion aktivieren
				addGalleryToEmbed(splitFragezeichen[0], picasaslideshow);	
			}
		} 
	}	
	
	/*
	 * Aus einer Slideshow das Feed extrahieren
	 */
	addJsonToAddGalleryToEmbed = function(picasaslideshow) {
		var h = $(picasaslideshow).attr("flashvars");
		if (h){
			var re = "http%3A%2F%2Fpicasaweb.google..([a-z\.]+)%2F(.*)";
			var m = h.match(re);
			var	ga, ga2, ga6;
			if (m) {
				ga2= m[2].split('%2F');
				ga6= ga2[6].split('%3F');
				ga=m[0].split('%3F');
				picasaslideshow.picasaId = ga6[0];
				picasaslideshow.aufruf = "http://picasaweb.google.de/data/feed/api/user/" + ga2[4] + "/" + ga2[5] + "/" + ga6[0];	
				var splitFragezeichen = picasaslideshow.picasaId.split('?')
				
				// Die Json-Funktion aktivieren
				addGalleryToEmbed(splitFragezeichen[0], picasaslideshow);	
			}
		} 
	}
	
	/*
	 * JSon für Embed aktivieren
	 */
	function addGalleryToEmbed(name, dieses){
		window['_f_' + name] = function(data) {
								$().addGallery(data, dieses);
							};
		// Ein Script-Element dazu in der Datei ablegen
		var script = document.createElement( 'script' );
		script.type = 'text/javascript';
		script.src = dieses.aufruf + "?alt=json-in-script&callback=" + '_f_'+ name;
		script.charset = "utf-8";
		$('head',document).append( script );							
	}
		
	/*
	 * Alle Tables durch Slideshows ersetzen
	 */
	$.fn.replaceTablesWithSlideshows = function(json,tabelle) {
		var data = json.feed;

		// Die über Json ermittelte ID des Albums wird für die Slideshow benötigt. Es ist daher kein einfaches Replace ohne JSon möglich.	
		// Slideshowgroessen: 800*533, 600*400, 400*267, 288*192, 144*96
		var slideshowFeed = 'http%3A%2F%2Fpicasaweb.google.' + tabelle.picasaDomain + 
		'%2Fdata%2Ffeed%2Fapi%2Fuser%2F' + tabelle.picasaGallery + '%2Falbumid%2F' + data.gphoto$id["$t"] + '%3Falt%3Drss%26kind%3Dphoto%26hl%3Den_US';
		var embed = $('<embed class="picasa-embed" pluginspage="http://www.macromedia.com/go/getflashplayer" src="http://picasaweb.google.de/s/c/bin/slideshow.swf" type="application/x-shockwave-flash" ' + 
		'flashvars="host=picasaweb.google.de&amp;captions=1&amp;noautoplay=1&amp;hl=en_US&amp;feat=flashalbum&amp;RGB=0x000000&amp;feed=' + slideshowFeed + 
		'" height="400" width="600">');
		embed.picasaId = data.gphoto$id["$t"];
		embed.attr("picasaId", data.gphoto$id["$t"]);
				
		// Tabelle mit Embed ersetzen
		$(tabelle).after(embed);	
		$(tabelle).remove();	
		
		// Gallerie hinzufügen
		$().addGallery(json, embed);
	};
	

	
	// picasaviews anstoßen
	$(document).ready(function() {$().picasaviews();});

})(jQuery);