GMap2.prototype.wefiOnLoad = function(o)
{
    function startMML()
    {
        oMap.MML.startMML();
        GEvent.trigger(oMap.mee,'click');
        messageBox.hideWait();
    }
    var oMap = this;
    this.setUIToDefault();

    this.setMapType(G_NORMAL_MAP);
    this.wefiLimitZoomLevels(2,19);

    this.wefiMotionMode = false;
    GEvent.addListener(this, "zoomend", this.wefiOnZoom);
    this.wefiShowMarkers = (o.showMarkers==true)?true:false;
    this.wefiShowCluster = (o.showCluster==true)?true:false;
    this.wefiShowMe = true;//(o.showMe==true)?true:false;
    this.wefiMML = (o.wefiMML==true)?true:false;
    this.wefiMobileMode = o.mobileMode;


    if(o.mml) this.MML = new MML(this);
    this.filter = o.filter;
    this.wefiShowZooom();
    this.wefiSupportCallout = o.supportCallout;
    this.filter.on = (o.wefiFilter==true)?true:false;

    GEvent.addListener(this, "wefiResetMap",function(){
        oMap.wefiResetMap();
    });
    GEvent.addListener(this, "infowindowopen",this.wefiOnInfoWidowOpen);
    GEvent.addListener(this, "extinfowindowopen",this.wefiOnInfoWidowOpen);
    GEvent.addListener(this, "infowindowclose",this.wefiOnInfoWidowClose);
    GEvent.addListener(this, "extinfowindowclose",this.wefiOnInfoWidowClose);
    gEvents.listener("wefiSpotAddedToMap",function(oSpot){oMap.wefiAddMarkerSpot(oSpot)});
    GEvent.addListener(this, "wefiSpotListOnMapRequest",this.wefiShowSpot);
    GEvent.addListener(this, "dragend", function() {});
    GEvent.addListener(this, "moveend", function() {});
    GEvent.addListener(this, "zoomend", this.wefiOnZoom);
    GEvent.addListener(this, "load",function()
    {
        if(o.startMML)
            messageBox.showWait({msg:'Please wait'});
//        else
//            messageBox.showWait({msg:'Loading spots, please wait'});
        oMap.wefiAddOverlay();
        if(this.wefiMobileMode) oMap.wefiLoadNavigation();
        if(!glParseQuery("nomarkers"))
        {
            setInterval(function(){oMap.wefiOnTileRequest();},200);
        }
        else
            messageBox.hideWait();

    });


    /* Set Starting Position */


    if(o.center.r)
    {

        GEvent.trigger(oMap,'wefiSpotListOnMapRequest',{r:o.center.r,click:o.center.rClick},o.center.rIndex);
        this.wefiShowSpot({r:o.center.r,click:true});
        messageBox.hideWait();
        return;
    }else if(o.center.spot)
    {
        var marker = oMap.wefiAddMarkerSpot(o.center.spot,1);
        var z = (spot.defZoom?spot.defZoom:15);
        oMap.wefiSetCenter({lat:o.center.spot.lat,lng:o.center.spot.lng,zoom:parseInt(z,10)});
        if(o.center.spot.wefiEditFlag)
        {
            o.center.spot.wefiEditFlag = false;
            new clsEditSpot().edit(oMap,o.center.spot,marker);
        }
        messageBox.hideWait();
        GEvent.trigger(marker,'click');
        return;
    }
    else if(o.center.u)
    {
        this.wefiGetPerson(o.center.u,function(p)
        {
            oMap.setCenter(new GLatLng(p.lat,p.lng),17)
            var marker = oMap.wefiAddFriendMarker(p);
            GEvent.trigger(marker,'click');
            messageBox.hideWait();
        })
        return;
    }
    else
        this.wefiSetCenter(o.center);

    if(o.startMML)
    {
        if(!gUser.isLoggedIn)
        {
            oMap.wefiShowMarkers = false;
            oMap.wefiShowCluster = false;
            oMap.wefiShowMe = true;
            gUser.onLoggin(function(){startMML();})
        }
        else
            startMML();
    }
}

GMap2.prototype.wefiShowSpot = function(oShow,index)
{
    var oMap = this;
    this.wefiGetSpotDataByID(oShow.r,null,function(marker,spot)
    {
        messageBox.hideWait(function()
        {

        });
    })
}

GMap2.prototype.wefiGetZoom = function()
{
    return this.getZoom()?this.getZoom():16;
}
GMap2.prototype.wefiGetDis = function(spot)
{
    var sO = $("<span></span>");
    var sKM = spot.disKM + " KM";
    var sMI = spot.disMI + " Miles";
    sO.html("(" + sKM + ")")
    sO.attr("title",sKM + ", " + sMI);
    return sO;
}


GMap2.prototype.wefiInMotionCounter = 0;
GMap2.prototype.wefiInMotion = function()
{
    var oMap = this;
    this.wefiMotionMode = true;
    this.wefiShowMarkers = false;
    this.wefiShowCluster = false;
    this.wefiShowMe = false;
    this.wefiMML = false;
    this.filter.on = false;
    this.wefiResetMap();
    this.wefiLimitZoomLevels(3,3);
    this.setZoom(3)
    this.wefiInMotionCounter = 0;
    this.setMapType(G_HYBRID_MAP);
    this.wefiHideZooom();
    var evWindowOpwnd = GEvent.addListener(this, "infowindowopen",function(){setTimeout(function()
    {
        if(!oMap.wefiMotionMode)
        {
            evWindowOpwnd.remove();
            return;
        }
        oMap.wefiInMotionNextSpot(evWindowOpwnd);
    },5000)});
    this.wefiInMotionNextSpot(evWindowOpwnd);
}

GMap2.prototype.wefiInMotionNextSpot = function(evWindowOpwnd)
{
    var oMap = this;
    oMap.wefiInMotionCounter++;
    GEvent.trigger(oMap,'wefiReqest');
    $.get("/maps/wimNext.ajax.php?counter="+ oMap.wefiInMotionCounter,function(html){
        GEvent.trigger(oMap,'wefiReqestDone');
        if(!parseInt(html,10))
        {
            evWindowOpwnd.remove();
            messageBox.showAlert({title:"error",msg:'Server error, Please try again later'})
            return;
        }
        if(!oMap.wefiMotionMode)
        {
            evWindowOpwnd.remove();
            return;
        }
        oMap.wefiAddSpot(html,evWindowOpwnd);
    });
}
GMap2.prototype.wefiAddSpot = function(id,evWindowOpwnd)
{
    var oMap = this;
    oMap.wefiGetSpotDataByID(id,null,function(marker,spot)
    {
        oMap.clearOverlays();
        var marker = oMap.wefiAddMarkerSpot(spot);
        if(!oMap.wefiMotionMode)
        {
            evWindowOpwnd.remove()
            return;
        }
        oMap.wefiCloseInfoWindow();
        GEvent.trigger(marker,'click')
    })
}

GMap2.prototype.wefiHideZooom = function()
{
    $("#divMML").hide();
    $("img[src$=mapcontrols3d3.png]").hide();
}
GMap2.prototype.wefiShowZooom = function()
{
    $("#divMML").show();
    $("img[src$=mapcontrols3d3.png]").show();
}

GMap2.prototype.wefiOnInfoWidowClose = function()
{
}

GMap2.prototype.wefiOnInfoWidowOpen = function()
{
}

GMap2.prototype.mee = function(){};

GMap2.prototype.wefiLoadMe = function()
{
    if(!this.wefiShowMe) return;
    var meicon = new GIcon();
    this.mee = meicon.wefiLoadMe(this);
    this.addOverlay(this.mee);
}


GMap2.prototype.wefiLimitZoomLevels = function(low,height)
{
    G_PHYSICAL_MAP.getMinimumResolution = function () {return low};
    G_NORMAL_MAP.getMinimumResolution = function () {return low};
    G_SATELLITE_MAP.getMinimumResolution = function () {return low};
    G_HYBRID_MAP.getMinimumResolution = function () {return low};
    G_PHYSICAL_MAP.getMaximumResolution = function () {return height};
    G_NORMAL_MAP.getMaximumResolution = function () {return height};
    G_SATELLITE_MAP.getMaximumResolution = function () {return height};
    G_HYBRID_MAP.getMaximumResolution = function () {return height};
}

GMap2.prototype.wefiAddOverlay = function()
{

    GMap2.prototype.wefiTileRequest = true;
    var dl = new GTileLayer(new GCopyrightCollection(''));
    dl.wefiLayer(this);
    this.addOverlay(new GTileLayerOverlay(dl));
    this.wefiLoadMe();
}

GMap2.prototype.wefiRemoveOverlay = function()
{
}

GMap2.prototype.wefiOnZoom = function(a,b)
{
    if(!a) return;
    if(a == b) return;
    this.wefiResetMap();
}

GMap2.prototype.wefiResetMap = function(dontAdd)
{
    this.wefiCloseInfoWindow();
    this.clearOverlays();
    this.wefiTiles = new Array();
    if(!dontAdd)
        this.wefiAddOverlay();
}
GMap2.prototype.wefiTiles = new Array();

GMap2.prototype.wefiCloseInfoWindow = function()
{
    this.closeExtInfoWindow();
    this.closeInfoWindow();
}

GMap2.prototype.wefiSetMapType = function(o)
{
    if(gInIsrael(o))
        this.setMapType(G_SATELLITE_MAP);
    else
    {
        if(wMap.getCurrentMapType().getName() == "Satellite")
            this.setMapType(G_NORMAL_MAP);
    }
}

GMap2.prototype.wefiSetCenter = function(o,x)
{
    this.wefiSetMapType(new GLatLng(o.lat, o.lng));
    this.setCenter(new GLatLng(o.lat, o.lng), o.zoom?o.zoom:this.getZoom());
    if(x) //if loading search location add marker at center
    {
        var sMarker = new GMarker(new GLatLng(o.lat, o.lng));
        this.addOverlay(sMarker);
    }
}

GMap2.prototype.wefiOnTileRequest = function(callback)
{

    var oMap =this;
    if(!this.wefiTileRequest) return;
    var NW = new GLatLng(this.getBounds().getNorthEast().lat(),this.getBounds().getSouthWest().lng());
    var SE = new GLatLng(this.getBounds().getSouthWest().lat(),this.getBounds().getNorthEast().lng());
    var point = {lat:SE.lat(),lng:SE.lng()};
    gEvents.trigger("wefiLatLongToXY",{lat:point.lat,lng:point.lng,z:this.getZoom(),callback:function(x,y){SE.x = x;SE.y = y;}});
    point = {lat:NW.lat(),lng:NW.lng()};
    gEvents.trigger("wefiLatLongToXY",{lat:point.lat,lng:point.lng,z:this.getZoom(),callback:function(x,y)
    {
        if(SE.x<x)
        {
            NW.x = SE.x;
            SE.x = x;
        }
        else
        {
            NW.x = x;
        }
        NW.y = y;
    }});
    if(this.getZoom() == 2)
    {
        NW.x = 0;NW.y = 0;
        SE.x = 3;SE.y = 3;
    }

    var loopy = 1;
    if(NW.y==SE.y)
        SE.y = SE.y + 1;
    var tileList = "";
    while(loopy)
    {
        var myY = NW.y + loopy-1;var loopx = 1;
        while(loopx)
        {
            var myX = NW.x + loopx-1;
            if(!this.wefiTiles[myX]) this.wefiTiles[myX] = new Array();
            if(!this.wefiTiles[myX][myY])
            {
                this.wefiTiles[myX][myY] = 1;
//                if((myX=="9649")&&(myY=="12315")&&(this.getZoom()==15))
//                this.wefiGetMarkers(myX,myY,this.getZoom());
                tileList?tileList+="|":"";
                tileList += myX+","+myY+","+this.getZoom()
            }
            (myX < SE.x)?loopx++:loopx=0;
        }
        (myY < SE.y)?loopy++:loopy=0;
    }

    (tileList)?oMap.wefiGetMarkers(999,999,this.getZoom(),999,tileList):this.wefiTileRequest = false;

}


GMap2.prototype.wefiGetMarkers = function(x,y,z,kid,tileList)
{
    var oMap = this;
    if(this.wefiMotionMode)
        return;

    if(glParseQuery("custom"))
    {
        var eCountry = 6;
        var eRegion = 10;
        var eCity = 11;
        var eCluster = 11;        
    }
    else
    {
        var eCountry = 6;
        var eRegion = 10;
        var eCity = 12;
        var eCluster = 14;        
    }
    if(this.getZoom()<=eCity)
    {
        if(!this.wefiShowCluster) return;
        var level = "eCity";
        if(z<=eRegion)
            level = "eRegion";
        if(z<eCountry)
            level = "eCountry";

        for(var i=0;i<tileList.split('|').length;i++)
        {
            var t = tileList.split('|')[i]
            var sRequrest = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wef="http://wefi.com/services/wefiServices"><soapenv:Header/><soapenv:Body><wef:getTileMetroClusterRequest><wef:tileX>'+t.split(",")[0]+'</wef:tileX><wef:tileY>'+t.split(",")[1]+'</wef:tileY><wef:tileZ>'+t.split(",")[2]+'</wef:tileZ><wef:CNUID>'+gUser.data.cnu+'</wef:CNUID><wef:metroLevel>'+level+'</wef:metroLevel></wef:getTileMetroClusterRequest></soapenv:Body></soapenv:Envelope>';
            GEvent.trigger(oMap,'wefiReqest');
            $.glPostSoapRequest("", sRequrest,function(clusters)
            {
                GEvent.trigger(oMap,'wefiReqestDone');
                messageBox.hideWait()
                if(oMap.wefiMotionMode) return;
                var cAps = $.getNode(clusters,"mClusterAps");
                if(cAps)
                {
                    var t = cAps.length < 5?cAps.length:5;
                    for(var i=0;i<t;i++)
                    {
                        if(oMap.getZoom()<=eCity)
                          oMap.addMarkerCluster(new oMap.jCluster(cAps[i]));
                    }
                }
            })
        }
        return;
    }
    if(this.getZoom()<=eCluster)
    {
        for(var i=0;i<tileList.split('|').length;i++)
        {
            var t = tileList.split('|')[i]
            if(!this.wefiShowCluster) return;
            var sRequrest = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wef="http://wefi.com/services/wefiServices"><soapenv:Header/><soapenv:Body><wef:getTileClusterRequest><wef:tileX>'+t.split(",")[0]+'</wef:tileX><wef:tileY>'+t.split(",")[1]+'</wef:tileY><wef:tileZ>'+t.split(",")[2]+'</wef:tileZ><wef:CNUID>'+gUser.data.cnu+'</wef:CNUID></wef:getTileClusterRequest></soapenv:Body></soapenv:Envelope>';
            GEvent.trigger(oMap,'wefiReqest');
            $.glPostSoapRequest("", sRequrest,function(clusters)
            {
                messageBox.hideWait()
                GEvent.trigger(oMap,'wefiReqestDone');
                if(oMap.wefiMotionMode) return;
                if(oMap.getZoom()<=eCluster)
                    oMap.addMarkerCluster(new oMap.jCluster(clusters));
            })
        }
        return;
    }
    if(!this.wefiShowMarkers) return;
    if(this.filter.People())
    {
        var sRequrest = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wef="http://wefi.com/services/wefiServices"><soapenv:Header/><soapenv:Body><wef:getTilesUsersRequest><wef:tileX>'+x+'</wef:tileX><wef:tileY>'+y+'</wef:tileY><wef:tileZ>'+z+'</wef:tileZ><wef:cnuId>'+gUser.data.cnu+'</wef:cnuId></wef:getTilesUsersRequest></soapenv:Body></soapenv:Envelope>';
        GEvent.trigger(oMap,'wefiReqest');
        $.glPostSoapRequest("", sRequrest,function(peo)
        {
            GEvent.trigger(oMap,'wefiReqestDone');

            if(oMap.wefiMotionMode) return;
            var arrPeo = $.getNode(peo,"users");
            if(!arrPeo) return;
            if(!oMap.filter.People()) return;
            for(var i =0;i<arrPeo.length;i++)
            {
                oMap.wefiAddFriendMarker(new oMap.jPerson(arrPeo[i]));
            }
        })
    }

    if(!this.filter.hasFilter()) return;
    gEvents.trigger("wefiGetTile",{tileList:tileList,type:"json",kid:kid,nocache:glParseQuery("nocache"),f:oFilter,callback:function(aps)
    {
        for(var i=0;i<aps.length;i++)
        {
            var oSpot = oMap.jSpotArray(aps[i]);
            if((oMap.wefiMotionMode)||(!spots)||(oSpot.z!=z)) return;
            if(!oMap.wefiAdvanceSearch)
            {
                if(glParseQuery("classified"))
                {
                    if(oSpot.mapType == "7")
                        gEvents.trigger("wefiSpotAddedToMap",oSpot);
//                        alert("maptype = 7");
                }
                else
                    gEvents.trigger("wefiSpotAddedToMap",oSpot);
            }
            else if(oMap.wefiAdvanceSearch(oSpot))
            {
                gEvents.trigger("wefiSpotAddedToMap",oSpot);
            }
        }
    }});

}





