var timerswitch=1;// enable image rotation on startup
var resizeblack=0;// disable stretch of black
var footerpos=0;//footer outside tienifooter
var timeoutID='';//timour variable for slide
var firstcycle=1;// first cycle for "come lavoriamo" (disply text)

window.addEvent('domready', function() {
	
	// reSize Listner
	window.addEvent('resize',function(e){
		reDraw();
	});
	
	// Log Out
	if(gup('alert')=='logout')alert('Sessione Terminata');

	// Initialize
	$('myForm').setStyle('display', 'none');
	var myForm = new Fx.Style('myForm', 'opacity');
	myForm.start(0.0);
	var preloadedImages = [
		'img/prev.gif',
		'img/next.gif',
		'img/case_history.gif',
		'img/spinner.gif',
		'img/spinner_grey.gif',
		'slimbox/nextlabel.gif',
		'slimbox/prevlabel.gif',
		'slimbox/loading.gif',
		'slimbox/closelabel.gif',
		'img/data_bg.jpg'
	];
	var myImages = new Asset.images(preloadedImages, {
	    onComplete: function(){
			$('carousel').removeClass('loading');// Remove spinner
			if(	(gup('p')=='links')||// iframe exception
				(gup('p')=='condo')
			){
				var bFrame = new Element('iframe',{
					'id': 'bFrame',
					'src': 'frame.php?f='+gup('p')+'&risp='+gup('risp'),
					'height': 397,
					'width': 849,
					'frameborder': 0,
					'scrolling': 'auto'
				});
				bFrame.injectInside('carousel');
			} else {
				switch (gup('p')){
				   case 'spazi':
				      spaziFrame(gup('p'));
				      break;
				   case 'admin':
				      spaziFrame(gup('p'));
				      break;
				   case 'come':
				      refreshimg(1);
				      break;
				   case '':
				      refreshimg(1);
				      break;
				   default : refresh(1);
				}
				//if((gup('p')=='spazi')||(gup('p')=='admin')){spaziFrame(gup('p'))} else {refresh(1);}
			}
	    }
	});

	// Display Log-In Form
	$('loginbutton').addEvent('click', function(action){
		$('loginbutton').setHTML('');
		$('myForm').setStyle('display', 'block');
		myForm.start(1.0);
    });

	// Log-In
	$('myForm').addEvent('submit', function(e) {
		$('myForm').setStyle('display', 'none');// Hide Form
		$('login').addClass('loading_grey');// Show spinner
		new Event(e).stop();
		$('myForm').send({// Send logout request
			update: $('login'),
			onComplete: function(){
				$('login').removeClass('loading_grey');// Remove spinner
			}
		});
	});
	
	// Footer links
/* 	$('footRac').addEvent('click', function(){
	    storicoUrl.sort(function() {return 0.5 - Math.random();});
		Slimbox.open(storicoUrl,0); 
	}); */
	//$('footCon').addEvent('click', function(){Condominio('f');});
	//$('footSca').addEvent('click', function(){window.open('ARP_brochure.pdf', 'Brochure');});

});// end DOM

// Carousel routine
function refresh(nn){
	if(timerswitch==1){//check if ritation is enabled
		immagine = assUrl(nn,'i');// Prepare image url
		ele = new Array();dat = new Array();// Prepare Div elements
		np = parseFloat(nn)+1;nm = parseFloat(nn)-1;// Prepare slide numbers
		$('carousel').empty().addClass('loading');// Display spinner
		new Asset.images([immagine], {// Load image
			onProgress: function(){
				ele[1] = this;
			},
		    onComplete: function(){
				ele[3] = new Element('a',{'href': 'javascript:refresh(\''+np+'\')','class': 'nxt'})
				ele[2] = new Element('a',{'href': 'javascript:refresh(\''+nm+'\')','class': 'prv'})
				ele[0] = new Element('div',{'id': 'data'})
				//ele[4] = new Element('a',{'href': '?p='+gup('p')+'&case=1','class':'case'})
				// Case button not in Come Lavoriamo
				if((gup('p')!='come')&(gup('p')!=''))ele[4] = new Element('a',{'href': 'javascript:iFrame()','class':'case'})
				dat[0] = new Element('span',{'class': 'data_title'})
				dat[1] = new Element('span',{'class': 'data_address'})
				dat[2] = new Element('span',{'class': 'data_desc'})
				var jSonRequest = new Json.Remote(assUrl(nn,'d'), {
					onComplete: function(response){
						if(timerswitch==1){// check rotation active
							// Prepare spinner fade out
							var fadeout = new Fx.Style('carousel','opacity', {
								onComplete: function(){
									// Inject elements
									ele.each(function(tag){tag.injectInside('carousel');});
									dat.each(function(tag){tag.injectInside('data');});
									dat[0].setHTML(response.title+"<br>");
									dat[1].setHTML(response.address+"<br><br>");
									dat[2].setHTML(response.desc+"<br>");
									$('carousel').removeClass('loading');// Remove spinner
									new Fx.Style('carousel', 'opacity').start(1.0);// Fade in
									timeoutID=setTimeout('refresh_cast('+np+');', 5000);// Slide every 5 secs
								}
							}).start(0.0);// Start spinner fade out;
						}
					}
				}).send();
		    }
		});
	}
}

