var request = null;
var siteId = null;
var officeID = null;
var agentID = null;
var domainName = null;
var url = null;
var indexVar = null;
var clientSearch = null;
var mapZoom = null
var map = null;
var control = null;
var icon = null;
var tooltip = null;
var defaultLat = null;
var defaultLon = null;
var debug = 0;
var setUrl = 0;
var agentData = null;
var officeData = null;
var remoteLocation = null;
var newMls = null;
var currentMls = null;
var map = null;
var sid = null;
var pins = new Array(null,null);
var pinIndex = 0;
var clickCounts = new Array(0,0);
var currentID = null;
var usingRoute = 0;
var directionInfo =null;
var routeinfo = null;
var routeControl = null;
var loadingMessage = null;
var listingLinks = 0;
var officeArray = new Array(null, null);
var controlHTML = "<table width='200' heigth='50'><tr><td><center><font color='#ffffff' size='3'><b>Loading Listings...</b></font></center></td></tr></table>";

function setIndex(temp){indexVar = temp;}
function setCID(temp){clientID = temp;}
function setOfficeID(temp){officeID = temp;}
function setAgentID(temp){agentID = temp;}
function setSiteID(temp){siteId = temp;}
function setMapZoom(temp){mapZoom = temp;}
function setDefault_lat(temp){defaultLat = temp;}
function setDefault_lon(temp){defaultLon = temp;}
function setDomain(temp){domainName = temp; url =  domainName + "/lib/map/get_listings_ve.php?stuff=" + new Date().getTime() + "&site_id=" + siteId;}
function setAgentData(temp){agentData = temp;}//not used?
function setOfficeData(temp){officeData = temp;}
function setRemoteLoc(temp){ remoteLocation = temp; }
function startMessage(displayMessage){om.Set(displayMessage);}
function pausedClearMessage(){window.setTimeout("om.Clear();", 1500);}
function clearMessage(){om.Clear();}

function GetMap(genNewID){

	map = new VEMap('map-search');

	var you_areHere = new VELatLong(defaultLat, defaultLon);
	mapZoom = parseInt(mapZoom);
	map.LoadMap(you_areHere, mapZoom);
	map.AttachEvent("onchangeview", getNewData);
	map.AttachEvent("onendzoom", getNewData);
	map.AttachEvent("onclick", '');

	AddResetControl();
	addLoadingMessage();
	createSearchCriteria(genNewID);
}


function AddResetControl(){
	if (control == null){
		control = document.createElement("div");
		control.id = "myControl";
		control.style.top ="140px";
		control.style.left = "3px";
		control.style.width="22px";
		control.style.height="22px";
		control.style.zIndex=1;

		var agent = navigator.userAgent.toLowerCase(); // Iuse AlphaImageLoader if IE
		if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){this.ie = true} else {this.ie = false}

		if (this.ie){// Handle transparent PNG files in MSIE
			var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+remoteLocation+"images/map/map_reset.png', sizingMethod='scale');";
			control.innerHTML = '<a href="javascript:void(0);" onClick="javascript:clearForm();" title="Reset The Map View"><div style="height:22px; width:22px; ' +loader+ '" ></div></a>';
		} else {
			var tempInnerHTML = '<a href="javascript:void(0);" onClick="javascript:clearForm();" title="Reset The Map View"><img src="'+remoteLocation+'"images/map/map_reset.png" width=22 height=22 border="0"/></a>';
			control.innerHTML = tempInnerHTML;
		}

		map.AddControl(control);
	}
}

function sendMessage(_msg){

	if(_msg != '' && debug==1){
		document.getElementById("message").innerHTML = _msg;
	}
}

function drawBaseMap(){

	map = new VEMap('map-search');

	document.getElementById("message").innerHTML = "";
	map.LoadMap(new VELatLong(defaultLat, defaultLon), 11, VEMapStyle.Hybrid, false);

	addLoadingMessage();
	loadingMessage.style.display = "inline";
   	return 1;
}


function getNewData(mapEvent){ createSearchCriteria(0); }

