DealerShopsControl = {
	shop_map: null,
    directions: null,
	points: {},
	focus_coords: null,
	focus_zoom: 10,
	icon: null,
    action_queue: [], /* custom action after map fully loads */
    curr_marker: null,
	initMap: function() {
		if(DealerShopsControl.shop_map == null) {
			/* bind our key events to handle "enter" presses in search fields */
			$('.shops_content > input[name=location_field]')
			.add('.shops_content > input[name=dealer_field]')
			.bind('keyup', function(e) {
			   if(e.keyCode == 13) {
				   DealerShopsControl.initSearchCallback();
				   return false;
			   }
			   return true;
			});
			
			google.load("maps", "2", {callback: DealerShopsControl.initMapCallback});
		}
	},
	
	initMapCallback: function() {
		if (google.maps.BrowserIsCompatible()) {
			var ico = DealerShopsControl.icon = new google.maps.Icon();
			ico.image = 'images/shops/marker_icon.png';
			ico.iconSize = new google.maps.Size(21, 21);
			ico.iconAnchor = new google.maps.Point(10, 10);
			ico.infoWindowAnchor = new google.maps.Point(18, 3);
			ico.transparent = 'images/shops/marker_icon_transparent.png';

			DealerShopsControl.shop_map = new google.maps.Map2(document.getElementById ('publicmapview'));
			DealerShopsControl.shop_map.enableScrollWheelZoom();
			DealerShopsControl.shop_map.addControl(new google.maps.LargeMapControl());
			google.maps.Event.addListener(DealerShopsControl.shop_map, "click", DealerShopsControl.mapClickCallback);
			
            if(DealerShopsControl.action_queue.length) {
				for(ii=0, cnt=DealerShopsControl.action_queue.length;ii<cnt;++ii)
					DealerShopsControl.action_queue[ii]();
            }
            else
                DealerShopsControl.loadDefaultMapPoints();
            
            DealerShopsControl.initDirections();
		}
		else
			alert('Din browser er desværre inkomtitabel med Google Maps');
	},
    
    initDirections: function() {
        if(this.directions == null) {
            this.directions = new google.maps.Directions(
                this.shop_map,
                document.getElementById('map_directions')
            );
            
            google.maps.Event.addListener(this.directions, 'error', this.directionsErrorCallback);
            google.maps.Event.addListener(this.directions, 'addoverlay', this.directionsOverlayCallback);
        }
    },
	
	queueAction: function(func) {
		var ii = DealerShopsControl.action_queue.length;
		DealerShopsControl.action_queue[ii] = func;
	},
    
    resetMapState: function() {
        DealerShopsControl.shop_map.clearOverlays();
        DealerShopsControl.directions.clear();
        ClearFields.resetFields();
    },
	
	loadDefaultMapPoints: function() {
		DealerShopsControl.startLoader();
		$.getJSON('shops_frame.php', {get: 'dpoints'}, DealerShopsControl.placeMapPoints);
	},
	
	loadShopDetails: function(shop_id) {
		DealerShopsControl.startLoader();
		$.get('shops_frame.php',
            {sid:shop_id, get:'shopdata'},
            function(data, status) {
              DealerShopsControl.shopDetailsCallback(data, status, shop_id)
            });
	},
	
	loadShopSearch: function(location_str, dealer_str) {
		DealerShopsControl.startLoader();
		$.getJSON('shops_frame.php',
            {loc:location_str, dlr:dealer_str, get:'spoints'},
            function(data) {
                DealerShopsControl.resetMapState();
                DealerShopsControl.placeMapPoints(data);
                DealerShopsControl.openFocusedMarkerInfoWindow();
            });
	},
    
    loadShopIdSearch: function(dlr_id) {
		if(DealerShopsControl.shop_map == null) {
			DealerShopsControl.queueAction(function(){DealerShopsControl.loadShopIdSearch(dlr_id)});
			return;
		}
		
        DealerShopsControl.startLoader();
        $.getJSON('shops_frame.php',
            {id: dlr_id, get:'spointsid'},
            function(data) {
                if(data.dealer != 'undefined')
                    $('.shops_content > input[name=dealer_field]').val(data.dealer.company);
                DealerShopsControl.resetMapState();
                DealerShopsControl.placeMapPoints(data);
                DealerShopsControl.openFocusedMarkerInfoWindow();
            });
    },
	
	placeMapPoints: function(data) {
		if(typeof data.focus !== 'undefined') {
			DealerShopsControl.focus_coords = new google.maps.LatLng(data.focus.lat, data.focus.lng);
			if(typeof data.focus.zoom !== 'undefined')
				DealerShopsControl.focus_zoom = data.focus.zoom;
			DealerShopsControl.setMapFocus(DealerShopsControl.focus_coords, DealerShopsControl.focus_zoom);
		}
		
		for (var ii = 0, cnt = data.points.length; ii < cnt; ++ii) {
			var point = data.points[ii];
			DealerShopsControl.points[point.sid] = new google.maps.Marker(new google.maps.LatLng(point.lat, point.lng),
																		  {icon: DealerShopsControl.icon});
			DealerShopsControl.points[point.sid].shop = {'shop_id': point.sid};
			DealerShopsControl.shop_map.addOverlay(DealerShopsControl.points[point.sid]);
		}
		DealerShopsControl.stopLoader();
	},
    
    openFocusedMarkerInfoWindow: function() {
        for(key in DealerShopsControl.points) {
            var crd = DealerShopsControl.points[key].getLatLng();
            if(DealerShopsControl.focus_coords.lat() == crd.lat() &&
               DealerShopsControl.focus_coords.lng() == crd.lng()) {
                DealerShopsControl.mapClickCallback(DealerShopsControl.points[key]);
                break;
            }
        }
    },
    
    openDirections: function(elmt) {
        $(elmt).hide().next().fadeIn('fast');
    },
    
    closeDirections: function(elmt) {
        $(elmt).hide().prev().fadeIn('fast');
    },
    
    findDirections: function(sform) {
        if(DealerShopsControl.curr_marker !== null) {
            var coords = DealerShopsControl.curr_marker.getLatLng();
			var sstring = sform.elements.saddr.value.toLowerCase();
            $('#map_directions').html(''); //clear any possible error messages
			
			if(sstring.indexOf('danmark') == -1 && sstring.indexOf('denmark') == -1)
				sstring += ', Danmark';
			
            DealerShopsControl.directions.load('from: ' + sstring +
                                               ' to: ' + coords.lat() + ',' + coords.lng());
        }
        
        return false;
    },
	
	mapClickCallback: function(overlay, point) {
        if(typeof overlay != 'undefined' &&
           overlay != null &&
           typeof overlay.shop != 'undefined') {
            DealerShopsControl.curr_marker = overlay;
            
            if(typeof overlay.shop.info_bound == 'undefined') /* bind dealer info window if none exist yet */
                DealerShopsControl.loadShopDetails(overlay.shop.shop_id);
        }
	},
	
	shopDetailsCallback: function(data, status, shop_id) {
		var tabs = data.split('||');
		var iw_tabs = [new google.maps.InfoWindowTab('Generelt',tabs[0]),
					   new google.maps.InfoWindowTab('Åbningstider',tabs[1])];
		DealerShopsControl.points[shop_id].bindInfoWindowTabsHtml(iw_tabs, {maxWidth: 280});
		/* force open, since bind doesn't automatically show at first */
		DealerShopsControl.points[shop_id].openInfoWindowTabsHtml(iw_tabs, {maxWidth: 280});
		DealerShopsControl.points[shop_id].shop.info_bound = true;
		DealerShopsControl.stopLoader();
	},
    
    directionsOverlayCallback: function() {
        DealerShopsControl.scrollToElement($('#map_directions'), 140, true);
    },
    
    directionsErrorCallback: function() {
        var err_msg = '';
        if(DealerShopsControl.directions.getStatus().code == 602)
            err_msg = 'Kan desværre ikke finde startsstedet';
        else
            err_msg = 'Kan desværre ikke finde den bedste rute for turen..';
        
        $('#map_directions')
                .slideUp('fast')
                .html('<div class="route_error">' + err_msg +'</div>')
                .slideDown('fast', function() {
                    DealerShopsControl.scrollToElement($('#map_directions > .route_error'), 30)
                    }
                );
    },
	
	initSearchCallback: function() {
		DealerShopsControl.loadShopSearch(
			$('.shops_content > input[name=location_field]').val(),
			$('.shops_content > input[name=dealer_field]').val());
	},
    
    clearInput: function(elmt) {
        var old_name = elmt.name;
        elmt.name = elmt.name + '_' + DealerShopsControl.curr_marker.shop.shop_id;
        if(ClearFields.clearOnce(elmt)) //"enhance" the method since it only checks state by name
            $(elmt).css('color', '#333333');
        elmt.name = old_name;
    },
	
	setMapFocus: function(point, zoom) {
		if(typeof zoom != 'undefined')
			DealerShopsControl.shop_map.setCenter(point, zoom);
		else
			DealerShopsControl.shop_map.setCenter(point);
	},
    
    scrollToElement: function(elmt, offset, elmt_top) {
        if(typeof elmt_top == 'undefined')
            elmt_top = false;
        
        var wtop = $('html').scrollTop();
        var wheight = $('html').height();
        var wbtm = wtop + wheight;
        var etop = $(elmt).offset().top;
        var ebtm = etop + $(elmt).height();
        if(!elmt_top && wbtm < ebtm + offset)
            $('html').animate({scrollTop: ebtm - wheight + offset}, 400)
        else if(elmt_top && wbtm < etop + offset)
            $('html').animate({scrollTop: wtop + etop - wbtm + offset}, 400)
    },
	
	startLoader: function() {
		$('.shops_content > .loader').show();
	},
	
	stopLoader: function() {
		$('.shops_content > .loader').hide();
	}
}

