﻿// MUTUAL across more than one control

function trapEnter(evnt) {
    var key = evnt.keyCode || evnt.which;
    return key != 13;
}
// *****************    AGENT LISTING CONTROL SCRIPT     ***************

function loadAgentListingControl(operatorValue) {

    if (agentListings == null || agentListings == 'undefined') return;

    var leftArrow = document.getElementById('_myListingPropertyPhotoLeftArrow');
    var rightArrow = document.getElementById('_myListingPropertyPhotoRightArrow');


    if (operatorValue == 1) {
        if (agentListingIndex == agentListings.length - 1) return;
        agentListingIndex++;
    }
    else {
        if (agentListingIndex < 1) return;
        agentListingIndex--;
    }

    var addressLine = document.getElementById('_myListingsAddressLine');
    var descriptorLine = document.getElementById('_myListingsDescriptorLine');
    var propertyPhoto = document.getElementById('_myListingsPropertyPhoto');
    var propertyPhotoAnchor = document.getElementById('_myListingPropertyPhotoAnchor');

    var myListing = agentListings[agentListingIndex].split('~');

    propertyPhoto.src = myListing[0];
    propertyPhotoAnchor.href = myListing[1];
    addressLine.href = myListing[1];
    addressLine.innerHTML = myListing[2];
    descriptorLine.innerHTML = myListing[3];

    if (agentListingIndex == agentListings.length - 1) { rightArrow.src = 'Images/ListingAgentControlRightArrow.gif'; rightArrow.style.cursor='default'; }
    else { rightArrow.src = 'Images/ListingAgentControlRightArrow_act.gif'; rightArrow.style.cursor='pointer'; }

    if (agentListingIndex == 0) { leftArrow.src = 'Images/ListingAgentControlLeftArrow.gif'; leftArrow.style.cursor='default'; }
    else { leftArrow.src = 'Images/ListingAgentControlLeftArrow_act.gif';leftArrow.style.cursor='pointer'; }

    //hide nav arrows if only 1 listing
    if (agentListings.length == 1)
    {
		rightArrow.style.display='none';
		leftArrow.style.display='none';   
    }
}

