// ----------------------------------------------------------------------------------------------
// ------------------------------- CONTACT US AJAX FUNCTIONS ------------------------------------
// ----------------------------------------------------------------------------------------------

var metroAreaSelectedID = 0;


// create containers for community selection state
function InterestStateSelected (stateID) {
  var brandID = productSearchBrandIds[getCurrSite()];
	if (stateID!='') {Pulte08.AjaxWebServices.ContactUsService.GetAreasByState(stateID,brandID,ShowAreas)}
	else {
		var select = document.contact.interestMetroArea;
		select.options.length=0;
		select.options[0] = new Option('Select',''); 
		resetMultiSelect();
		a$.multiSelectCreate('interestSelect');
	}
}

// populate community selection state
function ShowAreas (result) {
	var select = document.contact.interestMetroArea;
		select.options.length = 0;
		select.options[0] = new Option('Select','');
	for (var i=0; i < result.length; i++) select.options[i+1] = new Option(result[i].Description,result[i].Title);
}

// create containers for community selection metro area
function InterestMetroAreaSelected (areaID) {
  var brandID = productSearchBrandIds[getCurrSite()];
	if (metroAreaSelectedID != areaID) { 
		metroAreaSelectedID = areaID; // to prevent it of running more than once
		if (areaID!='') {Pulte08.AjaxWebServices.ContactUsService.GetCommunitiesByArea(areaID,brandID,ShowCommunities)}
		else {
			resetMultiSelect();
			a$.multiSelectCreate('interestSelect');
		}
	}
}

// populate community selection metro area
function ShowCommunities(result) {
	resetMultiSelect(); // clear any existing multiselects
	// get the communities already selected
	var	selectedCommunities = getMultiSelectValues();
	var select = document.getElementById('interestSelect');
	var html = '';

	// set checkbox for already selected communites
	for (var i=0; i < result.length; i++) {
		var communityID = result[i].Title;
		var isSelected = false;
		for (var j=0; j < selectedCommunities.length; j++) {
			if (selectedCommunities[j]==communityID) isSelected = true;
		}
		html += '<option value="' + result[i].Title + '"';
		if (isSelected) html += ' selected';
		html += '>' + result[i].Description + '</option>';
	}
	
	// IE6 bug makes programmatically setting options via DOM or innerHTML difficult
	if (isIE) {
		html = '<select id="interestSelect" name="interestSelect" class="multiSelect" multiple="multiple" size="4" title="Select " + brandNeighborhoodLabels + " of Interest">' + html + '</select>';
		document.getElementById('interestSelect').outerHTML = html;
	}
	else {document.getElementById('interestSelect').innerHTML = html}

	a$.multiSelectCreate('interestSelect'); // create dhtml multi-select
	deactivateCheck(); // deactivate checkboxes if > 4 selected communities
}

// call web service method - pass data to eai to update a contact information  
function SaveContactUs(){ 
	var siteID = productSearchBrandIds[getCurrSite()];
	var eventContext = 'CONTACT_US'
	var isLoggedIn = (document.getElementById('isLoggedIn').value=='1');
	var isInternational = false;
	var communityID = document.getElementById('communityID');
	var topicID = 0;
	var serviceRequest = false;
	
	if (document.select.selectInfo.checked) topicID = 1;
	if (document.select.selectMortgages.checked) topicID = 2;
	//if (document.select.selectSupport.checked) topicID = 3;
	if (document.select.selectHomeowner.checked) topicID = 4;
	/* service request is moved to homeowner portal page
	if (document.select.selectServiceRequest.checked) {
	    topicID = 4;
	    serviceRequest = true;
	}
	*/
	//if (document.select.selectCorpComm.checked) topicID = 5;
	//if (document.select.selectInvRelations.checked) topicID = 6;
	//if (document.select.selectCareers.checked) topicID = 7;
	//if (document.select.selectGeneral.checked) topicID = 8;

	var firstName = document.contact.firstName;
	var lastName = document.contact.lastName;
	var email = document.contact.email;
	var address1 = document.contact.address1;
	var address2 = document.contact.address2;
	var city = document.contact.city;
	var state = document.contact.state;
	var zip = document.contact.zip;
	var areaCode1 = document.contact.primaryPhone1;
	var prefix1 = document.contact.primaryPhone2;
	var suffix1 = document.contact.primaryPhone3;
	var areaCode2 = document.contact.secondPhone1;
	var prefix2 = document.contact.secondPhone2;
	var suffix2 = document.contact.secondPhone3;
	var profilePhone1 = document.contact.contactProfilePhone1;
	var profilePhone2 = document.contact.contactProfilePhone2;

	var country = document.contact.country;
	var countryName = '';
	if (country.selectedIndex>0) countryName = country.options[country.selectedIndex].text;

	var provinceRegionValue = '';
	var postalCodeValue = '';
	var international = document.getElementById('international');

	if (!YUD.hasClass(international,'hide')) {
		isInternational = true;
		provinceRegionValue = document.contact.province.value;
		postalCodeValue = document.contact.postal.value;
	}

	var phone1 = document.contact.international1;
	var phone2 = document.contact.international2;
	var updateProfile = document.contact.updateInfo;

	var message = document.contact.message;
	var informationSource = "";  document.contact.hearAboutUs;
	var isBroker = document.contact.realtor;
	var brokerOfficeValue = '';
	var taxIDValue = '';

	if (isBroker.checked) {
		brokerOfficeValue = document.contact.brokerOffice.value;
		taxIDValue = document.contact.brokerID.value;
	}
	else {
		brokerOfficeValue = '';
		taxIDValue = '';
	}
  
	var selectedCommunities = new Array();
	selectedCommunities = getMultiSelectValues();

	
	var serviceArea = document.contact.serviceArea;
	var serviceCommunityName = document.contact.serviceCommunityName;
	var serviceItem = document.contact.serviceItem;
	var serviceRoom = document.contact.serviceRoom;

	ajaxLoading('contactUsSubmit','submit','start'); // show the spinner
    //ajaxLoading('topContactUsSubmit','submit','start');
  
	Pulte08.AjaxWebServices.ContactUsService.SaveContactUs(siteID,eventContext,isLoggedIn,topicID,selectedCommunities,
	firstName.value,lastName.value,email.value,address1.value,address2.value,city.value,state.value,
	zip.value,areaCode1.value,prefix1.value,suffix1.value,areaCode2.value,prefix2.value,suffix2.value, profilePhone1.value, profilePhone2.value,isInternational,
	country.value,countryName,provinceRegionValue,postalCodeValue,phone1.value,phone2.value,updateProfile.checked,message.value,
	informationSource, isBroker.checked, brokerOfficeValue, taxIDValue,
	serviceRequest, serviceArea.value, serviceCommunityName.value, serviceItem.value, serviceRoom.value,
	ContactUsSaved);

	return true;
}

