var TPprofileJSON = null;
var TPphotoJSON = null;
var TPretry = 0;
var TPretries = 10;
var TPcolor = null;

function TPinit(user_id, count, color) {
    TPcolor = color;
    TPjsonpSearch('http://api.tweetphoto.com/api/TPAPI.svc/jsonp/users/' + user_id + '?', 'TPhandleProfileData', 0);
    TPjsonpSearch('http://api.tweetphoto.com/api/TPAPI.svc/jsonp/users/' + user_id + '/favorites?ps=' + count, 'TPhandlePhotoData', 1);
    TPrender();
}
function TPjsonpSearch(url, callback, index) {
    var head = document.getElementsByTagName('head');
    var scriptElement = document.createElement('script');
    scriptElement.type = 'text/javascript';
    scriptElement.src = url + '&callback=' + callback;
    scriptElement.id = 'TPjsonp_' + index;
    head[0].appendChild(scriptElement);
}
function TPhandleProfileData(data) {
    TPprofileJSON = data;
}
function TPhandlePhotoData(data) {
    TPphotoJSON = data;
}
function TPclean(index) {
    var script = document.getElementById('TPjsonp_' + index);
    if (script) {
        for (var property in script) {
            if (property) {
                delete script[property];
            }
        }
        var parent = script.parentNode;
        for (i = 0; i < parent.children.length; i++) {
            if (parent.children[i].id == 'TPjsonp_' + index) {
                delete parent.children[i];
            }
        }
    }
}
function TPrender() {
    if (TPprofileJSON && TPphotoJSON) {
        TPdraw(TPprofileJSON, TPphotoJSON);
    } else {
        if (TPretry++ < TPretries) {
            setTimeout('TPrender()', 1000);
        }
    }
}
function TPdraw(profileData, photoData) {
    var widget = document.getElementById('TPwidget');
    var widgetHtml = '<div style="width:300px; margin:0px 20px 10px 20px; background-color:' + TPcolor + ';">';
    widgetHtml += '<ul style="position:relative;margin:0px;padding:0px;list-style-image:none !important;list-style-position:outside !important;list-style-type:none !important;overflow:hidden !important;">';
    var photos = photoData.List;
    for (i = 0; i < photos.length; i++) {
        if ((i % 2) == 0) {
            widgetHtml += TPinsertPhoto(photos[i].Photo, false);
        } else {
            widgetHtml += TPinsertPhoto(photos[i].Photo, true);
        }
    }
    widgetHtml += '</ul>';
    widgetHtml += '</div>';
    widget.innerHTML = widgetHtml;
}
function TPinsertPhoto(photo, odd) {
    var li = '<li';
    if (odd) {
        li = li + ' style="padding:0;float:left;margin:5px 15px 5px 5px;position:relative;border:2px solid #fff;">';
    } else {
        li = li + ' style="padding:0;float:left;margin:5px 15px 5px 5px;position:relative;border:2px solid #fff;">';
    }
    return li + '<a href="' + photo['BigImageUrl'] + '" rel="shadowbox"><img style="height:69px;width:69px;border:none;" align="top" alt="" src="' + photo['ThumbnailUrl'] + '"/></a></li>';
}