// JavaScript Document
var map;
var xml;
var gmarkers = [];
var glabels = [];
var def_lat=36.842705;
var def_lng=-75.976469;
var def_latlng = new GLatLng(def_lat, def_lng);
var def_zoom=15;
var bounds = new GLatLngBounds();
var arrCategories=['Lodging','Dining','Shopping','Attractions'];
var gdir;
var to_htmls = [];
var from_htmls = [];

// === Array for decoding the failure codes ===
var reasons=[];
//reasons[G_GEO_SUCCESS]            = "Success";
//reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.";
//reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "The given key is either invalid or does not match the domain for which it was given.";
reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
//reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]       = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.";
reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
//reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";
	

function initialize() 
{
	if (GBrowserIsCompatible()) 
	{
		/////////////show map/////////////////////////////////
		map = new GMap2(document.getElementById("map_canvas"));
		var point = new GLatLng(def_lat, def_lng);
		map.setMapType(G_NORMAL_MAP);
		var center=point;
		map.setCenter(center, 15);
		map.setUIToDefault();
		map.disableScrollWheelZoom();
		
		var searchUrl = "/maps.xml";	//the page to get all markers in the form of xml
		
		//GDownloadUrl is a google map api function to get markers data asynchronously using xml or json
		
		GDownloadUrl(searchUrl, function(data) {
			xml = GXml.parse(data);
			
			// ========= Now process the polylines ===========
            var lines = xml.documentElement.getElementsByTagName("line");
            // read each line
            for (var a = 0; a < lines.length; a++) {
                // get any line attributes
                var colour = lines[a].getAttribute("colour");
                var width  = parseFloat(lines[a].getAttribute("width"));
                // read each point on that line
                var points = lines[a].getElementsByTagName("point");
                var pts = [];
                for (var i = 0; i < points.length; i++) {
                    pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")),
                    parseFloat(points[i].getAttribute("lng")));
                }
                map.addOverlay(new GPolyline(pts,colour,width));
            }
            // ================================================  

            // ========= Now Add Beach Street USA text ===========

            var sw = new GLatLng(36.849578,-75.973206);
            var ne = new GLatLng(36.857819,-75.969000);
            var bounds=new GLatLngBounds(sw,ne);
            var overlay = EInsert.groundOverlay("/images_map_markers/beach_street_usa.png",bounds);
            map.addOverlay(overlay);

           // ================================================  
            gdir = new GDirections(map, document.getElementById("directions"));
			
			// === catch Directions errors ===
	        GEvent.addListener(gdir, "error", function() {
		        var code = gdir.getStatus().code;
		        var reason = "Code " + code;
		        if (reasons[code]) {
			        reason = reasons[code]
		        } 
	
		        alert(reason);
	        });
			

			GetAllMarkersData();
		});		
	}
}
//--------------------------------------------------------------------------------------------------------
function createSimpleMarker(point,title,CompanyIcon,description) 
{
	  var marker = new GMarker(point,{title: status,icon:CompanyIcon});

	  GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(description);
	  });
	  map.addOverlay(marker);
	 // bounds.extend(point);
	  //map.addOverlay(new GMarker(point));
	  return marker;
}
//---------------------------------------------------------------------------------------------------------

