

    //ABQIAAAAufon4Pew5yXo-359nMMWJRROFIBwrsbByLK8J49DWFrtDg72CBT1p9hyxmvYC96Xq8aYHCEsQ_WCHg crobinson.icon...site key
	var GoogleMaps;
	var BabyNamespace;
	var StatesToPlotOnStart = new Array();
	window.addEvent( "domready", function() {
		if( GBrowserIsCompatible() ) {
		    var BabyNamespaceClass = new Class( BabyNameSpaceGoogleMapsMashUpImpl );
            BabyNamespace = new BabyNamespaceClass();
            
			var mooGooMapsClass = new Class( mooGooMaps );
			
			GoogleMaps = new mooGooMapsClass( "map", {
				centerX: BabyNamespace.GoogleMapSettings.CenterX,
		        centerY: BabyNamespace.GoogleMapSettings.CenterY,
		        zoom: BabyNamespace.GoogleMapSettings.DefaultZoom
		        //,customIcon: BabyNamespace.GoogleMapSettings.stateIcon
		    });
			BabyNamespace.setMapRef(GoogleMaps);
			GoogleMaps.showLargeZoom();
			//this.map.addControl(new GSmallMapControl());
		}
		
	});
	
	window.onunload = function() {
		GUnload();	
	};

// Adjust so we don't need the country drop down.
function CountryDropDownFix(country) {
    this.value = country;
}

