﻿
//                              *********************************
//                              **        MR.MICRO-2009        **    
//                              *********************************
//                              ** RAFAEL MARTINEZ CARLAVILLA  **
//                              ** JOSE IGNACIO BIENCINTO ALBA **
//                              *********************************

    var map;
    var Pais = 'E-';
    var PuntoSeleccionado = '';
    var SessionId = '';
    var directionsPanel;
    var directions;
    var TEngoAlgunErrorBusqueda = false;
    var MiGeo='';
    var MiLAt='';
    var MiLong='';

    

    

    function updatePosition(position) {
            MiLAt=position.latitude;
            MiLong=position.longitude;
         return position.latitude + ',' + position.longitude;
    }

    function handleError(positionError) {
        //alert('Attempt to get location failed: ' + positionError.message);
    }



function PaisSeleccionado() {
    if (Pais == 'E-') { return 'es' } else {return 'ad' }
}

function InitMaps() {

if (!window.google || !google.gears) {

//    if (confirm('¿te gustaria que te mostremos las tiendas mas cercanas a tu ubicacion?') == true) {
//        location.href = "http://gears.google.com/?action=install" +
//                  "&message=Para poder mostrarte las tiendas mas cercanas debemos poder acceder a tu ubicacion&return=www.mrmicro.es/SeleccionarTienda.aspx";
//    } else {
//        CargarMapaMrMicro(); }
    CargarMapaMrMicro();
}

    else {

        MiGeo = google.gears.factory.create('beta.geolocation');
        MiGeo.getCurrentPosition(updatePosition, handleError);
        setTimeout("CargarMapaMrMicro()", 1000)
    }

 }

function CargarMapaMrMicro() {
   if (GBrowserIsCompatible()) {
        //INICIALIZO MAPA ESPAÑA
        var map2 = new GMap2($get("Googlemap"));
        map2.addControl(new GSmallMapControl());
        map2.addControl(new GMapTypeControl());
        map2.enableScrollWheelZoom();
        if (MiLAt != '') {
        map2.setCenter(new GLatLng(MiLAt, MiLong), 10)
        }else{
        map2.setCenter(new GLatLng(40.424931, -3.698187), 5);
        }
        geocoder = new GClientGeocoder();
        geocoder.setBaseCountryCode(PaisSeleccionado());

        //PONGO LAS MARCAS DE LOS PUNTOS MR
        PintarPuntosMR(map2,20,30);
   }
}

function EscribeTuCP(nombreSitio) {
   var geocoder = new GClientGeocoder();
   geocoder.setBaseCountryCode(PaisSeleccionado());
   geocoder.getLatLng(nombreSitio, function(point) {
        if (!point) {
            
        } else {
        var map2 = new GMap2($get("Googlemap"));
        map2.addControl(new GSmallMapControl());
        map2.addControl(new GMapTypeControl());
        map2.enableScrollWheelZoom(); 
        map2.setCenter(point, 12);
        
        //PONGO LAS MARCAS DE LOS PUNTOS MR
        PintarPuntosMR(map2,20,30);
        }
   });

   //MIRO EN MI LISTADO DE PUNTOS MR.MICRO.
   BuscarPuntosMRNavision(nombreSitio);
    
}

function BuscarPuntosMRNavision(Txt) {
   ConexionSW.BusCarPuntosMR(Txt,Pais,PintarResultadosPuntos);
}

function PintarResultadosPuntos(resultado) {
   $get('ST_listado_puntos').innerHTML = resultado;
}

