

(function (){

    var d = window.document;
    var active=false, banners = [], buttons = [];
    var timer=null, time=6000;

    function init (b) {
        var holder=b[0].getElementsByClassName('home-banners-holder');

        if ( holder && holder.length>0 ) {
            banners=holder[0].getElementsByClassName('home-banners-banner');
            buttons=holder[0].getElementsByClassName('home-banners-index');
            if ( banners && buttons && banners.length==buttons.length ) {
                for ( var a = 0; a < banners.length; a ++ ) {
                    buttons[a].onclick=(function(a){ return function(){gotopage(a)} })(a);

                    state_inactive(banners[a]);
                    state_inactive(buttons[a]);
                }
                timer=create_timer(page_auto,time);
                timer.start();

                gotopage(0);
            }
        }
    }

    function gotopage(p) {
        timer.stop();

        if ( active!==false ) {
            state_inactive(banners[active]);
            state_inactive(buttons[active]);
        }

        state_active(banners[p]);
        state_active(buttons[p]);
        active=p;

        timer.start();
    }

    function state_active (e) {
        state_inactive(e);
        e.className+=' active';
    }

    function state_inactive(e) {
        e.className=e.className.replace(/\s*active\s*/g,'');
    }


    function create_timer (callback,timeout){

        var t=null;

        function start () {
            stop();
            t=setTimeout(callback,timeout);
        }

        function trigger() {
            stop();
            callback.apply();
        }

        function stop () {
            clearTimeout(t);
        }

        return {
            start: start,
            stop:  stop
        };
    };

    function page_auto() {
        gotopage(active+1>=banners.length?0:active+1);
    }


    function wait() {
        var b=d.getElementsByTagName('body');
        if (b.length>0) {
            init(b);
        } else {
            setTimeout( wait, 80 );
        }
    }

    wait();

    return {};
})();
