﻿// 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 SCRIPT     ***************
var agentListings = new Array();
var agentListingIndex = new Array();

function loadAgentListingControl(index, operatorValue)
{

    if (agentListings == null || agentListings == "undefined") return;

    var controlPrefix = "";
    var controlIndex = index + 1;
    if (controlIndex < 10)
    {
        controlPrefix = "ctl0" + controlIndex.toString() + "_";
    } else
    {
        controlPrefix = "ctl" + controlIndex.toString() + "_";
    }

    var leftArrow = NRT.Utility.getElementByTagNameAndID(controlPrefix + "imgMyListingLeftArrow", "IMG");
    var rightArrow = NRT.Utility.getElementByTagNameAndID(controlPrefix + "imgMyListingRightArrow", "IMG");

    if (operatorValue == 1)
    {
        if (agentListingIndex[index] == agentListings[index].length - 1) return;
        agentListingIndex[index]++;
    }
    else
    {
        if (agentListingIndex[index] < 1) return;
        agentListingIndex[index]--;
    }

    var addressLine = NRT.Utility.getElementByTagNameAndID(controlPrefix + "hlMyListingsAddress", "A");
    var descriptorLine = NRT.Utility.getElementByTagNameAndID(controlPrefix + "spnMyListingsDescriptor", "P");
    var propertyPhoto = NRT.Utility.getElementByTagNameAndID(controlPrefix + "imgMyListings", "IMG");
    var propertyPhotoAnchor = NRT.Utility.getElementByTagNameAndID(controlPrefix + "imgMyListingAnchor", "A");
    var myListings = agentListings[index]; //agentListingIndex[index].split('~');
    var myListing = myListings[agentListingIndex[index]].split('~');
    
    propertyPhoto.src = myListing[0];
    propertyPhotoAnchor.href = myListing[1];
    addressLine.href = myListing[1];
    addressLine.innerHTML = myListing[2];
    descriptorLine.innerHTML = myListing[3];

    if (agentListingIndex[index] == agentListings[index].length - 1) { rightArrow.src = "/NRTProducts/include/Images/agentrightarrow.gif"; rightArrow.style.cursor = "default"; }
    else { rightArrow.src = "/NRTProducts/include/Images/agentrightarrow_act.gif"; rightArrow.style.cursor = "pointer"; }

    if (agentListingIndex[index] == 0) { leftArrow.src = "/NRTProducts/include/Images/agentleftarrow.gif"; leftArrow.style.cursor = "default"; }
    else { leftArrow.src = "/NRTProducts/include/Images/agentleftarrow_act.gif"; leftArrow.style.cursor = "pointer"; }

    //hide nav arrows if only 1 listing
    if (agentListings[index].length == 1)
    {
        rightArrow.style.display = "none";
        leftArrow.style.display = "none";
    }

}

// ****************         LISTING MAP CONTROL              ***************
function Page_Load() { if (GetMap != undefined) GetMap(); AddPushpin(); }
//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.Resize(mapWidth, mapHeight);
    document.getElementById('hlViewLargerMap').innerHTML = s;

}

function AddPushpin()
{
    var shape = new VEShape(VEShapeType.Pushpin, map.GetCenter());
    var icon = "<img src='/NRTProducts/include/Images/map_results_pushpin_.gif' >";
    //Set the icon
    shape.SetCustomIcon(icon);
    //Add the shape the the map
    map.AddShape(shape);
}


function MapMouseWheelHandler(e)
{

    if (mapBrowserDetectIsFirefox)
        window.scrollBy(0, -20 * e.mouseWheelChange);
    else
        window.scrollBy(0, -1 * e.mouseWheelChange);

    return true;
}

function trapEnterMap(evt)
{
	try
	{
		var charCode = (evt.which) ? evt.which : event.keyCode

		if (charCode == 13)
		{
			getDirections();
			return false;
			//            var hlGetDirections = document.getElementById('hlGetDirections');
			//            if (NRT.Utility.objectExists(hlGetDirections))
			//            {
			//                hlGetDirections.click();
			//                return true;
			//            } else {
			//                return false;
			//            }
		}
		return false;
	}
	catch (err)
	{
		_oErrorHandler.Error('NRT.Property.Search.QuickSearch.trapEnterMap', _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()
{

    //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;

    //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);

    //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);

    //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 = '';
	}

    //set payment information
    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 initializePropertyDetailsPhotoControl()
{
    if (thumbnailDivElements != null && thumbnailDivElements != 'undefined')
    {
        for (var i = 0; i < thumbnailDivElements.length; i++)
        {
        }
    }
}

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";
    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 = "PropertyID=" + pdPropertyID +
            "&abrand=" + pdBrandedAgentID +
            "&tbrand=" + pdBrandedTeamID +
            "&cid=" + pdCampaignID +
            "&agent=" + pdAgent +
            "&team=" + pdTeam +
            "&office=" + pdOffice +
            "&msg=" + message +
            "&fn=" + firstName +
            "&ln=" + lastName +
            "&email=" + providedEmailAddress +
            "&phone=" + providedPhoneNumber;

        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';
                        }
                    }
                    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');
                }
                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, 'LI');
    if (NRT.Utility.objectExists(liTab))
    {
		liTab.onclick();
    }
}
