﻿window.onerror=winerror;
function winerror(sMessage,sUrl,sLine) {try {window.status="L:"+sLine+"|M:"+sMessage+"|URL:"+sUrl;} catch(e) {}var currentURL=document.location.href.toLowerCase();if (currentURL.indexOf("www.me.") > 0) {rState=false;} else {rState=true;}return rState;}
//-- BKV
var media="";var keyword="";var lander="";var tg="";var misc="";var pos;var endpos;
var url = location.href.toLowerCase();
pos = url.indexOf("media=");
if (pos>0) {endpos=url.indexOf("&", pos);if (endpos<0) {media=url.substring(pos+6);} else {media=url.substring(pos+6,endpos);}}
pos = url.indexOf("keyword=");
if (pos>0) {endpos=url.indexOf("&", pos);if (endpos<0) {keyword=url.substring(pos+8);} else {keyword=url.substring(pos+8,endpos);}}
pos = url.indexOf("tg=");
if (pos>0) {endpos=url.indexOf("&", pos);if (endpos<0) {tg=url.substring(pos+3);} else {tg=url.substring(pos+3,endpos);}}
pos = url.indexOf("lander=");
if (pos>0) {endpos=url.indexOf("&", pos);if (endpos<0) {lander=url.substring(pos+7);} else {lander=url.substring(pos+7,endpos);}}
pos = url.indexOf("misc=");
if (pos>0) {endpos=url.indexOf("&", pos);if (endpos<0) {misc=url.substring(pos+5);} else {misc=url.substring(pos+5,endpos);}}

function pageLoad() {
    try {scLite();} catch(e) {}
    try {scHorizontal();} catch(e) {}
    //try {onResizeTasks();} catch(e) {}
    try {loadLeadForm();} catch(e) {}
    try {attachContentEvents();} catch(e) {}
    try { initializeGoogleMap(); } catch (e) { }
    try { loadSearchResultsMap(); } catch (e) { }
    try {if (photos != null) {loadPhotoViewer();}} catch(e) {}
    analytics();
}
function analytics() {
	try {
		var allowAnalytics = true;
		var currentURL = document.location.href.toLowerCase();
		//if (currentURL.indexOf("www.me.") > 0) {allowAnalytics = false;} 
		if (allowAnalytics) {
			//try {headerLoadScript("http://www.google-analytics.com/urchin.js");headerLoadScriptString("_uacct = \"UA-461438-1\";urchinTracker();");} catch(e) {}
			try {if (crazyEgg == "true") {headerLoadScript("http://cetrk.com/pages/scripts/0009/7901.js");}} catch(e) {}
			try {if (pm_tagversion != "") {bodyLoadScript("http://srv.perf.overture.com/collweb/ScriptServlet?" + "ver=" + pm_tagversion + "&aid=ROTJACM8FKEI0M2B78CVG78KJ4&" + pm_customargs);}} catch(e) {}
			try {bkv();} catch(e) {}
			try {if (pageATDMT != "") {switchATDMT(pageATDMT);}} catch(e) {}
			try {if (mediaPlexAds != "") {loadMediaPlexByScript();}} catch(e) {}
		}
	} catch(e) {}
}
function loadPhotoViewer() {
    var pArray = photos.split("|");
    document.getElementById("PhotoViewer").src = pArray[0];
    var thumbs = "";
    for (x = 0; x < pArray.length; x++) {
        if (pArray[x].length > 1) {
            thumbs += "<img src=\""+pArray[x]+"\" class=\"photothumbs\" onmouseover=\"this.style.cursor='pointer';\" onclick=\"loadPreview('"+pArray[x]+"');\" onerror=\"this.src='/images/nhg_plan_nophoto.jpg';\"/>";
        }
    }
    document.getElementById("PhotoViewerThumbs").innerHTML = "<nobr>"+thumbs+"</nobr>";
}
function loadPreview(sImg) {document.getElementById("PhotoViewer").src = sImg;}
function scrollThumbs(sDir) {
    if (sDir == "LEFT") {
        $("#PhotoViewerThumbs").animate({ "scrollLeft": "-=69px" }, "slow");
        //document.getElementById("PhotoViewerThumbs").scrollLeft -= 69;
    } else {
        $("#PhotoViewerThumbs").animate({ "scrollLeft": "+=69px" }, "slow");
        //document.getElementById("PhotoViewerThumbs").scrollLeft += 69;
    } 
}


function enableControl(id, enable){
    var element = document.getElementById(id);
    var parent = (element.parentNode)? element.parentNode: element.parentElement;
    if(enable == false) {parent.disabled = enable;element.disabled = enable;} else {element.disabled = enable;}
    return false;
}
function javaNav( href ) {window.location.href = href;}
function PhotoNotAvail(obj, imageSrc) {obj.src = imageSrc;}
function handlephoto(obj, imagePath, elevationwithdelimiter, defaultphotourl){
    //Split the Elevation images..
    var RawElevation = elevationwithdelimiter.split("|");
    var ArrElevation = new Array();
    var ArrCtr=0;
    for (i=0; i<RawElevation.length; i++) {if (RawElevation[i].indexOf('/') > -1) {ArrElevation[ArrCtr++]= RawElevation[i];}}
    if (ArrElevation.length == 0) {obj.src = defaultphotourl;return;}
    for( i=0; i<ArrElevation.length; i++ )
    {
        if( obj.src == imagePath + ArrElevation[i] ) //Match errored image
        {
            //If there is next elevation available, assign that to src
            if( i+1 < ArrElevation.length )
            {
                obj.src = imagePath + ArrElevation[i + 1];
                return;
             }
             else //All elevations failed, assign no photo avail
             {
                obj.src = defaultphotourl;
                return;
             }
        }
      }
      //No elevations attempted yet, assign first elevation
      obj.src =   imagePath + ArrElevation[0];
}

