// http://ajc-dev.gabriels.net/includes/javascript/global.js

function PageLoader(){void(null);}function GUnload(){void(null);}var PageCache=null;try{document.execCommand("BackgroundImageCache",false,true);}catch(err){};if(window.location.href.indexOf('#')>-1){var SEOPath=window.location.href.substring(window.location.href.indexOf('#')+1);if(SEOPath.indexOf("/")>-1&&SEOPath.length>3){window.location.href="http://"+window.location.hostname+SEOPath;}}function trim(str){if(str==null){return"";}if(GetType(str)=="object"){return"";}return str.replace(/^\s*|\s*$/g,"");}function gE(objId){if(document.getElementById(objId)){return document.getElementById(objId);}return null;}function gEDisplay(objId,display){gE(objId).style.display=display;}function DoReport(Data){if(Data!=""){var URL=WebRoot+"Controls/AjaxCalls/DoReport.aspx?Data="+Data;$AJAX.GetAsync(URL);}}function SetCookieState(CookieName,Key,Value){var Query=String.format("CookieName={0}&Key={1}&Value={2}",CookieName,Key,Value);var URL=WebRoot+"Controls/AjaxCalls/SetCookieState.aspx?"+Query;$AJAX.GetAsync(URL);}var MousePosition=new Object();MousePosition.X=0;MousePosition.Y=0;function captureMousePosition(e){if(document.layers){MousePosition.X=e.pageX+25;MousePosition.Y=e.pageY-25;}else if(document.all){MousePosition.X=window.event.x+document.body.scrollLeft+25;MousePosition.Y=window.event.y+document.body.scrollTop-25;}else if(document.getElementById){MousePosition.X=e.pageX+25;MousePosition.Y=e.pageY-25;}}function CaptureMouseXY(){if(document.layers){document.captureEvents(Event.MOUSEMOVE);document.onmousemove=captureMousePosition;}else if(document.all){document.onmousemove=captureMousePosition;}else if(document.getElementById){document.onmousemove=captureMousePosition;}}function RecurseOffset(obj){if(GetType(obj)=="string"){if(gE(obj)==null){alert("RecurseOffset requires a valid DOM object");}else{obj=gE(obj);}}var ROO=new RecurseOffsetObject(obj);var Offsets=new Object();Offsets.offsetLeft=ROO.GetOffsetLeft();Offsets.offsetTop=ROO.GetOffsetTop();Offsets.offsetWidth=ROO.GetOffsetWidth();Offsets.offsetHeight=ROO.GetOffsetHeight();return Offsets;}function RecurseOffsetObject(obj){this.ParentObj=null;this.CurrentObj=obj;this.offsetLeft=obj.offsetLeft;this.offsetTop=obj.offsetTop;this.offsetWidth=obj.offsetWidth;this.offsetHeight=obj.offsetHeight;RecurseOffsetObject.prototype.Init=function(){if(this.CurrentObj.offsetParent!=null){do{this.ParentObj=this.CurrentObj.offsetParent;this.offsetLeft+=this.ParentObj.offsetLeft;this.offsetTop+=this.ParentObj.offsetTop;this.CurrentObj=this.ParentObj;}while(this.CurrentObj.offsetParent!=null);}};RecurseOffsetObject.prototype.GetOffsetLeft=function(){return this.offsetLeft;};RecurseOffsetObject.prototype.GetOffsetTop=function(){return this.offsetTop;};RecurseOffsetObject.prototype.GetOffsetWidth=function(){return this.offsetWidth;};RecurseOffsetObject.prototype.GetOffsetHeight=function(){return this.offsetHeight;};this.Init();}String.format=function(){if(arguments.length==0){throw("String.format requires arguments");}var str=" "+arguments[0];for(var i=1;i<arguments.length;i++){var re=new RegExp('([^\\{]{1})(\\{'+(i-1)+'\\}(?!\\}))','gm');str=str.replace(re,'\$1'+arguments[i]);}str=str.replace(new RegExp('\\{\\{','gm'),"{");str=str.replace(new RegExp('\\}\\}','gm'),"}");return str.substring(1);};function GetType(Element){if(Element==null){return"null";}if(Element.constructor==null){return"object";}else{var Catches=Element.constructor.toString().toLowerCase().match(/([a-z0-9]+)(\(\))/i);if(Catches!=null){return Catches[1];}else{return"unknown";}}}function GetWindowBunds(){this.PageWidth=0;this.PageHeight=0;this.VisibleTop=0;this.VisibleLeft=0;this.VisibleWidth=0;this.VisibleHeight=0;this.isDefined=true;GetWindowBunds.prototype.Init=function(){if(window.innerHeight&&window.scrollMaxY){this.PageWidth=window.innerWidth+window.scrollMaxX;this.PageHeight=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){this.PageWidth=document.body.scrollWidth;this.PageHeight=document.body.scrollHeight;}else{this.PageWidth=document.body.offsetWidth+document.body.offsetLeft;this.PageHeight=document.body.offsetHeight+document.body.offsetTop;}if(typeof(window.innerWidth)=='number'){this.VisibleWidth=window.innerWidth;this.VisibleHeight=window.innerHeight;}else if(document.documentElement&&document.documentElement.clientWidth){this.VisibleWidth=document.documentElement.clientWidth;this.VisibleHeight=document.documentElement.clientHeight;}else if(document.body&&document.body.clientWidth){this.VisibleWidth=document.body.clientWidth;this.VisibleHeight=document.body.clientHeight;}if(!isNaN(window.pageYOffset)){this.VisibleTop=window.pageYOffset;this.VisibleLeft=window.pageXOffset;}else if(document.body&&(document.body.scrollTop||document.body.scrollLeft)){this.VisibleTop=document.body.scrollTop;this.VisibleLeft=document.body.scrollLeft;}else if(document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)){this.VisibleTop=document.documentElement.scrollTop;this.VisibleLeft=document.documentElement.scrollLeft;}else{this.isDefined=false;}if(navigator.userAgent.indexOf('Safari')>-1){this.VisibleHeight=window.innerHeight;}};this.Init();}function FormatNumber(NumberString){NumberString+='';Parts=NumberString.split('.');Number1=Parts[0];Number2=Parts.length>1?'.'+Parts[1]:'';var rgx=/(\d+)(\d{3})/;while(rgx.test(Number1)){Number1=Number1.replace(rgx,'$1'+','+'$2');}return Number1+Number2;}function ImportJS(strFile,strTemplateName){document.write('<scri'+'pt language="javascript" type="text/javascript" src="http://www.househunting.ca/scripts/include.aspx?file=/themes/'+strTemplateName+'/'+strFile+'.inc"></scr'+'ipt>');}function OnBoardNav(state,address,zip,city){tb_show('Detail Info',WebRoot+"Controls/AjaxCalls/onboardnavigator.aspx?height=510&width=704&state="+state+"&address="+escape(address)+"&zip="+zip+"&city="+escape(city),false);}function EmailAgentDir(IdAgentForeignKey,Agent,EmailLeadType){if(EmailLeadType=='2'){tb_show('Email Agent',WebRoot+"Controls/AjaxCalls/EmailAgent.aspx?height=620&width=450&IdAgentForeignKey="+IdAgentForeignKey+"&Agent="+escape(Agent)+"&EmailLeadType="+EmailLeadType,false);}else{tb_show('Email Agent',WebRoot+"Controls/AjaxCalls/EmailAgent.aspx?height=375&width=450&IdAgentForeignKey="+IdAgentForeignKey+"&Agent="+escape(Agent)+"&EmailLeadType="+EmailLeadType,false);}}function EmailAgent(IdListing,Agent,EmailLeadType,flag,Refer){if(EmailLeadType=='2'){tb_show('Email Agent',WebRoot+"Controls/AjaxCalls/EmailAgent.aspx?height=600&width=450&IdListing="+IdListing+"&Agent="+escape(Agent)+"&EmailLeadType="+EmailLeadType+"&PageFlag="+flag,false);}else{tb_show('Email Agent',WebRoot+"Controls/AjaxCalls/EmailAgent.aspx?height=400&width=450&IdListing="+IdListing+"&Agent="+escape(Agent)+"&EmailLeadType="+EmailLeadType+"&PageFlag="+flag,false);}}function SMSFriend(IdListing,flag,url){tb_show('Listing you are sharing:',WebRoot+"Controls/AjaxCalls/EmailToMobile.aspx?height=390&width=450&IdListing="+IdListing+"&PageFlag="+flag+"&Url="+url,false);}function EmailFriend(IdListing,flag,url){tb_show('Listing you are sharing:',WebRoot+"Controls/AjaxCalls/EmailFriend.aspx?height=390&width=450&IdListing="+IdListing+"&PageFlag="+flag+"&Url="+url,false);}function ReportAsSpamThickBox(IdListing,DetailUrl,IdWeb,flag){tb_show('Report As Spam',WebRoot+"Controls/AjaxCalls/ReportAsSpam.aspx?height=225&width=450&IdListing="+IdListing+"&DetailUrl="+DetailUrl+"&IdWeb="+IdWeb+"&PageFlag="+flag,false);}function MortgageCalThickBox(Address,CityState,IdWeb,Price,SponseredURL,AdvertiserLogo){tb_show('Calculate Mortgage',WebRoot+"Controls/AjaxCalls/MortgageCalculater.aspx?height=400&width=500&Address="+escape(Address)+"&IdWeb="+IdWeb+"&Price="+Price+"&SponseredURL="+SponseredURL+"&AdvertiserLogo="+AdvertiserLogo+"&CityState="+escape(CityState),false);}function SMSAgentThickBox(AgentPhone,IdWeb){tb_show('Send SMS',WebRoot+"Controls/AjaxCalls/Send_SMS.aspx?height=300&width=400&AgentPhone="+AgentPhone+"&IdWeb="+IdWeb,false);}function SendEmail(emailstring){tb_show('Success',WebRoot+"send_email_lead.aspx?"+emailstring+"&height=50&width=250",false);ResetQues();}function ResetQues(){gE("FirstName").value="";gE("EmailAddress").value="";gE("Message").value="";}function FloorPlan(URL){var flr=new UrlGen(URL);var flrplanURL="";if(flr.GetParam("U")!=""){flrplanURL=flr.GetParam("U");}else{flrplanURL=URL;}if(flrplanURL!=""){if(URL.indexOf('.html')>-1||URL.indexOf('.htm')>-1||URL.indexOf('.pdf')>-1){window.open(flrplanURL);}else{tb_show('Floor Plan',WebRoot+"Controls/AjaxCalls/FloorPlan.aspx?height=530&width=400&FloorPlanURL="+flrplanURL,false);}}}function SendSMS(theForm){if(theForm.txtName.value==""){alert("Please enter your name");theForm.txtName.focus();return(false);}if(theForm.txtPhone.value==""){alert("Please enter your phone no");theForm.txtPhone.focus();return(false);}if(theForm.txtMessage.value==""){alert("Please enter message");theForm.txtMessage.focus();return(false);}if(theForm.txtMessage.value.length>120){alert("You can not enter more than 120 charaters");theForm.txtMessage.focus();return(false);}tb_show('Success',WebRoot+"send_email_lead.aspx?AgentPhone="+theForm.AgentPhone.value+"&UName="+escape(theForm.txtName.value)+"&UPhone="+theForm.txtPhone.value+"&Message="+escape(theForm.txtMessage.value)+"&IdWeb="+theForm.IdWeb.value+"&SMS=true"+"&height=150&width=250",false);}function formatCurrency(num){num=num.toString().replace(/\$|\,/g,'');if(isNaN(num))num="0";sign=(num==(num=Math.abs(num)));num=Math.floor(num*100+0.50000000001);cents=num%100;num=Math.floor(num/100).toString();if(cents<10)cents="0"+cents;for(var i=0;i<Math.floor((num.length-(1+i))/3);i++)num=num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));return(((sign)?'':'-')+'$'+num);}function MortgageCalculate(theForm){var price=parseInt(theForm.Price.value);var downPayment=theForm.DownPayment.value;if(!IsNumeric(downPayment)||theForm.DownPayment.value==""){alert("Please enter numeric value in Down payment");theForm.DownPayment.focus();return(false);}var loanT=theForm.LoanTerm;loanTerm=parseFloat(loanT[loanT.selectedIndex].value)*12;var Rate=theForm.IntersetRate.value;if(!IsNumeric(Rate)||theForm.IntersetRate.value==""){alert("Please enter numeric value in Interset Rate");theForm.IntersetRate.focus();return(false);}Rate=(parseFloat(theForm.IntersetRate.value)/100)/12;var Principal=(price)-((price*downPayment)/100)
var totalMonthlypayment=0;totalMonthlypayment=(Rate+(Rate/(Math.pow(1+Rate,loanTerm)-1)))*Principal;theForm.MonthlyPayment.value=formatCurrency(Math.round(totalMonthlypayment));}function ResetValue(){var price=parseInt(gE("Price").value);gE("DownPayment").value="20";gE("LoanTerm").value="30";gE("IntersetRate").value="6";var Rate=(parseInt(gE("IntersetRate").value)/100)/12;var Principal=(price)-((price*parseInt(gE("DownPayment").value))/100)
var totalMonthlypayment=0;totalMonthlypayment=(Rate+(Rate/(Math.pow(1+Rate,(parseInt(gE("LoanTerm").value)*12))-1)))*Principal;gE("MonthlyPayment").value=formatCurrency(Math.round(totalMonthlypayment));}function ValidateSMSFriend(theForm){if(theForm.txtName.value==""){alert("Please enter your name.");theForm.txtName.focus();return(false);}if(theForm.txtPhone.value==""){alert("Please enter your phone no");theForm.txtPhone.focus();return(false);}if(theForm.provider.value=="x"){alert("Please choose a provider for your mobile phone.");theForm.provider.focus();return(false);}if(theForm.accept_terms.checked==false){alert("Please accept the Terms and Conditions");theForm.accept_terms.focus();return(false);}var phoneno=theForm.txtPhone.value;var EmailToAdress=phoneno.replace(/[^0-9]*/g,'')+"@"+theForm.provider.value;SendEmail("PageFlag="+theForm.PageFlag.value+"&IdListing="+theForm.IdListing.value+"&EmailFriendAddress="+EmailToAdress+"&Name="+escape(theForm.txtName.value)+"&emailto=friend"+"&Url="+theForm.Url.value+"&mobile=true");return(true);}function ValidateEmailFriend(theForm){if(theForm.flName.value==""){alert("Please enter your name.");theForm.flName.focus();return(false);}if(theForm.EmailAddress.value==""){alert("Please enter your email address.");theForm.EmailAddress.focus();return(false);}var addFlag=validEmailField(theForm.EmailAddress,"Please Enter valid E-mail address in the form: yourname@yourdomain.com");if(!addFlag){return(false);}if(theForm.NameFriend.value==""){alert("Please enter your Friend's name.");theForm.NameFriend.focus();return(false);}if(theForm.EmailFriendAddress.value==""){alert("Please enter your Friend's email address.");theForm.EmailFriendAddress.focus();return(false);}var addrss=theForm.EmailFriendAddress.value;theForm.EmailFriendAddress.value=addrss.replace(";",",");var faddFlag=validEmailFieldMultiple(theForm.EmailFriendAddress,",","Please Enter valid E-mail addresses in the form: yourname@yourdomain.com");if(!faddFlag){return(false);}if(theForm.Message.value!=""){var checkOK="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzƒŠŒŽšœžŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ0123456789-@%:')(#_*&+!.$/ ,- ; <=^>\"\t\r\n\f~";var checkStr=theForm.Message.value;var allValid=true;var k=checkStr.length;var p=0;for(i=0;i<k;i++){ch=checkStr.charAt(p);for(j=0;j<checkOK.length;j++){if(ch==checkOK.charAt(j)){p=p+1;break;}if(j==checkOK.length){checkStr=checkStr.substring(0,p)+checkStr.substring(p+1);}}}theForm.Message.value=checkStr;if(!allValid){alert("Please enter only letter, digit, whitespace and \"@%*$/:)(#_&-+!.;,<=^> \" characters in the \"Message\" field.");document.theForm.Message.focus();return(false);}}SendEmail("PageFlag="+theForm.PageFlag.value+"&IdListing="+theForm.IdListing.value+"&EmailAddress="+theForm.EmailAddress.value+"&EmailFriendAddress="+theForm.EmailFriendAddress.value+"&Message="+escape(theForm.Message.value)+"&Name="+escape(theForm.flName.value)+"&NameFriend="+escape(theForm.NameFriend.value)+"&emailto=friend"+"&Url="+theForm.Url.value);return(true);}function ValidateEmailAgent(theForm){var IdListing="";var PhoneNo="";var Ext="";if(theForm.IdListing){IdListing=theForm.IdListing.value;}if(theForm.Phone){PhoneNo=theForm.Phone.value;}if(theForm.Extension){Ext=theForm.Extension.value;}var EmailLeadType=theForm.EmailLeadType.value;if(theForm.FirstName.value==""){alert("Please enter your first name.");theForm.FirstName.focus();return(false);}if(theForm.LastName.value==""){alert("Please enter your last name.");theForm.LastName.focus();return(false);}if(theForm.EmailAddress.value==""){alert("Please enter your email address.");theForm.EmailAddress.focus();return(false);}var addFlag=validEmailField(theForm.EmailAddress,"Please enter valid email address in the format: yourname@yourdomain.com",1);if(!addFlag)return(false);if(EmailLeadType!="2"){if(theForm.Phone){addFlag=validateUSPhone(theForm.Phone,"Please enter valid phone number",2);if(!addFlag)return(false);}}if(theForm.Message.value!=""){var checkOK="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzƒ0123456789-@%:')(#_*&+!.$/ ,- ; <=^>\"\t\r\n\f~";var checkStr=theForm.Message.value;var allValid=true;var k=checkStr.length;var p=0;for(i=0;i<k;i++){ch=checkStr.charAt(p);for(j=0;j<checkOK.length;j++){if(ch==checkOK.charAt(j)){p=p+1;break;}if(j==checkOK.length){checkStr=checkStr.substring(0,p)+checkStr.substring(p+1);}}}theForm.Message.value=checkStr;if(!allValid){alert("Please enter only letter, digit, whitespace and \"@%*$/:)(#_&-+!.;,<=^> \" characters in the \"Message\" field.");document.theForm.Message.focus();return(false);}}if(EmailLeadType=="2"){SendEmail("PageFlag="+theForm.PageFlag.value+"&IdListing="+IdListing+"&IdAgentForeignKey="+theForm.IdAgentForeignKey.value+"&EmailAddress="+theForm.EmailAddress.value+"&Phone="+PhoneNo+"&Extension="+Ext+"&Message="+escape(theForm.Message.value)+"&Move="+escape(theForm.Move.value)+"&FirstName="+escape(theForm.FirstName.value)+"&LastName="+escape(theForm.LastName.value)+"&State="+escape(theForm.State.value)+"&City="+escape(theForm.City.value)+"&Street="+escape(theForm.Street.value)+"&Zip="+theForm.Zip.value+"&emailto=agent");}else{SendEmail("PageFlag="+theForm.PageFlag.value+"&IdListing="+IdListing+"&IdAgentForeignKey="+theForm.IdAgentForeignKey.value+"&EmailAddress="+theForm.EmailAddress.value+"&Phone="+PhoneNo+"&Extension="+Ext+"&Message="+escape(theForm.Message.value)+"&FirstName="+escape(theForm.FirstName.value)+"&LastName="+escape(theForm.LastName.value)+"&emailto=agent");}return(true);}function AskAQues(theForm){if(theForm.FirstName.value==""){alert("Please enter your name.");theForm.FirstName.focus();return(false);}if(theForm.EmailAddress.value==""){alert("Please enter your email address.");theForm.EmailAddress.focus();return(false);}var addFlag=validEmailField(theForm.EmailAddress,"Please enter valid email address in the format: yourname@yourdomain.com",1);if(!addFlag)return(false);if(theForm.Message.value!=""){var checkOK="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzƒ0123456789-@%:')(#_*&+!.$/ ,- ; <=^>\"\t\r\n\f~";var checkStr=theForm.Message.value;var allValid=true;var k=checkStr.length;var p=0;for(i=0;i<k;i++){ch=checkStr.charAt(p);for(j=0;j<checkOK.length;j++){if(ch==checkOK.charAt(j)){p=p+1;break;}if(j==checkOK.length){checkStr=checkStr.substring(0,p)+checkStr.substring(p+1);}}}theForm.Message.value=checkStr;if(!allValid){alert("Please enter only letter, digit, whitespace and \"@%*$/:)(#_&-+!.;,<=^> \" characters in the \"Message\" field.");document.theForm.Message.focus();return(false);}}SendEmail("PageFlag="+theForm.PageFlag.value+"&IdListing="+theForm.IdListing.value+"&IdAgentForeignKey="+theForm.IdAgentForeignKey.value+"&EmailAddress="+theForm.EmailAddress.value+"&Message="+escape(theForm.Message.value)+"&Name="+escape(theForm.FirstName.value)+"&emailto=agent");return(true);}function RestoreSelects(){if(!document.all){return;}var SelectCollection=document.getElementsByTagName("select");for(var s=0;s<SelectCollection.length;s++){SelectCollection[s].style.visibility="visible";}}function SweepSelects(TargetObject){if(!document.all){return;}var TRO=new RecurseOffset(TargetObject);var MatchLeft=TRO.offsetLeft;var MatchTop=TRO.offsetTop;var MatchRight=MatchLeft+TRO.offsetWidth;var MatchBottom=MatchTop+TRO.offsetHeight;var SelectCollection=document.getElementsByTagName("select");for(var s=0;s<SelectCollection.length;s++){var SelectObject=SelectCollection[s];var SRO=new RecurseOffset(SelectObject);var SelectLeft=SRO.offsetLeft;var SelectTop=SRO.offsetTop;var SelectRight=SelectLeft+SRO.offsetWidth;var SelectBottom=SelectTop+SRO.offsetHeight;if((SelectRight>MatchLeft)&&(SelectBottom>MatchTop)&&(SelectLeft<MatchRight)&&(SelectTop<MatchBottom)){SelectObject.style.visibility="hidden";}if((SelectLeft==0)&&(SelectTop==0)){SelectObject.style.visibility="hidden";}}}function UrlGen(strQueryString){this.Parameters=new Array();UrlGen.prototype.Init=function(strQueryString){with(this){Parameters=new Array();var QueryString=strQueryString.replace(/&amp;/gi,'&');QueryString=QueryString.replace('%7c','|');QueryString=unescape(QueryString);var _tempParams=QueryString.split('&');for(var i=0;i<_tempParams.length;i++){var _Param=_tempParams[i].split('=');Parameters.push(_Param);}}};UrlGen.prototype.RemoveParam=function(strKey){with(this){var _tempParams=new Array();for(var i=0;i<Parameters.length;i++){if(Parameters[i][0].toLowerCase()!=strKey.toLowerCase()){_tempParams.push(Parameters[i]);}}Parameters=_tempParams;}};UrlGen.prototype.RemoveParams=function(arrParams){with(this){for(var p=0;p<arrParams.length;p++){RemoveParam(arrParams[p]);}}};UrlGen.prototype.AddParam=function(strKey,strValue){with(this){Parameters.push(new Array(strKey,strValue));}};UrlGen.prototype.RemoveNValue=function(strValue){with(this){var _tempval=new Array();for(var i=0;i<Parameters.length;i++){if(Parameters[i][0].toLowerCase()!="n"){_tempval.push(Parameters[i]);}else{var _tempN=new Array();arrNewN=Parameters[i][1].split('+');for(var j=0;j<arrNewN.length;j++){if(arrNewN[j]!=strValue){_tempN.push(arrNewN[j]);}}if(_tempN.length>1){_tempval.push(new Array("N",_tempN.join('+').toString()));}else{_tempval.push(new Array("N",_tempN.toString()));}}}Parameters=_tempval;}};UrlGen.prototype.AddNValue=function(strValue){with(this){var _tempval=new Array();for(var i=0;i<Parameters.length;i++){if(Parameters[i][0].toLowerCase()!="n"){_tempval.push(Parameters[i]);}else{var arrN=new Array();arrN=Parameters[i][1].split('+');arrN.push(strValue);if(arrN.length>1){_tempval.push(new Array("N",arrN.join('+').toString()))}else{_tempval.push(new Array("N",arrN.toString()))}}}Parameters=_tempval;}};UrlGen.prototype.GetParam=function(strKey){with(this){for(var i=0;i<Parameters.length;i++){if(Parameters[i][0].toLowerCase()==strKey.toLowerCase()){return Parameters[i][1];}}return"";}};UrlGen.prototype.ToString=function(){with(this){var _tempParams=new Array();for(var i=0;i<Parameters.length;i++){if(trim(Parameters[i][0])!=""){_tempParams.push(Parameters[i].join('='));}}return _tempParams.join('&');}};this.Init(strQueryString);}function setAdTagsParameters(){document.globalPageSite="AJC";document.globalPageSctnName=adtag_globalPageSctnName;document.globalPageSctnId=adtag_globalPageSctnId;document.globalPageType=adtag_globalPageType;document.globalCategoryDspName=adtag_globalCategoryDspName;document.globalSctnDspName=adtag_globalSctnDspName;document.globalPageTitle=adtag_globalPageTitle;document.globalPageAbstract=adtag_globalPageAbstract;document.globalPageKeywords=adtag_globalPageKeywords;document.globalPageSponsorship=adtag_globalPageSponsorship;document.globalSctnLineage=adtag_globalSctnLineage;mdManager.addParameter("Url",adtag_url);mdManager.addParameter("Type",adtag_globalPageType);mdManager.addParameter("Role","");mdManager.addParameter("Title",adtag_globalPageTitle);mdManager.addParameter("Sponsorship",adtag_globalPageSponsorship);mdManager.addParameter("Abstract",adtag_globalPageAbstract);mdManager.addParameter("Keywords",adtag_globalPageKeywords);mdManager.addParameter("Classification",adtag_globalSctnLineage);mdManager.addParameter("Site","DOOR");mdManager.addParameter("SctnName",adtag_globalPageSctnName);mdManager.addParameter("SctnDspName",adtag_globalSctnDspName);mdManager.addParameter("CategoryDspName",adtag_globalCategoryDspName);mdManager.addParameter("SctnId",adtag_globalPageSctnId);mdManager.addParameter("DetailId","");mdManager.addParameter("PageNumber","1");mdManager.addParameter("UniqueId",adtag_globalUniqueId);mdManager.addParameter("Show_Abbr","");mdManager.addParameter("SearchKeywords","<% // FROM INITIAL SEARCH BOX %>");mdManager.addParameter("SearchFilters","<% // FROM REFINEMENTS %>");}function SetDefault(CurrentValue,DefaultValue){if(CurrentValue==undefined){return DefaultValue;}return CurrentValue;}function Dimensiondisplay(dimensionName){if(gE("refinement_"+dimensionName).style.display=="block"){gE("refinement_"+dimensionName).style.display="none";gE("link_"+dimensionName).className="open";}else{gE("refinement_"+dimensionName).style.display="block"
gE("link_"+dimensionName).className="close";}}