/*This function gets all the markers data and shows on the map*/
function GetAllMarkersData()
{
	
	ClearMap();
	//------------------------------------------------------------------
	var markers = xml.documentElement.getElementsByTagName('marker');
	
	if (markers.length == 0) 
	{
		map.setCenter(new GLatLng(parseFloat(def_lat),parseFloat(def_lng)), def_zoom);
		return;
	}
			
			
	var id;	
	var cat_id;		
	var type_id;
	var subcategory_name;
	var loc_name=" ";		
	var loc_name_trunc=" ";		
	var seoname;
	var street_address;
	var city;
	var state;
	var zip;
	var local_phone;
	var other_phone;
	var lat;
	var lng;
	var description;
	var logo_image;
	
	var resultsCat1 = '<ul>';
	var resultsCat2 = '<ul>';
	var resultsCat3 = '<ul>';
	var resultsCat4 = '<ul>';
	var num = 0;
			
	for (var i = 0; i < markers.length-1; i++) 
	{
		if (showMarker(markers[i]))
		{
			id 					= markers[i].getAttribute('id');	
			cat_id 				= markers[i].getAttribute('cat_id');		
			type_id 			= markers[i].getAttribute('type_id');	
			subcategory_name    = markers[i].getAttribute('subcategory_name');
			package 			= markers[i].getAttribute('package');		
			package_override	= markers[i].getAttribute('package_override');		
			featured 			= markers[i].getAttribute('featured');		
			loc_name 			= markers[i].getAttribute('loc_name');		
			loc_name_trunc		= markers[i].getAttribute('loc_name_trunc');		
			seoname 			= markers[i].getAttribute('seoname');
			logo_image 			= markers[i].getAttribute('logo_image');
			street_address 		= markers[i].getAttribute('street_address');
			city				= markers[i].getAttribute('city');
			state				= markers[i].getAttribute('state');
			zip					= markers[i].getAttribute('zip');
			local_phone			= markers[i].getAttribute('local_phone');
			other_phone			= markers[i].getAttribute('other_phone');
			lat		 			= markers[i].getAttribute('lat');
			lng 				= markers[i].getAttribute('lng');
			description			= markers[i].getAttribute('description');
							
			if(package_override>package)
			{package=package_override;}
				
			if(local_phone=="" || local_phone==null)
			{local_phone="";	}

			if(other_phone=="" || other_phone==null)
			{other_phone="";	}

			var tab1_html="<div style='overflow:auto; width:350px;height:150px;'>";
			tab1_html=tab1_html+"<table width='350px' ><tr><td width='75px' style='padding-right:5px;' valign='top' align='center'>";
			if(logo_image=="")
			{ tab1_html=tab1_html+"</td>";}
			else
			{ tab1_html=tab1_html+"<img alt='' style='border:1px solid #7b7b7b' width='75px' src='/images_members/"+logo_image+"'></td>";}
				
			tab1_html=tab1_html+"<td><b>" + loc_name + "</b><br />";
			tab1_html=tab1_html+ street_address +"<br>"+ city + " " + state +", "+ zip + "<br>";
			tab1_html=tab1_html+ local_phone +"<br>"+ other_phone +"</td></tr>";
				
			if(package>=1)
			{tab1_html=tab1_html+ '<tr><td colspan="2" align="right"><br><a href="http://www.vabeach.com/'+seoname+'">(more info)</a></td></tr>';	}

			tab1_html=tab1_html+"</table>Directions: <a href='javascript:tohere(" + num + ")'>To here<\/a> - <a href='javascript:fromhere(" + num + ")'>From here<\/a></div>";
			
			// The info window version with the "to here" form open
            to_htmls[num] = '<br>Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + num + ')">From here<\/a>' +
                '<br>Start address:<form action="javascript:getDirections()">' +
                '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
                '<select id="d_mode"><option value="d">By car</option><option value="w">Walking</option><br>' +
				'<INPUT value="Get Directions" TYPE="SUBMIT">' +
                '<input type="hidden" id="daddr" value="'+loc_name+"@"+ lat + ',' + lng + 
                 '"/>';
		   

            // The info window version with the "from here" form open
            from_htmls[num] = '<br>Directions: <a href="javascript:tohere(' + num + ')">To here<\/a> - <b>From here<\/b>' +
                '<br>End address:<form action="javascript:getDirections()">' +
                '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
                '<select id="d_mode"><option value="d">By car</option><option value="w">Walking</option><br>' +
				'<INPUT value="Get Directions" TYPE="SUBMIT">' +
                '<input type="hidden" id="saddr" value="'+loc_name+"@"+ lat + ',' + lng +
                '"/>';
				
			var tab2_html="<div style='overflow:auto; width:350px;height:150px;'>";
			tab2_html=tab2_html+"<table width='350px' ><tr><td valign='top'>";
			tab2_html=tab2_html+description+"... ";
			tab2_html=tab2_html+"</td></tr>";
			tab2_html=tab2_html+"</table></div>";
				
				
			if(package>=1)
			{tab2_html=tab2_html+ '<a><a href="http://www.vabeach.com/'+seoname+'">(more info)</a>';	}

				
			var MarkerIcon = new GIcon(G_DEFAULT_ICON);
				
			if(cat_id==1)
			{
				if(featured==1)
				{
					var label = new ELabel(new GLatLng(lat,lng),loc_name, "featured_marker_lodging");	
					label.pixelOffset=new GSize(10,-18);
					map.addOverlay(label);
					glabels.push(label);
				}				
					
				//MarkerIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/green/blank.png";
				MarkerIcon.image ="/images_map_markers/marker_lodging.png";
				MarkerIcon.iconSize = new GSize(15, 21);
				MarkerIcon.shadow = "/images_map_markers/shadow.png";
      			MarkerIcon.shadowSize = new GSize(29, 20);
					
			}
			else if(cat_id==2)
			{
				if(featured==1)
				{
					var label = new ELabel(new GLatLng(lat,lng),loc_name, "featured_marker_dining");	
					label.pixelOffset=new GSize(10,-18);
					map.addOverlay(label);
					glabels.push(label);
				}				

				//MarkerIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/red/blank.png";	
				MarkerIcon.image ="/images_map_markers/marker_dining.png";
				MarkerIcon.iconSize = new GSize(15, 21);
				MarkerIcon.shadow = "/images_map_markers/shadow.png";
      			MarkerIcon.shadowSize = new GSize(29, 20);

			}
			else if(cat_id==3)
			{
				if(featured==1)
				{
					var label = new ELabel(new GLatLng(lat,lng),loc_name, "featured_marker_shopping");	
					label.pixelOffset=new GSize(10,-18);
					map.addOverlay(label);
					glabels.push(label);
				}				
				//MarkerIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";	
				MarkerIcon.image ="/images_map_markers/marker_shopping.png";
				MarkerIcon.iconSize = new GSize(15, 21);
				MarkerIcon.shadow = "/images_map_markers/shadow.png";
      			MarkerIcon.shadowSize = new GSize(29, 20);
				
			}
			else if(cat_id==4)
			{
				if(featured==1)
				{
					var label = new ELabel(new GLatLng(lat,lng),loc_name, "featured_marker_attractions");	
					label.pixelOffset=new GSize(10,-18);
					map.addOverlay(label);
					glabels.push(label);
				}				
				//MarkerIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/orange/blank.png";	
				MarkerIcon.image ="/images_map_markers/marker_attractions.png";
				MarkerIcon.iconSize = new GSize(15, 21);
				MarkerIcon.shadow = "/images_map_markers/shadow.png";
      			MarkerIcon.shadowSize = new GSize(29, 20);
				
			}

			var marker=createTabbedMarker(new GLatLng(lat,lng), loc_name, MarkerIcon, [tab1_html, tab2_html], ['Info', 'Description']);
				
			gmarkers.push(marker);
			
			if(package>3 || featured==1)
			{
			   	if(cat_id==1)
			    {
					resultsCat1 = resultsCat1 + '<li><a href="#" onclick="myclick(' + num  + '); return false;">' + loc_name_trunc + '</a></li>';
				}
			    else if(cat_id==2)
			    {
					resultsCat2 = resultsCat2 + '<li><a href="#" onclick="myclick(' + num  + '); return false;">' + loc_name_trunc + '</a></li>';
				}
			    else if(cat_id==3)
			    {
					resultsCat3 = resultsCat3 + '<li><a href="#" onclick="myclick(' + num  + '); return false;">' + loc_name_trunc + '</a></li>';
				}
			    else if(cat_id==4)
			    {
					resultsCat4 = resultsCat4 + '<li><a href="#" onclick="myclick(' + num  + '); return false;">' + loc_name_trunc + '</a></li>';
				}
			   
			}
			num = num + 1;
		}
	}
	
	resultsCat1 = resultsCat1 + "</ul>";
	resultsCat2 = resultsCat2 + "</ul>";
	resultsCat3 = resultsCat3 + "</ul>";
	resultsCat4 = resultsCat4 + "</ul>";

	$("#results .mapselecttext_lodging").html(resultsCat1);
	$("#results .mapselecttext_dining").html(resultsCat2);
	$("#results .mapselecttext_shopping").html(resultsCat3);
	$("#results .mapselecttext_attractions").html(resultsCat4);
}

