YAHOO.util.Event.onDOMReady(function(){
	HD.REO.SearchForm = {
		init : function() {
			var cb = this;
			SessionService.setAttribute("expLvl", expLvl, function(){
				HD.REO.experienceLevel = hbxExpLvl;
				if (!YAHOO.util.Dom. hasClass(document.body, "yui-skin-sam")){ 
					YAHOO.util.Dom.addClass(document.body, "yui-skin-sam DARK masked");
					}
				cb.initWidgets.call(cb);
				cb.initErrorHandler.call(cb);
			});
		},
		
		initErrorHandler : function() {
			HD.REO.initErrorHandler();
			HD.util.DWR.showErrorMessage = function(message) {
				HD.REO.SearchForm.searchView.setMessage(message);
			};
		},
		
		executeSearch : function() {
			this.searchView.executeSearch(null, true);
		},
		
		initWidgets : function() {
			// create model
			var reoModel = new HD.REO.Model();
			
			var reoView = new HD.REO.View({
				parent : "contentwrapper"
			});
			
			var isDealerView = HD.REO.setupDealerView(reoView);
			
			// create widgets
			var searchView = new HD.REO.View.Search({
				parent : "reoSearch",
				message  : "reoMessage"
			}, reoModel, reoView);
			searchView.render();
			this.searchView = searchView;
			
			//set Rollover state on search button
			var btnSearchClasses = YAHOO.util.Dom.getElementsByClassName('hdSearchButton');
			if(btnSearchClasses){
				YAHOO.util.Event.on(btnSearchClasses[0], 'mouseover', function(){
					btnSearchClasses[0].style.backgroundPosition = "0 -24px";
				})
				YAHOO.util.Event.on(btnSearchClasses[0], 'mouseout', function(){
					btnSearchClasses[0].style.backgroundPosition = "0 0";
				})
			}
			
			var listView = new HD.REO.View.List({
				parent : "reoList"
			}, reoModel, reoView);
			
			// listen for user clicking on 'Enroll'
			var cb = this;
			reoView.addObserver({
				update : function(eventName, eventData) {
					if(eventName == "listView_CourseEnroll_Click") {
						window.location = HD.util.Common.getForwardUrl("/wcm/Content/Pages/riders_edge_online/enrollment.jsp?form=1&locale=en_US", HD.REO.paramsToPropagate, "https");
					}
				}
			});
			
			if(isDealerView) {
				var common = HD.util.Common;
				var dealerId = common.getRequestParam("dwp_dealerid") || common.getRequestParam("dealerid");
				var dealerUrl = common.getRequestParam("ret_page");
				dealerId = parseInt(dealerId) / 29;
				searchView.setDealer({id : dealerId});
				searchView.dealerReturnUrl = dealerUrl;
				searchView.render();
				HD.REO.analytics.searchResultsPage = dealerId + '/RE+Online+Reservations/Class+List/_COURSE_TYPE/_NUM_OF_RESULTS';
			} else {
				SessionService.removeAttributes(["dealerLink", "dealerLinkName"]);
				HD.REO.populateFormData(HD.REO.View.Search.template.formId, function(){
					cb.executeSearch.call(cb);
				});
			}
		}
	};
	
	
	HD.REO.SearchForm.init();
	
	


});




// Copy changes on search form
HD.REO.View.Search.template.initial = '<div style="text-align: center;" class="hdSearchInitialMessage">' +
									'<h2>Start Searching for Classes Here.</h2>' +
									'<p>Enter your desired location and distance, then click Search Classes.<br/>' +
									'You can always change your search options to find the date and location that works best for you.</p>' +
									'</div>';
									
HD.REO.View.Search.template.message.noLocation = "You must enter a valid ZIP code or city and state to search classes.";		

HD.REO.View.List.template.courseSubTypesInfos = [
	    null,        
		"<div>This class is reserved for Women students only.</div>",
		"<div>This class is offered in Spanish and uses Spanish written materials.</div>"
	];

HD.REO.View.Search.template.suggestions.msfLink = "<a id=\"msfCourse\" class=\"msfCourse\" href=\"javascript:void(0);\" onClick=\"window.open('http://www.msf-usa.org/')\"><span>Find MSF Courses</span></a>";

HD.REO.View.Search.template.suggestions.maxDistanceAndDates = "We\'ve automatically increased your search to include the maximum distance and date range";

HD.REO.View.Search.template.suggestions.maxDistance = "We\'ve automatically increased your search to include the maximum distance";

HD.REO.View.Search.template.suggestions.maxDates = "We\'ve automatically increased your search to include all future dates";


