var flagMenus = false;

function cambiarPrincipal(enlace) {
	$('#principal *').unbind();
	iniciarCambiarPrincipal(function() {
		// Pasamos como argumento la funcion que se ejecutara al finalizar la animacion de salida

		$.ajax({
	        url: enlace,
	        dataType: 'html',
			async: true,
	        success: function(r) {
				var _r = $(r).find('#principal');
	            _r.hide().replaceAll('#principal');
				finalizarCambiarPrincipal(_r.attr('className'));
	        }
	    });
	});
}

function iniciarCambiarPrincipal(callback) {
    var principal = $('#principal');
    var familia = principal.attr('className');
    var cen = $('div.decoCentral');
    var izq = cen.prev();
    var der = cen.next();

    if (familia.indexOf('estandar') != -1) {
        familia = 'estandar';
    }
	// animaciones de salida (dependen de las clases CSS)
	switch (familia) {
		case 'estandar':
			cen.css({
				'overflow': 'hidden',
				'width': cen.width() + 'px',
				'height': cen.height() + 'px'
			});
			principal.css({'overflow': 'hidden', 'width': principal.width() + 'px', 'height': principal.height() + 'px'})
			    .animate({'width': principal.width() - 29 + 'px'}, 600, 'easeOutQuint')
			    .hide('blind', {direction: 'left'}, 800, callback);
			break;
		case 'packaging':
		    der.hide('drop', {direction: 'left'}, 400, function() {
				cen.hide('fold', {size: 404}, 900, function() {
					izq.hide('blind', {
						direction: 'vertical'
					}, 600, callback);
				})
			});
			break;
		case 'comunicacion':
			der.hide('blind', {direction: 'left'}, 400, function() {
				cen.hide(600, function() {
				    izq.hide('blind', {direction: 'right'}, 800, callback)
                });
			});
			break;
		case 'editorial':
            if (!$('#temporalAnimacion').is('div')) {
				principal.wrapInner('<div id="temporalAnimacion"></div>');
			}
			$('#temporalAnimacion').css({
				overflow: 'hidden',
				position: 'relative',
				width: '737px',
				height: '456px'
			}).parent().hide('clip', {direction: 'horizontal'}, 1000, callback);
			$('#temporalAnimacion').animate({'left': -737/2 +'px'}, 1000)
			break;
		default:
            der.hide('drop', {direction: 'left'}, 400, function() {
				principal.hide('fold', {size: 150}, 1000, callback);
			});
	}
}

function finalizarCambiarPrincipal(familia) {
    var principal = $('#principal');
    var familia = principal.attr('className');
    var cen = $('div.decoCentral');
    var izq = cen.prev();
    var der = cen.next();
    var posFondo;

	switch ($('#principal').attr('className')) {
	    case 'packaging':
	        posFondo = '(0% 0%)';
	        break;
	    case 'identidad':
	        posFondo = '(100% 0%)';
	        break;
	    case 'editorial':
	    case 'comunicacion':
	        posFondo = '(0% 100%)';
	        break;
	    case 'case':
	        posFondo = '(100% 100%)';
	        break;
	    default:
	        posFondo = '(50% 50%)';
	}

    if (familia.indexOf('estandar') != -1) {
        familia = 'estandar';
    }

	prepararEventos();

    switch (familia) {
		case 'estandar':
			principal.css({'overflow': 'hidden', 'width': 674-29 +'px'})
			    .show('blind', {direction: 'left'}, 800)
				.animate({'width': '674px'}, 600, 'easeInQuint', function() {
				    flagMenus = false;
				    $('#fondo').animate({'backgroundPosition': posFondo}, 1500);
				});
			break;
		case 'packaging':
		    principal.children().hide().parent().show();
			izq.show('blind', {direction: 'vertical'}, 600, function() {
				cen.show('fold', {size: 404}, 900, function() {
					der.show('drop', {direction: 'left'}, 400, function() {
					    flagMenus = false;
					    $('#fondo').animate({'backgroundPosition': posFondo}, 1500);
					});
				});
			});
			break;
		case 'comunicacion':
		    principal.children().hide().parent().show();
		    izq.show('blind', {direction: 'right'}, 800, function() {
				cen.show(600, function() {
                    der.show('blind', {direction: 'left'}, 400, function() {
                        flagMenus = false;
                        $('#fondo').animate({'backgroundPosition': posFondo}, 1500);
                    });
                });
			});
			break;
		case 'editorial':
            principal.wrapInner('<div id="temporalAnimacion"></div>').children().css({
                overflow: 'hidden',
                position: 'relative',
                width: '737px',
                height: '456px',
				left: -737/2 +'px'
            }).end().show('clip', {direction: 'horizontal'}, 1000);
            $('#temporalAnimacion').animate({'left': 0}, 1000, function() {
                flagMenus = false;
                $('#fondo').animate({'backgroundPosition': posFondo}, 1500);
            })
			break;
		default:
            der.hide();
			principal.show('fold', {size: 150}, 1000, function() {
				der.show('drop', {direction: 'left'}, 400, function() {
				    flagMenus = false;
                    $('#fondo').animate({'backgroundPosition': posFondo}, 1500);
				});
			});
	}

}

