var map;
var centerLatitude = 38;
var centerLongitude = -122;
var startZoom = 12;
var listingZoom = 15;
var cats='';
var showcaseCount=0;
var mTest = null;
var startScroll = null;
var prevent_scroll = false;
var mapMove = null;

var baseIcon = new GIcon();
baseIcon.iconSize = new GSize(21, 35);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(6, 20);


function handleGetDirections(destination) {
	var myAddress = document.getElementById('my-address').value;
	var myCity = document.getElementById('my-city').value;
	var origin = myAddress +  ', ' + myCity;
	if (myAddress == '' && myCity == '') {
        alert('Please enter an address.');
        return false;
    };
	window.open('http://maps.google.com/maps?f=d&hl=en&saddr='+origin+'&daddr='+destination,'directions');
}

var deselectCurrent = function() {};

function initializePoint(pointData,index,thisFile,prevMode) {

  if (pointData.mode == 'showcase') ++showcaseCount;

  if (prevMode=='' && pointData.mode == 'showcase') {
// this is the 1st showcase listing
// add a title row

    var emptyRow = document.createElement('tr');
    var emptyTd = document.createElement('td');

    emptyTd.setAttribute('colSpan','4');
    emptyTd.setAttribute('valign','bottom');
    emptyTd.innerHTML = "<b>&nbsp;&nbsp;Showcase Listings</b>";
    emptyTd.style.padding='0';
    emptyRow.appendChild(emptyTd);
    emptyRow.style.height="17px";

    document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(emptyRow);

  } else if ( (prevMode=='' || prevMode == 'showcase') && pointData.mode == 'additional') {

// this is the 1st additional criteria listing
// add a title row

    var emptyRow = document.createElement('tr');
    var emptyTd = document.createElement('td');

    emptyTd.setAttribute('colSpan','4');
    emptyTd.setAttribute('valign','bottom');
    emptyTd.innerHTML = "<b>Listings that match your search</b><br><img src='/images/results_bottom_thin.gif'>";
    emptyTd.style.padding='0';
    emptyRow.appendChild(emptyTd);
    emptyRow.style.height="30px";

    document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(emptyRow);

  } else if ((prevMode=='' || prevMode == 'showcase' || prevMode == 'additional') && pointData.mode == 'other') {

    if (prevMode == 'showcase' && pointData.mode == 'other' && additionalCriteriaSpecified) {

      var emptyRow = document.createElement('tr');
      var emptyTd = document.createElement('td');

      emptyTd.setAttribute('colSpan','4');
      emptyTd.setAttribute('valign','bottom');
      emptyTd.innerHTML = "<b>Listings that match your search</b><br><img src='/images/results_bottom_thin.gif'>";
      emptyTd.style.padding='0';
      emptyRow.appendChild(emptyTd);
      emptyRow.style.height="30px";

      document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(emptyRow);

      var emptyRow = document.createElement('tr');
      var emptyTd = document.createElement('td');

      emptyTd.setAttribute('colSpan','4');
      emptyTd.setAttribute('valign','bottom');
      emptyTd.innerHTML = "<p>No listings matched your additional search criteria</p>";
      emptyRow.appendChild(emptyTd);

      document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(emptyRow);

// add a header for other listings

      var emptyRow = document.createElement('tr');
      var emptyTd = document.createElement('td');

  	  emptyTd.setAttribute('colSpan','4');
  	  emptyTd.setAttribute('valign','bottom');
  	  emptyTd.innerHTML = "<b>Other listings in your area</b><br><img src='/images/results_bottom_thin.gif'>";
  	  emptyTd.style.padding='0';
  	  emptyRow.appendChild(emptyTd);
  	  emptyRow.style.height="30px";

      document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(emptyRow);

    } else if (prevMode == '' && pointData.mode == 'other' && additionalCriteriaSpecified) {

// no matches for users specified search criteria :(

      if(page == 1) {
        var emptyRow = document.createElement('tr');
        var emptyTd = document.createElement('td');

        emptyTd.setAttribute('colSpan','4');
        emptyTd.setAttribute('valign','bottom');
        emptyTd.innerHTML = "<b>Listings that match your search</b><br><img src='/images/results_bottom_thin.gif'>";
        emptyTd.style.padding='0';
        emptyRow.appendChild(emptyTd);
        emptyRow.style.height="30px";

        document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(emptyRow);

        var emptyRow = document.createElement('tr');
        var emptyTd = document.createElement('td');

        emptyTd.setAttribute('colSpan','4');
        emptyTd.setAttribute('valign','bottom');
        emptyTd.innerHTML = "<p>No listings matched your additional search criteria</p>";
        emptyRow.appendChild(emptyTd);

        document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(emptyRow);
      }
// add a header for other listings

  		var emptyRow = document.createElement('tr');
  		var emptyTd = document.createElement('td');

  	  emptyTd.setAttribute('colSpan','4');
  	  emptyTd.setAttribute('valign','bottom');
  	  emptyTd.innerHTML = "<b>Other listings in your area</b><br><img src='/images/results_bottom_thin.gif'>";
  	  emptyTd.style.padding='0';
  	  emptyRow.appendChild(emptyTd);
  	  emptyRow.style.height="30px";

      document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(emptyRow);

    } else {

  		var emptyRow = document.createElement('tr');
  		var emptyTd = document.createElement('td');

  	  emptyTd.setAttribute('colSpan','4');
  	  emptyTd.setAttribute('valign','bottom');

  	  if (prevMode == '' && page == 1 && !additionalCriteriaSpecified) {
    	  emptyTd.innerHTML = "<b>Listings in your area</b>";
  	  } else {
    	  emptyTd.innerHTML = "<b>Other listings in your area</b>";
  	  }

  	  emptyTd.style.padding='0';
  	  emptyRow.appendChild(emptyTd);
  	  emptyRow.style.height="30px";

      document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(emptyRow);
    }
  }

	pointData.glatlng = new GLatLng(pointData.latitude, pointData.longitude);

	var flagNumber = Number(index);
	if(pointData.offset) {
    	flagNumber = Number(index) + Number(pointData.offset);
	}
	if(flagNumber>99) {
	   flagNumber = '';
	}
	pointData.icon = new GIcon(baseIcon);
		pointData.icon.image = "http://www.gilbertguide.com/pics/caresearch/googlemap/flag"+flagNumber+".png";
	var focusIcon = new GIcon(baseIcon);
		focusIcon.image = "http://www.gilbertguide.com/pics/caresearch/googlemap/flag"+flagNumber+"_on.png";

	function bringToFront(marker,b) {
		focusIndex = -GOverlay.getZIndex(marker.getPoint().lat());
		return focusIndex;
	}

	pointData.marker = new GMarker(pointData.glatlng, {icon:pointData.icon});
	var focusMarker = new GMarker(pointData.glatlng, {zIndexProcess:bringToFront, icon:focusIcon});

	var popPhotoDiv = document.createElement('div');
		popPhotoDiv.id = 'mappop_photo';
	if (pointData.photo != ""){
		var popPhoto = document.createElement('img');
		popPhoto.src = pointData.photo;
		popPhotoDiv.appendChild(popPhoto);
		popPhotoDiv.style.display = "block";
		var popWidth = '260px';
		var popTop = '-20px';
		var popLeft = '-25px';
	}
	else{
		popPhotoDiv.style.display = "none";
		var popWidth = '180px';
		var popTop = '-20px';
		var popLeft = '-25px';
	}
	var popTitle = document.createElement('h1');
		popTitle.innerHTML = pointData.facility;
	var popAddress = document.createElement('p');
		popAddress.className = 'address';
		if(pointData.address==undefined || pointData.address == '') {
			popAddress.innerHTML = pointData.city + ', ' + pointData.state;
		} else {
			popAddress.innerHTML = pointData.address + '<br />' + pointData.city + ', ' + pointData.state;
		}
	var popPhone = document.createElement('p');
		popPhone.className = 'phone';
		popPhone.innerHTML = pointData.phone;

	oldRow = pointData.listingRow;

	if (thisFile == "search_result"){
		pointData.listingRowPre = document.createElement('tr');
		pointData.listingRow = document.createElement('tr');
		pointData.listingRowPost = document.createElement('tr');

		var tdtop = document.createElement('td');
			tdtop.setAttribute('colSpan','4');
		var topImg = tdtop.appendChild(document.createElement('img'));

    if(pointData.mode == 'showcase') {
      topImg.setAttribute('src','/images/results_top_green.gif');
      topImg.style.width = "425px";
		} else {
			topImg.setAttribute('src','/images/results_top.gif');
      topImg.style.width = "425px";
		}
		
		pointData.listingRowPre.appendChild(tdtop);

    if(pointData.mode == 'showcase' || pointData.mode == 'additional') {
			pointData.listingRow.className = 'results_green';
		}
		var listItemNumber = Number(index) + Number(pointData.offset);


	  pointData.titleRow = document.createElement('tr');
	  var tdleft = document.createElement('td');
      if(pointData.mode == 'showcase') {
  			tdleft.className = 'cell1';
  			tdleft.style.backgroundColor = '#FA7E1C';
  		} else {
  			tdleft.className = 'cell1';
  			tdleft.innerHTML = '&nbsp;';
  		}
	    pointData.titleRow.appendChild(tdleft);
		var tdtop = document.createElement('td');
			tdtop.setAttribute('colSpan','3');
			tdtop.style.padding = '5px';
			tdtop.style.paddingLeft = '10px';
		
  		var linkNameHeader = tdtop.appendChild(document.createElement('div'));
  		  linkNameHeader.className='hdr_top';
  		var listItemHeader = linkNameHeader.appendChild(document.createElement('h4'));
  		var listItemLink = listItemHeader.appendChild(document.createElement('a'));
  			listItemLink.href = pointData.url;
  			listItemLink.innerHTML = pointData.facility;
  			listItemLink.style.fontSize = '14px';
			tdtop.innerHTML = linkNameHeader.innerHTML;
		  pointData.titleRow.appendChild(tdtop);
		
		
		var td0 = document.createElement('td');

    if(pointData.mode == 'showcase') {
			td0.className = 'cell1';
			//td0.innerHTML = '<img src="/images/showcase_result.gif" border=0 width=10/>';
			td0.style.backgroundColor = '#FA7E1C';
		} else {
			td0.className = 'cell1';
			td0.innerHTML = '&nbsp;';
		}

		var td1 = document.createElement('td');
			td1.className = 'cell2 results_pad results_blue_bold';
			td1.setAttribute('vAlign','top');
			td1.innerHTML = listItemNumber + '.';

		var td2 = document.createElement('td');
			td2.className = 'cell3 results_pad2';
			td2.setAttribute('vAlign','top');
		if(pointData.photo) {
			var listItemPhoto = td2.appendChild(document.createElement('img'));
			listItemPhoto.setAttribute('src',pointData.photo);

		} else {
			td2.innerHTML = '&nbsp;';
		}
		
		var td3 = document.createElement('td');
			td3.className = 'cell4 results_pad';
			td3.setAttribute('vAlign','top');

		var linkNameHeader = td3.appendChild(document.createElement('div'));
		  linkNameHeader.className='hdr_top';

		var listItemAddress = linkNameHeader.appendChild(document.createElement('span'));
		if (pointData.address!=undefined && pointData.address != '') {
			//listItemAddress.innerHTML = pointData.address + "<br />";
		}
			listItemAddress.innerHTML += pointData.city + ', ' + pointData.state;

      if (pointData.type == 'HOMECARE' && pointData.source == 'service' && pointData.mode == 'showcase') {
        listItemAddress.innerHTML += "<br/><em>Services this area</em>";
      } else {
        listItemAddress.innerHTML += "<br/>Distance: " + pointData.distance;
      }

// optional seal
  		if(pointData.reviewed == 'yes') {

  		  linkNameHeader.className='hdr_left';

    		var seal = td3.appendChild(document.createElement('div'));

    		seal.className = 'hdr_right';

        var scats = document.getElementById('sCategoryVal');
        if (scats) {
          var cats = scats.value;
          if (cats == 'CCRC' || cats == 'AL' || cats == 'IL' || cats == 'SNF' || cats == 'ADS') {
            seal.innerHTML = '<a href="/jtip/qualityseal.php?msg=service-seal" class="jTip" id="service-seal' + pointData.address + '" ><img border="0" align="left" src="/images/seal_results_sm.gif" alt="Gilbert Guide Quality Approved Care Provider"></a><p>Gilbert Guide Approved</p>';
          } else {
            seal.innerHTML = '<a href="/jtip/qualityseal.php?msg=facility-seal" class="jTip" id="facility-seal' + pointData.address + '" ><img border="0" align="left" src="/images/seal_results_sm.gif" alt="Gilbert Guide Quality Approved Care Provider"></a><p>Gilbert Guide Approved</p>';
          }
        }

        var clr = td3.appendChild(document.createElement('br'));
        clr.clear = 'all';
  		} else if (pointData.mode == 'showcase') {

  		  linkNameHeader.className='hdr_left';

    		var seal = td3.appendChild(document.createElement('div'));

    		seal.className = 'hdr_right';
    		seal.innerHTML = '<img align="left" src="/images/senior_showcase_sm.gif" style="padding-left:14px;" alt="Gilbert Guide Showcase Listing"><p>Showcase<br>Listing</p>';
        var clr = td3.appendChild(document.createElement('br'));
        clr.clear = 'all';
  		}


			if (pointData.mode == 'showcase' || pointData.mode == 'additional') {

  			var listCategorization = td3.appendChild(document.createElement('p'));

  			var tmp = '';

	      if (pointData.costs && pointData.costs != '') {

	        if(tmp)  tmp += ', ';
	        tmp += pointData.costs;
	      }

	      if (pointData.categorization && pointData.categorization != '') {
          if(tmp)  tmp += ', ';
    			tmp += pointData.categorization;
	      }

        if (pointData.extra && pointData.extra != '') {

	        if(tmp)  tmp += ', ';
          tmp += pointData.extra;
        }

			  listCategorization.innerHTML = tmp;

			  var portrait = td3.appendChild(document.createElement('div'));

			  if (pointData.portrait) {
  			  portrait.className = 'portrait';
  			  portrait.innerHTML = pointData.portrait + '<a href="' + pointData.url + '">more</a>';
			  } else {
  			  portrait.className = 'portrait_none';
			  }

        if (additionalCriteriaSpecified) {
  			  var matched = td3.appendChild(document.createElement('div'));
  			  matched.className = 'matched';
  			  matched.innerHTML = 'MATCHED OPTIONS: ' + (pointData.matched ? pointData.matched : '-');
        }
			}

		var td6 = document.createElement('td');
			td6.className = 'cell7 results_pad results_orange';
			td6.setAttribute('vAlign','top');

		var listItemLink1 = td6.appendChild(document.createElement('a'));
			listItemLink1.href = pointData.url;
		var listItemButton = listItemLink1.appendChild(document.createElement('img'));

		  if (pointData.mode == 'showcase') {

			  listItemButton.setAttribute('src',"/images/Org_Details_Button.gif");
			  listItemButton.setAttribute('width','95');

		  } else {

			  listItemButton.setAttribute('src',"/images/Org_Details_Button.gif");
			  listItemButton.setAttribute('width','95');

//			  listItemButton.setAttribute('src',"/images/results_details_blue.jpg");
//			  listItemButton.setAttribute('width','75');
		  }

			listItemButton.className = 'results_imgpad';
			listItemButton.setAttribute('alt','Details');
			listItemButton.setAttribute('border','0');

// add the distance
      if ('service'==pointData.source) {

          td6.innerHTML += '<br><em>SERVICES YOUR AREA</em>';

      } else {

          td6.innerHTML += '<br>' + pointData.distance;
      }

		pointData.listingRow.appendChild(td0);
//		pointData.listingRow.appendChild(td1);
		pointData.listingRow.appendChild(td2);
		pointData.listingRow.appendChild(td3);
//		pointData.listingRow.appendChild(td4);
//		pointData.listingRow.appendChild(td5);
//		pointData.listingRow.appendChild(td6);

		var tdbottom = document.createElement('td');
	  tdbottom.setAttribute('colSpan','4');

		var bottomImg = tdbottom.appendChild(document.createElement('img'));
		if(pointData.mode == 'showcase') {
			bottomImg.setAttribute('src','/images/results_bottom_green.gif');
      bottomImg.style.width = "425px";
		} else {
			bottomImg.setAttribute('src','/images/results_bottom.gif');
      bottomImg.style.width = "425px";
		}
		pointData.listingRowPost.appendChild(tdbottom);
//		pointData.listingRowPost.style.height = '50px';

	 	//alert(document.getElementById('results-table').innerHTML);

	}

	var focusPoint = function(shiftMap) {

		deselectCurrent();
		map.addOverlay(focusMarker);
		pointData.listingRow.className += ' current';
		if (pointData.isNearest == true)
			pointData.nearbyItem.className += ' current';
		if(!document.all)
			mappop = document.getElementById('mappop');
		mappop.replaceChild(popTitle,mappop.getElementsByTagName('h1')[0]);
		mappop.replaceChild(popAddress,mappop.getElementsByTagName('p')[0]);
		//if(pointData.address!=undefined) mappop.replaceChild(popPhone,mappop.getElementsByTagName('p')[1]);
		mappop.replaceChild(popPhotoDiv,document.getElementById('mappop_photo'));
		mappop.style.width = popWidth;
		mappop.style.top = popTop;
		mappop.style.left = popLeft;
		mappop.style.display = 'block';
		deselectCurrent = function() {
			map.removeOverlay(focusMarker);
			pointData.listingRow.className = pointData.listingRow.className.replace('current', '');
			if (pointData.isNearest == true)
				pointData.nearbyItem.className = pointData.nearbyItem.className.replace('current', '');
			mappop.style.display = 'none';
		};
		if (shiftMap == true) map.panTo(pointData.glatlng);
		return false;
	}



	var unfocusPoint = function(){
		deselectCurrent();
	}

	var getListing = function(){
		window.location = pointData.url;
	}

	GEvent.addListener(pointData.marker, 'mouseover', function() { focusPoint(false); });
	pointData.listingRow.onmouseover = function() { focusPoint(true); };

	GEvent.addListener(focusMarker, 'mouseout', unfocusPoint);
	pointData.listingRow.onmouseout = unfocusPoint;

	GEvent.addListener(focusMarker, 'click', getListing);

	if (oldRow == undefined){
        if(pointData.listingRowPre) {
            document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(pointData.listingRowPre);
        };
        document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(pointData.titleRow);
        document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(pointData.listingRow);
        if(pointData.listingRowPost) {
            document.getElementById('results-table').getElementsByTagName('tbody')[0].appendChild(pointData.listingRowPost);
        };
	}
	else{
		document.getElementById('results-table').getElementsByTagName('tbody')[0].replaceChild(pointData.listingRow, oldRow);
	}

	map.addOverlay(pointData.marker);
}




