var map;
var map_hold;
var geocoder;
var zoomlevel_storedetail = 16;
var zoomlevel_default = 4;
var radius_default = 25;
var markers; // array to hold xml data
var debug = false;
var passedparams;
var results_hold;

function pause(duration) { 
	if (debug) {alert( "Starting something"); }
	setTimeout( "pauseend();", duration);
} 

function pauseend() { 
	if (debug) {alert( "5 seconds later!"); }
} 

function searchLocations (querystring) {
	if (debug) {alert('starting function searchLocations');}
	// provide link on results page to list all locations or all in a specific state(?)
	// Perhaps show them the Google US map with all locations having markers.
	// Then they can drill down on the map.  May be too CPU intensive though.
	var address = document.getElementById('addressInput').value;
	// geocoder.reset();
	geocoder.getLatLng(address, function(latlng) {
	  if (!latlng) {
		var results2 = document.getElementById('coda-slider-1');
		results2.innerHTML = 'No results found.';
	  }
	  else {
		searchLocationsNear (latlng, querystring);
	  }
	});
  // pause(5000);
}

function getGData (markers, mindex, bounds) {
	var locid    = markers[mindex].getAttribute('locid');
	var name     = markers[mindex].getAttribute('city');
	var address1 = markers[mindex].getAttribute('address1');
	var address2 = markers[mindex].getAttribute('address2');
	var state    = markers[mindex].getAttribute('state');
	var zip      = markers[mindex].getAttribute('zip');
	var phone    = markers[mindex].getAttribute('phone');
	var hours    = markers[mindex].getAttribute('hours');
	var address  = address1 + '<br/>';
	if (address2 != '') {
		address += address2 + '<br/>';
	}
	var results = document.getElementById('coda-slider-1');
	address +=state + ', ' + zip + '<br/>' + phone;
	var distance = parseFloat(markers[mindex].getAttribute('distance'));
	/*
		Comento esto para obtener la lat/long a traves de google y no con los datos de la base
	var point = new GLatLng(parseFloat(markers[mindex].getAttribute('lat')),
					 parseFloat(markers[mindex].getAttribute('lng')));
	*/
	// Agregado para obtener el punto a traves de google
	document.distances = new Array ();
	var geoCoder = new GClientGeocoder ();
	var dire = address1 + ', ' + address2 + ' ' + name + ', ' + state + ', ' + zip;
	var addressInput = document.getElementById('addressInput').value;
	var geoCoder2 = new GClientGeocoder ();
	geoCoder2.getLatLng (addressInput, function (p2) {
		geoCoder.getLatLng (dire, function (point) {
			if (point) {
				window.gPoint = point;
				if (p2) {
					distance = p2.distanceFrom (point);
					// 1609,344 metros = 1 milla
					// 'distance' metros = (distance / 1609,344) millas
					distance = distance / 1609.344;
					distance = distance.toFixed (1);
					//document.distances.push (distance);
					markers[mindex].setAttribute ('distance', distance);
				}
				var marker = createMarker(point, mindex);
				map.addOverlay(marker);
				var sidebarEntry = createSidebarEntry(marker, mindex, point);
				results.appendChild(sidebarEntry);
				bounds.extend(point);
				mindex++;
				if (mindex < markers.length) {
					getGData (markers, mindex, bounds);
				}
				else {
					if (markers.length < 2) {
						map.setCenter(bounds.getCenter(), (map.getBoundsZoomLevel(bounds)-2));
					}
					else {
						map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
					}
				}
			}
		});
	});
	// Fin agregado
}

