﻿/// <reference path="~/MapSearchControl.aspx" />
/// <reference path="HillsideUI.js" />
/// <reference path="MapState.js" />
/// <reference path="MapSearchControl.Core.js" />
/// <reference path="MapObjects-Search.js" />

var mapSearchWindow;
var locationProvided = false;
var SignupMessage = new Object();

SignupMessage.MorePics = "<div align=\"center\" style=\"font-size: 12px;\">In order to access the additional photos you must first create an account. Once you have an account you get much more than just photos, you also get:</div><ul style=\"font-size: 12px; margin: 1px;\"><li>Your own <span style=\"color: red\">Password Protected Personal Buyer Website</span></li><li><span style=\"color: red\">Save the Listings</span> that you like</li><li><span style=\"color: red\">Email Notifications for new listings</span> that come on the Market</li><li>Access all <span style=\"color: red\">Virtual tours</span></li><li>And more...</li></ul>This is a completely free service so sign up and get started today!<br />";
SignupMessage.SaveListing = "<div align=\"center\" style=\"font-size: 12px;\">In order to save this property you must first create an account. Once you have an account you get much more than simply a place to track your favorite properties, you also get:</div><ul style=\"font-size: 12px; margin: 1px;\"><li>Your own <span style=\"color: red\">Password Protected Personal Buyer Website</span></li><li><span style=\"color: red\">Email Notifications for new listings</span> that come on the Market</li><li>Access all <span style=\"color: red\">Virtual tours</span></li><li>And more...</li></ul>This is a completely free service so sign up and get started today!<br />";

try {
	if (navigator.geolocation) {
		locationProvided = true;
	}
} catch (e) {
	/* Do Nothing */
}

function loadCurrentPosition() {
	navigator.geolocation.getCurrentPosition(function(position) {
		alert(position.coords.latitude + ", " + position.coords.longitude);
		map.SetCenter(new VELatLong(position.coords.latitude, position.coords.longitude));
	}, getLocationError);
}

function getLocationError(errCode) {
	if (errCode.code == 1) {
		alert("Permission to access your current location was denied.");
	}
	if (errCode.code == 2) {
		alert("Your location could not be determined by the browser.");
	}
	if (errCode.code == 3) {
		alert("Location request took too long. Your location could not be determined by the browser.");
	}
}

function openMapSearch() {
	if (!CurrentAgent || !CurrentAgent.WebID || CurrentAgent.WebID < 10001) {alert("No WebID found. Please let our support team know about this issue at:\n\nEmail: Support@Hillsoft.com\nTel: (303) 221-4444");}
	mapSearchWindow = window.open("MapSearchControl.aspx?wID=" + CurrentAgent.WebID, "_blank", "resizable=yes,location=no,scrollbars=no,toolbar=no,status=yes,menubar=yes,left=15,top=15,address=no");
}

function TrimSpaces(str) {
	matchWhitespaceBegin = /^\s+/;
	matchWhitespaceEnd = /\s+$/;
	//Example str: str = " 	\nSmith, John  ";
	newstr = str.replace(matchWhitespaceBegin, "");
	newstr = newstr.replace(matchWhitespaceEnd, "");
	return newstr;
}

function getISOTimezoneOffset() {
  var dif  = this.getHours()-this.getUTCHours();
  var hDif = Math.abs(dif);
  var m    = this.getMinutes();
  var mUTC = this.getUTCMinutes();

  if(m!=mUTC&&mUTC<30&&dif<0){ hDif--; }
  if(m!=mUTC&&mUTC>30&&dif>0){ hDif--; }

  return(((dif<0)?'-':'+')+((hDif<10)?'0'+hDif:''+hDif)+':'+((m!=mUTC)?'30':'00'));
}
Date.prototype.getISOTimezoneOffset = getISOTimezoneOffset;

function getISOTimezoneOffsetMinutes() {
  var dif  = this.getHours()-this.getUTCHours();
  var hDif = Math.abs(dif);
  var m    = this.getMinutes();
  var mUTC = this.getUTCMinutes();
  var minutesOffset = 0;

  if(m!=mUTC&&mUTC<30&&dif<0){ hDif--; }
  if(m!=mUTC&&mUTC>30&&dif>0){ hDif--; }

	minutesOffset = parseFloat(hDif * 60);
	if (m!=mUTC) {minutesOffset += 30;}
	if (dif<0) {minutesOffset = minutesOffset * -1;}

  return minutesOffset;
}
Date.prototype.getISOTimezoneOffsetMinutes = getISOTimezoneOffsetMinutes;

