﻿/*
// Carolator - A jQuery Carousel
// VERSION: 1.2 (2011-09-07)
//
// DEVELOPED BY:
// Alex Vaos
// simplex0@gmail.com
// 2010-08-11
// 
// REQUIRES:
// jQuery
*/

(function($) {

    // UTILITIES
   $.debug = function(text, type) {
		if (window.console && window.console.log) {
			if (type == 'info' && window.console.info) {
				window.console.info(text);
			}
			else if (type == 'warn' && window.console.warn) {
				window.console.warn(text);
			}
			else {
				window.console.log(text);
			}
		}
	};

    $.create = function(sel) {
        if (typeof sel != "string") return sel;
        var t = "div", c, p;
        p = sel.indexOf(".");
        if (p != -1) {
            t = sel.substring(0, p);
            c = sel.substring(p + 1);
        } else {
            c = sel;
        }

        return jQuery("<" + t + ">").addClass(c);
    };

    $.findOrCreate = function(el, ctn) {
        var r;
        if (ctn) {
            r = ctn.find(el);
        } else {
            r = $(el);
        }
        // CHECK
        if (!(r.length > 0)) {
            $.debug("jandi - NOT FOUND, WILL CREATE: " + el);
            r = $.create(el);
            if (ctn)
                ctn.append(r);
        }
        return r;
    };

    // CLASS DEFINITION
    $.fn.carolator = function(options) {

        // DEFAULTS
        var d = {
            transition: true, 		// FALSE, FADE, OR SLIDE
            speed: 750,
            sectionStart: 1,
            autoplay: true, 			// IF IT PLAYS AT THE BEGINNING
            continueTime: 20, 		// SECONDS BEFORE STARTING TO PLAY AGAIN, 0 FOR OFF
            animateLinks: true, 		// IF <A> TAGS SHOULD SLIDE UP
            showControls: true,
            showTimer: false, 		// DOESNT EXIST YET
            width: null,
            height: null, 			// auto/null, max, or integer (ex. 305)
            buttonsOnBottom: true,
            repeat: true,
            timeout: 6, 				// SECONDS OF SLIDESHOW
            pagerTransition: "fade", // TRANSITION USED IN THE DOTS: fade, wipe, none
            sectionMargin: 10,
            // CONTROLS
            content: "div.carolator-content",
            contentScroller: "div.carolator-contentScroller",
            section: "div.carolator-section",
            controls: "div.carolator-controls",
            // EVENTS
            slideChange: null,
            //
            debugging: false
        };
        var o = $.extend({}, d, options);

        // VALIDATE OPTIONS
        if (!o.slideChange) o.slideChange = function() { };

        // GLOBALS
        var g = {
            name: "carolator"
        };

        var debug = function(t1, t2) {
            if (o.debugging) {
                if ($.type(t1) == "string") t1 = "CAROLATOR - " + t1;
                $.debug(t1, t2);
            }
        };



        // CONTROLS
        var c = {
            self: null,
            buttons: null,
            navCtn: null,
            navPrev: null,
            navNext: null,
            sections: null,
            selectBg: null,
            content: null,
            contentScroller: null,
            pagerCtn: null,
            pagers: null
        };

        c.self = $(this);

        // PRIVATE
        var _p = {
            unitSize: 0,
            width: 0,
            height: 0,
            transitioning: false, // IF IN TRANSITION
            sectionSelected: 0, // SECTION BY ID
            sectionTotal: 0,
            ctnOffset: 0, // CONTAINER OFFSET
            playing: false,
            playInterval: null,
            navPrev: "carolator-prev",
            navNext: "carolator-next",
            continueTimer: null
        };

        // EVENTS


        var display = function(n) {
            if (!(c.sections.length > 0)) {
                var l = 0;
                debug("NO SECTIONS FOUND");
                _stop();
                return;
            }

            if (typeof (n) == "undefined") n = _p.sectionSelected;
            else _p.sectionSelected = n;

            // CUSTOM EVENT
            o.slideChange(n);

            //debug("CAROLATOR - DISPLAY: " + n + " - OFFSET: " + $(c.sections[n]).offset().left + " - CONTENT OFFSET: " + c.content.offset().left);

            // THIS SECTION
            var ts = c.sections.eq(n);

            // FIND LINKS TO ANIMATE BUTTONS
            var links = ts.find("a");
            links.css({
                "position": "relative",
                top: 50,
                opacity: 0
            });


            if (o.showControls) {
                // CLEAR PAGER
                for (i = 0; i < _p.sectionTotal; i++) {
                    if (o.pagerTransition == "fade") {
                        $(c.pagers[i]).find("b").fadeOut();
                    }
                    c.pagers[i].removeClass("pager-selected");
                }
            }

            var l = c.contentScroller.offset().left - $(c.sections[n]).offset().left;

            // ANIMATOR CAROUSEL
            c.contentScroller.animate(
				{
				    left: l // - c.content.offset().left
				},
				{
				    duration: o.speed,
				    queue: false,
				    complete: function() {

				        // ANIMATE LINKS
				        links.animate(
							{
							    top: 0,
							    opacity: 1
							}, {
							    queue: false,
							    duration: o.speed
							}
						);


				        // ANIMATE PUSHES

				        if (o.showControls) {
				            // CLEAR PAGER
				            for (i = 0; i < _p.sectionTotal; i++) {
				                if (o.pagerTransition == "fade") {
				                    $(c.pagers[i]).find("b").fadeOut();
				                }
				                c.pagers[i].removeClass("pager-selected");
				            }

				            // SET PAGER
				            $(c.pagers[n]).addClass("pager-selected");
				            if (o.pagerTransition == "fade") {
				                $(c.pagers[n]).find("b").fadeIn();
				            }
				        }
				    }
				}
			);
        };


        var _next = function() {
            if (_p.sectionSelected < (_p.sectionTotal - 1)) {
                _p.sectionSelected++;
            } else if (o.repeat) {
                _p.sectionSelected = 0;
            }
            display();
            if (o.continueTime) continueTimer.set();
        };
        var _previous = function() {
            if (_p.sectionSelected > 0) {
                _p.sectionSelected--;
            } else if (o.repeat) {
                _p.sectionSelected = (_p.sectionTotal - 1);
            }
            display();
            if (o.continueTime) continueTimer.set();
        };

        var _play = function() {
            _stop();
            _p.playInterval = setInterval(_next, o.timeout * 1000);
            _p.playing = true;
        };

        var _stop = function() {
            clearInterval(_p.playInterval);
            _p.playing = false;
        };

        var goToSlide = function(n) {
            if (n >= c.sections.length) return;
            var was = _p.playing;
            if (was) _stop();
            display(n);
            if (was) _play();
        };

        var continueTimer = {
            set: function() {
                this.clear();
                _p.continueTimer = setTimeout(function() { _play(); }, o.continueTime * 1000);
            },
            clear: function() {
                clearTimeout(_p.continueTimer);
            }
        };

        var _init = function() {

            // CREATE DOM
            c.self.addClass("ui-" + g.name);

            _p.width = c.self.width();
            _p.height = c.self.height();

            //debug(_p);

            _p.transitioning = false;
            _p.sectionSelected = 0;


            // CREATE DOM				

            // CHECK CONTENT / SECTION CONTAINER
            c.content = $.findOrCreate(o.content, c.self);
            c.content.addClass(g.name + "-content");

            // CHECK CONTENT SCROLLER	
            c.contentScroller = c.self.find(o.contentScroller);

            if (!(c.contentScroller.length > 0)) {
                debug("NOT FOUND: " + o.contentScroller);
                c.contentScroller = $.create(o.contentScroller);
                c.content.wrapInner(c.contentScroller);

                c.contentScroller = c.content.find(o.contentScroller);
            }
            c.contentScroller.addClass(g.name + "-contentScroller");


            /*
            // CHECK NAV CONTAINER
            c.navCtn = c.self.find(".carolator-nav");
            if (!(c.navCtn.length > 0)) {
            c.navCtn = $("<div>").addClass("carolator-nav");
            c.self.prepend(c.navCtn);
            }
            */

            if (o.showControls) {

                // CHECK CONTROLS
                c.controls = $.findOrCreate(o.controls, c.self);

                // CHECK PAGER CONTAINER
                c.pagerCtn = c.self.find("." + g.name + "-pager");
                if (!(c.pagerCtn.length > 0)) {
                    c.pagerCtn = $("<div>").addClass(g.name + "-pager");
                    o.buttonsOnBottom ? c.controls.append(c.pagerCtn) : c.controls.prepend(c.pagerCtn);
                }

                // NAV BUTTONS
                c.navPrev = c.self.find("." + _p.navPrev);
                if (!(c.navPrev.length > 0))
                    c.controls.prepend(c.navPrev = $("<a href=\"javascript: void(0)\"><b></b></a>").addClass(_p.navPrev).addClass(g.name + "-nav"));
                c.navPrev.click(function() { _stop(); _previous(); });

                c.navNext = c.self.find("." + _p.navNext);
                if (!(c.navNext.length > 0))
                    c.controls.append(c.navNext = $("<a href=\"javascript: void(0)\"><b></b></a>").addClass(_p.navNext).addClass(g.name + "-nav"));
                c.navNext.click(function() { _stop(); _next(); });

            }


            // SECTIONS
            c.sections = c.self.find(o.section);
            if (!(c.sections.length > 0)) {
                debug("NO SECTIONS FOUND: " + o.section);
            }


            _p.unitSize = c.content.width() * 1.2;

            c.contentScroller.css({
                width: c.sections.length * _p.unitSize,
                height: c.content.height()
            });
            c.contentScroller.append(c.sections);

            // SECTION STYLES
            c.sections.css({
                float: "left",
                width: c.content.width(),
                height: c.content.height(),
                marginLeft: o.sectionMargin,
                marginRight: o.sectionMargin
            });

            // CREATE BUTTONS IN PAGER
            c.pagers = [];
            c.sections.each(function(num) {
                _p.sectionTotal++;

                var title = $(this).attr("title") || num + 1;

                //c.pagerCtn.append(c.pagers[num] = $("<a href='javascript: void(0);' title='" + (num + 1) + "'>" + (num + 1) + "</a>"));
                debug("SECTION OFFSET:" + num + " - " + $(this).offset().left);

                if (o.showControls) {
                    // CREATE PAGER BUTTON
                    c.pagerCtn.append(c.pagers[num] = $("<a href='javascript: void(0);' title='" + title + "'><b>" + (num + 1) + "</b></a>"));
                    // PAGER BUTTONS EVENTS
                    c.pagers[num].click(function() {
                        //debug("CAROLATOR - DISPLAY: " + num);
                        //var num = parseInt($(this).attr("title")) - 1;
                        _stop();
                        display(num);
                    });
                }
            });

            //c.pagers = c.pagerCtn.find("a");

            debug("CONTENT SCROLLER OFFSET:" + c.content.offset().left);

            display();
            if (o.autoplay) _play();


        }; // INIT

        _init();



        var r = {
            items: null,
            goToSlide: goToSlide
        };
        r.items = this;

        return r;


    };

})(jQuery); // end of closure, bind to jQuery Object


/*
Colunator Example
*/
jQuery(function($) {

    $("div.ui-carolator").carolator();

});