function searchLocationsNear (center, querystring) {
	if (debug) {alert('starting function searchLocationsNear');}
	var radius = document.getElementById('radiusSelect').value;
	var searchUrl = 'locator.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
	//var searchUrl = 'locator.php?q=' + querystring;
	GDownloadUrl(searchUrl, function(data) {
		var xml = GXml.parse(data);
		markers = xml.documentElement.getElementsByTagName('marker');
		map.clearOverlays();
		var results = document.getElementById('coda-slider-1');
		results.innerHTML = '';
		if (markers.length == 0) {
			results.innerHTML = 'No results found.';
			// This shows entire US map (without markers).
			// map.setCenter(new GLatLng(40, -100), zoomlevel_default);
			return;
		}
		var bounds = new GLatLngBounds();
		// Agregado por casu
		var cont1 = document.createElement ("div");
		cont1.className = 'panel';
		var cont2 = document.createElement ("div");
		cont2.className = 'panel-wrapper';
		cont2.id = 'panel_0';
		cont1.appendChild (cont2);
		results.appendChild (cont1);
		document.getElementById ("results").innerHTML = '<strong>' + markers.length + '</strong> Stores Found';
		var ultimoIndex = 0;
		// Fin agregado
		getGData (markers, 0, bounds);
		
		// FIX: Seemingly, when there is only one returned item, zoom level is too high and nothing shows.
		// Actually something does show, but the zoom level is so high, it appears there is nothing there.
		// Can we set a max zoom level or -1 on the zoom level if only 1 marker is returned?
		// I believe this can be done if we use the marker manager.  check into that.
	});
}

/*  Original function
function createMarker(point, name, address) {
  var marker = new GMarker(point);
  var html = '<b>' + name + '</b><br/>' + address;
  GEvent.addListener(marker, 'click', function() {
	marker.openInfoWindowHtml(html);
  });
  return marker;
}
*/

function createCustomIcon() {
	if (debug) {alert('start of function createCustomIcon');}
	var cI = new GIcon(G_DEFAULT_ICON);
	cI.image = "images/favicon.png";
	cI.iconSize = new GSize(16, 16);
	cI.shadow = "images/marker_SC_shadow.png";
	cI.shadowSize = new GSize(44, 32);
	cI.iconAnchor = new GPoint(14, 31);
	cI.infoWindowAnchor = new GPoint(20, 2);
	return cI;
} 

function createMarker(point, mindex) {
	if (debug) {alert('start of function createMarker');}
	var company    = markers[mindex].getAttribute('company');
	var store_name = markers[mindex].getAttribute('store_name');
	var address1   = markers[mindex].getAttribute('address1');
	var address2   = markers[mindex].getAttribute('address2');
	var city       = markers[mindex].getAttribute('city');
	var state      = markers[mindex].getAttribute('state');
	var zip        = markers[mindex].getAttribute('zip');
	var country    = markers[mindex].getAttribute('country');
	var phone      = markers[mindex].getAttribute('phone');
	var distance   = markers[mindex].getAttribute('distance');

	var name     = markers[mindex].getAttribute('city');
	var zip      = markers[mindex].getAttribute('zip');
	var fax      = markers[mindex].getAttribute('fax');
	var hours    = markers[mindex].getAttribute('hours');
	var address  = address1 + '<br/>';
	if (address2 != '') {
		address += address2 + '<br/>';
	}
	address +=state + ', ' + zip + '<br/>phn: ' + phone;
	if (fax != '') {
		address += '<br/>fax: ' + fax;
	}
	
	var marker = new GMarker(point,markerOptions);
	var id1 = 'markercontent';
	var id2 = 'left';
	var id3 = 'right';
	var divopen = '<div style="width: 300px;" id="';
	var divopenend = '">';
	var divclose = '</div>';
	var contentleft = '<b>' + store_name + ' - ' + distance + ' miles</b><br /><b>' + company + '</b>';
	contentleft += '<br />' + address1 + ', ' + address2;
	contentleft += '<br/>' + city + ', ' + state + ' ' + zip;
	contentleft += '<br />' + country + '<br />Phone: ' + phone;
	hours = '';
	if (hours != '') {
		var contentright = '<b>Hours</b><br />' + hours;
	}
	else {
		var contentright = '';
	}
	var html = divopen + id1 + divopenend;
	html = html + divopen + id2 + divopenend + contentleft + divclose;
	//html = html + divopen + id3 + divopenend + contentright + divclose;
	html = html + divclose;
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
		// Add code here to also bring the sidebar entry into focus if
		// the marker is clicked, so background hover color shows on the sidebar. 
	});
	GEvent.addListener(marker, 'mouseover', function() {
		marker.openInfoWindowHtml(html);
		// Add code here to also bring the sidebar entry into focus if
		// the marker is moused over, so background hover color shows on the sidebar. 
	});
	// For now, take this listener out as it disallows the infowindow from remaining open
	// when a click event occurs. 
	GEvent.addListener(marker, 'mouseout', function() {
		marker.closeInfoWindow();
		// Add code here to also bring the sidebar entry into focus if
		// the marker is moused over, so background hover color shows on the sidebar. 
	});
	return marker;
}