// callback function that processes the web service return value
function ContactUsSaved(result){
	var target = document.getElementById('contactUsSubmit')
	ajaxLoading('contactUsSubmit','submit','stop');
	//ajaxLoading('topContactUsSubmit','submit','stop');
	if (result != null && result[0] != null) {
	    ShowThankYou(result);   // Show Thank you even if error occured (6/16/2011)
	    /*
		if (result[0].Title!='error') ShowThankYou(result);
		else {
		  if(document.URL.indexOf('localhost')>=0 || document.URL.indexOf('.dev.')>=0 || document.URL.indexOf('.qa.')>=0) alert(result[0].Description);
		  else target.innerHTML = '<div class="ajaxError">There was a server error. Please try again later...</div>';
		}
		*/
	}
	else {
		target.innerHTML = '<div class="ajaxError">The server did not respond. Please try again later...</div>';
	}
	return false;
}

// show thank you page on successful submission
function ShowThankYou(result) {
  /* Text is specific for Jump Start campaign:
  if (currSelectedTopic == 'info' || currSelectedTopic == 'general' || currSelectedTopic == 'investor' || currSelectedTopic == 'mortgages') {
    $get('thankYouText').innerHTML = '<p class="promotion1">Thank you for contacting Pulte Homes. If you had a specific question, we will contact you soon.</p>' + 
    '<p class="promotion">At Pulte Homes, we understand that getting a jump-start on homeownership is everything. ' +
    'That\'s why for a limited time, Pulte Homes is giving at least $7,500* in incentives to ALL of our homebuyers. ' +
    'It\'s a wonderful opportunity to enjoy a little relief on the purchase of your new home.</p>' + 
    '<p class="promotionB">To get a jump-start on your dream home, <a href="/assets/pdf/Jump_Start_to_Savings.pdf" target=_blank>click here</a>.';
    $get('thankYouDisclaimer').innerHTML = '<p class="disclaimer">*Jump-Start offerings valid only on new purchase agreements executed between August 5, 2008 and September 15, 2008. ' +
    'Offerings vary by community and may be part of or in addition to existing offers. ' +
    'Please see a sales associate at the community of your interest for full details. Offer subject to change without notice.<br>' +
    '&copy; 2008 Pulte Home Corporation.</p>';
  }
  */
    if (currSelectedTopic == 'info')  {

	if (UseHitBox) _hbPageView('ContactUs-NeighborhoodInfo-ThankYou','/form_conversion'); // hbx conversion tracking

    //SiteCatalyst code to track form conversion***************************************************************************************
    if (UseSiteCatalyst)
    {
 

       var sOldPageName = s.pageName;

       s.pageName='ContactUs-ThankYou';
       if (sOldPageName.length>0) 
			s.pageName = sOldPageName + " - ContactUs-ThankYou"
       



       //var sOldPageName = s.pageName;
       //s.pageName=s.pageName + 'ContactUs-ThankYou';
       s.events="event2"
       s.eVar1="contact us"
       s.t();
       s.pageName = sOldPageName;
    }
	//End SiteCatalyst code to track form conversion***********************************************************************************


    }
    var thankyouHtml = "";
    if (currSelectedTopic == 'homeowner') { // it includes service request
        switch (productSearchBrandIds[getCurrSite()]) {
            case 1:
                thankyouHtml = "<p class='thankyou'>Thank you for contacting Pulte Homes. Your request has been received and a market representative will contact you within two business days.</p><br />" +
                            "<p class='thankyou'>If this is an emergency, warranty service is available after hours, on weekends and holidays by contacting the emergency service information " +
                            "provided by your local Pulte Homes representative during contract signing. " +
                            "Some examples of emergencies include gas leaks, no heat in extreme cold, no cooling in extreme heat, severe electrical problems, or severe plumbing leaks that cannot be isolated.</p>";
                break;
            case 2:
                thankyouHtml = "<p class='thankyou'>Thank you for contacting Del Webb. Your request has been received and a market representative will contact you within two business days.</p><br />" +
                            "<p class='thankyou'>If this is an emergency, warranty service is available after hours, on weekends and holidays by contacting the emergency service information provided by your local Del Webb representative during contract signing. Some examples of emergencies include gas leaks, no heat in extreme cold, no cooling in extreme heat, severe electrical problems, or severe plumbing leaks that cannot be isolated.</p>";
                break;

            case 3:
                thankyouHtml = "<p class='thankyou'>Thank you for contacting DiVosta. Your request has been received and a market representative will contact you within two business days.</p><br />" +
                            "<p class='thankyou'>If this is an emergency, warranty service is available after hours, on weekends and holidays by contacting the emergency service information provided by your local DiVosta representative during contract signing. Some examples of emergencies include gas leaks, no heat in extreme cold, no cooling in extreme heat, severe electrical problems, or severe plumbing leaks that cannot be isolated.</p>";
                break;

            case 4:
                thankyouHtml = "<p class='thankyou'>Thank you for contacting Centex. Your request has been received and a market representative will contact you within two business days.</p><br />" +
                            "<p class='thankyou'>If this is an emergency, warranty service is available after hours, on weekends and holidays by contacting the emergency service information provided by your local Centex representative during contract signing. Some examples of emergencies include gas leaks, no heat in extreme cold, no cooling in extreme heat, severe electrical problems, or severe plumbing leaks that cannot be isolated.</p>";
                break;
        }
    } else {
        switch (productSearchBrandIds[getCurrSite()]) {
            case 1:
                thankyouHtml = "<p class='thankyou'>Thank you for contacting Pulte Homes. Your request has been sent. If you had a specific question, we will contact you soon.</p>";
                break;
            case 2:
                thankyouHtml = "<p class='thankyou'>Thank you for contacting Del Webb. Your request has been sent. If you had a specific question, we will contact you soon.</p>";
                break;

            case 3:
                thankyouHtml = "<p class='thankyou'>Thank you for contacting DiVosta. Your request has been sent. If you had a specific question, we will contact you soon.</p>";
                break;

            case 4:
                thankyouHtml = "<p class='thankyou'>Thank you for contacting Centex. Your request has been sent. If you had a specific question, we will contact you soon.</p>";
                break;
        }
    }
    $get('thankYouText').innerHTML = thankyouHtml;
	
	var isRegistered = document.getElementById('isRegistered');
	if (isRegistered != null) {
		isRegistered.value = result[0].Description; // "1" if registered
	}
	var neighborhoodCodes = "";
	var geoRegions = "";
	var html = '<table summary="Visit Us in Person"><tbody id="visitOptions">';

	for (var i=1; i < result.length  ;i++) {
	  if (result[i].Title.substr(0,4)=="atc2") {
	    neighborhoodCodes = result[i].Description;
	  } 
	  else {
	    if (result[i].Title.substr(0,4)=="atc3") {
	      geoRegions = result[i].Description;
      } 
	    else {  // community information
		    html += '<tr><td colspan="2" class="check"><input type="radio" id="visitCommunity' + eval(i) + '" value="' + 
		    result[i].Description + '" name="visitCommunity" class="styleInput"';
		    if(i==1) html += ' checked';
		    html += ' /><label for="visitCommunity' + eval(i) + '" >' + result[i].Title + '</label></td></tr>\r\n';
		  }
		}
	}
	var seoTag = "";    // atlasConversion(neighborhoodCodes, geoRegions); // atlas conversion tracking. removed 6/1/10
	html += // need to add the whole table in div innerHTML or div adds </table> by itself
		'<tr><td colspan="2" class="hrspace"></td></tr><tr>'+
		'<td colspan="2"><label for="visitAddress">Starting Address</label><input type="text" id="visitAddress" name="visitAddress" class="inputStyle" tabindex="47" maxlength="200" size="45" /></td></tr>\r\n' +
		'<tr><td><label for="visitCity">City</label><input type="text" id="visitCity" name="visitCity" class="inputStyle" tabindex="48" maxlength="50" size="22" /></td>'+
		'<td><label for="visitState">State</label><select id="visitState" name="visitState" tabindex="49">'+
		'<option value="">Select</option><option value="AA">AA (military)</option><option value="AE">AE (military)</option><option value="AP">AP (military)</option><option value="AL">Alabama</option><option value="AK">Alaska</option><option value="AZ">Arizona</option><option value="AR">Arkansas</option><option value="CA">California</option><option value="CO">Colorado</option><option value="CT">Connecticut</option><option value="DE">Delaware</option><option value="DC">District of Columbia</option><option value="FL">Florida</option><option value="GA">Georgia</option><option value="HI">Hawaii</option><option value="ID">Idaho</option><option value="IL">Illinois</option><option value="IN">Indiana</option><option value="IA">Iowa</option><option value="KS">Kansas</option><option value="KY">Kentucky</option><option value="LA">Louisiana</option><option value="ME">Maine</option><option value="MD">Maryland</option><option value="MA">Massachusetts</option><option value="MI">Michigan</option><option value="MN">Minnesota</option><option value="MS">Mississippi</option><option value="MO">Missouri</option><option value="MT">Montana</option><option value="NE">Nebraska</option><option value="NV">Nevada</option><option value="NH">New Hampshire</option><option value="NJ">New Jersey</option><option value="NM">New Mexico</option><option value="NY">New York</option><option value="NC">North Carolina</option><option value="ND">North Dakota</option><option value="OH">Ohio</option><option value="OK">Oklahoma</option><option value="OR">Oregon</option><option value="PA">Pennsylvania</option><option value="RI">Rhode Island</option><option value="SC">South Carolina</option><option value="SD">South Dakota</option><option value="TN">Tennessee</option><option value="TX">Texas</option><option value="UT">Utah</option><option value="VT">Vermont</option><option value="VA">Virginia</option><option value="WA">Washington</option><option value="WV">West Virginia</option><option value="WI">Wisconsin</option><option value="WY">Wyoming</option></select></td></tr>\r\n'+
		'<tr><td><label for="visitZip">ZIP Code</label><input type="text" id="visitZip" name="visitZip" class="inputStyle" tabindex="50" maxlength="10" size="22" /></td><td><div class="right"><input type="image" src="/images/Pulte/button-go.gif" onclick="fastPassDirections();" alt="Go" class="submit legal" tabindex="51" /></div></td></tr>\r\n'+
		'</tbody></table>\r\n'  + seoTag;
  //  alert(html);
	$get('visitCommunityArea').innerHTML = html;
	styleButtonInput();

	if (document.getElementById('state').value !='') {
		document.getElementById('visitAddress').value = document.getElementById('address1').value;
		document.getElementById('visitCity').value = document.getElementById('city').value;
		document.getElementById('visitZip').value = document.getElementById('zip').value;
		document.getElementById('visitState').value = document.getElementById('state').value;
	}

	var level1 = YUD.getElementsByClassName('level1','div')[0];
	var level2 = YUD.getElementsByClassName('level2','div')[0];
	var level3 = YUD.getElementsByClassName('level3','div')[0];
	var level4 = YUD.getElementsByClassName('level4','div')[0];
 
	// if user is logged in
	if (document.getElementById('isLoggedIn') && document.getElementById('isLoggedIn').value !=0) YUD.setStyle(document.thankyou,'display','none');

	// if user is NOT logged in but...
	else {
	    if (currSelectedTopic == 'homeowner') { // it includes service request
	        YUD.replaceClass(document.getElementById('thankYouSignIn'), 'show', 'hide');
	    } else {
	        // user is registered
	        if (document.getElementById('isRegistered') && document.getElementById('isRegistered').value != 0) { YUD.replaceClass(document.getElementById('thankYouSignIn'), 'hide', 'show') }
	        // user is NOT registered
	        else { YUD.replaceClass(document.getElementById('thankYouActivateNotebook'), 'hide', 'show') }
	    }
	}
	YUD.setStyle([level1,level2,level3],'display','none');
	YUD.setStyle(level4,'display','block');
}

