var searchTerm = '';

getPopularPhotos = function(lim, off) {
    var height = 120;
    var width = 160;
    var bgcolor = 'efefef';
    $.ajax({
        url:  'api/feed.php',
        data: 'limit='+lim+'&offset='+off+'&height='+height+'&width='+width+'&background='+bgcolor+searchTerm,
        beforeSend: function () {
            $('#status').html('<img src="images/loadingAnimation.gif" />');
        },
        success: function(data, reqStatus) {
            $('#status').html('&nbsp;');
            $('#photos').html('');
            $(data).find("photo").each(showPhoto);
            updateLinks(lim, off, $(data).find("photos").attr("results"));
        }
    });
};

showPhoto = function(idx, elm) {
    var e = $(elm);
    var p = $(document.createElement("span"));
    p.attr('class', 'photo');
    var a = $(document.createElement('a'));
    var url = 'photo.php?id='+e.attr('id')+'&origin=';
    a.attr('href', url + (searchTerm === '' ? 'popular' : ('search' + searchTerm)) + '&offset=' + (idx));
    p.append(a);
    var i = $(document.createElement('img'));
    i.attr('src',$(e.find('img')).attr('src'));
    i.attr('height',$(e.find('img')).attr('height'));
    i.attr('width',$(e.find('img')).attr('width'));
    i.attr('alt',$(e.find('img')).attr('alt'));
    a.append(i);

    $('#photos').append(p);
};

updateLinks = function (lim, off, tot) {
    $('#next_link').unbind('click');
    $('#next_link').click(function() {
        getPopularPhotos(lim, off + lim);
        return false;
    });
    $('#prev_link').unbind('click');
    $('#prev_link').click(function() {
        getPopularPhotos(lim, off - lim);
        return false;
    });
    
    if (off > 0) {
        $('#prev_link').show();
    } else {
        $('#prev_link').hide();
    }

    if (lim + off > tot) {
        $('#next_link').hide();
    } else {
        $('#next_link').show();
    }
};

