﻿var ImageRotater = Class.create();
ImageRotater.prototype = {
    initialize: function(divID,image_hashes,speed){
        try{
            var im;
            this.rotation = 0;
            this.images = [];
            this.div = $(divID);
            
            if(!this.div)
            {
                alert("Could not find div for cover images");
                return;
            }
            
            //no images. exit
            if(image_hashes.length==0)
                return;
            
            //one image insert and exit
            if(image_hashes.length==1){
                im = this.createImage(images[0]);
                this.div.insert(im);
                return;
            }
            var me = this;
            image_hashes.each(function(h,index){
                im = me.createImage(h);
                if(index>0)
                    im.hide();
                me.images[me.images.length] = im;
                me.div.insert(im);
            });
            
            
            this.current = this.images[0];
            this.current.show();
            this.div.style.height = this.current.getHeight()+"px";
            this.current.observe("load",function(){me.div.style.height = me.current.getHeight()+"px";});
            this.timer = setInterval(function(){imageRotater.rotate()},speed*1000);
        }
        catch(Error){alert(Error.message)}
    },
    
    rotate: function(){
        this.div.style.height = this.div.getHeight()+"px";
    
        this.images.each(function(img){
            if(img!=imageRotater.current)
            {
                img.hide();
                img.style.zIndex=1;
            }
        });
        
        this.rotation+=1;
        if(this.rotation>=this.images.length)
            this.rotation=0;
        var next = this.images[this.rotation];
        
        this.current.style.zIndex=2;
        next.style.zIndex=3;
        new Effect.Appear(next,{duration:1});
        this.current = next;
        
        this.div.style.height = this.current.getHeight()+"px";
    },
    
    createImage: function(image_hash){
        var img = new Element("img",{src:image_hash["url"]});
        img.title = image_hash["title"];
        img.alt = image_hash["title"];
        if(image_hash["description_url"])
            img.longDesc = image_hash["description_url"];
        return img
    }
    

};