// ----------------------------------------------------------------------------------------------
// --------------------------------- AUTO COMPLETE ARRAY ----------------------------------------
// ----------------------------------------------------------------------------------------------

var AutoCompleteDataControl = {

    getCityState: function(){
        var results = [];
        var curBrand = getCurrSite().toLowerCase();
        for (var i=0; i < communities[curBrand].length; i++) {
            results.unshift([communities[curBrand][i].stateName, null, null]);
            if (communities[curBrand][i].cities && communities[curBrand][i].cities.length) {
                for (var k=0; k < communities[curBrand][i].cities.length; k++) results.unshift([communities[curBrand][i].cities[k].city, communities[curBrand][i].stateName]);
            }
        }
        return results;
    },

    getMatchedCityState: function(sQuery){
        var sKey, sKeyIndex, sVal;
        var results = [];
        var curBrand = getCurrSite().toLowerCase();
        if(sQuery && sQuery.length > 0) {
            for (var i=0; i < communities[curBrand].length; i++) {
                sKey = communities[curBrand][i].stateName;
                sKeyIndex = encodeURI(sKey.toLowerCase()).indexOf(sQuery.toLowerCase());

                // Query found at the beginning of the key string for STARTSWITH - returns an array of arrays where STATE is index=0, ABBR is index=1
                if (sKeyIndex === 0) results.unshift([sKey, null,null]);

                if (communities[curBrand][i].cities && communities[curBrand][i].cities.length) {
                    for (var k=0; k < communities[curBrand][i].cities.length; k++){
                        sKey = communities[curBrand][i].cities[k].city;
                        sKeyIndex = encodeURI(sKey.toLowerCase()).indexOf(sQuery.toLowerCase());
                        if (sKeyIndex === 0) {
                            sVal = sKey + ', ' + communities[curBrand][i].stateName;
                            results.unshift([sVal, sKey, communities[curBrand][i].stateName]);
                        }
                    }
                }
            }
        }
        return results.sort(sortByReturnValue);
    },

    getCommunity: function(){
        var results = [];
        var curBrand = getCurrSite().toLowerCase();

        for (var i=0; i < communities[curBrand].length; i++){
            if (communities[curBrand][i].cities && communities[curBrand][i].cities.length) {
                for (var k=0; k < communities[curBrand][i].cities.length; k++) {
                    if (communities[curBrand][i].cities[k].communities && communities[curBrand][i].cities[k].communities.length) {
                        for (var m = 0; m < communities[curBrand][i].cities[k].communities.length; m++) results.push(communities[curBrand][i].cities[k].communities[m]  + ' in ' + communities[curBrand][i].cities[k].city + ', ' + communities[curBrand][i].stateName);
                    }
                }
            }
        }
        return results;
    },

    getMatchedCommunity: function(sQuery){
      var sKey, sKeyIndex1, sKeyIndex2, sVal, sQuery2;
      var results = []; 
      var matchesFound = 0;
      if(sQuery && sQuery.length > 0) {
            sQuery = decodeURI(sQuery); // to get real spaces, not %20
            sQuery2 = " " + sQuery;
            for (var i=0; i < communityNameA.length; i++) {
                sKey = communityNameA[i];
                sKeyIndex1 = sKey.toLowerCase().indexOf(sQuery.toLowerCase()); // first word match
                sKeyIndex2 = sKey.toLowerCase().indexOf(sQuery2.toLowerCase()); // next words match
                // Query found at the beginning of the key string for STARTSWITH - returns an array of arrays where STATE is index=0, ABBR is index=1
                if ((sKeyIndex1 === 0) || (sKeyIndex2 > 0)) {
                  results.unshift([communityNameA[i], communityNameA[i], communityAddressA[i]]);
                  matchesFound++;
                  //sKey = sKey + ' -- ' + communityAddressA[i];
                  //results.unshift([sKey,null, null]);
                }
            }
       }
       if (matchesFound == 0) {
         results.unshift([sQuery, "No Matches", ""]);
       }
       var res = document.getElementById("autoCompleteContainer");
       res.style.visibility = "visible";
       return results.sort(sortByReturnValue);
    },
    
    formatMatched: function(sKey, sQuery){
        var val = "";
        var sQuery2 = " " + sQuery;
        var sKeyIndex = sKey.toLowerCase().indexOf(sQuery.toLowerCase()); // for highlighting first word
        var sKeyIndex2 = sKey.toLowerCase().indexOf(sQuery2.toLowerCase()); // for highlighting other words, only before first comma
        if (sKeyIndex === 0) { // match in first word
          val = '<strong>' + sKey.substr(0,sQuery.length) + '</strong>';
        } else { // no match in first word
          val = sKey.substr(0,sQuery.length);
        }
        if (sKeyIndex2 < 0) { // no match in other words
            val = val + sKey.substr(sQuery.length);
        } else { // match in other words
          val = val + sKey.substring(sQuery.length,sKeyIndex2) + '<strong>' + sKey.substr(sKeyIndex2, sQuery2.length) + '</strong>';
          var sKey2 = sKey.substr(sKeyIndex2 + sQuery2.length);
          var sKeyIndex3 = sKey2.toLowerCase().indexOf(sQuery2.toLowerCase());
          if (sKeyIndex3 < 0) {
            val = val + sKey2;
          } else {
            val = val + sKey2.substring(0, sKeyIndex3) + '<strong>' + sKey2.substr(sKeyIndex3, sQuery2.length) + '</strong>';
            // the rest
            val = val + sKey2.substr(sKeyIndex3 + sQuery2.length);
          }
        }
        return val;
    }
}

