//set global variables
var map
var mgr
var side_bar_html = ""
var geocoder
var gmarkers = []
var htmls = []
var i = 0
var side_bar_html = "";
var xml = ""
var markers = ""
var lat = ""
var lng = ""
var storeName = ""
var address = ""
var hours = ""
var phone = ""
var directions = ""
var scurl = ""
var x_coord=""
var y_coord=""


//safari hack
function state_Change()
{
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4)
  {
  // if "OK"
  if (xmlhttp.status==200)
  {
    
    response = xmlhttp.responseXML.documentElement;
    markers = response.getElementsByTagName("root")
    //alert('me first' + markers.length)
    
    //alert(y_coord)
    //alert(x_coord)
        determineLoad(y_coord,x_coord)
    
  }
  else
  {
    //alert("Problem retrieving XML data:" + xmlhttp.statusText)
  }
  }
}


function load_xml(y,x)
{
//alert('load')

 if (BrowserDetect.browser == "Safari")
    {
    
        
        
        //safari browser hack
        xmlhttp=null
        // code for Mozilla, etc.
        if (window.XMLHttpRequest)
        {
            xmlhttp=new XMLHttpRequest()
           // alert('mozilla');
        }
          if (xmlhttp!=null)
          {
              //alert('safari');
              y_coord = y;
              x_coord = x;
              xmlhttp.onreadystatechange=state_Change
              xmlhttp.open("GET","cached_feed.xml",true)
              xmlhttp.send(null)
              
          } 
        
          
    
    
    }else{
                   
    //new code for ff3
            
            if (window.XMLHttpRequest)
            {
	            //Create XMLHttpRequest object in non-Microsoft browsers
	            request = new XMLHttpRequest();
	            
            }
            else if (window.ActiveXObject)
            {
	            // Create XMLHttpRequest via MS ActiveX
	            try
	            {
		            // Try to create XMLHttpRequest in later versions
		            // of Internet Explorer
		            request = new ActiveXObject("Msxml2.XMLHTTP");
	            }
	            catch (e1)
	            {
		            // Failed to create required ActiveXObject
		            try
		            {
			            // Try version supported by older versions
			            // of Internet Explorer
			            request = new ActiveXObject("Microsoft.XMLHTTP");
		            } catch (e2)

		            {
		            // Unable to create an XMLHttpRequest with ActiveX
		            }
	            }
            }
            
            request.open("GET","cached_feed.xml",true);
            request.onreadystatechange = function()
            {
            
	            if (request.readyState == 4)
	            {
		            xmlDoc = request.responseXML;
		            markers = xmlDoc.getElementsByTagName("root")
		            determineLoad(y,x)
         		    //processing xml...
	            }
            }
            request.send(null)

    
        
    }
    
     
}

