/*
 * @brief jQuery carousel
 * @author Matthew Turnbull (monkii.com.au)
 */
var carousel = {

    zindex: 1,
    isAutoAnimate: false,
    autoAnimateInterval: null,

    getCurrentImage: function() {

        return jQuery('.carousel .images img.current');

    },

    getFirstImage: function() {

        return jQuery('.carousel .images img').first()

    },

    getLastImage: function() {

        return jQuery('.carousel .images img').last()

    },

    init: function() {

        //Hide all images
        jQuery('.carousel .images img').hide();

        //Show first one
        carousel.getFirstImage().show().addClass('current');

        //Hide all headings
        jQuery('.carousel .headings div').hide();

        //Show first one
        jQuery('.carousel .headings div').first().show();

        //Start animating immediately
        carousel.startAutoAnimate();

    },

    showNext: function() {

        var image = carousel.getCurrentImage().next();

        if (jQuery(image).length == 0) {

            image = carousel.getFirstImage();

        }

        carousel.show(image);

    },

    showPrev: function() {

        var image = carousel.getCurrentImage().prev();

        if (jQuery(image).length == 0) {

            image = carousel.getLastImage();

        }

        carousel.show(image);

    },

    show: function(image) {

        //Stop any existing animations so we don't flood the browser

        jQuery('.carousel .images img').stop();

        //swap the .current class

        carousel.getCurrentImage().removeClass('current');

        image.addClass('current');

        //hide the new image with clipping

        image.css('clip', 'rect(0px, 0px, 425px, 0px)');

        //we can display it now (hidden with clipping)

        image.show();

        //place it on top

        carousel.zindex += 1;

        image.css('z-index', carousel.zindex);

        //lets see it!

        image.animate({
            'clip': 'rect(0px, 525px, 425px, 0px)'
        }, 1000, function() {

            //Animation is over
            //Reset all image clipping
            //This keeps animation smooth (otherwise browser gets overwhelmed with all clipping rules)

            jQuery('.carousel .images img[class!="current"]').css('clip', '').hide();

            jQuery(this).css('clip', '').show();

        });

        //And show the appropriate heading too

        var headingSelector = '#heading-' + image.attr('rel');
        
        jQuery('.carousel .headings div').hide();
        jQuery(headingSelector).show();

        //may need to stop / start animation
        //this avoids the image switching again too soon

        if (carousel.isAutoAnimate === true) {

            carousel.stopAutoAnimate();
            carousel.startAutoAnimate();

        }

    },

    startAutoAnimate: function() {

        if (carousel.isAutoAnimate === true) {

            //already going!
            return;

        }

        carousel.isAutoAnimate = true;

        carousel.autoAnimateInterval = setInterval(function() {

            carousel.showNext();

        }, 6000);

    },

    stopAutoAnimate: function() {

        if (carousel.isAutoAnimate === false) {

            //already stopped!
            return;

        }

        carousel.isAutoAnimate = false;

        clearInterval(carousel.autoAnimateInterval);

    },

    toggleAutoAnimate: function() {

        if (carousel.isAutoAnimate === true) {

            carousel.stopAutoAnimate();

        } else {

            carousel.startAutoAnimate();


        }

    }

};

jQuery(function() {

    jQuery('.carousel .controls .prev').click(function(ev) {

        ev.preventDefault();

        carousel.showPrev();

    });

    jQuery('.carousel .controls .next').click(function(ev) {

        ev.preventDefault();

        carousel.showNext();

    });

    jQuery('.carousel .controls .toggle').click(function(ev) {

        ev.preventDefault();

        carousel.toggleAutoAnimate();

    });

    carousel.init();

});


/*
 * @brief jQuery css clip animation support
 * @author hon2a
 * @version 1.0.0
 * Released under the MIT license.
 */
jQuery.fx.step.clip = function (fx) {
        if ($(fx.elem).is(':visible')) {
                if (fx.start == 0) {
                        var emCoef = ( parseInt($(fx.elem).css('fontSize')) * 1.333 ),
                                horizontalPercentCoef = $(fx.elem).width() / 100,
                                verticalPercentCoef = $(fx.elem).height() / 100,
                                regExp = {
                                        parseSize: /^(\d{1,}(\.\d+)?)(px|em|%)$/,
                                        stripRect: /rect\(([^)]*)\)/,
                                        splitRect: /[,\s]\s*/,
                                        matchAuto: /^auto$/
                                },
                                autoSizes = ['0px', '101%', '105%', '0px'];
                        var parseClipRect = function (rectStr) {
                                var rect = ((typeof rectStr != 'string') || (rectStr == '') || (rectStr == 'auto'))
                                        ? ['auto', 'auto', 'auto', 'auto']
                                        : rectStr.replace(regExp.stripRect, '$1').split(regExp.splitRect);
                                $.each(rect, function (i, size) {
                                        var matches = regExp.parseSize.exec(size.replace(regExp.matchAuto, autoSizes[i]));
                                        rect[i] = parseFloat(matches[1]);
                                        switch (matches[3]) {
                                                case 'em':
                                                        rect[i] *= emCoef;
                                                        break;
                                                case '%':
                                                        rect[i] *= ((i % 2) ? horizontalPercentCoef : verticalPercentCoef);
                                                        break;
                                        }
                                });
                                return rect;
                        };

                        fx.start = parseClipRect(fx.elem.style.clip);
                        fx.end = parseClipRect(fx.end);
                }

                var currentRect = [];
                for (var i = 0; i < 4; ++i) {
                        currentRect.push((fx.pos * (fx.end[i] - fx.start[i])) + fx.start[i]);
                }
                fx.elem.style.clip = 'rect(' + currentRect.join('px ') + 'px)';
        } else {
                fx.elem.style.clip = 'auto';
        }
}