/*  Below function is for when we start using tabbed infowindows.
function createMarker(point, name, address, hours) {
//     if (debug) {alert('starting function createMarker');}
  // Switch this to start WITHOUT tabs and fit all the info in formatted to fit one infowindow.
  // Then work on customized tabs.
  // Can tabs be numbered or is there a way to offer an overlay that shows numbers that would
  // correspond to numbered results?
  var marker = new GMarker(point);
  GEvent.addListener(marker, 'click', function() {
	var tabs = [];
	var tablabel1 = 'DETAILS';
	var tablabel2 = 'HOURS';
	var content1 = '<b>' + name + '</b><br/>' + address;
	var content2 = hours;
	// Update this to display any other info pulled; fax, hours_note, teaser, etc.
	// Problem: default tab setup does not expand to fit more than two tabs or more than one word
	// per tab label.
	// Two choices for fix:  (1) Either put all the information in the main infowindow and don't use tabs
	// or (2) customize the tabs to fit properly.
	// Solution 2 may not have a payoff as it will take a lot of work.
	// Solution 1 has a downside that the info balloon could grow too large unless we can format it better.
	tabs.push(new GInfoWindowTab(tablabel1, content1));
	tabs.push(new GInfoWindowTab(tablabel2, content2));
	marker.openInfoWindowTabsHtml(tabs);
  });
  // Might want to also add a mouseover event listener that does the same thing.
  return marker;
}
*/

function createSidebarEntry(marker, mindex, point) {
	if (debug) {alert('starting function createSidebarEntry');}
	// gather db data
	var company    = markers[mindex].getAttribute('company');
	var store_name = markers[mindex].getAttribute('store_name');
	var address1   = markers[mindex].getAttribute('address1');
	var address2   = markers[mindex].getAttribute('address2');
	var city       = markers[mindex].getAttribute('city');
	var state      = markers[mindex].getAttribute('state');
	var zip        = markers[mindex].getAttribute('zip');
	var country    = markers[mindex].getAttribute('country');
	
	var locid    = markers[mindex].getAttribute('locid');
	var phone    = markers[mindex].getAttribute('phone');
	var fax      = markers[mindex].getAttribute('fax');
	var dist     = markers[mindex].getAttribute('dist');
	var hours    = markers[mindex].getAttribute('hours');
	var address  = address1 + '<br/>';
	if (address2 != '') {
		address += address2 + '<br/>';
	}
	address +=state + ', ' + zip + '<br/>phn: ' + phone;
	if (fax != '') {
		address += '<br/>fax: ' + fax;
	}
	var distance = parseFloat(markers[mindex].getAttribute('distance'));
	var div = document.createElement('div');
	div.id = 'list_' + mindex;
	div.className = "list";
	var html = "";
	html += '<h5>';
	html += '	<a href="javascript:;">' + store_name + ' - <span class="violet2">' + distance.toFixed (1) + ' miles</span></a>';
	html += '</h5>';
	html += '<ul>';
	html += '	<li>' + company + '</li>';
	html += '	<li>' + address1 + ' - ' + address2 + '</li>';
	html += '	<li>' + city + ', ' + state + ', ' + zip + '</li>';
	html += '	<li>' + country + '</li>';
	html += '	<li> Phone: ' + phone + '</li>';
	html += '</ul>';
	// link 1 setup; MapIt
	var zoom = zoomlevel_storedetail;
	var pointlat = point.lat();
	var pointlng = point.lng();
	var link1href = 'href="javascript:mapit(' + pointlat + ',' + pointlng + ',' + zoom + ',' + mindex + ')"';
	var link1text = 'Map It';
	//var link1 = '<ul><li><a ' + link1href + '>' + link1text + '</a></li>';
	var link1 = '<div class="links"><a id="lnkMapit" ' + link1href + '>' + link1text + '</a> ';
	// link 2 setup; Directions
	//var link2href = 'href="/stores/directions.htm?locid=' + locid + '"';
	var link2href = 'href="javascript:directions (' + pointlat + ', ' + pointlng + ', \'' + address1 + ', ' + city + ', ' + state + ' ' + zip + '\');"';
	var link2text = 'Directions';
	var link2 = '<a ' + link2href + '>' + link2text + '</a></div>';
	//var link2 = '</div>';
	// link 3 setup; Education on store page
	if (dist==1) { var link3href = 'href="http://www.baistore.com/education.htm"'; }  // bai
	if (dist==2) { var link3href = 'href="http://www.cbslink.com/education_calendar.php"'; }  // cbs
	if (dist==3) { var link3href = 'href="http://www.malys.com/web/stores/store_detail.php?locid=' + locid + '"'; } // malys west
	if (dist==4) { var link3href = 'href="http://www.malys-midwest.com/"'; } // malys midwest
	if (dist==5) { var link3href = 'href="http://www.4mss.com/geteducated.html"'; } // marshall
	if (dist==6) { var link3href = 'href="http://www.cbsullivan.com/pages/education.cfm"'; } // CBSullivan
	var link3text = 'Education';
	//var link3 = '<li><a ' + link3href + 'target="blank">' + link3text + '</a></li></ul>';
	var link3 = '<a href="javascript:jQuery.jPrintArea (document.getElementById (\'map_group\'));">PRINT IT</a></div>';
	html = html + link1 + link2; // + link3;
	div.innerHTML = html;
	GEvent.addDomListener(div, 'click', function() {
	  // get hover bg color to stick on a click													 
	  // div.style.backgroundColor = '#ccc';
	  // GEvent.trigger(marker, 'click');
	});
	GEvent.addDomListener(div, 'mouseover', function() {
	  //div.style.backgroundColor = '#D6ECF5';
	  GEvent.trigger(marker, 'mouseover');
	});
	GEvent.addDomListener(div, 'mouseout', function() {
	  //GEvent.trigger(marker, 'mouseout');														
	  //div.style.backgroundColor = '#fff';
	});
	return div;
}

