﻿
if ( window.Netism == undefined )
{
    window.Netism = {};
}

window.Netism.currentPin = null;
window.Netism.OnLoad = window.onload;

var GeoCodeCalc = {};
GeoCodeCalc.EarthRadiusInMiles = 3956.0;
GeoCodeCalc.EarthRadiusInKilometers = 6367.0;
GeoCodeCalc.ToRadian = function(v) { return v * (Math.PI / 180);};
GeoCodeCalc.DiffRadian = function(v1, v2) {
return GeoCodeCalc.ToRadian(v2) - GeoCodeCalc.ToRadian(v1);
};
GeoCodeCalc.CalcDistance = function(lat1, lng1, lat2, lng2, radius) {
    return radius * 2 * Math.asin( Math.min(1, Math.sqrt( ( Math.pow(Math.sin((GeoCodeCalc.DiffRadian(lat1, lat2)) / 2.0), 2.0) + Math.cos(GeoCodeCalc.ToRadian(lat1)) * Math.cos(GeoCodeCalc.ToRadian(lat2)) * Math.pow(Math.sin((GeoCodeCalc.DiffRadian(lng1, lng2)) / 2.0), 2.0) ) ) ) );
};

function NetismMapToggleDisplay(el)
{
    el = document.getElementById(el);
    if ( el.style.display == '' )
        el.style.display = 'none';
    else
        el.style.display = '';
}

function checkIsEnter(e)
{
    if ( !e ) e = window.event;
    return e.which == 13 || e.keyCode == 13;
}

window.onload = function()
{
    window.Netism.OnLoad();
    
    window.Netism.Map = new NetismMap();
    window.Netism.Map.path = window.Netism.Path;
    window.Netism.Map.Download();
    window.Netism.Map.Render();
}

function NetismMapLocation(mid, lid)
{
    this.LocationID = "";
    this.Title = "";
    this.Link = "";
    this.Description = "";
    this.Address = "";
    this.City = "";
    this.State = "";
    this.Zip = "";
    this.Country = "";
    this.Longitude = "";
    this.Latitude = "";
    this.SortOrder = "";
    this.CreatedDate = "";
    this.IsActive = "";
    this.Icon_Idle = "";
    this.Icon_Active = "";
    this.Icon_Popup = "";

    var fieldDiv = null;
    
    for ( var field in this )
    {
        fieldDiv = document.getElementById("NetismMap_" + mid + "_" + lid + "_" + field.toLowerCase().replace("_", "-"));
        if ( fieldDiv == null )
            continue;
        this[ field ] = fieldDiv.innerHTML;
    }
}

