var infoWindowText;

var map;
var marker;

var gdir;

var toAddress;
var fromAddress;

// the value of this one gets set in the page
var point;

function showInfoWindow() {
	marker.openInfoWindowHtml(infoWindowText);
	
}

function createMarker(point) {
	/*
	var baseIcon = new GIcon();
	baseIcon.image = "images/bottleMarker.png";
	baseIcon.shadow = "bottle_shadow.png";
	baseIcon.iconSize = new GSize(25, 50);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(12, 25);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);
	var markerOptions = { icon:baseIcon };
	var marker = new GMarker(point, markerOptions);
	*/

	marker = new GMarker(point);

	GEvent.addListener(marker, "click", function() {
	  showInfoWindow();
	});
	
	GEvent.addListener(marker, "infowindowopen", function() {document.getElementById("fromAddress").focus();}); 
	
	return marker;
}

function doGetDirections() {
	fromAddress = document.getElementById("fromAddress").value;
	getDirections(document.getElementById("fromAddress").value);
	return false;

}

function loadMap() {
  if (GBrowserIsCompatible()) {
	
	map = new GMap2(document.getElementById("locationMap"), { size:new GSize(400,378) });
	map.addControl(new GSmallMapControl());
	
	map.setCenter(point, 13);
	
	marker = createMarker(point);
	map.addOverlay(marker);
	
	toAddress = document.getElementById("storeAddress").innerHTML.replace( /<[^<|>]+?>/gi,' ' );//.replace(/^\s+|\s+$/g, '');//.replace(/\n/gi, ' ').replace(/\s+/gi, ' ');
	infoWindowText = "<b>From:</b> <form onsubmit='return doGetDirections();'><input type='text' id='fromAddress' /><br/><br/><b>To: </b>" + document.getElementById("storeAddress").innerHTML + "<br/><input type='submit' value='Get Directions &raquo;'/></form>";
	
  }
  
}

var secondTry = false;
function handleErrors() {
        
		if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS && !secondTry) {
				secondTry = true;
				toAddress = point.toString().substring(1, point.toString().length-1);
				getDirections(fromAddress);
		}
		else if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS && secondTry) {
				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: " + gdir.getStatus().code);
				showInfoWindow();
		}
        else if (gdir.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: " + gdir.getStatus().code);
        		showInfoWindow();
		}
        else if (gdir.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: " + gdir.getStatus().code);
				showInfoWindow();
        }
        else if (gdir.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: " + gdir.getStatus().code);
        		showInfoWindow();
		}
        else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {
                alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
        		showInfoWindow();
		}
        else {
                alert("An unknown error occurred.");
				showInfoWindow();
        }

} 

function getDirections(fromAddress) {
	if (fromAddress == "") return;
	gdir = new GDirections(map, document.getElementById('directions'));
	GEvent.addListener(gdir, "error", handleErrors);
	GEvent.addListener(gdir, "load", function() {document.getElementById("directions").style.display="block"; });
	gdir.load("from: " + fromAddress + " to: " + toAddress,
			{ "locale": "en_US" });
	marker.closeInfoWindow();
	
}

var currentId = 'storeInfo';
function showContent(newId) {
	if (newId == currentId) return;
	
	document.getElementById(newId).className="opaque";
	
	document.getElementById(newId).style.display="block";
	
	if (newId != "mapContainer")
		Spry.Effect.DoFade(newId, {from: 0, to: 100});
	else
		Spry.Effect.DoFade(newId, {from: 0, to: 100, finish: function() {showInfoWindow();} });
	
	document.getElementById(currentId).style.display="none";
	
	currentId = newId;	
}

function urlencode(str) {
str = escape(str);
str = str.replace('+', '%2B');
str = str.replace(/%20/ig, '+');
str = str.replace('*', '%2A');
str = str.replace('/', '%2F');
str = str.replace('@', '%40');
return str;
}

function showPrintWindow() {
	var url = "http://maps.google.com/maps?f=d&saddr="+urlencode(fromAddress)+"&daddr="+urlencode(toAddress)+"&hl=en&pw=2";
	var printWindow = window.open(url, 'printMap');
}



function displayImagesWithThumbnails() {
	var imgs = document.getElementById("images").childNodes;
	for(var i = 0; i < imgs.length; i++) {
		if (imgs[i].tagName == "IMG") {
			document.write("<img src='"+imgs[i].src+"' id='mainImage' /><p id='mainCaption' class='caption'>"+imgs[i].alt+"</p>");
			break;
		}
	}
	for(var i = 0; i < imgs.length; i++) {
		if (imgs[i].tagName == "IMG") {
			document.write("<img src='"+imgs[i].src+"' alt='"+imgs[i].alt+"' class='"+imgs[i].className+"Thumbnail' onclick='javascript:document.getElementById(\"mainImage\").src=this.src;document.getElementById(\"mainCaption\").innerHTML=this.alt;' />");
		}
	}	
}



function ajaxRequest(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]; //activeX versions to check for in IE
 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i]);
   }
   catch(e){
    //suppress error
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  return new XMLHttpRequest();
 else
  return false;
}

var contactFormRequest=new ajaxRequest();

contactFormRequest.onreadystatechange=function(){
 if (contactFormRequest.readyState==4){
  if (contactFormRequest.status==200 || window.location.href.indexOf("http")==-1){
   document.getElementById("contact").innerHTML=contactFormRequest.responseText;
  }
  else{
   alert("An error has occured making the request");
  }
 }
}

function storeContactFormPost() {
	
	var namevalue=encodeURIComponent(document.getElementById("contactName").value);
	var emailvalue=encodeURIComponent(document.getElementById("contactEmail").value);
	var commentsvalue=encodeURIComponent(document.getElementById("contactComments").value);
	var storeemailvalue=encodeURIComponent(document.getElementById("storeEmail").value);

	var parameters="name="+namevalue+"&email="+emailvalue+"&comments="+commentsvalue+"&storeemail="+storeemailvalue;
	contactFormRequest.open("POST", "../../storeEmail.php", true);
	contactFormRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	contactFormRequest.send(parameters);
}