GMap2.prototype.wefiSpotValid = function(oSpot,eCluster)
{
    if(this.wefiAdvanceSearch)
    {
        return this.wefiAdvanceSearch(oSpot);
    }


    if(this.getZoom()<=eCluster)
        return false;
    if(oSpot.isPlace)
    {
        if((!oSpot.ispaid) && (!oFilter.PF))
            return false;
        if((oSpot.ispaid) && (!oFilter.PP))
            return false;
        return true;
    }

    if((oSpot.apgroup==1) && (!oFilter.OP))
        return false;
    if((oSpot.apgroup==5) && (!oFilter.SI))
        return false;
    if((oSpot.apgroup==4) && (!oFilter.LO))
        return false;
    if((oSpot.apgroup==0) && (oFilter.TS != -1))
        return false;
    return true;
}

GMap2.prototype.addMarkerCluster = function(oCluster)
{
    if(!oCluster.ap)return
    var meicon = new GIcon();
    this.addOverlay(meicon.wefiLoadCluster(oCluster,this));
}


GMap2.prototype.wefiLoadArrow = function(oSpot)
{
    if(this.wefiArrow)
        this.removeOverlay(this.wefiArrow);
    var meicon = new GIcon();
    var marker = meicon.wefiLoadArrow(oSpot,this)
    this.addOverlay(marker);
    this.wefiArrow = marker;
    return marker;
}

GMap2.prototype.wefiLoadNavigation = function()
{
    var oMap=this;
    function addOverlays()
    {
        oMap.addOverlay(new GIcon().wefiLoadNavigation({type:"up",oMap:oMap}))
        oMap.addOverlay(new GIcon().wefiLoadNavigation({type:"down",oMap:oMap}))
        oMap.addOverlay(new GIcon().wefiLoadNavigation({type:"left",oMap:oMap}));
        oMap.addOverlay(new GIcon().wefiLoadNavigation({type:"right",oMap:oMap}));
    }
    addOverlays();
    GEvent.addListener(this, "moveend", function()
    {
        addOverlays();
    });
    GEvent.addListener(this, "resize", function()
    {
        addOverlays();
    });
}



GMap2.prototype.wefiAddMarkerSpot = function(oSpot,index,click)
{
    zspot = (glParseQuery("custom"))?11:14
    if((this.getZoom()<=zspot)&&(!this.wefiMotionMode))
        return;
    var meicon = new GIcon();
    var marker = meicon.wefiLoadSpot(oSpot,this,index,click)
    this.addOverlay(marker);
    return marker;
}


GMap2.prototype.wefiAddFriendMarker = function(person)
{
    if(person.id == gUser.data.cnu)
        return;
    var meicon = new GIcon();
    var marker = meicon.wefiLoadPerson(person,this);
    this.addOverlay(marker);
    return marker;
}


GMap2.prototype.jCluster = function(clusterInfo)
{
    this.users = 0;
    this.friends = 0;
    if($.getNode(clusterInfo,"clusterUsers"))
    {
        var users = $.getNode(clusterInfo,"clusterUsers")[0];
        this.users =  parseInt($.getText(users,"userCount"),10);
        this.friends =  parseInt($.getText(users,"friendsCount"),10);

    }
    this.hasPeople = ((this.friends) || (this.users))?1:0;
    cluster = $.getNode(clusterInfo,"clusterAps")?$.getNode(clusterInfo,"clusterAps")[0]:"";
    if(!cluster)
        cluster =  clusterInfo;
    this.name = $.getText(cluster,"location");

    this.lat = $.getText(cluster,"lat");
    this.longt = $.getText(cluster,"long");
    this.metroid = $.getText(cluster,"metroid");
    var groups = $.getNode(cluster,"apCountByGroup")
    if(groups)
    {
        this.openNotVerified = parseInt(groups[0].textContent?groups[0].textContent:groups[0].text,10);
        this.internetVerified = parseInt(groups[1].textContent?groups[1].textContent:groups[1].text,10);
        this.openWefi = parseInt(groups[2].textContent?groups[2].textContent:groups[2].text,10);
        this.lockedWefi= parseInt(groups[3].textContent?groups[3].textContent:groups[3].text,10);
        this.locked = parseInt(groups[4].textContent?groups[4].textContent:groups[4].text,10);
        this.captivePortal = parseInt(groups[5].textContent?groups[5].textContent:groups[5].text,10);
    }
    this.locked = this.locked + this.lockedWefi;
    this.access = this.internetVerified;
    this.accessunknown = this.openNotVerified + this.openWefi;
    this.requires = this.captivePortal;
    this.ap = this.openNotVerified + this.internetVerified + this.openWefi + this.lockedWefi + this.locked + this.captivePortal;
    this.url = "/maps/images/marker.png.php?name="+this.name+"&ap="+this.ap+"&peo="+this.users+"&friend="+this.friends;
}

GMap2.prototype.wefiGetPerson = function(cnu,callback)
{
    var oMap = this;
    var sRequrest = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wef="http://wefi.com/services/wefiServices"><soapenv:Header/><soapenv:Body><wef:getUserProfileRequest><wef:CNUID>'+cnu+'</wef:CNUID></wef:getUserProfileRequest></soapenv:Body></soapenv:Envelope>';
    GEvent.trigger(oMap,'wefiReqest');
    $.glPostSoapRequest("", sRequrest,function(personDom)
    {
        GEvent.trigger(oMap,'wefiReqestDone');
        if(!$.getNode(personDom,"userProfile"))
            return;
        callback(oMap.jPersonFull(personDom,cnu));
    });
}

GMap2.prototype.jPersonFull = function(person,cnu)
{
    var o = Object();
    var up = $.getNode(person,"userProfile")[0];
    o.id=cnu;
    o.lat = $.getText(person,"lat");
    o.lng = $.getText(person,"long");
    o.cnrId = $.getText(person,"cnrId");
    o.ss_id = $.getText(person,"ss_id");
    o.avatarURL = $.getText(person,"avatarURL");
    o.connectionStatus = $.getText(person,"connectionStatus");
    o.locationStreet = $.getText(person,"locationStreet");
    o.locationCity = $.getText(person,"locationCity");
    o.locationCountry = $.getText(person,"locationCountry");
    o.locationState = $.getText(person,"locationState");
    o.userName =  $.getText(up,"userName");
    o.seeWhereIam =  $.getText(up,"seeWhereIam");
    o.seeMyFriendsList =  $.getText(up,"seeMyFriendsList");
    o.nick =  $.getText(up,"nickName");
    o.firstName =  $.getText(up,"firstName");
    o.lastName =  $.getText(up,"lastName");
    o.gender =  $.getText(up,"gender");
    o.birthDate =  $.getText(up,"birthDate");
    o.tagLine =  $.getText(up,"tagLine");
    o.makeMyEmailPrivate =  $.getText(up,"makeMyEmailPrivate");
    o.blog =  $.getText(up,"blog");
    o.phoneNum =  $.getText(up,"phoneNum");
    o.skype =  $.getText(up,"skype");
    o.ICQ =  $.getText(up,"ICQ");
    o.website =  $.getText(up,"website");
    o.homePhone =  $.getText(up,"homePhone");
    o.yahoo =  $.getText(up,"yahoo");
    o.wantToMeetup =  $.getText(up,"wantToMeetup");
    o.inAromanticMood =  $.getText(up,"inAromanticMood");
    o.liveNearby =  $.getText(up,"liveNearby");
    o.status =  $.getText(up,"status");
    o.AddrCity =  $.getText(up,"AddrCity");
    o.twitter =  $.getText(up,"twitter");
    o.spotsMapped =  $.getText(up,"spotsMapped");
    o.topMappersRank =  $.getText(up,"topMappersRank");
    o.rankedBelow =  $.getText(up,"rankedBelow");
    o.rankedBelowId =  $.getText(up,"rankedBelowId");
    o.spotsToNextRank =  $.getText(up,"spotsToNextRank");
    o.relation = 0
    var icoUser = "/maps/images/people/user.png?id="+(o.id?o.id:"guest");
    var icoFriend = "/maps/images/people/friend.png?id="+(o.id?o.id:"guest");
    o.icon = o.relation?icoUser:icoFriend;
    return o;
}


GMap2.prototype.jPerson = function(person)
{
    this.nick = $.getText(person,"nickName")
    this.id = $.getText(person,"CNUID");
    this.lat = $.getText(person,"lat");
    this.lng = $.getText(person,"long")
    this.relation = $.getText(person,"relation")
    var icoUser = "/maps/images/people/user.png?id="+(this.id?this.id:"guest");
    var icoFriend = "/maps/images/people/friend.png?id="+(this.id?this.id:"guest");
    this.icon = ($.getText(person,"relation")=="eNoRelationship")?icoUser:icoFriend;
}

GMap2.prototype.jSpotArray = function(spot)
{
    spot.updateName = function()
    {
        spot.name = spot.apName?spot.apName + " (" +spot.SSID+ ")":spot.SSID;
        spot.placeName = spot.name;
    }
    spot.getisactiveDesc=function(isactive){switch(isactive){case "2":return "Unknown";case "3":return "Inactive";case "4":return "Active";default:return ""}}
    spot.getCatDescByCatID = function(category){switch(category){case "1":return "Restaurant";case "3":return "Transportation";case "4":return "Park";case "5":return "Library";case "7":return "Hotel";case "8":return "Caf&eacute;";case "9":return "Park";case "11":return "Medical";case "12":return "Community";case "13":return "Retail";case "14":return "Other";case "17":return "School";case "18":return "University";case "19":return "Book store";case "20":return "Airport";case "21":return "Port";case "22":return "Entertainment";case "23":return "Park";case "24":return "Shop";case "25":return "Bar";case "26":return "Shop";case "27":return "Business";case "28":return "Medical";case "29":return "Tourist";case "30":return "Home";case "32":return "WeFi Premium";default:return "Unknown";}}
    spot.getapgroupDesc=function(apgroup){switch(apgroup){case "1":return "Internet verified";case "4":return "Locked";case "5":return "Requires sign-in";case "0":return "Unknown";default:return apgroup}}
    spot.updateHS = function() {spot.hs = spot.category!= "0"?spot.category:(spot.isPlace == "1"?"14":"");}
    spot.updateUrl = function() {ispaid = spot.isPaid?"1":"0";spot.url = "/maps/images/spot.png.php?type="+spot.apgroup+"&isplace="+spot.isplace+"&pay="+ispaid+"&loginType="+spot.loginType+"&multi="+spot.multi+"&hs="+spot.hs+"&v=2";}
    spot.getDateDes = function(s)
    {
        try{
        var oDate = new Date()
        oDate.getDate("02:04:2008")
        var d = s.split("T")[0]
        oDate.setYear(d.split("-")[0]);
        oDate.setMonth(d.split("-")[1]-1);
        oDate.setDate(d.split("-")[2]);
        return oDate.format("mediumDate") + " " + oDate.format("shortTime") ;
        }catch(e){return "N/A"}
    }
    spot.getIcoUrl = function(apgroup,hs,ispaid,zoom,id,isplace,loginType)
    {
        spot.updateUrl();
        return spot.url;
    }
    spot.updateCategoryDesc = function(cat)
    {
        this.category = cat;
        this.categoryDesc = this.getCatDescByCatID(cat);
    }
    spot.updateAPGroupDesc = function(ap)
    {
        this.apgroup = ap;
        this.apgroupDesc = this.getapgroupDesc(ap);
    }

    spot.mapType = spot.geoInfo.mapType;

    spot.id = spot.CNRID;
    spot.lat = spot.lat;
    spot.lng = spot.long;
    spot.long = spot.long;
    spot.longt = spot.long;
    spot.isPaid = spot.isPaid=="1"?1:0;
    spot.ispaid = spot.isPaid;


    spot.ssid = spot.SSID?spot.SSID:"N/A";
    spot.loginType = spot.loginType?spot.loginType:"eUnknown";
    spot.isPlace = parseInt(spot.isPlace,10);
    spot.isplace = spot.isPlace;
    spot.isUpdateable = parseInt(spot.isUpdateable,10);
    spot.multi = spot.multi?parseInt(spot.multi,10):1;

    spot.point = new GLatLng(spot.lat,spot.lng);

    gEvents.trigger("wefiGetDis",{from:new GLatLng(wMap.mee.getLatLng().lat(),wMap.mee.getLatLng().lng()),to:spot.point ,callback:function(s,dis)
    {
        spot.dis = s;
    }})


    spot.updateCategoryDesc(spot.category)
    spot.updateAPGroupDesc(spot.apGroup)

    spot.updateHS();
    spot.updateUrl();
    spot.updateName();
    spot.updateUrl()
    return spot;
}