function showMarker(marker){
	var cat_id 				= marker.getAttribute('cat_id');		
	var type_id 			= marker.getAttribute('type_id');	
	var subcategory_name    = marker.getAttribute('subcategory_name');
	var package 			= marker.getAttribute('package');
	
	var show = false;
	
	if (package >= 1 || featured == 1){
	    if ($("#chkCat1").attr('checked') == true && cat_id == "1"){
            show = true;
        }
		if ($("#chkCat2").attr('checked') == true && cat_id == "2"){
            show = true;
        }
		if ($("#chkCat3").attr('checked') == true && cat_id == "3"){
            show = true;
        }
		if ($("#chkCat4").attr('checked') == true && cat_id == "4"){
            show = true;
        }
        if ($("#chkSubCat1").attr('checked') == true && subcategory_name == "Hotels & Motels"){
            show = true;
        }
	    if ($("#chkSubCat2").attr('checked') == true && subcategory_name == "Apts., B&B's, Condo Units"){
            show = true;
        }
	    if ($("#chkSubCat3").attr('checked') == true && subcategory_name == "Vacation Ownership"){
            show = true;
        }
	    if ($("#chkSubCat4").attr('checked') == true && subcategory_name == "Campgrounds & RV Parks"){
            show = true;
        }
	    if ($("#chkSubCat5").attr('checked') == true && subcategory_name == "Condominium Rentals"){
            show = true;
        }
	    if ($("#chkSubCat6").attr('checked') == true && subcategory_name == "Beach Home Rentals"){
            show = true;
        }
	    if ($("#chkSubCat7").attr('checked') == true && subcategory_name == "Seafood &amp; Steak"){
            show = true;
        }
	    if ($("#chkSubCat8").attr('checked') == true && subcategory_name == "International & Other"){
            show = true;
        }
	    if ($("#chkSubCat9").attr('checked') == true && subcategory_name == "Ice Cream and Sweets"){
            show = true;
        }
	    if ($("#chkSubCat10").attr('checked') == true && subcategory_name == "Mexican & Southwestern"){
            show = true;
        }
	    if ($("#chkSubCat11").attr('checked') == true && subcategory_name == "Pizza & Italian"){
            show = true;
        }
	    if ($("#chkSubCat12").attr('checked') == true && subcategory_name == "Chinese - Japanese - Asian"){
            show = true;
        }
	    if ($("#chkSubCat13").attr('checked') == true && subcategory_name == "Carry Out"){
            show = true;
        }
	    if ($("#chkSubCat14").attr('checked') == true && subcategory_name == "American & Cafe"){
            show = true;
        }
	    if ($("#chkSubCat15").attr('checked') == true && subcategory_name == "Catering and Events"){
            show = true;
        }
	    if ($("#chkSubCat16").attr('checked') == true && subcategory_name == "Bar-B-Que"){
            show = true;
        }
	    if ($("#chkSubCat17").attr('checked') == true && subcategory_name == "Repair"){
            show = true;
        }
	    if ($("#chkSubCat18").attr('checked') == true && subcategory_name == "Antiques & Thrift"){
            show = true;
        }
	    if ($("#chkSubCat19").attr('checked') == true && subcategory_name == "Clothing"){
            show = true;
        }
	    if ($("#chkSubCat20").attr('checked') == true && subcategory_name == "Surf Shops"){
            show = true;
        }
	    if ($("#chkSubCat21").attr('checked') == true && subcategory_name == "Gifts"){
            show = true;
        }
	    if ($("#chkSubCat22").attr('checked') == true && subcategory_name == "Shopping Malls"){
            show = true;
        }
	    if ($("#chkSubCat23").attr('checked') == true && subcategory_name == "Misc."){
            show = true;
        }
	    if ($("#chkSubCat24").attr('checked') == true && subcategory_name == "Waverunners"){
            show = true;
        }
	    if ($("#chkSubCat25").attr('checked') == true && subcategory_name == "Surfing"){
            show = true;
        }
	    if ($("#chkSubCat26").attr('checked') == true && subcategory_name == "Spa - Therapy"){
            show = true;
        }
	    if ($("#chkSubCat27").attr('checked') == true && subcategory_name == "Venues"){
            show = true;
        }
	    if ($("#chkSubCat28").attr('checked') == true && subcategory_name == "Golf"){
            show = true;
        }
	    if ($("#chkSubCat29").attr('checked') == true && subcategory_name == "Fishing"){
            show = true;
        }
	    if ($("#chkSubCat30").attr('checked') == true && subcategory_name == "Ecotourism"){
            show = true;
        }
	}
		
	return show;
}

