var comSvcBaseUrl = "/Community/services";
var comMediaBaseUrl = "/Community/media";
var comSiteName = "Dark Custom";
var comPageUrl = "dark_custom_art.jsp";

var login = null;

var DarkCustom = (function() {
	// Base configuration.
	var itemsX = 3;
	var itemsY = 3;
	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>';
	siteCategories = ['Art/Gas Tanks', 'Art/Graffiti & Tags', 'Art/Helmets', 'Art/Paintings', 'Art/Scars, Scrapes & Burns', 'Art/Sculptures', 'Art/Tattoos & Piercings', 'Art/Other'];
	siteCategoriesFriendly = ['Gas Tanks', 'Graffiti & Tags', 'Helmets', 'Paintings', 'Scars, Scrapes & Burns', 'Sculptures', 'Tattoos & Piercings', 'Other'];
	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: 'Art'
		},
	
		// 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');
			
			// Update config.
			this.config.dao.categories = this.configMore.dao.categories = siteCategories;
			this.config.widgets.upload.categories = siteCategories;
			this.config.dao.categoriesFriendly = this.config.widgets.upload.categoriesFriendly = siteCategoriesFriendly;
			this.config.widgets.comments.requiresLogin = this.requiresLogin;
			this.config.widgets.detail.photoTemplates = this.templates.detail.photoTemplates;
			this.config.widgets.gallery.photoTemplates = this.templates.gallery.photoTemplates;
			this.config.widgets.detail.videoTemplates = this.templates.detail.videoTemplates;
			this.config.widgets.gallery.videoTemplates = this.templates.gallery.videoTemplates;
			this.configFeatured.widgets.featuredPosts.blogTemplates = this.templates.featuredPosts.blogTemplates;
			this.configMore.widgets.moreArt.photoTemplates = this.templates.gallery.photoTemplates;
			this.configMore.widgets.moreArt.videoTemplates = this.templates.gallery.videoTemplates;

			// 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.ERRORS.upload_title_displayname = 'Art Title';
			HD.ERRORS.upload_story_displayname = 'Art 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 Art Title.';
				} 
				else if (error.fieldName == 'story' && error.errorArguments && error.errorArguments[0] && error.errorArguments[0] == 'upload.story.displayname') {
					return 'You must enter an Art 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="{if rows == 1}${classes.LAST}{else}${classes.FIRST}{/if} 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/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}">${templates.getTitleLabel(comments.length)}</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/btn_next.gif" alt="NEXT" />';
			HD.community.Video.templates.previousLabel = HD.community.Photo.templates.previousLabel = '<img src="/en_US/Media/images/Content/Pictorial/dark_custom_v3/btn_previous.gif" alt="PREVIOUS" />';
			HD.community.Blog.templates.authorLabel = HD.community.Video.templates.authorLabel = HD.community.Photo.templates.authorLabel = "By&nbsp;";
			HD.community.Blog.templates.dateLabel = 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/comment_bubble.gif" alt="" /> <span class="hdCommentsButtonLink">Comments</span> ({number})';
			HD.community.Video.templates.getCommentsButtonText = HD.community.Photo.templates.getCommentsButtonText = function(){
				return this.commentsButtonText;
			};
							
			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.engineMore = new HD.CommunityEngine(this.configMore);
			
			// 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 | Art',
					thumbUrl : '',
					title : 'Dark Custom | Art'
			};
						
			// 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.engineFeatured.dao.setTags('art');
					self.engineMore.dao.getMedia(1);
				}
				else {
					setTimeout(getMedia, 50);
				}
			}, 50);

		},
	
		// Engine/widget config.
		configFeatured: {
			dao: {
				baseUrl : comSvcBaseUrl,
				siteName : comSiteName,
				contentType : 'blog',
				categories : ['Dark Custom'],
				startIndex : startIndex,
				pageSize : itemsX * itemsY,
				thumbWidth : 160,
				mediaWidth : 420
			},
			cluster: {
				baseUrl : comMediaBaseUrl
			},
			view: {
				navigation : 'nav',
				canvas : 'canvas'
			},
			widgets: {
				featuredPosts:{
					parent: 'artBlog',
					type: 'hd_feature_stories_widget',
					contentType: 'blog',
					pageSize: 5,
					previewLength: 0,
					contentFeed: 'getMedia'
				}
			}
		},
		
		// Engine/widget config.
		configMore: {
			dao: {
				baseUrl : comSvcBaseUrl,
				siteName : comSiteName,
				contentType : 'both',
				startIndex : startIndex,
				pageSize : itemsX * itemsY,
				thumbWidth : 160,
				mediaWidth : 420,
				filters: { tags: 'art' }
			},
			cluster: {
				baseUrl : comMediaBaseUrl
			},
			view: {
				navigation : 'nav',
				canvas : 'canvas'
			},
			widgets: {
				moreArt:{
					parent: 'moreArt',
					type: 'hd_feature_stories_widget',
					contentType: 'both',
					pageSize: 3,
					previewLength: 0,
					contentFeed: 'getMedia',
					randomize: true
				}
			}
		},
		
		config: {
			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}
			        ]	
				},
				detail: { 
					parent: 'detailContent', 
					type: 'hd_detail_widget', 
					contentType : 'both', 
					dateFormat : dateFormat,
					requiresRatingLogin: false,
					showYourRatingText: true,
					embedSendFriend: true,
					sendFriendConfig: sendFriendConfig /* dcUtil.js */,
					embedShare: true,
					shareConfig:{
						type: 'hd_share_widget',
						useShareAPI: true,
						services: [services.FACEBOOK, 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 : 'both', 
					dateFormat : dateFormat,
					confirmation : true,
					submitBelow : false,
					submitAbove : true,
					requiresLogin : true,
					confirmation : false
				},
				upload: {
					type: 'hd_upload_widget',
					siteName: comSiteName,
					contentType :'both',
					title :'Upload',
					dialog: {
						confirm: ['580px','210px']
					},
					templates: {
						introText: 'Just pick the category, give it a title, and upload your art.',
						uploadMediaLabel: 'Art Title',
						descriptionLabel: 'Art Description',
						descriptionInstructionText: 'Please describe your art in 2500 characters or less.',
						uploadMediaTypeBothLabel: 'Photo OR Video of your art.'
					}
				},
				share: {
					parent: 'share',
					type: 'hd_share_widget',
					getPermalink: function(media) {
						return window.location.href;
					},
					services: [services.FACEBOOK, 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 art', categories: siteCategories },
						{ name: 'Graffiti & Tags', categories: ['Art/Graffiti & Tags'] },
						{ name: 'Tattoos & Piercings', categories: ['Art/Tattoos & Piercings'] },
						{ name: 'Paintings', categories: ['Art/Paintings'] },
						{ name: 'Sculptures', categories: ['Art/Sculptures'] },
						{ name: 'Gas Tanks', categories: ['Art/Gas Tanks'] },
						{ name: 'Helmets', categories: ['Art/Helmets'] },
						{ name: 'Scars, Scrapes & Burns', categories: ['Art/Scars, Scrapes & Burns'] },						
						{ name: 'Other', categories: ['Art/Other'] }
					]
				}
			}
		},
		
		// 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 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);
						}
					}
					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;
					}
					else if (eventName == 'categories_Set') {
						
						self.engineMore.dao.setCategories(self.config.dao.categories);
					}
					
				}
			});
			
			// Attach gallery observer.
			this.engineFeatured.addObserver({
				widgets: ['featuredPosts'],
				update: function(eventName, eventData) {

					if (eventName == 'viewFeatureStory')  {
						HD.util.Player.View.stopAll();
			
						// Update navigation.
						window.location.href = 'Dark_Custom.jsp#loc=detail/blog/'+eventData.mediaId;
					}	
				}
			});
			
			// Attach gallery observer.
			this.engineMore.addObserver({
				widgets: ['moreArt'],
				update: function(eventName, eventData) {

					if (eventName == 'viewFeatureStory')  {
						
						HD.util.Player.View.stopAll();
			
						// Update navigation.
						self.setNavigation('detail', eventData.contentType, eventData.mediaId, null, false);
					}	
				}
			});
			
			// 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.engine.dao.config.categories,  self.engine.dao.config.categoriesFriendly);
				};
			});
			
			// 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() {
						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();
					}
					
				});
			}
		}
	};
})();

// Load the page.
HD.util.DOM.onDOMReady(function() {
	DarkCustom.init();
});
