var markerCnt;
var map;
var poly;
var directions;
var directionsPanel;
var gDirections;
var centerLatitude = 28.798495;
var centerLongitude = -96.996994; 
var startZoom = 5;
var bounds = new GLatLngBounds();
var start_set = false;
var start_coordinates;
var pointData = [];
var isIE = document.all;

var new_window;

var baseIcon = new GIcon();
baseIcon.iconSize=new GSize(20,30);
baseIcon.shadowSize=new GSize(41,30);
baseIcon.iconAnchor=new GPoint(10,15);
baseIcon.infoWindowAnchor=new GPoint(10,15);
          
var auctions = new GIcon(baseIcon, "http://media.crossroadstreasures.com/images/icon_map_pin_sign_green.png", null, "http://media.crossroadstreasures.com/images/icon_map_pin_sign_shadow.png");
var garagesales = new GIcon(baseIcon, "http://media.crossroadstreasures.com/images/icon_map_pin_sign_blue.png", null, "http://media.crossroadstreasures.com/images/icon_map_pin_sign_shadow.png");
var estatesales = new GIcon(baseIcon, "http://media.crossroadstreasures.com/images/icon_map_pin_sign_red.png", null, "http://media.crossroadstreasures.com/images/icon_map_pin_sign_shadow.png");
var startpoint = new GIcon(baseIcon, "http://media.crossroadstreasures.com/images/icon_map_pin_sign_start.png", null, "http://media.crossroadstreasures.com/images/icon_map_pin_sign_shadow.png");


var icon = [];
icon = new GIcon();
icon.image="http://media.crossroadstreasures.com/images/icon10.png";
icon.shadow = "http://media.crossroadstreasures.com/images/icon10s.png";
icon.iconSize = new GSize(32,32);
icon.shadowSize = new GSize(59,32);
icon.iconAnchor = new GPoint(16,32);
icon.infoWindowAnchor = new GPoint(16,32);


var gDirections=new GDirections(null, document.getElementById("route-directions"));
var deselectCurrent = function() {};

// ====== Array for decoding the failure codes ======
var reasons=[];
reasons[G_GEO_SUCCESS]            = "Success";
//reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
//reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
reasons[G_GEO_UNKNOWN_DIRECTIONS] = "We could not compute directions between the points.";

function changeBodyClass(from, to) {
	document.body.className = document.body.className.replace(from, to);
	return false;
}