var AJC = new GTSSearch("AJC");

/*
================================================================
JSON Request Components ( All Must Be Defined )
================================================================
NAME                    TYPE
================================================================
jsonSRC                 string, path to json script
````````````````````````````````````````````````````````````````
Points to the JSON response script to be called. Can be 
relative or absolute URL.
----------------------------------------------------------------
searchTerm                    String, partial word fragment
````````````````````````````````````````````````````````````````
The term to be searched. minimum of 2 characters.
----------------------------------------------------------------
levelLimit                  String, comma separated numeric list
````````````````````````````````````````````````````````````````
Represents a list of Levels that the response could be 
limited by. This field may be empty for "all levels"
----------------------------------------------------------------
parentRegionID          Number, region id
````````````````````````````````````````````````````````````````
Limits the responses to only be children of the region id that 
is passed. To allow all, may be left blank.
----------------------------------------------------------------
maxSuggestReturns       Number
````````````````````````````````````````````````````````````````
Limits the number of responses in the result set. May be left
blank, for a default of 10.
----------------------------------------------------------------
jsonResponseName        String
````````````````````````````````````````````````````````````````
The name of the object that the JSON response is loaded into
----------------------------------------------------------------
caching                 Number; 0=false; 1=true, in minutes
````````````````````````````````````````````````````````````````
Turns caching of the response on or off. If true, number
represents the number of minutes responses are cached.
----------------------------------------------------------------
ResponseDelegate        String, name of function
````````````````````````````````````````````````````````````````
This function is called immediately after all JSON object data
is loaded in the response.
----------------------------------------------------------------
*/