HD.REO.View.List.template.getDealerContact = function(dealer) {
		var address = dealer.address;
		var phone = dealer.phone;


		return [
			'<ul class="hdContactAddress">',
				'<li class="shopName">', dealer.name, '</li>',
				'<li class="shopAdd">', address.street1, '</li>',
				'<li class="shopCity">', address.city, ', ', address.state, ' ', address.zip, '</li>',
				'<li class="shopPh">(', phone.npa, ') ', phone.nxx, '-', phone.station, '</li>',
			'</ul>',
			'<ul class="hdContactInfo">',
				'<li class="maps"><a href="javascript:void(0)" onclick="', HD.REO.getDealerHref(dealer) ,'" class="hdMapDirectionsHours">Map, Directions & Hours</a></li>',
				'<li class="REcontact">Rider\'s Edge Contact</li>',
				'<li class="RECntctName">',
					'<a class="hdLink" href="mailto:', dealer.contactEmail, '">', dealer.contactName, '</a> (', dealer.contactEmail, ')',
				'</li>',
				( dealer.url != null ? '<li class="hdContactUrl">Website<br/><a class="hdLink" href="javascript:void(0);" onClick="window.open(\''+dealer.url+'\')">'+dealer.url+'</a></li>' : ''),
			'</ul>'
		].join('');
	};






