/**
 * @class HD.util.DealerFinder
 * @description Displays an overlay with the results of a dealer search based on the parameters passed.
 * 
 * @constructor
 * @property {object} 	config
 *                    	The configuration for the widget.
 * @property {string} 	location (Optional)
 * 						This is a free text search, it's value could be anything. New York City, NY, Golden Gate Bridge, 111 Somewhere Ave, Some City, AK
 * @property {string} 	size (Optional)
 * 						This is the number of dealer you want to be returned. The max dealers for a search is 500, this is a Ride Planner limit.
 * @property {string} 	miles (Optional)
 * 						This is the radius in miles you wish to seach for.
 * @property {boolean} 	useDealerToZipMappings (Optional)
 * 						The default is to use the dealer to zip mapping file. So if true is passed then the proximity search will look at the dealer to zip mapping file and if a dealer search was preformed by postalCode, then we will make sure the dealer who owns that postalCode is returned 1 st in the list of dealer returned, reguardless of the distance by proximity. true or false
 * @property {boolean} 	buellDealer (Optional)
 * 						If you wish to only search for Buell dealer's pass a "true" here, then the results will only contain dealers that sell Buell Motorcycles. false/true
 * @property {object} 	programCodes (Optional)
 * 						These are codes that represent dealer programs in GDIS, see all the mappings with descriptions. You can pass in multiple program codes and if a dealer is in any of those programs they will be returned in the result.
 * 						More info: https://content1.harley-davidson.com/projects/DealerServices/rest-api/dealer-proximity-search.html
 * @property {string} 	locale (Optional)
 * 						The country code from the locale - ISO 3166-1 alpha-3 Country code - en_US, pt_BR
 * 						Default value is en_US 
 * @property {string} 	buttonLabel
 *                    	Defines the label on the action button for each dealer on the results.
 * @property {string} 	buttonAction
 * 						Defines the onclick function on the action button for each dealer on the results. Value will be assigned directly to the button onclick function.
 * 						The dealer id will be the id of the button object, in order to pass the dealer id use function(this.id)
 * @property {string} 	displayEmptyWithSearch
 * 						This is a flag that will display the overlay empty with a search box on top.  
 *                    
 */

HD.util.DealerFinder = function(config) {
	config = config || {};
	this.model = new HD.util.DealerFinder.Model(config);
	this.view = new HD.util.DealerFinder.View(this.model);
	this.controller = new HD.util.DealerFinder.Controller(this.model, this.view);
	this.model.addObserver(this.view);
};

/**
 * The data model for HD.util.DealerFinder
 * @param {object}	config The configuration for the model.
 */
HD.util.DealerFinder.Model = function(config) {
	this.config = config;
	this.observers = [];
};

HD.util.DealerFinder.Model.prototype = {

};


HD.extend(HD.util.DealerFinder.Model, [HD.util.Observable]);

/**
 * The view for HD.util.DealerFinder
 * @param {object}	model The data model for the player
 */
HD.util.DealerFinder.View = function(model){
	this.model = model;
	this.config = this.model.config;
	this.observers = [];
};

/**
 * The collection of default templates.
 * @fieldOf HD.util.DealerFinder.View
 */
HD.util.DealerFinder.View.templates = {
	/**
	 * Placeholder text for the content.
	 * @memberOf HD.util.DealerFinder.View
	 */
	placeholderText : 'Missing buttonLabel or buttonAction. buttonLabel and buttonAction must be provided on the widget config.',
	
	/**
	 * @constant
	 * @return {string} Placeholder text for the content.
	 * @memberOf HD.util.DealerFinder.View
	 */
	getPlaceholderText : function(){
		return this.placeholderText;
	}
	
};

