﻿
//globals
var map;
var lastMapPoint;
var lastMapLatLng;    
var bbicon; 
var bbicon_active;
var allmarkers = [];
var searchresultmarker;
var features = new Hash();
var g_isAdmin=false;
var g_isLoggedIn=false;
var g_loginURL="";
var g_pano=null;
var g_currentPlace;
var g_FilterControl;
var g_HelpControl;

var geocoder;
var clusterer;
//globals for star ratings
var sMax;	// Isthe maximum number of stars
var holder; // Is the holding pattern for clicked state
var preSet; // Is the PreSet value onces a selection has been made
var rated;



//constants
var FLASH_UNAVAILABLE=603;



var wait_img = new Element('img', { 'src': '/static/waiting.gif','align': 'middle', 'id': 'wait_img' });


//utilities

function Left(str, n)
{
    if (n <= 0)     // Invalid bound, return blank string
            return "";
    else if (n > String(str).length)   // Invalid bound, return
            return str;                // entire string
    else // Valid bound, return appropriate substring
            return String(str).substring(0,n);
}


//classes
function Filter() {

}

Filter.prototype._features;
Filter.prototype._active;
Filter.prototype._distance;
Filter.prototype._location;
Filter.prototype.getFeatures = function() {
    return this._features;
}
Filter.prototype.setFeatures = function(features) {
    this._features=features;
}
Filter.prototype.getFeatures = function() {
    return this._features;
}
Filter.prototype.getActive = function() {
    return this._active;
}
Filter.prototype.setActive = function(active) {
    this._active=active;
}
Filter.prototype.getDistance = function() {
    return this._distance;
}
Filter.prototype.setDistance = function(distance) {
    this._distance=distance;
}

Filter.prototype.getLocation = function() {
    return this._location;
}
Filter.prototype.setLocation = function(location) {
    this._location=location;
}

Filter.prototype.getFeatureString = function() {
    var resp = "";
    if(this._features)
    {
        var k = this._features.values();
        k.each(function(s){resp+=s.value+","});
        resp=Left(resp,resp.length-1);   
    }
    
    return resp;
}

Filter.prototype.getFeatureKeyString = function() {
    var resp = "";
    if(this._features)
    {
        var k = this._features.keys();
        k.each(function(s){resp+=s+","});
        resp=Left(resp,resp.length-1);   
    }
    
    return resp;
}

Filter.prototype.setFeaturesFromString = function(fs) {
    var ff = new Hash();

    var ca = fs.split(',');
    for(var i=0;i < ca.length;i++) 
    {
	    ff.set(ca[i], ca[i]);
    }
    this._features=ff;
}

g_filter = new Filter();


function onUnload()
{
    if(g_pano)
    {
        g_pano.remove();
    }
        
    GUnload();

}

//NAVIGATION FUNCTIONS
function showHelp() 
{
    // create a GControlPosition
    $("addform").style.visibility="hidden";
    $("contextmenu").style.visibility="hidden";
    $("filter").style.visibility="hidden";

    $("help").style.width="800px";

    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(180,50));  
    pos.apply($("help"));
    $("help").style.visibility = "visible";
}

function closeHelp() 
{
    $("help").style.visibility = "hidden";
}

function showFilter() 
{
    // store the "pixel" info in case we need it later
    // adjust the context menu location if near an egde
    // create a GControlPosition
    // apply it to the context menu, and make the context menu visible
    //hide the add form div just in case
    $("addform").style.visibility="hidden";
    $("contextmenu").style.visibility="hidden";


    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(100,26));  
    pos.apply($("filter"));
    $("filter").style.visibility = "visible";
}

function applyFilter()
{
    var ff = new Hash();

    var so = $('filter_features').options;
    
    for (var i = 0; i < so.length; i ++)
    {
        if(so[i].selected)
            ff.set(so[i].value, so[i].text);
    }

    g_filter.setFeatures(ff);
    g_filter.setDistance($("filter_distance").value);
    g_filter.setLocation($("filter_loc").value);
    g_filter.setActive(true);

    saveState();    
    filterSearch();    

    $("filter").style.visibility = "hidden";
    $("divFilterControl").innerHTML = "Filter *";
   
}

function removeFilter()
{

    g_filter.setActive(false);

    filterSearch();    
    saveState();    

    $("filter").style.visibility = "hidden";
    $("divFilterControl").innerHTML = "Filter";
  
}

function cancelFilter()
{
    $("filter").style.visibility = "hidden";
}

function clearFilter()
{
    var so = $('filter_features').options;
    
    for (var i = 0; i < so.length; i ++)
    {
        so[i].selected = false;
    }
    
    $("filter_distance").value="";
    $("filter_loc").value="";

}

function tab(id)
{
    if(id==1)
    {
        //general
        $("at1").addClassName('tab_sel').removeClassName('tab_unsel');
        $("at2").addClassName('tab_unsel').removeClassName('tab_sel');
        $("at3").addClassName('tab_unsel').removeClassName('tab_sel');
        $("at4").addClassName('tab_unsel').removeClassName('tab_sel');

        $("info").show();
        $("links").hide();
        $("pano").hide();
        if(g_pano)
            g_pano.hide();
        $("comments").hide();

    }
    else if (id==2)
    {
        //street view
        $("at1").addClassName('tab_unsel').removeClassName('tab_sel');
        $("at2").addClassName('tab_sel').removeClassName('tab_unsel');
        $("at3").addClassName('tab_unsel').removeClassName('tab_sel');
        $("at4").addClassName('tab_unsel').removeClassName('tab_sel');
        $("info").hide();
        $("links").hide();
        $("pano").show();
        if(g_pano)
            g_pano.show();
        $("comments").hide();

    }
    else if (id==3)
    {
        //Links
        $("at1").addClassName('tab_unsel').removeClassName('tab_sel');
        $("at2").addClassName('tab_unsel').removeClassName('tab_sel');
        $("at3").addClassName('tab_sel').removeClassName('tab_unsel');
        $("at4").addClassName('tab_unsel').removeClassName('tab_sel');       
   
        
        $("info").hide();
        $("pano").hide();
        if(g_pano)
            g_pano.hide(); 
        $("comments").hide();
                
        if(g_currentPlace)
        {
            $("links").show();
            $("addlink").show();
            $("showlinks").show();            
        } 
       
    }
    else if (id==4)
    {
        //Comments
        $("at1").addClassName('tab_unsel').removeClassName('tab_sel');
        $("at2").addClassName('tab_unsel').removeClassName('tab_sel');
        $("at3").addClassName('tab_unsel').removeClassName('tab_sel');
        $("at4").addClassName('tab_sel').removeClassName('tab_unsel');      
        
        $("links").hide();
        $("info").hide();
        $("pano").hide();
        if(g_pano)
            g_pano.hide();  
            
        if(g_currentPlace)
        {
            $("comments").show();
            $("addcomment").show();
            $("showcomments").show();            
        } 
    }     

}

