﻿var bObj;                             //First JSON object for zip search
var bObjDetails;                      //Second JSON object for details
var intCount = 1;                     //Variable checked to open Google Maps info window on first marker only
var intCounter = 0;                   //Counter that numbers the markers
var ResultList = new Array();         //Array that contains all the Location-ID's for the zip search results
var MapLatitude = new Array();        //Array with the Lats for all of the results
var MapLongitude = new Array();       //Array with the Longs for all of the results
var map = null;                       //The map object
var intStartIndex = 0;                //The index of ResultList, where to start depending on page number
var intEndIndex = 0;                  //The index of ResultList, where to end depending on page number

$(document).ready(function ()
{
    //If JS then hide the warning and show the map and search
    $('.WithoutJS').hide();
    $('.RecycleSearch').show();
 
    //Invoke the Map Call
    this.invoke = JSONCall();
});

function JSONCall()
{
    //If the search box is empty show the map with ERI's locations on it - CALLED FOR EVERY SEARCH CLICK OR PAGE LOAD
    if ($('.txtSearch').val() == '')
    {
        if (GBrowserIsCompatible()) 
        {
            //Initialize map and center it
            map = new GMap2(document.getElementById("Map"));
            map.setCenter(new GLatLng(36.7, -119.77), 12);  
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            
            //Coords and info for ERI - Fresno
            var point = new GLatLng(36.7, -119.77);        
            var marker = createMarker(point, 'Electronic Recyclers, Inc.', '2860 S. East Ave. Fresno, CA 93725', '1.800.884.8466');
            map.addOverlay(marker);
            
            //Coords and info for ERI - Boston
            point = new GLatLng(42.56, -72.00);  
            var marker = createMarker(point, 'Electronic Recyclers, Inc.', '461 West Broadway Gardner, MA 01440', '1.800.884.8466');
            map.addOverlay(marker);

            //Center map and zoom out to see both
            map.setCenter(new GLatLng(39, -95), 3);
        }    
    }
    else
    {
        //Something has been searched, reinitialize the map
        if (GBrowserIsCompatible()) 
        {
            map = new GMap2(document.getElementById("Map"));
            map.setCenter(new GLatLng(36.7, -119.77), 8);  
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
        }
        
        //The Earth911 JSON API Call with the zip code
        var req  = 'http://api.globalalerts.com/json/earth911-find-service-locations-by-zip?api-key=54f7621e5d9db8f0&zip=' + 
            $('.txtSearch').val() + '&service-id=125&callback=GetJSONPacket';
        bObj = new JSONscriptRequest(req);
        bObj.buildScriptTag();
        bObj.addScriptTag();
    }
}

function GetJSONPacket(jsonData) 
{      
    //Callback function of the JSON Zip Call - THIS IS ONLY CALLED ON ZIP SEARCH NOT ON PAGE CHANGE
    var location = "location-id";
    var LoopCount = 0;
    
    //Get all of the results and fill the corresponding arrays
    for (var i in jsonData.result)
    {
        ResultList[LoopCount] = jsonData.result[i][location];
        MapLatitude[LoopCount] = jsonData.result[i].latitude;
        MapLongitude[LoopCount] = jsonData.result[i].longitude;
        LoopCount = LoopCount + 1;
    }
    
    //Setup the pager
    Pager(ResultList.length);
    
    //Setup the display results call 
    intStartIndex = 0;
    if (ResultList.length < 5)
    {
        intEndIndex = ResultList.length;
    }
    else
    {
        intEndIndex = 4;
    }
    
    //Print the first 5 results
    GetFiveResults();
    bObj.removeScriptTag();
}

function GetFiveResults()
{    
    //Get the results from the JSON Details call - THIS IS CALLED ONCE WHEN NEW RESULTS ARE NEEDED
    var i = intStartIndex;            //Set Counter for loops to equal the start index
    var details = 'http://api.globalalerts.com/json/earth911-find-location-details?api-key=54f7621e5d9db8f0'; 

    //Setup the location details call then execute
    while (i <= intEndIndex)
    {
        details = details + '&location-id[]=' + ResultList[i];
        i++;
    }
    details = details + '&callback=GetJSONDetails';

    bObjDetails = new JSONscriptRequest(details); 
    bObjDetails.buildScriptTag();
    bObjDetails.addScriptTag();
}