function myclick(i) {
        GEvent.trigger(gmarkers[i],"click");
}

function clearDirections() {
		gdir.clear();
		dircontent.innerHTML = "";
		map.setCenter(def_latlng, 15);
		return false;
}

// ===== request the directions =====
function getDirections() {
	// ==== Set up the walk option ====
	var opts = {};
	if (document.getElementById("d_mode").value == "d") {
		opts.travelMode = G_TRAVEL_MODE_DRIVING;
	}
	else if(document.getElementById("d_mode").value == "w"){
		opts.travelMode = G_TRAVEL_MODE_WALKING;
		opts.avoidHighways = true;
	}
	// ==== set the start and end locations ====
	var saddr = document.getElementById("saddr").value
	var daddr = document.getElementById("daddr").value
	gdir.load("from: " + saddr + " to: " + daddr, opts);
		
	dircontent = document.getElementById('directions');
	dircontent.innerHTML = "<p><a href='#' onClick='clearDirections(); return false;'>Clear Directions</a></p>";

}

// functions that open the directions forms
function tohere(i) {
	gmarkers[i].openInfoWindowHtml("<div class='infowindow'>" + to_htmls[i] + "</div>");
}

function fromhere(i) {
	gmarkers[i].openInfoWindowHtml("<div class='infowindow'>" + from_htmls[i] + "</div>");
}