function AddMorePins(mls, lat, lng){

	var pin = new VEPushpin(
		mls,   /*Id*/
		new VELatLong(lat, lng),  /*location*/
		domainName + '/images/map/map_house1.gif', /*ICON*/
    	'', /*title*/
    	mls /*Details*/
    );

    VEPushpin.ShowDetailOnMouseOver = false;
    VEPushpin.OnMouseOverCallback = PinHover;

	pins[mls] = pin;
	pinIndex++;
	map.AddPushpin(pin);
}

function AddFeaturedPins(mls, lat, lng){

	var pin = new VEPushpin(
		mls,   /*Id*/
		new VELatLong(lat, lng),  /*location*/
		domainName + '/images/map/map_house2.gif', /*ICON*/
    	'', /*title*/
    	mls     /*Details*/
	);

	VEPushpin.ShowDetailOnMouseOver = false;
    VEPushpin.OnMouseOverCallback = PinHover;

	pins[mls] = pin;
	pinIndex++;
	map.AddPushpin(pin);
}

function AddOfficeAgentPinPoint(){

	//alert(officeData);
	tempData = officeData;
	tempData = tempData.split("-");

	var pin = new VEPushpin(
	tempData[0],   /*Id*/
	new VELatLong(defaultLat, defaultLon),  /*location*/
	domainName + '/images/map/icon12.gif', /*ICON*/
    	tempData[1], /*title*/
    	"officeid"     /*Details*/
	);

	pins[tempData[0]] = pin;
	map.AddPushpin(pin);
}

function createRequest(){
	try{request = new XMLHttpRequest();	}
	catch(trymicrosoft){
		try{request = new ActiveXObject("Msxm12.XMLHTTP");}
		catch(othermicrosoft){
			try{request = new ActiveXObject("Microsoft.XMLHTTP");	}
			catch(fail){request = null;}
		}
	}
	if(request == null){sendMessage("Error creating XMLHttpRequest!");}
}

function createSearchCriteria(genSid){

	if(usingRoute == 0){ DeletePin(); }

	var mapData = map.GetMapView();
	var mapArray = new Array(2);
	mapArray[0] = mapData.TopLeftLatLong;
	mapArray[1] = mapData.BottomRightLatLong;

	mapCenter = map.GetCenter();
	mapZoom = map.GetZoomLevel();

    try{
		createRequest();

		mapUrl = url + "&top=" + mapArray[0] + "&bottom=" + mapArray[1] + "&agent_id=" + agentID + "&office_id=" + officeID + "&index=" + indexVar;
		mapUrl += "&mapCenter=" + mapCenter + "&mapZoom=" + mapZoom + "&client_search=" + clientSearch + "&listingLinks=" + listingLinks;

		if(genSid == 1){ mapUrl+="&genID=1"; } else { mapUrl+="&sid="+sid; }

		if(document.getElementById("class_id").value != "")
		{	mapUrl = mapUrl + "&class_id=" + document.getElementById("class_id").value;		}

		if(document.getElementById("bedrooms").value != "")
		{	mapUrl = mapUrl + "&bedrooms=" + document.getElementById("bedrooms").value;		}

		if(document.getElementById("bathrooms").value != "")
		{	mapUrl = mapUrl + "&bathrooms=" + document.getElementById("bathrooms").value;	}

		if(document.getElementById("price_range_low").value != "")
		{	mapUrl = mapUrl + "&price_range_low=" + document.getElementById("price_range_low").value;	}

		if(document.getElementById("price_range_high").value != "")
		{	mapUrl = mapUrl + "&price_range_high=" + document.getElementById("price_range_high").value;	}

		sendMessage(mapUrl);
		if(setUrl==1){ document.getElementById("link_url").value = mapUrl; }
		request.open("GET", mapUrl, true);
		var updateMapResource = new updateMapOuter;
		request.onreadystatechange = updateMapResource;
		request.send(null);/**/

    } catch(err){ sendMessage(err); }
}

