var geocoder;   
var map;  
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var contentStrings = new Array();
var marker = new Array();
var i = 1;
var isMobileWindow = 0;
var defaultzoom = 12;
var fishmarkersArray = [];

var standardlat = "48.2000341";
var standardlong = "-121.1111068";

// console.log("defaultzoom: "+defaultzoom+", zoomoverride: "+zoomoverride);
// if(zoomoverride > 0)
// {
// 	defaultzoom = zoomoverride;
// }

if(defaultlat != "")
{
	standardlat = defaultlat;
}

if(defaultlong != "")
{
	standardlong = defaultlong;
}

function initializeMap() 
{   
	geocoder = new google.maps.Geocoder();     
	// var latlng = new google.maps.LatLng(45.334047,-122.598767); 
	var latlng = new google.maps.LatLng(standardlat,standardlong); 
	var myOptions = { 
	  zoom: defaultzoom, //Comment Out
	  center: latlng, 
	  mapTypeId: google.maps.MapTypeId.ROADMAP,
	  scrollwheel: false 
	}; 
	
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
}

function toggleWhatsNearby()
{
    var whatsnearbytabDiv = document.getElementById("whatsnearbytab");
    //alert(whatsnearbytabDiv.style.marginLeft);
    if(whatsnearbytabDiv.style.top == "1px")
    {
        $("#whatsnearbytab").animate({ top: drawerouterposition},500, 'swing'); //draweroutposition set in whatsnearbyinclude
        $("#whatsnearbycategories").animate({ top: '1'},500, 'swing');
    }
    else
    {
        $("#whatsnearbytab").animate({ top: '1'},500, 'swing');
        $("#whatsnearbycategories").animate({ top: '-'+drawerouterposition},500, 'swing');  //draweroutposition set in whatsnearbyinclude
    }
}//end function

function clearMap()
{
	var placeholder = 1;
	// alert("Length 2: " + marker.length);

	for (var c = 1; c < marker.length; c++) {

		// if (typeof marker[c] !== 'undefined') {
		//     marker[c].setMap(null);
		// }
    	// marker[c].setMap(null);
    	try {
		    marker[c].setMap(null);
		}
		catch(err) {
		    // document.getElementById("demo").innerHTML = err.message;
		}
	}

	marker.length = 0;
	marker = new Array();
	i = 1;
	contentStrings = new Array();
	bounds = new google.maps.LatLngBounds();

	$("#listingcontentdiv").html("");
}

function clearWhatsNearby()
{
	$("input:checkbox").attr('checked', false);
	clearMap();
	initializeMap();				
}

function toggleVenue(venuediv)
{
	jQuery("#"+venuediv).slideToggle();
	var pm = document.getElementById("plusMinus-"+venuediv);
	if(pm.innerHTML == "+"){pm.innerHTML = '-';} else {pm.innerHTML = '+';}
}

