// ----------------------------------------------------------------------------------------------
// ------------------------------- 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;

	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;
	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 serviceRequest = document.contact.serviceRequest;
	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.value, isBroker.checked, brokerOfficeValue, taxIDValue,
	serviceRequest.checked, 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) {
		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') _hbPageView('ContactUs-NeighborhoodInfo-ThankYou','/form_conversion'); // hbx conversion tracking
	
	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
	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 {
		
		// 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 = "";
  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;
}

// ----------------------------------------------------------------------------------------------