var FDS = new GTSSearch("FDS");

/*
================================================================
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.inputElementId = ""
    this.jsonResponseName = "JsonResponse";
    this.consumer = ""; 
    this.jsonSRC = "";
    this.levelLimit = "";
    this.parentRegionID = "";
    this.caching = 15;
    this.suggestID = "suggest";
    this.maxSuggestReturns = 10;
    this.searchType = "For_Sale";
    this.resultsUrl = "http://frontdoor.com/";
    this.alertID = "search-alert";
    this.alertMsgID = "search-alert-message";
    this.errMsgLTS = "Please enter a location of at least 2 characters";
    this.errMsgNM = "<p>Your search for <b>\"[location]\"</b> could not be found please try another search                       term. </p><p>Example: New York, NY</p>";
    this.errMsgDYM = "There were multiple location matches found. Did you mean one of the following?";
    this.ResponseDelegate = ObjectInstanceName + ".ShowSuggest"; // self referencing object method call
    this.textlocation = "";
    this.iszip = false;

    var My = this;

    //========================================================
    //  Search Page functions - submitGTSSearch
    //========================================================
    GTSSearch.prototype.submitGTSSearch = function(theForm) {
        with (this) {

            //alert("in submitGTSSearch. consumer=" + consumer);

            if (!validateGTSSearch()) {
                return false;
            }
            //alert('after validateGTSSearch');
            if (consumer == "SMsearchbar") {
               RemoveCookie("MapViewState");
                searchType = "For_Sale";
                var x

                var strPropertyType = gE("search_propertytype1").innerHTML;
                strPropertyType = strPropertyType.toUpperCase();
                x = strPropertyType.indexOf(">");
                strPropertyType = strPropertyType.substring(x + 1, strPropertyType.length)
                strPropertyType = strPropertyType.replace("</SPAN>", "")

                var strBedrooms = gE("search_bedrooms1").innerHTML;
                strBedrooms = strBedrooms.toUpperCase();
                x = strBedrooms.indexOf(">");
                strBedrooms = strBedrooms.substring(x + 1, strBedrooms.length)
                strBedrooms = strBedrooms.replace("</SPAN>", "")

                var strBathrooms = gE("search_bathrooms1").innerHTML;
                strBathrooms = strBathrooms.toUpperCase();
                x = strBathrooms.indexOf(">");
                strBathrooms = strBathrooms.substring(x + 1, strBathrooms.length)
                strBathrooms = strBathrooms.replace("</SPAN>", "")

                var minPrice = gE("search_pricemin1").innerHTML;
                minPrice = minPrice.toUpperCase();
                x = minPrice.indexOf(">");
                minPrice = minPrice.substring(x + 1, minPrice.length)
                minPrice = minPrice.replace("</SPAN>", "")
                if(minPrice.toString().toLowerCase().indexOf('million') > -1) {minPrice = minPrice.substring(0,1) + "000000";}                

                var maxPrice = gE("search_pricemax1").innerHTML;
                maxPrice = maxPrice.toUpperCase();
                x = maxPrice.indexOf(">");
                maxPrice = maxPrice.substring(x + 1, maxPrice.length)
                maxPrice = maxPrice.replace("</SPAN>", "")
                if(maxPrice.toString().toLowerCase().indexOf('million') > -1) {maxPrice = maxPrice.substring(0,1) + "000000";}

                //alert("strBedrooms=" + strBedrooms + " strBathrooms=" + strBathrooms);
                //alert("minPrice=" + minPrice + " maxPrice=" + maxPrice);

                if (strBedrooms.trim() == "ANY") { strBedrooms = ""; }
                if (strBathrooms.trim() == "ANY") { strBathrooms = ""; }
                if (strPropertyType.trim() == "ANY") { strPropertyType = ""; }
                if (minPrice.trim() == "ANY PRICE") { minPrice = ""; }
                if (maxPrice.trim() == "ANY PRICE") { maxPrice = ""; }

                strPropertyType = strPropertyType.replace(" ", "-");
                strPropertyType = strPropertyType.toUpperCase();
                minPrice = minPrice.replace(",", "").replace(",", "");
                maxPrice = maxPrice.replace(",", "").replace(",", "");

                var strPriceRange = "";
                
              
                if ((minPrice.trim() != "Any Price") && (maxPrice.trim() != "Any Price")) {
                    if ((minPrice.trim() != "") && (maxPrice.trim() != "")) {
                        strPriceRange = minPrice + "-" + maxPrice;
                    }
                    else{
                        if(minPrice.trim() == "" && maxPrice.trim() != "")
                        {
                             strPriceRange = "0" + "-" + maxPrice;
                        }
                        else if(minPrice.trim() != "" && maxPrice.trim() == "")
                        {
                                 strPriceRange = minPrice + "-" + "999999999";
                        }
                        
                    }
                }

                // Build refinements string
                var strRefinements = "";
                if (strPriceRange.length > 0) { strRefinements += strPriceRange + "_price/"; }    
                if (strBedrooms.length > 0) { strRefinements += strBedrooms + "_beds/"; }
                if (strBathrooms.length > 0) { strRefinements += strBathrooms + "_baths/"; }
                if (strPropertyType.length > 0) { strRefinements += strPropertyType + "_type/"; }
                // Do we need an extension?
                //                var strExtension = ""
                //                var strSalesType = gE('SalesType').value;
                //                if (strSalesType == "foreclosures") {
                //                    strExtension = "F_foreclosures"
                //                }

                //                if (strSalesType == "newconstruction") {
                //                    strExtension = "N_newhomes"
                //                }
            }

            //var strLocation = gE('txtSearch').value;
//            var strLocation = gE('sbRegionId').value;
//            if (strLocation == "") {
//                strLocation = gE('txtAboutPageSearch').value;
//            }
                var strLocation;
               if(gE('txtAboutPageSearch') == null)
               {
                    strLocation = gE('sbRegionId').value;
               }
               else
               {
                    strLocation = gE('txtAboutPageSearch').value;
               }
            //alert('strLocation=' + strLocation);

            if (strLocation.length > 0) {
                if (consumer == "SMsearchbar") {

                    if (strLocation.length > 2) {
                        if (strLocation.substring(strLocation.length - 3) != 'USA') {
                            if (strLocation.substring(strLocation.length - 1) == '-' || strLocation.substring(strLocation.length - 1) == ',') {
                                strLocation += 'USA';
                            }
                            else {
                                strLocation += ', USA';
                            }
                        }
                    }

                    //                  strLocation = strLocation.replace(",", "-").replace(",", "-").replace(",", "-");
                    strLocation = strLocation.replace(", ", "-");

                    strLocation = strLocation.replace(", ", ",");

                    strLocation = strLocation.replace(" ", "_");


                    strLocation = strLocation.replace("-USA", ",USA");
                    //Captalizing the City Name.
                    var strLocs = strLocation.split("-");
                    if (strLocs.length > 2) {
                        for (var i = 0; i < strLocs.length - 2; i++) {
                            strLocs[i] = CapFirstLetter(strLocs[i]);
                        }
                        strLocation = strLocs.join("-");
                    }
                    var strRedirect = resultsUrl + searchType + "/" + strLocation;
                    if (strRefinements.length > 0) { strRedirect += "/" + strRefinements }
                    // if (strExtension.length > 0) { strRedirect += "/" + strExtension }
                    // this will fail for neighborhoods and two word cities.
                    // strRedirect = strRedirect.replace("//", "/");
                    //strRedirect = strRedirect.replace("-", ",").replace("-", ",").replace("-", ",");
                }
                else if (consumer == 'LocationModule') {
                    //Remove cookie so map won't show up by default
                    
                    RemoveCookie("MapViewState");
                    
                    var strURL = WebRoot + "Controls/AjaxCalls/SearchBar.aspx?SearchType=sale&txtSearch=" + strLocation;
                    
                    LocationModule(strURL);
                    //OOps_lp(strURL);

                    OmReportLocationSearchModule(this, strLocation, 'locationmodule');
                    document.getElementById("results_search_submit").style.display = "none";
                    // var strRedirect = resultsUrl + "for_sale/" + strLocation;
                    // window.location = strRedirect;                                        
                }
                else {
                    if (strLocation.length > 2) {
                        if (strLocation.substring(strLocation.length - 3) != 'USA') {
                            if (strLocation.substring(strLocation.length - 1) == '-' || strLocation.substring(strLocation.length - 1) == ',') {
                                strLocation += 'USA';
                            }
                            else {
                                strLocation += '-USA';
                            }
                        }
                    }
                    strLocation = strLocation.replace(" ", "-").replace(" ", "-").replace(" ", "-");
                    strLocation = strLocation.replace(",", "-").replace(",", "-").replace(",", "-");
                    strLocation = strLocation.replace("_", "-").replace("_", "-").replace("_", "-");
                    //Captalizing the City Name.
                    var strLocs = strLocation.split("-");
                    if (strLocs.length > 2) {
                        for (var i = 0; i < strLocs.length - 2; i++) {
                            strLocs[i] = CapFirstLetter(strLocs[i]);
                        }
                        strLocation = strLocs.join("-");
                       
                    }
                    var strRedirect = resultsUrl + "City-Guide/" + strLocation;
                }
                if (consumer != 'LocationModule') {
                    //alert("Redirecting to: " + strRedirect);
                    window.location = strRedirect;
                }
            }
        }
    }

    //========================================================
    //  validateGTSSearch Location
    //========================================================
    GTSSearch.prototype.validateGTSSearch = function(origin) {
        with (this) {
            var txt = gE(FDS.inputElementId).value;
            var regionid = gE('sbRegionId').value;

            CloseSuggest();

            if (txt.toUpperCase() == "SEARCH BY CITY, STATE") {
                //alert("Please enter a city name. E.g. New York, NY");
                OOps_lp("<p class='top'>Please enter a city/state or a zip code into the search field.  We recommend that you follow the following format:</p><ul><li>City, State (e.g. <a href=\"javascript:FoeSearch('San Francisco, CA');\">San Francisco, CA</a>)</li><li>Zip Code (e.g.  <a href=\"javascript:FoeSearch('89148');\">89148</a>)</li></ul>");
                return false;
            }

            if (txt.length == 0) {
                //alert("Please enter a city name. E.g. New York, NY");
                OOps_lp("<p class='top'>Please enter a city/state or a zip code into the search field.  We recommend that you follow the following format:</p><ul><li>City, State (e.g. <a href=\"javascript:FoeSearch('San Francisco, CA');\">San Francisco, CA</a>)</li><li>Zip Code (e.g.  <a href=\"javascript:FoeSearch('89148');\">89148</a>)</li></ul>");
                return false;
            }

            tmpRegionId = regionid.toUpperCase();
            tmpRegionId = tmpRegionId.replace("_", "-");

            // replace commas and spaces with hyphens.
            txt = txt.toUpperCase();
            txt = txt.replace(/,/g, "");
            txt = txt.replace(/\s+/g, "-");

            var pos = tmpRegionId.indexOf(txt)

            //alert("txt=" + txt + " regionid=" + tmpRegionId + " pos=" + pos);
    
            if (consumer == 'LocationModule') {
                // is it a zip code?
                if (isZip(txt)) {
                    //alert(txt + ' is a zip code.');
                    OmReportLocationSearchModule(this, txt, 'locationmodule');  
                    FDS.iszip = true;
                    var strURL = WebRoot + "controls/AjaxCalls/GetRedirectFromZip.aspx?zip=" + txt;
                    LocationModule(strURL);  
                    return false;                  
                }
            }

            if (pos >= 0) {
                return true;
            }

            if (txt.length < 2) {                       // Too cold.
                alert("errMsgLTS: " + errMsgLTS);
                return false;
            }


            if (consumer != 'LocationModule') 
            {
                var matchCount = gE('matchCount').value; 
                if (matchCount == 0) {                      // Still too cold.
                    OOps_lp(errMsgNM.replace('[location]', gE(FDS.inputElementId).value));
                    return false;
                } 
                else if (matchCount > 1) {                  // Much too hot. 
                    gE(suggestID).style.display = "none";
                    if(gE(alertID))
                    {
                       gE(alertID).style.display = "block";
                       gE(alertID).focus();
                    }
                    return false;
                }
                else {                                      // Just right!
                    return true;
                }
            }
            else {                                      // Just right!
                    return true;
                }
        }
    }

    //========================================================
    //  Initialize Object, pseudo constructor
    //  Throw JSON Response up into mem.
    //========================================================
    GTSSearch.prototype.Init = function() {
        with (this) {
            eval("var " + jsonResponseName + " = null;");
        }
    };

    //========================================================
    //  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( 'result_wrapper' == e.target.getAttribute( 'id') ){
        return; // give control to HTML element scrollbars in IE
    }
        if (e.target.nodeType == 3) { e.target = target.parentNode }        // Safari bug?


        if (e.target.parentNode.id == undefined) {                          // if the parentNode is undefined,
            FDS.gE(FDS.suggestID).style.display = "none";      // they're off the page.
            FDS.searchAlertClose();
        }
        else {
            if (e.target.parentNode.id == "search-alert") {                 // header text
            }
            else if (e.target.parentNode.id == "search-alert-message") {    // close button
            }
//            else if (FDS.gE("More").style.display != null && FDS.gE("More").style.display == "block") {
//                if (e.target.parentNode.innerHTML.indexOf('Results.aspx') == -1) {
//                    gECloseNearCities('More', 'nearestcities_more_open', 'none');
//                }
//            }
//            else if (FDS.gE("MoreNei").style.display != null && FDS.gE("MoreNei").style.display == "block") {
//                if (e.target.parentNode.innerHTML.indexOf('Results.aspx') == -1) {
//                    gECloseNearCities('MoreNei', 'nearestneighborhoods_more_open', 'none');
//                }
//            }
            else if (e.target.parentNode.id == "nearestcities_more_open") {
                gEOpenNearCities('More', 'nearestcities_more_open', 'block');
            }
            else if (e.target.parentNode.id == "nearestneighborhoods_more_open") {
                gEOpenNearCities('MoreNei', 'nearestneighborhoods_more_open', 'block');
            }
            else if (e.target.parentNode.id == "") {                        // ile spans.
            }
            else if (e.target.parentNode.id.substring(0, 3) == "ila") {     // on the location text
                FDS.AddSuggest(FDS.CurrentSuggestIndex());
            }
            else if (e.target.parentNode.id == FDS.suggestID) {                 // a location is highlighted,
                FDS.AddSuggest(FDS.CurrentSuggestIndex());                  // but the click is between the cracks.
            }
            else {
                FDS.gE(FDS.suggestID).style.display = "none";
                FDS.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) {

            var val = ele.value;

            //alert("in sd");
            if (gE(alertID) != null) {
                if (gE(alertID).style.display == "block") {
                    return false;
                }
            }

            if (window.event) {
                keynum = e.keyCode;
            }
            else if (e.which) {
                keynum = e.which;
            }
            switch (keynum) {
                case 13: // enter key 
                    if (gE(suggestID) != null) {
                        if (gE(suggestID).style.display == "block") {
                            if (CurrentSuggestIndex() > -1) {
                                AddSuggest(CurrentSuggestIndex());
                                StopProcessingEvents(e);
                                return false;
                            }
                        }
                    }
                    submitGTSSearch(ele.form);
                    // validateGTSSearch();
                    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) {
            if (gE(alertID) != null)
            {
                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) != null)
                    {
                        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);
                        FDS.locationfield = searchTerm;
                        //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;
            }
        }
    };

    //========================================================
    //  Stops processing Events
    //========================================================
    GTSSearch.prototype.StopProcessingEvents = function(e) {
        //alert('in StopProcessingEvents');
        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("div");
            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;
            }
        }
    };
 
    //========================================================
    //  OOps
    //========================================================
   // function OOps(strMessage, strClassName)
    GTSSearch.prototype.OOps_lp = function(strMessage, strClassName) 
    {
        window.setTimeout(function()
        {
            if (strClassName == undefined)
            {
                strClassName = "oops_wrapper clearfix";
            }
            if (BarStatus.value != BevtQueue)
            {
                gE("txtLandingPageSearch").blur(); // cause the sales search bar to close
                window.setTimeout(function()
                {
                    OOps_lp(strMessage, strClassName); // recall oops after it's closed
                },300);
                return;
            }
                CloseSuggest();
                ToggleSelects("hidden");
                gE("oops_wrapper_lp").style.display = "block";
                gE("oops_wrapper_lp").className = strClassName;
                gE("oops_text_lp").innerHTML = strMessage;
        },300);
    }
    
    GTSSearch.prototype.OOpsClose = function()
    {
        if (gE(SuggestId).style.display == "none")
        {
            ToggleSelects("visible");
        }
        gE("oops_wrapper_lp").style.display = "none";
        gE("txtAboutPageSearch").value = FDS.locationfield;
    }
    
    
    GTSSearch.prototype.FoeSearch_lp = function(strMessage) 
    {
      with (this) {
        window.setTimeout(function()
        {
          OOpsClose();
          gE("txtAboutPageSearch").focus();
          gE("txtAboutPageSearch").value = strMessage;
        },300);
      }
    }
    //========================================================
    //  SuggestSelect
    //  Used for Suggest functionality
    //========================================================
    GTSSearch.prototype.SuggestSelect = function(num) {
        with (this) {
            var LIS = gE(suggestID).getElementsByTagName("div");
            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 = "\
    <div class='non' id='ila{1}' name='{2}' onclick=\"{6}.gE('{7}').focus();{6}.AddSuggest({1});\" onmouseover=\"{6}.SuggestSelect({1});\">\
        <span class='display'>{3}</span>\
    </div>";
            var Validation = "\
    <div class='val' id='ila{1}' name='{2}' >\
        <a onclick=\"{6}.gE('{7}').focus();{6}.AddSuggest({1});{6}.searchAlertClose();\">{3}</a>\
    </div>";

            if (SR.success == "true") {
                var responseHTML = "";

                var responseVal = "<p>" + errMsgDYM + "</p>";

                var Matches = new Array();
                if (SR.matches.length == undefined) // there is only one
                {
                    Matches.push(SR.matches);
                    var txt = Matches[0].display;
                    txt = txt.toUpperCase();
                    txt = txt.replace("<B>", "");
                    txt = txt.replace("</B>", "");
                    txt = txt.replace(/,/g, "");
                    txt = txt.replace(/\s+/g, "-");
                    gE("sbRegionId").value = txt;
                    //alert("saving " + 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('-', ' ').replace('-', ' ').replace('-', ' ').replace('-', ' '),
                                Matches[x].priority,
                                Matches[x].level,
                                ObjectInstanceName,
                                FDS.inputElementId);
                    //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,
                                FDS.inputElementId);

                }

                if (gE(suggestID).style.display != "block") {
                    gE(suggestID).style.display = "block";
                }

                searchAlertClose();

                gE(suggestID).innerHTML = responseHTML;

                responseVal += "<div id='search-alert-close'><a href='javascript:FDS.searchAlertClose();'>close</a>";
                if(gE(alertMsgID))
                {
                    gE(alertMsgID).innerHTML = responseVal;
                }

                if (SR.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();
            }
        }
    };

    //========================================================
    //  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(FDS.inputElementId).value = CityName.toUpperCase();            
            FDS.locationfield = gE(FDS.inputElementId).value;     
            gE("sbRegionId").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), "");
        }
    };


    //========================================================
    //  searchAlert
    //========================================================
    //GTSSearch.prototype.searchAlert = function(strMessage, strClassName) {
    //window.setTimeout(function() {
    //with (this) {
    //CloseSuggest();
    //ToggleSelects(gE(suggestID), "hidden");
    //gE(alertID).style.display = "block";
    //gE(alertID).className = strClassName;
    //gE(alertMsgID).innerHTML = strMessage;
    //}
    //}, 300);
    //};

    //========================================================
    //  searchAlertClose
    //========================================================
    GTSSearch.prototype.searchAlertClose = function() {
        with (this) {
            if (gE(suggestID) != null)
            {
                if (gE(suggestID).style.display == "none") {
                    ToggleSelects(gE(suggestID), "");
                }
            }
            if (gE(alertID) != null) 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;
        }
    }
}


//========================================================
//  RecurseOffsetObject(object) used in RecurseOffset(object)
//  This can be called directly
//========================================================
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.prototype.trim = function() {
    a = this.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
};

     
GTSSearch.prototype.LocationModule = function(strURL) {
          $AJAX.GetForDelegate( 
                FDS.LocationModule_DELEGATE, 
                strURL,
                true
          );      
    };

GTSSearch.prototype.LocationModule_DELEGATE = function(ajaxResponse)
    {
       if (ajaxResponse.indexOf("var doEval = true;") > -1) // flag indicating we should evaluate the response
        {
          ajaxResponse = ajaxResponse.replace("OOps(", "FDS.OOps_lp(");
          ajaxResponse = ajaxResponse.replace(/FoeSearch\(/g, "FDS.FoeSearch_lp\(");
          eval(ajaxResponse);
        }     
    };

function repositionAd() {
    var leftRailHeight = $('#global_content_left').height();
    var centerRailHeight = $('#center-rail').height();
    var rightRail = gE('right_rail');
    
    if( leftRailHeight > centerRailHeight){
        rightRail.style.height = leftRailHeight+'px';
    }else{
        if(gE('pagination_results') != null){
            rightRail.style.height = (centerRailHeight - 85)+'px';
        }else{
            rightRail.style.height = (centerRailHeight - 59)+'px';
        }
    }
}