//var iPad = (jQuery.browser.webkit || jQuery.browser.safari)?true:false;
//iPad = true;
var iPad = (navigator.userAgent.match(/iPad/i) != null && jQuery.browser.safari) || (navigator.userAgent.match(/iPhone/i) != null && jQuery.browser.safari);

var MouseDeltaMultiplier = 10;
var bodyImgLoaded = 0; //cant imagenes en pagina
var prysLoaded = 0; //ttl proyectos cargados
var imgsPryLoaded = 0; //imagenes de un proyecto luego de mostrado
var currentProyect = 0; //proyecto mostrado actualmente
var isHome = false;
var sec=null;
var isProyects=false;
function updateBodyLoader() {
	try{console.debug("updateBodyLoader");}catch(e){}
	bodyImgLoaded++;
	pct = 100 * bodyImgLoaded / $("img").length;
	$('#page_loader span').html(Math.round(pct));
	if (pct == 100) {
		$('#page_loader').fadeTo(250,0,function(){$(this).css('display', 'none');
			if(isHome) {
				try{console.debug("isHome or isProyects");}catch(e){}
				animateFirm();
			} else{
				$(".sm").css("display","block");
				$('h1 img').stop(true, true).css("margin-right",0);
				showContent();
			}
		});
		
	}
}
function showContent() {
	try{console.debug("showContent");}catch(e){}
	$('#menu').css('visibility', 'visible');
	$('#content').css('visibility', 'visible');
	$('#disclaimer').css('visibility', 'visible');
	//
	try{
		var myurl=$(document).url();
		var hash=myurl.attr('hash');
		if(hash.indexOf("id")==0) {
			id=hash.slice(2);	
			$(".prylink[rel="+id+"]").click();
		}
	}catch(e){}
	if(isProyects)$("#orderby").css("visibility","visible");
	

			
}
function animateFirm() {	
	try{console.debug("animateFirm");}catch(e){}	
		$('h1 img').stop(true, true).animate({
			'margin-right': 0
		}, 1000, function() {
			
			if (isHome) {
				$('#homeslider').nivoSlider({
					effect: 'fade', // Specify sets like: 'fold,fade,sliceDown'
					slices: 1, // For slice animations
					boxCols: 8, // For box animations
					boxRows: 4, // For box animations
					animSpeed: 500, // Slide transition speed
					pauseTime: 2500, // How long each slide will show
					startSlide: 0, // Set starting Slide (0 index)
					directionNav: true, // Next & Prev navigation
					directionNavHide: true, // Only show on hover
					controlNav: false, // 1,2,3... navigation
					controlNavThumbs: false, // Use thumbnails for Control Nav
					controlNavThumbsFromRel: false, // Use image rel for thumbs
					controlNavThumbsSearch: '.jpg', // Replace this with...
					controlNavThumbsReplace: '_thumb.jpg', // ...this in thumb Image src
					keyboardNav: false, // Use left & right arrows
					pauseOnHover: false, // Stop animation while hovering
					manualAdvance: false, // Force manual transitions
					captionOpacity: 0.8, // Universal caption opacity
					prevText: 'Prev', // Prev directionNav text
					nextText: 'Next', // Next directionNav text
					beforeChange: function(){}, // Triggers before a slide transition
					afterChange: function(){}, // Triggers after a slide transition
					slideshowEnd: function(){}, // Triggers after all slides have been shown
					lastSlide: function(){}, // Triggers when last slide is shown
					afterLoad: function(){} // Triggers when slider has loaded
				});
			} else {
				$(".sm").css("display","block");
			}
			showContent();
		});
}
var onload = function() {
	try{console.debug("onload");}catch(e){}
	updateBodyLoader();
};
/*------------------------------------------------*/
/*cargador de paginas - de todas*/
$(document).ready(function() {
	//try{console.debug("onready isHome="+isHome+" isProyects="+isProyects);}catch(e){}
	
	if(iPad) {
		$("#main,.sc_content,#content")
			.css("overflow","visible")
			.css("height","auto")
		$("#disclaimer")
			.css("position","fixed")
			.css("bottom","10px")
		$(".prylink").live('click',function(){
			$(document).scrollTop(0);
		});
	}
	if ((isHome || isProyects) && $("img").length > 0) {
		try{console.debug("home o proyects and img > 0");}catch(e){}	
		$('#page_loader span').html('0');
		$('img').each(function() {
			var img = new Image();
			img.src = $(this).attr('src');;
			// IE 7 workarond
			if ($.browser.version.substr(0, 1) <= 8) {
				function testImg() {
					if (img.complete != null && img.complete == true) {
						onload();
						return;
					}
					setTimeout(testImg, 1000);
				}
				setTimeout(testImg, 1000);
			} else {
				img.onload = onload
			}
		});
	} else {
		if(isHome) {
			try{console.debug("isHome");}catch(e){}
			animateFirm();
		} else {
			if(!isProyects) {
				try{console.debug("!isProyects");}catch(e){}
				$("#page_loader").css("display","none");
			}
			$(".sm").css("display","block");
			$('h1 img').stop(true, true).css("margin-right",0);
			showContent();
		}
	}
	

});