function prepararEventos() {
	/* Definimos todos los eventos dentro de una funcion
	 * para poder llamarlos cada vez que recarguemos una
	 * parte de <div id="principal" /> por AJAX
	 * IMPORTANTE: siempre que se llame a esta funcion
	 * se tienen que desvicular los eventos mediante
	 * $('#principal *').unbind()
	 */

	// linksBlank(); // Links en ventana nueva / De momento no se usa
	clasesListado(); // Poner clases a los listados

	// Desplegable del archivo de noticias
	$('#archivoNoticias').find('span a').click( function() {
		$('#archivoNoticias').children('ol').toggle(400);
		return false;
	}).end().mouseout( function() {
		this.temporizador = setTimeout(function() {
			$('#archivoNoticias').children('ol').hide(400);
		}, 1000);
	}).mouseover( function() {
		clearTimeout(this.temporizador);
	});

	// acciones de los links del <ul id="submenuPrincipal" />
	$('#submenuPrincipal a').click( function() {
		var _this = $(this);
		if (_this.is('.activo')) {
			return false; // si el elemento ya esta activado paramos aqui
		}
		$('#submenuPrincipal a.activo').removeClass('activo');
		_this.addClass('activo');
		$('#submenuSecundario li').filter(':visible').fadeOut(400, function() {
			$('#submenuSecundario li.'+ _this.attr('id')).fadeIn(400).eq(0).find('a').click();
		});
		return false;
	});

	// cambiar de proyecto (animacion y AJAX)
	var cambiarProyecto = function(urlProyecto) {
		$('#principal *').unbind(); // resetearemos TODO evento del <div id="principal" />
		$('div.decoCentral, div.decoDerecha').children().fadeOut(400);
        $.ajax({
            url: urlProyecto,
            type: 'GET',
            dataType: 'html',
            success: function(r) {
                var _r = $(r).find('#principal').find('div.decoCentral, div.decoDerecha').children().hide().end();
				// cambiamos los bloques central y derecho manteniendolos ocultos
                $('div.decoCentral').replaceWith(_r.eq(0));
                $('div.decoDerecha').replaceWith(_r.eq(1));
				// ocultamos los hijos, mostramos los padres y hacemos fadein
				$('div.decoCentral, div.decoDerecha').children().fadeIn(800);
				prepararEventos();

            }
        });
	}

	// cambiar de proyecto (menu secundario)
	$('#submenuSecundario a').click( function() {
		var _this = $(this);
		if (_this.is('.activo')) {
			return false;
		}
		// Comprobamos si tenemos que cambiar la clase del menu principal
		var numElemento = _this.parent().attr('className');
		numElemento = parseInt(numElemento.substring(numElemento.lastIndexOf('elemento')+8));
		$('#elemento'+ numElemento).click();
		// Cambiamos clases dentro del menu secundario
		$('#submenuSecundario a.activo').removeClass('activo');
		_this.addClass('activo');
        cambiarProyecto(this.href);
		return false;
	});

	$('#ampliarImagen').lightbox();

    $('#thumbnails a').click( function() {
        var _this = $(this);
        if (_this.is('.activo')) {
            return false; // si el elemnto ya esta activado paramos aqui
        }
		$('#ampliarImagen').attr('href', this.href)
        var numImagen = _this.attr('id').substring(7);
        $('#thumbnails a.activo').removeClass('activo');
        _this.addClass('activo');
        $('#imagen'+ numImagen).siblings().filter(':visible').fadeOut(400, function() {
            $('#imagen'+ numImagen).fadeIn(800).siblings().hide();
        });
        return false;
    });

	// Otros trabajos para el cliente y listados de proyectos, noticias y clientes
	$('div.infoProyecto, ul.trabajosRecientes,  #listadoNoticias, #listadoClientes ul').find('a').add('#volverListado').click( function() {
		cambiarPrincipal(this.href);
		return false;
	});

    // Control flechas siguiente/anterior
    var activo = $('#submenuSecundario a.activo').parent();
    if (activo.prev().children().attr('href')) {
        $('#navegacionProyecto a.anterior').show().click( function() {
            activo.prev().children().click();
        });
    }
    if (activo.next().children().attr('href')) {
        $('#navegacionProyecto a.siguiente').show().click( function() {
            activo.next().children().click();
        });
    }

	// paginacion (comprobado sobre noticias)
	$('ul.paginacion a').click( function() {
		var _this = $(this);
		var pagina = parseInt(_this.text());
		if (_this.is('.activo')) return false;
	    _this.parents('ul').find('a.activo').removeClass('activo').end()
		                   .prev().find('li:visible').fadeOut(200);
		setTimeout( function() {
			_this.addClass('activo').parents('ul').prev().find('li.pagina' + pagina).fadeIn(300);
	    }, 300);

		return false;
	});

	// archivo de noticias
	$('#archivoNoticias ol a').click( function() {
		var _this = $(this);
	    var contenedor = $('div.decoCentral');

		$.ajax({
	       url: this.href,
		   method: 'get',
		   dataType: 'html',
		   beforeSend: function() {
		   	   $('#principal *').unbind();
			   contenedor.hide(600);
		   },
		   complete: function(r) {
		   	   contenedor.stop();
			   $(r.responseText).find('div.decoCentral').hide().replaceAll('div.decoCentral').show(600);
			   prepararEventos();
		   }
		});
		return false;
	});

	$('form').submit( function() {
		$.ajax({
			url: 'contacto.php',
			type: 'post',
			data: $('form').serialize() + '&enviado=1',
			dataType: 'html',
			success: function(r) {
				var oko = $(r).find('#mensajicos').children();
				if (oko.eq(0).is(':visible')) {
					$('div.ok').slideUp(600);
                    $('div.ko').slideDown(600, function() {
                        setTimeout(function() {
                            $('div.ko').slideUp(600);
                        }, 5000);
                    });
				} else if (oko.eq(1).is(':visible')) {
					$('div.ko').slideUp(600);
					$('div.ok').slideDown(600, function() {
						setTimeout(function() {
							$('div.ok').slideUp(600);
						}, 5000);
					});
					$('input, textarea').val('');
				} else {
					alert('Se ha producido un error interno. Por favor, p�ngase en contacto con Cusid� Comella a trav�s del correo eltr�nico que hallar� en esta misma p�gina.');
				}
			}
		});
		return false;
	});
}

// plugin de jQuery para la animacion del fondo
(function($) {
	$.extend($.fx.step,{
	    backgroundPosition: function(fx) {
            if (fx.state === 0 && typeof fx.end == 'string') {
                var start = $.curCSS(fx.elem,'backgroundPosition');
                start = toArray(start);
                fx.start = [start[0],start[2]];
                var end = toArray(fx.end);
                fx.end = [end[0],end[2]];
                fx.unit = [end[1],end[3]];
			}
            var nowPosX = [];
            nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
            nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
            fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

           function toArray(strg){
               strg = strg.replace(/left|top/g,'0px');
               strg = strg.replace(/right|bottom/g,'100%');
               strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
               var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
               return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
           }
        }
	});
})(jQuery);
