﻿/* 
* Name : iSwitch
* Version : 1.3
* Author  : pivanov.com
* Author email: me@pivanov.com
*
* Examples of use:
*
*	$(switchElement).iSwitch({
*		tabsElements		: 'element',
*		startElement		: 1,
*		currentElementName	: 'name',
*		time				: 2000,
*		animateTime 		: 1000,
*       switcher            : true
*	});
*/

(function ($) {
    $.fn.iSwitch = function (options) {

        var options = $.extend({}, $.fn.iSwitch.defaults, options),
			tabsElements = $(options.tabsElements).children(),
			switchElement = $(this).children(),
			startElement = options.startElement - 1,
			currentElementName = options.currentElementName,
			transitionInterval = options.time + options.animateTime,
			switcher = (!options.time || options.time == 0 ? false : true);

        switchElement.hide().eq(startElement).show();

        if (tabsElements.length != 0) {
            currentElement = tabsElements;
        }
        else {
            currentElement = switchElement;
        }

        currentElement.eq(startElement).addClass(currentElementName);

        if (switcher == true) {
            var timer = setInterval(function () {
                switchImage();
            }, transitionInterval);

            //Call functions
            //pause(switchElement);
            pause(tabsElements);
        }

        /* functions */

        tabsElements.click(function () {

            if (switchElement.is(':animated') || $(this).hasClass('current')) {
                return false;
            }

            switchImage(tabsElements.index(this));

            return false;
        });

        function switchImage(index) {

            // if currentElement not exists
            if (typeof index == "undefined") {
                index = startElement + 1;
                index = index >= currentElement.length ? 0 : index;
            }

            if (tabsElements.length != 0) {
                tabsElements.removeClass(currentElementName).filter(":eq(" + index + ")").addClass(currentElementName);
            }

            //stop animation - very import to clearQueue and jumpToEnd
            switchElement.stop(true, true).filter(":visible").fadeOut(options.animateTime);
            switchElement.filter(":eq(" + index + ")").fadeIn(options.animateTime, function () {
                startElement = index;
            });
        }

        function pause(element) {
            element.mouseenter(function () {
                clearInterval(timer);
            }).mouseleave(function () {
                clearInterval(timer);
                timer = setInterval(function () {
                    switchImage();
                }, transitionInterval);
            });
        }
    };

    $.fn.iSwitch.defaults = {
        startElement: 1,
        currentElementName: 'current',
        time: 5000,
        animateTime: 1000,
        switcher: true
    };
})(jQuery);
