
function featureRotator(container, feed, slideDuration) {	
	/* Configuration options */
    this.openWidth = 750;
	this.slideshowDuration=(typeof slideDuration == "undefined")?5000:slideDuration;

	/* Store a reference to the main container element */
	this.container=jQuery(container);
	/* Store the total width of the container */
	this.totalWidth=this.container.width();
	/* Store the width of a closed element - calculated later */
	this.closedWidth=0;
	/* Store the data from the JSON call */
	this.data=[];
	/* Store a reference to all of the panes in an array */
	this.panes=[];
	/* Store whichever pane is currently active */
	this.currentPos=0;
	/* Store an internal timer */
	this.timer=null;
	/* Boolean flag for whether we're animating or not */
	this.timerRunning=true;
	
	/* Load the feed */
	this.loadFeed(feed);
}

/**
 * Show the element at a given position, taking duration milliseconds to animate to that position.
 */
featureRotator.prototype.show = function (newPos, duration) {
    var _self = this;

    /* Update the currentPos */
    this.currentPos = newPos;

    /* For each of the panes */
    this.panes.each(function (index, pane) {
        /* Store a jQuery wrapped reference */
        var $_pane = jQuery(pane);

        /* Calculate what the new left position should be */
        var leftPos = Math.floor(index * _self.closedWidth);
        if (index > newPos) {
            leftPos += Math.floor(_self.openWidth - _self.closedWidth);
        }

        /* Calculate the width - either open or closed */
        var width = Math.ceil(_self.closedWidth);
        if (index == newPos) {
            width = Math.ceil(_self.openWidth);
        }

        /* If we're the new active element */
        if (index == newPos) {
            /* Set the open/closed classes and show/hide the content */
            $_pane.addClass('rotatorOpen');
            $_pane.removeClass('rotatorClosed');
            $_pane.find('.content').show();
        } else {
            $_pane.removeClass('rotatorOpen');
            $_pane.addClass('rotatorClosed');
            $_pane.find('.content').hide();
        }

        /* Animate this pane to the new position */
        $_pane.animate({
            left: leftPos,
            width: width
        }, duration, "swing");
    });

    /* If the timer system is running, restart the current cycle */
    if (this.timerRunning) {
        this.startTimer();
    }
};

/**
 * Increment/decrement the currentPos by an amount
 * and animate to it.
 */
featureRotator.prototype.add = function (amount) {
    var next = this.currentPos + amount;
    if (this.panes.length < 2) {
        next = 0;
    } else {
        while (next < 0) {
            next += this.panes.length;
        }
        next = next % this.panes.length;
    }
    this.show(next);
};

/**
 * Next convenience function 
 */
featureRotator.prototype.next = function () {
    this.add(1);
};

/**
 * Previous convenience function 
 */
featureRotator.prototype.prev = function () {
    this.add(-1);
};

/**
 * Stop the timer from running and remove the class.
 */
featureRotator.prototype.stopTimer = function () {
    clearTimeout(this.timer);
    this.timerRunning = false;
    this.container.removeClass('rotatorTimerRunning');
};

/**
 * Start the timer running and add the class.
 * If a timer was already running, clear it.
 */
featureRotator.prototype.startTimer = function () {
    var _self = this;
    clearTimeout(this.timer);
    this.timerRunning = true;
    this.container.addClass('rotatorTimerRunning');
    this.timer = setTimeout(function () {
        _self.next();
    }, this.slideshowDuration);
};

/**
 * Toggle the on/off state of the timer system.
 */
featureRotator.prototype.toggleTimer = function (el) {
    if (this.timerRunning) {
        rotatorTrack("Homepage_Rotator", "pause_click", jQuery(el).attr("rel"));
        this.stopTimer();
    } else {
        rotatorTrack("Homepage_Rotator", "play_click", jQuery(el).attr("rel"));
        this.startTimer();
    }
};

/**
 * Calculate how large the closed pane widths should be.
 * Take the total width, subtract the open width.
 * Now divide what's left by the number of panes that'll be closed at any one time.
 */
featureRotator.prototype.calculateSizes = function () {
    var divisor = this.data.length - 1;
    if (divisor < 1) { divisor = 1; } // Prevent divide by zero errors
    this.closedWidth = (this.totalWidth - this.openWidth) / (divisor);
};

