if (typeof onepica == "undefined" || !onepica) {
    var onepica = {};
}

onepica.Partners = Class.create({
    /**
    * Constructor.
    *
    * @param string type map|list
    * @param string url
    */
    initialize: function(type, url, hiddenId) {
        this.type = type;
        this.url = url;
        this.hiddenId = hiddenId;


        this.dataUrl = url + "/Custom/Modules/Partners/Frontend/MapData.aspx";
        this.address = null;
        this.icon = null;
        this.mapMarkers = [];
        this.markerLis = null;
        this.infoWindowParams = { maxWidth: 200 };
        this.defaultZoom = 8;

        if (this.type == 'map' && GBrowserIsCompatible()) {
            // this.form = $('partners-form');
            this.loadingScreen = $('gmap-loading');
            this.markerContainer = $('partners-list');
            this.goButton = $('partners-go');
            this.goButton.observe('click', this._goEvent.bindAsEventListener(this));
            this.addressField = $('address');
            this.addressField.observe('keypress', this._addressFieldEvent.bindAsEventListener(this));
            this.mapEl = $('gmap');
            this.map = new GMap2(this.mapEl);
            this.map.addControl(new GLargeMapControl());
            this.map.enableScrollWheelZoom();  // this submits the ajax request too frequently
            this.setMapCenter(38.2, -95, 3);  // Center of the US
            this.mapManager = new MarkerManager(this.map);
            this.geocoder = new GClientGeocoder();
          //  GEvent.addListener(this.map, 'dragend', this._submitForm.bindAsEventListener(this));
          //  GEvent.addListener(this.map, 'zoomend', this._submitForm.bindAsEventListener(this));

            Event.observe(window, 'unload', GUnload);  // Helps IE avoid memory leaks
        }

        this.transportNav = $('transportation-method');
        this.transportMethods = this.transportNav.select('input.method');
        this.transportClickTargets = this.transportNav.select('div.click-target');

        for (var i = 0; i < this.transportMethods.length; i++) {
            this.transportMethods[i].observe('click', this._toggleTransportMethod.bindAsEventListener(this));
            this.transportClickTargets[i].observe('click', this._toggleTransportMethod.bindAsEventListener(this));
        }
    },

    /**
    * Positions the center of the map.
    *
    * @param int latitude
    * @param int longitude
    * @param int zoom 1-19.  1: continent, 19: street
    */
    setMapCenter: function(latitude, longitude, zoom) {
        if (!zoom) {
            var zoom = this.defaultZoom;
        }
        this.map.setCenter(new GLatLng(latitude, longitude), zoom);
    },

    /**
    * Adds a marker at the coordinates passed.
    *
    * @param string markerId
    * @param int latitude
    * @param int longitude
    * @param string type public-transit|parking|van-pooling|bicycling
    * @param string title
    * @param string html
    */
    addMapMarker: function(markerId, latitude, longitude, type, title, html) {
        var point = new GLatLng(latitude, longitude);
        var marker = new GMarker(point, this._getIcon());

        if (type && html) {

            html = this._getImageByType(type) + html;
            marker.opId = markerId;
            marker.opHtml = html;
            marker.opTitle = title;
            marker.bindInfoWindowHtml(html, this.infoWindowParams);  // adds marker click event to open info window
        }
        this.mapMarkers.push(marker);
    },

    /**
    * Adds the markers in the passed array to the map manager.  Each element in the array
    * should contain a hash with the function params for this.addMapMarker or an array.
    *
    * @param array markers
    */
    addMapMarkers: function(markers) {
        var str = "";

        for (var i = 0; i < markers.length; i++) {
            if (i == 0) str = str + markers[i][6];
            else str = str + "!" + markers[i][6];

            if (markers[i].markerId) {  // hash
                this.addMapMarker(markers[i].markerId, markers[i].latitude, markers[i].longitude, markers[i].type, markers[i].title, markers[i].html);
            }
            else {  // array
                this.addMapMarker(markers[i][0], markers[i][1], markers[i][2], markers[i][3], markers[i][4], markers[i][5]);
            }
        }

        if (str) {
            var hiddenField = $(this.hiddenId);
            if (hiddenField) {
                hiddenField.value = str;
                __doPostBack(this.hiddenId, '');
            }
        }
    },

    /**
    * Adds the markers added via this.addMapMarkers to the Map Manager and creates li's
    * which are added to the map list ul container.
    */
    renderMapMarkers: function() {
        for (var i = 0; i < this.mapMarkers.length; i++) {
            var li = $(document.createElement('li'));
            li.innerHTML = this.mapMarkers[i].opTitle;
            li.setAttribute('marker', this.mapMarkers[i].opId);
            this.markerContainer.appendChild(li);
            li.observe('click', this._mapLiClickEvent.bindAsEventListener(this));
        }
        this.mapManager.addMarkers(this.mapMarkers, 1);  // add markers to the map manager
        this.mapManager.refresh();
    },

    /**
    * Geocodes the address
    *
    * @param string address
    */
    geocode: function(address) {
        if (this.addressField.value) {
            this.geocoder.getLatLng(address, this._geocodeCallback.bindAsEventListener(this));
        }
    },

    _geocodeCallback: function(point) {
        if (!point) {
            alert(this.addressField.value + " not found.");
        }
        else {
            this.map.setCenter(point, this.defaultZoom);
            this._submitForm(point);
        }
    },

    _submitForm: function(point) {
        if (this.type != 'map') {
            return;
        }

        // remove markers, clear ul list
        this.mapManager.clearMarkers();
        this.mapMarkers = [];
        this.markerContainer.descendants().each(function(el) {
            el.stopObserving();  // remove event listeners
            el.remove();
        });

        if (point) {
            if (point.x) {
                var path = this._buildUrl(point);

                new Ajax.Request(path, {
                    method: 'get',
                    onSuccess: this._submitFormSuccess.bindAsEventListener(this),
                    onFailure: this._submitFormFailure.bindAsEventListener(this)
                });
            }
        }
    },

    _submitFormSuccess: function(transport) {
        this.loadingScreen.hide();
        var respArray = eval("(" + transport.responseText + ")");  // JSON response

        if (respArray.length) {
            // add new markers and render
            this.addMapMarkers(respArray);
            this.renderMapMarkers();
        }
    },

    _buildUrl: function(point) {
        var path = this.dataUrl;

        var radius = $('selRadius')
        path = path + "?lat=" + point.y + "&lon=" + point.x + "&miles=" + radius.value;

        var transit = $('public-transit');
        if (transit.checked == true) path = path + "&transit=true";

        var parking = $('parking');
        if (parking.checked == true) path = path + "&parking=true";

        var vanpooling = $('van-pooling');
        if (vanpooling.checked == true) path = path + "&vanpooling=true";

        var carsharing = $('car-sharing');
        if (carsharing.checked == true) path = path + "&carsharing=true";

        var tma = $('tma');
        if (tma.checked == true) path = path + "&tma=true";

        var bikeshop = $('bikeshop');
        if (bikeshop.checked == true) path = path + "&bikeshop=true";

        var bikerack = $('bikerack');
        if (bikerack.checked == true) path = path + "&bikerack=true";

        var bikeclub = $('bikeclub');
        if (bikeclub.checked == true) path = path + "&bikeclub=true";

        return path;
    },

    _submitFormFailure: function(transport) {
        this.loadingScreen.hide();
    },

    _addHiddenFormField: function(name, value) {
        var field;
        if (field = $(name)) {
            field.name = name;
            field.value = value;
        }
        else {
            field = document.createElement('input');
            field.type = 'hidden';
            field.id = name;
            field.name = name;
            field.value = value;
            //     this.form.appendChild(field);
        }
    },

    _goEvent: function(event) {
        this.geocode(this.addressField.value);
    },

    _addressFieldEvent: function(event) {
        if (event.keyCode == Event.KEY_RETURN) {
            this._goEvent(null);
        }
    },

    _getImageByType: function(type) {
        var lowerType = type.toLowerCase();

        if (lowerType.indexOf("transit") != -1)
            var src = this.url + '/images/icons/map_icon_public-transit.gif';
        else if (lowerType.indexOf("parking") != -1)
            var src = this.url + '/images/icons/map_icon_parking.gif';
        else if (lowerType.indexOf("van") != -1)
            var src = this.url + '/images/icons/map_icon_van-pooling.gif';
        else if (lowerType.indexOf("tma") != -1)
            var src = this.url + '/images/icons/map_icon_tma.gif';
        else if (lowerType.indexOf("sharing") != -1)
            var src = this.url + '/images/icons/map_icon_car-sharing.gif';   
        else
            var src = this.url + '/images/icons/map_icon_bicycling.gif';

        return '<img class="info-window-image" src="' + src + '" alt="" />';
    },

    _mapLiClickEvent: function(event) {
        var marker = this._getMarkerById(event.element().getAttribute('marker'));
        if (marker) {
            this.map.panTo(marker.getLatLng());
            if (marker.opHtml) {
                this.map.openInfoWindowHtml(marker.getLatLng(), marker.opHtml, this.infoWindowParams);
                //marker.openInfoWindowHtml(marker.opHtml, this.infoWindowParams);  // this throws an error i can't figure out
            }
        }
    },

    _getMarkerById: function(id) {
        for (var i = 0; i < this.mapMarkers.length; i++) {
            if (this.mapMarkers[i].opId == id) {
                return this.mapMarkers[i];
            }
        }
        return null;
    },

    _getIcon: function() {
        if (!this.icon) {
            this.icon = new GIcon();
            this.icon.image = this.url + "/images/icons/map_point.png";
            this.icon.iconSize = new GSize(15, 15);
            this.icon.iconAnchor = new GPoint(15, 15);
            this.icon.infoWindowAnchor = new GPoint(5, 1);
        }
        return this.icon;
    },

    _toggleTransportMethod: function(event) {
        var el;
        if (event.element().tagName.toLowerCase() != 'input') {  // in case the icon is clicked
            el = event.element().adjacent('input');
            el = el[0];
            if (el.checked) {
                el.checked = false;
            }
            else {
                el.checked = true;
            }
        }
        else {
            el = event.element();
        }
        if (el.checked) {
            $(el.parentNode).addClassName('active');
            $(el.parentNode).addClassName(el.id + '-active');
        }
        else {
            $(el.parentNode).removeClassName('active');
            $(el.parentNode).removeClassName(el.id + '-active');
        }
        this._submitForm();
    }
});

