﻿// MUTUAL across more than one control

function trapEnterPD(evnt) {
	var key = evnt.keyCode || evnt.which;
	return key != 13;
}


/*
Method		: flipButton
Summary		: mouse roll over/out function for flipping buttons - not visually seen in florida site
Inputs		: button = 'this' (image object)
: mode = 1(over), 2(out)
Author		: TSA
Create Date	: 2007.02.08
*/
function flipButton(button, mode) {
	var oImg = eval(button);

	try {
		switch (mode) {
			case 1: //over
				if (oImg.src.indexOf('_Over.gif') < 0) {
					oImg.src = oImg.src.replace('.gif', '_Over.gif');
				}
				return;

			case 0: //out
				if (oImg.src.indexOf('_Over.gif') > -1) {
					oImg.src = oImg.src.replace('_Over.gif', '.gif');
				}
				return;
		}
	}
	catch (err) {
		return;
	}
}

// *****************    AGENT LISTING CONTROL SCRIPTS     ***************

function loadAgentList(arr, cid, id) {

	if (arr == null || arr == "undefined") return;

	var ctl = $(id)
	var controlPrefix = "";
	var controlPrefix = cid.replace(id, "");

	for (i = 0; i < arr.length; i++) {
		var listingdata = arr[i].split('~');

		var newlisting = $(controlPrefix + "opt_x").clone(true);
		newlisting.attr("id", "opt" + i);
		if (listingdata[0] === "") //firefox hack (no onerror handling)
		{
			newlisting.find(controlPrefix + "imgphoto").attr("src", "/NRTProducts/include/images/NoPropertyPhoto.gif");
		}
		else {
			newlisting.find(controlPrefix + "imgphoto").attr("src", listingdata[0]);
		}
		newlisting.find(controlPrefix + "imglink").attr("href", listingdata[1]);

		if (i == 0) {
			$(controlPrefix + "add2").html(listingdata[3]);
			$(controlPrefix + "add2").attr("href", listingdata[1]);
			$(controlPrefix + "price").html(listingdata[4]);
		}
		$(controlPrefix + "simlist").append(newlisting);

		if (arr.length == 1) {
			$(controlPrefix + 'imgListingLeftArrow').attr("src", "/NRTProducts/include/images/spacer_clr.gif");
			$(controlPrefix + 'imgListingRightArrow').attr("src", "/NRTProducts/include/images/spacer_clr.gif");
		}

	}
	$(controlPrefix + "opt_x").remove();

	$(controlPrefix + "simlist").cycle({
		fx: 'scrollHorz',
		timeout: 0,
		prev: controlPrefix + 'imgListingLeftArrow',
		next: controlPrefix + 'imgListingRightArrow',
		after: onIndex,
		nowrap: true
	});

	function onIndex(curr, next, opts) {
		listingdata = arr[opts.currSlide].split('~');

		$(controlPrefix + "add2").html(listingdata[3]);
		$(controlPrefix + "add2").attr("href", listingdata[1]);
		$(controlPrefix + "price").html(listingdata[4]);
		$(controlPrefix + "simlist").append(newlisting);

		if (opts.currSlide == 0) {
			$(controlPrefix + 'imgListingLeftArrow').attr("src", "/NRTProducts/include/images/LeftArrowGreyDis.gif");
			$(controlPrefix + 'imgListingLeftArrow').attr("disabled", "disabled");
		}
		else {
			$(controlPrefix + 'imgListingLeftArrow').attr("src", "/NRTProducts/include/images/LeftArrowGrey.gif");
			$(controlPrefix + 'imgListingLeftArrow').removeAttr("disabled");
		}

		if (opts.currSlide + 1 == arr.length) {
			$(controlPrefix + 'imgListingRightArrow').attr("src", "/NRTProducts/include/images/RightArrowGreyDis.gif");
			$(controlPrefix + 'imgListingRightArrow').attr("disabled", "disabled");
		}
		else {
			$(controlPrefix + 'imgListingRightArrow').attr("src", "/NRTProducts/include/images/RightArrowGrey.gif");
			$(controlPrefix + 'imgListingRightArrow').removeAttr("disabled");
		}

	}

}


// *****************    RECENT/SIMILAR LISTING CONTROL SCRIPTS     ***************

