window.onload = init;

/**********************************************************************************
 * FUNCIONES GENERALES
 *********************************************************************************/
/**
 * Animacion inicial de la pagina
 */
function init(){
	// listen menu
	var items = $$("#menu li a");
	items.each(function(el){
		el.observe("click",goTo);
	});
	anima();
}

/**
 * Anima el titulo segun la seccion en la que nos encontremos
 */
function animaTitulo(seccion) {
   
    var correlacion = [];
    correlacion['home']=[]; correlacion['home']['letras']=['n','m']; correlacion['home']['color']="#2DACFD";
    correlacion['contact']=[]; correlacion['contact']['letras']=['b','o']; correlacion['contact']['color']="#FFA500";
    correlacion['gallery']=[]; correlacion['gallery']['letras']=['i','r']; correlacion['gallery']['color']="#8FBB3F";
    correlacion['where']=[]; correlacion['where']['letras']=['e','d']; correlacion['where']['color']="#FFFF00";

    // quitamos las letras anteriores
    $$('.resaltada').each(function(element) {
        $(element).morph('color:#FFFFFF');
        $(element).removeClassName('resaltada');
    })

    // animamos las letras de la seccion correspondiente
    for (var i=0; i<correlacion[seccion]['letras'].length; i++) {
        var letra = correlacion[seccion]['letras'][i];
        $(letra).morph("color:"+correlacion[seccion]['color']);
        $(letra).addClassName('resaltada');
    }
}

/**
 * Cambia de pagina/seccion
 */
function goTo(ev){
	// elimino la seccion resaltada
	var actual = $$("#menu li a.selected")[0];
	if(document.all)
		$(actual).setAttribute("className","");
	else
		$(actual).setAttribute("class","");

	// obtengo la seccion clicada
	var element = Event.element(ev);
	var id = element.id;

	// resalto la nueva seccion
	if(id == "home")
		element.addClassName("blue selected");
	else if (id == "contact")
		element.addClassName("orange selected");
	else if (id == "gallery")
		element.addClassName("green selected");
	else if (id == "where")
		element.addClassName("yellow selected");

	// animacion de cambio
	animaCambio(id);

	// paramos el evento para que no se lance la ejecucion del enlace
	Event.stop(ev);
	
	return false;
}

/**
 * Funcion que anima la pagina al cargar o recibir un nuevo contenido
 */
function anima(){
	var parrafos = $$('#infoCont p');

	//animamos la imagen
	new Effect.Appear("img",{duration: 0.8});
	new Effect.Move("img",{y:0,x:10,mode:'absolute',duration: 0.8});

	// comprobamos si hay otro objeto a animar (formulario, mapa o galeria)
	var objetos = $$('#infoCont div.obj');
	var iterador = parrafos.size();
	objetos.each(function(el){
		parrafos[iterador++] = el;
	});

	// animamos el texto
	var retardo = 0.0;
	parrafos.each(function(el){
		new Effect.Appear(el,{duration: 1.0, delay: retardo*2});
		new Effect.Move(el,{y:0, x:-150, mode:'relative', duration: 0.8, delay: retardo});
		retardo = retardo+0.1;
	});
	
	return false;
}

/**
 * Funcion realiza la animacion al abandonar una seccion, y que realiza la peticion por AJAX de la seccion solicitada
 * @param seccion identificador de la seccion a cargar
 */
function animaCambio(seccion){
    // animamos in y spain
    new Effect.Morph('in',{
        queue: {position:'front', scope:'inscope', limit:2},
        style: 'font-size:70px; position:relative; top:-3px; left:-15px; color:#ffffff',
        duration: 0.3
    });
    new Effect.Morph('in',{
        queue: {position:'end', scope:'inscope', limit:2},
        style: 'font-size:20px; position:relative; left:3px; color:#c1c1c1; top:7px',
        duration: 0.3
    });

    new Effect.Morph('spain',{
        queue: {position:'front', scope:'spainscope', limit:2},
        style: 'font-size:70px; position:absolute; top:-60px; left:305px; color:#ffffff',
        duration: 0.3
    });
    new Effect.Morph('spain',{
        queue: {position:'end', scope:'spainscope', limit:2},
        style: 'font-size:30px; position:absolute; left:342px; color:#c1c1c1; top:-15px',
        duration: 0.3
    });
    
    //animamos la imagen
    new Effect.Puff("img",{duration: 0.5});

    // recuperamos el texto
    var parrafos = $$('#infoCont p');
    // comprobamos si hay otro objeto a animar (formulario, mapa o galeria)
    var objetos = $$('#infoCont div.obj');
    var iterador = parrafos.size();
            objetos.each(function(el){
            parrafos[iterador++] = el;
    });

    // animamos el texto
    var retardo = 0.0;
    parrafos.each(function(el){
            if(el == parrafos.last()){
                    new Effect.Fade(el,{duration: 1.0});
                    new Effect.Move(el,{y:0, x:-2000, mode:'relative', duration: 1.0, delay: retardo,
                            afterFinish:function(){
                                    // al finalizar la animacion solicito los datos de la nueva seccion
                                    $("infoCont").update("<div id='loading'>loading</div>");
                                    var url = $(seccion).href;
                                    new Ajax.Request(url,{
                                            method: 'get',
                                            onComplete:getSeccionOk
                                    });
                            }
                    });
            }
            else {
                    new Effect.Fade(el,{duration: 1.0});
                    new Effect.Move(el,{y:0, x:-2000, mode:'relative', duration: 1.0, delay: retardo});
            }
            retardo = retardo+0.1;
    });
}


