// ------------------------------------------------------
// Copyright 2005 Jonathan Graham (www.tooleshed.com)
// ------------------------------------------------------
var map;
var baseIcon = new GIcon();

var _directfrto = null;

var _currMarkerPos = 0;
var _currMarkerIndex = 0;

var _clickMarkerPos = 0;
var _clickMarkerIndex = 0;

var _markers = new Array();

var _data = null;
var _default_companyids = "393,547,548";

var _SERVER = "http://www.elyminnesota.com";


var arVersion = navigator.appVersion.split("MSIE")
var is_ie = ((parseFloat(arVersion[1]) >= 5.5) && (document.body.filters))


Array.prototype.clear=function() {
	while(this.length>0) this.pop();
}

// ============================================================================= mapLoad
//
function mapLoad() {
	baseIcon.shadow = _SERVER + "/images/marker/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);	

	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.enableDoubleClickZoom();
	map.setCenter(new GLatLng(47.903435, -91.857042), 13);

	mapLoadData();	
}

// ============================================================================= categoryChange
//
function categoryChange(cid) {
	_categoryid = cid;
	document.getElementById("panel").innerHTML = "Loading...";
	mapLoadData("");
}

// ============================================================================= keywordSearch
//
function keywordSearch(frm) {
	var keyword = document.getElementById("search").value;
	_categoryid = 0;
	if ( keyword == "" ) {
		document.getElementById("panel").innerHTML = "Please enter a keyword to find businesses.";
		return false;
	}
	document.getElementById("panel").innerHTML = "Searching & Loading...";
	mapLoadData(keyword);
	return false;
}


// ============================================================================= mapLoadData
//
function mapLoadData(keyword) {
    //alert('Keyword: ' + _keyword);
	if (_keyword != "") keyword = _keyword;
	
	if (_categoryid == 0 && _coids == "" && (!keyword || keyword == "") && _default_companyids == "") {
		document.getElementById("panel").innerHTML = "Select a category above or search the directory by entering keywords.";
		return;
	}
	
	_currMarkerPos = 0;
	_currMarkerIndex = 0;
	
	_clickMarkerPos = 0;
	_clickMarkerIndex = 0;	
	
	_markers.clear();
	
	if ( !_categoryid && !keyword && !_coids != "") {
		url = "/directory/httpengine.php?op=mapdatanew&coids=" + _default_companyids;
	} else if ( _categoryid ) {
		url = "/directory/httpengine.php?op=mapdatanew&cid=" + _categoryid;
	} else if ( keyword && keyword != "") {
		url = "/directory/httpengine.php?op=mapdatanew&kw=" + keyword.replace(" ", "+");
	} else {
		url = "/directory/httpengine.php?op=mapdatanew&coids=" + _coids;
	}		

	var request = GXmlHttp.create();
	request.open("GET", url, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			req = request.responseText;

			eval("_data = " + req + ";");
			
			map.clearOverlays();
			document.getElementById("detailpanel").innerHTML = "";


            // Check to see if the _data["error"] variable is set or not, if not
            // declare it empty so that there is not an error when displaying
            // the correct information
            //
            // Added March 20, 2009 - Dustin Miller dustin@coldsnaptech.com
            if(typeof(_data["error"]) == 'undefined'){
                _data["error"] = "";
            }

			if ( _data["error"] != "") {
				map.setCenter(new GLatLng(47.903435, -91.857042), 13);
				document.getElementById("panel").innerHTML = _data["error"];
				return;
			}
			
			
			// Get center/span and calculate zoom 
			var sw		= new GLatLng(_data["clat"]-(_data["slat"]/2),  _data["clng"]-(_data["slng"]/2));
			var ne		= new GLatLng(_data["clat"]+(_data["slat"]/2),  _data["clng"]+(_data["slng"]/2));
			var center 	= new GLatLng(_data["clat"], _data["clng"]);

			var zoomlvl = map.getBoundsZoomLevel(new GLatLngBounds(sw, ne));
			map.setCenter(center, zoomlvl);
			
			// Load markers 
			var first = true;
			var openfirst = null;
			var comps = _data["cos"];
			if (!comps) return;
			
			for (var i= 0; i < comps.length; i++) {
				co = comps[i];
				if ( co["marker"] != "0" ) {
					var point = new GLatLng(co["Latitude"], co["Longitude"]);

					var mark = co["marker"];
					var marker = createMarker(point, mark, i, first);
					_markers[mark] = marker;
					map.addOverlay(marker);
					
					// Create function to "click" first marker after loading map and panel.
					if ( first ) { 
						first = false;
						var firstmarker = marker;
						openfirst = function() {
							GEvent.trigger(firstmarker, "click");
						}
					}
				}
			}
			
			// Load Panel html
			displayPanel(_data);
			
			openfirst();
			
			window.status = "";
		}
	};
	request.send(null);	
}

