var isVis = false;
var lat =0;
var lng =0;
var line;
var arrayString;
var directionTitle;

//  proxy variables
//  since it is my server, I can leave these blank, its relative to the page
var proxyServerName = "";
var proxyServerPort = "";

// this is the important one, it tells the JSAPI where to send the XML request (the location of the proxy on my own server)
// make relative to the html page, not the script page!
var proxyServerPath = "http://www.houstonalanon.org/mapquest/JSAPIProxyPage/JSReqHandler.php";
//var proxyServerPath = "/../../mapquest/JSAPIProxyPage/JSReqHandler.php";


var mqPort = "80";
var mqPath = "mq";
var myGExec = new MQExec("geocode.free.mapquest.com",mqPath,mqPort,proxyServerName,proxyServerPath,proxyServerPort);
var myRExec = new MQExec("route.free.mapquest.com",mqPath,mqPort,proxyServerName,proxyServerPath,proxyServerPort);
var myGcColl= new MQLocationCollection("MQGeoAddress");
var myRtColl= new MQLocationCollection("MQGeoAddress");

var myBoundingBox = new MQA.RectLL(new MQA.LatLng(),new MQA.LatLng());
var toAddress;
var frAddress;
var myOptions;

var myRtResults = new MQRouteResults();
var myTrkRtColl = new MQTrekRouteCollection();
var myManeuverColl = new MQManeuverCollection();
var mySessID;
var     routeisvis = false; //used in printing window



/*
 * Function to run AJAX portion of the map display
 */
function runCGI (){
        var xmlHttp;

        //document.getElementById("dir").innerHTML = "http://www.houstonalanon.org/cgi-bin/meetings/address.cgi?ll=" + lat + "," + lng ;

        // Create the XMLHttpRequest object -- the foundation of AJAX
        try {           // Firefox, Opera 8.0+, Safari
          xmlHttp=new XMLHttpRequest();
        } catch (e) {
                try {   // Internet Explorer
                xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                        try {
                                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {
                                document.getElementById("dir").innerHTML = "Your browser does not support AJAX!";
                                return false;
                        }
                }
        }

        // If here, create function that will write out the information
        xmlHttp.onreadystatechange=function() {
                if (xmlHttp.readyState==0) {
                        //document.getElementById("dir").innerHTML = "The request is not initialized.";
                } else if (xmlHttp.readyState==1) {
                        //document.getElementById("dir").innerHTML = "The request has been set up.";
                } else if (xmlHttp.readyState==2) {
                        //document.getElementById("dir").innerHTML = "The request has been sent.";
                } else if (xmlHttp.readyState==3) {
                        //document.getElementById("dir").innerHTML = "The request is in process.";
                } else if (xmlHttp.readyState==4) {
                        // Response gives us fields in single quotes: 'title','adddress1','city','zip'
                        line = xmlHttp.responseText;
                        arrayAddr = null;
                        arrayAddr = line.split( "|=|" );
                        directionTitle = "<br>To <u>" + arrayAddr[0] + ": </u><br><br>";
                        //if ( arrayAddr[3] == "Palacios" ) { // this is the funny one without an address
                        //      document.getElementById("route").innerHTML = directionTitle + "Please call for directions.";
                        //} else {

                        document.getElementById("route").innerHTML = "<br>Processing, please wait....";

                        // necessary for safari
                        window.scrollBy( 0, 1 );
                        window.scrollBy( 0, -1 );

                        showProgress( 20 );
                        //      process( arrayAddr[1], arrayAddr[2], arrayAddr[3] );
                        process();
                        //}
                }
        }

        // Send request
        url = "http://www.houstonalanon.org/cgi-bin/meetings/address.cgi?ll=" + lat + "," + lng;
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);

        // Necessary to keep link from redirecting page!
        return false;
}

function showDir( lat, lng ) {
        this.lat = lat;
        this.lng = lng;

        //
        // should we clear directions when user changes? yes
        //

        if ( !(isVis) ) {       // first time through
                showDirForm();
                isVis = true;
        } else {
                document.getElementById("route").innerHTML = "";
                hideRoute(); // just make sure.
        }
}

/*
 * Shows dir form
 */