function loadSecondaryAgentListingControl(operatorValue) {

    if (secondaryAgentListings == null || secondaryAgentListings == 'undefined') return;

    var leftArrow = document.getElementById('_secondaryMyListingPropertyPhotoLeftArrow');
    var rightArrow = document.getElementById('_secondaryMyListingPropertyPhotoRightArrow');


    if (operatorValue == 1) {
        if (secondaryAgentListingIndex == secondaryAgentListings.length - 1) return;
        secondaryAgentListingIndex++;
    }
    else {
        if (secondaryAgentListingIndex < 1) return;
        secondaryAgentListingIndex--;
    }

    var addressLine = document.getElementById('_secondaryMyListingsAddressLine');
    var descriptorLine = document.getElementById('_secondaryMyListingsDescriptorLine');
    var propertyPhoto = document.getElementById('_secondaryMyListingsPropertyPhoto');
    var propertyPhotoAnchor = document.getElementById('_secondaryMyListingPropertyPhotoAnchor');

    var myListing = secondaryAgentListings[secondaryAgentListingIndex].split('~');

    propertyPhoto.src = myListing[0];
    propertyPhotoAnchor.href = myListing[1];
    addressLine.href = myListing[1];
    addressLine.innerHTML = myListing[2];
    descriptorLine.innerHTML = myListing[3];

    if (secondaryAgentListingIndex == secondaryAgentListings.length - 1) { rightArrow.src = 'Images/ListingAgentControlRightArrow.gif'; rightArrow.style.cursor='default'; }
    else { rightArrow.src = 'Images/ListingAgentControlRightArrow_act.gif'; rightArrow.style.cursor='pointer'; }

    if (secondaryAgentListingIndex == 0) { leftArrow.src = 'Images/ListingAgentControlLeftArrow.gif'; leftArrow.style.cursor='default'; }
    else { leftArrow.src = 'Images/ListingAgentControlLeftArrow_act.gif';leftArrow.style.cursor='pointer'; }

	//hide nav arrows if only 1 listing
    if (secondaryAgentListings.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('_viewLargerMapAnchor').innerHTML = s;

}

function AddPushpin() {
    var shape = new VEShape(VEShapeType.Pushpin, map.GetCenter());
    var icon = "<img src='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;
}

// ***************  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 (rdoDownpaymentPercentage.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
    txtPurchasePrice.value = formatCurrency(present_value);
    txtDownpaymentAmount.value = formatCurrency(down_paymentAmount);
    txtAnnualTaxes.value = formatCurrency(annual_taxesAmount);
    txtAnnualInsurance.value = formatCurrency(annual_insuranceAmount);
    txtAnnualInterestRate.value = (interest_rate * 100).toString() + "%";

    //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 ********************

$(document).ready(function(){
if (typeof(propertyDetailsPhotoInfos) !== 'undefined' && 
    propertyDetailsPhotoInfos != null &&
    propertyDetailsPhotoInfos.length < 2) {
 $("#thumbnailsContainer").remove();
 $("#pageandlargePhs").remove(); $("#_photoNavigationButtons").remove();
}
else{
 $("#thumbnailsContainer").css({'display':'block'});
 $("#_photoNavigationButtons").css({'display':'inline'});
 $("#pageandlargePhs").css({'display':'inline'});
 
 $("#thumbnailsContainer: img").hover(function() {
    if ( ($(this).attr('alt')=='selected') || ($(this).attr('src')=='Images/common_spacer.gif') )
    {
        // image is currently selected, is at full opacity
    }
    else
    {
        $(this).fadeTo(500, 1); // fadeTo(time, opacity)
    }
}, function() { 
    if ( ($(this).attr('alt')=='selected') || ($(this).attr('src')=='Images/common_spacer.gif') )
    {
        // image is currently selected, is at full opacity
    }
    else
    {
        $(this).stop(true,true); // (all animations,complete current animation)
        $(this).fadeTo(500, 0.8);
    }
}); // end hover on thumbnails

$("#thumbnailsContainer: img").click(function(){

    var thisSRC = $(this).attr("src");
    var thisIndex =  $('#thumbnailsContainer: img').index(this);
       
    if (! ($(this).attr('src')=='Images/common_spacer.gif') )
    {
        $("#thumbnailsContainer: img[alt='selected']").attr('alt', '');
     
        $(this).attr('alt', 'selected').css({'border': '3px', 'border-color':'#6699cc', 'border-style':'solid'});
        $("#thumbnailsContainer: img:not([alt='selected'])").css({'border': '1px','border-color':'#cccccc','border-style':'solid','opacity':'0.8'});
        $("#thumbnailsContainer: img[alt='empty']").css({'opacity':'0.8', 'border-color':'#ffffff'});
               
        $('#plcLgPhoto').stop(true,false); // elminate stacked animations
        $('#plcLgPhoto').fadeTo(250, 0.1, function() {
              $('#plcLgPhoto img').attr('src', thisSRC); 
              resetPhoto();
        });
        
        highlightImageThumbnail(thisIndex); 
        setPhotoNavigationStyles();
    } // if not

}); // end click function
} // end of if no photos, everything above here contained in if no photos clause
}); // end docready

function removeEmptys()
{
    $("#thumbnailsContainer: img").attr('alt', '')
    $("#thumbnailsContainer: img").eq(currentPhotoHighlightIndex).attr('alt', 'selected').css({'border': '1px', 'border-color':'#cccccc', 'border-style':'solid'});
    
    $("#thumbnailsContainer: img").each(function(index){
        if ($(this).attr('src')=='Images/common_spacer.gif')        
        {
            $(this).attr('alt', 'empty');
            var tifl = $(this).parent().get(0)
            $(tifl).css({'display':'none'});
        }
    });
OpeningAnimation();

} // end removeEmptys

function OpeningAnimation()
{
    $('#plcLgPhoto').fadeTo(400, 1.0);
    $("#thumbnailsContainer: img").each(function(index){
        if ($(this).attr('alt')=='selected')
        {
            $(this).animate({ 
                opacity: 1.0
            }, 200, "swing");
            
            $(this).css({'border': '3px', 'border-color':'#6699cc', 'border-style':'solid'}); 
        }
        else
        {
            if (! ($(this).attr('src')=='Images/common_spacer.gif') )
            {
                $(this).animate({ 
                    opacity: 0.8
                }, 200, "swing");
                $(this).css({'border': '1px', 'border-color':'#cccccc', 'border-style':'solid'});
            }
        }
    });

} // end OpeningAnimation()

function animateNextPhoto(index)
{
    var thisSRC = $('#thumbnailsContainer: img').eq(index).attr("src");

    $('#thumbnailsContainer: img').css({'opacity': '0.8', 'border': '1px', 'border-color':'#cccccc', 'border-style':'solid'}); 
    $('#thumbnailsContainer: img').eq(index).css({'opacity': '1.0', 'border': '3px', 'border-color':'#6699cc', 'border-style':'solid'}); 
    $("#thumbnailsContainer: img[alt='empty']").css({'opacity':'0.8', 'border-color':'#ffffff'});
    //$('#plcLgPhoto img').attr('src', thisSRC); 
    
    $('#plcLgPhoto').stop(true,false); // elminate stacked animations
    $('#plcLgPhoto').fadeTo(250, 0.1, function() {
          $('#plcLgPhoto img').attr('src', thisSRC); 
          resetPhoto();
    });
}

function resetPhoto()
{
       $('#plcLgPhoto').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 = '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;
            thumbnailDivElements[j].style.display='inline';
            j++;
        }

        //assign the main image url
        //largeImageElementName.src = propertyDetailsPhotoInfos[currentPhotoPageIndex * 10 + currentPhotoHighlightIndex].mainURL;
        //set current index
        highlightImageThumbnail(currentPhotoHighlightIndex);
        animateNextPhoto(currentPhotoHighlightIndex);
        removeEmptys();
    }
}

