var map = null;             // The Map
var pinID = 1;
var rpEnableReverseGeocoding = true;
var bDuringReverseGeocode = false;

var bReverseGeocodingMode = false;

var mouseX=0;
var mouseY=0;
var m_shape=null;
var currentPinLatitude=0;
var currentPinLongitude=0;
var bCurrentPinCenterAtPoint=false;

var bUsageLimitExceeded=false;

var LLLimittopleft = new VELatLong();
var LLLimitbottomright = new VELatLong();




//**************************************************************************************************************************************
//**************************************************************************************************************************************


//
// Initializes Map
//	
function GetMap()
{
    map = new VEMap('divMap');
    map.LoadMap(new VELatLong(53.455,-7.8), 7 ,'h' ,false);
    

    var pixel = new VEPixel(-100, -100);
    LLLimittopleft = map.PixelToLatLong(pixel);
    var iMapStyleWidth = parseInt(document.getElementById("divMap").style.width.replace('px',''));
    var iMapStyleHeight = parseInt(document.getElementById("divMap").style.height.replace('px',''));
    pixel = new VEPixel(iMapStyleWidth+100, iMapStyleHeight+100);
    LLLimitbottomright = map.PixelToLatLong(pixel);

	map.AttachEvent("onmouseup", MouseUp);
	map.AttachEvent("onendzoom", OnEndZoom);
	map.AttachEvent("onchangeview", OnChangeView);
	map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
	
	
	
	map.SetShapesAccuracy(VEShapeAccuracy.Pushpin);
    map.SetFailedShapeRequest(VEFailedShapeRequest.DoNotDraw);
    map.SetShapesAccuracyRequestLimit(25);

 } 



//**************************************************************************************************************************************
//**************************************************************************************************************************************

function MouseUp(e)
{
    var x = e.clientX;
    var y = e.clientY;
    
    var style = map.GetMapStyle();
    
    if (bReverseGeocodingMode)
    {
        if ((style == VEMapStyle.Birdseye) || (style == VEMapStyle.BirdseyeHybrid))
        {
            alert('Due to Licensing restrictions of the Birdseye imagery the exact coordinates could not be extracted. Please switch to another style.' );
        }
        else
        { 
            var latLong = PixelToLatLong(e.mapX, e.mapY);
            document.getElementById("divMap").childNodes[0].style.cursor = "wait";
            ReverseGeocode(latLong.Latitude,latLong.Longitude,false);
        }
    }

}


//**************************************************************************************************************************************
//**************************************************************************************************************************************
         
         

function OnChangeView(e)
{
    //Pan if outside Ireland

    //Mode 3D to fix
    var mode = map.GetMapMode();

    if (mode == VEMapMode.Mode3D)
    {
    //to fix
        return;
    }

    
    
    //Change View event is fired when birdseye style is chosen. 
    //Zoom values are different (1,2..).
    //if birdseye then quit now.
    var style = map.GetMapStyle();
    if ((style == VEMapStyle.Birdseye) || (style == VEMapStyle.BirdseyeHybrid))
    {   
        return;
    }






    var deltaX=0;
    var deltaY=0;


    if (map.GetZoomLevel()<7) 
    {
        map.SetZoomLevel(7);
        return;
    }
    

    var iMapStyleWidth = parseInt(document.getElementById("divMap").style.width.replace('px',''));
    var iMapStyleHeight = parseInt(document.getElementById("divMap").style.height.replace('px',''));


    var pxLimittopleft = map.LatLongToPixel(LLLimittopleft);
    
    
    var pxLimitbottomright = map.LatLongToPixel(LLLimitbottomright);

    //Ireland is too far on the right
    if(pxLimittopleft.x > 10)
    {
        deltaX = parseInt(pxLimittopleft.x);
    };
    

    //Ireland is too far on the left
    if( iMapStyleWidth - pxLimitbottomright.x > 10)
    {
        deltaX = parseInt( - (iMapStyleWidth - pxLimitbottomright.x));
    }    
    
    
    //Ireland is too low
    if(pxLimittopleft.y > 10)
    {
        deltaY = parseInt(pxLimittopleft.y);
    };
    
    //Ireland is too high
    if(iMapStyleHeight - pxLimitbottomright.y > 10)
    {
        deltaY = parseInt( - (iMapStyleHeight - pxLimitbottomright.y));
    }    
       
    if ((deltaX!=0) || (deltaY!=0))
    {
        map.Pan(deltaX,deltaY);
    }



}
//**************************************************************************************************************************************
//**************************************************************************************************************************************

 function GetMapView()
 {
    view = map.GetMapView();
    topleft = view.TopLeftLatLong;
    bottomright = view.BottomRightLatLong;
    topright = view.TopRightLatLong;
    bottomleft = view.BottomLeftLatLong;
    info = "TopLeftLatLong: " + topleft + "<br/>";
    info += "BottomRightLatLong: " + bottomright + "<br/>";
    info += "TopRightLatLong: " + topright + " (3D mode only)<br/>";
    info += "BottomLeftLatLong: " + bottomleft + " (3D mode only)";
    alert(info);
 }  


