﻿var projectsController = (function () {
    // variables
    var fadeDelay = 900,
        fadeDuration = 550,
        imageData,
		images = [],
        imageUrls = [],
        imageWidth = '124px',
        imageHeight = '70px',
        imageBasePath,
        indexes = [],
		isInitialized = false,
		isLoaded = false,
		xmlhttp,
        viewer,
		maxRows = 4,
		maxColumns = 5,
        currentFadeIndex = 0,
        timeoutId,
    // methods
		init,
		getImageData,
		xmlLoad_success,
        fadeImage,
        fadeInCompleted,
        fadeOutCompleted;

    //
    // constructor
    // 
    $(document).ready(function () {        
        init();
    });

    // 
    // init function
    //
    init = function () {
        viewer = $("#viewer");
        getImageData();
    };

    // 
    // load image data
    // 
    getImageData = function () {
        $.ajax({
            type: "GET",
            url: "project_book.xml",
            dataType: "xml",
            success: xmlLoad_success
        });
    };

    //
    // event handler for the getImageData AJAX call
    //
    xmlLoad_success = function (xml) {
        // set image data array
        imageData = $(xml).find("image");

        // set image base path
        imageBasePath = $(xml).find("url").text();

        // variables
        var noItems = maxColumns * maxRows,
            currentIndex;

        // load image urls
        for (y = 0; y < imageData.length; y++) {
            imageUrls.push(imageBasePath + $(imageData[y]).text());
        }

        // create ul
        var ul = document.createElement('ul');
        $(ul).attr({
            id: 'projectsGallery',
            style: 'margin:0px;padding:0px;list-style-type:none;'
        });

        // grab first images
        for (i = 0; i < noItems; i++) {
            // get a new random index
            currentIndex = Math.min(Math.floor(Math.random() * imageUrls.length), imageUrls.length);

            // create li element
            var li = document.createElement('li');
            $(li).attr('style', 'float:left;width:' + imageWidth + ';height:' + imageHeight + ';display:block;');

            // create image element
            var img = document.createElement('img');
            $(img).attr({
                id: 'img' + i.toString(),
                src: imageUrls[currentIndex]
            });

            // add children
            li.appendChild(img);
            ul.appendChild(li);

            // remove the item from the array
            imageUrls.splice(currentIndex, 1);

            // add image id to the array
            images.push("#img" + i.toString());

            // add index
            indexes.push(i);
        }

        // variables to shuffle the array
        var tmp, current, top = indexes.length;

        // shuffle algorithm to shuffle index order
        if (top) while (--top) {
            current = Math.floor(Math.random() * (top + 1));
            tmp = indexes[current];
            indexes[current] = indexes[top];
            indexes[top] = tmp;
        }

        // add ul to the div
        viewer.append(ul);

        // set first image index to fade
        currentFadeIndex = indexes[0];

        // remove current index
        indexes.splice(0, 1);

        // push it back onto the array
        indexes.push(currentFadeIndex);

        // set timeout
        timeoutId = setTimeout(fadeImage, fadeDelay);
    };

    //
    // fade out the current image
    //
    fadeImage = function () {
        // fade out the current image
        $(images[currentFadeIndex]).fadeOut(fadeDuration, fadeOutCompleted);

        // clear current timeout
        clearTimeout(timeoutId);
    };

    //
    // fade in completed handler
    //
    fadeInCompleted = function () {
        // set next image index to fade
        currentFadeIndex = indexes[0];

        // remove current index
        indexes.splice(0, 1);

        // push it back onto the array
        indexes.push(currentFadeIndex);

        // reset timeout
        timeoutId = setTimeout(fadeImage, fadeDelay);
    };

    //
    // fade out completed handler
    //
    fadeOutCompleted = function () {
        // get a new random index
        var currentIndex = Math.min(Math.floor(Math.random() * imageUrls.length), imageUrls.length);

        // var last url
        var tempUrl = $(images[currentFadeIndex]).attr('src');

        // update src attribute
        $(images[currentFadeIndex]).attr('src', imageUrls[currentIndex]);

        // remove the item from the array
        imageUrls.splice(currentIndex, 1);

        // push old url onto the array
        imageUrls.push(tempUrl);

        // fade in new image
        $(images[currentFadeIndex]).fadeIn(fadeDuration * 2, fadeInCompleted);
    };

    //
    // start and stop functions
    //
    return {
        start: function () {
            if (!isInitialized && isLoaded) {
                init();
            }

            isInitialized = true;
        },

        stop: function () {

        }
    };

} ());
