/*
Plugin Name: jdatabase
Version: 1.0
Plugin URI: http://c-lab.co.uk
Description: jQuery Plugin for database fader
Author: Howard Boland
Author URI: http://c-lab.co.uk


*/

/* PLUGIN USAGE */
/* */


(function ($) {


    $.fn.jdatabase = function (options) {

        var opts = $.extend({ speed: null, direction: null, rootDir: null }, $.fn.jdatabase.defaults, options);
        var $controls = $($(this).find(opts.controls)[0]);

        var $obj = $(this);
        var $toslide = $($(this).find(opts.items)[0]);
        var $items = $toslide.find(".item");
        var $innerSize = $($(this).find(".innerSize")[0]);
        var $play = $($(this).find(opts.play)[0]);
        var $next = $($(this).find(opts.next)[0]);
        var $prev = $($(this).find(opts.prev)[0]);

        var index = 0;
        var MouseX = 0;
        var MouseY = 0;
        var startTop = 0;
        var isHover = false;
        var sliderInterval = null;
        var distance = 80 + 2;
        var speed = 10000;
        var hasStarted = false;
        var dummyItems = [];
        var datasource = [];
        var currentArray = [];
        var nextArray = [];
        var faded = [];




        var gather = function () {

            $innerSize.css("width", $toslide.innerWidth() + "px");
            distance = $($items[0]).outerWidth() + 2;
            offsetItems = ($items.length % 3);

            $obj.find(".item").each(function (index, el) {
                dummyItems[index] = $(el);
            });

        }


        var find = function (no) {


            $.ajax({
                type: "POST",
                url: opts.rootDir + "Webservice.asmx/GetResourceGallery",
                data: "{count: " + no + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    datasource = [];
                    datasource = response.d;
                    addData();
                },
                failure: function (msg) {
                    alert("error:" + msg)
                }
            });


        }
        var scroller = function () {
            clearInterval(sliderInterval);

            dummyItems = [];
            $obj.find(".item").each(function (index, el) {
                dummyItems[index] = $(el);
            });
            pause();

            var noVis = 4;
            var counter = 0

            var upperCheck = (index + noVis > dummyItems.length) ? (index + noVis - 1) % dummyItems.length : index + noVis - 1;
            var lowerCheck = index;
            var nextIndex = (index + noVis) > (dummyItems.length) ? (index + noVis) % (dummyItems.length) : (index + noVis);
            var upperCheck2 = (nextIndex + noVis > dummyItems.length) ? (nextIndex + noVis - 1) % dummyItems.length : nextIndex + noVis - 1;
            var lowerCheck2 = nextIndex;

            currentArray = [];
            nextArray = [];

            for (var i = 0; i < dummyItems.length; i++) {
                if ((index + noVis) > dummyItems.length) //modula situation
                {
                    if (i >= lowerCheck || i <= upperCheck) {
                        currentArray.push(i)
                    }
                } else {
                    if (i >= lowerCheck && i <= upperCheck) {
                        currentArray.push(i)
                    }
                }
                if ((nextIndex + noVis) > dummyItems.length) //modula situation
                {
                    if (i >= lowerCheck2 || i <= upperCheck2) {
                        nextArray.push(i)
                    }
                } else {
                    if (i >= lowerCheck2 && i <= upperCheck2) {
                        nextArray.push(i)
                    }
                }
            }

            for (var i = 0; i < dummyItems.length; i++) {
                dummyItems[i].hide();
                $(dummyItems[i]).stop(false, true);
                $(dummyItems[i]).fadeIn(0);
                dummyItems[i].css("z-index", 1);
                dummyItems[i].css("top", "0px");

            }
            var xOffset = -97;
            $toslide.css("left", "0px");
            var countFadeOut = 0;
            faded = [];
            for (var i = 0; i < noVis; i++) {
                xOffset += 103;
                var currentItem = dummyItems[currentArray[i]];
                var nextItem = dummyItems[nextArray[i]];
                currentItem.css("left", (xOffset) + "px");
                currentItem.css("top", "0px");
                currentItem.css("z-index", 1);
                currentItem.css({ opacity: 1 });
                nextItem.css("left", (xOffset) + "px");
                nextItem.css("z-index", 0);
                nextItem.css("top", "0px");

                currentItem.show();
                nextItem.show();
                currentItem.stop(false, true);
                faded.push(currentItem);

                currentItem.delay((i * 200)).fadeOut("slow", function () {
                    if (countFadeOut == noVis - 1) {
                        find(4)
                    } countFadeOut += 1;
                });

            }

            index = (index + noVis) > (dummyItems.length) ? (index + noVis) % (dummyItems.length) : (index + noVis);

            //restart()

        }

        var swapItems = function () {
            var noVis = 4;

            for (var i = 0; i < noVis; i++) {
                var nextItem = dummyItems[nextArray[i]];
                var currentItem = dummyItems[currentArray[i]];

                currentItem.css("z-index", 0);
                nextItem.css("z-index", 1);
            }
        }
        var addData = function () {

            var imagesLoaded = 0;

            swapItems()
            for (var i = 0; i < datasource.length; i++) {
                var r = datasource[i];
                //alert($items[currentArray[i]])
                var currentItem = faded[i]; // $($items[currentArray[i]]);
                //currentItem.css("top", "-80px");

                var $item = faded[i].clone(true);
                //currentItem.css("opacity", ".5");

                //     alert($(currentItem.find("img")).attr("src") + "->" + r.image.url)

                var $i = $item.clone(true);
                $(currentItem).replaceWith($i);

                //                $i.show().css({ opacity: 1 });

                //$($obj.find("item")[i]).remove($($obj.find("item")[i]).parent());
                if (true) {



                    $($i.find("a")).attr("title", r.image.description).attr("href", r.url);

                    var $div = $($i.find("div.imageWrapper")[0]);
                    $($div.find("div:first")).text(r.name);
                    $div.addClass("imageLoader");
                    var $img = $('<img />');
                    $i.show();
                    $($i.find("img")[0]).replaceWith($img);
                    $img.load(function () {
                        //                        alert($(this).outerWidth())
                        var mw = $div.width() / $(this).width();
                        var mh = $div.height() / $(this).height();
                        var mx = Math.max(mh, mw) == mw ? mw : mh;

                        if ($(this).width() < $div.width() || $(this).height() < $div.height()) {

                            var hx = $(this).height() * mx;
                            var wx = $(this).width() * mx;

                            $(this).css("width", wx + "px");
                            $(this).css("height", hx + "px");

                        }

                        $(this).css("position", "relative");
                        $(this).css("left", Math.round(($div.width() - $(this).outerWidth()) / 2) + "px");
                        $(this).css("top", Math.round(($div.height() - $(this).outerHeight()) / 2) + "px");
                        $div.removeClass("imageLoader")


                        imagesLoaded += 1;
                        if (imagesLoaded == datasource.length) {
                            //            alert("eo");
                            restart();

                        }
                    }).error(function () {
                        imagesLoaded += 1;
                        if (imagesLoaded == datasource.length) {
                            //          alert("eo");
                            restart();
                        }
                    }).attr("src", r.image.url).attr("title", r.image.description).attr("alt", r.image.description)
                }
            }
        }
        var play = function () {

            if (hasStarted) {

                pause();
                sliderInterval = setInterval(scroller, speed);
            }
        }

        var pause = function () {
            if (sliderInterval != null)
                clearInterval(sliderInterval)
        }

        var restart = function () {
            if (!$play.hasClass('pause')) {

                pause();
            }
            else {
                play();
            }
        }
        var restructureFloatToPosition = function () {
            var i = 0;
            $obj.find(".item").each(function (index, el) {

                var posX = ((i * $(el).width()) + 2);
                
                $(el).css({ left: posX+"px", top: 0 + "px", position: 'absolute', zIndex: '10' });
                i += 1;

            });

        }
        var showControls = function () {

            $controls.show();


            if (!$play.hasClass('pause')) {
                $play.addClass('pause');
            }
            $controls.delay(2000).animate({ opacity: 0 }, Math.round(500), function () { });
            //alert("test")
            hasStarted = true;
            scroller();
            //$toslide.animate({ opacity: 1 }, 500);
        }

        var bind = function () {

            $obj.bind('mousemove', function (event) {

                MouseX = event.pageX;
                MouseY = event.pageY;

            });


            $obj.bind('mouseenter mouseover mouseleave mouseout', function (event) {
                $controls.stop(false, true);
                $controls.css("opacity", 1);
                (event.type == "mouseenter" || event.type == "mouseover")
					? $controls.show()
					: $controls.hide();

                isHover = (event.type == "mouseenter" || event.type == "mouseover")

            });

            $obj.bind('videoplay', function () {
                pause();
            });

            $obj.bind('videopause', function () {
                restart();
            });

            $play.click(function () {
                $play.addClass('hover');
                if ($play.hasClass('pause')) {
                    $play.removeClass('pause');
                    $play.addClass('play');
                } else {
                    $play.removeClass('play');
                    $play.addClass('pause');
                }
                restart()
            }, $play.removeClass('no-hover'));

        }



        var getTopIndex = function () {

            var bottomIndex = -1;
            var topIndex = -1;


            $obj.find(".item").each(function (index, el) {

                if ($(el).offset().top > ($innerSize.offset().top + $obj.height()) && bottomIndex < 0) {
                    bottomIndex = index
                }
                if ($(el).offset().top >= $innerSize.offset().top && topIndex < 0) {
                    topIndex = index;
                }
                $(el).css("border", "none")
            });
            return topIndex
        }


        var centre = function () {

            var imagesProjectLoaded = 0;
            $obj.find(".item").each(function (index, el) {
                var $img = $($(el).find("img")[0]);
                var $div = $($(el).find("div.imageWrapper:first"));


                $div.addClass("imageLoader")

                if ($img.width() > 20 && $img.height() > 20) {
                    mx = Math.max($div.width() / $img.outerWidth(), $div.height() / $img.outerHeight());
                    $img.css({ width: ($img.outerWidth() * mx) + "px", height: ($img.outerHeight() * mx) + "px" });

                    $img.css("position", "relative");
                    $img.css("left", Math.round(($div.width() - $img.width()) / 2) + "px");
                    $img.css("top", Math.round(($div.height() - $img.height()) / 2) + "px");

                    $img.fadeIn();
                    imagesProjectLoaded += 1;
                    //$("#alter").html("right:"+($("#cellar .item").length-imagesProjectLoaded));
                    if ($items.length == imagesProjectLoaded) {

                        showControls();

                    }
                } else {
                    $img.hide();

                    $img.error(function () {
                        $div.removeClass("imageLoader");
                        imagesProjectLoaded += 1;
                        if ($items.length == imagesProjectLoaded) {

                            showControls();

                        }
                    }).load(function () {
                        var mw = $div.width() / $(this).width();
                        var mh = $div.height() / $(this).height();
                        var mx = Math.max(mh, mw) == mw ? mw : mh;

                        if ($(this).width() < $div.width() || $(this).height() < $div.height()) {

                            var hx = $(this).height() * mx;
                            var wx = $(this).width() * mx;

                            $(this).css("width", wx + "px");
                            $(this).css("height", hx + "px");

                        }

                        $img.css("position", "relative");
                        $img.css("left", (($div.width() - $img.width()) / 2) + "px");
                        $img.css("top", (($div.height() - $img.height()) / 2) + "px");
                        $div.removeClass("imageLoader")
                        $img.fadeIn();
                        imagesProjectLoaded += 1;
                        //$("#alter").html("right:"+($("#cellar .item").length-imagesProjectLoaded));
                        if ($items.length == imagesProjectLoaded) {

                            showControls();

                        }

                    }); // end loading images
                }

            }); // end for each	

        }

        gather();

        //$toslide.css({ opacity: 0 });
        //$toslide.show();
        bind();
        $controls.hide();
        restructureFloatToPosition();
        centre();

        //showControls()	
        //reset(true);	



    };


    $.fn.jdatabase.defaults = {
        items: ".items",
        controls: ".controls",
        play: ".play",
        pause: ".pause",
        next: ".next",
        prev: ".prev",
        noItems: 3,
        rootDir: "/"

    } //end function

})(jQuery);