function SetFocusToFirstControl() {}
// force IE not to shrink the container smaller then minwidth when body is shrinks beyond body minwidth
function IEMinWidth( elId, iMinElWidth, iMinBodyWidth ){
    try{
        var el = document.getElementById(elId);
        var bBigEnough = ( document.body.offsetWidth > iMinBodyWidth );
        el.style.width = ( bBigEnough ) ? "auto" : iMinElWidth;
    }catch(e){}
    return;
}
// append Hover to className onmouseover
function styleHover( el ){
    // persist classNames
    el.baseClassName = el.className;
    el.hoverClassName = el.className + "Hover";
    // attach to mouse over/out events, assign classNames
    el.onmouseover = function(){ this.className = this.hoverClassName; };
    el.onmouseout = function(){ this.className = this.baseClassName; };
    return;
}
// returns domain of browser url
function getThisDomain() {return window.location.href.substr(0, window.location.href.indexOf("/",8));}
// returns page path portion of browser url
function getThisPath() {return window.location.href.substr(window.location.href.indexOf("/",8));}
// returns false if the url points outside the domain of the browser 
function isThisDomain(sUrl){
    if(!/^http:\/\//i.test(sUrl)) return true;
    var domain = getThisDomain().toLowerCase();
    return sUrl.toLowerCase().substr(0,domain.length) == domain;
}
// finds all external links and attaches call back url to onclick
function clickTrackBacks(handlerUrl){
    var anchors = document.getElementsByTagName( "A" );
    var page = escape(getThisPath());
    for( var i=0; i<anchors.length;i++){
        var href = anchors[i].href;
        if(!isThisDomain(href)){
            anchors[i].onclick = function(){
                var sUrl=handlerUrl;
                sUrl+=(sUrl.indexOf("?")>-1)?"&":"?";
                sUrl+="clickTrackPage="+page;
                if(this.id)sUrl+="&linkid="+this.id;
                if(this.name)sUrl+="&linkname="+this.name;
                sUrl+="&targetUrl="+escape(this.href);
                var oImg = new Image();
                oImg.src = sUrl;
                return true;
            }  
        }
    }
}
// makes an element region clickable, navigating to the specified anchor's url, and styles onmouseover
function makeClickRegion( el, iAnchorIdx, bDontCaptureImageClicks )
{
    // make sure link is present
    if( el.getElementsByTagName( "A" ).length <= iAnchorIdx ) return;
    // assign target anchor element
    el.childHref = el.getElementsByTagName( "A" )[iAnchorIdx];
    // assign flag to suppress bubbling image clicks
    el.bNoCatchImgClk = bDontCaptureImageClicks;
    // assign nav action
    el.navAction = function() {if( this.childHref.onclick ) this.childHref.onclick();javaNav( this.childHref.href );};
    el.style.cursor = "pointer";
    // attach to click
    el.onclick = function(e){ 
        // event source element
        var elSrc = null;
        // if e is empty we're IE              
        if (!e){
            var e = window.event;
            elSrc = e.srcElement;
        }
        else
        {
            elSrc = e.target; 
        }
        // navigate if el was not a or img
        if( elSrc.tagName != "A" && !( elSrc.tagName == "IMG" && this.bNoCatchImgClk ) ){
            this.navAction();
        }; 
        // return for event bubble
        return true;
    };
    // style mouse over
    styleHover( el );
    return;
}   
// apply alternating style and clickable row
function styleResultsTable( tableId, iTargetLinkIdx ){
    // get the table
    var table = document.getElementById( tableId );
    if(!table) return;
    // see if a tbody is defined
    var tbody = table.getElementsByTagName( "TBODY" );
    // use the tbody (should only be one match) or table to get rows
    var rows = ( tbody.length > 0 ) ? tbody[0].rows : table.rows;
    // loop through rows, applying style and events
    var iAltCnt = 0;
    for( var iR=0; iR < rows.length; iR++){
        iAltCnt++;
       
        var row = rows[iR];
        // assign the row classname
        row.className = table.className + "Row";
        //increment every two
        if(iAltCnt > 2) {
            // assign the alt classname every other pair of rows
            row.className = row.className + "Alt";
            if(iAltCnt == 4) iAltCnt = 0;
        }
        // make the whole row clickable according to indicated link
        makeClickRegion( row, iTargetLinkIdx, true );
    }
}
// extend anchor href to container
function bubbleHref(containerId) {try {var el = document.getElementById(containerId);makeClickRegion(el, 0);} catch(e) {}return;}
// insert breaks to convert horizontal text to vertical text
function verticalText( el ){
    el.style.align = "center";
    el.style.color="#E5EEF5";
    el.style.fontFamily="arial";
    var sTxt = el.innerHTML;
    var sTxt2 = '';
    for(var iC=0;iC<sTxt.length;iC++) sTxt2+="" +sTxt.substr(iC,1)+"<br/>";
    el.innerHTML = sTxt2;
}
function verticalTextById(sElId) {verticalText( document.getElementById( sElId ) );}
function maxImage(img, width, height){
     //copy to new image so it will work in ie
    var newImg = new Image();
    newImg.src = img.src;
    var iWidth = newImg.width;
    var iHeight = newImg.height;
    var bAdjHeight = false;
    if (height != null)
    {
        if( iHeight > height ){
            var iRatio =  iHeight / height;
            img.height = height;
            img.width = iWidth / iRatio;
            bAdjHeight = true;
        }
        
        if (( iWidth >= width ) && (!bAdjHeight)){
            var iRatio =  iWidth / width;
            img.width = width;
            img.height = iHeight / iRatio;
        }        
    }
    else
    {
        if ( iWidth > width ){
            var iRatio =  iWidth / width;
            img.width = width;
            img.height = iHeight / iRatio;
        }
    }
}
function photoNotFound(oImgEl, iWidth, iHeight, sPath) {oImgEl.onerror = null;if(iWidth!=null && iHeight!=null) {oImgEl.style.width = iWidth;oImgEl.style.height = iHeight;oImgEl.width=iWidth;oImgEl.height=iHeight;}oImgEl.src = sPath + "images/image-not-set.jpg";}
// assigns image load "onerror" to images in container matching classname
function assignImgOnErrChilren(sCntrElId, sTargetImgClassName, iWidth, iHeight, sPath)
{
    if (document.getElementById(sCntrElId))
    {
        var arImages = document.getElementById(sCntrElId).getElementsByTagName("IMG");
        for(var i=0;i<arImages.length;i++)
        {
            if( arImages[i].className==sTargetImgClassName )
                arImages[i].onerror = function(){ photoNotFound(this, iWidth, iHeight, sPath) }; 
        }
    }
}
// standard drop down validation
function validateDD(sElId, args) {var dd = document.getElementById(sElId);args.IsValid = dropDownIsValid(dd);return;}
function dropDownIsValid(el) {var iDdIdValue = getDdIdVal(el);return (iDdIdValue > 0);}
function getDdIdVal(el) {return parseInt(el.options[el.selectedIndex].value,10);}
//Cross browser supported Add Event and Detach Event handler code
function addEvent(obj, evType, fn, useCapture) {if (obj.addEventListener) {obj.addEventListener(evType, fn, useCapture);return true;} else if (obj.attachEvent) {var r = obj.attachEvent("on"+evType, fn);return r;} else {alert("Handler could not be attached");}} 
function removeEvent(obj, evType, fn, useCapture) {if (obj.removeEventListener) {obj.removeEventListener(evType, fn, useCapture);return true;} else if (obj.detachEvent) {var r = obj.detachEvent("on"+evType, fn);return r;} else {alert("Handler could not be removed");}} 
//This function will allow clients to add new OnLoad events to the current window and guarantees that existing function calls will not be lost.
function addLoadEvent(func) {var oldonload = window.onload;if (typeof window.onload != 'function') {window.onload = func;} else {window.onload = function() {if (oldonload) {oldonload();}func();}}}
//Same thing as the addLoadEvent, but fires when the page is unloaded.
function addUnloadEvent(func) {var oldonunload = window.onunload;if (typeof window.onunload != 'function') {window.onunload = func;} else {window.onunload = function() {if (oldonunload) {oldonunload();}func();}}}
// Simple alert function for Funtionality not implented
function notImplemented(functionality){if (functionality == '') {functionality = 'This functionality';}alert(functionality+' is not available yet.');}
// Return the absolute X and Y coordinates of the document object.
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {curleft += obj.offsetLeft;curtop += obj.offsetTop;}
	}
	return [curleft,curtop];
}
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters) && (version < 7.0)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if ((imgName.substring(imgName.length-3, imgName.length) == "PNG") && img.plsclean)
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            var imgOnClick = (img.onclickAction) ? "onclick=\"" + img.onclickAction +"\" ": "";
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href || img.onclickAction || img.onclick) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle + imgOnClick
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}
function formatPhoneExt( e, obj ) {
	if(e.keyCode == 9) {return;}
	var validchars = '0123456789';
	p = obj.value;
	for (var i = p.length; i >= 0; i--) {if (validchars.indexOf(p.charAt(i)) == -1) {p = p.replace(p.charAt(i),'');}}
	var isValid = true;
	for (var i=0; i< p.length; i++) {if (validchars.indexOf(p.charAt(i)) == -1) {isValid = false;}}
	if ( ! isValid ) {p = p.substring(0,p.length - 1 );}
	obj.value = p;
}
function formatPhone( e, obj ) {
	if (e.keyCode == 9){return;}
	var validchars = '0123456789'; // define valid characters
	p = obj.value;
	for (var i = p.length; i >= 0; i--) {if (validchars.indexOf(p.charAt(i)) == -1) {p = p.replace(p.charAt(i),'');}}
	if ( p.length > 1 && p.charAt(0) != "(" ) {p = "(" + p;}
	if ( p.length > 4 && p.charAt(4) != ")" ) {p = p.substring(0,4) + ") " + p.substring(4);}
	if ( p.length > 5 && p.charAt(5) != " " ) {p = p.substring(0,5) + " " + p.substring(5);}
	if ( p.length > 9 && p.charAt(9) != "-" ) {p = p.substring(0,9) + "-" + p.substring(9);}
	for (var xPos=0; xPos < p.length; xPos++) {if ((p.charAt(xPos) == "-") && (xPos != 9)) {p = p.substring(0,p.length - 1 );}}
	if (p.length > 14) {p = p.substring(0,14);}
	obj.value = p;
}
function LogoNotAvail(obj) {document.getElementById(obj.id).style.display = "none";}
function CreateBookmarkLink(title,url) {
    title = title + " builder discounts";
    if (window.sidebar) { // Mozilla Firefox Bookmark
        window.sidebar.addPanel(title, url,"")
    } 
    else if(window.external) { // IE Favorite
        window.external.AddFavorite(url,title)
    }
    else if(window.opera && window.print) { // Opera Hotlist
        return true;
    }
    return false;
}
function loadSearchResultsMap () {
	var divMetroMap = document.getElementById('divMetroMap');
	if (divMetroMap == null) {
		return;
	} else {
		if (document.getElementById('frmMapClientID') != null) { document.getElementById (document.getElementById('frmMapClientID').value).src = document.getElementById ('mapurl').value; }
	}
}
function scrollMap(sMapDiv, minTop) {
	var oDiv=document.getElementById(sMapDiv);
	var sTop=0;
	var attachTo = document.getElementById("mapAnchorHere");
	var sLeft = findObjectOffset(attachTo, "left");
	if(document.all){
		if (document.documentElement) { sTop=document.documentElement.scrollTop; } else { sTop=document.body.scrollTop; }
	} else {
		sTop=window.pageYOffset;
	}
	if (sTop>minTop) {oDiv.style.top=sTop+"px";}
	oDiv.style.left=sLeft+"px";
}
function onResizeTasks() { try {$(window).resize(function(){scrollMap('divMetroMap',90);});} catch(e) {} }
function mortgagePopup(anchorObjId) {
	var popup = document.getElementById("mortagePopupDiv");
	if (popup.style.display == "") {
		popup.style.display = "none";
	} else {
		var anchorObj = document.getElementById(anchorObjId);
		popup.style.top = (findObjectOffset(anchorObj,"top") - 350) + "px";
		popup.style.left = (findObjectOffset(anchorObj,"left") - 130) + "px";
		popup.style.display = "";
	}
}
function mortgagePopupHide() {document.getElementById("mortagePopupDiv").style.display = "none";}
function videoPopup(videoUrl) {
	//-- video size 620X400
	window.open(videoUrl, null,"menubar=no,resizable=yes,status=no,scrollbars=no,toolbar=no,width=620,height=400");
}
function togglePreview(sLargeImgId, sourceObj) {
	var bigImg = document.getElementById(sLargeImgId);
	var pageWidth = document.body.clientWidth;
	var leftOffset = (pageWidth / 2) - 450;
	//bigImg.src = sourceObj.src + "&source=1";
	bigImg.src = sourceObj.src;
	bigImg.style.top = "143px";
	bigImg.style.left = leftOffset+"px";
	bigImg.style.width = "auto";
	bigImg.style.height = "auto";
	bigImg.style.minWidth = "550px";
	bigImg.style.minHeight = "400px";
	bigImg.style.display = "";
}
function switchATDMT(sParam) {bodyLoadImg("http://switch.atdmt.com"+sParam)}
function bkv() {
	var pageName = "";
	var vPath = "";
	var vPathItems;
	var qStr = "";
	var fullURL = document.URL;
	fullURL = fullURL.substring(fullURL.indexOf(".com")+4);
	if (fullURL.startsWith("/")) {fullURL = fullURL.substring(1);}
	if (fullURL.indexOf("?")>0) {qStr = fullURL.substring(fullURL.indexOf("?")+1); fullURL = fullURL.substring(0,fullURL.indexOf("?"));}
	if (fullURL.indexOf("/")==-1) {
		pageName = fullURL;
	} else {
		vPathItems = fullURL.split("/");
		pageName = vPathItems[vPathItems.length-1];
		for (var x = 0; x < vPathItems.length -1; x++) {vPath += vPathItems[x]+"/";}
	}
	if (fullURL == "") {
		var e=document.createElement("img");e.src="http://view.atdmt.com/action/bvknhg_homepage_1";e.alt="BKV";document.getElementsByTagName("body")[0].appendChild(e);
	}
	else if (pageName.toLowerCase() == "communitylist.aspx" || pageName.toLowerCase() == "planlist.aspx" || pageName.toLowerCase() == "builderlist.aspx") {
		var e=document.createElement("script");e.src="http://view.atdmt.com/jaction/bvknhg_SearchResultsPage_1";e.language="JavaScript";document.getElementsByTagName("body")[0].appendChild(e);
		var e=document.createElement("iframe");e.src="http://view.atdmt.com/iaction/bvknhg_SearchResultsPage_1";e.width="0";e.height="0";e.frameBorder="0";e.scrolling="No";document.getElementsByTagName("body")[0].appendChild(e);
	}
	else if (pageName.toLowerCase() == "communitydetail.aspx" || pageName.toLowerCase() == "plandetail.aspx" || pageName.toLowerCase() == "inventorydetail.aspx" || pageName.toLowerCase() == "builderdetail.aspx") {
		var e=document.createElement("script");e.src="http://view.atdmt.com/jaction/bvknhg_"+pageName.substring(0,pageName.length-5)+"Page_1";e.language="JavaScript";document.getElementsByTagName("body")[0].appendChild(e);
		var e=document.createElement("iframe");e.src="http://view.atdmt.com/iaction/bvknhg_"+pageName.substring(0,pageName.length-5)+"Page_1";e.width="0";e.height="0";e.frameBorder="0";e.scrolling="No";document.getElementsByTagName("body")[0].appendChild(e);
	}
	else if (vPath != "") {
	if (vPathItems.length == 4 && vPathItems[0].toLowerCase() == "new-homes") {
			if (vPathItems[2].toLowerCase().indexOf("-area") > 0) {
			    var metro = "";
			    if (document.getElementById ("hdSEOMetroName") != null)
			        metro = document.getElementById("hdSEOMetroName").value;
			    else
			        metro = vPathItems[2];
			    var e = document.createElement("script"); e.src = "http://view.atdmt.com/jaction/bvknhg_" + (metro.replace(/ /ig, "").replace(".", "").replace(/,/ig, "").replace(/_/ig, "").replace(/-areas/ig, "").replace(/-area/ig, "").replace(/-/g, "").replace(/\+/g, "")) + "Market_1"; e.language = "JavaScript"; document.getElementsByTagName("body")[0].appendChild(e);
			    var e = document.createElement("iframe"); e.src = "http://view.atdmt.com/iaction/bvknhg_" + (metro.replace(/ /ig, "").replace(".", "").replace(/,/ig, "").replace(/_/ig, "").replace(/-areas/ig, "").replace(/-area/ig, "").replace(/-/g, "").replace(/\+/g, "")) + "Market_1"; e.width = "0"; e.height = "0"; e.frameBorder = "0"; e.scrolling = "No"; document.getElementsByTagName("body")[0].appendChild(e);
			}
			else
			{
				var e=document.createElement("script");e.src="http://view.atdmt.com/jaction/bvknhg_SearchResultsPage_1";e.language="JavaScript";document.getElementsByTagName("body")[0].appendChild(e);
				var e=document.createElement("iframe");e.src="http://view.atdmt.com/iaction/bvknhg_SearchResultsPage_1";e.width="0";e.height="0";e.frameBorder="0";e.scrolling="No";document.getElementsByTagName("body")[0].appendChild(e);
			}
		}
		if (vPathItems.length == 5 && vPathItems[0].toLowerCase() == "new-homes") {
			var e=document.createElement("script");e.src="http://view.atdmt.com/jaction/bvknhg_DetailsPage_1";e.language="JavaScript";document.getElementsByTagName("body")[0].appendChild(e);
			var e=document.createElement("iframe");e.src="http://view.atdmt.com/iaction/bvknhg_DetailsPage_1";e.width="0";e.height="0";e.frameBorder="0";e.scrolling="No";document.getElementsByTagName("body")[0].appendChild(e);
		}
	}
	else {
		try {bkvOLD();} catch(e) { }
	}
	//alert("fullURL:"+fullURL+"\npageName:"+pageName+"\nvPath:"+vPath+"\nvPathItems:"+vPathItems+"\nqStr:"+qStr+"\n");
}
function bkvOLD() {
    var bkvStr = "server2.bkvtrack.com/spotlightEntry.jsp?url="+escape(document.URL)+"&referrer="+escape(document.referrer)+"&spotlightID=1090&pageN="+pageName+"&seQ="+sq+"&s5="+misc+"&s1="+media+"&s2="+keyword+"&s3="+lander+"&s4="+tg;
    if (document.location.href.substring(0,5).toLowerCase() == "https") {bodyLoadImg("https://"+bkvStr);} else {bodyLoadImg("http://"+bkvStr);}
}
function loadMediaPlexByScript() {
    if (mediaPlexAds.endsWith("||")) { mediaPlexAds = mediaPlexAds.substring(0, mediaPlexAds.Length - 2); }
	var ads = mediaPlexAds.split("||");
	for (x = 0; x <= ads.length; x++) {
		var ad = ads[x].split("|");
		document.getElementById("mediaplex"+ad[0]).src=ad[1].replace("{POS#}",ad[0]).replace("Category=","Category=0"+ad[0]);
	}
}
function findObjectOffset(obj, sDirection) {
	//-- PARAM:[obj] DOM object reference; PARAM:[sDirection] top,left
	var sReturn = "";var curleft = 0;var curtop = 0;
	try {
		if (obj.offsetParent) {
			curleft = obj.offsetLeft;curtop = obj.offsetTop;
			while (obj = obj.offsetParent) {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			}
		}
		if (sDirection == "left") {sReturn = curleft;} else {sReturn = curtop;}
	} catch(e) {sReturn = 0;}
	return sReturn;
}
function postLeadForm(bOverride) {
    var sPKey = "";
    if ($("#contactBoxPopup").css("display") != null) { if ($("#contactBoxPopup").css("display") != "none") { sPKey = "P"; } }
    var sFirstName = $("#txtQuickLeadFirstName" + sPKey).val().trim();
    var sLastName = $("#txtQuickLeadLastName" + sPKey).val().trim();
    var sEmail = $("#txtQuickLeadEmail" + sPKey).val().trim();
    var sPhone = $("#txtQuickLeadPhone" + sPKey).val().trim();
    var sZipCode = $("#txtQuickLeadZip" + sPKey).val().trim();
    //var sComments = $("#txtQuickLeadComments" + sPKey).val().trim();
    var sComments = "";
    var iEntityType = $("#hdQuickLeadEntityType" + sPKey).val();
    var iEntityID = $("#hdQuickLeadEntityID" + sPKey).val();
    var sDataSource = $("#hdQuickLeadDataSource" + sPKey).val();
    var iEndecaID = $("#hdQuickLeadEndecaID" + sPKey).val();
    var iEndecaType = $("#hdQuickLeadEndecaType" + sPKey).val();
    var sMarketCD = $("#hdQuickLeadMarketCode" + sPKey).val();
    var sLeadTypeClientID = $("#hdLeadTypeClientID" + sPKey).val();
    var iLeadType = $("#ddlLeadType" + sPKey).val();
    var sLeadType = "Unknown";
    switch (iLeadType)
    {
        case "1":     sLeadType = "EmailBuilder";
                    break;
                 
        case "2":     sLeadType = "RequestAppointment";
                    break;
                 
        case "3":     sLeadType = "RequestBrochure";
                    break;
                 
        case "4":     sLeadType = "PrintBrochure";
                    break;
                 
        case "5":     sLeadType = "RapidRequest";
                    break;
	    
	    default:    sLeadType = "Undefined";
	                break;          
    }
    var iOptIn = $("#cbOptIn" + sPKey).attr("checked") ? 1 : 0;
    var iOptInSimilar = 0;
    if ($("#cbOptInSimilar" + sPKey) != null) {
        iOptInSimilar = $("#cbOptInSimilar" + sPKey).attr("checked") ? 1 : 0;
	}
	// These are needed for the WebTrends logging
	var sState = $("#hdQuickLeadStateName" + sPKey).val();
	var sMetro = $("#hdQuickLeadMetroName" + sPKey).val()
	var sPageName = $("#hdQuickLeadPageName" + sPKey).val();
	var sSynd = $("#hdQuickLeadSyndID" + sPKey).val();
	// There must be a first and last name + either a valid phone number or email address
	var divQuickLeadInputError = $("#divQuickLeadInputError" + sPKey);
	if ((sFirstName == "") || (sLastName == "") || ((sEmail == "") && (sPhone == "")))
    {
        divQuickLeadInputError.html("First name, Last name, and either Email or Phone are required");
        divQuickLeadInputError.slideDown("fast");
        return;
    }
    if ((sPhone.length != 0) && (sPhone.length != 14))
    {
        divQuickLeadInputError.html("Invalid phone number");
        divQuickLeadInputError.slideDown("fast");
        return;
    }
    if ((sEmail != "") && (sEmail.search (/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/) == -1))
    {
        divQuickLeadInputError.html("Invalid email address");
        divQuickLeadInputError.slideDown("fast");
        return;
    }
    if ((sZipCode.length == 0) || (sZipCode.length != 5))
    {
        divQuickLeadInputError.html("Invalid Zip Code");
        divQuickLeadInputError.slideDown("fast");
        return;
    }
    // Save the user settings to a cookie
    try {
		var sCookie = "QuickLeadData=" + sFirstName + "|" + sLastName + "|" + sEmail + "|" + sPhone + "|" + sComments + "|" + iOptIn + "|" + iLeadType + "|" + sZipCode;
		var date = new Date();date.setTime (date.getTime()+(365*24*60*60*1000));sCookie += ";expires=" + date.toGMTString();document.cookie = sCookie;
	} catch(e) {}
    // Submit Webtrends logging
	try { dcsMultiTrackCall(sPageName, sSynd, sLeadType, 1, sState, sMetro); } catch (e) { }
	// Submit the Lead
	var sQ = "sFirstName=" + sFirstName + "&sLastName=" + sLastName + "&sEmail=" + sEmail + "&sPhone=" + sPhone + "&sZipCode=" + sZipCode + "&iEntityType=" + iEntityType + "&iEntityID=" + iEntityID + "&sDataSource=" + sDataSource + "&iEndecaID=" + iEndecaID + "&iEndecaType=" + iEndecaType + "&sMarketCD=" + sMarketCD + "&iLeadType=" + iLeadType + "&iOptIn=" + iOptIn + "&iOptInSimilar=" + iOptInSimilar + "&sComments=" + sComments;
    if (window.XMLHttpRequest) { var request = new XMLHttpRequest(); } else { var request = new ActiveXObject("MSXML2.XMLHTTP.3.0"); }
	request.open("GET", "/submitLead.aspx?"+sQ+"&"+window.location.search.substring(1), false);
	request.setRequestHeader("Content-Type", "text/plain");
	request.send(null);
	var sResponse = request.responseText;
	if (sResponse != "true") {
	    $("#divQuickLeadError" + sPKey).slideDown("fast");
    } else if (bOverride) {
        $("#divQuickLeadThankYou" + sPKey).slideDown("fast");
        var e = document.createElement("img"); e.src = "http://view.atdmt.com/action/bvknhg_thankyoupage_3"; e.alt = "BKV"; document.getElementsByTagName("body")[0].appendChild(e);
        var e2 = document.createElement("img"); e2.src = "https://roi.trafficdashboard.com/pixel/?c_id=2750&fill_type=catalog&action="; e2.alt = "Marchex"; document.getElementsByTagName("body")[0].appendChild(e2);
    } else {
		if (iOptInSimilar == 0) 
		{
		    var sQS = "";
		    switch (iEntityType)
		    {
		        case "1":   // Builder
		                    sQS = "srch=bid_3_" + iEntityID; 
		                    break;
		         
		        case "2":   // Community
		                    sQS = "srch=cid_3_" + iEntityID;
		                    break;
		                
		        case "4":   // Inventory
		                    sQS = "srch=eid_3_" + iEndecaID;
		                    break;
		                
		        case "5":   // Plan
		                    sQS = "srch=pid_3_" + iEntityID;
		                    break;        
		    
		    }
			document.location.href = "/Leads/ThankYou.aspx?" + sQS;
		} else {
		    $("#divQuickLeadThankYou" + sPKey).slideDown("fast");
			var e=document.createElement("img");e.src="http://view.atdmt.com/action/bvknhg_thankyoupage_3";e.alt="BKV";document.getElementsByTagName("body")[0].appendChild(e);
            var e2 = document.createElement("img"); e2.src = "https://roi.trafficdashboard.com/pixel/?c_id=2750&fill_type=catalog&action="; e2.alt = "Marchex"; document.getElementsByTagName("body")[0].appendChild(e2);
		}
    }
}
function loadLeadForm() {
    // Read previous user values from cookie (if they are there) and pre-populate the form with these values;
    // QuickLeadData=FirstName|LastName|Email|Phone|Comments|OptIn|LeadType;
    var sCookies = document.cookie.split(';');
    for (var iCookie = 0; iCookie < sCookies.length; iCookie++)
    {
        var sCookie = sCookies[iCookie];
        if (sCookie.indexOf ("QuickLeadData=") > 0)
        {
            var sValues = sCookie.substring(sCookie.indexOf ("QuickLeadData=") + 14, sCookie.length).split('|');
            $("#txtQuickLeadFirstName").val(sValues[0]);
            $("#txtQuickLeadLastName").val(sValues[1]);
            $("#txtQuickLeadEmail").val(sValues[2]);        
            $("#txtQuickLeadPhone").val(sValues[3]);
            $("#txtQuickLeadComments").val(sValues[4]);
            var iOptIn = sValues[5];
            if (iOptIn == "0") {$("#cbOptIn").attr("checked", 0);}
            if (sValues.length >= 8) {$("#txtQuickLeadZip").val(sValues[7]);}
        }
    }
    document.getElementById("divQuickLeadThankYou").style.top = findObjectOffset(document.getElementById("sendEmailButton"),"top")+"px";
    document.getElementById("divQuickLeadThankYou").style.left = (findObjectOffset(document.getElementById("sendEmailButton"),"left")+220)+"px";
    document.getElementById("divQuickLeadError").style.top = findObjectOffset(document.getElementById("sendEmailButton"),"top")+"px";
    document.getElementById("divQuickLeadError").style.left = (findObjectOffset(document.getElementById("sendEmailButton"),"left")+220)+"px";
    document.getElementById("divQuickLeadInputError").style.top = findObjectOffset(document.getElementById("sendEmailButton"),"top")+"px";
    document.getElementById("divQuickLeadInputError").style.left = (findObjectOffset(document.getElementById("sendEmailButton"),"left")+220)+"px";
}
function toggleTR(sDivID, sCssDiv) {
    if ($("#" + sDivID).css("display") == "none") {
        $("#" + sDivID).css("display", ""); $("#" + sCssDiv).attr("class", "closedetails");
    } else {
        $("#" + sDivID).css("display", "none"); $("#" + sCssDiv).attr("class", "expanddetails");
    }
    try { leadDetailsPopupHide(); } catch (e) { }
}
function leadDetailsPopupHide() {
    var popForm = document.getElementById("contactBoxPopup");
    $(popForm).css("display", "none");
}
function leadDetailsPopup(sID, iEntityType, iEntityID, iEndecaID, iEndecaType, sDataSource, sMarketCode, sCommunityName, sPhone, sStateName, sMetroName) {
    var popForm = document.getElementById("contactBoxPopup");
    $(popForm).css("position", "absolute");
    $(popForm).css("display", "block");
    $(popForm).css("top", ($("#"+sID).offset().top - 260) + "px");
    $(popForm).css("left", ($("#" + sID).offset().left - 260) + "px");
    var sCookies = document.cookie.split(';');
    for (var iCookie = 0; iCookie < sCookies.length; iCookie++) {
        var sCookie = sCookies[iCookie];
        if (sCookie.indexOf("QuickLeadData=") > 0) {
            var sValues = sCookie.substring(sCookie.indexOf("QuickLeadData=") + 14, sCookie.length).split('|');
            $("#txtQuickLeadFirstNameP").val(sValues[0]);
            $("#txtQuickLeadLastNameP").val(sValues[1]);
            $("#txtQuickLeadEmailP").val(sValues[2]);
            $("#txtQuickLeadPhoneP").val(sValues[3]);
            $("#txtQuickLeadCommentsP").val(sValues[4]);
            var iOptIn = sValues[5];
            if (iOptIn == "0") { $("#cbOptInP").attr("checked", 0); }
            if (sValues.length >= 8) { $("#txtQuickLeadZipP").val(sValues[7]); }
        }
    }
    //$("#txtQuickLeadCommentsP").val().trim();
    $("#hdQuickLeadEntityTypeP").val(iEntityType);
    $("#hdQuickLeadEntityIDP").val(iEntityID);
    $("#hdQuickLeadEndecaIDP").val(iEndecaID);
    $("#hdQuickLeadEndecaTypeP").val(iEndecaType);
    $("#hdQuickLeadDataSourceP").val(sDataSource);
    $("#hdQuickLeadMarketCodeP").val(sMarketCode);
    $("#hdQuickLeadStateNameP").val(sStateName);
    $("#hdQuickLeadMetroNameP").val(sMetroName);
	var e=document.createElement("img");e.src="http://view.atdmt.com/action/bvknhg_FreeBrochureButton_1";e.alt="BKV";document.getElementsByTagName("body")[0].appendChild(e);
}
function bodyLoadImg(url) { var e = document.createElement("img"); e.src = url; e.alt = ""; document.getElementsByTagName("body")[0].appendChild(e); }
function bodyLoadScript(url) {var e=document.createElement("script");e.src=url;e.type="text/javascript";document.getElementsByTagName("body")[0].appendChild(e);}
function headerLoadScriptString(jsText) {var e=document.createElement("script");e.type="text/javascript";e.innerHTML=jsText;document.getElementsByTagName("head")[0].appendChild(e);}
function headerLoadScript(url) {var e=document.createElement("script");e.src=url;e.type="text/javascript";document.getElementsByTagName("head")[0].appendChild(e);}
function headerLoadCSS(url) {var e=document.createElement("link");e.href=url;e.type="text/css";e.rel="stylesheet";document.getElementsByTagName("head")[0].appendChild(e);}
String.decodeSpecialCharacters = function() {var str = arguments[0];return str.replace("&apos;", "'").replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">");}
String.prototype.endsWith = function(str) {return (this.match(str+"$")==str)}
String.prototype.startsWith = function(str) {return (this.match("^"+str)==str)}
String.prototype.trim = function(){return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))}

