// Google map Manipulation Script
//Written By Kevin Rice for Inroads LLC.

google.load("maps", "2");

var gmarkers = [];
var map;
 var pcSmallIcon;
var pcMedIcon;
var directionsPanel;
var directions;
var newwindow;
var startad;
var endadd;
var nomove = false;
var baseIcon;
var golferSmallIcon;
var courseList = document.getElementById('courses');

function centerOnThis(id)
{
  google.maps.Event.trigger(gmarkers[id], 'click');
}

function createMarker(i,point,name,html) 
{
    var marker = new google.maps.Marker(point,pcSmallIcon);
    // save the info we need to use later for the side_bar
    gmarkers[i] = marker;
    return marker;
}

function openWindow(path,wname,ht,wt)
{
    aswindow_width = get_document_window_width();
    aswidth = convert_width(wt,aswindow_width);
    aswindow_height = get_document_window_height();
    asheight = convert_height(ht,aswindow_height);
    asleft = calculate_left(aswidth,aswindow_width);
    astop = calculate_top(asheight,aswindow_height);
    if(newwindow) newwindow.close();
    newwindow = window.open (path, wname,"menubar=0,resizable=0,screenX="+asleft+",screenY="+astop+",left="+asleft+",top="+astop+",width="+wt+",height="+ht+"");
    newwindow.focus();
}
function createTabbedMarker(i,point,name,html1,tabname,html2,tabname2,html3,tabname3,html4) 
{
    var marker = new GMarker(point,{icon:pcSmallIcon,title:name});
    var tablist = new GMarker(point,pcSmallIcon);
    // save the info we need to use later for the side_bar
    gmarkers[i] = marker;
    return marker;
}

function showAdvancedSearch()
{
    aswindow_width = get_document_window_width();
    aswidth = convert_width(500,aswindow_width);
    aswindow_height = get_document_window_height();
    asheight = convert_height(305,aswindow_height);
    asleft = calculate_left(aswidth,aswindow_width);
    astop = calculate_top(asheight,aswindow_height);
		 $('advancedSearchContainer').style.left = asleft+'px';
    $('advancedSearchContainer').style.top = '155px';
    elementAppear('advancedSearchContainer');  }

function showVideo(vd)
{
	 vid = ($('videoContainercms'))?$('videoContainercms'):$('vidContainer');
    aswindow_width = get_document_window_width();
    aswidth = convert_width(500,aswindow_width);
    aswindow_height = get_document_window_height();
    asheight = convert_height(305,aswindow_height);
    asleft = calculate_left(aswidth,aswindow_width);
    astop = calculate_top(asheight,aswindow_height);
		 vid.style.left = asleft+'px';
    vid.style.top = astop+'px';
    vid.style.display = '';
    $('video').innerHTML = AC_FL_PreloadContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0','width','320','height','240','movie',vd,'quality','high','allowfullscreen','false' );
  }

function hideVideo()
{
	 vid = ($('videoContainercms'))?$('videoContainercms'):$('vidContainer');
		 vid.style.display = 'none';
    $('video').innerHTML = '';
  }