// ----------------------------------------------------------------------------------------------

// SET JAVA SCRIPT TO TRACK CONTACT US CONVERSION (ATLAS) ON THANK YOU MSG

var atlasConversion = function(neighborhoodCodes, geoRegions) {
    var seoTag = "";
    return seoTag; // Atlas tags are removed from the site 6/1/10
    /*
    if (currSelectedTopic == "info" || currSelectedTopic == "mortgages") {
        var referral = document.contact.hearAboutUs.value;
        var siteCode = "";
        var site = getCurrSite().toLowerCase();
        if (site == "pulte") { siteCode = "Pulte"; }
        if (site == "delwebb") { siteCode = "Del_Webb"; }
        if (site == "divosta") { siteCode = "DiVosta"; }
        if (currSelectedTopic == "info") {
            seoTag = "<script>document.write('<s'+'cript language=\"JavaScript\" src=\"http://switch.atdmt.com/jaction/" + siteCode +
      "_Neighborhood_Info_Reg_Confirm_EDAT_0109/v3/atc1." + referral + "/atc2." + neighborhoodCodes +
      "/atc3." + geoRegions + "\"></s'+'cript>')</script>" +
      "<noscript><iframe src=\"http://view.atdmt.com/iaction/" + siteCode + "_Neighborhood_Info_Reg_Confirm_EDAT_0109/v3/atc1." + referral +
      "/atc2." + neighborhoodCodes + "/atc3." + geoRegions + "\" width=\"1\" height=\"1\" frameborder=\"0\" scrolling=\"No\" marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\" leftmargin=\"0\"></iframe></noscript>";
            /*  Start of DoubleClick Floodlight Tag: Please do not remove * /
            var axel = Math.random() + "";
            var a = axel * 10000000000000;
            if (site == "pulte") {
                seoTag = seoTag + '<script>document.write(\'<SCR' + 'IPT SRC="http://fls.doubleclick.net/activityj;src=2622573;type=thank457;cat=conta612;ord=1;num=' + a + '?" type="text/javascript"></SCR\'+\'IPT>\');</script>' +
        '<noscript><iframe src="http://fls.doubleclick.net/activity;src=2622573;type=thank457;cat=conta612;ord=1;num=1?" width="1" height="1" frameborder="0"></iframe></noscript>';
            }
            if (site == "delwebb") {
                seoTag = seoTag + '<script>document.write(\'<iframe src="http://fls.doubleclick.net/activityi;src=2622574;type=thank174;cat=conta521;ord=1;num=' + a + '?" width="1" height="1" frameborder="0"></iframe>\');</script>' +
        '<noscript><iframe src="http://fls.doubleclick.net/activityi;src=2622574;type=thank174;cat=conta521;ord=1;num=1?" width="1" height="1" frameborder="0"></iframe></noscript>';
            }
            /* End of DoubleClick Floodlight Tag: Please do not remove * /
        }
        if (currSelectedTopic == "mortgages") {
            seoTag = "<script>document.write('<s'+'cript language=\"JavaScript\" src=\"http://switch.atdmt.com/jaction/" + siteCode +
      "_Mortgage_Finance_Reg_Confirm_EDAT_0109/v3/atc1." + referral + "\"></s'+'cript>')</script>" +
      "<noscript><iframe src=\"http://view.atdmt.com/iaction/" + siteCode + "_Mortgage_Finance_Reg_Confirm_EDAT_0109/v3/atc1." + referral +
      "\" width=\"1\" height=\"1\" frameborder=\"0\" scrolling=\"No\" marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\" leftmargin=\"0\"></iframe></noscript>";
        }
    }
    else {
        seoTag = atlasTagCONFIG.getAtlasScriptTag(atlasTagCONFIG.seoCatContactUs, currSelectedTopic);
        if (seoTag == null) seoTag = ""
    }
    //alert(seoTag);
    return seoTag;
    */
}