function loadSimList(arr, cid, id) {

	if (arr == null || arr == "undefined") return;

	var ctl = $(id)
	var controlPrefix = "";
	var controlPrefix = cid.replace(id, "");

	for (i = 0; i < arr.length; i++) {
		var listingdata = arr[i].split('~');

		var newlisting = $(controlPrefix + "opt_x").clone(true);
		newlisting.attr("id", "opt" + i);
		if (listingdata[0] === "") //firefox hack (no onerror handling)
		{
			newlisting.find(controlPrefix + "imgphoto").attr("src", "/NRTProducts/include/images/NoPropertyPhoto.gif");
		}
		else {
			newlisting.find(controlPrefix + "imgphoto").attr("src", listingdata[0]);
		}
		newlisting.find(controlPrefix + "imglink").attr("href", listingdata[1]);
		newlisting.find(controlPrefix + "add1").html(listingdata[2]);
		newlisting.find(controlPrefix + "add1").attr("href", listingdata[1]);
		newlisting.find(controlPrefix + "add2").html(listingdata[3]);
		newlisting.find(controlPrefix + "add2").attr("href", listingdata[1]);
		newlisting.find(controlPrefix + "price").html(listingdata[4]);
		$(controlPrefix + "simlist").append(newlisting);
	}
	$(controlPrefix + "opt_x").remove();

	var dNavs = $(controlPrefix + "divNav img.pd-similar-listing-nav-item");

	$(controlPrefix + "divNav").css("display", "none");

	dNavs.each(
	function (index) {
		if (index > arr.length - 1) {
			$(this).css("display", "none");
		}
		else {
			if (index > 0) { $(controlPrefix + "divNav").css("display", "inline-block"); }


			$(this).bind("click", function () { $(controlPrefix + "simlist").cycle(index); });
			if (index == 0) {
				$(this).attr("src", "/Images/Properties/featured/cycle-nav-on.gif");
			}
			else {
				$(this).attr("src", "/Images/Properties/featured/cycle-nav-off.gif");
			}
		}
	});

	$(controlPrefix + "simlist").cycle({
		fx: 'scrollHorz',
		timeout: 0,
		prev: controlPrefix + 'imgListingLeftArrow',
		next: controlPrefix + 'imgListingRightArrow',
		after: onIndex
	});

	function onIndex(curr, next, opts) {
		dNavs.each(function (index) {
			if (index == opts.currSlide) {
				$(this).attr("src", "/Images/Properties/featured/cycle-nav-on.gif");
			}
			else {
				$(this).attr("src", "/Images/Properties/featured/cycle-nav-off.gif");
			}
		});
	}

}

// ****************         LISTING MAP CONTROL              ***************
function Page_Load() { }
//Clean up all objects function 
function Page_Unload() {
	if (map != null) {
		map.dispose();
		map = null;
	}
}

function ToggleMapSize() {
	var mapHeight = map.getHeight();
	var mapWidth = map.getWidth();
	var s;

	if (!e) var e = window.event;

	if (mapHeight == 350) {
		mapHeight += 200;
		s = "View Smaller Map";
	}
	else {
		mapHeight -= 200;
		s = "View Larger Map";
	}

	// Resize the Virtual Earth Map itself
	map.setOptions({ width: mapWidth, height: mapHeight });
	document.getElementById('hlViewLargerMap').innerHTML = s;
}

function AddPushpin() {



	//Add the shape the the map
	var opts = { icon: '/NRTProducts/include/Images/map_results_pushpin_.gif' };
	var pin = new Microsoft.Maps.Pushpin(map.getCenter(), opts);
	map.entities.push(pin);
}


function MapMouseWheelHandler(e) {

	if (mapBrowserDetectIsFirefox)
		window.scrollBy(0, -20 * e.wheelDelta);
	else
		window.scrollBy(0, -1 * e.wheelDelta);

	e.handled = true;
	return true;
}

function trapEnterMap(evt) {
	try {
		var charCode = (evt.which) ? evt.which : event.keyCode

		if (charCode == 13) {
			getDirections();
			return false;








		}
		return false;
	}
	catch (err) {
		_oErrorHandler.Error('NRT.Property.Search.QuickSearch.trapEnter', _oErrorHandler.ERRORTYPE_JS, err);
		return;
	}
}

