var geocoder = new GClientGeocoder();

var search = '';

var contingency = '';



var reasons = [];

reasons[G_GEO_SUCCESS]            = "Success";

reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";

reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";

reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";

reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";

reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";

reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";





var address_attempts;

var found_address;

var address_attempt_counter;

var current_attempt;





function alreadyInAttempts(attempt)

{

   for(var i = 0; i < address_attempts.length; i++)

   {

      if(address_attempts[i] == attempt)

      {

         return true;  

      }

   }   

   return false;

}



function lookupAddress() 

{ 

   var line1 = document.getElementById('line1').value;

   var street = document.getElementById('street').value;

   var area = document.getElementById('area').value;

   var county = document.getElementById('county').value;

   var country = 'Ireland';

   

   // Permuation list

   

   // e.g. 31 Lindsay House, Patrick Street, [blank], Dublin, Ireland (p:3)

   // e.g. 48, George Street, Dun Laoghaire, Dublin, Ireland (p:1)

   // e.g. 10, Bull Alley Street, [blank], Dublin, Ireland (p:2)

   // e.g. Donnybrook Road, Dublin, Ireland (p:4)

   // e.g. [blank], [blank], Knocknakillew, Mayo, Ireland (p:5)

   

   // 1: line1 + street + area + county + country (all)

   // 2: line1 + street + county + country (axe area)

   // 3: street + area + county + country (axe line1)

   // 4: street + county + country (axe line1 and area)

   // 5: area + county + country (axe line1 and street)

   

   var full_address = '';

   var line1_present = false;

   var street_present = false;

   var area_present = false;

   if(line1 != '') { full_address += line1 + ', '; line1_present = true; }

   if(street != '') { full_address += street + ', '; street_present = true; }

   if(area != '') { full_address += area + ', '; area_present = true; }

   full_address += county + ', ' + country; 

   var no_info = county + ', ' + country;  

   

   if(!line1_present && !street_present && !area_present)

   {

      alert("Please provide your address");

      return;  

   }

   

    

   address_attempts = [];

   var aac = 0;

   address_attempts[aac++] = full_address;

   // There has to be something to axe

   if(area_present) 

   {

      var attempt = '';

      if(line1_present) attempt += line1 + ', ';

      if(street_present) attempt += street + ', ';

      // Ignore area

      attempt += county + ', ' + country;

      if(!alreadyInAttempts(attempt) && attempt != no_info)

      {

         address_attempts[aac++] = attempt;  

      }

   }

   // There has to be something to axe

   if(line1_present) 

   {

      var attempt = '';

      // Ignore line1

      if(street_present) attempt += street + ', ';

      if(area_present) attempt += area + ', '; 

      attempt += county + ', ' + country;

      if(!alreadyInAttempts(attempt) && attempt != no_info)

      {

         address_attempts[aac++] = attempt;  

      } 

   }

   // There has to be something to axe

   if(line1_present && area_present) 

   {

      var attempt = '';

      // Ignore line1

      if(street_present) attempt += street + ', ';

      // Ignore area

      attempt += county + ', ' + country;

      if(!alreadyInAttempts(attempt) && attempt != no_info)

      {

         address_attempts[aac++] = attempt;  

      }

   }

   // There has to be something to axe

   if(line1_present && street_present) 

   {

      var attempt = '';

      // Ignore line1

      // Ignore street

      if(area_present) attempt += area + ', ';

      attempt += county + ', ' + country;

      if(!alreadyInAttempts(attempt) && attempt != no_info)

      {

         address_attempts[aac++] = attempt;  

      }

   }

   

   

   found_address = false;

   address_attempt_counter = 0;

   if(address_attempts.length >= 1)

   {

      current_attempt = address_attempts[address_attempt_counter++];

      geocoder.getLocations(current_attempt,addressReturn);  

   }

}









function addressReturn(result)

{

   if (result.Status.code == G_GEO_SUCCESS) 

   {

     if (result.Placemark.length > 1) 

     { 

       found_address = true;

       // Loop through the results

       var m = 'Did you mean?<br>';

       for (var i=0; i<result.Placemark.length; i++) {

         var p = result.Placemark[i].Point.coordinates;

         m += ""+(i+1)+": <a href='javascript:findStore(" +p[1]+","+p[0]+")'>"+ result.Placemark[i].address+"</a><br>";

       }

       showMessage(m);

     }

     else 

     {

       var p = result.Placemark[0].Point.coordinates;

       found_address = true;

       findStore(p[1],p[0]); 

     }

   }

   else 

   {

     var reason="Code "+result.Status.code;

     if (reasons[result.Status.code]) {

       reason = reasons[result.Status.code]

     } 

     if(found_address == false)

     {

        if(address_attempt_counter < address_attempts.length)

        {

           current_attempt = address_attempts[address_attempt_counter++];

           geocoder.getLocations(current_attempt,addressReturn);  

        }

        else

        {
           // If we can't find this address, ajax call to determine
           // any address overrides...
           searchAddressOverride();
        }

     }

   }



}





