
(function($) {                                          // Compliant with jquery.noConflict()
$.fn.megagaleria = function(o) {
    o = $.extend({
        btnPrev: null,
        btnNext: null,
        btnGo: null,
        mouseWheel: false,
        auto: null,

        speed: 200,
        easing: null,

        vertical: false,
        circular: true,
        visible: 3,
        start: 0,
        scroll: 1,

        beforeStart: null,
        afterEnd: null,

        btnMainPrev: null,
        btnMainNext: null,
        mainImg: null,
        mainUrl: null,
        commentsUrl: null,
        title: null
    }, o || {});

    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;

        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(), curr = o.start;
        div.css("visibility", "visible");

        $.each(li, function(i, val) {
            $(val).click(function() {

                $(this).parent().children('.active').fadeTo(500, 0.5).removeClass("active");

                // add class to clicked element
                $(this).fadeTo(500,1);
                $(this).addClass('active');


                var url = $(this).children(':first').attr("src");
                var url2 = url.replace('_2.', '_4.');

                // set url with #filename
                window.location = window.location.href.replace(/\#.*/,'') + '#' + url;

                if(!o.circular) {
                    $(o.btnMainPrev + "," + o.btnMainNext).removeClass("disabled");
                    $( ($(this).is(":first-child") && o.btnMainPrev)
                        ||
                       ($(this).is(":last-child") && o.btnMainNext)
                        ||
                       []
                     ).addClass("disabled");
                }

//                var prev_src = $(o.mainImg).attr("src");

                $(o.mainImg).attr("src",url2);
                if ((i-curr) > 2) {
                    if(!o.circular) {
                        var where = i-2;
                        go(where > itemLength-v ? itemLength-v : where);
                    }
                    else {
                        go(curr+(i-curr-2));
                    }
                }
                else if ((i-curr) < 2){
                    if(!o.circular) {
                        var where = curr-(2 - (i - curr));
                        go(where < 0 ? 0 : where);
                    }
                    else {
                        go(curr-(2 - (i - curr)));
                    }
                }

                var current_img = div.children([type="ul"]).children([type="li"]).children('img[src='+url+']');

                // set alt and title from thumbnail to main img
                $(o.mainImg).attr("alt",  $(this).children().attr("alt"));
                $(o.mainImg).attr("title", $(this).children().attr("title"));

                // set title in additional place
                if(o.title) {
                    $(o.title).html($(this).children().attr("title"));
                }

                // set url at main photo
                if(o.mainUrl) {
                    var photo_url = $(this).children('a').attr("href");
                    $(o.mainUrl).attr("href",photo_url);
                }

                // set url at comments
                if(o.commentsUrl) {
                    var photo_url = $(this).children('a').attr("href");
                    $(o.commentsUrl).attr("href",photo_url+"#komentarze");
                }

            });

        });



        li.css({overflow: "hidden", margin: "10px",cursor: "pointer", border: "1px solid #eae8e9", '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"});
        div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"});

        if (o.btnMainPrev)
            $(o.btnMainPrev).css({cursor: "pointer"});

        if (o.btnMainNext)
            $(o.btnMainNext).css({cursor: "pointer"});

        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 = '650';                           		// 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

        if(o.btnPrev)
            $(o.btnPrev).click(function() {
                return go(curr-o.scroll);
            });

        if(o.btnNext)
            $(o.btnNext).click(function() {
                return go(curr+o.scroll);
            });

        if(o.btnMainPrev)
            $(o.btnMainPrev).click(function() {
                prevImg();
            });

        if(o.btnMainNext) {
            $(o.btnMainNext).click(function() {
                nextImg();
            });
        }



        if(o.btnGo)
            $.each(o.btnGo, function(i, val) {
                $(val).click(function() {
                    return go(o.circular ? o.visible+i : i);
                });
            });

        if(o.mouseWheel && ul.mousewheel)
            ul.mousewheel(function(e, d) {
                d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
                return false;
            });


        if(o.mouseWheel && $(o.mainImg).mousewheel) {
            $(o.mainImg).mousewheel(function(e, d) {
                if(!running) {
                    d>0 ? prevImg() : nextImg();
                }
                    return false;
            });
        }

        if (location.hash) {
//            $('.anyClass').children([type="ul"]).children([type="li"]).children('img[src='+location.hash.replace(/\#/,'')+']').parent().click();
            var current_img_n = $('.anyClass').children('.bottomframe').children('.mid').children([type="ul"]).children([type="li"]).children('img[src='+location.hash.replace(/\#/,'')+']');
            current_img_n.parent().click();
//            alert('img[src='+location.hash.replace(/\#/,'')+']');
        }

        function nextImg()
        {
            if(!running) {
                var main_url = $(o.mainImg).attr("src");
                var url = main_url.replace('_4.', '_2.');
                //console.log(url);

                var current_img = $('.anyClass').children('.bottomframe').children('.mid').children([type="ul"]).children([type="li"]).children('img[src='+url+']');
                current_img.parent().next().click();
            }
        }

        function prevImg()
        {
            if(!running) {
                var main_url = $(o.mainImg).attr("src");
                var url = main_url.replace('_4.', '_2.');

                var current_img = $('.anyClass').children('.bottomframe').children('.mid').children([type="ul"]).children([type="li"]).children('img[src='+url+']');
                current_img.parent().prev().click();
            }
        }

        if(o.auto)
            setInterval(function() {
                go(curr+o.scroll);
            }, o.auto+o.speed);

        function vis() {
            return li.slice(curr).slice(0,v);
        };

        function go(to) {
            if(!running) {

                if(o.beforeStart)
                    o.beforeStart.call(this, vis());

                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) return;
                    else curr = to;
                }                           // 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) } , o.speed, o.easing,
                    function() {
                        if(o.afterEnd)
                            o.afterEnd.call(this, vis());
                        running = false;
                    }
                );

                // Disable buttons when the carousel reaches the last/first, and enable when not
                if(!o.circular) {
                    $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                    $( (curr-o.scroll<0 && o.btnPrev)
                        ||
                       (curr+o.scroll > itemLength-v && o.btnNext)
                        ||
                       []
                     ).addClass("disabled");

                }

            }
            return false;
        };
    });

};

function css(el, prop) {
    return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
    return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
    return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};

})(jQuery);