// ***************  OPEN HOUSE CONTROL SCRIPTS  *****************
function toggleOpenHouseDatesList(objElement) {
	var expandoTextDiv = document.getElementById('additionalOpenHouseDatesDiv');
	var myExpandoAnchorDiv = document.getElementById('openhouseExpandoAnchorDiv');

	if (objElement.id == 'openhouseExpandoAnchor') {
		expandoTextDiv.className = 'visibleExpando';
		myExpandoAnchorDiv.className = 'hiddenExpando';
	}
	else {
		expandoTextDiv.className = 'hiddenExpando';
		myExpandoAnchorDiv.className = 'visibleExpando';
	}
}

// **************** LISTING DESCRIPTION CONTROL SCRIPTS ***************

function expandListingDescription(objElement) {
	var expandoTextDiv = document.getElementById('restOfString');
	var myExpandoAnchorDiv = document.getElementById('myExpandoAnchorDiv');

	if (objElement.id == 'myExpandoAnchor') {
		expandoTextDiv.className = 'visibleExpando';
		myExpandoAnchorDiv.className = 'hiddenExpando';

	}
	else {
		expandoTextDiv.className = 'hiddenExpando';
		myExpandoAnchorDiv.className = 'visibleExpando';
	}
}

// **************** MORTGAGE CALCULATOR     ****************************

function parseNumber(stringValue, defaultValue) {

	//strip any $ from string
	stringValue = stringValue.toString().replace(/\$|\,/g, '');

	var result;

	result = new Number(stringValue);
	if (isNaN(result)) {
		if (defaultValue != undefined) {
			defaultValue = new Number(defaultValue);
			if (isNaN(defaultValue) == false)
				result = defaultValue;
		}
		else {
			result = new Number();
			result = 0;
		}
	}
	return result;
}

function calculateAmoritizedPayment(PV, IR, NP) {
	var PMT = (PV * IR) / (1 - Math.pow(1 + IR, -NP));
	return roundDecimals(PMT, 2);
}

function roundDecimals(original_number, decimals) {
	var result1 = original_number * Math.pow(10, decimals);
	var result2 = Math.round(result1);
	var result3 = result2 / Math.pow(10, decimals);
	return (result3);
}

function formatCurrency(strValue) {
	return formatCurrency(strValue, false);
}

function formatCurrency(strValue, includeCents) {
	var blnSign;
	var dblValue;
	var intCents;
	var strCents;
	var strValue;

	strValue = strValue.toString().replace(/\$|\,/g, '');
	dblValue = parseFloat(strValue);
	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue * 100 + 0.50000000001);
	intCents = dblValue % 100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue / 100).toString();
	if (intCents < 10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length - (1 + i)) / 3); i++)
		dblValue = dblValue.substring(0, dblValue.length - (4 * i + 3)) + ',' +
		dblValue.substring(dblValue.length - (4 * i + 3));
	if (includeCents == true)
		return (((blnSign) ? '' : '-') + '$' + dblValue + '.' + strCents);
	else
		return (((blnSign) ? '' : '-') + '$' + dblValue);
}

