﻿ //**************************************************
//  GLOBAL VARS
//**************************************************
var map = null;
var address = "";
var dcLayer = null;
var loadingIndicator = "<img src=\"Images/ajax-loader_tiny.gif\" />loading...";
var pinWithStyle = "";
var listings = "";
var listings2 = "";
var waitStatus = "Loading... please wait...";


//**************************************************
//  FUNCTIONS
//**************************************************
function changePinStyle( msPinId, newClass, counter, daycareId, pinTextStyle )
{   
    var point = map.GetShapeByID( msPinId );
    var customIconHTML = '<DIV ID=' + counter + '><div id=\"pin' + daycareId + '\" class=\"' + newClass + '\"><div class=\"' + pinTextStyle + '\">' + counter + '</div></div>';
    point.Show();
    point.SetCustomIcon( customIconHTML );
}

function changePinStyleOut( msPinId, newClass, counter, daycareId, pinTextStyle )
{   
    var point = map.GetShapeByID( msPinId );
    var customIconHTML = '<DIV ID=' + counter + '><div id=\"pin' + daycareId + '\" class=\"' + newClass + '\"><div class=\"' + pinTextStyle + '\">' + counter + '</div></div>';
    point.Show();
    point.SetCustomIcon( customIconHTML );
}

function recordHoverStat( dcId )
{
    // record mouse over stat
    wsChildCare.RecordMouseOverPointStat( dcId );
}

// function to catch enter-key event
function onEnter( evt, frm ) 
{
    var keyCode = null;

    if( evt.which ) 
    {
        keyCode = evt.which;
    }
    else if( evt.keyCode ) 
    {
        keyCode = evt.keyCode;
    }
    if( 13 == keyCode ) 
    {
        frm.Button1.click();
        return false;
    }
    return true;
}


function loadPage()
{
    loadMap();
    getCityOrZip();    
    findAddress( address );
}

function Button1_onclick() 
{
    // clear up the map and listings
    listings = "";
    listings2 = "";
    waitStatus = "Loading... please wait...";
    setListingsToDiv();
    
    // get search criteria
    getCityOrZip();
    
    // find it
    findAddress( address );
}

function loadMap()
{
    map = new VEMap('myMap');
    map.SetDashboardSize("normal");
    map.LoadMap();
}

function getCityOrZip()
{
    var addressTemp = document.getElementById( 'ctl00_cphMainContent_txtCityZip' ).value;
    if( addressTemp == "Enter your city, postal code, or street address" )
    {
        addressTemp = "bogas lumby";
    }
    address = addressTemp;
}

function findAddress( strAddress )
{
    if( strAddress == "bogas lumby" || strAddress == "" )
    {
        FindMe();
    }
    else
    {
        try
        {
            map.Find( null, strAddress, null, null, 0, null, true, true, true, true, onFoundResults );
        }
        catch(e)
        {
            alert(e.message);
        }
    }
}

function detachEvents()
{
    map.DetachEvent( "onendpan", onChangeView );
    map.DetachEvent( "onendzoom", onChangeView );
}

function attachEvents()
{
    map.AttachEvent( "onendpan", onChangeView );
    map.AttachEvent( "onendzoom", onChangeView ); 
}

function clearPointsOnBaseLayer()
{
    var baseLayer = map.GetShapeLayerByIndex( 0 );
    baseLayer.DeleteAllShapes();
}

function onFoundResults(a, b, c, d)
{
    if(c != null)
    {
        try
        {
            // remove events so they don't fire when relocating
            detachEvents();
            
            // clear points on base map
            clearPointsOnBaseLayer();
            
            // plot new point
            //Add a pushpin to the first place
            var shape = new VEShape(VEShapeType.Pushpin, c[0].LatLong);
            shape.SetCustomIcon( "Images/MapIcons/CenterPoint.gif" );
            shape.SetTitle(c[0].Name);
            map.AddShape(shape);
        }
        catch(e)
        {
            alert(e.message);
        }
    }
    
    // get search results
    map.SetZoomLevel(14);
    
    // attach or re-attache map events
    attachEvents();
    
    getSearchResultsForCurrentMap();
}