function NetismMap()
{
    this.mapControl = null;
    this.mapControls = {};
    this.allLatLong = null;
    this.path = null;
    this.searchers = {};
    this.searchCount = 0;
    this.LocNameGeoCodeMap = {};
    this.matched = {};
    this.pageIdx = 0;
    this.tmpMap = null;

    this.Download = function()
    {
        var e = document.createElement("script");
        var src = 'http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2';
        if ( window.Netism.MapSettings != null && window.Netism.MapSettings.length > 0 
             && window.Netism.MapSettings[0].Language != null && window.Netism.MapSettings[0].Language != "" )
        {
            src += "&mkt=" + window.Netism.MapSettings[0].Language;
        }
        else if ( window.Netism.MapLanguage )
        {
            src += "&mkt=" + window.Netism.MapLanguage;
        }
        e.src = src;
        e.type = "text/javascript";
        document.getElementsByTagName("body")[0].appendChild(e);
    }

    this.Render = function(OnlyModuleID)
    {
        var me = this;
        
        if( window.VEMap === undefined || 
            ( window.Netism.MapSettings && document.getElementById("NetismMap_" + window.Netism.MapSettings[0].ModuleID).attachEvent === undefined ) ||
            ( window.Netism.ModuleId && document.getElementById("NetismMap_" + window.Netism.ModuleId).attachEvent === undefined )
          )
        {
            setTimeout(function() { me.Render(); }, 200);
            return;
        }

        var loc = document.getElementById("nme_search_location");

        if ( loc && loc.value == "" && Netism.MapSettings[0].Location && this.searchCount == 0 )
            loc.value = Netism.MapSettings[0].Location;

        if ( loc == null || loc.value == null || loc.value == "" || Netism.Map.LocNameGeoCodeMap[loc.value] )
        {
            this.RealRender(OnlyModuleID);
            return;
        }

        var v = this.mapControls[Netism.MapSettings[0].ModuleID];
        var me = this;

        if ( v == null )
        {
            v = new VEMap("NetismMap_" + Netism.MapSettings[0].ModuleID);
            v.LoadMap();
        }

        v.Find(null, loc.value, null, null, null, null, null, null, false, false, 
            function(a, b, results, d, e)
            {
                if ( !results || !results.length || results.length == 0 )
                {
                    alert("location not recognized");
                    return;
                }
                loc.value = results[0].Name;
                Netism.Map.LocNameGeoCodeMap[results[0].Name] = results[0].LatLong;
                me.RealRender(OnlyModuleID);
            });
    }

    this.RealRender = function(OnlyModuleID)
    {
        var me = this;

        if ( window.Netism.ModuleId != undefined && window.Netism.ModuleName != undefined )
        {
            if ( window.Netism.ModuleName != "MapSettings" && window.Netism.ModuleName != "EditLocation" )
                return;

            var baseElementId = "dnn_ctr" + window.Netism.ModuleId + "_" + window.Netism.ModuleName + "_";
            var mapDivID = "NetismMap_" + window.Netism.ModuleId;
            var mapDiv = document.getElementById(mapDivID);
            if ( !mapDiv )
                return;
            
            var vem = new VEMap(mapDivID);
            if ( !vem ) return;
            this.mapControl = vem;
            
            var mapStyle = document.getElementById( baseElementId + "ddlStyle" );
            var mapControl = document.getElementById( baseElementId + "ddlControls" );
            
            if ( mapControl )
            {
                mapControl = mapControl.options[ mapControl.selectedIndex ].value;
                if ( mapControl == "-" )
                    vem.HideDashboard();
                else
                    vem.SetDashboardSize(mapControl);
            }

            vem.LoadMap();

            var glat = document.getElementById( baseElementId + "txtLatitude" ).value;
            var glong = document.getElementById( baseElementId + "txtLongitude" ).value;
            var gzoom = document.getElementById( baseElementId + "txtZoom" ).value;
            
            if ( !gzoom || gzoom == "" || gzoom == "0" || isNaN(gzoom) ) gzoom = 10;

            if ( mapStyle )
                mapStyle = mapStyle.options[ mapStyle.selectedIndex ].value;

            if ( mapStyle == "o" || mapStyle == "b" )
            {
                vem.SetBirdseyeScene(new VELatLong(glat, glong));
            }
            else
            {
                if ( glat != "" && glat != "0" && !isNaN(glat) )
                    if ( glong != "" && glong != "0" && !isNaN(glong) )
                        vem.SetCenterAndZoom(new VELatLong(glat, glong), gzoom);

                if ( mapStyle )
                    vem.SetMapStyle(mapStyle);
            }
            
            var myPath = this.path;
            var mapCenter = vem.GetCenter();
            vem.AddPushpin(new VEPushpin(1, mapCenter, this.path + "Images/youarehere.png", "", ""));

            vem.AttachEvent("onchangeview", function(e) {
            
                vem.DeleteAllPushpins();
                var mapCenter = vem.GetCenter();

                if ( !mapCenter ) return;

                vem.AddPushpin(new VEPushpin(1, mapCenter, myPath + "Images/youarehere.png", "", ""));

                var mStyle = vem.GetMapStyle();
                var mLat = "";
                var mLong = "";
                
                if ( mStyle == "b" || mStyle == "o" )
                {
                    var view = vem.GetBirdseyeScene().GetBoundingRectangle();
                    mLat = ( view.TopLeftLatLong.Latitude + view.BottomRightLatLong.Latitude ) / 2;
                    mLong = ( view.BottomRightLatLong.Longitude + view.TopLeftLatLong.Longitude) / 2;
                }
                else
                {
                    mLat = mapCenter.Latitude;
                    mLong = mapCenter.Longitude;
                }

                glat = document.getElementById( baseElementId + "txtLatitude" );
                if ( glat ) glat.value = mLat;

                glong = document.getElementById( baseElementId + "txtLongitude" );
                if ( glong ) glong.value = mLong;

                gzoom = document.getElementById( baseElementId + "txtZoom" );
                if ( gzoom ) gzoom.value = vem.GetZoomLevel();
            });
        }
        else if ( window.Netism != undefined && window.Netism &&
                 window.Netism.MapSettings != undefined && window.Netism.MapSettings &&
                 window.Netism.MapSettings.length )
        {   
            if ( typeof(jQuery) == 'undefined' )
            {
                alert("jQuery needs to be referenced in map settings");
                return;
            }
    
            for ( var mapIdx = 0; mapIdx < window.Netism.MapSettings.length; mapIdx ++ )
            {
                var mapSetting = window.Netism.MapSettings[mapIdx];

                if ( OnlyModuleID && !isNaN(OnlyModuleID) && OnlyModuleID != mapSetting.ModuleID )
                    continue;
                
                var mapDivID = "NetismMap_" + mapSetting.ModuleID;
                var mapDiv = document.getElementById(mapDivID);
                if ( !mapDiv )
                    continue;
                
                var vem = null;
                if ( !this.mapControls[mapSetting.ModuleID] )
                {
                    vem = new VEMap(mapDivID);
                    this.mapControls[mapSetting.ModuleID] = vem;
                        
                    if ( mapSetting.Control == "-" )
                        vem.HideDashboard();
                    else
                        vem.SetDashboardSize(mapSetting.Control);

                    vem.LoadMap();
                    
                    if ( mapSetting.Unit == "k" )
                        vem.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
                    else if ( mapSetting.Unit == "m" )
                        vem.SetScaleBarDistanceUnit(VEDistanceUnit.Miles);

                }

                vem = this.mapControls[mapSetting.ModuleID];
                vem.ModuleID = mapSetting.ModuleID;
                                
                var latlongArr = [];
                this.allLatLong = latlongArr;
                
                var mapLocations = document.getElementById("NetismMap_" + mapSetting.ModuleID + "_Locations");
                if ( !mapLocations )
                    continue;

                var idxFrom = this.pageIdx * mapSetting.PageSize;
                var idxTo = idxFrom + mapSetting.PageSize - 1;

                this.searchCount ++;
                var searcher = new NetismMapSearcher(mapSetting);
                searcher.Search(vem, idxFrom, idxTo, latlongArr);
             
                if ( mapSetting.SearchConfig.IsServerSearch )
                {
                    var sf = document.getElementById("nme_SearchForm");
                    if ( sf ) sf.style.display = '';

                    return;
                }

                this.searchers[mapSetting.ModuleID] = searcher;

                var locations = mapLocations.childNodes;
                var location = null;
                var locCount = 0;
                var locView = null;

                this.matched[mapSetting.ModuleID] = [];
                vem.Clear();
                CheckExternalResource(vem, mapSetting);
                
                for ( var locIdx = 0; locIdx < locations.length; locIdx ++ )
                {
                    if ( !locations[locIdx].id || locations[locIdx].id.indexOf("NetismMap_") != 0 )
                        continue;

                    locCount ++;
                    location = new NetismMapLocation( mapSetting.ModuleID, locCount );
                    locView = document.getElementById("NetismMap_" + mapSetting.ModuleID + "_" + (locIdx+1) + "_Display");

                    if ( isNaN(location.Latitude) || isNaN(location.Longitude) || 
                         location.Latitude == 0 || location.Longitude == 0 )
                        continue;

                    if ( searcher.flags[locIdx] )
                    {
                        this.matched[mapSetting.ModuleID].push(locView);
                        var currentIdx = this.matched[mapSetting.ModuleID].length - 1;
                        
                        if ( currentIdx >= idxFrom && currentIdx <= idxTo )
                        {
                            location.Icon_Idle = location.Icon_Idle.replace("id=", "x=");
                            location.Icon_Idle += (location.Icon_Idle.indexOf("?")==-1?"?":"&") + "id=" + this.matched[mapSetting.ModuleID].length;

                            var image = locView.getElementsByTagName("img");
                            
                            if ( image == null || image.length == null || image.length == 0 )
                                image = document.getElementById( "nmi_" + (locIdx+1) );
                            else
                                image = image[0];
                            
                            if ( image )
                            {
                                image.src = image.src.replace("id=", "x=");
                                image.src += (image.src.indexOf("?")==-1?"?":"&") + "id=" + this.matched[mapSetting.ModuleID].length;
                            }
                            
                            latlongArr.push( new VELatLong(location.Latitude, location.Longitude) );
                            vem.AddPushpin( new VEPushpin("NetismMapPP_" + mapSetting.ModuleID + "_" + locCount, 
                                            new VELatLong(location.Latitude, location.Longitude), 
                                            location.Icon_Idle, "", location.Icon_Popup));
                            locView.style.display = "";
                        }
                        else
                        {
                            locView.style.display = "none";
                        }
                    }
                    else
                    {
                        locView.style.display = "none";
                    }
                    
                }

                var geo = searcher.GetGeocode();
                if ( geo && mapSetting.IsAddLocationIcon )
                {
                    var icon_idle = mapSetting.ModulePath + "/images/youarehere.png";
                    var icon_active = mapSetting.ModulePath + "/images/youarehere.png";
                    var popup = geo.Name;
                    latlongArr.push( new VELatLong(geo.Latitude, geo.Longitude) );
                    var pin = new VEPushpin("NetismMapPP_" + mapSetting.ModuleID + "__", 
                                    new VELatLong(geo.Latitude, geo.Longitude), 
                                    icon_idle, "", popup);
                    pin.icon_idle = icon_idle;
                    pin.icon_active = icon_active;

                    vem.AddPushpin(pin);
                }
                
                MakeMap(vem, mapSetting, latlongArr);
                
                var matchedTotal = this.matched[mapSetting.ModuleID].length;
                MakePager(idxFrom, idxTo, matchedTotal, mapSetting);
            }

            var sf = document.getElementById("nme_SearchForm");
            if ( sf ) sf.style.display = '';
        }

        return false;
    }
}