///WARNING!

function fixProyectsWidth() {
	/*ttl = $('.proyectos li').length;
	 oneCol = $('.proyectos li:first').width();
	 
	 pw = $('.proyectos').width();
	 maxCol = Math.floor(pw / oneCol);
	 
	 ml = $('.proyectos').width() - parseInt(maxCol*oneCol);
	 $('.proyectos').css('margin-left',ml);
	 $('.proyectos').width(maxCol*oneCol);*/

}

function setUp(q) {
	try{console.debug("setup("+q+")");}catch(e){}
	switch (q) {
	case "home":
			isHome = true;
		break;

	case "projects":
	case "projects_filter":
		isProyects = true;
		sec="projects";
		$(document).ready(function() {
			
			/*cambia el link de PROJECTS para que muestra un submnenu*/
			$('#link_sm_projects').attr('href', 'javascript:;');
			$('#link_sm_projects').addClass('smtg');
			$('#link_sm_projects').click(function() {
				var s = $(this).next();
				//s.height(0);
				//h = 
				$('ul', s).height(250);
				$('ul', s).parent().width(153);
				try{
				}catch(e){}
				$(s).stop(true, true).animate({
					'opacity': 1/*,
					height: h*/
				}, 500, function() {
					//$("#orderby").css("visibility","visible");
				});
			});
			$('#link_sm_projects').click(); 
			
			
			/*------------------------------------------------*/

			//ajusta el margen izquierdo de los proyectos en funcion de la cantidad de proyectos cargados
			//


		});
		break;
	case "index":
		$(document).ready(function() {
			/*------------------------------------------------*/
			/*muestra los submenus de los items del submenu PROJECTS*/
			$("#orderby ul li a.smtg_sc").click(function(){
				switch($(this).attr("rel")) {
					case "alphabetically":
						location.href="index.php?mod=ajaxloader&func=projects_filter&value=search&orderby=proyecto_nombre&q=";
					break;	
					case "practice":
					location.href="index.php?mod=ajaxloader&func=projects_filter&value=search&orderby=practica_id&q=";
					break;	
					case "type":
					location.href="index.php?mod=ajaxloader&func=projects_filter&value=search&orderby=tipo_id&q=";
					break;
					case "location":
					location.href="index.php?mod=ajaxloader&func=projects_filter&value=search&orderby=pais_id&q=";
					break;
					case "date":
					location.href="index.php?mod=ajaxloader&func=projects_filter&value=search&orderby=fecha&q=";
					break;
				}
				
			});
			$('#menu a.smtg_sc').click(function() {
				$("#formSearch").fadeTo(250,0);
				$('.menu_scrollable').css('opacity', 0);
				$('.menu_scrollable').css('heigth', 0);
				$(this).find('.sc_content').parent().css({
					'opacity': '0',
					'height': 0
				});
				if (!$(this).attr('rel')) {
					var s = $(this).next();
					var scch = $(s).find('.sc_content').css('height');
					scch = parseInt(scch) + 40;
				} else {
					var s = $('div[title="' + $(this).attr('rel') + '"]');
					scch = 400;
				}
				/*				
				 $(s).css('opacity',1);
				 */
				 $(s).css('height',scch);
				$(s).animate({
					opacity: 1,
					height: scch
				}, 500, function() {
					
				});
			}); /*------------------------------------------------*/



			/*oculta el submenu activo de los items del submenu PROJECTS*/
			$('p.back').click(function() {
				$("#formSearch").fadeTo(250,1);
				th = $(this).parent();
				th.animate({
					opacity: 0,
					height: '0'
				}, 500, function() {

				});

			}); /*------------------------------------------------*/


			/*------------------------------------------------*/
			/*establece el scrollbar del submenu de los items del submenu PROJECTS*/
			if(!iPad) {
				$('#menu .sc_scroller').each(function() {
	
					var V = $(this).prev(); // Ventana
					var Ce = V.children(); // Contenido a escrolear					
					if (Ce.height() >= 200) {
						V.height(200);
					}
					var h = Ce.height() - V.height();
					$(this).css('height', V.height());
	
	
					if (Ce.height() > V.height()) {
						$(this).slider({
							orientation: 'vertical',
							min: 0,
							max: h,
							value: h,
							slide: function(event, ui) {
								calc = Ce.height() - V.height() - ui.value;
								Ce.css('marginTop', -calc);
								
							}
						})
						.prev().children().mousewheel(function(objEvent, intDelta){
							var sc_scroller = $(this).parent().next();
							sc_scroller.slider("value", sc_scroller.slider("value") + (intDelta * MouseDeltaMultiplier));
						});
					}
					//Ce.width(V.width() - $(this).width());
					$(this).height(V.height() - 5);
				});
			}
				 /*------------------------------------------------*/


			/*------------------------------------------------*/
			/*llama a la carga de un proyecto*/
			$('a.prylink').live('click', function() {
				loadProyect($(this).attr('rel'), $(this).attr('rev'));
			});

			/*------------------------------------------------*/
			/*aumenta el contador de imagenes de un proyecto*/
			$('a.prylink img').live('load', function() {
				prysLoaded++;
			});

			/*------------------------------------------------*/
			/*abre o cierra la informacion adicional de un proyecto, ya cargado*/
			$('#infoswp a').live('click', function() {
				if ($('#info').css('visibility') == 'hidden') {
					$(this).html('-info').css("color","#999");
					$('#info').css('visibility', 'visible');
				} else {
					$(this).html('+info').css("color","#eee");
					$('#info').css('visibility', 'hidden');
				}
			});

			/*------------------------------------------------*/
			/* establece altos de contenido izquierdo y los scrollbars verticales correspondientes*/
			setContentDims();
			setScrollbars();
			$(window).resize(function() {
				setContentDims();
				setScrollbars();
			}); /*------------------------------------------------*/



		});
		break;
	}
}

