/*
 * jQuery Flickr - jQuery plug-in
 * Version 1.0, Released 2008.04.17
 *
 * Copyright (c) 2008 Daniel MacDonald (www.projectatomic.com)
 * Dual licensed GPL http://www.gnu.org/licenses/gpl.html 
 * and MIT http://www.opensource.org/licenses/mit-license.php
 */

(function($) {
$.fn.flickr = function(o,pid,typ,uid){
var s = {
    api_key: '307c5e26da851fb7940230a8c64c2e58',              // [string]    required, see http://www.flickr.com/services/api/misc.api_keys.html
    type: typ,                		 // [string]    allowed values: 'photoset', 'search', default: 'flickr.photos.getRecent'
    photoset_id: pid,				 // [string]    required, for type=='photoset'  
    text: '',			         	 // [string]    for type=='search' free text search
    user_id: uid,         			// [string]    for type=='search' search by user id
    group_id: null,        			 // [string]    for type=='search' search by group id
    tags: null,                 	 // [string]    for type=='search' comma separated list
    tag_mode: 'any',            	 // [string]    for type=='search' allowed values: 'any' (OR), 'all' (AND)
    sort: 'date-posted-desc',    	 // [string]    for type=='search' allowed values: 'date-posted-asc', 'date-posted-desc', 'date-taken-asc', 'date-taken-desc', 'interestingness-desc', 'interestingness-asc', 'relevance'
    thumb_size: 's',           		 // [string]    allowed values: 's' (75x75), 't' (100x?), 'm' (240x?)
    size: 'b',                 		 // [string]    allowed values: 'm' (240x?), 'b' (1024x?), 'o' (original), default: (500x?)
    per_page: 50,              		 // [integer]   allowed values: max of 500
    page: 1,   		           		 // [integer]   see paging notes
    attr: '',                  		 // [string]    optional, attributes applied to thumbnail <a> tag
    api_url: null,             		 // [string]    optional, custom url that returns flickr JSON or JSON-P 'photos' or 'photoset'
    params: '',                		 // [string]    optional, custom arguments, see http://www.flickr.com/services/api/flickr.photos.search.html
    api_callback: '?',         		 // [string]    optional, custom callback in flickr JSON-P response
    callback: null            		  // [function]  optional, callback function applied to entire <ul>

    // PAGING NOTES: jQuery Flickr plug-in does not provide paging functionality, but does provide hooks for a custom paging routine
    // within the <ul> created by the plug-in, there are two hidden <input> tags, 
    // input:eq(0): current page, input:eq(1): total number of pages, input:eq(2): images per page, input:eq(3): total number of images
    
    // SEARCH NOTES: when setting type to 'search' at least one search parameter  must also be passed text, user_id, group_id, or tags
    
    // SIZE NOTES: photos must allow viewing original size for size 'o' to function, if not, default size is shown
  };
  if(o) $.extend(s, o);
  return this.each(function(){
    // create unordered list to contain flickr images
	var container = $('<div>').appendTo(this);
    container.addClass('flickrContainer');
    //Pfeile
    l = $('<a />').attr('href','#').attr('id','go_next');
    i = $('<a />').attr('href','#').attr('id','go_prev');
    imgn = $('<img />').attr('src', DBName + '/galleryview/next.gif')
    imgp = $('<img />').attr('src', DBName + '/galleryview/prev.gif')
    l.append(imgn);i.append(imgp);
    $('#flickrBildgross').append(l).append(i);
    initDart();
    
    
    var list = $('<ul>').appendTo(container);
    var url = $.flickr.format(s);
		$.getJSON(url, function(r){
      if (r.stat != "ok"){
        for (i in r){
	        $('<li>').text(i+': '+ r[i]).appendTo(list);
        };
      } else {
        if (s.type == 'photoset') r.photos = r.photoset;
        // add hooks to access paging data
        for (var i=0; i<r.photos.photo.length; i++){
		  	  
		  var photo = r.photos.photo[i];
          // format thumbnail url
          var t = 'http://farm'+photo['farm']+'.static.flickr.com/'+photo['server']+'/'+photo['id']+'_'+photo['secret']+'_'+s.thumb_size+'.jpg';
          //format image url
          var h = 'http://farm'+photo['farm']+'.static.flickr.com/'+photo['server']+'/'+photo['id']+'_';
        switch (s.size){
            case 'm':
              h += photo['secret'] + '_m.jpg';
              break;
            case 'b':
              h += photo['secret'] + '_b.jpg';
              break;
            case 'o':
              if (photo['originalsecret'] && photo['originalformat']) {
                h += photo['originalsecret'] + '_o.' + photo['originalformat'];
              } else {
                h += photo['secret'] + '_b.jpg';
              };
              break;
            default:
              h += photo['secret'] + '.jpg';
          
		  };
		  //Bild eins laden
		  if(i==0) {
				showFlickrPic(h,'');
			}
		  
		  var mylink = "<li><a rel=\"" + h + "\" href=\"#pic\" "+s.attr+" title=\""+photo['title']+"\"><img src=\""+t+"\" alt=\""+photo['title']+"\" /></a></li>";
          list.append(mylink);
        };
        initLinks();
        if (s.callback) s.callback(list);
      };
		});
  });
};

// static function to format the flickr API url according to the plug-in settings 
$.flickr = {
    format: function(s){
        if (s.url) return s.url;
        var url = 'http://api.flickr.com/services/rest/?format=json&jsoncallback='+s.api_callback+'&api_key='+s.api_key;
        switch (s.type){
            case 'photoset':
                url += '&method=flickr.photosets.getPhotos&photoset_id=' + s.photoset_id;
                break;
            case 'search':
                url += '&method=flickr.photos.search&sort=' + s.sort;
                if (s.user_id) url += '&user_id=' + s.user_id;
                if (s.group_id) url += '&group_id=' + s.group_id;
                if (s.tags) url += '&tags=' + s.tags;
                if (s.tag_mode) url += '&tag_mode=' + s.tag_mode;
                if (s.text) url += '&text=' + s.text;
                break;
            default:
                url += '&method=flickr.photos.getRecent';
        };
        if (s.size == 'o') url += '&extras=original_format';
        url += '&per_page=' + s.per_page + '&page=' + s.page + s.params;
        return url;
    }
};
})(jQuery);