/*** (Previously) Inline Script Block (#1) ***/
	var ol_width=340;
	var ol_fgcolor='#FFFFFF';
	var ol_bgcolor='#777698';
	var ol_border='3';
	var ol_textsize='2';

	var ErrorFlag_SetScreen = false;
	var frameWidth = 0;
	var frameHeight = 0;
	var frameSize;
	var objFrameSize = new Array();
	frameSize = _getCookie("HCScript=ScreenSize");
	if (frameSize) {objFrameSize = frameSize.split("|");}
	if (frameSize != "-1|-1" && objFrameSize.length > 1) {
		frameWidth = objFrameSize[0];
		frameHeight = objFrameSize[1];
	}

/*** (Previously) Inline Script Block (#2) ***/
	function loginRequiredNote() {alert("Please Login.\n\nLogin required before you can use this functionality.");}
	function onCallbackError() {ErrorFlag_SetScreen = true; return;}

	function setScreenInfo() {
		if (ErrorFlag_SetScreen) {return; /* We encountered an error already trying this from this *currently* viewed/loaded page... */}
		try {
			if (document.documentElement && document.documentElement.clientWidth) {
				if (navigator.userAgent.toLowerCase().indexOf("safari") > -1) {
					//alert(document.documentElement.clientWidth)
				}
				frameWidth = document.documentElement.clientWidth;
				frameHeight = document.documentElement.clientHeight;
			} else if (self.innerWidth) {
				frameWidth = self.innerWidth;
				frameHeight = self.innerHeight;
			} else if (document.body) {
				frameWidth = document.body.clientWidth;
				frameHeight = document.body.clientHeight;
			} else {
				return;
			}
			/* alert("frameWidth: " + frameWidth + "\nframeHeight: " + frameHeight); */
			if (frameWidth > 1 && frameHeight > 1) {
				/* Upgraded by Dan: Use COOKIES - easier on server load and UI/UX speed */
				//alert(frameWidth + "|" + frameHeight);
				_setCookie("HCScript=ScreenSize", frameWidth + "|" + frameHeight);
				//alert("frameWidth: " + _getCookie("frameWidth") + "\n" + "HCScript=ScreenSize: " + _getCookie("HCScript=ScreenSize"));
			}
		} catch (e) {
			throw (e);
			ErrorFlag_SetScreen = true;
		}
	}
	function checkAndInitScreenInfo() {
		if (frameWidth <= 0 || frameHeight <= 0) {
			setScreenInfo();
		}
		/* Added By: Dan L. - 04/15/2007 */
		setTimezoneOffset();
	}

	function getExpandedNavBar1State() {
		var strIDs = new String();
		var strID = new String();
		var navBar1 = eval(navBar1Name);
		var rootItems = navBar1.get_items();
		for (var i = 0; i < rootItems.get_length(); i++) {
			if (rootItems.getItem(i).get_expanded()) {strID = rootItems.getItem(i).get_id();}
		}
		return strID;
	}

	function setExpandedNavBar1State(strIDs) {
		var IDs = new Array();
		IDs = strIDs.split(",");
		var navBar1 = eval(navBar1Name);
		var rootItems = navBar1.get_items();
		
		for (var i = 0; i < IDs.length; i++) {
			if (navBar1.findItemById(IDs[i])) {navBar1.findItemById(IDs[i]).set_expanded(true);}
		}
		//return strIDs;
	}

	function NavBar1_onItemExpand(sender, eventArgs) {
		_setCookie("NavBar1=SelectedID", getExpandedNavBar1State());
	}
	function NavBar1_onItemCollapse(sender, eventArgs) {
		//_setCookie("NavBar1=SelectedID", getExpandedNavBar1State());
	}
	function NavBar1_onLoad(sender, eventArgs) {
		var IDList = _getCookie("NavBar1=SelectedID");
		if (IDList) {setExpandedNavBar1State(IDList);}
	}

	/* Added By: Dan L. - 04/15/2007 */
	function setTimezoneOffset() {
		var TimezoneDate = new Date();
		_setCookie("HCAdmin=Timezone", TimezoneDate.getISOTimezoneOffsetMinutes());
	}

	function summaryRowHover(row) {
		row.className = "SummaryRowHover";
	}
	function summaryRowOut(row) {
		row.className = "SummaryRow";
	}
	function loadSummary(SummaryType, DaysBack) {
		//ActivitySummaryList.aspx?wID=10001&Type=Logins&DaysBack=30
		self.location.href = "ActivitySummaryList.aspx?wID=" + CurrentAgentWebID + "&Type=" + SummaryType + "&DaysBack=" + DaysBack;
	}


