var AcordionDeListas = {
    selectorLi: null,
    titulos: ['Ver +', 'Ver -'],
    init: function (selectorUl, selectorLi) {
        this.selectorLi = selectorLi;
        // oculta todos los elementos li
        $( this.selectorLi ).hide();
        // agrega un elemento mas con el comando para el acordeón
        var lstPlegables = $( selectorUl )
        for (var i=0; i<lstPlegables.size(); i++) {
            // se crea el li que se empleara como botón si existen elementos plegables
            lstPlegable = $(lstPlegables[i]);
            if ( lstPlegable.find(this.selectorLi).size() > 0) {
                lstPlegable.append(
                    $('<li class="cmdOn">'+ this.titulos[0] +'</li>')
                        .css('cursor', 'pointer')
                        .bind('click', function () { AcordionDeListas.run( $(this) ); })
                );
            }
        }
    },
    run: function (boton) {
        if ( boton.html() == this.titulos[0] ) {
            boton.parent().find( this.selectorLi ).slideDown('slow');
            boton.html(this.titulos[1]);
        } else {
            boton.parent().find( this.selectorLi ).slideUp('slow');
            boton.html(this.titulos[0]);
        }
    }
};

var Preferido = {
    cmd: null,
    accion: 'quitar',
    enviando: false,
    valores : null,
    issetParent: false,
    init: function (cmdPreferido, issetParent) {
        if (cmdPreferido.size() > 0) {
            this.cmd = cmdPreferido;
            this.href = ( document.location.pathname ).split('/realizar')[0];
            this.issetParent = issetParent;

            this.valores = ( (this.cmd.attr('title')).search('casa') == -1 )
                ? {quitar: 'Quitar este apartamento de mis preferidos', agregar: 'Agregar este apartamento a mis preferidos' }
                : {quitar: 'Quitar esta casa de mi lista de preferidos', agregar: 'Agregar esta casa a mi lista de preferidos' };

            this.cmd.attr('href', '#')
                    .bind('click', function () { Preferido.cambiarEstado(); return false; });

            this.accion = this.cmd.attr('name');
        }
    },
    cambiarEstado: function () {
        if (this.enviando == false) {
            this.enviando = true;

            this.cmd.html('Cambiando, un momento por favor ...');

            jQuery.ajax( {
                data: { 'nocacheajax': (new Date).getTime(), 'realizar':'preferidos', 'accion': this.accion },
                dataType: 'json',
                timeout: 12000,
                type: 'GET',
                url: this.href,
                error: function (objXMLHttpRequest, error, exeption) {
                    Preferido.confirmarEstado(null);
                },
                success: function (data, result) {
                    Preferido.confirmarEstado(data);
                },
                complete: function (objXMLHttpRequest, result) {}
            } );
        }
    },
    confirmarEstado: function (data) {
        if (data) {
            // guarda la futura acción
            this.accion = data.accion;
        }

        // cambia las clases, coloca el html nombre y title correspondiente
        var clases = (this.accion=='agregar') ? ['cmdPreferidoOn', 'cmdPreferidoOff'] : ['cmdPreferidoOff', 'cmdPreferidoOn'];
        this.cmd.removeClass( clases[0] ).addClass( clases[1] )
                .html( this.valores[ this.accion ] )
                .attr('title', this.valores[ this.accion ])
                .attr('name', this.accion);

        if (this.issetParent == true) {
            top.Seleccion.cambiarEstadoPreferido( (this.accion=='agregar') ? 0 : 1 );
        }
        this.enviando = false;
    }
};

/******************************************************************************
 * Clase que controla la galería de fotos
 */