function calculateMonthlyPayment(hideCalculation) {

	//initialize variables
	var down_paymentAmount = 0;
	var down_paymentPercentage = 0;
	var present_value = 0;
	var borrowed_value = 0;
	var interest_rate = 0.0625;
	var loan_term = 30;
	var annual_insuranceAmount = 0;
	var annual_taxesAmount = 0;
	var monthly_paymentPlusSup = 0;
	var common_charges = 0;

	//assign input values
	present_value = parseNumber(txtPurchasePrice.value);
	borrowed_value = present_value;
	down_paymentAmount = parseNumber(txtDownpaymentAmount.value);
	down_paymentPercentage = parseNumber(ddlDownpaymentPercentage.value);
	annual_taxesAmount = parseNumber(txtAnnualTaxes.value);
	annual_insuranceAmount = parseNumber(txtAnnualInsurance.value);
	interest_rate = parseNumber(txtAnnualInterestRate.value.replace(/\%/g, ''), 0.0625);

	if (txtCommonCharges != null) {
		common_charges = parseNumber(txtCommonCharges.value);
	}

	//reset input values
	txtDownpaymentAmount.value = '';
	paymentEstimateLabel.innerHTML = '';
	paymentInformationLabel.innerHTML = '';

	//if down payment is unrealistic, reset it to 0
	if (down_paymentAmount > present_value) down_paymentAmount = 0;

	//inspect loan term radio buttons
	if (rbDownpaymentPercentage.checked == true) {
		down_paymentPercentage = parseNumber(ddlDownpaymentPercentage.value);
		down_paymentAmount = roundDecimals(present_value * down_paymentPercentage, 2);
		borrowed_value = present_value - down_paymentAmount;
	}
	else {
		borrowed_value = present_value - down_paymentAmount;
		down_paymentPercentage = down_paymentAmount / present_value * 100;
	}

	//set interest rate to percentage if necessary
	if (interest_rate > 1) {
		interest_rate = interest_rate / 100;
		//if the user entered something like 110%, default it
		if (interest_rate > 1)
			interest_rate = 0.0625;
	}

	//inspect term - default to 30 unless other specified
	if (rdoTerm15.checked == true) {
		loan_term = 15;
	}

	var monthly_payment = calculateAmoritizedPayment(borrowed_value, interest_rate / 12, loan_term * 12);
	monthly_paymentPlusSup = monthly_payment + roundDecimals(annual_insuranceAmount / 12, 2) + roundDecimals(annual_taxesAmount / 12, 2) + roundDecimals(common_charges, 2);

	//format input values
	if (present_value > 0) {
		txtPurchasePrice.value = formatCurrency(present_value);
	} else {
		txtPurchasePrice.value = '';
	}
	if (down_paymentAmount > 0) {
		txtDownpaymentAmount.value = formatCurrency(down_paymentAmount);
	} else {
		txtDownpaymentAmount.value = '';
	}
	if (annual_taxesAmount > 0) {
		txtAnnualTaxes.value = formatCurrency(annual_taxesAmount);
	} else {
		txtAnnualTaxes.value = '';
	}
	if (annual_insuranceAmount > 0) {
		txtAnnualInsurance.value = formatCurrency(annual_insuranceAmount);
	} else {
		txtAnnualInsurance.value = '';
	}
	if (interest_rate > 0) {
		txtAnnualInterestRate.value = (interest_rate * 100).toString() + "%";
	} else {
		txtAnnualInterestRate.value = '';
	}
	if (txtCommonCharges != null) {
		if (common_charges > 0) {
			txtCommonCharges.value = formatCurrency(common_charges);
		} else {
			txtCommonCharges.value = '';
		}
	}

	//set payment information
	if (hideCalculation !== true) {
		paymentEstimateLabel.innerHTML = formatCurrency(monthly_paymentPlusSup.toString(), false) + " per month";
		paymentInformationLabel.innerHTML = formatCurrency(down_paymentAmount.toString())
        + " down, " + formatCurrency(borrowed_value.toString()) + " mortgage";
	}
}

// ***************   PHOTO CONTROL SCRIPTS ********************
function removeEmptys() {
	$("#divThumbnailsContainer img").attr('alt', '')
	$("#divThumbnailsContainer img").eq(currentPhotoHighlightIndex).attr('alt', 'selected').removeClass('pd-photo-thumbnail-selected');
	$("#divThumbnailsContainer img").eq(currentPhotoHighlightIndex).attr('alt', 'selected').removeClass('pd-photo-thumbnail-unselected');
	$("#divThumbnailsContainer img").eq(currentPhotoHighlightIndex).attr('alt', 'selected').removeClass('pd-photo-thumbnail-empty');
	$("#divThumbnailsContainer img").eq(currentPhotoHighlightIndex).attr('alt', 'selected').addClass('pd-photo-thumbnail-unselected');

	$("#divThumbnailsContainer img").each(function (index) {
		if ($(this).attr('src') == '/NRTProducts/include/Images/common_spacer.gif') {
			$(this).attr('alt', 'empty');
			var tifl = $(this).parent().get(0)
			$(tifl).css({ 'display': 'none' });
		}
	});
	OpeningAnimation();
}

function OpeningAnimation() {
	$('#divLargePhoto').fadeTo(400, 1.0);
	$("#divThumbnailsContainer img").each(function (index) {
		if ($(this).attr('alt') == 'selected') {
			$(this).animate({
				opacity: 1.0
			}, 200, "swing");

			$(this).removeClass('pd-photo-thumbnail-selected');
			$(this).removeClass('pd-photo-thumbnail-unselected');
			$(this).removeClass('pd-photo-thumbnail-empty');
			$(this).addClass('pd-photo-thumbnail-selected');
		}
		else {
			if (!($(this).attr('src') == '/NRTProducts/include/Images/common_spacer.gif')) {
				$(this).animate({
					opacity: 0.8
				}, 200, "swing");
				$(this).removeClass('pd-photo-thumbnail-selected');
				$(this).removeClass('pd-photo-thumbnail-unselected');
				$(this).removeClass('pd-photo-thumbnail-empty');
				$(this).addClass('pd-photo-thumbnail-unselected');
			}
		}
	});

}