function MakeMap(vem, mapSetting, latlongArr)
{
    if ( !isNaN(mapSetting.Longitude) && !isNaN(mapSetting.Latitude) && !isNaN(mapSetting.Zoom)
         && mapSetting.Longitude != 0 && mapSetting.Latitude != 0 && mapSetting.Zoom != 0 )
    {
        vem.SetCenterAndZoom(new VELatLong(mapSetting.Latitude, mapSetting.Longitude), mapSetting.Zoom);
    }
    else if ( latlongArr && latlongArr.length > 0 )
    {
        if ( !mapSetting.SearchConfig.Levels.length || mapSetting.SearchConfig.Levels.length <= 1 )
            vem.SetMapView(latlongArr);
    }

    vem.SetMapStyle(mapSetting.Style);
    
    vem.AttachEvent("onendpan", NetismMap_ShowPushpinBoxReal);
    
    vem.AttachEvent("onclick", function(e) {
        if ( !e.shiftKey )
            return;
        var addLink = document.getElementById("mapAddLink_" + vem.ModuleID);
        if ( addLink == null )
            return;
        var latlong = vem.PixelToLatLong(new VEPixel(e.mapX,e.mapY));
        var link = addLink.href + "&lat=" + latlong.Latitude + "&long=" + latlong.Longitude;
        top.location.href = link;
    });
    
    vem.AttachEvent("onendzoom", function(e) {
        if ( !mapSetting.SearchConfig.IsServerSearch )
            return;

        var levels = mapSetting.SearchConfig.Levels;
        if ( !levels || levels.length <= 1 )
            return;
        
        var lastLevelIdx = -1;
        var lastLevel = mapSetting.SearchConfig.LastLevel;
        
        for ( var i = 0; i < levels.length; i ++ )
        {
            if ( levels[i].length != 2 )
                return;
                
            if ( levels[i][0] <= lastLevel && levels[i][1] >= lastLevel )
            {
                lastLevelIdx = i;
                break;
            }
        }
        
        var nowLevelIdx = -1;
        var nowLevel = vem.GetZoomLevel();
        
        for ( var i = 0; i < levels.length; i ++ )
        {
            if ( levels[i].length != 2 )
                return;
                
            if ( levels[i][0] <= nowLevel && levels[i][1] >= nowLevel )
            {
                nowLevelIdx = i;
                break;
            }
        }

        if ( nowLevelIdx < 0 || lastLevelIdx < 0 )
            return;

        if ( lastLevelIdx != nowLevelIdx )
            Netism.Map.Render();
    });
}

