/*
Plugin Name: jFadeshow
Version: 1.0
Plugin URI: 
Description: jQuery Plugin for Fading between project
Author: Howard Boland
Author URI: http://portfolio.c-lab.co.uk

*/

/* PLUGIN USAGE */
/* 
	
*/


(function ($) {


    $.fn.jFadeShow = function (options) {

        var opts = $.extend({ speed: null, direction: null, rootDir: null }, $.fn.jFadeShow.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 $activeItem = null;
        var $nextItem = null

        var currentIndex = 0;
        var MouseX = 0;
        var MouseY = 0;
        var startTop = 0;
        var isHover = false;
        var sliderInterval = null;
        var distance = 2;
        var speed = 5000;
        var hasStarted = false;


        $innerSize.css("height", $toslide.innerHeight() + "px");


        var animate = function () {

            $activeItem.addClass('last-active');
            $activeItem.css({ opacity: 1 }).animate({ opacity: 0 }, 1000, function () { $activeItem.removeClass('active');  });

            $nextItem.css({ opacity: 0 })
            .addClass('active')
            .animate({ opacity: 1 }, 2000, function () {
                
                restart();
            });


        }



        var scroller = function () {
            next();


        }



        var next = function () {

            pause();
            if ($activeItem != null)
                $activeItem.stop(false, true);
            if ($nextItem != null)
                $nextItem.stop(false, true);

            $activeItem = $($obj.find('.active'));


            if ($activeItem.length == 0) $activeItem = $($obj.find('.item:first-child'));


            var currentId = $($activeItem.find("a")).length < 0 ? 0 : $($activeItem.find("a")).attr("rel");
            lookupNext(currentId);

        }

        var rolloverText = function () {

            el = $nextItem.find('.rolloutBlue')[0];

            $(el).css("width", "auto");
            $(el).css("left", "400px");

            $(el).unbind("mouseover mouseenter mouseout mouseexit")
            $(el).css('padding', '2px').corner("round 5px");

            var fullloc = $(el).text();

            $(el).text(fullloc);
            var fullwidth = $(el).outerWidth(true);
            $(el).css("width", fullwidth + "px");
            var shortloc = fullloc.split(",")[fullloc.split(",").length - 1];
            $(el).css("width", "auto");
            $(el).text(shortloc);
            var shortwidth = $(el).outerWidth(true);
            $(el).css('width', shortwidth + 'px');
            $(el).css('left', (410 - shortwidth) + "px");
            $(el).text(shortloc);

            $(el).bind("mouseover mouseenter mouseout mouseexit", function (event) {
                if (event.type == "mouseover" || event.type == "mouseenter") { $(el).text(fullloc); $(el).animate({ width: (fullwidth) + "px", left: (410 - fullwidth) + "px" }, 200, function () { $(el).text(fullloc); }) };
                if (event.type == "mouseout" || event.type == "mouseexit") { $(el).animate({ width: (shortwidth) + "px", left: (410 - shortwidth) + "px" }, 200, function () { $(el).text(shortloc); }) };
            })

        }
        var lookupNext = function (id) {
            lookupNextPrev(id, -1)
        }

        var lookupPrev = function (id) {
            lookupNextPrev(id, 1)
        }

        var lookupNextPrev = function (id, dir) {

            $.ajax({
                type: "POST",
                url: (dir == 1 ? opts.rootDir + "Webservice.asmx/NextEvent" : opts.rootDir + "Webservice.asmx/PreviousEvent"),
                data: "{currentId: " + id + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {

                    var event = response.d;

                    $nextItem = (dir == 1) ? ($activeItem.next().length ? $activeItem.next() : $($obj.find('.item:first'))) : ($activeItem.prev().length ? $activeItem.prev() : $($obj.find('.item:last')));
                    $($nextItem.find("h4")).text(event.name);
                    $($nextItem.find("div.rolloutBlue")).text(event.description);
                    rolloverText();

                    $($nextItem.find("a")).attr("rel", event.id);
                    $($nextItem.find("a")).each(function (index, el) { $(el).attr("href", event.link) });


                    var $div = $($nextItem.find("div.imageWrapper"));

                    var $img = $('<img />');
                    $($nextItem.find("img")[0]).replaceWith($img);
                    $div.addClass("imageLoader");
                    $img.error(function () {
                        animate();
                    });

                    $img.load(function () {

                        $img.show();

                        var mw = $div.width() / $img.width();
                        var mh = $div.height() / $img.height();
                        var mx = Math.max(mh, mw) == mw ? mw : mh;

                        if ($img.width() < $div.width() || $img.height() < $div.height()) {

                            var hx = $img.height() * mx;
                            var wx = $img.width() * mx;

                            $img.css("width", wx + "px");
                            $img.css("height", hx + "px");

                        } else {

                        }
                        $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");

                        animate();

                    });
                    $img.attr("src", event.image);
                },
                failure: function (msg) {
                    animate();
                    //$('#output').text(msg);
                }
            });
        }

        var previous = function () {

            pause();
            if ($activeItem != null)
                $activeItem.stop(false, true);
            if ($nextItem != null)
                $nextItem.stop(false, true);

            $activeItem = $($obj.find('.active'));

            if ($activeItem.length == 0) $activeItem = $($obj.find('.item:first-child'));
            /*
            $nextItem = $activeItem.prev().length ? $activeItem.prev()
            : $($obj.find('.item:last'));

            animate();
            */
            var currentId = $($activeItem.find("a")).length < 0 ? 0 : $($activeItem.find("a")).attr("rel");

            lookupPrev(currentId);


        }
        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 showControls = function () {

            $controls.show();

            if (!$play.hasClass('pause')) {
                $play.addClass('pause');
            }
            $controls.delay(2000).animate({ opacity: 0 }, Math.round(500), function () { });
            if ($activeItem != null)
                $activeItem.stop(false, true);
            if ($nextItem != null)
                $nextItem.stop(false, true);

            $activeItem = $($obj.find('.active'));



            if ($activeItem.length == 0) $activeItem = $($obj.find('.item:first-child'));

            $activeItem.addClass('last-active');
            $activeItem.css({ opacity: 1.0 })
            $nextItem = $activeItem;

            hasStarted = true;
            rolloverText();
            restart();

        }

        var bind = function () {

            $obj.bind('mousemove', function (event) {

                MouseX = event.pageX;
                MouseY = event.pageY;

            });
            $obj.bind('videoplay', function () {
                pause();
            });
            $obj.bind('videopause', function () {
                restart();
            });

            $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")

            });

            $prev.click(function () {

                $prev.addClass('no-hover');
                // ui.countWAPI("wa_p_pg=-1");

                previous();
            }, $prev.removeClass('no-hover'));

            $next.click(function () {
                $next.addClass('hover');
                next();
            }, $next.removeClass('no-hover'));


            $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 centre = function () {

            var imagesProjectLoaded = 0;
            $obj.find(".item").each(function (index, el) {
                var $img = $($(el).find("img")[0]);
                var $div = $($(el).find("div.imageWrapper")[0]);

                if ($img.width() > 20 && $img.height() > 20) {
                    var mw = $div.width() / $img.width();
                    var mh = $div.height() / $img.height();
                    var mx = Math.max(mh, mw) == mw ? mw : mh;
                    if ($img.width() < $div.width() || $img.height() < $div.height()) {

                        var hx = $img.height() * mx;
                        var wx = $img.width() * mx
                        $img.css("width", wx + "px");
                        $img.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");

                    $img.show();
                    imagesProjectLoaded += 1;
                    //$("#alter").html("right:"+($("#cellar .item").length-imagesProjectLoaded));
                    if ($items.length == imagesProjectLoaded) {
                        showControls();

                    }


                } else {
                    $div.addClass("imageLoader")
                    $img.hide();


                    $img.error(function () {
                        imagesProjectLoaded += 1;
                        if ($items.length == imagesProjectLoaded) {
                            showControls();

                        }
                    });
                    $img.load(function () {
                        var mw = $div.width() / $img.width();
                        var mh = $div.height() / $img.height();
                        var mx = Math.max(mh, mw) == mw ? mw : mh;
                        if ($img.width() < $div.width() || $img.height() < $div.height()) {

                            var hx = $img.height() * mx;
                            var wx = $img.width() * mx
                            $img.css("width", wx + "px");
                            $img.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("fast");
                        $img.show();
                        $img.unbind("load");
                        imagesProjectLoaded += 1;
                        //$("#alter").html("right:"+($("#cellar .item").length-imagesProjectLoaded));
                        if ($items.length == imagesProjectLoaded) {
                            showControls();

                        }

                    }); // end loading images
                }
            }); // end for each	

        }


        bind();
        centre();


    };


    $.fn.jFadeShow.defaults = {
        items: ".items",
        controls: ".controls",
        play: ".play",
        pause: ".pause",
        next: ".next",
        prev: ".prev",
        noItems: 3,
        rootDir: "/"
    } //end function

})(jQuery);