// ----------------------------------------------------------------------------------------------
// ------------------------------- LIFESTYLE ADVISOR AJAX FUNCTIONS -----------------------------
// ----------------------------------------------------------------------------------------------

// create containers for community selection metro area
function AdvisorInterestMetroAreaSelected(regionID) {
    var brandID = productSearchBrandIds[getCurrSite()];
    if (metroAreaSelectedID != regionID) {
        metroAreaSelectedID = regionID; // to prevent it of running more than once
        if (regionID != '') { Pulte08.AjaxWebServices.ContactUsService.GetCommunitiesByRegion(regionID, brandID, AdvisorShowCommunities) }
        else {
            resetMultiSelect();
            a$.multiSelectCreate('interestSelect');
        }
    }
}

// populate community selection metro area
function AdvisorShowCommunities(result) {
    YUD.replaceClass(document.getElementById('interestStep3'), 'hide', 'show');
    resetMultiSelect(); // clear any existing multiselects

    // get the communities already selected
    var selectedCommunities = getMultiSelectValues();
    var select = document.getElementById('interestSelect');
    var html = '';

    // set checkbox for already selected communites
    for (var i = 0; i < result.length; i++) {
        var communityID = result[i].Title;
        var isSelected = false;
        for (var j = 0; j < selectedCommunities.length; j++) {
            if (selectedCommunities[j] == communityID) isSelected = true;
        }
        html += '<option value="' + result[i].Title + '"';
        if (isSelected) html += ' selected';
        html += '>' + result[i].Description + '</option>';
    }

    // IE6 bug makes programmatically setting options via DOM or innerHTML difficult
    if (isIE) {
        html = '<select id="interestSelect" name="interestSelect" class="multiSelect" multiple="multiple" size="4" title="Select " + brandNeighborhoodLabels + " of Interest">' + html + '</select>';
        document.getElementById('interestSelect').outerHTML = html;
    }
    else { document.getElementById('interestSelect').innerHTML = html }

    a$.multiSelectCreate('interestSelect'); // create dhtml multi-select
    deactivateCheck(); // deactivate checkboxes if > 4 selected communities
}