function showDirForm() {
        document.getElementById("dir-form").innerHTML = 
        "<form name=\"infoForm\" onSubmit=\"getDir()\" id=\"dir-form\">" +
        "<table ID=\"Table1\" border=\"1\">" +
        "       <caption>Get Directions From:</caption>" +
        "       <tbody>" +
        "       <tr><th><label for=\"Fstreet\">Street:</label></th><td><input type=\"text\" ID=\"Fstreet\"></td></tr>" +
        "       <tr><th><label for=\"Fcity\">City:</label></th><td><input type=\"text\" ID=\"Fcity\"></td></tr>" +
        "       <!--<tr>State:</label></th><td><input type=\"text\" ID=\"Fstate\" SIZE=\"2\" maxlength=\"2\" value=\"TX\" ></td></tr>-->" +
        "       <tr><th><label for=\"Fstate\">State: </th><td><select name=\"state-select\" id=\"Fstate\"><option selected label=\"TX\" value=\"TX\">Texas</option><option label=\"LA\" value=\"LA\">Louisiana</option></select></td></tr>" +
        "       <tr><th><label for=\"Fzip\">Zip:</label></th><td><input type=\"text\" ID=\"Fzip\" SIZE=\"5\" maxlength=\"5\" value=\"\"></td></tr>" +
        "       <tr><th><label for=\"Dirlang\">Language: </th><td><select name=\"state-select\" id=\"Dirlang\"><option selected value =\"english\">English</option><option value =\"spanish\">Espa&ntilde;ol</option><option value =\"british english\">British English</option></select></td></tr>" +
        "       <tr><th></th><td id=\"rte-btn-cell\"><input type=\"button\" value=\"Get Route\" onclick=\"getDir()\" id=\"rte-btn\" class=\"mapbutton\" ></td></tr>" +
        "       </tbody>" +
        "       <tfoot>" +
        "       <tr><td colspan=\"2\" id=\"privacy\"><a href=\"http://www.houstonalanon.org/privacy.shtml\">Privacy Note</a>: Al-Anon does not collect address information. If you are concerned, please review the <a href=\"http://about.aol.com/aolnetwork/aol_pp\" class=\"ex\">AOL Network Privacy Policy<span> External Link</span></a>, and consider using a partial address, such as a zipcode or city name.</td></tr>" +
        "       </tfoot>" +
        "</table>" +
        "</form>";
        //"     <tr><td colspan=\"2\" id=\"privacy\"><a href=\"http://www.houstonalanon.org/privacy.shtml\">Privacy Notice</a>: Al-Anon does not collect or store this information.</td></tr>" +
        
        // For Safari -- doesn't show form unless paint window....
        window.scrollBy( 0, 1 );
        window.scrollBy( 0, -1 );
}


function getDir() {

        //Set cursor to hourglass
        //document.body.style.cursor = "wait";

        document.getElementById("route").innerHTML = "<br>Processing, please wait....";

        // necessary for safari
        window.scrollBy( 0, 1 );
        window.scrollBy( 0, -1 );


        runCGI ();

        //Turn hourglass off
        //document.body.style.cursor = "default";

}


function process ( street, city, zip ) {

        // Clear all collections
        myGcColl.removeAll();
        myRtColl.removeAll();
        myTrkRtColl.removeAll();
	myManeuverColl.removeAll();
	
	// Reset session b/c grows stale after awhile......could find a way to check if still good and refresh
	mySessID = myRExec.createSessionEx(new MQSession());

showProgress(30);

	toAddress = new MQAddress();
	frAddress = new MQAddress();
	myOptions = new MQRouteOptions();

	// From address (get from form)
	frAddress.setStreet(document.getElementById("Fstreet").value);
	frAddress.setCity(document.getElementById("Fcity").value);
	frAddress.setState(document.getElementById("Fstate").value);
	frAddress.setPostalCode(document.getElementById("Fzip").value);
	frAddress.setCountry("US");


	// To address (get from args)
// NOW USING LAT_LONG
//	toAddress.setStreet( street );
//	toAddress.setCity( city );
//	toAddress.setState( "TX" );
//	toAddress.setPostalCode( zip ); 
//	toAddress.setCountry("US");

	// Language, get from form
	myOptions.setLanguage(document.getElementById("Dirlang").value);

	try {
		geocodeThem();
		getRoute();
		displayIt();
		showRoute();
	} catch (e) {
		document.getElementById("route").innerHTML = "<br><br><strong>Processing Error:</strong><br>The routing functions were unable to process your request. There may be a simple solution. Try the following:<ul style=\"margin-left:15px\"><li>Reloading the page.&nbsp;</li><li>Entering a different address.&nbsp;</li><li>Using a different browser.</li></ul></em>";
	}
}

/*
 *  geocode the addresses
 *
 * Geocoding is expensive. Consider getting the GeoCode for the destination.
 */
