// ************************************
// photo-rotator.js
//
// Dependecies:
// jQuery.js
//
// ************************************

PhotoRotator = function (photos) {

    this._photos = photos;
    this._curPhoto = null;
    this._nextPhoto = null;
    this._curIndex = 0;
    this._newSrc = '';

    this._interval = 5000;
    this._timeoutHandle = null;

}

PhotoRotator.prototype = {

    init: function () {
        this.initNav();
        this.initPhotos();
        this.start();
    },

    initNav: function () {
        $('#rotator-nav-left').click(jQuery.proxy(this.prev, this));
        $('#rotator-nav-right').click(jQuery.proxy(this.next, this));
    },

    initPhotos: function () {
        $('#rotator .rotator-loading').hide();
        $('#rotator .rotator-imgloadcontainer').hide();
    },

    start: function () {
        this._timeoutHandle = setTimeout(jQuery.proxy(this.next, this), this._interval);
    },

    next: function () {
        clearTimeout(this._timeoutHandle);
        var nextIndex = (this._curIndex + 1) % this._photos.length;
        this.loadPhoto(nextIndex);
    },

    prev: function () {
        clearTimeout(this._timeoutHandle);
        var prevIndex = Math.abs((this._curIndex - 1) % this._photos.length);
        this.loadPhoto(prevIndex);
    },

    loadPhoto: function (index) {
        this._nextPhoto = this._photos[index];
        this.fadeToggle();
        this.slideOut();
        this._curIndex = index;
    },

    fadeToggle: function () {
        //var nextIndex = (curIndex + 1) % photos.length;
        //newSrc = photos[nextIndex].imageUrl;
        $('#rotator-image-back').attr('src', this._nextPhoto.imageUrl);
        $('#rotator-image-back').hide();
        $('#rotator-image-front').fadeOut(800);
        $('#rotator-image-back').fadeIn(800, jQuery.proxy(this.endFadeToggle, this));
        //curIndex = nextIndex;
    },

    endFadeToggle: function () {
        //alert(newSrc);
        $('#rotator-image-front').attr('src', this._nextPhoto.imageUrl);
        $('#rotator-image-front').show();
        $('#rotator-image-back').hide();
        this.endSlideOut();
    },

    slideOut: function () {
        $('.rotator-overlay').hide();
        //$('.rotator-overlay').slideToggle(300, function () { /*endSlideOut();*/ });
    },

    endSlideOut: function () {
        $('.rotator-title').html(this._nextPhoto.title);
        $('.rotator-content p').html(this._nextPhoto.desc);
        $('.rotator-overlay').slideToggle(300, jQuery.proxy(this.start, this));
    }

}