/**
 * Callback al recepcionar la respuesta de la peticion AJAX. Carga el contenido de la seccion a visualizar
 */
function getSeccionOk(transport){
	$("infoCont").update(transport.responseText);
	anima();
}

/**********************************************************************************
 * FUNCIONES DE LA SECCION HOME
 *********************************************************************************/
function initHome() {
    animaTitulo('home');
}

/**********************************************************************************
 * FUNCIONES DE LA SECCION DE CONTACTO
 *********************************************************************************/
/**
 * Inicializa la pagina de contacto
 */
function initContact(){
    animaTitulo('contact');
    // listeners
    $("btForm").observe('click',goToForm);
    $("btClose").observe('click',goToText);
}

/**
 * Muestra el formulario en la seccion de contacto
 */
function goToForm(){
	var parrafos = $$('#infoCont p');
	
	// quitamos el texto
	parrafos.each(function(el){
		new Effect.Opacity(el,{duration: 1.0,from: 1.0, to: 0.0});
		new Effect.Move(el,{y:-430, x:0, mode:'relative', duration: 0.8});
	});
	
	// mostramos el formulario
	new Effect.Appear('contFormulario',{duration: 1.0});
	new Effect.Move('contFormulario',{y:-360, x:0, mode:'relative', duration: 0.8});
	Form.reset('formulario');
	$('contFormulario').addClassName('visible');
}

/**
 * Cierra el formulario en la seccion de contacto
 */
function goToText(){
	var parrafos = $$('#infoCont p');
	
	// mostramos el texto
	parrafos.each(function(el){
		new Effect.Opacity(el,{duration: 1.0, from: 0.0, to: 1.0});
		new Effect.Move(el,{y:430, x:0, mode:'relative', duration: 0.8});
	});
	
	// quitamos el formulario
	new Effect.Fade('contFormulario',{duration: 1.0});
	new Effect.Move('contFormulario',{y:360, x:0, mode:'relative', duration: 0.8});
	$('contFormulario').removeClassName('visible');
}

/**
 * Muestra u oculta el formulario
 * @param bool show
 */
function showForm(show){
	if(show === true) new Effect.Opacity('contFormulario',{from:0.1,to:1.0});
	else new Effect.Opacity('contFormulario',{from:1.0,to:0.1});		
}

/**
 * Devuelve un array con los errores que hay en el formulario
 * @return array
 */
function errores(){
	// comprobamos los valores
	var errores = new Array();
	if($F('nombre') == '' || $F('nombre') == null)
		errores.push('name');
	if($F('phone') == 'telefono' && ($F('telfEmail') == '' || $F('telfEmail') == null))
		errores.push('telephone');
	if($F('mail') == 'email' && ($F('telfEmail') == '' || $F('telfEmail') == null))
		errores.push('email');
	if($F('msg') == '' || $F('msg') == null)
		errores.push('message');
	return errores;
}

/**
 * Funcion que envia el mensaje desde la web
 */
function enviarMensaje(){
	var err = errores();
	
	// comprobamos si se han rellenado los campos
	if(err.size() > 0){
		var errorMessage = '';
		if(err.size() == 1)
			errorMessage = err[0].capitalize() + ' is required.';
		else if(err.size() == 2)
			errorMessage = err[0].capitalize() + ' and ' + err[1] + ' are required.';
		else
			errorMessage = err[0].capitalize()+ ', ' + err[1] + ' and ' +err[2] + ' are required.';
		errorMessage += "<span title='close' id='btCloseMsg'>x</span>";

		showForm(false);
		showMessage(errorMessage,'msgError');
	}
	else{
		// si no hay errores enviamos los datos
		var datos = $('formulario').serialize();
		var url = "sender.php";
		new Ajax.Request(url,{
			method: 'post',
			postBody: datos,
			onCreate:waitMail,
			onComplete:enviarMensajeOk
		});
	}

	return false;
}

/**
 * Funcion que indica que se esta enviando el email
 */
