//LONG LIVE JQUERY

var menuSubOpen=null; //referencia a la opcion abierta del menu de proyectos

$(document).ready(function() { 
	setQTip();
	setVimeoThumbs();
	setDesc();
	setDirList();
	setPags();
	setMenuSub();	
	setMenuTop();
	
	setLinkedContent();
	$(window).bind('hashchange', function () {
		setLinkedContent();					   
	});
});

function setVimeoThumbs(){ //muestra thumbnails de videos de vimeo
	$('[data-tipo="vimeoThumb"]').each(function(index){
		var dato=$(this).attr("id").split("-"); //crear imagenes placeholder con id: 'vimeo-IDDELVIDEO'
		var id=dato[1];
		var url = "http://vimeo.com/api/v2/video/" + id + ".json?callback=showThumb";
		var id_img = "#vimeo-" + id;
		$(id_img).css("display","none");
		$(id_img).before('<script type="text/javascript" src="'+ url +'"></script>');
	});
}
function showThumb(data){ //muestra un thumbnail de videos de vimeo
	var id_img = "#vimeo-" + data[0].id;
	$(id_img).attr('src',data[0].thumbnail_medium);
	if(!$.browser.msie){
		$(id_img).load(thumbLoaded);
	}else{
		$(id_img).css("display","inline");
	}
}
function thumbLoaded(){
	$(this).fadeIn(100);
}

function setDesc(){ //ALINEA ALTURAS DESCRIPCION-CONTENIDO EN SECCION VER PROYECTO Y ACTIVA EL CUSTOM SCROLLBAR
	//440=espacio disponible
	if($("#txt").height()!=null){
		var th=$("#tecnica").height();
		var txh=$("#txt").height();
		
		if(txh==50){ //no tiene descripcion
			$("#tecnica").jScrollPane({showArrows: true, scrollbarWidth: 15});
			th=$("#tecnica").height();
			if(440-th>0){
				$("#txt").height(440-th);	
			}else{
				$("#txt").height(0);	
			}
			
			$(".jScrollPaneContainer").height(th);
			$("#tecnica").jScrollPane({showArrows: true, scrollbarWidth: 15});
			$("#txt").css("backgroundImage","url(img/bg_menu_works.gif)");
			if(440-th<=0){
				$("#tecnica").height(448);
			}	
		}else if(th==50){ //no tiene ficha tecnica
			$("#tecnica").height(0);	
			$("#tecnicaMargen").css("marginBottom",0);
			$("#txt").height(448);
			$("#txt").jScrollPane({showArrows: true, scrollbarWidth: 15});
		}else{
			$("#tecnica").css("maxHeight",220);
			th=$("#tecnica").height();
			$("#tecnica").css("maxHeight","none");
			$("#tecnica").height(th);
			
			$("#txt").height(440-th);	
			$("#txt").jScrollPane({showArrows: true, scrollbarWidth: 15});
			$("#tecnica").jScrollPane({showArrows: true, scrollbarWidth: 15});
		}
		//$("#tecnica").jScrollPane({showArrows: true, scrollbarWidth: 15});
	}
}

function overProyList(){ //animacion rollOver de proyectos en el listado de proyectos
	$(this).children().animate({marginTop: "120px" },150);
}
function outProyList(){ //animacion rollOut blabla
	$(this).children().animate({marginTop: "140px" },150);
}
function setProyList(){	//activa eventos de proyectos en el listado
	$("#list .proy").each(function(index){
		var img=$(this).attr("data-img");
		$(this).css("background-image","url(PROY_THUMB/" + img + ")");
		$(this).hover(overProyList,outProyList);
	});
}

function setDirList(){ //pone un fondo aleatorio en los nombres de los directores
	$('.nom').each(function(index){
		var tipo=Math.floor(Math.random()*4)+1;
		$(this).css("background-image","url(IMG/bg_dir_nom" + tipo + ".gif)");
	});
}

function centraVerOn(id){ //auto centrado del numero
	if(id.position()!=null && !$.browser.msie){
		var left;
		if($.browser.mozilla){
			left=id.position().left; //FIREFOX
		}else{
			left=id.position().left-id.parent().position().left; //CHOME
		}
		
		var scr=id.parent().scrollLeft();
		//alert(left + " - " + scr);
		if(left>22 || left<20){//centra el boton seleccionado	
			scrollPags(id.parent(),left-21);
		}
	}
}

