var map = null ;
var currentMarker = null ;
var currentLacode = 0 ;
var areaInfo = null ;
var localSearch = new GlocalSearch() ;

function pageLoad()
{
    OnResize() ; 
    SetStatus("") ;
    SetupMapAreas() ;
    Map_Setup(initSwLng, initSwLat, initNeLng, initNeLat, initialLongitude, initialLatitude, initialZoom) ;
    
    window.onresize = OnResize ;
    GEvent.addListener( map, "moveend", function(p)
    {
        Map_ViewChange() ;
    }) ;    
}

function OnResize()
{
    var width = 0 ;
    var height = 0 ;
  
    if( typeof( window.innerWidth ) == 'number' )
    {  //Non-IE
        width = window.innerWidth ;
        height = window.innerHeight ;
    } 
    else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
    {
        width = document.documentElement.clientWidth;
        height = document.documentElement.clientHeight ;        
    }
    else if (document.body && ( document.body.clientWidth || document.body.clientHeight ) )
    {
        width = document.body.clientWidth;
        height = document.body.clientHeight ;        
    } 

    var div = document.getElementById("header") ;
    height = height - div.offsetHeight ;
    
    div = document.getElementById("footer") ;
    height = height - div.offsetHeight ;
    
    height = height - 8 ;
    
    div = document.getElementById("sidepanel") ;
    width = width - div.offsetWidth ;    
    width = width - 34 ;
    
    div = document.getElementById("map") ;
    div.style.width  = width  + "px" ;
    div.style.height = height + "px" ;            

}

function OnAreaChange()
{
   var selAreas = document.getElementById("selAreas") ;
   var selectedItem = selAreas.selectedIndex ;
   if (selectedItem < 1)
      return ;
      
   var i = selAreas.options[selectedItem].value ;
   var areaItem = areaInfo[i] ;
   
   Map_ZoomToExtent(areaItem.BottomX, areaItem.BottomY, areaItem.TopX, areaItem.TopY) ;
    
   // selAreas.selectedIndex = 0 ;

}

function ReturnVisibleWorks(swLat, swLng, neLat, neLng)
{
    var txtStartDateF = document.getElementById(fieldFromDate) ;
    var startDate = null ;
    if (txtStartDateF.value == "" || txtStartDateF.value == null || txtStartDateF.value == 'dd/mm/yyyy' )
       startDate = Date.parseInvariant("01/01/1980","dd/MM/yyyy") ;
    else
       startDate = Date.parseInvariant(txtStartDateF.value,"dd/MM/yyyy") ;
       
    if (startDate==null)
       startDate = Date.parseInvariant("01/01/1980","dd/MM/yyyy") ;   
    
    var txtEndDateF   = document.getElementById(fieldToDate) ;
    var endDate = null ;
    if (txtEndDateF.value == "" || txtEndDateF.value == null || txtEndDateF.value == 'dd/mm/yyyy')
       endDate = Date.parseInvariant("31/12/2099","dd/MM/yyyy") ;
    else
       endDate = Date.parseInvariant(txtEndDateF.value,"dd/MM/yyyy") ;
       
    if (endDate==null)
       endDate = Date.parseInvariant("31/12/2099","dd/MM/yyyy");       
    
    requestSimpleService = MapService.ReturnWorksLatLog(
        swLat, swLng, neLat, neLng, startDate, endDate,
        OnReturnVisibleWorksComplete,   //Complete event
        OnTimeout,                      //Timeout event
        OnError
        );
    return false;
}

function OnReturnVisibleWorksComplete(result) 
{
    Map_ClearWorks() ;
        
    var s1 = " works" ;
    if (result.SearchCount == 1)
    {
       s1 = " work" ;
    }
    
    var s2 = "Found " + result.SearchCount + s1 + " in visible area." ;
    
    if (result.SearchCount > maxMarkers)
    {
       s2 = s2 + "   Roadworks will be displayed on map when less than " + maxMarkers + " are visible." ;
    }
    
    SetStatus(s2) ;

    if (!result.ItemsFound)
        return ;

    for (var i = 0 ; i < result.ItemsFound.length ; ++i )
    {
       var searchItem = result.ItemsFound[i] ;
       Map_AddMarker(searchItem.Latitude, searchItem.Longitude, searchItem.Key, searchItem.Impact) ;
    }
}

function SetupMapAreas()
{
    requestSimpleService = MapService.ReturnAreaList(
        OnReturnAreaListComplete,     //Complete event
        OnTimeout,                    //Timeout event
        OnError
        );
    return false;  
}