// Edit tooltip z-index for IE
HD.REO.View.List.prototype.setItemListener = function(courseEl, courseData) {
		var dom = HD.util.Dom;
		var cb = this;
		var viewCb = this.view;
		var courseId = courseData.id;
		var dealer = courseData.dealer;
		var dealerId = dealer.id;
		var isShowingOpenClassDealer = false;
		var openClassDealer;
		
		var summaryEl = dom.getByClass("hdSummary", "div", courseEl)[0];
		var detailsEl = dom.getByClass("hdDetails", "div", courseEl)[0];
		var scheduleEl = dom.getByClass("hdSchedule", "div", courseEl)[0];
		var enrollEl = dom.getByClass("hdEnroll", "div", courseEl)[0];
		var openingsEl = dom.getByClass("hdCourseOpenings", "div", courseEl)[0];
		var tooltipEls = dom.getByClass("hdTooltip", "div", courseEl);
		var typeEl = dom.getByClass("hdType", "div", courseEl)[0];
		var typeLinkEls =  dom.getByClass("hdLink", "span", typeEl);
		
		var modelCb = this.model;
		
		var expand = function() {
			modelCb.getCourseDetails.call(modelCb, {courseId:courseId, dealer:dealer});
			
			// added animation for dealer site search page
			var myAnim;
			
				myAnim = new YAHOO.util.Anim(courseEl, {
					height: {
						from: 32,
						to: 193
					}
				});
			
				myAnim.duration = 0.3;
				myAnim.animate();
				
				myAnim.onComplete.subscribe(function(){
					dom.removeClass(courseEl, "hdCollapsed");
					dom.addClass(courseEl, "hdExpanded");
				});
						
		};
		
		var collapse = function() {
			var myAnim;
				myAnim = new YAHOO.util.Anim(courseEl, {
					height: {
						from: 193,
						to: 32
					}
				});
			
			dom.removeClass(courseEl, "hdExpanded");
			dom.addClass(courseEl, "hdCollapsed");
			
			myAnim.duration = 0.3;
			myAnim.animate();
			
		};
		
		var isExpanded = false;
		summaryEl.onclick = function() {
			isExpanded = !isExpanded;
			if(isExpanded) {
				expand();
			} else {
				collapse();
			}
		};
		
		var scheduleView = new HD.REO.View.Schedule({
			parent : scheduleEl,
			courseId : courseId,
			dealerId : dealerId
		}, this.model, this.view);
		
		scheduleView.addObserver({
			update : function(eventName, eventData) {
				if(eventName == "detailView_Close_Click") {
					collapse();
				}
			}
		});

		var enrollView = new HD.REO.View.Enroll({
			parent : enrollEl,
			courseId : courseId,
			dealerId : dealerId
		}, this.model, this.view);
		
		openingsEl.onmouseover = function() {
			dom.show(tooltipEls[0]);
			courseEl.style.zIndex = "1";
		};
		
		openingsEl.onmouseout = function() {
			dom.hide(tooltipEls[0]);
			courseEl.style.zIndex = "0";
		};
		
		if(typeLinkEls.length > 0) {
			typeLinkEls[0].onmouseover = function() {
				dom.show(tooltipEls[1]);
				courseEl.style.zIndex = "1";
			};
			
			typeLinkEls[0].onmouseout = function() {
				dom.hide(tooltipEls[1]);
				courseEl.style.zIndex = "0";				
			};
		}
		
		//hide background
		var hideBkgd = document.getElementById("results");
		if(hideBkgd != null){
			hideBkgd.style.backgroundPosition = "0 -222px";			
		}	

	};
	
	
	HD.REO.View.Enroll.prototype.setListeners = function(data) {
		var reoClasses = HD.REO.View.CSS_CLASSES;
		var parentEl = this.getParent();
		var dom = HD.util.Dom;
		var enrollButtonEl = dom.getByClass("hdButton", "div", parentEl)[0];
		
		var modelCb = this.model;
		var cb = this;
		enrollButtonEl.onclick = function() {			
			if(cb.openingType == reoClasses.FULL) {
				return false;
			} else if(cb.openingType == reoClasses.OPEN || cb.openingType == reoClasses.WAITLIST) {
				var common = HD.util.Common;
				if(common.hasValue(data.disclaimer) && data.type == 1) {
					HD.util.Analytics.track(HD.REO.analytics.getStandardProgramNotice(HD.REO.experienceLevel));
					var disclaimer = data.disclaimer.replace(/&apos;/g,"'");
					common.showOverlay(HD.REO.View.Enroll.template.getDisclaimerText(disclaimer), null, "500px", "300px");
					var textHeight = YAHOO.util.Dom.getElementsByClassName("hdDisclaimerText")[0];
					var newOverlayHeight = textHeight.offsetHeight + 115;
					YAHOO.util.Dom.setStyle("hdwcOverlay", "height", newOverlayHeight+"px");
					var buttonYesEl = HD.util.Dom.getByClass("hdButtonYes", "div")[0];
					var buttonNoEl = HD.util.Dom.getByClass("hdButtonNo", "div")[0];
					buttonYesEl.onclick = function() {
						HD.util.Analytics.track(HD.REO.analytics.getStandardProgramNoticeContinueAction(HD.REO.experienceLevel, "Yes"));
						modelCb.setSelectedCourse.call(modelCb, data);
					};
					buttonNoEl.onclick = function() {
						HD.util.Analytics.track(HD.REO.analytics.getStandardProgramNoticeContinueAction(HD.REO.experienceLevel, "No"));
						common.hideOverlay();
					};
					buttonYesEl.onmouseover = function(){
						buttonYesEl.style.backgroundPosition = "0 -22px";
					};
					buttonYesEl.onmouseout = function(){
						buttonYesEl.style.backgroundPosition = "0 0";
					};
					buttonNoEl.onmouseover = function(){
						buttonNoEl.style.backgroundPosition = "0 -22px";
					};
					buttonNoEl.onmouseout = function(){
						buttonNoEl.style.backgroundPosition = "0 0";
					};						
					return false;
				}
				modelCb.setSelectedCourse.call(modelCb, data);
			}
		};
		
		enrollButtonEl.onmouseover = function(){
			enrollButtonEl.style.backgroundPosition = "0 -22px";
		};
		
		enrollButtonEl.onmouseout = function(){
			enrollButtonEl.style.backgroundPosition = "0 0";
		};
	};
	
	
	HD.REO.View.Search.prototype.handleSearchFinish = function(data) {
		var template = HD.REO.View.Search.template;
		
		var dealer = null;
		if(data.courses.length > 0 && this.dealer != null){
			dealer = data.courses[0].dealer;
		}
		
		var message = template.getCourseResultsMessage(this.lastRequest, data, dealer, this.dealer != null);
		this.setMessage(message);
		
		var dom = HD.util.Dom;
		var common = HD.util.Common;
		var parentEl = this.getParent();
		var messageEl = dom.get(this.config.message);
		var msfEls = dom.getByClass("msfCourse", "a", messageEl);
		if(msfEls.length > 0) {
			msfEls[0].onclick = function() {
				HD.util.Analytics.track(HD.REO.analytics.getMsfLink(HD.REO.experienceLevel));
				window.open("http://www.msf-usa.org/");
			};
		}

		if(data.errors.length > 0) {
			this.view.notifyObservers("searchView_Validation_Error");
		}
		
		if(data.showMsf) {
			if(dealer != null) {
				dom.get("reoList").innerHTML = "";
			}
			else {
				this.view.addClass(HD.REO.View.CSS_CLASSES.MSF_VIEW);
				
				var msfBtn = document.getElementById("msfCourse");
				
				if(msfBtn != null){
					msfBtn.onmouseover = function(){
						msfBtn.style.backgroundPosition = "0 -22px";
					};
					msfBtn.onmouseout = function(){
						msfBtn.style.backgroundPosition = "0 0";
					};
					var controlHdr = YAHOO.util.Dom.getElementsByClassName("hdControlHeader");
					if(controlHdr.length > 0){
						controlHdr[0].style.border = "none";
						controlHdr[0].style.padding = "0";
					}
					var det = YAHOO.util.Dom.getElementsByClassName("hdDetails");
					if(det.length > 0){
						for (var j = 0; j < det.length; j++){
							det[j].style.overflow = "hidden";
						}
					}
				}
			}
		} else {
			this.view.removeClass(HD.REO.View.CSS_CLASSES.MSF_VIEW);
		}
		
		if(data.radiusExpanded || data.numOfDaysExpanded) {
			if(data.radiusExpanded) {
				HD.util.Dom.setValue("radius", "100");
			}
			if(data.numOfDaysExpanded) {
				HD.util.Dom.setValue("numOfDays", "-1");
			}
			this.persistSearchParams();
		}
		
		var returnToDealerEls = dom.getByClass("hdReturnToDealer", "a", parentEl);
		if(data.courses.length > 0 && returnToDealerEls.length > 0) {
			var hrefEl = returnToDealerEls[0];
			var dealer = data.courses[0].dealer;
			var dealerLink = template.getDealerLink(dealer, this.dealerReturnUrl);
			if(dealerLink == null){
				dom.hide(hrefEl);
			}else{
				var dealerLinkName = template.getDealerLinkName(dealer);
				hrefEl.href = dealerLink;
				hrefEl.innerHTML = dealerLinkName;
				SessionService.setAttributes({dealerLink : dealerLink, dealerLinkName : dealerLinkName});
			}
		}

	};
	
	HD.REO.View.Search.template.getMsfMessage = function() {
		return ['<div class="hdSuggestion hdMessage">' ,
					'<h3>', this.message.msf ,'</h3><br/>' ,
					'<p>', this.suggestions.msf ,'</p>' ,
					this.suggestions.msfLink ,
				'</div>'].join('');
	};
	
	HD.REO.View.Search.template.nearbyStatesTooltip = 'Each state has different rules about motorcycle licenses and training.  It may be in your best interest to take a class in the state you are licensed to drive.  Please contact your state\'s DMV to find out more about completing a course out-of-state.';
	
	
	HD.REO.View.Enroll.template.disclaimer = 	'<div class="hdDisclaimer">'+
						'<div class="dblRuleBtm">' +
						'<div class="head">PLEASE NOTE</div>'+
						'</div>' +
						'<div class="hdDisclaimerText">_DISCLAIMER</div>'+
						'<div class="hdDisclaimerControl">'+
							'<div class="btnOrange hdButtonYes">Yes</div><div class="btnDarkGrey hdButtonNo">No</div>'+ 
						'</div>'+
					'</div>';
					

	HD.REO.View.Search.template.otherDealers ='<div class="hdSuggestion hdMessage" id="reo_msfMessageBottom"><h3>Or, we invite you to reach out to the Rider\'s Edge Program Manager at any of these participating Harley-Davidson dealerships to talk more about learning to ride.</h3></div>';