function getAccounts()
{
	// alert("I is: "+i);
	if(isMobileWindow == 1)
	{
		hideCategorySelection();
	}

	clearMap();
	initializeMap();
	// toggleWhatsNearby();

	var listingcontent = "";

	// var viewButton = document.getElementById("btnStartMap");
	// document.getElementById("btnStartMap").value= "Loading...";
	// viewButton.value = "Loading...";

	var currCkb;
	var executeAccountsCall = 0;
	var catselctions = "";
	var catselectioncount = 1;
	var hideloadingnow = 10;

	for(b = 1; b <= subCatCkbCount; b++)
	{
		currCkb = document.getElementById("ckb"+b);
		// currCkb = document.getElementsByName("ckb"+b);

		if(currCkb.checked == 1)
		{
			if(catselectioncount > 1)
			{
				catselctions += "-";							
			}
			
			catselctions += currCkb.value;

			catselectioncount++;
			executeAccountsCall = 1;
		}//end if currCkb.checked == 1

	}//end for b

	var attselections = "";

	for(c = 1; c <= attCkbCount; c++)
	{
		currCkb = document.getElementById("attckb"+c);
		// currCkb = document.getElementsByName("ckb"+b);

		if(currCkb.checked == 1)
		{
			attselections += "&atts%5B%5D="+currCkb.value;
			executeAccountsCall = 1;
		}//end if currCkb.checked == 1
	}

	var RegionSelections = "";

	$('.WhatsNearbyRegionCkb').each(function() {
		if(this.checked)
		{
			RegionSelections += "&region%5B%5D="+$(this).val();
			executeAccountsCall = 1;
	    }
	});

	// console.log("Regions: "+RegionSelections);

	if(executeAccountsCall == 1)
	{
		hideloadingnow--;
		// document.getElementById('btnStartMap').value= 'Loading...';
		document.getElementById('mapLoading').style.display = 'block';
		document.getElementById('mapLoadingText').style.display = 'block';

	    xmlhttp=new XMLHttpRequest();

	    xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				// console.log("Results: |"+xmlhttp.responseText+"|");

				if(xmlhttp.responseText != "noresults")
				{
					// alert(xmlhttp.responseText);

					// document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
					var parser = new DOMParser();
					var xmlDoc = parser.parseFromString(xmlhttp.responseText, "text/xml");

					// alert(xmlDoc);
					// alert("Length 1: " + marker.length);

					var accounts = xmlDoc.getElementsByTagName("account");
					// var regionselection = document.getElementById("mapexplorerregion");
					// var regionselectionvalue = regionselection.options[regionselection.selectedIndex].value;

					// var selectedRegionArray;

					// if(regionselectionvalue == 1) { selectedRegionArray = albanyarray; }
					// else if(regionselectionvalue == 2) { selectedRegionArray = corvallisarray; }
					// else if(regionselectionvalue == 3) { selectedRegionArray = eugenearray; }
					// else if(regionselectionvalue == 4) { selectedRegionArray = mthoodarray; }
					// else if(regionselectionvalue == 5) { selectedRegionArray = salemarray; }
					// else if(regionselectionvalue == 6) { selectedRegionArray = yamhillarray; }

					// alert("Selected: "+selectedRegionArray[0]);
					// alert("Index is: "+indexOf(selectedRegionArray, 97456));

					// alert(accounts.length);
					var missingaccounttext = "";

					// alert(accounts[0].childNodes[0].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", ""));
					// alert("Total: "+accounts.length);

					var otheritemslinkset = 0;

					listingcontent = "<div class='PageContent' style='margin-top:10px; margin-bottom:10px;'>"+accounts.length+" Results";

					if(subcatpriority.length > 0)
					{
						listingcontent += " (<a style='cursor:pointer; text-decoration:none;' onclick='scrollToOtherResults()'>Other Results</a>)";
					}

					listingcontent += "</div>";

					for (j=0;j<accounts.length;j++)
					{
						var accountnameitem = accounts[j].childNodes[1].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var latitudeitem = accounts[j].childNodes[3].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var longitudeitem = accounts[j].childNodes[5].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var address1item = accounts[j].childNodes[7].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var cityitem = accounts[j].childNodes[9].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var stateitem = accounts[j].childNodes[11].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var zipCodeitem = accounts[j].childNodes[13].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var websiteitem = accounts[j].childNodes[15].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var accounttypeitem = accounts[j].childNodes[17].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var phoneitem = accounts[j].childNodes[19].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var accountiditem = accounts[j].childNodes[21].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var initineraryitem = accounts[j].childNodes[23].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var accountimageitem = accounts[j].childNodes[25].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var accountdescitem = accounts[j].childNodes[27].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var accountadaitem = accounts[j].childNodes[29].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var accountapptitem = accounts[j].childNodes[31].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var accountbathroomitem = accounts[j].childNodes[33].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var accountpetitem = accounts[j].childNodes[35].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var accountfeeitem = accounts[j].childNodes[37].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var categorylistitem = accounts[j].childNodes[39].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var accountnameconverteditem = accounts[j].childNodes[41].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var accountlongdescitem = accounts[j].childNodes[43].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var facebookitem = accounts[j].childNodes[45].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var twitteritem = accounts[j].childNodes[47].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var youtubeitem = accounts[j].childNodes[49].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var amenitiesitem = accounts[j].childNodes[51].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var priorityitem = accounts[j].childNodes[53].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var featuredmemberitem = accounts[j].childNodes[55].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
						var outdooractiveitem = accounts[j].childNodes[57].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");

						// console.log("Account: "+accountnameitem);

						// var passesfilter = 0;
						var passesfilter = 1;

						// if(regionselectionvalue == 0)
						// {
						// 	passesfilter = 1;
						// }
						// else if(regionselectionvalue > 0 && indexOf(selectedRegionArray, zipCodeitem) > -1)
						// {
						// 	passesfilter = 1;
						// }

						if(limitdistance == 1)
						{
							if(distance(parseFloat(latitudeitem),parseFloat(longitudeitem),defaultlat,defaultlong) > limitdistancenumber)
							{
								passesfilter = 0;
							}
						}

						var latlng = null;

						if(passesfilter == 1 && accountiditem != accountiditemvalue)
						{
							if( latitudeitem != "" && latitudeitem != "0.000000" && latitudeitem != " "
							    && longitudeitem != "" && longitudeitem != "0.000000" && longitudeitem != " " 
								)
							{
								// alert(accountnameitem+" ("+latitudeitem+","+longitudeitem+")");
								latlng = new google.maps.LatLng(parseFloat(latitudeitem), parseFloat(longitudeitem));
								setAccountMarker(latlng,accountnameitem, latitudeitem, longitudeitem, address1item, cityitem, stateitem, zipCodeitem, websiteitem, accounttypeitem, phoneitem, accountiditem, initineraryitem, accountimageitem, accountdescitem, categorylistitem, accountnameconverteditem, accountlongdescitem, amenitiesitem, priorityitem, outdooractiveitem, i)
								i++;

							}
							else if( address1item != "" && cityitem != "" && stateitem != "" && zipCodeitem != "")
							{
								geoCodeLookup(latlng,accountnameitem, latitudeitem, longitudeitem, address1item, cityitem, stateitem, zipCodeitem, websiteitem, accounttypeitem, phoneitem, accountiditem, initineraryitem, accountimageitem, accountdescitem, categorylistitem, accountnameconverteditem, accountlongdescitem, amenitiesitem, priorityitem, outdooractiveitem, i)
							}
						}

					}//end for j

		   		}//if orbxml not empty
		   		else
		   		{
		   			$("#noresultsdiv").show(0).delay(1000).fadeOut(500);
		   		}

		   		listingcontent += "<div class='clear'></div>";

				hideloadingnow++;
				if(hideloadingnow == 10)
				{
					document.getElementById('mapLoading').style.display = 'none';
					document.getElementById('mapLoadingText').style.display = 'none';
				}
			}//end if readystate
		};

		// alert(catselctions);

		/* New xml accounts (non-legacy) */
		console.log("GET","/functions/xmlaccounts.php?b="+new Date().getTime()+"&cats="+catselctions+"&priority="+subcatpriority+attselections+RegionSelections);
	    xmlhttp.open("GET","/functions/xmlaccounts.php?b="+new Date().getTime()+"&cats="+catselctions+"&priority="+subcatpriority+attselections+RegionSelections,true);

	    /* Legacy xml accounts */
		//console.log("GET","/functions/legacyxmlaccounts.php?b="+new Date().getTime()+"&cats="+catselctions+attselections);
	    //xmlhttp.open("GET","/functions/legacyxmlaccounts.php?b="+new Date().getTime()+"&cats="+catselctions+attselections,true);

		xmlhttp.send();

		// var xml = xmlhttp.responseXML;

		// alert(xml);

		// var accounts = xml.getElementsByTagName("account");

	}//end if executeAccountsCall == 1;

	// var currFishCkb;
	// var executeFishCall = 0;
	// var fishselections = "";
	// var fishselectioncount = 0;

	// for(b = 1; b <= fishcount; b++)
	// {
	// 	currFishCkb = document.getElementById("ckbfish"+b);

	// 	if(currFishCkb.checked == 1)
	// 	{
	// 		fishselectioncount++;
	// 		if(fishselectioncount > 1)
	// 		{
	// 			fishselections += "-";							
	// 		}
			
	// 		fishselections += currFishCkb.value;
	// 		executeFishCall = 1;
	// 	}//end if currFishCkb.checked == 1

	// }//end for b

	// var fishbaitselections = "";
	// var fishbaitselectioncount = 0;

	// for(b = 1; b <= fishbaitcount; b++)
	// {
	// 	currFishCkb = document.getElementById("ckbfishbait"+b);

	// 	if(currFishCkb.checked == 1)
	// 	{
	// 		fishbaitselectioncount++;
	// 		if(fishbaitselectioncount > 1)
	// 		{
	// 			fishbaitselections += "-";							
	// 		}
			
	// 		fishbaitselections += currFishCkb.value;
	// 		executeFishCall = 1;
	// 	}//end if currFishCkb.checked == 1

	// }//end for b

	// var fishnathatselections = "";
	// var fishnathatselectioncount = 0;

	// for(b = 1; b <= fishnathatchcount; b++)
	// {
	// 	currFishCkb = document.getElementById("ckbnativehatchery"+b);

	// 	if(currFishCkb.checked == 1)
	// 	{
	// 		fishnathatselectioncount++;
	// 		if(fishnathatselectioncount > 1)
	// 		{
	// 			fishnathatselections += "-";							
	// 		}
			
	// 		fishnathatselections += currFishCkb.value;
	// 		executeFishCall = 1;
	// 	}//end if currFishCkb.checked == 1

	// }//end for b

	// var fishaccselections = "";
	// var fishaccselectioncount = 0;

	// for(b = 1; b <= fishacccount; b++)
	// {
	// 	currFishCkb = document.getElementById("ckbaccessibility"+b);

	// 	if(currFishCkb.checked == 1)
	// 	{
	// 		fishaccselectioncount++;
	// 		if(fishaccselectioncount > 1)
	// 		{
	// 			fishaccselections += "-";							
	// 		}
			
	// 		fishaccselections += currFishCkb.value;
	// 		executeFishCall = 1;
	// 	}//end if currFishCkb.checked == 1

	// }//end for b

	// if(executeFishCall == 1)
	// {
	// 	hideloadingnow--;
	// 	document.getElementById('mapLoading').style.display = 'block';
	// 	document.getElementById('mapLoadingText').style.display = 'block';

	// 	// console.log("Fish: "+fishselections+"; Bait: "+fishbaitselections+"; NatHat: "+fishnathatselections+"; Acc: "+fishaccselections);
	// 	console.log("/functions/xmlwaterway.php?fish="+fishselections+"&bait="+fishbaitselections+"&breeding="+fishnathatselections+"&acc="+fishaccselections);
	// 	jQuery.ajax({
	// 		type: "GET",
	// 		url: "/functions/xmlwaterway.php",
	// 		data: { fish: fishselections,
	// 				bait: fishbaitselections,
	// 				breeding: fishnathatselections,
	// 				acc: fishaccselections 
	// 			  },
	// 		success: function(msg) {

	// 			var xmlDoc = $.parseXML( msg ); 
	// 			var $xml = $(xmlDoc);

	// 			var $waterway = $xml.find("waterway");

	// 			$waterway.each(function(){

	// 		    var TrailID = $(this).find('TrailID').text(),
	// 		    	TrailName = $(this).find('TrailName').text(),
	// 		    	TrailDescription = $(this).find('TrailDescription').text(),
	// 		    	ParentID = $(this).find('ParentID').text(),
	// 		    	WeatherZipCode = $(this).find('WeatherZipCode').text(),
	// 		    	Latitude = $(this).find('Latitude').text(),
	// 		    	Longitude = $(this).find('Longitude').text(),
	// 		    	Colorvalue = $(this).find('Colorvalue').text(),
	// 		    	FishTypes = $(this).find('FishTypes').text(),
	// 		    	FishBait = $(this).find('FishBait').text(),
	// 		    	FishBreeding = $(this).find('FishBreeding').text(),
	// 		    	Season = $(this).find('Season').text(),
	// 		    	Accessibility = $(this).find('Accessibility').text(),
	// 		    	Weather = $(this).find('Weather').text();

	// 		    	// console.log("Trail Name: "+TrailName);
	// 		    	if(Latitude.length > 0 && Longitude.length > 0)
	// 		    	{
	// 		    		var fishlatlngItem = new google.maps.LatLng(parseFloat(Latitude), parseFloat(Longitude));
	// 		    		bounds.extend(fishlatlngItem);

	// 		    		var poiLocation = new google.maps.LatLng(parseFloat(Latitude), parseFloat(Longitude));

	// 					var fishcontent =  "<div id='content' align='left' style='max-width:400px;'>"; 
	// 					fishcontent +=			"<div id='siteNotice'></div>";
	// 					fishcontent += 			"<div align='left' class='GMapMarkerHeader PageHeader' style='font-size:20px; margin-bottom:0px;'><strong>"+TrailName+"</strong></div>";
	// 					fishcontent +=  		"<div id='bodyContent' class='GMapMarkerContent'>";
						
	// 					if(TrailDescription.length > 0)
	// 					{
	// 						fishcontent +=          	TrailDescription;
	// 					}
						
	// 					if(FishTypes.length > 0)
	// 					{
	// 						fishcontent += 				"<div style=\'margin-top:7px;\'><strong>Fish: </strong>"+FishTypes+"</div>";
	// 					}
	// 					if(FishBait.length > 0)
	// 					{
	// 						fishcontent += 				"<div style=\'margin-top:7px;\'><strong>Fish Bait: </strong>"+FishBait+"</div>";
	// 					}
	// 					if(FishBreeding.length > 0)
	// 					{
	// 						fishcontent += 				"<div style=\'margin-top:7px;\'><strong>Fish Breeding: </strong>"+FishBreeding+"</div>";
	// 					}
	// 					if(Season.length > 0)
	// 					{
	// 						fishcontent += 				"<div style=\'margin-top:7px;\'><strong>Season: </strong>"+Season+"</div>";
	// 					}
	// 					if(Accessibility.length > 0)
	// 					{
	// 						fishcontent += 				"<div style=\'margin-top:7px;\'><strong>Accessibility: </strong>"+Accessibility+"</div>";
	// 					}

	// 					if(Weather.length > 0)
	// 					{
	// 						fishcontent +=          	Weather;
	// 					}

	// 					fishcontent += 					"<br/<br/>";
	// 					fishcontent += 			"</div>";
	// 					fishcontent += 		"</div>";

	// 					placeFishMarker(poiLocation,TrailName,fishcontent,Colorvalue,TrailID);
	// 		    	}

	// 			}); //end each

	// 			map.fitBounds(bounds);

	// 			hideloadingnow++;
	// 			if(hideloadingnow == 10)
	// 			{
	// 				document.getElementById('mapLoading').style.display = 'none';
	// 				document.getElementById('mapLoadingText').style.display = 'none';
	// 			}
	// 			// console.log(msg);
	// 		}
	// 	});
	// }
	// // else
	// // {
	// // 	console.log("No Fish Search Selected");
	// // }

}//end function getAccounts

