/**
The below script has been modified for this project by MJ
**/
/**
* jQuery.nexGallery
* Copyright (c) 2009 Christof Haemmerle - Nex9 - http://www.nex9.com
* Dual licensed under MIT and GPL.
*
* @author Christof Haemmerle
* @version 0.4
* 
* history
* 0.1  initial release
* 0.2  if tracker not available script broke
*      double click in sfari fixed
* 0.3  centers selected thumbnail in center of thumbnail bar
*      scroll thumb wrapper to selected (still needs fix for opera offsetLeft detection problem)
* 0.4  check if there are images in the gallery, if there are none dont even start doing something
*      hide thumbs and fade them in when they are loaded
*      use new google tracker function from nex9.js
* 
* feature requests
* - mouse wheel scroll
* - track clicks on images
* - make images direct accessible via url (hash)
* - fix bug where loading the same image in safarie will never load, click on same story or tumb
* 
* 
* 
* @author Christof Haemmerle
* @version 0.5
* 
* @/depends jquery.browser.js
* @/depends jquery.scrollTo.js
* @/depends nexHelpers.js
**/



(function() {

    var version = '0.1';

    $.fn.nexGallery = function(options) {

        // default settings:
        var defaults = {
            thumbs: '#thumbs',
            showThumbnails: true,
            stories: '#stories',  // display stories
            imgWrapper: '#image', // container wrapping the large image
            imgFileHeight: false,
            imgSizeMode: 'fit larger side', // 'fit smaller side', 'fit larger side', 'fit width', 'fit height 
            imgCaption: '#caption',
            disableTextSelection: true, // requires disable text selection plugin
            showStories: true,
            clickThroughStories: false,
            resizeImage: true, // if true we use imgWrapper to get the width and height for the image

            onGalleryInit: function() { }, // after default init of gallery

            onImageShow: function() { }, // after image 
            onImageHide: function() { },

            onStoryShow: function() { },
            onStoryHide: function() { },

            onThumbClick: function() { },
            onStoryClick: function() { },

            onNextImage: function() { },
            onPrevImage: function() { },

            onLoadImage: function() { }, // called after largeImage is loaded
            resizeLargeImage: function() { } // called after largeImage gets resized - only if resize image is set to true.

        };

        var settings = $.extend(true, {}, defaults, options);

        return this.each(function() {

            // vars
            var gallery = this,
            //
            imgWidth,
            imgHeight,
            imgScale,
            //
            $thumbs = $(settings.thumbs),
            $stories = $(settings.stories),
            $imgCaption = $(settings.imgCaption),
            $imgWrapper = $(settings.imgWrapper),
            $img = $imgWrapper.find('img');

            // bind events to navigation
            $('a[href="#next-image"]').click(function() {
                //alert('next');
                showNextImage();
                return false;
            });
            $('a[href="#prev-image"]').click(function() {
                //alert('prev');
                showPrevImage();
                return false;
            });
            $('a[href="#next-story"]').click(function() {
                showNextStory();
                return false;
            });
            $('a[href="#prev-story"]').click(function() {
                showPrevStory();
                return false;
            });

            $imgWrapper.click(function() {
                showNextImage();
                centerThumbnail();
                return false;
            });


            function initGallery() {

                // hide thumbnail bar if configured
                if (!settings.showThumbnails) {
                    $thumbs.addClass('hidden')
                }

                // add needed classes to initial story and image
                // debug.log('window.location.hash: ', window.location.hash);
                var hash = window.location.hash,
                initial_story = hash.split('/')[0],
                initial_image = hash.split('/')[1];

                // debug.log('initial_story, initial_image: ', initial_story, initial_image);

                if (initial_story) {
                    $thumbs.find(initial_story)
                  .addClass('selected')
                      .find('a:first')
                      .addClass('selected');
                } else {
                    $thumbs.find('div:first')
                    .addClass('selected')
                        .find('a:first')
                        .addClass('selected');
                }

                $thumbs.find('a')
                .click(function() {
                    $(this)
                        .addClass('selected')
                        .siblings()
                            .removeClass('selected');
                    loadImage($(this));
                    //updateHash();
                    settings.onThumbClick.call(this); // callback
                    return false;
                });

                showStory(
                $thumbs.find('.selected').index(),
                determanFirstImage(initial_image)
            ); // initially show first image

                // debug.log('$stories.length: ', $stories.length);

                if ($stories.length !== 0 && settings.showStories) {
                    // init stories only if story menu present
                    if (initial_story) {
                        $stories.find('a[href="' + initial_story + '"]').addClass('selected');
                    } else {
                        $stories.find('a:first').addClass('selected');
                    }
                    $stories.find('a')
                    .click(function() {
                        index = $(this).index();
                        showStory(index, 0);
                        // debug.log('index: ', index);
                        $(this).addClass('selected')
                               .siblings().removeClass('selected');
                        settings.onStoryClick.call(this); // callback
                    });
                };

                // part 2 of fade action
                $img.load(function() {
                    // store original image dimensions in global variables
                    imgWidth = $img.width(),
                imgHeight = $img.height(),
                imgScale = imgHeight / imgWidth;

                    if (settings.resizeImage) {
                        resizeLargeImage() // resize image to fit the container
                    }

                    $(this).animate({ opacity: 1 }, 'slow');
                    preloadNextImage();

                    settings.onLoadImage.call(this); // ballback
                });

                if (settings.resizeImage) {
                    //alert('abc');
                    resizeLargeImage();
                    $(window).resize(function() {
                        resizeLargeImage(); // TODO: need to make firefox work around to resize while resizeing
                    });
                }

                settings.onGalleryInit.call(this); // ballback

            };

            initGallery();


            function determanFirstImage(initial_image) {
                // debug.log('initial_image: ', initial_image);
                var collection_length = $thumbs.find('div.selected').children().length;
                if (initial_image < collection_length) {
                    return initial_image;
                } else {
                    return 0;
                }
            };

            function updateHash() {
                story = $thumbs.find('div.selected').attr('id');
                img = $thumbs.find('div.selected').find('a.selected').index();

                window.location.hash = '#' + story + '/' + img;
            };

            function showNextStory(imageIndex) {
                if (!imageIndex) { // if no image index is parsed in lets assume we want to see the first of the story
                    var imageIndex = 0;
                };
                $selectedStory = $thumbs.find('>.selected');

                if (!$selectedStory.is(':last-child')) {
                    index = parseInt($selectedStory.index());
                    showStory(index + 1, imageIndex);
                } else {
                    // debug.log('no next story');
                };
            };

            function showPrevStory(imageIndex) {
                if (!imageIndex) { // if no image index is parsed in lets assume we want to see the first of the story
                    var imageIndex = 0;
                };
                $selectedStory = $thumbs
                               .find('>.selected');
                if (!$selectedStory.is(':first-child')) {
                    index = parseInt($selectedStory
                                   .prevAll().length);
                    showStory(index - 1, imageIndex);
                } else {
                    // debug.log('no next story - nothing to show');
                };
            };

            function showNextImage() {
                //alert('next')
                showImage('next');
                settings.onNextImage.call(this); // callback
            };

            function showPrevImage() {
                showImage('prev')
                settings.onPrevImage.call(this); // callback
            };

            function showStory(storyIndex, imageIndex) {

                $stories.children()
                    .eq(storyIndex)
                    .addClass('selected')
                    .siblings()
                        .removeClass('selected');

                $thumbs.children()
                .eq(storyIndex)
                .addClass('selected')
                .siblings()
                    .removeClass('selected');

                // adding images to the links in the thumbar if they are not loaded yet
                if (settings.showThumbnails) {
                    if ($thumbs.find('div.selected img').length === 0) {
                        $thumbs.find('div.selected')
                        .find('a').each(function() {
                            var img = new Image()
                            $this = $(this);
                            img.src = $this.attr('href') + '/1000/70';
                            $this.data('caption', $this.text()).empty().append(img);
                        });
                    }
                }
                showImage(imageIndex);

            };

            function showImage(imageIndex) {
                var $selected_thumbs = $('#images').find('a'),
                $current_thumb = $('#images').find('a.selected'),
                total_thumbs = $selected_thumbs.length;

                // debug.log('current selected image: ', $selected_thumbs.find('a.selected').index());

                if (imageIndex === 'last') {
                    imageIndex = total_thumbs;
                }
                if (imageIndex === 'first') {
                    imageIndex = 0;
                }
                if (imageIndex === 'next') {
                    var newImageIndex = $current_thumb.next().index();
                    if (newImageIndex === -1) {
                        // debug.log('newImageIndex: ', newImageIndex);
                        if (settings.clickThroughStories) {
                            showNextStory();
                        };
                        return;
                    }
                    imageIndex = $current_thumb.next().index();
                }
                if (imageIndex === 'prev') {
                    imageIndex = $current_thumb.prev().index();
                }

                if (imageIndex >= 0) {
                    $('#images').find('a.selected').removeClass('selected');
                    $('#images').find('a').eq(imageIndex).addClass('selected').trigger('click');
                }
            };

            function resizeLargeImage() {
                //alert(imgScale);
                dim = getStageDimensions();
                if (settings.imgSizeMode === 'fit larger side') {
                    if (dim.scale > imgScale) {
                        //alert('no');
                        if (imgScale <= 1) {
                            //alert($("#portfolio-right").css("width"));
                            //alert(dim.height + " " + dim.width + " IMAGE: " + imgHeight + "x" + imgWidth);
                            dim.height = dim.height - 65
                            $img.css({ 'width': parseInt((dim.height) / imgScale) });
                            //***
                            //alert($('#portfolio-right').css('width').replace('px', ''));
                            if ($img.css('width').replace("px", "") > dim.width) {
                                $img.css({ 'width': parseInt($('#portfolio-right').css('width').replace('px', '')) });
                            }
                            //***
                            $img.css({ 'margin-top': parseInt(35) });
                            $('#portfolio-left').css({ 'height': (parseInt($img.css('height').replace('px', '')) + 10) });
                            //alert($img.css('height'));
                            $imgWrapper.css({ 'height': (dim.height - 70) });
                            //$('#container footer').css({ 'height': ($(window).height() - (parseInt($('#portfolio-left').css('height').replace("px", "")) + 135)) });
                        }
                        else {
                            //alert('pt');
                            $img.css({ 'width': parseInt(dim.height / imgScale) });
                            $img.css({ 'margin-top': parseInt(0) });
                            $('#portfolio-left').css({ 'height': (dim.height - 23) });
                            $('#container footer').css({ 'height': ($(window).height() - (parseInt($('#portfolio-left').css('height').replace("px", "")) + 85)) });
                            $imgWrapper.css({ 'height': dim.height });
                        }
                        $('#nextprev').css({ 'margin-top': ($('#portfolio-left').css('height').replace("px", "") / 2) - 52 });
                    } else {
                        // debug.log('small: ', dim.scale, imgScale);
                        //landscape
                        if (imgScale <= 1) {
                            //alert('ls');
                            $img.css({ 'width': parseInt((dim.height - 65) / imgScale) });
                            $img.css({ 'margin-top': parseInt(35) });
                            $('#portfolio-left').css({ 'height': (dim.height - 58) });
                            $imgWrapper.css({ 'height': (dim.height - 70) });
                            //$('#container footer').css({ 'height': ($(window).height() - (parseInt($('#portfolio-left').css('height').replace("px", "")) + 135)) });
                        }
                        else {
                            //alert('pt');
                            $img.css({ 'width': parseInt(dim.height / imgScale) });
                            $img.css({ 'margin-top': parseInt(0) });
                            $('#portfolio-left').css({ 'height': (dim.height - 23) });
                            $('#container footer').css({ 'height': ($(window).height() - (parseInt($('#portfolio-left').css('height').replace("px", "")) + 85)) });
                            $imgWrapper.css({ 'height': dim.height });
                        }
                        $('#nextprev').css({ 'margin-top': ($('#portfolio-left').css('height').replace("px", "") / 2) - 52 });

                    };

                }

                //****

                //****
                if (settings.imgSizeMode === 'fit smaller side') {
                    if (dim.scale > imgScale) {
                        $img.css({ 'width': parseInt(dim.height / dim.scale) });
                    } else {
                        c
                    };
                    $imgWrapper.css({ 'height': dim.height });
                    $('#portfolio-left').css({ 'height': (dim.height) });
                }

                if (settings.imgSizeMode === 'fit height') {
                    //calc and resize here mj *******
                    //if (imgWidth > dim.height)
                    //alert($img.css('height'));

                    $img.css('height', dim.height);
                    //alert("h " + dim.height)
                    $img.css({ 'width': parseInt(dim.height / imgScale) });
                    if (($img.css('width').replace("px", "") > dim.width)) {
                    }
                    if ($img.css('height').replace("px", "") > dim.height) {
                        //alert('too high');
                    }
                    //*******************************

                    //$img.css('width', dim.width);
                    $('#portfolio-left').css({ 'height': (dim.height + 8) });
                    //$('#thumbs-wrapper').text(dim.height);
                }

                if (settings.imgSizeMode === 'fit width') {
                    $img.css('width', dim.width);
                    $('#portfolio-left').css({ 'height': (dim.height) });
                }

                settings.resizeLargeImage.call(this); // callback
            };

            function getStageDimensions() {
                var dimensions = {
                    width: $imgWrapper.width(),
                    height: $(window).height() - 160 //160 refers to footer
                }

                dimensions.scale = dimensions.height / dimensions.width;
                return dimensions;
            };

            function loadImage(anchorObj) {

                $img.stop()
                .animate({ opacity: 0 }, 'slow', function() {
                    $(this).attr('src', ''); // fix to make sure load is triggered in webkit browsers if image is cached
                    if (settings.imgFileHeight) {
                        $(this).attr('src', anchorObj.attr('href') + '/1000/' + settings.imgFileHeight);
                    } else {
                        $(this).attr('src', anchorObj.attr('href'));
                    }
                    $imgCaption.text(anchorObj.data('caption'));
                });
            };

            function preloadNextImage() {
                var imgurl = $('#thumbs')
                          .find('a.selected')
                          .next()
                          .attr('href'),
                 scale = settings.imgFileHeight ? '/1000/' + settings.imgFileHeight : '';
                jQuery.fn.preloadImages(imgurl + scale);
            };

            function centerThumbnail() {
                $wrapper = $thumbs.parent();
                $thumb = $thumbs.find('div.selected').find('a.selected');


                if ($.browser.opera) {
                    return false; // TODO: make this work for opera. attr('offsetLeft') does not really work in opera
                } else {
                    var scrollOffset = $thumbs.find('div.selected').find('a.selected').attr('offsetLeft'); // get offsetLeft of thumbnail
                    scrollOffset -= ($wrapper.width() / 2); // minus half width of wrapper container
                    scrollOffset += ($thumb.find('img').width() / 2); // add half width of thumbimage
                }


                scrollOffset = Math.round(Math.abs(Math.max(scrollOffset, 0))); // make sure not lower than 0 and absolute

                if (jQuery.scrollTo) { // use scrollTo plugin if available
                    $wrapper.stop().scrollTo(scrollOffset, 500, { axis: 'x' });
                    // debug.log('use scrollTo plugin');
                } else {
                    $wrapper.stop().animate({ scrollLeft: scrollOffset }, 'fast');
                    // debug.log('no scrollTo plugin');
                }
            };

        });

        $.fn.nexGallery.version = function() {
            return version;
        };

    };

})(jQuery);

// should be in an external plugin
jQuery.fn.preloadImages = function() {
    for (var i = 0; i < arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}

jQuery.fn.preloadContent = function() {
    for (var i = 0; i < arguments.length; i++) {
        jQuery("<div>").html(arguments[i]);
    }
}