function initializePoint(pointData) {
	if(pointData.latitude == 0) { return; }
	var visible = false;
	var point = new GLatLng(pointData.latitude, pointData.longitude);
   	//var point = new GPoint(pointData.longitude, pointData.latitude);
//	var marker = new GMarker(point,icon);

	if(pointData.icon == 'garage-sales') {
		var marker = new GMarker(point, {icon:garagesales,title:pointData.address});
	} else if(pointData.icon == 'auctions') {
		var marker = new GMarker(point, {icon:auctions,title:pointData.address});
	} else if(pointData.icon == 'estate-sales') {
		var marker = new GMarker(point, {icon:estatesales,title:pointData.address});
	} else {
		var marker = new GMarker(point, {icon:startpoint,title:pointData.address});
	}

	var listItem = document.createElement('li');
	listItem.id = 'sale-' + pointData.aid;
	var listItemLink = listItem.appendChild(document.createElement('a'));
	listItemLink.href = 'javascript:void(0);';
	
	listItemLink.innerHTML = '<b>' + pointData.address + '</b><br /><span class="listCity">' + pointData.city + ', ' + pointData.state + ' ' + pointData.zip_code + '<br /><i>' + pointData.body.substr(0,50) + '</i></span>';
	
	var infoUrl = '/detail/' + pointData.aid;
	
	var html = '<div id="infoWindow">' + 
		'<div class="infoDetail">' +
		'<img style="float:left;margin-right:5px;" src="'+ media_url +'images/sales_icons/'+ pointData.icon +'.png" width="35" height="35" />' +
		'<span class="title">'+ pointData.address +'</span><br />' +
		pointData.city + ', ' + pointData.state + ' ' + pointData.zip_code +
		'</div>' +
		'<div class="infoDetail" alt="' + pointData.body + '">' + pointData.body.substr(0,75) + '...</div>' +
		'<div id="infoWindowMenu" style="width:240px; text-align:right; padding: 5px 0px 5px 0px;">' +
		'<a style="float:left;" href="javascript:void(0);" onclick="addRoutePoint(\'' + pointData.aid + '\',\'' + pointData.address + '\',\'' + pointData.city + '\',\'' + pointData.state + '\',\'' + pointData.zip_code + '\',\'' + pointData.latitude + '\',\'' + pointData.longitude + '\');" title="add to trip planner">+ trip planner</a>' +
		'<a style="float:right;" href="javascript:void(0);" onclick="map.getInfoWindow().maximize();" title="expand window">more info &raquo;</a>' +
		'<br style="clear:both;" />' +
		'</div>' +
		'</div>';
    
	markerCnt += 1;

/*
	var focusPoint = function() {
		deselectCurrent();
		listItem.className = 'current';
		deselectCurrent = function() { listItem.className = ''; }
		marker.openInfoWindowHtml(html, {maxUrl:infoUrl});
		map.panTo(point);
		return false;
	}
*/

	// ADDED ON 3/16/08 BY TJO
	// NEW METHOD OF HANDELING MAX WINDOWS
	var focusPoint = function() {
		var maxContentDiv = document.createElement('div');
		maxContentDiv.innerHTML = 'Loading...';
		
		deselectCurrent();
		listItem.className = 'current';
		deselectCurrent = function() { listItem.className = ''; }
		
		marker.openInfoWindowHtml(html,
			{maxContent: maxContentDiv, 
			maxTitle: pointData.address});
			map.panTo(point);
		
		var iw = map.getInfoWindow();
		GEvent.addListener(iw, "maximizeclick", function() {
			GDownloadUrl(infoUrl, function(data) {
				maxContentDiv.innerHTML = data;
			});
		});
		return false;
	}

	GEvent.addListener(marker, 'click', focusPoint);
	listItemLink.onclick = focusPoint;

	pointData.show = function() {
		if (!visible) {
			document.getElementById('sidebar-list').appendChild(listItem);
			map.addOverlay(marker);
			bounds.extend(point);
			visible = true;
	        }
	}
	pointData.hide = function() {
		if (visible) {
			document.getElementById('sidebar-list').removeChild(listItem);
			map.removeOverlay(marker);
			visible = false;
		}
	}
	pointData.show();
}

function initializeSortTab(type) {
	var listItem = document.createElement('li');
	var listItemLink = listItem.appendChild(document.createElement('a'));
	listItemLink.href = "javascript:void(0);";
	listItemLink.title = "show " + type;
	switch(type){
	case 'Auctions':
		var iconcolor='green';
		break;
	case 'Garage Sales':
		var iconcolor='blue';
		break;
	case 'Estate Sales':
		var iconcolor='red';
		break;
	}
	if(iconcolor){
		html = '<img src="http://media.crossroadstreasures.com/images/icon_legend_sign_' + iconcolor + '.png" width="16" height="12" hspace=2 align="absmiddle" border="0" />&nbsp;' + type;
	} else {
		html = type;
	}
	listItemLink.innerHTML = html;
	listItemLink.onclick = function() {
		changeBodyClass('standby', 'loading');
		clearRoutes();
		markerCnt = 0;
		for(id in markers) {
        		if (markers[id].category == type || 'All' == type) {
				markers[id].show();
				markerCnt += 1;
			} else {
				markers[id].hide();
			}
		}
		var temp = document.getElementById('results').innerHTML;
		var spot = temp.indexOf(' ');
		temp = markerCnt + temp.substr(spot);
		document.getElementById('results').innerHTML = temp;
		changeBodyClass('loading', 'standby');
		centerMap();
		return false;
	}
	document.getElementById('filters').appendChild(listItem);
}

function enterStartAddress(choice) {
	switch(choice) {
	case 'no':
		document.getElementById('message').style.visibility = 'hidden';
		start_set = true;
		return;
		break;
	case 'yes':
		var messageHTML = document.getElementById('message2').innerHTML;
		var msg_box = document.getElementById('message')
		msg_box.innerHTML = messageHTML;
		break;
	}
}