HD.REO.View.List.prototype.getHtml = function(data) {
    	var classes = HD.CSS_CLASSES;
    	var reoClasses = HD.REO.View.CSS_CLASSES;
    	var template = HD.REO.View.List.template;
    	
    	var courses = data.courses;
    	
    	if(courses == null || courses.length < 1) {
    		return "";
    	}
    	
    	var firstIndex = 1 + ((data.pageNumber - 1) * data.pageSize);
    	var lastIndex = firstIndex - 1 + data.pageSize;
    	
    	if(lastIndex > data.totalItems) {
    		lastIndex = data.totalItems;
    	}
    	
    	var html = ['<div class="', classes.WIDGET, ' ', reoClasses.LIST ,'">',
    	            	'<div class="hdControlHeader">',
					    	'<div class="showing">', template.getShowingNumbers(firstIndex, lastIndex, data.totalItems), '</div>',
					    	'<div class="hdListSort">',
					    		'<span>',
						    		'<select id="hdSort" name="hdSort" class="hdSort">',
						    			'<option value="', HD.REO.template.sortByDate, '" ', (this.sortType == HD.REO.template.sortByDate ? ' selected' : ''), '>Sort By Date</option>',
						    			'<option value="', HD.REO.template.sortByDistance, '" ', (this.sortType == HD.REO.template.sortByDistance ? ' selected' : ''), '>Sort By Distance</option>',
						    		'</select> ',
						    	'</span>',
						    	'<div>&nbsp;</div>',
					    	'</div>',
					    	'<div class="hdNumOfItems">', template.getViewSomeViewAll(data.pageSize, data.totalItems, this.viewAll), '</div>',
					    	'<div class="hdPaging">&nbsp;</div>',
    	            	'</div>'];

    	for ( var i = 0, len = courses.length; i < len; i++) {
			var course = courses[i];
			var dealer = course.dealer;
			var address = dealer.address;
			var phone = dealer.phone;
			var schedule = course.schedule;
			var classDays = [];
			
			if(schedule != null && schedule.classes != null) {
				for(var j = 0, len1 = schedule.classes.length; j < len1; j++) {
					classDays.push(schedule.classes[j].startTime);
				}
			}
			
			var openingClass = reoClasses.FULL;
			var openingText = "Full";
			var openTooltip = template.getFullClassTooltip();
			if(course.openSeats > 0) {
				openingClass = reoClasses.OPEN;
				openingText = "Open";
				openTooltip = template.getOpenClassTooltip(course.openSeats, course.totalSeats);
			} else if(course.waitlistSeats > 0) {
				openingClass = reoClasses.WAITLIST;
				openingText = "Waitlist";
				openTooltip = template.getWaitlistClassTooltip(course.waitlistSeats, course.totalWaitlistSeats);
			}
			
			var typeTooltip = template.getCourseSubTypeInfo(course.subType);
			
			html.push([
				'<div class="hdItem hdCollapsed">',
					'<div class="hdTooltip hdEnrollTooltip hdHidden">',
						openTooltip,
					'</div>',
					'<div class="hdTooltip hdTypeTooltip hdHidden">',
						typeTooltip,
					'</div>',
					'<div class="hdSummary">',
						'<div class="expnd">',
							'<div class="hdExpand">&nbsp;</div>',
							'<div class="hdCollapse">&nbsp;</div>',
						'</div>',
						'<div class="rsltDate">',
							'<span class="clssDates">', HD.util.Date.formatSpan(course.startDate, course.endDate) ,'</span>',
							'<span class="clssDays">', HD.util.Date.formatDaySpan(classDays, 'ddd', ', ') ,'</span>',
						'</div>',
						'<div class="rsltLoc">',
							'<span class="locName">', dealer.name, '</span>',
							'<span class="locCity">', address.city, ', ', address.state, '</span>',
						'</div>',
						'<div class="hdDistance"><span>', Math.round(course.distance), ' mi.</span><div>&nbsp;</div></div>',
						'<div class="hdType">',
							, (course.subType > 0 ? '<span class="hdLink">'+HD.REO.template.courseSubTypesLabels[course.subType]+'</span>':'&nbsp;') , 
						'</div>',
						'<div class="hdCourseOpenings">',
							'<span class="hdOpenings ', openingClass ,'">&nbsp;</span><span class="statWrd">', openingText, '</span>',
						'</div>',
					'</div>',
					'<div class="hdDetails">',
						'<div class="hdSchedule">...</div>',
						'<div class="hdContact"><h4>Address & contact Info</h4>',
							template.getDealerContact(dealer), 
							'<span class="hdDistance"><span>', Math.round(course.distance), ' mi.</span><div>&nbsp;</div></span>',
						'</div>',
						'<div class="hdEnroll">...</div>',
					'</div>',
				'</div>'].join(''));
		}
    	
    	html.push(	['<div class="hdControlFooter">',
				    	'<div class="hdToTop">Back to Top</div>',
				    	'<div class="hdPaging">&nbsp;</div>',
				    '</div>'].join(''));
    	
    	html.push('</div>');
    	
    	return html.join('');
	};

	HD.REO.template.courseSubTypesLabels = [
		null,
		"Women's Only",
		"Spanish"
	];
	
	HD.REO.View.Search.template.getDealerLinkName = function(dealer) {
		return "Back to " + (dealer != null ? dealer.name : "dealer");
	};
	
	HD.REO.View.Search.template.message.msf = "";
	HD.REO.View.Search.template.suggestions.msf = "Rider's Edge<span id='reo_super'>&reg;</span> courses are not yet available in the search area you selected. Select the link below to be redirected to the Motorcycle Safety Foundations<span id='reo_super'>&reg;</span> (MSF) website where you may locate a motorcycle training provider.";
	HD.REO.View.Search.template.noReStates = "";