var submitAdvisorForm = function() {
    var errorConsole = YUD.getElementsByClassName('alertBar', '', document)[0];
    if (validate_advisor(errorConsole)) {

        // remove error console
        YUD.replaceClass(errorConsole, 'show', 'hide');
        if (document.getElementById('secondTitle')) { document.getElementById('secondTitle').style.display = "block"; }

        // grab email address and populate thank you page email
        //document.thankyou.confirmEmail.value = document.contact.email.value;

        SendAdvisorLead();
    }
    else { window.location = '#content' }
}

var validate_advisor = function(errorConsole) {

    var validity = true;
    var error_string = '';

    if (!check_notEmpty(document.advisorContact.firstName.value)) {
        validity = false;
        YUD.addClass(YUD.getAncestorByTagName(document.advisorContact.firstName, 'td'), 'error');
        error_string += '<li>Please enter a valid FIRST NAME</li>';
    }
    else { YUD.removeClass(YUD.getAncestorByTagName(document.advisorContact.firstName, 'td'), 'error') }

    if (!check_minChar(document.advisorContact.lastName.value)) { // must be at least two characters
        validity = false;
        YUD.addClass(YUD.getAncestorByTagName(document.advisorContact.lastName, 'td'), 'error');
        error_string += '<li>Please enter a valid LAST NAME</li>';
    }
    else { YUD.removeClass(YUD.getAncestorByTagName(document.advisorContact.lastName, 'td'), 'error') }

    if (!check_email(document.advisorContact.email.value)) {
        validity = false;
        YUD.addClass(YUD.getAncestorByTagName(document.advisorContact.email, 'td'), 'error');
        error_string += '<li>Please enter a valid EMAIL</li>';
    }
    else { YUD.removeClass(YUD.getAncestorByTagName(document.advisorContact.email, 'td'), 'error') }

    if (!check_empty(document.advisorContact.state.value)) {
        validity = false;
        YUD.addClass(YUD.getAncestorByTagName(document.advisorContact.state, 'td'), 'error');
        error_string += '<li>Please select a STATE</li>';
    }
    else { YUD.removeClass(YUD.getAncestorByTagName(document.advisorContact.state, 'td'), 'error') }

    /*  if no communities were selected, we need to generate brand level lead, with BrandID serving as CommunityID
    var selectedCommunities = new Array();
    selectedCommunities = getMultiSelectValues();

    if (selectedCommunities.length == 0) {
    validity = false;
    YUD.addClass(document.getElementById('interestStep3').getElementsByTagName('label')[0], 'error');
    document.getElementById('metro').style.borderColor = '#B35817';
    error_string += '<li>Please select at least one ' + brandNeighborhoodLabel.toUpperCase() + ' INTEREST</li>';
    }
    else {
    YUD.removeClass(document.getElementById('interestStep3').getElementsByTagName('label')[0], 'error');
    document.getElementById('metro').style.borderColor = '#D6BB85';
    }
    */

    // show error console
    if (validity == false) {
        if (document.getElementById('secondTitle')) { document.getElementById('secondTitle').style.display = "none"; }
        YUD.replaceClass(errorConsole, 'hide', 'show');
        displayError('contactError', error_string);
    }

    return validity;
}


// call web service method - pass data to eai to update a contact information  
function SendAdvisorLead(){ 
	var siteID = productSearchBrandIds[getCurrSite()];
	var eventContext = 'CONTACT_US'
	var isLoggedIn = false;
	var isInternational = false;
	var communityID = document.getElementById('communityID');
	var topicID = 13;
	var firstName = document.advisorContact.firstName;
	var lastName = document.advisorContact.lastName;
	var email = document.advisorContact.email;
	var state = document.advisorContact.state;
	var contactID = 0;
	var selectedCommunities = new Array();
	if (document.advisorContact.contactID) {
	    contactID = document.advisorContact.contactID.value; // hidden field in final page
	    selectedCommunities = getMultiSelectValues();
	} else {
	    topicID = 12; // "advisor in progress"
	}
	if (selectedCommunities.length == 0) {
	    // if no communities were selected, we need to generate brand level lead, with BrandID serving as CommunityID
	    selectedCommunities[0] = productSearchBrandIds[getCurrSite()];
	}
	ajaxLoading('contactUsSubmit','submit','start'); // show the spinner

  
	Pulte08.AjaxWebServices.ContactUsService.SaveContactUs(siteID,eventContext,isLoggedIn,topicID,selectedCommunities,
	firstName.value,lastName.value,email.value,contactID,'','',state.value,
	'','','','','','','', '', '',isInternational,
	'','','','','','',false,'',
	'', false, '','',
	false, '', '', '','',
	AdvisorLeadSent);

	return true;
}

function AdvisorLeadSent(result) {
    var target = document.getElementById('contactUsSubmit')
	ajaxLoading('contactUsSubmit','submit','stop');
	if (result != null && result[0] != null) {
	    if (result[0].Title != 'error') {
	        AdvisorEmailSent(result);
	    }
	    else {
	        if (document.URL.indexOf('localhost') >= 0 || document.URL.indexOf('.dev.') >= 0 || document.URL.indexOf('.qa.') >= 0) alert(result[0].Description);
	        else target.innerHTML = '<div class="ajaxError">There was a server error. Please try again later...</div>';
	    }
	}
	else {
		target.innerHTML = '<div class="ajaxError">The server did not respond. Please try again later...</div>';
	}
	return false;
}


