﻿//=================
// AddressGo flow
//=================
/*
	Summary:
		AddressGo attempts to parse input into a matching property by ML# or address.  
		If neither of those match it forwards the user to the appropriate PropertySearch page.
		Central to the process flow is the SearchOptions structure which is populated within 
		the SetSearchOptions function to be appropriate for the site code.

	Steps:
		1. Set SearchOptions to be appropriate for the site. (MFR, SND, etc.)
		2. If the input is blank determine whether to exit based upon the site.
				*SearchOptions.ExitOnEmptySearch : boolean
		3. If the input matches MLNumber syntax Call MyAjaxService.PropertyMLLookup wait for the callback and we're done. 
				*SearchOptions.MLPattern : regex
		4. Parse input into address and zip
		5. Call MyAjaxService.PropertyAddressLookup.
		6. Receive the callback from PropertyAddressLookup.
		7. If PropertyAddressLookupCallback receives a valid SysPropertyId then go to PropDetail for the property and we're done.
		8. Strip the last word from the address lookup and recursively call PropertyAddressLookup 
		9. Repeat previous step until we find a result or there are 2 or fewer words. 
		10. If no match can be found we forward to the GotoURL location
*/

//Global variables
var GotoURL = "";
var CurrentAddr = "";
var CurrentZipCode = "";
var SiteCode = "";
var MLNumber = "";

//Structure to hold site specific information relevant to the property search process
SearchOptions = { 
	MLPattern: null, 
	SiteContentUrl: "SiteContent/PropertySearch.aspx", 
	ExitOnEmptySearch: true 
};