onepica.PartnerList = Class.create({
    initialize: function(url, hiddenId, stateSelectorId) {
        this.url = url;
        this.dataUrl = url + "/Custom/Modules/Partners/Frontend/ListData.aspx";
        this.hiddenId = hiddenId;
        this.goButton = $('btnGo');
        this.goButton.observe('click', this._goEvent.bindAsEventListener(this));
        this.stateSelector = $(stateSelectorId);
        this.radiusSelector = $('selRadius');
        this.zip = $('tbZip');
        this.geocoder = new GClientGeocoder();

        Event.observe(window, 'unload', GUnload);

        this.transportNav = $('transportation-method');
        this.transportMethods = this.transportNav.select('input.method');
       // this.transportSubMethods = this.transportNav.select('input.sub-method');
        this.transportClickTargets = this.transportNav.select('div.click-target');

        for (var i = 0; i < this.transportMethods.length; i++) {
            this.transportMethods[i].observe('click', this._toggleTransportMethod.bindAsEventListener(this));
            this.transportClickTargets[i].observe('click', this._toggleTransportMethod.bindAsEventListener(this));
        }
       // for (var i = 0; i < this.transportSubMethods.length; i++) {
       //     this.transportSubMethods[i].observe('click', this._submitForm.bindAsEventListener(this));
       // }
    },

    _goEvent: function(event) {
        if (this.zip.value)
            this.geocode(this.zip.value);
        else {
            var url = this._buildUrl(this.stateSelector.value, null, null, null);
            this._submitForm(url);
        }
    },

    _buildUrl: function(state, lat, lon, miles) {
        var path = this.dataUrl;

        if (state)
            path = path + "?state=" + state;
        else
            path = path + "?lat=" + lat + "&lon=" + lon + "&miles=" + miles;

        var transit = $('public-transit');
        if (transit.checked == true) path = path + "&transit=true";

        var parking = $('parking');
        if (parking.checked == true) path = path + "&parking=true";

        var vanpooling = $('van-pooling');
        if (vanpooling.checked == true) path = path + "&vanpooling=true";

        var carsharing = $('car-sharing');
        if (carsharing.checked == true) path = path + "&carsharing=true";

        var tma = $('tma');
        if (tma.checked == true) path = path + "&tma=true";

        var bikeshop = $('bikeshop');
        if (bikeshop.checked == true) path = path + "&bikeshop=true";

        var bikerack = $('bikerack');
        if (bikerack.checked == true) path = path + "&bikerack=true";

        var bikeclub = $('bikeclub');
        if (bikeclub.checked == true) path = path + "&bikeclub=true";

        return path;
    },


    geocode: function(address) {
        if (this.zip.value) {
            this.geocoder.getLatLng(address, this._geocodeCallback.bindAsEventListener(this));
        }
    },

    _geocodeCallback: function(point) {
        if (!point) {
            alert("zip not found.");
        }
        else {
            var url = this._buildUrl(null, point.y, point.x, this.radiusSelector.value);
            this._submitForm(url);
        }
    },

    _submitForm: function(url) {
        new Ajax.Request(url, {
            method: 'get',
            onSuccess: this._submitFormSuccess.bindAsEventListener(this),
            onFailure: this._submitFormFailure.bindAsEventListener(this)
        });
    },

    _submitFormSuccess: function(transport) {

        if (transport.responseText) {

            var split = transport.responseText.split('|');
            var tree = $('xtree');
            tree.innerHTML = split[0];
            var optree = new onepica.Tree("xtree");

            var hiddenField = $(this.hiddenId);
            if (hiddenField) {
                hiddenField.value = split[1];
                __doPostBack(this.hiddenId, '');
            }

            $('results').removeClassName('hide');
            $('noresults').addClassName('hide');
        }
        else {
            $('results').addClassName('hide');
            $('noresults').removeClassName('hide');
        }
    },

    _submitFormFailure: function(transport) {
        // this.loadingScreen.hide();
    },

    _toggleTransportMethod: function(event) {
        var el;
        if (event.element().tagName.toLowerCase() != 'input') {  // in case the icon is clicked
            el = event.element().adjacent('input');
            el = el[0];
            if (el.checked) {
                el.checked = false;
            }
            else {
                el.checked = true;
            }
        }
        else {
            el = event.element();
        }
        if (el.checked) {
            $(el.parentNode).addClassName('active');
            $(el.parentNode).addClassName(el.id + '-active');
        }
        else {
            $(el.parentNode).removeClassName('active');
            $(el.parentNode).removeClassName(el.id + '-active');
        }
        // this._submitForm();
    }

});



