﻿var $LocationSuggestObject = function(){};

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Location Suggest JSON Begin
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Configuration Settings, use # notation for JQuery IDs
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$LocationSuggestObject.Json = function(type) 
{
    this.SuggestType=type;
    this.TextInputId = "#LocTerm";
    this.TextSEOId = "#LocSeo";
    this.DefaultText = $(this.TextInputId).val();
    this.TextSelectedDataId = "#LocLocationSuggested";
    this.ResponseContainerId = "#LocSuggestContainer";
    this.SubmitSearch = function(e)
    {
        window.alert("\"" + $(this.TextInputId).val() + "\" could not be found.");
        $LocSuggest.StopProcessingEvents(e);
    };
};

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  CloseSuggest
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$LocationSuggestObject.Json.prototype.CloseSuggest = function() 
{
    $($LocSuggest.ResponseContainerId).html("");
    $($LocSuggest.ResponseContainerId).removeClass("open closed");
    $($LocSuggest.ResponseContainerId).addClass("closed");
};
     
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  SuggestSelect
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$LocationSuggestObject.Json.prototype.SuggestSelect = function(num) 
{
    if (GetSearchType(CacheObject.SEOQueryRootPage) == "radius" || 
        GetSearchType(CacheObject.SEOQueryRootPage) == "map")
    {
       
        var NewId = $("#locsuggest-data-" + num).attr("name");
        var NewLocSEO = $("#locsuggest-data-" + num).attr("seo");
        var NewName = $("#locsuggest-data-" + num).val().replace(/<[^>]+?>/g,"");
            $LocSuggest.DefaultText = NewName;
            $(this.TextInputId).val(NewName);
            $(this.TextSelectedDataId).val(NewId);
            $(this.TextSEOId).val(NewLocSEO);
            
        var NewSEOQuery = CacheObject.SEOQueryRootPage.replace(CONST_RGX_LOCATION, String.Format("/$1/{0}$3", NewLocSEO));
        
        if (GetSearchType(CacheObject.SEOQueryRootPage) == "map")
        {
            var zoom = Map.getZoom();
            eval(String.Format("Map.setCenter(new GLatLng({0}), {1})", $("#locsuggest-data-" + num).attr("latlng"), zoom));
            var Bounds = Map.getBounds();
            var MapQuery = String.format("/{0}-{1}-{2}-{3}-map", 
                    (Math.round(Bounds.getNorthEast().lat()*1000000)/1000000), 
                    (Math.round(Bounds.getNorthEast().lng()*1000000)/1000000),
                    (Math.round(Bounds.getSouthWest().lat()*1000000)/1000000), 
                    (Math.round(Bounds.getSouthWest().lng()*1000000)/1000000));
            var rgx_alt = /(.+?)(\/[\(\)\-a-z0-9\.]+?\-(?:loc|map))(.*)/i;
            var NewSEOQuery = NewSEOQuery.replace(rgx_alt, "$1$3") + MapQuery;
        }
        
			window.location.href = NormalizeSEOQuery(NewSEOQuery);
            //ReloadListByMap(NormalizeSEOQuery(NewSEOQuery));
            
        //return;
    }
    else
    {
		var RegionIdsArray = new Array();
			RegionIdsArray.push($("#locsuggest-data-" + num).attr("name"));
        ActLocations("add", CacheObject.SEOQueryRootPage, RegionIdsArray);
    }

    $LocSuggest.CloseSuggest();
    window.setTimeout(function()
    {
        $($LocSuggest.TextInputId).val('');
        $($LocSuggest.TextInputId).trigger('focus');
    }, 100);
};

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  TotalSuggestMatches
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$LocationSuggestObject.Json.prototype.TotalSuggestMatches = function() 
{
    return $($LocSuggest.ResponseContainerId + " > div").length;
};

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  ScrollToItem
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$LocationSuggestObject.Json.prototype.ScrollToItem = function(elepos) 
{
    $($LocSuggest.ResponseContainerId + " > div").toggleClass("suggest-over", false);
    $("#locsuggest-data-" + elepos).toggleClass("suggest-over", true);
    
};
    
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  CurrentSuggestIndex of selection
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$LocationSuggestObject.Json.prototype.CurrentSuggestIndex = function() 
{
    var LIS = $($LocSuggest.ResponseContainerId + " > div");
    var T = -1;
    for (var x = 0; x < LIS.length; x++) 
    {
        if (LIS[x].className.indexOf("suggest-over") > -1) 
        {
            T = x;
            break;
        }
    }
    return T;
};
    
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Stops processing Events
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$LocationSuggestObject.Json.prototype.StopProcessingEvents = function(e) 
{
    if (e && e.preventDefault) 
    {
        e.preventDefault();
        return false;
    }
    else if (window.event && window.event.returnValue) 
    {
        window.eventReturnValue = false;
    }
};
    
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Events need to be built at load time AND reload time.
//  When the bar reloads, the DOM is reset on template based 
//  objects. This method is called after each refinement
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