function getDirections(endpoint)
{
	 showWindow('gdirectionsContainer');
   startadd =  $('gdaddress').value+" "+$('gdcity').value+" "+$('gdstate').value+" "+$('gdzipcode').value;
   endadd   = endpoint;
		aswindow_width = get_document_window_width();
		aswidth = convert_width(955,aswindow_width);
		asleft = calculate_left(aswidth,aswindow_width);
		$('searchContainer').style.left = asleft+'px';
		$('searchContainer').innerHTML = "<div id=\"asHeaderContainer\" style=\"width:955px;height:40px\" onMouseOver=\"dragWindow('searchContainer')\"><div id=\"asHeader\" style=\"width:860px\" ><h1 style=\"font-size:20px;color:#28903a;\">Public Courses Directions</h1></div><div class=\"closeBtn\" style=\"margin-right:20px\"><a href=\"javascript:elementFade('searchContainer');\"><img src=\"/images/blueclose.gif\" alt=\"Close the search window\" width=\"24\" height=\"24\" border=\"0\" /></a></div><div class=\"clearDivs\"><!-- --></div></div><iframe id=\"searchframe\" name=\"searchframe\" width=\"955\" height=\"550\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=" +startadd+"&daddr="+endadd+"\"></iframe><br>";
		 	elementAppear('searchContainer');
		
		return false;
}

		
		function openExternalSite(f) 
{	
	var divwidth = 700;
	var divheight =600;

	var window_width = get_document_window_width();
   	var width = convert_width(divwidth,window_width);
   	var window_height = get_document_window_height();
   	var height = convert_height(divheight,window_height);
   	var left = calculate_left(width,window_width);
   	var top = calculate_top(height,window_height);
	
	newwindow = window.open (f, "externalsite","menubar=0,resizable=0,scrollbars=1,screenX="+left+",screenY="+top+",left="+left+",top="+top+",width="+divwidth+",height="+divheight);
	newwindow.focus();
}

		function handleErrors(){
	   if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	   {
	     //alert("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.\nError code: " + directions.getStatus().code);
	       $('searchContainer').innerHTML = "<div id=\"asHeaderContainer\" style=\"width:955px;height:40px\" onMouseOver=\"dragWindow('searchContainer')\"><div id=\"asHeader\" style=\"width:860px\" ><h1 style=\"font-size:20px;color:#28903a;\">Public Courses Directions*</h1></div><div class=\"closeBtn\"><a href=\"javascript:elementFade('searchContainer');\"><img src=\"/images/blueclose.gif\" alt=\"Close the search window\" width=\"24\" height=\"24\" border=\"0\" /></a></div><div class=\"clearDivs\"><!-- --></div></div><iframe id=\"searchframe\" name=\"searchframe\" width=\"955\" height=\"600\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=" +startadd+"&daddr="+endadd+"\"></iframe><br><div style=\"padding:0px 5px;\"><strong>*You are being taken to this page because this address requires more information.</strong></div>";
		 	elementAppear('searchContainer');
	   }
	   else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code);
	   
	   else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code);

	//   else if (directions.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + directions.getStatus().code);
	     
	   else if (directions.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code);

	   else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
	}function updateButtons() {
    new Ajax.Request('/search/googlemap_search.php', {
    method: 'post',
    parameters: { action: 'updatebuttons', state: $('state').value }
    });
}
function updateClicks(course) {
    new Ajax.Request('/search/googlemap_search.php', {
    method: 'post',
    parameters: { action: 'updateclicks', id: course }
    });
}
function loadDirectionsWindow(endpoint)
{
	 showWindow('gdirectionsContainer');
   	$('endpoint').value = endpoint;
}

function loadEmailWindow(ec)
{
	 new Ajax.Request('/search/googlemap_search.php', {
	     method: 'post',
	     parameters: {action: 'efdisplay', course: ec},
		 onSuccess: function(transport) { $('largeContainer').innerHTML = transport.responseText;
 showWindow('largeContainer'); },
       onLoading: function() { printProcessWindow('Loading Email-A-Friend Window'); },
       onComplete: function() { closeProcessWindow(); }
	 });

}

function sendEmail(f)
{
	 new Ajax.Request('/search/googlemap_search.php', {
	     method: 'post',
	     parameters: $(f).serialize(),
		 onSuccess: function(transport) { showWindow('largeContainer'); },
       onLoading: function() { printProcessWindow('Sending Email'); },
       onComplete: function() { closeProcessWindow(); }
	 });

}

function generalSearch(searchterm)
{
	 new Ajax.Request('/search/googlemap_search.php', {
	     method: 'post',
	     parameters: {action: 'general', search: searchterm},
       onLoading: function() { printProcessWindow('Searching for golf courses in '+searchterm); },
       onComplete: function() { closeProcessWindow(); }
	 });
}

function moveSearch(searchterm)
{
	 new Ajax.Request('/search/googlemap_search.php', {
	     method: 'post',
	     parameters: {action: 'autopopulate', search: searchterm},
       onLoading: function() { printProcessWindow('Repopulating Search Area'); },
       onComplete: function() { closeProcessWindow(); }
	 });
}

function asUpdate()
{
   if($('rtu').value == 'Yes') { 
 if($('company').value != '' || ($('city').value != '' && $('state').value != '') || $('zipcode').value != '') {
	 new Ajax.Request('/search/googlemap_search.php', {
	     method: 'post',
	     parameters: $('advancedSearchForm').serialize() 
,       onLoading: function() { printProcessWindow('Narrowing down your search'); },
       onComplete: function() { closeProcessWindow(); },
       onSuccess: function() { elementFade('advancedSearchContainer'); },
		 onFailure: function() { alert('No courses could be found matching selected criteria. Please revise your search.') }
	 });
}
 else alert('You must have either a course name, a city and state, or a zipcode to search against');
}
}

function advancedSearch()
{
if(($('state').value == '&hellip;' || $('state').value == '') && ($('city').value != '') && ($('zipcode').value == ''))
{
    alert("You must select a state");
}
else { 
	 new Ajax.Request('/search/googlemap_search.php', {
	     method: 'post',
	     parameters: $('advancedSearchForm').serialize() 
,       onLoading: function() { printProcessWindow('Refining your search'); },
       onComplete: function() { closeProcessWindow(); },
       onSuccess: function() { elementFade('advancedSearchContainer'); },
		 onFailure: function() { alert('No courses could be found matching selected criteria. Please revise your search.') }
	 });
}
}