function animateNextPhoto(index) {
	var thisSRC = $('#divThumbnailsContainer img').eq(index).attr("src");
	var thisCaption = $('#divThumbnailsContainer img').eq(index).attr("title");
	var labelPhotoCaption = document.getElementById('lblPhotoCaption');

	$('#divThumbnailsContainer img').removeClass('pd-photo-thumbnail-selected');
	$('#divThumbnailsContainer img').removeClass('pd-photo-thumbnail-unselected');
	$('#divThumbnailsContainer img').removeClass('pd-photo-thumbnail-empty');
	$('#divThumbnailsContainer img').addClass('pd-photo-thumbnail-unselected');

	$('#divThumbnailsContainer img').eq(index).removeClass('pd-photo-thumbnail-selected');
	$('#divThumbnailsContainer img').eq(index).removeClass('pd-photo-thumbnail-unselected');
	$('#divThumbnailsContainer img').eq(index).removeClass('pd-photo-thumbnail-empty');
	$('#divThumbnailsContainer img').eq(index).addClass('pd-photo-thumbnail-selected');

	$("#divThumbnailsContainer img[alt='empty']").removeClass('pd-photo-thumbnail-selected');
	$("#divThumbnailsContainer img[alt='empty']").removeClass('pd-photo-thumbnail-unselected');
	$("#divThumbnailsContainer img[alt='empty']").removeClass('pd-photo-thumbnail-empty');
	$("#divThumbnailsContainer img[alt='empty']").addClass('pd-photo-thumbnail-empty');

	$('#divLargePhoto').stop(true, false); // elminate stacked animations
	$('#divLargePhoto').fadeTo(250, 0.1, function () {
		$('#divLargePhoto img').attr('src', thisSRC);
		labelPhotoCaption.innerHTML = thisCaption;
		$('#divLargePhoto img').attr('title', thisCaption);
		resetPhoto();
	});
}

function resetPhoto() {
	$('#divLargePhoto').fadeTo(300, 1.0);
}

function instantiatePropertyDetailsPhotoArray() {
	propertyDetailsPhotoInfos = new Array(photoControlsPhotoCollection.length);

	for (var i = 0; i < photoControlsPhotoCollection.length; i++) {
		var myphoto = new Object;
		var serializedString = photoControlsPhotoCollection[i].split("|");

		myphoto.caption = serializedString[2];
		myphoto.thumbnailURL = serializedString[1];
		myphoto.mainURL = serializedString[0];
		propertyDetailsPhotoInfos[i] = myphoto;
	}
}

function populatePropertyDetailsPhotoControl() {
	if (propertyDetailsPhotoInfos.length > 0) {
		//reset the image src's
		for (var i = 0; i < 10; i++) { thumbnailImgElements[i].src = '/NRTProducts/include/Images/common_spacer.gif'; }

		var lowerLimit = 10 * currentPhotoPageIndex;
		var upperLimit = 0;
		if ((propertyDetailsPhotoInfos.length - (10 * currentPhotoPageIndex)) < 10)
			upperLimit = propertyDetailsPhotoInfos.length;
		else
			upperLimit = ((10 * currentPhotoPageIndex) + 10);

		var j = 0;
		for (var i = lowerLimit; i < upperLimit; i++) {

			//assign the src to the img element
			thumbnailImgElements[j].src = propertyDetailsPhotoInfos[i].thumbnailURL;
			thumbnailImgElements[j].title = propertyDetailsPhotoInfos[i].caption;
			thumbnailDivElements[j].style.display = 'inline';
			j++;
		}

		//set current index
		highlightImageThumbnail(currentPhotoHighlightIndex);
		animateNextPhoto(currentPhotoHighlightIndex);
		removeEmptys();
	}
}

