﻿/* 
* V2.02 : Zoom in to the max available area based on available markers
* V2.03 : Resolve issue: markers being reloaded 3 times
* V2.05 : Plot Dealers on MAP
* V2.06 : Towers Count on OpenWindowTab
*/
    var _debug=false;
    var map;
    var geocoder;
    var validateUser;
    var baseCountrySearch="US";
    var baseIcon;
    var lzip;
    var dragmarker;
    var insertingComment = false;
    var getZip;       
    var changingTimeWindow = false;
    var newmarkerhtml = '<br/>You can now <a href="javascript:void(0);" onclick="return openCommentAndFocus();">post your review</a> using the form at the bottom of the page,<br/> or click <a href="javascript:void(0);" onclick="return changeAddress();">here</a> to change the address ';
    var myMarker = new Array();
    var markersNo = 0;
    var comments;
    var markers ;
    
    var towers = new Array();
    var towerMarkers;
    var totalTowers;
    //var maxTower = 1000;        
    var arrDealers=new Array();
    var buildings = new Array();
    var buildingMarkers;
    var totalBuildings;
    
    // V2.04
    var ToShowLoadingHint=true;
    //var maxBuilding = 1000;     
    //var mgr;
    
    // V3.0 // Custom carrier
    
    
    var objCarrier;
    var loadCarrierAsync = true;
    var isLoadingCarrier = true;
    var SelectedCarrier =function()
    {
        this.id = -1;
        this.name = "";
        this.coverage = "";
        this.logosmall = "";
        this.BestCarrierID = -1;
        this.UserSelectedCarrierId = -1;
        
        this.flat   =  -90;
        this.flng   = -180;
        this.tlat   =   90;
        this.tlng   =  180;
        this.dateFilter = 0;
    };
    SelectedCarrier.prototype.ShowBox= function()
    {
        jQuery("#divBoxTop").find(".dataarea").html("Calculating...");
        jQuery("#divBoxTop").find(".imagearea").html("");
        jQuery("#divBoxTop").css("position", "absolute");
        jQuery("#divBoxTop").css("left", jQuery("#googlemap").position().left+2 );
        jQuery("#divBoxTop").css("top", jQuery("#googlemap").position().top );
        
        // preload images
        jQuery("#divBoxTop").find(".imagearea").html("<div style='margin:auto;'><img alt='Loading...' src='/img/ajax.gif' width='48' height='48' /></div>");
        jQuery("#divBoxTop").show();
        
        var dataareaHTML = this.coverage +"% Coverage";
        var imageareaHTML= "<img alt='"+ this.name + "' src='/img/carriersSquare/"+ this.logosmall +"' width='51' height='33' />";
        
        jQuery("#divBoxTop").find(".dataarea").html(dataareaHTML);
        jQuery("#divBoxTop").find(".imagearea").html(imageareaHTML);
        
        var CID = this.id;
        var indexOfId = getCarrierIndexByID(CID);
        var sRGB = color[indexOfId].replace (".", ",");
        sRGB = sRGB.replace (".", ",");
        sRGB = sRGB.replace (".", ",");
        sRGB = sRGB.replace (".", ",");

        //var sBG_in_RGB = jQuery.RGB('rgb(' + sRGB + ')');//[0,0,0]
        var sBG_in_RGB = 'rgb(' + sRGB + ')';
        
        jQuery(".CIMG_" + CID).css("border-color", sBG_in_RGB); 
        jQuery(".CIMG_" + CID).css("background-color", sBG_in_RGB);
    };
    
    SelectedCarrier.prototype.GetCarrierByID= function(id)
    {
        //GetCarrierByID.ashx
        var myAjax = new Ajax.Request("/GetCarrierByID.ashx", 
        {
        parameters: "id=" + id+ "&flat=" + this.flat + "&flng=" + this.flng +"&tlat=" + this.tlat + "&tlng=" + this.tlng + "&dateFilter=" + this.dateFilter
        ,
        method: 'get',asynchronous: false } );	
        if (myAjax.transport.responseText=='FAIL')
            return null;
        else
        {
            var jsonData = eval('(' + myAjax.transport.responseText + ')');
            this.id = jsonData.results[0].id ;
            this.name= jsonData.results[0].name ;
            this.coverage= jsonData.results[0].coverage ;
            this.logosmall = jsonData.results[0].logosmall ;    
        }
    };
        
    SelectedCarrier.prototype.LoadBestCarrier = function()
    {
        //PageMethods.GetBestRatedCarrier(flat, flng, tlat, tlng, dFilter,this.LoadBestCarrierId_Callback); //loadXmlComments
       var myAjax = new Ajax.Request("/GetBestCarrier.ashx", {parameters: "flat=" + this.flat + "&flng=" + this.flng +"&tlat=" + this.tlat + "&tlng=" + this.tlng + "&dateFilter=" + this.dateFilter,
                    method: 'get',asynchronous: false } );	
        if (myAjax.transport.responseText=='FAIL')
            return;
        else{
            var jsonData = eval('(' + myAjax.transport.responseText + ')');
            this.id = jsonData.results[0].id ;
            this.name= jsonData.results[0].name ;
            this.coverage= jsonData.results[0].coverage ;
            this.logosmall = jsonData.results[0].logosmall ;    
        }
    };
    SelectedCarrier.prototype.LoadBestCarrierAsync = function()
    {
        oProgBar.show();
        
        var self = this;
        var myAjax = new Ajax.Request("/GetBestCarrier.ashx", 
        {
        parameters: "flat=" + this.flat + "&flng=" + this.flng +"&tlat=" + this.tlat + "&tlng=" + this.tlng + "&dateFilter=" + this.dateFilter,
        method: 'get',asynchronous: true,
        onSuccess: function(response) 
        {
                
            if (response.responseText=='FAIL')
                return;
            else
            {
                    var jsonData = eval('(' + response.responseText + ')');
                    self.id = jsonData.results[0].id ;
                    self.name= jsonData.results[0].name ;
                    self.coverage= jsonData.results[0].coverage ;
                    self.logosmall = jsonData.results[0].logosmall ;   
                    self.ShowBox();
                    if ( jQuery('.CssBestCarrierId'))
                        jQuery('.CssBestCarrierId').val(self.id);
                    if ( jQuery('.CssBestCarrierName'))
                        jQuery('.CssBestCarrierName').val(self.name);
                    if ( jQuery('.spanCssBestCarrierName'))
                        jQuery('.spanCssBestCarrierName').html(self.name);
                    
                    
                    if(isLoadingCarrier)
                    {
                        self.ShowHeatMap(self.id ); 
                        isLoadingCarrier=false;
                    }
                }
                oProgBar.hide();
            },
            onFailure: function(resp)
            {
                oProgBar.hide();
            }
        });	
    };
    SelectedCarrier.prototype.Refresh = function()
    {
        this.flat = map.getBounds().getSouthWest().lat();
        this.flng = map.getBounds().getSouthWest().lng();
        this.tlat = map.getBounds().getNorthEast().lat();
        this.tlng = map.getBounds().getNorthEast().lng();
        this.dateFilter=$get(sliderId).value;
        
        //alert(loadCarrierAsync);
        if(loadCarrierAsync)
            this.LoadBestCarrierAsync();
        else{
            this.LoadBestCarrier();
            this.ShowBox();
        }
    };
    SelectedCarrier.prototype.ShowPanel = function()
    {
        var midpos = jQuery("#googlemap").position().left + (jQuery("#googlemap").width() - jQuery(".RamanDropDown").width())/2
        midpos = jQuery("#googlemap").position().left ;
        
        jQuery(".RamanDropDown").css("position", "absolute");
        //jQuery(".RamanDropDown").css("left", jQuery("#googlemap").position().left );
        jQuery(".RamanDropDown").css("left", midpos );
        jQuery(".RamanDropDown").css("top", jQuery("#googlemap").position().top + jQuery("#googlemap").height() - 45  );
        
        jQuery(".RamanDropDown").show();
    };
    SelectedCarrier.prototype.ShowHeatMap = function(CarrierID)
    { 
        $get('ctl00_SidebarPlaceHolder_CarriersCheckboxes_0').checked = false;

        var indexOfId = getCarrierIndexByID(CarrierID);
        checkAll(false); 
        justCheckAll = true;
        toggleOverlay(CarrierID,true); 
        getZip=null; 
        
        $get('ctl00_SidebarPlaceHolder_CarriersCheckboxes_' + (indexOfId+1)).checked = true;
               
        
    };
    var oProgBar;
    function ProgressbarMapControl(map, width) { 
      this.map_ = map; 
      this.width_ = width; 
      
      var container_ = document.createElement('div');
      container_.innerHTML = '<div style="position:absolute;width:100%;border:5px;'
        + 'text-align:center;vertical-align:bottom;color:#fff" id="geo_progress_text"></div>'
        + '<div style="background-color:#6c9ddf;height:100%;" id="geo_progress"></div>';
      container_.id = "geo_progress_container";
      container_.style.display = "none";
      container_.style.width = this.width_ + "px";
      container_.style.fontSize = "0.8em";
      container_.style.height = "1.3em";
      container_.style.border = "1px solid #FFF";
      container_.style.backgroundColor = "white";
      container_.style.textAlign = "left";
      this.map_.getContainer().appendChild(container_);
   
        
      this.div_ = document.getElementById('geo_progress');
      this.text_ = document.getElementById('geo_progress_text');
      this.container_ = document.getElementById('geo_progress_container');
      var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(30,56));
        pos.apply(this.container_);
    
      
    }
    ProgressbarMapControl.prototype.initialize = function () {
      
    };
    ProgressbarMapControl.prototype.show = function (loadstring) {
      this.container_.style.display = 'block';
      this.text_.innerHTML = loadstring || 'One moment please...';
    };
    ProgressbarMapControl.prototype.hide = function () {
      this.container_.style.display = 'none';
    };
    
    jQuery(document).ready(function()
    {
        objCarrier=new SelectedCarrier();
        jQuery(".RamanDropDown a.item").click(function(){
            jQuery(".RamanDropDown img").css("border-color", "#fff"); 
            jQuery(".RamanDropDown img").css("background-color", "#fff"); 
            objCarrier.ShowHeatMap(jQuery(this).attr("accesskey") );
            fetchLocations(); 
            refreshComments();
            //jQuery(this).find("img").css("border-color", sBG_in_RGB); 
            //jQuery(this).find("img").css("background-color", sBG_in_RGB); 
         });
    });
   
    function load() 
    {    
      
      
      if (map != null)
        return;         
      if (typeof(GBrowserIsCompatible) != 'undefined')
      {
          if (GBrowserIsCompatible()) 
          {
            map = new GMap2(document.getElementById('map'));
            map.addControl (new GSmallMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,75)));
            
            var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0,1));
            pos.apply(document.getElementById("TerrainButton"));
            map.getContainer().appendChild(document.getElementById("TerrainButton")); 
            
            /*
            * progressbar 
            */
            oProgBar = new ProgressbarMapControl(map, 150);
            oProgBar.show();
            //var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0,35));
            //pos.apply(document.getElementById("ZoomButton"));
            //map.getContainer().appendChild(document.getElementById("ZoomButton"));         

            //var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(5,75));
            //pos.apply(document.getElementById("PanButton"));
            //map.getContainer().appendChild(document.getElementById("PanButton"));         
        
            // adding logo
            pos = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(5,5));
            pos.apply(document.getElementById("grlogo"));
            map.getContainer().appendChild(document.getElementById("grlogo")); 
            // end
            
            //map.addControl(new GOverviewMapControl());
            
            geocoder = new GClientGeocoder();
            baseIcon = new GIcon();
            baseIcon.iconSize = new GSize(27, 35);
            baseIcon.iconAnchor = new GPoint(6, 35);
            baseIcon.infoWindowAnchor = new GPoint(5, 1);        
            
            map.setCenter(new GLatLng(startLat, startLng),4);  // the two variables are set in vb code	    
            
            GEvent.addListener(map, "moveend", mapMoveend);  
            GEvent.addListener(map, "zoomend", mapZoomEnd); 
            GEvent.addListener(map, "dragend", mapDragEnd);
            
            GEvent.addListener(map, "click", mapClick);         //click the comments/towers markers on the map => pop info window
                        
            if(!ToLoadUserComment)
            {            
                showInsertCommentBubble();
            }
            closeCommentForm();     //empty function in vb code           
            
            oProgBar.hide();
            // following line commented because we wont show all the carriers checked, rather recommended one
            //toggleOverlay(-1,true);                             //check carriers checked status
            
            //objCarrier.LoadBestCarrierAsync();
            //objCarrier.ShowHeatMap(objCarrier.id );
            //objCarrier.Refresh();
            refreshComments();
            
            CWload();                                           //load Customization Widget
            objCarrier.ShowPanel();
            //mgr= new GMarkerManager(map);
          }
      }
    }

    function commentObj (_id, _lat, _lng, _rat, _orat, _carr, _phonb, _phonm, _zip, _add1,
                        _add2, _city, _st, _dat, _comm, _us, _av,
                        _php, _lsm, _towercount,_tab1Html, _tab2Html, _tab3Html, _mark)
    {
        this.id = _id;
        this.lat = _lat;
        this.lng = _lng;
        this.rating = _rat;
        this.overallrating = _orat;
        this.carrier = _carr;
        this.phoneb = _phonb;
        this.phonem = _phonm;
        this.zip = _zip;
        this.address = _add1;
        this.address2 = _add2;
        this.city = _city;
        this.state = _st;
        this.date =  _dat;
        this.comment = _comm;
        this.username = _us;
        this.avatarPic = _av;
        this.phonePic = _php;
        this.logoSmall = _lsm;
        this.towercount=_towercount;
        this.tab1Html = _tab1Html;
        this.tab2Html = _tab2Html;
        this.tab3Html = _tab3Html;
        this.marker = _mark;       
    }
    
    //:)
    function dealerObj (_id, _doublelat, _doublelon, _tab1html, _tab2html,  _marker, _carrier)
    {
        this.Id=_id;
        this.Lat= _doublelat;
        this.Lng= _doublelon;
        this.Label= _tab1html;
        this.Label2 = _tab2html;
        this.Marker=_marker;
        this.Carriers = _carrier;
    }
    function towerObj (_id, _carrierfk, _doublelat, _doublelon, _date, _street, _city, _state, _height,
                     _groundele, _overalheight, _heightamsl, _structuretype, _marker)
    {
        this.id=_id;
        this.carrierfk=_carrierfk;
        this.doublelat= _doublelat;
        this.doublelon= _doublelon;
        this.date=_date;                                //date_constructed
        this.street= _street;                           //structure_street_address
        this.city= _city;
        this.state= _state;
        this.height= _height;
        this.groundele=_groundele;
        this.overalheight= _overalheight;
        this.heightamsl= _heightamsl;
        this.structuretype= _structuretype;
        this.marker=_marker;
    }

    //:)
    function buildingObj (_id, _entityname, _doublelat, _doublelon, _date, _street, _city, _state, _height,
                     _groundele, _overalheight, _heightamsl, _structuretype, _marker)
    {
        this.id=_id;
        this.entityname=_entityname;
        this.doublelat= _doublelat;
        this.doublelon= _doublelon;
        this.date=_date; 
        this.street= _street; 
        this.city= _city;
        this.state= _state;
        this.height= _height;
        this.groundele=_groundele;
        this.overalheight= _overalheight;
        this.heightamsl= _heightamsl;
        this.structuretype= _structuretype;
        this.marker=_marker;
    }
    
    function addressDetails (_point, _street, _state, _city, _zip)
    {
        this.point = _point;
        this.street = _street;
        this.state = _state;
        this.city = _city;
        this.zip = _zip;
    }
    
    function getCurrentCarriersString()
    {
        var tempStr="";
        for(i=0; i < maxcarrier; i++)
        {
            str = carrierName[i];            
            if(isCarrierChecked(str))
            {
                if (str=="AT&T")
                    str="ATnT";
                tempStr += str + "_";
            }
        }
        return tempStr;
    }
    function updateEmbedURL()
    {
        var gll = map.getCenter();
        var lat = gll.lat();
        var lng = gll.lng();
        var zoom = map.getZoom();
        carriersStr= getCurrentCarriersString();                
        embedurl ="<iframe scrolling=\"no\" src =\"" + grRoot + "GREmbed.aspx?domain=www.gotreception.com&zoom=" + zoom + "&latitude=" + lat + "&longitude=" + lng + "&width=380&height=570&carriers=" + carriersStr + "\" style=\"border:solid 1px black\" width=\"380\" height=\"570\"></iframe>";        
        $get('embedurl').value = embedurl;                
    }
    
    function mapMoveend()               //display current map center in URL textbox
    {
        var gll = map.getCenter();
        var lat = gll.lat();
        var lng = gll.lng();
        var zoom = map.getZoom();
        var dateFilter=$get(sliderId).value;                
        var url =webRoot + "Default.aspx?exactmap=true&lat=" + lat + "&lng=" + lng + "&zoom=" + zoom + "&dfilter=" + dateFilter + "&carrier=" + carriers;        
        $get('mapurl').value = url;
        updateEmbedURL();
        //$get(maplat).value = lat;
        //$get(maplng).value = lng;
    }
     
   /* V2.03
    *  Instead of calling refreshComments() directly, call this function first.
    */
    function mapZoomEnd()
    {
        if(_debug) alert('mapZoomEnd()');
        refreshComments();
    }
    
   /* V2.03
    *  Instead of calling refreshComments() directly, call this function first.
    */
    function mapDragEnd()
    {
        refreshComments();
    }
    
    function refreshComments()
    {
        
        // Raman V6.0 over V3.0
        objCarrier.Refresh();
        //
        // :)
        if(typeof(getCommentByID) != 'undefined')
        {
            if(getCommentByID==true)     //we will not refresh comments if we are choosing to view only 1 comment
            {
                return;
            }
        }
            
        if(waitForGetUserComment || waitForLoadXmlLocations || waitToSetCenter || waitForMoveToState)
            return;                 //we will not refresh if some actions are waiting in the queue
        
        /* Raman V2.02
        * ToLoadUserComment = true when single user's comment is to be loaded.
        * There is no need to refresh comments
        */
        if(ToLoadUserComment==true)
            return;
        /* End */
        
        flat = map.getBounds().getSouthWest().lat();
        flng = map.getBounds().getSouthWest().lng();
        tlat = map.getBounds().getNorthEast().lat();
        tlng = map.getBounds().getNorthEast().lng();
        dateFilter=$get(sliderId).value;
        if (map.getZoom() < minCommentVisibleZoom ) 
            fetchSomeComments(flat, flng, tlat, tlng, dateFilter); //use this methods to server for large area  - small zoom
        else
            fetchComments(flat, flng, tlat, tlng, dateFilter); 
        
        
        //V2.05 ----------------------------------------------
        fetchDealers(flat, flng, tlat, tlng, true);
        //=====================================================
        
        if (towers != null)    
        {
            for (i=0; i < towers.length; i++)         
            {             
                towers[i].marker.hide();
            }
        }                
        if (map.getZoom() >= minTowerVisibleZoom && $('chkTower').checked) 
            fetchTowers(flat, flng, tlat, tlng);        
        
        // :)
        if (buildings != null)    
        {
            for (var bi=0; bi < buildings.length; bi++)    
            {                
                buildings[bi].marker.hide();
            }
        }                        
        if (map.getZoom() >= minTowerVisibleZoom && $('chkBuilding').checked) 
            fetchBuildings(flat, flng, tlat, tlng);
    }
    //V2.05
    function fetchDealers(flat, flng, tlat, tlng, dorefresh)
    {	
        if (arrDealers != null)
        {
            for (i=0; i < arrDealers.length; i++)         
            {             
                arrDealers[i].Marker.hide();
            }
        }
        if ( map.getZoom() < 5 || $('chkDealers').checked==false ) 
            return;
        
        if( arrDealers==null || arrDealers.length==0 || dorefresh)
        {
            oProgBar.show('Loading dealer info...');
            jQuery.ajax({url: "/GetDealerLocationMarkup.ashx",dataType: "json",
                success: function(data){loadDealers(data);}
           });
        }        
    }
    function loadDealers(data)
    {
        //if (arrDealers == null) return;
        if (arrDealers != null)
        {
            for (var i=0; i < arrDealers.length; i++) 
            {
                map.removeOverlay(arrDealers[i].Marker);        
            }
        }
        
        for(var i=0;i<data.results.length; i++)
        {
            var _marker_HTML='';
            var _marker;
            var _myIcon;
            var _point;
            
            _point = new GLatLng( parseFloat(data.results[i].Lat), parseFloat(data.results[i].Lng) );
            
            _marker_HTML = '<table style="font-family:tahoma;font-size:11px;"><tr><td colspan="2"></td></tr>';
            _marker_HTML += '<tr><td colspan="2"><b><a href="' + data.results[i].WebPage + '">'+ data.results[i].Name +'</a></b></td>';
            _marker_HTML += '<tr><td colspan="2"><b>' + data.results[i].BusinessStreet + '</b></td>';
            _marker_HTML += '<tr><td colspan="2">' + data.results[i].BusinessCity + '<br />' + data.results[i].BusinessState + ', ' + data.results[i].BusinessPostalCode + '</td></tr>';
            _marker_HTML += '<tr><td>Phone: <b>' + data.results[i].BusinessPhone1 + '</b></td><td><b>' + data.results[i].BusinessPhone2 + '</b></td></tr>';
            _marker_HTML += '<tr>';
            _marker_HTML += '<td colspan="2">';
            _marker_HTML += '<a href="http://www.cellswapper.com" target=_blank >Escape any cell phone contract</a>';
            _marker_HTML += '</td>';
            _marker_HTML += '</tr>';
            _marker_HTML += '</table>';       
                        
            _myIcon = new GIcon(G_DEFAULT_ICON);
            //myIcon.image = "img/FilledBar.png";        
            _myIcon.shadowSize = new GSize(0,0);  
            
            if(arrDealers[i]!=null)
            {
                _marker = arrDealers[i].Marker;
                _marker.setLatLng(new GLatLng(_point.lat(), _point.lng()));
                //_marker.setImage(_myIcon.image);                    
                _marker.show();
                //towers[i]=new towerObj(id, carrier, point.lat(), point.lng(), date, address, city, state, null, null, null,null,null,marker)                    
                arrDealers[i].Marker = _marker;
            }
            else
            {
                _marker = new GMarker(_point, _myIcon);
                arrDealers.push(new dealerObj(data.results[i].Id, _point.lat(), _point.lng(), _marker_HTML, data.results[i].Label2, _marker, data.results[i].Carriers));
            }
            arrDealers[i].Label = _marker_HTML;
            arrDealers[i].Label2 = data.results[i].Label2;
            
            map.addOverlay(arrDealers[i].Marker);
            //arrDealers[i].Marker.openInfoWindowHtml( arrDealers[i].Label );
//            GEvent.addListener(arrDealers[i].Marker, "click", function() {
//                arrDealers[i].Marker.openInfoWindowHtml(arrDealers[i].Label);
//            });
            
        }
        
        for (var i=0; i < arrDealers.length; i++) 
        {
            var foundchecked= false;
            var arrDealerCarriers = arrDealers[i].Carriers;
            for (var j=0; j < arrDealerCarriers.length; j++) 
            {
                if( isCarrierIDChecked(arrDealerCarriers[j]) )
                {
                    foundchecked=true;
                }
            }
            if( foundchecked==true)
                arrDealers[i].Marker.show();
            else
                arrDealers[i].Marker.hide();
            //isCarrierIDChecked
        }
        oProgBar.hide();
    }
    //:)
    function fetchTowers(flat, flng, tlat, tlng)
    {	
        PageMethods.GetTowers(flat, flng, tlat, tlng, loadXmlTowers);
    }
    
    //:)
    function fetchBuildings(flat, flng, tlat, tlng)
    {	    
        PageMethods.GetBuildings(flat, flng, tlat, tlng, loadXmlBuildings);
    }
    
    function fetchComments(flat, flng, tlat, tlng, dFilter)
    {	    
        PageMethods.GetComments(flat, flng, tlat, tlng, dFilter,loadXmlLocations); //loadXmlComments
    }

    function fetchSomeComments(flat, flng, tlat, tlng, dFilter)
    {	    
        PageMethods.GetSomeComments(flat, flng, tlat, tlng, dFilter,loadXmlLocations); //loadXmlComments
        
        /// V3.0
        //// Raman: Dec 12, Uncomment below to show Best carrier dialog
        //fetchBestRatedCarrier(flat, flng, tlat, tlng, dFilter);
    }
    
    // Dec 11. Raman - Begin 
    //"Best Carrier" --------------------------------------------------
    function fetchBestRatedCarrier(flat, flng, tlat, tlng, dFilter)
    {
        jQuery("#divBoxTop").find(".dataarea").html("Calculating...");
        jQuery("#divBoxTop").find(".imagearea").html("");
        jQuery("#divBoxTop").css("position", "absolute");
        jQuery("#divBoxTop").css("left", jQuery("#googlemap").position().left+5 );
        jQuery("#divBoxTop").css("top", jQuery("#googlemap").position().top+5 );
        
        // preload images
        jQuery("#divBoxTop").find(".imagearea").html("<div style='margin:auto;'><img alt='Loading...' src='/img/ajax.gif' width='48' height='48' /></div>");
        
        jQuery("#divBoxTop").show();
        
        PageMethods.GetBestRatedCarrier(flat, flng, tlat, tlng, dFilter,loadBestRatedCarrier_Callback); //loadXmlComments
    }
    function loadBestRatedCarrier_Callback(result, userContext, methodName)
    {    
        //if map is not loaded, then register this method to be called after load
        if(typeof(map) == 'undefined')
        {
            return;            
        }

        var xml = result;
        
        var data = xml.documentElement.getElementsByTagName("data");
        var id = data[0].getAttribute("id");
        var name = data[0].getAttribute("name");
        var coverage = data[0].getAttribute("coverage");
        var logosmall = data[0].getAttribute("logosmall");
        
        //var htmldata = "<table>";
        //htmldata+= "<tr>";
        //htmldata+= "<td><b>Optimal Carrier:</b></td><td><img width='40' height='26' alt='"+name+"' src='/img/carriersSmall/"+ logosmall +"' /></td><td><b>"+ coverage +"% Area Coverage</b></td>";
        //htmldata+= "</tr>";
        //htmldata+= "";
        //htmldata+= "</table>";
        var dataareaHTML = coverage +"% Coverage";
        var imageareaHTML= "<img alt='"+name+"' src='/img/carriersSquare/"+ logosmall +"' width='51' height='33' />";
        
        jQuery("#divBoxTop").find(".dataarea").html(dataareaHTML);
        jQuery("#divBoxTop").find(".imagearea").html(imageareaHTML);
    }
    
    
    // End of Best Carrier
    // -------------------------------------------------------------
    
    function changeAddress()
    {
        map.removeOverlay(dragmarker)
        showInsertCommentBubble(map.getCenter().lat(), map.getCenter().lng());
    }
    
    var ICBmarker = null;
    function showInsertCommentBubble(clat,clng)
    {
        var zipe = $get('zipcode').value;          
        //destroy the old marker  ...
        if (ICBmarker != null)
            map.removeOverlay(ICBmarker);            
        // ... and recreate it at the new location
        html = "Enter your address, to post <br />or view comments in your area."
            + "<br /><b>Street:</b> <br><input type='text' id='streetq' onkeypress ='return ignoreEnter(event);' onkeyup = \"return selectTextboxOnEnter(event,$get('zipq'));\" />"
            + "<br /><b>Zip code:</b> <br><input type='text' id='zipq' onkeypress ='return ignoreEnter(event);' onkeyup = \"return clickButtonIfEnter(event,$get('gobubblebtn'));\" /> "
            + "<button id='gobubblebtn' onclick='checkValuesAndGo(); return false;' >Go</button>";

        var myIcon = new GIcon(G_DEFAULT_ICON);
        myIcon.image = "img/FilledBar.png";        
        myIcon.shadowSize = new GSize(0,0);        
        if(typeof(clat)!='undefined' && typeof(clng)!='undefined')
            ICBmarker = new GMarker(new GLatLng(clat,clng),{icon:myIcon});
        else
        {
            if(window.location.search.indexOf('exactmap')!=-1)                              //exact map
                ICBmarker = new GMarker(new GLatLng(startLat,startLng),{icon:myIcon});
            else                                                                            //not exactmap
                ICBmarker = new GMarker(new GLatLng(startLat-7,startLng),{icon:myIcon});
        }
        ICBmarker.myhtml = html;
        map.addOverlay(ICBmarker);
        ICBmarker.openInfoWindowHtml(html);               
        
        /* V2.03
        * if clat and clng are null, no need to refreshComments()
        */
        //refreshComments();
        if(clat!=null && clng!=null)
        {
            refreshComments();
        }
        /* End */
    }
    
    function checkValuesAndGo()
    {
        $(stateDDL).value="";
        $('city').value="";
        if (trim($get('streetq').value) != "" &&  trim($get('zipq').value) != "")
        {
            $get('zipcode').value = $get('zipq').value;
            getAddress($get('streetq').value, $get('zipq').value);
        }
        else if ($get('zipq').value != "")
        {
            $get('zipcode').value = $get('zipq').value;
            moveToZipCode($get('zipq').value);
        }
        else
        {
            $get('streetq').focus();
            alert('Please enter your address and zipcode');
        }
    }

    function getAddress(address, zip) {
      var query = address + ", ";
      query += getCityState(zip);
      query += " " + zip;
      lzip = zip; // ok, this is a hack
      geocoder.getLocations(query, gotAddress);
    }
    
    function preprareCitiesFromState(state)
    {   
        PageMethods.preprareCitiesFromState(state, preprareCitiesFromState_Callback);  
    }
    
    function preprareCitiesFromState_Callback(result, userContext, methodName)
    {        
        //this is where cities array will be prepared for auto suggest city names
        vals = result.split(",");               
    }
     
     function moveToZipCode(zip)
     {        
        PageMethods.LatLongFromZipCode(zip, LatLongFromZipCode_Callback);        
     }

     function LatLongFromZipCode_Callback(result, userContext, methodName)
     {
        if(typeof(map) == 'undefined')
            return;
            
        if (result == '')
        {           
            return;
        }
        
        $(stateDDL).value="";
        $('city').value="";
        
        var lat = result.split(",")[0];
        var lng = result.split(",")[1];
        var point = new GLatLng(lat, lng);
        map.setCenter(point, defaultZoom);     
        showInsertCommentBubble(lat,lng);
        if($get('zipq')!=null)
            $get('zipq').value=$get('zipcode').value;
     }
     
     function moveToCityState(city, state)
     {       
        if(city != '')
            PageMethods.LatLongFromCityState(city, state, LatLongFromCityState_Callback);        
     }
     
     //=================PHONE HINT=====================
     var timeout=0;
     var paused=true;
     function slowlyTurnHintOff()
     {
        setTimeout(slowlyTurnHintOff,1000);        
        if(paused==true)
        {            
            return;
        }
        if(timeout<=0)            
        {
            $get('hintPhone').style.visibility="hidden";
            $get('hintPhone').style.left = "-337px";
            $get('hintPhone').style.zIndex = -1;
        }
        else
        {
            timeout--;            
        }   
        
     }
     
     function initPhoneHint(phoneText)
     {      
        //in IE, offsets are get from parent container. Meanwhile in FF, offset are get from screen edge
        //we put comments at the edge of content => in IE comments offset is 0, in FF comments offset is > 0
        if($('comments').offsetLeft==0) 
        {
            //IE
            $get('hintPhone').style.left = ($('wrapper').offsetLeft + $('content').offsetLeft + $('comment_form').offsetLeft + $('commentFieldCol1').offsetLeft+$('commentFieldCol1').clientWidth) + "px";
        }
        else
        {
            //FF
            $get('hintPhone').style.left = ($('commentFieldCol1').offsetLeft+$('commentFieldCol1').clientWidth) + "px";
        }        
        
        $get('hintPhone').style.visibility="visible";
        //$get('hintPhone').style.left = ($('commentFieldCol1').offsetLeft+$('commentFieldCol1').clientWidth) + "px";
        $get('hintPhone').style.zIndex = 1;        
        timeout=2;        
        paused=true;
        slowlyTurnHintOff();
        $get('imgLoading').style.visibility="visible";
        if(phoneText)
            if(phoneText.length>=2)
                PageMethods.getPhoneHint(phoneText,phoneHint_Callback);
     }
     
     function phoneHint_Callback(result, userContext, methodName)
     {  
        $get('imgLoading').style.visibility="hidden";   
        htmlHint = "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"backGround-Color:white;\">";
        for (i=0; i<Math.min(30 , result.length); i++)  //get 30 first result only
        {
            if (result[i]!=null)
                if(result[i].length>0)
                {
                    try
                    {
                        arr=result[i].split(",");
                        start = arr[0].substr(0,arr[2]);
                        mid = arr[0].substr(arr[2],arr[3]);
                        end=arr[0].substr(eval(arr[2]) + eval(arr[3]),arr[0].length-eval(arr[2]) - eval(arr[3]));
                        strName=start + "<span class='highlightBackGround'>" + mid + "</span>" + end;                                                            
                        phoneModel=arr[4];                    
                        phoneBrand=arr[5];                    
                        
                        if( arr[1]!=null && arr[1]=="")
                            continue;
                        if(arr[1].indexOf('http')==0)
                            src=arr[1];
                        else
                            src='uploadedImages/' + arr[1];
                        htmlHint += "<tr><td style='width:50px'><img src='" + src + "' alt='' width='50px' onclick=\"populatePhone('" + arr[1] + "','" + phoneBrand + "','" + phoneModel + "','" + arr[0] + "');\"/></td><td onclick=\"populatePhone('" + arr[1] + "','" + phoneBrand + "','" + phoneModel + "','" + arr[0] + "');\">" + strName + "</td></tr>";
                    }
                    catch(e)
                    {}
                    
                }
        }        
        htmlHint += "</table>";
        $get('hintPhoneContent').innerHTML=htmlHint;             
     }
     
     function populatePhone(img, brand, model, fullmodel)
     {        
        $get('ctl00_MainContentPlaceHolder_phonebrand').value=brand;
        $get('ctl00_MainContentPlaceHolder_phonemodel').value=model;
        $get('ctl00_MainContentPlaceHolder_phone').value=fullmodel;
        $get('hintPhone').style.visibility="hidden";        
        $get('hintPhone').style.left = "-337px";
        $get('hintPhone').style.zIndex = -1;        
        if(img.indexOf('http')==0)
            $get('phoneImg').src= img;
        else
            $get('phoneImg').src="uploadedImages/" + img;
        $get('phoneImg').style.visibility="visible";        
        $get('phoneImg').height="80";
     }
     //=============================================================
     
     function moveToState(state)
     {       
        if(state != '')
        {
            stateToMoveTo=state;
            PageMethods.LatLongFromState(state, LatLongFromState_Callback);                
        }
     }
     
     function LatLongFromState_Callback(result, userContext, methodName)
     {  
        if (result == '' || result == ',')
        {   
            return;
        }
        
        var lat = result.split(",")[0];
        var lng = result.split(",")[1];        
        
        
        
        if(typeof(map) == 'undefined')
        {
            stateLat=lat;
            stateLng=lng;
            waitForMoveToState=true;
            return;
        }                  
        
        var point = new GLatLng(lat, lng); 
        map.setCenter(point, defaultStateViewZoom);        
        $get(stateDDL).value=stateToMoveTo;
        $get('city').value="";                    
        showInsertCommentBubble(lat,lng);
     }
     
     
     function LatLongFromCityState_Callback(result, userContext, methodName)
     {
        if(typeof(map) == 'undefined')
            return;
            
        if (result == '')
        {   
            return;
        }
        var lat = result.split(",")[0];
        var lng = result.split(",")[1];        
        var point = new GLatLng(lat, lng);
        map.setCenter(point, defaultZoom);        
     }
          
       function getCityState(zipc)
       {
            var myAjax = new Ajax.Request("GetCityState.ashx", {
            parameters: "q=" + trim(zipc),
            method: 'get',
            asynchronous: false } );	
            if (myAjax.transport.responseText=='FAIL')
                return "";
            else
                return myAjax.transport.responseText;
       }
       
       function getAddressSync(address, zip)
       {
            var query = address + ", ";
            query += getCityState(zip);
            query += " " + zip;
            lzip = zip; // ok, this is a hack
      
            var myAjax = new Ajax.Request("GetAddressCoordinates.ashx", {
            parameters: "q=" + query,
            method: 'get',
            asynchronous: false } );     
            var rsp=myAjax.transport.responseText;       
            if(rsp.indexOf("error")!=0)
                return eval("(" + myAjax.transport.responseText + ")");
            else
            {
                alert(rsp.substring(5,rsp.length));
                return null;
            }
       }

        function processAddressResponse(response)
        {
            if(response == null)
                return null;
                
            var point;
            var street, state, city, zip = "";
            
            if (!response || response.Status.code != 200) {
                alert("We were unable to find your location");
                return null;
            }
            
            var accuracy = 0;
            for (i=0; i<response.Placemark.length; i++)
            {
                place = response.Placemark[i];

                if (place.AddressDetails.Country.CountryNameCode == baseCountrySearch
                    && place.AddressDetails.Accuracy > 4
                    && place.AddressDetails.Accuracy > accuracy) // we get the most accurate result
                {
                    point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                    
                    //try to move to the point
                    //map.setCenter(point, defaultZoom);                    
                    try{
                        map.setCenter(point, defaultZoom); 
                    }
                    catch(err){
                        //alert(err);
                    }
                    
                    
                    if (typeof(place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName)!='undefined')
                        state = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
                        
                    if(typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) != 'undefined')
                    {
                        if (typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) != 'undefined')                        
                            if (typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare)!='undefined')
                            {
                                street = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                            }                                
                        else if (typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Thoroughfare) != 'undefined')
                                street = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Thoroughfare.ThoroughfareName;
                        
                        if (typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) != 'undefined')
                            city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;                    
                        
                        if (typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality)!='undefined'
                            && typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber)!='undefined')
                            zip = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;                
                    }
                    else if(typeof(place.AddressDetails.Country.AdministrativeArea.Locality) != 'undefined')
                    {                        
                        if (place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare != null)
                                street = place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                        
                        if (typeof(place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName) != 'undefined')
                            city = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;                    
                        if (typeof(place.AddressDetails.Country.AdministrativeArea.Locality.PostalCode) != 'undefined'
                            && typeof(place.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber) != 'undefined')
                            zip = place.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
                    }
                    else if( place.AddressDetails.Country.AdministrativeArea.Thoroughfare!='undefined') /* added Raman 12 Dec 08*/
                    {
                        if (typeof(place.AddressDetails.Country.AdministrativeArea.Thoroughfare) != 'undefined')
                                street = place.AddressDetails.Country.AdministrativeArea.Thoroughfare.ThoroughfareName;
                        if (typeof(place.AddressDetails.Country.AdministrativeArea.LocalityName) != 'undefined')
                            city = place.AddressDetails.Country.AdministrativeArea.LocalityName;                    
                        if (typeof(place.AddressDetails.Country.AdministrativeArea.PostalCode) != 'undefined'
                            && typeof(place.AddressDetails.Country.AdministrativeArea.PostalCode.PostalCodeNumber) != 'undefined')
                            zip = place.AddressDetails.Country.AdministrativeArea.PostalCode.PostalCodeNumber;
                    }
                    accuracy = place.AddressDetails.Accuracy;                   
                }
            }
            
            if (point != null)
            {
                /* added Raman. Fix undefined with "" */
                if(street=='undefined') street = "";
                if(state=='undefined') state = "";
                if(city=='undefined') city = "";
                /* end */
                return new addressDetails(point, street, state, city, zip);
            }
            else
                return null;
        }
    
   function gotAddress(response) 
   {       
        if (!response || response.Status.code != 200) {
              alert("We were unable to find your location");
        } else {
                        
            addr = processAddressResponse(response);
        
            if (addr != null)
            {    
                if (addr.zip == "")
                    addr.zip = lzip; // I hate hacks
                    
                setLocationNew(addr.point.lat(), addr.point.lng(), addr.street, addr.zip, addr.city, addr.state);
              
                //--map.clearOverlays();
                 try
                 {
                    map.setCenter(addr.point, defaultZoom);
                 }
                 catch(err){
                 //alert(err);
                 }
                
                
                dragmarker = new GMarker(addr.point, {draggable: true});
                map.addOverlay(dragmarker);
                newmarkerhtml = '<br/>You can now <a href="javascript:void(0);" onclick="return openCommentAndFocus();">post your review</a> using the form at the bottom of the page,<br/> or click <a href="javascript:void(0);" onclick="return changeAddress();">here</a> to change the address ';
                dragmarker.openInfoWindowHtml(newmarkerhtml);
                GEvent.addListener(dragmarker, "dragend", function() { 
                    setLocationNew(dragmarker.getPoint().lat(),
                    dragmarker.getPoint().lng(), addr.street, addr.zip, addr.city, addr.state);
                    $get(maplat).value=dragmarker.getPoint().lat();
                    $get(maplng).value=dragmarker.getPoint().lng();
                    dragmarker.openInfoWindowHtml(newmarkerhtml);
                });
                GEvent.addListener(dragmarker, "click", function() {                     
                    dragmarker.openInfoWindowHtml(newmarkerhtml);
                });
                getZipRatings(addr.zip, $get(sliderId).value);
                location.href='#googlemap_anchor';
            }
            else
            {
                alert("No results found for your query. Try inserting more details to the address.");
            }
        }
   }
      
    function mapLoad (sender, args)
    {
        if (loadMapStuff == false) return;
        if (!args.get_isPartialLoad())
        {
            
            load();
            
            initOverLabels();
        }
        if (AdditionalOnLoadStuff)
            AdditionalOnLoadStuff();
    }
    
    try
    {
        Sys.Application.add_load(mapLoad);
    }
    catch(ex)
    {
        alert ('Sorry, we are currently unable to serve the functionalities');  //in stead of saying "exception"
    }

    function enterComment()
    {
        if (dragmarker != null)
        {
            dragmarker.openInfoWindowHtml(newmarkerhtml);
            return false;
        }
            
        if (getZip==true)
        {
            newmarkerhtml = '<br/>You can <a href="javascript:void(0);" onclick="return openCommentAndFocus();">post your review</a> using the form at the bottom of the page,<br/> or click <a href="javascript:void(0);" onclick="return changeAddress();">here</a> to put your address ';
            dragmarker = new GMarker(map.getCenter(), {draggable: true});
            map.addOverlay(dragmarker);
            dragmarker.openInfoWindowHtml(newmarkerhtml);
            GEvent.addListener(dragmarker, "dragend", function() { 
               dragmarker.openInfoWindowHtml(newmarkerhtml);
            });
        }
        else
        {        
            showInsertCommentBubble(map.getCenter().lat(),map.getCenter().lng());
        }
        return false;
    }

    function getZipRatings(zip, dateFilter)
    {
        insertingComment=true;
        PageMethods.ZipCodeSearch(new Array(), zip, false, dateFilter, loadXmlLocations);
    }
    var currentZoom = 0;

    function retrievePassword(email)
    {
        PageMethods.RetrievePassword(email, retrievePassComplete);
        closePopups();
    }

    function retrievePassComplete (result, userContext, methodName)
    {
        if (result==false)
            alert("That email address does not belong to a user.");
        else
            alert("Password has been sent to your email address.");
    }

    function FindLatLongForSearch()
    {
        var state =selectedState( $get(stateDDL));
        var city = $get('city').value;
        var zip = $get('zipcode').value;    
        PageMethods.FindLocation(city, state, zip, FindLatLongForSearchResponse);    
    }

    function FindLatLongForSearchResponse(result, userContext, methodName)
    {
        if (result == '')
        {
            alert ("Couldn't find any result");
            return;
        }
        var lat = result.split(",")[0];
        var lng = result.split(",")[1];

        map.setCenter(new GLatLng(lat, lng), defaultZoom);
        showInsertCommentBubble();    
    }

    function showUserComments(username)
    {   
        //aler(username);
        
        if(!map) //if map is not loaded yet, then register a flag so that this function is called after map is loaded
        {        
            currentUser = username;
            waitForGetUserComment=true;
        }
        else
        {    
            if (map.getZoom() < eval(minCommentVisibleZoom))
                map.setCenter(map.getCenter(), eval(minCommentVisibleZoom));
        }   
        
        if (username != null)
            PageMethods.GetUserCommentsName(username, loadXmlLocations); 
        else
            PageMethods.GetUserComments(loadXmlLocations);  
    }


    function getExactMap(lat, lng, zoom, dFilter)
    {    
        currentZoom  = zoom;        
        if(typeof(map) == 'undefined')
        {
                waitToSetCenter=true;
                setZoom=zoom;
                setLat = lat;
                setLng = lng;
                if(curWaitSecond==0)
                    showLoadingHint(); //hook to call back            
                return;
        }
        PageMethods.GetExactMap(lat, lng, zoom, dFilter,loadXmlLocations);                    
    }

    function filterState(state)
    {
        var result=false;
        if($get(stateDDL).value!="")
        {
             if($get(stateDDL).value==state)
                result=true;
             else
                result=false;
        }
        else    
            result=true;
            
        return result;
    }

    function loadXmlTowers(result, userContext, methodName)
    {
        var xml = result;       
        
        if(typeof(map) == 'undefined')
            return;    
        
        towerMarkers = xml.documentElement.getElementsByTagName("marker");    
                
        if($('chkTower').checked==false)
            return;
            
        totalTowers=0;
        for (i = 0; i < towerMarkers.length; i++)     
            if (isCarrierIDChecked(towerMarkers[i].getAttribute("carrier")) && filterState(towerMarkers[i].getAttribute("state")))        
                  totalTowers++;        
        
        if(_debug ) alert(totalTowers);
        
        for (i = 0; i < Math.min(towerMarkers.length, maxTower); i++) 
        {
            var point = new GLatLng(parseFloat(towerMarkers[i].getAttribute("lat")),parseFloat(towerMarkers[i].getAttribute("lng")));        
            var id = parseInt(towerMarkers[i].getAttribute("id"), 10);        
            var carrier =towerMarkers[i].getAttribute("carrier");        
            var address = towerMarkers[i].getAttribute("address");        
            var city = towerMarkers[i].getAttribute("city");
            var state = towerMarkers[i].getAttribute("state");
            var date =  towerMarkers[i].getAttribute("date");                
            var heightAboveGround = towerMarkers[i].getAttribute("heightAboveGround");
            var heightOfStructure = towerMarkers[i].getAttribute("heightOfStructure");                
            var groundElevation = towerMarkers[i].getAttribute("groundElevation");                
            var heightAMSL = towerMarkers[i].getAttribute("heightAMSL");                
            var structureType = towerMarkers[i].getAttribute("structureType");                
            var icon = new GIcon(G_DEFAULT_ICON);
            var cZoom=map.getZoom();
            switch (cZoom)
            {
                case 10: icon.iconSize = new GSize(10, 20);icon.iconAnchor = new GPoint(5, 10);break;
                case 11: icon.iconSize = new GSize(12, 24);icon.iconAnchor = new GPoint(6, 12);break;
                case 12: icon.iconSize = new GSize(14, 28);icon.iconAnchor = new GPoint(7, 14);break;
                case 13: icon.iconSize = new GSize(16, 32);icon.iconAnchor = new GPoint(8, 16);break;
                case 14: icon.iconSize = new GSize(18, 36);icon.iconAnchor = new GPoint(9, 18);break;
                case 15: icon.iconSize = new GSize(20, 40);icon.iconAnchor = new GPoint(10, 20);break;
                case 16: icon.iconSize = new GSize(22, 44);icon.iconAnchor = new GPoint(11, 22);break;
                case 17: icon.iconSize = new GSize(24, 48);icon.iconAnchor = new GPoint(12, 24);break;
                default: icon.iconSize = new GSize(20, 40);icon.iconAnchor = new GPoint(7, 14);break;
            }
            icon.shadowSize = new GSize(0,0);                 
            switch (carrier)
            {
                case '0': icon.image = "img/TOWATNT.PNG"; break;
                case '1': icon.image = "img/TOWSPRINT.PNG"; break;
                case '3': icon.image = "img/TOWNEXTEL.PNG"; break;
                case '4': icon.image = "img/TOWTMOBILE.PNG"; break;
                case '7': icon.image = "img/TOWVERIZON.PNG"; break;
                default: icon.image = "img/TOWER.PNG"; break;            
            }
            if (isCarrierIDChecked(carrier) && filterState(state))  //only show towers markers that related to a checked carrier, filter as of state
            {
                var marker;
                if(towers[i]!=null)
                {
                    marker = towers[i].marker;
                    marker.myhtml = '<table>';
                    marker.myhtml += '<tr><td rowspan="4"><img src="' + icon.image + '" width="30" Alt="Tower icon"/></td><td><b><big>Tower Information</big></b></td></tr>';
                    marker.myhtml += '<tr><td>Carrier: <b>' + getCarrierName(carrier) + '</b></td></tr>';
                    marker.myhtml += '<tr><td>Location:<b> ' + address + ', ' + city + ', ' + state + '</b></td>';            
                    marker.myhtml += '<tr><td colspan="2">Date constructed:<b> ' + (date.trim()!=""?date.trim():"Not Available") + '</b></td></tr>';
                    marker.myhtml += '<tr><td colspan="2">StructureType:<b> ' + structureType + '</b></td></tr>';
                    marker.myhtml += '<tr><td colspan="2">Height:<b> ' + heightOfStructure + 'm</b></td></tr>';
                    marker.myhtml += '<tr><td colspan="2">Ground elevation:<b> ' + groundElevation + 'm</b></td></tr>';
                    marker.myhtml += '<tr><td colspan="2">Height above ground:<b> ' + heightAboveGround + 'm</b></td></tr>';
                    marker.myhtml += '<tr><td colspan="2">Overal height above mean sea level:<b> ' + heightAMSL + 'm</b></td></tr>';            
                    marker.myhtml += '</table>';                            
                    marker.setLatLng(new GLatLng(point.lat(), point.lng()));
                    marker.setImage(icon.image);                    
                    marker.show();
                    //towers[i]=new towerObj(id, carrier, point.lat(), point.lng(), date, address, city, state, null, null, null,null,null,marker)                    
                    towers[i].marker = marker;
                }
                else
                {                    
                    marker = new GMarker(point, icon);                    
                    marker.myhtml = '<table>';
                    marker.myhtml += '<tr><td rowspan="4"><img src="' + icon.image + '" width="30" Alt="Tower icon"/></td><td><b><big>Tower Information</big></b></td></tr>';
                    marker.myhtml += '<tr><td>Carrier: <b>' + getCarrierName(carrier) + '</b></td></tr>';
                    marker.myhtml += '<tr><td>Location:<b> ' + address + ', ' + city + ', ' + state + '</b></td>';            
                    marker.myhtml += '<tr><td colspan="2">Date constructed:<b> ' + (date.trim()!=""?date.trim():"Not Available") + '</b></td></tr>';
                    marker.myhtml += '<tr><td colspan="2">StructureType:<b> ' + structureType + '</b></td></tr>';
                    marker.myhtml += '<tr><td colspan="2">Height:<b> ' + heightOfStructure + 'm</b></td></tr>';
                    marker.myhtml += '<tr><td colspan="2">Ground elevation:<b> ' + groundElevation + 'm</b></td></tr>';
                    marker.myhtml += '<tr><td colspan="2">Height above ground:<b> ' + heightAboveGround + 'm</b></td></tr>';
                    marker.myhtml += '<tr><td colspan="2">Overal height above mean sea level:<b> ' + heightAMSL + 'm</b></td></tr>';            
                    marker.myhtml += '</table>';        
                    towers.push(new towerObj(id, carrier, point.lat(), point.lng(), date, address, city, state, 
                                null, null, null,null,null,marker));              
                    map.addOverlay(marker);               
                }
            }
        }     
    }

    //:)
    function loadXmlBuildings(result, userContext, methodName)
    {
        var xml = result;       
        
        if(typeof(map) == 'undefined')
            return;    
        
        buildingMarkers = xml.documentElement.getElementsByTagName("marker");                    
        
        if($('chkBuilding').checked==false)
            return;            
        
        totalBuildings=buildingMarkers.length;
                
        for (ti = 0; ti < Math.min(buildingMarkers.length, maxBuilding); ti++) 
        {
            var point = new GLatLng(parseFloat(buildingMarkers[ti].getAttribute("lat")),parseFloat(buildingMarkers[ti].getAttribute("lng")));        
            var id = parseInt(buildingMarkers[ti].getAttribute("id"), 10);        
            var entityname =buildingMarkers[ti].getAttribute("entityname");        
            var address = buildingMarkers[ti].getAttribute("address");        
            var city = buildingMarkers[ti].getAttribute("city");
            var state = buildingMarkers[ti].getAttribute("state");
            var date =  buildingMarkers[ti].getAttribute("date");                
            var heightAboveGround = buildingMarkers[ti].getAttribute("heightAboveGround");
            var heightOfStructure = buildingMarkers[ti].getAttribute("heightOfStructure");                
            var groundElevation = buildingMarkers[ti].getAttribute("groundElevation");                
            var heightAMSL = buildingMarkers[ti].getAttribute("heightAMSL");                
            var structureType = buildingMarkers[ti].getAttribute("structureType");                
            var icon = new GIcon(G_DEFAULT_ICON);
            var cZoom=map.getZoom();
            switch (cZoom)
            {
                case 10: icon.iconSize = new GSize(15, 25);icon.iconAnchor = new GPoint(8, 12);break;
                case 11: icon.iconSize = new GSize(17, 28);icon.iconAnchor = new GPoint(9, 14);break;
                case 12: icon.iconSize = new GSize(19, 31);icon.iconAnchor = new GPoint(10, 16);break;
                case 13: icon.iconSize = new GSize(21, 35);icon.iconAnchor = new GPoint(11, 17);break;
                case 14: icon.iconSize = new GSize(23, 38);icon.iconAnchor = new GPoint(12, 19);break;
                case 15: icon.iconSize = new GSize(25, 41);icon.iconAnchor = new GPoint(13, 21);break;
                case 16: icon.iconSize = new GSize(27, 45);icon.iconAnchor = new GPoint(14, 22);break;
                case 17: icon.iconSize = new GSize(29, 48);icon.iconAnchor = new GPoint(15, 24);break;
                default: icon.iconSize = new GSize(20, 33);icon.iconAnchor = new GPoint(10, 17);break;
            }
            icon.shadowSize = new GSize(0,0);     
            icon.image = "img/Building.png";                            
            var marker;
            if(buildings[ti]!=null)
            {
                marker = buildings[ti].marker;
                marker.myhtml = '<table>';        
                marker.myhtml += '<tr><td rowspan="4"><img src="' + icon.image + '" width="30" Alt="Tower icon"/></td><td><b><big>Building Information</big></b></td></tr>';
                marker.myhtml += '<tr><td>Owner: <b>' + entityname + '</b></td></tr>';
                marker.myhtml += '<tr><td>Location:<b> ' + address + ', ' + city + ', ' + state + '</b></td>';            
                marker.myhtml += '<tr><td colspan="2">Date constructed:<b> ' + (date.trim()!=""?date.trim():"Not Available") + '</b></td></tr>';
                marker.myhtml += '<tr><td colspan="2">StructureType:<b> ' + structureType + '</b></td></tr>';
                marker.myhtml += '<tr><td colspan="2">Height:<b> ' + heightOfStructure + 'm</b></td></tr>';
                marker.myhtml += '<tr><td colspan="2">Ground elevation:<b> ' + groundElevation + 'm</b></td></tr>';
                marker.myhtml += '<tr><td colspan="2">Height above ground:<b> ' + heightAboveGround + 'm</b></td></tr>';
                marker.myhtml += '<tr><td colspan="2">Overal height above mean sea level:<b> ' + heightAMSL + 'm</b></td></tr>';                    
                marker.myhtml += '</table>';      
                marker.setLatLng(new GLatLng(point.lat(), point.lng()));
                marker.show();
                //buildings[ti] = new buildingObj(id, entityname, point.lat(), point.lng(), date, address, city, state, null, null, null,null,null,marker);                
                buildings[ti].marker = marker;
            }
            else
            {   
                marker = new GMarker(point, icon);                
                marker.myhtml = '<table>';        
                marker.myhtml += '<tr><td rowspan="4"><img src="' + icon.image + '" width="30" Alt="Tower icon"/></td><td><b><big>Building Information</big></b></td></tr>';
                marker.myhtml += '<tr><td>Owner: <b>' + entityname + '</b></td></tr>';
                marker.myhtml += '<tr><td>Location:<b> ' + address + ', ' + city + ', ' + state + '</b></td>';            
                marker.myhtml += '<tr><td colspan="2">Date constructed:<b> ' + (date.trim()!=""?date.trim():"Not Available") + '</b></td></tr>';
                marker.myhtml += '<tr><td colspan="2">StructureType:<b> ' + structureType + '</b></td></tr>';
                marker.myhtml += '<tr><td colspan="2">Height:<b> ' + heightOfStructure + 'm</b></td></tr>';
                marker.myhtml += '<tr><td colspan="2">Ground elevation:<b> ' + groundElevation + 'm</b></td></tr>';
                marker.myhtml += '<tr><td colspan="2">Height above ground:<b> ' + heightAboveGround + 'm</b></td></tr>';
                marker.myhtml += '<tr><td colspan="2">Overal height above mean sea level:<b> ' + heightAMSL + 'm</b></td></tr>';                    
                marker.myhtml += '</table>';                      
                buildings.push(new buildingObj(id, entityname, point.lat(), point.lng(), date, address, city, state, 
                            null, null, null,null,null,marker));
                map.addOverlay(marker);                   
            }
        }     
    }

    function loadXmlComments(result, userContext, methodName)
    {
        oProgBar.show();
        
        xml = result;        
        
        if (insertingComment==false)
        {       
            var center = xml.documentElement.getElementsByTagName("center");
        }
        currentZoom = 0;
        
        if(typeof(map) == 'undefined')
        {
            oProgBar.hide();
            return;
        }
            
        if (map.getZoom() < minCommentVisibleZoom && methodName=="GetCommentByID")
        {
            if(_debug) alert("loadXmlComments():"+map.getZoom());
            map.setCenter(map.getCenter(), eval(minCommentVisibleZoom))
        }
        markers = xml.documentElement.getElementsByTagName("marker");
        
        if (comments != null)
        {
            for (i=0; i < comments.length; i++) 
            {
                map.removeOverlay(comments[i].marker);        
            }
        }
        
        if($('chkReview').checked==false)
        {
            oProgBar.hide();
            return;
        }
               
        comments = new Array();
        $get('commentsplace').innerHTML = "";
        
        totalComment=0;
        for (i = 0; i < markers.length; i++) 
        {        
            if (isCarrierChecked(markers[i].getAttribute("carrier")) && filterState(markers[i].getAttribute("state")))
                 totalComment++;
        }

        //If insertingComment==false, then we already hve moved to the location. So we dont need to move there again...
        if (markers.length == 0 && methodName != 'ZipCodeSearch' )
        {
            if (methodName != 'GetExactMap' && methodName!= 'CitySearch' &&  methodName != 'GetComments')
                FindLatLongForSearch();
            oProgBar.hide();
            return;
        } 
        
        /* Raman V2.02
        * Calculate Min Max of Lat and Lng
        */
        var minLat = 90.0;
        var maxLat = -90.0;
        var minLng = 180.0;
        var maxLng = -180.0;
        /*End*/
        
        for (i = 0; i < markers.length; i++) 
        {
            /* Raman V2.02
            */
            minLat = Math.min (minLat, parseFloat(markers[i].getAttribute("lat")));
            maxLat = Math.max (maxLat, parseFloat(markers[i].getAttribute("lat")));
            minLng = Math.min (minLng, parseFloat(markers[i].getAttribute("lng")));
            maxLng = Math.max (maxLng, parseFloat(markers[i].getAttribute("lng")));
            /* End */
            
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
            var rating = parseInt(markers[i].getAttribute("rating"), 10);
            var id = parseInt(markers[i].getAttribute("id"), 10);
            var display = markers[i].getAttribute("display");
            var overallrating = parseInt(markers[i].getAttribute("overallrating"), 10);
            var carrier = markers[i].getAttribute("carrier");
            var phoneb = markers[i].getAttribute("phoneb");
            var phonem = markers[i].getAttribute("phonem");
            var zip = markers[i].getAttribute("zip");
            var address = markers[i].getAttribute("address");
            var address2 = markers[i].getAttribute("address2");
            var city = markers[i].getAttribute("city");
            var state = markers[i].getAttribute("state");
            var date =  markers[i].getAttribute("date");
            var comment =  markers[i].getAttribute("comment");
            var username =  markers[i].getAttribute("username");
            var avatarPic =  markers[i].getAttribute("avatarpic");
            var phonePic =  markers[i].getAttribute("phonepic");
            var signalIcon0 =  markers[i].getAttribute("signalicon0"); 
            var signalIcon1 =  markers[i].getAttribute("signalicon1"); 
            var signalIcon2 =  markers[i].getAttribute("signalicon2"); 
            var signalIcon3 =  markers[i].getAttribute("signalicon3"); 
            var signalIcon4 =  markers[i].getAttribute("signalicon4"); 
            var signalIcon5 =  markers[i].getAttribute("signalicon5"); 
            var logo_small =  markers[i].getAttribute("logo_small");
            var towercount = markers[i].getAttribute("towercount");
            var tab1Html = '';
            var tab2Html = '';
            var tab3Html = '';
            
            var icon = new GIcon(baseIcon);
            switch(rating)
            {
                case 0:
                    icon.image = "UploadedImages/" + signalIcon0;
                    break;
                case 1:
                    icon.image = "UploadedImages/" + signalIcon1;
                    break;
                case 2:
                    icon.image = "UploadedImages/" + signalIcon2;
                    break;
                case 3:
                    icon.image = "UploadedImages/" + signalIcon3;
                    break;
                case 4:
                    icon.image = "UploadedImages/" + signalIcon4;
                    break;
                case 5:
                    icon.image = "UploadedImages/" + signalIcon5;
                    break;                
            }                                         

            //============= 
            if (isCarrierChecked(carrier) && filterState(state))  //only show comments markers that related to a checked carrier, filter as of state
            {
                var marker ;            
                //show the wave icons or invisible icons depends on zoom level
                
                if(map.getZoom() >= minCommentVisibleZoom)
                {
                    marker = new GMarker(point, icon);                    
                }
                else
                {
                    var myIcon = new GIcon(G_DEFAULT_ICON);
                    myIcon.image = "/img/FilledBar.png";        
                    myIcon.shadowSize = new GSize(0,0);  
                    marker = new GMarker(point, myIcon);
                }
                                
                
                tab1Html = '<table style="font-family:tahoma;font-size:11px;width:300px">';
                tab1Html += '<tr><td>Signal:</td><td><img class="rate" src="img/signal/' + rating + '.gif" alt="' + rating + '" />' + '</td><td>Carrier:</td><td><img width="80" src="img/carriersSmall/' + logo_small + '" alt="Carrier logo" /></td></tr>';
                tab1Html += '<tr><td colspan="4">Towers: ' + towercount+ ' (Search Radius at 4.0 miles)</td></tr>';
                //tab1Html += '<tr></tr>';
                
                //<frequency bandid="3" bandname="PCS 1900" carriername="T-Mobile" minfrequency="1850" maxfrequency="1990" zipcode="08701" />
                var frequncyArray = markers[i].getElementsByTagName("frequency");
                
                if(frequncyArray!=null && frequncyArray.length>0)
                {
                    tab1Html += '<tr><td colspan="4">'
                    tab1Html += '<table style="font-family:tahoma;font-size:11px;width:275px">';
                    tab1Html += '<tr style="background-color:#ddd"><td>Band</td><td>Min Frequency</td><td>Max Frequency</td></tr>';
                    for(var iFreq=0; iFreq<frequncyArray.length;iFreq++)
                    {
                        tab1Html += '<tr>';
                        tab1Html += '<td>'+ frequncyArray[iFreq].getAttribute("bandname") +'</td>';
                        tab1Html += '<td>'+ frequncyArray[iFreq].getAttribute("minfrequency") +' Mhz</td>';
                        tab1Html += '<td>'+ frequncyArray[iFreq].getAttribute("maxfrequency") +' Mhz</td>';
                        tab1Html += '</tr>';
                    }
                    tab1Html += '</table>';
                    tab1Html += '</td></tr>';
                }
                
                tab1Html += '<tr><td colspan="4"><a href="http://www.cellswapper.com" target="_blank" style="color:blue">Escape any cell phone contract</a>' + '</td></tr>';
                tab1Html += '</table>';
                
                tab2Html = '<table style="font-family:tahoma;font-size:11px;width:300px">';
                tab2Html += '<tr><td colspan="4">Address: ' + address + '</td></tr>';
                tab2Html += '<tr><td colspan="4">' + address2 +'</td></tr>';
                tab2Html += '<tr><td colspan="4">' + city + '<br />' + state + ', ' + zip + '</td></tr>';
                
                tab3Html = '<table style="font-family:tahoma;font-size:11px;width:300px">';
                tab3Html += '<tr><td colspan="4">Phone: ' + phoneb + ' ' + phonem  + '</td></tr>';
                
                tab3Html += '<tr><td colspan="4">';
                if (phonePic != '')
                    if(phonePic.indexOf('http')==0)
                        tab3Html += '<img src="' + phonePic  + '" alt="' + phonem +'" width="80" />';
                    else
                        tab3Html += '<img src="UploadedImages/' + phonePic  + '" alt="' + phonem +'" width="80" />';
                tab3Html += '</td></tr>';
                
                if (avatarPic != '')
                {
                    tab3Html += '<tr><td colspan="4">';
                    tab3Html += '<img src="UploadedImages/' + avatarPic  + '" alt="' + username +'" width="80" />';
                    tab3Html += '</td></tr>';
                }
                tab3Html += '<tr><td colspan="4"><a href="http://www.cellswapper.com" target="_blank" style="color:blue">Escape any cell phone contract</a>' + '</td></tr>';
                tab3Html += '</table>';
               
                comments.push(new commentObj(id, point.lat(), point.lng(), rating, overallrating, carrier, phoneb, phonem, zip, address, address2, city, state, date, comment, username, avatarPic, phonePic, logo_small, towercount, tab1Html, tab2Html, tab3Html, marker ));
                
                map.addOverlay(marker);
               
                if(typeof(getCommentByID) != 'undefined')
                {
                   if(getCommentByID==true){                    
                        if(_debug) alert("map.getZoom():"+map.getZoom());
                        ofs = map.getBounds().getNorthEast().lat() - map.getBounds().getSouthWest().lat();
                        ofs /= 4;                    
                        map.setCenter(new GLatLng(point.lat() + ofs , point.lng()), map.getZoom());
                        //marker.openInfoWindowHtml(marker.myhtml);
                        //marker.openInfoWindowTabsHtml([new GInfoWindowTab("Reception",tab1Html), new GInfoWindowTab("Location",tab2Html), new GInfoWindowTab("Phone",tab3Html)]);
                        var tabs = [];
                        tabs.push(new GInfoWindowTab("Reception",comment.tab1Html));
                        tabs.push(new GInfoWindowTab("Location",comment.tab2Html));
                        tabs.push(new GInfoWindowTab("Phone",comment.tab3Html));
                        marker.openInfoWindowTabsHtml(tabs, {maxWidth: '450'});
                   }
               }    
            }
            
            //V6.0 -----------
            if(typeof(getCommentByID) != 'undefined')
            {
                if( getCommentByID==true && newCommentPosted==true)
                {
                    if( rating<=2){
                        jQuery('.suggestion').show();
                        jQuery('.spanCssBestCarrierName').html(objCarrier.name);
                        if(objCarrier.name!= carrier){
                            jQuery('.suggestion1').show();
                            jQuery('.suggestion2').show();
                        }
                        else{
                            jQuery('.suggestion1').hide();
                            jQuery('.suggestion2').show();
                        }
                    }
                newCommentPosted=false;
                }
            }
        }//end of FOR LOOP
        
       /* Raman V2.02
        *Find the maximum zoom level at which all of the requested addresses
        *will fit into the map (with a bit of margin), and zoom the map to
        *that level.  Note that it doesn't seem to work to specify the
        *corners of the bounding box when creating the GLatLngBounds
        *object, so we need to use the alternate approach of calling the
        *extend method instead.
       */
        
        if(ToLoadUserComment!='undefined' && ToLoadUserComment==true)
        {
            var bounds = new GLatLngBounds;
            bounds.extend (new GLatLng (minLat - ((maxLat - minLat) / 12),minLng - ((maxLng - minLng) / 12)));
            bounds.extend (new GLatLng (maxLat + ((maxLat - minLat) / 12),maxLng + ((maxLng - minLng) / 12)));
            var newZoomLevel = map.getBoundsZoomLevel (bounds);
            map.setZoom (newZoomLevel);
            map.setCenter(bounds.getCenter(), newZoomLevel);
            if(_debug) alert("newZoomLevel:"+ newZoomLevel);
        }
        
        /* Raman Alternative to the above */ 
        //// Define the two corners of the bounding box 
		//var sw = new GLatLng(minLat, minLng);
		//var ne = new GLatLng(maxLat, maxLng);
		//// Create a bounding box  
		//var bounds = new GLatLngBounds(sw, ne);
		////Center map in the center of the bounding box and calculate the appropriate zoom level
        //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
		/* End  */
		
		
        if(typeof(getCommentByID)!='undefined')
        {
            if(getCommentByID==true)
                getCommentByID=false;
        }
        oProgBar.hide();
    }

    function mapClick(theMarker, coord)
    {
    if (comments != null)
    {
        //if(_debug) alert("mapClick:totalComment"+ totalComment);
        for (i=0; i < totalComment; i++) 
        {
            if(typeof(comments[i])!='undefined')
            {
                if(comments[i].marker == theMarker)
                {                        
                    //comments[i].marker.openInfoWindowHtml(comments[i].marker.myhtml);    
                    var tabs = [];
                    tabs.push(new GInfoWindowTab("Reception",comment.tab1Html));
                    tabs.push(new GInfoWindowTab("Location",comment.tab2Html));
                    tabs.push(new GInfoWindowTab("Phone",comment.tab3Html));
                    comments[i].marker.openInfoWindowTabsHtml(tabs, {maxWidth: '450'});
                    return;
                }
            }
        }
    } 
    //arrDealers[i].Marker.openInfoWindowHtml(arrDealers[i].Label);
    if (arrDealers != null)
    {
        for (i=0; i < arrDealers.length; i++) 
        {
            if(typeof(arrDealers[i])!='undefined')
            {
                if(arrDealers[i].Marker == theMarker)
                {                        
                    //arrDealers[i].Marker.openInfoWindowHtml(arrDealers[i].Label);
                    var _marker = arrDealers[i].Marker;
                    _marker.openInfoWindowTabsHtml([new GInfoWindowTab("ADDRESS",arrDealers[i].Label), new GInfoWindowTab("HOURS",arrDealers[i].Label2)]);

                    return;
                }
            }
        }
    }
    if(towers != null)
    {
        if(_debug) alert(totalTowers);
        
        for (i=0; i < totalTowers; i++) 
        {
            if(typeof(towers[i])!='undefined')
            {
                if(towers[i].marker == theMarker)
                {                        
                    towers[i].marker.openInfoWindowHtml(towers[i].marker.myhtml);    
                    return;
                }
            }
        }  
    }

    if(buildings != null)
    {
        for (i=0; i < totalBuildings; i++) 
        {
            if(typeof(buildings[i])!='undefined')
            {
                if(buildings[i].marker == theMarker)
                {                        
                    buildings[i].marker.openInfoWindowHtml(buildings[i].marker.myhtml);    
                    return;
                }
            }
        }  
    }
    }

    function loadXmlLocations(result, userContext, methodName)
    {    
        //if map is not loaded, then register this method to be called after load
        if(typeof(map) == 'undefined')
        {
                r=result;
                u=userContext;
                m=methodName;
                waitForLoadXmlLocations=true;
                if(curWaitSecond==0)
                    showLoadingHint(); //hook to call back
                return;            
        }            

        loadXmlComments(result, userContext, methodName);   
        insertingComment=false;   
        curCommentPage=0;
        populateComments(methodName); 
    }
    
    /* Raman V2.06 */
    function plotOnMap(markerIndex)
    {
        ToLoadUserComment=true;
        
        var comment = comments[markerIndex];
        var _marker = comment.marker;
        
        var newZoomLevel = parseFloat(minCommentVisibleZoom) + 2;
        var bounds = new GLatLngBounds;
//        bounds.extend (new GLatLng (minLat - ((maxLat - minLat) / 12),minLng - ((maxLng - minLng) / 12)));
//        bounds.extend (new GLatLng (maxLat + ((maxLat - minLat) / 12),maxLng + ((maxLng - minLng) / 12)));
//        var newZoomLevel = map.getBoundsZoomLevel (bounds);

//        map.setZoom (newZoomLevel);
//        map.setCenter(bounds.getCenter(), newZoomLevel);
        
        var tabs = [];
        tabs.push(new GInfoWindowTab("Reception",comment.tab1Html));
        tabs.push(new GInfoWindowTab("Location",comment.tab2Html));
        tabs.push(new GInfoWindowTab("Phone",comment.tab3Html));
        _marker.openInfoWindowTabsHtml(tabs, {maxWidth: '450'});
        //_marker.show();
        //_marker.openInfoWindowHtml(_marker.myhtml);
        var point = new GLatLng(parseFloat(comment.lat), parseFloat(comment.lng));
                
        map.setCenter(point, newZoomLevel);
        map.setZoom (newZoomLevel);
        var newPoint1=map.getCenter();
        map.panTo (newPoint1, newZoomLevel);

        var mz = map.getCurrentMapType().getMaximumResolution();
        //alert(mz);
    }
    
    //displaying comments grid below map
    var curCommentPage=0;
    function populateComments(meth)
        {
        if (comments == null)
            return;

        if($('chkReview').checked==false)
        {
            //$get('commentsplace').innerHTML="";
            return;
        }
     
        var gridhtml = "";
        totalComments=comments.length;
        commentPages=Math.ceil(totalComments/5);   //5 comments/page

        //====paging start grid
        if(commentPages > 1)
        {
            gridhtml += '<br/><div align="center">';
            for(k = 0; k < commentPages; k++)
            {
                if(k == curCommentPage)
                {
                    gridhtml += '<b>' + (k+1) + '</b>';
                }
                else
                {
                    gridhtml += '<a href="javascript:void(0);" onclick="curCommentPage=' + k + '; populateComments(\'' + meth + '\');">' + (k+1) + '</a>';
                }           
                
                if(k < commentPages)
                    gridhtml += '&nbsp;';
            }        
            gridhtml+= '</div>';    
        }

        //====comment grid        
        for (i=curCommentPage*5; i < Math.min(curCommentPage*5+5,totalComments); i++) 
        {
            comment = comments[i];
            st = "dark"
            if (i%2 == 0)
                st = "light"

            //gridhtml += '<a class="commentlink_' + st + '" href="#" onclick="comments[' + i + '].marker.openInfoWindowHtml(comments[' + i + '].marker.myhtml);">';
            gridhtml += '<a class="commentlink_' + st + '" href="#" onclick="plotOnMap(' + i + '); return false;">';
            gridhtml += '<div class="comment_' + st + '">';
            gridhtml += '<div class="avatar"><img src="';
                
            if (comment.avatarPic != '')
                gridhtml += 'UploadedImages/' + comment.avatarPic;
            else
                gridhtml += 'img/cplaceholder.jpg';        
                gridhtml += '" alt="Avatar" /><p>'    
                            + comment.username + '</p><p>' + /*comment.address*/ '' + '</p>'
                            + '</div>'
                            + '<div class="cellphone_image">'
                            + '<img width="68" onload="if(this.height>64){this.style.width=\'auto\'; this.style.height=\'64px\';}"  src="';    
            if (comment.phonePic != '')
            {
                if(comment.phonePic.indexOf('http')==0)                
                         gridhtml += comment.phonePic;
                else
                         gridhtml += 'UploadedImages/' + comment.phonePic;
            }
            else
                gridhtml += 'img/MOBICON.jpg';            
                
            gridhtml += '" alt="Cellphone" /><p>'
                + comment.phoneb + (comment.phonem!=comment.phoneb?comment.phonem:'') + '</p>'
                + '</div>'
                + '<div class="ratings">'
	             + '<div class="carrier"><img width="80" src="img/carriersSmall/' + comment.logoSmall + '" alt="Carrier logo" /></div>'
                + '<div class="stars"><img src="img/stars/' + comment.overallrating + '.gif" alt="' + comment.overallrating + '" /></div>'
                + '<div class="signal"><img src="img/signal/' + comment.rating + '.gif" alt="' + comment.rating + '" /></div>'
                + '</div>'
                + '<div class="comment">'
                + '<p>' + comment.address;
            gridhtml += (comment.address2 != '') ? '<br/>' + comment.address2 : '';
            gridhtml += '<br>' + comment.city + ', ' + comment.state + ' ' + comment.zip + '</p>'
                + '<p>' + comment.comment + '</p></div>'
                + '</div>';
            if (meth == 'GetUserComments')
                gridhtml += '<div style="position: absolute;"><div class="popupeditcomment"><a href="javascript:void(0);" onclick="editComment(comments[' + i + ']);">Edit</a>&nbsp;<a href="javascript:void(0);" class="delete_link" onclick="deleteComment(comments[' + i + '].id);">Delete</a></div></div>';
            gridhtml += '</a>';
            gridhtml += '<div style="clear:both;">';
        }    

        //====paging end grid
        if(commentPages > 1)
        {
            gridhtml += '<br/><div align="center">';
            for(k = 0; k < commentPages; k++)
            {
                if(k == curCommentPage)
                {
                    gridhtml += '<b>' + (k+1) + '</b>';
                }
                else
                {
                    gridhtml += '<a href="javascript:void(0);" onclick="curCommentPage=' + k + '; populateComments(\'' + meth + '\');">' + (k+1) + '</a>';
                }           
                
                if(k < commentPages)
                    gridhtml += '&nbsp;';
            }        
            gridhtml+= '</div>';
        }
        $get('commentsplace').innerHTML = gridhtml;
        ddequalcolumns.resetHeights();

    }

    function deleteComment(cmtID)
    {    
        var res=confirm("Are you sure you want to delete that comment?");
        if (res)
            PageMethods.DeleteComment(cmtID, onDeleteComplete);     
        return false;
    }

    function onDeleteComplete (result, userContext, methodName)
    {
        showUserComments();
    }

    function openCommentAndFocus()
    {
        expandCommentForm();    //empty function in vb code
        location.href='#comment_anchor';
        return false;
    }
        
    function trim (str) 
    {
        return str.replace(/^\s+|\s+$/g, '');
    }

    function ValidateEmpty(source, arguments)
    {
      if (validateUser == false)
      {
        arguments.IsValid = true;
        return;
      }
        
      if (trim(arguments.Value) == "")
        arguments.IsValid = false;
      else
        arguments.IsValid = true;
    }
               
    function validateUsername(source, arguments)
    {
      if (validateUser == false)
      {
        arguments.IsValid = true;
        return;
      }
        
      if (trim(arguments.Value) == "")
        arguments.IsValid = false;
      else
      {
        var myAjax = new Ajax.Request("CheckUsername.ashx", {
        parameters: "q=" + trim(arguments.Value),
        method: 'get',
        asynchronous: false } );	
        if (myAjax.transport.responseText=='true')
            arguments.IsValid = true;
        else
            arguments.IsValid = false;
      }
    }
           
    function validateEmail(source, arguments)
    {
      if (validateUser == false)
      {
        arguments.IsValid = true;
        return;
      }
        
      if (trim(arguments.Value) == "")
        arguments.IsValid = false;
      else
      {
        var myAjax = new Ajax.Request("CheckEmail.ashx", {
        parameters: "q=" + trim(arguments.Value),
        method: 'get',
        asynchronous: false } );	
        if (myAjax.transport.responseText=='true')
            arguments.IsValid = true;
        else
            arguments.IsValid = false;
      }
    }

    function selectTextboxOnEnter(e, txb) 
    {   
    var iKeyCode;
    if (window.event) 
        iKeyCode = window.event.keyCode;
    else if (e) 
        iKeyCode = e.which;

    if(iKeyCode)
    {
        if (iKeyCode==13)
        {        
            txb.focus();
            return false;
        }
    }
    return;    
    }   
        
    function clickBtnOnEnter(evt, btn) 
    {  
      var evt = (evt) ? evt : window.event;
      if (evt.keyCode == 13) { 
        btn.click(); 
        //return false;
      }
      //return false;
    }
        
    function closePopups ()
    {
        if(AjaxControlToolkit.PopupControlBehavior.__VisiblePopup)
            AjaxControlToolkit.PopupControlBehavior.__VisiblePopup.hidePopup(); 
        return false;
    }
        
    function showLoginBox()
    {
        var logctr = $get('login_container');
        if (logctr.style.display == 'none')
            logctr.style.display='block';
        else
            logctr.style.display='none';
    }
        
    function initOverLabels () 
    {
      
        if (!document.getElementById) return;  	
        var labels, id, field;

          // Set focus and blur handlers to hide and show 
          // LABELs with 'overlabel' class names.
        labels = document.getElementsByTagName('label');
        for (i = 0; i < labels.length; i++) 
        {	
            if (labels[i].className == 'overlabel') 
            {
              // Skip labels that do not have a named association with another field.
              id = labels[i].htmlFor || labels[i].getAttribute('for');
              if (!id || !(field = document.getElementById(id))) 
              {
                continue;
              }

              // Change the applied class to hover the label 
              // over the form field.
              labels[i].className = 'overlabel-apply';

              // Hide any fields having an initial value.
              if (field.value !== '') {
                hideLabel(field.getAttribute('id'), true);
              }

              // Set handlers to show and hide labels.
              field.onfocus = function () {
                hideLabel(this.getAttribute('id'), true);
              };
              field.onblur = function () {
                if (this.value === '') {
                  hideLabel(this.getAttribute('id'), false);
                }
              };

              // Handle clicks to LABEL elements (for Safari).
              labels[i].onclick = function () {
                var id, field;
                id = this.getAttribute('for');
                if (id && (field = document.getElementById(id))) {
                  field.focus();
                }
              };
            }
        }
    }

    function hideLabel (field_id, hide) 
    {
      var field_for;
      var labels = document.getElementsByTagName('label');
      for (i = 0; i < labels.length; i++) {
        field_for = labels[i].htmlFor || labels[i].getAttribute('for');
        if (field_for == field_id) {
          labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
          return true;
        }
      }
    }

    function selectState(ddl, state)
    {
        i;        
        for (i=0; i<ddl.options.length; i++)
        {
            if (ddl.options[i].value == state)
            {
                ddl.options[i].selected = true;
                return;
            }
        }    
    }

    function selectedState(ddl)
    {
        i;        
        for (i=0; i<ddl.options.length; i++)
        {
            if (ddl.options[i].selected)
            {
                return ddl.options[i].value;
            }
        }
        return "";
    }

    //this function task is to override the default emptyStar with 5 different emptyStar for Reception Rating
    function updateBar(barID, value)
    {
        
        //For IE: argument "value" is undefined because IE doesn't update RatingBehavior._currentRating until mouse is clicked
        //so we have to calculate the current hover rating by using x coordinate of event object
        if(typeof(value)=='undefined')
        {
            if(event != null)
            {
                if($('comments').offsetLeft==0) //IE case
                {    
                    start1 = $('wrapper').offsetLeft + $('content').offsetLeft + $('comment_form').offsetLeft +  $('cpadding').offsetLeft  + $('ratingTable').offsetLeft  + $('ratingRow').offsetLeft  + $('ratingCell').offsetLeft  + $('ratingSpan').offsetLeft   + $(barID+"_Star_1").offsetLeft;
                    value = Math.ceil((event.x-start1)/13);            //13 is the width of 1 bar            
                }
            }
            else
            {
                return true;
            }       
        }    
        
        $(barID + "_Star_1").attributes['class'].value = value<1?"ratingItem emptyRatingBar1":"ratingItem filledRatingBar";
        $(barID + "_Star_2").attributes['class'].value = value<2?"ratingItem emptyRatingBar2":"ratingItem filledRatingBar";
        $(barID + "_Star_3").attributes['class'].value = value<3?"ratingItem emptyRatingBar3":"ratingItem filledRatingBar";
        $(barID + "_Star_4").attributes['class'].value = value<4?"ratingItem emptyRatingBar4":"ratingItem filledRatingBar";
        $(barID + "_Star_5").attributes['class'].value = value<5?"ratingItem emptyRatingBar5":"ratingItem  filledRatingBar";
        return true;
    }

    function loadGoogleScripts()  //body.onload will call trigger() to dynamically load the google map script
    { 
      if(ToShowLoadingHint)
        showLoadingHint();  
      script = document.createElement("script");
      script.type = "text/javascript";  
      gmapScriptAddress="http://maps.google.com/maps?file=api&v=2.x&async=2&callback=load&key=" + gkey;
      script.src = gmapScriptAddress;
      document.body.appendChild(script);
      script = document.createElement("script");
      script.type = "text/javascript";
      script.src = urchinScript;
      document.body.appendChild(script);  
      _uacct = "UA-1109792-8";
      if(typeof(urchinTracker) != 'undefined')
        urchinTracker();  
    }

    var maxWaitSecond=30;
    var curWaitSecond=0;
    var waitForGetUserComment=false;
    var currentUser="";
    var r="";
    var u="";
    var m="";
    var waitForLoadXmlLocations=false;
    var setZoom;
    var setLat;
    var setLng;
    var waitToSetCenter=false;           
    var waitForMoveToState=false;
    var stateLat=null;
    var stateLng=null;
    var stateToMoveTo=null;

    function showLoadingHint()
    {
        mapdiv = document.getElementById('map');
        
        if (typeof(map) == 'undefined')        
            if (curWaitSecond==0)
                mapdiv.innerHTML ="Map loading ";
              
        if (typeof(map) == 'undefined')
        {
            curWaitSecond += 1;
            if(curWaitSecond <= maxWaitSecond)
            {
                mapdiv.innerHTML += "<img src='/img/progressDot.jpg' width='13' height = '13'/>" ;
                setTimeout(showLoadingHint,1000);       
            }
            else
            {
                    mapdiv.innerHTML = "The map loading takes longer than usual, you can keep on waiting or try again later";                            
                    curWaitSecond=0;
                    window.setTimeout(showLoadingHint,1500);
            }
        }
        else
        {
            curWaitSecond=0;
            
            if(waitForLoadXmlLocations == true)
            {
                //call back after load
                loadXmlLocations(r,u,m);
                r="";
                u="";
                m="";
                waitForLoadXmlLocations=false;
            }
            
            if(waitToSetCenter==true)
            {
                waitToSetCenter=false;           
                map.setCenter(new GLatLng(setLat, setLng),setZoom);
            }        
            
            if(waitForMoveToState==true)       
            {            
                waitForMoveToState=false;
                map.setCenter(new GLatLng(stateLat, stateLng), defaultStateViewZoom);                    
                $get(stateDDL).value=stateToMoveTo;
                $get('city').value="";
                showInsertCommentBubble(stateLat, stateLng);
            }                  
            
            if(waitForGetUserComment == true)
            {
                //call back after load
                showUserComments(currentUser);            
                currentUser="";
                waitForGetUserComment=false;
            }
        }
}