//document.write("<script type='text/javascript' src='https://maps.google.com/maps?file=api&v=3&key=ABQIAAAAe6DG_BkV9uj5TM9B-zuGwRTvZ4WEo0ZdZKGdg3Ss4nrynvE8_RRHG8FKWAblUPDi9Opey3qAtyg86w'></scr"+"ipt>");
//document.write("<script type='text/javascript' src='https://www.usimagingnetwork.com/js/jquery.js'></scr"+"ipt>");

var directions;
var j=0;
var i=0;
var provlatlong = new Array();
var provgeodist = new Array();
var xmlhttp3=GetXmlHttpObject();
var xmlhttp5=GetXmlHttpObject();
var xmlhttp6=GetXmlHttpObject();
var strZip="";
var strLoc="";
var intProgress=0;
var intResults=0;
var startLat=0.0000;
var startlng=0.0000;

function jInitialization() 
{
	jToggleHeader();
	USIset_interval();
	$("#divLogo").animate({backgroundPosition:"(-20px 94px)"}, {duration:500});
}

function jToggleHeader()
{
	$("#feed-control").slideToggle();
	$("#imgHeader").slideToggle();
	$("#divLogo").slideToggle();
}

function checkzip() 
{
	document.getElementById("warncity").innerHTML="&nbsp;";
	document.getElementById("warnstate").innerHTML="&nbsp;";

	document.getElementById("zipmessage").style.visibility="visible";
		
	reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
    	if (!reZip.test(document.getElementById("zip").value) && document.getElementById("zip").value.length != 5
		&& document.getElementById("zip").value != "Zip") 
	{
		document.getElementById("showzip").innerHTML="Please enter a 5 digit zip";
		$("#showzip").css("color","red");
	}

	if (!reZip.test(document.getElementById("zip").value) || document.getElementById("zip").value.length != 5) 
	{
		if (document.getElementById("city").value != "" && document.getElementById("city").value != "City")
		{
			if (document.getElementById("state").value != "State")
			{	showResults();	}
			else
			{
				document.getElementById("warnstate").innerHTML="Select a state";
				$("#warnstate").css("color","red"); 
			}
		}
		else
		{
			document.getElementById("showzip").innerHTML="Please enter a 5 digit zip";
			document.getElementById("warncity").innerHTML="or a city <big><b>+</b></big> state";
			$("#showzip").css("color","red");
			$("#warncity").css("color","red");
		}
	}
	else 
	{	showResults();}
}


function showResults()
{
	j=0;
	intProgress=1;
	intResults=document.getElementById("no_of_results").value;

	document.getElementById("divFacilities").innerHTML = "Locating Facilities.";

	document.getElementById("divMessage").innerHTML = "";

	xmlhttp=GetXmlHttpObject();
	if (xmlhttp==null)
	  { alert ("Your browser does not support AJAX!");  return;  }

	var url="php/getFacilities.php";
	url=url+"?no_of_results="+document.getElementById("no_of_results").value;
	url=url+"&zip="+document.getElementById("zip").value;
	url=url+"&city="+document.getElementById("city").value;
	url=url+"&state="+document.getElementById("state").value;
	url=url+"&modality="+document.getElementById("modality").value;
	url=url+"&facility_name="+document.getElementById("facility_name").value;
	url=url+"&street_address="+document.getElementById("street_address").value;
	url=url+"&sid="+Math.random();

	xmlhttp.open("GET",url,false);
	xmlhttp.send(null);

	geocode();

}// End of showResults Function


function geocode() 
{
	document.getElementById("divFacilities").innerHTML += ".";

	document.getElementById("provider_results").innerHTML=xmlhttp.responseText;
	document.getElementById("provider_results").style.visibility="hidden";
	var x = document.getElementById("no_of_results").value;
	var y = document.getElementById("search_results").value;
	
	var origloc = document.getElementById("zip").value;
	if (origloc=="Zip" || origloc=="" )
	{	
		if(document.getElementById("street_address").value == "" || document.getElementById("street_address").value == "Street address") 
		{	
			getzipfromcity();
			origloc = strZip;
		}
		else
		{	origloc = document.getElementById("street_address").value + "+" + document.getElementById("city").value + "+" + document.getElementById("state").value;}
	}
	
	if(y==0)
	{    
		document.getElementById("divFacilities").innerHTML="No Facilities Found Within 250 miles of "+origloc ;
		return;
	}
	else
	{
		//if(x > y/2) 
		//{	x = y;}
		for(i=0;i<y; i++)
		{ 
			var strX = "opt" + i;
			provlatlong[i]=document.getElementById(strX).value;	
		}
		calcDistance();
	}	
}// End of geocode Function