function setContentDims() {
	wW = parseInt($(window).width());
	wH = parseInt($(window).height());
	var h = wH - 100;
	//$('#content').height(h);
	//$('#content').width($('#content').width - $('#menu').width());

	/*$('#modal_loader').height(wH);
	$('#modal_loader').width(wW);
	$('#modal_loader').css('left', 0);
	$('#modal_loader').css('top', 0);
	$('#modal_loader img').css('marginTop', parseInt(wW / 4));*/

}

function showProyectLoader() {
	if(iPad) {
		$('#modal_loader').height($(document).height());
		$('#modal_loader').width($(document).width());
	}
	$('#modal_loader').stop(true, true).fadeTo(250,1);
}

function hideProyectLoader() {
	$('#modal_loader').stop(true, true).fadeTo(250,0,function(){
		$('#modal_loader').css('display', 'none');
	});
}

function prvPry() {
	var pr = $('.proyectos a[rev="' + (parseInt(currentProyect) - 1) + '"]');
	if (!pr.length) {
		var pr = $('.proyectos a[rev="' + $('.proyectos a').length + '"]');
	}
	pr.click();

}

function nextPry() {
	var pr = $('.proyectos [rev="' + (parseInt(currentProyect) + 1) + '"]');
	if (!pr.length) {
		var pr = $('.proyectos a[rev="1"]');
	}
	pr.click();
}