/**** dealer-side functions ****/
var shop_map = null;
var shop_geocoder = null;
var shop_marker = null;

function initDealerMap() {
	if (google.maps.BrowserIsCompatible()) {
		shop_map = new google.maps.Map2 (document.getElementById ('mapview'));
		shop_map.enableScrollWheelZoom();
		shop_map.addControl (new google.maps.SmallZoomControl ());
		google.maps.Event.addListener (shop_map, "click", mapClickCallback );
		var coords = getShopCoords ();
		if (coords) {
			shop_map.setCenter(coords, 13);
			createShopMarker (coords);
		}
		else
			shop_map.setCenter(new google.maps.LatLng(55.788929, 10.7), 6); /* a general starting location of the map */
	}
	else
		setStatusText ('Din browser er desværre inkomtitabel med Google Maps');
}

function toggleMapsLocationBox () {
	var elmt = document.getElementById ('maps_popup');
	
	if (elmt.style.visibility == '')
		elmt.style.visibility = 'visible';
	else
		elmt.style.visibility = '';
	
	if (!shop_map) {
		google.load("maps", "2", {callback: initDealerMap});
	}
}

function createShopMarker (point) {
	shop_marker = new google.maps.Marker(point, {draggable: true});
	google.maps.Event.addListener (shop_marker, "dragend",
		function () {setShopCoords (this.getLatLng ())}
	);
	shop_map.addOverlay (shop_marker);
	setShopCoords (shop_marker.getLatLng ());
}

