var comSvcBaseUrl = "/Community/services";
var comMediaBaseUrl = "/Community/media";
var comSiteName = "Dark Custom";
var comPageUrl = "blog.html";

var login = null;

var DarkCustom = (function() {
	// Base configuration.
	var itemsX = 1;
	var itemsY = 8;
	var startIndex = 1;
	var classes = HD.CSS_CLASSES;
	var dateFormat = "ddd, d mmm yyyy";
	var services = HD.ShareWidget.SERVICES;
	var loadingHtml = '<div class="' + classes.LOADING + '"></div>';
	var siteCategories = ['Dark Custom'];
	
	// See if a tag was passed in externally
	var externalTag = HD.util.Common.getRequestParam("tag");
	if (externalTag != null){
		externalTag = externalTag.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,
		// 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: 'Blog'
		},

		// Initialize the page.
		init: function() {
			
			YAHOO.util.Dom.addClass('body','yui-skin-sam');

		
			var self = this;
			this.editorsChoiceTag = "editor's pick";
		
			// Preselect common elements.
			this.containerEl = HD.get('darkCustom');
			this.galleryEl = HD.get('galleryContent');
			this.detailEl = HD.get('detailContent');
			this.featuredEl = HD.get('blogFeatured');
			this.editorsChoiceEl = HD.get('blogEditors');
			this.memberProfileEl = HD.get('memberProfile');
			
			// Update config.
			this.config.dao.categories = this.configFeatured.dao.categories = siteCategories;
			this.config.widgets.comments.requiresLogin = this.requiresLogin;
			this.config.widgets.detail.blogTemplates = this.templates.detail.blogTemplates;
			this.config.widgets.gallery.blogTemplates = this.templates.gallery.blogTemplates;
			this.configFeatured.widgets.featuredPosts.blogTemplates = this.templates.featuredPosts.blogTemplates;
			this.configVideo.widgets.carousel.blogTemplates = this.templates.carousel.blogTemplates;

			// Initialize the session.
			HD.util.DWR.initSession();
			HD.util.DWR.setErrorHandler();
			login = new HD.Login({siteName : comSiteName});
			login.model.init(function() {
				login.model.getUser();
			});
			
			// Override copy
			HD.TagCloudWidget.templates.moreTagsLabel = 'More Tags&nbsp;<img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/icon_next.gif">';
			HD.TagCloudWidget.templates.lessTagsLabel = 'Less Tags&nbsp;<img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/icon_next.gif">';
			HD.SendFriendWidget.templates.sendFriendInstructionalText = this.templates.sendFriend.sendFriendTemplates.sendFriendInstructionalText;
			HD.CarouselWidget.templates.carouselLabel = '<h5><img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/hdr_latest_videos.gif" height="19" width="147" alt="LATEST VIDEOS" title="LATEST VIDEOS" /></h5>';
			HD.CarouselWidget.templates.viewAllText = 'More Videos&nbsp;<img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/icon_next.gif">';
			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.community.Blog.templates.moreText = '<img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/btn-read-more.gif">';
			HD.CommentsWidget.templates.getTitleLabel = function(numComments){
				if (numComments > 1){
					return this.titleMultiLabel.replace(/\$\{number\}/, numComments);
				}
				else{
					return this.titleSingleLabel.replace(/\$\{number\}/, numComments);
				}
			};
			//TODO: Figure out why the below <li> elements are necessary
			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/btn_submit.gif" 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}\
					</ul>\
				</div>\
				{if config.submitBelow}\
					${commentsForm()}\
				{/if}\
			{else}\
				${templates.getLoadingText()}\
			{/if}';
			
			HD.community.Blog.templates.authorLabel = "by&nbsp;";
			HD.community.Blog.templates.commentsButtonText = "Post Comment";
			HD.community.Blog.templates.commentsText = '<img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/comment_bubble.gif" alt="" /> <span class="hdCommentsButtonLink">Comments</span> ({number})';
			HD.community.Blog.templates.averageVotesText = "${num_of_votes}&nbsp;ratings&nbsp;|&nbsp;${text_rating}&nbsp;stars",
			HD.community.Blog.templates.getCommentsButtonText = function(){
				return this.commentsButtonText;
			};
			HD.ContextWidget.templates.backText = '<img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/btn_back_blog.gif" alt="BACK TO BLOG" />';
			HD.community.Blog.templates.nextLabel = '<img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/btn_next.gif" alt="NEXT" />';
			HD.community.Blog.templates.previousLabel = '<img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/btn_previous.gif" alt="PREVIOUS" />';
			HD.community.Blog.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.TagCloudWidget.templates.html =  '\
					<div class="${classes.TAG_CLOUD} ${classes.WIDGET} ${thresholdClasses} ${hooks.CLOUD}">\
					{for tag in tags}\
						{if tag_index} {/if}\
						<span class="${classes.TAG} ${activeTags|isActive} {if isHint}scale-${tag.fontSize|parse} {elseif isLimit(tag)}scale-limit {/if}"><a href="javascript:void(0)" class="${hooks.TAG}" style="font-size: ${tag.fontSize}">${tag.tagName}</a></span>\
					{/for}\
					{if hasThreshold}\
						<div class="${classes.VIEW_ALL}">\
							<a href="javascript:void(0)" class="${classes.MORE} ${hooks.MORE}">${templates.getMoreTagsLabel()}</a>\
							<a href="javascript:void(0)" class="${classes.LESS} ${hooks.LESS}">${templates.getLessTagsLabel()}</a>\
						</div>\
					{/if}\
					</div>';
			
			HD.FeatureStoriesWidget.templates.html = '\
				<div class="${classes.FEATURE_STORIES} ${classes.WIDGET}">\
					<span class="${classes.TITLE}">${templates.getFeatureStoriesLabel()}</span>\
					<ul class="${classes.LIST}">\
					{for item in items}\
						{var post = parseInt(item_index)+1}\
						{if post % 2 == 0}\
							<li class="${hooks.STORY} ${classes.ACTIVE}">\
						{else}\
							<li class="${hooks.STORY}">\
						{/if}\
						${item|facade}\
						</li>\
					{/for}\
					</ul>\
				<a href="#featAnchorAll" name="featAnchorAll" class="${classes.VIEW_ALL} ${classes.CONTROL} ${hooks.VIEW_ALL}">${templates.getViewAllStoriesText()}</a>\
			</div>';
			
				
			// Preload the data
			this.config.dao.preloadedMedia = this.preloadedMedia || null;

			// Initialize the main engine.
			this.engine = new HD.CommunityEngine(this.config);
			this.engineFeatured = new HD.CommunityEngine(this.configFeatured);
			this.engineVideo = new HD.CommunityEngine(this.configVideo);
			
			// 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 | Blog',
					thumbUrl : '',
					title : 'Dark Custom | Blog'
			};
			
			// Initialize the navigation.
			this.initNavigation();

			// Get media.
			setTimeout(function getMedia() {
				if (self.getNavigation() ) {
					self.engine.dao.getTags(20);
					
					// Set the tag if it exists
					if (externalTag != null){
						self.engine.dao.setTags(externalTag, true);
					}
					
					self.engine.dao.getMedia(startIndex, null, true);
					self.engineFeatured.dao.setTags(self.editorsChoiceTag, true);
					self.engineFeatured.dao.getPopular(5);
					self.engineVideo.dao.setContentSubtype('video');
					self.engine.dao.getMonthly(60);
					self.engine.dao.notifyObservers.call(self.engine.dao, "loadShare_Start", sharedItem);
					self.engine.dao.notifyObservers.call(self.engine.dao, "loadSTAF_Start", sharedItem);
				}
				else {
					setTimeout(getMedia, 50);
				}
			}, 50);
		},
	
		// Engine/widget config.
		config: {
			dao: {
				baseUrl : comSvcBaseUrl,
				siteName : comSiteName,
				contentType : 'blog',
				categories : ['Dark Custom'],
				startIndex : startIndex,
				pageSize : itemsX * itemsY
			},
			cluster: {
				baseUrl : comMediaBaseUrl
			},
			view: {
				navigation : 'nav',
				canvas : 'canvas'
			},
			widgets: {
				gallery: { 
					parent: 'galleryContent', 
					type: 'hd_gallery_widget',
					itemsX : itemsX, 
					itemsY : itemsY, 
					contentType : 'blog',
					titleLength : 100,
					previewLength : 100, 
					dateFormat : dateFormat,
					embedSendFriend: true,
					requiresRatingLogin: false,
					sendFriendConfig: sendFriendConfig /* dcUtil.js */,
					embedShare: true,
					shareConfig:{
						type: 'hd_share_widget',
						useShareAPI: true,	
						getPermalink: function(media, service, config) {						
							var params = { communityName: 'darkcustom' };
							return media.facade.generatePermalink(params);
						},
						services: [
							// (optional) Inject a URL into links with "{permalink}", "{title}", "{description}", and "{thumbnail}" replaced
							services.FACEBOOK,
							services.TWITTER,
							services.MYSPACE,
							services.BLOGGER,					
							services.WORDPRESS
						],
						previewLength: 140
					}
				},
				detail: { 
					parent: 'detailContent', 
					type: 'hd_detail_widget', 
					contentType : 'blog', 
					dateFormat : dateFormat,
					embedSendFriend: true,
					sendFriendConfig: sendFriendConfig /* dcUtil.js */,
					embedBlogDetailNavigation: true,
					requiresRatingLogin: false,
					showYourRatingText: true,
					embedShare: true,
					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 = { communityName: 'darkcustom' };
							return media.facade.generatePermalink(params);
						}
					}
				},
				comments: {
					parent: 'comments', 
					type: 'hd_comments_widget', 
					contentType : 'blog', 
					dateFormat : dateFormat,
					confirmation : true,
					submitBelow : false,
					submitAbove : true,
					requiresLogin : true,
					confirmation : false
				},
				tagCloud: {
					parent: 'tagCloud', 
					type: 'hd_tag_cloud_widget', 
					contentType : 'blog',
					pageSize : 20,
					pageType : 'limit',
					maxFontSize : 100,
					minFontSize : 100
					
				},
				memberProfile: { 
					parent: 'memberProfile', 
					type: 'hd_member_widget', 
					title : 'Contributor' 
				},
				monthly: {
					parent: 'blogMonthly', 
					type: 'hd_monthly_widget', 
					itemsLimit : 5, 
					contentType : 'blog',
					dateFormat : 'mmmm yyyy',
					renderMode : 'select'
				},
				context: {
					parent: 'galleryHeader', 
					type: 'hd_context_widget'
				},
				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)
			}
		},
		
		configFeatured: {
			dao: {
				baseUrl : comSvcBaseUrl,
				siteName : comSiteName,
				contentType : 'blog',
				categories : ['Dark Custom'],
				startIndex : startIndex,
				pageSize : itemsX * itemsY
			},
			cluster: {
				baseUrl : comMediaBaseUrl
			},
			view: {
				navigation : 'nav',
				canvas : 'canvas'
			},
			widgets: {
				featuredPosts:{
					parent: 'blogFeatured',
					type: 'hd_feature_stories_widget',
					contentType: 'blog',
					pageSize: 5,
					previewLength: 0
				}
			}
		},
		
		configVideo: {
			dao: {
				baseUrl : comSvcBaseUrl,
				siteName : comSiteName,
				contentType : 'blog',
				categories : ['Dark Custom'],
				startIndex : startIndex,
				pageSize : itemsX * itemsY
			},
			cluster: {
				baseUrl : comMediaBaseUrl
			},
			view: {
				navigation : 'nav',
				canvas : 'canvas'
			},
			widgets: {
				carousel:{
					parent: 'latestVideos',
					type: 'hd_carousel_widget',
					compact: true,
					playerWidth : '240px',
					playerHeight : '200px'
				}
			}
		},
		
		// 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);
					}	
				}
			});
	
			
			// Attach gallery observer.
			this.engineFeatured.addObserver({
				widgets: ['featuredPosts'],
				update: function(eventName, eventData) {

					if (eventName == 'viewFeatureStory')  {
						HD.util.Player.View.stopAll();
									
						// Update navigation.
						self.setNavigation('detail', eventData.contentType, eventData.mediaId, null, false);
					}	
				}
			});
			
			this.engineVideo.addObserver({
				widgets: ['carousel'],
				update: function(eventName, eventData) {
					if (eventName == 'viewCarouselItemTitle')  {
						HD.util.Player.View.stopAll();
			
						// Update navigation.
						window.location.href = 'videos.html#loc=detail/blog/'+eventData.mediaId;
					}	
					else if (eventName == 'viewAllCarouselItems')  {
						HD.util.Player.View.stopAll();
			
						// Update navigation.
						window.location.href = 'videos.html';
					}	
				}
			}); 
			
			// 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);
						}
					}
					if (eventName == "activeItem_PageChange") {
						// Show loading animation.
						self.detailEl.innerHTML = loadingHtml;
					}
					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.showMedia({ mediaId: eventData.mediaId, contentType: eventData.contentType });
					}
					else if (eventName == "getComments_Finish"){
						self.isRequestActive = false;
					}
					
				}
			});
			
			// Attach filtering observer.
			this.engine.addObserver({
				widgets: ['monthly', 'tagCloud', 'dao'],
				update: function(eventName, eventData) {
					
					var dao = self.engine.dao;
					if(eventName == "dateRange_Set") {		
						dao.clearTags(true);
						self.setNavigation('gallery', 'all', '0');
					}
					else if(eventName == "tags_Set") {		
						dao.clearDateRange(true);
						self.setNavigation('gallery', 'all', '0');
					}
					else if (eventName == "dateRange_Clear") {
						HD.getByClass('hdList', '*', 'blogMonthly', function(el) {
							this.selectedIndex = 0;
						});
					}
					
				}
			});
					
			this.engine.addObserver({
				widgets: ['detail', 'gallery'],
				update: function(eventName, eventData) {
					
					if(eventName == "authorSelected") {								
						self.showMemberPanel();		
					}
				}
			});
		
			
			// 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;
			
			
			// Return to the gallery.
			HD.getByClass('viewGallery', 'a', this.containerEl, function(el) {
				el.onclick = function() {
					self.setNavigation('gallery', 'all', '0');
				};
			});
			
			// Choose Featured Posts Filters
			HD.getByClass('hdControlFeatures', 'input', this.containerEl, function(el) {
				el.onclick = function() {
					if(this.value == 0){
						var featuredPanelEl = HD.getByClass(classes.FEATURE_STORIES, '*', self.featuredEl)[0] || self.featuredEl;
						featuredPanelEl.innerHTML = loadingHtml;
						self.engineFeatured.dao.clearTags();
						self.engineFeatured.dao.getPopular(5);
						HD.hide(self.editorsChoiceEl);
					}
					else{
						var featuredPanelEl = HD.getByClass(classes.FEATURE_STORIES, '*', self.featuredEl)[0] || self.featuredEl;
						featuredPanelEl.innerHTML = loadingHtml;
						self.engineFeatured.dao.setTags(this.value);
						self.engineFeatured.dao.getPopular(5);
						HD.show(self.editorsChoiceEl);
					}
				};
			});
			
			self.editorsChoiceEl.onclick = function() {
				self.engine.dao.setTags(self.editorsChoiceTag);
				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) {
			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) {
						this.engine.dao.getMedium(id, function() {}, type);
					}
					
					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();
					}
					
				});
			}
		},
		
		showMemberPanel: function() {
			
			var memberEl = HD.get("memberProfile");	
			if(memberEl){
				HD.removeClass(memberEl, classes.HIDDEN);
				HD.util.Common.showOverlay(memberEl, "", 475, 350, true);
			}
		}
	};
})();

// Load the page.
HD.util.DOM.onDOMReady(function() {
	DarkCustom.init();
});