function updateMapOuter(){

	return function updateMap(){

		if(request.readyState == 4){// && request.status == 200

			var mapPoints = request.responseText;
			var tempMap = mapPoints.split("|");

			tempMap.reverse();
			var showListings = tempMap.pop();
			var listingsCount = tempMap.pop();
			var tempSid = tempMap.pop();
			if(tempSid != ""){ sid = tempSid; }

			if(showListings == 1){

				var tempListingsCount = listingsCount.split("+");
				clientSearch = tempListingsCount[2];

				if(tempListingsCount[0] == tempListingsCount[1]){
					var messageHTML = "Showing " + tempListingsCount[0] + " of " + tempListingsCount[1] + " Listings.";
					document.getElementById("message").innerHTML = messageHTML;
				} else {
					var messageHTML = "Showing " + tempListingsCount[0] + " of " + tempListingsCount[1] + " Listings.";
					document.getElementById("message").innerHTML = messageHTML;
				}

				var i = 0;
				//sendMessage(mapPoints);

				while(tempMap.length != 0){

					var data = tempMap.pop();
					var lat = tempMap.pop();
					var lng = tempMap.pop();

					var tempData = data.split("+");
					var mls = tempData[0];
					var toolTipData = "";
					var featuredListing = tempData[2]
					var classId = tempData[3];

					if(featuredListing == 1){
						AddFeaturedPins(mls, lat, lng);
					} else {
						AddMorePins(mls, lat, lng);
					}

				}


			} else if(showListings == 0){
				var messageHTML = "<font color='red'><b>" + listingsCount + " Results. Please narrow your search results.</b></font>";
				document.getElementById("message").innerHTML = messageHTML;
			}

			loadingMessage.style.display = "none";
			if(agentData != "" || officeData != ""){
				AddOfficeAgentPinPoint();
			}
		}
	}
}

function getMlsInfo(){

	try{
		// + "&sid=" + sid;

		mlsUrl = url + "&agent_id=" + agentID + "&office_id=" + officeID + "&mls=" + currentMls + "&sid=" + sid + "&client_search=" + clientSearch;
		sendMessage(mlsUrl);
		request.open("GET", mlsUrl, true);
		request.onreadystatechange = infoWindow;
		request.send(null);
	} catch(err){ sendMessage(err); }
}

function setFavorites(mls){
	try{
		favoritesUrl = url + "&cid=" + clientID + "&mls=" + currentMls + "&favorites=1";
		request.open("GET", favoritesUrl, true);
		request.onreadystatechange = favoritesComplete;
		request.send(null);
	} catch(err){ sendMessage(err); }
}

function favoritesComplete(){

	if(request.readyState == 4){
		var favoritesResponse = request.responseText;

		if(favoritesResponse == 1){
			document.getElementById("favorites").innerHTML = "<font color='blue'><b>This listing has been added to your Favorites.</b></font>";
		} else if(favoritesResponse == 2){
			document.getElementById("favorites").innerHTML = "<font color='blue'><b>This listing is already in your Favorites.</b></font>";
		} else if(favoritesResponse == 0){
			document.getElementById("favorites").innerHTML = "<font color='blue'><b>You must sign in to Use this Feature.</b></font>";
		}
	}
}

function infoWindow(){//x, y

	if(request.readyState == 4){// && request.status == 200

		var mapInfo = request.responseText;
		tempMapInfo = mapInfo.split("|");

		var mls = tempMapInfo[0];
		var lat = tempMapInfo[1];
		var lng = tempMapInfo[2];
		var featuredListing = tempMapInfo[3];
		var listingHTML = tempMapInfo[4];

		directionInfo = lat + "|" + lng + "|" + mls + "|" + featuredListing;

		ID = mls;
		pin = pins[ID];
	    var obj = pin.GetContent();
	    pin.Details = listingHTML;

	    var e = document.getElementById(ID+"_"+map.GUID);
		e.style.overflow = "hidden";

		if(e != null && e != "undefined"){

			var eroContent="<p>";
			if(pin.Title.length>0) eroContent+="<div class=\"VE_Pushpin_Popup_Title\">" + unescape(pin.Title) + "</div>";
			if(pin.Details.length>0)eroContent+="<div class=\"VE_Pushpin_Popup_Body\">" + unescape(pin.Details) + "</div>";
			eroContent+="</p>";

			window.ero.setContent(eroContent);
			window.ero.dockToElement(e);
		}
	}
}