function MakePager(idxFrom, idxTo, matchedTotal, mapSetting)
{
    var pager = document.getElementById("nme_list_pager");
    var pagerMain = document.getElementById("nme_list_pager_main");
    var pagerP0 = document.getElementById("nme_list_pager_p0");
    var pagerP1 = document.getElementById("nme_list_pager_p1");
    var pagerP2 = document.getElementById("nme_list_pager_p2");
    var pagerP3 = document.getElementById("nme_list_pager_p3");
    var pagerP4 = document.getElementById("nme_list_pager_p4");

    if ( idxTo > matchedTotal - 1 )
        idxTo = matchedTotal - 1;
                    
    if ( pager && pagerMain && pagerP1 && pagerP2 && pagerP3 && pagerP4 )
    {
        var html = "";
        
        if ( matchedTotal == 0 )
        {
            html = pagerP0.innerHTML;
        }
        else
        {
            html = pagerMain.innerHTML;
            html = html.replace("{from}", idxFrom+1);
            html = html.replace("{to}", idxTo+1);
            html = html.replace("{total}", matchedTotal);

            if ( idxFrom == 0 )
            {
                html = html.replace("{last}", pagerP2.innerHTML);
            }
            else
            {
                var lastLink = "Netism.Map.pageIdx--;Netism.Map.Render(" + mapSetting.ModuleID + ");return false;";
                lastLink = pagerP1.innerHTML.replace("{last-link}", lastLink);
                html = html.replace("{last}", lastLink);
            }

            if ( idxTo >= matchedTotal - 1 )
            {
                html = html.replace("{next}", pagerP4.innerHTML);
            }
            else
            {
                var nextLink = "Netism.Map.pageIdx++;Netism.Map.Render(" + mapSetting.ModuleID + ");return false;";
                nextLink = pagerP3.innerHTML.replace("{next-link}", nextLink);
                html = html.replace("{next}", nextLink);
            }
        }

        pager.innerHTML = html;
    }   
}