var loadingintervalobject = setInterval('animateLoading()', 700);

var loadingcount = 1;

function animateLoading()
{
	var loadingdivvar = document.getElementById("mapLoadingText");
	//if(loadingcount == 1){loadingdivvar.innerHTML = 'Loading';}
	if(loadingcount == 1){loadingdivvar.innerHTML = 'Loading';}
	else if(loadingcount == 2){loadingdivvar.innerHTML = 'Loading.';}
	else if(loadingcount == 3){loadingdivvar.innerHTML = 'Loading..';}
	else if(loadingcount == 4){loadingdivvar.innerHTML = 'Loading...'; loadingcount = 0; }
	
	loadingcount++;
}

function distance(lat1, lon1, lat2, lon2) {
  var p = 0.017453292519943295;    // Math.PI / 180
  var c = Math.cos;
  var a = 0.5 - c((lat2 - lat1) * p)/2 + 
          c(lat1 * p) * c(lat2 * p) * 
          (1 - c((lon2 - lon1) * p))/2;

  var distInKm = 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km
  return distInKm * 0.6; //distance in miles
}

function openInfowWindow(thismarker)
{
	return function() {         
			var thisPosition = thismarker.getPosition();
			infowindow.close();    
			infowindow.setContent(contentStrings[thisPosition.lat()+thisPosition.lng()]);     
			infowindow.open(map, thismarker);	
	};//end function
} //end function openInfowWindow