function mapit(pointlat, pointlng, zoom, mindex) {
	if (debug) {alert('starting function mapit');}
	// Agregado por casu
	document.getElementById ("results").innerHTML = "";
	customIcon = createCustomIcon();
	markerOptions = {icon:customIcon};
	// Fin agregado
	map_hold = map;
	var map_dtl = new GMap2(document.getElementById('map2'));
	map_dtl.addControl(new GLargeMapControl3D());
	map_dtl.addControl(new GMapTypeControl());
	var point = new GLatLng(pointlat, pointlng);
	map_dtl.setCenter(point,zoom);
	var marker = createMarker(point, mindex);
	var results_hold = document.getElementById('coda-slider-1');
	var results = document.getElementById('coda-slider-1');
	results.innerHTML='';
	var sidebarEntry = createSidebarEntry(marker, mindex, point);
	results.appendChild(sidebarEntry);
	//
	//elementgot = document.getElementById('storedets');
	elementgot = document.getElementById('list_' + mindex);
	atags = elementgot.getElementsByTagName('a');
	//atags[0].innerHTML = 'Print It';
	//atags[0].href = 'javascript:window.print();';
	// create link to return to previous listing.
	var div = document.createElement('div');
	div.className='returntofull';
	var html = '';
	var link1href = 'href="javascript:load()"';
	var link1text = 'Back to previous full listing';
	var link1 = '<a ' + link1href + '>' + link1text + '</a>';
	html = link1;
	document.ref
	div.innerHTML = html;
	results.appendChild(div);
	map_dtl.addOverlay(marker);
	// Agregado por casu - borro el 'Map It'
	lnkMapit = document.getElementById ("lnkMapit");
	var mapitParent = lnkMapit.parentNode;
	mapitParent.removeChild (lnkMapit);
	// Agrego el 'Print It'
	var printIt = document.createElement ("a");
	var mark = markers[mindex];
	var addr = markers[mindex].getAttribute ("address1") + ", " + markers[mindex].getAttribute ("address2");
	var address = addr + ", " + mark.getAttribute ("city") + ", " + mark.getAttribute ("state") + " " + mark.getAttribute ("zip");
	printIt.href = "javascript:jQuery.jPrintArea (document.getElementById (\'map2\'), '" + address + "');";
	printIt.innerHTML = 'Print It';
	mapitParent.appendChild (printIt);
	// Fin agregado
}

