var Typewriter = new Class({
	Implements: [Options,Asset],//implements
        options: {
                    container: $$('body')[0],
                    message: '',
                    delay: 90,
                    cursor: 0,
                    variance: 200,
                    backChar: '|',
                    backDelay: 30
                    //imageSet:[],
                    //imagePath:'',
                    //currentImageIndex:0,
                    //imageContainer:''
                    },
        initialize: function(options){ this.setOptions(options); }, //initialization set options
        start: function() {//start the Typewriter
                            //this.options.imageSet.each( function(item, index, array){array[index]=path+item+'.png'} );
                            //this.options.imageSet = this.images(this.options.imageSet);
                            //(function(){ this.options.container.fade('toggle')}).delay(pace,this);
                            for(x = 0; x < this.options.message.length; x++)
                            {
                                var pace = (this.options.delay * x) + $random(0,this.options.variance);
                                var current = this.options.message.charAt(x);
                                if(current != this.options.backChar) //spit out the letter
                                {
                                        this.setLetter.delay(pace,this);
                                }
                                else
                                {
                                        this.deleteLetter.delay(pace + this.options.backDelay,this);
                                }

                            }
                            (function(){ this.options.container.fade('toggle')}).delay(pace,this); // häivyttää puhekuplan pois
        },
	setLetter: function() {//place the newest letter in the container
                            //this.options.imageContainer.set('src', this.options.imageSet[this.options.currentImageIndex].src);
                            //if(++this.options.currentImageIndex == this.options.imageSet.length)
                            //{
                                    //this.options.currentImageIndex=0;
                            //}
                            this.options.container.set('html',this.options.container.get('html') + '' + this.options.message.charAt(this.options.cursor));
                            this.options.cursor++;//increment cursor
        },
        deleteLetter: function() {//deletes a letters -- goes backward
                                this.options.container.set('html',this.options.container.get('html').substr(0,this.options.container.get('html').length - 1));
                                this.options.cursor++;//increment cursor
        }

});
window.addEvent('domready', function() {


var myRequest = new Request.JSON({
    url : 'index.php',
    method : 'get',
    link : 'chain',
    onSuccess : function(responseJSON, responseText)
    {
        var img = [];
        responseJSON.each(function(item,key){
            if($defined(item.src))
            {
                img[key] = item.src;
            }
            else if($defined(item.speech))
            {
                
            }
        });

        var images = new Asset.images(img, {
        onComplete: function(){
            images.each(function(item,key){
                images[key].setStyles(responseJSON[key]['style']);

            });
            setImage(document.getElements('div.figure')[[0,1].getRandom()],images);
           /* var figLayerImg = document.getElements('div.figure')[[0,1].getRandom()].getElements('img');
                figLayerImg.each(function(item,key){
                item.addClass('hide');
               if($defined(images[key]))
               {
                    images[key].replaces(item);
               }
            });*/
            //var rand = Math.floor(Math.random()*1000);
            //rand = rand<100?rand+100:rand;
            changeFigure.delay(Math.floor((800-200)*Math.random()) + 300);
        }
        });
    }
});
var setImage = function(container, images)
{
     //var figLayerImg = document.getElements('div.figure')[[0,1].getRandom()].getElements('img');
     var currImages = container.getElements('img'),c,d;
     for(var i; i<3; i++)
     {
        c = $defined(currImages[i]);
        d = $defined(images[i]);
        if(c && d)
        {
            images[i].replaces(i);
        }
        else
        {
            
        }

     }
     var currImages = container.getElements('img');
                images.each(function(item,key){
     
                                                    if($defined(currImages[key]))
                                                    {
                                                       images[key].replaces(item);
                                                    }
            });
}//setImage ends
var changeFigure = function(){
    var toPost = {newFigure : ['men','women'].getRandom()};
    var images = myRequest.send('newFigure='+['men','women'].getRandom());
};
var setImages = function(images)
{
    var figLayerImg = document.getElements('div.figure img');
    figLayerImg.each(function(item,key){images[key].replaces(item);});
    if($defined(images[key+1]))
    {
        container.inject();
    }
}
//var Site = { counter: 0 };
//var addCount = function(){ this.counter++; };
//changeFigure.periodical(2000); //Will add the number of seconds at the Site.

return changeFigure();
/*var anim = new Hash({
			mMEtuC:1000,
			mMEtuA:1000,
			mMEtuHei:1200,
			speak:{images:{mTHead1Eteen:200,mTHead2EteenPuhe:200},speach:"HEI, MITÄ PITÄISIT VAATEKAUPASTA JOSSA VAATTEET ON VALMISTETTU\nSINUN VARTALON MUKAAN.\nSYKSYLLÄ TÄHÄN AVATTAVA VAATEKAUPPA\nMITOITTAA VAATTEET SINUN|||||| JUURI SINUN\nVARTALON MITTOJEN MUKAAN.",ddelay:90,variance:200},
			mMEtuA:1000,
			mMEtuC:1000,
			mTHead4OikeallePuhe:0
			});
*/
//anim = JSON.encode(anim);
//anim = JSON.decode(anim);
var path = 'image/figures/',path2 = path+'head/',I = [],p,picSet=1;

var toLoad = function(obj){
	//obj = $(obj);
	//alert(obj);
	obj.each(function(item,key){
			//alert(item);
			if($type(item)=='number'){
				
				I.include((key.contains('Head')?path2:path+picSet+'/'+key+'.png'));
			}
			//else if($type(item)=='object'){
			//	toLoad(item["images"]);
			//}
})};
//toLoad(anim);
//alert(I);
});/*.addEvent('load', function() {
	
	
	set.each(function(item, index, array){array[index]=path+item+'.png'});
	
	set = new Asset.images(set,{
    											onComplete: function(){
        											alert('All images loaded!');
													//var$('div.figure');
													//var top = $('head');
													//for(i in picSet[0])
													//{
													//	alert(i+' on '+picSet[0][i]);
													//}
													
													//var ind=0,t=0;
													//function animate(){
													//	var t = 0;
													//		picSet.each(function(item){ t+=400; (function(){top.set('src', item.src); }).delay(t) });
													//	}
														
													//function A(){ alert(picSet); t=t>=0?0:t++; top.set('src', picSet[t].src)};
													//A();
													//top.set('src', picSet[10].src);
													//animate.periodical(800, animate);
												}});
});
*/
//once the DOM is ready

