// Switch to tries and use loc: before the city, state zip

var GLOBALTEST = "GLOBAL";
var globalCount = 0;
var globalMax = 0;
var globalMarkers = new Array();
var loc;
var name = new Array();
var transcodeAddress = new Array();
var useLatitude = new Array();
var useLongitude = new Array();
var addressType = new Array();
var phone = new Array();
var hours = new Array();
var retried = false;
var viewMode = 'normal';
var numColumns = 3;
var defaultDistance = 5;
if (location.href.indexOf("iframe") > 0){
  viewMode = 'iframe';
  numColumns = 2;
  defaultDistance = 15;
}
var reasons = new Array();
      // ====== Array for decoding the failure codes ======
      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.";

loc = new Locater();
window.addEvent('domready', function() {
    loc.init("locaterResponse","search_term");
    $("search_button").addEvent('click',function(){loc.send();});
    loc.mapLoad("map");
    var defaulDistance = defaultDistance;
    if($("sliderOverrideValue"))
    {
        //alert($("sliderOverrideValue").value); 
        defaultDistance = $("sliderOverrideValue").value;
    }
    var mySlide = new Slider($('area'), $('knob'), {
    	steps: 25,
    	onChange: function(step){
    		$('upd').setHTML(step);
    	}
    }).set(defaulDistance);
    
    if(search_term!="")
    {
        $("search_term").value = search_term;
        loc.send();
    }
});

