// <![CDATA[
var ampleCaixaProjecte = 240;
var altCaixaProjecte = 200;
var margeCaixaProjecte = 13;
var caixaVisorAlt = 500;
var filaAmpliada = 100;
var arrayInfo = new Array();
var intervalo;

// cookie
var arrayCapes = new Array();
var arraySeleccionat = new Array();
var arrayCapesComplet = new Array();
var projecteActual
var projecteActualID
var columnesMinima = 4
var columnesMaxima = 99
var resizeActiu = true;
var periodeClic = true;
var periodeClicID
var nadalaVista = true;
//
function updateOrientation(){
  var orientation = window.orientation;
  switch(orientation) {
    case 0:
        /* If in portrait mode, sets the body's class attribute to portrait. Consequently, all style definitions matching the body[class="portrait"] declaration
           in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
        document.body.setAttribute("class","portrait");
		
        /* Add a descriptive message on "Handling iPhone or iPod touch Orientation Events"  */
       
        break; 
    case 90:
        /* If in landscape mode with the screen turned to the left, sets the body's class attribute to landscapeLeft. In this case, all style definitions matching the
           body[class="landscapeLeft"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
        document.body.setAttribute("class","landscapeLeft");
		
        break;
    case -90: 
        /* If in landscape mode with the screen turned to the right, sets the body's class attribute to landscapeRight. Here, all style definitions matching the
           body[class="landscapeRight"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
        document.body.setAttribute("class","landscapeRight");
		 

        break;
  }

}

window.onorientationchange=updateOrientation;
function desactivaPeriodeClic(){ periodeClic = false;}

// funció de la capa projecte
function amplia(idProjecte, manteObert){
	
	//desactivaFlash();
	
	//alert(arrayCapes[capaIdDinsArray])
	var tempName  = "p"+idProjecte;
	
	for(var i=0; i<(arrayCapes.length-1); i++){
		if(arrayCapes[i].id == tempName){
			var capaIdDinsArray = i;
		}
	}
	desactivaResize(800);
	// descobreixo la posicio real de la capa
	if(capaIdDinsArray != -1 && arrayCapes[capaIdDinsArray]){
		if(capaIdDinsArray != projecteActual) {
			projecteActual = capaIdDinsArray;
			//alert(arrayCapes)
			projecteActualID = arrayCapes[capaIdDinsArray].ide
			var temp = arrayCapes[capaIdDinsArray]
		
			//alert((arrayCapes[capaIdDinsArray].fila));
			//(function() {  new Fx.Scroll(window,{offset:{x:0, y:-10}}).toElement(temp) }).delay(800)
			getInfo(idProjecte);
			// coloco visor Projectes
			
			colocaCapaProjecte((arrayCapes[capaIdDinsArray].fila)*(altCaixaProjecte+margeCaixaProjecte), caixaVisorAlt)
			detectaCapes("funcio amplia 1r if");
			//document.getElementById(tempName).style.background="#F08000";
			//document.getElementById("m"+element.ide).style.display="block";
		
			document.getElementById("bottom_udz").style.top=(arrayCapes[capaIdDinsArray].fila+(caixaVisorAlt-230))+"px";
			//wid3 = sizethis();
			//$('menuBase').tween('height', Math.ceil(wid3[1]));
		} 
		else if(manteObert){
			projecteActual = capaIdDinsArray;	
			projecteActualID = arrayCapes[capaIdDinsArray].ide
			
			// coloco visor Projectes
			colocaCapaProjecte((arrayCapes[capaIdDinsArray].fila)*(altCaixaProjecte+margeCaixaProjecte), caixaVisorAlt)
			detectaCapes("funcio amplia 2n if");
			//alert("mantinc obert");
			
		
		} else {
			projecteActual = null;
			projecteActualID = null
			filaAmpliada = 100;
			
			colocaCapaProjecte((arrayCapes[capaIdDinsArray].fila)*(altCaixaProjecte+margeCaixaProjecte), 0);
			detectaCapes("funcio amplia 3r if");
			//new Fx.Scroll(window, {offset:{x:0, y:-10}}).toTop(); 
			//document.getElementById("p"+element.ide).style.background="#FFFFFF";
			document.getElementById("m"+element.ide).style.display="none";
			document.getElementById("bottom_udz").style.top="1px";//(altCaixaProjecte+margeCaixaProjecte)+"px";
		}
	} else {
			projecteActual = null;
			projecteActualID = null;
			filaAmpliada = 100;
			
			colocaCapaProjecte((arrayCapes[0].fila)*(altCaixaProjecte+margeCaixaProjecte), 0);
			detectaCapes("primera opcio");
			//new Fx.Scroll(window, {offset:{x:0, y:-10}}).toTop(); 

	}
	
	//alert(arrayCapes.length)
	for(var i=0; i<(arrayCapes.length-1); i++){
	
		//out(arrayCapes[i].ide)
		
		
		//alert(arrayCapes[i].ide)
		if(arrayCapes[i].ide!=idProjecte)	document.getElementById("m"+arrayCapes[i].ide).style.display="none";//document.getElementById("p"+arrayCapes[i].ide).style.background="#FFFFFF";
		
	}
	periodeClic = true
	if(periodeClicID){
		clearTimeout(periodeClicID)
	}
	periodeClicID = setTimeout(desactivaPeriodeClic, 1000)
	//inactivaCapes(projecteActual)
	//amplia(40)
}
function getInfo(id){
	
	var req = new Request({
		url: 'proj.php?id='+id, 
		evalScripts: true, 
		onSuccess: function(txt){
			$('cVisor').set('html',txt),
			visorInit();
			scriptAdicional();
			pageTracker._trackPageview("/proj.php?id="+id);
			(function() {  new Fx.Scroll(window, {offset:{x:0, y:-10}}).toElement(arrayCapes[projecteActual]); }).delay(700)
			//var myFx = ;
			//init();
		},	
		onFailure: function(){
			$('cVisor').set('text','has arribatssssssss al final d\'internet ');
		}
	});
	req.send();
	
}


function reescala(){
	//alert("reescala")
	if($chk(projecteActual)){
		amplia(projecteActualID, false, true);
		//alert("oops")
		//detectaCapes("funció reescala primer if");
		
	} else {
		//alert("oops")
		detectaCapes("funcio reescala");
	}
}
function colocaCapaProjecte(y, alt)
{
	$('cVisor').morph({top:y, height:alt});
}


function seleccionaCapes(capa){ 


	colocaCapaProjecte(0, 0);
	arrayCapesComplet = new Array();
	arraySeleccionat = new Array();
		
	for (var i=0; i<=idArray.length; i++)
	{
		arrayCapesComplet.push($('p'+idArray[i]));
		
		if(idArray.length==(i+1)){ 
		
			intervalo = window.setInterval(function(){ 
				
				
				detectaCapes("funcio seleccionaCapes"); 
				
		
			}, 500);
		
		}
	}
		
	if(capa)
	{
		
		for(var i =0; i<=arrayIndex[capa].length; i++){
			arraySeleccionat.push($('p'+arrayIndex[capa][i]));
		}
	
		arrayCapes = arraySeleccionat;
		//alert(arrayCapes)
		
	} 
	else 
	{
	
		document.getElementById("loading_stuff").style.display="none";
		arrayCapes = arrayCapesComplet;
		//alert(arrayCapes)
	}
	
	if($chk(projecteActual)){
		amplia(null, false);
		//out(projecteActualID)
	}
	detectaCapes("funcio seleccionaCapes");
		
	//wid = sizethis();
	//anim($('hProjectes'), (Math.ceil(wid[0])-20)+"px", 'block');
}



window.addEvent('domready', function() { ampliacions = new Array()});
	
function initCapes(){}

function detectaCapes(origen){
	//alert("detecta capes origen "+origen)
	//var list = $$('.caixaProjecte');
	var graella
	var col = 1; 
	var files = 1;
	
	var margeFilesOberta = 0;
	var colMax = descobreixCol();
	//list.each(function(element) {
	var i = 0; 
	var final;
	

	
	//alert(colMax + " *" + ampleCaixaProjecte+"+"+margeCaixaProjecte+"="+colMax*(ampleCaixaProjecte+margeCaixaProjecte))
	//alert(Math.round(wid[0]) + " - " +colMax*(ampleCaixaProjecte+margeCaixaProjecte))
	wid = sizethis();
	$('menuBase').tween('width', Math.ceil(wid[0])-1);
	

	for(var j=0; j< (arrayCapesComplet.length - 1); j++){
	 	if(arrayCapes.indexOf(arrayCapesComplet[j]) < 0){
	
			// amago la capa
			arrayCapesComplet[j].morph({opacity:0});
		} else {
			// coloco capa
			element = arrayCapes[i];
			
			arrayCapes[i].col = col
			arrayCapes[i].fila = files
	
			
			if(projecteActual != null){
			
				if(arrayCapes[i].fila > arrayCapes[projecteActual].fila){
					margeFilesOberta =  caixaVisorAlt+margeCaixaProjecte;
					
				} else {
					margeFilesOberta = 0;
				}
			} else {
				margeFilesOberta = 0;
			}
			
			
			var x = (col-1) * (ampleCaixaProjecte + margeCaixaProjecte)
			var y =  ((files-1) * (altCaixaProjecte + margeCaixaProjecte)) + margeFilesOberta
			
			mou(element, x, y, j*15);
	
			if(col<colMax){
				col++;
			} else {
				col = 1
				files++;
			}
	
			
			i++
			final = y;
			}
	}


	// calcul alçada necessària pels projectes 
	if($chk(projecteActual)){
		var visorObert = 240//360
	} else {
		visorObert = 0
	}

	var alt2 = ((arrayCapes[arrayCapes.length-2].fila* (altCaixaProjecte + margeCaixaProjecte)) + visorObert +10);// aqui é aonde se define a altura total
	
	$('conteProjectes').morph({ height:alt2});	
	clearInterval(intervalo);

}
function descobreixCol(){
	
	var dimensions = $('conteProjectes').getSize()
	
	var col = Math.floor(dimensions.x / (ampleCaixaProjecte + margeCaixaProjecte -2));
	
	if(col < columnesMinima){
		col = columnesMinima
	} else if(col > columnesMaxima) {
		col = columnesMaxima
	}
	return col;
}

var moviment

function mou(element, x, y, delai){
	//delai = 0
	if(periodeClic == true){
		delai = 0;	
	}

	if(!delai){
		delai = 0;	
	}
	var canviX = (element.getStyle('left').toInt() != x)
	var canviY =  (element.getStyle('top').toInt() != y)
	
	//alert(projecteActualID +"  "+element.ide)
	var opacitat 
	if(projecteActualID == element.ide || projecteActualID == null ){
		opacitat = 1
	} else if (element.ide == null){
		
		opacitat = 1
	} else {
		opacitat = 0.3
	}
	//delai=0;
	element.delaiID = $clear(element.delaiID);
	if(!element.eFX){
		element.eFX = new Fx.Morph(element, {transition: Fx.Transitions.Quad.easeInOut, duration:500, link:'cancel'});
	}
	if(canviX && canviY){
		element.mouFunc = function() {  element.eFX.start({left: x, top:y, opacity:opacitat}); }
		element.delaiID = element.mouFunc.delay(delai)
		

		
	} else if (canviX) {
		element.mouFunc = function() {  element.eFX.start({left: x, opacity:opacitat}); }
		element.delaiID = element.mouFunc.delay(delai)
	
	
	} else if (canviY){
		element.mouFunc = function() {  element.eFX.start({top: y, opacity:opacitat}); }
		element.delaiID = element.mouFunc.delay(delai)
		
		
	} else {
		element.mouFunc = function() {  element.eFX.start({opacity:opacitat}); }
		element.delaiID = element.mouFunc.delay(delai)
	
	}	

}

var timerResize;

function init(){
	if(!resizeActiu){
		//alert("activo resize")
		resizeActiu = true
		window.addEvent('resize', funcioResize);
	}
}
function desactivaResize(temps){
	if(resizeActiu){
		//alert("desactivo resize")
		resizeActiu = false;
		window.removeEvent('resize', funcioResize);	
		if(temps){
			setTimeout(init, temps);	
		}
	
	}
}
function funcioResize(){
	// condicional perquè no salti just carregar
	//alert("resize! ");
	if(timerResize){
		//alert("resize! ");
		clearTimeout(timerResize);
		timerResize = setTimeout(reescala, 500);
		
	} else {
		timerResize = 1;	
	}
	
}

function over(id) {	
	var clip = $('pi'+id);
	//clip.set('morph',{duration:250});
	//clip.morph({height:37, bottom:[20,37]});
}

function out(id){
	var clip = $('pi'+id);	
	if(id != projecteActualID){
		//clip.morph({height:0, bottom:20});
  } else {
	over(id)  
  }
}

function reordre2(){
	var llistaCapes = $('conteProjectes');
	var novaArray = new Array();
	for(var i=0; i<15; i++){
		novaArray.push($('p'+i));
	}

	var reordenar = new Sortables(llistaCapes,{
	
		clone:true,
		opacity: 0.5,
		complete: showNewOrder
	});
	
	var showNewOrder = function() { /*alert("suola!")*/ }

}
function eliminaNadala(){
	swfobject.removeSWF("caixaFlash2");
	$('caixaFlash').setStyle('height','0px');
	$('caixaFlash').setStyle('width', '0px');

}


