
var EXTFuncNextArray = [];
var EXTFuncPrevArray = [];

function EXTFuncNext(funcid) {
    EXTFuncNextArray[funcid]();
}
function EXTFuncPrev(funcid) {
    EXTFuncPrevArray[funcid]()
}


(function($) {
    $.fn.jCarouselLite = function(o) {

        o = $.extend({
            btnPrev: null,
            btnNext: null,
            btnGo: null,
            mouseWheel: false,
            auto: null,

            speed: 200,
            scrollspeed: 800,
            easing: null,

            vertical: false,
            circular: true,
            visible: 3,
            start: 0,
            scroll: 1,

            beforeStart: null,
            afterEnd: null,
            itemTag: 'img',

            btnMoveLeft: null,
            btnMoveRight: null,
            selected: -1,
            default_width: 68,
            default_height: 70,
            operation: 'create',
            GetObjectFromImg: function(img) {
                var iobj = {
                    Src: img.attr('src'),
                    Alt: img.attr('Alt'),
                    OrderNum: img.attr('OrderNum'),
                    OriginalWidth: img.attr('OriginalWidth'),
                    OriginalHeight: img.attr('OriginalHeight'),
                    Url: img.attr('Url'),
                    PosLeft: img.attr('PosLeft'),
                    PosTop: img.attr('PosTop')
                };
                return iobj;
            },
            SetObjectToImg: function(img, iobj) {
                img.attr('src', iobj.Src);
                img.attr('Alt', iobj.Alt);
                img.attr('OrderNum', iobj.OrderNum);
                img.attr('OriginalWidth', iobj.OriginalWidth);
                img.attr('OriginalHeight', iobj.OriginalHeight);
                img.attr('Url', iobj.Url);
                img.attr('PosLeft', iobj.PosLeft);
                img.attr('PosTop', iobj.PosTop)
            }

        }, o || {});

        if (o.operation == 'recreate') {

            this.each(function() {

                if (o.btnPrev) {
                    $(o.btnPrev).unbind('click');
                    $(o.btnPrev).unbind('mouseenter');
                    $(o.btnPrev).unbind('mouseleave');
                }

                if (o.btnNext) {
                    $(o.btnNext).unbind('click');
                    $(o.btnNext).unbind('mouseenter');
                    $(o.btnNext).unbind('mouseleave');
                }

                if (o.btnMoveLeft && o.btnMoveRight) {
                    o.btnMoveLeft.unbind('click');
                    o.btnMoveRight.unbind('click');
                }
                $(o.itemTag, this).unbind('click');
            });
        }


        return this.each(function() {                           // Returns the element collection. Chainable.

            var running = false, animCss = o.vertical ? "top" : "left", sizeCss = o.vertical ? "height" : "width";
            var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;
            var funcid = EXTFuncNextArray.length

            if (o.circular) {
                ul.prepend(tLi.slice(tl - v - 1 + 1).clone())
              .append(tLi.slice(0, v).clone());
                o.start += v;
            }

            var li = $("li", ul), itemLength = li.size();
            var curr = o.start;

            if (o.selected != -1 && o.selected < tl) {
                SetSelected($(o.itemTag, tLi[o.selected]));
                if (o.selected < curr) curr = o.selected;
                if (o.selected >= curr + o.visible) curr = o.selected - o.visible + 1;
            }


            $('#CurrentCarouselItem').val(curr);
            div.css("visibility", "visible");

            li.removeClass("nodisplay");
            li.css({ overflow: "hidden", float: o.vertical ? "none" : "left" });
            ul.css({ 'margin': '0', padding: 0, position: "relative", "list-style-type": "none", "z-index": "1" });
            div.css({ overflow: "hidden", position: "relative", "z-index": "2", left: "0px" });

            var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
            var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
            var divSize = liSize * v;                           // size of entire div(total length for just the visible items)

            //li.css({ width: li.width(), height: li.height() });   Зачем это ?????????????
            ul.css(sizeCss, ulSize + "px").css(animCss, -(curr * liSize));

            div.css(sizeCss, divSize + "px");                     // Width of the DIV. length of visible images
            div.css("height", height(li) + "px");

            var prevRunFlag = false;
            var nextRunFlag = false;
            EXTFuncPrevArray[funcid] = PrevAutoScroll;
            function PrevAutoScroll() {
                if (prevRunFlag) {
                    setTimeout('EXTFuncPrev(' + funcid + ')', 50);
                    return go(Number(curr - o.scroll), o.scrollspeed);
                }
            }

            if (o.btnPrev) {
                $(o.btnPrev).click(function() {
                    prevRunFlag = false;
                    nextRunFlag = false;
                    if (running)
                        ul.stop(true, true);
                    else
                        go(Number(curr - o.scroll), o.speed);
                });
                $(o.btnPrev).mouseenter(function() {
                    prevRunFlag = true;
                    if (curr > 0)
                        $(this).addClass('oprev');
                    PrevAutoScroll();
                });
                $(o.btnPrev).mouseleave(function() {
                    prevRunFlag = false;
                    $(this).removeClass('oprev');
                });

            }

            EXTFuncNextArray[funcid] = NextAutoScroll
            function NextAutoScroll() {
                if (nextRunFlag) {
                    setTimeout('EXTFuncNext(' + funcid + ')', 50);
                    go(Number(curr + o.scroll), o.scrollspeed);
                }
            }
            if (o.btnNext) {
                $(o.btnNext).click(function() {
                    prevRunFlag = false;
                    nextRunFlag = false;
                    if (running)
                        ul.stop(true, true);
                    else
                        go(Number(curr + o.scroll), o.speed);
                });
                $(o.btnNext).mouseenter(function() {
                    nextRunFlag = true;

                    if (curr <= itemLength - v - 1)
                        $(o.btnNext).addClass('onext');
                    NextAutoScroll();
                });
                $(o.btnNext).mouseleave(function() {
                    nextRunFlag = false;
                    $(o.btnNext).removeClass('onext');
                });
            }


            if (o.btnGo)
                $.each(o.btnGo, function(i, val) {
                    $(val).click(function() {
                        return go(o.circular ? o.visible + i : i);
                    });
                });

            if (o.mouseWheel && div.mousewheel)
                div.mousewheel(function(e, d) {
                    return d > 0 ? go(curr - o.scroll) : go(curr + o.scroll);
                });

            if (o.auto)
                setInterval(function() {
                    go(curr + o.scroll);
                }, o.auto + o.speed);

            var moving = false;



            if (o.btnMoveLeft && o.btnMoveRight) {
                o.btnMoveLeft.click(function() {
                    if (moving) return false;
                    var ind = GetSelectedIndex();
                    if (ind == -1 || ind == 0) return false;
                    moving = true;
                    ExchangeImage($(o.itemTag, tLi[ind]), $(o.itemTag, tLi[ind - 1]));
                    SetSelected($(o.itemTag, tLi[ind - 1]));
                    moving = false;
                    return false;
                });

                o.btnMoveRight.click(function() {
                    if (moving) return false;
                    var ind = GetSelectedIndex();
                    if (ind == -1 || ind == tl - 1) return false;
                    moving = true;
                    ExchangeImage($(o.itemTag, tLi[ind]), $(o.itemTag, tLi[ind + 1]));
                    SetSelected($(o.itemTag, tLi[ind + 1]));
                    moving = false;
                    return false;
                });
            }


            $(o.itemTag, this).click(function() {
                SetSelected($(this));

            });

            function vis() {
                return li.slice(curr).slice(0, v);
            };

            function GetSelectedIndex() {
                for (var i = 0; i < tl; i++) {
                    var selected = $('.image_selector', tLi[i]);
                    if (selected.size() != 0) return i;
                }
                return -1;
            };

            function SetSelected(img) {
                var img_div = img.parent();
                var li = img_div.parent();

                var selected = $('.image_selector', ul);
                if (selected.size() == 0) {
                    img_div.addClass('image_selector');
                }
                else {
                    selected.removeClass('image_selector');
                    img_div.addClass('image_selector');
                }
            };
            function go(to, speed) {

                if (!running) {
                    var correction = 0;


                    if (o.beforeStart)
                        o.beforeStart.call(curr);

                    if (o.circular) {            // If circular we are in first or last, then goto the other end
                        if (to <= o.start - v - 1) {           // If first, then goto last
                            ul.css(animCss, -((itemLength - (v * 2)) * liSize) + "px");
                            // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
                            curr = to == o.start - v - 1 ? itemLength - (v * 2) - 1 : itemLength - (v * 2) - o.scroll;
                        } else if (to >= itemLength - v + 1) { // If last, then goto first
                            ul.css(animCss, -((v) * liSize) + "px");
                            // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
                            curr = to == itemLength - v + 1 ? v + 1 : v + o.scroll;
                        } else curr = to;
                    } else {                    // If non-circular and to points to first or last, we just return.
                        if (!(to < 0 || to > itemLength - v)) {
                            curr = to;
                            $('#CurrentCarouselItem').val(curr);
                        }
                    }                           // If neither overrides it, the curr will still be "to" and we can proceed.

                    running = true;
                    ul.animate(
                    animCss == "left" ? { left: -(curr * liSize)} : { top: -(curr * liSize) }, speed, o.easing,
                    function() {
                        if (o.afterEnd)
                            o.afterEnd.call(curr);
                        running = false;
                        if (!o.circular) {
                            if (curr - o.scroll < 0) $(o.btnPrev).removeClass('oprev');
                            if (curr + o.scroll > itemLength - v) $(o.btnNext).removeClass('onext');
                        }
                    }
                );
                    // Disable buttons when the carousel reaches the last/first, and enable when not


                }
                return false;
            };
        });

        function width(el) {
            if (!el) return o.default_width;
            if (el.size() == 0) return o.default_width;
            var _w = el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight')
            if (_w == 0) return o.default_width;
            return _w;
        };
        function height(el) {
            if (!el) return o.default_height;
            if (el.size() == 0) return o.default_height;
            var _h = el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
            if (_h == 0) return o.default_height;
            return _h;
        };
        function css(el, prop) {
            return parseInt($.css(el[0], prop)) || 0;
        };

        function ExchangeImage(img1, img2) {
            var obj1 = o.GetObjectFromImg(img1);
            var obj2 = o.GetObjectFromImg(img2);
            o.SetObjectToImg(img1, obj2);
            o.SetObjectToImg(img2, obj1);
        }
    };

})(jQuery);