function AdvisorEmailSent(result) {
    ajaxLoading('contactUsSubmit', 'submit', 'stop');
    if (result != null && result[0] != null) {
        if (result[0].Title != 'error') {
            // show final Thank you section
            if (document.getElementById("advisorContactDiv")) {
                YUD.replaceClass(document.getElementById('advisorContactDiv'), 'show', 'hide');
                if (document.getElementById('firstTitle')) { document.getElementById('firstTitle').style.display = "none"; }
                if (document.getElementById('secondTitle')) { document.getElementById('secondTitle').style.display = "none"; }
                if (document.getElementById('thanks1')) { document.getElementById('thanks1').style.display = "block"; }
                if (document.URL.toLowerCase().indexOf("questions") < 0) {
                    document.getElementById('advisorAfterSubmitionText').style.visibility = "visible";
                    document.getElementById('advisorAfterSubmitionText').style.display = "block";
                }
            }
            else { // we are in FinalPage, go to ThankYouPage
                loc = window.location.href;
                loc = loc.replace("FinalPage.aspx", "ThankYouPage.aspx");
                window.location.href = loc;
            }
        }
        else {
            if (document.URL.indexOf('localhost') >= 0 || document.URL.indexOf('.dev.') >= 0 || document.URL.indexOf('.qa.') >= 0) alert(result[0].Description);
            else target.innerHTML = '<div class="ajaxError">There was a server error. Please try again later...</div>';
        }
    }
    else {
        target.innerHTML = '<div class="ajaxError">The server did not respond. Please try again later...</div>';
    }
    return false;

}


YUE.onDOMReady(function() {
    if (document.advisorContact) {
        if (signedInStatus) {
            ShowUserInfo();
        }
    }
    if (document.getElementById("inProcessContactID")) {
        if (document.getElementById("inProcessContactID").value == "") {
            // contact's information hasn't been entered, show the form
            if (document.getElementById("advisorContactDiv")) {
                document.getElementById('advisorContactDiv').style.visibility = "visible";
            }
        } else {
            if (document.getElementById('firstTitle')) { document.getElementById('firstTitle').style.display = "none"; }
            if (document.getElementById('secondTitle')) { document.getElementById('secondTitle').style.display = "none"; }
            if (document.getElementById('thanks1')) { document.getElementById('thanks1').style.display = "block"; }
            if (document.URL.toLowerCase().indexOf("questions") < 0) {
                YUD.replaceClass(document.getElementById('advisorContactDiv'), 'show', 'hide');
                document.getElementById('advisorAfterSubmitionText').style.visibility = "visible";
                document.getElementById('advisorAfterSubmitionText').style.display = "block";
            }
        }
    }

});

function ShowUserInfo() {

    if (document.advisorContact.firstName!=null) {
        document.advisorContact.firstName.value = signedInUser.FirstName;
    }
    if (document.advisorContact.lastName != null) {
        document.advisorContact.lastName.value = signedInUser.LastName;
    }
    if (document.advisorContact.email != null) {
        document.advisorContact.email.value = signedInUser.Email;
    }
    if (document.advisorContact.state != null) {
        document.advisorContact.state.value = signedInUser.StateAbbreviation;
    }
}

function RemoveUserInfo() {
    if (document.advisorContact.firstName!=null) {
        document.advisorContact.firstName.value = "";
    }
    if (document.advisorContact.lastName != null) {
        document.advisorContact.lastName.value = "";
    }
    if (document.advisorContact.email != null) {
        document.advisorContact.email.value = "";
    }
    if (document.advisorContact.state != null) {
        document.advisorContact.state.value = "";
    }
}

function PopulateAdvisorContactForm() {
    // populate form fields
    if (document.getElementById('profileFirstName')) document.advisorContact.firstName.value = document.getElementById('profileFirstName').value;
    if (document.getElementById('profileLastName')) document.advisorContact.lastName.value = document.getElementById('profileLastName').value;
    if (document.getElementById('profileUserEmail')) document.advisorContact.email.value = document.getElementById('profileUserEmail').value;
    if (document.getElementById('profileState')) setSelectBoxValue(document.advisorContact.state, document.getElementById('profileState').value);
}



//////////////////////////////////////////////////////////////////////////////////////
//////////    REGION EVENTS AND DEALS          ///////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////