function geocodeThem() {

showProgress(40);
	
	// Geocode addresses -- opera doesn't like geocoding.....
	myGExec.geocode(frAddress, myGcColl);
	myRtColl.add(myGcColl.get(0));

	//original:
	//myGExec.geocode(toAddress, myGcColl);
	//myRtColl.add(myGcColl.get(0));

showProgress(50);
	
	// try.....
	mg = new MQGeoAddress();
	mg.setMQLatLng( new MQLatLng(lat,lng) );
	myRtColl.add( mg );


}

/*
 *  make the doRoute call
 */
function getRoute() {
showProgress(60);

	// Necessary to remove original distance!
	myRtResults = new MQRouteResults(); 
showProgress(70);
	
	// For route only, not the map and route: 
	//myRExec.doRoute(myRtColl,myOptions,myRtResults,mySessID,new MQA.RectLL(MQA.LatLng(),MQA.LatLng()));
	myRExec.doRoute(myRtColl,myOptions,myRtResults,mySessID,myBoundingBox);
showProgress(80);
}

/*
 *  display route results
 */
function displayIt() {
	var myMinutes = myRtResults.getTime()/60;
	if (myMinutes > 60) {
		if (myMinutes/60 == 1) {
			var myTotTime = "1 hr ";
		} else {
			var myTotTime = Math.round((myMinutes/60)*100)/100 + " hrs";
		}
	} else {
		var myTotTime = myMinutes + " min";
	}

showProgress(90);

	var myDist = Math.round(myRtResults.getDistance()*100)/100;
	myTrkRtColl = myRtResults.getTrekRoutes();
	myManeuverColl = myTrkRtColl.get(0).getManeuvers();

	var myManDist = 0;
	var myManStr = "";
	var myTrkStr = "";
	for (intX = 0; intX < myManeuverColl.getSize(); intX ++){
		myManDist = Math.round(myManeuverColl.get(intX).getDistance()*100)/100;
		myManStr = (intX +1) +  ". " + myManeuverColl.get(intX).getNarrative() + "(Distance: " + myManDist + " mi)";
		myTrkStr = myTrkStr + myManStr + "<br/><hr/>";
	}
	document.getElementById("route").innerHTML = directionTitle + "<br><input type=\"button\" value=\"Hide Route on Map\" onclick=\"handleRouteButton()\" id=\"rteButton\" class=\"mapbutton\" style=\"border:1px outset black; padding:1px;\" ><br /><br />" + "<hr/><b>DRIVING DIRECTIONS: </b><br/><hr/>" + myTrkStr + "<b>Total Time: </b>" + myTotTime + "<b> Total Distance: </b>" + myDist + " miles<hr/><br/>";
	//+ "<form onSubmit=\"showRoute()\" ><input type=\"button\" value=\"Show Route\" onclick=\"showRoute()\" id=\"showrte-btn\" class=\"mapbutton\" ></form><br>";
	//document.getElementById("routeDiv").innerHTML = "hello";
	
}

function handleRouteButton() {
	if ( document.getElementById("rteButton").value == "Hide Route on Map" ) {
		hideRoute();
		document.getElementById("rteButton").value = "Show Route on Map";
	} else {
		showRoute();
		document.getElementById("rteButton").value = "Hide Route on Map";
	}
}

/*
 * Show route on map
 */
function showRoute() {
	map.addRouteHighlight(myBoundingBox,"http://map.free.mapquest.com",mySessID,true);
	routeisvis = true;
}

/*
 * Hide route on map
 */
function hideRoute() {
	map.removeRouteHighlight();
	routeisvis = false;
}


function initProgress( prog ) {
	//document.getElementById("route").innerHTML = "<br>Processing, please wait....<input type=\"text\" size=\"5\" id=\"progressbar\" />";
	//document.getElementById("route").innerHTML = "<br>Processing, please wait....";
	//document.getElementById("route").innerHTML = "<br><input type=\"text\" size=\"100\" id=\"progressbar\" />";
	document.getElementById("route").innerHTML = "<br>Processing, please wait....";

	// necessary for safari
	window.scrollBy( 0, 1 );
	window.scrollBy( 0, -1 );

	//showProgress( prog );
}

function showProgress( prog ) {

if (DEBUG) alert(prog);

	//document.getElementById("progressbar").value = "Processing, please wait...." + prog  + "%";
	//document.getElementById("route").innerHTML = "<br>Processing, please wait...." + prog  + "%";
	//window.scrollBy( 0, 1 );
	//window.scrollBy( 0, -1 );
	// + prog + " of " + last;
	//window.blur( );
	//window.focus( );
}