function onChangeView()
{
    getSearchResultsForCurrentMap();
}

function getSearchResultsForCurrentMap()
 {
    var zoomLevel = map.GetZoomLevel();
    if( zoomLevel >= 14 )
    {
         // get searched point
        var baseLayer = map.GetShapeLayerByIndex(0);
        var mainPoint = baseLayer.GetShapeByIndex( 0 );
        var pts = mainPoint.GetPoints();

        var lat = pts[0].Latitude;
        var lng = pts[0].Longitude;
        
        var view = map.GetMapView();
        var top = view.TopLeftLatLong.Latitude;
        var bottom = view.BottomRightLatLong.Latitude;
        var left = view.TopLeftLatLong.Longitude;
        var right = view.BottomRightLatLong.Longitude;

        // start the loading indicator
        document.getElementById('waitStatus').innerHTML = loadingIndicator;
        
        //alert( "Top: " + top + "\nBottom: " + bottom + "\nLeft: " + left + "\nRight: " + right + "\nCenterLat:" + lat + "\nCenterLng:" + lng );
        wsChildCare.GetDaycares( top, bottom, left, right, lat, lng, OnComplete );
        
        doFind();
    }
    else
    {
        // delete all points
        if( dcLayer != null )
        {
            dcLayer.DeleteAllShapes();
        }
        
        // remove all listings
        listings = "Zoom in to see results";
        listings2 = "";
        waitStatus = "There are no results plotted at this zoom level; use the map's magnifying glass to zoom in to see results, or enter a new search above.";
        setListingsToDiv();
    }
 }

function OnComplete( dcXml ) {
    // remove all points from restaurant layer
    if( dcLayer != null )
    {
        dcLayer.DeleteAllShapes();
    }
    
    // reset listings
    listings = "";
    listings2 = "";
    waitStatus = "Loading... please wait...";
    setListingsToDiv();

    //  alert(dcXml);
    var dcDisplayId = 0;

    if (dcXml.length > 21) // 21 is the length of <daycares></daycares> which is what is returned with no results
    {
        var counter = 0;

        // ie fix
        if ($.browser.msie) {
        
            var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.loadXML(dcXml);
            dcXml = xmlDoc;

            var x = xmlDoc.getElementsByTagName("daycares")
            var displayId = "";

            if (x[0].childNodes.length > 0) {
                // plot paid first
                for (j = 0; j < x[0].childNodes.length; j++) {
                    displayId = x[0].childNodes[j].childNodes[12].text;
                    if (displayId == 1) {
                        extractFromXMLandPlot(x, j);
                    }
                }

                // plot others after
                for (j = 0; j < x[0].childNodes.length; j++) {
                    displayId = x[0].childNodes[j].childNodes[12].text;
                    if (displayId > 1) {
                        extractFromXMLandPlot(x, j);
                    }
                }
            }
        }
        
        // all other browsers
        else {

            // plot PREMO listings first
            $(dcXml).find("daycare").each(function() {
                dcDisplayId = parseInt($(this).find("displayid").text());
                if (dcDisplayId == 1) {
                    counter++;
                    extractFromXMLandPlot2(this, counter);
                }
            });

            // plot BASIC listings next
            $(dcXml).find("daycare").each(function() {
                dcDisplayId = parseInt($(this).find("displayid").text());
                if (dcDisplayId > 1) {
                    counter++;
                    extractFromXMLandPlot2(this, counter);
                }
            });
            
        }
    }
    else
    {
        // reset listings
        listings = "<div style=\"error\">No listings found.</div>";
        waitStatus = "Your search returns zero results, please refine your search-text and click 'search' again.";
        setListingsToDiv();
    }
        
        // drop loading indicator
        document.getElementById('waitStatus').innerHTML = "";
    }

    function extractFromXMLandPlot(x, j) //  x is the xml doc and j is the counter
    {
        // extract values
        var dcId = x[0].childNodes[j].childNodes[0].text;
        var dcGuid = x[0].childNodes[j].childNodes[1].text;
        var name = x[0].childNodes[j].childNodes[2].text;
        var description = x[0].childNodes[j].childNodes[3].text;
        var street = x[0].childNodes[j].childNodes[4].text;
        var city = x[0].childNodes[j].childNodes[5].text;
        var prov = x[0].childNodes[j].childNodes[6].text;
        var zip = x[0].childNodes[j].childNodes[7].text;
        var lat = x[0].childNodes[j].childNodes[8].text;
        var lng = x[0].childNodes[j].childNodes[9].text;
        var phone = x[0].childNodes[j].childNodes[10].text;
        var image = x[0].childNodes[j].childNodes[11].text;
        var displayId = x[0].childNodes[j].childNodes[12].text;
        var distanceFromTarget = x[0].childNodes[j].childNodes[13].text;
        var seoLink = x[0].childNodes[j].childNodes[14].text;
        var moreInfoLink = 'onclick="showListing( \'' + dcGuid + '\' ); return false;"';
        //var moreInfoLink = 'onclick="showListing( \'' + dcGuid + '\',\'' + name + '\' ); return false;"';
        var fullAddress = "";

        if (displayId == 3) {
            fullAddress = '<b>' + street + '</b><br /><a ' + moreInfoLink + ' class="moreInfoLnk">more info</a>';
        }
        else {
            fullAddress = '<b>' + street + '</b><br />' + description + '<br /><a ' + moreInfoLink + ' class="moreInfoLnk">more info</a>';
        }

        var index = j;
        var counter = j + 1;

        // plot the point
        plotPoint(lat, lng, name, fullAddress, dcId, counter, displayId);
    }