function OnReturnAreaListComplete(result) 
{
   if (result.ItemsFound.length <= 0)
      return ;
   
   areaInfo = result.ItemsFound ;

   var selAreas = document.getElementById("selAreas") ;
   var o = new Option() ;
   o.text = "- Zoom to City/County -" ;
   o.value = -1 ;
   selAreas.options[selAreas.options.length] = o ;   

   for (var i = 0; i < result.ItemsFound.length ; ++i )
   {
      var option = new Option() ;
      var areaItem = result.ItemsFound[i] ;
      option.text = areaItem.AreaName ;
      option.value = i ;
      selAreas.options[selAreas.options.length] = option ;
   }
}


function FindAddrOrPostcode()
{
    SetStatus(" ") ;
    var input  = document.getElementById("txtSearchAddress") ;
   
    var match = /^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?[ ]*[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/.test(input.value.toUpperCase()) ;
    if (!match)
    {
        SetStatus("Specified postcode is invalid.") ;
        return ;
    }
  
    localSearch.setSearchCompleteCallback(null, 
        function()
        {
            if (localSearch.results[0])
            {
               var resultLat = localSearch.results[0].lat ;
               var resultLng = localSearch.results[0].lng ;
               Map_MoveTo(resultLat, resultLng, 16) ;
            }
            else
            {
                SetStatus("Postcode invalid or not found.") ;
            }
        }
    ) ;
    
    var pc = input.value + "," + postcodeGeocode ;
    localSearch.execute(pc) ; 
}

function OnReturnCheckPostcode(result)
{
   if (result.Latitude == 0 && result.Longitude == 0)
   {
      SetStatus("Address or Postcode not found") ;
   }
   else
   {
      Map_MoveTo(result.Latitude, result.Longitude, 17) ;
   }
}


function markerClicked(marker, name)
{
    currentMarker = marker ;
    currentLacode = name ;
    // alert(name) ;

    requestSimpleService = MapService.ReturnWorksSummary(
        name,
        OnReturnWorksSummaryComplete, //Complete event
        OnTimeout,                    //Timeout event
        OnError
        );
}

function OnReturnWorksSummaryComplete(result)
{
    var location = result.Location ;
    var address = result.Address ;
    if (result.Locality != null && result.Locality != "" )
    {
       address = address + ", " + result.Locality ;
    }    
    if (result.Town != null && result.Town != "")
    {
       address = address + ", " + result.Town ;
    }
    
    if (location.length > 40)
    {
       location = location.substr(0,40) + "..." ;
    }    
    
    if (address.length > 40)
    {
       address = address.substr(0,40) + "..." ;
    }
    
    var    html = "<div>" ;
    html = html + "Reference: <b>" + result.PromoterRef + " (" + result.LaRef + ")</b><br/>" ;
    html = html + "Location: <b>"  + location +  "</b><br/>" ;
    html = html + "Address: <b>"   + address +  "</b><br/>" ;    
    html = html + "Promoter: <b>"  + result.PromoterName + "</b><br/>" ;
    html = html + "Telephone: <b>" + result.PromoterContact + "</b><br/>" ;
    html = html + "Dates : <b>"    + result.PlannedStartDate.format("dd/MM/yyyy") + " - " +
                                     result.PlannedEndDate.format("dd/MM/yyyy") + "</b><br/>" ;
    if (fullDetailsUrl != "")
    {
       html = html + "<center><i><a href=\"javascript:ShowFullDetails(" + currentLacode + ");\"" ;
       html = html + ">Click here to view full details</a></i></center>" ;
    }                                
    html = html + "</div>" ;
    currentMarker.openInfoWindowHtml(html) ;
    currentMarker = null ;
}

function ShowFullDetails(laRef)
{
   var la = laRef /10000 ;
   var url = fullDetailsUrl + la ;
   win = window.open(url,'','width=800,height=550,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,scrollbars=1'); 
}


function OnTimeout(result) 
{
   alert("Timed out");
   alert("Error: " + result.get_message()) ;
   alert("Error: " + result.get_stackTrace());    
}
    
function OnError(result)
{
   alert("Error: " + result.get_message()) ;
   alert("Error: " + result.get_stackTrace());
}

function SetStatus(text)
{
    var lbStatus = document.getElementById(fieldStatusBar) ;
    lbStatus.innerHTML = text ;
  
}


function OnKeyPressPostcode(e,form)
{
   var key = e.keyCode || e.which;
   if (key == 13)
   {
      FindAddrOrPostcode() ;
      
      return false ;
   }
}
   