function AddressGo(DefaultCityStZip, inputId) {
	var Addr = { str: GetVal(inputId) };

	if (Addr.str.length == 0) return; 

	SiteCode = $get("hSiteCode").value;
	SetSearchOptions(SiteCode);

	// If no entry exit early.
	if ((SearchOptions.ExitOnEmptySearch) && (0 == Addr.str.length)) return;

	DimPage();

	//Is Addr.str a potential MLNumber? Updates MLNumber if a match is found
	if (InputIsMLNumber()) {
		MyAjaxService.PropertyMLLookup(MLNumber, "0,0,0,0", PropertyMLLookupCallback, FailedCallback);
		return;
	}	

	var zipPattern = /(\d{5}(-\d{4})?$)|([ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)/
	var Zip = FindAndReplace(zipPattern, Addr);
	if (Zip.length == 0) {
		Zip = "";
	}

	var url = "?Addr=" + escape(Addr.str) + "&CityStZip=" + escape(Zip);
	GotoURL = FullURL(SearchOptions.SiteContentUrl + url);

	MyAjaxService.PropertyAddressLookup(Addr.str, Zip, PropertyAddressLookupCallback, FailedCallback);

	function FindAndReplace(regex, string) {
		var result = regex.exec(string.str);
		if (result != null && result.length > 0) {
			string.str = TRIM(string.str.replace(result[0], ""));
		} else {
			result = new Array();
			result[0] = "";
		}
		return result[0];
	}

	function InputIsMLNumber() {
		if (SearchOptions.MLPattern != null) {
			MLNumber = FindAndReplace(SearchOptions.MLPattern, Addr);
		}
		if (MLNumber.length > 0) {
			return true;
		}
	}
}

function SetSearchOptions(source) {
	//set defaults
	SearchOptions.SiteContentUrl = "SiteContent/PropertySearch.aspx";
	SearchOptions.MLPattern = null;

	//override per source if necessary
	switch (source) {
		case "LAS":
			SearchOptions.SiteContentUrl = "SiteContent/LAS/PropertySearchLAS.aspx";
			break;
		case "MFR":
			SearchOptions.MLPattern = /^[A-Za-z][0-9]+$/;
			break;
		case "NYS":
			SearchOptions.MLPattern = /^(R|r)[0-9]+/;
			break;
		case "OKC":
			SearchOptions.MLPattern = /^[0-9]{6}$/;
			break;
		case "SND":
			SearchOptions.SiteContentUrl = "SiteContent/SND/PropertySearchSND.aspx";
			SearchOptions.MLPattern = /^[0-9]{9}$/;
			SearchOptions.ExitOnEmptySearch = false;
		default:
			break;
	}
}


function PropertyAddressLookupCallback(SysPropID) {
	// If this address is for an active listing, then show the detail, else just go to 
	// regular property search centered on this address
	if (SysPropID.length > 0) {
		var aSysID = (SysPropID + ",,").split(",");
		GotoURL = CreateNoCookieURL("SiteContent/PropDetail.aspx?N=0&S=" + aSysID[0] + "&id=" + aSysID[1]);
		var SiteCode = $get("hSiteCode").value;
		if (SiteCode == "Demo") GotoURL = GotoURL.replace("Content/PropDetail.aspx", "Content/Demo/PropDetailDemo.aspx");
		document.location.href = GotoURL;
		return
	}
	// If not found but there are more than 2 words to this address, try dropping the last word (e.g. street) and try again
	var aAddr = CurrentAddr.split(" ");
	if (aAddr.length > 2) {
		CurrentAddr = aAddr.slice(0, length - 1).join(" ");
		if (CurrentAddr.length > 0) {
			MyAjaxService.PropertyAddressLookup(CurrentAddr, CurrentZipCode, PropertyAddressLookupCallback, FailedCallback);
			return;
		}
	}

	document.location.href = GotoURL;
}


function PropertyMLLookupCallback(Result) {
	//We had good reason to believe the user entered an ML number.
	//This is the callback from MyAjaxService
	if (0 == Result.length) {
		
		//Orlando ML numbers start with a capital O but users may think it's a zero
		if ("0" == MLNumber.substring(0, 1)) { // Try replacing leading zero with the letter O
			MLNumber = "O" + MLNumber.substr(1);
			MyAjaxService.PropertyMLLookup(MLNumber, "0,0,0,0", PropertyMLLookupCallback, FailedCallback);
		} else alert("Listing # Not found")
		return;
	}
	var Res = (Result + ",").split(",")
	GotoURL = CreateNoCookieURL("SiteContent/PropDetail.aspx?N=0&S=" + Res[0] + "&ID=" + Res[1]);
	if (SiteCode == "Demo") GotoURL = GotoURL.replace("Content/PropDetail.aspx", "Content/Demo/PropDetailDemo.aspx");
	document.location.href = GotoURL;
}

function GetVal(CtrlName) {
	var oCtrl = $get(CtrlName);
	if (!oCtrl) return "";
	var Val = oCtrl.value
	// Remove the help text that might be in an empty field
	var Text = "!"
	if (oCtrl.getAttribute) Text = oCtrl.getAttribute("title");
	return TRIM(Val.replace(Text, ""));
}

function StartAreaSearch(CtrlName) {
	// If user enters a City, Zip or Subdivision, go to Search screen with search criteria filled in.
	var Entry = GetVal(CtrlName);
	var VisitorID = $get("hEncryptedVisitorID").value
	DimPage()
	MyAjaxService.ValidAreaLookup(Entry, VisitorID, ValidAreaCallBack, FailedCallback);
}

function ValidAreaCallBack(Parms) {
	// We wait for return to sure that the Area field has been filled in.
	var SiteCode = $get("hSiteCode").value;
	switch (SiteCode) {
		case "MFR":
		case "OKC":
		case "NYS":
		case "Demo":
			GotoURL = FullURL("SiteContent/PropertySearch.aspx"); break;
		case "LAS": GotoURL = FullURL("SiteContent/LAS/PropertySearchLAS.aspx"); break;
		default: alert("Missing SiteCode Handler in StartAreaSearch():" + SiteCode);
	}
	document.location.href = GotoURL;
}

function DimPage() {
	$get("form1").style.backgroundColor = "#cccccc";
	$get("form1").style.backgroundColor = "#999999";
}


function Initialize() {
	var Site = $get("hSiteCode").value;

	FixNoCookieLinks();
	GoogleAnalytics();
	iPad_Lock();

	var oDiv = $get("flashcontent")
	BgColor = GetAttrStr(oDiv, "bgColor", "");
	PMovie = GetAttrStr(oDiv, "pMovie", "");
	AttribID = GetAttrStr(oDiv, "attribID", "");
	AttribName = GetAttrStr(oDiv, "attribName", "");
	EmbedPath = GetAttrStr(oDiv, "embedPath", "");
	EmbedWidth = GetAttrStr(oDiv, "embedWidth", "");
	EmbedHeight = GetAttrStr(oDiv, "embedHeight", "");

	if ("COOP" == Site) {
		var flashvars = {};
		var params = {
			quality: "high",
			play: "true",
			loop: "true",
			scale: "showall",
			wmode: "transparent",
			devicefont: "false",
			bgcolor: "#ffffff",
			menu: "true",
			allowfullscreen: "false",
			allowscriptaccess: "sameDomain",
			movie: "SiteContent/OKC/Images/OKC_Map_w5.swf"
		};
		var attributes = {
			id: "MyMLSMapW9",
			name: "MyMLSMapW9",
			align: "middle",
			wmode: "transparent"
		};
		// need to adjust map size to fit space available
		// image is oversized so that background is consistent for odd-shaped browser windows
		var h = 1.6 * GetScreenHeight();
		var w = 1.6 * GetScreenWidth();
		var AspectRatio = 900.0 / 645.0;
		w = Math.min(w, h * AspectRatio);
		h = Math.min(h, w / AspectRatio);
		var oImg = $get("imgMap")
		oImg.style.width = w + "px";

		swfobject.embedSWF("Images/MyMLSMapW08.swf", "flashcontent", w, h, "9.0.0", flashvars, params, attributes);
	}
	else {
		var flashvars = {};
		var params = {
			quality: "high",
			play: "true",
			loop: "true",
			scale: "showall",
			wmode: "transparent",
			devicefont: "false",
			bgcolor: BgColor,
			menu: "true",
			allowfullscreen: "false",
			allowscriptaccess: "sameDomain",
			movie: PMovie
		};
		var attributes = {
			id: AttribID,
			name: AttribName,
			wmode: "transparent",
			align: "middle"
		};
		swfobject.embedSWF(EmbedPath, "flashcontent", EmbedWidth, EmbedHeight, "9.0.0", flashvars, params, attributes);
		return;
	}
}

//===========================
//  Image Map drill in
//===========================

function DrillInMapControl(containingDiv, overviewDiv, overviewMap, detailDiv, detailMap, zoomOut, leftEdgeMapContainer, topEdgeMapContainer) {

	var lat = 0.0;
	var lon = 0.0;

	this.DrillIn = function (ev) {
		overviewDiv.style.display = "none";
		detailDiv.style.display = "block";
		zoomOut.style.display = "inline";

		// Compute location of top left corner of the mapcontainer relative to the screen
		var MouseLoc = getMouseOffset(containingDiv, ev);
		var Scroll = getScrollXY();

		var TopOffsetZoomedMap = topEdgeMapContainer - Math.floor(detailMap.height * (MouseLoc.y + Scroll.Y) / containingDiv.clientHeight);
		var LeftOffsetZoomedMap = leftEdgeMapContainer - Math.floor(detailMap.width * (MouseLoc.x + Scroll.X) / containingDiv.clientWidth);

		detailDiv.style.top = TopOffsetZoomedMap + "px";
		detailDiv.style.left = LeftOffsetZoomedMap + "px";
	}
	this.ZoomOut = function () {
		overviewDiv.style.display = "block";
		detailDiv.style.display = "none";
		zoomOut.style.display = "none";
	}
	this.SelectByLatLon = function (ev, topLeft, bottomRight) {
		// Compute location of top left corner of the mapcontainer relative to the screen
		var MouseLoc = getMouseOffset(detailMap, ev);
		var Scroll = getScrollXY();

		lat = topLeft.lat - (MouseLoc.y + Scroll.Y) * (topLeft.lat - bottomRight.lat) / detailMap.clientHeight;
		lon = topLeft.lon + (MouseLoc.x + Scroll.X) * (bottomRight.lon - topLeft.lon) / detailMap.clientWidth;
		MyAjaxService.RememberSetting("isListView", "N", $get("hEncryptedVisitorID").value, LatLonCallback, LatLonCallback);
	}

	function LatLonCallback() {
		var Site = $get("hSiteCode").value;
		var URL = "SiteContent/PropertySearch.aspx?Lat=" + lat + "&Lon=" + lon
		if (Site=="SND") URL = URL.replace("PropertySearch.aspx","SND/PropertySearchSND.aspx")

		document.location.href = CreateNoCookieURL(URL);
	}

	function getMouseOffset(target, ev) {
		ev = ev || window.event;
		var docPos = getPosition(target);
		var mousePos = mouseCoords(ev);
		return { x: mousePos.x - docPos.x, y: mousePos.y - docPos.y };
	}
	function getScrollXY() {
		var scrOfX = 0, scrOfY = 0;
		if (typeof (window.pageYOffset) == 'number') {
			//Netscape compliant
			//Both Chrome and Firefox work better without the offset factor
			return { X: 0, Y: 0 };
		} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
			//DOM compliant
			alert("DOM compliant");
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
			//IE6 standards compliant mode
			//alert("IE6 compliant");
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		return { X: scrOfX, Y: scrOfY };
	}
	function getPosition(e) {
		var left = 0;
		var top = 0;

		while (e.offsetParent) {
			left += e.offsetLeft;
			top += e.offsetTop;
			e = e.offsetParent;
		}

		left += e.offsetLeft;
		top += e.offsetTop;
		return { x: left, y: top };
	}
	function mouseCoords(ev) {
		if (!ev) return { x: 0, y: 0 }
		if (ev.pageX && ev.pageY) return { x: ev.pageX, y: ev.pageY };
		if ((!ev.clientX) || (!ev.clientY)) return { x: 0, y: 0 }
		if (!document.body) return { x: 0, y: 0 }

		return {
			x: ev.clientX + document.body.scrollLeft - document.body.clientLeft,
			y: ev.clientY + document.body.scrollTop - document.body.clientTop
		};
	}
}




function LatLong(latitude, longitude) {
	this.Latitude = latitude;
	this.Longitude = longitude;
}









//		function Goto(Location){
//		var Area = "";
//		var Site = $get("hSiteCode").value;
//		var ID = $get("hEncryptedVisitorID").value
//			
//				switch(Site)
//				{
//					case "Demo":
//						switch (Location){
//							case "LAS": Area="Las Vegas, NV"; break;
//							case "HHI": Area="Hilton Head, SC"; break;
//							case "MFR": Area="Polk County, FL"; break;
//						}
//						MyAjaxService.RememberSetting("ZoomLevel",0,ID); // Reset the map to center on default address
//						document.location.href=FullURL("SiteContent/PropertySearch.aspx?Area=" + Area);
//						return;		
//						break;
//						
//				
//					case "HHI":
//					case "LAS":
//					case "MFR":
//						switch (Location){
//							case "BR" : Area = "Brevard County, FL"; break;
//							case "CH" : Area = "Charlotte County, FL"; break;
//							case "DS" : Area = "DeSoto County, FL"; break;
//							case "HD" : Area = "Hardee County, FL"; break;
//							case "HC" : Area = "Hernando County, FL"; break;
//							case "HL" : Area = "Highlands County, FL"; break;
//							case "HB" : Area = "Hillsborough County, FL"; break;
//							case "IR" : Area = "Indian River County, FL"; break;
//							case "LK" : Area = "Lake County, FL"; break;
//							case "MT" : Area = "Manatee County, FL"; break;
//							case "MA" : Area = "Marion County, FL"; break;
//							case "OK" : Area = "Okeechobee County, FL"; break;
//							case "OC" : Area = "Orange County, FL"; break;
//							case "OS" : Area = "Osceola County, FL"; break;
//							case "PO" : Area = "Pasco County, FL"; break;
//							case "PN" : Area = "Pinellas County, FL"; break;
//							case "PK" : Area = "Polk County, FL"; break;
//							case "SA" : Area = "Sarasota County, FL"; break;
//							case "SM" : Area = "Seminole County, FL"; break;
//							case "SU" : Area = "Sumter County, FL"; break;
//							case "SL" : Area = "St. Lucie County, FL"; break;
//							case "VL" : Area = "Volusia County, FL"; break;
//							default: alert("Unknown region: " + Location); Area=""; return;
//						}

//						MyAjaxService.RememberSetting("ZoomLevel",0,ID); // Reset the map to center on default address
//						document.location.href=FullURL("SiteContent/PropertySearch.aspx?Area=" + Area);
//						return;		
//						break;
//						
//						
//					case "OKC":
//						switch (Location){
//							case "CA": Area="Canadian County, OK"; break;
//							case "PK": Area="Oklahoma County, OK"; break;
//							case "LI": Area="Lincoln County, OK"; break;
//							case "CD": Area="Caddo County, OK"; break;
//							case "GR": Area="Grady County, OK"; break;
//							case "MC": Area="McClain County, OK"; break;
//							case "CL": Area="Cleveland County, OK"; break;
//							case "PO": Area="Pottawatomie County, OK"; break;
//							case "KF": Area="Kingfisher County, OK"; break;
//							case "LO": Area="Logan County, OK"; break;
//							//top unkowns
//							case "MA": Area="Major County, OK"; break;
//							case "GF": Area="Garfield County, OK"; break;
//							case "NO": Area="Noble County, OK"; break;
//							case "PY": Area="Payne County, OK"; break;
//							case "PW": Area="Pawnee County, OK"; break;
//							//left side unknowns
//							case "DW": Area="Dewey County, OK"; break;
//							case "CU": Area="Custer County, OK"; break;
//							case "WA": Area="Washita County, OK"; break;
//							case "KI": Area="Kiowa County, OK"; break;
//							case "BL": Area="Blaine County, OK"; break;
//							case "CO": Area="Comanche County, OK"; break;
//							//right side unknowns
//							case "CK": Area="Creek County, OK"; break;ar
//							case "OF": Area="Okfuskee County, OK"; break;
//							case "SE": Area="Seminole County, OK"; break;
//							case "PT": Area="Pontotoc County, OK"; break;
//							//bottom unknowns
//							case "SN": Area="Stephens County, OK"; break;
//							case "GV": Area="Garvin County, OK"; break;
//								//Area="Extended Area in OK"; break;
//								
//							default: alert("Unknown region: " + Location); Area=""; return;
//						}
//						MyAjaxService.RememberSetting("ZoomLevel",0,ID); // Reset the map to center on default address
//						document.location.href=FullURL("SiteContent/PropertySearch.aspx?Area=" + Area);
//						return;		
//						break;		
//					
//					case "COOP": parent.MenuFrame.ToggleMLSList(Location);
//						return;
//						
//					default: alert("Missing Site: " +Site);
//		
//				}
//				document.location.href="NotAvail.htm";
//	}
	