/**
 * Once the JSON response comes back, process it, initializing the system.
 */
featureRotator.prototype.processFeed = function (data) {
    var _self = this;

    /* Store the data */
    this.data = data;

    /* Calculate widths */
    this.calculateSizes();

    /* Clear anything that was already in there */
    this.container.html("");

    /* Create the base pane divs */
    for (var i = 0; i < this.data.length; i++) {
        this.container.append('<div class="pane"></div>');
    }

    /* Find all of the panes we just created */
    this.panes = this.container.find('.pane');

    /* Write the content in to each pane */
    this.panes.each(function (index, pane) {
        var $_pane = jQuery(pane);
        var _page = _self.data[index];

        var trackLabel = (_page.label == "" || typeof _page.label == "undefined" || _page.label.toLowerCase().indexOf("<img") != -1) ? "Untitled" : _page.label;
       
        /* Build their inner HTML */
        var html = [];
	var _slideLabel = (_page.shortTitle == "" || typeof _page.shortTitle == "undefined") ? _page.title.substr(0, 6) : _page.shortTitle;
        
      html.push('<a onclick="rotatorTrack(\'Homepage_Rotator\',\'rotator_slide_click\',\'' + trackLabel + '\');" href="#" class="clickTrigger"><span>' + _slideLabel   + '</span></a>');


        html.push('<a rel="' + trackLabel + '" href="#" class="rotatorPlayPause"></a>');

        html.push('   <a class="largeImageHitArea" ' + _page.target + ' onclick="return rotatorTrack(\'Homepage_Rotator\',\'internal_link_click\',\'' + trackLabel + ':' + _page.title + '\');" href="' + _page.url + '"></a>');
        html.push('<div class="content">');
        
        html.push('   <h2><a '+_page.target+' onclick="return rotatorTrack(\'Homepage_Rotator\',\'internal_link_click\',\'' + trackLabel + ':' + _page.title + '\');" href="' + _page.url + '">' + _page.title + '</a></h2>');
        html.push('   <div class="description">' + _page.description + '</div>');
        if (_page.links) {
            html.push('   <ul class="links">');

            for (var i = 0; i < _page.links.length; i++) {
                tempLinkType = ((_page.links[i].url.indexOf("http") != -1) && (_page.links[i].url.indexOf("http://" + document.domain) == -1)) ? "external_link_click" : "internal_link_click";
                html.push('      <li><a '+_page.links[i].target+' onclick="return rotatorTrack(\'Homepage_Rotator\',\'' + tempLinkType + '\',\'' + trackLabel + ':' + _page.links[i].title + '\');" href="' + _page.links[i].url + '">' + _page.links[i].title + '</a></li>');
            }

            html.push('   </ul>');
        }
        html.push('</div>');
        $_pane.css('background-image', 'url(' + _page.image + ')').html(html.join("\n"));

        /* Bind their clickTriggers - the links that'll make them "current" */
        $_pane.find('.clickTrigger').click(function (e) {
            e.preventDefault();
            _self.show(index, 300);
        });
    });

    /* Add the play/pause button and then bind it */
    //this.container.append('<a href="#" class="rotatorPlayPause"></a>');
    this.container.find('.rotatorPlayPause').click(function (e) {
        e.preventDefault();
        _self.toggleTimer(this);
    });

    this.show(0, 0);
    this.setupMouseOver();
};

featureRotator.prototype.setupMouseOver = function () {
    //grayscale($('.rotatorClosed'));
    //grayscale.reset($('.rotatorClosed .clickTrigger'));
    /*
     $('.rotatorClosed .clickTrigger').hover(function(){
            grayscale(this);
        }, function(){
            grayscale.reset(this);
       });
    */
};

/* Load the JSON feed */
featureRotator.prototype.loadFeed = function (feed) {
    var _self = this;
    jQuery.ajax({
        url: feed,
        dataType: 'json',
        cache:false,
        success: function (data) {
            _self.processFeed(data);
        },
        error: function (data) {
            if (console && console.log) {
                console.debug(data);
                console.log("Unable to load rotator feed.");
            }
        }
    });
};
rotatorTrack = function (category, optional_label, optionalValue) {
    //console.log(category + ", " + optional_label + ", " + optionalValue);
    pageTracker._trackEvent(category, optional_label, optionalValue);
    return;
};