function mapClickCallback (overlay, point) {
	if (overlay == null) {
		if (!shop_marker) {
			createShopMarker (point);
		}
		else {
			shop_marker.setLatLng (point);
			setShopCoords (point);
		}
	}
	else {
		this.removeOverlay (overlay);
		shop_marker = null;
		clearShopCoords ();
	}
}

function locateAddress (addr) {
	setStatusText ('Søger...');
	if (!shop_geocoder) {
		shop_geocoder = new google.maps.ClientGeocoder ();
		shop_geocoder.setBaseCountryCode('dk');
	}
	shop_geocoder.getLatLng (addr, geoLocateCallback);
}

function geoLocateCallback (point) {
	if (point != null) {
		if (shop_marker)
			shop_marker.setLatLng (point);
		else {
			createShopMarker (point);
		}
		shop_map.setCenter (point, 13);
		setShopCoords (point);
		
		setStatusText ('Overensstemmende placering er fundet');
	}
	else
		setStatusText ('Ingen overensstemmende placering fundet');
}

function setStatusText (text) {
	$('#shop_status_field').text (text);
}

function setShopCoords (point) {
	$('#shop_coords')[0].value = point.toUrlValue ().replace (',', ';');
}

function clearShopCoords () {
	$('#shop_coords')[0].value = '';
}

function getShopCoords () {
	var coords = $('#shop_coords')[0].value.split(';');
	if (coords.length == 2) {
		return new google.maps.LatLng (coords[0], coords[1]);
	}
	else
		return null;
}

function confirmDelete () {
	return confirm ('Er du sikker på, at du ønsker at slette denne butik?');
}