var returnedRotatorData;
var currentRotatorItem = 0;
var rfgRotatorScope;
function initRFGRotator(id) {
    if (document.getElementById("rfgRotator")) {
        jQuery.ajax({
            url: "/handlers/rotatorfeed.aspx?id=" + id,
            dataType: "json",
            success: function (data) {
                returnedRotatorData = data;
                rfgRotatorScope = jQuery("#rfgRotatorInner");
                panelSource = [];
                panelSource.push('<img class="mainImage" src="' + data[0].image + '"  />');
                panelSource.push('<div id="rfgRotatorPanel">');
                if (data.length > 1)
                    panelSource.push('<a onclick="prevRFGRotatorItem(); return false;" class="rfgPanelControls rfgControlPrev" href="#">Previous</a>');
                panelSource.push('<div id="rfgPanelInfo">');
                panelSource.push('<h2 class="mainRFGTitle">' + data[0].title + '</h2>');
                panelSource.push('<div class="mainRFGInfo">' + data[0].description + '</div>');
                panelSource.push('</div>');
                if (data.length > 1)
                    panelSource.push('<a onclick="nextRFGRotatorItem(); return false;" class="rfgPanelControls rfgControlNext" href="#">Previous</a>');
                panelSource.push('</div>');

                rfgRotatorScope.append(panelSource.join(''));
                delete panelSource;

                preloadedImages = [];
                for (i = 1; i < data.length; i++) {
                    preloadedImages[i] = new Image();
                    preloadedImages[i].src = data[i].image;
                }
            }
        });

    }
}
function prevRFGRotatorItem() {
    pageTracker._trackEvent("RFG_Rotator", "previous_click", "");
    currentRotatorItem = (currentRotatorItem == 0) ? (returnedRotatorData.length - 1) : currentRotatorItem - 1;
    loadNewData(returnedRotatorData[currentRotatorItem]);
}
function nextRFGRotatorItem() {
    pageTracker._trackEvent("RFG_Rotator", "next_click", "");
    currentRotatorItem = (currentRotatorItem == (returnedRotatorData.length - 1)) ? 0 : currentRotatorItem + 1;
    loadNewData(returnedRotatorData[currentRotatorItem]);
}
function loadNewData(dataItem) {
    tempRef = jQuery(".mainImage", rfgRotatorScope);
    rfgRotatorScope.prepend('<img src="' + dataItem.image + '" class="mainImage newImage" style="display:none;">');
    jQuery(".newImage", rfgRotatorScope).fadeIn(500).removeClass("newImage");
    tempRef.fadeOut(400, function () {
        tempRef.remove();
    });
    jQuery("h2.mainRFGTitle", rfgRotatorScope).html(dataItem.title);
    jQuery("div.mainRFGInfo", rfgRotatorScope).html(dataItem.description);
}