// ============================================================================= createMarker
//
function createMarker(point, mpos, mindex, sel) {
	var icon = new GIcon(baseIcon);
	if ( sel ) {
		icon.image = _SERVER + "/images/markersel/markersel" + mpos + ".png";
	} else {
		icon.image = _SERVER + "/images/marker/marker" + mpos + ".png";
	}
	var marker = new GMarker(point, icon);
	
	GEvent.addListener(marker, "click", function() {
		markerClick(marker, mpos, mindex);
	});
	
	return marker;
}

// ============================================================================= markerClick
//
function markerClick(marker, mpos, mindex) {
	_clickMarkerPos = mpos;
	_clickMarkerIndex = mindex;

	var comp = _data["cos"][mindex];

	markerColor(marker, mpos, mindex);
	
	displayDetail(comp);
	marker.openInfoWindowHtml(displayMarker(comp));
	
}


// ============================================================================= panelMarker
//
function panelMarkerClick(pos) {
	GEvent.trigger(_markers[pos], "click");
}


// ============================================================================= markerColor
//
function markerColor(marker, mpos, mindex) {
	if ( mpos != _currMarkerPos ) {
	
		// Change color of the clicked-on marker
		var npoint = marker.getPoint();
		newmark = createMarker(npoint, mpos, mindex, true);
		_markers[mpos] = newmark;
		map.addOverlay(newmark);

		if (!is_ie) {
			var panelimg = document.getElementById("panelmarkerimg"+mpos);
			panelimg.src = _SERVER + "/images/markersel/markersel" + mpos + ".png";
		} else {
			var panelspan = document.getElementById("panelmarkerspan"+mpos);
			src = _SERVER + "/images/markersel/markersel" + mpos + ".png";
			panelspan.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader'
				+ '(src=\'' + src + '\', sizingMethod=\'scale\');"></span>';
		}
		
		GEvent.clearListeners(marker, "click")			
		map.removeOverlay(marker);
		
		if (_currMarkerPos != 0 ) {	// Revert previous marker to default color
			var marker = _markers[_currMarkerPos];
			var mpoint = marker.getPoint();
			newmark = createMarker(mpoint, _currMarkerPos, _currMarkerIndex, false);
			_markers[_currMarkerPos] = newmark;
			map.addOverlay(newmark);

			if ( !is_ie) {			
				panelimg = document.getElementById("panelmarkerimg"+_currMarkerPos);
				panelimg.src = _SERVER + "/images/marker/marker" + _currMarkerPos + ".png";
			} else {
				panelspan = document.getElementById("panelmarkerspan"+_currMarkerPos);
				src = _SERVER + "/images/marker/marker" + _currMarkerPos + ".png";
				panelspan.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader'
					+ '(src=\'' + src + '\', sizingMethod=\'scale\');"></span>';
			}

			GEvent.clearListeners(marker, "click")			
			map.removeOverlay(marker);
		}
		
		map.setCenter(npoint);
		
		_currMarkerPos = mpos;
		_currMarkerIndex = mindex;
	}

}

// ============================================================================= displayPanel
//
function displayPanel(rs) {
	var html = "";
	
	html += '<table cellspacing="0" cellpadding="2" border="0">';
	
	comps = rs["cos"];
	for (i=0;i<comps.length;i++) {
		co = comps[i];
		if ( i%2 == 1) {
			html += '<tr bgcolor="#DBC299">';
		} else {
			html += '<tr>';
		}
			
		html += '<td style="font-size:10pt; font-weight:bold;">';
		mark = co["marker"];
		if ( mark != 0 ){
			html += '<a href="javascript: panelMarkerClick(' + mark + ');">';
			
			if ( mark == 1 ) {
				src = _SERVER + "/images/markersel/markersel" + mark + ".png";
			} else {
				src = _SERVER + "/images/marker/marker" + mark + ".png";
			}
			
			if (is_ie) {
				h = '<span id="panelmarkerspan'+ mark +'" '
					+ 'style="display:inline-block; cursor:hand; width: 20px; height: 34px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader'
					+ '(src=\'' + src + '\', sizingMethod=\'scale\');"></span>';
				html += h;	
			} else {
				html += '<img border="0" id="panelmarkerimg' + mark + '" src="' + src + '"/></a>';
			}
		}
		html += "</td>";
		html += "<td>";
		
		style = "";
		if ( co["choiceboldPrint"] == 1) {
			style += "font-weight: bold; ";
		}
		else if ( co["choiceboldRedPrint"] == 1) {
			style += "color: #ff0000; font-weight: bold; ";
		}
		else if ( co["choiceboldBluePrint"] == 1) {
			style += "color: #0000ff; font-weight: bold; ";
		}
		html += '<span style="' + style + '">' + co["Company"] + '</span><br/>';
		html += co["Address"] + ", " + co["City"] + " - " + co["Phone"];
		html += '</td></tr>';
	}
	html += '</table>';

	document.getElementById("panel").innerHTML = html;

}


