var g_map = null;
var g_wordList = ['I','a','about','an','are','as','at','be','by','com','de','en','for','from','how','in','is',
'it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with'];
var g_ignoreMapChanges = false;
var g_mapCenter = new GLatLng(40.4419, -96.1419);
var g_mapZoom = 4;
var g_markerListeners = [];
var g_NoResultsMessage = 'No results in this area. Try zooming out, moving map, or changing search.';
var g_SubmitSearchText = 'Search Map';
var g_HelpMeSearchText = 'Help Me Search';
var g_SearchTipsText = 'Search tips';
var g_SeeAllPeopleText = 'See all %%MEMBERTOTAL%% people';

function map_setBaseLocation( lat, lng ) {
    g_mapCenter = new GLatLng(lat, lng);
    g_mapZoom = 8;
}

//startup method
function ppmOnStartup() 
{
  if (GBrowserIsCompatible()) 
  {
    g_map = new GMap2( document.getElementById( "ppmMapCanvas" ) );
    g_map.setCenter(g_mapCenter, g_mapZoom);
    g_map.addControl(new GLargeMapControl());
    g_map.addControl(new GMapTypeControl());
    GEvent.addListener(g_map, "click", function() { g_ignoreMapChanges = false; });
    GEvent.addListener(g_map, "moveend", OnMapChanged);
    GEvent.addListener(g_map, "zoomend", OnMapChanged);
   }
   
   //event handlers
   $('#ppmSearchText').keydown(OnSearchTextKeydown);
   $('#ppmSearchSubmit').click(RunPlaceSearch);
   $('#ppmFindPeople').click(RunPlaceSearch);
   $('#ppmHelpMeSearch').click(ToggleMapFilters);
   $('#ppmNoResults').hide();
   $('#ppmTabsArea').hide();
   
   $('#ppmNoResults').text(g_NoResultsMessage);
   $('#ppmSearchSubmit').val(g_SubmitSearchText);
   $('#ppmHelpMeSearch').text(g_HelpMeSearchText);

   //create tabs from data
   CreateMapFilters();  
   //run search for current area 
   RunPlaceSearch();
      
   function OnMapChanged() 
   {
       if ( g_ignoreMapChanges == false )
           $('#ppmFindPeople').show();
   }
   
   function OnSearchTextKeydown( e ) 
   {
       if ( e.keyCode == Event.KEY_RETURN ) {
           e.preventDefault();
           RunPlaceSearch();
       }
   }
}