$LocationSuggestObject.Json.prototype.HookupEvents = function()
{ 

//    $($LocSuggest.TextInputId).qtip({
//         style: { 
//            name: 'blue',
//            tip: 'bottomLeft',
//            width: 300
//         },
//          content: "Begin typing for auto suggestions.<br/>Enter key adds to search.",
//            position: {
//              corner: {
//                target: 'topRight',
//                tooltip: 'bottomLeft'
//              }
//            },
//            show: { 
//                delay: 500,
//                when: { event: 'mouseover' }
//            },
//            hide: { 
//                delay: 4000,
//                when: { event: 'inactive' }
//            }
//        });
        
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  OnKeyUp (event, suggest text object) Hookup Event
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    $($LocSuggest.TextInputId).keyup(function (e)
    {
    //````````````````````````````````````````````````````````````````
    // KeyNum = int indicating which key was pressed
    //````````````````````````````````````````````````````````````````
    var KeyNum;         
    if (window.event) // ie
    {
        KeyNum = e.keyCode;
    }
    else if (e.which) // all others
    {
        KeyNum = e.which;
    }
    
    switch (KeyNum)
    {
        //````````````````````````````````````````````````````````````````
        case 13: // enter key
            if ($($LocSuggest.ResponseContainerId).hasClass("open")) 
            {
                $LocSuggest.CloseSuggest();
                $LocSuggest.StopProcessingEvents(e);
                $.log("Enter Key Released");
                return false;
            }
            $.log("Enter Key Released");
            return false;
            break;
        //````````````````````````````````````````````````````````````````
        case 27: // escape key
            $LocSuggest.CloseSuggest();
            $.log("Escape Key Released");
            return false;
            break;
        //````````````````````````````````````````````````````````````````
        case 40: // arrow down key
            $LocSuggest.ScrollToItem($LocSuggest.CurrentSuggestIndex() + 1);
            $.log("Down Key Released: index " + parseFloat($LocSuggest.CurrentSuggestIndex() + 1));
            break;
        //````````````````````````````````````````````````````````````````
        case 38: // arrow up key
            $LocSuggest.ScrollToItem($LocSuggest.CurrentSuggestIndex() - 1);
            $.log("Up Key Released: index " + parseFloat($LocSuggest.CurrentSuggestIndex() - 1));
            break;
        //````````````````````````````````````````````````````````````````
        default: // any other key
            $.log(String.fromCharCode(KeyNum) + " Key Released (" + KeyNum + ")");
            if ($($LocSuggest.TextInputId).val().length > 1) 
            {
                
                var Url=String.Format("{0}Service.aspx?Channel={1}&SearchType={2}&MaxReturns=10&ReturnType=json&Term={3}", 
                                        CacheObject.SearchServiceRoot, 
                                        CacheObject.Channel, 
                                        $LocSuggest.SuggestType,
                                        $($LocSuggest.TextInputId).val());
                //window.location.href=Url;
                $.ajax({
                  type: "GET",
                  contentType: "application/json; charset=utf-8",
                  url: Url,
                  data: "{}",
                  dataType: "jsonp",
                  error: function(XMLHttpRequest, textStatus, errorThrown)
                  {
                    $LocSuggest.CloseSuggest();  
                    $.log("Json Error Message: error(" + errorThrown + ") \"" + textStatus + "\""); 
                  },
                  success: function(response) 
                  {
                      //````````````````````````````````````````````````````````````````
                      // Insert the returned HTML into the <div>.
                      // This method is called ASYNCHRONOUSLY
                      // so it is not aware of variables in it's scope.
                      //````````````````````````````````````````````````````````````````                   
                      var thishtml = "";
                      
                      if (response.group && 
                            response.group.length>0 && 
                            response.group[0].option &&
                            response.group[0].option.length > 0)
                      {
                            $("#LocationSuggested").val(""); // refresh if suggest opens
                            
                          for(var x=0;x<response.group[0].option.length;x++)
                          {
                              var template = "<div class=\"locsuggest-data\" id=\"locsuggest-data-{0}\" name=\"{1}\" onmousedown=\"$LocSuggest.SuggestSelect({2})\" onmouseover=\"$LocSuggest.ScrollToItem({3})\" seo=\"{4}\" latlng=\"{5}\">{6}</div>";
                              thishtml += String.Format(template, x, response.group[0].option[x].valuegid, x, x, response.group[0].option[x].valueseo, response.group[0].option[x].valuelatlng, response.group[0].option[x].title);
                          }
                          
                          //document.getElementById("SuggestJsonContainer").innerHTML = thishtml;
                          
                          $($LocSuggest.ResponseContainerId).html(thishtml);
                          $($LocSuggest.ResponseContainerId).toggleClass("open", true).toggleClass("closed", false);
                          //alert((new $LocationSuggestObject.Json()).ResponseContainerId);
                      }
                      else
                      {
                            $LocSuggest.CloseSuggest();  
                            $.log("Suggest Term \"" + $($LocSuggest.TextInputId).val() + "\" = No Matches");                        
                      }
                  }
                });
            }
            else 
            {
                $LocSuggest.CloseSuggest();
                $.log("Suggest Term \"" + $($LocSuggest.TextInputId).val() + "\" = Too Short"); 
            }
            break;
        }
    })


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  OnKeyDown (event, suggest text object) Hookup Event
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    $($LocSuggest.TextInputId).keydown(function (e)
    {
        //````````````````````````````````````````````````````````````````
        // KeyNum = int indicating which key was pressed
        //````````````````````````````````````````````````````````````````
        var KeyNum;         
        if (window.event) // ie
        {
            KeyNum = e.keyCode;
        }
        else if (e.which) // all others
        {
            KeyNum = e.which;
        }
        
        //````````````````````````````````````````````````````````````````
        // Switch KeyNum and respond on a per case basis
        //````````````````````````````````````````````````````````````````
        switch(KeyNum)
        {
            //````````````````````````````````````````````````````````````````
            case 13: // enter key
                if ($($LocSuggest.ResponseContainerId).hasClass("open")) 
                {
                    if ($LocSuggest.CurrentSuggestIndex() > -1) 
                    {
                        $LocSuggest.SuggestSelect($LocSuggest.CurrentSuggestIndex());
                        $LocSuggest.StopProcessingEvents(e);
                        $.log("Enter Key Down");
                        return false;
                    }
                    
                    if ($LocSuggest.TotalSuggestMatches() == 1)
                    {
                        $LocSuggest.SuggestSelect(0);
                        $.log("Enter Key Down");
                        return false;
                    }
                }
                $.log("Enter Key Down");
                $LocSuggest.SubmitSearch(e);
                return false;
                break;
            //````````````````````````````````````````````````````````````````
            case 27: // escape key
                $LocSuggest.CloseSuggest();
                $.log("Escape Key Down");
                return false;
                break;
            //````````````````````````````````````````````````````````````````
            case 40: // arrow down key
                $.log("Down Key Pressed");
                break;
            //````````````````````````````````````````````````````````````````
            case 38: // arrow up key
                $.log("Up Key Pressed");
                break;
            //````````````````````````````````````````````````````````````````
            default:
                $.log(String.fromCharCode(KeyNum) + " Key Down (" + KeyNum + ")");
                return true;
                break;
        }
    })


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Blur - Hookup Event
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    
    $($LocSuggest.TextInputId).blur(function()
    {
        $LocSuggest.CloseSuggest();
        if ($(this).val() == '')
        {
            $(this).val($LocSuggest.DefaultText);
            $(this).css('font-color', '#777');
        }
    })


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Focus - Hookup Event
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    $($LocSuggest.TextInputId).focus(function()
    {
        $LocSuggest.CloseSuggest();
        if ($(this).val() == $LocSuggest.DefaultText)
        {
            $(this).val('');
            $(this).css('font-color', '#000');
        }
    })

};

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Hookup Events & Globalize It
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var $LocSuggest;

function SetUpLocationSuggest()
{
    $LocSuggest = new $LocationSuggestObject.Json('Suggest');
    $LocSuggest.HookupEvents();
    $($LocSuggest.TextInputId).trigger('blur'); 
}

$(function()
{
    SetUpLocationSuggest();
});

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Location Suggest JSON End
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