GMap2.prototype.jSpot = function(spot)
{
    var sp = this;
    sp.data = spot;
    function getCatDescByCatID(category){switch(category){case "1":return "Restaurant";case "3":return "Transportation";case "4":return "Park";case "5":return "Library";case "7":return "Hotel";case "8":return "Caf&eacute;";case "9":return "Park";case "11":return "Medical";case "12":return "Community";case "13":return "Retail";case "14":return "Other";case "17":return "School";case "18":return "University";case "19":return "Book store";case "20":return "Airport";case "21":return "Port";case "22":return "Entertainment";case "23":return "Park";case "24":return "Shop";case "25":return "Bar";case "26":return "Shop";case "27":return "Business";case "28":return "Medical";case "29":return "Tourist";case "30":return "Home";case "32":return "WeFi Premium";default:return "Unknown";}}
    function getapgroupDesc(apgroup){switch(apgroup){case "1":return "Internet verified";case "4":return "Locked";case "5":return "Requires sign-in";case "0":return "Unknown";default:return apgroup}}
    function getisactiveDesc(isactive){switch(isactive){case "2":return "Unknown";case "3":return "Inactive";case "4":return "Active";default:return ""}}
    function getDateDes(s)
    {
        try{
        var oDate = new Date()
        oDate.getDate("02:04:2008")
        var d = s.split("T")[0]
        oDate.setYear(d.split("-")[0]);
        oDate.setMonth(d.split("-")[1]-1);
        oDate.setDate(d.split("-")[2]);
        return oDate.format("mediumDate") + " " + oDate.format("shortTime") ;
        }catch(e){return "N/A"}
    }

    var apInfo =  ($.getNode(spot,"apGeoInfo"))?$.getNode(spot,"apGeoInfo")[0 ]:spot;
    this.lat = $.getText(apInfo,"lat");
    this.lng = $.getText(apInfo,"long");
    this.longt = $.getText(apInfo,"long");
    this.point = new GLatLng(this.lat,this.longt);

    this.id = $.getText(apInfo,"CNRID");
    this.ssid = $.getText(apInfo,"SSID")?$.getText(apInfo,"SSID"):"N/A";

    this.isPlace = parseInt($.getText(apInfo,"isPlace"),10);
    this.placeName = $.getText(apInfo,"apName");
    this.category = $.getText(apInfo,"category");
    this.multi = $.getText(apInfo,"multi");
    this.multi = this.multi?parseInt(this.multi,10):1;
    this.updateCategoryDesc = function(cat)
    {
        sp.category = cat;
        sp.categoryDesc = getCatDescByCatID(cat);
    }
    sp.updateCategoryDesc(sp.category)
    this.apgroup = $.getText(apInfo,"apGroup");
    this.apgroupDesc = getapgroupDesc(this.apgroup)
    this.isUpdateable = parseInt($.getText(apInfo,"isUpdateable"),10);
    this.ispaid = ($.getText(apInfo,"isPaid") == "1")?true:false;
    this.loginType = $.getText(apInfo,"loginType")?$.getText(apInfo,"loginType"):"eUnknown";
    this.dateCreated = getDateDes($.getText(apInfo,"creationDate"));
    this.hs = this.category!= "0"?this.category:(this.isPlace == "1"?"14":"");
    this.updateUrl = function()
    {
        sp.url = getIcoUrl(sp.apgroup,sp.category,sp.ispaid,sp.zoom,sp.id,sp.isPlace,sp.loginType,sp.multi);
    }
    sp.updateUrl();

    this.updateName = function()
    {
        sp.name=sp.placeName?sp.placeName + " (" +sp.ssid+ ")":sp.ssid;
    }
    sp.updateName();

    this.address = "";
    var ADDInfo =  ($.getNode(spot,"apInfo"))?$.getNode(spot,"apInfo")[0]:null;
    if(!ADDInfo)
    {
        if($.getNode(spot,"geoInfo"))
            ADDInfo = $.getNode(spot,"geoInfo")[0];
    }
   if(ADDInfo)
    {
        this.state = $.getText(ADDInfo,"state")?$.getText(ADDInfo,"state"):$.getText(ADDInfo,"State");
        this.country = $.getText(ADDInfo,"country")?$.getText(ADDInfo,"country"):$.getText(ADDInfo,"Country");
        this.city = $.getText(ADDInfo,"city")?$.getText(ADDInfo,"city"):$.getText(ADDInfo,"City");
        this.street = $.getText(ADDInfo,"street")?$.getText(ADDInfo,"street"):$.getText(ADDInfo,"Street");

        this.address = (this.street?this.street+", ":"")+(this.city?this.city+", ":"")+(this.state?this.state + ", " : "")+ (this.country?this.country:"");
        this.address = (this.address.indexOf("???") < 0)?this.address:"";
        this.address = (this.address.indexOf("NOT_AVAILABLE") < 0)?this.address:"";
    }
    if(!this.name)
        this.name = this.ssid;
    function getIcoUrl(apgroup,hs,ispaid,zoom,id,isplace,loginType,multi)
    {
        ispaid = ispaid?"1":"0";
        return "/maps/images/spot.png.php?type="+apgroup+"&isplace="+isplace+"&pay="+ispaid+"&loginType="+loginType+"&hs="+hs+"&multi="+multi+"&v=2";//+"&id=" + this.id;
    }
    apInfo =  ($.getNode(spot,"apInfo"))?$.getNode(spot,"apInfo")[0]:null;
    gEvents.trigger("wefiGetDis",{from:new GLatLng(gUser.data.lat,gUser.data.lng),to:this.point ,callback:function(s,dis)
    {
        sp.dis = s;
    }})

    if(!apInfo) return;
    this.mappedbycnu = $.getText(apInfo,"mappedByCNU");
    this.mappedbyname = $.getText(apInfo,"mappedByName");
    this.state = $.getText(apInfo,"state");
    this.state = (this.state == "NOT_AVAILABLE")?"":this.state;
    this.country = $.getText(apInfo,"country");
    this.country = (this.country == "NOT_AVAILABLE")?"":this.country;
    this.city = $.getText(apInfo,"city");
    this.city = (this.city == "NOT_AVAILABLE")?"":this.city;
    this.street = $.getText(apInfo,"street");
    this.street = (this.street == "NOT_AVAILABLE")?"":this.street;
    this.placeName = $.getText(apInfo,"apName");
    this.totalscore = $.getText(apInfo,"totalScore");
    this.tags = $.getText(apInfo,"tags");
    this.tagsDesc = this.tags.replace(/,/g,", ");
    this.isactive = $.getText(apInfo,"isActive");
    this.isactiveDesc = getisactiveDesc(this.isactive);

    this.numReviews = parseInt($.getText(apInfo,"numReviews"),10);
    this.spotURL = $.getText(apInfo,"URL");
    this.proximity = $.getText(apInfo,"proximity");

    var resConUser =  ($.getNode(apInfo,"recentlyConnectedUser"))?$.getNode(apInfo,"recentlyConnectedUser")[0 ]:null;
    if(resConUser)
    {
        this.resCNU = $.getText(resConUser,"CNUID");
        this.resNick = $.getText(resConUser,"nickname");
    }
    this.lastConnect = getDateDes($.getText(apInfo,"lastConnected"));

    this.proximityKM = Math.round(Math.round(this.proximity * 100)/100 * 1.609344*100)/100 + "";
    this.cost = jQuery.trim($.getText(apInfo,"cost"));
    this.hours = $.getText(apInfo,"hours");
    this.ownerid = $.getText(apInfo,"ownerId");
    this.providerid = $.getText(apInfo,"providerId");
    this.phone = $.getText(apInfo,"phone");
    this.email= $.getText(apInfo,"email");
    this.ownerAvatar = "/global/php/userAvatar.php?id="+this.mappedbycnu+"&s=2"+"&t="+new Date().getTime();
//    this.ownerAvatar = "/global/php/userAvatar.php?id="+this.mappedbycnu+"&s=1";
    this.aps = ($.getNode(spot,"aps"))?$.getNode(spot,"aps"):null;
    this.name=this.placeName?this.placeName + " (" +this.ssid+ ")":this.ssid;
    if(!this.name) this.name = this.ssid;
}



GMap2.prototype.wefiRemoveMapLisitener = function()
{
    if(this.wefiOnInfoWindowClose) this.wefiOnInfoWindowClose();
    this.wefiClickHandle.remove();

}

GMap2.prototype.wefiLocate = function(s,callback,silent)
{
    var me = this;

    s = unescape(s);
    function error()
    {
        messageBox.hideWait()
        if(!silent)
            glAlert('Error', 'The location ‘'+s+'’ cannot be found, please try again.');
//            glAlert('Error', 'The location ‘'+Url.decode(s)+'’ cannot be found, please try again.');
    }
    function success(lat,lng,accuracy)
    {
        var z = 0;
        switch (accuracy) {case 0:z = 0;break;case 1:z = 5;break;case 2:z = 8;break;case 3:z = 10;break;case 4:z = 11;break;case 5:z = 14;break;case 6:z = 14;break;case 7:z = 16;break;case 8:z = 16;;case 9:z = 17;break;}
        var o = {lat:lat,lng:lng,z:z};
        callback(lat,lng, 15,true);
        GEvent.trigger(oMap,'wefiLocated',o);
    }

    function GetGoogLocation1(s)
    {
        geocoder = new   GClientGeocoder();
        geocoder.getLocations(s, function(response)
        {
            if (!response)
            {
                error();
                return;
            }
            if (response.Status.code != 200)
            {
                GetGoogLocation2(s);
                return;
            }
            if(gInIsrael(new GLatLng(response.Placemark[0].Point.coordinates[1],response.Placemark[0].Point.coordinates[0])))
            {
                GetGoogLocation2(s);
                return;
            }
            //check possible matches and offer "did you mean?" dialog
            if(response.Placemark.length > 1)
            {
                if(me.didYouMean) me.didYouMean(response,success);
            }
            else
                success(response.Placemark[0].Point.coordinates[1],response.Placemark[0].Point.coordinates[0],response.Placemark[0].AddressDetails.Accuracy);
        });
    }

    function GetGoogLocation2(s)
    {
        var url = '/maps/geo.ajax.php?q='+s;
        $.get(url,function(j){
            eval("var response = " + j);
            if(response.lat == "999")
            {
                error();
                return;
            }
            success(response.lat,response.lng, 9,true);
        })
    }
    

    var oMap = this;
    if($.browser.msie)
        s = Url.encode(s)

    GetGoogLocation1(s);
}

GMap2.prototype.wefiGetSpotDataByID = function(id,marker,callback)
{
    var oMap = this;
    var sRequrest = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wef="http://wefi.com/services/wefiServices"><soapenv:Header/><soapenv:Body><wef:getApInfoRequest><wef:CNRID>'+id+'</wef:CNRID></wef:getApInfoRequest></soapenv:Body></soapenv:Envelope>';
    GEvent.trigger(oMap,'wefiReqest');
    $.glPostSoapRequest("", sRequrest,function(res){
        GEvent.trigger(oMap,'wefiReqestDone');
        spot = new oMap.jSpot(res);
        callback(marker,spot);
    });
}