function ShowContactForm(formDivId, message) {
    html = "<div id='formWrapperSJ'><div id='form_prompt' class='softJoinMsg'>Please allow our friendly and knowledgeable advisor send you additional information about your community of interest. We will NEVER give your email address to anyone else.</div>" +
           "<form name='LandingSignUpForm' id='LandingSignUpForm' action='' onsubmit='return false' >" +
           "<fieldset> <div class=alertBar hide> <div class='alertHdr'></div> <div class='alertBdy' id='landingFormError'></div><div class='alertFtr'></div></div>" +
           "<div class='col'><label for='landingFirstName'>First Name<em>*</em></label><br /><INPUT type='text' id='landingFirstName' name='landingFirstName' style='border: 1px solid #D6BB85;' size='18' maxlength='50' tabindex='1' /></div>" +
           "<div class='col'><label for='landingLastName'>Last Name<em>*</em></label><br /><INPUT type='text' id='landingLastName' name='landingLastName' style='border: 1px solid #D6BB85;' size='18' maxlength='50' tabindex='2' /></div>" +
           "<div class='clear'></div><div class='colFull addressTrigger'><div class='domestic'><label for=landingState'>State of Residence<em>*</em> </label><br />" +
           "<select name='landingState' id='landingState' tabindex='3'>" +
           "<option value=''>Select</option><option value='AA'>AA (military)</option><option value='AE'>AE (military)</option><option value='AP'>AP (military)</option><option value='AL'>Alabama</option><option value='AK'>Alaska</option><option value='AZ'>Arizona</option><option value='AR'>Arkansas</option><option value='CA'>California</option><option value='CO'>Colorado</option><option value='CT'>Connecticut</option><option value='DE'>Delaware</option><option value='DC'>District of Columbia</option><option value='FL'>Florida</option><option value='GA'>Georgia</option><option value='HI'>Hawaii</option><option value='ID'>Idaho</option><option value='IL'>Illinois</option><option value='IN'>Indiana</option><option value='IA'>Iowa</option><option value='KS'>Kansas</option><option value='KY'>Kentucky</option><option value='LA'>Louisiana</option><option value='ME'>Maine</option><option value='MD'>Maryland</option><option value='MA'>Massachusetts</option><option value='MI'>Michigan</option><option value='MN'>Minnesota</option><option value='MS'>Mississippi</option><option value='MO'>Missouri</option><option value='MT'>Montana</option><option value='NE'>Nebraska</option><option value='NV'>Nevada</option><option value='NH'>New Hampshire</option><option value='NJ'>New Jersey</option><option value='NM'>New Mexico</option><option value='NY'>New York</option><option value='NC'>North Carolina</option><option value='ND'>North Dakota</option><option value='OH'>Ohio</option><option value='OK'>Oklahoma</option><option value='OR'>Oregon</option><option value='PA'>Pennsylvania</option><option value='RI'>Rhode Island</option><option value='SC'>South Carolina</option><option value='SD'>South Dakota</option><option value='TN'>Tennessee</option><option value='TX'>Texas</option><option value='UT'>Utah</option><option value='VT'>Vermont</option><option value='VA'>Virginia</option><option value='WA'>Washington</option><option value='WV'>West Virginia</option><option value='WI'>Wisconsin</option><option value='WY'>Wyoming</option>" +
           "</select></div>" +
           "<div class='international hide'><label for='landingCountry'>Country<em>*</em></label><div class='clear'></div>" +
           "<select id='landingCountry' class='countryOptions' tabindex='3'></select></div></div>" +
           "<div class='colLeft'><label for='landingEmail'>Email Address<em>*</em></label><br /><INPUT type='text' id='landingEmail' name='landingEmail' style='border: 1px solid #D6BB85;' size='18' maxlength='100' tabindex='4' /></div>" +
           "<div id='submitLandingSignUp'><input type='image' src='/images/Pulte/button-send-orange.gif' class='submit' alt='Send' id='landingSubmit' tabindex='5' />" +
           "<input type='hidden' id='landingComID' name='landingComID' value='' /><input type='hidden' id='message' name='message' value='' /></div>" +
           "<div class='clear'></div><div class='colFull'></div><div class='clear'></div></fieldset></form><div class='closeBtn'><a href='javascript:ReallyCloseAllForms();'>Close X</a></div></div><div class='thankyouWrapper hide' id='thankyouSJ'>" +
           "<h3>" + window.regionOffer_ThankYou + "</h3></div>";
    if (formDivId.indexOf("_") < 0) {
        // need to open hot home form
        CloseAllForms();
        formDiv = document.getElementById("hotHomeForm");
        formDiv.innerHTML = html;
        document.LandingSignUpForm.landingComID.value = formDivId;
        document.LandingSignUpForm.message.value = message;
        // display previously submitted information (window variables got values in global.js submitSignUp function)
        document.LandingSignUpForm.landingFirstName.value = window.regionOffer_fName;
        document.LandingSignUpForm.landingLastName.value = window.regionOffer_lName;
        document.LandingSignUpForm.landingEmail.value = window.regionOffer_email;
        document.LandingSignUpForm.landingState.value = window.regionOffer_state;
        formDiv.style.display = "block";
        window.leadTopicID = "111";
        CommunitySignUp.initialize();
    } else {
        if (document.getElementById(formDivId) != null) {
            document.getElementById("hotHomeForm").style.display = "none";
            document.getElementById("hotHomeForm").innerHTML = "";
            CloseAllForms();
            formDiv = document.getElementById(formDivId);
            formDiv.innerHTML = html;
            if (document.LandingSignUpForm.landingComID) {
                //alert(formDivId.substr(formDivId.indexOf("_") + 1));
                document.LandingSignUpForm.landingComID.value = formDivId.substr(formDivId.indexOf("_") + 1);
            }
            // display previously submitted information (window variables got values in global.js submitSignUp function)
            document.LandingSignUpForm.landingFirstName.value = window.regionOffer_fName;
            document.LandingSignUpForm.landingLastName.value = window.regionOffer_lName;
            document.LandingSignUpForm.landingEmail.value = window.regionOffer_email;
            document.LandingSignUpForm.landingState.value = window.regionOffer_state;
            // make the form visible
            formDiv.style.display = "block";
            window.leadTopicID = "110";
            CommunitySignUp.initialize();
        }
    }
}
function ReallyCloseAllForms(){
    document.getElementById("hotHomeForm").style.display = "none";
    document.getElementById("hotHomeForm").innerHTML = "";
    CloseAllForms();
}






function ShowMap (communityID) { //(latitude, longitude) {
    defaultMapLat = 33;
    defaultMapLng = -112;
    customMarkerUtils.gmap = YUD.getElementsByClassName('google-map', 'div')[0].map;
    var comID = new Array();
    comID[0] = communityID;
    Pulte08.AjaxWebServices.PredefinedLandingService.GetPredefinedResults(comID, RegionOffer.initializeMap);
}

var RegionOffer = {
    searchResults: [],
    sortedResults: [], // capture the index of the searchResult
    resultLocations: [],
    priceSort: 0, // 0 is low to hight, 1 is high to low
    selectedCommunities: [],
    currentPage: 1,
    totalPages: 0,
    startIndex: 0,
    endIndex: 0,
    curPriceFilter: "",
    highestPrice: 0,
    selectedComList: [],
    userDetails: [],
    priceLabel: "",

    initializeMap: function(results) {
        if (!results || !results.markersArray || results.markersArray.length < 1) return;
        RegionOffer.searchResults = results.markersArray.slice(0);
        RegionOffer.searchResults[0].point = { latitude: RegionOffer.searchResults[0].point.Latitude, longitude: RegionOffer.searchResults[0].point.Longitude, zoom: 14 };
        customMarkerUtils.buildDynamicMarkers(RegionOffer.searchResults);
        YAHOO.mapPopUp.showMap();
    }
}

function HideMap() {
    YAHOO.mapPopUp.hideMap();
}


YAHOO.namespace('mapPopUp');
YAHOO.mapPopUp.init = function() {

    // Build overlay based on markup
    YAHOO.mapPopUp.overlay = new YAHOO.widget.Overlay('mapWrapper', { 'fixedCenter': true, 'width': 380, 'visible': false, 'zIndex': 1100, 'effect': { 'effect': YAHOO.widget.ContainerEffect.FADE, duration: 0.25} });
    YAHOO.mapPopUp.overlay.render();

}

