$(document).ready(function() {
	
	/* Navigation: */
	nav = $('.subsite');
	$(nav).css('opacity','.5');
	$(nav).hover(function() {
		$(this).fadeTo('fast', 1);
	}, function() {
		$(this).fadeTo('slow', 0.5);
	});
	
	/* flickr: */
	$('#flickr').flickr();	
	
	/* Bilder: */
	// Links oder rechts gefloatete Bilder zusammen mit dem nächsten P-Tag in
	// einen DIV-Container wrappen:
	$('img.left,img.right').each(function() {
	    // Image bzw. umgebenden Link holen:
	    var img = $(this).parent('a');
	    if($(img).length == 0) img = $(this);
	    
        // Zugehörigen Paragraphen:
        var p = $(img).parent('p');
        $(img).remove();
        
        // Container erstellen & Paragraphen ersetzen:
        var container = $('<div class="container" />');
        $(container).append($(img).clone());
        $(container).append($(p).clone());
        $(p).replaceWith($(container));
	});
	
	/* Externe Links: */
    $("a").each(function() {
        // Extern -> Neues Fenster
        var href = $(this).attr("href");
        if(href != undefined) {
            if(href.substring(0,21) != "http://www.msites.net" && href.substring(0,11) != "javascript:")
                $(this).attr("target", "_blank");  
        }
    });
	
	/* Messages ausblenden: */
	$('.message').fadeOut(5000, function() { $(this).remove(); });
	
	/* Texteditor: */
	if($('textarea.editor').size() > 0) $('textarea.editor').markItUp(mySettings);
});