function findStore(lat,lng)

{
   var store_match = -1;

   for(var i = 0; i < stores.length; i++)

   {

      i_pol = stores[i][2];

      if(i_pol.Contains(new GLatLng(lat,lng)))

      {

         store_match = i;
         break;

      } 

   } 

   if(store_match == -1)

   {

      showMessage("Unfortunately, we don't deliver to this address");

   }  

   else

   {
      document.location.href = '/branch/'+encodeURI(stores[store_match][0].toLowerCase())+'.html';
      //showMessage("Your nearest store is: <a href=\"/branch/"+encodeURI(stores[store_match][0].toLowerCase())+".html\">" + stores[store_match][0] + "</a>");  

   }

}


function jumpStore(s)
{
   document.location.href = '/branch/'+encodeURI(s.toLowerCase())+'.html';
   //showMessage("Your nearest store is: <a href=\"/branch/"+encodeURI(s.toLowerCase())+".html\">" + s + "</a>");  
}





function showMessage(m)

{

   var inner = '<table cellpadding="0" cellspacing="0"><tr><td style="width:20px;">&nbsp;</td><td id="AddressRecommendations" style="width:500px; height:55px;">'+m+'</td></tr></table>'; 

   var obj = document.getElementById('message');

   obj.innerHTML = inner;

   obj.style.display = '';  

}







function loadPolygons()

{

   for(var k = 0; k < stores.length; k++)

   {

       var locs = [];

       var locc = 0;

       var stringified = stores[k][1];

       stringified = stringified.replace(/\),\(/g,'|');  

       var toks = stringified.split('|');

       for(var i = 0; i < toks.length; i++)

       {

          var clear_t = toks[i].replace(/[()]/g,'');  

          var clear_t_parts = clear_t.split(',');

          if(clear_t_parts.length == 2)

          {

             var glatlng = new GLatLng(clear_t_parts[0],clear_t_parts[1]);

             locs[locc++] = glatlng;

          }

       }

       if(!locs[locs.length-1].equals(locs[0]))

       {

          locs[locs.length] = locs[0]; // Join

       }

       stores[k][2] = new GPolygon(locs, "#F4BA0E", 2, 1, "#E04B2A", 0.2);  

   }

}











function searchAddressOverride()
{
   var url = '/ajax/search_address_override.ajax.php?address='+current_attempt;
   searchAddressOverrideRequest(url);
}


function searchAddressOverrideResponse()
{
   if (xmlHttp.readyState==4)
   {
      rc = xmlHttp.responseText;
      if(rc != '')
      {
         var res = rc.split('#');
         if(res.length == 1)
         {
            var res_parts = res[0].split('|');
            showMessage("Your nearest store is: <a href=\"/branch/"+encodeURI(res_parts[1].toLowerCase())+".html\">" + res_parts[1] + "</a>");  
         }
         else
         {
            var m = 'Did you mean?<br>';
            for (var i = 0; i < res.length; i++) 
            {
               var res_parts = res[i].split('|');
               m += ""+(i+1)+": <a href=\"javascript:jumpStore('"+res_parts[1].replace("'","\\'")+"')\">"+res_parts[0]+"</a><br>";
            }
            showMessage(m);
         }
      }
      else
      {
         showMessage("Unfortunately, we couldn't find this address"); 
         log();
      }
   }
}

function log()
{
   xmlHttp=GetXmlHttpObject();
   if (xmlHttp!=null)
   {
      xmlHttp.open("GET",'/ajax/log.ajax.php?current_attempt='+current_attempt,true);
      xmlHttp.send(null);
   }
}

function searchAddressOverrideRequest(url)
{
   xmlHttp=GetXmlHttpObject();
   if (xmlHttp!=null)
   {
      xmlHttp.onreadystatechange=searchAddressOverrideResponse;
      xmlHttp.open("GET",url,true);
      xmlHttp.send(null);
   }
}





function GetXmlHttpObject()
{
   var xmlHttp;
   try
   {
      xmlHttp=new XMLHttpRequest();
   }
   catch (e)
   {
      try
      {
         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e)
      {
         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
   }
   return xmlHttp;
}