function calcDistance() 
{
	document.getElementById("divFacilities").innerHTML += ".";
	directions = new GDirections();
	GEvent.addListener(directions, "load", jGDirectionsLoad);

	//GEvent.addListener(directions, "error", jHandleErrors);
	var x = document.getElementById("no_of_results").value;
	var y = document.getElementById("search_results").value;
	//if(x >= (y/2 + 3)){x=y;}

	calcRoutes();
}

function calcRoutes() 
{
	document.getElementById("divFacilities").innerHTML += ".";

	if(intProgress != 1)
	{	sleep(100);	}

	if(intProgress <= intResults)
	{	document.getElementById("divFacilities").innerHTML = "Calculating Route:" + intProgress + " of " + intResults;	}
	else
	{	document.getElementById("divFacilities").innerHTML += "<br>Mapping Routes "+Math.random()+": ";		}

	var origloc=document.getElementById("zip").value;
	if (origloc=="Zip" || origloc=="" )
	{	
		getzipfromcity();
		origloc = strZip;
		getState(strZip);
	}
	
	var address=document.getElementById("street_address").value+", "+strLoc+" "+origloc;

	var strX = "opt" + j;
	
	document.getElementById("divFacilities").innerHTML += ".";
	
	if(document.getElementById("street_address").value == "" || document.getElementById("street_address").value == "Street address") 
	{	
		document.getElementById("divFacilities").innerHTML += " from: "+origloc+" to: "+provlatlong[j].substr(10);
		directions.load("from: "+origloc+" to: "+provlatlong[j].substr(10));
	}
	else 
	{
		// ====== Create a Client Geocoder ======
		var geo = new GClientGeocoder(); 

		// ====== 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.";

		if(startLat == 0)
		{
			// ====== Geocoding ======
			geo.getLocations
			(
				address, 
				function (result)
				{
					if (result.Status.code == G_GEO_SUCCESS) 
					{
						document.getElementById("divFacilities").innerHTML += " geo success";
						var p = result.Placemark[0].Point.coordinates;
						startLat=p[1];
						startLng=p[0];
						directions.load("from: "+p[1]+","+p[0]+" to: "+provlatlong[j].substr(10)); 	
								
						if(directions.getStatus().code==500 || directions.getStatus().code==602)
						{
							//document.getElementById("divMessage").style.color="red";
							//document.getElementById("divMessage").innerHTML ="Warning: Address Typed Maybe Incorrect! Error Code:"+directions.getStatus().code;
							//document.getElementById("divFacilities").innerHTML = "Unable to locate Address..Please Check and Try Again";
						}
					}
					else
					{
						document.getElementById("divFacilities").innerHTML += " geo fail";
						var reason="Code "+result.Status.code;
						if (reasons[result.Status.code]) 
						{	reason = reasons[result.Status.code];    }
						
						document.getElementById("divFacilities").innerHTML = 'Could not find "'+address+ '" ' + reason;

					}
				}
			);
		}
		else
		{
			directions.load("from: "+startLat+","+startLng+" to: "+provlatlong[j].substr(10)); 	
		}

	}

} //end of calcRoutes Function

function jGDirectionsLoad()
{
	var x = document.getElementById("no_of_results").value;
	var y = document.getElementById("search_results").value;
	//if(x>=(y/2 + 3))
	//	{x=y;}
	
	var strX = "opt" + j;

	if(directions.getStatus().code == 200)
	{
		provgeodist[j]=	document.getElementById(strX).value.substr(0,10)+directions.getDistance().meters * 0.000621371192+","+directions.getDuration().html;
	}
	else
	{
		document.getElementById("divMessage").style.color="red";
		document.getElementById("divMessage").innerHTML="Warning: Address Typed Maybe Incorrect!";
	}
	j++;

	if(j<y)
	{	calcRoutes();}
	else 
	{	showtrueResults();}

	intProgress++;
	
} //end of GDirectionsLoad Function

