/**
 * Created by JetBrains WebStorm.
 * User: Power
 * Date: 06.12.11
 * Time: 14:35
 * To change this template use File | Settings | File Templates.
 */
var Carousel = function (initObj) {
    //Inheritance
    EventCommander.apply(this);

    var this_ = this;
    var currentIndex_;
    var isRunning_;

    this.getCurrentIndex = function () {
        return currentIndex_;
    };

    this.isRunning = function () {
        return isRunning_;
    };

    this.setAnimationTime = function (time) {
        this_.animationTime = time;
    };

    this.getChildren = function () {
        return $(this_.child);
    };

    this.next = function () {
        this.goTo(currentIndex_ + 1);
    };

    this.prev = function () {
        this.goTo(currentIndex_ - 1);
    };

    this.goTo = function (index, jump, complete) {
        jump = jump || false;

		this_.trigger("beforeChange",[currentIndex_,index]);
		isRunning_ = true;

        var step = 100 * (index - currentIndex_);

        $(this_.child).each(function (animationIndex) {
            this_.trigger("beforeElementChange", [currentIndex_, animationIndex, index]);
            $(this).animate({
                left: "-=" + step + "%"
            },
						{
						    duration: !jump ? this_.animationTime : 0,
						    specialEasing: {
						        left: this_.animationEasing
						    },
						    complete: function () {
						        this_.trigger("afterElementChange", [currentIndex_, animationIndex, index]);
						        if (animationIndex == $(this_.child).length - 1) {
						            this_.trigger("afterChange", [index, currentIndex_]);
						            isRunning_ = false;
						            currentIndex_ = index;
						        }
						        if (complete != null)
						            complete();
						    },
						    queue: true
						}
				);
        });
    };

    this.jumpTo = function (index, complete) {
        this.goTo(index, true, complete);
    };

    function init_() {
        if (initObj.container) {
            this_.container = initObj.container;
        }

        if (initObj.child) {
            this_.child = initObj.child;
        }

        if (initObj.currentIndex != undefined) {
            currentIndex_ = initObj.currentIndex;
        }

        if (initObj.animationTime != undefined) {
            this_.animationTime = initObj.animationTime;
        }

        if (initObj.animationEasing != undefined) {
            this_.animationEasing = initObj.animationEasing;
        }
    }
    init_();
};

Carousel.prototype = {
  container: $("#main"),
  child: $("#main article"),
  animationTime: 1000,
  animationEasing: "linear"
};