/* Functions and variables used for the scrolling Featured Community Banner */
var iCurrFeatComm = 0;
var FeatCommTimeout = null;

function InitFeatComm ()
{
    document.getElementById ("divFeatCom").style.display = "";
    RefreshFeatComm ();
    if (aFeatComNames.length > 1)
    {
        document.getElementById ("divFeatComControls").style.display = "";
        var hdFeatComScrollTime = document.getElementById ("hdFeatComScrollTime");
        if ((hdFeatComScrollTime != null) && (hdFeatComScrollTime.value != ""))
            FeatCommTimeout = setTimeout (AutoScroll, hdFeatComScrollTime.value);
        else
            FeatCommTimeout = setTimeout (AutoScroll, 4000);
    }
}
    
function AutoScroll ()
{
    scrollFeatCommRight ();
    var hdFeatComScrollTime = document.getElementById ("hdFeatComScrollTime");
    if ((hdFeatComScrollTime != null) && (hdFeatComScrollTime.value != ""))
        FeatCommTimeout = setTimeout (AutoScroll, hdFeatComScrollTime.value);
    else
        FeatCommTimeout = setTimeout (AutoScroll, 4000);
}

function ToggleAutoScroll()
{
    var divFeatCommPlayPause = document.getElementById ("divFeatCommPlayPause");
    if (divFeatCommPlayPause.className == "featcompause")
        KillAutoScroll ();
    else
    {
        AutoScroll();
        divFeatCommPlayPause.className = "featcompause";
    }
}