function PintarPuntosMR(Obj,Ancho,Alto) {

   //PUNTOS MR
    var PuntosMR = new Array($get('ctl00_ContentPlaceHolder1_Puntos').value.split('#'));
    try {
        $get('NumTiendas').innerHTML = PuntosMR[0].length;
    } catch (Error) { }

    //Recorremos array buscando coordenadas de los puntos MR
    var m = PuntosMR[0].length -1;

    for (i = 0; i < m; i++) {
        var CodCliente = '';
        var Lat = '';
        var Long = '';
        var Ciudad = '';
        var ImagenDelPunto = '';
        var DireccionDelPunto = '';
        var CP = '';
        var Telefono = '';
        var NombreContacto = '';
        var NombreTienda = '';
        var Paypal = '';
        var Transferencia = '';
        var MSN = '';
                
        var Desglose = new Array(PuntosMR[0][i].split(';'));
        CodCliente = Desglose[0][0];
        Lat = Desglose[0][1];
        Long = Desglose[0][2];
        Ciudad = Desglose[0][3];
        NombreTienda = Desglose[0][4];
        SessionId = Desglose[0][5];
        ImagenDelPunto = Desglose[0][6];
        DireccionDelPunto = Desglose[0][7];
        CP = Desglose[0][8];
        Telefono = Desglose[0][9];
        NombreContacto = Desglose[0][10];
        Paypal = Desglose[0][11];
        Transferencia = Desglose[0][12];
        MSN=Desglose[0][13];
            
        var DivTienda = '';
        DivTienda += '<div id="ST_googlemap_tienda_div">'
        DivTienda += '<span id="ST_googlemap_tienda_nombre">MR MICRO - ' + Ciudad + '</span><br />'
        DivTienda += '<span id="ST_googlemap_tienda_persona">' + NombreContacto + '</span><br />'
        DivTienda += '<div id="ST_googlemap_tienda_infodire">'
        DivTienda += '<span>' + DireccionDelPunto + '</span><br />'
        DivTienda += '<span>' + CP + ' ' + Ciudad + '</span><br />'
        DivTienda += '<span>' + Telefono + '</span>'
        DivTienda += '</div>'
        DivTienda += '<div id="ST_googlemap_tienda_img">'
        DivTienda += '<img src="' + ImagenDelPunto + '" width="68" height="48" alt="tienda" />'
        DivTienda += '</div>'
        DivTienda += '<img class="googlemap_fijartienda_ico" src="imagenes/seleccionar_tienda/googlemap_fijartienda_ico.jpg" width="16" height="16" alt="fijar" />'
        DivTienda += '<a onclick=SeleccionarTienda(\'' + CodCliente + '\');><strong>Seleccionar esta tienda</strong></a>'
        DivTienda += '</div>'


        if (Lat != '' || Long != '') {
            //COMPRUEBO EL FILTRO DE PAGO POR INTERNET
     try{           
            if ($get('PagoEnInternet').checked == true) {

                if ($get('chkSupportMSN').checked == true) {
                    if (MSN != '') {
                        //if (Paypal != '' || Transferencia != '') {
                            var point = new GPoint(Long, Lat);
                            var address = DivTienda;
                            var marker = CrearMarcaMR(point, address, Ancho, Alto, Paypal, Transferencia, MSN);
                            Obj.addOverlay(marker);
                        //}

                    }
                    else {
//                        if (Paypal != '' || Transferencia != '') {
//                            var point = new GPoint(Long, Lat);
//                            var address = DivTienda;
//                            var marker = CrearMarcaMR(point, address, Ancho, Alto, Paypal, Transferencia, MSN);
//                            Obj.addOverlay(marker);
//                        }

                    }
                }
                else {
                    if (Paypal != '' || Transferencia != '') {
                        var point = new GPoint(Long, Lat);
                        var address = DivTienda;
                        var marker = CrearMarcaMR(point, address, Ancho, Alto, Paypal, Transferencia, MSN);
                        Obj.addOverlay(marker);
                    }

                }
               
            }
            else {
                if ($get('chkSupportMSN').checked == true) {
                    if (MSN != '') {
                        var point = new GPoint(Long, Lat);
                        var address = DivTienda;
                        var marker = CrearMarcaMR(point, address, Ancho, Alto, Paypal, Transferencia, MSN);
                        Obj.addOverlay(marker);
                    
                    }
                    

                }
                else {//86
                    var point = new GPoint(Long, Lat);
                    var address = DivTienda;
                    var marker = CrearMarcaMR(point, address, Ancho, Alto, Paypal, Transferencia, MSN);
                    try {
                        Obj.addOverlay(marker);
                    } catch (Error) { }

                }
            }
        } catch (Error) {

        var point = new GPoint(Long, Lat);
        var address = DivTienda;
        var marker = CrearMarcaMR(point, address, Ancho, Alto, Paypal, Transferencia, MSN);
        try {
            Obj.addOverlay(marker);
        } catch (Error) { }
        
         }
        }
        
    }
}

