/*
    Note: This plugin depends on the thoAccordion plugin to function properly.
*/

(function( $ ){
    $.fn.loadAdServerData = function(adCallArray) {
        var base = this;
        base.$el = $(this);

        var pendingRequests = adCallArray.length;

        var populate = function (value, index) {
            $.ajax({
                url: '/documents/sitestructure/resources/jsp/proxy.jsp?' + value,
                data: index,
                error: function(data) {
                    tryToMergeRequests();
                },
                success: function(data) {
                    // Get the relevant data from the XML source
                    var title = $('file title', data).text();
                    var link = $('link', data).text();
                    var imgUrl = $('file', data).attr('url');

                    // if the data is useable, add it to the list
                    if ( (title != null) && (link != null) && (imgUrl != null)) {
                        var newItem = $("<li>");
                        newItem.append('<div class="collapsible collapsibleImage"><a href="' + link + '"><img src="' + imgUrl + '" border="0"/></a></div><div class="title"><a href="' + link + '">' + title + '</a></div>');
                        base.$el.find(".accordion_content").append(newItem);
                    }

                    tryToMergeRequests();
                },
                dataType: "xml"
            });
        }; /* end populate() */

        for ( var i = 0; i < adCallArray.length; i++ ) {
            populate(adCallArray[i], i);
        }

        /* This function checks if all the AJAX requests have been completed.  If they have, we can go ahead and initialize the widget for usage. */
        function tryToMergeRequests() {
            pendingRequests--; // if this method is being called, one of the requests has returned
            if (pendingRequests == 0) { // if there are no more pending ajax requests
                base.$el.thoAccordion();
            }
        }
    };
})( jQuery );
