var comSvcBaseUrl = "/Community/services";
var comMediaBaseUrl = "/Community/media";
var comSiteName = "Dark Custom";
var comSiteSection = "Bikes";
var comPageUrl = "bikes.html";

var login = null;

var DarkCustom = (function() {
	// Base configuration.
	var itemsX = 4;
	var itemsY = 1;
	var startIndex = 1;
	var classes = HD.CSS_CLASSES;
	var dateFormat = "d mmm yyyy 'at' hh:MM tt";
	var services = HD.ShareWidget.SERVICES;
	var loadingHtml = '<div class="' + classes.LOADING + '"></div>';

	return {
		// #darkCustom (the parent container).
		containerEl: null,
		// #galleryContent
		galleryEl: null,
		// Categories config.
		categories: [],
		// Whether a deep link is active.
		isDeepLink: false,
		// Whether an overlay is active.
		isOverlayOpen: false,
		// Whether a media request is active.
		isRequestActive: false,
		// Whether this is the initial load.
		isInitialLoad: true,
		// Whether to check the user prior to submitting comments.
		requiresLogin: true,
		// Analytics settings.
		thisBike: {},
		analytics: {
			section: 'BikesPromo'
		},
		
		// Initialize the page.
		init: function() {

			var self = this;
		
			// Preselect common elements.
			this.containerEl = HD.get('darkCustom');
			this.galleryEl = HD.get('galleryContent');
			
			this.categories = this.thisBike.category;
			
			// Update config.
			this.config.main.dao.categories = this.thisBike.category;
			this.config.main.widgets.upload.categories = this.thisBike.category;
			this.config.main.dao.categoriesFriendly = this.config.main.widgets.upload.categoriesFriendly = this.thisBike.categoryFriendly;
			this.config.main.widgets.gallery.photoTemplates = this.templates.gallery.photoTemplates;
			this.config.main.widgets.gallery.videoTemplates = this.templates.gallery.videoTemplates;

			// Initialize the session.
			HD.util.DWR.initSession();
			HD.util.DWR.setErrorHandler();
			login = HD.Profile.profile;

			//Override copy		
			HD.UploadWidget.templates.overlayHtml = this.templates.upload.uploadTemplates.overlayHtml;
			HD.SendFriendWidget.templates.sendFriendInstructionalText = this.templates.sendFriend.sendFriendTemplates.sendFriendInstructionalText;
			HD.community.Video.templates.authorLabel = HD.community.Photo.templates.authorLabel = "By&nbsp;";
			HD.community.Video.templates.dateLabel = HD.community.Photo.templates.dateLabel = "Posted&nbsp;";
			HD.util.StarRating.templates.rateThisLabel = "YOUR RATING:&nbsp;";
			HD.util.StarRating.templates.yourRatingLabel = 'YOUR RATING:&nbsp;';
			HD.util.StarRating.templates.ratingLabel     = 'AVG. RATING:&nbsp;';
			HD.GalleryWidget.templates.html = this.templates.gallery.html;
			HD.CarouselWidget.templates.bikeID = this.thisBike.bikeID;
			HD.CarouselWidget.templates.bikeURL = '/en_US/Motorcycles/${bikeID}.html';
			HD.CarouselWidget.templates.getBikeURL = function(bikeID) {
				return HD.CarouselWidget.templates.bikeURL.replace(/\$\{bikeID\}/, bikeID);
			};
			HD.CarouselWidget.templates.paymentURL = '/en_US/Content/Pages/2012-Motorcycles/estimate-payments.html?modelCode=${bikeCode}';
			HD.CarouselWidget.templates.testRideURL = '/en_US/Content/Pages/Try_a_Bike/Schedule_a_Test_Ride.html?bikeModel=${bikeCode}';
			HD.CarouselWidget.templates.getLinkURL = function(bikeID,returnValue) {
	            var bikeCode = "";
	            if (bikeID == "iron-883") {
	                bikeCode = 'xl883n';
	            } else if (bikeID == "nightster") {
	                bikeCode = 'xl1200n';                                                                     
	            } else if (bikeID == "street-bob") {
	                bikeCode = 'fxdb';                                                                           
	            } else if (bikeID == "cross-bones") {
	                bikeCode = 'flstsb';                                                                          
	            } else if (bikeID == "fat-bob") {
	                bikeCode = 'fxdf';                                                                            
	            } else if (bikeID == "forty-eight") {
	                bikeCode = 'xl1200x';                                                                      
	            } else if (bikeID == "blackline") {
	                bikeCode = 'fxs';                                                                      
	            } else if (bikeID == "seventy-two") {
                    bikeCode = 'xl1200v';                                                                      
	            }
	            if(returnValue == 'payment') {
	            	return HD.CarouselWidget.templates.paymentURL.replace(/\$\{bikeCode\}/, bikeCode);
	            } else {
	            	return HD.CarouselWidget.templates.testRideURL.replace(/\$\{bikeCode\}/, bikeCode);	            	
	            }
			};
			HD.CarouselWidget.templates.facebookLike = '<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.harley-davidson.com%2Fen_US%2FContent%2FPages%2Fdark-custom%2F${bikeID}.html&amp;layout=standard&amp;show_faces=false&amp;width=430&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:430px;" allowTransparency="true"></iframe>';
			HD.CarouselWidget.templates.getFacebookLike = function(bikeID) {
				return HD.CarouselWidget.templates.facebookLike.replace(/\$\{bikeID\}/, bikeID);
			};
			HD.CarouselWidget.templates.html = '\
				{macro thumbs(isCompact)}\
					{if !isCompact}\
					<div class="${hooks.SCROLL_LEFT}" id="topscroll-left">${templates.getScrollLeftText()}</div>\
					<div class="${hooks.SCROLL_RIGHT}" id="topscroll-right">${templates.getScrollRightText()}</div>\
					<div class="${classes.CAROUSEL}-scroller">\
						<div class="${hooks.SCROLL_LEFT}">${templates.getScrollLeftText()}</div>\
						<div class="${hooks.SCROLL_CONTAINER}">\
					{/if}\
						<ul class="${hooks.THUMBS_CONTAINER}">\
							{for item in items}\
								<li class="${hooks.THUMB}{if item_index==0}${" "}${classes.CAROUSEL}-active{/if}">\
										${item|facade}\
								</li>\
							{/for}\
						</ul>\
					{if !isCompact}\
						</div>\
						<div class="${hooks.SCROLL_RIGHT}">${templates.getScrollRightText()}</div>\
					</div>\
					{/if}\
				{/macro}\
				<div class="${classes.CAROUSEL} ${classes.CAROUSEL}-{if config.compact}compact{else}full{/if} ${classes.WIDGET}">\
					{if config.compact}${thumbs(config.compact)}{/if}\
					<ul class="${hooks.ITEMS_CONTAINER}">\
						{for item in items}\
							<li class="${hooks.ITEM}{if item_index==0}${" "}${classes.CAROUSEL}-active{/if}">\
								${item|facade}\
							</li>\
						{/for}\
					</ul>\
					{if !config.compact}${thumbs(config.compact)}{/if}\
				</div>\
				<div class="bikes-carousel-links-top">\
					<a href="${templates.getBikeURL(templates.bikeID)}" class="seeMoreBtn">See More at H-D.com</a>\
					${templates.getFacebookLike(templates.bikeID)}\
				</div>\
				<div class="bikes-carousel-links">\
					<ul>\
						<li><a href="http://www.harley-davidson.com/wcm/Content/Pages/Get_On_A_Bike/Learn_To_Ride/learn_to_ride.jsp?locale=en_US&amp;bmLocale=en_US">Learn To Ride <img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/blue_Bullet.png" alt="" /></a></li>\
						<li><a href="${templates.getLinkURL(templates.bikeID,\'testRide\')}">Schedule a Test Ride <img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/blue_Bullet.png" alt="" /></a></li>\
						<li><a href="${templates.getLinkURL(templates.bikeID,\'payment\')}">Estimate Payments <img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/blue_Bullet.png" alt="" /></a></li>\
						<li><a href="javascript:void(0)" onclick="javascript:DC.util.launchDealerLocatorPopup();">Locate a Dealer <img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/blue_locator_icon.png" alt="" /></a></li>\
					</ul>\
				</div>';

			// Preload the data
			this.config.main.dao.preloadedMedia = this.preloadedMedia || null;
	
			// Initialize the main engine.
			this.engine = new HD.CommunityEngine(this.config.main);
			this.carouselEngine = new HD.CommunityEngine(this.config.carousel);
			
			// Attach widget observers.
			this.setObservers();

			// Attach DOM event listeners.
			this.setListeners();

			// Set global templates.
			this.setTemplates();
	
			// Set analytics
			if (this.setAnalytics) {
				this.setAnalytics();
			}
			
			// Create the object to be shared here
			var sharedItem = {
					author : "Dark Custom",
					category : this.thisBike.name,
					description : 'Dark Custom | Bikes | ' + this.thisBike.name,
					thumbUrl : '',
					title : 'Dark Custom | Bikes | ' + this.thisBike.name
			};
						
			// Initialize the navigation.
			this.initNavigation();
	
			// Get media.
			setTimeout(function getMedia() {
				if (self.getNavigation() ) {
					self.engine.dao.notifyObservers.call(self.engine.dao, "loadShare_Start", sharedItem);
					self.engine.dao.notifyObservers.call(self.engine.dao, "loadSTAF_Start", sharedItem);
					self.engine.dao.getMedia(startIndex, null, true);
					self.carouselEngine.dao.getMedia(1);
				}
				else {
					setTimeout(getMedia, 50);
				}
			}, 50);
	
		},
		
		// Engine/widget config.
			
		// Engine/widget config.
		config: {
			main: {
				dao: {
					baseUrl : comSvcBaseUrl,
					siteName : comSiteName,
					contentType : 'both',
					categories : [],
					startIndex : startIndex,
					pageSize : itemsX * itemsY,
					thumbWidth : 160,
					mediaWidth : 420
				},
				cluster: {
					baseUrl : comMediaBaseUrl
				},
				view: {
					navigation : 'nav',
					canvas : 'canvas'
				},
				widgets: {
					gallery: { 
						parent: 'galleryContent', 
						type: 'hd_gallery_widget',
						itemsX : itemsX, 
						itemsY : itemsY, 
						contentType : 'both',
						titleLength : 18,
						previewLength : 500, 
						dateFormat : dateFormat,
						isShowPopups : true,
						requiresRatingLogin: false,				
						sorts: [
					        {value: HD.SORTS.NEW_TO_OLD,name:'View by date',isDefault: true},
					        {value: HD.SORTS.HIGHEST_RATED,name:'View by rating',isDefault: false},
					        {value: HD.SORTS.MOST_COMMENTED,name:'View by comment count',isDefault: false}
				        ]	
					},					
					upload: {
						type: 'hd_upload_widget',
						siteName: comSiteName,
						siteSection: comSiteSection,
						contentType :'both',
						title :'Upload',
						dialog: {
							confirm: ['580px','210px']
						}
					},
					share: {
						parent: 'share',
						type: 'hd_share_widget',
						getPermalink: function(media) {
							return window.location.href;
						},
						services: [services.FACEBOOK, services.TWITTER, services.MYSPACE, services.BLOGGER, services.WORDPRESS],
						callback: function(service, title, description, thumbnail, permalink) {
							
						},
						standaloneMode : true
					},
					sendFriend: HD.merge({
						parent: 'sendFriend',
						type: 'hd_send_friend_widget',
						standaloneMode : true
					}, sendFriendConfig)
				}
			},
			carousel: {
				dao: {
					baseUrl : comSvcBaseUrl,
					siteName : comSiteName,
					contentType : 'both',
					categories : ['Dark Custom'],
					preloadedMedia: {
						getMedia: function() {
							var populateMedia = function(media) {
								// Add dummy properties to each object.
								var dummy = {
									author: '', authorId: '', category: 'Dark Custom', city: '', comments: null, contentType: 'photo',
									country: null, currentUserRating: 0, description: 'Art of Rebellion',
									hiddenAuthor: true, index: 0, mediaId: '', numberOfComments: 0, numberOfViews: 0, rating: 1, state: '', 
									tags: null, thumbUrl: '', title: '', uploadedDate: new Date, url: '', viewUrl: '', zip: ''
								};
								var urlPrefix = '/en_US/Media/images/Content/Pictorial/dark_custom_v3/bikes/';
								for (var i = 0; i < media.length; i++) {
									media[i] = HD.merge(HD.clone(dummy), media[i]);
									media[i].index = i + 1;
									media[i].thumbUrl = urlPrefix + media[i].thumbUrl;
									if (media[i].contentType == 'photo') {
										media[i].url = urlPrefix + media[i].url;
									}
									else if (media[i].contentType == 'video') {
										media[i].url = HD.util.Common.getServerUrl() + media[i].url;
										media[i].largeThumbUrl = HD.util.Common.getServerUrl() + urlPrefix + media[i].largeThumbUrl;
										media[i].viewUrl = media[i].url;
									}
								}
								return media;
							};
							return {
								contentType: 'both',
								errors: [],
								media: populateMedia(self.thisBike.media),
								pageNumber: 1,
								pageSize: self.thisBike.media.length,
								profile: null,
								success: true,
								tags: null,
								totalMedia: self.thisBike.media.length,
								totalPages: 1
							};
						}
					}
				},
				cluster: {
					baseUrl : comMediaBaseUrl
				},
				view: {
					navigation : 'nav',
					canvas : 'canvas'
				},
				widgets: {
					carousel: {
						parent: 'carousel',
						type: 'hd_carousel_widget',
						compact: false,
						pageSize: 7,
						playerHeight: 429,
						playerWidth: 604,
						scrollDirection: 'vertical'
					}
				}
			}
		},
		
		// Attach observer methods to widgets.
		setObservers: function() {
			var self = this;
			
			// Attach dao/view observer.
			this.engine.addObserver({
				widgets: ['dao', 'view'],
				update: function(eventName, eventData) {
					if (eventName == "getMedia_Start") {
						// Show loading animation.
						var galleryPanelEl = HD.getByClass(classes.CONTENT_PANEL, '*', self.galleryEl)[0] || self.galleryEl;
						galleryPanelEl.innerHTML = loadingHtml;
					}
					else if (eventName == "getMedia_Finish" && self.isInitialLoad) {
						self.isInitialLoad = false;
					}
					else if (eventName == 'videoPlayed'){
						DarkCustom.carouselEngine.widgets.carousel.clearQueue();
					}
				}
			});
			
			// Disable video players when overlays are opened.
		    this.engine.addObserver({
				widgets: [HD.util.Common.getObservable()],
		        update: function(eventName, eventData) {	    	
			    	if (eventName == "overlayClose") {
			    		if (jwplayer()){
			    			jwplayer().stop();
			    		}
					}
		        }
		    });
			
			// Attach gallery observer.
			this.engine.addObserver({
				widgets: ['gallery'],
				update: function(eventName, eventData) {
					if (eventName == "itemSelected" || eventName == "itemChange_Start") {
						HD.util.Player.View.stopAll();
						
						// Update navigation.
						window.location.href = 'bikes-gallery.html#loc=detail/'+eventData.contentType+'/'+eventData.mediaId;
					}	
				}
			});
						
			
			// Disable video players when overlays are opened.
		    this.engine.addObserver({
				widgets: [HD.util.Common.getObservable()],
		        update: function(eventName, eventData) {	    	
		    		if (eventName == "overlayOpen") {
						isOverlayOpen = true;
						HD.util.Player.View.stopAll();
			        }
					else if (eventName == "overlayClose") {
						setTimeout(function() {
							isOverlayOpen = false;
						}, 50);
					}
		        }
		    });
		},
		
		// Attach DOM event listeners.
		setListeners: function() {
			var self = this;
			
			// Submit a story.
			HD.getByClass('submitStory', 'a', this.containerEl, function(el) {
				el.onclick = function() {
					self.engine.widgets.upload.renderBoth('Select a category', self.thisBike.category,  self.thisBike.categoryFriendly);
				};
			});
			
		},
		
	
		// Get the current view.
		getView: function() {
			return this.containerEl.className;
		},
	
		// Set the current view.
		setView: function(view) {
			this.containerEl.className = view;
			HD.util.Player.View.stopAll();
		},
		
		// Set the navigation location (loading data as needed).
		setNavigation: function(view, type, id, skipHistory, hasMedia, category) {
			
			HD.util.Common.scrollToTop();
			if (view == 'gallery') {
				this.setView('gallery');
			}
			
			// Add history if necessary.
			var newView = view + '/' + type + '/' + id;
			var skipHistory = !!skipHistory || this.getNavigation(null, true) == newView;
			return !skipHistory && YAHOO.util.History.navigate('loc', newView);
		},
		
		// Retrieve the current navigation location.
		getNavigation: function(navState, asString) {
			try {
				var nav = (navState || YAHOO.util.History.getCurrentState('loc') || '').split('/');
				return !!asString ? nav.join('/') : { view: nav[0] || '', type: nav[1] || '', id: nav[2] || '' };
			}
			catch(e) {
				// History manager isn't ready yet.
				return false;
			}
		},
		
		// Initialize the history manager and load initial location.
		initNavigation: function() {
			var self = this;
			
			// Determine state.
			var state = YAHOO.util.History.getBookmarkedState('loc');
			if (state) {
				state = this.getNavigation(state);
			}
			
			state = { view: 'gallery', type: 'init', id: '0' };	
			
		
			// Initialize history object.
			YAHOO.util.History.register('loc', state.view+'/'+state.type+'/'+state.id, function(view) {
				var prevState = self.getNavigation(view);
				self.setNavigation(prevState.view, prevState.type, prevState.id, false);	
				
				return true;
			});
		
			// Initialize history elements.
		    try {
		        YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
		    } catch (e) {}
			this.setNavigation(state.view, state.type, state.id, true);
		},
		
		// Set custom templates.
		setTemplates: function() {
			// Custom templates as necessary.
		}
	};
})();