function extractFromXMLandPlot2( dcXml, dcCount )
{
    // extract values
    var dcId = $(dcXml).find("id").text();
    var dcGuid = $(dcXml).find("guid").text();
    var name = $(dcXml).find("name").text();
    var description = $(dcXml).find("description").text();
    var street = $(dcXml).find("street").text();
    var city = $(dcXml).find("city").text();
    var prov = $(dcXml).find("prov").text();
    var zip = $(dcXml).find("zip").text();
    var lat = $(dcXml).find("lat").text();
    var lng = $(dcXml).find("lng").text();
    var phone = $(dcXml).find("phone").text();
    var image = $(dcXml).find("image").text();
    var displayId = $(dcXml).find("displayid").text();
    var distanceFromTarget = $(dcXml).find("distancefromtarget").text();
    var seoLink = $(dcXml).find("seolink").text();
    var moreInfoLink = 'onclick="showListing( \'' + dcGuid + '\' ); return false;"';
    var fullAddress = "";
    
    if( displayId == 3 )
    {
        fullAddress = '<b>' + street + '</b><br /><a ' + moreInfoLink + ' class="moreInfoLnk">more info</a>';
    }
    else
    {
        fullAddress = '<b>' + street + '</b><br />' +  description + '<br /><a ' + moreInfoLink + ' class="moreInfoLnk">more info</a>';
    }

    var index = dcCount;
    var counter = dcCount + 1;
        
    // plot the point
    plotPoint( lat, lng, name, fullAddress, dcId, counter, displayId );
}

function buildOnMouseOverListingEvent( msPinId, counter, dcId )
{
    var onMouseOverEvent = " onmouseover=\"changePinStyle( '" + msPinId + "', 'hoverOverPin', '" + counter + "', '" + dcId + "', 'pinText' ); recordHoverStat( '" + dcId + "' );\"; ";
    return onMouseOverEvent;
}

function buildOnMouseOutListingEvent( msPinId, counter, dcId )
{
    var onMouseOutEvent = " onmouseout=\"changePinStyleOut( '" + msPinId + "', 'pin', '" + counter + "', '" + dcId + "', 'pinText' )\";";
    return onMouseOutEvent;
}

function buildOnMouseOverListingEvent2( msPinId, counter, dcId )
{
    var onMouseOverEvent = " onmouseover=\"changePinStyle( '" + msPinId + "', 'hoverOverPin2', '" + counter + "', '" + dcId + "', 'pinText2' ); recordHoverStat( '" + dcId + "' );\"; ";
    return onMouseOverEvent;
}

