var comSvcBaseUrl = "/Community/services";
var comMediaBaseUrl = "/Community/media";
var comSiteName = "Dark Custom";
var comSiteSection = "Bikes";
var comPageUrl = "bikes-gallery.html";

var login = null;

var DarkCustom = (function() {
	// Base configuration.
	var itemsX = 5;
	var itemsY = 4;
	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>';
	siteCategories = ['Bikes/Fat Bob', 'Bikes/Iron 883', 'Bikes/Nightster', 'Bikes/Street Bob', 'Bikes/Forty-Eight', 'Bikes/Seventy-Two', 'Bikes/Blackline', 'Bikes/Other H-D bike'];
	siteCategoriesFriendly = ['Fat Bob', 'Iron 883', 'Nightster', 'Street Bob', 'Forty-Eight', 'Seventy-Two', 'Blackline' , 'Other H-D bike'];
	
	// See if a tag was passed in externally
	var externalCat = HD.util.Common.getRequestParam("bikeCategory");
	if (externalCat != null){
		externalCat = externalCat.replace(/\+/g, ' ');
	}
	
	return {
		// #darkCustom (the parent container).
		containerEl: null,
		// #galleryContent
		galleryEl: null,
		// #detailContent
		detailEl: null,
		// Categories config.
		categories: [],
		// Whether a deep link is active.
		isDeepLink: false,
		isDeepSideLink: 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.
		analytics: {
			section: 'Bikes'
		},
	
		// Initialize the page.
		init: function() {
			var self = this;
		
			// Preselect common elements.
			this.containerEl = HD.get('darkCustom');
			this.galleryEl = HD.get('galleryContent');
			this.detailEl = HD.get('detailContent');
			this.moreBikesEl = HD.get('moreBikes');
			
			
			// Update config.
			this.config.main.dao.categories = this.config.more.dao.categories = siteCategories;
			this.config.main.widgets.upload.categories = siteCategories;
			this.config.main.dao.categoriesFriendly = this.config.main.widgets.upload.categoriesFriendly = siteCategoriesFriendly;
			this.config.main.widgets.comments.requiresLogin = this.requiresLogin;
			this.config.main.widgets.detail.photoTemplates = this.templates.detail.photoTemplates;
			this.config.main.widgets.gallery.photoTemplates = this.templates.gallery.photoTemplates;
			this.config.main.widgets.detail.videoTemplates = this.templates.detail.videoTemplates;
			this.config.main.widgets.gallery.videoTemplates = this.templates.gallery.videoTemplates;
			this.config.more.widgets.moreBikes.photoTemplates = this.templates.gallery.photoTemplates;
			this.config.more.widgets.moreBikes.videoTemplates = this.templates.gallery.videoTemplates;
			this.config.more.widgets.moreBikes.templates = this.templates.moreBikes.templates;
			
			// Initialize the session.
			HD.util.DWR.initSession();
			HD.util.DWR.setErrorHandler();
			login = HD.Profile.profile;

			//Override copy
			HD.ERRORS.upload_title_displayname = 'Bike Title';
			HD.ERRORS.upload_story_displayname = 'Bike Description';
			HD.ERRORS.error_required = function(error) {
				// Modify the error object contextually.
				if (error.fieldName == 'title' && error.errorArguments && error.errorArguments[0] && error.errorArguments[0] == 'upload.title.displayname') {
					return 'You must enter an Bike Title.';
				} 
				else if (error.fieldName == 'story' && error.errorArguments && error.errorArguments[0] && error.errorArguments[0] == 'upload.story.displayname') {
					return 'You must enter an Bike Description.';
				}
				else if (error.fieldName == 'category' && error.errorArguments && error.errorArguments[0] && error.errorArguments[0] == 'upload.category.displayname') {
					return 'You must select a Category.';
				}
				return '{0}';
			};
			HD.UploadWidget.templates.overlayHtml = this.templates.upload.uploadTemplates.overlayHtml;
			HD.SendFriendWidget.templates.sendFriendInstructionalText = this.templates.sendFriend.sendFriendTemplates.sendFriendInstructionalText;
			HD.CommentsWidget.templates.titleSingleLabel = this.templates.comments.commentsTemplates.titleSingleLabel;
			HD.CommentsWidget.templates.titleMultiLabel = this.templates.comments.commentsTemplates.titleMultiLabel;
			HD.CommentsWidget.templates.termsConditionsText = this.templates.comments.commentsTemplates.termsConditionsText;
			HD.CommentsWidget.templates.getTitleLabel = function(numComments){
				if (numComments > 1){
					return this.titleMultiLabel.replace(/\$\{number\}/, numComments);
				}
				else{
					return this.titleSingleLabel.replace(/\$\{number\}/, numComments);
				}
			};
			
			HD.GalleryWidget.templates.html = '\
				<div class="${classes.GALLERY} ${classes.WIDGET}">\
					<div class="${classes.CONTROL_PANEL}">\
						<div class="${classes.SORT}">\
							<select class="${hooks.SORTING}">\
								{for sort in config.sorts}\
									{if selectedSort == sort.value || sort.isDefault}\
										<option value="${sort.value}" selected>${sort.name}</option>\
									{else}\
										<option value="${sort.value}">${sort.name}</option>\
									{/if}\
								{/for}\
							</select>\
						</div>\
						<span class="${hooks.PAGING}"></span>\
					</div>\
					<div class="${classes.CONTENT_PANEL}">\
						{var rows = Math.ceil(items.length / config.itemsX)}\
						<div class="${classes.FIRST} hdRow">\
						{for item in items}\
							{if item_index > 0 && item_index % config.itemsX == 0}\
								{if rows == (Math.ceil(item_index / config.itemsX) + 1)}\
									</div><div class="hdClear"></div><div class="${classes.LAST} hdRow">\
								{else}\
									</div><div class="hdClear"></div><div class="hdRow">\
								{/if}\
							{/if}\
							<div class="{if item_index % config.itemsX == 0}${classes.FIRST}{/if} hdItemWrapper">${item|facade}</div>\
							{/for}\
							<div class="hdClear"></div>\
						</div>\
					</div>\
					<div class="${classes.CONTROL_PANEL} ${classes.LAST}">\
						<span class="${hooks.PAGING}"></span>\
					</div>\
				</div>';
			
			HD.CommentsWidget.templates.html = '\
			{if comments}\
				{macro commentsForm()}\
					<li><form class="${hooks.FORM}">\
						<div class="${classes.TITLE}"><strong>${templates.getPostCommentLabel()}</strong></div>\
						<div class="${hooks.ERROR}"></div>\
						<div class="${classes.WRAPPER}">\
							<textarea cols="30" rows="5" class="${classes.VALUE} ${hooks.TEXTAREA}"></textarea><br/>\
							<div class="${classes.AGREEMENT}">\
								<div class="${classes.LABEL} ${hooks.LEGAL_SM}">\
									${templates.getTermsConditionsShortPreText()}\
								</div>\
							</div>\
							<input type="image" src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/DC_submit_btn.jpg" value="${templates.getSubmitLabel()}"/>\
						</div>\
					</form></li>\
					<li class="${classes.HIDDEN}">\
						<div class="${classes.CONFIRMATION} ${hooks.CONFIRMATION}">\
							<div class="${classes.LABEL}"><strong>${templates.getConfirmationLabel()}</strong></div>\
							<div class="${classes.VALUE}">${templates.getConfirmationValue()}</div>\
							<div class="hdSubmitComment hdSubmitAnotherComment ${hooks.SUBMIT_ANOTHER_COMMENT}">${templates.getSubmitAnotherText()}</div>\
						</div>\
					</li>\
				{/macro}\
				<div class="${classes.COMMENTS} ${classes.WIDGET}">\
					{if config.submitAbove}\
						${commentsForm()}\
					{/if}\
					{if comments.length > 0}\
						<div class="${classes.TITLE}">\
							<div class="${classes.LABEL}">${templates.getTitleLabel(comments.length)}</div>\
							<div class="hdSubmitComment" onclick="DarkCustom.focusComments();">Post a Comment</div>\
							<div class="hdClear"></div>\
						</div>\
						<ul>\
						{for comment in comments}\
							<li class="${classes.COMMENT}">\
								<div>\
									<span class="${classes.DATE}">${comment.createdDate|date}</span> \
									<span class="${classes.AUTHOR}">${comment.submittedBy}</span>\
								</div>\
								<div class="${classes.VALUE}">${comment.text}</div>\
							</li>\
						{/for}\
						</ul>\
					{else}\
						<ul>\
						<li class="${classes.EMPTY}">${templates.getNoCommentsText()}</li>\
						</ul>\
					{/if}\
				</div>\
				{if config.submitBelow}\
					${commentsForm()}\
				{/if}\
			{else}\
				${templates.getLoadingText()}\
			{/if}';
			HD.community.Video.templates.nextLabel = HD.community.Photo.templates.nextLabel = '<img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/spacer.gif" alt="NEXT" class="nextBtn" />';
			HD.community.Video.templates.previousLabel = HD.community.Photo.templates.previousLabel = '<img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/spacer.gif" alt="PREVIOUS" class="prevBtn" />';
			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.community.Video.templates.commentsTextFirst = HD.community.Photo.templates.commentsTextFirst = '<span class="hdCommentsButtonLink">Add The First Comment</span>';
			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.community.Video.templates.commentsButtonText = HD.community.Photo.templates.commentsButtonText = "Post Comment";
			HD.community.Video.templates.commentsText = HD.community.Photo.templates.commentsText ='<img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/DC_comment_icon.jpg" alt="" /> <span class="hdCommentsButtonLink">Comments</span> ({number})';
			HD.community.Video.templates.getCommentsButtonText = HD.community.Photo.templates.getCommentsButtonText = function(){
				return this.commentsButtonText;
			};

			// Preload the data
			this.config.main.dao.preloadedMedia = this.preloadedMedia || null;
	
			// Initialize the main engine.
			this.engine = new HD.CommunityEngine(this.config.main);
			this.engineMore = new HD.CommunityEngine(this.config.more);

			// 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 : "Dark Custom",
					description : 'Dark Custom | Bikes',
					thumbUrl : '',
					title : 'Dark Custom | Bikes'
			};
			

			
			// 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);
					
					// Set the tag if it exists
					if (externalCat != null){
						self.engine.dao.setCategories(['Bikes/'+externalCat], true);
					}
					self.engine.dao.getMedia(startIndex, null, true);
				}
				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 : 530
				},
				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}
				        ]	
					},
					detail: { 
						parent: 'detailContent', 
						type: 'hd_detail_widget', 
						contentType : 'both', 
						dateFormat : dateFormat,
						requiresRatingLogin: false,
						showYourRatingText: true,
						embedSendFriend: false,
						sendFriendConfig: sendFriendConfig /* dcUtil.js */,
						embedShare: false,
						shareConfig:{
							type: 'hd_share_widget',
							useShareAPI: true,
							services: [services.FACEBOOK, services.TWITTER, services.MYSPACE, services.BLOGGER, services.WORDPRESS],					
							previewLength: 140,		
							getPermalink: function(media, service, config) {						
								var params = null;
								if (media && media.mediaId && service && service == services.FACEBOOK) {
									var imageUrl = media.thumbUrl || '';
									// Grab the first image from blog posts.
									if (HD.community.isBlog(media.contentType) && media.description.match(/\<img.+?src=["'](.+?)["'].*?\>/)) {
										imageUrl = media.description.match(/\<img.+?src=["'](.+?)["'].*?\>/)[1] || imageUrl;
									}
									params = {
										title: media.title || '',
										description: HD.util.Common.ellipseText(HD.util.Common.stripHtmlTags(media.description || ''), (config && config.previewLength) || 140),
										image: imageUrl,
										loc: 'detail/' + media.contentType + '/' + media.mediaId
									};
								}	
								return media.facade.generatePermalink(params);
							}
						}
					},
					comments: {
						parent: 'comments', 
						type: 'hd_comments_widget', 
						contentType : 'both', 
						dateFormat : dateFormat,
						confirmation : true,
						submitBelow : false,
						submitAbove : true,
						requiresLogin : true,
						confirmation : false
					},
					upload: {
						type: 'hd_upload_widget',
						siteName: comSiteName,
						siteSection: comSiteSection,
						contentType :'both',
						title :'Upload',
						dialog: {
							confirm: ['580px','210px']
						},
						templates: {
							introText: 'Just pick the category, give it a title, and upload your bike.',
							uploadMediaLabel: 'Bike Title',
							descriptionLabel: 'Bike Description',
							descriptionInstructionText: 'Please describe your bike in 2500 characters or less.',
							uploadMediaTypeBothLabel: 'Photo OR Video of your bike.'
						}
					},
					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),
					chooseCategories: {
						parent: 'categories',
						type: 'hd_categories_widget',
						renderMode: 'select',
						items: [
							{ name: 'Show all bikes', categories: siteCategories },							
							{ name: 'Iron 883', categories: ['Bikes/Iron 883'] },
							{ name: 'Nightster', categories: ['Bikes/Nightster'] },
							{ name: 'Forty-Eight', categories: ['Bikes/Forty-Eight'] },
							{ name: 'Seventy-Two', categories: ['Bikes/Seventy-Two'] },
							{ name: 'Street Bob', categories: ['Bikes/Street Bob'] },
							{ name: 'Fat Bob', categories: ['Bikes/Fat Bob'] },
							{ name: 'Blackline', categories: ['Bikes/Blackline'] },
							{ name: 'Other H-D bike', categories: ['Bikes/Other H-D bike'] }
						]
					}
				}
			},
			more:{
				dao: {
					baseUrl : comSvcBaseUrl,
					siteName : comSiteName,
					contentType : 'both',
					startIndex : startIndex,
					pageSize : itemsX * itemsY,
					thumbWidth : 160,
					mediaWidth : 530,
					filters: { tags: 'bikes' }
				},
				cluster: {
					baseUrl : comMediaBaseUrl
				},
				view: {
					navigation : 'nav',
					canvas : 'canvas'
				},
				widgets: {
					moreBikes:{
						parent: 'moreBikes',
						type: 'hd_feature_stories_widget',
						contentType: 'both',
						pageSize: 3,
						previewLength: 0,
						contentFeed: 'getMedia',
						randomize: true,
						templates: {}
					}
				}
			}
		},
		
		// 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;
					}
				}
			});
		
			// Attach login observer.
			this.engine.addObserver({
				widgets: [login.model],
				update: function(eventName, eventData) {
			
		
						if (eventName == "logged_In") {

							var el = HD.get('detail');
							HD.addClass(el, "hdLI");
							HD.removeClass(el, "hdNLI");
						}
						else if (eventName == "notLogged_In") {
							var el = HD.get('detail');
							HD.addClass(el, "hdNLI");
							HD.removeClass(el, "hdLI");
						}
					
				}
			});
			
			// 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.
						self.setNavigation('detail', eventData.contentType, eventData.mediaId, null, !!eventData, eventData.category);
					}	
				}
			});
			
			// Attach detail observer.
			this.engine.addObserver({
				widgets: ['detail', 'dao'],
				update: function(eventName, eventData) {
				
					if (eventName == "activeItem_Change" && !self.isInitialLoad) {
						HD.util.Player.View.stopAll();
						
						// Update navigation.
						var view = self.getNavigation().view;
						if (view != 'gallery' && !self.isDeepLink) {
							self.setNavigation('detail', eventData.contentType, eventData.mediaId, null, !!eventData, eventData.category);
						}
					}
					else if (eventName == "getMedium_Start") {
						self.isRequestActive = true;
						
						// Show loading animation.
						self.detailEl.innerHTML = loadingHtml;
					}
					else if (eventName == "getMedium_Finish") {
						self.isRequestActive = false;
						self.isDeepLink = false;
						self.isDeepSideLink = false;
						self.showMedia({ mediaId: eventData.mediaId, contentType: eventData.contentType });
						
						// Update user submitted bikes and bike ad
						if(eventData.category != self.engineMore.dao.config.categories){
							self.moreBikesEl.innerHTML = loadingHtml;
							self.engineMore.dao.setCategories(eventData.category);
						}
						
					}
					else if (eventName == "getComments_Finish"){
						self.isRequestActive = false;
					}		
					else if (eventName == 'categories_Set') {
						
						self.engineMore.dao.setCategories(self.config.main.dao.categories);
					}
				}
			});
			
			// Attach gallery observer.
			this.engineMore.addObserver({
				widgets: ['moreBikes'],
				update: function(eventName, eventData) {

					if (eventName == 'viewFeatureStory')  {
						
						HD.util.Player.View.stopAll();
						self.isDeepSideLink = true;
						// Update navigation.
						self.setNavigation('detail', eventData.contentType, eventData.mediaId, null, false, eventData.category);
					}	
					else if (eventName == 'viewAllFeatureStories'){
						self.engine.dao.setCategories([self.config.more.dao.categories]);
						self.setNavigation('gallery', 'all', '0');
					}
				}
			});
			
		    // 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 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', siteCategories,  siteCategoriesFriendly);
				};
			});
			
			// Return to the gallery.
			HD.getByClass('viewGallery', 'a', this.containerEl, function(el) {
				el.onclick = function() {
					self.setNavigation('gallery', 'all', '0');
				};
			});
			
			// Return to the gallery.
			HD.getByClass('hdViewAll', 'div', this.containerEl, function(el) {
				el.onclick = function() {
					self.setNavigation('gallery', 'all', '0');
				};
			});
			
			// Submit a comment.
			HD.getByClass('hdSubmitComment', 'div', HD.get('detail'), function(el) {
				el.onclick = function() {
					self.focusComments();
				};
			});
		},
		
		// Show media detail.
		showMedia: function(eventData) {
			var self = this;
			// Switch to the detail view.
			this.setView('detail');
			
			// Set listener for comments link (delay to override hd_photo/hd_video hardcoded function).
			setTimeout(function() {
				HD.getByClass('hdCommentsButton', '*', self.detailEl, function(el) {
					el.onclick = function() {
						HD.get('comments').scrollIntoView();
					};
				});
				
				// Submit a comment.
				HD.getByClass('hdSubmitComment', '*', self.detailEl, function(el) {
					el.onclick = function() {
						self.focusComments();
					};
				});
			}, 50);
		},
	
		// 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');
			}
			else if (view == 'detail') {
				var self = this;
				
				// Request the detailed media data (unless a request is active).
				self.showMedia({ mediaId: id, contentType: type });
				if (!this.isRequestActive) {
					this.isRequestActive = true;
					if (!hasMedia) {
						if(self.isDeepSideLink || self.isDeepLink){
							this.engine.dao.getMedium(id, function() {}, type);
						}
						
					}
					else{
						// Update the user submitted bikes and bike ad
						if(category != this.engineMore.dao.config.categories){
							self.moreBikesEl.innerHTML = loadingHtml;
							self.engineMore.dao.setCategories(category);
						}
					}
					this.engine.dao.getComments(id, type);
					
				}
			}
			// 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);
			}
			if (state && state.view == 'detail') {
				this.isDeepLink = true;
			}
			else {
				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.
		},
		
		// Focus the comments form.
		focusComments: function() {
			if (HD.hasClass(HD.get('detail'), 'hdLI')) {
				HD.get('comments').scrollIntoView();
			}
			else {
				login.model.isUserLoggedIn(function(userResponse) {
					
					if(userResponse.loggedInLevel > 0){
						login.view.promptCreateScreenName();
					}
					else{
						login.view.promptAuthentication();
					}
					
				});
			}
		}
	};
})();

// 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";
		
			});
		
		}
	};