GMap2.prototype.wefiMaxZoom = function()
{
    if(this.getZoom()>=19) return true;
    if(gInIsrael(this.getCenter()))
        if(this.getZoom()>=17) return true;
    return false;

}
gEvents.listener("wefiGetTile",function(o)
{
    function getSpotsPerTile()
    {
        if($.browser.msie) return 30;
        if(glParseQuery("custom")) return 100;
        if(glParseQuery("limit")) return glParseQuery("limit");
        if(wMap.wefiMobileMode) return 10;
        return 55;
    }

    function getTileList()
    {
        if(glParseQuery("tile"))
        {
            if(o.tileList.indexOf(glParseQuery("tile"))!= -1)
                return glParseQuery("tile")
            messageBox.hideWait()
            return null;
        }
        return o.tileList;
    }
    var t = setTimeout(function(){messageBox.hideWait();$.get("/maps/images/track.html?type=wsTimeOut&method=getTile");},30000);
    var nocache = "0";
    if(o.nocache)
        nocache = "1&date=" + new Date().getTime();
    get(o);
    //setTimeout(function(){get(o)},500);
    
    function get(o)
    {
        if(!getTileList()) return;
        var url= "/maps/tile/get.php?v=4";
        url += "&kid="+o.kid;
        url += "&PF=" + oFilter.PF;
        url += "&PP=" + oFilter.PP;
        url += "&OP=" + oFilter.OP;
        url += "&SI=" + oFilter.SI;
        url += "&LO=" + oFilter.LO;
        url += "&TS=" + oFilter.TS;
        url += "&PE=" + (oFilter.People()?'true':'false');
        url += "&limit=" + getSpotsPerTile();
        url += "&nocache=" + ((o.nocache)?'1':'0');
        url += "&tileList=" + getTileList();

        var url = url;
        if(wMap) GEvent.trigger(wMap,'wefiReqest');


        jQuery.ajax({
            type: "GET",
            url: url+"&type=json",
            dataType: "json",
            success: function(d){
                messageBox.hideWait()
                if(wMap) GEvent.trigger(wMap,'wefiReqestDone');
                clearTimeout(t);
                d = d[1];
                for(i=0;i<d.length;i++)
                {
                    eval('spots = ' + d[i]);
                    //aps = spots.EnvelopeAPS.Body.getTilesApsResponse.aps
                    if(spots.Envelope.Body.getTilesApsResponse)
                    {
                        var aps = spots.Envelope.Body.getTilesApsResponse.aps
                        var Pe = spots.EnvelopePe?spots.EnvelopePe.Body.getTilesApsResponse.aps:null;
                        if(aps)
                        {
                            if(aps.CNRID)
                            {
                                var arr = new Array();
                                arr[0] = aps;
                                aps = arr;
                            }
                            o.callback(aps);
                        }
                        if(Pe)
                        {
                            $.c("PE")
                        }

                    }
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                messageBox.hideWait();
                GEvent.trigger(wMap,'wefiReqestDone');
             }
        });
    }
});

gEvents.listener("wefiResetCacheForTile",function(o)
{
    $.get("/maps/tile/cacheReset.php?lat=" +o.lat + "&lng=" + o.lng + "&d="+new Date().getTime());
})

gEvents.listener("wefiGetADDLocation",function(oData)
{
    var geocoder = new GClientGeocoder()
    geocoder.getLocations(new GLatLng(oData.lat,oData.lng),function(oRevGeo)
    {
        if(oRevGeo.Placemark)
        {
            if(oData.located)
                oData.located(oRevGeo.Placemark[0].address,oRevGeo)
        }
        else
        {
            if(oData.notLocated)
                oData.notLocated();
        }
    });
});


gEvents.listener("wefiGetDis",function(o)
{
    function wefiInUSA(point)
    {
        var wefiBounds = new GLatLngBounds()
        wefiBounds.extend(new GLatLng(59.418255937032335,-141.328125));
        wefiBounds.extend(new GLatLng(58.42012705867864,-51.85546875));
        wefiBounds.extend(new GLatLng(23.676724673360717,-132.1875));
        wefiBounds.extend(new GLatLng(23.354359365593126,-58.53515625));
        return wefiBounds.containsLatLng(point)
    }

    var dis = o.from.distanceFrom(o.to);
    var disKM = dis?(Math.round(dis/10)/100):0;
    var disMil = dis?Math.round(disKM*0.62*100)/100:0;
    if(disMil < 0.2)
    {
        o.callback("Very close",dis);
        return;
    }

    if(disMil > 12)
    {
        o.callback("Very far",dis);
        return;
    }

    if(wefiInUSA(o.from))
        o.callback(disMil + " Miles",dis);
    else
        o.callback(disKM + " KM",dis);
});

gEvents.listener("wefiLatLongToXY",function(o)
{
    var tileX = Math.floor((o.lng/360 + 0.5) * Math.pow(2,o.z));
    var tileY = Math.floor(xn(o.lat) * Math.pow(2,o.z));
    o.callback(tileX,tileY,o.z);
    function rad(p){return p*Math.PI/180}
    function tanrad(p){return Math.tan(rad(p));}
    function xn(lat){return Math.abs(Math.log(tanrad(lat) + Math.sqrt(Math.pow(tanrad(lat),2) + 1))/(2*Math.PI) - 0.5);}
});
;var wMap = null;
var gMapsMsg = null;
$(function(){new clsMapsPage();})
function clsMapsPage()
{
    var didyoumean = $(".mDYM").clone();
    
    function getMapHeight()
    {
        var h = $(window).height() - $("#newHeader").height() - $("#topnav").height() - $("#mapToolbar").height() - $("#mapBottomLegend").height() - 30;
        return h>300?h:300;
    }

    function setDivHeight()
    {
        $("#map").css("height",getMapHeight());
        $("#MapList").css("height",$("#map").height());
        $("#divMapSpotList").css("height",$("#map").height()-$("#diPlacesText").height-10);

        if($.browser.mozilla)
        {
            $("#legendMoreOther").css("bottom","27px").css("left","555px");
            $("#legendMoreCats").css("bottom","27px").css("left","112px");
            $("#legendMorePlaces").css("bottom","22px").css("left","18px");
        } else {
            $("#legendMoreOther").css("bottom","27px").css("left","590px");
            $("#legendMoreCats").css("bottom","27px").css("left","125px");
            $("#legendMorePlaces").css("bottom","22px").css("left","25px");
        }

    }

    function IE6()
    {
        var bv = $.browser.version.split(".");
        if(($.browser.msie)&&(bv[0] >=6)&&(bv[0] <7))
        {
            $("#mapDrawer").hide();
            //$("#map").html()
            glAlert("Compatibility issue","WeFi works best with <a href='http://www.microsoft.com/windows/Internet-explorer/beta/default.aspx'>IE7</a> or higher, <a href='http://firefox.com'>Firefox</a>, <a href='http://chrome.google.com'>Chrome</a>, <a href='http://opera.com'>Opera</a> or <a href='http://www.apple.com/safari/download/'>Safari</a>   please upgrade your Internet explorer or use one of the other browsers")
            return true;
        }
        return false;
    }

    function loadMap()
    {
        wMap = new GMap2($("#map")[0]);
        gMapsMsg = new clsMapsMsg();
        GEvent.addListener(wMap, "wefiReqest",function(){
            //wMap.wefiOnInfoWindowClose();
            gMapsMsg.add(1);
        });
        GEvent.addListener(wMap, "wefiReqestDone",function(){gMapsMsg.done()});

        gEvents.listener("wefiFilterEvent",function(o){GEvent.trigger(wMap,'wefiResetMap');});

        GEvent.addListener(wMap, "load",function()
        {
            if(gUser.data.cnu)
             gUser.get(gUser.data.cnu,0,null);
        });

    }

    function normalModeStyle() {
        $("#WefiInMotion").toggleClass("mapTypeButton").toggleClass("mapTypeButtonOff");
        $(".coBottomLinks").show();
    }

    function motionModeStyle() {
        $("#WefiInMotion").toggleClass("mapTypeButtonOff").toggleClass("mapTypeButton");
        $(".coBottomLinks").hide();
        $("#filterContent").hide();
    }
        
    function showMapFilter() {
        $("#filterContent").show();
        $("#filterButton").toggleClass("mapTypeButton");
        $("#filterButton").toggleClass("mapTypeButtonOff");
    }

    function hideMapFilter() {
        $("#filterContent").hide();
        $("#filterButton").toggleClass("mapTypeButton");
        $("#filterButton").toggleClass("mapTypeButtonOff");
    }

    function filterCount() {
        var fCount = 0;
        fCount += (oFilter.PF)?1:0;
        fCount += (oFilter.PP)?1:0;
        fCount += (oFilter.OP)?1:0;
        fCount += (oFilter.SI)?1:0;
        fCount += (oFilter.LO)?1:0;
        fCount += (oFilter.PE)?1:0;
        $("#filterButton>div").html("Filter ("+fCount+")");
    }


    function getMapInitParameters(lat,lng,zoom,spot)
    {
        var o = new Object();
        o.center = {lat:lat,lng:lng,zoom:zoom,spot:spot,rClick:true,u:glParseQuery("u")};
        o.showMarkers=true;
        o.showCluster = true;
        o.showMe = true;
        o.wefiMML = true;
        o.wefiFilter = true;
        o.filter = oFilter;
        o.mml = true;
        o.supportCallout = true;
        o.startMML = glParseQuery("MML");
        return o;
    }

    function loadNormalMode()
    {
        normalModeStyle();
        wMap.wefiMotionMode = false;
        var starting = new clsMapStartingPoint({locate:wMap.wefiLocate,callback:function(lat,lng,zoom,spot)
        {
            var o = getMapInitParameters(lat,lng,zoom,spot)
            wMap.wefiOnLoad(o);
            gEvents.trigger("wefiStartingPoint",o)
        }});
        $("#WefiInMotion div").html("New spots - Live view")
    }

    function loadMotionMode()
    {
        motionModeStyle();
        wMap.wefiMotionMode = true;
        wMap.wefiInMotion();
        $("#WefiInMotion div").html("Stop Live view")
    }

    function setPageButtonsEvents()
    {
        $("#searchField").glInputDefText(1);
        $("#searchField").keypress(function(event){
            if(!wMap) return;
            if (event.keyCode != 13) return true;
            messageBox.showWait({title:"Locating...",msg:""});
            wMap.wefiLocate($('#searchField').val(),function(lat,lng,z)
            {
                messageBox.hideWait();
                wMap.wefiSetCenter({lat:lat,lng:lng,zoom:z},x)
            });
        })
        $("#searchButton").click(function(){
            if(!wMap) return;
            messageBox.showWait({title:"Locating...",msg:""});
            wMap.wefiLocate($('#searchField').val(),function(lat,lng,z)
            {
                messageBox.hideWait();
                wMap.wefiSetCenter({lat:lat,lng:lng,z:z});
            });
        })
        $("#searchField2").keypress(function(event){
            if(!wMap) return;
            if (event.keyCode != 13) return true;
            wMap.wefiLocate($('#searchField2').val(),function(lat,lng,z){wMap.wefiSetCenter({lat:lat,lng:lng,z:z})});
        })
        $(".buttonGo").click(function(){
            wMap.wefiLocate($('#searchField2').val(),function(lat,lng,z){wMap.wefiSetCenter({lat:lat,lng:lng,z:z})});
        })
        $("#filterContent input").click(filterCount);
        $("#filterButton").hover(showMapFilter,hideMapFilter);
        $("#filterContent").hover(showMapFilter,hideMapFilter);
    }

    function setDidYouMean(response,success)
    {
        console.log(success);
        //dialog for "did you mean?" option
        didyoumean.dialog({
            modal: true,
            autoOpen: false,
            title: "Did you mean?"
        });
        didyoumean.find("ul.dym").html("");

        messageBox.hideWait();
        didyoumean.dialog('open');
        for (var i=0; i<response.Placemark.length; i++)
        {
            console.log(response.Placemark[i]);
            var rAddress = response.Placemark[i].address;
            var rLat = response.Placemark[i].Point.coordinates[1];
            var rLng = response.Placemark[i].Point.coordinates[0];
            var accuracy = response.Placemark[i].AddressDetails.Accuracy;
            didyoumean.find("ul.dym").append(getli(rAddress,rLat,rLng,accuracy,success));
        }
    }

    function getli(address,lat,lng,accuracy,success)
    {
        //create a list item for each possible match
        var li = $("<li></li>");
        li.html(address);
        li.click(function()
        {
            success(lat,lng,accuracy);
            didyoumean.dialog('close');
        });
        li.hover(function(){$(this).addClass("over")},function(){$(this).removeClass("over")});
        return li;
    }

    //get list item lat and long, convert to GLatLng object and send to setMapCenter function
    function liSetMapCenter (address,coordsLat,coordsLng)
    {
        //parse separate lat and lng from list to send data to setMapCenter function
        var oGLatLng = new google.maps.LatLng(coordsLat,coordsLng)
        mapCenter(oGLatLng,address);
    }

    function load()
    {
        setDivHeight();
        setPageButtonsEvents();
        if(IE6()) return false;
        loadMap();
        wMap.wefiMotionMode = true;
        $("#WefiInMotion").click(function(){
            if(!wMap) return;
            wMap.wefiMotionMode = !wMap.wefiMotionMode;
            (wMap.wefiMotionMode)?loadMotionMode():loadNormalMode();
        }).click();
        setTimeout(function(){
            $("#filterButton").show();
            $("#WefiInMotion").show();
        },1000);
        filterCount();

        wMap.didYouMean = setDidYouMean;
    }
    load();
}


function clsMapsMsg()
{
    var me = this;
    this.total = 0;
    this.current = 0;
    this.load = function(){}

    this.done = function(z)
    {
        me.current += 1;
        if(me.current > me.total)
            me.current = me.total;
        me.set(z);
    }

    this.add = function(i,z)
    {
        me.total += i;
        me.loaded += i;
        me.set(z);
    }
    this.set = function(z)
    {
        if(!wMap.wefiMotionMode)
        {
            if(me.total)
                $("#prog").show();

            if(me.total == me.current)// && me.total != "0" )
            {
                setTimeout(function(){
                    GEvent.trigger(wMap,'wefiPrgressDone');
                    $("#prog").fadeOut();
                    me.reset();
                },1500)
            }
        }
    }

    this.reset = function()
    {
        me.total = 0;
        me.current = 0;
        GEvent.trigger(wMap,'wefiProgressDone');
    }
    me.load();
};GIcon.prototype.wefiRandom = function(l)
{
    var r = parseFloat("0.000" + Math.floor(Math.random() * 04))
    return (Math.floor(Math.random() * 2)) ? parseFloat(l) + r : parseFloat(l) - r;
}

GIcon.prototype.wefiLoadCluster = function(oCluster,oMap)
{
    this.image = oCluster.url;
    this.iconAnchor = (oCluster.hasPeople)?new GPoint(56, 50):new GPoint(40, 35);
    this.infoWindowAnchor = (oCluster.hasPeople)?new GPoint(56, -25):new GPoint(50, -25);
    this.iconSize = (oCluster.hasPeople)?new GSize(113, 100):new GSize(81, 70);
    var marker = new GMarker(new GLatLng(oCluster.lat, oCluster.longt), {icon:this,zIndexProcess:function(){return 20;}})
    var markerIn = false;
    var markerLisitener = null;
    GEvent.addListener(marker, 'mouseover',function()
    {
        if(markerIn) return;
        markerIn = true;;
        oMap.removeOverlay(marker)
        oMap.addOverlay(marker)
        markerLisitener = GEvent.addListener(marker, 'click',markerClick);
    });
    GEvent.addListener(marker, 'mouseout',function()
    {
        markerIn = false;
        if(!markerLisitener)
            return;
        GEvent.removeListener(markerLisitener);
        markerLisitener = null;
    });
    //GEvent.addListener(marker, 'click',markerClick);
    function markerClick()
    {
        marker.openExtInfoWindow(oMap,
        "simple_example_window",
        "<div>Loading ... </div>",
        {
            ajaxUrl:"/maps/cluster/cluster.html.php?lat="+oCluster.lat+"&longt="+oCluster.longt,beakOffset: 34,beakOffsetX: 63,ajaxCallback:function()
            {
                var o = oCluster;
                var getZoom = oMap.getZoom() + parseInt((17 - oMap.getZoom()) / 2, 10);
                $("#clZoom").attr("href", "javascript:void(0)");
                $("#clZoom").click(function(){oMap.wefiSetCenter({lat:o.lat,lng:o.longt,zoom:getZoom})});
                $("#bblClose").click(function(){oMap.wefiCloseInfoWindow()});
                $("#clName").html(o.name);
                $("#clAccess:last").html(o.access + "");
                $("#clAccess").AddCommas();
                $("#clAccessunknown").html(o.accessunknown + "");
                $("#clAccessunknown").AddCommas();
                $("#clRequires").html(o.requires + "");
                $("#clRequires").AddCommas();
                $("#clLocked").html(o.locked + "");
                $("#clLocked").AddCommas();
                $("#clUsers").html(o.users + "");
                $("#clUsers").AddCommas();
                o.users?$("#clUsers").parent().css("visibility",""):$("#clUsers").parent().css("visibility","hidden");
                o.friends?$("#clFriends").parent().css("visibility",""):$("#clFriends").parent().css("visibility","hidden");
                $("#clFriends").html(o.friends + "");
                $("#clFriends").AddCommas();
            }
        });
    };
    return marker;
}

GIcon.prototype.wefiLoadArrow = function(o)
{
    this.image = "/mobile/map/images/map_arrow.png";
    this.iconAnchor = new GPoint(25,o.isPlace?60:53)
//    this.iconSize = new GSize(237, 237);
    //this.iconSize = new GSize(24, 31);
    var marker = new GMarker(new GLatLng(o.lat, o.lng), {title: "location",icon:this,zIndexProcess:function(){return 1}})
    return marker;
};

GIcon.prototype.wefiLoadNavigation = function(o)
{

    var me = this;
    var ll = (o.oMap.getBounds().getNorthEast().lat() - o.oMap.getBounds().getSouthWest().lat())/2
    var ln = (o.oMap.getBounds().getNorthEast().lng() - o.oMap.getBounds().getSouthWest().lng())/2
    var lat=null;lng=null;var x=0;y=0;var image = null;
    switch(o.type)
    {
        case "up":
                image = "/mobile/map/images/android_arrow_up.png";
                lat=o.oMap.getCenter().lat() + ll;
                lng=o.oMap.getCenter().lng();
                x=25;y=0;
            break;
        case "down":
                image = "/mobile/map/images/android_arrow_down.png";
                lat=o.oMap.getCenter().lat() - ll;
                lng=o.oMap.getCenter().lng();
                x=25;y=50;
            break;
        case "left":
                image = "/mobile/map/images/android_arrow_left.png";
                lat=o.oMap.getCenter().lat();
                lng=o.oMap.getCenter().lng() -ln ;
                x=5;y=20;
            break;
        case "right":
                image = "/mobile/map/images/android_arrow_right.png";
                lat=o.oMap.getCenter().lat();
                lng=o.oMap.getCenter().lng() +ln;
                x=50;y=20;
            break;
    }
    this.image = image;
    this.iconAnchor = new GPoint(x,y)
    var marker = new GMarker(new GLatLng(lat,lng), {title: "Nav",icon:this,zIndexProcess:function(){return 1}});
    marker.o = o;
    GEvent.addListener(marker, 'click',function()
    {
        GEvent.trigger(o.oMap,'wefiReqest');
        GEvent.trigger(o.oMap,'wefiReqest');
        GEvent.trigger(o.oMap,'wefiReqestDone');
        setTimeout(function(){
            o.oMap.wefiSetCenter({lat:marker.getLatLng().lat(),lng:marker.getLatLng().lng()});
            GEvent.trigger(o.oMap,'wefiReqestDone');
        },1000)
    });
    GEvent.addListener(o.oMap, "moveend", function()
    {
        o.oMap.removeOverlay(marker);        
    });
    GEvent.addListener(o.oMap, "resize", function()
    {
        o.oMap.removeOverlay(marker);
    });
    return marker;
};


GIcon.prototype.wefiLoadSpot = function(oSpot,oMap,index,click,moreinfo)
{
    function iconAnchor(oSpot)
    {
        if(!oSpot.isPlace)
            return new GPoint(8, 8);
        if(oSpot.multi == 1)
            return new GPoint(20, 20);
        return new GPoint(28, 28); 
    }

    function iconSize(oSpot)
    {
        if(!oSpot.isPlace)
            return new GSize(16, 16);
        if(oSpot.multi == 1)
            return new GSize(37, 37);
        if(oSpot.multi > 100)
            return new GSize(69, 69);
        if(oSpot.multi > 10)
            return new GSize(55, 55);
        return new GSize(43, 43);
    }

    function infoWindowAnchor(oSpot)
    {
        if(!oSpot.isPlace)
            return new GPoint(8, 8);
        if(oSpot.multi == 1)
            return new GPoint(20, 10);
        return new GPoint(20, 10);
    }



    this.image = oSpot.url;
    this.iconAnchor = iconAnchor(oSpot);
    this.infoWindowAnchor = infoWindowAnchor(oSpot);
    this.iconSize = iconSize(oSpot);

    function importanceOrder (marker)
    {
        var i = GOverlay.getZIndex(marker.getPoint().lat());
        if((marker.spot.multi > 1))
            i+=9000000;
        else if((marker.spot.isPlace) && (!marker.spot.ispaid))
            i+=7000000;
        else if((marker.spot.isPlace) && (marker.spot.ispaid))
        {
            if(marker.spot.category == '32')
                i+=8000000;
            else
                i+=6000000;      
        }
        else
            switch(marker.spot.apgroup)
            {
                case "0": i+=2000000;break;
                case "4": i+=3000000;break;
                case "1": i+=4000000;break;
                case "5": i+=5000000;break;
                default: i+=1000000;break;
            }

        return index?index:i;
    }
    var marker = new GMarker(new GLatLng(oSpot.lat, oSpot.longt), {title: oSpot.name,icon:this,zIndexProcess:importanceOrder})
    marker.spot = oSpot;
    //GEvent.addListener(marker, 'infowindowopen', function()
    GEvent.addListener(marker, 'infowindowopen', function()
    {
        var a = oMap.fromLatLngToDivPixel(marker.getLatLng())
        var b = oMap.fromLatLngToDivPixel(oMap.getBounds().getSouthWest())
        var c = oMap.fromLatLngToDivPixel(oMap.getBounds().getNorthEast())
        var w = (b.x-a.x) * -1 - 250;
        var ww = w<0?w*-1:0;
        ww = w>300?(w-300)*-1:ww;
        var h = (c.y-a.y) * -1 - 300;
        var hh = h<0?h*-1:0;
        hh = (b.y-a.y)<0?(b.y-a.y):hh
        oMap.panBy(new GSize(ww,hh));
    });

    GEvent.addListener(marker, 'click', function()
    {
        GEvent.trigger(oMap,'wefiSpotClick',oSpot);
        if(!oMap.wefiSupportCallout)
            return;

        oMap.wefiCloseInfoWindow();
        var oDetailsDialog = new spotDetailsDialog();
        var oDetailsDialogSmall = new oDetailsDialog.getDetailsSmall(oSpot,marker,oMap);
        marker.openInfoWindowHtml(oDetailsDialogSmall.get());
    });
    if(click) setTimeout(function(){GEvent.trigger(marker, 'click')},500)

    return marker;
}

GIcon.prototype.wefiLoadPerson = function(person,oMap)
{
    this.image = person.icon;
    this.iconAnchor = new GPoint(0, 22);
    this.infoWindowAnchor = new GPoint(5, 0);
    this.lat = this.wefiRandom(person.lat);
    this.lng = this.wefiRandom(person.lng);
    var marker = new GMarker(new GLatLng(this.lat, this.lng), {title:person.nick,icon:this});
    GEvent.addListener(marker, 'click', function() {
        marker.wefiInfoWindowPerson(person,oMap);
    })

    return marker;
}

GMarker.prototype.wefiInfoWindowPerson = function(person,oMap)
{
    var marker = this
    var cnu = person?person.id:gUser.data.cnu;
    oMap.wefiGetPerson(cnu,function(p){
        var of = $("#userCallout").clone();
        var cs = p.connectionStatus;
        of.find("#friendLink").html(p.nick);
        of.find("#friendLink").click(function(){window.location = "/profile/?id=" + cnu});
        if(p.tagLine)
            of.find("#frTagline").html(p.tagLine);
        else
            of.find("#frTagline").hide();
        of.find("#frEmail").html(p.userName);
        of.find("#frPlaceLink").html(p.ss_id);
        of.find("#frPlaceLink").click(function()
        {
            oMap.wefiGetSpotDataByID(p.cnrId,null,function(marker,spot)
            {
                var marker = oMap.wefiAddMarkerSpot(spot);
                oMap.setCenter(new GLatLng(spot.lat,spot.longt),17)
                GEvent.trigger(marker,'click');
            })

        })
        var dis = marker.getPoint().distanceFrom(oMap.mee.getPoint());

        var disKM = dis?(Math.round(dis/10)/100):0;
        var disMI = dis?Math.round(disKM*0.62*100)/100:0;
        if(disKM<1){
            of.find("#frNick2").html(p.nickName)
            of.find("#frClose").show();
            of.find("#frDistant").hide();
        } else {
            of.find("#frDistance1").html(disMI);
            of.find("#frDistance2").html(disKM);
            of.find("#frDistant").show();
            of.find("#frClose").hide();
        }
        (cnu==gUser.data.cnu)?of.find("#frClose").hide():"";
        of.find("#frAddress").html("N/A");
        of.show();
        of.find("#frAvatar").attr("src", "/global/php/userAvatar.php?s=2&id=" + cnu);
        marker.openInfoWindow(of.get(0));
    });

}

GIcon.prototype.wefiLoadMe = function(oMap)
{
    this.image = "/maps/images/people/me.png";
    this.iconAnchor = new GPoint(10, 32);
    this.infoWindowAnchor = new GPoint(10, 0);
    this.lat = this.wefiRandom(gUser.data.lat);
    this.lng = this.wefiRandom(gUser.data.lng);
    var loc = (gUser.data.lat)?new GLatLng(gUser.data.lat, gUser.data.lng):oMap.getCenter();
    var marker = new GMarker(loc, {title:gUser.data.nickName,icon:this,zIndexProcess:function(){return 1}});
    marker.center = function()
    {
        oMap.wefiSetCenter({lat:gUser.data.lat,lng:gUser.data.lng,zoom:oMap.getZoom()});
    }

    marker.wefiInfoWindowNotConnected = function()
    {
        this.openInfoWindowHtml("<div style='width: 250px; text-align: left;'><h2>Did we get it right?</h2><p>We assume this is your location, but if you <a href='/download/'>download WeFi</a> and login you can let your friends know exactly where you are.</p></div>");
    }


    GEvent.addListener(marker, 'infowindowopen', function()
    {
        var a = wMap.fromLatLngToDivPixel(oMap.mee.getLatLng())
        var b = wMap.fromLatLngToDivPixel(oMap.getBounds().getNorthEast())
        var h = (a.y - b.y)   -370
        var w = (a.x - b.x) *-1 -250
        oMap.panBy(new GSize(w<0?w:0,h<0?h*-1:0));
    });
    GEvent.addListener(marker, 'click', function() {
        if(!gUser.data.connected)
        {
            marker.wefiInfoWindowNotConnected();
            return;
        }
        if (!oMap.MML.MMLStatus)
        {
            marker.wefiInfoWindowPerson(null,oMap);
            return;
        }
        marker.wefiInfoWindowMML(oMap);
    });
    return marker;
}

GMarker.prototype.wefiInfoWindowMML = function(oMap,marker)
{
    var oMarker = this;
    $.get("/maps/callouts/loc.html.php?lat="+this.getLatLng().lat() + "&long="+ this.getLatLng().lng(), function(html)
    {
       //wemap.addEvent.AddMapLisitener();
        var o = $(html);
        o.find("#locAddress").keypress(function(event){
            $("#locNoAddress").attr("checked","checked")
            if (event.keyCode != 13) return true;
                oMap.MML.locGo(oMap);
//            oMap.wefiLocate($('#locNoAddress').val(),function(lat,lng,z){oMap.wefiSetCenter({lat:lat,lng:lng,z:z})});
        })
        o.find("#locGo").click(function()
        {
            oMap.MML.locGo(oMap);
        });
        o.find("#locCancel").click(function(){
            oMap.MML.stopMML;
        });
       oMarker.openInfoWindow(o.get(0));
    });
}

GTileLayer.prototype.wefiLayer = function(oMap)
{
    this.isPng = function(){return true};
    this.getTileUrl = function(tile, zoom)
    {
        oMap.wefiTileRequest = true;
        var googURL = "";//http://mt3.google.com/vt/lyrs=m@107&hl=iw&x="+tile.x+"&y="+tile.y+"&z="+zoom+"&s=Galile";
        if(oMap.getCenter())
            return (gInIsrael(oMap.getCenter()) && (oMap.getCurrentMapType().getName() == "Map"))?googURL:"";
        else
           return "";
    };
    return this;
}




$.fn.rate = function(v,active){
    var me = this;
     this.each(function(init){
         var me = this;
         set(me,v);
         if(active)
             $(this).bind("click",function(e){
                 var rr = oRate($(this).find(".star")[0]);
                 var p=abPos(rr), x=XY(e), oX=x.X-p.X, oY=x.Y-p.Y;;
                 var s = getStars(x.X - $(this).offset().left);
                 set(me,s);
             })
     });

    function set(o,v)
    {
        $(me).find(".curr").css("width",getwidth(v) + "px")
        $(me).attr("weRate",v);
    }
    function oRate(v,o) {
        return v;
        return((typeof(o)=='object'?o:document).getElementById(v));
    }

    function XY(e) {
        if($.browser.msie)
            return {'X':event.clientX+document.body.scrollLeft,'Y':event.clientY+document.body.scrollTop};
        else
            return {'X':e.pageX,'Y':e.pageY};
    }

    function abPos(o) {
        var o=(typeof(o)=='object'?o:oRate(o));
        z={X:0,Y:0};
        while(o!=null)
        {
            z.X+=o.offsetLeft; z.Y+=o.offsetTop; o=o.offsetParent;
        };
        return(z);
    }

    function getStars(oX)
    {
        var s = -1;
        s = (oX<=5)?"0":s;
        s = (oX>5)&&(oX<=15)?"1":s;
        s = (oX>15)&&(oX<=35)?"2":s;
        s = (oX>35)&&(oX<=50)?"3":s;
        s = (oX>50)&&(oX<=65)?"4":s;
        s = (oX>65)&&(oX<=85)?"5":s;
        return s
    }

    function getwidth(s)
    {
        var oX = 0;
        oX = (s<=0)?0:oX;//0star
        oX = (s==1)?15:oX;//1star
        oX = (s==2)?35:oX;//2star
        oX = (s==3)?50:oX;//3star
        oX = (s==4)?65:oX;//4star
        oX = (s>=5)?85:oX;//5star
        return oX;
    }
 };;
;/**
 * jquery.scrollable 1.0.2. Put your HTML scroll.
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/scrollable.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : March 2008
 * Version : 1.0.2 - Tue Feb 24 2009 10:52:04 GMT-0000 (GMT+00:00)
 */
(function($){function fireEvent(opts,name,self,arg){var fn=opts[name];if($.isFunction(fn)){try{return fn.call(self,arg);}catch(error){if(opts.alert){alert("Error calling scrollable."+name+": "+error);}else{throw error;}return false;}}return true;}var current=null;function Scrollable(root,conf){var self=this;if(!current){current=self;}var horizontal=!conf.vertical;var wrap=$(conf.items,root);var index=0;var navi=root.siblings(conf.navi).eq(0);var prev=root.siblings(conf.prev).eq(0);var next=root.siblings(conf.next).eq(0);var prevPage=root.siblings(conf.prevPage).eq(0);var nextPage=root.siblings(conf.nextPage).eq(0);$.extend(self,{getVersion:function(){return[1,0,1];},getIndex:function(){return index;},getConf:function(){return conf;},getSize:function(){return self.getItems().size();},getPageAmount:function(){return Math.ceil(this.getSize()/conf.size);},getPageIndex:function(){return Math.ceil(index/conf.size);},getRoot:function(){return root;},getItemWrap:function(){return wrap;},getItems:function(){return wrap.children();},seekTo:function(i,time,fn){time=time||conf.speed;if($.isFunction(time)){fn=time;time=conf.speed;}if(i<0){i=0;}if(i>self.getSize()-conf.size){return self;}var item=self.getItems().eq(i);if(!item.length){return self;}if(fireEvent(conf,"onBeforeSeek",self,i)===false){return self;}if(horizontal){var left=-(item.outerWidth(true)*i);wrap.animate({left:left},time,conf.easing,fn?function(){fn.call(self);}:null);}else{var top=-(item.outerHeight(true)*i);wrap.animate({top:top},time,conf.easing,fn?function(){fn.call(self);}:null);}if(navi.length){var klass=conf.activeClass;var page=Math.ceil(i/conf.size);page=Math.min(page,navi.children().length-1);navi.children().removeClass(klass).eq(page).addClass(klass);}if(i===0){prev.add(prevPage).addClass(conf.disabledClass);}else{prev.add(prevPage).removeClass(conf.disabledClass);}if(i>=self.getSize()-conf.size){next.add(nextPage).addClass(conf.disabledClass);}else{next.add(nextPage).removeClass(conf.disabledClass);}current=self;index=i;fireEvent(conf,"onSeek",self,i);return self;},move:function(offset,time,fn){var to=index+offset;if(conf.loop&&to>(self.getSize()-conf.size)){to=0;}return this.seekTo(to,time,fn);},next:function(time,fn){return this.move(1,time,fn);},prev:function(time,fn){return this.move(-1,time,fn);},movePage:function(offset,time,fn){return this.move(conf.size*offset,time,fn);},setPage:function(page,time,fn){var size=conf.size;var index=size*page;var lastPage=index+size>=this.getSize();if(lastPage){index=this.getSize()-conf.size;}return this.seekTo(index,time,fn);},prevPage:function(time,fn){return this.setPage(this.getPageIndex()-1,time,fn);},nextPage:function(time,fn){return this.setPage(this.getPageIndex()+1,time,fn);},begin:function(time,fn){return this.seekTo(0,time,fn);},end:function(time,fn){return this.seekTo(this.getSize()-conf.size,time,fn);},reload:function(){return load();},click:function(index,time,fn){var item=self.getItems().eq(index);var klass=conf.activeClass;if(!item.hasClass(klass)&&(index>=0||index<this.getSize())){self.getItems().removeClass(klass);item.addClass(klass);var delta=Math.floor(conf.size/2);var to=index-delta;if(to>self.getSize()-conf.size){to--;}if(to!==index){return this.seekTo(to,time,fn);}}return self;}});if($.isFunction($.fn.mousewheel)){root.bind("mousewheel.scrollable",function(e,delta){var step=$.browser.opera?1:-1;self.move(delta>0?step:-step,50);return false;});}prev.addClass(conf.disabledClass).click(function(){self.prev();});next.click(function(){self.next();});nextPage.click(function(){self.nextPage();});prevPage.addClass(conf.disabledClass).click(function(){self.prevPage();});if(conf.keyboard){$(window).unbind("keypress.scrollable").bind("keypress.scrollable",function(evt){var el=current;if(!el){return;}if(horizontal&&(evt.keyCode==37||evt.keyCode==39)){el.move(evt.keyCode==37?-1:1);return evt.preventDefault();}if(!horizontal&&(evt.keyCode==38||evt.keyCode==40)){el.move(evt.keyCode==38?-1:1);return evt.preventDefault();}return true;});}function load(){navi.each(function(){var nav=$(this);if(nav.is(":empty")||nav.data("me")==self){nav.empty();nav.data("me",self);for(var i=0;i<self.getPageAmount();i++){var item=$("<"+conf.naviItem+"/>").attr("href",i).click(function(e){var el=$(this);el.parent().children().removeClass(conf.activeClass);el.addClass(conf.activeClass);self.setPage(el.attr("href"));return e.preventDefault();});if(i===0){item.addClass(conf.activeClass);}nav.append(item);}}else{var els=nav.children();els.each(function(i){var item=$(this);item.attr("href",i);if(i===0){item.addClass(conf.activeClass);}item.click(function(){nav.find("."+conf.activeClass).removeClass(conf.activeClass);item.addClass(conf.activeClass);self.setPage(item.attr("href"));});});}});if(conf.clickable){self.getItems().each(function(index,arg){var el=$(this);if(!el.data("set")){el.bind("click.scrollable",function(){self.click(index);});el.data("set",true);}});}if(conf.hoverClass){self.getItems().hover(function(){$(this).addClass(conf.hoverClass);},function(){$(this).removeClass(conf.hoverClass);});}return self;}load();var timer=null;function setTimer(){timer=setInterval(function(){self.next();},conf.interval);}if(conf.interval>0){root.hover(function(){clearInterval(timer);},function(){setTimer();});setTimer();}}jQuery.prototype.scrollable=function(conf){var api=this.eq(typeof conf=='number'?conf:0).data("scrollable");if(api){return api;}var opts={size:5,vertical:false,clickable:true,loop:false,interval:0,speed:400,keyboard:true,activeClass:'active',disabledClass:'disabled',hoverClass:null,easing:'swing',items:'.items',prev:'.prev',next:'.next',prevPage:'.prevPage',nextPage:'.nextPage',navi:'.navi',naviItem:'a',onBeforeSeek:null,onSeek:null,alert:true};$.extend(opts,conf);this.each(function(){var el=new Scrollable($(this),opts);$(this).data("scrollable",el);});return this;};})(jQuery);;function clsMapStartingPoint(o)
{
    var me = this;
    var defZoom = glParseQuery("custom")?12:15
    defZoom = glParseQuery("zoom")?parseInt(glParseQuery("zoom"),10):defZoom;
    this.load = function()
    {
        var locateFriend = ((glParseQuery("type") == "ff")&&(glParseQuery("u")));
        var locateSpot = (glParseQuery("r"));
        var locateString = (glParseQuery("q"));
        var locateLat = (glParseQuery("lat"));
        var locateLng = (glParseQuery("lng"));
        if(locateSpot)
            getSpotLocation(glParseQuery("r"),o.callback);
        else if(locateFriend)
            getFriendLocation(glParseQuery("u"));
        else if(locateString)
        {
            o.locate(glParseQuery("q"),function(lat,lng,z)
            {
                o.callback(lat,lng,z);
            });
        }
        else if(locateLat)
        {
            o.callback(locateLat,locateLng, defZoom);
        }
        else if(!gUser.data.located)
        {
            getIPLocation(o.callback);
        }
        else
        {
            o.callback(gUser.data.lat,gUser.data.lng, defZoom);
        }
    }
    function getFriendLocation(fID)
    {
        var sRequrest = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wef="http://wefi.com/services/wefiServices"><soapenv:Header/><soapenv:Body><wef:getUserProfileRequest><wef:CNUID>'+fID+'</wef:CNUID></wef:getUserProfileRequest></soapenv:Body></soapenv:Envelope>';
        messageBox.showWait("wait","Looking for your friend");
        $.glPostSoapRequest("", sRequrest,function(personDom){
            messageBox.hideWait();
            o.callback($.getText(personDom,"lat"), $.getText(personDom,"long"), o.zoom)
        })
    }

    function getSpotLocation(sID,callback)
    {
        wMap.wefiGetSpotDataByID(sID,null,function(marker,spot)
        {
            spot.defZoom = glParseQuery("z")?glParseQuery("z"):defZoom;
            if(glParseQuery("edit"))
                spot.wefiEditFlag = true;
            (spot.lat!='0.0')?callback(null,null,null,spot.lat=='0.0'?null:spot):getIPLocation(callback);
        })
    }


    function getIPLocation(callback)
    {
        var oIP = new clsIPToLocation();
        //messageBox.showWait({title:"searching",msg:"<center>Locating,<br> please wait</center>"})
        oIP.get(function(loc){
          //  messageBox.hideWait();
            gUser.setLat(loc.lat);
            gUser.setLng(loc.long);
            callback(gUser.data.lat,gUser.data.lng, defZoom);
        });

    }
    me.load();
};//var oFilter = new filterObj("mapDrawer");
//oFilter.tabFilter();
//$(function(){if(oFilter.load)oFilter.load();})
//$(window).load(oFilter.set);
//$(oFilter.set);


/*
function filterObj(con)
{
    var container = function(){
        return $("#" + con)};

    var me = this;
    this.tabFilter = tabFilter;
	this.tabInfo = tabInfo;
	this.tabLegend = tabLegend;
    this.get = get;
    this.setCoockie = setCoockie;
    this.visible = visible;
    this.hide = hide;
    this.show = show;
    this.tempHide = tempHide;
    var visible = true;
    this.visible = function(){return visible};
    this.isLoaded = 0;
    function hide()
	{
        if(!container().length) return;
        me.animateClose()
        visible = false;
    }

    function tempHide()
	{
        if(!container().length) return;
        me.animateClose()
    }

    function show(fource)
	{
        if(!container().length) return;
        if(!me.on)
            return;
        me.animateOpen();
        visible = true;
    }

    this.places = function()
    {
        return $("#fltrPlaces").checked();
    }
    this.allSpot = function()
    {
        return $("#fltrHS").checked();
    }

    this.open = function()
    {
        return $("#fltrOpen").checked();
    }

    this.requires = function()
    {
        return $("#fltrRequires").checked();
    }

    this.locked = function()
    {
        return $("#fltrLocked").checked();
    }
    this.recently = function()
    {
        return $("#fltrRecently").checked();
    }


    function getrecently()
	{
        var val = Math.round($("#freqSlider").slider("value"));
        switch(val)
        {
            case 1:
                return "7";
            case 2:
                return "30";
            case 3:
                return "180";
            default:
                return "0";
        }
	}


    function get()
    {
        var f = "";
        if(!me.isLoaded) load();
        if($("#fltrPlaces").checked())
        {
            f += "<wef:filter>PLACES</wef:filter>";
            if($("#fltrPaid").attr("checked"))
                f += "<wef:filter>PAID</wef:filter>";
        }
        if($("#fltrOpen").checked())
            f += "<wef:filter>OPEN_INTERNET_VERIFIED</wef:filter>";
        if(!$("#fltrRecently").checked())
            f += "<wef:filter>OPEN_NOT_VERIFIED</wef:filter>";


        if($("#fltrRequires").checked())
            f += "<wef:filter>REQUIRES_SIGN_IN</wef:filter>";
        if($("#fltrLocked").checked())
            f += "<wef:filter>LOCKED</wef:filter>";
        f+= "<wef:recentTimestamp>"+getrecently()+"</wef:recentTimestamp>";
        return f;
    }
    this.hasFilter = function()
    {
        this.get();
        return !(!($("#fltrOpen").checked()) && !($("#fltrRequires").checked()) && !($("#fltrLocked").checked()))
    }

    this.People = function()
    {
        return $("#fltrPeople").checked();
    }

    this.set = function()
    {
        load();
        if(!$("#fltrPlaces").length) return;
        glCreateCookie("fltrPlaces",$("#fltrPlaces").checked()?"true":"false");
        glCreateCookie("fltrHS",$("#fltrHS").checked()?"true":"false");
        if($("#fltrHS").checked())
            $("#fltrPaid").checked("false");

        glCreateCookie("fltrPaid",$("#fltrPaid").checked()?"true":"false");
        glCreateCookie("fltrOpen",$("#fltrOpen").checked()?"true":"false");
        glCreateCookie("fltrRecently",$("#fltrRecently").checked()?"true":"true");
        glCreateCookie("fltrRequires",$("#fltrRequires").checked()?"true":"false");
        glCreateCookie("fltrLocked",$("#fltrLocked").checked()?"true":"false");
        glCreateCookie("fltrPeople",$("#fltrPeople").checked()?"true":"false");
        glCreateCookie("freqSlider",$("#freqSlider").slider("value"));

        gEvents.trigger("wefiFilterEvent");
    }



    this.setCallback = function()
    {
    }

    var animWorking = false;
    this.animateClose = function()
    {
        if(animWorking)
            return;
        animWorking = true;
        container().animate({width:0},1000,'swing',function(){
//            container().animate({width:40},200,'swing',function(){
////                container().animate({width:0},200,'swing',function(){})
//            })
        })
        setTimeout('$("#mdOpen").show()',1400);
        setTimeout(function(){animWorking = false},1500);
    }

    this.animateOpen = function()
    {
        if(animWorking)
            return;
        animWorking = true;
        container().animate({width:222},1000,'swing',function(){
//            container().animate({width:182},200,'swing',function(){
//  //              $("#mapDrawer").animate({width:222},200,'swing',function(){})
//            })
        })
        $("#mdOpen").hide();
        setTimeout(function(){animWorking = false},1500);
    }

    function load()
	{
        if(me.isLoaded) return;
        visible=true;
        tabFilter();
        $("#mdClose").click(function() {
            me.animateClose();
        });
        $("#mdOpen").click(function() {
            me.animateOpen();
        });
        var sValue = glReadCookie("freqSlider")?glReadCookie("freqSlider"):"4";
        $("#freqSlider").slider({
            value:sValue,
            min:1,
            max:4,
            steps: 1,
            animate: true,
            slide: function(event, ui) {
                onSliderChange();
            }

        });

        glReadCookie("fltrPlaces")?$("#fltrPlaces").checked(glReadCookie("fltrPlaces")):$("#fltrPlaces").checked("true");
        glReadCookie("fltrHS")?$("#fltrHS").checked(glReadCookie("fltrHS")):$("#fltrHS").checked("true");
        glReadCookie("fltrPaid")?$("#fltrPaid").checked(glReadCookie("fltrPaid")):$("#fltrPaid").checked("true");
        glReadCookie("fltrOpen")?$("#fltrOpen").checked(glReadCookie("fltrOpen")):$("#fltrOpen").checked("true");
        glReadCookie("fltrRecently")?$("#fltrRecently").checked(glReadCookie("fltrRecently")):$("#fltrRecently").checked("true");
        glReadCookie("fltrRequires")?$("#fltrRequires").checked(glReadCookie("fltrRequires")):$("#fltrRequires").checked("true");
        glReadCookie("fltrLocked")?$("#fltrLocked").checked(glReadCookie("fltrLocked")):$("#fltrLocked").checked("false");
        glReadCookie("fltrPeople")?$("#fltrPeople").checked(glReadCookie("fltrPeople")):$("#fltrPeople").checked("false");


        //glReadCookie("fltrPeople")?$("#fltrPeople").checked(glReadCookie("fltrPeople")):$("#fltrPeople").checked("false");
        if(glParseQuery("type") == "ff")
            $("#fltrPeople").checked("true");
        me.isLoaded = 1;
    }

    function onSliderChange()
    {
        if($("#freqSlider").slider("value") == glReadCookie("freqSlider") )
            return;
        me.set();
    }

    function setCoockie(oElement)
    {
        glCreateCookie(oElement.id,$("#" + oElement.id).attr("checked"));
    }

    function getCurrentFilter()
	{
		return "open=1;places=0";
	}

	function tabFilter() {
		$("#tabsFilter").show();
		$("#tabsInfo").hide();
		$("#tabsLegend").hide();
		$("#mdFilter").show();
		$("#mdInfo").hide();
		$("#mdLegend").hide();
		$("#mdClose").css("top","123px");
	}

	function tabInfo() {
		$("#tabsFilter").hide();
		$("#tabsInfo").show();
		$("#tabsLegend").hide();
		$("#mdFilter").hide();
		$("#mdInfo").show();
		$("#mdLegend").hide();
		$("#mdClose").css("top","42px");
	}

	function tabLegend() {
		$("#tabsFilter").hide();
		$("#tabsInfo").hide();
		$("#tabsLegend").show();
		$("#mdFilter").hide();
		$("#mdInfo").hide();
		$("#mdLegend").show();
		$("#mdClose").css("top","90px");
        $("#mdOpen").css("top","209px");
    }

}


*/;/*
* ExtInfoWindow Class, v1.0
*  Copyright (c) 2007, Joe Monahan (http://www.seejoecode.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This class lets you add an info window to the map which mimics GInfoWindow
* and allows for users to skin it via CSS.  Additionally it has options to
* pull in HTML content from an ajax request, triggered when a user clicks on
* the associated marker.
*/


/**
 * Creates a new ExtInfoWindow that will initialize by reading styles from css
 *
 * @constructor
 * @param {GMarker} marker The marker associated with the info window
 * @param {String} windowId The DOM Id we will use to reference the info window
 * @param {String} html The HTML contents
 * @param {Object} opt_opts A contianer for optional arguments:
 *    {String} ajaxUrl The Url to hit on the server to request some contents
 *    {Number} paddingX The padding size in pixels that the info window will leave on
 *                    the left and right sides of the map when panning is involved.
 *    {Number} paddingY The padding size in pixels that the info window will leave on
 *                    the top and bottom sides of the map when panning is involved.
 *    {Number} beakOffset The repositioning offset for when aligning the beak element.
 *                    This is used to make sure the beak lines up correcting if the
 *                    info window styling containers a border.
 */
function ExtInfoWindow(marker, windowId, html, opt_opts) {
  this.html_ = html;
  this.marker_ = marker;
  this.infoWindowId_ = windowId;

  this.options_ = opt_opts == null ? {} : opt_opts;
  this.ajaxUrl_ = this.options_.ajaxUrl == null ? null : this.options_.ajaxUrl;
  this.callback_ = this.options_.ajaxCallback == null ? null : this.options_.ajaxCallback;

  this.borderSize_ = this.options_.beakOffset == null ? 0 : this.options_.beakOffset;
  this.paddingX_ = this.options_.paddingX == null ? 0 + this.borderSize_ : this.options_.paddingX + this.borderSize_;
  this.paddingY_ = this.options_.paddingY == null ? 0 + this.borderSize_ : this.options_.paddingY + this.borderSize_;

  this.map_ = null;

  this.container_ = document.createElement('div');
  this.container_.style.position = 'relative';
  this.container_.style.display = 'none';

  this.contentDiv_ = document.createElement('div');
  this.contentDiv_.id = this.infoWindowId_ + '_contents';
  this.contentDiv_.innerHTML = this.html_;
  this.contentDiv_.style.display = 'block';
  this.contentDiv_.style.visibility = 'hidden';

  this.wrapperDiv_ = document.createElement('div');
};

//use the GOverlay class
ExtInfoWindow.prototype = new GOverlay();

/**
 * Called by GMap2's addOverlay method.  Creates the wrapping div for our info window and adds
 * it to the relevant map pane.  Also binds mousedown event to a private function so that they
 * are not passed to the underlying map.  Finally, performs ajax request if set up to use ajax
 * in the constructor.
 * @param {GMap2} map The map that has had this extInfoWindow is added to it.
 */
ExtInfoWindow.prototype.initialize = function(map) {
  this.map_ = map;

  this.defaultStyles = {
    containerWidth: this.map_.getSize().width / 2,
    borderSize: 1
  };

  this.wrapperParts = {
    tl:{t:0, l:0, w:0, h:0, domElement: null},
    t:{t:0, l:0, w:0, h:0, domElement: null},
    tr:{t:0, l:0, w:0, h:0, domElement: null},
    l:{t:0, l:0, w:0, h:0, domElement: null},
    r:{t:0, l:0, w:0, h:0, domElement: null},
    bl:{t:0, l:0, w:0, h:0, domElement: null},
    b:{t:0, l:0, w:0, h:0, domElement: null},
    br:{t:0, l:0, w:0, h:0, domElement: null},
    beak:{t:0, l:0, w:0, h:0, domElement: null},
    close:{t:0, l:0, w:0, h:0, domElement: null}
  };

  for (var i in this.wrapperParts ) {
    var tempElement = document.createElement('div');
    tempElement.id = this.infoWindowId_ + '_' + i;
    tempElement.style.visibility = 'hidden';
    document.body.appendChild(tempElement);
    tempElement = document.getElementById(this.infoWindowId_ + '_' + i);
    var tempWrapperPart = eval('this.wrapperParts.' + i);
    tempWrapperPart.w = parseInt(this.getStyle_(tempElement, 'width'));
    tempWrapperPart.h = parseInt(this.getStyle_(tempElement, 'height'));
    document.body.removeChild(tempElement);
  }
  for (var i in this.wrapperParts) {
    if (i == 'close' ) {
      //first append the content so the close button is layered above it
      this.wrapperDiv_.appendChild(this.contentDiv_);
    }
    var wrapperPartsDiv = null;
    if (this.wrapperParts[i].domElement == null) {
      wrapperPartsDiv = document.createElement('div');
      this.wrapperDiv_.appendChild(wrapperPartsDiv);
    } else {
      wrapperPartsDiv = this.wrapperParts[i].domElement;
    }
    wrapperPartsDiv.id = this.infoWindowId_ + '_' + i;
    wrapperPartsDiv.style.position = 'absolute';
    wrapperPartsDiv.style.width = this.wrapperParts[i].w + 'px';
    wrapperPartsDiv.style.height = this.wrapperParts[i].h + 'px';
    wrapperPartsDiv.style.top = this.wrapperParts[i].t + 'px';

    wrapperPartsDiv.style.left = this.wrapperParts[i].l + 'px';
    this.wrapperParts[i].domElement = wrapperPartsDiv;
  }

  this.map_.getPane(G_MAP_FLOAT_PANE).appendChild(this.container_);
  this.container_.id = this.infoWindowId_;
  var containerWidth  = this.getStyle_(document.getElementById(this.infoWindowId_), 'width');
  this.container_.style.width = (containerWidth == null ? this.defaultStyles.containerWidth : containerWidth);

  this.map_.getContainer().appendChild(this.contentDiv_);
  this.contentWidth = this.getDimensions_(this.container_).width;
  this.contentDiv_.style.width = this.contentWidth + 'px';
  this.contentDiv_.style.position = 'absolute';

  this.container_.appendChild(this.wrapperDiv_);

  GEvent.bindDom(this.container_, 'mousedown', this,this.onClick_);
  GEvent.bindDom(this.container_, 'dblclick', this,this.onClick_);
  GEvent.bindDom(this.container_, 'DOMMouseScroll', this, this.onClick_);


  GEvent.trigger(this.map_, 'extinfowindowopen');
  if (this.ajaxUrl_ != null ) {
    this.ajaxRequest_(this.ajaxUrl_);
  }
};

/**
 * Private function to steal mouse click events to prevent it from returning to the map.
 * Without this links in the ExtInfoWindow would not work, and you could click to zoom or drag
 * the map behind it.
 * @private
 * @param {MouseEvent} e The mouse event caught by this function
 */
ExtInfoWindow.prototype.onClick_ = function(e) {
  if(navigator.userAgent.toLowerCase().indexOf('msie') != -1 && document.all) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  } else {
    //e.preventDefault();
    e.stopPropagation();
  }
};