function loadProyect(id_proyecto, list_index) {
	currentProyect = list_index;
	showProyectLoader();
	var M = $('#modal_proyecto'); //toda la ventana
	var INF = $('#modal_proyecto #info'); //el cuadro de informacion a la derecha
	var G = $('#galeria ul'); //galeria de imagenes
	var GN = $('#galeria_nav ul#pics'); //contador de imagenes
	var PN = $('#galeria_nav ul#prys'); //navegador de		<anterior siguiente>
	G.html('');
	GN.html('');
	//vacia todos los spans que son contenedores de datos 
	$('.modaldata', M).html('...');
	//redimensionado del modal y del cuadro informativo
	//M.width($(window).width() - parseInt($('#menu').width() / 2)); //ancho del modal para no sobrepasar el menu
	//saca el modal para afuera de la pantalla
	//M.fadeTo(250,0);
	M.css({
		'left': -(M.width()),
		'visibility': 'visible'
	});

	$.get('index.php', {
		mod: 'proyectos',
		func: 'ajaxget',
		proyecto_id: id_proyecto
	}, function(data) {

		//resetea el posible scroll de la descripcion del proyecto
		$('#MDL_descripcion').css('marginTop', 0);

		/*
		 el array devuelto por json es:
		 proyecto
		 proyecto (t:proyectos)
		 a_pais (t:paises)
		 a_estado (t:estados)
		 a_tipo (t:tipos)
		 a_practica (t:practicas)
		 a_imagenes (t:to do)
		 */

		$.each(data.proyecto.proyecto, function(index, value) {
			$('#MDL_' + index).html(value);
		});


		$.each(data.proyecto.a_pais, function(index, value) {
			$('#MDL_' + index).html(value);
		});
		$.each(data.proyecto.a_estado, function(index, value) {
			$('#MDL_' + index).html(value);
		});
		$.each(data.proyecto.a_tipo, function(index, value) {
			$('#MDL_' + index).html(value);
		});
		$.each(data.proyecto.a_practica, function(index, value) {
			$('#MDL_' + index).html(value);
		});
		/*var bw = 1200; //ancho maximo en que pueden venir las imagenes
		var bh = 750; //alto maximo
		iw = M.width();
		ih = Math.round(bh / 100 * (iw * 100 / bw)); //cuenta magica! pa establecer el ancho de la imagen*/
		$.each(data.proyecto.a_imagenes, function(index, value) {
			//G.append('<li id="img_' + (index + 1) + '"><img src="' + value + '" width="' + parseInt(iw) + '" /></li>');
			G.append('<li id="img_' + (index + 1) + '"><img src="' + value + '" /></li>');
			GN.append('<li><a href="javascript:;" rel="img_' + (index + 1) + '" class="gal_nav_link">' + (index + 1) + '</a></li>');
		});
		//muestra la primer imagen
		G.data('current', 1);
		$(':first', G).css('visibility', 'visible');
		$(':first', G).addClass('current');
		//M.height($('#content').height());
		//INF.height(M.height() - 42);
		//acomoda la navegacion de imagnes en lo vertical
		//GN.parent().css('top', M.height() - 29);
		//tira un interval y llama a la una funcion para determinar si todas las imagenes del proyecto se cargaron
		imgsPryLoaded = 0;
		intClock = setInterval("isProyectLoaded()", 250);
		$('img', G).load(function() {
			imgsPryLoaded++
		});


		//navegacion entre proyectos dentro de un proyecto
		PN.html('');
		PN.append('<li><a href="javascript:prvPry();">PREVIOUS PROJECT</a></li>');
		PN.append('<li><a href="javascript:nextPry();" style="border-right:0px none">NEXT PROJECT</a></li>');
		/*PN.css('marginLeft', M.width() - PN.width());
		PN.css('marginTop', -15);*/

		//pone el primer item del navegador de imagenes como "seleccionado"
		$('li:first a', GN).addClass('selected');

		//establece la funcion de mostrar una imagen al clickar en un item del navegador de imagenes
		$('li a.gal_nav_link', GN).click(function() {
			$('li a', GN).removeClass('selected');
			$(this).addClass('selected');
			var tg = $('#' + $(this).attr('rel'));
			if (!tg.hasClass('current')) {
				$('.current', G).stop(true, true).fadeTo(250,0,function(){
					$(this).removeClass('current');
					tg.css('top', 0);
					tg.fadeTo(250,0);
					//tg.css('left', tg.width() * -1);
					tg.css('visibility', 'visible');
					tg.stop(true, true).fadeTo(250,1,function(){tg.addClass('current');});
					
					/*tg.stop(true, true).animate({
						'left': 0
					}, 750, function() {
						tg.addClass('current');
					});*/
				});
				
				/*
				$('.current', G).stop(true, true).animate({
					'left': $('.current', G).width() * -1
				}, 750, function() {
					$(this).removeClass('current');
					tg.css('top', 0);
					tg.css('left', tg.width() * -1);
					tg.css('visibility', 'visible');
					tg.stop(true, true).animate({
						'left': 0
					}, 750, function() {
						tg.addClass('current');
					});
				});
				*/
			}
		});
	}, 'json');

	/**/
}