function DeletePin(id){
	try{
    	if(id!=null){ map.DeletePushpin(id);}
    	else{ map.DeleteAllPushpins(); }
    } catch (err){ sendMessage(err.message); }
}

function ShowControl(){map.ShowDashboard();}
function HideControl(){map.HideDashboard();}

function PinHover(x, y, title, details){

	if(details == "officeid"){ showOfficeAgent(); }
	else {
		//alert("test");
		pin = pins[details];
		currentMls = details;
	    getMlsInfo();
	}
}

VEPushpin.prototype.GetContent = function(){

	var pinId=this.ID+"_"+this.m_vemap.GUID;
    var content="<img class='"+this.IconStyle+"' src='"+this.Iconurl+"' id='"+pinId+"' ";

	var isTitleValid=this.Title!=null&&this.Title!="undefined"&&this.Title.length>0;
  	var isDetailsValid=this.Details!=null&&this.Details!="undefined"&&this.Details.length>0;

	if(isTitleValid||isDetailsValid){

		    content+=" onmouseout='VEPushpin.Hide();' onmousedown='VEPushpin.Hide(true);' onclick='VEPushpin.Show(\""
		      +this.m_vemap.GUID
		      +"\",\""
		      +this.ID
		      +"\","
		      +this.LatLong.Latitude
		      +","+this.LatLong.Longitude;

		    if(isTitleValid){ content+=", \"" + escape(this.Title) + "\""; }
			else { content+=",\"\""; }

		    if(isDetailsValid) { content+=", \""+escape(this.Details)+"\""; }
		    else { content+=",\"\""; }

		    content+=",\"" + this.TitleStyle + "\"";
		    content+=",\"" + this.DetailsStyle + "\"";
		    content+=");' ";
	}
    content+=" />";
    return content;
}

function GetDirections(){

	var pinPointInfo = directionInfo;
	var userCity = prompt("Please enter the city and state you will be starting from:\ni.e.(Seattle, Wa.)"+pinPointInfo, '');
	if(userCity == null || userCity == ""){ userCity = prompt("Please enter the city and state you will be starting from:\ni.e.(Seattle, Wa.)"+pinPointInfo, ""); }
	if(userCity == null || userCity == ""){ alert("No Route can be displayed without a starting City."); }

	else{

		usingRoute = 1;

		pinPointInfo = pinPointInfo.split("|");
		var lat = pinPointInfo[0];
		var lng = pinPointInfo[1];
		var routeMls = pinPointInfo[2];
		var featuredListing = pinPointInfo[3];

		DeletePin();
		HideControl();

		if(featuredListing == 1)
		{	AddFeaturedPins(routeMls, lat, lng);	}
		else
		{	AddMorePins(routeMls, lat, lng);	}

		VEPushpin.ShowDetailOnMouseOver = true;
		var routeInfo = map.GetRoute(userCity, new VELatLong(lat, lng), null, null, onGotRoute);
		map.SetMapStyle(VEMapStyle.Road);

		addRouteControl(routeInfo);

	}
}

function addRouteControl()
{
	var controlHTML = "<input id=\"displaydirections\" type=\"button\" value=\"&nbsp;&nbsp;Directions&nbsp;\" onclick=\"displayDirections();\"/>";
	controlHTML += "<input id=\"closeroute\" type=\"button\" value=\"Close Route\" onclick=\"deleteRoute();\"/>";

	routeControl = document.createElement("div");
	routeControl.style.top ="10px";
	routeControl.style.left = "10px";
	routeControl.innerHTML = controlHTML;
	map.AddControl(routeControl);
}


