AMEXGlobal = Class.create({});
Object.extend(AMEXGlobal, {
    APPLICATION_ROOT: '',
    /* */
    APPLICATION_ROOT: '/wheretobuy/',
    /* */
    EMAIL_AJAX: 'email',
    PAGES: {
        LANDING: '',
        RESULTS: 'search.jsp',
        PRINT_RESULTS: 'print_map.jsf',
        PRINT_DIRECTIONS: 'print_directions.jsf',
        EMAIL_AJAX: 'sendemail'
    },
    EMAIL_FORM_ID: 'emailform'
    /*********************************************************************************
     *
     *      DO NOT EDIT BELOW THIS LINE
     *
     *********************************************************************************/
});

AMEXGlobal.addMethods({
    initialize: function() {
        $$('.infoTipLink').invoke('observe', 'click', this.showInfoTip.bind(this));
        $$('.infoTip .close a').invoke('observe', 'click', this.hideInfoTip.bind(this));
        $$('.printResults').invoke('observe', 'click', this.printResults.bind(this));
        $$('.printDirections').invoke('observe', 'click', this.printDirections.bind(this));
        $$('.e-mail').invoke('observe', 'click', this.showEmailForm.bind(this));
        if($('cancelemail')) {
            $('cancelemail').observe('click', this.hideEmailForm.bindAsEventListener(this));
        }
        
        this.sefx = this.sendEmail.bindAsEventListener(this);
    },
    showInfoTip: function(event) {
        event.stop();

        $$('.infoTip').invoke('setStyle', {left: '-999em'});
        
        var link = event.target;
        if(event.target.nodeName.toLowerCase() !== 'a') {
            link = event.target.parentNode;
        }
        // Get the correct tooltip
        var tooltip = $(link.href.split('#')[1]);

        var xPos = link.viewportOffset()[0]+link.offsetWidth+document.viewport.getScrollOffsets()[0];
        var yPos = link.viewportOffset()[1]-Math.floor(tooltip.offsetHeight/2)+document.viewport.getScrollOffsets()[1];
        
        tooltip.setStyle({top: yPos+'px', left: xPos+'px'});    
    },
    hideInfoTip: function(event) {
        event.stop();
        var tooltip = event.target.parentNode.parentNode;
        tooltip.setStyle({left: '-999em'});
    },
    printResults: function(event) {
        event.stop();
        var printPage = event.target.href;
        
        var locations = [];
        var pois = [];
        
        for(var i = 0; i < AMEXMap.instance.model.get('mapLocations').length; i++) {
            var location = AMEXMap.instance.model.get('mapLocations')[i].poi;
            if(location.leaderLine.parent == null) {
                locations.push([location.key, 0, 0]);
            } else {
                var xOffset = location.leaderLine.bbox.r-location.leaderLine.bbox.l;
                var yOffset = location.leaderLine.bbox.t-location.leaderLine.bbox.b;
                if(location.leaderLine.last.x == location.leaderLine.bbox.r) { xOffset = -xOffset; }
                if(location.leaderLine.last.y == location.leaderLine.bbox.t) { yOffset = -yOffset; }
                locations.push([location.key, xOffset, yOffset])
            }
        }
                
        if(locations.length > 0) {
                        
            var printParams = $H({
                'printForm:centerLatitude': AMEXMap.instance.map.getCenter().lat,
                'printForm:centerLongitude': AMEXMap.instance.map.getCenter().lng,
                'printForm:startLatitude': AMEXMap.instance.model.get('response').getMQLatLng().lat,
                'printForm:startLongitude': AMEXMap.instance.model.get('response').getMQLatLng().lng,
                'printForm:radius': AMEXMap.instance.model.get('radius').value,
                'printForm:units': AMEXMap.instance.model.get('radius').units,
                'printForm:zoom': AMEXMap.instance.map.getZoomLevel(),
                'printForm:locations': locations,
                'printForm:pois': pois
            });

            this.printPage = window.open(
                printPage, 
                'printpage', 
                'menubar=yes,location=no,resizable=yes,scrollbars=yes,status=yes'
            );
            document.observe('print:ready', function() {
                this.printPage.$$('input').each(function(input) {
                    if (input.id.match(/printForm/)) {
                        input.value = printParams.get(input.id);
                    }
                });
                this.printPage.$('printForm').action = printPage;
                this.printPage.$('printForm').submit();
                document.stopObserving('print:ready');
            }.bind(this));
            
        } else {
            AMEXMap.instance.messageBox.showMessage(Lang.STRINGS.print_error);
        }
    },
    printDirections: function(event) {
        event.stop();
        var printPage = event.target.href;
                
        if(AMEXMap.instance.wayPoints.getSize() === 2) {
            this.printPage = window.open(
                printPage, 
                'printpage', 
                'menubar=yes,location=no,resizable=yes,scrollbars=yes,status=yes'
            );
   
            var printParams = $H({
                'printForm:startAddress': AMEXMap.instance.startString,
                'printForm:startLatitude': AMEXMap.instance.wayPoints.getAt(0).getMQLatLng().lat,
                'printForm:startLongitude': AMEXMap.instance.wayPoints.getAt(0).getMQLatLng().lng,
                'printForm:endAddress': AMEXMap.instance.endPoint,
                'printForm:endLatitude': AMEXMap.instance.wayPoints.getAt(1).getMQLatLng().lat,
                'printForm:endLongitude': AMEXMap.instance.wayPoints.getAt(1).getMQLatLng().lng,
                'printForm:units': AMEXSearchForm.instance.radiusUnits
            });
            
            document.observe('print:ready', function() {
                this.printPage.$$('input').each(function(input) {
                    if (input.id.match(/printForm/)) {
                        input.value = printParams.get(input.id);
                    }
                });
                this.printPage.$('printForm').action = printPage;
                this.printPage.$('printForm').submit();
                document.stopObserving('print:ready');
            }.bind(this));
        } else {
            alert(Lang.STRINGS.print_error.header+'\n'+Lang.STRINGS.print_error.content);
        }    
    },
    showEmailForm: function(event) {
        event.stop();
        $(AMEXGlobal.EMAIL_FORM_ID).addClassName('show');
        $('opt_radius').setStyle({ visibility: 'hidden' });
        
        $('emailmap').observe('click', this.sefx);
        $('emailform').select('input').invoke('observe', 'keypress', this.sefx);
    },
    sendEmail: function(event) {
        if(event.keyCode == Event.KEY_RETURN || event.keyCode == null || event.target.id == 'emailmap') {
		    event.stop();
		    
		    AMEXMap.instance.messageBox.showLoading();
		    
            var locations = [];
            if (AMEXMap.instance.model.get('mapLocations')) {
                for(var i = 0; i < AMEXMap.instance.model.get('mapLocations').length; i++) {
                    var location = AMEXMap.instance.model.get('mapLocations')[i].poi;
                    locations.push(location.key);
                }
            }

            var startLatitude;
            var startLongitude;
            var endLatitude;
            var endLongitude;
            var endpointId;
            var queryParams;
            if (AMEXMap.instance.model.get('response')) {
                startLatitude = AMEXMap.instance.model.get('response').getMQLatLng().lat;
                startLongitude = AMEXMap.instance.model.get('response').getMQLatLng().lng;
                endLatitude = '';
                endLongitude = '';
                endpointId = '';
                queryParams = AMEXSearchForm.instance.getFormValues();
            }
            else {
                startLatitude = AMEXMap.instance.wayPoints.getAt(0).getMQLatLng().lat;
                startLongitude = AMEXMap.instance.wayPoints.getAt(0).getMQLatLng().lng;
                endLatitude = AMEXMap.instance.wayPoints.getAt(1).getMQLatLng().lat;
                endLongitude = AMEXMap.instance.wayPoints.getAt(1).getMQLatLng().lng;
                endpointId = AMEXMap.instance.dirParams.id;
                queryParams = AMEXSearchForm.instance.getFormValues(AMEXSearchForm.instance.setValuesFromParams(AMEXMap.instance.dirParams));
            }

            var send = new Ajax.Request(
    	        AMEXGlobal.APPLICATION_ROOT+AMEXGlobal.EMAIL_AJAX, {
    	            method: 'post',
    	            parameters: {
    	                emailto: $('emailto').getValue(),
    	                subject: $('subject').getValue(),
    	                comments: $('comments').getValue(),
    	                query: queryParams,
    	                page: (AMEXMap.instance.model.get('page')) ? AMEXMap.instance.model.get('page') : '',
    	                locations: locations,
    	                startLatitude: startLatitude,
    	                startLongitude: startLongitude,
    	                startAddress: (AMEXMap.instance.startString) ? AMEXMap.instance.startString : '',
    	                endLatitude: endLatitude,
    	                endLongitude: endLongitude,
    	                endAddress: (AMEXMap.instance.endPoint) ? AMEXMap.instance.endPoint : '',
    	                units: AMEXSearchForm.instance.radiusUnits,
    	                endLocationId: endpointId
    	            },
    	            onSuccess: function(response) {
    	                this.hideEmailForm();
    	                
    	                AMEXMap.instance.messageBox.showMessage(Lang.STRINGS.email_success);
    	            }.bind(this),
                    onComplete: function(response) {
                        if(response.transport.status !== 200) {
                            AMEXMap.instance.messageBox.showMessage(Lang.STRINGS.email_error);
                        }
                    }.bind(this),
                    onException: function(response) {
                        if(response.transport.status !== 200) {
                            AMEXMap.instance.messageBox.showMessage(Lang.STRINGS.email_error);
                        }
                    }.bind(this),
                    onFailure: function(response) {
                        AMEXMap.instance.messageBox.showMessage(Lang.STRINGS.email_error);
                    }.bind(this)
    	        }
    	    );
		} else {
		    return;
		}
    },
    hideEmailForm: function(event) {
        if(event) {
            event.stop();
        }
        $(AMEXGlobal.EMAIL_FORM_ID).removeClassName('show');
        $('opt_radius').setStyle({ visibility: 'visible' });
    }
});


AMEXGlobal.init = function() {
    AMEXGlobal.instance = new AMEXGlobal;
    document.fire('global:loaded');
};
document.observe("dom:loaded", AMEXGlobal.init);