function showtrueResults() 
{
	document.getElementById("divFacilities").innerHTML = "Formatting results.";

	var x=document.getElementById("no_of_results").value;
	var y=document.getElementById("search_results").value;
	//if(x >= (y/2 + 3)){x=y;}

	var xmlhttp2 =GetXmlHttpObject();
	try
	{
		if (xmlhttp2==null)
			{ alert ("Your browser does not support AJAX!");  return;  }

		var url="php/finaldisplay.php";
		url=url+"?no_of_results="+x;
	
		for(var i=0;i<y;i++) 
		{
			url=url+"&provgeodist"+i+"="+provgeodist[i];
		}
		url=url+"&sAddress="+document.getElementById("street_address").value;
		url=url+"&sCity="+document.getElementById("city").value;
		url=url+"&sState="+document.getElementById("state").value;
		url=url+"&sZip="+document.getElementById("zip").value;
		url=url+"&sid="+Math.random();

		xmlhttp2.open("GET",url,true);
		xmlhttp2.onreadystatechange = geocode2; 
		xmlhttp2.send(null);
	}
	catch (e) {alert("Unable to send http request");}

	function geocode2() 
	{
		document.getElementById("divFacilities").innerHTML += ".";
		//document.getElementById("divFooter").innerHTML+=xmlhttp2.readyState+"<br>";
		if(xmlhttp2.readyState == 4) 
		{
			if(xmlhttp2.status == 200) 
			{
				//	alert(xmlhttp2.responseText);
				document.getElementById("divMessage").style.color="black";

				var strStreet = "";
				if (document.getElementById("street_address").value != "Street address")
				{	strStreet = document.getElementById("street_address").value + ", ";	}

				var strType = "";
				if (document.getElementById("modality").value != "All")
				{	strType = " " + document.getElementById("modality").value; }

				var origZip = document.getElementById("zip").value;
				if (origZip == "Zip")
				{	origZip = "";	}

				document.getElementById("divMessage").innerHTML="Nearest  "+document.getElementById("no_of_results").value+strType+" facilities to "+strStreet+document.getElementById("city").value+",  "+document.getElementById("state").value+" "+origZip;
				
				document.getElementById("divFacilities").innerHTML= xmlhttp2.responseText;		
			}
			else 
			{alert("Problem retrieving data from the server.<br> Please refresh page and try again.");}
		}
	}
} //End of showTrue Results

function GetXmlHttpObject()
{
	if (window.XMLHttpRequest)
	  {  return new XMLHttpRequest();  }
	if (window.ActiveXObject)
	  {	  return new ActiveXObject("Microsoft.XMLHTTP");  }
	return null;
}

function dispstate(str) 
{
	if(str.length == 5)
	{
		if(xmlhttp3==null) 
		{
			alert("Your Browser does not support Ajax");
			return;
		}
		var url="php/getloc.php";
		url=url+"?zip="+str;
		url=url+"&sid="+Math.random();
		xmlhttp3.open("GET",url,false);
		xmlhttp3.send(null);
		showlocation();
	}
	else
	{
		document.getElementById("showzip").innerHTML="";
		return;
	}
}

function showlocation() 
{
		if (xmlhttp3.responseText.length < 3)
		{
			document.getElementById("showzip").innerHTML="Invalid Zip";
			$("#showzip").css("color","red");
		}
		else
		{
			document.getElementById("showzip").innerHTML=xmlhttp3.responseText;

			document.getElementById("city").value=xmlhttp3.responseText.split(", ",1);
			document.getElementById("state").value=xmlhttp3.responseText.substr(xmlhttp3.responseText.length-2,xmlhttp3.responseText.length);
			$("#showzip").css("color","black");
		}
}

function getState(str) 
{
	if(xmlhttp6==null) 
	{
		alert("Your Browser does not support Ajax");
		return;
	}
	var url="php/getloc.php";
	url=url+"?zip="+str;
	url=url+"&sid="+Math.random();
	xmlhttp6.open("GET",url,false);
	xmlhttp6.send(null);
	strLoc = xmlhttp6.responseText;
}


function dispEquipmentDetails(provaddr,manufacturer_model,Equipment_Key)
{
	xmlhttp4=GetXmlHttpObject();
	if(xmlhttp4==null)
	{
			alert("Your Browser does not support Ajax");
			return;
	}
	var url="php/dispEquipmentDetails.php";
	url=url+"?provider_key="+provaddr;
	url=url+"&Equipment_Key="+Equipment_Key;
	url=url+"&sid="+Math.random();
	xmlhttp4.open("GET",url,false);
	xmlhttp4.send(null);
			
	var strDiv = "divEq" + Equipment_Key+provaddr;

	document.getElementById(strDiv).innerHTML=xmlhttp4.responseText;
	$("#"+strDiv).slideToggle('fast');
}