function onAddrKeyDown(e)
{
    var keynum;

    if(window.event) // IE
    {
      keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
      keynum = e.which;
    }
    
    if(keynum==13)
        quickSearch();


}

function filterSearch()
{
    if($F("filter_loc")!="")
    {
        geocoder.getLocations($F("filter_loc"), processQuickSearchResults);
    }

}

function quickSearch()
{
    if($F("addr")!="")
    {
        geocoder.getLocations($F("addr"), processQuickSearchResults);
    }

}

function processQuickSearchResults(response)
{
    if (!response || response.Status.code != 200) 
    {
        alert("Sorry, we were unable to geocode that address");
    } 
    else 
    {
        var tabAccuracy = new Array(2,4,6,10,12,13,16,16,17);
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);
                            
        if(searchresultmarker)
            map.removeOverlay(searchresultmarker);
        
        //searchresultmarker = new GMarker(point);
        //map.addOverlay(searchresultmarker);
        ///allmarkers.push(searchresultmarker);                
        map.setCenter(point,tabAccuracy[place.AddressDetails.Accuracy]);

      }



}

 
//END NAVIGATION FUNCTIONS


//CUSTOM MAP CONTROLS


// We define the function first
function FilterControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
FilterControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
FilterControl.prototype.initialize = function(map) {

  var FilterDiv = document.createElement("div");
  FilterDiv.id = "divFilterControl";
  this.setButtonStyle_(FilterDiv);
  FilterDiv.appendChild(document.createTextNode("Filter"));
  GEvent.addDomListener(FilterDiv, "click", function() {
    showFilter();
  });


  map.getContainer().appendChild(FilterDiv);
  return FilterDiv;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
FilterControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(100, 7));
}

// Sets the proper CSS for the given button element.
FilterControl.prototype.setButtonStyle_ = function(button) {
  //button.style.textDecoration = "underline";
  //button.style.color = "#0000cc";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.padding = "1px";
  button.style.marginBottom = "1px";
  button.style.textAlign = "center";
  button.style.width = "5em";
  button.style.cursor = "pointer";
}


// We define the function first
function HelpControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
HelpControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
HelpControl.prototype.initialize = function(map) {

  var HelpDiv = document.createElement("div");
  HelpDiv.id = "divHelpControl";
  this.setButtonStyle_(HelpDiv);
  HelpDiv.appendChild(document.createTextNode("Help"));
  GEvent.addDomListener(HelpDiv, "click", function() {
    showHelp();
  });


  map.getContainer().appendChild(HelpDiv);
  return HelpDiv;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
HelpControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(180, 7));
}

// Sets the proper CSS for the given button element.
HelpControl.prototype.setButtonStyle_ = function(button) {
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.padding = "1px";
  button.style.marginBottom = "1px";
  button.style.textAlign = "center";
  button.style.width = "5em";
  button.style.cursor = "pointer";
}



//INITIALIZATION FUNCTIONS 
 
