function Flickr(){
    this.num_results = 10;
    this.requests = 0;
    this.flickr = {};
    this.apikey = '8cf8daeb825332d7817aa09dc81f09f6';
    this.flickr.search = 'http://api.flickr.com/services/rest/?method=flickr.photos.search';
    this.flickr.getInfo = 'http://api.flickr.com/services/rest/?method=flickr.photos.getInfo';
    this.user_id = '';
};

Flickr.prototype.init = function(){
    //attach events
    this.calcNumResults();
    this.createPlaceholders();
    var c = this;
    $('#flickr_search').keypress(function(e){
        if(e.keyCode == 13){
            $('#viewer').html('');
            c.resetAll();
            c.searchFlickr({'search':$(this).val(),'page':1,'perpage':c.num_results});
        }
    });
    $('#next').click(function(){
        $('#viewer').html('');
        var page = parseInt($(this).attr('alt')) + 1;
        c.updateControls(page);
        c.searchFlickr({'search':$('#flickr_search').val(),'page':page,'perpage':c.num_results});
    });
    $('#previous').click(function(){
        if(parseInt($(this).attr('alt')) == 1) return;
        $('#viewer').html('');
        var page = (parseInt($(this).attr('alt')) != 1) ? (parseInt($(this).attr('alt')) - 1) : 1;
        c.updateControls(page);
        c.searchFlickr({'search':$('#flickr_search').val(),'page':page,'perpage':c.num_results});
    });
    $(window).resize(function(){
         $('#viewer').html('');
         c.calcNumResults();
         c.createPlaceholders();
         c.searchFlickr({'search':$('#flickr_search').val(),'page':$('#next').attr('alt'),'perpage':c.num_results});
    });
    $('#info_button').click(function(){
        var el = $('#photo_info');

        if(el.html() == ''){
            $('.error').html('No image selected.');
            $('.error').fadeIn(500,function(){
                $(this).fadeOut(500);
                $(this).html();
            });
            return;
        }

        if(el.is(':hidden')){
            el.fadeIn(500);
            $('#info_button').html('Hide Info');
        }
        else{
            el.fadeOut(500);
            $('#info_button').html('Show Info');
        }
    });

    //initialize app with a search
    $('#flickr_search').val('mountains');
    this.searchFlickr({'search':$('#flickr_search').val(),'page':1,'perpage':c.num_results});
};

Flickr.prototype.resetPhotoInfo = function(){
    $('#info_button').html('Show Info');
     $('#photo_info').fadeOut(500);
     $('#photo_info').html('');
};

Flickr.prototype.parseSearchResults = function(data){
   
   if(data.stat != "ok") return;

    this.resetPhotoInfo()
    var photos = data.photos.photo,
        s_url,
        img_url,
        img,
        i=0,
        c=this;
        
    //determines how big the image should be
    this.calcImgSize();
    
    for(var item in photos){
         if(i==0)
            $('#current_img').attr('alt',photos[item].id);
        
         img_url = 'http://farm'+photos[item].farm+'.static.flickr.com/'+photos[item].server+'/'+photos[item].id+'_'+photos[item].secret+'_'+c.img_size+'.jpg';
         s_url = 'http://farm'+photos[item].farm+'.static.flickr.com/'+photos[item].server+'/'+photos[item].id+'_'+photos[item].secret+'_s.jpg';

         //go ahead and preload larger images
         $('#viewer').append('<img id="'+photos[item].id+'" style="display:none;" src="'+img_url+'" />');

         img = $('<img src="'+s_url+'" id="s_'+photos[item].id+'" style="display:none" />');
         $('#img-'+i).html(img);

         $('#s_'+photos[item].id).click(function(){
             var id= $(this).attr('id').replace('s_','');
             c.showLargeImg(id);
         });
         $('#s_'+photos[item].id).load(function(){
             $(this).fadeIn(500);
         });
         
         i++;
    }

        //when the first thumbnail is loaded show the larger image
   $('#'+$('#current_img').attr('alt')).load(function(){
       c.showLargeImg($(this).attr('id'));
   });
   $('#loader').hide();
};

Flickr.prototype.parseImgInfo = function(data){
     if(data.stat != "ok") return;
     var photo = data.photo;
     $('#photo_info').html('');
     $('#photo_info').append('<h1>'+photo.title._content+'</h1>');
     $('#photo_info').append('<div>'+photo.description._content+'</div>');
};

Flickr.prototype.searchFlickr = function(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;
};

Flickr.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;
       }
   });
};

Flickr.prototype.constructUrl = function(params){
   var page = (params['page']) ? '&page='+params['page'] : '&page=1',
       perpage = (params['perpage']) ? '&per_page='+params['perpage'] : '',
       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',
       url = this.flickr.search;

       if(urltype == 'getinfo')
            url = this.flickr.getInfo;
        
  return url+page+perpage+search+format+jsoncallback+sort+id+'&api_key='+this.apikey;
};

Flickr.prototype.updateControls = function(page){
    $('#next,#previous').attr('alt',page);
    $('#page_num').html(page);
    $('#preloaded').html('');
};

Flickr.prototype.calcNumResults = function(){
  var size = $(window).width();
  var count = Math.floor(size / 75);
  this.num_results = count;
};

Flickr.prototype.createPlaceholders = function(){
    $('#photo_reel').html('');
    for(var i=0; i<this.num_results;i++)
        $('#photo_reel').append('<li><div id="img-'+i+'" class="img"></div></li>');
};

Flickr.prototype.calcImgSize = function(){
  var size = $(window).width();
  var img_size = 'z';
  if(size >= 1024){
      img_size = 'z';
  }
  this.img_size = img_size;
};

Flickr.prototype.resetAll = function(){
    $('#next,#previous').attr('alt',1);
    $('#page_num').html(1);
};

Flickr.prototype.showLargeImg = function(id){
     var c = this;
     var el = $('#'+id);
     $(el).parent('#viewer').children().not(el).hide();
     $(el).fadeIn(300,function(){
         c.getImgInfo({photoid : id,urltype:'getinfo',jsoncallback : '?'});
     });
     $('#current_img').attr('alt',id);
};