function sortByReturnValue(a, b) {
    var x = a[0].toLowerCase();
    var y = b[0].toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

YAHOO.widget.AutoComplete.prototype.doBeforeSendQuery = function(sQuery) {
    if (sQuery.toLowerCase() == 'az') return 'Arizona';
    if (sQuery.toLowerCase() == 'ak') return 'Alaska';
    if (sQuery.toLowerCase() == 'ct') return 'Connecticut';
    if (sQuery.toLowerCase() == 'ga') return 'Georgia';
    if (sQuery.toLowerCase() == 'hi') return 'Hawaii';
    if (sQuery.toLowerCase() == 'ia') return 'Iowa';
    if (sQuery.toLowerCase() == 'ks') return 'Kansas';
    if (sQuery.toLowerCase() == 'ky') return 'Kentucky';
    if (sQuery.toLowerCase() == 'la') return 'Louisiana';
    if (sQuery.toLowerCase() == 'me') return 'Maine';
    if (sQuery.toLowerCase() == 'md') return 'Maryland';
    if (sQuery.toLowerCase() == 'mn') return 'Minnesota';
    if (sQuery.toLowerCase() == 'ms') return 'Mississippi';
    if (sQuery.toLowerCase() == 'mo') return 'Missouri';
    if (sQuery.toLowerCase() == 'mt') return 'Montana';
    if (sQuery.toLowerCase() == 'nv') return 'Nevada';
    if (sQuery.toLowerCase() == 'nh') return 'New%20H';
    if (sQuery.toLowerCase() == 'nj') return 'New%20Jersey';
    if (sQuery.toLowerCase() == 'nm') return 'New%20Mexico';
    if (sQuery.toLowerCase() == 'ny') return 'New%20York';
    if (sQuery.toLowerCase() == 'nc') return 'North%20Carolina';
    if (sQuery.toLowerCase() == 'nd') return 'North%20Dakota';
    if (sQuery.toLowerCase() == 'pa') return 'Pennsylvania';
    if (sQuery.toLowerCase() == 'ri') return 'Rhode%20Island';
    if (sQuery.toLowerCase() == 'sc') return 'South%20Carolina';
    if (sQuery.toLowerCase() == 'sd') return 'South%20Dakota';
    if (sQuery.toLowerCase() == 'tn') return 'Tennessee';
    if (sQuery.toLowerCase() == 'tx') return 'Texas';
    if (sQuery.toLowerCase() == 'vt') return 'Vermont';
    if (sQuery.toLowerCase() == 'va') return 'Virginia';
    if (sQuery.toLowerCase() == 'wv') return 'West%20Virginia';
	if (sQuery.toLowerCase() == 'phoenix') return 'Phoenix,%20AZ';
	if (sQuery.toLowerCase() == 'atlanta') return 'Atlanta,%20GA';
    return sQuery;
};

// ----------------------------------------------------------------------------------------------

 function   submitAutoCompleteEnter(myfield,e){
        var keycode;
        if (window.event) keycode = window.event.keyCode;
        else if (e) keycode = e.which;
        else return true;

        // if return key is pressed
        if (keycode == 13){
            //submitAutoComplete(true);
            submitCommunityName();
            return false;
        } else return true;
}

function submitAutoComplete(showError) { 
  var searchVal = document.getElementById('communityAutoCompleteSearch').value;
  if(searchVal != ''){
    for (var i=0; i < communityNameA.length; i++) {
      sKey = communityNameA[i]; 
      if (searchVal == sKey) {
        window.location = communityUrlA[i];
        return true;
      }
    } 
  }
  if (showError) {
    return false;
  }
  return true;
}

// COMMUNITY AUTO COMPLETE

YUE.onAvailable('communityAutoCompleteSearch',function() {
	YAHOO.example.ACJSFunction = new function(){

        // instantiate js function datasource
        this.oACDS = new YAHOO.widget.DS_JSFunction(AutoCompleteDataControl.getMatchedCommunity);
        this.oACDS.maxCacheEntries = 0;
        this.oACDS.responseSchema = {fields : ["name"]};

        // instantiate autocomplete
        this.oAutoComp = new YAHOO.widget.AutoComplete('communityAutoCompleteSearch','autoCompleteContainer', this.oACDS);
        //this.oAutoComp.prehighlightClassName = 'yui-ac-prehighlight'; // causes keyboard and mouse select independently!! looks like a YUI bug
        this.oAutoComp.highlightClassName  = 'yui-ac-highlight'; //added
        this.oAutoComp.typeAhead = false;
        this.oAutoComp.useShadow = true;
        this.oAutoComp.minQueryLength = 0;
        this.oAutoComp.maxResultsDisplayed = 10;
        this.oAutoComp.useIFrame = true;  
        this.oAutoComp.autoHighlight = true;  
        
        this.oAutoComp.textboxFocusEvent.subscribe(function(){
			    var sInputValue = YAHOO.util.Dom.get('communityAutoCompleteSearch').value;
			    if(sInputValue.length === 1) {
			      var oSelf = this;
			      setTimeout(function(){oSelf.sendQuery(sInputValue);},0);
			    }
		    });

        var myHandler = function(sType, aArgs) {
          var myAC = aArgs[0]; // reference back to the AC instance
          var elLI = aArgs[1]; // reference to the selected LI element
          var oData = aArgs[2]; // object literal of selected item's result data
          
          //alert(oData[0]);
        };
        
        this.oAutoComp.itemSelectEvent.subscribe(myHandler);
        
        
        
        this.oAutoComp.formatResult = function(oResultItem, sQuery) {
            var sKey = oResultItem[0];//alert(sKey);
            var sVal = ""; 
            if(oResultItem[1] != null && oResultItem[1] != ''){
                sKey = oResultItem[1];
                sVal = oResultItem[2];
            }
            //alert(sKey); alert(sVal); if (sVal == null) alert("sVal is null");
            var sMarkup = AutoCompleteDataControl.formatMatched(sKey, sQuery)  + ((sVal != '')?' in ' + sVal:'');
            return (sMarkup);
        };
        
        this.oAutoComp.doBeforeSendQuery = function(sQuery) {
          return sQuery;
        };
    };
});
