/***********************************************************************\
* File:     jQuery.randomAd.js                                          *
* Date:     October 28, 2009                                            *
* Author:   James Carpenter                                             *
* Purpose:  Simple Ad rotator to change the src of an image tag to a    *
*           random option from a static file                            *
*                                                                       *
* Usage:    $('#imgId').randomAd( {                                     *
*			    adDir   : '/images/ads/',       // default              *
*               xmlFile : 'ads.xml'             // default              *
*			});                                                         *
\***********************************************************************/

(function($) {
    // handle to the image
    var opts, img;

    // begin plugin
    jQuery.fn.randomAd = function(options) {
        // merge the options passed w/ the defaults and grab handle to image
        opts = jQuery.extend(jQuery.fn.randomAd.defaults, options);
        img = $(this);

        // query the XML data file and 
        $.ajax({
            type: 'GET',
            dataType: 'xml',
            url: opts.adDir + opts.xmlFile,
            success: onSuccess,
            error: onError
        });
    };

    function onSuccess(data, textStatus) {
        // parse xml and get info we need
        var xml = $(data),
            ads = xml.children().children(),
            cnt = ads.length,
            rndAd = $(ads[rndInRange(0, cnt)]);

        // swap the image and wrap with link
        $(img).attr('src', opts.adDir + rndAd.children('image').text())
                .wrap('<a target="_blank" href="' + rndAd.children('link').text() + '"></a>');
    }

    function onError(XMLHttpRequest, textStatus, errorThrown) {
        // ToDo: Do something here
    }

    function rndInRange(min, max) {
        return min + Math.floor((max - min) * Math.random());
    }

    // declare the default values for the plugin (make public to allow for override)
    jQuery.fn.randomAd.defaults = {
        adDir: '/images/ads/',
        xmlFile: 'ads.xml'
    };

})(jQuery);