/**
 * Remove the extInfoWindow container from the map pane.
 */
ExtInfoWindow.prototype.remove = function() {
  if (this.map_.getExtInfoWindow() != null) {
    GEvent.trigger(this.map_, 'extinfowindowbeforeclose');

    GEvent.clearInstanceListeners(this.container_);
    if (this.container_.outerHTML) {
      this.container_.outerHTML = ''; //prevent pseudo-leak in IE
    }
    if (this.container_.parentNode) {
      this.container_.parentNode.removeChild(this.container_);
    }
    this.container_ = null;
    GEvent.trigger(this.map_, 'extinfowindowclose');
    this.map_.setExtInfoWindow_(null);
  }
};

/**
 * Return a copy of this overlay, for the parent Map to duplicate itself in full. This
 * is part of the Overlay interface and is used, for example, to copy everything in the
 * main view into the mini-map.
 * @return {GOverlay}
 */
ExtInfoWindow.prototype.copy = function() {
  return new ExtInfoWindow(this.marker_, this.infoWindowId_, this.html_, this.options_);
};

/**
 * Draw extInfoWindow and wrapping decorators onto the map.  Resize and reposition
 * the map as necessary.
 * @param {Boolean} force Will be true when pixel coordinates need to be recomputed.
 */
ExtInfoWindow.prototype.redraw = function(force) {
  if (!force || this.container_ == null) return;

  //set the content section's height, needed so  browser font resizing does not affect the window's dimensions
  var contentHeight = this.contentDiv_.offsetHeight;
  this.contentDiv_.style.height = contentHeight + 'px';

  //reposition contents depending on wrapper parts.
  //this is necessary for content that is pulled in via ajax
  this.contentDiv_.style.left = this.wrapperParts.l.w + 'px';
  this.contentDiv_.style.top = this.wrapperParts.tl.h + 'px';
  this.contentDiv_.style.visibility = 'visible';

  //Finish configuring wrapper parts that were not set in initialization
  this.wrapperParts.tl.t = 0;
  this.wrapperParts.tl.l = 0;
  this.wrapperParts.t.l = this.wrapperParts.tl.w;
  this.wrapperParts.t.w = (this.wrapperParts.l.w + this.contentWidth + this.wrapperParts.r.w) - this.wrapperParts.tl.w - this.wrapperParts.tr.w;
  this.wrapperParts.t.h = this.wrapperParts.tl.h;
  this.wrapperParts.tr.l = this.wrapperParts.t.w + this.wrapperParts.tl.w;
  this.wrapperParts.l.t = this.wrapperParts.tl.h;
  this.wrapperParts.l.h = contentHeight;
  this.wrapperParts.r.l = this.contentWidth + this.wrapperParts.l.w;
  this.wrapperParts.r.t = this.wrapperParts.tr.h;
  this.wrapperParts.r.h = contentHeight;
  this.wrapperParts.bl.t = contentHeight + this.wrapperParts.tl.h;
  this.wrapperParts.b.l = this.wrapperParts.bl.w;
  this.wrapperParts.b.t = contentHeight + this.wrapperParts.tl.h;
  this.wrapperParts.b.w = (this.wrapperParts.l.w + this.contentWidth + this.wrapperParts.r.w) - this.wrapperParts.bl.w - this.wrapperParts.br.w;
  this.wrapperParts.b.h = this.wrapperParts.bl.h;
  this.wrapperParts.br.l = this.wrapperParts.b.w + this.wrapperParts.bl.w;
  this.wrapperParts.br.t = contentHeight + this.wrapperParts.tr.h;
  this.wrapperParts.close.l = this.wrapperParts.tr.l +this.wrapperParts.tr.w - this.wrapperParts.close.w - this.borderSize_;
  this.wrapperParts.close.t = this.borderSize_;
  this.wrapperParts.beak.l = this.borderSize_ + (this.contentWidth / 2) - (this.wrapperParts.beak.w / 2);
  this.wrapperParts.beak.t = this.wrapperParts.bl.t + this.wrapperParts.bl.h - this.borderSize_;

  //create the decoration wrapper DOM objects
  //append the styled info window to the container
  for (var i in this.wrapperParts) {
    if (i == 'close' ) {
      //first append the content so the close button is layered above it
      this.wrapperDiv_.insertBefore(this.contentDiv_, this.wrapperParts[i].domElement);
    }
    var wrapperPartsDiv = null;
    if (this.wrapperParts[i].domElement == null) {
      wrapperPartsDiv = document.createElement('div');
      this.wrapperDiv_.appendChild(wrapperPartsDiv);
    } else {
      wrapperPartsDiv = this.wrapperParts[i].domElement;
    }
    wrapperPartsDiv.id = this.infoWindowId_ + '_' + i;
    wrapperPartsDiv.style.position='absolute';
    wrapperPartsDiv.style.width = this.wrapperParts[i].w + 'px';
    wrapperPartsDiv.style.height = this.wrapperParts[i].h + 'px';
    wrapperPartsDiv.style.top = this.wrapperParts[i].t + 'px';
    wrapperPartsDiv.style.left = this.wrapperParts[i].l + 'px';
    this.wrapperParts[i].domElement = wrapperPartsDiv;
  }

  //add event handler for the close box
  var currentMarker = this.marker_;
  var thisMap = this.map_;
  GEvent.addDomListener(this.wrapperParts.close.domElement, 'click',
    function() {
      thisMap.closeExtInfoWindow();
    }
  );

  //position the container on the map, over the marker
  var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
  this.container_.style.position = 'absolute';
  var markerIcon = this.marker_.getIcon();
  this.container_.style.left = (pixelLocation.x
    - (this.contentWidth / 2)
    - markerIcon.iconAnchor.x
    + markerIcon.infoWindowAnchor.x
    + this.options_.beakOffsetX
  ) + 'px';
    this.container_.style.top = (pixelLocation.y
    - this.wrapperParts.bl.h
    - contentHeight
    - this.wrapperParts.tl.h
    - this.wrapperParts.beak.h
    - markerIcon.iconAnchor.y
    + markerIcon.infoWindowAnchor.y
    + this.borderSize_
  ) + 'px';

  this.container_.style.display = 'block';

  if(this.map_.getExtInfoWindow() != null) {
    this.repositionMap_();
  }
};