function onGotRoute(route)
{
	routeinfo = "Route info:\n\n";
	routeinfo +="Total distance: ";
	routeinfo +=   route.Itinerary.Distance+" ";
	routeinfo +=   route.Itinerary.DistanceUnit+"\n\n";

	var steps="";
	var len = route.Itinerary.Segments.length;

	for(var i = 0; i < len ;i++)
	{
		if(route.Itinerary.Segments[i].Instruction == "Arrive at ")
		{
			var segmentInstruction = "Arriving at Destination ";
		}
		else
		{
			var segmentInstruction = route.Itinerary.Segments[i].Instruction;
		}

		steps += "Step " + i + ": " + segmentInstruction + " -- (";

		if(route.Itinerary.Segments[i].Distance == null)
		{
			var segmentDistance = 0;
		}
		else
		{
			var segmentDistance = route.Itinerary.Segments[i].Distance;
		}

		steps += segmentDistance + ") "; //route.Itinerary.Segments[i].Distance+") ";
		steps += route.Itinerary.DistanceUnit + "\n";
	}

	routeinfo += steps;
}


function displayDirections(){ alert(routeinfo); }
function closeRoute(){ deleteRoute(); }

function deleteRoute(){

	try{
		usingRoute = 0;
		map.DeleteRoute();
		routeControl.style.display = "none";
		ShowControl();
		map.SetZoomLevel(10);
	}
	catch (err){ sendMessage(err.message); }
}

function findSpecificLocation()
{
	var userCity = prompt("What Location do you want to find:\nUse the Form: 126 E. Johnson, Chelan, Wa.", '');

	if(userCity == null || userCity == ""){ userCity = prompt("What Location do you want to find:\nUse the Form: 126 E. Johnson, Chelan, Wa.", ""); }
	if(userCity == null || userCity == ""){ alert("No Location can be displayed."); }
	else { map.FindLocation(userCity); }
}


function addLoadingMessage(){

	loadingMessage = document.createElement("div");
	loadingMessage.style.top ="250px";
	loadingMessage.style.left = "175px";
	loadingMessage.style.border = "2px solid black";
	loadingMessage.style.background = "#666666";
	loadingMessage.style.display = "none";
	//loadingMessage.style.color = "#ffffff";
	//loadingMessage.style.font-size = "12px";
	loadingMessage.innerHTML = controlHTML;
	map.AddControl(loadingMessage);
}


function showOfficeAgent(){

	alert(officeData);

	tempData = officeData.split("-");

	var tempOfficeId = tempData[0];
	var tempOfficeName = tempData[1];
	var tempOfficeStreetAddress = tempData[2];
	var tempOfficeCity = tempData[3];
	var tempOfficeState = tempData[4];
	var tempOfficeCounty = tempData[6];
	var tempAreaCode = tempData[7];
	var tempPhoneNumber = tempData[8];

	ID = tempOfficeId;
	pin = pins[ID];
    	var obj = pin.GetContent();
    	pin.Details = tempOfficeStreetAddress + "<br/>" + tempOfficeCity + ", " + tempOfficeState;
    	pin.Details += "<br/>(" + tempAreaCode + ") " + tempPhoneNumber;

    	var e=document.getElementById(ID+"_"+map.GUID);

	if(e != null && e != "undefined"){

		window.ero.setBoundingArea(
		new Microsoft.Web.Geometry.Point(0,0),
		new Microsoft.Web.Geometry.Point(document.body.clientWidth,document.body.clientHeight));

		var eroContent="<p>";

		if(pin.Title.length>0) eroContent+="<div class=\"VE_Pushpin_Popup_Title\">"+unescape(pin.Title)+"</div>";

		if(pin.Details.length>0)eroContent+="<div class=\"VE_Pushpin_Popup_Body\">"+unescape(pin.Details)+"</div>";

		eroContent+="</p>";

		window.ero.setContent(eroContent);
		window.ero.dockToElement(e);
	}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
	w = window.open(theURL,winName,features);
	w.focus();
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != "function") {window.onload = func;} else {window.onload = function () {oldonload();func();}}
}
function addUnloadEvent(func) {
	var oldonunload = window.onunload;
	if (typeof window.onunload != "function") {window.onunload = func;} else {window.onunload = function () {oldonunload();func();}}
}