YAHOO.mapPopUp.showMap = function() {
    modalBackdrop.show();
    setTimeout('YAHOO.mapPopUp.overlay.show()', 100);
    YUE.addListener(document.getElementById("modalDialog"), 'click', function() {
        YAHOO.mapPopUp.hideMap();
    })
}

YAHOO.mapPopUp.hideMap = function() {
    YAHOO.mapPopUp.overlay.hide();
    setTimeout('modalBackdrop.hide()', 100);
}

YUE.addListener(window, 'load', YAHOO.mapPopUp.init);




//////////////////////////////////////////////////////////////////////////////////////
//////////    INVENTORY HOME LISTING PAGE (ReadyHome.ascx)          //////////////////
//////////////////////////////////////////////////////////////////////////////////////


function ShowIHContactForm(formDivId, message) {
    s.tl("true", "o", "InventoryHomes_Request_Info");
    html = "<div id='formWrapperSJ'>" +
    	"<div class='request_more_info_form_wrapper'>" +
    		"<form name='LandingSignUpForm' id='LandingSignUpForm' action='' onsubmit='return false'>" +
        		"<div class=alertBar hide> <div class='alertHdr'></div> <div class='alertBdy' id='landingFormError'></div><div class='alertFtr'></div></div>" +
				"<a href='javascript:rh_CloseAllForms();' class='close_request_more_info' >X Close</a>" +
				"<div class='request_more_info_form_wrapper'>" +
					"<p class='comm_request_instructions'>Fill out this short form and one of our experts will be in touch to answer any questions you may have.</p>" +
					"<label for='landingFirstName'>First Name<input type='text' name='landingFirstName' value='' id='landingFirstName' tabindex='21' /></label>" +
					"<label for='landingLastName'>Last Name<input type='text' name='landingLastName' value='' id='landingLastName' tabindex='22' /></label>" +
					"<label for='landingState'>State of Residence" +
						"<select tabindex='23' id='landingState' name='landingState'><option value=''>Select</option><option value='AA'>AA (military)</option><option value='AE'>AE (military)</option>" +
							"<option value='AP'>AP (military)</option><option value='AL'>Alabama</option><option value='AK'>Alaska</option><option value='AZ'>Arizona</option><option value='AR'>Arkansas</option>" +
							"<option value='CA'>California</option><option value='CO'>Colorado</option><option value='CT'>Connecticut</option><option value='DE'>Delaware</option><option value='DC'>District of Columbia</option>" +
							"<option value='FL'>Florida</option><option value='GA'>Georgia</option><option value='HI'>Hawaii</option><option value='ID'>Idaho</option><option value='IL'>Illinois</option><option value='IN'>Indiana</option>" +
							"<option value='IA'>Iowa</option><option value='KS'>Kansas</option><option value='KY'>Kentucky</option><option value='LA'>Louisiana</option><option value='ME'>Maine</option><option value='MD'>Maryland</option>" +
							"<option value='MA'>Massachusetts</option><option value='MI'>Michigan</option><option value='MN'>Minnesota</option><option value='MS'>Mississippi</option><option value='MO'>Missouri</option>" +
							"<option value='MT'>Montana</option><option value='NE'>Nebraska</option><option value='NV'>Nevada</option><option value='NH'>New Hampshire</option><option value='NJ'>New Jersey</option><option value='NM'>New Mexico</option>" +
							"<option value='NY'>New York</option><option value='NC'>North Carolina</option><option value='ND'>North Dakota</option><option value='OH'>Ohio</option><option value='OK'>Oklahoma</option>" +
	    					"<option value='OR'>Oregon</option><option value='PA'>Pennsylvania</option><option value='RI'>Rhode Island</option><option value='SC'>South Carolina</option><option value='SD'>South Dakota</option>" +
	    					"<option value='TN'>Tennessee</option><option value='TX'>Texas</option><option value='UT'>Utah</option><option value='VT'>Vermont</option><option value='VA'>Virginia</option><option value='WA'>Washington</option>" +
							"<option value='WV'>West Virginia</option><option value='WI'>Wisconsin</option><option value='WY'>Wyoming</option></select>" +
					"</label>" +
					"<label for='landingEmail'>Email Address<input type='text' name='landingEmail' value='' id='landingEmail' tabindex='24' /></label>" +
					"<div class='international hide'><label for='landingCountry'>Country<em>*</em></label>" +
        			"<select id='landingCountry' class='countryOptions' tabindex='3'></select></div>" +
					"<div id='submitLandingSignUp'><input type='image' tabindex='25' id='landingSubmit' alt='Send' class='submit' src='/images/" + getCurrSite() + "/button-submit2.gif' /></div><div class='clear'></div>" +
					"<input type='hidden' id='landingComID' name='landingComID' value='' /><input type='hidden' id='message' name='message' value='' />" +
				"</div><!--request_more_info_form_wrapper--><div class='clear'></div><!--clear-->" +
			"</form>" +
		"</div><!--request_more_info_form_wrapper--><div class='clear'></div><!--clear-->" +
	"</div><!--formWrapperSJ-->" +
	"<div class='thankyouWrapper hide' id='thankyouSJ'><h3>" + window.rh_ThankYou + "</h3></div>";

    if (document.getElementById(formDivId) != null) {
        rh_CloseAllForms();
        formDiv = document.getElementById(formDivId);
        formDiv.innerHTML = html;

        if (document.LandingSignUpForm.landingComID) {
            //alert(formDivId.substr(formDivId.indexOf("_") + 1));
            document.LandingSignUpForm.landingComID.value = formDivId.substr(formDivId.indexOf("_") + 1);
        }
        // display previously submitted information (window variables got values in global.js submitSignUp function)
        document.LandingSignUpForm.landingFirstName.value = window.rh_fName;
        document.LandingSignUpForm.landingLastName.value = window.rh_lName;
        document.LandingSignUpForm.landingEmail.value = window.rh_email;
        document.LandingSignUpForm.landingState.value = window.rh_state;

        // make the form visible
        formDiv.style.display = "block";
        CommunitySignUp.initialize();
    }
}