function initialize() 
{  

    if(!($("map_canvas")))
        return;
        
    map = new google.maps.Map2($("map_canvas"));
    map.disableDoubleClickZoom();
    //map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
    var clat = readCookie("clat");
    var clng = readCookie("clng");
    var ctr;
    
    
    if(clat==null)
        ctr=new google.maps.LatLng(geoip_latitude(), geoip_longitude());
    else
        ctr=new google.maps.LatLng(clat, clng);
       
    map.setCenter(ctr);
    
    var zm = readCookie("zm");
    if(zm==null)
        zm=12;
    map.setZoom(parseInt(zm)); 
      
    var mapControl = new GMapTypeControl();
    map.addControl(mapControl);
    
    //map.addControl(new GLargeMapControl());
    var adsManager = new GAdsManager(map, "ca-pub-7018625661294984",{"maxAdsOnMap":5, "minZoomLevel": 6, "channel":"0796064672"});
    adsManager.enable();
  
      
    //var searchControl = new google.search.SearchControl();        
    //searchControl.addSearcher(new google.search.WebSearch());        
    //searchControl.addSearcher(new google.search.NewsSearch());        
    //searchControl.draw(document.getElementById("searchcontrol"));

    
    // === create the context menu div ===
    var contextmenu = document.createElement("div");
    contextmenu.id = "contextmenu";
    contextmenu.style.visibility="hidden";
    contextmenu.style.background="#ffffff";
    contextmenu.style.border="2px solid black";

    contextmenu.innerHTML = '<a href="javascript:zoomIn()"><div class="context">&nbsp;&nbsp;Zoom in&nbsp;&nbsp;</div></a>'
                        + '<a href="javascript:zoomOut()"><div class="context">&nbsp;&nbsp;Zoom out&nbsp;&nbsp;</div></a>'
                        + '<a href="javascript:zoomInHere()"><div class="context">&nbsp;&nbsp;Zoom in here&nbsp;&nbsp;</div></a>'
                        + '<a href="javascript:zoomOutHere()"><div class="context">&nbsp;&nbsp;Zoom out here&nbsp;&nbsp;</div></a>'
                        + '<a href="javascript:centreMapHere()"><div class="context">&nbsp;&nbsp;Centre map here&nbsp;&nbsp;</div></a>';

    map.getContainer().appendChild(contextmenu);
    
    
    //initFeatures();
    
    // === create the add place form ===
    var addform = document.createElement("div");
    addform.id = "addform";
    addform.style.visibility="hidden";
    addform.style.background="#ffffff";
    addform.style.border="2px solid black";
    addform.style.zIndex="10";


    var sHTML = '<div id="addformtitle" class="context" style="border-bottom: 2px solid black">Create</div>'
                        + '<table class="context"><tr><td>Name:</td><td><input type="text" class="context" id="placename" ' 
                        + ' name="placename" size="50"/></td></tr>'
                        + '<tr><td valign="top">Description:</td> ' 
                        + '<td><textarea id="placedescription" name="placedescription" rows="10" cols="60" class="context"></textarea></td></tr>'
                        + '<tr><td>Features:</td><td><select id="features" name="features" size="4" multiple="true">'
                        
    features.each(function(pair) 
        {sHTML += '<option value=' + pair.key + '>' + pair.value + '</option>'; });                     
    
    sHTML +=            '</select></td></tr>' ;
    //sHTML +=            '<tr><td colspan="2" style="text-align:center"><div id="recaptcha_div"></td></tr>';                                             
    sHTML +=            '<tr><td>&nbsp;</td><td align="right" style="text-align: right"><a id="saveplace" href="javascript:createPlace();" class="divlink">Add</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="javascript:closeAddForm();" class="divlink">Cancel</a></td></tr></table>';

    addform.innerHTML = sHTML;
    map.getContainer().appendChild(addform);
    
    // === create the filter form ===
    var filter = document.createElement("div");
    filter.id = "filter";
    filter.style.visibility="hidden";
    filter.style.background="#ffffff";
    filter.style.border="2px solid black";
    filter.style.zIndex="10";


    sHTML = '<table class="context"><tr><td colspan="2">Show me sites with these features:</td></tr>'
    sHTML +=    '<tr><td colspan="2">&nbsp;</td></tr>'
    sHTML +=    '<tr><td colspan="2"><select id="filter_features" name="filter_features" size="4" multiple="true">'
                        
    features.each(function(pair) 
        {sHTML += '<option value=' + pair.key + '>' + pair.value + '</option>'; });                     
    
    sHTML +=    '</select></td></tr>' ;
    sHTML +=    '<tr><td colspan="2">&nbsp;</td></tr>'
    sHTML +=    '<tr><td colspan="2">within <input type="text" size="2" class="context" id="filter_distance" name="filter_distance" />'
    sHTML +=    ' miles '
    sHTML +=    'of <input type="text" size="15" title="Name or Zip" class="context" id="filter_loc" name="filter_loc" /></td></tr>'
    sHTML +=    '<tr><td colspan="2">&nbsp;</td></tr>'
    sHTML +=    '<tr><td>&nbsp;</td><td align="right" style="text-align: right">'
    sHTML +=    '<a id="applyfilter" href="javascript:applyFilter();" class="divlink">Apply</a>'
    sHTML +=    '&nbsp;&nbsp;|&nbsp;&nbsp;<a id="applyfilter" href="javascript:clearFilter();" class="divlink">Clear</a>'
    sHTML +=    '&nbsp;&nbsp;|&nbsp;&nbsp;<a id="applyfilter" href="javascript:removeFilter();" class="divlink">Remove</a>'
    sHTML +=    '&nbsp;&nbsp;|&nbsp;&nbsp;<a href="javascript:cancelFilter();" class="divlink">Cancel</a></td></tr></table>';

    filter.innerHTML = sHTML;
    map.getContainer().appendChild(filter);

    // === create the login form ===
    var loginform = document.createElement("div");
    loginform.id = "loginform";
    loginform.style.visibility="hidden";
    loginform.style.background="#ffffff";
    loginform.style.border="2px solid black";
    loginform.style.zIndex="10";


    sHTML = '<table class="context"><tr><td>You must be logged in to add a new place.</td></tr>'
                        
    sHTML +=            '<tr><td align="right" style="text-align: left">'
    sHTML +=            '<a id="gotologin" href="javascript:gotoLogin();" class="divlink">Login/Register</a>'
    //sHTML +=            '&nbsp;&nbsp;|&nbsp;&nbsp;<a id="gotoregister" href="javascript:gotoRegister();" class="divlink">Register</a>'
    sHTML +=            '&nbsp;&nbsp;|&nbsp;&nbsp;<a id="cancel" href="javascript:closeLoginForm();" class="divlink">Close</a>'
    sHTML +=            '</td></tr></table>';

    loginform.innerHTML = sHTML;
    map.getContainer().appendChild(loginform);
    
    
    
    //create the help div
    var helpform = document.createElement("div");
    helpform.id = "help";
    helpform.style.visibility="hidden";
    helpform.style.background="#ffffff";
    helpform.style.border="2px solid black";
    helpform.style.zIndex="10";
    helpform.style.paddingLeft="5px";
    helpform.style.paddingRight="5px";
    helpform.style.height="auto";

    
    sHTML = '<p>                                                                                                        \
            Welcome to Sportsity! Sportsity allows you to quickly locate places to play sports,                         \
            and share your own favorites.</p>                                                                           \
            <p>Here is a quick guide to the site and what you can do:</p>                                               \
            <ul>                                                                                                        \
                <li><b>Browse the Map</b><br />                                                                                \
                Simply navigate the map as you would any Google map (zoom, drag, change views, etc.) Sports sites       \
                will show up as tiny basketballs or green arrows (a green arrow means there are multiple sites located  \
                within the area indicated by the arrow). Click on a basketball icon to see more information about that  \
                site in the info panel to the right of the map.                                                         \
                </li>                                                                                                   \
                <li><b>Explore a Sports Site</b><br />                                                                         \
                When you click on an icon on the map, Sportsity will populate the info panel to the right of the map    \
                with information about the site. The info panel has 4 tabs: General displays a description, rating,     \
                site features, and geographical data; Street View displays a Google street view of the site             \
                (if available); Links displays web links related to the site (and allows you to add your own);          \
                Comments displays user comments about the site (and allows you to add your own).                        \
                </li>                                                                                                   \
                <li><b>Perform a Location Search</b><br />                                                                     \
                Just above the info panel is the Location Search box--simply enter a combination                        \
                of city, state, and/or zip and Sportsity will display that area on the map.                             \
                </li>                                                                                                   \
                <li><b>Apply a Filter</b><br />                                                                                  \
                The Filter button, located in the upper left corner of the map, allows you to filter                    \
                the sports sites shown on the map by feature and proximity to a location.                               \
                </li>                                                                                                   \
                <li><b>Add Your Favorite Sports Sites</b><br />                                                                \
                Logged-in users can quickly and easily add their own favorite sites by simply                           \
                clicking on the appropriate map location and filling out a simple form.                                 \
                </li>                                                                                                   \
            </ul>                                                                                                       \
            <center>                                                                                                    \
            <a id="cancel" href="javascript:closeHelp();" class="divlink">Close</a>                                 \
            </center>                                                                                                   '                                                       
        
        helpform.innerHTML = sHTML;
        map.getContainer().appendChild(helpform);
   
    
    if(!readCookie("visited"))
    {
        showHelp();
        updateCookie("visited",1,1000);
    }
    
    geocoder = new GClientGeocoder();

    clusterer = new ClusterMarker(map);
    clusterer.clusterMarkerTitle='%count sites (click to zoom in)';    
    map.addControl(new GLargeMapControl());
    g_FilterControl = new FilterControl();
    map.addControl(g_FilterControl);

    //g_HelpControl = new HelpControl();
    //map.addControl(g_HelpControl);

    GEvent.addListener(map,"click", onMapClick);  
    GEvent.addListener(map,"singlerightclick",showContextMenu);
    GEvent.addListener(map,"dragstart",hideDivs);
    GEvent.addListener(map,"dragend",onDragEnd);
    GEvent.addListener(map,"zoomend",onZoomEnd);
    GEvent.addListener(map,"moveend",onMoveEnd);
    
    initIcons();
    initFilter();
    loadMarkers();
    
}