function scrollPags(id,num){
	var tipo=$(id).attr("data-tipo");
	
	var div=$(".pags[data-tipo='" + tipo + "']");
	var s=div.scrollLeft();
	
	var w=0;
	div.children().each(function(i){
		w+=21;								   
	});
	
	
	$(div).animate({ scrollLeft: s+num }, 150);
	
	if(s+num>0){
		$(".pagPrev[data-tipo='" + tipo + "']").css("visibility","visible");
	}else{
		$(".pagPrev[data-tipo='" + tipo + "']").css("visibility","hidden");
	}
	
	if(s+num<w-64){
		$(".pagNext[data-tipo='" + tipo + "']").css("visibility","visible");
	}else{
		$(".pagNext[data-tipo='" + tipo + "']").css("visibility","hidden");
	}
	if(w<70){
		$(".pagNext[data-tipo='" + tipo + "']").css("display","none");	
		$(".pagPrev[data-tipo='" + tipo + "']").css("display","none");
	}
}
function prevPags(){
	scrollPags(this,-42);
}
function nextPags(){
	scrollPags(this,42);
}
function setPags(){
	scrollPags($(".pagPrev"),0);
	$(".pags").scrollLeft(0);	
	$(".pags").live('mousedown',noReturn);
	
	$(".pagPrev").live('click',prevPags);
	$(".pagNext").live('click',nextPags);
}

var totalAboutFotos=7;
var numAboutFoto=1;
function aboutFotoChange(){
	var numar=$("#aboutFotos").html().split("/");
	numAboutFoto++;
	if(parseFloat(numAboutFoto)>totalAboutFotos){
		numAboutFoto=1;	
	}
	$("#aboutFotos").children("img").attr("src","ABOUT_IMG/a" + numAboutFoto + ".jpg");
	$("#aboutFotos").children("img").load(aboutFotoLoaded);
}

function aboutFotoLoaded(){
	$("#aboutFotos").children("img").css("display","none");
	$("#aboutFotos").children("img").fadeIn(100);	
}

var aboutTimer;
function aboutReady(){
	aboutTimer=setInterval(aboutFotoChange,3000);
}	

function setMenuTop(){ //activa opciones ABOUT y CLIENTS
	$("#menuTop").mousedown(noReturn);
	$('#about').qtip({ 
		show: 'click',
		hide: 'unfocus',
		content: {
			url: 'AJAX/about.html?id=343'
		},
		style: 'estilo',
		show: { 
			when: 'click',
			delay: 10,
			effect: { type: 'slide' } 
		},
		style: { 
			name: 'estilo',
			width: 500,
			border: {
				radius: 0
			},
			tip: { // Now an object instead of a string
				corner: 'topMiddle'
			}
		},
		position: {
			corner: {
				target: 'bottomLeft',
				tooltip: 'topMiddle'
			},
			adjust: {
				x:30
			}
		},
		api: {
		  onShow: function() {
			 $('#contact').qtip("hide");
			 $('#clients').qtip("hide");
		  }
	   }
	});
	
	$('#contact').qtip({ 
		show: 'click',
		hide: 'unfocus',
		content: {
			url: 'AJAX/contact.html?id=343'
		},
		style: 'estilo',
		show: { 
			when: 'click',
			delay: 10,
			effect: { type: 'slide' } 
		},
		style: { 
			name: 'estilo',
			width: 216,
			border: {
				radius: 0
			},
			tip: { // Now an object instead of a string
				corner: 'topRight'
			}
		},
		position: {
			corner: {
				target: 'bottomLeft',
				tooltip: 'topRight'
			},
			adjust: {
				x:30
			}
		},
		api: {
		  onShow: function() {
			 $('#about').qtip("hide");
			 $('#clients').qtip("hide");
		  }
	   }
	});

	$('#clients').qtip({
		show: 'click',
		hide: 'unfocus',
		content: {
			url: ' AJAX/clients.html?caca'
		},
		style: 'estilo',
		show: { 
			when: 'click',
			delay: 10,
			effect: { type: 'slide' } 
		},
		style: { 
			name: 'estilo',
			width: 370,
			border: {
				radius: 0
			},
			tip: { // Now an object instead of a string
				corner: 'topRight' // We declare our corner within the object using the corner sub-option
			}
		},
		position: {
			corner: {
				target: 'bottomLeft',
				tooltip: 'topRight'
			},
			adjust: {
				x: 30
			}
		},
		api: {
		  onShow: function() {
			 $('#contact').qtip("hide");
			 $('#about').qtip("hide");
		  }
	   }
	});
}