function CheckExternalResource(vem, setting)
{
    var layer = new VEShapeLayer();
    var spec = null;

    if ( setting.VECollection )
        spec = new VEShapeSourceSpecification(VEDataType.VECollection, setting.VECollection, layer);

    if ( setting.GeoRSS )
        spec = new VEShapeSourceSpecification(VEDataType.GeoRSS, setting.GeoRSS, layer);
                                  
    if ( setting.KML )
        spec = new VEShapeSourceSpecification(VEDataType.ImportXML, setting.KML, layer);

    if ( spec )
        vem.ImportShapeLayerData(spec);
}

function NetismMap_PlotAddressOnMap()
{
    if ( !window.Netism || !window.Netism.Map || !window.Netism.Map.mapControl )
        return;

    var baseElementId = "dnn_ctr" + window.Netism.ModuleId + "_EditLocation_";
    var address = document.getElementById(baseElementId+"txtAddress").value;
    var city = document.getElementById(baseElementId+"txtCity").value;
    var state = document.getElementById(baseElementId+"txtState").value;
    var zip = document.getElementById(baseElementId+"txtZip").value;
    var country = document.getElementById(baseElementId+"txtCountry").value;
    var useAddress = address + ", " + city + ", " + state + " " + zip + ", " + country;
    
    window.Netism.Map.mapControl.Find(null, useAddress);
    return false;
}

function NetismMap_ShowPushpinBoxReal(status)
{
    var pinID = window.Netism.currentPin;
    if ( pinID == null || pinID == "" )
        return;
    
    var pinAnchor = document.getElementById(pinID.toString());
    if ( !pinAnchor )
        return;

    var pinImg = pinAnchor.getElementsByTagName("img");
    if ( !pinImg || !pinImg.length || pinImg.length == 0 )
        return;

    if ( pinImg[0].src.toLowerCase().indexOf("selected=1") == -1 )
    {
        if ( pinImg[0].src.indexOf("?") == -1 )
            pinImg[0].src += "?selected=1";
        else
            pinImg[0].src += "&selected=1";
    }
   
    var pinImgMouseOver = pinImg[0].onmouseover;
    pinImgMouseOver();
    
    if ( status != 1 )
    {
        setTimeout("NetismMap_ShowPushpinBoxReal(1)", 50);
        return;
    }
    window.Netism.currentPin = null;
}

function NetismMap_ShowPushpinBox(pinID)
{
    var parts = pinID.split('_');
    if ( parts.length != 3 )
        return;

    var moduleID = parts[1];
    var locationID = parts[2];

    var mc = Netism.Map.mapControls[moduleID];
    if ( !mc )
        return;
    
    var latitude = document.getElementById("NetismMap_" + moduleID + "_" + locationID + "_latitude");
    var longitude = document.getElementById("NetismMap_" + moduleID + "_" + locationID + "_longitude");
    if ( !latitude || !longitude )
        return;
    
    latitude = latitude.innerHTML;
    longitude = longitude.innerHTML;
    
    var delta = 0;
    var topleft = mc.LatLongToPixel(mc.GetMapView().TopLeftLatLong, mc.GetZoomLevel());
    var bottomright = mc.LatLongToPixel(mc.GetMapView().BottomRightLatLong, mc.GetZoomLevel());
    var px = mc.LatLongToPixel(new VELatLong(latitude, longitude), mc.GetZoomLevel());
    
    topleft.x += delta;
    topleft.y += delta;
    
    bottomright.x -= (delta*2);
    bottomright.y -= (delta*2);

    window.Netism.currentPin = pinID;

    if ( px.x < topleft.x || px.y < topleft.y || px.x > bottomright.x || px.y > bottomright.y )
    {
        mc.PanToLatLong(new VELatLong(latitude, longitude));
    }
    else
    {
        NetismMap_ShowPushpinBoxReal(1);
    }
}

function NetismMap_HidePushpinBox(pinID)
{
    var pinAnchor = document.getElementById(pinID.toString());
    if ( !pinAnchor )
        return;
    
    var pinImg = pinAnchor.getElementsByTagName("img");
    if ( !pinImg || !pinImg.length || pinImg.length == 0 )
        return;
    
    pinImg[0].src = pinImg[0].src.replace("selected=1", "");
    var pinImgMouseOut = pinImg[0].onmouseout;
    pinImgMouseOut();
}

function NetismMap_ZoomView(ModuleID, Latitude, Longitude, Zoom, Style)
{
    if ( !Netism || !Netism.Map || !Netism.Map.mapControls )
        return false;
    
    var map = Netism.Map.mapControls[ModuleID];
    
    if ( !map )
        return false;

    if ( Style != "-" && map.GetMapStyle() != Style )
        map.SetMapStyle(Style);

    if ( map.GetZoomLevel() == Zoom )
        map.SetCenter( new VELatLong(Latitude, Longitude) );
    else
        map.SetCenterAndZoom(new VELatLong(Latitude, Longitude), Zoom);
            
    return false;
}

