var FLICKR_SIZES = {
		small: '_s',	// 75x75
		medium: '_m',	// 240px longest
		normal: '', 	// 500px longest
		big: '_b'		// 1024px longest
		//original: '_o' // original (if available), warning may not be jpg!!
	};

function parseParameter()
{
    var l = location.href,
        index = l.indexOf('?');
    return index > -1 ? l.substr(index + 1) : '';
}

function getUserId(userName, apiKey, callback)
{
    $.getJSON('http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&username=' + userName + '&format=json&jsoncallback=?&api_key=' + apiKey,
    function(data)
    {
        callback(data.user ? data.user.id : null);
    });
}

function getUserName(userId, apiKey, callback)
{
    $.getJSON('http://api.flickr.com/services/rest/?method=flickr.people.getInfo&user_id=' + userId + '&format=json&jsoncallback=?&api_key=' + apiKey,
    function(data)
    {
        callback(data.person ? data.person.username._content : null);
    });
}

function get(input, apiKey, callback)
{
    // see if they're passing in an ID (application default)
    getUserName(input, apiKey, function(userName)
    {
        if(userName) {
            callback(input, userName);
        } else {
            // not a userId, check the username
            getUserId(input, apiKey, function(userId)
            {
                if(userId) {
                    callback(userId, input);
                } else {
                    throw new Error('User ID/Name could not be found.');
                }
            });
        }
    });
}

function multiflickrscrollf(context, apiKey, userId, userName, suffix)
{
	$.getJSON('http://api.flickr.com/services/rest/?method=flickr.contacts.getPublicList&user_id=' + userId + '&page=1&format=json&jsoncallback=?&api_key=' + apiKey,
		function(data)
		{
		    var userIds = [],
		        userNames = []
		        contacts = data.contacts.contact;

		    userIds.push(userId);
		    userNames.push(userName || userId);
		
		    for(var j=0, k=contacts.length; j<k; j++)
		    {
		        userIds.push(contacts[j].nsid);
		        userNames.push(contacts[j].username);
		    }
		
		    flickrscrollf(context, apiKey, userIds, userNames, suffix);
		});
}

function singleflickrscrollf(context, apiKey, userId, userName, suffix)
{
	flickrscrollf(context, apiKey, [userId], [userName], suffix);
}

function flickrscrollf(context, apiKey, userIds, userNames, suffix)
{
	var b = new scrollf();
    b.init(context, {
    	SCROLL_VERTICAL: userIds.length > 1,
        BOUNDS: {
    		top: 0,
            bottom: userIds.length - 1,
            left: 0,
            right: 199 // adjusted to # of photos from contact with most photos below
        },
        callback: function(x, y)
        {
            var panel = $('.p' + x + '_' + y, context);
            if(panel.find('img').length === 0) {
                var perPage = 50,
                    page = Math.floor(x/perPage) + 1, // flickr is 1-indexed
                    baseX = (page - 1)*perPage;

                // only perform request if on an anchor index or anchor was not requested yet (ie: paging every 50, we enter on 11 => cache pending miss) 
                if(x % perPage === 0 || !b.cacheIsPending(baseX, y)) {
                    b.cacheSetPending(baseX, y, true);
                    $.getJSON('http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&user_id=' + userIds[y] + '&per_page=' + perPage + '&page=' + page + '&format=json&jsoncallback=?&api_key=' + apiKey,
                    function(data)
                    {
                        function getInternalLink(userId, userName)
                        {
                            return '<a class="internal" href="' + loc.substring(loc.lastIndexOf('/')+1, loc.indexOf('?')) + '?' + userId + '">' + (userName || userId) + '</a>';
                        } 
                        // set new right bound (if total # of photos is bigger)
                        b.setBound('right', Math.max(data.photos.pages * perPage - 1, b.getBound('right')));

                        // make it so it loads X per request (where X is the number of panels shown on the screen)
                        var photos = data.photos.photo,
                            content,
                            url,
                            pageUrl,
                            description
                            loc = location.href;

                        for(var j=0,k=photos.length; j<k; j++) {
                            url = 'http://farm' + photos[j].farm + '.static.flickr.com/' + photos[j].server + '/' + photos[j].id + '_' + photos[j].secret + (suffix || '') + '.jpg';
                            pageUrl = 'http://www.flickr.com/photos/' + userIds[y] + '/' + photos[j].id;
                            description = photos[j].title;
                            			// '<span class="title">' + photos[j].title + '</span>' +
                            content = getInternalLink(userIds[y], userNames[y]) + 
                                    '<a class="external" href="' + pageUrl + '"><span class="flick">flick</span><span class="r">r</span></a>' + 
                            		'<img src="' + url + '" title="' + description + '"/>';

                            b.setContent(baseX + j, y, content);
                        }

                        for(var j=photos.length,k=perPage; j<k; j++) {
                            content = getInternalLink(userIds[y], userNames[y]) + '<div class="notfound">No Photo Found</div>';

                            b.setContent(baseX + j, y, content);
                        }
                    });
                }
            }
        }
    });
}