function setMenuSub(){ //activa opciones menu
	$("#works").mousedown(noReturn);
	$(".menuPrin li.prin").each(function(index) {
		var menuSub=$(this).children(".menuSub"); //guarda el <UL> de la subopcion objetivo
		menuSub.css("display","none"); //las oculta
		var col=$(this).attr("data-color");	 //pilla el color
		menuSub.children().children().css("background-color",col); //setea el color de fondo de los <SPAN> de cada <LI>
	});
}
function toggleMenuSubById(id,speed){
  	speed = typeof(speed) != 'undefined' ? speed : 150;
	var menuSub=$('[data-id="' + id + '"]');
	toggleMenuSub(menuSub,speed);
}
function toggleMenuSub(id,speed){
	speed = typeof(speed) != 'undefined' ? speed : 150;
	var menuSub=$(id).parent().children(".menuSub"); //guarda el UL de la subopcion objetivo
	if(menuSubOpen!=null){ //comprueba si hay alguna opcion abierta
		if(menuSubOpen.attr("data-id")!=menuSub.attr("data-id")){ //y que no sea la misma que se ha picado
			menuSubOpen.slideToggle(speed); //la cierra
		}
	}
	if(menuSub.css("display")=="none"){ //comprueba si esta cerrando o abriendo
		menuSubOpen=menuSub; //guarda la subopcion si la esta abriendo
	}else{
		menuSubOpen=null;	
	}
	menuSub.slideToggle(speed);
}

var menuSubSelected=0
function setMenuSubSelected(id){
	menuSubSelected=id;
}

function setQTip(){
	$.fn.qtip.styles.estilo = { // configura estilo de los Q-TIP
	   background: '#2A282C',
	   color: 'white',
	   fontFamily: 'Arial',
	   fontSize: '12px',
	   textAlign: 'center',
	   border: {
		  width: 1,
		  radius: 3,
		  color: '#2A282C'
	   },
	   tip: 'bottomRight',
	   name: 'green' // Inherit the rest of the attributes from the preset style
	}

	$('[title]').qtip({ 
	   show: 'mouseover',
	   hide: 'mouseout',
	   style: 'estilo',
	   show: { 
		delay: 10,
		effect: { type: 'fade' } 
		},
	   position: {
		  corner: {
			 target: 'topLeft',
			 tooltip: 'bottomRight'
		  },
		  adjust: {
			  x: 8  
		  }
	   }
	});	
}

function verReel(id,tit,file){ //carga el video seleccionado y cambia el texto inferior
	content='<iframe src="http://player.vimeo.com/video/' + id + '" width="482" height="361" frameborder="0"></iframe>';
	$('#video').html(content);
	
	window.location.hash="verVideo=" + id;
	$('#desc').html('WATCH: ' + tit + '<br><a href="REEL_MOV/' + file + '" target="_blank">DOWNLOAD QUICKTIME</a>');
	return false;
}

function resetVerOn(){
	if(videoOn!=null){
		$(videoOn).css("background-color","#FFF");
		$(videoOn).children().css("color","#2C2A25");
	}
	if(boardOn!=null){
		$(boardOn).css("background-color","#FFF");
		$(boardOn).children().css("color","#2C2A25");
	}
	videoOn=boardOn=null;
}


var videoOn;
function verVideo(id,txt){ //carga video 
	if(window.location.hash!="#verVideo=" + id){
		window.location.hash="verVideo=" + id;
	}else{
		resetVerOn();
		videoOn=$("[data-id='viewV" + id + "']");
		centraVerOn(videoOn);
		
		var color="#2A292C";
		videoOn.css("background-color",color);
		videoOn.children().css("color","#FFFFFF");
		
		$("#video").animate({marginLeft: 0, width:482 },100);
		var content='<iframe src="http://player.vimeo.com/video/' + id + '" width="482" height="361" frameborder="0"></iframe>';
		if(txt!=null){
			content+='<p></p>' + txt;
		}
		$('#video').html(content);
	}
	return false;
	
}

function boardLoaded(){
	var w=$(this).width();
	var ml=482-w;
	$(this).animate({opacity: 1},100);
	$(this).qtip({
		show: 'mouseover',
	   hide: 'mouseout',
	   style: 'estilo',
	   content: {
			text: 'Ampliar'
		},
	   show: { 
		delay: 10,
		effect: { type: 'fade' } 
		},
	   position: {
		  corner: {
			 target: 'topMiddle',
			 tooltip: 'bottomMiddle'
		  },
		  adjust: {
			  x: 8  
		  }
	   },
	   style: { 
			name: 'estilo',
			tip: { // Now an object instead of a string
				corner: 'bottomMiddle' // We declare our corner within the object using the corner sub-option
			}
		}
	});
	$("#video").animate({marginLeft: ml, width: w },100);
	
	//$("#content").css("margin-left",ml);	
}