function openLargePhotos(address, listingID) {

    var j = window.open("CaliforniaMoves.com", "LargePhotos", "height=650,width=650,status=1,toolbar=1,menubar=1,scrollbars=1,top=5,location=1,resizable=1");
    j.document.write("<body style='padding:0px 0px;margin: 0px 0px;>");
    j.document.write("<table width='639' 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'><img src='../../images/printbanner.jpg' /><p style='font-weight:bold;color:#003169;'>" + address + "</p>");
    j.document.write("<p style='color:#003169;'>MLS #" + listingID + "</p><p>&nbsp;</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;' src='" + propertyDetailsPhotoInfos[i].mainURL + "' /><br /></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].style.backgroundColor = "#ededed";
        pagingPads[i].style.border = "solid 1px #cccccc";
        pagingPads[i].style.color = "#639ace";
        pagingPads[i].style.cursor = "pointer";
    }

    //border:solid 1px #cccccc;background-color:#ededed;
    pagingPads[currentPhotoPageIndex].style.backgroundColor = "#ffffff";
    pagingPads[currentPhotoPageIndex].style.border = "none 0px #ffffff";
    pagingPads[currentPhotoPageIndex].style.color = "#000000";
    pagingPads[currentPhotoPageIndex].style.cursor = "default";
}

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 3 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;
    //check first name

    message = document.getElementById('_contactFormMessage').value.trimSpaces();
    if (message.length == 0)
        errorMessage += "Message is a required field.\r\n";
    firstName = document.getElementById('_contactFormFirstName').value.trimSpaces();
    if (firstName.length == 0)
        errorMessage += "First Name is a required field.\r\n";
    lastName = document.getElementById('_contactFormLastName').value.trimSpaces();
    if (lastName.length == 0)
        errorMessage += "Last Name is a required field.\r\n";
    providedEmailAddress = document.getElementById('_contactFormEmail').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('_contactFormPhoneNumber').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=" + propDetailContactFormPropID +
                      "&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 (this.status = 200) {
                    if (typeof (oXMLHttpRequest.responseText) != 'undefined') {
                        document.getElementById('contactForm').innerHTML = oXMLHttpRequest.responseText;
                    }
                }
                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*$/, '');
};