window.addEvent('load', function() {

//var ind=0,t=0;
			//picSet = ['wHeadEteen','wHeadEteenPuhe'/*,'wHeadOikeallePuhe'*/];
//var top = $('head'),t=0;

//function A(){ t = t>1?0:t++; alert(t);/*top.set('src', picSet[t].src);*/ };
//A();
/*roundedRect(
			$('speech'),
			2,  // x
			4,  // y
			100-2*2,         // width
			100-2*4,        // height
			10,                 // corner radius
			[255, 51, 0]      // Footer color
);*/
			//class is in
		
			
			//usage
			var figure = document.getElement('div.figure'),
			image = figure.getElement('img[src*=Head]'),w = figure.getStyle('width');
			//alert(image)
			var speech = new Element('div',{'class':'speech','id':'speech','styles':{top:'7em'}}).inject(figure);
			//alert();
			//var speech2 = new Element('div',{styles:{background:'url(image/balloonCenter.png)'}});
			//speech.adopt(new Element('img',{src:'image/balloonTop.png',styles:{width:w,position:'static'}}),speech2,new Element('img',{src:'image/balloonBottom.png',styles:{width:w,position:'static'}}));
			
			//speech.inject(figure);
			//var balloon = new Element('img',{src:'image/balloon.png',styles:{position:'absolute',left:'0em',top:'0em',width:'100%',height:'100%'}}).inject(speech)
			
			
			
			var t = new Typewriter({
				container: speech,
				message: "HEI, MITÄ PITÄISIT VAATEKAUPASTA JOSSA VAATTEET ON VALMISTETTU\nSINUN VARTALON MUKAAN.\nSYKSYLLÄ TÄHÄN AVATTAVA VAATEKAUPPA\nMITOITTAA VAATTEET SINUN|||||| JUURI SINUN\nVARTALON MITTOJEN MUKAAN."
				//delay:90,
				//variance:200,
				//backChar: '|',
				//backDelay:30,
				//imageSet: ['mTHead1Eteen','mTHead2EteenPuhe'],
				//imagePath:'image/figures/head/',
				//imageContainer: image
			}).start();
                        
			
});

/*
var roundedRect = function(ctx, x, y, width, height, radius, rgb, a)
{
		ctx.fillStyle = 'rgba(' + rgb.join(',') + ',' + a + ')';
		ctx.beginPath();
		ctx.moveTo(x, y + radius);
		ctx.lineTo(x, y + height - radius);
		ctx.quadraticCurveTo(x, y + height, x + radius, y + height);
		ctx.lineTo(x + width - radius, y + height);
		ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius);
		ctx.lineTo(x + width, y + radius);
		ctx.quadraticCurveTo(x + width, y, x + width - radius, y);
		ctx.lineTo(x + radius, y);
		ctx.quadraticCurveTo(x, y, x, y + radius);
		ctx.fill(); 
};
//roundedRect(2,2,300,300,10l,[200,200,200])
/*
ctx,                          // context
			shadowBlur - shadowOffset.x,  // x
			shadowBlur - shadowOffset.y,  // y
			width - shadowBlur2x,         // width
			height - shadowBlur2x,        // height
			cornerRadius,                 // corner radius
			this.options.bodyBgColor      // Footer color
*/