//**************************************************************************************************************************************
//**************************************************************************************************************************************

function OnEndZoom(e)
{
    //End Zoom event is fired when birdseye style is chosen. 
    //To prevent the map to revert to hybrid/road style exit now if birdeyes.
    var style = map.GetMapStyle();
    if ((style == VEMapStyle.Birdseye) || (style == VEMapStyle.BirdseyeHybrid))
    {   
        return;
    }
               
                
    if(map.GetZoomLevel()>9)
    {
        map.SetMapStyle(VEMapStyle.Road);    
    }
    else
    {
        map.SetMapStyle(VEMapStyle.Hybrid);    
    }
}

//**************************************************************************************************************************************

function LocateOnMapOnClick()
{
    if (bReverseGeocodingMode)
    {
        document.getElementById("divMap").childNodes[0].style.cursor = "";
        bReverseGeocodingMode=false;
    }
    else
    {
        if (!bUsageLimitExceeded)
        {
            document.getElementById("divMap").childNodes[0].style.cursor = "crosshair";
            bReverseGeocodingMode=true;
        }
    }
        

}

//**************************************************************************************************************************************

//
// ReverseGeocode - Called in MouseUp
//        
function ReverseGeocode(latitude, longitude, bCenterAtPoint)
{
    if (bDuringReverseGeocode == true)
    {
        alert('Currently adding a pin. Please wait a moment.');
        return;
    }
    bDuringReverseGeocode = true;


    currentPinLatitude = latitude;
    currentPinLongitude = longitude;
    
    bCurrentPinCenterAtPoint = bCenterAtPoint;

    AddPin(currentPinLatitude, currentPinLongitude, bCurrentPinCenterAtPoint, "");
    
    
    GeoDirectoryWeb.GeoDirectoryWebService1.ReverseGeocode('', '', latitude, longitude, onReverseGeocodeComplete);
    
    document.getElementById("TextAddress1").innerText = '';
    
    document.getElementById("txtSearch").value = '';
    document.getElementById("txtOrganisationSearch").value = '';
    document.getElementById('tdOrganisationHelp').innerText = " ";
    document.getElementById('tdCurrentAddressOrganisationsCount').innerText = "";
    document.getElementById('txtOrganisationSearch').disabled=true;
    
}

//**************************************************************************************************************************************
//**************************************************************************************************************************************

