﻿// Class MapLoader
BenefulMap.ResultsMapLoader = Class.extend({
	init: function() {
        this.mapState;
        this.getInitialMapState();
	},
	getMapState: function() {
	   return this.mapState;
	},
	setMapState: function(mapState) {
	   this.mapState = mapState;
	},
	getGeocoder: function() {
	   return this.geocoder;
	},
	getInitialMapState: function() {
        console.log("Getting initial map state from cookie or search...");
	    var self = this;
	    var mapState;
	    WagWorld.Web.AjaxUtility.SelectLocationCookie(function(result) {
	        var params = {
	        	key: result.value.Keyword,
	        	loc: result.value.Location,
	        	latitude: result.value.Latitude,
	        	longitude: result.value.Longitude
	        };
			
		    mapState = self.getMapStateFromCookie(params.latitude, params.longitude, params.key, params.loc);
            self.setMapState(mapState);
            self.triggerMapLoad();		   
		});
	},	
	getMapStateFromCookie: function(lat, lng, key, loc) {
	    var self = this;
		var mapState = new BenefulMap.MapState(lat, lng, key, loc, 1, 15, 1, [], 0, []);
		
	    console.debug('Current location: ' + loc);

        var keyword = $('#keyword-search').val();
		var location = $('#address-search').val();
        
        if(jQuery.url.param("keyword") || jQuery.url.param("search")) {
        	mapState.setDefaultView(false);
        }
        else if(keyword && keyword !== BenefulMap.Constants.SEARCH_KEYWORD_DEFAULT_VALUE) {
        	mapState.setDefaultView(false);
        }
        else if(location && location !== BenefulMap.Constants.SEARCH_LOCATION_DEFAULT_VALUE) {
        	mapState.setDefaultView(false);
        }
        else {
        	mapState.setDefaultView(true);
        }
		mapState.validQuery();
       
        return mapState;
	},	
	triggerMapLoad: function() {
	    var mapState = this.getMapState();
		mapState.setGoButtonClicked(true);
	    $(document).trigger("map.load", [mapState]);
	}
});