function Pager(intResultCount)
{
    //Setup the page numbers and the click events
    var PageCount = 0;
    var i = 1;
    
    //Checks number of results and sets the page accordingly
    if (intResultCount > 0 && intResultCount <= 4)
    {
        PageCount = 1;
    }
    else
    {
        PageCount = intResultCount / 5;
    }
    
    //Fill the Pager Div with the links
    $('.Pager').html('Results Page: ')
    while (i <= PageCount)
    {
        $('.Pager').html($('.Pager').html() + ' <a href="#" title="View page ' + i + ' of the results" class="' + i + '" />' + i + '</a>');
        i++;
    }
    
    //Reset the counter variable and then bind the click events for each page
    i = 1;
    while (i <= PageCount)
    {
        $('.' + i).click(function() { NextPage($(this).attr('class')); return false; });
        i++;
    }
}

function NextPage(intPageNumber)
{
    //This is called when a page number is clicked
    $(".txtPacket").html('');        //Reset the results list text
    intCount = 1;                    //Reset the first result variable
    intCounter = 0;                  //Reset the marker counter
    
    //Reset the map
    if (GBrowserIsCompatible()) 
    {
        map = new GMap2(document.getElementById("Map"));
        map.setCenter(new GLatLng(41, -92.28815625), 8);  
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
    }
    
    //Setup the results to be displayed then call GetFiveResults to get them
    intStartIndex = intPageNumber * 5 - 5;
    intEndIndex = intPageNumber * 5 - 1;
    GetFiveResults();
}

function GetJSONDetails(jsonData)
{
    //Prints the results in the results list and fills the map - THIS CALLED FOR EVERY PAGE NUMBER CHANGE
    var i = intStartIndex;          //Set loop variable to match the starting index
    var point = null;               //Initialize the map point object to null
    
    //Ran for result from intStartIndecx to intEndIndex
    while (i <= intEndIndex)
    {    
        //Print the search results
        $(".txtPacket").html($(".txtPacket").html() + '<li><div class="Title"><strong>' + jsonData.result[ResultList[i]].name + 
            '</strong></div><div class="Address">' + jsonData.result[ResultList[i]].address + ' ' + jsonData.result[ResultList[i]].city + 
            ',' + jsonData.result[ResultList[i]].state + ' ' + jsonData.result[ResultList[i]].zip + ' ' + jsonData.result[ResultList[i]].phone + 
            '</div></li>');

        //Set the point using the corresponding coordinates
        point = new GLatLng(MapLatitude[i], MapLongitude[i]);
        //Load the map marker
        LoadMap(point, jsonData.result[ResultList[i]].name, jsonData.result[ResultList[i]].address + ' ' + 
            jsonData.result[ResultList[i]].city + ',' + jsonData.result[ResultList[i]].state + ' ' + 
            jsonData.result[ResultList[i]].zip, jsonData.result[ResultList[i]].phone);
        i++;
    }        
}
   
function LoadMap(point, strName, strAddress, strPhone)
{ 
    //Calls the createMarker function and adds it to the map - CALLED FOR EVERY RESULT    
    var marker = createMarker(point, strName, strAddress, strPhone);
    map.addOverlay(marker);
    
    //Only ran for the first(closest) result, shows the info window
    if(intCount == 1)
    {
        intCount = 2;
        marker.openInfoWindowHtml('<strong>' + strName + '</strong><br />' + strAddress + '<br />'+ strPhone + '</div>');        
    }
}  

function createMarker(point, strName, strAddress, strPhone) 
{ 
    //Creates the marker and returns it - CALLED FOR EVERY RESULT
    var baseIcon = new GIcon();
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    baseIcon.infoShadowAnchor = new GPoint(18, 25);

    //Create a numbered icon for this point using our icon class from above
    intCounter = 1 + intCounter;
    var icon = new GIcon(baseIcon);
    icon.image = "images/numberedmarkers/marker"+ intCounter + ".png";
    var marker = new GMarker(point, icon);
    
    //Watch for click to redisplay the information
    GEvent.addListener(marker, "click", function() 
    { 
        //Add information to a marker
        marker.openInfoWindowHtml('<strong>' + strName + '</strong><br />'+ strAddress + '<br />'+ strPhone + '</div>');
    });
    
    return marker;
}