function setMapWidth()
{
	var windowwidth = $(window).width();

	if(windowwidth > 800)
	{		
        $('#whatsnearbycategories').css('left', "0px");
        $('#map_canvas').css('left', '300px');
        $('#map_canvas').css('width', (windowwidth - 300)+"px");
        $('#mobileCategoryMenuButton').hide();
        isMobileWindow = 0;
	}
	else
	{
        $('#whatsnearbycategories').css('left', "-300px");
        $('#map_canvas').css('left', '0px');
        $('#map_canvas').css('width', windowwidth+"px");
        $('#mobileCategoryMenuButton').show();
        isMobileWindow = 1;
	}
}

function displayCategorySelection()
{
    var cssvars = {'left' : '0px'};
    $( '#whatsnearbycategories' ).animate(cssvars,'fast');
    $( "#map_canvas" ).click(function() {
          hideCategorySelection();
    });
}

function hideCategorySelection()
{
    var cssvars = {'left' : '-300px'};
    $( '#whatsnearbycategories' ).animate(cssvars,'fast');
    $( "#map_canvas").unbind( "click" );
}

function placeFishMarker(location, title, contentstring, colorvalue, trailid) 
{
    // first remove all markers if there are any
    // deleteOverlays();

    /******* When not assigning colors *************/
    // var marker = new google.maps.Marker({
    //     position: location, 
    //     map: map,
    //     draggable: true
    // });

    /******* When assigning colors *************/
	// var pinColor = colorvalue;
//       var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
	// 									        new google.maps.Size(21, 34),
	// 									        new google.maps.Point(0,0),
	// 									        new google.maps.Point(10, 34));

	var pinShadow = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_shadow",
										         new google.maps.Size(40, 37),
										         new google.maps.Point(0, 0),
										         new google.maps.Point(12, 35));

	var marker = new google.maps.Marker({ position: location, 
							              map: map,
							              icon: '/images/Fish-Marker-small.png',
							              shadow: pinShadow,
							              title: title
									    });        // add marker in markers array
    fishmarkersArray.push(marker);

    var infowindow = new google.maps.InfoWindow({ content: contentstring });
			
	google.maps.event.addListener(marker, 'click', function() {
								   						infowindow.open(map,marker);
								   						highlightWaterway(trailid,colorvalue); 
													});
}//end function placeFishMarker