// Load the page.
var isLoggedIntoCommunity = false;
HD.Config.profile = {
		showSoftProfile: false,
		requireScreenName: true,
		cssFile: "/en_US/Media/css/dark_custom_v3/dark_custom_downloadsLogin.css",
		initCallback: function() {
		
			HD.Profile.profile.model.getUser(function(userResponse) {
				DarkCustom.init();
				
				var observer = {
					update : function(eventName, eventData) {
						if (eventName == HD.Profile.profile.model.getEventName('LOGGED_IN') || eventName == HD.Profile.profile.model.getEventName('SCREENNAME_CREATE_SUCCESSFUL')) {				
							if (!isLoggedIntoCommunity){
								UserService.getLoggedInStatus({ token: HD.Profile.token, siteName : comSiteName });
								isLoggedIntoCommunity = true;
							}
							var el = HD.get('hdLogin');
							HD.addClass(el, "hdLI");
							HD.removeClass(el, "hdNLI");
						} 
						else if (eventName == "notLogged_In") {
							var el = HD.get('hdLogin');
							HD.addClass(el, "hdNLI");
							HD.removeClass(el, "hdLI");
						}
					}
				};
				HD.util.Common.getObservable().addObserver(observer);
				HD.Profile.profile.model.addObserver(observer);
				
				HD.Profile.Content.AUTHENTICATE.contentURL = "/en_US/Content/Pages/dark-custom/authenticate.htm";
				HD.Profile.Content.REGISTER.contentURL = "/en_US/Content/Pages/dark-custom/create_profile.htm";
		
			});
		
		}
	};

