Ext.namespace('Locator');

Locator.app = function(options) {
    // do NOT access DOM from here; elements don't exist yet
    // private variables	
	this.map = null;
	this.locations = null;
	this.geocoder = null;
	this.miles = 20;
	this.faddress = '';

	this.infobubble_tpl = new Ext.XTemplate(
    	'<p><strong>{NAME}</strong><br>',
        '{ADDRESS}<br>{CITY}, {STATE} {ZIPCODE}<br>{PHONE}</p>',
		'<p class="distance">Distance: {[Math.abs(values.MILES).toFixed(1)]} miles > <a href="javascript:Locator.app.getDirections({index})">get directions</a></p>'
	);
	this.infobubble_tpl.compile();

	this.initializeMap = function(){
		this.map = new GMap2(document.getElementById('locator-map'));
		this.map.addControl(new GSmallMapControl());
		// Create a base icon for all of our markers that specifies the shadow, icon dimensions, etc.
		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);
		this.baseIcon = baseIcon;
    };
	
	this.applyMarkers = function(locations) {
		this.map.clearOverlays();
		var bounds = new GLatLngBounds();
		for( var i=0; i<locations.length; i++ ) {
			var point = new GLatLng(locations[i].LAT, locations[i].LNG);
			var icon = new GIcon(baseIcon);
			icon.image = '/images/map_markers/numbered/marker' + (i+1) + '.png';
			var marker = new GMarker(point, {title: locations[i].NAME, icon: icon });
			this.map.addOverlay(marker);
			bounds.extend(point);
			locations[i].index = i + 1;
			marker.bindInfoWindowHtml(this.infobubble_tpl.apply(locations[i]));
			locations[i].marker = marker;
		}
		this.map.setCenter(bounds.getCenter(), Math.min(this.map.getBoundsZoomLevel(bounds)-1,13) );
	};
	
    // public space
    return {
        // public properties, e.g. strings to translate
 		
        // public methods
        init: function() {
			directions_url = '/store-locator/directions.cfm';
			tracking_var = 'c1';
			nolistings_tpl = new Ext.XTemplate(
				'<p><strong>',
			    'No stores were found within {miles} miles of {address}. Please try a broader search area.',
				'</strong></p>'
			);
			nolistings_tpl.compile();
		
			listings_tpl = new Ext.XTemplate(
				'<p id="locator-disclaimer">Please note that these retail locations may not carry all Wilton products. ',
				'Therefore, we recommend that you call ahead to check the availability of a specific product.</p>',
				'<div id="locations-list">',
				'<ol>',
			    '<tpl for="data">',
			    	'<li><h3>{NAME}</h3>',
			        '<p>{ADDRESS}<br>{CITY}, {STATE} {ZIPCODE}<br>{PHONE}</p>',
					'<p class="distance">Distance: {[Math.abs(values.MILES).toFixed(1)]} miles',
					' > <a name="&lid={NAME}" href="javascript:Locator.app.getDirections({#})">get directions</a>',
					'</p></li>',
			    '</tpl>',
				'</ol>',
				'</div>'
			);
			listings_tpl.compile();
        },

        initforclasses: function() {
			directions_url = '/classes/directions.cfm';
			tracking_var = 'c2';
		 	nolistings_tpl = new Ext.XTemplate(
				'<p><strong>',
			    'No class locations were found within {miles} miles of {address}. Please try a broader search area.',
				'If you are still unable to find a retailer in your area, call 1-800-942-8881 in the USA or 1-416-679-0790 in Canada for assistance.',
				'</strong></p>'
			);
			nolistings_tpl.compile();

			listings_tpl = new Ext.XTemplate(
				'<p id="locator-disclaimer" style="font-weight:bold;">Not all classes are offered at all store locations. ',
				'Please check with your local retailer for class offerings.</p>', 
				'<div id="locations-list">', 
				'<ol>', 
				'<tpl for="data">', 
				'<li><h3>{NAME}</h3>',
				'<p>{ADDRESS}<br>{CITY}, {STATE} {ZIPCODE}<br>{PHONE}',
				'{[this.getScheduleLink(xindex,values.NAME,values.WEBSITE)]}',
				'</p>', 
				'<p class="distance">Distance: {[Math.abs(values.MILES).toFixed(1)]} miles', ' > <a name="&lid={NAME}" href="javascript:Locator.app.getDirections({#})">get directions</a>', 
				'</p></li>', 
				'</tpl>', 
				'</ol>', 
				'</div>', {
				getScheduleLink: function(index, name, website){
					//var linkStr = '';
					//if (lname.search(/Jo Ann/i) != -1) linkStr = 'http://www.joann.com/joann/catalog.jsp?CATID=stores';
					//else if (lname.search(/Hobby Lobby/i) != -1) linkStr = 'http://www.hobbylobby.com/stores/stores.cfm?page=3&menu=0';
					//else if (lname.search(/Michaels/i) != -1) linkStr = 'http://www.michaels.com/art/online/static?page=wilton_cake_decorating';
					if( website != '') { return '<br><a href="'+website+'" onClick="Locator.app.visitRetailer(\''+index+'\')" target="_blank">Visit retailer website</a>'; }
					else if( name.search(/Jo Ann/i) != -1) { return '<br><a href="http://www.joann.com/joann/catalog.jsp?CATID=stores" onClick="Locator.app.visitRetailer(\''+index+'\')" target="_blank">Visit retailer website</a>'; }
					else return '';
				}
			}			
			);
			listings_tpl.compile();
        },
		
		getLocations: function(lat, lng) {
			Ext.Ajax.request({
				url: '/components/public.cfc?method=getLocations&lng='+lng+'&lat='+lat+'&miles='+miles,
				success: function(response, options) {
					var responseObj = Ext.util.JSON.decode(response.responseText);
					listings_tpl.overwrite(Ext.get('locator-listingscol'), responseObj);
					locations = responseObj.data;
					Ext.get('locator-map').dom.style.display = 'block';
					if( !map ) initializeMap();
					map.setCenter(new GLatLng(lat,lng),13);
					if (locations.length) {
						applyMarkers(locations);
						var lnames = '';
						for( var i=0; i<locations.length; i++) {
							lnames += (i > 0 ? ',' : '') + locations[i].NAME.replace(/,/g,"");
						}
						WSS_Set('n','/' + document.title + ' - Submit');
						WSS_Set(tracking_var,lnames);
						_hbSend();
					}
					else {
						nolistings_tpl.overwrite(Ext.get('locator-listingscol'), {
							miles: miles,
							address: faddress
						});
					}
				},
				failure: function(response, options) {
					alert('error connecting to server');
				}
			});
		},
		
		showErrorMessage: function(str) {
			var elm = Ext.get('locator-error').dom;
			elm.innerHTML = str;
			elm.style.display = 'block';
		},
		
		clearErrorMessage: function() {
			var elm = Ext.get('locator-error').dom;
			elm.style.display = 'none';			
		},
		
		validateForm: function(form) {
			this.clearErrorMessage();
			var zipcode = form.zipcode.value;
			var city = form.city.value;
			var state = form.state.value;

			if( zipcode == '' && ( city == '' || state == '') ) {
				this.showErrorMessage('Please enter your zip code or your city and state.');
				return;
			}

			miles = form.miles.value;
			faddress = '';
			if( zipcode.length ) faddress += (faddress.length ? ', ' : '') + zipcode;
			else {
				if( city.length ) faddress += (faddress.length ? ', ' : '') + city;
				if( state.length ) faddress += (faddress.length ? ', ' : '') + state;				
			}			
			
			if( !geocoder) geocoder = new GClientGeocoder();
	        geocoder.getLatLng( faddress, function(point) {
	            if (!point) {
	              Locator.app.showErrorMessage('We were unable to locate the address you entered. Please verify that everything is spelled correctly and ensure that you have included the city and state/province or zip code.');
	            } else {
					Locator.app.getLocations(point.lat(), point.lng());
	            }
	          }
	        );
		},
		
		getDirections: function(locationindex) {
			var location = locations[locationindex-1];
			var url=directions_url+'?name='+location.NAME+'&address='+location.ADDRESS+'&city='+location.CITY+
						'&state='+location.STATE+'&zipcode='+location.ZIPCODE+'&phone='+location.PHONE;
			window.open(url,'directions','width=800,height=600,scrollbars=yes,resizable=yes');
			_hbLink(location.NAME+' : Get Directions');
		},
	
		visitRetailer: function(locationindex) {
			var location = locations[locationindex-1];
			_hbLink(location.NAME+' : Visit Website');
		}
	
    };
}(); // end of app