var boardOn;
function verBoard(id,txt){ //carga imagen
	resetVerOn();
	boardOn=$("[data-id='viewB" + id + "']");
	centraVerOn(boardOn);
	
	var color="#2A292C"; //var color=$(".menuSub[data-id='" + menuSubSelected + "']").parent().attr("data-color");
	boardOn.css("background-color",color);
	boardOn.children().css("color","#FFFFFF");
	
	$("#content").css("margin-left",0);	
	var content='';
	
	$(".numPag").each(function(index){
		var url=$(this).attr("data-id");
		if(url.indexOf("viewB")>-1){
			var data=url.substring(5).split(".");
			var style="";
			var clas="";
			if(url!="viewB" + id){ style="style='display:none;'"; }else{ clas='class="board"'; }
			content+='<a class="lightbox" rel="galeria" ' + style + ' href="PROY_BOARDS/' + data[0] + '_xl.' + data[1] + '"><img ' + clas + ' src="PROY_BOARDS/' + url.substring(5) + '" /></a>';
		}
	});
	
	//var content='<a class="lightbox" href="PROY_BOARDS/' + data[0] + '_xl.' + data[1] + '"><img class="board" src="PROY_BOARDS/' + id + '" /></a>';
	if(txt!=null){	
		content+='<p></p>' + txt;
	}

	$('#video').html(content);	//imagen ampliada= nombredeimagen_xl.extension
	$('.lightbox').fancybox(); //activa el plugin fancybox
	$('.board').css("opacity",0);
	$('.board').load(boardLoaded);
	
	window.location.hash="verBoard=" + id;
	
	return false;
}

function setLinkedContent(){
	
	var url=window.location.toString();
	var hash=window.location.hash;
	if(hash!=""){
		if(url.indexOf("reel.asp")>-1){
			var data=hash.split("=");
			var a=$("[data-id='viewV" + data[1] + "']");
			var txt=a.attr("data-txt");
			var file=a.attr("data-file");
			verReel(data[1],txt,file);
		}else if(url.indexOf("default.asp")>-1 || url.indexOf(".asp")<0){
			var data=hash.split("=");
			verPagProy(data[1]-1);
		}else if(hash.indexOf("verVideo")>-1){
			var data=hash.split("=");
			var txt=$("[data-id='viewV" + data[1] + "']").attr("data-txt");
			verVideo(data[1],txt);
		}else if(hash.indexOf("verBoard")>-1){
			var data=hash.split("=");
			var txt=$("[data-id='viewB" + data[1] + "']").attr("data-txt");
			verBoard(data[1],txt);
		}
	}else{
		if(url.indexOf("default.asp")>-1 || url.indexOf(".asp")<0){
			verPagProy(0);
		}
	}
}

function proyListLoaded(r,s,x){
	setProyList();
}

function cargaProyList(tipo,subtipo,pag){
	$("#list").load("AJAX/proyList.asp", { t:tipo, st: subtipo, p: pag }, proyListLoaded);
	pagProyOn=$(".numPag[data-id='" + pag + "']");
	pagProyOn.css("background-color","#DDD");
}

function resetPagProyOn(){
	if(pagProyOn!=null){
		$(pagProyOn).css("background-color","#FFF");
	}
	pagProyOn=null;
}

var pagProyOn;
function verPagProy(pag){
	resetPagProyOn();
	
	var t;
	var st;
	var url=window.location.toString();
	if(url.indexOf("?")>-1){
		t=querySt("t");
		st=querySt("st");
	}else{
		t=-1;
		st=-1;
	}
	cargaProyList(t,st,pag);
	centraVerOn(pagProyOn);
	if(parseFloat(pag)+1>1){
		window.location.hash="verPag=" + (parseFloat(pag)+1);
	}
	return false;
}

function dirContentLoaded(r,s,x){
	scrollPags($(".pagPrev"),0);
}

function cargaDirContent(dir,id){
	$("#content").load("AJAX/dirProy.asp",{ d: dir, id: id},dirContentLoaded);	
	return false;
}

function dirListLoaded(r,s,x){
	setVimeoThumbs();
}

function cargaDirList(dir,pag){
	$(".proys").load("AJAX/dirProyList.asp",{ d: dir, p:pag },dirListLoaded);
	pagDirOn=$(".numPag[data-id='" + pag + "']");
	pagDirOn.css("background-color","#DDD");
}

function resetPagDirOn(){
	if(pagDirOn!=null){
		$(pagDirOn).css("background-color","#FFF");
	}
	pagDirOn=null;
}

var pagDirOn;
function verPagDir(pag){
	resetPagDirOn();
	var d=querySt("d");
	cargaDirList(d,pag);
	centraVerOn(pagDirOn);
	
	return false;
}


//FUNCION PARA LEER QUERYSTRING, BUSCA LA STRING ji
function querySt(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}
	}
}

function noReturn(){
	return false;	
}


//HELL YEAH