function highlightWaterway(trailid, colorvalue)
{
	// alert("Trail:"+trailid+", Color: "+colorvalue);

	var trailpoints = [];
    xmlhttp=new XMLHttpRequest();

    xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			if(xmlhttp.responseText != "noresults")
			{
				var parser = new DOMParser();
				var xmlDoc = parser.parseFromString(xmlhttp.responseText, "text/xml");

				var accounts = xmlDoc.getElementsByTagName("latlongitem");
				var missingaccounttext = "";

				for (j=0;j<accounts.length;j++)
				{
					var latitudeitem = accounts[j].childNodes[1].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");
					var longitudeitem = accounts[j].childNodes[3].firstChild.nodeValue.replace("<![CDATA[", "").replace("]]>", "");

					// alert(latitudeitem)

					if(latitudeitem != "" && latitudeitem != "0.000000" && latitudeitem != " "
					    && longitudeitem != "" && longitudeitem != "0.000000" && longitudeitem != " "  )
					{
						latlngItem = new google.maps.LatLng(parseFloat(latitudeitem), parseFloat(longitudeitem));
						trailpoints.push(latlngItem)
					}
				}//end for j

				var trailPath = new google.maps.Polyline({  path: trailpoints,     
															strokeColor: "#"+colorvalue,     
															strokeOpacity: 0.7,     
															strokeWeight: 5   });
			
				trailPath.setMap(map);
		   		// map.fitBounds(bounds);
	   		}//if orbxml not empty

		}//end if readystate
	}

    xmlhttp.open("GET","/functions/xmltraillatlong.php?trailid="+trailid+"&b="+new Date().getTime(),true);
	xmlhttp.send();

	// var xml = xmlhttp.responseXML;
	// alert(xml);
	// var accounts = xml.getElementsByTagName("account");
}//end function highlightWaterway

function geoCodeLookup(latlng,accountnameitem, latitudeitem, longitudeitem, address1item, cityitem, stateitem, zipCodeitem, websiteitem, accounttypeitem, phoneitem, accountiditem, initineraryitem, accountimageitem, accountdescitem, categorylistitem, accountnameconverteditem, accountlongdescitem, amenitiesitem, priorityitem, outdooractiveitem, i)
{
	var geocoder = new google.maps.Geocoder();
	var lookupaddressvalue = address1item+', '+cityitem+', '+stateitem+' '+zipCodeitem;
	geocoder.geocode( { 'address' : lookupaddressvalue }, function( results, status ) {
        if( status == google.maps.GeocoderStatus.OK ) 
        {
			// latlng = results[0].geometry.location;
			latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
			console.log("Geocode Found: "+latlng);
			setAccountMarker(latlng,accountnameitem, latitudeitem, longitudeitem, address1item, cityitem, stateitem, zipCodeitem, websiteitem, accounttypeitem, phoneitem, accountiditem, initineraryitem, accountimageitem, accountdescitem, categorylistitem, accountnameconverteditem, accountlongdescitem, amenitiesitem, priorityitem, outdooractiveitem, i)
			i++;

			jQuery.ajax({
				type: "POST",
				url: "/functions/saveaccountlatlong.php",
				data: { AccountID: accountiditem,
						Latitude: results[0].geometry.location.lat(), 
						Longitude: results[0].geometry.location.lng()
					  },
				success: function(msg) {
					// document.getElementById("imageloadergifsocialroller").style.display = 'none';
					// alert("It worked!");
		    	  	console.log(accountnameitem+" LatLong: "+msg);
				}
			});

            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            // map.setCenter( results[0].geometry.location );
            // var marker = new google.maps.Marker( {
            //     map     : map,
            //     position: results[0].geometry.location
            // } );
        } 
        else 
        {
            console.log( 'Geocode was not successful for the following reason: ' + status );
        }
    } );
}