function waitMail(transport){
	showForm(false);
	
	// anulamos el menu y el abandonar el formulario
	var items = $$("#menu li");
	items.each(function(el){
		el.stopObserving("click",goTo);
	});
	
	//mostramos el mensaje de espera
	showMessage('Sending message', 'msgWait');
}

/**
 * Funcion que procesa la respuesta al envio del mensje
 */
function enviarMensajeOk(transport){
	var respuesta = transport.responseText;
	var oRespuesta = respuesta.evalJSON(true);

	if(oRespuesta.enviado)
		showMessage("Message send OK", 'msgOk', true);
	else
		showMessage("Error: can not send message in this moment.", 'msgError', true);
}

/**
 * Cierra un mensaje popUp
 */
function closeMessage(){
	showForm(true);

	// reestablecemos los listen del menu y del boton de cerrar form
	var items = $$("#menu li");
	items.each(function(el){
		el.observe("click",goTo)
	});
	
	$("btClose").observe('click',goToText);

	// establecemos el mensaje por defecto
	$('enviando').hide();
	$('enviando').update("sending message");
}

/**
 * Muestra un mensaje
 */
function showMessage(msg, type, btClose){
	
	$('btClose').stopObserving('click',goToText);
		
	var btClose = (btClose === true)? "<span title='close' id='btCloseMsg'>x</span>" : "";
	msg += btClose;
	
	$('enviando').update(msg);
	$('enviando').show();
	
	$('enviando').removeClassName('msgError');
	$('enviando').removeClassName('msgOk');
	$('enviando').removeClassName('msgWait');
	$('enviando').addClassName(type);
	
	if($('btCloseMsg')) $('btCloseMsg').observe('click',closeMessage);
}


/**********************************************************************************
 * FUNCIONES DE LA GALERIA DE IMAGENES
 *********************************************************************************/
/**
 * Inicializa la pagina de la galeria
 */
function initGallery(){
    animaTitulo('gallery');

    // listeners
    $("next").observe('click',nextImage);
    $("prev").observe('click',prevImage);

    NUM_IMAGENES =  28; // indica el mayor numero de imagen, para pasar de la ultima al cero y viceversa
    LIMIT_1 = 9;		// indica el limite para concatenar 2 ceros por la izquierda
    LIMIT_2 = 99;		// indica el limite para concatenar 1 cero por la izquierda
}

/**
 * Muestra la siguiente imagen de la galeria 
 * @return
 */
function nextImage(){
	$('next').stopObserving('click',nextImage);
	$('prev').stopObserving('click',prevImage);
	
	// obtengo la actual
	var actual = $('imgGallery').getAttribute('class');
	if(actual == null)
		actual = 0;
	actual = Number(actual);
		
	var next = (actual < NUM_IMAGENES)? actual+1 : 0;
	var ceros = "";

	if(next <= LIMIT_1)
		ceros = "00";
	else if(next <= LIMIT_2)
		ceros = "0";
	
	//mostramos mensaje de cargando
	new Effect.Opacity('imgGallery',{form:1.0, to:0.2, duration:1.0,queue:'end',
		afterFinish:function(){
			// precargamos la imagen
			$('imgGallery').setAttribute('class',next);
			var url = "imagenes/small/"+ceros+next+".jpg";
			var i = new Image();
			i.src = url;
			i.onload = imgCargada(url,i);	
		}
	});
	$('loadingImg').show();
	
}

/**
 * Funcion que cambia la imagen cuando la imagen esta cargada
 */
function imgCargada(url){
	$('imgGallery').src = url;
	new Effect.Opacity('imgGallery',{form:0.2, to:1.0, duration:1.0,queue:'end',
		beforeStart:function(){
			$('loadingImg').hide();
		}
	});
	$("next").observe('click',nextImage);
	$("prev").observe('click',prevImage);
}

/**
 * Muestra la anterior imagen de la galeria
 * @return
 */
function prevImage(){
	$('next').stopObserving('click',nextImage);
	$('prev').stopObserving('click',prevImage);

	// obtengo la actual
	var actual = $('imgGallery').getAttribute('class');
	actual = Number(actual);

	var next = (actual > 0)? actual-1 : NUM_IMAGENES;
	var ceros;

	if(next > LIMIT_1)
		ceros = "0";
	else if(next >= 0)
		ceros = "00";
		
	//mostramos mensaje de cargando
	new Effect.Opacity('imgGallery',{form:1.0, to:0.2, duration:1.0,queue:'end',
		afterFinish:function(){
			// precargamos la imagen
			$('imgGallery').setAttribute('class',next);
			var url = "imagenes/small/"+ceros+next+".jpg";
			var i = new Image();
			i.src = url;
			i.onLoad = imgCargada(url,i);	
		}
	});
	$('loadingImg').show();	
}

/**********************************************************************************
 * FUNCIONES DE LA SECCION WHERE WE ARE
 *********************************************************************************/
function initWhere() {
    animaTitulo('where');
}





