var BA = function()
{

    var full_address = null, icon = null, polylines = [], icon2 = null, bounds = null, centerPoint = null, map = null, northEast = null, radius = null, southWest = null, directions = null, geocoder = null, $load = $("#loader"), $feedback = $("#feedback");
    
    function processLocations(json)
    {
        if (json.length <= 0) {
            setDefaultMap();
            showFeedback("Your search yielded no results.  Please try again.");
        } else {
            createMarkers(json);
        }
        
    }
    
    function createMarkers(json)
    {
    
        for (var i = 0; i < json.length; i++) {
            var latitude = parseFloat(json[i].latitude);
            var longitude = parseFloat(json[i].longitude);
            
            if (BA.sType == 'parish') {
                setCenter(latitude, longitude);
            }
            
            var coords = new GLatLng(latitude, longitude);
            
            var marker = new GMarker(coords, {
                title: "Click to view information on " + json[i].name + ' - ' + json[i].city + ', ' + json[i].state,
                icon: icon
            });
            
            var daddr = "http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=" + BA.sZip + '&daddr=' + json[i].street_address + ',+' + json[i].city + ',+' + json[i].state + '+' + json[i].zip;
            var dir = '<a href="' + daddr + '" target="_blank">Get Directions</a>';
            var addressText = getAddressText(json[i].name, json[i].street_address, json[i].mailing_address, json[i].city, json[i].state, json[i].zip, dir);
            var contactText = getContactText(json[i].name, json[i].phone, json[i].website);
                        
            var infoTabs = [ 
                new GInfoWindowTab("Contact", addressText + '<br /><br />' + contactText)
            ];
            
            var informationText = "<h6>" + json[i].name + "</h6>";
            
            if (json[i].service_times != '') {
                informationText += "<br /><strong>Services</strong><br />" + json[i].service_times;
            }
            
            if (json[i].special_instructions != '') {
                informationText += "<br /><br /><strong>Special Instructions</strong><br />" + json[i].special_instructions;
            }
            
            //commented out per request from client
            //when reactivated, be sure to modify schools index to 2 (see line 63)
            if (json[i].service_times != '' || json[i].special_instructions != '') {
                infoTabs[1] = new GInfoWindowTab("Schedules", informationText);
            }
            
            if (json[i].schools != '') {
                var schools = "<h6>Schools</h6>";
                schools += json[i].schools;
                infoTabs[2] = new GInfoWindowTab("School", schools);
            }
            
            addGEventListener(marker, coords, infoTabs);
            map.addOverlay(marker);
            
            //if it appears as though a search is being performed for a single church, display the associated infoTabs   
            if (json.length == 1) {
                marker.openInfoWindowTabsHtml(infoTabs);
            }
        }
        
        showFeedback("Your request has been processed.  Just click on a parish icon to view information about a parish.");
    }
    
    function addGEventListener(marker, coords, infoTabs)
    {
        GEvent.addListener(marker, "click", function()
        {
            //ensure that we remove previously set polylines
            $.each(polylines, function()
            {
                map.removeOverlay(this);
                polylines.pop();
            });
            
            var polyline = new GPolyline([centerPoint, coords], "#FE766A", 4);
            
            map.addOverlay(polyline);
            polylines.push(polyline);
            
            marker.openInfoWindowTabsHtml(infoTabs);
        });
    }
    
    function getContactText(name, phone, url)
    {
        if (url !== "") {
            url = 'Website: <a href="' + url + '" target="_blank">' + url + '</a>';
        }
        return "Phone: " + phone + "<br />" + url;
    }
    
    function getAddressText(name, street_address, mailing_address, city, state, zip, dir)
    {
        var addressText = "<h6>" + name + "</h6>";
        
        if (mailing_address == '' || (mailing_address == street_address)) {
            addressText += street_address + "<br />";
        } else {
            addressText += "<strong>Street Address: </strong><br />" + street_address + "<br />" + "<strong>Mailing Address: </strong><br />" + mailing_address + "<br />";
        }
        
        return addressText + city + ", " + state + " " + zip + "<br />" + dir;
    }
    
    function setDefaultMap()
    {
        //center map at a zoom level of 6 centered on Arlington
        map.setCenter(new GLatLng(BA.defaultCenterLat, BA.defaultCenterLong), BA.defaultRadius);
    }
    
    function setCenter(lat, lng)
    {
        centerPoint = new GLatLng(lat, lng);
        map.setCenter(centerPoint, BA.sRadius);
    }
    
    function createCenterMarker(info)
    {
        var marker = new GMarker(centerPoint, {
            title: info,
            icon: icon2
        });
        
        GEvent.addListener(marker, "click", function()
        {
            marker.openInfoWindowHtml(info);
        });
        
        return marker;
    }
    
    function showFeedback(value)
    {
        $load.slideUp("slow", function()
        {
            $feedback.text(value);
            $feedback.slideDown("slow");
        });
    }
    
    return {
        sLat: 0.0,
        sLng: 0.0,
        defaultCenterLat: 38.892636,
        defaultCenterLong: -77.085571,
        defaultRadius: 13,
        sRadius: 15,
        sZip: "",
        sAddress: "",
        sDirectionsPanel: 1,
        sType: '', //type will either be zip or address
        loadmap: function()
        {
        
            var stamp = new Date();
            stamp = stamp.getTime();
            
            icon = new GIcon();
            icon.image = "/assets/images/cda_marker.png";
            icon.shadow = "/assets/images/cda_marker_shadow.png";
            icon.iconSize = new GSize(20, 35);
            icon.shadowSize = new GSize(39, 39);
            icon.iconAnchor = new GPoint(2, 39);
            icon.infoWindowAnchor = new GPoint(10, 1);
            
            icon2 = new GIcon();
            icon2.image = "/assets/images/mm_20_red.png";
            icon2.shadow = "/assets/images/mm_20_shadow.png";
            icon2.iconSize = new GSize(12, 20);
            icon2.shadowSize = new GSize(22, 20);
            icon2.iconAnchor = new GPoint(6, 20);
            icon2.infoWindowAnchor = new GPoint(5, 1);
            
            map = new GMap2(document.getElementById("map"));
            map.addControl(new GLargeMapControl());
            map.addControl(new GOverviewMapControl());
            map.addControl(new GMapTypeControl());
            
            if (BA.sType == 'zip' && BA.sZip != '') {
                $load.show();
                
                var retrieve = '/parishes/getGeoData.php?location=' + BA.sZip;
                if(BA.is_dev()) {
                    retrieve = '/parish_locator/parishes/getGeoData.php?location=' + BA.sZip;
                }
                
                $.getJSON(retrieve, function(json)
                {
                
                    var code = json[0];
                    
                    if (code == '200') {
                        BA.sLat = json[2];
                        BA.sLng = json[3];
                        
                        //pan out in order to see more map area in relation to the search
                        BA.sRadius = 11;
                        
                        setCenter(BA.sLat, BA.sLng);
                        
                        var markerText = "Search From: " + BA.sZip;
                        var marker = createCenterMarker(markerText);
                        map.addOverlay(marker);
                        marker.openInfoWindowHtml(markerText);
                        
                        
                        retrieve = '/parishes/parishes.php';
                        if(BA.is_dev()) {
                            retrieve = '/parish_locator/parishes/parishes.php';
                        }
                        $.getJSON(retrieve, processLocations);
                    } else {
                        setDefaultMap();
                        showFeedback("Unable to process your request.  Please try again.");
                    }
                    
                });
            } else {
                if (BA.sType == 'parish') {
                    $load.show();
                    var retrieve = '/parishes/parish.php?id=' + BA.sAddress;
                    if(BA.is_dev()) {
                        retrieve = '/parish_locator/parishes/parish.php?id=' + BA.sAddress;
                    }
                    $.getJSON(retrieve, processLocations);
                } else {
                    setDefaultMap();
                }
            }
            
            //setup the query string to add to the screen toggler
            var queryString = document.location.search || null;
            if (queryString) {
                var r = $('#screentype a').attr('href').match(/index\.php/g) || [];
                $('#screentype a').attr('href', r.length > 0 ? 'index.php' + queryString : 'index_full.php' + queryString);
            }
            
        },
        
        is_dev : function()
        {
            return location.href.indexOf("local")!=-1;
        }
    };
}();