function openLargePhotos(address, listingID, websiteName, disclaimerID) {
	var j = window.open("Coldwell Banker", "LargePhotos", "height=650,width=650,status=yes,toolbar=yes,menubar=yes,scrollbars=yes,top=5,location=no,resizable=yes");
	j.document.write("<link href=\"/NRTProducts/include/css/PropertyDetailsPrint.css\" rel=\"stylesheet\" type=\"text/css\" />")
	j.document.write("<body style=\"padding: 0px 0px; margin: 5px 5px; font-family: Arial, Helvetica, Sans-Serif; font-size: 12px;\">");
	j.document.write("<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" align=\"center\"><tr><td width=\"100%\" align=\"center\"><table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td width=\"100%\" align=\"center\"><div><img src=\"/Images/forms/cblogo.gif\" alt=\"Coldwell Banker\" style=\"float: left;\" /><span class=\"pd-print-banner\">" + websiteName + "</span><div style=\"clear: both; padding-top: 3px;\"></div><hr class=\"pd-print-banner-rule\" /></div>");
	j.document.write("<p style=\"color: #003169; font-size: 14px; line-height: 22px; padding-bottom: 10px;\"><span style=\"font-weight: bold; \">" + address + "</span>");

	if (listingID !== null && listingID !== "") {
		j.document.write("<br /><span>MLS# " + listingID + "</span>");
	}

	j.document.write("</p></td></tr>");

	for (var i = 0; i < propertyDetailsPhotoInfos.length; i++) {
		j.document.write("<tr><td width=\"100%\" align=\"center\"><img style=\"padding: 0px 0px; margin: 0px 0px 10px 0px; border: solid 1px #cccccc;\" src=\"" + propertyDetailsPhotoInfos[i].mainURL + "\" onerror=\"this.src='/NRTProducts/include/images/NoPropertyPhoto.gif';\" /><br /></td></tr>");
	}

	var divDisclaimer = document.getElementById(disclaimerID);
	if (divDisclaimer !== null && typeof divDisclaimer !== 'undefined' && divDisclaimer.innerHTML !== '') {
		j.document.write("<tr><td class=\"pd-additionalinfo\">" + divDisclaimer.innerHTML + "</td></tr>");
	}

    j.document.write("</table></td></tr></table></body");
}

function highlightImageThumbnail(index) {
	if (index + (currentPhotoPageIndex * 10) >= propertyDetailsPhotoInfos.length) return;
	currentPhotoHighlightIndex = index;

	previousPhotoHighlightIndex = currentPhotoHighlightIndex;
	//set label
	photoControlIterationLabelReference.innerHTML =
                (currentPhotoHighlightIndex + currentPhotoPageIndex * 10 + 1).toString()
                + " of " + propertyDetailsPhotoInfos.length.toString();
}

function movePrevThumbnail() {
	if (currentPhotoHighlightIndex > 0) {
		currentPhotoHighlightIndex -= 1;
		highlightImageThumbnail(currentPhotoHighlightIndex);
		animateNextPhoto(currentPhotoHighlightIndex);
	}
	else {
		if (currentPhotoPageIndex > 0) {
			currentPhotoPageIndex -= 1;
			currentPhotoHighlightIndex = 9;
			highlightImageThumbnail(currentPhotoHighlightIndex);
			populatePropertyDetailsPhotoControl();
		}
	}

	setPhotoNavigationStyles();
	setPagingTabStyles();
}

function moveNextThumbnail() {
	if (currentPhotoPageIndex * 10 + currentPhotoHighlightIndex < propertyDetailsPhotoInfos.length - 1) {
		if (currentPhotoHighlightIndex < 9) {
			currentPhotoHighlightIndex += 1;
			highlightImageThumbnail(currentPhotoHighlightIndex);
			animateNextPhoto(currentPhotoHighlightIndex);
		}
		else {
			//moving to next page
			currentPhotoPageIndex += 1;
			currentPhotoHighlightIndex = 0;
			highlightImageThumbnail(currentPhotoHighlightIndex);
			populatePropertyDetailsPhotoControl();
		}
	}

	setPhotoNavigationStyles();
	setPagingTabStyles();
}

function setPhotoNavigationStyles() {
	if ((currentPhotoPageIndex * 10 + currentPhotoHighlightIndex) == 0)
		photoNavigatePreviousControlReference.style.color = '#999999';
	else
		photoNavigatePreviousControlReference.style.color = '#003366';

	if ((currentPhotoPageIndex * 10 + currentPhotoHighlightIndex) != propertyDetailsPhotoInfos.length - 1)
		photoNavigateNextControlReference.style.color = '#003366';
	else
		photoNavigateNextControlReference.style.color = '#999999';
}

