﻿
var activeInstaller = null;
var originMarker = null;
var address = null;
var radius = null;

$( document ).ready( function() {

    // Installers search page
    var gmap = $( "div.gmap" );

    if ( gmap.length > 0 ) {    
        
        // Init map
        $( gmap ).css( { 
            width: 500,
            height: 460
        } );

        var myOptions = {
            zoom: 15,                                    
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map( gmap[ 0 ], myOptions );        
        var bounds = new google.maps.LatLngBounds();
        var markersArray = [];    

        // Geocode our address
        var geocoder = new google.maps.Geocoder();
        
        //alert( $( "#hf-address" ).val() );

        // Find address
        address = $( "#hf-address" ).val();
        radius = $( "#hf-radius" ).val();

        geocoder.geocode( { "address": address }, function( results, status ) {
            if ( status == google.maps.GeocoderStatus.OK ) {                
                map.setCenter( results[ 0 ].geometry.location );
                originMarker = new google.maps.Marker( {
                    map: map,
                    position: results[ 0 ].geometry.location,
                    icon: "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=|027F01|000000"
                } );

                google.maps.event.addListener( originMarker, "click", function() {
                    map.panTo( originMarker.getPosition() );
                    if ( activeInstaller ) activeInstaller.removeClass( "active" );                    
                    activeInstaller = null;   
                    //infowindow.open( map,marker );
                } );

                markersArray.push( originMarker );
                bounds.extend( originMarker.getPosition() );

                plotInstallers( map, markersArray, bounds );
            } else {
                alert( "Geocode was not successful for the following reason: " + status );
            }
        } );
    }

} );

function plotInstallers( map, markersArray, bounds ) {

    var infoWindow = new google.maps.InfoWindow();
    /*google.maps.event.addListener( infoWindow, 'content_changed', function() {
        setTimeout( function() {
            //alert( $( ".bubble" ).height() );
            $( ".bubble" ).parent().height( $( ".bubble" ).height() ).css(
        }, 200 );
    } );*/

    // Plot our installers
    $( "ul.installers li" ).each( function( idx, el ) {    

        // Find hidden fields
        var latlng = $( this ).find( 'input[name="latlng"]' ).val();
        var email = $( this ).find( 'input[name="email"]' ).val();
        var siteemail = $( 'input[name="siteemail"]' ).val();
                
        var marker = new google.maps.Marker( {
            position: parseToLatLng( latlng ),
            icon: "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=|D00020|000000"           
        } );       
        
        if ( !parseInt( radius ) ) {
            marker.setMap( map );
            bounds.extend( marker.getPosition() );                
        }        
        
        google.maps.event.addListener( marker, "click", function() {
            map.panTo( marker.getPosition() );
            if ( activeInstaller ) activeInstaller.removeClass( "active" );
            $( el ).addClass( "active" ).focus();                 
            activeInstaller = $( el );   
            window.location.hash = "#" + $( el ).attr( "id" ); 
            infoWindow.setContent( "<div class=\"bubble\">" + $( el ).html() + "<a target=\"_blank\" href=\"http://maps.google.co.uk/?saddr=" + originMarker.getPosition().toUrlValue() + "&amp;daddr=" + marker.getPosition().toUrlValue() + "\">Get Directions</a>" + ( email != "" ? " | <a href=\"mailto:" + email + "?cc=" + siteemail + "\">Contact Us</a>" : "" ) + "</div>" );       
            infoWindow.open( map, marker );
        } );
            
        markersArray.push( marker );        

        // If result clicked show marker
        $( el ).click( function() {                                        
            if ( activeInstaller ) activeInstaller.removeClass( "active" );
            $( el ).addClass( "active" );
            activeInstaller = $( el );
            map.panTo( marker.getPosition() );
            infoWindow.setContent( "<div class=\"bubble\">" + $( this ).html() + "<a target=\"_blank\" href=\"http://maps.google.co.uk/?saddr=" + originMarker.getPosition().toUrlValue() + "&amp;daddr=" + marker.getPosition().toUrlValue() + "\">Get Directions</a>" + ( email != "" ? " | <a href=\"mailto:" + email + "?cc=" + siteemail + "\">Contact Us</a>" : "" ) + "</div>" );            
            infoWindow.open( map, marker );     
        } );            

    } );

    if ( !parseInt( radius ) ) {
        map.fitBounds( bounds );
        $( "ul.installers" ).css( "visibility", "visible" );
        return;
    }    

    $( "ul.installers li" ).hide();

    var destinationLatLngs = [];    

    for ( var i = 1; i <= markersArray.length - 1; i++ )
    {
        destinationLatLngs.push( markersArray[ i ].getPosition() );
    }
    
    // Check if its in our radius
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix( {
        origins: [ originMarker.getPosition() ],
        destinations: destinationLatLngs,
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL,
        avoidHighways: false,
        avoidTolls: false
    }, function( response, status ) {
        if ( status == google.maps.DistanceMatrixStatus.OK ) {
            var origins = response.originAddresses;
            var destinations = response.destinationAddresses;

            for (var i = 0; i < origins.length; i++) {
                var results = response.rows[i].elements;
                for (var j = 0; j < results.length; j++) {
                    var element = results[j];
                    var distance = element.distance.text;
                    var duration = element.duration.text;
                    var from = origins[i];
                    var to = destinations[j];

                    var dist = parseFloat( distance );

                    //alert( "To: " + to + " Distance: " + distance + " Dist: " + dist + " idx: " + j );

                    if ( dist <= radius ) {
                        console.log( markersArray[ j + 1 ].getPosition() );
                        markersArray[ j + 1 ].setMap( map );
                        bounds.extend( markersArray[ j + 1 ].getPosition() );                
                        $( "ul.installers li:eq(" + ( j ) + ")" ).show();
                    }
                }
            }

            map.fitBounds( bounds );
            $( "ul.installers" ).css( "visibility", "visible" );
        } 
    } );    
}


function parseToLatLng( str ) {
    var latlngStr = str.split( ",", 2 );
    var lat = parseFloat( latlngStr[ 0 ] );
    var lng = parseFloat( latlngStr[ 1 ] );
    var latlng = new google.maps.LatLng( lat, lng );
    return latlng;
}
