var client_address =  window.location.search.split("=");
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."
	},
	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_sidebar');
		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);
	},
	clientDirections: function(){
		client_address = client_address[2].split('+');
		client_address = client_address.join(' ');
	},
	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');
		var dir_clear = document.createElement('a');
		$(dir_clear)
			.attr('href', '#')
			.attr('id', 'gmaps_directions_clear_button')
			.html('Clear Route')
			.click( ecarlist.map.clearDirections );
		$(dir_wrap).append(dir_clear);
		$(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.showDirections);
		GEvent.addListener(ecarlist.map.gdir, "error", ecarlist.map.errorDirections);
		if(client_address && (document.getElementById("saddr").value == "" || document.getElementById("saddr").value == " ")){
			var saddr = client_address;
		}else{
			var saddr = document.getElementById("saddr").value;
		}
		var daddr = document.getElementById("daddr").value;
		ecarlist.map.gdir.load("from: "+saddr+" to: "+daddr);	
	},
	showDirections: function(){
		$('#ec_gmap').css('width', ecarlist.map.width_dir + 'px');
		ecarlist.map.map.checkResize();
		$('#gmaps_directions_box_wrap').css('display', 'block');
	},
	errorDirections: function(){
		alert(ecarlist.map.gErrors[ecarlist.map.gErrorConstant[ecarlist.map.gdir.getStatus().code]]);
	},
	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);
		});
		GEvent.addListener(marker, "infowindowclose", function() {
			ecarlist.map.setView()
		});
		return marker;
	},
	createIcon: function(icon){
		icon.obj = new GIcon(G_DEFAULT_ICON);
		icon.obj.iconSize = new GSize(icon.width, icon.height);
		if(icon.y && icon.y != ""){
			icon.obj.sprite = {	image: icon.src,
													top: icon.y };
		}else{
			icon.obj.image = icon.src;
		}
		icon.obj.shadow = icon.shadow.src;
		icon.obj.shadowSize = new GSize(icon.shadow.width, icon.shadow.height);
		icon.obj.iconAnchor = new GPoint(icon.iconAnchor.x, icon.iconAnchor.y);
		icon.obj.infoWindowAnchor = new GPoint(icon.infoWindowAnchor.x, icon.infoWindowAnchor.y);
		icon.obj.transparent = icon.transparent;
		icon.obj.printImage = icon.printImage;
	//	icon.obj.imageMap = 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);
				try{
					ecarlist.map.map.addOverlay(ecarlist.map.dealers[d].marker);
				}catch(e){}
			}
		}
		//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);
		}			
	  if(typeof(client_address) !== 'undefined' && typeof(client_address[2]) !== 'undefined'){
	  	ecarlist.map.clientDirections();
		  ecarlist.map.getDirections();
	  }		
	}
};		