var GaleriaDeImagenes = {
    inicio: false,
    
    imgCambia: null, 

    className: null,

    galeria: null,
    numFotos: 0,

    fotoActual: 0,
    
    notificarFaltaImagen: true,

    init : function (className) {
        this.inicio = true;
        this.className = className;
    },
    prepare : function () {
        // SACAMOS LOS LINKS NORMALES
        $("#anchor").remove();
        //$("#anchor").hide();
        if (true === this.recuperarGaleria()) {
            if (this.numFotos > 1) {
                // COLOCAMOS LOS BOTONES
                $("#links")
                    .prepend('<div class="ctlFotos">'
                            +'<a id="anterior">anterior</a>'
                            +'<a id="siguiente">siguiente</a>'
                            +'<br class="clear" />'
                            +'<div id="numFoto"></div>'
                            +'</div>')
                    .css('margin-bottom', 0)
                    .css('position', 'relative')
                    .css('top', -46)

                $('#numFoto').html((this.fotoActual+1)+'/'+this.numFotos);
                var clouser = this;
                var anterior = $('#anterior');
                anterior.click( function() {
                    clouser.fotoActual--;
                    if (clouser.fotoActual < 0) { clouser.fotoActual = clouser.numFotos-1; }
                    return clouser.cambiarImagen();
                });
                var siguiente = $('#siguiente');
                siguiente.click( function() {
                    clouser.fotoActual++;
                    if (clouser.fotoActual >= clouser.numFotos) { clouser.fotoActual = 0; }
                    return clouser.cambiarImagen();
                });
            }
        } else {
            $('.contenedorImg').append('<a><img class="galeria" src="/public/imgs/nodisponibleg.jpg" width="520px" height="320px" /></a>');
        }
    },
    recuperarGaleria : function () {
        var imagenes = $('img.'+this.className);
        //var imagenes = $('img').filter('.'+this.className);
        var galeria = [];
        $.each( imagenes, function(i, imagen){
            if (imagen.src != null) {
                galeria[i] = imagen.src;
            }
        });

        this.imgCambia = imagenes[0];

        this.galeria = galeria;
        this.numFotos = galeria.length || 0;

        return (this.numFotos > 0);
    },
    cambiarImagen : function () {
        var clouser = this;
        var clouserSrcImg = this.galeria[this.fotoActual];
        $('#numFoto').html((this.fotoActual+1)+'/'+this.numFotos );
        $(this.imgCambia).fadeOut("slow", function () {
            this.src = clouserSrcImg;
            return $(clouser.imgCambia).fadeIn("slow");
        });
        return this;
    },
    imagenNoDisponible: function (img) {
        // sustituye el manejador para que no falle si la imagen sustituta no se encuentra
        img.onerror = function () {};
        
        if (this.inicio == false) {
            // si el objeto que controla la galería no se inicio quita la imagen
            img.parentNode.removeChild(img);
        } else {
            // sustituye el src de la imagen
            img.src = '/public/imgs/nodisponibleg.jpg';
        }

        // si ahu no se ha notificado de faltas de imágenesse notifica
        if (this.notificarFaltaImagen == true) {
            this.notificarFaltaImagen = false;

            // /ficha/rei/numero/x.x.x > rei registro de error en imagenes
            var urlRei = document.location.pathname;
            urlRei = urlRei.replace('casa', 'rei');
            urlRei = urlRei.replace('apartamento', 'rei');
            $.get( urlRei );
        }
    }
};

/*******************************************************************************
 * Clase que controla el despliegue y el envió de consultas sobre las propiedades
 */