////////////////////////////////////////////////////////////////////////////////////////////////////
function createTabbedMarker(point, marker_title,LocationIcon, htmls, labels) 
{
	var marker = new GMarker(point, {title: marker_title,icon: LocationIcon});
	map.addOverlay(marker);
	//bounds.extend(point);
	// adjust the width so that the info window is large enough for this many tabs
	if (htmls.length > 2) 
		{
			htmls[0] = '<div style="width:'+htmls.length*90+'px">' + htmls[0] + '<\/div>';
		//htmls[0] = '<div style="width:392px">' + htmls[0] + '<\/div>';
		}
	
	var tabs = [];
	for (var i=0; i<htmls.length; i++) 
		{
			tabs.push(new GInfoWindowTab(labels[i],htmls[i]));
		}	
				   
	GEvent.addListener(marker, "click", function() {
	  marker.openInfoWindowTabsHtml(tabs);
	});
	
	return marker;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
function ClearMap()
{
	for (var i=0;i<gmarkers.length;i++)
	{
		map.removeOverlay(gmarkers[i]); 	
	}
	gmarkers.length=0;
	for (var j=0;j<glabels.length;j++)
	{
		map.removeOverlay(glabels[j]); 	
	}
	glabels.length=0;
	
}

function zzzz()
{
  alert("zzzz");
}

$(document).ready(function()
{     
    var checkboxes = $(".category ul").find(':checkbox');
	
	checkboxes.change(function() {
        if($(this).not(':checked')) {
		   $(this).parent().parent().parent().find(':checkbox:first').removeAttr('checked');
		}
		if($(this).parent().parent().find(':checkbox:checked').length == $(this).parent().parent().find(':checkbox').length) {
		   $(this).parent().parent().parent().find(':checkbox:first').attr('checked', 'checked');
		}
		GetAllMarkersData();
    });
    
   $(".category").find(':checkbox:first').change(function() {
        var checkboxes = $(this).parent().find(':checkbox');
	    if($(this).is(':checked')) {
            checkboxes.attr('checked', 'checked');
        } else {
            checkboxes.removeAttr('checked');
        }
		GetAllMarkersData();
    });
	
	//$("#map_checkboxes").find(':checkbox').change(function() {
		//GetAllMarkersData();
   // });
	
	
	
 });

