//////////////////// global variables ////////////////////////
var xm = 0; // mouse position
var ym = 0;
var nx = 0; // screen position & size
var ny = 0;
var nw = 0;
var nh = 0;
var scr;
var scartoNonTagliare = 55; // RBAL : La uso per restringere manualmennte per non far uscire fuori lateralmente le immagini
var scartoNonTagliare2 = 3; // RBAL : La uso per centrare dato che il left appare non preciso di circa 10 px
var disattivaSlide = 0;

//////////////////// mouse - resize //////////////////////////
document.onselectstart = new Function("return false");

function disattivaSlideFunc() {
	
	// Disattivo lo slideshow solo se vado su un link interno; lo lascio attivo se apro un link esterno
	disattivaSlide = 1;
	JQ('#caricando').css('display','');
	
}

var isXuiTouch = xui.touch;
if (isXuiTouch) {			/** PGEN: check mobile events support **/
	
	function checkMouse(e) {
		if (e.targetTouches[0]) {
			xm = e.targetTouches[0].clientX;
			ym = nh * .5; 
			
			// Con le due if seguenti creo una zona intermedia di 200px in cui se si trova il mouse lo slideshow è fermo
			if (xm < nw * .5 + nx) { xm = xm + 100; if (xm > nw * .5 + nx) xm = nw * .5 + nx; }
			if (xm > nw * .5 + nx) { xm = xm - 100; if (xm < nw * .5 + nx) xm = nw * .5 + nx; }
			
			// Se disattivaSlide==1 allora disattivo lo slide
			if (disattivaSlide == 1) {
				xm = nw * .5 + nx; 
			}
			
		}
	}; 
	// Bind actions to the scorricatalogo container
	x$(document).on('touchstart',function(e){checkMouse(e);});
	x$("#a_prev_img").on('touchstart',function(e){checkMouse(e);return false;});
	// x$("#prev_img").on('touchend',checkMouse);
	x$("#a_next_img").on('touchstart',function(e){checkMouse(e);return false;});
	// x$("#next_img").on('touchend',checkMouse);
	
} else {

	document.onmousemove = function(e)
	{
		if (window.event) e = window.event;
		xm = (e.x || e.clientX);
		
		//if (xm-nx > 790) xm = 790+nx; // RBAL : questa e la riga seguente servono per limitare la velocità limitando la zona di azione del mouse lateralmente
		//if (xm-nx < 200) xm = 200+nx;

		// Con le due if seguenti creo una zona intermedia di 200px in cui se si trova il mouse lo slideshow è fermo
		if (xm < nw * .5 + nx) { xm = xm + 100; if (xm > nw * .5 + nx) xm = nw * .5 + nx; }
		if (xm > nw * .5 + nx) { xm = xm - 100; if (xm < nw * .5 + nx) xm = nw * .5 + nx; }
		
		// Se disattivaSlide==1 allora disattivo lo slide
		if (disattivaSlide == 1) {
			xm = nw * .5 + nx; 
		}
		
		//ym = (e.y || e.clientY); commento per non far muovere verticalmente il carousel
		ym = nh * .5; // metto questa al posto della precedente
	}
}		


function resize(){
	nx = pxLeft(scr);
	ny = pxTop(scr);
	nw = scr.offsetWidth - (scartoNonTagliare); // RBAL : -(scartoNonTagliare) restringimento fatto per non far uscire fuori lateralmente le immagini
	nh = scr.offsetHeight;
	s3D.resize();
}
onresize = resize;

/////////////////// DOM functions ////////////////////////////
px = function (x)
{
	return ''.concat(Math.round(x), 'px');
}
pxLeft = function(o)
{
	for(var x = -document.documentElement.scrollLeft; o != null; o = o.offsetParent)
		x += o.offsetLeft;
	return x;
}
pxTop = function(o)
{
	for(var y = -document.documentElement.scrollTop; o != null; o = o.offsetParent)
		y += o.offsetTop;
	return y;
}
/////////////////////// script ///////////////////////////////