//
// Reverse Geocode Callback
//        
function onReverseGeocodeComplete(result)
{

    if (result == null)
    {
        alert('No address found.');
    }

    fillGeoDirectoryAddressTextBoxes(result);
    
    map.DeleteShape(m_shape);
    
    //the pin was already added
    pinID--;
    if (result != null)
    {
        AddPin(currentPinLatitude,currentPinLongitude,false,result);
    }
    
    bDuringReverseGeocode = false;
    
    bReverseGeocodingMode=false;
    document.getElementById("divMap").childNodes[0].style.cursor = "";

    if (result != null)
    {
        var f = document.getElementById('usageFrame');
        f.src="Usage.aspx?action=reverseGeocode&rand=" + (new Date()).valueOf();

        DecrementCounter();
    }
}
//**************************************************************************************************************************************
//**************************************************************************************************************************************
//
// AutoAddressControl return function
//
function onResult(result)
{
    var lat = result.Rows[1].Value;
    var lng = result.Rows[2].Value;
    
    var address = "";
    address = result.Rows[0].Value;
    
    //document.getElementById('tdSearchHelp').innerText = "Address found.";
    document.getElementById('tdSearchHelp').innerText = " ";
    document.getElementById('tdOrganisationHelp').innerText = " ";
  
    
    fillGeoDirectoryAddressTextBoxes(address);
    

    // before adding the pin I must check that I am not in birdseye, otherwise the map will not pan
    var style = map.GetMapStyle();
    if ((style == VEMapStyle.Birdseye) || (style == VEMapStyle.BirdseyeHybrid))
    {
        map.SetMapStyle(VEMapStyle.Road); 
  
    }

    map.SetZoomLevel(12);


    AddPin(lat, lng, true, address);
    
    

    
    if (result.GeoDirectoryIDTypeString != "Organisation")
    {
        document.getElementById('tdSearchHelp').innerText = " ";
        document.getElementById('tdCurrentAddressOrganisationsCount').innerText = "(" + result.OrganisationsResultCount + " commercial properties in area)";
        document.getElementById('txtOrganisationSearch').disabled=false;
        
        
        //help text organisation
        if ((result.OrganisationsResultCount<150) &&  (result.OrganisationsResultCount>0))
        {
            //press arrow
            document.getElementById('tdOrganisationHelp').innerText = "Press down arrow key.";
            document.getElementById('txtOrganisationSearch').focus();
        }    
        if (result.OrganisationsResultCount==0)
        {
            //press arrow
            document.getElementById('txtOrganisationSearch').disabled=true;
        }    
    }
    else
    {
        document.getElementById('tdCurrentAddressOrganisationsCount').innerText = "";
        document.getElementById('txtOrganisationSearch').disabled=true;
   }


    var f = document.getElementById('usageFrame');
    f.src="Usage.aspx?action=Geocode&rand=" + (new Date()).valueOf();


    DecrementCounter();

   

    
}




//**************************************************************************************************************************************

//
// OrganisationResult event
//
function onOrganisationResult(result)
{
    // Does nothing
    
}
//**************************************************************************************************************************************

//
// LookupResult event
//
function onLookupResult(result)
{
    document.getElementById('tdOrganisationHelp').innerText = " ";

    if(result.ResultCount==0)
    {
        //no result

        //document.getElementById('tdSearchHelp').innerText = "No matches have been found. Please enter an alternative address, or click on map to locate the nearest GeoDirectory address to any point.";
        document.getElementById('tdSearchHelp').innerText = " ";
    }
    else
    {
        if(result.ResultCount>150)
        {
            //too many results 
            //document.getElementById('tdSearchHelp').innerText = " ";
                document.getElementById('tdSearchHelp').innerText = " ";
        }
        else
        {
            if (result.ResultCount>10)
            {
                //press arrow
                document.getElementById('tdSearchHelp').innerText = "Press down arrow key to see all matches.";
            }
            else
            {
                //drop down is displayed automatically

                //document.getElementById('tdSearchHelp').innerText = "Select from the list by using down arrow key and enter or clicking with your mouse.";
            }
        }
    }

    return;
}
//**************************************************************************************************************************************

