if(typeof(ecarlist) === 'undefined'){ ecarlist = {}; }
ecarlist.map = {
	dealers: { },
	bounds: new GLatLngBounds(),
	gdir: '',
	current_dealer: '',
	gErrorConstant: {
		'200': 'G_GEO_SUCCESS',
		'601': 'G_GEO_MISSING_ADDRESS',
		'602': 'G_GEO_UNKNOWN_ADDRESS',
		'603': 'G_GEO_UNAVAILABLE_ADDRESS',
		'610': 'G_GEO_BAD_KEY',
		'620': 'G_GEO_TOO_MANY_QUERIES',
		'500': 'G_GEO_SERVER_ERROR',
		'400': 'G_GEO_BAD_REQUEST',
		'601': 'G_GEO_MISSING_QUERY',
		'604': 'G_GEO_UNKNOWN_DIRECTIONS'
	},
	gErrors: {
		'G_GEO_SUCCESS' : "Success",
		'G_GEO_MISSING_ADDRESS' : "Missing Address: The address was either missing or had no value.",
		'G_GEO_UNKNOWN_ADDRESS' : "Unknown Address:  No corresponding geographic location could be found for the specified address.",
		'G_GEO_UNAVAILABLE_ADDRESS' : "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.",
		'G_GEO_BAD_KEY' : "Bad Key: The API key is either invalid or does not match the domain for which it was given",
		'G_GEO_TOO_MANY_QUERIES' : "Too Many Queries: The daily geocoding quota for this site has been exceeded.",
		'G_GEO_SERVER_ERROR' : "Server error: The geocoding request could not be successfully processed.",
		'G_GEO_BAD_REQUEST' : "A directions request could not be successfully parsed.",
		'G_GEO_MISSING_QUERY' : "No query was specified in the input.",
		'G_GEO_UNKNOWN_DIRECTIONS' : "The GDirections object could not compute directions between the points."
	},
	propertyDefined: function(ele){
		if(ele && ele.length > 0 && ele != 0 && typeof(ele) != 'undefined'){
			return ele;
		}
	},
	coordsDefined: function(x, y, obj){
		if( (x && x != '' && typeof(x) != 'undefined') && (y && y != '' && typeof(y) != 'undefined') ){
			return new obj(x,y);
		} 
	},
	sidebarLink: function(d){
		ecarlist.map.current_dealer = d;
		GEvent.trigger(ecarlist.map.dealers[d].marker, "click");
	},
	sidebarList: function(){
		var sidebar = document.createElement('div');
		$(sidebar).attr('id', 'gmap_header');
		var sidebar_ul = document.createElement('ul');
		$(sidebar_ul).attr('id', 'map_sidebar_list');
		$(sidebar).append(sidebar_ul);
		for(d in ecarlist.map.dealers){
			var sidebar_li = document.createElement('li');
			$(sidebar_li).attr('id', 'sidebar_link_' + d);
			var sidebar_link = document.createElement('a');
			$(sidebar_link).attr('href', '#' + ecarlist.map.dealers[d].dealer_name)
				.attr('id', 'link_' + d)
				.html(ecarlist.map.dealers[d].dealer_name);
			$(sidebar_li).append(sidebar_link);
			$(sidebar_ul).append(sidebar_li);
		}
		$(sidebar).find('a').bind('click', function(){
			var d = $(this).attr('id').split('_')[1];
			ecarlist.map.sidebarLink(d);
			return false;
		});
		$('#gmap_sidebar').remove();
		$('#ec_gmap').before(sidebar);
	},
	sidebarDirections: function(d){
		var header = document.createElement('div');
		$(header).attr('id', 'gmap_header');
		// ### top div
		var dir_top = document.createElement('div');
		$(dir_top).attr('id', 'gmap_directions_input');
		// ### form element
		var dir_form = document.createElement('form');
		$(dir_form).attr('id', 'gmap_directions_form')
			.attr('action', 'javascript: ecarlist.map.getDirections()');
		$(dir_top).append(dir_form);
		// ### from field
		var from_div = document.createElement('div');
		$(from_div).attr('id', 'gmap_directions_from');
		var from_label = document.createElement('label');
		$(from_label).attr('id', 'gmap_directions_from_label')
			.html('Start Address:');
		var from_input = document.createElement('input');
		$(from_input).attr('id', 'saddr')
			.attr('name', 'saddr')
			.attr('type', 'text');
		$(from_div).append(from_label)
			.append(from_input);
		$(dir_form).append(from_div);
		// ### to information
		var to_div = document.createElement('div');
		$(to_div).attr('id', 'gmap_directions_to');
		var to_label = document.createElement('p');
		$(to_label).attr('id', 'gmap_directions_to_label')
			.html('End:');
		var to_input = document.createElement('p');
		$(to_input).attr('id', 'gmap_directions_to_input')
			.html(ecarlist.map.dealers[d].dealer_name + '<br/>' + ecarlist.map.dealers[d].address + '<br/>' + ecarlist.map.dealers[d].city + ', ' + ecarlist.map.dealers[d].state + ' ' + ecarlist.map.dealers[d].zip_code);
		$(to_div).append(to_label)
			.append(to_input);
		$(dir_form).append(to_div);
		// ### submit
		var inputHidden = document.createElement('input');
		$(inputHidden).attr('type', 'hidden')
			.attr('name', 'daddr')
			.attr('id', 'daddr')
			.attr('value', ecarlist.map.dealers[d].address + ', ' + ecarlist.map.dealers[d].city + ', ' + ecarlist.map.dealers[d].state + ' ' + ecarlist.map.dealers[d].zip_code);
		$(dir_form).append(inputHidden);
		var dir_submit_div = document.createElement('div');
		$(dir_submit_div).attr('id', 'gmap_directions_submit');
		var dir_submit = document.createElement('input');
		$(dir_submit).attr('type', 'submit')
			.attr('value', 'Get Directions')
			.attr('id', 'gmaps_directions_submit_button');
		$(dir_submit_div).append(dir_submit);
		$(dir_form).append(dir_submit_div);
		// ### append top
		$(header).append(dir_top);
		// append div to page
		$('#gmap_header').remove();
		$('#ec_gmap_wrap').before(header);
	},
	getDirections: function(){
		ecarlist.map.clearRoute();
		var dir_wrap = document.createElement('div');
		$(dir_wrap).attr('id', 'gmaps_directions_box_wrap')
			.css({ height: ecarlist.map.height + 'px', display: 'none' });
		var dir_box = document.createElement('div');
		$(dir_box).attr('id', 'gmaps_directions_box');
		$(dir_wrap).append(dir_box);
		$('#ec_gmap_wrap').append(dir_wrap);
		ecarlist.map.gdir=new GDirections(ecarlist.map.map, document.getElementById("gmaps_directions_box"));
		GEvent.addListener(ecarlist.map.gdir, "load", ecarlist.map.buildDirections);
		GEvent.addListener(ecarlist.map.gdir, "error", ecarlist.map.errorDirections);
		var saddr = document.getElementById("saddr").value;
		var daddr = document.getElementById("daddr").value;
		ecarlist.map.gdir.load("from: "+saddr+" to: "+daddr);	
	},
	buildDirections: function(){
		var dir_print = document.createElement('a');
		$(dir_print).attr('id','gmaps_directions_print')
			.attr('href', '#')
			.html('Print Directions')
			.click( function(){ window.print() })
		var dir_clear = document.createElement('a');
		$(dir_clear)
			.attr('href', '#')
			.attr('id', 'gmaps_directions_clear_button')
			.html('Clear Route')
			.click( ecarlist.map.clearDirections );
		$('#gmaps_directions_box_wrap')
			.append(dir_clear)
			.append(dir_print);
		ecarlist.map.displayDirections();
	},
	displayDirections: function(){
		$('#gmaps_directions_box_wrap')
			.css('display', 'block');
		// resize map and elements
		$('#ec_gmap').css('width', ecarlist.map.width_dir + 'px');
		ecarlist.map.map.checkResize();
	},
	errorDirections: function(){
		if( ecarlist.map.gdir.getStatus().code == 602 ){
			ecarlist.map.errorAlternateStart();
		}else{
			alert(ecarlist.map.gErrors[ecarlist.map.gErrorConstant[ecarlist.map.gdir.getStatus().code]]);
		}
	},
	errorAlternateStart: function(){
		var saddr = document.getElementById("saddr").value;
		var geoCoder = new GClientGeocoder();
		geoCoder.getLocations(saddr, function(result){
			var gmaps_didYouMean = document.createElement('div');
			$(gmaps_didYouMean).attr('id', 'gmaps_didYouMean');
			var gmaps_dym_head = document.createElement('h5');
			$(gmaps_dym_head).html("Did you mean:");
			var gmaps_dym_list = document.createElement('ul');
			$(gmaps_dym_list).attr('id', 'gmaps_dym_list');
			for( var i = 0; i < result.Placemark.length; i++ ){
				var addr = result.Placemark[i].address;
				var gmaps_dym_list_item = document.createElement('li');
				var gmaps_dym_a = document.createElement('a');
				$(gmaps_dym_a).attr('href', '#')
					.click( function() { ecarlist.map.showAlternateStartDirections(this); return false; })
					.html(addr);
				$(gmaps_dym_list_item).append(gmaps_dym_a);
				$(gmaps_dym_list).append(gmaps_dym_list_item);
			}
			$(gmaps_didYouMean).append(gmaps_dym_head)
				.append(gmaps_dym_list);
			$('#gmaps_directions_box')
				.append(gmaps_didYouMean);
			ecarlist.map.displayDirections();
		});
	},
	showAlternateStartDirections: function(ele){
		$('#saddr').attr('value', $(ele).html());
		ecarlist.map.getDirections();
	},
	clearDirections: function(){
		ecarlist.map.clearRoute();
		ecarlist.map.sidebarLink(ecarlist.map.current_dealer);
	},
	clearRoute: function(){
		if( ecarlist.map.gdir == '' ) { return; }
		ecarlist.map.gdir.clear();
		$('#gmaps_directions_box_wrap').remove();
		$('#ec_gmap').css('width', ecarlist.map.width + 'px');
		ecarlist.map.map.checkResize();
	},
	createMarker: function(point, icon, html, dealer){
		var marker = new GMarker(point, icon);
		GEvent.addListener(marker, "click", function() {
				ecarlist.map.clearRoute();
				marker.openInfoWindowHtml(html);
				ecarlist.map.setDealerView(point);
				ecarlist.map.sidebarDirections(dealer);
		});
		return marker;
	},
	createIcon: function(icon){
		icon.obj = new GIcon(G_DEFAULT_ICON);
		icon.obj.iconSize = ecarlist.map.coordsDefined(icon.width, icon.height, GSize);
		if(icon.y && icon.y != ""){
			icon.obj.sprite = {	image: icon.src,
													top: icon.y };
		}else{
			icon.obj.image = icon.src;
		}
		icon.obj.shadow = ecarlist.map.propertyDefined(icon.shadow.src);
		icon.obj.shadowSize = ecarlist.map.coordsDefined(icon.shadow.width, icon.shadow.height, GSize);
		icon.obj.iconAnchor = ecarlist.map.coordsDefined(icon.iconAnchor.x, icon.iconAnchor.y, GPoint);
		icon.obj.infoWindowAnchor = new GPoint(icon.infoWindowAnchor.x, icon.infoWindowAnchor.y);
		icon.obj.transparent = ecarlist.map.propertyDefined(icon.transparent);
		icon.obj.printImage = ecarlist.map.coordsDefined(icon.printImage);
		icon.obj.imageMap = ecarlist.map.coordsDefined(icon.imageMap);
	},
	setView: function(){
		ecarlist.map.map.setCenter(ecarlist.map.bounds.getCenter());
		ecarlist.map.map.setZoom(ecarlist.map.map.getBoundsZoomLevel(ecarlist.map.bounds));
	},
	setDealerView: function(point){
			ecarlist.map.map.setZoom(ecarlist.map.initial_zoom);
			ecarlist.map.map.setCenter(point);
	},
	loadMap: function(){
		if (GBrowserIsCompatible()) {
			ecarlist.map.map = new GMap2(document.getElementById("ec_gmap"), { size: new GSize(ecarlist.map.width,ecarlist.map.height) });
			ecarlist.map.map.addControl(new GLargeMapControl());
			ecarlist.map.map.setCenter(new GLatLng(0,0),0);
		}
		//create markers
		for(d in ecarlist.map.dealers){
			ecarlist.map.createIcon(ecarlist.map.dealers[d].icon);
			ecarlist.map.dealers[d].geo = new GLatLng(ecarlist.map.dealers[d].y, ecarlist.map.dealers[d].x);
			if( ecarlist.map.dealers[d].geo != '' ){
				var html = ecarlist.map.dealers[d].html;
				if(!(html) || html == ''){
					html = '<strong>' + ecarlist.map.dealers[d].dealer_name + "</strong><br />" + ecarlist.map.dealers[d].address + "<br />" + ecarlist.map.dealers[d].city + ", " + ecarlist.map.dealers[d].state + " " + ecarlist.map.dealers[d].zip_code;
				}
				//build and set markers
				ecarlist.map.bounds.extend(ecarlist.map.dealers[d].geo);
				ecarlist.map.dealers[d].marker = ecarlist.map.createMarker(ecarlist.map.dealers[d].geo, ecarlist.map.dealers[d].icon.obj, html, d);
				ecarlist.map.map.addOverlay(ecarlist.map.dealers[d].marker);
			}
		}
		//set zoom and center
		if( typeof(ecarlist.map.initial_dealer) === 'undefined' ){
			ecarlist.map.setView();
			ecarlist.map.sidebarList();
		} else {
			ecarlist.map.sidebarLink(ecarlist.map.initial_dealer);
			ecarlist.map.sidebarDirections(ecarlist.map.initial_dealer);
		}
	}
};