function CrearMarcaMR(point, address,Ancho,Alto,PayPal,Transferencia,MSN) {
    var IC = RecuperarIcono(Ancho, Alto,PayPal,Transferencia,MSN);
    var marker = new GMarker(point,IC);
    if (address != '') { GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(address); }); }
    return marker;
}

function MoverMapa(Latitud,Longitud,CodCliente) {
    var map2 = new GMap2($get("Googlemap"));
    map2.addControl(new GSmallMapControl());
    map2.addControl(new GMapTypeControl());
    map2.enableScrollWheelZoom(); 
    map2.setCenter(new GLatLng(Latitud, Longitud), 17);
    geocoder = new GClientGeocoder();
    geocoder.setBaseCountryCode(PaisSeleccionado());

    //PONGO LAS MARCAS DE LOS PUNTOS MR
    PintarPuntosMR(map2,20,30);
}

function RecuperarIcono(Ancho,Alto,Paypal,Transferencia,MSN) {
    //ICONO PUNTOS MR.MICRO
    var iconoVerde = new GIcon(G_DEFAULT_ICON);
    iconoVerde.iconSize = new GSize(Ancho, Alto);

    if (MSN == '') {
        //DEPENDE DE LOS METODOS DE PAGO ASI SERA EL ICONO
        if (Paypal != '' || Transferencia != '') {
            iconoVerde.image = "Imagenes/seleccionar_tienda/ico_mr_paypal.png";
        } else {
            iconoVerde.image = "Imagenes/seleccionar_tienda/ico_mrmicro.png";
        }
    }
    else { 
        //CON SOPORTE MSN
        if (Paypal != '' || Transferencia != '') {
            iconoVerde.image = "Imagenes/seleccionar_tienda/ico_mr_paypal.png";
        } else {
            iconoVerde.image = "Imagenes/seleccionar_tienda/ico_mrmicro.png";
        }
}
    
    return iconoVerde;
}

function RedirijeaProductos() {
    var Catid = $get('ctl00_ContentPlaceHolder1_codigoDeSubCategoriaSeleccionada').value;
    
    if (Catid != '') { location.href = 'Busqueda.aspx?SubCatid=' + Catid; }
    else {
        var CodCliente = $get('ctl00_CodCliente').value;   
        location.href = 'http://www.mrmicro.es/Tienda.aspx?Tienda=' + CodCliente; }
}

function ExpandirGoogleMap() {
    if (listado_puntosmr == 0) {
        $get('ST_mostrarocultar_listado').style.display = 'none';
        $get('ST_listado_puntos').style.display = 'none';
        $get('Googlemap').style.width = 780 + "px";
        $get('ST_btn_mostrarocultar_listado').src = "imagenes/seleccionar_tienda/ST_btn_mostrar_listado.jpg";
        listado_puntosmr = 1;
    } else {
        $get('ST_mostrarocultar_listado').style.display = 'block';
        $get('ST_listado_puntos').style.display = 'block';
        $get('Googlemap').style.width = 560 + "px";
        $get('ST_btn_mostrarocultar_listado').src = "imagenes/seleccionar_tienda/ST_btn_ocultar_listado.jpg";
        listado_puntosmr = 0;
    }
}

var directionsPanel;
var directions;

function TrazarMapa() {
    //PONGO EL LOADER
    var from = $get('ST_input_Route').value;
    $get('T_localizacion_ruta_content').innerHTML = '';
    var Provincia = $get('ctl00_ContentPlaceHolder1_T_tienda_info_provincia').innerHTML;
    var Destino = $get('ctl00_ContentPlaceHolder1_T_localizacion_coordenadas').innerHTML;
    map = new GMap2($get("T_localizacion_googlemap"));
    map.setCenter(new GLatLng(42.351505, -71.094455), 15);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.enableScrollWheelZoom();
    var Lat = $get('ctl00_ContentPlaceHolder1_Lat').value;
    var Long = $get('ctl00_ContentPlaceHolder1_Longi').value;
    var PagoPaypal = $get('ctl00_Pago_Paypal').value;
    var Pago_Trans = $get('ctl00_Pago_Transferencia').value;
    var point = new GPoint(Long, Lat);
    var marker = CrearMarcaMR(point, '', 40, 50, PagoPaypal,Pago_Trans);
    map.addOverlay(marker);
    
    directionsPanel = $get("T_localizacion_ruta_content");
    directions = new GDirections(map, directionsPanel);
    GEvent.addListener(directions, "load", onGDirectionsLoad);
    GEvent.addListener(directions, "error", handleErrors);
    InicioCargando();
    directions.load("from: " + from + " to:" + Destino);
}