//function display customer for a place based on index
function DisplayCustomer(placeID,custIndex,callback)
{       
    var args= GetSearchArgs();
    args.placeid= placeID;
    args.custindex= custIndex;
   
    $.get('place_profile_data.aspx', args, function(response) 
    { 
        try 
        {
            var customers = eval( response );
            var customer= customers[0];
            var html= GetCustomerDisplay(customer);   
            
            if (callback)
                callback(html);
            else 
                document.getElementById( customer.PlaceID ).innerHTML = html;   
        } 
        catch( error ) { document.location = 'login.aspx'; }
    });
    
    //html for customer
    function GetCustomerDisplay(place)
    {            
        var profileUrl= 'profile_view.aspx?CustomerID='+ place.CustomerID;
        var searchUrl= 'search_place.aspx?placeid='+place.PlaceID+'&keywords='+escape($('#ppmSearchText').val());
        
        var display= '<div class="thumb-block">';
        display+= '<a href="'+ profileUrl +'" class="thumb-link" target="mapprofile">';
        display+= '<img src="thumbnail.aspx?dt=photo&fid='+ place.CustomerID +'&w=50&h=50" border="0"';
        
        if (place.ThumbnailAltText)
            display+= ' alt="'+ place.ThumbnailAltText.replace(/"/g,"&quot;") +'"';
        
        display+= '></a>';           
        
        if (place.Count > 1)
        {
            display+= (place.CustomerIndex == 0) ? '&lt; ' : '<a href="javascript:void(0);" onclick="DisplayCustomer(\''+ place.PlaceID +'\',\''+ (place.CustomerIndex-1) +'\');">&lt;</a> ';
            display+= ((place.CustomerIndex+1) >= place.Count) ? '&gt;' : '<a href="javascript:void(0);" onclick="DisplayCustomer(\''+ place.PlaceID +'\',\''+ (place.CustomerIndex+1) +'\');">&gt;</a> ';
        }
        
        display+= '</div><div class="member-data">'
        display+= '<p><a href="'+ profileUrl +'" class="title-link" target="mapprofile">'+ place.MemberName +'</a></p>';
        display+= '<p>'+ place.CustomerDescription +'</p></div>';
        
        if (place.Count > 1)
            display+= '<div class="stats-action"><a href="'+ searchUrl +'" target="mapprofile">'+g_SeeAllPeopleText.replace("%%MEMBERTOTAL%%", place.Count)+'</a></div>';
        
        return display;
    }
}

//get args based on form
function GetSearchArgs()
{    
    var term= GetSearchTerm();
    var bounds = g_map.getBounds();
    var southWest = bounds.getSouthWest(); 
    var northEast = bounds.getNorthEast();
    
    var args= { 
                q: term, 
                minlat: southWest.lat(), 
                maxlat: northEast.lat(), 
                t: (new Date()).valueOf() 
              };

    if ( southWest.lng() > northEast.lng() ) 
    {
        args.minlon= southWest.lng();
        args.maxlon= 180;
        args.minlon2= -180;
        args.maxlon2= northEast.lng();
    }
    else 
    {
        args.minlon= southWest.lng();
        args.maxlon= northEast.lng();
    }
    
    return args;
    
    //get search term, omitting noise words
    function GetSearchTerm() 
    {
        var term = ' ' + $('#ppmSearchText').val() + ' ';    
        $('#ppmFindPeople').hide();
        
        $.map(g_wordList, function(word) 
        {
            var re = new RegExp( '\\s('+word+')\\s', 'ig' );
            term = term.replace( re, ' ' );
        });
        
        term = term.replace( /\s+/, ' ' );
        term = term.replace( /^\s+/, '' );
        term = term.replace( /\s+$/, '' );
        return term;
    }
}

//run search!
function RunPlaceSearch() 
{ 
    g_map.clearOverlays();
    $('#ppmLoading').show();

    var args= GetSearchArgs();    
    
    $.get('place_profile_data.aspx', args, function(response) 
    {
        $('#ppmLoading').hide();    
        var arrPlaces = eval( response ); 
        
        try { map_update(arrPlaces); } 
        catch( error ) { document.location = 'login.aspx'; }
    });    
    
    //display pins based on g_places results
    function map_update(arrPlaces)
    {            
        $.map(g_markerListeners, function(ml) { GEvent.removeListener(ml); });
        g_map.clearOverlays();

        if ( arrPlaces.length > 0 ) 
        {
           $('#ppmNoResults').hide();
           g_ignoreMapChanges = true;
            
           $.map(arrPlaces, function(place) { g_map.addOverlay(map_createMarker(place)); });

           g_ignoreMapChanges = false;
        }
        else
           $('#ppmNoResults').show();
    }
    
    //create marker from place data
    function map_createMarker( place ) 
    {
        var point = new GLatLng( place.Latitude, place.Longitude );
        var baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.shadow = "images/shadow50.png"; 
        baseIcon.iconSize = new GSize(23, 37);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
        baseIcon.image = 'images/a-grey.gif';
        
        var marker = new GMarker( point, { icon:baseIcon } );
        
        g_markerListeners.push( GEvent.addListener(marker, "click", function() 
        {
            g_ignoreMapChanges = true;
            var callback= function(customerHtml) { 
                            var placeHtml= CreatePlaceHtml(place,customerHtml);
                            g_map.openInfoWindowHtml(point, placeHtml); 
                          };
            
            DisplayCustomer(place.PlaceID,0, callback);        
        }));
        
        return marker;
    }
    
    //html for the place-specific data
    function CreatePlaceHtml(place,customerHtml)
    {
        var display = "<b>" + place.LocationName + "</b><br/>";
        
        var address = '';
        if ( place.Address != null && place.Address.length > 0 )
            address += place.Address + ', ';
        if ( place.City != null && place.City.length > 0 )
            address += place.City + ' ';
        if ( place.State != null && place.State.length > 0 )
            address += place.State;
            
       // TODO: Change this to change the search.aspx syntax
       display += address;
       display += '<hr color="#dbdbdb" size="1" style="width:260px" noshade>';
       display+= '<div class="balloon-content" id="'+ place.PlaceID +'">';
       display+= customerHtml
       display+= '</div>';
       return display;
    }
}

function CreateMapFilters() 
{
    var $tabs= $('#ppmTabs');
    var $filters= $('#ppmCheckFields');
    var currentTabIndex= -1;

    $.map(g_profiles, function(tab, tabIndex) 
    {
        AddTab(tab.Title, tabIndex);
        AddFilters(tab.CheckFields, tabIndex);
    });

    AddTips();
    SelectTab(0); 
    
    function AddTab(title,index)
    {
        var display= '<li><a href="javascript:void(0);" style="backgroundColor: #ffffff; fontWeight: normal; marginRight: 0px;">';
        display+= title + '</a></li>';

        $tabs.append(display);
        $tabs.find("a:last").click(function() { SelectTab(index); });
    }
    
    function AddFilters(arr,tabIndex)
    {            
        $filters.append('<div class="filter-section" style="display:none;"></div>');
        var $div= $filters.find("div:last");
            
        $.map(arr, function(filter,index)
        {           
            AddFilterHeader($div, filter.Title, index);            
            AddFilterValues($div, tabIndex, filter.Values);
        });
    }
    
    function AddFilterHeader($div,title,index)
    {            
        var display= '<table class="data-table-1" width="100%" style="border: 0pt; border-collapse: collapse;"><tr>';
        display+= '<td class="cell-3" colspan="4" style="border: 0pt; background-color: #dbdbdb; color: #666666;">';
        display+= '<a class="arrow-right" href="javascript:void(0);">'+ title +'</a>';
        display+= '</td></tr></table>';
        
        $div.append(display);
        $div.find("a:last").click(function() { OnFilterClick(this,index); });
    }
    
    function AddFilterValues($div, tabIndex, arr)
    {
        var tbl= '<table class="data-table-1 filter-values" width="100%" style="border: 0pt none ; border-collapse: collapse; display:none;">'
        tbl+= '<tr class="row-1"><td class="cell-3" colspan="4" style="border: 0pt none ; font-size: 7pt;"/></tr></table>';
        
        $div.append(tbl);
        var $tbl= $filters.find("table:last");
        var $tr= null;
        
        $.map(arr, function(val,index)
        {
            if ((index % 2) == 0)
            {
                $tbl.append('<tr class="row-1">');
                $tr= $tbl.find("tr:last");
            }
            
            var display= '<td class="cell-3" style="border: 0pt none ; text-align: left; width: 50%;">';
            display+= '<a href="javascript:void(0);" name="Profile">'+ val +'</a></td>';
            
            $tr.append(display);
            $tr.find("a:last").click(function() { OnFilterValueClick(tabIndex,val); });
        });
    }
   
    function AddTips()
    {        
        $tabs.append('<li><a href="javascript:void(0);" class="no-tab">'+g_SearchTipsText+' &#187;</a></li>');
        $tabs.find("a:last").click(OpenTips);
    }
   
    function OpenTips(e) 
    {
        window.open('./places/searchtips.htm', 'SearchTips', 'width=600,height=375,resizable=yes,scrollbars=1'); 
    }
    
    function OnFilterClick(lnk,filterIndex) 
    {
        var $lnk= $(lnk);
        $lnk.parents("table").eq(0).next().toggle();
        
        if ($lnk.is('.arrow-right'))
            $lnk.removeClass('arrow-right').addClass('arrow-down');
        else
            $lnk.removeClass('arrow-down').addClass('arrow-right');
    }
    
    function OnFilterValueClick(tabIndex,val) 
    { 
        $('#ppmSearchText').val(g_profiles[tabIndex].Title + ': ' + val);
        RunPlaceSearch();
    }
    
    function SelectTab(i) 
    {
        if (i == currentTabIndex)
            return;
        
        var $tabs= $('#ppmTabs');
        var $divs= $('#ppmCheckFields').find("div.filter-section");

        if (currentTabIndex != -1) 
        {
            var $prev= $tabs.find('li').eq(currentTabIndex).find('a');
            $prev.css('backgroundColor','#ffffff');
            $prev.css('borderBottomColor','#ffffff');
            $prev.removeClass('current');
        }

        var $tab= $tabs.find('li').eq(i).find('a');  
        $tab.css('backgroundColor','#f1f1f1');
        $tab.css('borderBottomColor','#f1f1f1');
        $tab.addClass('current');
        
        $divs.hide();
        $divs.eq(i).show();
        
        currentTabIndex = i;
    }
}

function ToggleMapFilters() {
    if ( $('#ppmTabs:visible').length > 0 ) {
        $('#ppmTabs').hide();
        $('#ppmTabsArea').hide();
    } else {
        $('#ppmTabs').show();
        $('#ppmTabsArea').show();
    }
}

$(function() { 
    ppmOnStartup();
});