// Carousel routine image only
function refreshimg(nn){
	ele = new Array();dat = new Array();img = new Array();// Prepare Div elements
	np = parseFloat(nn)+1;nm = parseFloat(nn)-1;// Prepare slide numbers
	if(timerswitch==1){//check if rotation is enabled
		if(firstcycle==1){
			// display text
			firstcycle=0;
			$('carousel').empty();
			//$('carousel').empty().addClass('loading');// Display spinner
			ele[0] = new Element('div',{'id': 'imgframe'});
			ele[1] = new Element('div',{'id': 'data'});
			ele.each(function(tag){tag.injectInside('carousel')});
			dat[0] = new Element('span',{'class': 'data_title'});
			dat[1] = new Element('span',{'class': 'data_address'});
			dat[2] = new Element('span',{'class': 'data_desc'});
			var jSonRequest = new Json.Remote(assUrl(nn,'d'), {
				onComplete: function(response){
					if(timerswitch==1){// check rotation active
						// Prepare spinner fade out
						var fadeout = new Fx.Style('data','opacity', {
							onComplete: function(){
								// Inject elements
								//ele.each(function(tag){tag.injectInside('carousel');});
								dat.each(function(tag){tag.injectInside('data');});
								dat[0].setHTML(response.title+"<br>");
								dat[1].setHTML(response.address+"<br><br>");
								dat[2].setHTML(response.desc+"<br>");
								//$('carousel').removeClass('loading');// Remove spinner
								new Fx.Style('data', 'opacity').start(1.0);// Fade in
							}
						}).start(0.0);// Start spinner fade out;
					}
				}
			}).send();
		}
		// refresh image
		immagine = assUrl(nn,'i');// Prepare image url
		$('imgframe').empty().addClass('loading');// Display spinner
		new Asset.images([immagine], {// Load image
			onProgress: function(){
				eccola = this;
			},
		    onComplete: function(){
				var fadeout = new Fx.Style('imgframe','opacity', {
					onComplete: function(){
						// Inject elements
/* 						img[1] = new Element('a',{'href': 'javascript:refresh(\''+np+'\')','class': 'nxt'})
						img[2] = new Element('a',{'href': 'javascript:refresh(\''+nm+'\')','class': 'prv'})
						img.each(function(tag){tag.injectInside('carousel');}); */
						eccola.injectInside('imgframe');
						$('imgframe').removeClass('loading');// Remove spinner
						new Fx.Style('imgframe', 'opacity').start(1.0);// Fade in
						timeoutID=setTimeout('refreshimg_cast('+np+');', 5000);// Slide every 5 secs
					}
				}).start(0.0);// Start spinner fade out;
		    }
		});
	}
}


function refresh_cast(np){
	if(timerswitch==1)refresh(np);// check if image rotation is active
}

function refreshimg_cast(np){
	if(timerswitch==1)refreshimg(np);// check if image rotation is active
}

// Assemble url
function assUrl(n,t){
	// n = numero slide, i=image, d=data, c=case history, f=form condominio, p = pagina
	if(gup('p')=='')ppp='come';else ppp=gup('p');
	url = 'ciclo1.php?t='+t+'&n='+n+'&r='+Math.random()+'&p='+ppp;
	return url;
}

// Log-Out for same-page
/* function Logout(){
	$('login').empty().addClass('loading_grey');
	var doStuff = new Ajax('logout.php', {// Prepare logout request
		update: $('login'),
		onComplete: function() {
			$('login').removeClass('loading_grey');// Remove spinner
		}
	}).request();// Log out
} */

// Extract Get vars
function gup(name){
	name = name.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
	var regexS = '[\\?&]'+name+'=([^&#]*)';
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if(results == null)	return ''; else	return results[1];
}

// Get window Height
function windowHeight() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return myHeight-240;/* 317-77 */
}