function TrazarMapaSeguro(Ciudad) {
    var from = Ciudad;
    var Destino = $get('ctl00_ContentPlaceHolder1_T_localizacion_coordenadas').innerHTML;
    map = new GMap2($get("T_localizacion_googlemap"));
    map.setCenter(new GLatLng(42.351505, -71.094455), 15);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.enableScrollWheelZoom();
    var Lat = $get('ctl00_ContentPlaceHolder1_Lat').value;
    var Long = $get('ctl00_ContentPlaceHolder1_Longi').value;
    var PagoPaypal = $get('ctl00_Pago_Paypal').value;
    var Pago_Trans = $get('ctl00_Pago_Transferencia').value;
    var point = new GPoint(Long, Lat);
    var marker = CrearMarcaMR(point, '', 40, 50, PagoPaypal, Pago_Trans);
    map.addOverlay(marker);

    directionsPanel = $get("T_localizacion_ruta_content");
    directions = new GDirections(map, directionsPanel);
    InicioCargando();
    GEvent.addListener(directions, "load", onGDirectionsLoad);
    GEvent.addListener(directions, "error", handleErrors);
    directions.load("from: " + from + " to:" + Destino);
}

function onGDirectionsLoad() {
    $get('Km').innerHTML = directions.getDistance().html;
    $get('Time').innerHTML = directions.getDuration().html;
    FinCargando();
}

function PrintMap() {
    var from = $get('ST_input_Route').value;
    if (from != 'Buscar...') {
        var Provincia = $get('ctl00_ContentPlaceHolder1_T_tienda_info_provincia').innerHTML;
        var Destino = $get('ctl00_ContentPlaceHolder1_T_localizacion_coordenadas').innerHTML;
        var Link = 'http://maps.google.es/maps?f=d&source=s_d&saddr=' + from + ',' + Provincia + '&daddr=' + Destino + '&hl=es&geocode=&mra=pe&mrcr=0&sll=40.329363,-3.491313&sspn=0.075377,0.181274&ie=UTF8&ll=40.327964,-3.493652&spn=0.075379,0.181274&z=13&layer=c&pw=2';
        window.open(Link);
    }
    else {
        alert('Debe introducir su direccion');
    }
}

function InicializarMapaTienda() {
    var Lat = $get('ctl00_ContentPlaceHolder1_Lat').value;
    var Long = $get('ctl00_ContentPlaceHolder1_Longi').value;
    map = new GMap2($get("T_localizacion_googlemap"));
    map.setMapType(G_SATELLITE_MAP);
    map.setCenter(new GLatLng(Lat,Long), 16);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.enableScrollWheelZoom();
    var PagoPaypal = $get('ctl00_Pago_Paypal').value;
    var Pago_Trans = $get('ctl00_Pago_Transferencia').value;
    var point = new GPoint(Long, Lat);
    var marker = CrearMarcaMR(point, '', 40, 50,PagoPaypal,Pago_Trans);
    map.addOverlay(marker);
}

function handleErrors() {
    if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
        InicializarMapaTienda();
        //VUELVO A CARGAR EL MAPA CON LA CIUDAD DEL CLIENTE REGISTRADO
        if (TEngoAlgunErrorBusqueda == false) {
            TEngoAlgunErrorBusqueda = true;
            var CiudadDelUsuarioRegistrado = $get('ST_input_Route_Ciudad').value;
            $get('ST_input_Route').value = CiudadDelUsuarioRegistrado;
            TrazarMapaSeguro(CiudadDelUsuarioRegistrado);
        } else
         { alert('No se encuentra la direccion introducida'); }
        FinCargando();
    }

}

function InicioCargando() {
    $get('T_localizacion_loader').style.display = 'block';
 }

 function FinCargando() {
     $get('T_localizacion_loader').style.display = 'none';
 }
 