function setPagingTabStyles() {
	//reset pagingPads
	for (var i = 0; i < pagingPads.length; i++) {
		pagingPads[i].className = "pd-photo-tab-inactive";
	}
	pagingPads[currentPhotoPageIndex].className = "pd-photo-tab";
}

function moveToPage(index) {
	currentPhotoHighlightIndex = 0;
	currentPhotoPageIndex = index - 1;
	highlightImageThumbnail(currentPhotoHighlightIndex);
	populatePropertyDetailsPhotoControl();
	setPhotoNavigationStyles();
	setPagingTabStyles();

	removeEmptys();
}

function instantiatePhotoPagingPads() {
	var startIndex = 1;
	var endIndex = 1;
	var done = false;

	//first reset pads to not display
	for (var i = 0; i < pagingPads.length; i++) {
		if (pagingPads[i].parentNode != 'undefined')
		{ pagingPads[i].parentNode.style.display = 'none'; }
		else { pagingPads[i].parentElement.style.display = 'none'; }
		pagingPads[i].style.display = 'none';
	}

	//our current page design only allows room for 4 paging tabs
	if (propertyDetailsPhotoInfos.length > 0) {
		for (var i = 0; i < 4 && done == false; i++) {

			if ((endIndex + 10) > propertyDetailsPhotoInfos.length) {
				endIndex = propertyDetailsPhotoInfos.length;
				done = true;
			}
			else {
				endIndex = startIndex + 9;
				if (endIndex == propertyDetailsPhotoInfos.length) done = true;
			}

			if (pagingPads[i].parentNode != 'undefined')
				pagingPads[i].parentNode.style.display = 'inline';
			else
				pagingPads[i].parentElement.style.display = 'inline';

			pagingPads[i].style.display = 'block';

			//if start and end are same, don't include hypen
			if (endIndex != startIndex)
				pagingPads[i].innerHTML = startIndex + "-" + endIndex;
			else
				pagingPads[i].innerHTML = startIndex;

			startIndex += 10;
			photoNavigationPages += 1;
		}
	}
}

// ******************* PROPERTY DETAILS CONTACT FORM *****************