function showFlickrPic(pic,link){
		
		if(link != ''){
			var dd =(link.html());
			var dd2 = $('.flickrContainer ul li:first-child a').html();
			var dd3 = $('.flickrContainer ul li:last-child a').html();
			if(dd == dd2){
				$('#go_prev').fadeOut(1);
			}
			else {$('#go_prev').fadeIn();}
			
			if(dd == dd3){
				$('#go_next').fadeOut(1);
			}
			else {$('#go_next').fadeIn();}
		$('#flickrPage ul li a').removeClass('aktiv')
		link.addClass('aktiv');
		var a = link.position();
		
		if(a.left > 348){
			
			var x = parseInt(298 - a.left) + "px";
			//console.log(x)
			$('.full #flickrPage .flickrContainer').stop().animate({'left':x})
		}
		else {$('.full #flickrPage .flickrContainer').stop().animate({'left':0})}
		}
		var test = $("#pic").attr("src");
		if(test != pic)
		{
			$("#Flickrloader").css("display","block");
			var zz = $("#pic").innerHeight() + 20;
			$("#flickrBildgross").css("height", zz);
			$("#pic").fadeOut(300, function(){
				$("#pic").attr({
					"src": pic
					}).unbind('load').load(function(){
						
						$("#Flickrloader").css("display","none");
						//Falls HochkantBild
						if($("#pic").innerHeight() > $("#pic").innerWidth()){
							$("#pic").css({"width": "auto","height": "500px"});
							
							
							//Mittiges Ausrichten
							var ll = Math.floor($('#flickrBildgross ').innerWidth()/2) - Math.floor($("#pic").innerWidth()/2) +"px"
							$("#pic").css({
								"margin":" 10px auto",
								"margin-left": ll
							});
							var yy = $("#pic").innerHeight() + 20;
							
						}
						else {
							$("#pic").css({
							"width": "696px",
							"height":"auto",
							"left": "0",
							"margin": "0"
							});
							var yy = $("#pic").innerHeight();
						}
						$("#pic").fadeIn(300);
						$("#flickrBildgross").animate({"height": yy});
				});
				
				
			});
			
				
			}
			return false;
}

function initLinks(){
	$('#flickrPage .flickrContainer a').unbind('click').click(function(){
		showFlickrPic($(this).attr('rel'),$(this))
		
	})
}

function initDart(){
	$('#go_next').unbind('click').click(function(){
		$('#go_prev').fadeIn();
		var oldImgID = $('#pic').attr('src');
		//var link_last = $('a[rel="' + oldImgID + '"]').parent().next().next().find('a').length;
			var link = $('a[rel="' + oldImgID + '"]').parent().next().find('a');
			var newImgId =link.attr('rel')
			showFlickrPic(newImgId,link)
			//if(link_last == 0){$('#go_next').fadeOut();}
		return false;
	})
	
	$('#go_prev').unbind('click').click(function(){
		$('#go_next').fadeIn();
		var oldImgID = $('#pic').attr('src');
		//var link_first = $('a[rel="' + oldImgID + '"]').parent().prev().prev().find('a').length;
			var link = $('a[rel="' + oldImgID + '"]').parent().prev().find('a');
			var newImgId =link.attr('rel')
			showFlickrPic(newImgId,link)
			//if(link_first == 0){$('#go_prev').fadeOut();}
		return false;
	})
	
}

