var FormularioConsultaPorPropiedad = function(){ return this.construct.apply(this, arguments); };
FormularioConsultaPorPropiedad.prototype = {
    formulario : null,
    zonaMensajes : null,
    disparadorToggle : null,

    scroll : 0,
    moveScroll : null,

    construct : function (name) {
        this.formulario = $('#'+name);
        return this;
    },
    setZonaMensajes : function (zona) {
        this.zonaMensajes = !document.getElementById('mensajeForm');
        return this;
    },
    setDisparadorToggle : function (disparador) {
        this.disparadorToggle = $('#'+disparador);
        return this;
    },
    prepare : function () {
        if (this.zonaMensajes) {
            this.formulario.hide();

            var clouser = this;
            this.disparadorToggle.click( function () {
                clouser.moverPagina(true);
            });
        } else {
            this.moverPagina(false);
        }
        return this;
    },
    moverPagina : function (toogle) {
        this.disparadorToggle.click(function () {});

        if (this.scroll <= 0) {
            if (true === toogle) { this.formulario.toggle('slow'); }

            var clouser = this;
            this.moveScroll = window.setInterval( function(){
                if (clouser.scroll < 50) {
                    window.scrollBy(0, clouser.scroll++);
                } else {
                    window.clearInterval(clouser.moveScroll);
                    clouser.moveScroll = null;
                }
            }, 24);
        }
    }
}
$(document).ready(function () {
    GaleriaDeImagenes.init('galeria');
    GaleriaDeImagenes.prepare();

    if ($('#mensajeFormConsulta').length > 0) {
        $.scrollTo($('#formConsulta'), 1000);
    }
    if ($('#mensajeFormRecomendacion').length > 0) {
        $.scrollTo($('#formRecomendacion'), 1000);
    }

    if (history.back) {
        $('#volverListado').bind('click', function () {
            history.back(1);
            window.setTimeout(function () {
                window.location = '/';
            }, 2000);
            return false;
        }).attr('href', '#');
    }

    $('.imgCaptcha').bind('click', function () {
        this.src = this.name +'/nocache/'+ Math.random();
        return false;
    });
    $('.reloadCaptcha').html( 'Cliché sobre la imagen para cambiar la clave.' );

    // verifica si la pagina es abierta dentro de otra(ej: iframe)
    var issetParent = (window == top) ? false : true;

    if (issetParent == true) {
        // establece el cierre de la ventana virtual si el archivo es abierto en un iframe
        $('#cmdRegresarListado').bind('click', function () { top.Seleccion.cerrarFicha(); });
        $('#cmdRegresarListadoNoDisponible').bind('click', function () { top.Seleccion.cerrarFicha(); });

        // quita el boton para ir a la lista de preferidos
        $('#cmdMisPreferidos').remove();
    }

    // desplaza la pagina a las secciones de los formularios correspondientes
    $('#cmdConsultar').bind('click', function () { $.scrollTo('#formConsulta', 1000); return false; });
    $('#cmdRecomendar').bind('click', function () { $.scrollTo('#formRecomendacion', 1000); return false; });

    // inicia las operaciones para cambiar el estado de la propiedad con respecto a los inmuebles favoritos
    Preferido.init( $('#cmdPreferido'), issetParent );


    AcordionDeListas.init('.lstPlegable', '.lstPlegableOff');


    // QR
    $('#cmdQR').bind('click', function () {
        var vinculo = $(this);
        var name = $(this).attr('name');
        if (name != 'bacio') {
            $(this).attr('name', 'bacio');
            $('#codigoQR').append(
                '<div id="imgQR">'
                + '<div class="codigo"><a title="Haga clic sobre la imagen para descargarla." id="vinculoQR" target="tQR" href="'+ name +'/color/negro"><img id="imagenQR" src="'+ name +'/color/negro" /></a><br class="clear" /></div>'
                + '<ul name="'+ name +'" class="colores" id="coloresQR"><li class="negro">&#160;</li><li class="rojo">&#160;</li><li class="verde">&#160;</li><li class="azul">&#160;</li></ul><br class="clear" />'
                + '</div>'
            );
            $('#imgQR').slideDown('slow');
            $('#coloresQR').bind('click', function (e) {                
                var color = $(e.target).attr('class');
                if ($.inArray(color, ['negro', 'rojo', 'verde', 'azul']) >= 0) {
                    $('#imagenQR').attr('src', $(this).attr('name') +'/color/'+ color +'/nocache/'+ Math.random());
                    $('#vinculoQR').attr('href', $(this).attr('name') +'/color/'+ color +'/nocache/'+ Math.random());
                }
            });
        }
        return false;
    });
});