function initFilter()
{  
    if(readCookie("fa")=="true")
    {
        //set filter properties
        g_filter.setActive(true);    
        g_filter.setFeaturesFromString(readCookie("ff"));
        g_filter.setDistance(readCookie("fd"));
        g_filter.setLocation(readCookie("fl"));  


        //set html fields
        var so = $('filter_features').options;
        
        var k = g_filter.getFeatures().keys();
        
        for(var j=0;j<k.length;j++)
        {
            for (var i = 0; i < so.length; i ++)
            {
                if(so[i].value == k[j])
                    so[i].selected = true;
            }
        
        }
        $("filter_distance").value = g_filter.getDistance();
        $("filter_loc").value = g_filter.getLocation();

        $("divFilterControl").innerHTML = "Filter *";

        
    }

}
    
function initIcons()
{
    bbicon = new GIcon();
    bbicon.image = "static/basketball_icon.png";
    bbicon.iconAnchor = new GPoint(16, 16);
    bbicon.infoWindowAnchor = new GPoint(16, 0);
    bbicon.iconSize = new GSize(20, 20);
    
    bbicon_active = new GIcon();
    bbicon_active.image = "static/basketball_icon_active.png";
    bbicon_active.iconAnchor = new GPoint(16, 16);
    bbicon_active.infoWindowAnchor = new GPoint(16, 0);
    bbicon_active.iconSize = new GSize(20, 20);

}


//not used any more, candidate for deletion
function initFeatures()
{
        var k = features.keys();
        var v = features.values();
       
        for(var j=0;j<k.length;j++)
        {
            var o = document.createElement('option');
            var o2 = document.createElement('option');
            o.text = v[j];
            o.value = k[j];
            o2.text = v[j];
            o2.value = k[j];
            try 
            {
                $('features').add(o,null); // standards compliant; doesn't work in IE
                $('filter_features').add(o2,null); // standards compliant; doesn't work in IE
            }
            catch(ex) 
            {
                $('features').add(o); // IE only
                $('filter_features').add(o2); // IE only
            }
        }


/*
    var params = '';
    var req = new Ajax.Request('getfeatures', 
        {   method: 'post',   
            parameters: params,
            onSuccess: function(transport){loadFeatures(transport);},   //function(transport){alert(transport.responseText)},//  
            onFailure: function(){ alert('Something went wrong...') }                     
            });                 
*/

}

//load the global hash "features" from the server datastore
function loadFeatures(transport)
{
    var json = transport.responseText.evalJSON()    
    //debugger;
    for(var i=0;i<json.length;i++)
    {  
        features.set(json[i].id, json[i].name);
        var o = document.createElement('option');
        var o2 = document.createElement('option');
        o.text = json[i].name;
        o.value = json[i].id;
        o2.text = json[i].name;
        o2.value = json[i].id;
        try 
        {
            $('features').add(o,null); // standards compliant; doesn't work in IE
            $('filter_features').add(o2,null); // standards compliant; doesn't work in IE
        }
        catch(ex) 
        {
            $('features').add(o); // IE only
            $('filter_features').add(o2); // IE only
        }



    } 
}

//END INITIALIZATION FUNCTIONS 




//MAP EVENT HANDLERS 
function onDragEnd()
{
    //loadMarkers();
    //saveState();

}

function onZoomEnd()
{
    loadMarkers();
    saveState();    
}

function onMoveEnd()
{
    loadMarkers();
    saveState();    
}


function onMapClick(overlay,latlng)
{
    //hide the context menu just in case
    $("contextmenu").style.visibility="hidden";
    $("addform").style.visibility = "hidden";
    
    if(overlay) //we have clicked a marker
    {
        getMarkerInfo(overlay);
    }
    else
    {
        if(true)
            showCreatePlace(latlng);
        else
            showLogin(latlng);
    }
}
//END MAP EVENT HANDLERS 




//SESSION STATE/COOKIE FUNCTIONS
function saveState()
{
    updateCookie("zm",map.getZoom(),90);
    updateCookie("clat",map.getCenter().lat(),90);  
    updateCookie("clng",map.getCenter().lng(),90);  
    if(g_currentPlace)
        updateCookie("pid",g_currentPlace.id,90);  
        
    updateCookie("fa",g_filter.getActive(),90);  
    updateCookie("fd",g_filter.getDistance(),90);  
    updateCookie("fl",g_filter.getLocation(),90);  
    updateCookie("ff",g_filter.getFeatureKeyString(),90);  
    
}

function existsCookie()
{
    if(document.cookie.length>0)
        return true;
    else
        return false;

}

