(function($){

	$.fn.photostream = $.photostream = function(params){
		params = params || {};

		params.target = (this.size() > 0) ? this : $('body');
		
		var photostream = new Photostream(params);
	};
	
	var Photostream = function(config){
		this.config = {
			numResults : 20,
	    	requests : 0,
	    	apiKey : '8cf8daeb825332d7817aa09dc81f09f6',
	    	searchUrl : 'http://api.flickr.com/services/rest/?method=flickr.photos.search',
	    	getInfoUrl : 'http://api.flickr.com/services/rest/?method=flickr.photos.getInfo',
	    	userId : ''
		};
		
		this.bigImages = {};
		this.config = $.extend({}, config, this.config);
		
		this.init();
	};

	Photostream.prototype.init = function(){
	    //attach events
	    this.calcNumResults();
	    this.createPlaceholders();
		this.makeRequest();
		var c = this;
		
		if(!$.isMobile()){
		    $(window).resize(function(){
		         $('#viewer').html('');
		         c.calcNumResults();
		         c.createPlaceholders();
		         c.makeRequest({'search':$('#flickr_search').val(),'page':$('#next').attr('alt'),'perpage':c.num_results});
		    });
	    }
	};
	
	Photostream.prototype.parseSearchResults = function(data){
		
		if(data.stat != "ok") return;
		
		var photos = data.photos.photo,
			s_url,
			l_url,
			img_url,
			large_img,
			img,
			i=0,
			c=this;
		
		//determines how big the image should be
		this.calcImgSize();
		
		for(var item in photos){
		
			img_url = 'http://farm'+photos[item].farm+'.static.flickr.com/'+photos[item].server+'/'+photos[item].id+'_'+photos[item].secret+'_m.jpg';	
			s_url = 'http://farm'+photos[item].farm+'.static.flickr.com/'+photos[item].server+'/'+photos[item].id+'_'+photos[item].secret+'_s.jpg';
			l_url = 'http://www.flickr.com/photos/mattnull/'+photos[item].id+'/in/photostream';
			
			//preload larger images
			
			large_img = $('<img id="'+photos[item].id+'" style="z-index:10000;display:none;position:absolute;" src="'+img_url+'" />');
			$('#viewer').append(large_img);
			
			img = $('<a href="'+l_url+'" target="_blank"><img src="'+s_url+'" img-id="'+photos[item].id+'" id="s_'+photos[item].id+'" style="display:none" /></a>');
			
			$('#img-'+i).html(img);
		
			$('#s_'+photos[item].id).mouseenter(function(e){
				var x = e.clientX,
					y = e.clientY,
					id = $(this).attr('img-id'),
					img = $('#'+id);
	
				var pos = $(this).position();
				
				img.css({"top" : pos.bottom+"px","left" : pos.left+'px'});

				img.fadeIn(200);		
			});
			
			$('#s_'+photos[item].id).mouseleave(function(e){
				var img = $('#'+$(this).attr('img-id'));

				img.hide();		
			});
			
				
			$('#s_'+photos[item].id).load(function(){
				$(this).fadeIn(500);
			});
		
			i++;
	    }
	};
	
	Photostream.prototype.makeRequest = function(params){	
		params = params || {};
	   var c = this;  
	   //make sure we aren't running more than one request at once
	   if(this.requests > 0){
	       window.stop();
	   }
	
	   $.extend(params,{sort:'interestingness-desc',jsoncallback : '?'});
	
	  var url = this.constructUrl(params);
	   
	   $('#loader').show();
	   
	   $.ajax({
	       dataType:'json',
	       url:url,
	       success:function(data){ 
	           c.parseSearchResults(data);
	           c.requests = 0;
	       }
	   });
	
	   this.requests += 1;
	};
	
	Photostream.prototype.getImgInfo = function(params){
	   var c = this;
	   //make sure we aren't running more than one request at once
	   if(this.requests > 0){
	       window.stop();
	   }
	
	   var url = this.constructUrl(params);
	   $.ajax({
	       dataType:'json',
	       url:url,
	       success:function(data){ 
	           c.parseImgInfo(data);
	           c.requests = 0;
	       }
	   });
	};
	
	Photostream.prototype.constructUrl = function(params){
	   var page = (params['page']) ? '&page='+params['page'] : '&page=1',
	       perpage = (params['perpage']) ? '&per_page='+params['perpage'] : '&perpage=100',
	       search = (params['search']) ? '&text='+params['search'] : '',
	       format = (params['format']) ? '&format='+params['format'] : '&format=json',
	       jsoncallback = (params['jsoncallback']) ? '&jsoncallback='+params['jsoncallback'] : '',
	       sort = (params['sort']) ? '&sort='+params['sort'] : '',
	       id = (params['photoid']) ? '&photo_id='+params['photoid'] : '';
	       urltype = params['urltype'] || 'search',
	       userid = (this.config.userId) ? '&user_id='+this.config.userId : '&user_id=55575121@N03';
	       url = this.config.searchUrl;
	        
	  return url+page+perpage+search+format+jsoncallback+sort+userid+id+'&api_key='+this.config.apiKey;
	};
	
	Photostream.prototype.calcNumResults = function(){
	  var size = $(window).width();
	  var count = Math.floor(size / 75);
	  this.num_results = count;
	};
	
	Photostream.prototype.createPlaceholders = function(){
	    this.config.target.html('');
	    for(var i=0; i<this.num_results;i++)
	        this.config.target.append('<li><div id="img-'+i+'" class="img"></div></li>');
	};
	
	Photostream.prototype.calcImgSize = function(){
	  var size = $(window).width();
	  var img_size = 'z';
	  if(size >= 1024){
	      img_size = 'z';
	  }
	  this.img_size = img_size;
	};
	
	Photostream.prototype.resetAll = function(){
	    $('#next,#previous').attr('alt',1);
	    $('#page_num').html(1);
	};

})(jQuery);