function initialize()
{
       printProcessWindow('Loading Google Map');
   map = new GMap2(document.getElementById("map"));

   directionsPanel = $('gdirectionsdiv');
   directions = new GDirections(map, directionsPanel);
   GEvent.addListener(directions, "error", handleErrors);    baseIcon = new GIcon();
   baseIcon.iconSize = new GSize(15, 13);
   baseIcon.iconAnchor = new GPoint(5, 0);
   baseIcon.infoWindowAnchor = new GPoint(4, 2);
   baseIcon.infoShadowAnchor = new GPoint(6,-1);

   golferSmallIcon = new GIcon();
   golferSmallIcon.iconSize = new GSize(25, 40);
   golferSmallIcon.iconAnchor = new GPoint(11, 40);
   golferSmallIcon.infoWindowAnchor = new GPoint(22, 0);
   golferSmallIcon.infoShadowAnchor = new GPoint(11,0);

   map.addControl(new GSmallMapControl());

map.clearOverlays();
map.setCenter(new GLatLng(39.5,-96), 4);
var ctable=$('courses');
var bounds = new GLatLngBounds();

if(ctable) {
while(ctable.rows.length > 1 ) { 
   ctable.deleteRow(ctable.rows.length - 1);
}}

var point = new GLatLng(44.85291672,-92.79132080);
 //Google
   pcSmallIcon = new GIcon(baseIcon);
   pcSmallIcon.image = "http://www.publiccourses.com/images/mapimages/small-marker-green.png";

   pcSmallIcon.transparent = "http://www.publiccourses.com/images/mapimages/small-marker-green-ie.png";
   pcSmallIcon.imageMap=[0,12,7,0,14,12];
   pcSmallIcon.printImage = "http://www.publiccourses.com/images/mapimages/small-marker-green.gif";
   pcSmallIcon.mozPrintImage = "http://www.publiccourses.com/images/mapimages/small-marker-green-ff.gif";
   var general = "<div style='overflow:auto;width:390px;height:145px;'><div style='float:left;width:160px;height:140px;text-align:center'><img src='/images/course_images/pcdefault.jpg' height='120px' width='160px' border='0'  /><br></div><div style='float:left;width:200px;height:145px;padding-left:6px;'><strong>Afton Alps Golf Course</strong><br />6600 Peller Ave S<br />Hastings, MN 55033-9474<br /><strong>Telephone</strong>: 651.436.1320<br /><br /><strong>Green Fees</strong> <a href='' target='_blank' onclick='return false'><!-- <img src='/images/More_info.gif' border='0' /> --></a>: Between $25 - $50<br /><strong>Holes</strong>: 18 Regular | 0 Executive<br /><strong>Par</strong>: 72&nbsp;&nbsp;<strong>Slope</strong>: N/A&nbsp;&nbsp;<strong>Rating</strong>: N/A<br/><strong>Arch.</strong>: N/A<br/></div></div>";

var bubbleFooter = "<div style='padding:5px 0px;width:400px;font-size:11px;text-align:center;'><br/><a href=\"javascript:loadDirectionsWindow('6600 Peller Ave S Hastings, MN');\" >Directions</a> | <a href=\"javascript:loadEmailWindow('11407');\" >Email Friends</a> | <a href='/golf-courses/minnesota/afton-alps-golf-course-MN' target='_blank'>Print</a> | <a href='http://www.aftonalps.com' target='_blank' >Home Page</a><br /><br /><a class=\"hAltBlue\" href=\"http://www.kqzyfj.com/n0116r09608OSPQTUXUOQPURPQTW\" target=\"_blank\" onmouseover=\"window.status=\'http://www.expedia.com\';return true;\" onmouseout=\"window.status=\' \';return true;\">Book with confidence thanks to the Best Price Guarantee from Expedia.com</a><img src=\"http://www.tqlkg.com/kr118m-3sywHLIJMNQNHJINKIJMP\" width=\"1\" height=\"1\" border=\"0\"/></div>";

var marker = createTabbedMarker(11407,point,"Afton Alps Golf Course",general+bubbleFooter);
map.addOverlay(marker);
if(ctable) {
var x=ctable.insertRow(1);
var y=x.insertCell(0);
var z=x.insertCell(1);
y.style.padding = '0px 7px 3px 5px';
y.innerHTML="<a class='gmaptip' href=\"javascript:centerOnThis(11407)\" title='Afton Alps Golf Course'>Afton Alps Golf Course</a>"
z.innerHTML="0.00 mi." 
}
bounds.extend(point);
map.setZoom(map.getBoundsZoomLevel(bounds)-5);
 map.setCenter(bounds.getCenter());

if($('eventlink')) $('eventlink').href = '/events/';
if($('couponlink')) $('couponlink').href = '/coupons/';

 ;

      closeProcessWindow(); 
   GEvent.addListener(map, "infowindowopen", function() {
      nomove = true;
   });

   GEvent.addListener(map, "infowindowbeforeclose", function() {
      nomove = false;
   });

}

 google.setOnLoadCallback(initialize);