/**
 * Determine the dimensions of the contents to recalculate and reposition the
 * wrapping decorator elements accordingly.
 */
ExtInfoWindow.prototype.resize = function(){

  //Create temporary DOM node for new contents to get new height
  //This is done because if you manipulate this.contentDiv_ directly it causes visual errors in IE6
  var tempElement = this.contentDiv_.cloneNode(true);
  tempElement.id = this.infoWindowId_ + '_tempContents';
  tempElement.style.visibility = 'hidden';
  tempElement.style.height = 'auto';
  document.body.appendChild(tempElement);
  tempElement = document.getElementById(this.infoWindowId_ + '_tempContents');
  var contentHeight = tempElement.offsetHeight;
  document.body.removeChild(tempElement);

  //Set the new height to eliminate visual defects that can be caused by font resizing in browser
  this.contentDiv_.style.height = contentHeight + 'px';

  var contentWidth = this.contentDiv_.offsetWidth;
  var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());

  var oldWindowHeight = this.wrapperParts.t.domElement.offsetHeight + this.wrapperParts.l.domElement.offsetHeight + this.wrapperParts.b.domElement.offsetHeight;
  var oldWindowPosTop = this.wrapperParts.t.domElement.offsetTop;

  //resize info window to look correct for new height
  this.wrapperParts.l.domElement.style.height = contentHeight + 'px';
  this.wrapperParts.r.domElement.style.height = contentHeight + 'px';
  var newPosTop = this.wrapperParts.b.domElement.offsetTop - contentHeight;
  this.wrapperParts.l.domElement.style.top = newPosTop + 'px';
  this.wrapperParts.r.domElement.style.top = newPosTop + 'px';
  this.contentDiv_.style.top = newPosTop + 'px';
  windowTHeight = parseInt(this.wrapperParts.t.domElement.style.height);
  newPosTop -= windowTHeight;
  this.wrapperParts.close.domElement.style.top = newPosTop + this.borderSize_ + 'px';
  this.wrapperParts.tl.domElement.style.top = newPosTop + 'px';
  this.wrapperParts.t.domElement.style.top = newPosTop + 'px';
  this.wrapperParts.tr.domElement.style.top = newPosTop + 'px';

  this.repositionMap_();
};