function KillAutoScroll()
{
    var divFeatCommPlayPause = document.getElementById ("divFeatCommPlayPause");
    if (FeatCommTimeout != null)
        clearTimeout (FeatCommTimeout);
    divFeatCommPlayPause.className = "featcomgo";
}

function scrollFeatCommRight ()
{
    if (aFeatComNames.length <= 1)
        return;
        
    iCurrFeatComm++;
    if (iCurrFeatComm == aFeatComNames.length)
        iCurrFeatComm = 0;
        
    $("#divFeatCommContainer").animate({ "scrollLeft": "+=467px" }, "slow", RefreshFeatComm);
}

function scrollFeatCommLeft ()
{
    if (aFeatComNames.length <= 1)
        return;
        
    iCurrFeatComm--;
    if (iCurrFeatComm < 0)
        iCurrFeatComm = aFeatComNames.length - 1;
        
    $("#divFeatCommContainer").animate({ "scrollLeft": "-=467px" }, "slow", RefreshFeatComm);
}

function RefreshFeatComm ()
{
    if (aFeatComNames.length == 1)
    {
        var sHtml = "<nobr><div style=\"display:inline;\">";
        sHtml += GetFeatCommTable (0);
        sHtml += "</div></nobr>";
        document.getElementById ("divFeatCommContainer").innerHTML = sHtml;
    }
    else
    {
        var sLeftTable;
        if (iCurrFeatComm > 0)
            sLeftTable = GetFeatCommTable (iCurrFeatComm - 1);
        else
            sLeftTable = GetFeatCommTable (aFeatComNames.length - 1);
            
        var sMiddleTable = GetFeatCommTable (iCurrFeatComm);
        
        var sRightTable;
        if (iCurrFeatComm < aFeatComNames.length - 1)
            sRightTable = GetFeatCommTable (iCurrFeatComm + 1);
        else
            sRightTable = GetFeatCommTable (0);
            
        var sDivTag = "<div style=\"display:inline-block;vertical-align:top;\">";
        if (navigator.appName.indexOf ('Microsoft Internet Explorer') != -1 )
            sDivTag = "<div style=\"display:inline;vertical-align:top;\">";
                   
        var sHtml = "<nobr>" + sDivTag;
        sHtml += sLeftTable;
        sHtml += "</div>" + sDivTag;
        sHtml += sMiddleTable;
        sHtml += "</div>" + sDivTag;
        sHtml += sRightTable;
        sHtml += "</div></nobr>";

        document.getElementById ("divFeatCommContainer").innerHTML = sHtml;
        document.getElementById ("divFeatCommContainer").scrollLeft = 467;
    }
}

