var map = null;
var BaseShapeLayer = null;
var mapCenter = new VELatLong(53.7, -1.0);
var mapZoom = 8;
var CurrentPostcode = 0;
var CurrentLocationName = '';
var CurrentLocationAddress = '';
var CurrentAdditionalInfo = '';

var icon = new VECustomIconSpecification();

var PostcodeLocations = new Array();
var LongLatLocations = new Array();
var CurrentLocation = 0;


    function LoadMap()
    {
     
        map = new VEMap('LocationMap');
        map.LoadMap();
        map.SetZoomLevel(10);
        map.SetDashboardSize(VEDashboardSize.Small);
        icon.Image = '/images/logo4.gif';
        
        
        BaseShapeLayer = new VEShapeLayer();
        map.AddShapeLayer(BaseShapeLayer);
        

    }
    
    function ResetMap()
    {
        for(var i = 0; i < LongLatLocations.length; i ++)
        {
            CurrentShape = BaseShapeLayer.GetShapeByIndex(i);
            CurrentShape.Show();
        }
        map.DeleteRoute();
        var path = '/plugins/map/LocationsAjax.php?cleardirections=true';
        var AjaxLoader = new Ajax("Directions", path);

        HideDetails();
        
        HideRouteForm();

        map.SetCenterAndZoom(mapCenter, mapZoom);
        CurrentPostcode = '';
    }

    function AddLocationFromPostcode(index, title, description, postcode, WYSIWYG, id)
    {
        if(postcode != null && postcode != undefined)
        {
            PostcodeLocations[index] = new Array(title, description, postcode, WYSIWYG, id);
        }
    }

    function AddLocationFromLongLat(index, title, description, WYSIWYG, longitude, latitude, id)
    {
        LongLatLocations[index] = new Array(title, description, WYSIWYG, longitude, latitude, id);
    }


    
    function LoadPostcodeLocations()
    {
        
        if(PostcodeLocations.length > 0)
        {
        results = map.Find('',
            PostcodeLocations[CurrentLocation][2],
            null,
            null,
            null,
            null,
            true,
            true,
            true,
            true,
            AddPostcodePin);
        }

    }
    
    
    function LoadLongLatLocations()
    {
        for(var i = 0; i < LongLatLocations.length; i ++)
        {
            var tmpLong = parseFloat(LongLatLocations[i][3]);
            var tmpLat = parseFloat(LongLatLocations[i][4]);
            var LL = new VELatLong(tmpLat,tmpLong);
            var pin = new VEShape(VEShapeType.Pushpin, LL);

            pin.SetCustomIcon(icon);
            pin.SetTitle('<h4 class="mapTitle">'+LongLatLocations[i][0]+'</h4>');
            pin.SetDescription('<div class="mapInfoBox">'+LongLatLocations[i][1]+'<div class="clear">&nbsp;</div></div>');
            BaseShapeLayer.AddShape(pin);
        }
        


    }
    
    function AddPostcodePin(layer, resultsArray, places, hasMore, veErrorMessage)
    {
        if(places != null)
        {
            var pin = new VEShape(VEShapeType.Pushpin, places[0].LatLong);
            pin.SetCustomIcon(icon);
            pin.SetTitle('<h4 class="mapTitle">'+PostcodeLocations[CurrentLocation][0]+'</h4>');
            pin.SetDescription('<div class="mapInfoBox">'+PostcodeLocations[CurrentLocation][1]+'<div class="clear">&nbsp;</div></div>');
            BaseShapeLayer.AddShape(pin);
            
            // Store pin location in datascheme
            var path = '/plugins/map/LocationsAjax.php?savelocation=true&dsid=36&id='+PostcodeLocations[CurrentLocation][4]+'&long='+places[0].LatLong.Longitude+'&lat='+places[0].LatLong.Latitude;
            var AjaxLoader = new Ajax(null, path);
            
            PostcodeLocations[CurrentLocation] = pin.GetID();
            

            CurrentLocation ++;
        }
        else if(resultsArray == null)
        {
            PostcodeLocations[CurrentLocation] = null;
            CurrentLocation ++;
        }
        
        if(CurrentLocation < PostcodeLocations.length)
        {
            // Run next iteration
            LoadPostcodeLocations();
        }
    }


    function ShowDetails(contentId)
    {

            var path = '/plugins/map/LocationsAjax.php?showdetails=' + contentId;
            var AjaxLoader = new Ajax('LocationDetailsContainer', path);
    }
    
    function HideDetails()
    {
        var path = '/plugins/map/LocationsAjax.php?showdetails=none';
        var AjaxLoader = new Ajax("LocationDetailsContainer", path);
    }
    
    function SetFocus(locationName, locationAddress, markerId, postcode, locationAdditionalInfo)
    {
            CurrentPostcode = postcode;
            CurrentLocationName = locationName;
            CurrentLocationAddress = locationAddress;
            CurrentAdditionalInfo = locationAdditionalInfo;
            map.DeleteRoute();
            
            for(var i = 0; i < LongLatLocations.length; i ++)
            {
                CurrentShape = BaseShapeLayer.GetShapeByIndex(i);
                CurrentShape.Hide();
            }
            CurrentShape = BaseShapeLayer.GetShapeByIndex(markerId);
            CurrentShape.Show();
            
            PinCenter = new VELatLong(CurrentShape.Latitude, CurrentShape.Longitude);
            map.SetCenterAndZoom(PinCenter, 9);
            var path = '/plugins/map/LocationsAjax.php?cleardirections=true';
            var AjaxLoader = new Ajax("Directions", path);
            
            ShowRouteForm(CurrentPostcode, "false");
            
    }

    function ShowRouteForm(postcode, showbutton)
    {
        var from = '';
        if(document.getElementById("search_location") != null)
        {
            from = document.getElementById("search_location").value;
        }
        var path = '/plugins/map/LocationsAjax.php?showrouteform=show&showbutton=' + showbutton + '&from=' + from + '&to=' + postcode + '&location_name=' + CurrentLocationName + "&location_address=" + CurrentLocationAddress + "&location_additional_info=" + CurrentAdditionalInfo;
        var AjaxLoader = new Ajax("SearchBox", path);
    }
    
    function HideRouteForm()
    {
        var path = '/plugins/map/LocationsAjax.php?showrouteform=hide';
        var AjaxLoader = new Ajax("SearchBox", path);
    }
    
    function GetRoute(to, from)
    {
        if(typeof(CurrentPostcode) !== 'undefined' && CurrentPostcode != '') 
        {
        
            var from = document.getElementById("search_location").value;
            var locations = new Array(from, CurrentPostcode);
            var options = new VERouteOptions();

            options.DrawRoute = true;
            options.RouteCallback = onGotRoute;
            options.RouteOptimize = VERouteOptimize.MinimizeTime;
            map.GetDirections(locations,options);
            ShowRouteForm(CurrentPostcode, "true");
            HideDetails();
        }
        else if(to != null && to != '' && from != null && from != '')
        {
            var locations = new Array(from, to);
            var options = new VERouteOptions();

            options.DrawRoute = true;
            options.RouteCallback = onGotRoute;
            map.GetDirections(locations,options);
        }
        else
        {
            alert("Please select a location");
        }
    }



    function onGotRoute(route)
    {
       // Unroll route
       var legs     = route.RouteLegs;
       var turns    = "<div class='dest'><strong>Directions:</strong><br /><b>Your route to " + CurrentLocationName + ", " + CurrentLocationAddress + ". <br/>" + CurrentAdditionalInfo + "<br/>Total distance: " + route.Distance.toFixed(1) + " miles</b><br></div>";
       var numTurns = 0;
       var leg      = null;

       // Get intermediate legs
        for(var i = 0; i < legs.length; i++)
        {
           // Get this leg so we don't have to derefernce multiple times
           leg = legs[i];  // Leg is a VERouteLeg object

           // Unroll each intermediate leg
           var turn = null;  // The itinerary leg

           for(var j = 0; j < leg.Itinerary.Items.length; j ++)
           {
              turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
              numTurns++;
              turns += numTurns + ".\t" + turn.Text + "<psan class='dest'> (" + turn.Distance.toFixed(1) + " miles)<br></span>";
           }
        }
        turns += "<div class='dest'>You have arrived at " + CurrentLocationName + ".<Br><br></div>";
        turns += "<div class='dest'><img src='/images/logo.gif' border='0' /></div>";
        document.getElementById('Directions').innerHTML = turns;
     }
    


    function fnFocusClear(oControl, sString)
    {
        if (oControl.value == sString) oControl.value = '';
    }


    $(document).ready(function(){
				LoadMap();
				InitLocations();	
				            
				            map.SetCenter(mapCenter);
            map.SetZoomLevel(mapZoom);
    });