function GTSSearch(ObjectInstanceName) 
{
    this.GhostMessage = "Enter a city, state or ZIP code";   
    this.resultsUrl = ""; 
    this.redirectUrl = "http://ajchomefinder.com/"
    this.jsonResponseName = "JsonResponse";
    this.jsonSRC = "";
    this.jsonSearchSRC = "";
    this.levelLimit = "";
    this.parentRegionID = "";
    this.caching = 30;
    this.suggestID = "suggest";
    this.maxSuggestReturns = 10;
    this.searchType = "for-sale";
    this.alertID = "search-alert";
    this.alertMsgID = "search-alert-message";
    this.errMsgLTS = "Please enter a location of at least 2 characters";
    this.errMsgNM = "There were no matching locations found. Please try again.";
    this.errMsgNMAddrSearch = "There were no listings found to match your criteria.Please try again.";
    this.errMsgDYM = "There were multiple location matches found. Did you mean one of the following?";
    this.errPriceCheck = "The Min.Price cannot be greater than the Max.Price. Please try again.";
    this.errMsgAddrSearch="There were multiple matches found. Click the link to view details...";
    this.errMsgEmpty = "Please enter a location";
    this.ResponseDelegate = ObjectInstanceName + ".ShowSuggest"; // self referencing object method call    
    this.ResponseDelegateSearchZip = ObjectInstanceName + ".ShowSearchZip";  
    this.SearchTypeByZip      = "ByZip";            //the enum SearchType is defined in 
    this.SearchTypeByIdWeb    = "ByIdWeb";
    this.SearchTypeByAddress  = "ByAddress";
    var My = this;
    
    var strRefinements ="";
      
    //========================================================
    //  Ghost Text Functionality
    //========================================================
    GTSSearch.prototype.ManageSearchText = function(txtSearchId, strDefault) 
    {
        var ts = document.getElementById(txtSearchId);
        if (strDefault != undefined)
        {
            if (ts.value.replace(/^\s+|\s+$/g,'') == this.GhostMessage)
            {
                ts.value = '';
                ts.className = '';
                return;
            }
        }
        if (ts.value.replace(/^\s+|\s+$/g,'') == '')
        {
            ts.value = this.GhostMessage;
            ts.className = 'ghost-text';
            return;
        }
        ts.className = '';
    };
   
   
   
   GTSSearch.prototype.submitSearch = function(theForm)   {
    with (this) {
            if (!validateGTSSearch(theForm)) {
               
                return false;                
            }

            if(!validateRefinements(theForm))
            {
                alert(AJC.errPriceCheck);
                return false;
            }
          
           strRefinements = buildRefinements(theForm);
            submitGTSSearch();    
    }
   
   };
   
    //========================================================
    //  Search Page functions - submitGTSSearch
    //========================================================
    GTSSearch.prototype.submitGTSSearch = function() {
        with (this) { 
            var strLocation = gE('RegionId').value;
            strLocation = strLocation.replace(",", "");
            strLocation = strLocation.replace("(", "");
            strLocation = strLocation.replace(")", "")
            strLocation = strLocation.replace(/\s+/g, "-");
            if (strLocation.length > 0) {
                var strRedirect = resultsUrl + searchType + strLocation;               
                if (strRefinements.length > 0) { strRedirect += "/" + strRefinements }    
                //alert(strRedirect);           
                top.window.location.href  = strRedirect;
            }
        }
    };
    
    
    //========================================================
    //  validateGTSSearch Location
    //========================================================
    GTSSearch.prototype.validateGTSSearch = function(origin) 
    {
      
        with (this) {
            var txt = gE('txtSearch').value;
            var regionid = gE('RegionId').value;

            if (txt == this.GhostMessage) 
            {
                alert(errMsgEmpty);
                document.getElementById('txtSearch').focus();
                window.setTimeout(function()
                {
                    document.getElementById('txtSearch').value = '';
                }, 100);
                return;
            }
            
            // replace commas and spaces with hyphens.
            txt = txt.toUpperCase();
            txt = txt.replace(/,/g, "");
            txt = txt.replace(/\s+/g, "-");

            var pos = regionid.indexOf(txt)
            //alert("txt=" + txt + " regionid=" + regionid + " pos=" + pos);
            
            if(txt.length==0)
            {
                alert(errMsgEmpty);
                gE('txtSearch').focus();
                return false;
            }
            if (pos >= 0) {
               
                return true;
               
            }

            if (txt.length < 2) {                       // Too cold.
                alert(errMsgLTS);
                return false;
            }

            var matchCount = gE('matchCount').value;
            if (matchCount > 1) {                  // Much too hot. 
                gE(suggestID).style.display = "none";
                gE(alertID).style.display = "block";
                gE(alertID).focus();
                return false;
            }
            else {                                      // Just right!
                return true;
            }
        }
    };
    
    GTSSearch.prototype.validateRefinements = function (theForm)
    {
             var minPrice = "";
             var maxPrice = "";
        if(this.searchType =="rentals" || this.searchType =="apartments")
        { 
            minPrice = theForm.r_pricemin.options;
            maxPrice = theForm.r_pricemax.options;
                
        }
        else
        {
              minPrice = theForm.s_pricemin.options;
              maxPrice = theForm.s_pricemax.options;
        }
    
           
            if((minPrice.selectedIndex > maxPrice.selectedIndex) && (maxPrice.selectedIndex != 0))
            {
                alert(AJC.errPriceCheck);
                 return false;
            }
            else
            {
                  return true;   
       
            }
           
                
    };
    GTSSearch.prototype.buildRefinements = function(theForm)
    {
                 var strRefinements = "";
                 var b="";                
                 var p="";
                 var cf ="";
                 var minPrice = theForm.s_pricemin.options;
                 var maxPrice = theForm.s_pricemax.options;
                  switch(this.searchType.toLowerCase())
                    {             
                       case "new-homes":
                               b ="";                               
                               p = "cs"; 
                               cf = "communityfeature";       
                             break;
                         case "rentals":                      
                                b ="r";                               
                                p = "r";  
                             minPrice = theForm.r_pricemin.options;
                             maxPrice = theForm.r_pricemax.options;
                             break;   
                          case "apartments":
                            b ="cr";                           
                            p = "cr"; 
                            minPrice = theForm.r_pricemin.options;
                           maxPrice = theForm.r_pricemax.options;
                         break;
                        default:
                             b ="";                           
                             p = "";
                             cf="commfeat";           
                            break;
                    }     
                  if (theForm.search_bedrooms)
                    {
                        var bedslist = theForm.search_bedrooms.options;
                        if (bedslist.selectedIndex > 0)
                        {   
                             strRefinements += bedslist[bedslist.selectedIndex].value + "-" + b + "beds/";                            
                        } 
                    }

                 if (theForm.search_bathrooms)
                   {
                        var bathslist = theForm.search_bathrooms.options;
                        if (bathslist.selectedIndex > 0)
                        {
                             strRefinements += bathslist[bathslist.selectedIndex].value +  "-" + b + "baths/"; 
                           
                        } 
                    }
                    
                   if (theForm.search_propertytype)
                   {
                        var propertyType = theForm.search_propertytype.options;
                        if (propertyType.selectedIndex > 0)
                        {
                            strRefinements += propertyType[propertyType.selectedIndex].value + "-type/"; 
                        } 
                    }
                        if ((minPrice.selectedIndex > 0) || (maxPrice.selectedIndex > 0))
                        {
                           strRefinements += minPrice[minPrice.selectedIndex].value + "-" +  maxPrice[maxPrice.selectedIndex].value +  "-" + p + "price/";   
                           
                        }                        
                   
                    
              if (theForm.search_keywords)
                {
                    var txtkeyword = trim(theForm.search_keywords.value);
                    if (txtkeyword != "")
                    {
                        if (txtkeyword.length <3)
                        {
                           alert("Please enter minimum 3 characters.");
                            return false;
                        }
                        var RegExKW = new RegExp(/[^A-Za-z0-9\-\s]+/);
	                    if (RegExKW.exec(txtkeyword)) 
	                    { 
	                       alert("Please enter alpha numeric and space only.");
	                        return false;
	                    } 
                       
                        strRefinements += theForm.search_keywords.value + "-keyword/";      
                    }
                }
               
                    if(theForm.popfeature){
                            for (var i=0; i < theForm.popfeature.length; i++)
                            {
                                  if (theForm.popfeature[i].checked)
                                  {
                                     strRefinements += theForm.popfeature[i].value + "-popfeat/";   
                                  }
                           }
                       }                      
                       if(theForm.limitsearchto)
                       {
                             for (var i=0; i < theForm.limitsearchto.length; i++)
                            {
                                  if (theForm.limitsearchto[i].checked && theForm.limitsearchto[i].value !="")
                                  {
                                     strRefinements += theForm.limitsearchto[i].value + "-limitsearchto/";   
                                  }
                           }
                       }

                    if(theForm.communityfeature)
                       {
                             for (var i=0; i < theForm.communityfeature.length; i++)
                            {
                                  if (theForm.communityfeature[i].checked && theForm.limitsearchto[i].value !="")
                                  {
                                     strRefinements += theForm.communityfeature[i].value + "-" + cf + "/";   
                                  }
                           }
                       }
            
			return strRefinements;
    };
    
       
    //========================================================
    //  Initialize Object, pseudo constructor
    //  Throw JSON Response up into mem.
    //  Add Ghost Text.
    //========================================================
    GTSSearch.prototype.Init = function() {
        with (this) {
            eval("var " + jsonResponseName + " = null;");
            window.setTimeout(function()
            {
                document.getElementById('txtSearch').value = GhostMessage;
            },250);
        }
    };

    //========================================================
    //  One mousedown to rule them all.
    //========================================================
    GTSSearch.prototype.mH = function(e) {
            if (!e) {                               // ie.
                var e = window.event;
                e.target = e.srcElement;
                e.cancelBubble = true;
            }
            else {
                e.stopPropagation();                // moz & webkit.
            }

            if (e.target.nodeType == 3) { e.target = target.parentNode }        // Safari bug?

            if (e.target.parentNode.id == undefined) {                          // if the parentNode is undefined,
                AJC.gE("suggest").style.display = "none";      // they're off the page.
                AJC.searchAlertClose();
            }
            else {
                if (e.target.parentNode.id == "search-alert") {                 // header text
                }
                else if (e.target.parentNode.id == "search-alert-message") {    // close button
                }
                else if (e.target.parentNode.id == "") {                        // ile spans.
                }
                else if (e.target.parentNode.id.substring(0, 3) == "ila") {     // on the location text
                    AJC.AddSuggest(AJC.CurrentSuggestIndex());
                }
                else if (e.target.parentNode.id == "suggest") {                 // a location is highlighted,
                    AJC.AddSuggest(AJC.CurrentSuggestIndex());                  // but the click is between the cracks.
                }
                else {
                    AJC.gE("suggest").style.display = "none";
                    AJC.searchAlertClose();
                }
            }
    };
    
    //===============================================
    //	System Types are caught with GetType()
    //	Or, any custom type built with a constructor
    //===============================================
    GTSSearch.prototype.GetType = function(Element) {

        if (Element == null) {
            return "null";
        }
        if (Element.constructor == null) {
            return "object";
        }
        else {
            var Catches = Element.constructor.toString().toLowerCase().match(/([a-z0-9]+)(\(\))/i);
            if (Catches != null) {
                if (Catches.length > 0) {
                    return Catches[1].toString();
                }
                else {
                    return "unknown";
                }
            }
            else {
                return "unknown";
            }
        }
    };

    //========================================================
    //  standard TRIM() function using Regular Expressions
    //========================================================
    GTSSearch.prototype.Trim = function(str) {
        if (str == null) { return ""; }
        if (this.GetType(str) == "object") { return ""; }
        return str.replace(/^\s*|\s*$/g, "");
    };

    //========================================================
    //   String.format gives you C# style string formatting
    //========================================================
    String.format = function() {
        if (arguments.length == 0) {
            throw ("String.format requires arguments");
        }
        var str = " " + arguments[0];
        for (var i = 1; i < arguments.length; i++) {
            var re = new RegExp('([^\\{]{1})(\\{' + (i - 1) + '\\}(?!\\}))', 'gm');
            str = str.replace(re, '\$1' + arguments[i]);
        }
        str = str.replace(new RegExp('\\{\\{', 'gm'), "{");
        str = str.replace(new RegExp('\\}\\}', 'gm'), "}");
        return str.substring(1);
    };

    //========================================================
    //  Shorthand for document.GetElementById
    //========================================================
    GTSSearch.prototype.gE = function(objId) {
        if (document.getElementById(objId)) {
            return document.getElementById(objId);
        }
        return null;
    };

    //========================================================
    //  SuggestDown
    //  Called OnKeyDown in target Text Box
    //========================================================
    GTSSearch.prototype.SuggestDown = function(e, ele) {

        with (this) {

            if (gE(alertID).style.display == "block") {
                return false;
            }
            var val = ele.value;

            if (window.event) {
                keynum = e.keyCode;
            }
            else if (e.which) {
                keynum = e.which;
            }
            switch (keynum) {
                case 13: // enter key
                   if (gE(suggestID).style.display == "block") {
                        if (CurrentSuggestIndex() > -1) {
                            AddSuggest(CurrentSuggestIndex());
                            StopProcessingEvents(e);
                            return false;
                        }
                    }
                    if (validateGTSSearch())
                    {
                       submitGTSSearch();                       
                    }
                    
                    break;

                case 27: // escape
                    CloseSuggest();
                    ele.value = val;
                    return false;
                    break;
                default:
                    return true;
                    break;
            }
        }
    };

    //========================================================
    //  SuggestUp
    //  Called OnKeyUp in target Text Box
    //========================================================
    GTSSearch.prototype.SuggestUp = function(e, ele) {
        with (this) {
        ele.value = ReplacePotentiallyDangerous(ele);
            if (gE(alertID).style.display == "block") {
               return false;
            }
            
            var val = ele.value;
            if (window.event) {
                keynum = e.keyCode;
            }
            else if (e.which) {
                keynum = e.which;
            }

            switch (keynum) {
                case 13: // enter key
                    if (gE(suggestID).style.display == "block") {
                        CloseSuggest();
                        StopProcessingEvents(e);
                        return false;
                    }
                    return true;
                    break;
                case 27: // escape
                    CloseSuggest();
                    ele.value = val;
                    return false;
                    break;
                case 40:
                    SuggestSelect(CurrentSuggestIndex() + 1);
                    break;
                case 38:
                    SuggestSelect(CurrentSuggestIndex() - 1);
                    break;
                default:
                 
                    if (Trim(ele.value).length > 1) {

                        var searchTerm = Trim(ele.value);
                        
                        //CloseSuggest();
                        var Query = String.format("{0}?q={1}&l={2}&p={3}&m={4}&n={5}&d={6}&c={7}",
                                            jsonSRC,
                                            searchTerm,
                                            levelLimit,
                                            parentRegionID,
                                            maxSuggestReturns,
                                            jsonResponseName,
                                            ResponseDelegate,
                                            caching);
                        CallJSON(Query);
                    }
                    else {
                        CloseSuggest();
                    }
                    break;
            }
        }
    };
    //========================================================
    //  Removes dangerous characters(<,>,etc.)
    //========================================================
    function ReplacePotentiallyDangerous(ele)
    {
        var re = /[^a-z0-9\s-,()\/\:'\&]/gi;
        return ele.value.replace(re, '');
    }

    //========================================================
    //  Stops processing Events
    //========================================================
    GTSSearch.prototype.StopProcessingEvents = function(e) {
        if (e && e.preventDefault) {
            e.preventDefault();
        }
        else if (window.event && window.event.returnValue) {
            window.eventReturnValue = false;
        }
    };


    //========================================================
    //  CurrentSuggestIndex
    //  Used for Suggest functionality
    //========================================================
    GTSSearch.prototype.CurrentSuggestIndex = function() {
        with (this) {
            var LIS = gE(suggestID).getElementsByTagName("li");
            var T = -1;
            for (var x = 0; x < LIS.length; x++) {
                if (LIS[x].className == 'selected') {
                    T = x;
                    break;
                }
            }
            return T;
        }
    };

    //========================================================
    //  ScrollToItem
    //  Used for Suggest functionality
    //========================================================
    GTSSearch.prototype.ScrollToItem = function(elepos) {
        with (this) {
            var eleE = gE('ila' + elepos);
            var eleS = gE(suggestID);
            var Etop = eleE.offsetTop;
            var Stop = eleS.scrollTop;

            if (Etop < gE(suggestID).scrollTop) {
                gE(suggestID).scrollTop = Etop;
            }
            else if ((Etop + eleE.offsetHeight) > (Stop + eleS.offsetHeight)) {
                gE(suggestID).scrollTop = Etop - eleS.offsetHeight + eleE.offsetHeight;
            }
        }
    };

    //========================================================
    //  SuggestSelect
    //  Used for Suggest functionality
    //========================================================
    GTSSearch.prototype.SuggestSelect = function(num) {
        with (this) {
            var LIS = gE(suggestID).getElementsByTagName("li");
            var item = null;

            for (var x = 0; x < LIS.length; x++) {
                if (x == num) {
                    LIS[x].className = 'selected';
                    item = x;
                }
                else {
                    LIS[x].className = 'non';
                }
            }
            if (item == null) {
                if (num > LIS.length - 1) {
                    item = LIS.length - 1;
                    LIS[item].className = 'selected';
                }
                else {
                    item = 0;
                }
            }

            if (item > 0) {
                ScrollToItem(item);
               
            }
        }
    };





    //========================================================
    //  ShowSuggest
    //  Reads JSON response into to be visible DIV for selection
    //========================================================
    GTSSearch.prototype.ShowSuggest = function() {
        with (this) {
            eval("var SR = " + jsonResponseName + ".suggestresponse;");
            var Formatting = "\
    <li class='non' id='ila{1}' name='{2}' onclick=\"{6}.gE('txtSearch').focus();{6}.AddSuggest({1});\" onmouseover=\"{6}.SuggestSelect({1});\">\
        <span class='display'>{3}</span>\
    </li>";
            var Validation = "\
    <li class='val' id='ila{1}' name='{2}' >\
        <a onclick=\"{6}.gE('txtSearch').focus();{6}.AddSuggest({1});{6}.searchAlertClose();\">{3}</a>\
    </li>";
            if(SR.matches != undefined){
                if (SR.success == "true") {
                    var responseHTML = "<ul>";

                    var responseVal = "<p>" + errMsgDYM + "</p><ul>";

                    var Matches = new Array();
                    if (SR.matches.length == undefined) // there is only one
                    {
                        Matches.push(SR.matches);
                        var txt = Matches[0].id;
    //                    var txt = Matches[0].display;

    //                    for(a in SR.matches)
    //                    {
    //                        alert(a + "=" + SR.matches[a]);
    //                    }

                        txt = txt.toUpperCase();
                        txt = txt.replace("<B>", "");
                        txt = txt.replace("</B>", "");
                        txt = txt.replace(/,/g, "");
                        txt = txt.replace(/\s+/g, "-");
                        gE("RegionId").value = txt;
                    //    alert("saving1 " + txt + " to RegionId");
                    }
                    else {
                        Matches = SR.matches;
                    }

                    for (var x = 0; x < Matches.length; x++) {
                        responseHTML += String.format(Formatting,
                                    Matches[x].name,
                                    x,
                                    Matches[x].id,
                                    //Matches[x].display.replace('-USA', '').replace('-', ' ').replace('-', ' ').replace('-', ' ').replace('-', ' '),
                                    Matches[x].display.replace('-', ' ').replace('-', ' ').replace('-', ' ').replace('-', ' '),
                                    Matches[x].priority,
                                    Matches[x].level,
                                    ObjectInstanceName);
                        //alert("mId:" + Matches[x].id);
                        responseVal += String.format(Validation,
                                    Matches[x].name,
                                    x,
                                    Matches[x].id,
                                    Matches[x].display,
                                    Matches[x].priority,
                                    Matches[x].level,
                                    ObjectInstanceName);

                    }

                    if (gE(suggestID).style.display != "block") {
                        gE(suggestID).style.display = "block";
                    }

                    searchAlertClose();
                    
                    responseHTML += "</ul>";

                    gE(suggestID).innerHTML = responseHTML;

                    responseVal += "</ul><div id='search-alert-close'><a href='javascript:AJC.searchAlertClose();'>close</a>";
                    gE(alertMsgID).innerHTML = responseVal;

                    if (Matches.length == undefined) {
                        gE("matchCount").value = 0;
                    }
                    else {
                        gE("matchCount").value = Matches.length;
                    }
                    ToggleSelects(gE(suggestID), "hidden"); // Should appear AFTER content is written

                }
                else {
                    gE("matchCount").value = 0;
                    CloseSuggest();
                }
            
            }
            else
            {   gE("matchCount").value = 0; CloseSuggest();}
            
        }
    };

    //========================================================
    //  AddSuggest
    //  Used for Suggest functionality
    //========================================================
    GTSSearch.prototype.AddSuggest = function(index) {
        with (this) {
            var CityName = gE("ila" + index).getElementsByTagName("span")[0].innerHTML.replace(/<[^>]+>/g, "").replace(/\s\/\s/g, "/");
            var RegionId = gE("ila" + index).getAttribute('name');
            //alert("Regionid: " + RegionId);
            gE("txtSearch").value = CityName.toUpperCase();
            gE("RegionId").value = RegionId;

            gE("matchCount").value = 1;
            CloseSuggest();
        }
    };
    
    //========================================================
    //  ToggleSelects
    //  Hides Select elements that may overlap open
    //  Suggest box
    //========================================================
    GTSSearch.prototype.ToggleSelects = function(TargetObject, Visibility) {
        if (Visibility == "") {
            this.RestoreSelects();
            return;
        }

        if (!document.all) { return; }                                  // ie specific

        var TRO = new this.RecurseOffset(TargetObject);
        var MatchLeft = TRO.offsetLeft;
        var MatchTop = TRO.offsetTop;
        var MatchRight = MatchLeft + TRO.offsetWidth;
        var MatchBottom = MatchTop + TRO.offsetHeight;

        var SelectCollection = document.getElementsByTagName("select");

        for (var s = 0; s < SelectCollection.length; s++) {
            var SelectObject = SelectCollection[s];

            var SRO = new this.RecurseOffset(SelectObject);

            var SelectLeft = SRO.offsetLeft;
            var SelectTop = SRO.offsetTop;
            var SelectRight = SelectLeft + SRO.offsetWidth;
            var SelectBottom = SelectTop + SRO.offsetHeight;

            //====================== detect collision

            if (
                (SelectRight > MatchLeft) &&
                (SelectBottom > MatchTop) &&
                (SelectLeft < MatchRight) &&
                (SelectTop < MatchBottom)
                ) {
                SelectObject.style.visibility = "hidden";
                //return;
            }

            //======================= if position of select is not detectible, hide to be sure
            if ((SelectLeft == 0) && (SelectTop == 0)) {
                SelectObject.style.visibility = "hidden";
                //return;
            }
        }
    };

    //========================================================
    //   RestoreSelects
    //   Restores selects on page none by menu
    //========================================================
    GTSSearch.prototype.RestoreSelects = function() {
        if (!document.all) { return; } // no need in other than IE
        var SelectCollection = document.getElementsByTagName("select");
        for (var s = 0; s < SelectCollection.length; s++) {
            SelectCollection[s].style.visibility = "visible";
        }
    };

    //========================================================
    //  RecurseOffset(object)
    //  returns true cross-browser offsetLeft and offsetTop of an object.
    //  offsetWidth and offsetHeight are included for 
    //  ease of use.
    //--------------------------------------------------------
    //  ex. var Left = RecurseOffset(obj).offsetLeft;
    //========================================================
    GTSSearch.prototype.RecurseOffset = function(obj) {
        if (My.GetType(obj) == "string") {
            if (My.gE(obj) == null) {
                return new Object();
            }
            else {
                obj = My.gE(obj);
            }
        }
        var ROO = new RecurseOffsetObject(obj);
        var Offsets = new Object();
        Offsets.offsetLeft = ROO.GetOffsetLeft();
        Offsets.offsetTop = ROO.GetOffsetTop();
        Offsets.offsetWidth = ROO.GetOffsetWidth();
        Offsets.offsetHeight = ROO.GetOffsetHeight();

        return Offsets;
    };

    //========================================================
    //  CloseSuggest
    //  Closes suggest box and untoggles selects
    //========================================================
    GTSSearch.prototype.CloseSuggest = function() {
        with (this) {
            gE(suggestID).style.display = "none";
            ToggleSelects(gE(suggestID), "");
        }
    };


    //========================================================
    //  searchAlertClose
    //========================================================
    GTSSearch.prototype.searchAlertClose = function() {
        with (this) {
            if (gE(suggestID).style.display == "none") {
                ToggleSelects(gE(suggestID), "");
            }
            gE(alertID).style.display = "none";
        }
    };

    //========================================================
    //  Calls JSON data into DOM
    //========================================================
    GTSSearch.prototype.CallJSON = function(url) {
        var DOMHead = document.getElementsByTagName("head")[0];
        var DOMScript = document.createElement('script');
        DOMScript.type = 'text/javascript';
        DOMScript.src = url;
        DOMHead.appendChild(DOMScript);
    };

    this.Init(); // call constructor
}


//========================================================
//  setCheckedValue
//  Used to default set a radio button to checked state
//========================================================
function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}


//========================================================
//  FoeSearch - used for clicking search examples 
//  below Sales Search Text input
//========================================================
function foeSearch(string)
{
    var theForm = document.forms['gts-search'];
    theForm.txtSearch.value = string;
}

 AJC.jsonSRC = "http://homes.ajchomefinder.com/JSONSuggestService.aspx";
 AJC.searchType = "for-sale";
 AJC.resultsUrl = "http://homes.ajchomefinder.com/";
 AJC.searchType ="for-sale";