function addRoutePoint(id,address,city,state,zip,lat,lon) {
	var dupCheck = document.getElementById("item"+id);
	if(dupCheck){
		alert('This address is already in the list');
		return false;
	}	
	var routeListItem = document.createElement('li');
	routeListItem.id = 'item' + id;
	routeListItem.className = 'sortableitem';
	
	routeListItem.innerHTML = '<span style="text-transform:uppercase;">' + address + ', ' + city + ', ' + state + ' ' + zip + '</span>'
		+ '&nbsp;<span>&nbsp;<a href="javascript:void(0);" onclick="remRoutes(\'' + routeListItem.id + '\');"><img src="http://media.crossroadstreasures.com/images/iw_close.gif" height="12" width="12" alt="close" border="0" /></a>&nbsp;</span>'
		+ '<span class="noShow">' + address + ', ' + city + ', ' + state + ' ' + zip + '@' + lat + ',' + lon + '</span>';
	
	document.getElementById('route-list').appendChild(routeListItem);
	
	changeBodyClass('sidebar-right', 'nosidebar');
	
	map.closeInfoWindow();
	$("#route-list").sortableRefresh();
	directions.clear();
	getRoutes(); 
}	

function remRoutes(id) {
	var element = document.getElementById("route-list");
	var list = document.getElementById(id); 
	var removeNode = element.removeChild(list);
	map.closeInfoWindow();
	getRoutes();
}

function clearRoutes() {
	var element = document.getElementById("route-list");
	while (element.firstChild) { element.removeChild(element.firstChild); }
	map.closeInfoWindow();
	//directions.clear();
	getRoutes();
}

// ADDED ON 3/16/08 BY TJO
// NEW FUNCTION TO HANDLE ROUTING
function getRoutes() {
	var routeList = document.getElementById("route-list");
	var myPoints = new Array();
	var startingPoint = document.getElementById("routeStartPoint").innerHTML;
	if(startingPoint) myPoints.push(startingPoint);
	map.closeInfoWindow();
	if (routeList.hasChildNodes()) {
		var children = routeList.childNodes;
		for (var i = 0; i < children.length; i++) {
			myPoints.push(children[i].lastChild.innerHTML);
		};
	};
	setTimeout(function() {
		directions.loadFromWaypoints(myPoints,{preserveViewport:true,getPolyline:true,getSteps:true,locale:"en_US"});
	},500);
	printRoute(myPoints);
	//centerMap();
}