function reordre(){
	//var llistaCapes = $('conteProjectes');
	//if(!nadalaVista){
	if(false){
		var att = { data:'nadal09/zounadal.swf', width:'100%', height:'100%' };
		//var par = { menu:'false' };
		var par = { menu:'false',wmode:'transparent' };
		var id = 'caixaFlash2';

		swfobject.createSWF(att, par, id);
		nadalaVista = true
	} else {
		$('caixaFlash').setStyle('height','0px');
		$('caixaFlash').setStyle('width', '0px');
	}

	//var llistaCapes = novaArray
	//var llistaCapes = $$('.caixaProjecte');
	var llistaCapes = $$('.caixaProjecte');
	
	
	llistaCapes.each(function(element){
		
		var temp
		var temp2
		var dropps = $('.caixaProjecte');
		
		var myDrag = new Drag.Move(element, {
							   
			//droppables: dropps,
			droppables: '.caixaProjecte',
			
			onStart: function(element){
				//alert("onStart");
				//alert(myDrag.droppables);
				element.removeEvents('mouseup')

				//temp = element.removeEvents('onmouseup')
				element.onclick = null;
				
				//alert(element.onclick)
				element.setStyle('z-index', 100);
				
				
				var indexElement = myDrag.droppables.indexOf(element)
				myDrag.droppables.splice(indexElement, 1);
				
				element.setOpacity(0.5);
			},
			
			
			onComplete: function(element){
				//alert("onComplete")
				myDrag.droppables.push(element);
				element.setOpacity(1);
				
				
				element.addEvent('mouseup', function(event){
					amplia(element.ide)
				});
				
				//element.onmouseup = temp
				//alert("el deixo en una zona que no hi ha res "+element);
			},
			onDrop: function(element, droppable){
				//alert("onDrop");
				if(droppable != null){
					var indexElement = arrayCapes.indexOf(element);
					var indexDrop = arrayCapes.indexOf(droppable);
	
					arrayCapes.splice(indexElement, 1);
					arrayCapes.splice(indexDrop, 0, element);
									
				}
				detectaCapes("funcio reordre");
				
			}			
		});
	});
}

function sizethis() {
	        
 var xScroll, yScroll;

if (window.innerHeight && window.scrollMaxY) {	
	xScroll = window.innerWidth + window.scrollMaxX;
	yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
	xScroll = document.body.scrollWidth;
	yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	xScroll = document.body.offsetWidth;
	yScroll = document.body.offsetHeight;
}

var windowWidth, windowHeight;

if (self.innerHeight) {	// all except Explorer
	if(document.documentElement.clientWidth){
		windowWidth = document.documentElement.clientWidth; 
	} else {
		windowWidth = self.innerWidth;
	}
	windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	windowWidth = document.documentElement.clientWidth;
	windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
	windowWidth = document.body.clientWidth;
	windowHeight = document.body.clientHeight;
}	

// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
	pageHeight = windowHeight;
} else { 
	pageHeight = yScroll;
}

// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){	
	pageWidth = xScroll;		
} else {
	pageWidth = windowWidth;
}

return [pageWidth,pageHeight];
}
