// Variable globales
// ---------------------------------------
var listadoDesplegado = false;
var lang = "es";
$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase()); 
// ---------------------------------------
// PORTFOLIO
var title_actual = "";
var listado_height = 0;
var min_height = 342;

var fila1 = -10;
var fila2 = -150;
var fila3 = -290;
var fila4 = -430;
var fila5 = -570;
var fila6 = -710;
var fila7 = -850;
var max_fila = 0;

var columna1 = 480;
var columna2 = 300;
var columna3 = 119; 
var columna4 = -61; 
var columna5 = -242;

var poweringTheArts_height = 679;
var gentDeVins_height = 426;
var trespins_height = 528;

var filtrar = new Array();
var contador_filtro = 0;

// ---------------------------------------

// Recogemos las variables GET para poder tratarlas
var $_GET = {};

document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
    }

    $_GET[decode(arguments[1])] = decode(arguments[2]);
});
// ---------------------------------------
// FORMULARIOS

function obligatorio(id, campo_es, campo_ca)
{
	problem = false;

	if ( !problem ) {
		if ( $("#" + id).val() == "" ) {
			msg = ( lang == "es" ) ? "El campo " + campo_es + " es obligatorio" : "El camp " + campo_ca + " és obligatori";
			alert(msg);
			$("#" + id).focus();
			problem = true;
		}
	}

	return problem;
}

function esemail(id, campo_es, campo_ca)
{
	problem = false;

	str = new String($("#" + id).val());
	var supported = 0;
	if (window.RegExp) {
		var tempStr = "a";
		var tempReg = new RegExp(tempStr);
		if (tempReg.test(tempStr)) supported = 1;
	}
	if (!supported) return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{2,4})(\\]?)$");
	if ((!r1.test(str) && r2.test(str)) || (str == ""))
	{
		// Correcto
	} else {
		msg = ( lang == "es" ) ? "El formato de mail del campo " + campo_es + " no es valido" : "El format de mail del camp " + campo_ca + " no es valid";
		alert(msg);
		$("#" + id).focus();
		problem = true;
	}

	return problem;
}

// ---------------------------------------

function volver()
{
	$(".volver").click(function(e){
		e.preventDefault();

		listadoDesplegado = false;

		$(".detalle").fadeOut("slow").remove();
		$(".absolute").fadeOut("slow").remove();
		$(".listado").show();
		$(".listado li > div").children().show();
		$(".listado > ul > li").removeClass("oculto");
		$(".listado li > div").children("div").hide();
		$(".listado li > div").fadeIn("slow");

		$(".listado").animate({"height":listado_height}, false);
		$("html head title").html(title_actual);

		if ( $.browser.chrome ) {
			$("#contenido").height(listado_height+80);
		}
	});
}

$.extend({
	random: function(X) {
	    return Math.floor(X * (Math.random() % 1));
	},
	randomBetween: function(MinV, MaxV) {
	  return MinV + jQuery.random(MaxV - MinV + 1);
	}
});

/* ******************************************** */