//move 
function moveOption(selectO, to) {
	var index = selectO.selectedIndex;
	var selectLength	= selectO.length - 1;
	//error handling ... //nothing selected
	if (index == -1) return false;
	if(to == +1 && index == selectLength) {
		return false; //("Cannot move down anymore!");
	} else if (to == -1 && index == 0) {
		return false; //("Cannot move up anymore!");
	}
	swapOption(index,index+to,selectO);
	return true;
}

function swapOption(fIndex, sIndex, selectO) {
	//store first
	fText	= selectO.options[fIndex].text;
	fValue = selectO.options[fIndex].value;
	//make first = second
	selectO.options[fIndex].text	= selectO.options[sIndex].text;
	selectO.options[fIndex].value = selectO.options[sIndex].value;	
	//make second = first
	selectO.options[sIndex].text = fText;
	selectO.options[sIndex].value = fValue;
	//amke new one be selected
	selectO.options[sIndex].selected = true;		
	//maintain field that stores order
	recalculateOrder(selectO);
}

//return current order
function recalculateOrder(selectO) {
	var sep = "";
	var newOrderText = "";
	for (i = 0; i <= selectO.options.length-1; i++) {	 
		newOrderText += "" + sep + selectO.options[i].value;
		sep = ",";
	}
	return newOrderText;
}

function addOptionToSelect(select, text, value) {
	if (!value) {value = text;}
	select.options[select.options.length] = new Option(text, value);
}
function getOptIndexByValue(select, value) {
	for (i = 0; i <= select.options.length-1; i++) {	 
		if (select.options[i].value.toString().toLowerCase() == value.toString().toLowerCase()) {
			/* Found matching index */
			return i;
		}
	}
	/* no match found */
	return -1;
}

/* Inspiration & Credit: SalesForce.com */
function formatPhone(field) {
	field.value = trim(field.value);

	var ov = field.value;
	var v = "";
	var x = -1;

	// is this phone number 'escaped' by a leading plus?
	if (0 < ov.length && '+' != ov.charAt(0)) { // format it
		// count number of digits
		var n = 0;
		if ('1' == ov.charAt(0)) {  // skip it
			ov = ov.substring(1, ov.length);
		}

		for (i = 0; i < ov.length; i++) {
			var ch = ov.charAt(i);

			// build up formatted number
			if (ch >= '0' && ch <= '9') {
				if (n == 0) v += "(";
				else if (n == 3) v += ") ";
				else if (n == 6) v += "-";
				v += ch;
				n++;
			}
			// check for extension type section;
			// are spaces, dots, dashes and parentheses the only valid non-digits in a phone number?
			if (!(ch >= '0' && ch <= '9') && ch != ' ' && ch != '-' && ch != '.' && ch != '(' && ch != ')') {
				x = i;
				break;
			}
		}
		// add the extension
		if (x >= 0) v += " " + ov.substring(x, ov.length);

		// if we recognize the number, then format it
		if (n == 10 && v.length <= 40) field.value = v;
	}
	return true;
}

function formatNumber(myNumber, decimalPlaces) {
	//decimalPlaces  - the number of decimals after the digit from 0 to 3
	//-- Returns the passed number as a string in the xxx,xxx.xx format.
	anynum = eval(myNumber);
	divider = 10;
	switch (decimalPlaces) {
		case 0:
			divider = 1;
			break;
		case 1:
			divider = 10;
			break;
		case 2:
			divider = 100;
			break;
		default:       //for 3 decimal places
			divider = 1000;
	}

	workNum = Math.abs((Math.round(anynum * divider) / divider));

	workStr = "" + workNum

	if (workStr.indexOf(".") == -1) { workStr += "." }

	dStr = workStr.substr(0, workStr.indexOf(".")); dNum = dStr - 0
	pStr = workStr.substr(workStr.indexOf("."))

	while (pStr.length - 1 < decimalPlaces) { pStr += "0" }

	if (pStr == '.') pStr = '';

	//--- Adds a comma in the thousands place.    
	if (dNum >= 1000) {
		dLen = dStr.length
		dStr = parseInt("" + (dNum / 1000)) + "," + dStr.substring(dLen - 3, dLen)
	}

	//-- Adds a comma in the millions place.
	if (dNum >= 1000000) {
		dLen = dStr.length
		dStr = parseInt("" + (dNum / 1000000)) + "," + dStr.substring(dLen - 7, dLen)
	}
	retval = dStr + pStr
	//-- Put numbers in parentheses if negative.
	if (anynum < 0) { retval = "(" + retval + ")"; }

	//You could include a dollar sign in the return value.
	//retval =  "$"+retval
	return retval;
}