/**
 * Check to see if the displayed extInfoWindow is positioned off the viewable
 * map region and by how much.  Use that information to pan the map so that
 * the extInfoWindow is completely displayed.
 * @private
 */
ExtInfoWindow.prototype.repositionMap_ = function(){
  //pan if necessary so it shows on the screen
  var mapNE = this.map_.fromLatLngToDivPixel(
    this.map_.getBounds().getNorthEast()
  );
  var mapSW = this.map_.fromLatLngToDivPixel(
    this.map_.getBounds().getSouthWest()
  );
  var markerPosition = this.map_.fromLatLngToDivPixel(
    this.marker_.getPoint()
  );

  var panX = 0;
  var panY = 0;
  var paddingX = this.paddingX_;
  var paddingY = this.paddingY_;
  var infoWindowAnchor = this.marker_.getIcon().infoWindowAnchor;
  var iconAnchor = this.marker_.getIcon().iconAnchor;

  //test top of screen
  var windowT = this.wrapperParts.t.domElement;
  var windowL = this.wrapperParts.l.domElement;
  var windowB = this.wrapperParts.b.domElement;
  var windowR = this.wrapperParts.r.domElement;
  var windowBeak = this.wrapperParts.beak.domElement;

  var offsetTop = markerPosition.y - ( -infoWindowAnchor.y + iconAnchor.y +  this.getDimensions_(windowBeak).height + this.getDimensions_(windowB).height + this.getDimensions_(windowL).height + this.getDimensions_(windowT).height + this.paddingY_);
  if (offsetTop < mapNE.y) {
    panY = mapNE.y - offsetTop;
  } else {
    //test bottom of screen
    var offsetBottom = markerPosition.y + this.paddingY_;
    if (offsetBottom >= mapSW.y) {
      panY = -(offsetBottom - mapSW.y);
    }
  }

  //test right of screen
  var offsetRight = Math.round(markerPosition.x + this.getDimensions_(this.container_).width/2 + this.getDimensions_(windowR).width + this.paddingX_ + infoWindowAnchor.x - iconAnchor.x);
  if (offsetRight > mapNE.x) {
    panX = -( offsetRight - mapNE.x);
  } else {
    //test left of screen
    var offsetLeft = - (Math.round( (this.getDimensions_(this.container_).width/2 - this.marker_.getIcon().iconSize.width/2) + this.getDimensions_(windowL).width + this.borderSize_ + this.paddingX_) - markerPosition.x - infoWindowAnchor.x + iconAnchor.x);
    if( offsetLeft < mapSW.x) {
      panX = mapSW.x - offsetLeft;
    }
  }

  if (panX != 0 || panY != 0 && this.map_.getExtInfoWindow() != null ) {
    this.map_.panBy(new GSize(panX,panY));
  }
};

/**
 * Private function that handles performing an ajax request to the server.  The response
 * information is assumed to be HTML and is placed inside this extInfoWindow's contents region.
 * Last, check to see if the height has changed, and resize the extInfoWindow accordingly.
 * @private
 * @param {String} url The Url of where to make the ajax request on the server
 */
ExtInfoWindow.prototype.ajaxRequest_ = function(url){
  var thisMap = this.map_;
  var thisCallback = this.callback_;
  GDownloadUrl(url, function(response, status){
    var infoWindow = document.getElementById(thisMap.getExtInfoWindow().infoWindowId_ + '_contents');
    if (response == null || status == -1 ) {
      infoWindow.innerHTML = '<span class="error">ERROR: The Ajax request failed to get HTML content from "' + url + '"</span>';
    } else {
      infoWindow.innerHTML = response;
    }
    if (thisCallback != null ) {
      thisCallback();
    }
    thisMap.getExtInfoWindow().resize();
    GEvent.trigger(thisMap, 'extinfowindowupdate');
  });
};

/**
 * Private function derived from Prototype.js to get a given element's
 * height and width
 * @private
 * @param {Object} element The DOM element that will have height and
 *                    width will be calculated for it.
 * @return {Object} Object with keys: width, height
 */
ExtInfoWindow.prototype.getDimensions_ = function(element) {
  var display = this.getStyle_(element, 'display');
  if (display != 'none' && display != null) { // Safari bug
    return {width: element.offsetWidth, height: element.offsetHeight};
  }

  // All *Width and *Height properties give 0 on elements with display none,
  // so enable the element temporarily
  var els = element.style;
  var originalVisibility = els.visibility;
  var originalPosition = els.position;
  var originalDisplay = els.display;
  els.visibility = 'hidden';
  els.position = 'absolute';
  els.display = 'block';
  var originalWidth = element.clientWidth;
  var originalHeight = element.clientHeight;
  els.display = originalDisplay;
  els.position = originalPosition;
  els.visibility = originalVisibility;
  return {width: originalWidth, height: originalHeight};
};

/**
 * Private function derived from Prototype.js to get a given element's
 * value that is associated with the passed style
 * @private
 * @param {Object} element The DOM element that will be checked.
 * @param {String} style The style name that will be have it's value returned.
 * @return {Object}
 */
ExtInfoWindow.prototype.getStyle_ = function(element, style) {
  var found = false;
  style = this.camelize_(style);
  var value = element.style[style];
  if (!value) {
    if (document.defaultView && document.defaultView.getComputedStyle) {
      var css = document.defaultView.getComputedStyle(element, null);
      value = css ? css[style] : null;
    } else if (element.currentStyle) {
      value = element.currentStyle[style];
    }
  }
  if((value == 'auto') && (style == 'width' || style == 'height') && (this.getStyle_(element, 'display') != 'none')) {
    if( style == 'width' ) {
      value = element.offsetWidth;
    }else {
      value = element.offsetHeight;
    }
  }
  return (value == 'auto') ? null : value;
};

/**
 * Private function pulled from Prototype.js that will change a hyphened
 * style name into camel case.
 * @private
 * @param {String} element The string that will be parsed and made into camel case
 * @return {String}
 */
ExtInfoWindow.prototype.camelize_ = function(element) {
  var parts = element.split('-'), len = parts.length;
  if (len == 1) return parts[0];
  var camelized = element.charAt(0) == '-'
    ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
    : parts[0];

  for (var i = 1; i < len; i++) {
    camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
  }
  return camelized;
};

GMap.prototype.ExtInfoWindowInstance_ = null;
GMap.prototype.ClickListener_ = null;
GMap.prototype.InfoWindowListener_ = null;

/**
 * Creates a new instance of ExtInfoWindow for the GMarker.  Register the newly created
 * instance with the map, ensuring only one window is open at a time. If this is the first
 * ExtInfoWindow ever opened, add event listeners to the map to close the ExtInfoWindow on
 * zoom and click, to mimic the default GInfoWindow behavior.
 *
 * @param {GMap} map The GMap2 object where the ExtInfoWindow will open
 * @param {String} cssId The id we will use to reference the info window
 * @param {String} html The HTML contents
 * @param {Object} opt_opts A contianer for optional arguments:
 *    {String} ajaxUrl The Url to hit on the server to request some contents
 *    {Number} paddingX The padding size in pixels that the info window will leave on
 *                    the left and right sides of the map when panning is involved.
 *    {Number} paddingX The padding size in pixels that the info window will leave on
 *                    the top and bottom sides of the map when panning is involved.
 *    {Number} beakOffset The repositioning offset for when aligning the beak element.
 *                    This is used to make sure the beak lines up correcting if the
 *                    info window styling containers a border.
 */
GMarker.prototype.openExtInfoWindow = function(map, cssId, html, opt_opts) {
  if (map == null) {
    throw 'Error in GMarker.openExtInfoWindow: map cannot be null';
    return false;
  }
  if (cssId == null || cssId == '') {
    throw 'Error in GMarker.openExtInfoWindow: must specify a cssId';
    return false;
  }

  map.closeInfoWindow();
  if (map.getExtInfoWindow() != null) {
    map.closeExtInfoWindow();
  }
  if (map.getExtInfoWindow() == null) {
    map.setExtInfoWindow_( new ExtInfoWindow(
      this,
      cssId,
      html,
      opt_opts
    ) );
    if (map.ClickListener_ == null) {
      //listen for map click, close ExtInfoWindow if open
      map.ClickListener_ = GEvent.addListener(map, 'click',
      function(event) {
          if( !event && map.getExtInfoWindow() != null ){
            map.closeExtInfoWindow();
          }
        }
      );
    }
    if (map.InfoWindowListener_ == null) {
      //listen for default info window open, close ExtInfoWindow if open
      map.InfoWindowListener_ = GEvent.addListener(map, 'infowindowopen',
      function(event) {
          if (map.getExtInfoWindow() != null) {
            map.closeExtInfoWindow();
          }
        }
      );
    }
    map.addOverlay(map.getExtInfoWindow());
  }
};

/**
 * Remove the ExtInfoWindow instance
 * @param {GMap2} map The map where the GMarker and ExtInfoWindow exist
 */
GMarker.prototype.closeExtInfoWindow = function(map) {
  if( map.getExtInfWindow() != null ){

    map.closeExtInfoWindow();
  }
};

/**
 * Get the ExtInfoWindow instance from the map
 */
GMap2.prototype.getExtInfoWindow = function(){
  return this.ExtInfoWindowInstance_;
};
/**
 * Set the ExtInfoWindow instance for the map
 * @private
 */
GMap2.prototype.setExtInfoWindow_ = function( extInfoWindow ){
  this.ExtInfoWindowInstance_ = extInfoWindow;
}
/**
 * Remove the ExtInfoWindow from the map
 */
GMap2.prototype.closeExtInfoWindow = function(){
  if( this.getExtInfoWindow() != null ){
      this.ExtInfoWindowInstance_.remove();

  }
};
;var options = {
    script: "tags.php?json=true&limit=6&",
    varname: "input",
    json: true,
    shownoresults: true,
    timeout: 10000,
    delay: 100,
    offsety: 2,
    maxresults: 6,
    callback: function () {}
};

function tags(container)
{
	this.addAll = addAll;
	
	container.click(onContainerClick)

	
	function onContainerClick()
	{
		if($("li input").length>0) return;
		container.append("<li/>");
		var li = container.find("li:last");
		li.append("<input type='text' ' style='width:40px' id='tagField' />");
		var input = $(li).find("input");
		input.attr("id",container);
		var as_json = new bsn.AutoSuggest(container, options);
		input.focus();
		input.blur(saveTag);
		input.keypress(function(event){
			if (event.keyCode != 13) return true;
			saveTag();
		})				
	}
	
	
	function saveTag() 
	{
		if(container.find("input").length == 0) return;
		$("#tagField").remove();
		var tagVal = container.find("input").val();
		container.find("li:last").remove();
		if (!tagVal) return;
		add({
			"id": "5",
			"name": tagVal
		},true);
		
		container.click(onContainerClick);
	}
	
	
	function addAll(Arr)
	{
		$.each(Arr,function(){
			add(this,false);
		})
	}
	
	
	function add(Arr,remove)
	{
		container.append("<li/>")	;
		var li = container.find("li:last");
		li.addClass("tag");
		li.attr("tagid",Arr.id);
		li.attr("name",Arr.name);
        if(remove)
            li.html(Arr.name + "<img src='/maps/images/buttons/tag_close.png'  class='removeTag' />");
        else
            li.html(Arr.name)// + "<img src='/maps/images/buttons/tag_close.png'  class='removeTag' />");

        // click on x img to remove tag
		li.click(function(){return false});
		li.find("img").click(function(){
			$(this).parent("li").remove();
			saveTag();
			return false;
		});			
	}
    this.get = function(){
        var s = "";
        for(var i=0;i<container.find("li").length;i++)
        {
            (s)?s += ",":"";
            s += container.find("li").eq(i).text();
        }
        return s;
    }

    this.reset = function()
    {
        container.find("li").remove();
    }

    function get()
	{
		return "";
	}
	
};/**
 *  author:		Timothy Groves - http://www.brandspankingnew.net
 *	version:	1.2 - 2006-11-17
 *              1.3 - 2006-12-04
 *              2.0 - 2007-02-07
 *              2.1.1 - 2007-04-13
 *              2.1.2 - 2007-07-07
 *              2.1.3 - 2007-07-19
 *
 */