$(document).ready(function() {

	lang = $("html").attr("lang");

	if ( $("#contenido .listado").length > 0 ) {

		if ( $("#filtro").length > 0 ) {
			$("#filtro input[type='checkbox']").click(function(){

				filtrar = new Array();
				contador_filtro = 0;

				$("#filtro ul li input:checked").each(function(){
					filtrar[contador_filtro] = $(this).val();
					contador_filtro++;
				});

				$("#filtro").next("ul").children("li").children("div").each(function(){

					encontrado = false;
					for ( i=0; ( (i<filtrar.length) && (!encontrado) ); i++ ) {
						if ( $(this).hasClass(filtrar[i]) ) {
							encontrado = true;
						}
					}				

					if ( encontrado ) {
						$(this).removeClass("ocultar");
						$(this).parent().fadeIn("slow");
					} else {
						$(this).addClass("ocultar");
						$(this).parent().fadeOut("slow");
					}
				});
			});
		}

		// ----------------------------------------------------------

		title_actual = $("html head title").html();

		var fila = 0;
		var columna = 0;
		$(".listado > ul > li").each(function(i){

			columna++;

			if ( (i%5) == 0 ) {
				fila++;
				max_fila++;
				columna = 1;
			}

			$(this).addClass("fila" + fila).addClass("columna" + columna);

			// Ubicamos la clase ultimo, la última
			if ( $(this).hasClass("ultimo") ) {
				$(this).removeClass("ultimo").addClass("ultimo");
			}
		});

		listado_height = $("#contenido .listado").height();

		if ( $.browser.chrome ) {
			$("#contenido").height(listado_height+80);
		}

		$(".listado a").click(function(e){
			e.preventDefault();

			if( !$(".listado").is(":animated") ) {

				obj = this;
				src = $(this).find("img").attr("src");

				$(this).parent().children().fadeOut("fast");

				$(".listado img").each(function(){

					$(this).parents().each(function(){
						
						if ( $(this).get(0).tagName == "DIV" ) {
							$(this).fadeOut(3000);
							
							return false;
						}

						if ( $(this).get(0).tagName == "LI" ) {
							return false;
						}
					});
				});

				if ( !listadoDesplegado ) {

					listadoDesplegado = true;

					clases = $(this).parent().parent().attr("class").replace("ultimo ", "").split(" ");

					_top = eval(clases[0]);
					_left = eval(clases[1]);
					
					_height = min_height;
					try {
						_height = eval($(this).parent().parent().find("div > a").attr("name") + "_height");
					}
					catch (err) { }


					img_seleccionada = $(this).parent().parent().find("div > a > img").attr("src");
					arr_img = img_seleccionada.split(".");
					img_seleccionada = arr_img[0] + "g." + arr_img[1];

					$('html, body').animate({scrollTop:0}, 'slow');

					$(this).parent().parent().prepend("<img src='" + $(obj).parent().find("img").attr("src") + "' class='absolute'>");
					$(this).parent().parent().find(".absolute").animate({"top":_top,"left":_left,"width":415,"height":326},3000, function(){

						$(".listado").animate({"height":_height}, 1000);

						$(this).attr("src", img_seleccionada);


						// Escondemos los otros proyectos para que no se solape el menú y el pie
						fila = $(this).parent().attr("class").substring(4, $(this).parent().attr("class").indexOf(" "));

						for ( i=1; i<=max_fila; i++ ) {
							if ( parseInt(fila,10) != i ) {
								$(".listado > ul > .fila" + i).addClass("oculto");
							}
						}

						$(this).animate({"top":fila1}, 0);


						// Titulo
						tag = $(obj).parent().parent().children("div").children("div").prev().get(0).tagName.toLowerCase();
						tagHtml = $(obj).parent().parent().children("div").children("div").prev().html();
						soloTitulo = $(obj).parent().parent().children("div").children("div").prev().children("span").html();
						titulo = "<" + tag + ">" + tagHtml + "</" + tag + ">";

						$("html head title").html(soloTitulo + " | " + title_actual);

						html = titulo + $(obj).parent().parent().children("div").children("div").html();

						try
						{
							if ( $.browser.msie ) {
								$("#contenido").prepend("<div class='detalle'>" + html + "</div>");
								$("#contenido .detalle").slideDown(2000);
								volver();
							} else {
		
								$("html head title").html(soloTitulo + " | " + title_actual);

								$(".listado li div").children().each(function(i){
									
									$(this).fadeOut("slow", function(){

										if( i == $(".listado li > div").children().length - 1 ) {
											$("#contenido").prepend("<div class='detalle'>" + html + "</div>");
											$("#contenido .detalle").slideDown(2000);
											volver();
										}
									});
								});
							}

							if ( $.browser.chrome ) {
								$("#contenido").height("auto");
							}
						}
						catch (err)
						{
						}
					});
				}
			}
		});

		if ( $_GET["proyecto"] != "undefined" ) {
			if ( $('a[name="' + $_GET["proyecto"] + '"]').length > 0 ) {
				$('a[name="' + $_GET["proyecto"] + '"]').click();
			}
		}
	}

	if ( $("#contenido.servicios").length > 0 ) {

		$("#contenido.servicios div a").click(function(e){
			e.preventDefault();
		});
		
		$("#contenido.servicios div > div").each(function(i){
			var tmp = parseInt( Math.random() * 3);

			if ( tmp == 1 ) {
				tmp = 15;
				$(this).addClass("fondo15");
			} else if ( tmp == 2 ) {
				$(this).addClass("fondo20");
			} else {
				/*
					Es por defecto: $(this).addClass("fondo15");
				*/
			}

		});			
	}

	if ( $("#formContacto").length > 0 ) {
		$("#formContacto #nombre").focus();
		
		$("#formContacto").submit(function(e){

			problem = false;

			if ( !problem ) {
				problem = obligatorio("nombre", "NOMBRE", "NOM");
			}
			if ( !problem ) {
				problem = obligatorio("apellidos", "APELLIDOS", "COGNOMS");
			}
			if ( !problem ) {
				problem = obligatorio("telefono", "TEL\u00C9FONO", "TEL\u00C8FON");
			}
			if ( !problem ) {
				problem = obligatorio("direccion", "DIRECCI\u00D3N", "ADREÇA");
			}
			if ( !problem ) {
				problem = obligatorio("ciudad", "CIUDAD", "CIUTAT");
			}
			if ( !problem ) {
				problem = obligatorio("email", "E-MAIL", "E-MAIL");

				if ( !problem ) {
					problem = esemail("email", "E-MAIL", "E-MAIL");
				}
			}
			if ( !problem ) {
				problem = obligatorio("motivo", "MOTIVO DEL CONTACTO", "MOTIU DEL CONTACTE");
			}
			if ( !problem ) {
				problem = obligatorio("conocido", "C\u00D3MO NOS HA CONOCIDO", "COM ENS HA CONEGUT");
			}
			if ( !problem ) {
				problem = obligatorio("comentarios", "COMENTARIOS", "COMENTARIS");
			}

			if ( !problem ) {
				$("#idioma").val(lang);
			}

			return (!problem);
		});
	}

	if ( $_GET["w"] != "undefined" ) {
		var w = $_GET["w"];
		
		$(".listado ul li div a").each(function(){
			if ( $(this).attr("name") == w ) {
				$(this).click();
			}
		});
	}

	// ----------------------------------------------------------

	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");

	//use jQuery to call the Google Analytics JavaScript
	$.getScript(gaJsHost + "google-analytics.com/ga.js", function(){

		//tell Analytics about the current page load using standard _trackPageview method
		try {
			var pageTracker = _gat._getTracker("UA-4539308-1");
			pageTracker._trackPageview();
		} catch(err) {}

		var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;

		//loop though each anchor element
		$('a').each(function(){

			var href = $(this).attr('href');

			//check for links starting with http or https, making sure that links to our own domain are excluded
			if ((href.match(/^https?\:/i)) && (!href.match(document.domain))){
				$(this).click(function() {
					var extLink = href.replace(/^https?\:\/\//i, '');
					pageTracker._trackEvent('External', 'Click', extLink);
				});
			}
			//check for links starting with mailto:
			else if (href.match(/^mailto\:/i)){
				$(this).click(function() {
					var mailLink = href.replace(/^mailto\:/i, '');
					pageTracker._trackEvent('Email', 'Click', mailLink);
				});
			}
			//check for links with file extension that match the filetypes regular expression:
			else if (href.match(filetypes)){
				$(this).click(function() {
  					var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
					var filePath = href.replace(/^https?\:\/\/(www.)mydomain\.com\//i, '');
					pageTracker._trackEvent('Download', 'Click - ' + extension, filePath);
				});
			}
			//servicios
			else if (href.match(/^portfolio_detalle/i)){
				$(this).click(function() {
					var mailLink = $(this).attr("title").replace(/^Ir a /i, '').replace(/^Anar a /i, '');
					pageTracker._trackEvent('Portfolio Detalle', 'Proyecto - ' + mailLink, $(this).attr("href"));
				});
			}
			//portfolio_detalle
			else if ( (href.match(/^#/i)) && ( $(".servicios").length > 0 ) ) {
				$(this).mouseover(function() {
					var mailLink = $(this).attr("title");
					pageTracker._trackEvent('Servicio Detalle', 'Servicio - ' + mailLink, mailLink);
				});
			}
		});
	});
});