/* Flickr-Plugin -------------------------------------------------------------*/
;(function($) {
    
    $.fn.flickr = function(options) {
        var defaults = {
            api_key: '3f635fe9747246af35d730db245f3b58',
            nsid: '29666781@N00',
    		sidebarId: '#flickr-sidebar',
    		max_latest_photos: 6,
    		loadingAnimation: 'images/loading.gif'
        };        
        var fancyBoxOptions = {
            'zoomSpeedIn':500,
            'zoomSpeedOut':400,
            'overlayShow':true,
            'overlayOpacity':0.2,
            'zoomOpacity':true,
            'enableEscapeButton':true,
            'hideOnOverlayClick':true,
            'padding':0,
            'useIdForImageSrc':true  // hack by manuel alabor
        };
        
        var options = $.extend(defaults, options);
        var flickrBrowser = $(this);
        var sidebar = $(options.sidebarId);
        
        if($(flickrBrowser).size() == 1) {
            hash = window.location.hash;
            //if(!hash) {
                _listAllAlbums();
            //} else {
                //_listPhotosFromAlbum();
            //}
        }
        
        /**
         * Holt alle Alben von flickr und zeigt diese im DOM-Lement flickrBrowser
         * an.
         */
        function _listAllAlbums() {
            var browserList = $('<ol class="container no-list-style" />');
            apiUrl = "http://api.flickr.com/services/rest/?method=flickr.photosets.getList&user_id=" + options.nsid
            	   + "&api_key=" + options.api_key
            	   + "&format=json&jsoncallback=?";
    
            /* Browser vorbereiten: */
    		_clearBrowser('Alben');
    		$(flickrBrowser).append('<section id="albums-load-info"><p><img src="' + options.loadingAnimation + '" /></p></section>');
    		
    		/* Sidebar vorbereiten: */
            _createLatestPhotosSidebar();
    		
            $.getJSON(apiUrl,
            function(data) {
                $.each(data.photosets.photoset, function(i, item) {
          			squareUrl = "http://farm" + item.farm + ".static.flickr.com/" + item.server
                    		  + "/" + item.primary + "_" + item.secret + "_s.jpg";
    				
    				if((i+1)%3 == 0) {
    					lastCol = ' last';
    				} else {
    					lastCol = '';
    				}
    				
    				thumbnail = '<img src="' + squareUrl + '" width="75" height="75" style="float: left;" />';
    				title = item.title._content;
    				section = $('<li class="column photo-col span-6' + lastCol +'">'
    				            + '<a style="overflow: hidden;" class="container hover-rounded" href="http://www.flickr.com/photos/' + options.nsid + '/sets/' + item.id + '">'
    						        + thumbnail
    						        + '<div style="padding-top: 6px; margin-left: 90px; margin-right: 10px">' + title + '</div>'
    						      + '</a>'
    						   +'</li>');
    				
    				$(section).bind('click', {'photoset_title':title, 'photoset_description':item.description._content, 'photoset_id':item.id}, function(e) {
                        window.location.hash = e.data.photoset_id;
                        _listPhotosFromAlbum(
                            e.data.photoset_title,
                            e.data.photoset_description,
                            e.data.photoset_id
                        );
                        return false;
                    });
                    
    				$(browserList).append(section);
                });
    			
    			$('#albums-load-info').replaceWith(browserList);
            });
    	};
    	
    	/**
    	 * Zeigt die Fotos aus einem Album an.
    	 */
    	function _listPhotosFromAlbum(photoset_title, photoset_description, photoset_id) {
            var browserList = $('<ol class="container no-list-style" />');
            apiUrl = "http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&user_id=" + options.nsid
            	   + "&api_key=" + options.api_key
            	   + "&photoset_id=" + photoset_id
            	   + "&page=1"
            	   + "&format=json&jsoncallback=?";
            	           
            /* flickr Browser vorbereiten: */
            _clearBrowser(photoset_title);
            $(flickrBrowser).append('<section id="photo-load-info"><p><img src="' + options.loadingAnimation + '" /></p></section>');
            
    		/* Sidebar vorbereiten: */
    		createSideBar = false;
            if(!$(sidebar).hasClass('album-details')) {
                createSideBar = true;
                $(sidebar).fadeOut('fast', function() {
                    $(this).empty();
                    $(this).addClass('album-details');
                });
            }
    		
    		/* Fotos holen: */
            $.getJSON(apiUrl,
            function(data) {
    			/* Seitenleiste: */
    			// Weitere Informationen zum Album:
    			if(createSideBar) {
        			if(photoset_description != '') desc = '<p>' + photoset_description + '</p>';
        			else desc = ''; 
                    $(sidebar).append(
                       '<section>' +
                           '<h3>Mehr zum Album</h3>' + 
                           desc + 
                       '</section>'
                    );
                     
                    linkList = $('<ul>' +
                                   '<li><a href="http://www.flickr.com/photos/' + options.nsid + '/sets/' + photoset_id + '" target="_blank">Album auf flickr anzeigen</a></li>' +
                                 '</ul>');
                    albumListLink = $('<a href="#">Zur&uuml;ck zur Alben&uuml;bersicht...</a>');
                    albumListLink.click(function() { _listAllAlbums(); });
                    albumListLinkItem = $('<li/>').append(albumListLink);
                    $(linkList).append(albumListLinkItem);
                    $(sidebar).append(linkList);
                    
                    $(sidebar).append('<section><h3>Tipps</h3><div class="small"><p>Klicken Sie auf ein Foto, um es zu vergr&ouml;ssern.</p><p>Verwenden Sie anschliessend die Pfeiltasten <em>Nach-Links</em> und <em>Nach-Rechts</em> auf Ihrer Tastatur, um zwischen den Fotos aus dem Album zu wechseln.<br/>Dr&uuml;cken Sie <em>Esc</em>, um das vergrösserte Foto zu schliessen.</p></div></section>');
                    
                    // Sidebar wieder einblenden:
                    $(sidebar).fadeIn('slow');
                }
    
                
                /* Fotos auflisten: */
                $.each(data.photoset.photo, function(i, item) {
          			baseUrl = "http://farm" + item.farm + ".static.flickr.com/" + item.server
                    	    + "/" + item.id + "_" + item.secret;
                    squareUrl = baseUrl + "_s.jpg";
    				normalUrl = baseUrl + ".jpg";
    				
    				photoLink = $('<a href="http://www.flickr.com/photos/' + options.nsid + '/' + item.id + '/" rel="album" title="' + item.title + '" id="' + normalUrl + '" class="image no-focus"></a>');
    				$(photoLink).append('<img src="' + squareUrl + '" alt="' + item.title + '" width="75" height="75" />');
    				li = $('<li class="column last" />');
    				$(li).append(photoLink);
    				$(browserList).append(li);
                });
    			
                // FancyBox auf Links in der Stream-Liste ansetzen
                $('a', browserList).fancybox(fancyBoxOptions);
    			
    			$('#photo-load-info').replaceWith(browserList);
            });
    	};
    	
    	/**
    	 * Leert den flickrBrowser und erstellt in diesem bei Bedarf bereits
    	 * ein Titel-Element mit dem Inhalt newTitle.
    	 *
    	 * @param newTitle
    	 */
    	function _clearBrowser(newTitle) {
    	   $(flickrBrowser).empty();
    	   if(newTitle != '') $(flickrBrowser).append('<h3>' + newTitle + '</h3>');
    	}
    	
    	
    	
    	function _createLatestPhotosSidebar() {
            // Sidebar zu Beginn ausblenden und anschliessend leeren.                
            if($(sidebar).hasClass('album-details')) {
                $(sidebar).fadeOut('fast', function() {
                    $(this).empty();
                    $(this).removeClass('album-details');
                    
                    _createLatestPhotosSidebar();
                    $(sidebar).fadeIn('slow');
                });
                
                return;
            }
            
            latestPhotos = $('<section><h3>Neuste Fotos</h3><img src="' + options.loadingAnimation + '" id="latestphotos-load-info" /></section>');
            _getLatestPhotos(latestPhotos);
            $(sidebar).append('<section>'
                                + '<h3>Fotografieren</h3>'
                                + '<p>'
                                  + 'Fotografieren geh&ouml;rt zu meinen Hobbies.<br/>'
                                  + 'Viele Dinge halte ich mit einem gewissen, andere aber auch ohne jeglichen Qualit&auml;tsanspruch fest.'
                                + '</p>'
                                + '<p class="small">'
                                  + 'Meine Fotos finden Sie auch direkt bei <a href="http://www.flickr.com/__manu/" target="blank">flickr.</a>'
                                + '</p>'
                            + '</section>');
            $(sidebar).append(latestPhotos);
                            
    	}
    	
    	/**
    	 * Gibt ein Element mit den neusten Fotos zurück.
    	 */
    	function _getLatestPhotos(container) {
            latestPhotosList = $('<ol class="container no-list-style" />');
            latestPhotosApiUrl = "http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos" 
                   + "&user_id=" + options.nsid
            	   + "&api_key=" + options.api_key
            	   + "&per_page=" + options.max_latest_photos
            	   + "&format=json&jsoncallback=?";
            	   
            $.getJSON(latestPhotosApiUrl,
            function(data) {
                $.each(data.photos.photo, function(i, item) {
          			baseUrl   = "http://farm" + item.farm + ".static.flickr.com/" + item.server
                    	      + "/" + item.id + "_" + item.secret;
                    smallUrl  = baseUrl + "_t.jpg";
    				normalUrl = baseUrl + ".jpg";
    				
    				title = item.title._content;
    				section = $('<li class="column last">'
    				            + '<a href="http://www.flickr.com/photos/' + options.nsid + '/' + item.id + '/" rel="latest" title="' + item.title + '" id="' + normalUrl + '" class="image no-focus">'
    						      + '<img src="' + smallUrl + '" />' 
    						    + '</a>'
    						   +'</li>');
                    
    				$(latestPhotosList).append(section);
                });
                
                $('a', latestPhotosList).fancybox(fancyBoxOptions);
                $('#latestphotos-load-info').replaceWith(latestPhotosList);
            });
    	}
	
	};
    
})(jQuery);