function Locater()
{
    this.responsePanel = null;
    this.inputID = null;
    this.val = null;
    this.map = null;
    this.geocoder = null;
    this.markers = new Array();
    this.max;
    this.count;
    this.locationInfo;
    //this.centerPointData = new MapBoundsData();

    this.init = function(responsePanelID,inputID)
    {
        this.inputID = inputID;
        this.responsePanelID = responsePanelID;
    };
    this.send = function()
    {
        if ($('store_locator_debugging_info')) {
          $('store_locator_debugging_info').innerHTML = "<h3>Addresses That Could Not Be Mapped (here for debugging/development only)</h3>";
        }
        globalCount = 0;
        globalMax = 0;
        this.val = new Validate("locaterResponse");
        this.val.setStyles("defaultLocator","errorLocator");
        this.val.isEmpty("search_term","search_termError","Enter city, state or zipcode");
        if(this.val.isValid)
        {
            // fill up serializer array
            if (viewMode == 'normal'){
              Utility.turnOnInline("loadingIcon");
            }
            var ar = new Array();
            var store_type = $("retail").checked ? "retail" : "grocery";
//            var store_type = $("retail").checked ? "grocery" : "retail";
            if($("upd").innerHTML=="0"){
              range = "1";
            }
            else if (queryString("distance") > 0){
              range = queryString("distance");
            }
            else{
              range = $("upd").innerHTML;
            }
            var URL = "/callback/locater/?search_term="+$("search_term").value+"&type="+store_type+"&range="+range;
            var trackingAddress = $("search_term").value;			
 		        if (viewMode != 'iframe'){
              track('cmCreatePageElementTag("'+trackingAddress+'","Store Locater")');
 		        }
//            alert ("URL:"+URL);
            var myAjax = new Ajax(URL,
			{
			    method:"get",
			    onSuccess:function(responseText)
			    {
			        var converter = new JSONtoObject();
			        converter.convert(responseText);
			        var _responses = converter.get();
			        _responses.error ? loc.printError(_responses) : loc.printResults(_responses);
			        Utility.turnOff("loadingIcon");
			    },
			    onFailure:function()
			    {
			        Utility.turnOff("loadingIcon");
			    }
			}).request();
        }
        else
        {
            this.val.peetsYield(true);
        }
    }
    this.printResults = function(oResults)
    {
        this.map.clearOverlays();
        globalMarkers = new Array();
        var alternator = false;
        this.val.reset();
        var resultChunk="";
        var cssContainer="";
        var roundImage="";
        var Latitude ="";
        var Longitude="";
        transcodeAddress = Array();
        useLatitude = Array();
        useLongitude = Array();
        addressType = Array();
        phone = Array();
        hours = Array();
        for(var i=0;i<oResults.data.length;i++)
        {
            var Name = oResults.data[i].name;
            var Address = oResults.data[i].address;
            var City = oResults.data[i].city;
            var State = oResults.data[i].state;
            var ZipCode = oResults.data[i].zip;
            var Phone = oResults.data[i].phone;
            var Distance = oResults.data[i].distance;
            var AlternateAddress = oResults.data[i].alternate_address;
            var Latitude = oResults.data[i].latitude;
            var Longitude = oResults.data[i].longitude;
            var Status = oResults.data[i].status;
            var StoreHours = "";
            if(oResults.data[i].type=="retail")
            {
                var dayData = new Array(
                                    oResults.data[i].Monday,
                                    oResults.data[i].Tuesday,
                                    oResults.data[i].Wednesday,
                                    oResults.data[i].Thursday,
                                    oResults.data[i].Friday,
                                    oResults.data[i].Saturday,
                                    oResults.data[i].Sunday
                                    );
                var dayNames = new Array(
                                    "Monday",
                                    "Tuesday",
                                    "Wednesday",
                                    "Thursday",
                                    "Friday",
                                    "Saturday",
                                    "Sunday"
                                    );
                last = 0;
                for(var j=1;j<dayData.length+1;j++)
                {
                	// if the previous day hours to not equal the current day's hours ->
                	if(dayData[last]!=dayData[j] || dayNames[j] == "Saturday" || dayNames[j] == "Sunday")
                    {
                    	if (last == j-1)
                    	{
                    		if (dayData[j-1] != null){
                    			StoreHours += dayNames[last] + " " + dayData[j-1] + "<br>";
                    		}
                    	}
                    	else{
                    		StoreHours += dayNames[last] + "-" + dayNames[j-1] + " " + dayData[j-1] + "<br>";
                    	}
                    	last = j;
                    }
                }
                StoreHours = StoreHours.replace("Monday-Monday","Monday");
                if(!oResults.data[i].Monday)   StoreHours = "";
                if(Status == "Opening Soon")   StoreHours = "<i>Opening Soon</i>";
            }
            var DirectionsLink = "Driving Directions";
            name[i] = Name;
//            alert("test/"+Address+"/"+AlternateAddress);
            if (Latitude && Longitude)
            {
//              alert(Latitude+", "+Longitude);
              transcodeAddress[i] = Address+', '+City+', '+State+' '+ZipCode;
              useLatitude[i] = Latitude;
              useLongitude[i] = Longitude;
            }
            else if (AlternateAddress){
              transcodeAddress[i] = AlternateAddress;
            }
            else
            {
              transcodeAddress[i] = Address+', '+City+', '+State+' '+ZipCode;
            }
            addressType[i] = oResults.data[i].type;
            phone[i] = oResults.data[i].phone;
            hours[i] = StoreHours;

        if (i < 26)
        {
          var letter = String.fromCharCode("A".charCodeAt(0) + i);
        }
        else
        {
          var letter = "";
        }

        if( $("resultContainer2") )
			  {
				  buildPrintResults(Name,Address,City,State,ZipCode,Phone,Distance,StoreHours,letter);
			  }

            if(oResults.data.length == 0)
            {
            	resultChunk +='\n'+
            	'<div id="resultContainerNull">'+
						'<h1>Sorry, no results found.</h1>'+
						'<p>'+
							'Peet&#8217;s is not available in stores within the selected mile radius of this location. Try expanding your search or entering another location above.'+
						'</p>'+
						'<p>'+
							'Sign up for our email newsletter and we&#8217;ll keep you posted on all new stores added to our list.'+
						'</p>'+
					'</div>';
            }

            if(i == 0)
            {
            	cssContainer="map_bg1";
		        	roundImage = "search_results_head.gif";
  		        if (viewMode == 'iframe'){
	 	             roundImage = roundImage.replace(".gif","_iframe.gif");
		          }
	            resultChunk +='\n'+
		        '<div class="store_locator_results_round">'+
					'<img src="/images/store_locator/'+roundImage+'" class="zero" alt="" title="" />'+
				'</div>'+
				'<div class="'+cssContainer+'">';
            }

        resultChunk +='\n'+
				'<div class="address_container">'+
					'<input type="hidden" id="fullAddress'+i+'" value="'+Address+' '+City+', '+State+' '+ZipCode+'" />' +
					        '<div style="color:#cc9999;float:left;margin-left:-15px;">'+letter+'. </div>' +
                	'<div class="address"><b>'+Name+'</b><br />'+Address+'<br />'+City+', '+State+' '+ZipCode+'<br />';
        if (Phone){
          resultChunk += Phone+'<br />';
        }
        resultChunk += Distance+" miles away<br />"+ 
            			'<div class="hours">'+StoreHours+'</div>'+
            			'<div class="directions">'+
            				'<a href="javascript:void(0);" onclick="Utility.turnOn(\'from_location_outer'+i+'\')">'+DirectionsLink+'</a><br />'+
            				'<span id="from_location_outer'+i+'" style="display:none;" />'+
            				'<input class="store_locator_directions_input" onclick="if(this.value==\'from...\') this.value=\'\'" value="from..."  id="from_location_input'+i+'" type="text" /><input type="image" class="go_button" src="/images/store_locator/go.gif" alt="Go" id="get_directions_btn'+i+'" value="get directions" onclick="loc.directions(\'from_location_input'+i+'\',\'fullAddress'+i+'\')" />'+
            				'</span>' +
             			'</div>'+
             		'</div>'+
				'</div>';
			if((i+1)%numColumns == 0 && i != 0 && i+1 != oResults.data.length)
      {
		        if(cssContainer == "map_bg1")
		        {
		        	cssContainer = "map_bg2";
		        	roundImage = "search_results_null_footer.gif";
		        	roundImage2 = "search_results_head2.gif";
		        }
		        else
		        {
		        	cssContainer = "map_bg1";
		        	roundImage = "search_results_footer2.gif";
		        	roundImage2 = "search_results_head.gif";
		        }

            	resultChunk +='\n'+
            	'<div class="toplink"><a href="#top">Back to Top</a></div>'+
		        '</div>'+
		        //'<br clear="all" />'+
            	//'<div class="store_locator_results_round2">'+
				//	'<img src="/images/store_locator/'+roundImage+'" height="6" width="894" class="zero" alt="" title="" />'+
				//'</div>'+
				//'<br clear="all" />'+
		        //'<div class="store_locator_results_round">'+
				//	'<img src="/images/store_locator/'+roundImage2+'" height="6" width="894" class="zero" alt="" title="" />'+
				//'</div>'+
				'<div class="'+cssContainer+'">';
            }

            if(i+1 == oResults.data.length)
            {
            	if(cssContainer == "map_bg2")
		        {
		        	roundImage = "search_results_footer2.gif";
		        }
		        else
		        {
		        	roundImage = "search_results_null_footer.gif";
		        }
		        if (viewMode == 'iframe'){
		          roundImage = roundImage.replace(".gif","_iframe.gif");
		        }
            	resultChunk +='\n'+
            	'<div class="toplink"><a href="#top">Back to Top</a></div>'+
            	'</div>'+
            	//'<br clear="all" />'+
		        '<div class="store_locator_results_round2">'+
					'<img src="/images/store_locator/'+roundImage+'" class="zero" alt="" title="" />'+
				'</div>'+
				'<br clear="all" />';
            }

        }
        // clear map

        // geocode & print to map
        globalMax = transcodeAddress.length;
        this.processAddress();
//        for(var x=0;x<transcodeAddress.length;x++)
//        {
//            //if(x<50)
//            //{
//            this.showAddress(name[x],transcodeAddress[x],addressType[x],phone[x],hours[x],x,transcodeAddress.length);
//            //}
//            globalCount++;
//        }
        if($("resultContainer2")) printResults();
        $("resultContainer").innerHTML = resultChunk;
    }
    this.processAddress = function()
    {
      if (globalCount < globalMax)
      {
        x = globalCount;
//        $('store_locator_debugging_info').innerHTML += x + "<br />";
//        setTimeout('loc.showAddress("'+name[x]+'","'+transcodeAddress[x]+'","'+addressType[x]+'","'+phone[x]+'","'+hours[x]+'",'+x+','+transcodeAddress.length+');', 150);
        this.showAddress(name[x],transcodeAddress[x],addressType[x],phone[x],hours[x],x,transcodeAddress.length,useLatitude[x],useLongitude[x]);
        globalCount++;
        setTimeout("loc.processAddress()",400);
        retried = false;
      }
      else
      {
        return;
      }
    }
    this.printError = function(oError)
    {
        this.val = new Validate("locaterResponse");
        this.val.generalError("search_termError",new Array(oError.response));
        this.val.peetsYield(true);
    }
    this.directions = function(inputID,fullAddressID)
    {
        if($(inputID).value != "")
        {
            if (viewMode = "iframe"){
              window.open("http://maps.google.com/?saddr="+$(inputID).value.replace('#','')+"&daddr="+$(fullAddressID).value.replace('#',''), "google", "width=850,height=510");
            }
            else{
              MOOdalBox.open( // case matters
              "/templates/googleModal.php?start_address="+$(inputID).value.replace('#','')+"&store_address="+$(fullAddressID).value.replace('#',''), // the link URL
             "Directions to Peet's stores by Google Maps: ", // the caption (link's title) - can be blank
             "850 510" // width and height of the box - can be left blank
              );
            }
        }
    }
    this.mapLoad = function(id)
    {
        if (GBrowserIsCompatible())
        {
            this.map = new GMap2(document.getElementById(id));
            this.map.addControl(new GLargeMapControl());
            this.map.addControl(new GMapTypeControl());
            this.map.addMapType(G_PHYSICAL_MAP);
            this.map.addControl(new GOverviewMapControl());
            this.map.setCenter(new GLatLng(37.02009820136811, -96.416015625), 3);
            this.geocoder = new GClientGeocoder();
        }
    }
    this.showAddress = function(name,address,type,phone,hours,count,max,lat,lng) {
//      confirm(count);
//if (count >= 6) return;
      if (count >= 26){
        return;
      }
      this.count = count;
      this.max = max;
      var GLOBALTEST = "FUNCTION SCOPE";
      if (lat && lng){
      	thislocation = lat+","+lng;
      }
      else{
      	thislocation = address;
      }
      this.geocoder.getLatLng(
        thislocation,
        function(point) {
          //alert("Point:"+point);
          if (!point) {
//          if (!point && !lat && !lng) {
//            alert("address: "+address+" / "+retried);
            if (retried == true)
            {
              if ($('store_locator_debugging_info')){
                $('store_locator_debugging_info').innerHTML += address + "<br />";
              }
              retried = false;
            }
            else{
//              $('store_locator_debugging_info').innerHTML += address + "  ------------------ NOT FOUND<br />";
              address = loc.cleanseAddress(address);
              loc.showAddress(name,address,type,phone,hours,count,max);
              retried = true;
            }
          } else {
//            if (lat && lng){
//            	point = "("+lat+","+lng+")";
//            }
          
            //            $('store_locator_debugging_info').innerHTML += address + " FOUND<br />";
            //loc.trackPoint(point);
            //loc.map.setCenter(point, 13);

            //            var marker = new GMarker(point);

            // Create a lettered icon for this point using our icon class
              // Create a base icon for all of our markers that specifies the
              // shadow, icon dimensions, etc.
              var baseIcon = new GIcon();
              baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
              baseIcon.iconSize = new GSize(20, 34);
              baseIcon.shadowSize = new GSize(37, 34);
              baseIcon.iconAnchor = new GPoint(9, 34);
              baseIcon.infoWindowAnchor = new GPoint(9, 2);
              baseIcon.infoShadowAnchor = new GPoint(18, 25);
              var letter = String.fromCharCode("A".charCodeAt(0) + count);
              var letteredIcon = new GIcon(baseIcon);
              letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";

              // Set up our GMarkerOptions object
              markerOptions = { icon:letteredIcon };
              var marker = new GMarker(point, markerOptions);

              var infoWindow = ""+
              "<div style=\"color:#000000;width:250px;padding:5px;\">";
              //alert(type);
              var PeetsRetail = (type=="retail") ? "Peet's Store: " : "" ;
              infoWindow += PeetsRetail+"<b>"+name+"</b><br />";
              infoWindow += address+"<br />";
              infoWindow += phone+"<br />";
              infoWindow += hours;
              infoWindow += "</div>";
              GEvent.addListener(marker, "mouseover", function() {
                marker.openInfoWindowHtml(infoWindow);
              });
              loc.map.addOverlay(marker);
              //marker.openInfoWindowHtml(address);
              globalMarkers.push(marker);
              //alert(globalCount);
              //alert(globalMax);
              //alert("defined?");
              if(loc.count < 10 || loc.count%10 == 0 || loc.count==loc.max-1 || loc.count==25)
              {
                var bounds = new GLatLngBounds;
                for (var i=0;i<globalMarkers.length;i++)
                {
                  bounds.extend(globalMarkers[i].getPoint());
                }
                loc.map.setZoom(loc.map.getBoundsZoomLevel(bounds)-1);
                loc.map.setCenter(bounds.getCenter());
              }
          }
        }
        );
    }
    this.printMap = function()
    {
        var store_type = $("retail").checked ? "retail" : "grocery";
        var catcher = window.open("/store_locator/print/?distance="+$("upd").innerHTML+"&type="+store_type+"&search_term_global="+$("search_term").value,"printMap","menubar=0,scrollbars=1,resizable=0,width=909,height=700");
    }
    this.cleanseAddress = function(address)
    {
      // List of words to be standardized
      var standards = [   ["Road","Rd."],   
                        ["Street","St."], 
                        ["Avenue","Ave."], 
                        ["Av","Ave."], 
                        ["Drive","Dr."],
                        ["Saint","St."], 
                        ["North","N."],   
                        ["South","S."],    
                        ["East","E."], 
                        ["West","W."],
                        ["Expressway","Expy."],
                        ["Parkway","Pkwy."],
                        ["Terrace","Ter."],
                        ["Turnpike","Tpke."],
                        ["Hwy.","Highway"],
                        ["HWY","Highway"],
                        ["Lane","Ln."],
                        ["Ste","Suite"],
                        ["Boulevard","Blvd."]
                     ];
      // Make sure that the address words are standardized
      for (var i=0; i<standards.length; i++) {
        regex = new RegExp('\\b'+standards[i][0]+'\\b', 'i');
        if (address.match(regex))
        {
          address = address.replace(regex,standards[i][1]+' ');
        }
      }

      // Remove PO Box
      address = address.replace(/(.*?)\/PO Box(.*?)/i,"$1");
      // Make sure there is a comma before the word 'Vendor'
      address = address.replace(/(?!,)\s*Vendor/,', Vendor');
      // Make sure there is a comma before the word 'Suite'
      address = address.replace(/(?!,)\s*Suite/,', Suite');
      if (address.indexOf('Routes') != -1){
        address = address.replace(/(.*)Routes(.*?)and(.*)/i, "$1Route$2at$3");
      }
      else if(address.indexOf('Storage') != -1 
              || address.indexOf('Stor') != -1
              || address.indexOf('Warehouse') != -1
              || address.indexOf('#') != -1
              || address.indexOf('Haul') != -1
              || address.indexOf('U-Store') != -1
              || address.match(/^\D/)
              || address.indexOf('C/O') != -1){
        // Use only after the first digit (trailing a space)
        address = address.replace(/(.*?)(\s\d.*)/, "$2");
      }
      else{
        address = address.replace('&','and');
        address = address.replace('NO SIGNATURE REQUIRED','');
        address = address.replace('Twentieth','20th');
        address = address.replace(',Shop',', Suite');

        var address_parts = address.split(",");
//        alert("first part"+address_parts[0]);
        if (address_parts.length > 3){
          for (i=0;i<=address_parts.length-3;i++){
            address_parts[i] = address_parts[i].replace(/^\s+|\s+$/g, '') ;
//            alert("Address Part: ("+i+"): "+address_parts[i]);
            if (/^\d/.test(address_parts[i])){
              address = address_parts[i]+", "+address_parts[address_parts.length-2]+", "+address_parts[address_parts.length-1];
            }
          }
        }
      }
      // Remove anything between astisks
      address = address.replace(/(.*?)\*(.*?)\*(.*?)/, "$1 $3");
      // Remove double-spaces 
      address = address.replace(/\s+/, " ");
      // Trim outside spaces
      address = address.replace(/^\s+(.*?)\s+$/, "$1");
//      alert("Retried Address: "+address);
      return address.toUpperCase();
    }
}
var printStoreList = new Array();
function buildPrintResults(Name,Address,City,State,ZipCode,Phone,Distance,StoreHours,Letter)
{
    var FullAddress = Letter+" <b>"+Name+"</b><br />"+
                      Address+"<br />" +
                      City+", "+State+" "+ZipCode+"<br />"+
                      "Distance: "+Distance+"<br />";
    FullAddress += StoreHours ? StoreHours+"<br />" : "";                      
    printStoreList.push(FullAddress);
}
function printResults()
{
    var finalString = "<b>Search Results: </b><table style='font-famaily:Arial;font-size:12px;' cellpadding='10' width='900'>\n";
        finalString += "<tr>\n";
    for(var i=0;i<printStoreList.length;i++)
    {
        finalString += "<td width='270' align='left'>\n";
        finalString += printStoreList[i];
        finalString += "</td>\n"
        if((i+1)%3==0)
        {
            finalString += "</tr>\n<tr>\n";
        }
    }
        finalString += "</tr>\n";
        finalString += "</table>\n";
    $("resultContainer2").innerHTML = finalString;
}
function queryString( key )
{
    var re = new RegExp( "[?&]" + key + "=([^&$]*)", "i" );
    var offset = location.search.search( re );
    if ( offset == -1 ) return null;
    return RegExp.$1;
}