Event.observe(window, 'load', preLoadGallery);

var myArrPhoto = [];
var theFadeForm;

var _ID = 0;
var _URL = 1;
var _DIDA = 2;
var _ORIGINAL_WIDTH = 3;
var _ORIGINAL_HEIGHT = 4;
var _NEW_WIDTH = 5;
var _NEW_HEIGHT = 6;

var sumW = 0;

var totalRedim = 0;


var gAllImages = []; 

function checkForAllImagesLoaded() 
{ 
    for (var i = 0; i < gAllImages.length; i++) { 
        if (!gAllImages[i].complete) { 
            var percentage = i * 100.0 / (gAllImages.length); 
            percentage = percentage.toFixed(0).toString() + ' %'; 
            //userMessagesController.setMessage("loading... " + percentage); 
            //$('label_330').innerHTML = "loading... " + percentage;
            setTimeout('checkForAllImagesLoaded()', 20); 
            return; 
        }
    } 
    //userMessagesController.setMessage(globals.defaultTitle); 
    //$('label_330').innerHTML = "caricata";
    getNewDimentions(i);
}

function preLoadGallery(){

	gAllImages = []; 
    for (var i=0;i<myArrPhoto.length;i++) {
        var theImage = new Image(); 
        theImage.src = myArrPhoto[i][_URL];
        gAllImages.push(theImage); 
        setTimeout('checkForAllImagesLoaded()', 5); 
    }
	
 }


function getNewDimentions(contat){

	$('baseStrip').innerHTML = '';
	$('Preview').innerHTML = '';
	var newDim = '';
	totalRedim+=1;

	if (contat==totalRedim){
		if (navigator.userAgent.indexOf('Chrome')<0){
			for (var i=0;i<myArrPhoto.length;i++) {

				newDim = resizeImg(myArrPhoto[i][_URL],1500,70);
				
				myArrPhoto[i][_ORIGINAL_WIDTH] = newDim.split("_")[0];
				myArrPhoto[i][_ORIGINAL_HEIGHT] = newDim.split("_")[1];
				myArrPhoto[i][_NEW_WIDTH] = newDim.split("_")[2];
				myArrPhoto[i][_NEW_HEIGHT] = newDim.split("_")[3];
				
				if ((myArrPhoto[i][_ORIGINAL_WIDTH] == 0) || (myArrPhoto[i][_ORIGINAL_HEIGHT] == 0)){
					myArrPhoto.splice(i,1);
					i--;
				}
			
				newDim = '';
			}
		}

		if (myArrPhoto.length > 0){
			appendMyPhoto();	
		}else{
			if($('fadeCont')){
				$('fadeCont').hide();	
			}
		}
		
		//resize Stripe per Chrome
		if (navigator.userAgent.indexOf('Chrome')>-1){
			var imgBoxes = document.getElementsByClassName('stripIMG');
			sumW = 0;
			for (var i=0;i<myArrPhoto.length;i++) {
				newDim = resizeImgChrome(myArrPhoto[i][_URL],1500,70,imgBoxes[i]);
				imgBoxes[i].down().style.width = newDim.split("_")[2] + 'px';
				imgBoxes[i].down().style.height = newDim.split("_")[3] + 'px';
				
				//myArrPhoto[i][_ORIGINAL_WIDTH] = newDim.split("_")[0];
				//myArrPhoto[i][_ORIGINAL_HEIGHT] = newDim.split("_")[1];
				myArrPhoto[i][_NEW_WIDTH] = newDim.split("_")[2];
				myArrPhoto[i][_NEW_HEIGHT] = newDim.split("_")[3];
				
				sumW += parseInt(myArrPhoto[i][_NEW_WIDTH]) + 6;
				newDim = '';
				
			}
			pageLoaded(sumW);
		}
	}
}