function submitContactForm() {
	var errorMessage = new String();
	var message;
	var firstName;
	var lastName;
	var providedEmailAddress;
	var providedPhoneNumber;
	var divContactFormMessage = document.getElementById('divContactFormMessage');
	var divContactFields = document.getElementById('divContactFields');
	//check first name

	message = document.getElementById('txtContactFormMessage').value.trimSpaces();
	if (message.length == 0)
		errorMessage += "Message is a required field.\r\n";
	message = message.replace(/</g, "< ");
	firstName = document.getElementById('txtContactFormFirstName').value.trimSpaces();
	if (firstName.length == 0)
		errorMessage += "First Name is a required field.\r\n";
	lastName = document.getElementById('txtContactFormLastName').value.trimSpaces();
	if (lastName.length == 0)
		errorMessage += "Last Name is a required field.\r\n";
	providedEmailAddress = document.getElementById('txtContactFormEmail').value.trimSpaces();
	if (providedEmailAddress.length == 0)
		errorMessage += "Email is a required field.\r\n";
	else {
		var emailRegexPattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
		if (!emailRegexPattern.test(providedEmailAddress))
			errorMessage += "Email address format is invalid.\r\n";
	}
	// phone isn't a require field. We could however
	// attempt to validate the foramt
	providedPhoneNumber = document.getElementById('txtContactFormPhoneNumber').value.trimSpaces();

	if (providedPhoneNumber.length > 0) {
		var phoneRegexPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
		if (!phoneRegexPattern.test(providedPhoneNumber))
			errorMessage += "Phone number format is invalid.\r\n";
	}

	if (errorMessage.length > 0) {
		alert("Please correct the following issues with the form and re-submit:\r\n\r\n" + errorMessage);
	}
	else {
		//this code utilizes cross-browser XMLHTTPREQUEST library by Sergey Ilinsky
		//http://code.google.com/p/xmlhttprequest/

		var msg = "propid=" + pdPropertyID +
            "&aid=" + pdBrandedAgentID +
            "&tid=" + pdBrandedTeamID +
            "&cid=" + pdCampaignID +
            "&communityID=" + pdCommunityID +
            "&modelid=" + pdModelID +
            "&rid=" + pdRegionID +
            "&sid=" + pdStateID +
            "&wn=" + pdWebsiteName +
            "&msg=" + message +
            "&fn=" + firstName +
            "&ln=" + lastName +
            "&email=" + providedEmailAddress +
            "&phone=" + providedPhoneNumber +
            "&ispreviews=" + pdIsPreviews +
            "&ismetroproperty=" + pdIsMetroProperty +
            "&propcategoryid=" + pdPropertyCategoryID;

		var oXMLHttpRequest = new XMLHttpRequest;
		oXMLHttpRequest.open("POST", "/PropertyDetailsContactFormHandler.ashx", true);
		oXMLHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		oXMLHttpRequest.onreadystatechange = function () {
			if (oXMLHttpRequest.readyState == 4) {
				if (oXMLHttpRequest.status == 200) {
					if (typeof (oXMLHttpRequest.responseText) != 'undefined') {
						if (divContactFormMessage !== null && typeof divContactFormMessage !== 'undefined') {
							divContactFormMessage.innerHTML = '<p>' + oXMLHttpRequest.responseText + '</p>';
						}
						if (divContactFields !== null && typeof divContactFields !== 'undefined') {
							divContactFields.style.display = 'none';
						}
					}
					//old WT code			dcsMultiTrack('DCS.dcsuri', '/forms/RequestMoreInformationInline_confirm.aspx', 'WT.ti', 'PropertyDetailsContactForm', 'WT.tx_e', 'n', 'WT.si_n', 'overview;RequestMoreInformationInline;cc', 'WT.si_x', '6;2;1');
					var isMetroProp = document.getElementById("ctl00_MainContent_hdnIsMetroProperty").value;

					// Google Analytics
					RunGoogleAnalytics('/Forms/RequestMoreInfoInline_confirm.aspx');
					if (isMetroProp == "True") {
						RunGoogleAnalyticsEvent('contact', 'submit-form-nrt', 'request-more-information-inline');
					}
					else {
						RunGoogleAnalyticsEvent('contact', 'submit-form-nonnrt', 'request-more-information-inline');
					}
				}
				else {
					alert('Sorry, there was an error submitting the form. Please try again.');
				}

			}
		}

		//send empty string to force FF to add Content-Length header
		oXMLHttpRequest.send(msg);
	}
}

// Steve Levithan MIT license
String.prototype.trimSpaces = function () {
	var str = this;
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};

// Tab Functions
function switchPDTab(tabName) {
	var liTab = NRT.Utility.getElementByTagNameAndID(tabName, 'a');
	if (NRT.Utility.objectExists(liTab)) {
		liTab.onClick();
	}
	$('#ctl00_MainContent_ctl02_Tabs1_hlMap:first').click();
}

$(function () {
	var link = $('a[id$=hlMap]').attr('href');
	$('#hlDrivingDirections').attr('href', link);
	$('#hlLowerDrivingDirections').attr('href', link);
});

// ******************* OPEN HOUSE "More Info" tooltip *****************

// Cross-Browser compatible tooltip
this.ttip = function () {
	this.xOffset = 10; // x distance from mouse
	this.yOffset = 10; // y distance from mouse

	$(".ttip").unbind().mouseenter(
			function (e) {
				this.t = this.title;
				this.title = '';
				this.top = (e.pageY + yOffset);
				this.left = (e.pageX + xOffset);

				$('body').append('<p id="ttip">' + this.t + '</p>');

				$('p#ttip').css("top", this.top + "px").css("left", this.left + "px").fadeIn("slow");

			}
		).mouseleave(
			function () {
				this.title = this.t;
				$("p#ttip").fadeOut("slow").remove();
			}
		).mousemove(
			function (e) {
				this.top = (e.pageY + yOffset);
				this.left = (e.pageX + xOffset);

				$("p#ttip").css("top", this.top + "px").css("left", this.left + "px");
			}
		);
};

jQuery(document).ready(function ($)
{
	ttip();

	$("#divThumbnailsContainer").delegate("img", "mouseover", function (evt)
	{
		$(this).animate({ opacity: 1.0 }, 200);
	});

	$("#divThumbnailsContainer").delegate("img", "mouseout", function (evt)
	{
		$(this).animate({ opacity: 0.8 }, 200);
	});
}) 