function setAccountMarker(latlng,accountnameitem, latitudeitem, longitudeitem, address1item, cityitem, stateitem, zipCodeitem, websiteitem, accounttypeitem, phoneitem, accountiditem, initineraryitem, accountimageitem, accountdescitem, categorylistitem, accountnameconverteditem, accountlongdescitem, amenitiesitem, priorityitem, outdooractiveitem, ivalue)
{
	// console.log(accountnameitem);
	var i = ivalue;
	// console.log("I Value: "+i);

	var icon = null;

	if(accounttypeitem != "" && accounttypeitem != " ")
	{
		icon = {
		    url: '/images/mapicons/'+accounttypeitem, // url
		    scaledSize: new google.maps.Size(50, 50)//, // scaled size
		    //origin: new google.maps.Point(0,0), // origin
		    //anchor: new google.maps.Point(0, 0) // anchor
		};
		// marker[i] = new google.maps.Marker({ position: latlng, 
		//  									 icon: '/images/mapicons/'+accounttypeitem }); 
	}
	else
	{
		icon = {
		    url: '/images/mapicons/map-icon-destination.png', // url
		    scaledSize: new google.maps.Size(50, 50)//, // scaled size
		    //origin: new google.maps.Point(0,0), // origin
		    //anchor: new google.maps.Point(0, 0) // anchor
		};
		// marker[i] = new google.maps.Marker({ position: latlng, 
		// 									 icon: '/images/mapicons/iconr.png' }); 
	}

	marker[i] = new google.maps.Marker({ position: latlng, 
											 icon: icon }); 


	marker[i].setMap(map);
	bounds.extend(latlng);
	// map.setCenter(latlng);

	marker[i].setTitle(accountnameitem);

	var contentString = '<div id="content" align="left">'+ 
							'<div id="siteNotice">'+'</div>'+ 
							'<div>';

	if(accountimageitem != " ")
	{
		contentString += '      <div style="float:left; width:170px; height:170px; overflow:hidden; margin-right:10px;">'+ 
									'<img src="'+accountimageitem+'" style="max-height:170px;"/>'+
								'</div>';
	}

	contentString += '           <div style="float:left; max-width:300px;">';
	contentString += 				'<div align="left" class="GMapMarkerHeader">';
	contentString += 					'<a href="/account/'+accountnameconverteditem;

	if(outdooractiveitem != ' ')
	{
		contentString += 					'#ipd='+outdooractiveitem;
	}

	contentString +=						'" target="_blank">';
	contentString += 						'<span class="PageHeader" style="font-size:24px; color: #3398d5;">'+accountnameitem+'</span>';
	contentString += 					'</a>';
	contentString += 				'</div>';
	contentString += 				'<div id="bodyContent" class="GMapMarkerContent">';							
  
  	var website = null;
  	if(websiteitem != null)
  	{
	 	website = websiteitem; 
	 	if(website.indexOf(".") != -1 && website.indexOf("http") == -1)
	 	{
			website = "http://" + website;  
	 	}
  	}
	
	//$directionsLink = "http://maps.google.com/maps?daddr=Sundial+Bridge,+Redding,+CA
	if(address1item != "" && address1item != null && address1item != ', ' && address1item != " ")
 	{
 	   // console.log("address1item: '"+address1item+"'");
	   var directionsLink = 'http://maps.google.com/maps?daddr='+address1item+',+'+cityitem+'+'+stateitem+'+'+zipCodeitem;
  	}
  	else if(latitudeitem != " " && longitudeitem != " ")
  	{
	   var directionsLink = 'http://maps.google.com/maps?daddr='+latitudeitem+','+longitudeitem;
  	}
  	else 
  	{
		// var directionsLink = 'http://maps.google.com/maps?daddr='+latitudeitem+','+longitudeitem;
		var directionsLink = '';
  	}

	if(address1item != "" && address1item != null && address1item != ', ' && address1item != ' ')
	{
		if(address1item != " ")
		{
			contentString += address1item+'<br/>';
		}
		contentString += cityitem+' '+stateitem+' '+zipCodeitem;
	}

	contentString += '<table>';

	contentString += '<tr><!--<td><img src="/images/listing-map-pin.png" alt="Directions" title="Directions" style="max-width:20px;"/></td>--><td>';
	if(directionsLink != '')
	{
		contentString += '<a href="'+directionsLink.replace(" ", "+")+'" target="_blank">Get Directions</a>';
	}
	else
	{
		contentString += 'Contact Business for Exact Address';
	}
	contentString += '</td></tr>';
	
	if(website != "")
	{
		contentString += '<tr><!--<td><img src="/images/website-icon-22.png" alt="Website" title="Website" style="max-width:20px;"/></td>--><td><a class="map-click-external-link" href="'+website+'" target="_blank">View Website</a></td></tr>';
	}

	if(phoneitem != "" && phoneitem != null)
	{
		contentString += '<tr><!--<td><img src="/images/Mobile-Phone-icon.png" alt="Phone" title="Phone" style="max-width:20px;"/></td>--><td><a class="map-click-external-link" href="tel:'+phoneitem+'" target="_blank">'+phoneitem+'</a></td></tr>';
		// listingcontent += '<span style="color:#f24842; margin-left:20px;">'+phoneitem+'</span>';
	}

	contentString += 	'<div style="display: table-cell; vertical-align: top; width: 160px;">';
	contentString += 		'<div id="MapAddTrip'+accountiditem+'" class="PageContent" style="cursor: pointer; width: 150px; border: 1px solid #4D2F47; text-align: center; font-size: 14px; height: 28px; line-height: 28px; margin-top: 3px;" onclick="'; 
		if(initineraryitem == 'x'){ contentString += "openItinerary();"; } else{ contentString += "addToItinerary('"+accountiditem+"');"; } contentString +='">';
	
	if(initineraryitem == 'x')
	{ 
		contentString += "IN TRIP - VIEW"; 
	} 
	else
	{ 
		contentString += "ADD TO MY TRIP"; 
	}
	
	contentString +=		'</div>';
	contentString +=	'</div>';	

	contentString += '</table>';

	contentString += '		</div></div><div class="clear"></div>';

	if(accountdescitem != "")
	{
		contentString += '	<div style="width:100%; max-width:400px; margin-top:5px; margin-bottom:5px;">'+accountdescitem+'</div>';
	}

	contentString += 	'</div>'+
					'</div>'; 

	var markerPosition = marker[i].getPosition();
	contentStrings[markerPosition.lat()+markerPosition.lng()] = contentString;
					
	google.maps.event.addListener(marker[i], 'click', openInfowWindow(marker[i]));	

	setBoundaryAndZoom();
}