s3D = {
	object : [],
	Im     : 0,
	Om     : 0,
	A      : 0,
	Y      : 0,
	/////////////////////
	temp   : 200,
	speed  : ((isXuiTouch) ? 500: 500),
	zOOm   : .25,
	fontzOOm : .04,
	HW     : .6,
	/////////////////////
	resize : function ()
	{
		////////////// resize /////////////////
		for(var i = 0; i < this.Om; i++)
		{
			var o = this.object[i];
			o.x   = .35 * nw * o.ac;
			o.z   = .35 * nw * o.as;
		}
	},

	run    : function ()
	{
		///////////// main loop ////////////////////////
		s3D.A += (xm - nw * .5 - nx) / s3D.speed;
		//document.getElementById('menu_bottom').innerHTML = s3D.A;
		
		s3D.Y = ym - nh * .5 - ny;		
		for(var i = 0; i < s3D.Om; i++)
			s3D.object[i].anim();
		setTimeout(s3D.run, 16);
	},

	CObj   : function (N)
	{
		////////////// create HTML /////////////////////////////
		var I = s3D.Im[N];
		var o = document.createElement("span");
		o.id = 'carousel_span_' + N;
		
		var ohref = document.createElement("a");
		ohref.id = 'carousel_a_' + N;
		
		ohref.href = I.parentNode.href;		
		hrefpiccolo = ohref.href.toLowerCase();
		if (hrefpiccolo.indexOf("www.cassina.com") == -1 && hrefpiccolo.indexOf("www.cassina.it") == -1) {
			ohref.target = '_blank';			
		} else {
			JQ(ohref).click(function() {disattivaSlideFunc();}); // Aggiungo l'onclick per bloccare lo slideshow quando seleziono un link da aprire nella stessa finestra
		}		
		
		o.appendChild(ohref);
		
		var oi = document.createElement("img");
		oi.src = I.src;
		oi.id = 'carousel_img_' + N;
		
		//oi.onclick = new Function("s3D.object["+N+"].clic();");
  		ohref.appendChild(oi);
		var ot = document.createElement("div");
		ot.onmousedown=new Function("return false;");
		ot.innerHTML = "&#8729;" + I.alt + "&#8729"
		o.appendChild(ot);
		var of = document.createElement("span");
		of.className = "chain";
		o.appendChild(of);
		scr.appendChild(o);
		/////////// variables ///////////
		this.o   = o.style;
		this.oi  = oi.style;
		this.ot  = ot.style;
		this.of  = of.style;
		this.N   = N;
		this.ys  = 0;
		this.ac  = Math.cos((360 * N / s3D.Om) * (Math.PI / 180));
		this.as  = Math.sin((360 * N / s3D.Om) * (Math.PI / 180));
		this.x   = .35 * nw * this.ac;
		this.z   = .35 * nw * this.as;
		this.Z   = .4;
		this.dZ  = false;
		this.pZ  = 0;

		//////////////// click /////////////////
		/*this.clic = function () {
			if(!this.dZ && this.pZ == 0)
				this.dZ = true;
			else
			{
				this.dZ = false;
				this.pZ = 0;
			}
		}*/

		//////////////// animation function ///////////////
		this.anim = function () {
			var s    = Math.sin(s3D.A * .01);
			var c    = Math.cos(s3D.A * .01);
			var xs   = s * this.x + c * this.z + (scartoNonTagliare * 0.33); // RBAL : +(scartoNonTagliare * 0.33) per centrare dopo il restringimento fatto per non far uscire fuori lateralmente le immagini
			var zs   = s * this.z - c * this.x;
			this.ys += (s3D.Y - this.ys) / (s3D.speed * .2);			
			var D    = nw / (nw + zs);
			var w    = D * (nw * s3D.zOOm);
			var h    = w * s3D.HW;
			if(this.Z > .4 && this.dZ || this.pZ > 0)
				s3D.A -= xs / 30;
			if(this.dZ)
			{
				this.Z *= 1.01;
				this.x  = this.Z * nw * this.ac;
				this.z  = this.Z * nw * this.as;
			}
			if(this.Z > .8 && this.dZ)
			{
				this.dZ = false;
				this.pZ = s3D.temp;
			}
			if(this.dZ == false && this.Z > .4)
			{
				if(this.pZ > 0)
					this.pZ--;
				else
				{
					this.Z  *= .995;
					this.x   = this.Z * nw * this.ac;
					this.z   = this.Z * nw * this.as;
				}
			}
			/////////////// HTML rendering ///////////////
			this.o.width        = px(w);
			this.o.height       = px(h);
			this.o.top          = px(nh * .5 + this.ys * D - (h * .5));
			this.o.left         = px(nw * .5 + xs * D - (w * .5) - scartoNonTagliare2); // scartoNonTagliare l'ho aggiunto per non far tagliare sui bordi sx e dx, scartoNonTagliare2 è una correzione manuale per centrare (è sbagliato proprio di base per qualche motivo non prende bene i px esatti del left)
			this.o.zIndex       = Math.round(D * 1000);
			this.oi.borderWidth = px(.03 * w);
			this.ot.fontSize    = px(s3D.fontzOOm * w);
			this.of.borderWidth = px(.01 * w);
		}
	},

	//////////////// init script ///////////////
	init   : function () {
		xm = nw * .8 - nx;
		//ym = nw * .5 - ny; RBAL commento per non far muovere verticalmente il carousel
		ym = nh * .5; // RBAL metto questa al posto di quella sopra
		this.Im = document.getElementById("img").getElementsByTagName("img");
		this.Om = this.Im.length;
		for(var i = 0; i < this.Om; i++) this.object[i] = new this.CObj(i);
		this.run();
	}
}

function createCookie(name,value,hours) {
	if (hours) {
		var date = new Date();
		date.setTime(date.getTime()+(hours*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
	}

	
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function eraseCookie(name) {
	createCookie(name,"",-1);
}

/////////////////////// start //////////////////////
onload = function (){
	document.getElementById("screen").innerHTML = "";
	scr = document.getElementById("screen");
	resize();
	s3D.init();
	if (isXuiTouch) {
		x$("#prev_img").setStyle('display','');
		x$("#next_img").setStyle('display','');
	}
	cookieName = "surveyCassinaDone";
	cookieTime = 8760;
	if (readCookie(cookieName) != "1") {
		window.open('http://www.surveymonkey.com/jsPopInvite.aspx?sm=TzcXw%2fxthXueEvNvKVF%2bBw%3d%3d', 'invitationwindow', 'height=350,width=500,scrollbars=yes,resizable=yes,status=yes')
		createCookie(cookieName,"1",cookieTime);
	}
}