// ============================================================================= displayDetail
//
function displayDetail(co) {
	var html = "";
	html += '<div align="left">';
	html += '<table cellpadding="0" cellspacing="0" border="0">';
	html += '<tr><td>';

	style = "";
	if ( co["choiceboldPrint"] == 1) {
		style += "font-weight: bold; ";
	}
	else if ( co["choiceboldRedPrint"] == 1) {
		style += "color: #ff0000; font-weight: bold; ";
	}
	else if ( co["choiceboldBluePrint"] == 1) {
		style += "color: #0000ff; font-weight: bold; ";
	}
	html += '<span style="' + style + '">' + co["Company"] + '</span><br/>';
	html += co["Address"] + ", " + co["City"] + ", " + co["State"] + ", " + co["Zip"] + "<br/>";
	html += co["Phone"];
	if ( co["choicetollFree"] == 1 ) {
		html += " | " + co["TollFree"];
	}
	if ( co["choiceFax"] == 1 ) {
		html += " | " + co["Fax"];
	}
	html += "<br>";
	
	if (co["choicehttpLink"] == 1) {
		html += '<a target="_new" href="' + co["WebsiteLink"] + '">' + co["Website"] + '</a><br>';
	}
	
	if (co["choiceEmail"] == 1) {
		html += '<a href="/directory/emailco.php?companyid=' + co["Companyid"] + '&action=newmail">Email this Company</a><br>';
	}

	if (co["choiceMoreInfo"] == 1) {
		html += '<a href="/directory/moreinfo.php?info=' + co["MoreInfo"] + '">' + co["MoreInfoDisplay"] + '</a><br>';
	}

	html += "</td></tr></table></div>";
	
	document.getElementById("detailpanel").innerHTML = html;

}

// ============================================================================= displayMarker
//
function displayMarker(co) {
	var html = "";
	html += '<div align="left">';
	
	if (co["choiceLogo"] == 1) {
		html += '<img border="0" height="' + co["LogoHeight"] + '" width="' + co["LogoWidth"] + '" src="/directory/images/' + co["Logo"] + '"><br>';
	}
	style = "";
	if ( co["choiceboldPrint"] == 1) {
		style += "font-weight: bold; ";
	}
	else if ( co["choiceboldRedPrint"] == 1) {
		style += "color: #ff0000; font-weight: bold; ";
	}
	else if ( co["choiceboldBluePrint"] == 1) {
		style += "color: #0000ff; font-weight: bold; ";
	}
	html += '<span style="' + style + '">' + co["Company"] + '</span><br/>';
	html += co["Address"] + ", " + co["City"] + ", " + co["State"] + ", " + co["Zip"] + "<br/>";
	html += '<strong>Directions:</strong>&nbsp;';
	html += '	<a href="javascript: showDirectDiv(0)">From Here</a> | ';
	html += '	<a href="javascript: showDirectDiv(1)">To Here</a>';
	html += '	<div id="directdiv">';
	html += '		<div id="directext"></div>';
	html += '		<form class="simpleform" name="directions" onsubmit="return false;">';
	html += '		<input type="text" name="directions" size="30"/><br/>';
	html += '		<input type="button" value="show" onclick="showDirections(this.form.directions.value)"/>';
	html += '		(opens new window)';
	html += '		</form>';
	html += '	</div>';	
	html += '</div>';

	return html;
}

// ============================================================================= showDirectDiv
//
function showDirectDiv(frto) {
	_directfrto = frto;
	if ( frto == 0 ) {
		html = "End Address:";
	} else {
		html = "Start Address:";
	}
	document.getElementById("directext").innerHTML = html;
	document.getElementById("directdiv").style.visibility = "visible";

}

// ============================================================================= showDirections
//
function showDirections(inaddr) {
	url = "http://maps.google.com/maps";  
	var comp = _data["cos"][_clickMarkerIndex];
	var addr = comp["Address"] + ", " + comp["City"] + ", " + comp["State"] + ", " + comp["Zip"];
	
	if ( _directfrto == 0 ) {	// From the clicked marker
		from = addr.replace(/ /g, "+");
		to = inaddr.replace(/ /g, "+");
	} else {					// To the clicked marker
		from = inaddr.replace(/ /g, "+");
		to = addr.replace(/ /g, "+");
	}
	url += "?saddr=" + from + "&daddr=" + to;
	window.open(url, "googlemaps");
}