// iFrame Case History
function iFrame(){
	timerswitch=0;// disable image rotation
	clearTimeout(timeoutID);
	$('carousel').empty().addClass('loading');// Display spinner
	new Fx.Style('carousel', 'height').start(397,windowHeight());
	new Fx.Style('black', 'height').start(397,windowHeight());
	
	var loadFrame = new Ajax('frame.php?f=spazi&case_cat='+gup('p'), {
		method: 'get',
		onComplete: function() {
			var iFrame = new Element('iframe',{
				'id': 'myFrame',
				'src': 'frame.php?f=spazi&case_cat='+gup('p'),
				'height': windowHeight(),
				'width': 849,
				'frameborder': 0,
				'scrolling': 'auto'
			});
			$('carousel').removeClass('loading');// Remove spinner
			iFrame.injectInside('carousel');
			new Fx.Style('carousel', 'opacity').start(1.0);// Fade in
		}
	}).request();// Log out	
	
	resizeblack=1;// enable stretch of black
}

// reDraw
function reDraw(){
	if(resizeblack==0){
		//footer position
		var cobra=windowHeight()+240-83;
		if(cobra<554){
			//alert('ok');
			if(footerpos==0){
				footerpos=1;
				//var posizionew=cobra-554;
				//new Fx.Style($('white'), 'bottom').set(posizionew);
				$('tienifooter').adopt('white');
			}
		}else{
			if(footerpos==1){
				footerpos=0;
				//var clone = $('white').clone().injectAfter('supertop');
				$('white').injectAfter('supertop');
				//$('tienifooter').setHTML('') //the innerHTML of tienifooter now is null
			}		
		};
	}else{
		// resize black
		var res = [$('carousel'),$('black'),$('myFrame')];
		res.each(function(tag){
			new Fx.Style(tag, 'height').set(windowHeight());
		});
	}
}

// Amministratore di Condominio
function Condominio(type){
	timerswitch=0;//Disable slide show
	clearTimeout(timeoutID);
	if(resizeblack==1){
		resizeblack=0;//Disable stretch of black	
		new Fx.Style('carousel', 'height').start(windowHeight(),397);
		new Fx.Style('black', 'height').start(windowHeight(),397);
	}
	var doStuff = new Ajax('ciclo1.php?t='+type+'&p='+gup('p'), {// Prepare condominio page request
		update: $('carousel'),
		onRequest: function() {
       		$('carousel').empty().addClass('loading');
    	},
		onComplete: function() {
			$('carousel').removeClass('loading');// Remove spinner
		}
	}).request();// Log out
}

// Spazi Disponibili Frame
function spaziFrame(quale){
	if (quale=='spazi')quale='spazi_disponibili';
	$('carousel').empty().addClass('loading');// Display spinner
	new Fx.Style('carousel', 'height').start(397,windowHeight());
	new Fx.Style('black', 'height').start(397,windowHeight());
	
	var loadFrame = new Ajax('frame.php?f='+quale, {
		method: 'get',
		onComplete: function() {
			var iFrame = new Element('iframe',{
				'id': 'myFrame',
				'src': 'frame.php?f='+quale,
				'height': windowHeight(),
				'width': 849,
				'frameborder': 0,
				'scrolling': 'auto'
			});
			$('carousel').removeClass('loading');// Remove spinner
			iFrame.injectInside('carousel');
			new Fx.Style('carousel', 'opacity').start(1.0);// Fade in
		}
	}).request();// Log out	
	
	resizeblack=1;// enable stretch of black
}

// Database History Pics
storicoUrl = [['ARP_storico/arco_di_traiano.jpg'],['ARP_storico/baci-perugina.jpg'],['ARP_storico/BELPAESE.jpg'],['ARP_storico/bernini.jpg'],['ARP_storico/bici.jpg'],['ARP_storico/bmp.jpg'],['ARP_storico/bnl.jpg'],['ARP_storico/bulli-e-pupe.jpg'],['ARP_storico/campari.jpg'],['ARP_storico/camparivoxson.jpg'],['ARP_storico/cocacola.jpg'],['ARP_storico/esso.jpg'],['ARP_storico/fiat.jpg'],['ARP_storico/ford.jpg'],['ARP_storico/il-tempo.jpg'],['ARP_storico/martini.jpg'],['ARP_storico/motta.jpg'],['ARP_storico/motta2.jpg'],['ARP_storico/NESTLe.jpg'],['ARP_storico/pan.jpg'],['ARP_storico/pan_am2.jpg'],['ARP_storico/panam.jpg'],['ARP_storico/paschi.jpg'],['ARP_storico/philips.jpg'],['ARP_storico/psdi.jpg'],['ARP_storico/recoaro.jpg'],['ARP_storico/salome.jpg'],['ARP_storico/sambuca.jpg'],['ARP_storico/stazione.jpg'],['ARP_storico/teatroadriano.jpg'],['ARP_storico/trattori-fiat.jpg']];