function createMarkers(newMarkers) {
	map.clearOverlays();
	var bounds = new GLatLngBounds();
	var i;
	var mode = '';
	for(markerIndex in newMarkers) {

		if (markerIndex >0){

			initializePoint(newMarkers[markerIndex],markerIndex,filename,mode);

			mode = newMarkers[markerIndex].mode;

			i = markerIndex;
			bounds.extend(newMarkers[markerIndex].glatlng);
		};
	}

	if (newMarkers[0].latitude != undefined && newMarkers[0].longitude != undefined){
		newMarkers[0].glatlng = new GLatLng(newMarkers[0].latitude, newMarkers[0].longitude);
	};
	if (newMarkers[0].glatlng != undefined){
		newMarkers[0].icon = new GIcon(baseIcon);
		newMarkers[0].icon.image = "http://www.gilbertguide.com/pics/caresearch/googlemap/flag0.png";
		newMarkers[0].marker = new GMarker(newMarkers[0].glatlng, newMarkers[0].icon);
		map.addOverlay(newMarkers[0].marker);
		bounds.extend(newMarkers[0].glatlng);
	};
		map.setZoom(map.getBoundsZoomLevel(bounds));
		map.setCenter(bounds.getCenter());

}

var hasStreetView = false;

function init() {
  var scats = document.getElementById('sCategoryVal');

  if (scats) {

    cats = document.getElementById('sCategoryVal').value;

    if (cats=='AL' || cats=='SNF' || cats=='CCRC' || cats=='ADS' || cats=='IL' ) {

      document.getElementById("mapwrapper").style.display="";

    } else {

      document.getElementById("mapwrapper").style.display="none";
    }
  }

	if (typeof(markers) != 'undefined'){

	  if ( typeof(ovrMapWidth)  != 'undefined' && typeof(ovrMapHeight)  != 'undefined' ) {

		  map = new GMap2(document.getElementById("map"), { size:new GSize(ovrMapWidth, ovrMapHeight) } );

	  } else {

		  map = new GMap2(document.getElementById("map"));
	  }

		map.addControl(new GSmallMapControl());

		map.removeMapType(G_HYBRID_MAP);
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
		createMarkers(markers);

		if (! markers[1]) {
				var thisLoc = markers[0].glatlng;
    		
				streetviewClient = new GStreetviewClient();
				streetviewClient.getNearestPanoramaLatLng(thisLoc, function(d) { 
					if (d) {    
						panoramaOptions = { latlng:d };
		    		myPano = new GStreetviewPanorama(document.getElementById("street"), panoramaOptions);
						document.getElementById("toggle").style.display="block";
						setMode(0);
					}
			});
		}
		
		var nearestSearchForm = document.getElementById('address-search');
		var getDirectionsForm = document.getElementById('get-directions');
		if (nearestSearchForm != undefined)
			nearestSearchForm.onsubmit = handleNearestSearch;
		else if (getDirectionsForm != undefined){
			var fullDestAddress = '';
			if(markers[0].address != undefined) fullDestAddress = fullDestAddress + markers[0].address;
			if(markers[0].city != undefined) fullDestAddress = fullDestAddress + ', ' + markers[0].city;
			if(markers[0].state != undefined) fullDestAddress = fullDestAddress + ', ' + markers[0].state;
			if(markers[0].zip != undefined) fullDestAddress = fullDestAddress + ', ' + markers[0].zip;
			getDirectionsForm.onsubmit = function(){handleGetDirections(fullDestAddress)};
		}
	}

	if (JT_init) JT_init();
}

window.onload = init;
window.onunload = GUnload;