$.fn.socioTip = function ( newConfig ) {
    var config = $.extend({
        imgLoad : '/public/imgs/loading.gif',           // img de cargando
        disTop : 6,                                     // distancia que diferirá el borde superior del tip con
        disLeft : -40,                                  // respecto a las coordenadas xy del evento click
        imgClouse : '/public/imgs/clousetip.jpg',
        timeLoad : 3
    }, newConfig);

    // datos
    var eventoActivo = null,
        visible = false,
        estado = 0,
        peticion = null,
        datos = null,
        logo = null,
        widthDoc = $(document).width(),
        heightDoc = $(document).height(),
        // num POP-UP
        numWinOpen = {
            urls: [],
            get: function (url) {
                var key = jQuery.inArray(url, this.urls);
                if(key === -1) {
                    this.urls.push( url );
                    key = this.urls.length - 1;
                }
                return key;
            }
        };
    // elementos
    var anclaActiva = null,
        tip = $('#tip'),
        loadLogo = config.loadLogo,
        data = $('#tipData');

    // al clickear en el vinculo
    $(this).click(function (e) {
        _showToolTip(e, $(this));
        return false;
    });

    // se coloca el botón de cerrar
    $('#tipCerrar').append( $( document.createElement('img') ).attr('src', config.imgClouse).bind('click', _hideToolTip) );

    /**
     * cierra el tooltip activo
     */
    function _hideToolTip() {
        tip.animate({opacity: 'hide', top: '-='+10}, 'fast', function () {
            data.empty();
            anclaActiva.css('color', 'green');
            anclaActiva = null;
            eventoActivo = null;
            visible = false;
            estado = 0;
        });
    }
    /**
     * abre el tooltip para el vinculo chiqueado
     */
    function _showToolTip(evento, ancla) {
        // si hay un evento activo y el target es igual finaliza
        if (eventoActivo != null) { if (eventoActivo.target === evento.target) { return false; } }
        // si estado > 0 se esta cargando los datos de un ancla seleccionada
        if (estado > 0) { return false; } 

        // inicia la carga de datos y guarda el evento
        estado = 1;
        eventoActivo = evento;

        // si precede un ancla activa se coloca el color de desactiva
        if (anclaActiva) { anclaActiva.css('color', 'green'); }
        // se activa el ancla seleccionada
        anclaActiva = ancla.css('color', 'blue');

        var dataCss = {
            'display': 'block',
            'background-image': 'url('+config.imgLoad+')',
            'background-position': 'center center',
            'background-repeat': 'no-repeat',
            'width': '100px',
            'height': '50px'
        };
        // se coloca limpia el contenido y se mueve el tip, de dos formas dependiendo de su visibilidad
        if (visible === true) {
            data.html('').css(dataCss)
            tip.css({'width':'auto'})
            tip.animate(_getTopLeftCorregida(null, true), 'slow', function () {
                _showData( ++estado );
            });
        } else {
            data.css(dataCss);
            var tipCss = _getTopLeftCorregida({'width':'auto'}, true); //Corregida
            tipCss.top -= 10;
            tip.css(tipCss).animate({opacity:'show', top:'+='+10}, 'slow', function () {
                _showData( ++estado );
            });

            visible = true;
        }

        // carga los datos
        _loadData();
    }
    /**
     * Aquí se establece la carga del logo y de los datos de la inmobiliaria el
     * que llegue ultimo muestra todo
     */
    function _loadData() {
        var id = (anclaActiva.attr('href').split('socio/'))[1];
        //logo = new Image();
//        logo = $('#imglogo'+id);
        /*if (logo.size() > 0) {
            logo = logo.get(0);
            _showData( ++estado );
        } else {*/
            logo = document.createElement('img');
            logo.id = 'imglogo'+id;
            logo.tymeout = window.setTimeout(function () {logo.onload(); }, config.timeLoad);
            logo.onload = function () {
                this.onload = function(){}; window.clearTimeout( this.tymeout )
                _showData( ++estado );
            };
            logo.src = '/imgs/'+id+'/logo.jpg?nocache'+Math.random();
            // zona donde cargan las imagenes
            loadLogo.append(logo);
        //}

        datos = null;
        peticion = jQuery.ajax( {
            responseData : null,
            
            dataType    : 'json',
            url         : anclaActiva.attr('href')+'/nocache/'+Math.random(),
            cache       : false,
            data        : {nocache:Math.random()},
            type        : 'POST',
            contentType : 'application/x-www-form-urlencoded',
            timeout     : config.timeout || 4000,
            async       : true,
            beforeSend  : function (XMLHttpRequest) {},
            complete    : function (XMLHttpRequest, textStatus) {
                if(XMLHttpRequest.readyState == 4) {
                    if(XMLHttpRequest.status == 200) {
                        //alert(XMLHttpRequest.responseText);
                        datos = this.responseData;
                        _showData( ++estado );
                    }
                }
            },
            error       : function (XMLHttpRequest, textStatus, errorThrown) {},
            success     : function (data, textStatus) {
                this.responseData = data;
            }
        } );
    }
    /**
     * Crea el texto que representa un socio
     */
    function _createSocio(datos, sucursal) {
        var center = $( document.createElement('center') );
        if (sucursal) {
            center.append( document.createElement('br') );
        } else {
            //if (logo.complete && logo.width > 0) {
            if (logo.complete || logo.readyState=="complete") {
                center.append( $(logo).clone(true).css({'margin-bottom': '6px', 'padding': '4px', 'border': '1px solid #DDDDDD'}) );
                center.append( document.createElement('br') );
            } else {
                center.append( $(document.createElement('h3')).append( document.createTextNode(datos.nombre) ) );
            }
        }

        var info = $( document.createElement('div') );
        info.append( $(document.createElement('b')).append( document.createTextNode(datos.direccion +' : '+ datos.zona) ) );
        info.append( document.createElement('br') );

        var info2 = $( document.createElement('div') ).css({'text-align':'left', 'width': 'auto', 'display':'inline', 'margin-top': '6px'});
        if (!$.browser.msie && $.browser.version!='6.0') {
            info2.css({'display': 'inline-block'}); }
        if (datos.telefono.length > 0)  {
            info2.append( $(document.createElement('b')).append( document.createTextNode('Telefono: ') ) );
            info2.append( document.createTextNode(datos.telefono) );
            info2.append( document.createElement('br') ); }
        if (datos.correo.length > 0)  {
            info2.append( $(document.createElement('b')).append( document.createTextNode('Correo: ') ) );
            info2.append( $(document.createElement('span')).append( document.createTextNode(datos.correo) ).attr({'id':datos.id, 'title':'Consultar a '+datos.nombre, 'class':'click'}).bind('click', function () {
                //Win.show(this.title, '/adipe/consultarsocio/numero/'+this.id);
                Win.show(this.title, '/contacto/index/numero/'+this.id);
            }) );
//            info2.append( document.createTextNode(datos.correo) );
            info2.append( document.createElement('br') ); }
        if (datos.sitio.length > 0)  {
            info2.append( $(document.createElement('b')).append( document.createTextNode('Sitio: ') ) );
//            info2.append( document.createTextNode(datos.sitio) );
            info2.append( $(document.createElement('span')).append( document.createTextNode(datos.sitio) ).attr({'title':datos.sitio, 'class':'click'}).bind('click', function () { 
                window.open('http://'+this.title, numWinOpen.get(this.title) ).focus();
            }) );
            info2.append( document.createElement('br') );
            // vinculo al web
           /* center.css('cursor', 'pointer').attr('title', datos.sitio).bind('click', function () {
                // habré la ventana llama el focus, emplea un numero que se asigna a cada url
                window.open('http://'+this.title, numWinOpen.get(this.title) ).focus();
            });*/
        }

        return center.append( info.append( info2 ) );
    }
    /**
     * Se encarga de mostrar los datos luego de que la animación y la carga de
     * el logo y la nueva información este completa
     */
    function _showData(state) {
        // si se cargo la img y los datos actúa
        if ( state >= 4 ) {
            var newData = $( document.createElement('div') ).append(datos);
            data.css({
                //'display': 'inline',
                'background-image': 'none',
                'width': 'auto',
                'height': 'auto'
            }).append( _createSocio(datos.socio) )
            if (datos.socio.sucursales.length > 0) {
                for (sucursal in datos.socio.sucursales) {
                    data.append( _createSocio(datos.socio.sucursales[sucursal], true) )
                }
            }
            tip.animate(_getTopLeftCorregida(), 'slow');
            estado = 0;
        }
    }
    /**
     * Retorna el punto x:left e y:top donde se posesionara el tooltip en referencia
     * al elemento seleccionado
     */
    function _getTopLeft( obj ) {
        if (eventoActivo.pageY > 0 && eventoActivo.pageX > 0) {
            return $.extend({
                top: eventoActivo.pageY + config.disTop,
                left: eventoActivo.pageX + config.disLeft
            } ,obj);
        }
        return $.extend({
            top: eventoActivo.target.offsetTop + config.disTop,
            left: eventoActivo.target.offsetLeft + (eventoActivo.target.offsetWidth /2) + config.disLeft
        } ,obj);
    }
    /**
     * igual que _getTopLeft, salvo que en este caso verifica si al agregarle al
     * tooltip el contenido este no se salga de la ventana corrigiendo los puntos
     */
    function _getTopLeftCorregida( obj, bajoestimar ) {
        var topLeft = _getTopLeft(obj);
        var wtt=tip.width(), htt=tip.height();

        tip.removeClass('tipTL').removeClass('tipTR').removeClass('tipBL').removeClass('tipBR');
        tip.addClass('tipTL');

        var right = false;
        if ((topLeft.left + wtt) > widthDoc) {
            // el contenedor supera el ancho de la pagina
            topLeft.left = widthDoc - wtt - 36;
       //     tip.addClass('tipTR');
            right = true;
        }
        if ((topLeft.top + htt) > heightDoc) {  // /2
            // el contenedor supera la altura de la pagina
            topLeft.top = topLeft.top - htt - 36//- ( $(document).height() - heightDoc);
            tip.addClass(right ? 'tipBL' : 'tipBL');
        }
        return topLeft;
    }
};
$(document).ready(function () { 
    $('.colIzq, .colDer').find('a').socioTip({timeLoad:8000, loadLogo:$('#loadLogo')});
    Win.init( $('#sombraWin'), $('#contenidoWin'), $('#cabeceraWin'), $('#cuerpoWin') );
});