//
// OrganisationLookupResult event
//
function onOrganisationLookupResult(result)
{
    if(result.ResultCount==0)
    {
        //no result
        document.getElementById('tdOrganisationHelp').innerText = " ";
    }
    else
    {
        if(result.ResultCount>150)
        {
            //too many results 
            //document.getElementById('tdSearchHelp').innerText = "Press down arrow key below.";
        }
        else
        {
            if (result.ResultCount>10)
            {
                //press arrow
                document.getElementById('tdOrganisationHelp').innerText = "Press down arrow key.";
            }
            else
            {
                //drop down is displayed automatically
                //document.getElementById('tdSearchHelp').innerText = "Select from the list by using down arrow key and enter or clicking with your mouse.";
            }
        }
    }
    return;
}

//**************************************************************************************************************************************
//**************************************************************************************************************************************

//
// Add Pin to map 
//
function AddPin(latitude, longitude, bCenterAtPoint, text)
{
    //map.Clear();
    //Workaround PF - 10/11/2009
    map.DeleteAllShapes();
    map.DeleteRoute();
    map.DeleteAllShapeLayers();
    
    var ll = new VELatLong(parseFloat(latitude), parseFloat(longitude));
    
    // Create shape
    m_shape = new VEShape(VEShapeType.Pushpin,ll);
    m_shape.SetCustomIcon("<div class='pinStyle1'><div class='text'></div></div>");
    if (text !== null && text !== "")
    {
        m_shape.SetTitle("Point " + pinID);
        var formattedText = formatDescription(text);
        m_shape.SetDescription(replaceAll(formattedText,',','<BR>',true));
    }
    
    map.AddShape(m_shape);

    pinID = pinID + 1;

    if (bCenterAtPoint == true)
    {
       map.SetCenter(ll);
    }
   

} 

//**************************************************************************************************************************************

function fillGeoDirectoryAddressTextBoxes(GeoAddress)
{
    if (GeoAddress==null)
    {
        document.getElementById("TextAddress1").innerHTML = '';
    }
    else
    {
        var address = GeoAddress;
        var line = '';   
        var formattedText = formatDescription(address);
        document.getElementById("TextAddress1").innerHTML = replaceAll(formattedText,',','<BR>',true);
    }
    
    
        
}  

//**************************************************************************************************************************************

function UsageLimitExceeded()
{
    if (javascriptWeekCounter ==0)
    {
        document.getElementById("txtSearch").value = "No Remaining Searches this week.";
        document.getElementById("txtOrganisationSearch").value = "No Remaining Searches this week.";  
    }  
    if (javascriptMonthCounter ==0)
    {
        document.getElementById("txtSearch").value = "No Remaining Searches this month.";
        document.getElementById("txtOrganisationSearch").value = "No Remaining Searches this month.";  
    }  
    document.getElementById('txtOrganisationSearch').disabled=true;
    document.getElementById('txtSearch').disabled=true;
    document.getElementById('btnLocateOnMap').disabled=true;
    bUsageLimitExceeded=true;
}



function DecrementCounter()
{
    javascriptWeekCounter--;
    if(javascriptWeekCounter==0)
    {
        UsageLimitExceeded();
    }
    javascriptMonthCounter--;
    if(javascriptMonthCounter==0)
    {
        UsageLimitExceeded();
    }

}


//**************************************************************************************************************************************

//
// Convert Pixel to LatLong
//
function PixelToLatLong(x,y)
{
   var latLong = map.PixelToLatLong(new VEPixel(x,y)); 
   return latLong;
}

//**************************************************************************************************************************************

function formatDescription(str)
{
    var a;
    var result='';
    a=str.split(',');
    
    for (var i=0;i<a.length;i++)
    {
        if (result!='')
        {
            if (a[i] != '')
            {
                result = result + '<BR>' + a[i];   
            }
        }
        else
        {
                result = a[i];   
        }
    }
    return result;
}


//**************************************************************************************************************************************

function trim(str)
{
	return str.replace(/^\s+|\s+$/g,"");
}
  
//**************************************************************************************************************************************

function replaceAll( str, searchTerm, replaceWith, ignoreCase )   {
   var regex = "/"+searchTerm+"/g";
   if( ignoreCase ) regex += "i";
   return str.replace( eval(regex), replaceWith );
}