function NetismMapSearcher(setting)
{
    this.flags = [];
    this.msetting = setting;
    this.fields = {};
    
    this.Search = function(veMap, idxFrom, idxTo, latlongArr)
    {

        var sf = document.getElementById("nme_SearchForm");

        if ( sf )
        {
            for ( var i = 0; i < setting.Count; i ++ )
                this.flags[i] = false;
        }
        else
        {
            for ( var i = 0; i < setting.Count; i ++ )
                this.flags[i] = true;
            return;
        }

        var elements = null;

        elements = sf.getElementsByTagName("input");
        for ( var i = 0; i < elements.length; i ++ )
        {
            if ( elements[i].name == "nme_search_location" )
            {
                if ( this.msetting.SearchConfig.AutoLocation == "1" )
                {
                    jQuery("#nme_search_location").autocomplete("", { width: 200, matchSubset: false, cacheLength: 100, minChars: 3, delay: 100, veMap: veMap, 
                            onItemSelect: function(li)
                            {
                                var v = jQuery.trim(li.selectValue ? li.selectValue : li.innerHTML);
                                var parts = v.split(" ");
                                if ( parts[1] == "(postal" && parts[2] == "code)," )
                                    jQuery("#nme_search_location").val( parts[0] );
                                else
                                    jQuery("#nme_search_location").val( v );
                            }
                    } );
                }

                eval("elements[i].onkeypress = function(event) { if ( checkIsEnter(event) ) { Netism.Map.pageIdx = 0; Netism.Map.Render(" + this.msetting.ModuleID + "); return true; } }");
                continue;
            }
            
            if ( elements[i].type == "button" )
                eval("elements[i].onclick = function() { Netism.Map.pageIdx = 0; Netism.Map.Render(" + this.msetting.ModuleID + "); }");
            else if ( elements[i].type == "text" )
            {
                if ( this.msetting.SearchConfig.IsServerSearch )
                    eval("elements[i].onkeypress = function(event) { if ( checkIsEnter(event) ) { Netism.Map.pageIdx = 0; Netism.Map.Render(" + this.msetting.ModuleID + "); return false; } }");
                else
                    eval("elements[i].onkeypress = function(event) { if ( checkIsEnter(event) ) return false; Netism.Map.pageIdx = 0; Netism.Map.Render(" + this.msetting.ModuleID + "); }");
            }
            else if ( elements[i].type == "checkbox" || elements[i].type == "radio" )
                eval("elements[i].onchange = function() { Netism.Map.pageIdx = 0; Netism.Map.Render(" + this.msetting.ModuleID + "); }");

            if ( !elements[i].name || elements[i].name.indexOf("nme_search_") != 0 )
                continue;
            
            this.fields[elements[i].name] = true;
        }

        elements = sf.getElementsByTagName("select");
        for ( var i = 0; i < elements.length; i ++ )
        {
            if ( !elements[i].name || elements[i].name.indexOf("nme_search_") != 0 )
                continue;

            eval("elements[i].onchange = function() { Netism.Map.pageIdx = 0; Netism.Map.Render(" + this.msetting.ModuleID + "); }");
                
            this.fields[elements[i].name] = true;
        }

        if ( Netism.Map.searchCount == 1 && this.msetting.SearchConfig.PreSearch != "1" )
            return;

        if ( this.msetting.SearchConfig.IsServerSearch )
        {
            this.GoSearch(veMap, idxFrom, idxTo, latlongArr);
        }
        else
        {
            for ( var i = 0; i < this.msetting.Count; i ++ )
            {
                this.flags[i] = this.IsMatch(i+1);
            }
        }
    }

    this.IsMatch = function(idx)
    {
        var f = null;
        var lv = null;
        var fv = null;
        var mid = this.msetting.ModuleID;

        for ( var fd in this.fields )
        {
            f = document.forms[0].elements[fd];
            lv = fd.replace("nme_search_", "").replace("_", "-");
            lv = document.getElementById("NetismMap_" + mid + "_" + idx + "_" + lv);
            if ( lv == null ) continue;
            lv = lv.innerHTML;
            if ( lv == null ) continue;
            lv = lv.toLowerCase();

            if ( f.value )
                fv = f.value.toLowerCase();
            else
                fv = "";

            if ( f.type == "text" )
            {
                if ( fv && lv.indexOf(fv) == -1 )
                    return false;
            }
            else if ( f.type == "checkbox" || f.type == "radio" )
            {
                if ( f.checked && fv && lv.indexOf(fv) == -1 )
                    return false;
            }
            else if ( f.type == "select-one" && f.name != "nme_search_distance" )
            {
                fv = f.options[f.selectedIndex].value.toLowerCase();
                if ( fv && lv.indexOf(fv) == -1 )
                    return false;
            }
            else if ( f.length && f.length > 0 )
            {
                var found = false;
                var uncheckedCount = 0;

                for ( var j = 0; j < f.length; j ++ )
                {
                    if ( !f[j].checked )
                        uncheckedCount ++;
                
                    fv = f[j].value.toLowerCase();
                    if ( fv && f[j].checked && lv.indexOf(fv) != -1 )
                    {
                        found = true;
                        break;
                    }
                }
                
                if ( uncheckedCount != f.length && !found )
                    return false;
            }
        }

        var enteredLocation = document.getElementById("nme_search_location");
        if ( enteredLocation == null )
            return true;
    
        enteredLocation = enteredLocation.value;
        if ( enteredLocation == null || enteredLocation == "" )
            return true;

        enteredLocation = Netism.Map.LocNameGeoCodeMap[enteredLocation];
        if ( enteredLocation == null )
            return true;
    
        var currentLat = document.getElementById("NetismMap_" + mid + "_" + idx + "_latitude");
        var currentLong = document.getElementById("NetismMap_" + mid + "_" + idx + "_longitude");
        
        if ( currentLat == null || currentLong == null )
            return true;
    
        currentLat = currentLat.innerHTML;
        currentLong = currentLong.innerHTML;
    
        var isMile = this.msetting.SearchConfig.DistanceUnit+"";
        isMile = ( isMile.toLowerCase().indexOf("k") != 0 );

        var unitText = this.msetting.SearchConfig.UnitText;
        if ( unitText == null || unitText == "" )
            unitText = "mi";

        var unit = ( isMile ? GeoCodeCalc.EarthRadiusInMiles : GeoCodeCalc.EarthRadiusInKilometers );
        var distance = GeoCodeCalc.CalcDistance(enteredLocation.Latitude, enteredLocation.Longitude, currentLat, currentLong, unit);
        distance = Math.round( distance * 100 ) / 100;

        var distanceSpan = document.getElementById("NetismMap_" + mid + "_" + idx + "_distance");
        if ( distanceSpan != null )
            distanceSpan.innerHTML = distance + " " + unitText;
        
        var maxDistance = document.getElementById("nme_search_distance");
        if ( maxDistance != null )
        {
            maxDistance = maxDistance.options[maxDistance.selectedIndex].value;
            
            if ( maxDistance != null && maxDistance != "" && !isNaN(maxDistance) )
            {
                maxDistance = parseFloat(maxDistance, 10);
                if ( distance > maxDistance )
                    return false;
            }
        }

        return true;
    }

    this.GetPair = function(f)
    {
        if ( !f ) return null;
        
        if ( f.type == "text" && f.value )
        {
            return { type: "mh", value: f.value };
        }
        else if ( ( f.type == "checkbox" || f.type == "radio" ) && f.checked )
        {
            return { type: "in", value: f.value };
        }
        else if ( f.type == "select-one" && f.selectedIndex >= 0 )
        {
            return { type: "eq", value: f.options[f.selectedIndex].value.toLowerCase() };
        }
        else
        {
            return null;
        }
    }

    this.GetGeocode = function()
    {
        var enteredLocation = document.getElementById("nme_search_location");
        if ( enteredLocation == null )
            return null;
    
        enteredLocation = enteredLocation.value;
        if ( enteredLocation == null || enteredLocation == "" )
            return null;

        var loc = Netism.Map.LocNameGeoCodeMap[enteredLocation];
        if ( loc == null )
            return null;

        return { Latitude: loc.Latitude, Longitude: loc.Longitude, Name: enteredLocation };
    }

    this.GoSearch = function(veMap, idxFrom, idxTo, latlongArr)
    {
        var url = "";

        var sf = document.getElementById("nme_SearchForm");
        if ( !sf ) return;
        
        var elements = [];
        var field = null;
        var val = null;
        var fn = null;
        var params = {};
        
        var elements1 = sf.getElementsByTagName("input");
        for ( var i = 0; i < elements1.length; i ++ )
            elements.push(elements1[i]);

        var elements2 = sf.getElementsByTagName("select");
        for ( var i = 0; i < elements2.length; i ++ )
            elements.push(elements2[i]);
        
        for ( var i = 0; i < elements.length; i ++ )
        {
            field = elements[i];
            if ( field.name.indexOf("nme_search_") != 0 || field.name == "nme_search_location" )
                continue;
            
            val = this.GetPair(field);
            if ( !val )
                continue;

            fn = field.name.replace("nme_search", val.type);
            if ( !params[fn] )
                params[fn] = [];
                        
            if ( val && val.value)
                params[fn].push(val.value);
        }

        var geo = this.GetGeocode();
        if ( geo )
        {
            params["lat"] = [geo.Latitude];
            params["lng"] = [geo.Longitude];
        }

        var distanceUnit = this.msetting.SearchConfig.DistanceUnit+"";
        distanceUnit = distanceUnit.toLowerCase();
        if ( distanceUnit != "kilo" )
            distanceUnit = "mile";

        var unitText = this.msetting.SearchConfig.UnitText+"";
        if ( unitText == "" )
            unitText = "mi";
        
        params["unit"] = [distanceUnit];
        params["from"] = [idxFrom];
        params["to"] = [idxTo];
        params["zoom"] = [veMap.GetZoomLevel()];

        var url = location.href;
        url = url.replace("#", "");
        url += ( url.indexOf("?") == -1 ? "?" : "&" ) + "nme_ajax=1";
        
        for ( var fd in params )
        {
            if ( !params[fd].length || params[fd].length == 0 )
                continue;

            if ( fd.indexOf("mh") == 0 || fd.indexOf("eq") == 0 || fd.indexOf("in") == 0 )
            {
                url += "&" + fd + "=";
                for ( var i = 0; i < params[fd].length; i ++ )
                {
                    url += escape(params[fd][i]);
                    if ( i < params[fd].length - 1 )
                        url += ",";                    
                }
            }
            else
            {
                url += "&" + fd + "=" + escape(params[fd][0]);
            }
        }

        var rd = document.getElementById("nme_searchresults");
        if ( !rd ) return;

        if ( location.href.indexOf("debug=ajax") != -1 )
        {
            rd.innerHTML = url.replace("debug=ajax", "") + "<br><br>";
            rd.innerHTML += url.replace("debug=ajax", "").replace("nme_ajax=1", "debug=query");
            return;
        }

        var settings = this.msetting;
        settings.SearchConfig.LastLevel = veMap.GetZoomLevel();
        
        jQuery.get(url, function(data)
        {
            var pg = document.getElementById("nme_list_pager");
            if ( data.indexOf("<!-- ajax no results -->") == 0 )
            {
                rd.innerHTML = "";
                rd.style.display = 'none';
                pg.innerHTML = data;
                pg.style.display = '';
                return;
            }
            else if ( !data || data.indexOf("<!-- ajax response -->") != 0 )
            {
                rd.innerHTML = "";
                rd.style.display = 'none';
                pg.innerHTML = "";
                pg.style.display = 'none';
                return;
            }

            rd.innerHTML = data;
            rd.style.display = '';
            
            var lat = null;
            var lng = null;
            var icon_idle = null;
            var icon_active = null;
            var popup = null;
            var locCount = 0;
            
            veMap.Clear();
            CheckExternalResource(veMap, settings);

            for ( var i = 0; i < rd.childNodes.length; i ++ )
            {
                if ( rd.childNodes[i].childNodes.length == 1 )
                {
                    pg.innerHTML = rd.childNodes[i].childNodes[0].innerHTML;
                    pg.style.display = '';
                    continue;
                }

                if ( rd.childNodes[i].childNodes.length != 6 )
                    continue;

                locCount ++;
                
                icon_idle = rd.childNodes[i].childNodes[0].innerHTML;
                icon_active = rd.childNodes[i].childNodes[1].innerHTML;
                popup = rd.childNodes[i].childNodes[2].innerHTML;
                lat = rd.childNodes[i].childNodes[3].innerHTML;
                lng = rd.childNodes[i].childNodes[4].innerHTML;

                latlongArr.push( new VELatLong(lat, lng) );
                var pin = new VEPushpin("NetismMapPP_" + settings.ModuleID + "_" + (locCount+idxFrom), 
                                new VELatLong(lat, lng), 
                                icon_idle, "", popup);
                pin.icon_idle = icon_idle;
                pin.icon_active = icon_active;

                veMap.AddPushpin(pin);
            }

            if ( geo && settings.IsAddLocationIcon )
            {
                icon_idle = settings.ModulePath + "/images/youarehere.png";
                icon_active = settings.ModulePath + "/images/youarehere.png";
                popup = geo.Name;
                latlongArr.push( new VELatLong(geo.Latitude, geo.Longitude) );
                var pin = new VEPushpin("NetismMapPP_" + settings.ModuleID + "__", 
                                new VELatLong(geo.Latitude, geo.Longitude), 
                                icon_idle, "", popup);
                pin.icon_idle = icon_idle;
                pin.icon_active = icon_active;

                veMap.AddPushpin(pin);
            }
            
            MakeMap(veMap, settings, latlongArr);
        });
    }
}