HD.util.DealerFinder.View.prototype = {
	/** Overlay events */
	EVENTS : {
		OPEN : "OPEN",
		CLOSE : "CLOSE"
	},
	
	/**
	 * Display the overlay and apply the config
	 */
	setListeners : function() {
		
		HD.util.DealerFinder.View.prototype.playerContainerID = null;
		HD.util.DealerFinder.View.prototype.data = null;
		HD.util.DealerFinder.View.prototype.config = this.config; 
		
		// Load all configs
		this.title = this.config.title ? this.config.title : '';
		this.street = this.config.street ? this.config.street : '';
		this.city = this.config.city ? this.config.city : '';
		this.state = this.config.state ? this.config.state : '';
		this.postalCode = this.config.postalCode ? this.config.postalCode : '';
		this.country = this.config.country ? this.config.country : '';
		this.location = this.config.location ? this.config.location : '';
		this.poi = this.config.poi ? this.config.poi : '';
		this.size = this.config.size ? this.config.size : '';
		this.miles = this.config.miles ? this.config.miles : '';
		this.useDealerToZipMappings = this.config.useDealerToZipMappings ? this.config.useDealerToZipMappings : '';
		this.buellDealer = this.config.buellDealer ? this.config.buellDealer : '';
		this.programCodes = this.config.programCodes ? this.config.programCodes : '';
		this.locale = this.config.locale ? this.config.locale : '';
		this.buttonLabel = this.config.buttonLabel ? this.config.buttonLabel : '';
		this.buttonAction = this.config.buttonAction ? this.config.buttonAction : '';
		this.searchForm = this.config.searchForm ? this.config.searchForm : 'true';
		this.displayEmptyWithSearch = this.config.displayEmptyWithSearch ? this.config.displayEmptyWithSearch : '';
		this.contentFunction = this.config.contentFunction ? this.config.contentFunction : '';
		this.channel = this.config.channel ? this.config.channel : '';
		this.searchedLocation = '';
		
		//If buttonLabel and buttonAction were not submitted display placeholder
		if (this.buttonLabel == '' && this.buttonAction == '') {
			this.displayPlaceholder();
			return false;
		}
		
		this.language = HD.util.Localization.getLanguageFromLocale({validLanguages : ['cs','da','de','en','es','fr','it','nl','no','pt']});

		//Load Google API Asynchronously
		if(!window.google) {
			var scriptSRC = window.parent.location.protocol + "//maps.googleapis.com/maps/api/js?sensor=false&callback=HD.util.DealerFinder.View.prototype.getLanguage&language=" + this.language; 
			if(this.channel != '') {
				scriptSRC += '&channel=' + this.channel; 
			}
			var script = document.createElement("script");
			script.src = scriptSRC;
			script.type = "text/javascript";
			document.body.appendChild(script);
		} else {
			this.getLanguage();
		}
		
	},
	
	/**
	 * Get language and continue
	 */
	getLanguage : function () {
		//Check if language is available, if not default to en
		if(this.language) {
			//Create the language file path
			var languageFile = '/en_US/Media/js/dealer-locator/language/' + this.language + '.js';
			
			//Load language file
			var headTag = document.getElementsByTagName('head')[0];
			var includeFile = document.createElement('script');
			includeFile.setAttribute('type','text/javascript');
			includeFile.setAttribute('src',languageFile);
			headTag.appendChild(includeFile);
		}
		
		this.checkLanguage();
	},
	
	/**
	 * Check if language is available and continue
	 */
	checkLanguage : function () {
		if(window.DealerSearch == undefined || window.DealerSearch.Language == undefined || !this.searchForm) {
			setTimeout("HD.util.DealerFinder.View.prototype.setListeners();",100);
		} else {
			
			//If this flag is set to true, don't bother building the URL
			//simply display the empty overlay with a search box
			if(this.displayEmptyWithSearch && this.buttonLabel){
				this.displayOverlay(null, this.locale, this.buttonLabel, this.buttonAction, this.searchForm);
				return false;

			} else if(this.location) {
					
				//Close auto-complete
				$('.ui-autocomplete').css("visibility","hidden");
				
				//Get Lat/Long from Google or display suggestions
				var geocoder = new google.maps.Geocoder();
				HD.util.DealerFinder.View.prototype.searchString = this.location;
				var self = this;
				geocoder.geocode( {'address': this.searchString }, function(results, status) {
					if(results[0]){
						
						self.latlng = results[0].geometry.location.lat() + ',' + results[0].geometry.location.lng();

						//Call endpoint and display overlay  
						var url = self.buildUrl(self.latlng, 
												self.size, 
												self.miles, 
												self.useDealerToZipMappings,
												self.buellDealer, 
												self.programCodes
											);
						self.submitEndpointRequest(url, self.locale, self.buttonLabel, self.buttonAction, self.searchForm, self.contentFunction);
						self.searchedLocation = results[0].formatted_address;

					} else {
						self.displayNoResults();
						return false;
					}       				
				});
			} else {
				this.displayOverlay(null, this.locale, this.buttonLabel, this.buttonAction, this.searchForm);
				return false;
			}
		}
		
	},

	/**
	 * Display the placeholder content if the dealer info is missing
	 */
	displayPlaceholder : function () {
		
		var placeholder = '<div class="missingPlaceholder">' + HD.util.DealerFinder.View.templates.getPlaceholderText() + '</div>';
		HD.util.Common.showOverlay( placeholder, '', 400, 150, true, 'dealerOverlay' );
		
	},
	
	/**
	 * Add a parameter to an array of parameters in name=value format, but only
	 * if the value is not empty.
	 * 
	 * @param {Array} params array to add to
	 * @param {String} name name for parameter
	 * @param {String} value for parameter
	 * @param {Boolean} forceAdd true to force add of parameter even if no value
	 * 
	 * @returns reference to current object so that calls are chainable
	 */
	pushParam: function( params, name, value, forceAdd ) {
		if ( null == forceAdd ) {
			forceAdd = false;
		}
		
		// only add if value not empty
		if ( /\S/.test( value ) || forceAdd ) {
			params.push( name + '=' + escape( value ) );
		}
		
		// make calls chainable
		return this;
	},
	
	/**
	 * This method puts together the full URL for a call to the endpoint.
	 * 
	 * @returns url for calling the endpoint
	 */
	buildUrl: function(latlng, size, miles, useDealerToZipMappings, buellDealer, programCodes) {
		var params   = [ '_type=json' ];
		var endpoint = HD.util.Common.getServerUrl() + '/dealerservices/services/rest/dealers/proximitySearch';
		
		this.pushParam( params, 'latlng', latlng );
		this.pushParam( params, 'size', size );
		this.pushParam( params, 'miles', miles );
		this.pushParam( params, 'useDealerToZipMappings', useDealerToZipMappings ); 
		this.pushParam( params, 'buellDealer', buellDealer );
		this.pushParam( params, 'programCodes', programCodes );
		
		return endpoint + '?' + params.join( '&' );
	},
	
	/**
	 * This method redirects the browser to the online rentals endpoint.
	 * 
	 * @returns url for calling the endpoint
	 */
	redirectToOnlineRentalsUrl: function(dealerid) {		 
		window.location = 'https://websolutions.tsd-inc.com/Harley-Davidson/frmRateQuote.aspx?locale=en_US&bmLocale=en_US&PickupLoc=' + dealerid;
	},
	
	/**
	 * This method provides the core functionality on the page by running the
	 * actual call to the endpoint and handling the response.
	 */
	submitEndpointRequest: function( url, locale, buttonLabel, buttonAction, searchForm, contentFunction ) {
		var self = this;
		
		//Close auto-complete
		$('.ui-autocomplete').css("visibility","hidden");
		
		//Disable submit button 
		HD.get('hdSearchButton').disabled = true;
		
		//Reset results container & header
		$('.dealersContainer').jScrollPane().data().jsp.destroy();
		HD.get('dealersContainer').innerHTML = '<div class="loading"></div>';
		var header = HD.get('tableHeader');
		if(header) {header.style.display = 'none';};
		
		YAHOO.util.Connect.asyncRequest( 'GET', url,
			{
				failure:
					function( response ) {
						alert('Internal error. Please try again.');
					},
					
				success:
					function( response ) {

						HD.util.form.jsonHandleResponse( response,
							function( responseData ) {
								var dealerResponse = ( null == responseData
										                 ? null
										                 : responseData.dealerResponse
										                 );
								var dealers        = ( null == dealerResponse
										                 ? []
										                 : dealerResponse.dealers
										                 );
								
								if ( ( null == dealers ) || ( 0 == dealerResponse.dealers.length ) ) {
									self.displayNoResults();
									return;
									
								} else {
									self.displayOverlay( dealers, locale, buttonLabel, buttonAction, searchForm, contentFunction );
									
									//Trigger tracking
									var documentPath = window.location.pathname;
									var pageNameTracking = documentPath.substring(documentPath.lastIndexOf('/') + 1);
									var trackingString = '/Locators/Rental+Locator/Search+Results/' + HD.util.DealerFinder.View.prototype.searchString;
									_hbPageView(pageNameTracking, trackingString);
									
								}

							}
						);
					}
			}
		);
		
		
	},

	//Display no results message
	displayNoResults: function(){ 
	
		//Reset results container & header
		$('.dealersContainer').jScrollPane().data().jsp.destroy();
		HD.get('dealersContainer').innerHTML = '<div class="loading"></div>';
		var header = HD.get('tableHeader');
		if(header) {header.style.display = 'none';};
		
		//Enable submit button
		var searchButton = HD.get('hdSearchButton');
		if(searchButton) {
			searchButton.disabled = false;
			searchButton.focus();
		}
		
		//Enable auto-complete
		$('.ui-autocomplete').css("visibility","visible");
		$('.ui-autocomplete').css("display","none");		
		
		//Display message
		HD.get('dealersContainer').innerHTML = '<div class="noResults">' + DealerSearch.Language.data.dealerSearch_noResultsMessage + '</div>';
		
		//Trigger tracking
		var documentPath = window.location.pathname;
		var pageNameTracking = documentPath.substring(documentPath.lastIndexOf('/') + 1);
		var trackingString = '/Locators/Rental+Locator/No+Results/' + HD.util.DealerFinder.View.prototype.searchString;
		_hbPageView(pageNameTracking, trackingString);

	},
	
	retrieveDefaultOverlayContent: function(dealer, buttonAction, buttonLabel, last){
		var toReturn = '<div class="dealerRowHeader '
			+ last
			+ '">'
			+ '<div class="dealerName">'
			+ dealer.name
			+ '</div></div><div class="dealerRowInfo '
			+ last
			+ '"><div id="'
			+ dealer.id
			+ '" class="orangeButton" onclick="'
			+ buttonAction
			+ '"><span>'
			+ buttonLabel
			+ '</span></div><p>'
			+ dealer.address1 + '<br/>';
		
		if(dealer.address2){
			toReturn += dealer.address2 + '<br/>';
		}
		
		if(dealer.address3){
			toReturn += dealer.address3 + '<br/>';
		}
		
		toReturn += dealer.city + ', ' + dealer.state + ', ' + dealer.country + ' ' + dealer.postalCode + '<br/>'
		+ dealer.phoneNumber + '<br/>'
		+ dealer.faxNumber
		+ dealer.website 
		+ '</p></div>';
			
		return toReturn;
	},
	
	/**
	 * Display dealer finder overlay
	 */
	displayOverlay: function( dealers, locale, buttonLabel, buttonAction, searchForm, contentFunction) {
		
		var formSearch = HD.util.DealerFinder.View.prototype.config.formSearch ? HD.util.DealerFinder.View.prototype.config.formSearch : false;
		var formSearchOptions = HD.util.DealerFinder.View.prototype.config.formSearchOptions == true ? 'block' : 'none';
		var language = DealerSearch.Language.data ? DealerSearch.Language.data : '';
		
		var overlayTitle = this.title ? this.title : language.dealerSearch_titleLabel; 
		
		var overlayContent =  '<h1 class="mainHeader">' + overlayTitle + '</h1>';
		var searchFormHTML = '<div id="searchFormContainer" class="byLocation">\
								<form id="byLocation" class="searchForm" name="byLocation" action="#" onsubmit="return false">\
									<input id="hdLocationField" type="text" value="" name="hdLocationField" />\
									<input type="submit" id="hdSearchButton" class="orangeButton" value="'
									+ language.dealerSearch_submitSearch
									+ '" />\
								</form>\
							 </div>';

		if( searchForm == true ) {
			overlayContent += searchFormHTML; 
		}

		overlayContent += '<div id="tableHeader">\
								<div class="dealerName">'
								+ language.dealerSearch_dealerTitleLabel
								+ '</div>\
							</div>\
							<div id="dealersContainer" class="dealersContainer">';
		
		if(formSearch) {
			overlayContent = '';
		}
		
		var hasResults = false;
		if(dealers) {
			for (var i = 0; i < dealers.length; i++) {
	
				currentDealer = new Object();
				currentDealer.address1 = dealers[i].contact.address1 ? dealers[i].contact.address1 : '';
				currentDealer.city = dealers[i].contact.city ? dealers[i].contact.city : '';
				currentDealer.country = dealers[i].contact.country ? dealers[i].contact.country : '';
				currentDealer.email = dealers[i].contact.email ? dealers[i].contact.email : '';
				currentDealer.faxNumber = dealers[i].contact.faxNumber ? dealers[i].contact.faxNumber + ' (' + language.dealerOverlay_faxLabel + ')<br/>' : '';
				currentDealer.phoneNumber = dealers[i].contact.phoneNumber ? dealers[i].contact.phoneNumber : '';
				currentDealer.postalCode = dealers[i].contact.postalCode ? dealers[i].contact.postalCode : '';
				currentDealer.state = dealers[i].contact.state ? dealers[i].contact.state : '';
				currentDealer.website = dealers[i].website ? '<a target="_blank" href="' + dealers[i].website + '">' + dealers[i].website + '</a>' : '';
				currentDealer.distance = dealers[i].distanceFromSearchedLocation ? dealers[i].distanceFromSearchedLocation : '';
				currentDealer.id = dealers[i].id ? dealers[i].id : '';
				currentDealer.name = dealers[i].name ? dealers[i].name : '';
				currentDealer.onlineRental =  dealers[i].onlineRental ? dealers[i].onlineRental : '';
				currentDealer.rentalName = dealers[i].rentalsInfo.name ? dealers[i].rentalsInfo.name : null;
				
				//Set class of first result
				var last = '';
				if(i == (dealers.length - 1)) {
					last = 'last';
				}
				
				if(contentFunction != null && !(0 === contentFunction.length)){
					overlayContent += contentFunction(currentDealer, last);
				} else {
					overlayContent += this.retrieveDefaultOverlayContent(currentDealer, buttonAction, buttonLabel, last);	
				}
				
			}
			hasResults = true;

		}
		
		if(!formSearch) {
			overlayContent += '</div>';
		}
		
		var overlayHeight = 325;
		if( searchForm == true ) {
			overlayHeight = 405; 
		}

		if(formSearch) {
			HD.get('dealersContainer').innerHTML = overlayContent;
		} else {
			HD.util.Common.showOverlay( overlayContent, '', 600, overlayHeight, true, 'dealerFinderOverlay' );
			
			//Trigger tracking
			var documentPath = window.location.pathname;
			var pageNameTracking = documentPath.substring(documentPath.lastIndexOf('/') + 1);
			var trackingString = '/Locators/Rental+Locator/Search+Overlay';
			_hbPageView(pageNameTracking, trackingString);
			
		}
		
		//Add functions to location field
		var locationField = HD.get('hdLocationField');
		if(locationField) {
			var locationFieldLabel = language.dealerSearch_locationFieldLabel;
			if(locationField.value == '') {
				locationField.value = locationFieldLabel;
			}
			locationField.onfocus = function() {
				locationField.className = '';
				if(locationField.value == locationFieldLabel) {
					locationField.value = '';
				}
			};
			locationField.onblur = function() {
				if(locationField.value == '') {
					locationField.value = locationFieldLabel;
				}
			};

			//Add validation to form
			var form = HD.get('byLocation');
			var self = this;
			form.onsubmit = function() {
				if(locationField.value == locationFieldLabel) {
					locationField.className = 'error';
					return false;
				} else {
					locationField.className = '';
					self.submitSearch('byLocation');
					return false;
				}
			}
		}

		$(document).ready(function(){
		
			if(hasResults) {
				HD.get('tableHeader').style.display = 'block';
	
				//Activate the accordion effect
				$('.dealersContainer').accordion({
					active: 0,
					autoHeight: false,
					icons: {
						header: "item-closed",
						headerSelected: "item-open"
					}
				});
				
				$('.dealersContainer').jScrollPane();
			}
					
			var geocoder = new google.maps.Geocoder();
			$("#hdLocationField").autocomplete({
			      //This bit uses the geocoder to fetch address values
			      source: function(request, response) {
			        geocoder.geocode( {'address': request.term }, function(results, status) {
			          response($.map(results, function(item) {
			            return {
			              label:  item.formatted_address,
			              value: item.formatted_address,
			              latitude: item.geometry.location.lat(),
			              longitude: item.geometry.location.lng()
			            };
			          }));
			        });
			      },
			      //This bit is executed upon selection of an address
			      select: function(event, ui) {
			    	  self.latlng = ui.item.latitude + ',' + ui.item.longitude;
	
						//Call endpoint and display overlay  
						var url = self.buildUrl(self.latlng, 
												self.size, 
												self.miles, 
												self.useDealerToZipMappings,
												self.buellDealer, 
												self.programCodes
											);
						HD.util.DealerFinder.View.prototype.searchString = ui.item.value;
						HD.util.DealerFinder.View.prototype.config.formSearch = true;
						self.submitEndpointRequest(url, self.locale, self.buttonLabel, self.buttonAction, self.searchForm, self.contentFunction);
						
			      }
			});
		});
			
		//Re-enable submit button
		var searchButton = HD.get('hdSearchButton');
		if(searchButton) {
			searchButton.disabled = false;
			searchButton.focus();
		}
		
		//Close auto-complete
		$('.ui-autocomplete').css("visibility","visible");
		$('.ui-autocomplete').css("display","none");
		
	},
	
	/**
	 * Validate and submit the request for search from the form
	 */
	submitSearch: function(searchType) {
		
		var locationField = HD.get('hdLocationField');
		
		var config = HD.util.DealerFinder.View.prototype.config; 
		
		var size = config.size ? config.size : '';
		var miles = config.miles ? config.miles : '';
		var useDealerToZipMappings = config.useDealerToZipMappings ? config.useDealerToZipMappings : '';
		var buellDealer = config.buellDealer ? config.buellDealer : '';
		var programCodes = config.programCodes ? config.programCodes : '';
		var locale = config.locale ? config.locale : '';
		var buttonLabel = config.buttonLabel ? config.buttonLabel : '';
		var buttonAction = config.buttonAction ? config.buttonAction : '';
		var searchForm = config.searchForm ? config.searchForm : '';
		var contentFunction = config.contentFunction ? config.contentFunction : '';
		
		config.formSearch = true;
		
		//Get Lat/Long from Google or display suggestions
		var geocoder = new google.maps.Geocoder();
		HD.util.DealerFinder.View.prototype.searchString = locationField.value;
		var self = this;
		geocoder.geocode( {'address': this.searchString }, function(results, status) {
			if(results[0]){
				var latlong = results[0].geometry.location.lat() + ',' + results[0].geometry.location.lng();

				//Call endpoint and display overlay  
				var url = self.buildUrl(latlong, 
										self.size, 
										self.miles, 
										self.useDealerToZipMappings,
										self.buellDealer, 
										self.programCodes
									);
				
				self.submitEndpointRequest(url, locale, buttonLabel, buttonAction, searchForm, contentFunction);
				locationField.value = results[0].formatted_address;

			} else {
				self.displayNoResults();
				return false;
			}       				
		});
		
		

	},
	
	/**
	 * Clear field content and style 
	 */
	displayDealerRentalWidget: function() {
		var self = this;
		var search = new HD.util.DealerFinder(
				{
					parent : 'dealerFinderContainer',
					searchForm : true,
					title : self.dealerFinderWidget_titleLabel,
					buttonLabel : 'View',
					buttonAction : 'var dealer = new HD.util.Dealer({parent : \'dealerContainer\', dealerid: this.id}); dealer.view.render({});',
					displayEmptyWithSearch : true,
					programCodes : 'RE',
					contentFunction : function(dealer, last) {
						var dealerName = dealer.name;
						if(dealer.rentalName != null) {
							dealerName = dealer.rentalName;
						}
						
						var toReturn = '<div class="dealerRowHeader '
							+ last
							+ '">'
							+ '<div class="dealerName">'
							+ dealerName
							+ '</div></div><div class="dealerRowInfo '
							+ last
							+ '"><p>'
							+ dealer.address1 + '<br/>';
						
						if(dealer.address2){
							toReturn += dealer.address2 + '<br/>';
						}
						
						if(dealer.address3){
							toReturn += dealer.address3 + '<br/>';
						}
						
						toReturn += dealer.city + ', '
							+ dealer.state + ', '
							+ dealer.country + ' '
							+ dealer.postalCode + '<br/>'
							+ dealer.phoneNumber + '<br/>'
							+ dealer.faxNumber
							+ dealer.website + '</p><div id="'
							+ dealer.id
							+ '" class="orangeButton" onclick="HD.util.DealerFinder.View.prototype.dealerSelectedTracking(\''
							+ dealer.country + '\',\''
							+ dealer.state + '\',\''
							+ dealer.id
							+ '\'); var dealer = new HD.util.Dealer({parent : \'dealerContainer\', dealerid: this.id, rentalDealer: true}); dealer.view.render({});"><span>'
							+ DealerSearch.Language.data.dealerFinderWidget_viewInfo
							+ '</span></div>';
						
						if (dealer.onlineRental) {
							
							var locale = HD.util.Localization.getLocale();
							var rentalSite = 'https://websolutions.tsd-inc.com/Harley-Davidson/frmRateQuote.aspx?locale=' + locale + '&amp;bmLocale=' + locale + '&amp;PickupLoc=';
							if(dealer.country != 'USA' && dealer.country != 'CAN'){
								rentalSite = 'https://www2.rentcentric.com/Client4317/webcustomer/harleydavidson.aspx?locale=' + locale + '&PickupLoc=';
							} 
							
							toReturn += '<div id="' + dealer.id + '" class="orangeButton" onclick="window.open(\''+ rentalSite
									+ dealer.id * 29
									+ '\')"><span>'
									+ DealerSearch.Language.data.dealerFinderWidget_bookOnline
									+ '</span></div>';
						}
						
						toReturn += '</div>';
						return toReturn;
					}
				});
		search.view.render({});
	},
	
	/**
	 * Fire tracking for when a dealer is selected 
	 */
	dealerSelectedTracking: function(country,state,id) {
		
		if(country && id) {
			if(!state || country != "USA") {
				state = 'noState'; 
			}
			
			var documentPath = window.location.pathname;
			var pageNameTracking = documentPath.substring(documentPath.lastIndexOf('/') + 1);
			var trackingString = '/Locators/Rental+Locator/Viewed+Results/' + country + '/' + state + '/' + id;
			_hbPageView(pageNameTracking, trackingString);
		}
	}
	
};

HD.extend(HD.util.DealerFinder.View, [HD.Widget]);

/**
 * The controller for HD.util.DealerFinder
 * @param {object}	model The data model for the player
 * @param {object}	view The view for the player
 */
HD.util.DealerFinder.Controller = function(model, view){
	this.model = model;
	this.view = view;
};

HD.util.DealerFinder.Controller.prototype = {
		
};

HD.register("hd_dealer", HD.util.DealerFinder, {version: "1.0", build: "1"});