function createCookie(name,value,days) 
{
    if (days) 
    {
	    var date = new Date();
	    date.setTime(date.getTime()+(days*24*60*60*1000));
	    var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) 
    {
	    var c = ca[i];
	    while (c.charAt(0)==' ') c = c.substring(1,c.length);
	    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) 
{
    createCookie(name,"",-1);
}

function updateCookie(name,value,days) 
{
    eraseCookie(name);
    createCookie(name,value,days);
}
//END SESSION STATE/COOKIE FUNCTIONS




//MAP MARKER-RELATED FUNCTIONS
function updateIcons(overlay)
{
    //debugger;
    allmarkers.each(function(s) {
        
        try{
        s.setImage('static/basketball_icon.png');
        }
        
        catch (e)
        {
        
        }
        
        });    
    /*
    var point = overlay.getLatLng();
    var mrkr = new GMarker(point,{title:json[i].name, icon: bbicon});
        map.addOverlay(mrkr);

    map.removeOverlay(overlay);
    map.addOverlay(point, 
    */
    if(overlay)
        overlay.setImage('static/basketball_icon_active.png');
    else
    {
    
        allmarkers.each(function(s) {
            
            try{
            if(s.id==g_currentPlace.id)
                s.setImage('static/basketball_icon_active.png');
            }
            
            catch (e)
            {
            
            }
            
            });        
    
    }

}



//load any markers within the current map boundary.
function loadMarkers()
{
    //map.clearOverlays()
    ///for(var i=0;i<clusterer.markers.length;i++)
    ///{
        ///map.removeOverlay(allmarkers[i]);

    ///}
    
    
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var minLng = southWest.lng();
    var maxLng = northEast.lng();
    var minLat = southWest.lat();
    var maxLat = northEast.lat();
    //get data from server...callback should be addMarkers
    var params = 'minlng=' + minLng + '&maxlng=' + maxLng + '&minlat=' + minLat
        + '&maxlat=' + maxLat + '&clat=' + map.getCenter().lat() + '&clng=' + map.getCenter().lng() 
        + '&zm=' + map.getZoom();
        
    if(g_filter.getActive())
    {
        params += '&floc=' + g_filter.getLocation() + '&fdist=' + g_filter.getDistance() + '&ff=' + g_filter.getFeatureKeyString();     
    } 

    //debugger;
        
    //alert(params);
    var req = new Ajax.Request('getplacesonmap', 
        {   method: 'post',   
            parameters: params,
            onSuccess: function(transport){addMarkers(transport);},   //function(transport){alert(transport.responseText)},//  
            onFailure: function(){ alert('Something went wrong...') }                     
            });                 


}

function addMarkers(transport)
{
    var json = transport.responseText.evalJSON()   
    var pid = readCookie("pid");
    var t;
 
    //alert("MarkerCount:" + json.length); 
    //debugger;
    clusterer.removeMarkers();
    allmarkers.clear();
    for(var i=0;i<json.length;i++)
    {
    	//alert(json[i].pf);           

        var point = new GLatLng(json[i].lat,
                          json[i].lng);
        var mrkr = new GMarker(point,{title:json[i].name + (json[i].pf.length > 0 ? ": " + json[i].pf : ""), icon: bbicon});
        ///map.addOverlay(mrkr);
        //mrkr.bindInfoWindowHtml(json[i].name + " " + json[i].id);
        mrkr.id = json[i].id;
        allmarkers.push(mrkr);
        if(mrkr.id==pid)
            t = mrkr;
    }
    
    if(allmarkers.length > 0)
        clusterer.addMarkers( allmarkers );

        
    clusterer.refresh(true);
    
    if(t&&(!g_currentPlace))
        getMarkerInfo(t);
    else
        updateIcons(null);

    //next
    
}

function getMarkerInfo(overlay)
{
    //get data from server...callback should be addMarkers
    //debugger;
    if(overlay.id)
    {

        clearInfoWindow();

        var wait_div = new Element('div',{ 'id': 'wait_div'});
        wait_div.setStyle({margin: '0px auto'});
        wait_div.setStyle({textAlign: 'left'});
        wait_div.setStyle({width: '50px'});
        wait_div.setStyle({top: '45%'});
        wait_div.setStyle({position: 'relative'});

        wait_div.appendChild(wait_img);
        
        $("info").appendChild(wait_div);
        
        var params = 'id=' + overlay.id;
        //alert(params);
        
        updateIcons(overlay);

        var req = new Ajax.Request('getplaceinfo', 
            {   method: 'post',   
                parameters: params,
                onSuccess: function(transport){showMarkerInfo(transport);},   //function(transport){alert(transport.responseText)},//  
                onFailure: function(){ alert('Something went wrong...') }                     
                });                 


        //load links
        
        params = 'id=' + overlay.id;
        req = new Ajax.Request('getplacelinks', 
            {   method: 'post',   
                parameters: params,
                onSuccess: function(transport){showPlaceLinks(transport);},   //function(transport){alert(transport.responseText)},//  
                onFailure: function(){ alert('Something went wrong...') }                     
                }); 
                
        //load comments    
        params = 'id=' + overlay.id;
        req = new Ajax.Request('getplacecomments', 
            {   method: 'post',   
                parameters: params,
                onSuccess: function(transport){showPlaceComments(transport);},   //function(transport){alert(transport.responseText)},//  
                onFailure: function(){ alert('Something went wrong...') }                     
                });           
                
                
        //load streetview (first, get nearest address, etc.)
        var wait_div2 = new Element('div',{ 'id': 'wait_div2'});
        wait_div2.setStyle({margin: '0px auto'});
        wait_div2.setStyle({textAlign: 'left'});
        wait_div2.setStyle({width: '50px'});
        wait_div2.setStyle({top: '60%'});
        wait_div2.setStyle({position: 'relative'});

        wait_div2.appendChild(wait_img);
        
        $("pano").appendChild(wait_div2);
        
        //debugger;
        var params = 'callback=processNearestAddressData&radius=1.5&lat=' + overlay.getLatLng().lat() + '&lng=' + overlay.getLatLng().lng();

     
        var request = 'http://ws.geonames.org/findNearestIntersectionJSON?' + params;

        // Create a new script object
        var aObj = new JSONscriptRequest(request);
        // Build the script tag
        aObj.buildScriptTag();
        // Execute (add) the script tag
        aObj.addScriptTag();
       
       /*
        var req = new Ajax.Request('dp', 
            {   method: 'post',   
                parameters: params,
                onSuccess: function(transport){processNearestAddressData(transport);},   //function(transport){alert(transport.responseText)},//  
                onFailure: function(){ alert('Something went wrong...') }                     
                });     
                
         */ 

    }
    

}

//END MAP MARKER-RELATED FUNCTIONS



//INFO WINDOW-RELATED FUNCTIONS
function processNearestAddressData(transport)
{
    //debugger;
    var json = transport; //transport.responseText.evalJSON(); 
    if(json.intersection)
    {   
        var item = json.intersection;
        //now show street view
        //debugger;
        var panoClient = new GStreetviewClient();
        panoClient.getNearestPanoramaLatLng(new GLatLng(item.lat,item.lng), handlePanoData)
    }
    else
    {
        $("pano").innerHTML='Unable to get Street View data from Google servers';
    }

}

function showMarkerInfo(transport)
{
    //alert("foo");
    var json = transport.responseText.evalJSON();    
    //alert("Success! \n\n" + transport.responseText); 
    //debugger;
       
    
    g_currentPlace = json[0];
    
    lastMapLatLng = new GLatLng(g_currentPlace.lat, g_currentPlace.lng);
    saveState();    

    var el = document.createElement('h3');
    el.innerHTML = g_currentPlace.nm;
    $("info").appendChild(el);

    //var el1 = document.createElement('div');
    //el1.className = "rate_cont";
    
    el = document.createElement('div');
    el.id = "rate";
    el.title = "Rate This";
    el.innerHTML = 'Rate This!' + 
        '<a onclick="rateIt(this)" id="_1" title="1" onmouseover="rating(this)" onmouseout="off(this)"></a>' + 
        '<a onclick="rateIt(this)" id="_2" title="2" onmouseover="rating(this)" onmouseout="off(this)"></a>' +
        '<a onclick="rateIt(this)" id="_3" title="3" onmouseover="rating(this)" onmouseout="off(this)"></a>' +
        '<a onclick="rateIt(this)" id="_4" title="4" onmouseover="rating(this)" onmouseout="off(this)"></a>' +
        '<a onclick="rateIt(this)" id="_5" title="5" onmouseover="rating(this)" onmouseout="off(this)"></a>';
    $("info").appendChild(el);

    
    el = document.createElement('div');
    el.id = "rating";
    
    if(isNaN(parseFloat(g_currentPlace.nrt)))
    {
        g_currentPlace.nrt  = 0;
        g_currentPlace.rt = 0;
    }   
 
    $("info").appendChild(el);   
    
    preSet=null;
    rated=null;
    updateAvgRating(Math.round(g_currentPlace.rt),g_currentPlace.nrt);
     
    el = document.createElement('br');            
    $("info").appendChild(el);     
          
    el = document.createTextNode('City: ' + g_currentPlace.ct);
    $("info").appendChild(el);  
    
    el = document.createElement('br');            
    $("info").appendChild(el);
            
    el = document.createTextNode('Postal Code: ' + g_currentPlace.pc);
    $("info").appendChild(el);  

    el = document.createElement('br');            
    $("info").appendChild(el);
            
    el = document.createTextNode('Lat/Lng: ' + g_currentPlace.lat+','+g_currentPlace.lng);
    $("info").appendChild(el);      
    
    
    if(g_currentPlace.desc!=null)
    {            
        el = document.createElement('p');
        el.innerHTML = g_currentPlace.desc.replace(new RegExp( "\\n", "g" ),"<br/>" );

        $("info").appendChild(el);     
    }
    
    if(g_currentPlace.pfs.length > 0)
    {
        el = document.createElement('p');
        el.innerHTML = 'Features:';
        $("info").appendChild(el); 
        el = document.createElement('ul');
        
        for(var j=0;j<g_currentPlace.pfs.length;j++)
        {
            el.innerHTML += '<li>' + g_currentPlace.pfs[j].nm + '</li>';          
        }
           
        $("info").appendChild(el); 
    }
    
    $("q").value = g_currentPlace.nm + " " + g_currentPlace.ct;

  

    
    //and add some actions
    

    if(g_isAdmin)
    {
        el = document.createElement('br');            
        $("info").appendChild(el);
        el = document.createElement('a');
        el.setAttribute('href','javascript:showEditPlace(' + g_currentPlace.id + ')');
        el.innerHTML = 'Edit';
        $("info").appendChild(el);
    } 

    if(g_isAdmin)
    { 
        el = document.createTextNode('\u00a0');            
        $("info").appendChild(el);
        el = document.createTextNode('\u00a0');            
        $("info").appendChild(el);
        
        el = document.createElement('a');
        el.setAttribute('href','javascript:removePlace(' + g_currentPlace.id + ')');
        el.innerHTML = 'Remove';
        $("info").appendChild(el);  
    }   

/*                  
    
    el = document.createElement('a');
    el.setAttribute('href','javascript:addToFavorites(' + g_currentPlace.id + ')');
    el.innerHTML = 'Add site to favorites';
    $(info).appendChild(el);
*/        

}

function handlePanoData(response)
{
    //debugger;

/*
    if(g_pano)
    {
        g_pano.remove();
        g_pano = null;
    }
    
    $("pano").innerHTML = "";
*/
    if(response)
    {
    
        //$(pano).setStyle({width: '276px'});
        //$(pano).setStyle({height: '276px'});


    
        var panoramaOptions = { latlng:response };
        g_pano = new GStreetviewPanorama($("pano"), panoramaOptions);
        
        GEvent.addListener(g_pano, "error", function(errorCode){ 
            if (errorCode == FLASH_UNAVAILABLE) 
            {    
                $("pano").innerHTML='The Flash control is unavailable in your browser.'; 
            }    
        });  
        //$(pano).show();

    } 
    else
    {
        $("pano").innerHTML='Unable to get Street View data from Google servers.';
    };    
}


function showPlaceLinks(transport)
{
    var json = transport.responseText.evalJSON();   
     
    for(var i=0;i<json.length;i++)
    {
        showLink(json[i]);      
    }

}

function showLink(item)
{
    var el; 
    var cb;
    
    el = document.createElement('a');
    el.innerHTML = decodeURIComponent(item.url);
    el.href = decodeURIComponent(item.url);
    el.style.fontSize = "10px";
    el.target="_blank";
    $("showlinks").appendChild(el);        
    
    if(item.cb != "None")
        cb=item.cb;
    else
        cb="Anonymous";
        
    el = document.createElement('p');
    el.innerHTML = item.desc;
    $("showlinks").appendChild(el);  
    
    el = document.createElement('p');
    el.innerHTML = "Created by&nbsp;" + cb;
    el.style.fontWeight = "lighter";
    el.style.fontSize = "9px";
    $("showlinks").appendChild(el);  
              
    el = document.createElement('hr');            
    $("showlinks").appendChild(el);  
}
            
function showPlaceComments(transport)
{
    var json = transport.responseText.evalJSON();   
     
    for(var i=0;i<json.length;i++)
    {
        showComment(json[i]);      
    }

}

function showComment(item)
{
    var el; 
    var cb;
         
    
    if(item.cb != "None")
        cb=item.cb;
    else
        cb="Anonymous";
        
    el = document.createElement('p');
    el.innerHTML = item.cm;
    $("showcomments").appendChild(el);  
    
    el = document.createElement('p');
    el.innerHTML = "Created by&nbsp;" + cb;
    el.style.fontWeight = "lighter";
    el.style.fontSize = "9px";
    $("showcomments").appendChild(el);  
              
    el = document.createElement('hr');            
    $("showcomments").appendChild(el);  
}
                        
//INFO WINDOW-RELATED FUNCTIONS



// ADD/EDIT/DELETE PLACE FUNCTIONS
function showCreatePlace(latlng)
{    
    var pt = map.fromLatLngToContainerPixel(latlng);
    lastMapPoint = pt;  //store for later
    lastMapLatLng = latlng;
    var x=pt.x;
    var y=pt.y;
    if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
    if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
    pos.apply($("addform"));
    $("addform").style.visibility = "visible";
    $('addformtitle').innerHTML = "<b>Create<b>";
    $('placename').focus();
    $('saveplace').href = "javascript:createPlace();";
    
    /*Recaptcha.create("6Lf2NwIAAAAAAN8ADopVHTuPRluIyt99Z1Jm9asn",
    "recaptcha_div", {
    theme: "red",
    callback: Recaptcha.focus_response_field
    });*/


} 

function showLogin(latlng)
{    
    var pt = map.fromLatLngToContainerPixel(latlng);
    lastMapPoint = pt;  //store for later
    lastMapLatLng = latlng;
    var x=pt.x;
    var y=pt.y;
    if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
    if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
    pos.apply($("loginform"));
    $("loginform").style.visibility = "visible";
    
}

function gotoLogin()
{
    closeLoginForm();
    window.location.href=g_loginURL;
}

function gotoRegister()
{
    closeLoginForm();
    window.open("https://www.google.com/accounts/NewAccount");

}


function closeLoginForm()
{
    $("loginform").style.visibility="hidden";
}



function showEditPlace(id)
{    

    var latlng = new GLatLng(g_currentPlace.lat, g_currentPlace.lng);
    var pt = map.fromLatLngToContainerPixel(latlng);
    lastMapPoint = pt;  //store for later
    lastMapLatLng = latlng;
    var x=pt.x;
    var y=pt.y;
    if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
    if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
    pos.apply($("addform"));
    $("addform").style.visibility = "visible";
    $('placename').value = g_currentPlace.nm;
    $('placedescription').value = g_currentPlace.desc;
   

    var pfs = g_currentPlace.pfs;
    var so = $('features').options;
    
    for (var i = 0; i < so.length; i ++)
    {
        so[i].selected = false;
    }
    
    for(var j=0;j<pfs.length;j++)
    {
        for(var k=0;k<so.length;k++)
        {
            if(String(so[k].value) == String(pfs[j].id))
                so[k].selected = true;
  
        }
    }   
    $('addformtitle').innerHTML = "<b>Edit</b>";    
    $('saveplace').href = "javascript:editPlace(" + id + ");";
    $('placename').focus();

}
 
function hideDivs()
{
    //hide everything
    $("addform").style.visibility="hidden";  
    $("contextmenu").style.visibility = "hidden";
}

function closeAddForm()
{
    //clear all fields
    $("placedescription").value="";
    $("placename").value="";
    var obj = $('features');
    for (var i=0; i < obj.options.length; i++) 
    {
        obj.options[i].selected = false;
    }

    $("addform").style.visibility="hidden";

}


function createPlace()
{
    //submit AJAX
    //store name, lastMapLatLng, map.getZoom(), and type of place
    var params = 'nm=' + $F('placename').escapeHTML() + '&lat=' + lastMapLatLng.lat() + '&lng=' + lastMapLatLng.lng()
        + '&zm=' + map.getZoom() + '&desc=' + $F('placedescription') ;
    
    params += '&features=';
    //debugger;
    var so = $('features').options;
    var first=true;
    for (var i=0; i<so.length; i++) 
    {
        if (so[i].selected) 
        {
            params += so[i].value+',';
        }
    }
        
        
    //alert(params);
    var req = new Ajax.Request('newplace', 
        {   method: 'post',   
            parameters: params,
            onSuccess: function(transport){       
                var response = transport.responseText || "no response text";       
                //alert("Success! \n\n" + response);     
                addNewPlaceMarker(transport);
                },     
            onFailure: function(transport){ alert("Server Exception: " & transport.responseText) }                     
            }); 
    closeAddForm(); 
}

function removePlace(id)
{
    //submit AJAX
    
    input_box=confirm("Are you sure you want to remove this place?");
    if (input_box==true)
    {
        var params = 'id=' + id ;
       
        //alert(params);
        var req = new Ajax.Request('removeplace', 
            {   method: 'post',   
                parameters: params,
                onSuccess: function(transport){       
                    var response = transport.responseText || "no response text";
                    clearInfoWindow();  
                    loadMarkers();     
                    alert(response);     
                    },     
                onFailure: function(){ alert('Something went wrong...') }                     
                }); 
    }
}

function clearInfoWindow()
{
    $("info").innerHTML = "";
    $("pano").innerHTML = "";
    if(g_pano)
    {
        g_pano.remove();
        g_pano = null;
    }
    $("showlinks").innerHTML = "";
    $("showcomments").innerHTML = "";
    rated = 0;
   
}

function editPlace(id)
{

    //submit AJAX
    //store name, lastMapLatLng, map.getZoom(), and type of place
    var params = '&nm=' + $F('placename').escapeHTML() + '&lat=' + lastMapLatLng.lat() + '&lng=' + lastMapLatLng.lng()
        + '&zm=' + map.getZoom() + '&desc=' + $F('placedescription') + '&id=' + id;
    
    params += '&features=';
    //debugger;
    var so = $('features').options;
    var first=true;
    for (var i=0; i<so.length; i++) 
    {
        if (so[i].selected) 
        {
            params += so[i].value+',';
        }
    }
        
        
    //alert(params);
    var req = new Ajax.Request('updateplace', 
        {   method: 'post',   
            parameters: params,
            onSuccess: function(transport){       
                var response = transport.responseText || "no response text";       
                //alert("Success! \n\n" + response);     
                //addNewPlaceMarker(transport);
                },     
            onFailure: function(){ alert('Something went wrong...') }                     
            }); 
    closeAddForm(); 
}


function addNewPlaceMarker(transport)
{
    //debugger;
    var json = transport.responseText.evalJSON();           
    var point = new GLatLng(json[0].lat,json[0].lng);
    var mrkr = new GMarker(point,{title:json[0].name + (json[0].pf.length > 0 ? ": " + json[0].pf : ""), icon: bbicon});
    var am = [];

    ///map.addOverlay(mrkr);
    mrkr.id = json[0].id;

    am.push(mrkr);
    
    if(am.length > 0)
    {
        clusterer.addMarkers( am );
        clusterer.refresh(true);
    }
    

    //mrkr.bindInfoWindowHtml(json[0].name);
    
    allmarkers.push(mrkr);

    clusterer.refresh();
 
    //now update the reverse geocoded information--split out for performance
    var req = new Ajax.Request('updateplacegc', 
        {   method: 'post',   
            parameters: 'id=' + mrkr.id,
            onSuccess: function(transport){       
                var response = transport.responseText || "no response text";       
                },     
            onFailure: function(){ alert('Something went wrong...') }                     
            }); 
    getMarkerInfo(mrkr);

}




function createLink()
{
    //submit AJAX
    //store url and desc
    
    var url = $F('linkurl');
    var re = new RegExp(/\b(https?|ftp):\/\/([-A-Z0-9.]+)(\/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?/i);

    if(!(re.test(url)))
    {
        alert("Please use a valid URL format.")
        return;
    }   
    
   
    var params = 'url=' + encodeURIComponent(url) + '&desc=' + encodeURIComponent($F('linkdesc')) 
        + '&id=' + g_currentPlace.id;
        
        
    //alert(params);
    var req = new Ajax.Request('newlink', 
        {   method: 'post',   
            parameters: params,
            onSuccess: function(transport){       
                var response = transport.responseText || "no response text";       
                //alert("Success! \n\n" + response); 
                var json = transport.responseText.evalJSON();       
                showLink(json[0]);
                },     
            onFailure: function(){ alert('Something went wrong...') }                     
            }); 
            
    clearAddLinkForm(); 
}  

function clearAddLinkForm()
{
    $("linkurl").value="";
    $("linkdesc").value="";
}
    
    
function createComment()
{
    //submit AJAX
    //store url and desc
        
   
    var params = 'comment=' + encodeURIComponent($F('comment')) 
        + '&id=' + g_currentPlace.id;
        
        
    //alert(params);
    var req = new Ajax.Request('newcomment', 
        {   method: 'post',   
            parameters: params,
            onSuccess: function(transport){       
                var response = transport.responseText || "no response text";       
                //alert("Success! \n\n" + response); 
                var json = transport.responseText.evalJSON();       
                showComment(json[0]);
                },     
            onFailure: function(){ alert('Something went wrong...') }                     
            }); 
            
    clearAddCommentForm(); 
}  

function clearAddCommentForm()
{
    $("comment").value="";
}
    
//END ADD NEW PLACE FUNCTIONS




//CONTEXT MENU FUNCTIONS
function showContextMenu(pixel,tile) 
{
    // store the "pixel" info in case we need it later
    // adjust the context menu location if near an egde
    // create a GControlPosition
    // apply it to the context menu, and make the context menu visible
    //hide the add form div just in case
    $("addform").style.visibility="hidden";
    lastMapPoint = pixel;
    var x=pixel.x;
    var y=pixel.y;
    if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
    if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
    pos.apply($("contextmenu"));
    $("contextmenu").style.visibility = "visible";
}

// === functions that perform the context menu options ===
function zoomIn() {
// perform the requested operation
$("contextmenu").style.visibility="hidden";
map.zoomIn();
// hide the context menu now that it has been used
}      
function zoomOut() {
// perform the requested operation
$("contextmenu").style.visibility="hidden";
map.zoomOut();
// hide the context menu now that it has been used
}      
function zoomInHere() {
// perform the requested operation
$("contextmenu").style.visibility="hidden";
var point = map.fromContainerPixelToLatLng(lastMapPoint)
map.zoomIn(point,true);
// hide the context menu now that it has been used
}      
function zoomOutHere() {
// perform the requested operation
$("contextmenu").style.visibility="hidden";
var point = map.fromContainerPixelToLatLng(lastMapPoint)
map.setCenter(point,map.getZoom()-1); // There is no map.zoomOut() equivalent
// hide the context menu now that it has been used
}      
function centreMapHere() {
// perform the requested operation
$("contextmenu").style.visibility="hidden";
var point = map.fromContainerPixelToLatLng(lastMapPoint)
map.setCenter(point);
// hide the context menu now that it has been used
}  


//star rating variables and functions

function updateAvgRating(rating, numratings)
{
    $("rating").title = "Avg Rating (" + numratings + " Ratings)";
    $("rating").innerHTML = 'Avg Rating<br/>';

    for(var r=0;r<rating;r++)
        $("rating").innerHTML += '<img src="static/star_on.gif" />';
        
    for(r=rating; r<5;r++)
        $("rating").innerHTML += '<img src="static/star_off.gif" />'


}


// Rollover for image Stars //
function rating(num){
	sMax = 5;	// Isthe maximum number of stars
	
	if(!rated){
		s = num.id.replace("_", ''); // Get the selected star
		a = 0;
		for(i=1; i<=sMax; i++){		
			if(i<=s){
				$("_"+i).className = "on";
				holder = a+1;
				a++;
			}else{
				$("_"+i).className = "off";
			}
		}
	}
}

// For when you roll out of the the whole thing //
function off(me){
	if(!rated){
		if(!preSet){	
			for(i=1; i<=sMax; i++){		
				$("_"+i).className = "off";
			}
		}else{
			rating(preSet);
		}
	}
}

// When you actually rate something //
function rateIt(me){

	if(!rated)
	{
	    preSet = me;
	    rated=1;
	    sendRate(me);
	    rating(me);
    }
}

// Send the rating information somewhere using Ajax or something like that.
function sendRate(sel)
{
    var req = new Ajax.Request('updateplacerating', 
        {   method: 'post',   
            parameters: 'id=' + g_currentPlace.id + '&rating=' + sel.id.replace("_", ''),
            onSuccess: function(transport){       
                var response = transport.responseText || "no response text";
                var json = transport.responseText.evalJSON();    
                g_currentPlace.rt = json[0].rt;
                g_currentPlace.nrt = json[0].nrt;
                updateAvgRating(Math.round(g_currentPlace.rt),g_currentPlace.nrt);
                },     
            onFailure: function(){ alert('Something went wrong...') }                     
            }); 
            
}




google.setOnLoadCallback(initialize);