var BabyNameSpaceGoogleMapsMashUpImpl = {
    mooGooMapRef: null,
    cachedStateHTML: null,
    cachedCityHTML: null,
    countryDropDown: null,
    stateDropDown: null,
    cityDropDown: null,
    currentState: null,
    currentCity: null,
    currentCityId: null,
    arrayOfStateNames: null,
    hasBubbleOpen: null,
    hasClickEvent: null,
    collectionOfStateLatsAndLongsToSave: new Array(),
    setMapRef: function(map) {
        this.mooGooMapRef = map;
    },
    setMessageAtTopOfMap: function(Message) {
        $('GoogleMapMessageBox').setText(Message);
    },
    SetMessageToStateAndCountry: function() {
        this.setMessageAtTopOfMap(this.cityDropDown.GetSelectedText() + ", " + this.arrayOfStateNames[this.stateDropDown.value] + ", " + this.countryDropDown.value);
    },
    setCityRolloverBoxMessage: function(CityName, addMessage) {
        if(!this.hasBubbleOpen && !this.hasClickEvent)
        {
            var currMessage = $('GoogleMapMessageBox').getText();
            
            var sections = currMessage.split(",");
            if(sections.length == 4) {
                currMessage = sections[2] + ", " + sections[3];
            }
            
            if(addMessage) {
                currMessage = CityName + ", " + currMessage;
            }else {
                currMessage = this.arrayOfStateNames[this.stateDropDown.value] + ", " + this.countryDropDown.value;
            }
            this.setMessageAtTopOfMap(currMessage);
        }
    },
    GoogleMapSettings: {
        DefaultZoom: 3,
        CenterX: 39.16414104768742,
        CenterY: -96.064453125,
        CACenterX: 56.218923189166624,
        CACenterY: -96.064453125
    },
    PanToCountry: function(countryCode) {
        this.mooGooMapRef.clearAllMarkers();
        if(this.countryDropDown.value == "CA") {
            this.mooGooMapRef.centerMap(new GLatLng( this.GoogleMapSettings.CACenterX, this.GoogleMapSettings.CACenterY ), BabyNamespace.GoogleMapSettings.DefaultZoom);
        }else {
            this.mooGooMapRef.centerMap( new GLatLng( this.GoogleMapSettings.CenterX, this.GoogleMapSettings.CenterY ), BabyNamespace.GoogleMapSettings.DefaultZoom );
        }
        this.stateDropDown.addClass("highlite");
        
        this.stateDropDown.SetSelectedValue("n/a");
        this.cityDropDown.SetSelectedValue("n/a");
        this.cityDropDown.disabled = true;
        this.cityDropDown.removeClass("highlite");
    },
    StartOverButton: function() {
        var OnCountrySelectedCallback = function(response) {
            OnCountrySelectedResponse = Json.evaluate(this.stripDotNetJson(response));
            BabyNamespace.UpdateNamesList(HTMLFactory.GetNamesHTMLFromJson(OnCountrySelectedResponse.StateNameRankGirls, OnCountrySelectedResponse.StateNameRankBoys ));
            BabyNamespace.PanToCountry();
        }.bind(this);
        var myAjax = new Ajax(BabyNamespace.settings.baseAjaxURL + BabyNamespace.settings.GetRanksByCountry, {
            method: 'post',
            onComplete: OnCountrySelectedCallback
        });
        myAjax.request("countryCode=" + this.countryDropDown.value);   
        this.setMessageAtTopOfMap(this.countryDropDown.value);
    },
    SetUpStateNamesArray: function(statesArray) {
        
        this.arrayOfStateNames = new Object();
        for(var i=0;i<statesArray.length;i++) {
            this.arrayOfStateNames[statesArray[i].StateCode] = statesArray[i].StateName;
        }
        
    },
    
    plotInitalPoints: function(pointCollection) {
        if( pointCollection.length > 0 ) { 
            var item = pointCollection.pop();
            
            try {
                var marker;
                var addEvents = function() {
                    GEvent.addListener(marker, "click", function(address) {
                      var markerOnClickajaxCallback = function(response) {
		                    stateNameRankJson = Json.evaluate(this.stripDotNetJson(response));
		                    var InfoWindows = HTMLFactory.createGoogleMapPopUps({json: stateNameRankJson, stateTab: 'State', stateName: stateNameRankJson.State});
		                    marker.openInfoWindowTabsHtml([new GInfoWindowTab( InfoWindows[0].tab, InfoWindows[0].content )]);
                        }.bind(this);
    	                
                        var myAjax = new Ajax(BabyNamespace.settings.baseAjaxURL + BabyNamespace.settings.OnStateSelected, {
                            method: 'post',
                            onComplete: markerOnClickajaxCallback
                        });
    	                
                        myAjax.request("stateOrProvince=" + address);
                    }.bind(this, [item.stateCode]));
                    this.mooGooMapRef.addMarker(marker, item.stateCode);
                    moveOn();
                }.bind(this);
                
                var moveOn = function() {
                    if( pointCollection.length > 0 ) {
                        setTimeout( this.plotInitalPoints.bind( this, [ pointCollection ] ), 100 );
                    }
                }.bind(this);
                
                if(item.lat != '' && item.lat != null) {
                    
                    marker = new GMarker( new GLatLng( item.lat, item.lng ), this.mooGooMapRef.customIcon );
                    addEvents();
                }else {
                    state = item.address;
                    if(item.address == "Washington"){
                        state = item.stateCode;
                    }
                    if(item.address == "New York"){
                        state = (item.address + " State");
                    }
                    var toCode;
                    if(item.address == "Puerto Rico") {
                        toCode = item.address;
                    }else {
                       toCode = state + ", " + this.countryDropDown.value
                    }
                    //
                    this.mooGooMapRef.geocoder.getLatLng(toCode, function(point){
                        if(point != null) {
                            marker = new GMarker( point, this.mooGooMapRef.customIcon );
                            addEvents();
                            this.collectionOfStateLatsAndLongsToSave.push("state="+ item.stateCode+ "&countrycode=" + this.countryDropDown.value + "&lat=" + point.y + "&longitude=" + point.x);                            
                        }else {
                            moveOn();
                        }
                    }.bind(this));
                }
            } catch( e ) {
              
            }
        }
        if(pointCollection.length == 0) {
            
            this.saveStateLatsAndLongs();
            
        }
    },
    saveStateLatsAndLongs: function() {
        var saveUrl = this.collectionOfStateLatsAndLongsToSave.pop();
        if(this.collectionOfStateLatsAndLongsToSave.length > 0) {
            var myAjax = new Ajax(BabyNamespace.settings.baseAjaxURL + BabyNamespace.settings.SaveStateLatLong, {
                method: 'post',
                onComplete: function() {setTimeout( this.saveStateLatsAndLongs.bind(this), 50 );}.bind(this)
            });
            myAjax.request(saveUrl);
        }
    },
    
    initialize: function( ) {
        this.hasBubbleOpen = false;
        this.hasClickEvent = false;
        this.setUpStateDropDown();
        this.SetUpCountryDropDown();
        this.setUpCityDropDown();
    },
    UpdateNamesForHospitals: function(theHospitalId, theHospitalName, cityId, cityName) {
        var markerOnClickajaxCallback = function(response) {
            hospitalNameRankJson = Json.evaluate(this.stripDotNetJson(response));
            BabyNamespace.UpdateNamesList(HTMLFactory.GetNamesHTMLFromJson(hospitalNameRankJson.HospitalNameRankGirls, hospitalNameRankJson.HospitalNameRankBoys));
            this.setMessageAtTopOfMap(theHospitalName + ", " +cityName + ", " + this.arrayOfStateNames[this.currentState] + ", " + this.countryDropDown.value);
        }.bind(this);
        var myAjax = new Ajax(BabyNamespace.settings.baseAjaxURL + BabyNamespace.settings.OnHospitalSelected, {
            method: 'post',
            onComplete: markerOnClickajaxCallback
        });
        myAjax.request("hospitalId=" + theHospitalId + "&state=" + this.currentState + "&cityId=" + cityId + "&cityName=" + cityName + "&hospitalName=" + theHospitalName);   
    },
    CityClickEvent: function(marker, cityId, cityName) {
        this.hasClickEvent = true;
        this.cityDropDown = $(this.settings.cityDropDownId);
        this.cityDropDown.SetSelectedValue(cityId);
        this.setMessageAtTopOfMap(cityName + ", " + this.arrayOfStateNames[this.currentState] + ", " + this.countryDropDown.value);
        var markerOnClickajaxCallback = function(response) {
            cityNameRankJson = Json.evaluate(this.stripDotNetJson(response));
            //FIND
            BabyNamespace.UpdateNamesList(HTMLFactory.GetNamesHTMLFromJson(cityNameRankJson.CityNameRankGirls, cityNameRankJson.CityNameRankBoys));
            
            var InfoWindow = HTMLFactory.createGoogleMapPopUpsForHospital({json: cityNameRankJson, tab: 'Hospitals in ' + cityName});
            
            if(cityNameRankJson.Hospitals.length == 1) {
                this.setMessageAtTopOfMap(cityNameRankJson.Hospitals[0].Name + ", " + cityName + ", " + this.arrayOfStateNames[this.currentState] + ", " + this.countryDropDown.value);
            }
            
            marker.openInfoWindowTabsHtml([new GInfoWindowTab( InfoWindow.tab, InfoWindow.content)]);
            InfoWindow.selectBox.addEvent("change", function() {
                BabyNamespace.UpdateNamesForHospitals(this.options[this.selectedIndex].value, this.options[this.selectedIndex].getText(), cityId, cityName);
            });
        }.bind(this);
        var myAjax = new Ajax(BabyNamespace.settings.baseAjaxURL + BabyNamespace.settings.OnCitySelected, {
            method: 'post',
            onComplete: markerOnClickajaxCallback
        });
        myAjax.request("cityId=" +cityId + "&state=" + this.currentState + "&cityName=" + cityName);
    },
    plotCityPoints: function(citiesJson) {
        if( citiesJson.length > 0 ) { 
            var city = citiesJson.pop();
            
            try {
               var marker
               var moveOn = function() {
                   if( citiesJson.length > 0 ) {
                        setTimeout( this.plotCityPoints.bind( this, [ citiesJson ] ), 100 );
                   }
               }.bind(this);
               var addEvents = function() {
                    GEvent.addListener(marker, "click", function(cityId, cityName) { 
                        BabyNamespace.hasBubbleOpen = true;   
			            BabyNamespace.CityClickEvent(marker, cityId, cityName);
		            }.bind(this, [city.Id, city.Name]));//addListener
		            //FINDME
		            
		            
		            GEvent.addListener(marker, "infowindowopen", function() {  
			            BabyNamespace.hasBubbleOpen = true;
			            BabyNamespace.hasClickEvent = false;
		            });
		            GEvent.addListener(marker, "infowindowclose", function() {    
			            BabyNamespace.hasBubbleOpen = false;
			            //BabyNamespace.SetMessageToStateAndCountry();
		            });
		            
		            GEvent.addListener(marker, "mouseover", function(cityId, cityName) {    
			            BabyNamespace.setCityRolloverBoxMessage(cityName, true);
		            }.bind(this, [city.Id, city.Name]));
		            
		            GEvent.addListener(marker, "mouseout", function(cityId, cityName) {   
			            BabyNamespace.setCityRolloverBoxMessage(cityName, false);
		            }.bind(this, [city.Id, city.Name]));
		            
		            
                   this.mooGooMapRef.addMarker(marker, city.Name + ", " + city.StateOrProvince);
                   moveOn();
               }.bind(this);
               
               if(city.Latitude == "" || city.Latitude == null) {
                //console.log(city.Name + ", " + this.currentState);
                    this.mooGooMapRef.geocoder.getLatLng(city.Name + ", " + city.StateOrProvince, function(point){
                        if(point != null) {
                            var myAjax = new Ajax(BabyNamespace.settings.baseAjaxURL + BabyNamespace.settings.SaveCityLatLong, {
                                method: 'post',
                                onComplete: function() {}
                            });
                            
                            marker = new GMarker(  point, this.mooGooMapRef.customIcon );
                            addEvents();
                            myAjax.request("cityId="+ city.Id+ "&lat=" + point.y + "&longitude=" + point.x );
                        } else {
                            moveOn();
                        }
                    }.bind(this));//geocode
                }else {
                    marker = new GMarker( new GLatLng( city.Latitude, city.Longitude ), this.mooGooMapRef.customIcon );
                    addEvents();
                }
            }catch(e) {
            }  
        }
    },
    getAndSetCityPoints: function() {
        var citiesJson;
        var getAndSetCityPointsCallBack = function(response) {
            citiesJson = Json.evaluate(this.stripDotNetJson(response));
            
            this.cityDropDown.disabled = false;
            this.cityDropDown.setHTML("");
            this.cityDropDown.adopt(new Element("option", {'value': 'n/a', 'selected': 'selected'}).setText("Choose"));
            citiesJson.each(function(city) {
                var cityOption = new Element("option", {'value': city.Id}).setText(city.Name);
                if(city.Latitude != '' && city.Longitude != '' && city.Latitude != null && city.Longitude != null) {
                    cityOption.PointObj = {'Lat': city.Latitude, 'Long': city.Longitude};
                }
                this.cityDropDown.adopt(cityOption);
            }.bind(this));
            this.plotCityPoints(citiesJson);
        }.bind(this);
        var myAjax = new Ajax(BabyNamespace.settings.baseAjaxURL + BabyNamespace.settings.GetCityByState, {
            method: 'post',
            onComplete: getAndSetCityPointsCallBack
        } );
        myAjax.request('stateOrProvince='+ this.currentState);
    },
    setMessageAtTopOfMap: function(Message) {
        $('GoogleMapMessageBox').setText(Message);
    },
    
    setUpStateDropDown: function() {
        this.stateDropDown = $(this.settings.stateDropDownId);
        this.stateDropDown.addEvent("change", function() {
            var selectedState = this.stateDropDown.value;
            this.stateDropDown.removeClass("highlite");
            this.cityDropDown.addClass("highlite");
            var pointObj = eval('(' + $(this.stateDropDown.options[this.stateDropDown.selectedIndex]).getAttribute("rel") + ')');
            
            if(selectedState != "n/a") {
                this.currentState = selectedState;
                this.mooGooMapRef.clearAllMarkers();
                
                
                var state = this.currentState;
                if(state == "NY")
                {
                   state = "New York State"; 
                }
                if(state == "UT")
                {
                   state = "Utah"; 
                }
                
                var zoom = this.settings.stateZoomLevel;
                if(this.countryDropDown.value != "US") {
                    zoom = this.settings.caStateZoomLevel;
                }
                if(pointObj.lat != null && pointObj.lng != null && pointObj.lat != ''&& pointObj.lng != '') {
                    this.mooGooMapRef.centerMap(new GLatLng(pointObj.lat, pointObj.lng), zoom);
                    this.getAndSetCityPoints();
                }else {
                    this.mooGooMapRef.geocoder.getLatLng(state + ", " + this.countryDropDown.value, function(point){
                        this.mooGooMapRef.centerMap(point, zoom);
                        this.getAndSetCityPoints();
                    }.bind(this));
                }
                
                var OnStateSelectedAjaxCallback = function(response) {
                    var stateJson = Json.evaluate(BabyNamespace.stripDotNetJson(response));
                    BabyNamespace.UpdateNamesList(HTMLFactory.GetNamesHTMLFromJson(stateJson.StateNameRankGirls, stateJson.StateNameRankBoys));
                    BabyNamespace.setMessageAtTopOfMap( this.arrayOfStateNames[this.currentState] + ", " + this.countryDropDown.value );
                }.bind(this);
                
                var myAjax = new Ajax(BabyNamespace.settings.baseAjaxURL + BabyNamespace.settings.OnStateSelected, {
                    method: 'post',
                    onComplete: OnStateSelectedAjaxCallback
                });
                myAjax.request("stateOrProvince=" + this.currentState);
                
                
            }else {
                this.stateDropDown.addClass("highlite");
                this.cityDropDown.removeClass("highlite");
                this.cityDropDown.setHTML("");
                this.cityDropDown.adopt(new Element("option", {'value': 'n/a', 'selected': 'selected'}).setText("Choose"));
            }
            
            
            
            
        }.bind(this));
    },
    GetCountryNames: function() {
        var OnCountrySelectedCallback = function(response) {
            OnCountrySelectedResponse = Json.evaluate(this.stripDotNetJson(response));
            BabyNamespace.UpdateNamesList(HTMLFactory.GetNamesHTMLFromJson(OnCountrySelectedResponse.StateNameRankGirls, OnCountrySelectedResponse.StateNameRankBoys));
        }.bind(this);
        var myAjax = new Ajax(BabyNamespace.settings.baseAjaxURL + BabyNamespace.settings.GetRanksByCountry, {
            method: 'post',
            onComplete: OnCountrySelectedCallback
        });
        myAjax.request("countryCode=" + this.countryDropDown.value);
        this.setMessageAtTopOfMap(this.countryDropDown.value);
    },
    SetUpCountryDropDown: function() {
//        this.countryDropDown = $$(this.settings.countryDropDownCssSelector)[0];

//      02/11/2009: Remove the country drop down selector. If you want to add back the country drop down,
//                  comment the below line and uncomment the above line. Also uncomment the below event.
//                  Finally, set visible="true" in the .ascx file.

        this.countryDropDown = new CountryDropDownFix('US');
        this.setMessageAtTopOfMap(this.countryDropDown.value);
//        this.countryDropDown.addEvent('change', function() {
//            
//            var OnCountrySelectedCallback = function(response) {
//                OnCountrySelectedResponse = Json.evaluate(this.stripDotNetJson(response));
//                
//                this.stateDropDown = $(this.settings.stateDropDownId);
//                this.stateDropDown.setHTML("");
//                this.stateDropDown.adopt(new Element("option", {'value': 'n/a', 'selected': 'selected'}).setText("Choose"));
//                this.stateDropDown.addClass("highlite");
//                this.cityDropDown.removeClass("highlite");
//                
//                var States = new Array();
//                for(var i=0;i<OnCountrySelectedResponse.length;i++) {
//                    States.push({'StateName': OnCountrySelectedResponse[i].StateName, 'StateCode': OnCountrySelectedResponse[i].StateOrProvince, 'address': OnCountrySelectedResponse[i].StateOrProvince, 'lat': OnCountrySelectedResponse[i].Latitude, 'lng': OnCountrySelectedResponse[i].Longitude});
//                    this.stateDropDown.adopt(new Element("option", {'rel': '{\'lat\': ' + OnCountrySelectedResponse[i].Latitude + ', \'lng\': ' + OnCountrySelectedResponse[i].Longitude + '}' ,'value': OnCountrySelectedResponse[i].StateOrProvince}).setText(OnCountrySelectedResponse[i].StateOrProvince));
//                }
//                this.SetUpStateNamesArray(States);
//                this.PanToCountry();
//                this.GetCountryNames();
//                //this.plotInitalPoints(States);
//            }.bind(this);
//            var myAjax = new Ajax(BabyNamespace.settings.baseAjaxURL + BabyNamespace.settings.GetStateByCountry, {
//                method: 'post',
//                onComplete: OnCountrySelectedCallback
//            });
//            myAjax.request("countryCode=" + this.countryDropDown.value);   
//        }.bind(this));
    },
    setUpCityDropDown: function() {
        this.cityDropDown = $(this.settings.cityDropDownId);
        this.cityDropDown.disabled = true;
        this.cityDropDown.addEvent("change", function() {
            
            var selectedCity = this.cityDropDown.options[this.cityDropDown.selectedIndex].innerHTML;
            var selectedCityId = this.cityDropDown.value;
            if(selectedCityId != "n/a") {
                this.currentCity = selectedCity;
                this.currentCityId = selectedCityId;
                var marker = this.mooGooMapRef.getMarker(selectedCity + ", " + this.currentState);
                
                if(marker) {
                    BabyNamespace.CityClickEvent(marker, selectedCityId, selectedCity);
                }
                //find
            }
        }.bind(this));
        
    },
    UpdateNamesList: function(html) {
        var BabyNameList = $("BabyNameList");
        BabyNameList.setHTML("");
        BabyNameList.adopt(html);
    },
    stripDotNetJson: function(dirtyJsonString) {
        var dirtyJsonString = dirtyJsonString.split("string xmlns=\"http://tempuri.org/\">")[1];
        return dirtyJsonString = dirtyJsonString.split("</string>")[0];
    },
    settings: {
        country: ", US",
        baseAjaxURL: '/WebServices/BabyNamescapeService.asmx/',
        GetRanksByCountry: 'GetRanksByCountry',
        GetStateByCountry: 'GetStateByCountry',
        GetCityByState: 'GetCityByState',
        GetHospitalByCity: 'GetHospitalByCity',
        OnCitySelected: 'OnCitySelected',
        OnStateSelected: 'OnStateSelected',
        OnCountrySelected: 'OnCountrySelected',
        SaveStateLatLong: 'SaveStateLatLong',
        SaveCityLatLong: 'SaveCityLatLong',
        SaveHospitalLatLong: 'SaveHospitalLatLong',
        OnHospitalSelected: 'OnHospitalSelected',
        baseGetRankHTMLAjax: '/Wisdom/BabyNamescape/NamescapeAjax.aspx?RequestType=',
        stateDropDownId: 'view_map_state',
        cityDropDownId: 'view_map_city',
        countryDropDownCssSelector: 'select.CountryDropDown',
        countryZoomLevel: 3,
        stateZoomLevel: 6,
        caStateZoomLevel: 5,
        cityZoomLevel: 11
    }
}
