/*
 * jQuery Focus rotate by Overchuk
 *
 *
 *
 */
(function($) {

    $.fn.fads = function(options)
    {
        var defaults =
        {
            oneclick : false,   // Jump to href by one click. Default: first click is select, second - jump
            zindex : 1,         // Base z-index
            speed  : 500,       // Fade speed
            timeout: 3000,      // Interval between slide
            klass  : 'liact'    // Class of active <li>
        }


        var $a = $(this).children('ul').children('li').children('a');
        if($a.size() == 0)
            return;

        var $opt = $.extend({}, defaults, options);
        var $i = 0;
        var $t = null;

        // Z-INDEX
        $z1 = $opt.zindex;
        $z2 = $opt.zindex+1;

        var get = function(o)
        {
            var i;
            for(i = 0; i< $a.size(); i++)
                if(o == $a[i])
                    return i;

            return -1;
        }

        var name = function(o)
        {
            return o.rel;
        }


        var $div = [];
        for(i=0; i<$a.size(); i++)
        {
            $div[i] = $('#' + name( $a[i] ) );
            $div[i].css('z-index', $z1);
        }


        var show = function(n)
        {
            stop();
            for(i=0; i<$div.length; i++)
                if(i == n)
                {
                    $( $a[i] ).parent().addClass($opt.klass);
                    $div[i].show();
                }
                else
                {
                    $div[i].hide();
                    $( $a[i] ).parent().removeClass($opt.klass);
                }

            $div[n].css('z-index', $z1);
            go();
        }

        var fade = function(n)
        {
            stop();
            $div[n].css('z-index', $z2);
            $div[n].fadeIn($opt.speed, function(){ var i = n; show(n); });
        }

        $a.unbind('click.fad').bind('click.fad', function(e){
                stop();
                $t = $(this);
                if( $opt.oneclick || $t.parent().hasClass($opt.klass) )
                    document.location = $t.attr('href');
                else
                {
                    $i = get(this);
                    show( $i );
                }
                e.stopPropagation();
                return false;
            });

        var step = function(){
                    if($a.size() == 0)
                        return;

                    $i++;
                    if($i >= $a.size())
                        $i = 0;

                    fade($i);
                };

        var stop = function(){ if($t) clearTimeout($t); $t = null; }

        var go = function(){ stop(); $t = setTimeout(step, $opt.timeout); }


        go();
    }

})(jQuery);

