﻿// Class MapLoader

BenefulMap.ResultsMapLoader = Class.extend({
	init: function() {
        this.mapState;
        this.geocoder = new GClientGeocoder();
        
        this.getInitialMapState();
	},
	getMapState: function() {
	   return this.mapState;
	},
	setMapState: function(mapState) {
	   this.mapState = mapState;
	},
	getGeocoder: function() {
	   return this.geocoder;
	},
	getInitialMapState: function() {
        var idParam = jQuery.url.param("id");
        if (idParam) {
            this.getMapStateFromQueryString(idParam);
        } else {
            this.getMapStateFromCookieOrSearch();
        }
	},
	getMapStateFromQueryString: function(jsonData) {
	   	console.log("Getting initial map state from query string...");
    	var self = this;
    	WagWorld.Web.AjaxUtility.CleanseInitialQuerystring(jsonData, function(result) {
    		var data = result.value;
    		var mapState = new MapState(data.Latitude, data.Longitude, "", data.Page, data.Radius, data.SortBy, data.BusinessId, data.Category, 0, data.state, []);
    		var point = new GLatLng(data.Latitude, data.Longitude);
    		
    		self.setMapState(mapState);
    		self.geocodeInitialLocation(point);
    	});
	},
	getMapStateFromCookieOrSearch: function() {
	    var self = this;
	    var mapState;
	    WagWorld.Web.AjaxUtility.SelectLocationCookie( function(result) {
            //set up the map per the cookie --- This block is strictly to trap the back button
	        var loc = result.value.Location;
		    var latitude = result.value.Latitude;
		    var longitude = result.value.Longitude;

		    mapState = self.getMapStateFromCookie(latitude, longitude, loc);
            self.setMapState(mapState);
            self.triggerMapLoad();		   
		});
	},
	getMapStateFromCookie: function(lat, lng, loc) {
	    var cats = [1, 2, 3];
	    if (jQuery.url.param("categories")) {
            cats = JSON.parse(jQuery.url.param("categories"));
            $(document).trigger("search_bar.set_checkboxes", [cats]);
        }
        
	    var mapState = new BenefulMap.MapState(lat, lng, loc, 1, 15, 1, [], cats, 0, []);
        
        if (loc && lat != 0 && lng != 0) {
            mapState.validQuery();
            console.log("Valid Cookie data");
        } else if ( loc == "" || lat == 0 || lng == 0 ) {
            mapState.noCookieDetected();
            mapState.setLatitude(BenefulMap.Constants.CENTER_LAT);
            mapState.setLongitude(BenefulMap.Constants.CENTER_LNG);
            mapState.setLocation("the U.S.");
            if (jQuery.url.param("search")) {
            	mapState.setDefaultView(false);
            } else {
            	mapState.setDefaultView(true);
            }
			mapState.validQuery();
            console.log("No Cookie data detected");
			console.log("Showing initial 'entire US' state ");
        } else {
            mapState.inputError();
            console.log("Invalid data from cookie");
        }
        return mapState;
	},
	geocodeInitialLocation: function() {

		var geo = this.getGeocoder();
		var mapState = this.getMapState();
		var self = this;
		geo.getLocations(point, function(result) {
			if (result == null) {
				console.warn("Input error in geocoder data");
				mapState.inputError();
			} else {
				if (!mapState.isNoCookieDetected()) {
					mapState.validQuery();
				}
			}
			var loc = result.Placemark[0];
			var details = loc.AddressDetails.Country.AdministrativeArea;
			var city;
			var state;
			if (details.Locality) {
				city = details.Locality.LocalityName;
				state = details.AdministrativeAreaName;
				mapState.setLocation( city + ", " + state );
			} else {
				try {
					city = details.SubAdministrativeArea.Locality.LocalityName;
					state = details.AdministrativeAreaName;
					mapState.setLocation( city + ", " + state );
				}
				catch(error) {
					console.log(error);
					state = details.AdministrativeAreaName;
					mapState.setLocation( state + ", USA");
				}
			}
			self.setMapState(mapState);
			self.triggerMapLoad();
		});
	},
	triggerMapLoad: function() {
	    var mapState = this.getMapState();
		mapState.setGoButtonClicked(true);
	    $(document).trigger("map.load", [mapState]);
	}
});