function buildOnMouseOutListingEvent2( msPinId, counter, dcId )
{
    var onMouseOutEvent = " onmouseout=\"changePinStyleOut( '" + msPinId + "', 'pin2', '" + counter + "', '" + dcId + "', 'pinText2' )\";";
    return onMouseOutEvent;
}

function buildOnClickListingEvent( lat, lng )
{
    var onMouseClickEvent = " onclick=\"centerMap(" + lat + ", " + lng + ")\";";
    return onMouseClickEvent;
}

function addListing( lat, lng, strTitle, strDescription, dcId, counter, msPinId, displayId )
{
    var onMouseClickEvent = buildOnClickListingEvent( lat, lng );
    var onMouseOverEvent = buildOnMouseOverListingEvent( msPinId, counter, dcId );
    var onMouseOutEvent = buildOnMouseOutListingEvent( msPinId, counter, dcId );
    
    var onMouseOverEvent2 = buildOnMouseOverListingEvent2( msPinId, counter, dcId );
    var onMouseOutEvent2 = buildOnMouseOutListingEvent2( msPinId, counter, dcId );
    var description = strDescription;
    
    // display text
    if( displayId == 3 )
    {
        pinWithStyle = '<div id=\"pin' + dcId + '\" class=\"pin2\"' + onMouseOverEvent2 + onMouseOutEvent2 + onMouseClickEvent + '><div class=\"pinText2\">' + counter + '</div>';
    }
    else
    {
        pinWithStyle = '<div id=\"pin' + dcId + '\" class=\"pin\"' + onMouseOverEvent + onMouseOutEvent + onMouseClickEvent + '><div class=\"pinText\">' + counter + '</div>';
    }

    var oneListing = '<table width=\"240px\" cellpadding=\"5\" border=\"0\" cellspacing=\"0\">';
    oneListing += '<tr>';
    oneListing += '<td rowspan=\"2\" valign=\"top\" width=\"40px\">';
    oneListing += '<div ID=' + counter + '>';
    oneListing += pinWithStyle; // <div id=\"listing' + dcId + '\" class=\"pin\"' + onMouseOverEvent + onMouseOutEvent + onMouseClickEvent + '><div class=\"pinText\">' + counter + '</div>';
    oneListing += '</div>'
    oneListing += '</td>';
    oneListing += '<td class=\"listingTitle\">' + strTitle + '</td>';
    oneListing += '<tr><td class=\"listingDescription\">' + description + '<hr /></td></tr>';
    oneListing += '</table>';
    
    if( displayId == 3 )
    {
        listings2 += oneListing;
    }
    else
    {
        listings += oneListing;
    }
    waitStatus = "Hover your mouse over the map points to get more information.";
    setListingsToDiv();    
}

function setListingsToDiv()
{
    document.getElementById('listResults').innerHTML = listings;
    document.getElementById('listResults2').innerHTML = listings2;
    document.getElementById('waitStatusText').innerHTML = waitStatus;
}

function addDcLayer()
{
    dcLayer = new VEShapeLayer();
    dcLayer.SetTitle( "Daycare Layer" );
    dcLayer.SetDescription( "All child care facilities are plotted on this layer." );
    map.AddShapeLayer( dcLayer );
}