function setBoundaryAndZoom()
{
	if (navigator.geolocation) 
	{
		// alert("geolocation!");
		if($( window ).width() < 700)
		{
		  	navigator.geolocation.getCurrentPosition(function(position) {
		  												var pos = {
											              lat: position.coords.latitude,
											              lng: position.coords.longitude
											            };

											            if(-122.862638 < position.coords.longitude && position.coords.longitude < -121.688677
											            	&& 44.888574 < position.coords.latitude && position.coords.latitude < 45.462639)
											            {
											            	var navinfowindow = new google.maps.InfoWindow();
												            navinfowindow.setPosition(pos);
												            navinfowindow.setContent('Your location.');
												            navinfowindow.open(map);
											            	// var navmarker = new google.maps.Marker({  position: pos, 
																						  //             map: map,
																						  //             //icon: '/images/Fish-Marker-small.png',
																						  //             shadow: pinShadow,
																						  //             title: 'Your Location'
																								//     });        // add marker in markers array

												            map.setCenter(pos);

												            if(-122.862638 < position.coords.longitude && position.coords.longitude < -122.552025
											            		&& 45.313763 < position.coords.latitude && position.coords.latitude < 45.462639)
												            {
			  													map.setZoom(14);
												            }
												            else
												            {
			  													map.setZoom(12);
												            }

			  												console.log("Latitude: "+position.coords.latitude+" Longitude: "+position.coords.longitude);
			  											}
															else if(defaultlat != "" && defaultlong != "")
														{
															//do nothing
														}
			  											else
			  											{
			  												map.fitBounds(bounds);

			  												if(i == 1)
															{
																map.setZoom(14);
															}
			  												// map.setZoom(map.getZoom() - 1);
			  											}

													  });
		}
		else if(defaultlat != "" && defaultlong != "")
		{
			//do nothing
		}
		else
		{
			map.fitBounds(bounds);
			
			if(i == 1)
			{
				map.setZoom(14);
			}
			// map.setZoom(map.getZoom() - 1);
		}
	} 
	// else if(zoomoverride > 0) //if(zoomoverride > 0)
	// {
	// 		map.setZoom(zoomoverride);
	// }
	else if(defaultlat != "" && defaultlong != "")
	{
		//do nothing
	}
	else
	{
		map.fitBounds(bounds);
		// map.setZoom(map.getZoom() - 1);
	}

}