function getZipFromQueryString()
{
    var args = getArgs()
    if (args.Zip)
    {
      zip = Number(args.Zip)
      
    }
    
    return zip
    
    
}
    
    function getArgs() {
        var args = new Object()
        var query = location.search.substring(1)
        var pairs = query.split("&")
        for(var i = 0; i < pairs.length; i++) {
            var pos = pairs[i].indexOf('=')
            if (pos == -1) continue;
                var argname = pairs[i].substring(0,pos)
                var value = pairs[i].substring(pos+1)
                args[argname] = unescape(value)
        }
        return args
    }


    function determineLoad(y,x)
    {
    
        /*//load xml data
        GDownloadUrl("DataFeed.aspx", function(data) {

            xml = GXml.parse(data)
  	        markers = xml.documentElement.getElementsByTagName("root")
          	

        })*/
        
       // alert('here');
        
        //alert(y + "," + x);
        if(x && y)
        {
            load(y,x);
            
            //load(y,x)
        }else{
        
            img = document.getElementById("map").style.background = "url(storelocator_startbg.gif)"
            if(side_bar_html != "")
            {
                document.getElementById("sl_side_bar").innerHTML = side_bar_html
            }
		
        }    
        
    
    }
   


   function load(y,x) {
   
    //alert('test')
     if (GBrowserIsCompatible()) {
       
       map = new GMap2(document.getElementById("map"))
       

       geocoder = new GClientGeocoder()
       //alert(x + "," + y);
	  	map.enableDoubleClickZoom()
        map.addControl(new GMapTypeControl())
        map.addControl(new GLargeMapControl())
        map.addControl(new GScaleControl())
        map.addControl(new GOverviewMapControl())
        
        
        if(x && y)
        {
            map.setCenter(new GLatLng(x, y), 11)
            //display locations
	        display_locations()
                
        }else{
            map.setCenter(new GLatLng(38.27268853598097, -96.943359375), 4)
        }


	      // arrays to hold copies of the markers and html used by the side_bar
	      // because the function closure trick doesnt work there
	     
	
		
		
		GEvent.addListener(map, 'moveend', function () {
		        
		                display_locations()
                    

		 			})
            

     }
   }







	 function createMarker(point, number,htmlMsg, sideBarHTML) 
        {
          var marker = new GMarker(point)
          GEvent.addListener(marker, "click", function() 
          {
            marker.openInfoWindowHtml("<div class=\"sl_info_window\">" + htmlMsg + "</div>")
          })

			// save the info we need to use later for the side_bar
			gmarkers[number] = marker
			htmls[number] = "<div class=\"sl_info_window\">" + htmlMsg + "</div>"
			// add a line to the side_bar html
	        side_bar_html += "<div class=\"sl_listing\">" + sideBarHTML + "<div class=\"sl_separator\">&nbsp;</div></div>"
		    
		    //alert(side_bar_html)
		     
	        i++
          return marker
        }
	
		// This function picks up the click and opens the corresponding info window
	      function myclick(i) {
	        gmarkers[i].openInfoWindowHtml(htmls[i])
	      }
	

   function showAddress(formValue) {
   
   //first, look for map
   //alert(formValue)
	    if(!map)
	    {
	        
	        img = document.getElementById("map").style.background = ""
	        load()
	        
	     }
	/*
		//parse address fields
		rules: 
		if city is present, state is required
		state is fine by itself
		zip is fine by itself

	*/
	
	    //alert(formValue)
		city = formValue.city.value
		state = formValue.state.value
		zip = formValue.zip.value
		miles = formValue.miles.value
		
		if (city && !state)
		{
			document.getElementById("error_message").innerHTML = "Please select a state with your city selection"
			return
		}else{
			document.getElementById("error_message").innerHTML = ""
		}
	
		var address= ""
		//form address
		if (city) { address = city + ", "}
		if (state) { address += state + " "}
		if (zip) {address += zip}
	
	
     if (geocoder) {
       geocoder.getLatLng(
         address,
         function(point) {
           if (!point) {
             alert("We are sorry, that address cannot be found in our system. Please check that you typed the address correctly and enter it again.")
           } else {
           
            if(city)
            {
                var zoomLvl = 10
            }
            
            if(state && !city)
            {
            
                var zoomLvl = 7
            
            }
            
            if(zip)
            {   
                var zoomLvl = 11
            }
            switch(miles)
            {
            
                case "10":
                    zoomLvl = 12
                    break
                    
                case "20":
                    zoomLvl = 11
                    break
                
                case "30-50":
                    zoomLvl = 10
                    break
                    
                
           }
           
           // alert(zoomLvl)
             map.setCenter(point, zoomLvl)
             //var marker = new GMarker(point)
             //map.addOverlay(marker)
             //marker.openInfoWindowHtml(address)
           }
         }
       )
     }
   }
   
    function getSurveyID(storeID)
    {
        
        var stateAbbr = storeID.substr(0,2)
        var newAbbr = ''
        
        switch(stateAbbr)
        {
            case "AL":
               newAbbr = "01"
               break
               
            case "AK":
               newAbbr = "02"
               break
               
            case "AZ":
               newAbbr = "03"
               break
               
            case "AR":
                newAbbr = "04"
                break
                
            case "CA":
                newAbbr = "05"
                break
                
            case "CO":
                newAbbr = "06"
                break
                
            case "CT":
                newAbbr = "07"
                break
                
            case "DE":
                newAbbr = "08"
                break
                
            case "FL":
                newAbbr = "09"
                break
                
            case "GA":
                newAbbr = "10"
                break
                
            case "HI":
                newAbbr = "11"
                break
                
            case "ID":
                newAbbr = "12"
                break
                
            case "IL":
                newAbbr = "13"
                break
                
            case "IN":
                newAbbr = "14"
                break
                
            case "IA":
                newAbbr = "15"
                break
                
            case "KS":
                newAbbr = "16"
                break
                
            case "KY":
                newAbbr = "17"
                break
                
            case "LA":
                newAbbr = "18"
                break
                
            case "ME":
                newAbbr = "19"
                break
                
            case "MD":
                newAbbr = "20"
                break
            
            case "MA":
                newAbbr = "21"
                break
                
            case "MI":
                newAbbr = "22"
                break
                
            case "MN":
                newAbbr = "23"
                break
                
            case "MS":
                newAbbr = "24"
                break
                
            case "MO":
                newAbbr = "25"
                break
                
            case "MT":
                newAbbr = "26"
                break
                
            case "NE":
                newAbbr = "27"
                break
                
            case "NV":
                newAbbr = "28"
                break
                
            case "NH":
                newAbbr = "29"
                break
                
            case "NJ":
                newAbbr = "30"
                break
                
            case "NM":
                newAbbr = "31"
                break
                
            case "NY":
                newAbbr = "32"
                break
                
             case "NC":
                newAbbr = "33"
                break
                
             case "ND":
                newAbbr = "34"
                break
                
             case "OH":
                newAbbr = "35"
                break
                
             case "OK":
                newAbbr = "36"
                break
                
             case "OR":
                newAbbr = "37"
                break
                
             case "PA":
                newAbbr = "38"
                break
                
             case "RI":
                newAbbr = "39"
                break
                
             case "SC":
                newAbbr = "40"
                break
                
             case "SD":
                newAbbr = "41"
                break
                
             case "TN":
                newAbbr = "42"
                break
                
             case "TX":
                newAbbr = "43"
                break
                
             case "UT":
                newAbbr = "44"
                break
                
             case "VT":
                newAbbr = "45"
                break
                
             case "VA":
                newAbbr = "46"
                break
                
              case "WA":
                newAbbr = "47"
                break
                
              case "WV":
                newAbbr = "48"
                break
                
              case "WI":
                newAbbr = "49"
                break
                
              case "WY":
                newAbbr = "50"
                break
                
              case "DC":
                newAbbr = "51"
                break
                
               case "PR":
                newAbbr = "52"
                break
                
        
        }
        surveyID = newAbbr + storeID.substr(2)
        return surveyID
    
    }

	function checkForValue(the_node)
	{

		if(the_node)
		{

			if(the_node.nodeValue != "NULL")
			{
				return the_node.nodeValue
			}else{

				return ""

			}

		}else{

		        return ""
		}

	}



	function checkForValueAddress(the_node)
	{

		if(the_node)
		{

			if(the_node.nodeValue != "NULL")
			{
				return "<br />" + the_node.nodeValue
			}else{

				return ""

			}

		}else{

		        return ""
		}

	}



	function display_locations()
	{
		
		bounds = map.getBounds()
		
		
        
        var total = 0;
        //alert(markers.length);
		for (var i = 0; i < markers.length; i++) 
          {
          
		        var a_location = markers[i]
          
                
            
                
				crm = a_location.getElementsByTagName("CRM_CODE")[0].firstChild.nodeValue
				lat = a_location.getElementsByTagName("Latitude")[0].firstChild.nodeValue
				lng = a_location.getElementsByTagName("Longitude")[0].firstChild.nodeValue
				storeName = checkForValue(a_location.getElementsByTagName("StoreName")[0].firstChild)
                    	address = checkForValue(a_location.getElementsByTagName("Address")[0].firstChild) + checkForValueAddress(a_location.getElementsByTagName("Address2")[0].firstChild) + "<br />" + checkForValue(a_location.getElementsByTagName("City")[0].firstChild)
 + "," + checkForValue(a_location.getElementsByTagName("State")[0].firstChild)+ " " + checkForValue(a_location.getElementsByTagName("Zip")[0].firstChild)

                    	hours = checkForValue(a_location.getElementsByTagName("Hours")[0].firstChild)

                    	phone = checkForValue(a_location.getElementsByTagName("Phone")[0].firstChild)

                    	directions = checkForValue(a_location.getElementsByTagName("Directions")[0].firstChild)

                    	scurl = getSurveyID(checkForValue(a_location.getElementsByTagName("CRM_CODE")[0].firstChild))
				
			                    
                    
                
                
            
             
            
            var point = new GLatLng(parseFloat(lat), parseFloat(lng))
            
            if(bounds.contains(point))
			{
			    //total += 1
			    var googleDirections
			    
			    if (address)
			    {
			        googleDirections = "http://www.google.com/maps?f=q&hl=en&q=" + address.replace("<br />","+") + " &sll=" + lat + "," + lng + "&ie=UTF8&z=16&iwloc=addr&om=1"
			    
			    }
			    
			    var htmlMsg = String("<div class=\"storeName\"><b>" + storeName + "</b></div>")
                htmlMsg += String("<div class=\"address\">" + address + "</div>")
                htmlMsg += String("<div class=\"hours\"><b>Hours of operation</b><br />" + hours + "</div>")
                htmlMsg += String("<div class=\"phone\"><b>Telephone</b><br />" + phone + "</div>")
                htmlMsg += String("<div class=\"directions\"><b>Directions</b><br />" + directions + "</div>")
                htmlMsg += String("<div class=\"get_directions\"><a href=\"" + googleDirections + "\" target=\"_blank\">Get Directions</a></div>")
                //htmlMsg += String("<div class=\"survey\"><a href=\"http://www.mshare.net/websurvey/app?gateway=sportclips&storeNumber=" + scurl + "\" target=\"_blank\">Offer store feedback</a></div><br /><br />")
                htmlMsg += String("<div class=\"survey\"><a href=\"http://www.instantevaluatereports.com/demos/SC/internet_feedback.php?storeNumber=" + scurl + "\" target=\"_blank\">Offer store feedback</a></div><br /><br />")
                
                var sideBarHTML = String("<div class=\"storeName\"><a href=\"javascript:myclick(" + i + ")\">" + storeName + "</a></div>")
                sideBarHTML += String("<div class=\"address\">" + address + "</div>")
                sideBarHTML += String("<div class=\"hours\"><b>Hours of operation</b><br />" + hours  + "</div>")
                sideBarHTML += String("<div class=\"phone\"><b>Telephone</b><br />" + phone  + "</div>")
                //sideBarHTML += String("<div class=\"survey\"><a href=\"http://www.mshare.net/websurvey/app?gateway=sportclips&storeNumber=" + scurl + "\" target=\"_blank\">Offer store feedback</a></div><br /><br />")
                sideBarHTML += String("<div class=\"survey\"><a href=\"http://www.instantevaluatereports.com/demos/SC/internet_feedback.php?storeNumber=" + scurl + "\" target=\"_blank\">Offer store feedback</a></div><br /><br />")
                
            	var ObjHtmlMarker = createMarker(point, i,htmlMsg, sideBarHTML)
            	
            	map.addOverlay(ObjHtmlMarker)
     
			}
	  }
	  
	  	// put the assembled side_bar_html contents into the side_bar div
		if(side_bar_html != "")
		{
		    document.getElementById("sl_side_bar").innerHTML = side_bar_html
		    side_bar_html = ""
	    }
	    
	    //alert(total)
}