function hideEquipmentDetails(provaddr,manufacturer_model,Equipment_Key)
{
	var strDiv = "divEq" + Equipment_Key;
	$("#"+strDiv).slideToggle('fast');	
}

function jAddressClicked()
{
	if(document.getElementById("street_address").value == "Street address")
	{
		document.getElementById("street_address").value="";
		$("#street_address").css("color","black");
	}
}

function jAddressLostFocus()
{
	if(document.getElementById("street_address").value == "Street address" || document.getElementById("street_address").value == "" )
	{
		document.getElementById("street_address").value="Street address";
		$("#street_address").css("color","dimGray");
	}
}

function jCityClicked()
{
	if(document.getElementById("city").value == "City")
	{
		document.getElementById("city").value="";
		$("#city").css("color","black");
	}
}

function jCityLostFocus()
{
	if(document.getElementById("city").value == "City" || document.getElementById("city").value == "" )
	{
		document.getElementById("city").value="City";
		$("#city").css("color","dimGray");
	}
}

function jStateClicked()
{
	$("#state").css("color","black");
}

function jZipClicked()
{
	if(document.getElementById("zip").value == "Zip")
	{
		document.getElementById("zip").value="";
		$("#zip").css("color","black");
	}
}

function jZipLostFocus()
{
	if(document.getElementById("zip").value == "Zip" || document.getElementById("zip").value == "" )
	{
		document.getElementById("zip").value="Zip";
		$("#zip").css("color","dimGray");
	}
}

function clearzipfields() 
{
	if(document.getElementById("facility_name").value == "Enter facility name")
	{
		document.getElementById("facility_name").value="";
		$("#facility_name").css("color","black");
	}
}


function jFacilityLostFocus()
{
	if(document.getElementById("facility_name").value == "Enter facility name" || document.getElementById("facility_name").value == "" )
	{
		document.getElementById("facility_name").value="Enter facility name";
		$("#facility_name").css("color","dimGray");
	}
}


function jClearSearch()
{
	document.getElementById("no_of_results").value="5";

	document.getElementById("street_address").value="Street address";
	$("#street_address").css("color","dimgray");

	document.getElementById("zip").value="Zip";
	$("#zip").css("color","dimgray");
	document.getElementById("showzip").innerHTML="&nbsp;";

	document.getElementById("city").value="City";
	$("#city").css("color","dimgray");
	document.getElementById("warncity").innerHTML="&nbsp;";

	document.getElementById("state").value="State";
	document.getElementById("warnstate").innerHTML="&nbsp;";

	document.getElementById("modality").value="All";

	document.getElementById("facility_name").value="Enter facility name";
	$("#facility_name").css("color","dimgray");
	document.getElementById("warnfacname").innerHTML="&nbsp;";

}


function searchby_facility_name()
{
	document.getElementById("warnfacname").innerHTML="";

	if (document.getElementById("facility_name").value=="Enter facility name" ||
		document.getElementById("facility_name").value=="")
	{
		document.getElementById("warnfacname").innerHTML="Please enter a facility name";
		$("#warnfacname").css("color","red");
	}
	else
	{
		xmlhttp=GetXmlHttpObject();
		if (xmlhttp==null)
		  { alert ("Your browser does not support AJAX!");  return;  }

		var url="php/getFacilityByName.php";
		url=url+"?no_of_results="+document.getElementById("no_of_results").value;
		url=url+"&facility_name="+document.getElementById("facility_name").value;
		url=url+"&sid="+Math.random();

		xmlhttp.open("GET",url,false);
		xmlhttp.send(null);

		document.getElementById("divFacilities").innerHTML=xmlhttp.responseText;

	}
}



function sleep(delay)
{
	var start = new Date().getTime();
	while (new Date().getTime() < start + delay);
}

function getzipfromcity() 
{
	if (xmlhttp5==null)
	{ alert ("Your browser does not support AJAX!");  return;  }
	
	var url="php/getzipcode.php";
	url=url+"?city="+document.getElementById("city").value;
	url=url+"&state="+document.getElementById("state").value;
	url=url+"&sid="+Math.random();
	xmlhttp5.open("GET",url,false);
	xmlhttp5.send(null);
	strZip = xmlhttp5.responseText;
}

function hide() 
{
	document.getElementById("divSearchBox").style.visibility="hidden";
}
