﻿var carousel = {

    /* 'GLOBAL VARS' - Hidden from the global namespace */
    clickAllowed: 'true',
    imageArray: new Array(),
    slideDimension: 0,
    count: 0,
    imageCount: 0,
    selectedState: 0,
    direction: 'Top',
    constrainViewport: 'height',
    shiftDirection: 'bottom',
    selectedOffset: 0,

    /* Maps page integer in the url hash to html pages - this is essentially an associative array */
    pageMappings: {},

    /* Initialize the carousel */
    init: function(slideDimension, imagesWide, orientation, pageMappings, selectedOffset) {
        
        //Find out the carousel orientation
        if (orientation !== 'vertical') {
            if (orientation == 'horizontal') {
                carousel.direction = 'Left';
                carousel.constrainViewport = 'width';
                carousel.shiftDirection = 'right';
            }
        }
        
        //Allow the user to offset the carousel to a certain position 
        if (selectedOffset !== 0) {
            carousel.selectedOffset = selectedOffset;
        }
        
        //Plumb the user defined page mappings to the carousel object
        carousel.pageMappings = pageMappings;
        
        /* Preload the slider buttons that need it */
        var upArrow = new Image();
        upArrow.src = '../Images/carousel-images/btn_bck.gif';
        var ArrowDownDisabled = new Image();
        ArrowDownDisabled.src = '../Images/carousel-images/btn_forwards_disabled.gif';
        
        var viewportHeight = (slideDimension * imagesWide);
        var viewport = document.getElementById('viewport').style[carousel.constrainViewport] = viewportHeight + 'px';
        carousel.slideDimension = slideDimension;
        var container = document.getElementById('carouselSlider');
        var image = container.getElementsByTagName('a');

        /* Loop over the images*/
        for (var i = 0; i < image.length; ++i) {
            
            //if a selected state isn't set then set the selected state on the first image in the carousel
            if (carousel.selectedState === 0) {
                image[0].className = 'selected';
                carousel.selectedState = '1';
            }
            
            /* filter out whitespace nodes created by DOM's rubbish API */
            if (image[i].nodeType == 1) {
                
                /* Set images to correct size as they've been scaled down for the non-javascript version */
                var theImage = image[i].firstChild;
                theImage.setAttribute('width', '132');
                theImage.setAttribute('height', '157');
                
                /* Also switch the clicker images on - they're switched off by default for the non js version */
                $('.clicker').show();
                
                /* Hijack the links - replace them with a hash plus an integer */
                image[i].href = '#' + (this.imageCount + 1);
                
                /* Listen for Clicks */
                image[i].onclick = function(num) {
                    
                    /* Create a closure to the current iteration isn't lost */
                    return function() {
                        
                        /* Assign/de-assign selected classes on the carousel images */
                        $('a.selected').removeClass('selected');
                        image[num].className = 'selected';
                        var titleText = image[num].getAttribute('title');
                        var heading = $('#carousel h3').css({ 'display': 'none' });
                        heading.html(titleText);
                        heading.css({ 'display': 'block' });

                        /* Determine which html we need to load in */
                        var url = image[num].href;
                        var spl = url.split('#');
                        var target = carousel.pageMappings[spl[1]] + ' #carouselContent';
                        
                        /* Use jquery ajax engine to pull in relevant html */
                        $('#carouselContent').slideUp('normal', function() {
                            $('.loading').fadeIn();
                            $("#carouselContent").load(target, function() {
                                $('.loading').fadeOut();
                                $("#carouselContent").slideDown('normal');
                            });
                        })
                    }
                }(i)
                
                //This is a hack - yuck - if the user has come from the environment page then show the correct case-study
                if (location.href.indexOf('?referer=environment') !== -1) {
                    carousel.count = 1;
                    image[1].className = 'selected';
                    container.style.right = '154px';
                    $("#carouselContent").load("case-study1.aspx #carouselContent");
                }
                ++this.imageCount;
                this.imageArray.push(image[i]);
            }
        }
        
        /* Set up some initial states for the back/forward buttons */
        var ptag = document.getElementsByTagName('a');
        for (var i = 0; i < ptag.length; i++) {
            if ((" " + ptag[i].className + " ").toLowerCase().indexOf(" clicker ") != -1) {
                ptag[i].style.display = 'block';
                carousel.setControllerStates();
                
                /* Listen for clicks on the carousel buttons */
                ptag[i].onclick = function() {
                    if ((" " + this.className + " ").toLowerCase().indexOf(" disabled ") == -1) {
                        var buttonDirection = '';
                        var oldPos = 0;
                        var newPos = 0;
                        buttonDirection = this.id.replace('button_', '');
                        
                        /* Mechanism to stop the user breaking the carousel by clicking too quickly */
                        if (carousel.clickAllowed) {
                            carousel.clickAllowed = false;
                            
                            /* If the button isn't disabled */
                            if ((" " + this.className + " ").toLowerCase().indexOf(" disabled ") == -1) {
                                
                                /* Find out the old position of the carousel */
                                oldPos = Math.abs(container['offset' + carousel.direction]);
                                
                                /* Find out the direciton the user wants to go in */
                                if (buttonDirection == 'backwards') {
                                    --carousel.count;
                                    newPos = (oldPos - carousel.slideDimension);
                                } else if (buttonDirection == 'forwards') {
                                    ++carousel.count;
                                    newPos = (oldPos + carousel.slideDimension);
                                }
                                
                                /* Animate the carousel */
                                carousel.animate(container, carousel.shiftDirection, oldPos, newPos, 'easeInOutSine');
                                
                                /* Now deal with the back/forwards buttons again */
                                carousel.setControllerStates();
                                
                                /* Allow the user to click the buttons again after a certain period of time */
                                setTimeout('carousel.clickAllowed = true', 800);
                            }
                        }
                    }
                }
            }
        }
    },

    //set the disabled/enabled states for the carousel buttons
    setControllerStates: function() {
        var l = document.getElementById('button_backwards');
        var r = document.getElementById('button_forwards');
        if (carousel.count == 0) {
            l.className = 'disabled';
            l.style.cursor = 'default';
        } else if (carousel.count == (carousel.imageCount - 5)) {
            r.className += ' ' + 'disabled';
            r.style.cursor = 'default';
            buttonDirection = '';
            newPos = '';
            l.className = l.className.replace('disabled', ' ');
            l.style.cursor = 'pointer';
        } else if (carousel.count > 0) {
            r.className = l.className.replace('disabled', ' ');
            l.className = l.className.replace('disabled', ' ');
            r.style.cursor = 'pointer';
            l.style.cursor = 'pointer';
        }
    },


    /* Custom animate function */
    animate: function(obj, elm, begin, end, duration, fps, easing) {
        begin = parseFloat(begin);
        end = parseFloat(end);
        var change = end - begin;
        for (i = 1; i <= 16; i++) {
            (function() {
                increase = 0;
                var frame = i;
                function innerChangeWidth() {
                    var s = eval(carousel.easeInOutSine);
                    var increase = s(frame, begin, change, 16);
                    obj.style[elm] = increase + 'px';
                }

                timer = setTimeout(innerChangeWidth, 26 * frame);
            })();
        }
    },

    //Credit to Robert Penner for this easing equation...
    easeInOutSine: function(t, b, c, d) {
        return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
    }

};