/*BILDERWIDGET*/
(function($) {
	$.fn.flickr1 = function(o1,pid1,typ1){
	var s1 = {
	    api_key: '307c5e26da851fb7940230a8c64c2e58',              // [string]    required, see http://www.flickr.com/services/api/misc.api_keys.html
	    type: typ1,                		 // [string]    allowed values: 'photoset', 'search', default: 'flickr.photos.getRecent'
	    photoset_id: pid1,				 // [string]    required, for type=='photoset'  
	    text: '',			         // [string]    for type=='search' free text search
	    user_id: '52473987@N06',         // [string]    for type=='search' search by user id
	    group_id: null,        			 // [string]    for type=='search' search by group id
	    tags: null,                 	 // [string]    for type=='search' comma separated list
	    tag_mode: 'any',            	 // [string]    for type=='search' allowed values: 'any' (OR), 'all' (AND)
	    sort: 'date-posted-desc',    	 // [string]    for type=='search' allowed values: 'date-posted-asc', 'date-posted-desc', 'date-taken-asc', 'date-taken-desc', 'interestingness-desc', 'interestingness-asc', 'relevance'
	    thumb_size: 'm',           		 // [string]    allowed values: 's' (75x75), 't' (100x?), 'm' (240x?)
	    size: 'o',                 		 // [string]    allowed values: 'm' (240x?), 'b' (1024x?), 'o' (original), default: (500x?)
	    per_page: 50,              		 // [integer]   allowed values: max of 500
	    page: 1,   		           		 // [integer]   see paging notes
	    attr: '',                  		 // [string]    optional, attributes applied to thumbnail <a> tag
	    api_url: null,             		 // [string]    optional, custom url that returns flickr JSON or JSON-P 'photos' or 'photoset'
	    params: '',                		 // [string]    optional, custom arguments, see http://www.flickr.com/services/api/flickr.photos.search.html
	    api_callback: '?',         		 // [string]    optional, custom callback in flickr JSON-P response
	    callback: callBackFlickr            		  // [function]  optional, callback function applied to entire <ul>

	    // PAGING NOTES: jQuery Flickr plug-in does not provide paging functionality, but does provide hooks for a custom paging routine
	    // within the <ul> created by the plug-in, there are two hidden <input> tags, 
	    // input:eq(0): current page, input:eq(1): total number of pages, input:eq(2): images per page, input:eq(3): total number of images
	    
	    // SEARCH NOTES: when setting type to 'search' at least one search parameter  must also be passed text, user_id, group_id, or tags
	    
	    // SIZE NOTES: photos must allow viewing original size for size 'o' to function, if not, default size is shown
	  };
	  if(o1) $.extend(s1, o1);
	  return this.each(function(){
	    // create unordered list to contain flickr images
		var container = $('<div>').appendTo(this);
	    container.attr('id','flickrWidget');
	    //Pfeile
	    
	    var url = $.flickr1.format(s1);
			$.getJSON(url, function(r){
	      if (r.stat != "ok"){
	        for (i in r){
		        $('<li>').text(i+': '+ r[i]).appendTo(list);
	        };
	      } else {
	        if (s1.type == 'photoset') r.photos = r.photoset;
	        // add hooks to access paging data
	        for (var i=0; i<r.photos.photo.length; i++){
			  	  
			  var photo = r.photos.photo[i];
	          // format thumbnail url
	          var t = 'http://farm'+photo['farm']+'.static.flickr.com/'+photo['server']+'/'+photo['id']+'_'+photo['secret']+'_'+s1.thumb_size+'.jpg';
	          //format image url
	          var h = 'http://farm'+photo['farm']+'.static.flickr.com/'+photo['server']+'/'+photo['id']+'_';
	        switch (s1.size){
	            case 'm':
	              h += photo['secret'] + '_m.jpg';
	              break;
	            case 'b':
	              h += photo['secret'] + '_b.jpg';
	              break;
	            case 'o':
	              if (photo['originalsecret'] && photo['originalformat']) {
	                h += photo['originalsecret'] + '_o.' + photo['originalformat'];
	              } else {
	                h += photo['secret'] + '_b.jpg';
	              };
	              break;
	            default:
	              h += photo['secret'] + '.jpg';
	          
			  };
			  var mylink = "<img src=\""+t+"\" alt=\""+photo['title']+"\" />";
	          container.append(mylink);
	        };
	        initLinks();
	        if (s1.callback) s1.callback(container);
	      };
			});
	  });
	};
	// static function to format the flickr API url according to the plug-in settings 
	$.flickr1 = {
	    format: function(s1){
	        if (s1.url) return s1.url;
	        var url = 'http://api.flickr.com/services/rest/?format=json&jsoncallback='+s1.api_callback+'&api_key='+s1.api_key;
	        switch (s1.type){
	            case 'photoset':
	                url += '&method=flickr.photosets.getPhotos&photoset_id=' + s1.photoset_id;
	                break;
	            case 'search':
	                url += '&method=flickr.photos.search&sort=' + s1.sort;
	                if (s1.user_id) url += '&user_id=' + s1.user_id;
	                if (s1.group_id) url += '&group_id=' + s1.group_id;
	                if (s1.tags) url += '&tags=' + s1.tags;
	                if (s1.tag_mode) url += '&tag_mode=' + s1.tag_mode;
	                if (s1.text) url += '&text=' + s1.text;
	                break;
	            default:
	                url += '&method=flickr.photos.getRecent';
	        };
	        if (s1.size == 'o') url += '&extras=original_format';
	        url += '&per_page=' + s1.per_page + '&page=' + s1.page + s1.params;
	        return url;
	    }
	};
	})(jQuery);


