(function($) {
    $.fn.beforeAfter = function(options) {
        var defaults =
		{
		    animateIntro: false,
		    introDelay: 1000,
		    introDuration: 1000,
		    showFullLinks: true,
		    imagePath: '/content/images/before-after/',
		    zoomFactor: 2
		};

        var options = $.extend(defaults, options);

        // used to create unique IDs
        var caseID = Math.round(Math.random() * 100000000);


        return this.each(function() {
            var o = options;
            var obj = $(this);

            obj.addClass("beforeAfter");

            var images = $(".image");
            var image = $(images[0]);
            var imgBefore = $(images[0]);
            var imgAfter = $(images[1]);

            var imgWidth = image.width();
            var imgHeight = image.height();

            var divBefore = $('.beforeContainer:first', obj);
            var divAfter = $('.afterContainer:first', obj);

            // breathing room to load
            divBefore.delay(3000).css('visibility', 'visible');
            divAfter.delay(3000).css('visibility', 'visible');

            $(obj).width(imgWidth).height(imgHeight)

            // store some data in the image...
            image.data({
                zoom: 1,
                top: 0,
                left: 0,
                width: imgWidth,
                height: imgHeight,
                originalWidth: imgWidth,
                originalHeight: imgHeight
            });

            // Preload images and assign them IDs
            var srcs = [imgBefore.attr('src'), imgAfter.attr('src')];
            var cache = [];
            var srcsLen = srcs.length;
            for (var i = srcsLen; i--; ) {
                var cacheImg = document.createElement('img');
                cacheImg.src = srcs[i];
                cache.push(cacheImg);
            }
            imgBefore.attr('id', 'beforeimage' + caseID);
            imgAfter.attr('id', 'afterimage' + caseID);

            // Create an inner div wrapper (dragwrapper) to hold the images.
            var dragwrapper = '<div id="dragwrapper' + caseID + '" class="dragwrapper"><div id="drag' + caseID + '" class="drag"><img alt="handle" src="' + o.imagePath + 'handle.gif" id="handle' + caseID + '" class="handle" /></div></div>';
            var arrows = '<img src="' + o.imagePath + 'lt-small.png" id="lt-arrow' + caseID + '"><img src="' + o.imagePath + 'rt-small.png" id="rt-arrow' + caseID + '">';

            $(obj).append(arrows);
            $(obj).prepend(dragwrapper);

            var dwWidth = 24;
            var dwLeft = (imgWidth / 2) - (dwWidth / 2);
            //console.log(dwLeft);

            $('#dragwrapper' + caseID).css({
                'position': 'absolute',
                'left': dwLeft + 'px',
                'width': dwWidth + 'px',
                'height': imgHeight
            });

            divBefore.css({
                'position': 'absolute',
                'left': '0px',
                'height': imgHeight,
                'width': imgWidth / 2
            }); // Set CSS properties of the before image div

            divAfter.css({
                'position': 'absolute',
                'overflow': 'hidden',
                'right': '0px',
                'height': imgHeight,
                'width': imgWidth
            }); // Set CSS properties of the after image div

            $('#drag' + caseID).css({
                'position': 'absolute',
                'left': '50%',
                'height': imgHeight
            }); // Set drag handle CSS properties

            $('#beforeimage' + caseID).css({
                'position': 'absolute',
                'top': '0px',
                'left': '0px'
            });
            $('#afterimage' + caseID).css({
                'position': 'absolute',
                'top': '0px',
                'right': '0px'
            });
            $('#handle' + caseID).css({
                'position': 'absolute',
                'top': (imgHeight / 2) - ($('#handle' + caseID).height() / 2) + 'px',
                'left': '-3px'
            });

            if (o.showFullLinks) {
                $('#links').attr('id', 'links' + caseID);
                var balinks = $('#links' + caseID);
                $('#showleft').attr('id', 'showleft' + caseID);
                $('#showright').attr('id', 'showright' + caseID);
                $('#showleft2').attr('id', 'showleft2' + caseID);
                $('#showright2').attr('id', 'showright2' + caseID);
                $('#links').attr('id', 'links' + caseID);
                $('#links2').attr('id', 'links2' + caseID);

                $('a', balinks).click(function(evt) {
                    evt.preventDefault();
                });

                var dragger = $('#dragwrapper' + caseID);
                var dragWidth = dragger.width();
                var rightPos = imgWidth - dragWidth - 20; // 20 pixel cushion
                var leftPos = 20;
                var num = dragger.position().left;

                //calculate interval for sliding left/right
                var numSections = (imgWidth / dragWidth);           //calculate how many sections the dragger takes up
                var divisions = numSections / 10;                   //calc how many divisions the img will be divided into
                var interval = Math.floor(dragWidth * divisions);   //convert to pixels

                $('#showleft' + caseID).click(function() {
                    moveTo(rightPos, this);
                });
                $('#showright' + caseID).click(function() {
                    moveTo(leftPos, this);
                });
                $('#showleft2' + caseID).click(function() {
                    num = dragger.position().left;
                    var limit = leftPos + interval;
                    if (num > limit) { num = num - interval } else { num = leftPos }
                    moveTo(num, this);
                });
                $('#showright2' + caseID).click(function() {
                    num = dragger.position().left;
                    var limit = rightPos - interval;
                    if (num < limit) { num = num + interval; } else { num = rightPos }
                    moveTo(num, this);
                });


                var showLeft = $('#showleft' + caseID);
                var showRight = $('#showright' + caseID);

                var moveTo = function(num, e) {
                    var rightWidth = 390 - 2 - num;
                    var id = $(e).attr('id');

                    if (id == 'showleft2' + caseID) {
                        showLeft.animate({ width: num }, 300);
                        showRight.animate({ width: rightWidth }, 300, "linear");
                    } else {
                        showRight.animate({ width: rightWidth }, 300);
                        showLeft.animate({ width: num }, 300, "linear");
                    }
                    showLabel(num);
                    dragger.animate({ left: num - (dwWidth / 2) }, 300);
                    divBefore.animate({ width: num }, 300);
                }
            }

            var showLabel = function showLabel(num) {
                var dur = 300;
                if (num < 190) {
                    if (showLeft.css('opacity') != '0') {
                        showLeft.animate({ 'opacity': '0' }, dur);
                    }
                    showRight.animate({ 'opacity': '1' }, dur);
                } else if (num > 200) {
                    if (showRight.css('opacity') != '0') {
                        showRight.animate({ 'opacity': '0' }, dur);
                    }
                    showLeft.animate({ 'opacity': '1' }, dur);
                } else {
                    showLeft.animate({ 'opacity': '1' }, dur);
                    showRight.animate({ 'opacity': '1' }, dur);
                }
            }

            var barOffset = $('#dragwrapper' + caseID).offset(); // The coordinates of the dragwrapper div
            var startBarOffset = barOffset.left; // The left coordinate of the dragwrapper div
            var originalLeftWidth = divBefore.width();
            var originalRightWidth = divAfter.width();

            $('#dragwrapper' + caseID).draggable({
                containment: obj,
                axis: 'x'
            });

            $('#dragwrapper' + caseID).bind("drag", function(e, ui) {
                var offset = $(this).offset();
                var barPosition = offset.left - startBarOffset;
                var newWidth = originalLeftWidth + barPosition;
                if (newWidth < 190) {
                    if (showLeft.css('opacity') != '0') {
                        showLeft.css({ 'opacity': '0' });
                    }
                    showRight.css({ 'opacity': '1' });
                } else if (newWidth > 200) {
                    if (showRight.css('opacity') != '0') {
                        showRight.css({ 'opacity': '0' });
                    }
                    showLeft.css({ 'opacity': '1' });
                } else {
                    showLeft.css({ 'opacity': '1' });
                    showRight.css({ 'opacity': '1' });
                }
                divBefore.width(newWidth);
                showLeft.width(newWidth);
                showRight.width(390 - 2 - newWidth); // img width - border width - showLeft width
            });

            $('#dragwrapper' + caseID).bind('dragstop', function() { });


            $('#ctrlZoomIn').hide();
            $('#ctrlZoomOut').hide();
            // begin zoom feature
            /*
            var zoom = $("<a class='zoom'></a>");

            zoom.width(Math.floor(imgWidth / 2));
            zoom.height(Math.floor(imgHeight / 2));

            obj.append(zoom);

            obj.hover(
            function(event) {
            zoom.show();
            },
            function(event) {
            zoom.hide();
            }
            );

            viewOffset = obj.offset();
            var window = $(window);



            obj.mousemove(
            function(event) {
            var windowScrollTop = window.scrollTop();
            var windowScrollLeft = window.scrollLeft();

				    setZoomPosition(
            Math.floor(
            event.pageX - viewOffset.left + windowScrollLeft
            ),
            Math.floor(
            event.pageY - viewOffset.top + windowScrollTop
            )
            );
            }
            );


            var setZoomPosition = function(mouseLeft, mouseTop) {
            var zoomLeft = (mouseLeft - (zoom.width() / o.zoomFactor));
            var zoomTop = (mouseTop - (zoom.height() / o.zoomFactor))

                // Protect the top-left bounds.
            zoomLeft = Math.max(zoomLeft, 0);
            zoomTop = Math.max(zoomTop, 0);



                // Protect the bottom-right bounds.
            zoomLeft = Math.min(
            zoomLeft,
            (obj.width() - zoom.outerWidth())
            );
            zoomTop = Math.min(
            zoomTop,
            (obj.height() - zoom.outerHeight())
            );

                zoom.css({
            left: (zoomLeft + "px"),
            top: (zoomTop + "px")
            });
            };

            zoom.click(
            function(event) {
            event.preventDefault();
            zoomImage(
            zoom.position().left,
            zoom.position().top
            );
            }
            );

            // zoom function in controls
            var xCenter = obj.width() / 4;
            var yCenter = obj.height() / 4;

            $('.zoom-in').click(
            function(event) {
            event.preventDefault();
            zoomImage(xCenter, yCenter);
            }
            );

            $('.zoom-out').click(function() {
            resetZoom();
            });

            var zoomImage = function(zoomLeft, zoomTop) {
            var imageData = image.data();

                // max zoom before resetting
            if ((imageData.zoom > 2) || image.is(":animated")) {
            resetZoom();
            return;
            }

                // Scale the image up based on the zoom factor.
            imageData.width = (image.width() * o.zoomFactor);
            imageData.height = (image.height() * o.zoomFactor);

                // Change the offset set data
            imageData.left = ((imageData.left - zoomLeft) * o.zoomFactor);
            imageData.top = ((imageData.top - zoomTop) * o.zoomFactor);

                // Increase the zoom.
            imageData.zoom++;

                // Animate the zoom.
            images.each(function() {
            $(this).animate(
            {
            width: imageData.width,
            height: imageData.height,
            left: imageData.left,
            top: imageData.top
            },
            o.zoomSpeed
            );
            });
            };

            var resetZoom = function() {
            var imageData = image.data();

                // Reset the image data.
            imageData.zoom = 1;
            imageData.top = 0;
            imageData.left = 0;
            imageData.width = imageData.originalWidth;
            imageData.height = imageData.originalHeight;

                // Animate the zoom.
            images.each(function() {
            $(this).animate(
            {
            width: imageData.width,
            height: imageData.height,
            left: imageData.left,
            top: imageData.top
            },
            Math.floor(o.zoomSpeed * 0.5)
            );
            });
            };
            
            */

        }); // return this.each
    }
})(jQuery);