// ADDED ON 3/28/08 BY TJO
// NEW FUNCTION TO HANDLE ROUTE PRINTING
function printRoute(myPoints) {
	var theRouteLink = document.getElementById('printRoute');
	var myRoute = '';
	for (var i = 0; i < myPoints.length; i++) {
		if(i > 0)
			myRoute = myRoute + '+to:+' + myPoints[i];
		else
			myRoute = myRoute + 'http://maps.google.com/maps?f=q&hl=en&geocode=&q=from:+' + myPoints[i];
	};
	myRoute = myRoute + '&ie=UTF8&z=13&om=1&pw=2';
	theRouteLink.href = 'javascript:void(0)';
	theRouteLink.innerHTML = 'print';
	theRouteLink.onclick = function() {
		if(myPoints.length != 0) {
			window.open(myRoute,'RouteList','width=800,height=500,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
		}
	}
}

function addRouteStartingPoint(lat,lon,address) {
	var innerHTML = address + '@' + lat + ',' + lon;
	document.getElementById("startingPoint").value = address;
	document.getElementById("routeStartPoint").innerHTML = innerHTML;
	getRoutes();
}

GEvent.addListener(gDirections,"error", function() {
	var code = gDirections.getStatus().code;
	var reason="Code " + code;
	if (reasons[code]) {
		reason = "Code "+code +" : "+reasons[code]
	} 
	// alert("Failed to obtain directions, "+reason);
});

GEvent.addListener(gDirections, "load", function() {
	if (poly) map.removeOverlay(poly);
	poly = gDirections.getPolyline();
	map.addOverlay(poly);
	setTimeout('customPanel(map,"map",gDirections,document.getElementById("route-directions"))', 1);
});
     
GEvent.addListener(gDirections, "clear", function() {
	gDirections.clear();
	document.getElementById("route-directions").innerHTML = '';
});

 // ============ custom direction panel ===============
function customPanel(map,mapname,dirn,div) {
	var html = "";

	// ===== local functions =====

	// === waypoint banner ===
	function waypoint(point, type, address) {
		var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
		html += '<table style="border: 1px solid silver; margin: 10px 0px; background-color: rgb(238, 238, 238); border-collapse: collapse; color: rgb(0, 0, 0);">';
		html += '  <tr style="cursor: pointer;" onclick='+target+'>';
		html += '    <td style="padding: 4px 15px 0px 5px; vertical-align: middle; width: 20px;">';
		html += '      <img src="http://www.google.com/intl/en_ALL/mapfiles/icon-dd-' +type+ '-trans.png">'
		html += '    </td>';
		html += '    <td style="vertical-align: middle; width: 100%;">';
		html +=        address;
		html += '    </td>';
		html += '  </tr>';
		html += '</table>';
	}

	// === route distance ===
	function routeDistance(dist) {
		html += '<div style="text-align:right;padding-bottom:0.3em;">' + dist + '</div>';
	}      

	// === step detail ===
	function detail(point, num, description, dist) {
		var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
		html += '<table style="margin: 0px; padding: 0px; border-collapse: collapse;">';
		html += '  <tr style="cursor: pointer;" onclick='+target+'>';
		html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; text-align: right;">';
		html += '      <a href="javascript:void(0)"> '+num+'. </a>';
		html += '    </td>';
		html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; width: 100%;">';
		html +=        description;
		html += '    </td>';
		html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: right;">';
		html +=        dist;
		html += '    </td>';
		html += '  </tr>';
		html += '</table>';
	}

	// === Copyright tag ===
	function copyright(text) {
		html += '<div style="font-size: 0.86em;">' + text + "</div>";
	}


	// === read through the GRoutes and GSteps ===

	for (var i=0; i<dirn.getNumRoutes(); i++) {
		if (i==0) {
			var type="play";
		} else {
			var type="pause";
		}
		var route = dirn.getRoute(i);
		var geocode = route.getStartGeocode();
		var point = route.getStep(0).getLatLng();
		// === Waypoint at the start of each GRoute
		waypoint(point, type, geocode.address);
		routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");

		for (var j=0; j<route.getNumSteps(); j++) {
			var step = route.getStep(j);
			// === detail lines for each step ===
			detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html);
		 }
	}

	// === the final destination waypoint ===   
	var geocode = route.getEndGeocode();
	var point = route.getEndLatLng();
	waypoint(point, "stop", geocode.address);
             
	// === the copyright text ===
	copyright(dirn.getCopyrightsHtml());

	// === drop the whole thing into the target div
	div.innerHTML = html;

} 
// ============ end of customPanel function ===========
   
