"use strict";

jQuery.fn.flickrSet=function(opts){
    
    var photosetId = opts.photoset_id,
        apiKey = opts.api_key,
        onComplete = opts.onComplete || function () {},
        obj = this;
        
    $.getJSON('http://api.flickr.com/services/rest/?jsoncallback=?',
              {format: 'json', method: 'flickr.photosets.getPhotos',photoset_id: photosetId, api_key: apiKey},
              function(response){
                var i = 0,
                    img = null,
                    imgTag = '',
                    imgUrl = '',
					prev=0;
                if(response && response.photoset && response.photoset.photo)
                {
                    for(i in response.photoset.photo)
                    {
                        if(!response.photoset.photo.hasOwnProperty(i))
                        {
                            continue;
                        }


                        
                        img = response.photoset.photo[i];


						//we can't just get the next in the photoset, so after getting the previous we set the previous's next to our current id
						if (prev)
						{
							$('#'+prev).attr('next',img.id);
						}
                        next = 0;
                        imgUrl = 'http://static.flickr.com/' + img.server + '/' + img.id + '_' + img.secret;
                        
                        imgTag = $('<div class="galleryline">' +
                                   '    <div class="image"><a prev="'+prev+'" next="'+next+'" id="'+img.id+'" href="' + imgUrl + '.jpg" title="'+ img.title +'" rel="lightbox">' +
                                   '<img src="' + imgUrl + '_s.jpg" />' +
                                   '</a></div>' +
                                   '    <div class="name clearfix">' + img.title + '</div>' +
                                   '</div>');
                        
                        $(obj).append(imgTag);

						prev = img.id;
                    }
                    
                    onComplete();
                }
                
              });
    
};