if (typeof(bsn) == "undefined")
	_b = bsn = {};

if (typeof(_b.Autosuggest) == "undefined")
	_b.Autosuggest = {};
else
	alert("Autosuggest is already set!");


_b.AutoSuggest = function (id, param)
{
	// no DOM - give up!
	//
	if (!document.getElementById)
		return 0;
	
	
	// get field via DOM
	//
	this.fld = _b.DOM.gE(id);

	if (!this.fld)
		return 0;
	
	
	// init variables
	//
	this.sInp 	= "";
	this.nInpC 	= 0;
	this.aSug 	= [];
	this.iHigh 	= 0;
	
	
	// parameters object
	//
	this.oP = param ? param : {};
	
	// defaults	
	//
	var k, def = {minchars:1, meth:"get", varname:"input", className:"autosuggest", timeout:2500, delay:500, offsety:-5, shownoresults: true, noresults: "Come up with your own tags!", maxheight: 250, cache: true, maxentries: 25};
	for (k in def)
	{
		if (typeof(this.oP[k]) != typeof(def[k]))
			this.oP[k] = def[k];
	}
	
	
	// set keyup handler for field
	// and prevent autocomplete from client
	//
	var p = this;
	
	// NOTE: not using addEventListener because UpArrow fired twice in Safari
	//_b.DOM.addEvent( this.fld, 'keyup', function(ev){ return pointer.onKeyPress(ev); } );
	
	this.fld.onkeypress 	= function(ev){ return p.onKeyPress(ev); };
	this.fld.onkeyup 		= function(ev){ return p.onKeyUp(ev); };
	
	this.fld.setAttribute("autocomplete","off");
};


_b.AutoSuggest.prototype.onKeyPress = function(ev)
{
	
	var key = (window.event) ? window.event.keyCode : ev.keyCode;


	// set responses to keydown events in the field
	// this allows the user to use the arrow keys to scroll through the results
	// ESCAPE clears the list
	// TAB sets the current highlighted value
	//
	var RETURN = 13;
	var TAB = 9;
	var ESC = 27;
	
	var bubble = 1;

	switch(key)
	{
		case RETURN:
			this.setHighlightedValue();
			bubble = 0;
			break;

		case ESC:
			this.clearSuggestions();
			break;
	}

	return bubble;
};


_b.AutoSuggest.prototype.onKeyUp = function(ev)
{
	var key = (window.event) ? window.event.keyCode : ev.keyCode;
	

	// set responses to keydown events in the field
	// this allows the user to use the arrow keys to scroll through the results
	// ESCAPE clears the list
	// TAB sets the current highlighted value
	//

	var ARRUP = 38;
	var ARRDN = 40;
	
	var bubble = 1;

	switch(key)
	{


		case ARRUP:
			this.changeHighlight(key);
			bubble = 0;
			break;


		case ARRDN:
			this.changeHighlight(key);
			bubble = 0;
			break;
		
		
		default:
			this.getSuggestions(this.fld.value);
	}

	return bubble;
	

};


_b.AutoSuggest.prototype.getSuggestions = function (val)
{
	
	// if input stays the same, do nothing
	//
	if (val == this.sInp)
		return 0;
	
	
	// kill list
	//
	_b.DOM.remE(this.idAs);
	
	
	this.sInp = val;
	
	
	// input length is less than the min required to trigger a request
	// do nothing
	//
	if (val.length < this.oP.minchars)
	{
		this.aSug = [];
		this.nInpC = val.length;
		return 0;
	}
	
	
	var ol = this.nInpC; // old length
	this.nInpC = val.length ? val.length : 0;
	
	
	// if caching enabled, and user is typing (ie. length of input is increasing)
	// filter results out of aSuggestions from last request
	//
	var l = this.aSug.length;
	if (this.nInpC > ol && l && l<this.oP.maxentries && this.oP.cache)
	{
		var arr = [];
		for (var i=0;i<l;i++)
		{
			if (this.aSug[i].value.substr(0,val.length).toLowerCase() == val.toLowerCase())
				arr.push( this.aSug[i] );
		}
		this.aSug = arr;
		
		this.createList(this.aSug);
		
		
		
		return false;
	}
	else
	// do new request
	//
	{
		var pointer = this;
		var input = this.sInp;
		clearTimeout(this.ajID);
		this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
	}

	return false;
};


_b.AutoSuggest.prototype.doAjaxRequest = function (input)
{
	// check that saved input is still the value of the field
	//
	if (input != this.fld.value)
		return false;
	
	
	var pointer = this;
	
	
	// create ajax request
	//
	if (typeof(this.oP.script) == "function")
		var url = this.oP.script(encodeURIComponent(this.sInp));
	else
		var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp);
	
	if (!url)
		return false;
	
	var meth = this.oP.meth;
	var input = this.sInp;
	
	var onSuccessFunc = function (req) { pointer.setSuggestions(req, input) };
	var onErrorFunc = function (status) { alert("AJAX error: "+status); };

	var myAjax = new _b.Ajax();
	myAjax.makeRequest( url, meth, onSuccessFunc, onErrorFunc );
};


_b.AutoSuggest.prototype.setSuggestions = function (req, input)
{
	// if field input no longer matches what was passed to the request
	// don't show the suggestions
	//
	if (input != this.fld.value)
		return false;
	
	
	this.aSug = [];
	
	
	if (this.oP.json)
	{
		var jsondata = eval('(' + req.responseText + ')');
		
		for (var i=0;i<jsondata.results.length;i++)
		{
			this.aSug.push(  { 'id':jsondata.results[i].id, 'value':jsondata.results[i].value, 'info':jsondata.results[i].info }  );
		}
	}
	else
	{

		var xml = req.responseXML;
	
		// traverse xml
		//
		var results = xml.getElementsByTagName('results')[0].childNodes;

		for (var i=0;i<results.length;i++)
		{
			if (results[i].hasChildNodes())
				this.aSug.push(  { 'id':results[i].getAttribute('id'), 'value':results[i].childNodes[0].nodeValue, 'info':results[i].getAttribute('info') }  );
		}
	
	}
	
	this.idAs = "as_"+this.fld.id;
	

	this.createList(this.aSug);

};


_b.AutoSuggest.prototype.createList = function(arr)
{
	var pointer = this;
	
	// get rid of old list
	// and clear the list removal timeout
	//
	_b.DOM.remE(this.idAs);
	this.killTimeout();
	
	
	// if no results, and shownoresults is false, do nothing
	//
	if (arr.length == 0 && !this.oP.shownoresults)
		return false;
	
	
	// create holding div
	//
	var div = _b.DOM.cE("div", {id:this.idAs, className:this.oP.className});	
	
	var hcorner = _b.DOM.cE("div", {className:"as_corner"});
	var hbar = _b.DOM.cE("div", {className:"as_bar"});
	var header = _b.DOM.cE("div", {className:"as_header"});
	header.appendChild(hcorner);
	header.appendChild(hbar);
	div.appendChild(header);
	
	
	// create and populate ul
	//
	var ul = _b.DOM.cE("ul", {id:"as_ul"});
	
	
	// loop throught arr of suggestions
	// creating an LI element for each suggestion
	//
	for (var i=0;i<arr.length;i++)
	{
		// format output with the input enclosed in a EM element
		// (as HTML, not DOM)
		//
		var val = arr[i].value;
		var st = val.toLowerCase().indexOf( this.sInp.toLowerCase() );
		var output = val.substring(0,st) + "<em>" + val.substring(st, st+this.sInp.length) + "</em>" + val.substring(st+this.sInp.length);
		
		
		var span 		= _b.DOM.cE("span", {}, output, true);
		if (arr[i].info != "")
		{
			var br			= _b.DOM.cE("br", {});
			span.appendChild(br);
			var small		= _b.DOM.cE("small", {}, arr[i].info);
			span.appendChild(small);
		}
		
		var a 			= _b.DOM.cE("a", { href:"#" });
		
		var tl 		= _b.DOM.cE("span", {className:"tl"}, " ");
		var tr 		= _b.DOM.cE("span", {className:"tr"}, " ");
		a.appendChild(tl);
		a.appendChild(tr);
		
		a.appendChild(span);
		
		a.name = i+1;
		a.onclick = function () { pointer.setHighlightedValue(); return false; };
		a.onmouseover = function () { pointer.setHighlight(this.name); };
		
		var li = _b.DOM.cE(  "li", {}, a  );
		
		ul.appendChild( li );
	}
	
	
	// no results
	//
	if (arr.length == 0 && this.oP.shownoresults)
	{
		var li = _b.DOM.cE(  "li", {className:"as_warning"}, this.oP.noresults  );
		ul.appendChild( li );
	}
	
	
	div.appendChild( ul );
	
	
	var fcorner = _b.DOM.cE("div", {className:"as_corner"});
	var fbar = _b.DOM.cE("div", {className:"as_bar"});
	var footer = _b.DOM.cE("div", {className:"as_footer"});
	footer.appendChild(fcorner);
	footer.appendChild(fbar);
	div.appendChild(footer);
	
	
	// get position of target textfield
	// position holding div below it
	// set width of holding div to width of field
	//
	var pos = _b.DOM.getPos(this.fld);
	
	div.style.left 		= pos.x + "px";
	div.style.top 		= ( pos.y + this.fld.offsetHeight + this.oP.offsety ) + "px";
	div.style.width 	= this.fld.offsetWidth + "px";
	
	
	// set mouseover functions for div
	// when mouse pointer leaves div, set a timeout to remove the list after an interval
	// when mouse enters div, kill the timeout so the list won't be removed
	//
	div.onmouseover 	= function(){ pointer.killTimeout() };
	div.onmouseout 		= function(){ pointer.resetTimeout() };


	// add DIV to document
	//
	$(div).css("z-index","3000");
	document.getElementsByTagName("body")[0].appendChild(div);
	
	
	// currently no item is highlighted
	//
	this.iHigh = 0;
	
	
	// remove list after an interval
	//
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, this.oP.timeout);
};


_b.AutoSuggest.prototype.changeHighlight = function(key)
{	
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	var n;

	if (key == 40)
		n = this.iHigh + 1;
	else if (key == 38)
		n = this.iHigh - 1;
	
	
	if (n > list.childNodes.length)
		n = list.childNodes.length;
	if (n < 1)
		n = 1;
	
	
	this.setHighlight(n);
};


_b.AutoSuggest.prototype.setHighlight = function(n)
{
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	if (this.iHigh > 0)
		this.clearHighlight();
	
	this.iHigh = Number(n);
	
	list.childNodes[this.iHigh-1].className = "as_highlight";


	this.killTimeout();
};


_b.AutoSuggest.prototype.clearHighlight = function()
{
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	if (this.iHigh > 0)
	{
		list.childNodes[this.iHigh-1].className = "";
		this.iHigh = 0;
	}
};


_b.AutoSuggest.prototype.setHighlightedValue = function ()
{
	if (this.iHigh)
	{
		this.sInp = this.fld.value = this.aSug[ this.iHigh-1 ].value;
		
		// move cursor to end of input (safari)
		//
		this.fld.focus();
		if (this.fld.selectionStart)
			this.fld.setSelectionRange(this.sInp.length, this.sInp.length);
		

		this.clearSuggestions();
		
		// pass selected object to callback function, if exists
		//
		if (typeof(this.oP.callback) == "function")
			this.oP.callback( this.aSug[this.iHigh-1] );
	}
};


_b.AutoSuggest.prototype.killTimeout = function()
{
	clearTimeout(this.toID);
};

_b.AutoSuggest.prototype.resetTimeout = function()
{
	clearTimeout(this.toID);
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, 1000);
};


_b.AutoSuggest.prototype.clearSuggestions = function ()
{
	
	this.killTimeout();
	
	var ele = _b.DOM.gE(this.idAs);
	var pointer = this;
	if (ele)
	{
		var fade = new _b.Fader(ele,1,0,250,function () { _b.DOM.remE(pointer.idAs) });
	}
};


// AJAX PROTOTYPE _____________________________________________


if (typeof(_b.Ajax) == "undefined")
	_b.Ajax = {};



_b.Ajax = function ()
{
	this.req = {};
	this.isIE = false;
};


_b.Ajax.prototype.makeRequest = function (url, meth, onComp, onErr)
{
	
	if (meth != "POST")
		meth = "GET";
	
	this.onComplete = onComp;
	this.onError = onErr;
	
	var pointer = this;
	
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest)
	{
		this.req = new XMLHttpRequest();
		this.req.onreadystatechange = function () { pointer.processReqChange() };
		this.req.open("GET", url, true); //
		this.req.send(null);
	// branch for IE/Windows ActiveX version
	}
	else if (window.ActiveXObject)
	{
		this.req = new ActiveXObject("Microsoft.XMLHTTP");
		if (this.req)
		{
			this.req.onreadystatechange = function () { pointer.processReqChange() };
			this.req.open(meth, url, true);
			this.req.send();
		}
	}
};


_b.Ajax.prototype.processReqChange = function()
{
	
	// only if req shows "loaded"
	if (this.req.readyState == 4) {
		// only if "OK"
		if (this.req.status == 200)
		{
			this.onComplete( this.req );
		} else {
			this.onError( this.req.status );
		}
	}
};


// DOM PROTOTYPE _____________________________________________


if (typeof(_b.DOM) == "undefined")
	_b.DOM = {};


/* create element */
_b.DOM.cE = function ( type, attr, cont, html )
{
	var ne = document.createElement( type );
	if (!ne)
		return 0;
		
	for (var a in attr)
		ne[a] = attr[a];
	
	var t = typeof(cont);
	
	if (t == "string" && !html)
		ne.appendChild( document.createTextNode(cont) );
	else if (t == "string" && html)
		ne.innerHTML = cont;
	else if (t == "object")
		ne.appendChild( cont );

	return ne;
};


/* get element */
_b.DOM.gE = function ( e )
{
	var t=typeof(e);
	if (t == "undefined")
		return 0;
	else if (t == "string")
	{
		var re = document.getElementById( e );
		if (!re)
			return 0;
		else if (typeof(re.appendChild) != "undefined" )
			return re;
		else
			return 0;
	}
	else if (typeof(e.appendChild) != "undefined")
		return e;
	else
		return 0;
};


/* remove element */
_b.DOM.remE = function ( ele )
{
	var e = this.gE(ele);
	
	if (!e)
		return 0;
	else if (e.parentNode.removeChild(e))
		return true;
	else
		return 0;
};


/* get position */
_b.DOM.getPos = function ( e )
{
	var e = this.gE(e);

	var obj = e;

	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	
	var obj = e;
	
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;

	return {x:curleft, y:curtop};
};


// FADER PROTOTYPE _____________________________________________



if (typeof(_b.Fader) == "undefined")
	_b.Fader = {};


_b.Fader = function (ele, from, to, fadetime, callback)
{	
	if (!ele)
		return 0;
	
	this.e = ele;
	
	this.from = from;
	this.to = to;
	
	this.cb = callback;
	
	this.nDur = fadetime;
		
	this.nInt = 50;
	this.nTime = 0;
	
	var p = this;
	this.nID = setInterval(function() { p._fade() }, this.nInt);
};


_b.Fader.prototype._fade = function()
{
	this.nTime += this.nInt;
	
	var ieop = Math.round( this._tween(this.nTime, this.from, this.to, this.nDur) * 100 );
	var op = ieop / 100;
	
	if (this.e.filters) // internet explorer
	{
		try
		{
			this.e.filters.item("DXImageTransform.Microsoft.Alpha").opacity = ieop;
		} catch (e) { 
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			this.e.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+ieop+')';
		}
	}
	else // other browsers
	{
		this.e.style.opacity = op;
	}
	
	
	if (this.nTime == this.nDur)
	{
		clearInterval( this.nID );
		if (this.cb != undefined)
			this.cb();
	}
};


_b.Fader.prototype._tween = function(t,b,c,d)
{
	return b + ( (c-b) * (t/d) );
};;