function isProyectLoaded() {
	//si cargo todas las imagenes 
	if (imgsPryLoaded >= $('#galeria .items li').length) {

		hideProyectLoader();
		$('#modal_proyecto').stop(true, true).animate({
			'left': 0
		}, 750, function() {
			//$("#orderby").css("visibility","hidden");
			setScrollbarProyect();
			if(iPad) {
				$("#content").css("display","none");
				$('#modal_loader').height($(document).height());
				$('#modal_loader').width($(document).width());
			}
		});
		clearInterval(intClock);
	}
}



function hideProyectModal() {
	if(iPad) {
			$("#content").css("display","block");
			$('#modal_loader').height($(document).height());
			$('#modal_loader').width($(document).width());
		}
	$('#modal_proyecto').stop(true, true).animate({
		'left': ($('#modal_proyecto').width() + 10) * -1
	}, 750, function() {
		$('#modal_proyecto .sc_scroller').slider("destroy");
		
	});

}

function setScrollbarProyect() {
	$('#modal_proyecto .sc_scroller').each(function() {
		var fix = 110;
		var V = $(this).prev(); // Ventana
		var Ce = V.children(); // Contenido a escrolear
		var INF = $('#modal_proyecto #info');

		var dh = INF.height() - $('ul:first', INF).height() - 30;


		V.height(dh);

		$(this).css('height', V.height());
		var SV = Ce.height() - V.height();
		if (SV > 0) {
			
			$(this).slider({
				orientation: 'vertical',
				min: 0,
				max: SV,
				value: SV,
				slide: function(event, ui) {
					calc = Ce.height() - V.height() - ui.value;
					Ce.css('marginTop', -calc);
				}
			})
			.prev().children().mousewheel(function(objEvent, intDelta){
				var sc_scroller = $(this).parent().next();
				sc_scroller.slider("value", sc_scroller.slider("value") + (intDelta * MouseDeltaMultiplier));
			});
		}
	});

}

function setScrollbars() {
	
	$('#content .sc_scroller').each(function() {
		
		var fix = 110;
		var V = $(this).prev(); // Ventana
		try{console.debug(V);}catch(e){}
		var Ce = V.children(); // Contenido a escrolear
		/*if (Ce.height() > $(window).height() - fix) {
			V.height($(window).height() - fix);
		}*/
		$(this).css('height', V.height());
		$(this).css('marginLeft', '10px');

		if (Ce.height() > V.height()) {
			$(this).slider({
				orientation: 'vertical',
				min: 0,
				max: Ce.height() - V.height(),
				value: Ce.height() - V.height()
			}).
			bind("slide slidechange", function(e, ui) {
				
				var val = ui.value;
				calc = Ce.height() - V.height() - val;
				Ce.css('marginTop', -calc);
			})
			.prev().children().mousewheel(function(objEvent, intDelta){
				var sc_scroller = $(this).parent().next();
				sc_scroller.slider("value", sc_scroller.slider("value") + (intDelta * MouseDeltaMultiplier));
			});

			//Ce.width(V.width() - $(this).width() - 20);
		}
	});
	/*$("._contenido").mousewheel(function(objEvent, intDelta){
		$('#content .sc_scroller').each(function(){
			$(this).slider("value", $(this).slider("value") + (intDelta * MouseDeltaMultiplier));
		});
	});*/
}


function dbg(o) {
	try {
		console.debug(o);
	} catch (e) { /*fucking ie*/
	}
}
