// Copyright (c) 2006 Sébastien Grosjean (http://box.re, http://zencocoon.com)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// VERSION 0.5.1



// ///////////////////////////////////////////////////////////////////////
//
//
// Global Variables
//
var timerId = null;
var secs = 0;
//
// Structure
// simpleSlideArray = new Array(imageId,
//                              new Array(new Array(img_id, file1_path, loader, loaded?),
//                                        new Array(img_id, file2_path, loader, loaded?),
//                                        ...),
//                              actualImage);
// simpleSlideHash[simpleSlideId] => simpleSlideArray;
//
var simpleSlideHash = Hash;

//
// list of all the simpleSlides Ids
var simpleSlideArray = new Array();

// ----------------------------------
//
//
// SimpleSlide Class Declaration
// - initialize()
// - loadImagesPath()
// - response()
// - preloadImages()
// - startLooping()
//
var SimpleSlide = Class.create();

SimpleSlide.prototype = {
    //
    // initialize()
    //
    initialize: function() {
        var divs = $$('div.' + classToLoad);
        
        for (var i = 0; i < divs.length; i++) {
            var div = divs[i];
            var images = div.getElementsByTagName('img');
            var image = images[0];
            
            // get simpleSlideId that will need to be loaded
            var simpleSlideId = div.id.replace(classToLoad + '-', '');
            
            // set id to the first image
            image.id = classToLoad + '-' + simpleSlideId + '-1';
            
            // set div size
            div.style.height = image.offsetHeight + 'px';
            div.style.width = image.offsetWidth + 'px';
            
            // set image position to absolute
            image.style.position = 'absolute';
            
            // save simpleSlideId
            simpleSlideArray.push(simpleSlideId);
            
            // init global variable simpleSlideHash
            simpleSlideHash[simpleSlideId] = new Array(div.id,
                                                       new Array(new Array(image.id, image.src, null, 1)),
                                                       0);
                                                       
            // load images path from simpleSlideId
            this.loadImagesPath(simpleSlideId);
        }
        this.startLooping();
    },
    
    //
    // loadImagesPath()
    // 
    loadImagesPath: function(simpleSlideId) {
        new Ajax.Request(urlUsedForLoadingImages,
                         {asynchronous: true, evalScripts: true,
                          onComplete: function(request) {
                            mySimpleSlide.response(simpleSlideId, request);
                          }, parameters: 'simpleslideid='+simpleSlideId});
    },
    
    //
    // response()
    //
    response: function(simpleSlideId, request) {
        var images = request.responseText.split(',');
        
        // loop through images to save them in the global variable simpleSlideHash
        for (var i = 0; i < images.length; i++) {
            var image = images[i];
            
            // save image location and set loaded? to zero
            simpleSlideHash[simpleSlideId][1].push(new Array(classToLoad + '-' + simpleSlideId + '-' + (i + 2),
                                                             slidesLocation + image));
        }
        this.preloadImages(simpleSlideId);
    },
    
    //
    // preloadImages()
    //
    preloadImages: function(simpleSlideId) {
        // loop through new images
        for (var i = 1; i < simpleSlideHash[simpleSlideId][1].length; i++) {
            var image = simpleSlideHash[simpleSlideId][1][i];
            
            // init preloader
            simpleSlideHash[simpleSlideId][1][i][2] = new Image();
            
            // action to do once image loaded
            simpleSlideHash[simpleSlideId][1][i][2].onload = function() {
                var array = this.id.replace(classToLoad + '-', '').split('-');
                var simpleSlideId = array[0];
                var imageId = array[1] - 1;
                
                // add image to the DOM but actually still not displayed, it wil be done later
                var objImage = document.createElement("img");
                objImage.setAttribute("id", this.id);
                objImage.style.display = 'none';
                objImage.setAttribute("src", this.src);
                objImage.style.position = 'absolute';
                // objImage.setAttribute("style", "display: none; position: absolute;");
                $(simpleSlideHash[simpleSlideId][0]).appendChild(objImage);
                
                // save this image as loaded
                simpleSlideHash[simpleSlideId][1][imageId][3] = 1;
            }
            
            // set image to load
            simpleSlideHash[simpleSlideId][1][i][2].src = image[1];
            
            // use id to keep variables for after loading
            simpleSlideHash[simpleSlideId][1][i][2].id = image[0];
        }
    },
    
    //
    // startLooping()
    //
    startLooping: function() {
        timerId = self.setTimeout("mySimpleSlide.startLooping()", 1000);
        secs += 1;
        
        if (secs == delay) {
            // init again to loop again
            secs = 0;
            // loop through simpleSlides
            for (var i = 0; i < simpleSlideArray.length; i++) {
                var simpleSlideId = simpleSlideArray[i];
                var simpleSlide = simpleSlideHash[simpleSlideId];
                var actual = simpleSlide[2];
                var previus = actual;
                                  
                // update actual
                if (simpleSlide[1][actual + 1]) {
                    if (simpleSlide[1][actual + 1][3] == 1) {
                        // keep actual as previus
                        previus = actual;
                        // save new actual
                        simpleSlide[2] += 1;
                        actual = simpleSlide[2];
                    }
                } else {
                    if (simpleSlide[1][0][3] == 1) {
                        // keep actual as previus
                        previus = actual;
                        // save new actual
                        simpleSlide[2] = 0;
                        actual = 0;
                    }
                }
                // be sure that a new image where loaded
                if (actual != previus) {
                    // launch fading/appearing effects
                    new Effect.Parallel(
                        [ new Effect.Fade( simpleSlide[1][previus][0], { sync: true, duration: duration }),
                          new Effect.Appear( simpleSlide[1][actual][0], { sync: true, duration: duration }) ],
                        { duration: duration }
                    );
                }
            }
        }
    }
}

function initSimpleSlide() { mySimpleSlide = new SimpleSlide(); }
Event.observe(window, 'load', initSimpleSlide, false);