function appendMyPhoto(){
	sumW = 0;
	for (var i=0;i<myArrPhoto.length;i++) {
		var myIMG;
		var new_divCont = document.createElement('div');
		new_divCont.className = 'stripIMG';
		myIMG = $('baseStrip').appendChild(new_divCont);
	
		var new_element = document.createElement('img');
		new_element.src = myArrPhoto[i][_URL];
		new_element.id = 'PG_' + myArrPhoto[i][_ID];
		Element.setStyle(new_element, {width:myArrPhoto[i][_NEW_WIDTH] + 'px', height:myArrPhoto[i][_NEW_HEIGHT] + 'px'});
		
		myIMG.appendChild(new_element);
		sumW += parseInt(myArrPhoto[i][_NEW_WIDTH]) + 6;
		
		//observe per stile img/////////////////////////////////
		Event.observe(myIMG, 'mouseover' , box.enter.bindAsEventListener(box, 'stripIMG'));
		Event.observe(myIMG, 'mouseout' , box.exit.bindAsEventListener(box, 'stripIMG'));
		////////////////////////////////////////////////////////

	}

	//First image ///////////////////////////////
	if (navigator.userAgent.indexOf('Chrome')>-1){	
		var myDim = resizeImgChrome(myArrPhoto[0][_URL],476,parseInt(myArrPhoto[0][_ORIGINAL_HEIGHT]),$('Preview'));
	}else{
		var myDim = resizeImg(myArrPhoto[0][_URL],476,parseInt(myArrPhoto[0][_ORIGINAL_HEIGHT]));
	}
	var new_element = document.createElement('img');
	new_element.src = myArrPhoto[0][_URL];
	if (parseInt(myArrPhoto[0][_ORIGINAL_WIDTH]) > 476){
		Element.setStyle(new_element, {width:myDim.split("_")[2] + 'px', height:myDim.split("_")[3] + 'px'});
	}else{
		Element.setStyle(new_element, {width:parseInt(myArrPhoto[0][_ORIGINAL_WIDTH]) + 'px', height:parseInt(myArrPhoto[0][_ORIGINAL_HEIGHT]) + 'px'});
	}
	$('Preview').appendChild(new_element);
	//////////////////////////////////////////////
	if (navigator.userAgent.indexOf('Chrome')<0){
		pageLoaded(sumW);
	}
}


function resizeImgChrome(myImg,myMaxW,myMaxH,myImgCont){
	var MaxW = myMaxW;
	var MaxH = myMaxH;
	var NewW;
	var NewH;
	var resizedH = false;
		if (myImgCont.down()){
			var dimensions = myImgCont.down().getDimensions();
			//alert(dimensions.width)
		}
    var height_immagine = 90;//myImgCont.height;
    var width_immagine = 70;//myImgCont.width;

	if ((height_immagine>MaxH) || (width_immagine > MaxW)){
			if (height_immagine != MaxH) {
				NewH = MaxH;
				NewW = (width_immagine * NewH) / height_immagine;
				resizedH = true;
			}
			
			if ((width_immagine != MaxW) && (!resizedH)) {
				NewW = MaxW;
				NewH = (height_immagine * NewW) / width_immagine;
			}

			if (NewW > MaxW) {
				NewW = MaxW;
				NewH = (height_immagine * NewW) / width_immagine;
			}
	}
	return parseInt(width_immagine) + '_' + parseInt(height_immagine) + '_' + parseInt(NewW) + '_'+ parseInt(NewH);
}


function resizeImg(myImg,myMaxW,myMaxH){
	var MaxW = myMaxW;
	var MaxH = myMaxH;
	var NewW;
	var NewH;
	var resizedH = false;

	var NewImmagine;
	var Immagine = myImg;
    NewImmagine = new Image();
    NewImmagine.src = Immagine;
    var height_immagine = NewImmagine.height;
    var width_immagine = NewImmagine.width;

	if (height_immagine != MaxH) {
		NewH = MaxH;
		NewW = (width_immagine * NewH) / height_immagine;
		resizedH = true;
	}

	if ((width_immagine != MaxW) && (!resizedH)) {
		NewW = MaxW;
		NewH = (height_immagine * NewW) / width_immagine;
	}
	
	return parseInt(width_immagine) + '_' + parseInt(height_immagine) + '_' + parseInt(NewW) + '_'+ parseInt(NewH);
//	document.getElementById('fotoSogg').setStyle({width:parseInt(NewW) + 'px', height:parseInt(NewH) + 'px'});

}





function pageLoaded() {

	if($('fadeCont')){
		$('fadeCont').hide();	
	}
	
	if ($('Box')!=null){
		//inizializza Move
		Move.init();
		Move.fps = 25; //imposta Frame al secondo (opzionale)
		Move.pps = -40; //imposta pixel al secondo (opzionale)
	} 
}

function lento() {
	Move.pps *= .80;
}

function veloce() {
	Move.pps *= 1.20;
}

function display(str) {
	$('display').update(str);	
	}
	
function displayImgBig(str) {
	$('displayImgBig').update(str);	
	}



function displayImgBigV(str) {
	//$('photoBox').update(str);
	//alert(str);
	$('Preview').innerHTML = str;
	if (navigator.userAgent.indexOf('Chrome')>-1){
		CHR();
	}
}
	
function CHR(){
	var t=setTimeout("KIK($('pip').width,$('pip').height)",1000);
}

function KIK(lookSizeW,lookSizeH){
	if (lookSizeW > 0){
		var MaxW = 670;
		var NewW;
		var resizedH = false;
	    var height_immagine = lookSizeH;
	    var width_immagine = lookSizeW;
	
		if (parseInt(width_immagine) > MaxW){
			NewW = MaxW;
			NewH = (height_immagine * NewW) / width_immagine;
			 $('pip').style.width = NewW + 'px';
			 $('pip').style.height = NewH + 'px';
		}
	}


}