// ====== Create a Client Geocoder ======
var geo = new GClientGeocoder(new GGeocodeCache()); 

      
function getAddress() {
	//var search = document.getElementById("search").value;
	var combined = document.getElementById("startingPoint").value;
	if(combined) {
		var search = combined;
	} else {
		var address = document.getElementById("start_address").value;
		var search = address;
		if (document.getElementById("start_city").value) {
			var city = document.getElementById("start_city").value;
			search += ' ' + city;
		}
		if (document.getElementById("start_state").value) {
			var state = document.getElementById("start_state").value;
			search += ', ' + state;
		}
		if (document.getElementById("start_zipcode").value) {
			var zipcode = document.getElementById("start_zipcode").value;
			search += ' ' + zipcode;
		}
	}

	// ====== Perform the Geocoding ======        
	geo.getLocations(search, function (result)
	{
		//map.clearOverlays(); 
		if (result.Status.code == G_GEO_SUCCESS) {
			// ===== If there was more than one result, "ask did you mean" on them all =====
			if (result.Placemark.length > 1) { 
				document.getElementById("message").style.visibility = 'visible';
				var innerHTML = "<table><tr><td align='center'colspan=2><b>Did you mean</b></td></tr>";
				// Loop through the results
				for (var i=0; i<result.Placemark.length; i++) {
					var p = result.Placemark[i].Point.coordinates;
					//document.getElementById("message").innerHTML += "<tr><td>"+(i+1)+": <a href='javascript:place(" +p[1]+","+p[0]+")'>"+ result.Placemark[i].address+"</a></td></tr>";
					innerHTML += "<tr><td>"+(i+1)+": <a href='javascript:place(" +p[1]+","+p[0]+",\""+result.Placemark[i].address+"\")'>"+ result.Placemark[i].address+"</a></td></tr>";
				}
				innerHTML += "</table>";
				document.getElementById("message").innerHTML = innerHTML;
			}
			// ===== If there was a single marker =====
			else {
				document.getElementById("message").innerHTML = "";
				var p = result.Placemark[0].Point.coordinates;
				var address = result.Placemark[0].address;
				place(p[1],p[0],address);
			}
		}
		// ====== Decode the error status ======
		else {
			var reason="Code "+result.Status.code;
			if (reasons[result.Status.code]) {
				reason = reasons[result.Status.code]
			} 
			alert('Could not find "'+search+ '" ' + reason);
		}
	}
	);
}

function place(lat,lng,address) {
	var point = new GLatLng(lat,lng);
	map.setCenter(point,14); 
	map.addOverlay(new GMarker(point,startpoint));
	document.getElementById("message").innerHTML = "";
	document.getElementById("message").style.visibility = "hidden";
	tart_set = true;
	addRouteStartingPoint(lat,lng,address);
}

function centerMap() {
	map.setZoom(map.getBoundsZoomLevel(bounds));
	var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
	var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
	map.setCenter(new GLatLng(clat,clng));
}

function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc. )
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return y = document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case.
	return 0;
}

function handleResize() {
	var height = windowHeight();
	height -= document.getElementById('header').offsetHeight + 35;
	document.getElementById('content').style.height = height + 'px';
	document.getElementById('map-wrapper').style.height = height - 0 + 'px';
	if(height<185){ height=186; }
	document.getElementById('sidebar').style.height = height - 185 + 'px';
	if(height<315){ height=316;}
	document.getElementById('directions').style.height = height - 315 + 'px';
	
}

function mapDetail(lat,lon,zoom) {
	if (GBrowserIsCompatible()) {
		var point = new GLatLng(lat, lon);
		var smallmap = new GMap2(document.getElementById("mapdetail"));
		smallmap.addControl(new GSmallMapControl());
		smallmap.setCenter(new GLatLng(point), zoom);
		smallmap.addOverlay(new GMarker(point));
	}
}

function init() {
	if (GBrowserIsCompatible()) {
		var type;
		var allTypes = {'All':[] };
        
		document.getElementById('button-sidebar-route').onclick = function() { return changeBodyClass('sidebar-right', 'nosidebar'); }
		document.getElementById('button-sidebar-calendar').onclick = function() { return changeBodyClass('nosidebar', 'sidebar-right'); }
		
		handleResize();

		map = new GMap2(document.getElementById("map"), {googleBarOptions:{showOnLoad:true}});
		//map.enableGoogleBar();
		map.addControl(new GScaleControl());
		map.enableDoubleClickZoom();
		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		map.addControl(new GOverviewMapControl(new GSize(133,75)));
		
		var pt = new GLatLng(top.map_lat, top.map_long);
		map.setCenter(pt, 17 - top.map_zoom);
		
		directionsPanel = document.getElementById("route-directions");
		directions = new GDirections(map, directionsPanel);
		
		for(id in markers) {
			initializePoint(markers[id]);
			allTypes[markers[id].category] = true;
		}
		
		for(type in allTypes) {
			initializeSortTab(type);
		}
        
		centerMap();
        
		changeBodyClass('loading', 'standby');
	}
}

function clear_directions() {
	gDirections.clear();
}

function getPrivateParty(search) {
	document.privatePartyForm.search.value = search ;
	document.privatePartyForm.submit() ;
}

window.onresize = handleResize;
	window.onload = init;