var g_sPageName = "";
function GetFeatCommTable (iFeatComm)
{
    var sFeatCommTable = "<table cellpadding=\"0\" cellspacing=\"0\" style=\"display:inline;\">" + 
                         "  <tr>" +
                         "      <td rowspan=\"5\" style=\"padding-left: 9px; width: 140px; text-align:center;\">" +
                         "          <a href=\"[FEAT_COMM_URL]\"><img src=\"[FEAT_COMM_IMAGE]\" style=\"display:inline;border:0px; max-width:140px;max-height:110px;width:140px;\" /></a>" + 
                         "      </td>" +
                         "      <td rowspan=\"5\">&nbsp;&nbsp;</td>" +
                         "      <td class=\"text12pxboldblk\">[FEAT_COMM_NAME]</td>" +
                         "  </tr>" +
                         "  <tr><td class=\"text12pxboldblk\">[BUILDER_NAME]</td></tr>" +
                         "  <tr><td class=\"text12ptblk\">[CITY]</td></tr>" +
                         "  <tr><td class=\"text12ptblk\">[PRICE_RANGE]</td></tr>" +
                         "  <tr><td class=\"text18pxboldblk\" style=\"width:310px;\">" + 
                         "      [PHONE_NUMBER]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                         "      <a href=\"javascript:dcsTrackingCall('[PAGE_NAME]','[STATE_NAME]','[METRO_NAME]','[ENTITY_ID]','[WEBSITE_PREFIX]_c_leadpop',false);" +
                         "      ToggleAutoScroll();ShowQuickLead(2, [ENTITY_ID], [ENDECA_ID], 3, '[DATA_SOURCE]', '[MARKET_CODE]', '[FEAT_COMM_NAME]', '[PHONE_NUMBER]', '[STATE_NAME]', '[METRO_NAME]', 'FREE BROCHURE');\"" + 
                         "       style=\"background-image:url(/images/images002.png);background-position:-86px -149px;text-decoration:none;\" onmouseover=\"this.style.backgroundPosition='-86px -172px';\" onmouseout=\"this.style.backgroundPosition='-86px -149px';\">" +
                         "       &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></td></tr>" +
                         "</table>";
    
    sFeatCommTable = sFeatCommTable.replace (/\[FEAT_COMM_NAME\]/g, aFeatComNames [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[FEAT_COMM_IMAGE\]/g, aFeatComImages [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[BUILDER_NAME\]/g, aFeatComBuilders [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[CITY\]/g, aFeatComCities [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[PRICE_RANGE\]/g, aFeatComPrices [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[PHONE_NUMBER\]/g, aFeatComPhones [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[ENTITY_ID\]/g, aFeatComEntityIDs [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[ENDECA_ID\]/g, aFeatComEndecaIDs [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[DATA_SOURCE\]/g, aFeatComDataSources [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[MARKET_CODE\]/g, aFeatComMarketCodes [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[STATE_NAME\]/g, aFeatComStates [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[METRO_NAME\]/g, aFeatComMetros [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[PAGE_NAME\]/g, g_sPageName);
    sFeatCommTable = sFeatCommTable.replace (/\[FEAT_COMM_URL]/g, aFeatComUrls [iFeatComm]);
    sFeatCommTable = sFeatCommTable.replace (/\[WEBSITE_PREFIX]/g, g_WebsitePrefix);
    
    return sFeatCommTable;
}
/* End of functions and variables used for the rotating featured community banner */