var Move = {
	fps: 25,
	pps: -40,
	stripeWidth: 0,
	x: 0,
	status: 'stop',

	init: function(event) {
		var baseDiv = 'stripBox';

		this.stageWidth = Element.getDimensions($('Box')).width;
		if (this.stageWidth == 0) {
			this.stageWidth = 476;
		}
		this.stripeWidth = Element.getDimensions($('baseStrip')).width;
		this.stripeWidth = sumW;
		this.stripeHeight = Element.getDimensions($('baseStrip')).height;

		
		Event.observe($('Box'), 'click', Move.open.bindAsEventListener(Move));
		$('Box').show();

		if (this.stageWidth <= this.stripeWidth)
		{

			var repliche = Math.floor(this.stageWidth / this.stripeWidth);
			repliche = 2;

			//this.start();
			Event.observe($('Box'), 'mouseover', Move.freeze.bindAsEventListener(Move));
			Event.observe($('Box'), 'mouseout', Move.start.bindAsEventListener(Move));
			this.stripBoxWidth = (repliche+1) * this.stripeWidth;
			var newStripe = $('baseStrip').innerHTML;

			for (var i=0; i <= repliche; i++) {
				new Insertion.Bottom($(baseDiv), newStripe);
			}
			this.moveAgent = new PeriodicalExecuter(this.mover,1/this.fps);
		}
		
	},


	start: function(event) {
		var myDiv = Event.findElement(event, 'div');
		var destDiv =  $( (event.relatedTarget) ? event.relatedTarget : event.toElement ); //browser dipendent !!!
		if(destDiv == null)return; //nessun oggetto

		if((Element.childOf(destDiv,$('Box'))) || (Element.classNames(destDiv)=='BoxPreview')) return;
		this.moveAgent = new PeriodicalExecuter(this.mover,1/this.fps);
		this.status = 'play';
		Event.stop(event);
	},
	freeze: function(event) {
		//alert('Freez');
		var myDiv = Event.findElement(event, 'div');
		if((Element.childOf($(myDiv),$('Box'))) || (Element.classNames(myDiv)=='BoxPreview')) {
			this.moveAgent.stop();
			this.status = 'stop';
			Event.stop(event);
		}
		
		
	},
	mover: function() {
		//!! var offset = Move.pps / Move.fps; //va modificatoper unbinding corretto dobbiamo riferirci a this o riuscire a passare di parametri!!
		//alert(Move.stripeWidth);
		
		Move.x += Move.pps / Move.fps;
		if ( Move.x >= Move.stripeWidth*2 ) {
			Move.x -= Move.stripeWidth;
			//alert('reset1');
		}
		if ( Move.x <= -Move.stripeWidth ) {
			Move.x += Move.stripeWidth;
			//alert('reset2');
		}
		var newPos = Math.floor(Move.x) + 'px'
		
		Element.setStyle($('stripBox'),{
			left: newPos 
		});

	},
	open: function(event) {
		var elt = Event.findElement(event,'img');
		var newX, newY
		newX = 476
		var myIDIMG = $(elt).id;
		myIDIMG = myIDIMG.split('_')[1];
		var myPointer = -1;

		for (var i=0;i<myArrPhoto.length;i++) {
			if (myArrPhoto[i][0] == myIDIMG){
				myPointer = i;
				break;
			}
		}
		
		if (myPointer != -1) {
			if (myArrPhoto[myPointer][_ORIGINAL_WIDTH] > newX){
				newY = (myArrPhoto[myPointer][_ORIGINAL_HEIGHT] * newX) / myArrPhoto[myPointer][_ORIGINAL_WIDTH]
				newX = parseInt(newX) //+ 20;
				newY = parseInt(newY) //+ 28;
			}else{
				newX = myArrPhoto[myPointer][_ORIGINAL_WIDTH];
				newY = myArrPhoto[myPointer][_ORIGINAL_HEIGHT];
			}
			
			var myArr = $(elt).src.split('/');
			myArr[myArr.length-2] = '468_220';
			
			var imgTag = ""
			for (var i=0;i<myArr.length-1;i++) 
				imgTag += myArr[i] + '/';
			imgTag += myArr[myArr.length-1];
			
			if(($(elt).title) != ""){
				displayImgBigV('<img id="pip" src="'+imgTag +'" width="'+newX+'" height="'+newY+'"><div class="textB">' + $(elt).title + '</div>');
			}
			else{
				displayImgBigV('<img id="pip" src="'+imgTag +'" width="'+newX+'" height="'+newY+'">');
			}
		}

	}
}//Move