function plotPoint( lat, lng, strTitle, strDescription, dcId, counter, displayId )
{
    if( dcLayer == null )
    {
        addDcLayer();
    }
    
    //var layer = restaurantLayer;
    var i = counter;
    var shape = null;
    var pin = null;
    var description = strDescription;
    var pinWithStyle = "";
    
    // display text
    if( displayId == 3 )
    {
        pinWithStyle = '<div id=\"pin' + dcId + '\" class=\"pin2\" onmouseover=\"recordHoverStat( ' + dcId + ' );\"><div class=\"pinText2\">' + i + '</div>';
    }
    else
    {
        pinWithStyle = '<div id=\"pin' + dcId + '\" class=\"pin\" onmouseover=\"recordHoverStat( ' + dcId + ' );\"><div class=\"pinText\">' + i + '</div>';
    }
    
    var customIconHTML = '<div ID=' + counter + '>' + pinWithStyle + '</div>';  // '<DIV ID=' + counter + '><div id=\"pin' + dcId + '\" class=\"pin\"><div class=\"pinText\">' + counter + '</div></div>';
    
    try
    {
        var point = new VELatLong( Number( lat ), Number( lng ) );    // must be numeric
    	pin = new VEShape(VEShapeType.Pushpin, point);
	    pin.SetTitle(strTitle);
	    pin.SetDescription( description );
	    pin.SetCustomIcon( customIconHTML );
	    dcLayer.AddShape( pin );
	    
	    // SHAPE METHOD HERE
	    
	    
	    // plot point now that we have the pin ID
	    var msPinId = pin.GetID();
	    addListing( lat, lng, strTitle, description, dcId, counter, msPinId, displayId );
    }
    catch( e )
    {
        alert( e.message );
    }
}

function centerMap( lat, lng )
{
    var point = new VELatLong( Number( lat ), Number( lng ) );
    map.PanToLatLong( point );
}

//-------------------------------------------------------------------------------------
// MS MAP Find DC
//-------------------------------------------------------------------------------------
function doFind()
{
    var where = null;
    var what = "daycare";
   // map.Find(what, where, null, null, null, 20, false, false, false, false, ProcessResults);
}

function ProcessResults( layer, findResults, places, hasMore, veErrorMessage )
{
  if( null != findResults )
  {
    var dcName = "";
    var dcAddress = "";
    var dcPhone = "";
    var dcLatLng = null;
    var dcLat = "";
    var dcLng = "";
    var dcPaidAd = false;
    
    var numresults = findResults.length;
    for ( r=0; r<numresults; r++ )
    {
         if( findResults[ r ].Name!=null )
         {
            dcName = findResults[ r ].Name;
            dcAddress = findResults[ r ].Description;
            dcPhone = findResults[ r ].Phone;
            dcLatLng = findResults[ r ].LatLong;
            dcLat = dcLatLng.Latitude;
            dcLng = dcLatLng.Longitude;
            dcPaidAd = findResults[ r ].IsSponsored;
            
            //  alert( dcName + '\n' + dcAddress + '\n' + dcPhone + '\n' + dcLat + '\n' + dcLng + '\n' + dcPaidAd );
            wsChildCare.AddDC( dcName, dcAddress, dcPhone, dcLat, dcLng, dcPaidAd );
         }
    }
  }
}



//-------------------------------------------------------------------------------------
// TELERIK RadWindow Code here
//-------------------------------------------------------------------------------------
function handleShowWindowClick( dcGUID )
{
    var manager = GetRadWindowManager();
    var window1 = manager.GetWindowByName("RadWindow1");
    window1.SetUrl( "listing.aspx?id=" + dcGUID );
    //window1.SetTitle( dcName );    
    window1.Show();
}

function showListing( dcGUID )
{
    handleShowWindowClick( dcGUID );
}


//  -----------------------------------------------------------------
//  IP Address
//  -----------------------------------------------------------------
var loc = null;

function SetAutoLocateViewport(latitude, longitude, lvl, bl, msg)
{
    loc = new VELatLong(latitude, longitude);
}

function FindMe()
{
    // remove events so they don't fire when relocating
    detachEvents();

    // clear points on base map
    clearPointsOnBaseLayer();
    
    if( loc )
    {
        if( map )
        {
            //Add a pushpin to the first place
            var shape = new VEShape(VEShapeType.Pushpin, loc);
            shape.SetCustomIcon( "Images/MapIcons/spacerGif.gif" );
            shape.SetTitle( "Area near you" );
            map.AddShape(shape);
                        
            map.SetCenterAndZoom( loc, 11 );
        }
    }

    // attach or re-attache map events
    attachEvents();    
    getSearchResultsForCurrentMap();
}