function showAccountPin(acctid)
{		
	// alert("I = "+i);
	tempacctid = acctid;

	var currlatitude = document.getElementById("lat"+acctid).innerHTML;
	var currlongitude = document.getElementById("long"+acctid).innerHTML;
	
	//var currlatitude = 40.5+(0.1*i);
	//var currlongitude = -122+(0.1*i);
	
	if(currlatitude != 0 && currlongitude != 0)
	{
		// alert("here 1!");

		var latlng = new google.maps.LatLng(parseFloat(currlatitude), parseFloat(currlongitude));
			  
		marker[i] = new google.maps.Marker({ position: latlng, 
											 icon: '/images/mapicons/iconr1.png' }); 
		marker[i].setMap(map);
		bounds.extend(latlng);
		map.setCenter(latlng);

		// alert(marker.length);
		map.fitBounds(bounds);

		if(i == 1)
		{
			map.setZoom(14);
		}

		buildMarkerAttributes(acctid);
		// marker[i].click();
		i++;

	    q++;
		if($('#address1'+acctid+'-alt'+q).length > 0) 
		{
		    showAccountPin(acctid+'-alt'+q);
		}
	}
	else if(document.getElementById("address1clear"+acctid).innerHTML != "" &&
			document.getElementById("city"+acctid).innerHTML != " " &&
			document.getElementById("state"+acctid).innerHTML != "")
	{
		// alert("here 2!");

		var address = document.getElementById("address1clear"+acctid).innerHTML+', '+
					  document.getElementById("city"+acctid).innerHTML+' '+
					  document.getElementById("state"+acctid).innerHTML+' '+
					  document.getElementById("zip"+acctid).innerHTML;
					  
		geocoder.geocode( {'address': address}, function(results, status) 
												{       
												    if (status == google.maps.GeocoderStatus.OK) 
												    { 
												   	    marker[i] = new google.maps.Marker({map: map,            
																								position: results[0].geometry.location, 
																								icon: '/images/mapicons/iconr'+i+'.png'
																								});  
														// alert("here 1! "+marker.length);

														jQuery.ajax({
															type: "POST",
															url: "/functions/saveaccountlatlong.php",
															data: { AccountID: $("#AccountID"+acctid).val(),
																	Latitude: results[0].geometry.location.lat(), 
																	Longitude: results[0].geometry.location.lng()
																  },
															success: function(msg) {
																// document.getElementById("imageloadergifsocialroller").style.display = 'none';
																// alert("It worked!");
													    	  	// console.log(accountnameitem+" LatLong: "+msg);
															}
														});

														bounds.extend(results[0].geometry.location);
														map.setCenter(latlng);
												
														map.fitBounds(bounds);
														
														if(i == 1)
														{
															map.setZoom(14);
														}

														buildMarkerAttributes(tempacctid);
														// openInfowWindowNow(marker[i]);
														i++;
														
													    q++;
														// if($('#address1'+acctid+'-alt'+q).length > 0) 
														if($('#address1'+acctid+'-alt'+q).length > 0) 
														{
														    showAccountPin(acctid+'-alt'+q);
														}
   												    } //end if status
												} );

	}//end else if address is not null
	else
	{
		// alert("here 3!");
	    q++;
		// if($('#address1'+acctid+'-alt'+q).length > 0) 
		if($('#address1'+acctid+'-alt'+q).length > 0) 
		{
		    showAccountPin(acctid+'-alt'+q);
		}
	}

} // end function executeGeoCoding

function buildMarkerAttributes(acctid)
{
	// alert("here 2! "+marker.length);
	var markerTitle = document.getElementById('desc'+acctid).innerHTML;
	marker[i].setTitle(markerTitle);
	
	var websiteitem = null;
  	websiteitem = document.getElementById("website"+acctid);
  
  	var website = null;
  	if(websiteitem.innerHTML != null)
  	{
	 	website = websiteitem.innerHTML; 
	 	// console.log('website.indexOf("http") '+website.indexOf("http"));
	 	if(website.indexOf(".") != -1 && website.indexOf("http") == -1)
	 	{
			website = "http://" + website;  
	 	}
  	}
	
	//$directionsLink = "http://maps.google.com/maps?daddr=Sundial+Bridge,+Redding,+CA
	if(document.getElementById("address1"+acctid).innerHTML != ""
	 	&& document.getElementById("address1"+acctid).innerHTML != null
	 	&& document.getElementById("address1"+acctid).innerHTML != ', ')
 	{
	   var directionsLink = 'http://maps.google.com/maps?daddr='+
		document.getElementById("address1clear"+acctid).innerHTML+',+'+
		document.getElementById("city"+acctid).innerHTML+'+'+
		document.getElementById("state"+acctid).innerHTML+'+'+
		document.getElementById("zip"+acctid).innerHTML;
  	}
  	else 
  	{
		var directionsLink = 'http://maps.google.com/maps?daddr='+
		document.getElementById("lat"+acctid).innerHTML+','+
		document.getElementById("long"+acctid).innerHTML;
  	}
					  
	var contentString = '<div id="content" align="left">'+ 
						'<div id="siteNotice">'+ 
						'</div>'+ 
						'<div align="left" class="GMapMarkerHeader"><strong>'+markerTitle+'</strong></div>'+
						'<div id="bodyContent" class="GMapMarkerContent">';
		
	if(document.getElementById("address1"+acctid).innerHTML != ""
		 && document.getElementById("address1"+acctid).innerHTML != null
		 && document.getElementById("address1"+acctid).innerHTML != ', ')
	{
		contentString += document.getElementById("address1clear"+acctid).innerHTML+'<br/>'+
				document.getElementById("city"+acctid).innerHTML+' '+
				document.getElementById("state"+acctid).innerHTML+' '+
				document.getElementById("zip"+acctid).innerHTML;
	}
	
	contentString += '<br/><br/><a href="'+directionsLink.replace(" ", "+")+'" target="_blank">Get Directions</a>';
	
	if(website != "")
	{
		contentString += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="'+website+'" target="_blank">View Website</a>';
	}

	contentString += '</div>'+
					'</div>'; 
	var markerPosition = marker[i].getPosition();
	contentStrings[markerPosition.lat()+markerPosition.lng()] = contentString;
					
	google.maps.event.addListener(marker[i], 'click', openInfowWindow(marker[i]));		
}
