// Hide the no address error
document.getElementById('map-no-directions').style.display = 'none'; 
document.getElementById('map-got-directions').style.display = 'none'; 

function googleSubmit()
{
	// Get the originating and destination addresses
	var daddr = document.getElementById('daddr').value;
	var saddr = document.getElementById('saddr').value;
	
	if (saddr == "" || daddr == "")
	{
		// Show the no address error
		document.getElementById('map-no-directions').style.display = 'block';
		document.getElementById('map-got-directions').style.display = 'none';
		opacity('map-no-directions', 0, 100, 1000);
	}
	else
	{
		// Show the success message
		document.getElementById('map-no-directions').style.display = 'none';
		document.getElementById('map-got-directions').style.display = 'block';
		document.getElementById('directions').style.display = 'block';
		opacity('map-got-directions', 0, 100, 1000);
		
		var objDiv = document.getElementById("map");
		objDiv.scrollTop = objDiv.scrollHeight;
		self.scroll(0, 500);
	}
}

function opacity(id, opacStart, opacEnd, millisec) 
{
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(i = opacStart; i >= opacEnd; i--) {
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	} else if(opacStart < opacEnd) {
		for(i = opacStart; i <= opacEnd; i++)
			{
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	}
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function shiftOpacity(id, millisec) {
	//if an element is invisible, make it visible, else make it ivisible
	if(document.getElementById(id).style.opacity == 0) {
		opacity(id, 0, 100, millisec);
	} else {
		opacity(id, 100, 0, millisec);
	}
}

function blendimage(divid, imageid, imagefile, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 0;
	
	//set the current image as background
	document.getElementById(divid).style.backgroundImage = "url(" + document.getElementById(imageid).src + ")";
	
	//make image transparent
	changeOpac(0, imageid);
	
	//make new image
	document.getElementById(imageid).src = imagefile;

	//fade in image
	for(i = 0; i <= 100; i++) {
		setTimeout("changeOpac(" + i + ",'" + imageid + "')",(timer * speed));
		timer++;
	}
}

function currentOpac(id, opacEnd, millisec) {
	//standard opacity is 100
	var currentOpac = 100;
	
	//if the element has an opacity set, get it
	if(document.getElementById(id).style.opacity < 100) {
		currentOpac = document.getElementById(id).style.opacity * 100;
	}

	//call for the function that changes the opacity
	opacity(id, currentOpac, opacEnd, millisec)
}


if (GBrowserIsCompatible()) {
  var side_bar_html = "";
  var gmarkers = [];
  var htmls = [];
  var i = 0;
  // arrays to hold variants of the info window html with get direction forms open
  var to_htmls = [];
  var from_htmls = [];

  // A function to create the marker and set up the event window
  function createMarker(point,name,html) {
    var marker = new GMarker(point);

    // The info window version with the "to here" form open
    to_htmls[i] = html + '<br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
       '<br>Start address:<form action="javascript:getDirections()" name="google-directions">' +
       '<input type="text" SIZE=40 name="saddr" id="saddr" value="" class="google-address textbox" /><br>' +
       '<INPUT value="Get Directions" TYPE="SUBMIT" class="submit-google">' +
       '<input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + 
       '"/>';
    // The info window version with the "to here" form open
    from_htmls[i] = html + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
       '<br>End address:<form action="javascript:getDirections()" name="google-directions">' +
       '<input type="text" SIZE=40 name="daddr" id="daddr" value="" class="google-address textbox" /><br>' +
       '<INPUT value="Get Directions" TYPE="SUBMIT" class="submit-google">' +
       '<input type="hidden" id="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +
       '"/>';
    // The inactive version of the direction info
    html = html + '<br>Directions: <a href="javascript:tohere('+i+')">To here</a> - <a href="javascript:fromhere('+i+')">From here</a>';

    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(html);
    });
    
    // save the info we need to use later for the side_bar
    gmarkers[i] = marker;
    htmls[i] = html;
    // add a line to the side_bar html
    side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a><br>';
    i++;
    return marker;
  }

  // ===== request the directions =====
  function getDirections() {
    var saddr = document.getElementById("saddr").value
    var daddr = document.getElementById("daddr").value
    gdir.load("from: "+saddr+" to: "+daddr);
  }


  // This function picks up the click and opens the corresponding info window
  function myclick(i) {
    gmarkers[i].openInfoWindowHtml(htmls[i]);
  }

  // functions that open the directions forms
  function tohere(i) {
    gmarkers[i].openInfoWindowHtml(to_htmls[i]);
  }
  function fromhere(i) {
    gmarkers[i].openInfoWindowHtml(from_htmls[i]);
  }


  // create the map
  var map = new GMap2(document.getElementById("map"));
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  map.setCenter(new GLatLng(33.637934, -117.610066), 12);

  // === create a GDirections Object ===
  var gdir=new GDirections(map, document.getElementById("directions"));

  // === 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]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
  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]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
  reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
  reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
  reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
  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.";

  // === catch Directions errors ===
  GEvent.addListener(gdir, "error", function() {
    var code = gdir.getStatus().code;
    var reason="Code "+code;
    if (reasons[code]) {
      reason = reasons[code]
    } 

	//document.getElementById('errors').innerHMTL = reason;
    //alert("Failed to obtain directions, "+reason);
  });

  // Read the data from example.xml
  var request = GXmlHttp.create();
  request.open("GET", "/wp-content/themes/dmgpromotions/xml/location.xml", true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var xmlDoc = GXml.parse(request.responseText);
      // obtain the array of markers and loop through it
      var markers = xmlDoc.documentElement.getElementsByTagName("marker");
      
      for (var i = 0; i < markers.length; i++) {
        // obtain the attribues of each marker
        var lat = parseFloat(markers[i].getAttribute("lat"));
        var lng = parseFloat(markers[i].getAttribute("lng"));
        var point = new GLatLng(lat,lng);
        var html = markers[i].getAttribute("html");
        var label = markers[i].getAttribute("label");
        // create the marker
        var marker = createMarker(point,label,html);
        map.addOverlay(marker);
        
        html = html + '<br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
				       '<br>Start address:<form action="javascript:getDirections()" name="google-directions">' +
				       '<input type="text" SIZE=40 name="saddr" id="saddr" value="" class="google-address textbox" /><br>' +
				       '<input value="Get Directions" type="submit" class="submit-google" onclick="googleSubmit();">' +
				       '<input type="hidden" id="daddr" value="'+label+"@"+ point.lat() + ',' + point.lng() + 
				       '"/>';
				        
        marker.openInfoWindowHtml(html);
      }
      // put the assembled side_bar_html contents into the side_bar div
      //document.getElementById("side_bar").innerHTML = side_bar_html;
    }
  }
  request.send(null);
}

else {
  alert("Sorry, the Google Maps API is not compatible with this browser");
}

